diff --git a/AGENTS.md b/AGENTS.md index a4aa7d0..9f6c624 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -9,7 +9,8 @@ tracking, import/merge workflows, or synchronization with another skills reposit - Product Kit owns exploration, research, PRDs, requirements/questions, and WBS. Reuse its record contract rather than duplicating requirements or resolutions. - Engineering Kit owns technical decisions, implementation plans and execution, - specialized reviews, business-rule modeling, and verification. Keep delivery + adopted implementation conventions, specialized reviews, business-rule modeling, + and verification. Keep delivery breakdowns distinct from implementation plans; no automatic handoff is required. - Design Kit owns interface design, critique, accessibility, UX copy, and study planning. Product Kit owns research synthesis; Engineering Kit owns functional verification. diff --git a/README.md b/README.md index a287a1a..dc54254 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ repository; there is no upstream import, tracking, or merge workflow. | Plugin | Purpose | Skills | Version | | --- | --- | --- | --- | | [Product Kit](plugins/product-kit/README.md) | Research, requirements, PRDs, and delivery breakdowns | 6 | 0.3.2 | -| [Engineering Kit](plugins/engineering-kit/README.md) | Technical decisions, implementation, reviews, and verification | 11 | 0.1.1 | +| [Engineering Kit](plugins/engineering-kit/README.md) | Technical decisions, implementation, reviews, and verification | 12 | 0.2.0 | | [Design Kit](plugins/design-kit/README.md) | Interface design, critique, accessibility, UX copy, and research planning | 10 | 0.1.0 | Product Kit owns the shared requirements, questions, and decisions. Engineering diff --git a/plugins/engineering-kit/.claude-plugin/plugin.json b/plugins/engineering-kit/.claude-plugin/plugin.json index 9acc0dc..b1149c7 100644 --- a/plugins/engineering-kit/.claude-plugin/plugin.json +++ b/plugins/engineering-kit/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "engineering-kit", - "version": "0.1.1", + "version": "0.2.0", "description": "Engineering architecture, implementation planning, focused reviews, business rules, and web-app verification.", "author": { "name": "Concepta" diff --git a/plugins/engineering-kit/.codex-plugin/plugin.json b/plugins/engineering-kit/.codex-plugin/plugin.json index 9b8fdfc..5452332 100644 --- a/plugins/engineering-kit/.codex-plugin/plugin.json +++ b/plugins/engineering-kit/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "engineering-kit", - "version": "0.1.1", + "version": "0.2.0", "description": "Engineering architecture, implementation planning, focused reviews, business rules, and web-app verification.", "author": { "name": "Concepta" @@ -12,7 +12,8 @@ "claude-code", "engineering", "architecture", - "planning" + "planning", + "nestjs" ], "skills": "./skills/", "interface": { @@ -27,6 +28,7 @@ ], "defaultPrompt": [ "Help me make and document an architecture decision.", + "Place a new NestJS endpoint using the modular NestJS rules.", "Create an implementation plan for this approved specification.", "Re-examine this existing solution from a clean sheet." ] diff --git a/plugins/engineering-kit/README.md b/plugins/engineering-kit/README.md index 41b837d..ee13378 100644 --- a/plugins/engineering-kit/README.md +++ b/plugins/engineering-kit/README.md @@ -1,13 +1,14 @@ # Engineering Kit Engineering workflows for Codex and Claude Code, installed as -`engineering-kit@conceptadev`. The kit contains 11 focused skills and their helpers. +`engineering-kit@conceptadev`. The kit contains 12 focused skills and their helpers. ## Skills | Skill | Outcome | | --- | --- | | [architecture](skills/architecture/SKILL.md) | A grounded technical choice or architecture decision record | +| [modular-nestjs](skills/modular-nestjs/SKILL.md) | File placement and implementation rules for a modular NestJS API | | [writing-plans](skills/writing-plans/SKILL.md) | An executable implementation plan from settled requirements | | [executing-plans](skills/executing-plans/SKILL.md) | Carry out an existing authorized implementation plan | | [webapp-verification](skills/webapp-verification/SKILL.md) | Browser evidence and appropriate regression coverage | diff --git a/plugins/engineering-kit/SOURCES.md b/plugins/engineering-kit/SOURCES.md index 072e01a..21f54c8 100644 --- a/plugins/engineering-kit/SOURCES.md +++ b/plugins/engineering-kit/SOURCES.md @@ -12,6 +12,7 @@ Skills, helpers, and fixtures derive from [Leo Farias's skills](https://github.c | `writing-plans`, `executing-plans` | [Superpowers](https://github.com/obra/superpowers), respective `skills/` directories, `b36e0829c6d0140e93cfef2ca599b1b07d4a7797` | [MIT](licenses/superpowers-MIT.txt) | | `code-simplifier` | [Anthropic Code Simplifier](https://github.com/anthropics/claude-plugins-official), `plugins/code-simplifier/agents/code-simplifier.md`, `ceb9b72b4c4c20ad39efce780edd0aabe80ebce3` | [Apache-2.0](licenses/anthropic-code-simplifier-Apache-2.0.txt) | | Remaining skills and local adaptations | Leo Farias | [BSD-3-Clause](LICENSE) | +| `modular-nestjs` | Original to this kit. No external skill source | [BSD-3-Clause](LICENSE) | Concepta's publisher metadata does not replace the original copyright notices. No external source repository or plugin is required to run these skills. diff --git a/plugins/engineering-kit/skills/modular-nestjs/SKILL.md b/plugins/engineering-kit/skills/modular-nestjs/SKILL.md new file mode 100644 index 0000000..28844a7 --- /dev/null +++ b/plugins/engineering-kit/skills/modular-nestjs/SKILL.md @@ -0,0 +1,73 @@ +--- +name: modular-nestjs +description: >- + Use when building, changing, or reviewing a NestJS API that follows modular NestJS: + the first URL segment after /api names the module, request and response schemas are + Zod contracts, and only repositories and one transaction runner touch the database. + Covers file placement, module shape, tests, transactions, errors, TypeORM, and gates. + Do not use to choose NestJS versus another stack, to write an architecture decision, + or for an application that has not adopted this convention. +--- + + + +# Modular NestJS + +Apply these rules when the user asks for modular NestJS, or when the repository already follows them. If the repository uses a different NestJS layout, follow that layout and say so. Do not convert it unless the user asks. + +This skill is generic. Do not invent a product name, a requirement catalog, or a tenancy model. + +## Boundaries + +- Choosing NestJS, the database, or a module boundary is the `architecture` skill. This skill starts after that choice. +- Turning requirements into a task list is `writing-plans`. When the plan targets a repository that uses this convention, the plan's paths follow this skill. +- Carrying out an approved plan is `executing-plans`. Obey this skill while placing files. +- A project document owns runtime, deployment, and database roles. Do not invent those rules. + +## The one rule + +The first segment of the URL after `/api` is the module name. Use that name for the module folder, the main file prefix, the contracts folder, and the web feature folder. + +```text +URL /api/users/:id/role +module folder apps/api/src/users/ +contracts packages/contracts/src/users/ +use-case tests apps/api/src/users/e2e/ +``` + +A sub-resource belongs to that module. A table with no route of its own belongs to the module whose routes change it. + +Two exceptions only: + +- Health routes live in `apps/api/src/health/` at `/health/*`, without the `/api` prefix. +- `common/`, `config/`, `database/`, and `logging/` have no routes. + +## What to read + +Read only the reference the task needs. + +| Task | Reference | +| --- | --- | +| Place a file, name a module, or split a topic | [references/structure.md](references/structure.md) | +| Add schemas, tests, or a contract-phase slice | [references/contracts-and-delivery.md](references/contracts-and-delivery.md) | +| Write a repository, a command, or a query | [references/persistence.md](references/persistence.md) | +| Auth, validation, OpenAPI, errors, or logs | [references/http.md](references/http.md) | +| Entity, relation, query, migration, or seed | [references/typeorm.md](references/typeorm.md) | +| Security, gates, a new project, or the feature checklist | [references/quality.md](references/quality.md) | + +## Apply the change + +1. Derive the module from the URL. Do not add a domain folder above the modules. +2. Create only the files the change needs. Two or more files of one kind go in that kind's folder. One file stays loose. +3. For a new use case, add the contract, the failing use-case test, and the service stub before the repository and the rules. +4. A command runs in one `TransactionRunner.run`. A query does not open a transaction. +5. A service throws a module exception. It does not throw a NestJS HTTP exception, return an entity, or import the ORM. +6. Every route declares `@RequirePermission(...)`, `@Authenticated()`, or `@Public()`. Every `@Body`, `@Query`, and `@Param` declares a Zod schema. +7. Stop when the repository already has a rule this skill does not cover. Ask. Do not invent the missing rule. + +## Check before you finish + +- The new path follows the URL. +- The module does not export its repository. +- The success test of a new use case failed before the behavior existed, unless the repository's own process says otherwise. +- You did not add a DTO class, `@ManyToMany`, a skipped test, `any`, or `console`. diff --git a/plugins/engineering-kit/skills/modular-nestjs/evals/evals.json b/plugins/engineering-kit/skills/modular-nestjs/evals/evals.json new file mode 100644 index 0000000..b92e30e --- /dev/null +++ b/plugins/engineering-kit/skills/modular-nestjs/evals/evals.json @@ -0,0 +1,42 @@ +{ + "skill_name": "modular-nestjs", + "evals": [ + { + "id": 1, + "prompt": "Add POST /api/orders/:id/cancel to a NestJS API that follows modular NestJS. Do not implement the business rule yet. The repository already has the foundation: auth decorators, TransactionRunner, the contracts package, and the acceptance ratchet. Cancellation is allowed only for an OPEN order in the caller's active context, writes an audit event, and returns the order id and status. Tell me which files to add and what the contract-phase stub and use-case test must do.", + "expected_output": "A contract-phase slice whose paths come from the orders URL, with schemas, a service stub that throws the not-implemented exception, and a failing success test. No repository rule yet.", + "files": [], + "expectations": [ + "Places the route in apps/api/src/orders and the schemas in packages/contracts/src/orders.", + "The controller only maps the route to one service call, takes the principal from the session, and declares a permission decorator and a schema on the id param.", + "The service stub throws UseCaseNotImplementedException and does not open a transaction or import the ORM.", + "The use-case test lives in orders/e2e, expects the successful cancel to fail until implementation, and includes the denied cases that apply.", + "Does not invent a product name, a tenancy model, or a domain folder above the module." + ] + }, + { + "id": 2, + "prompt": "Our NestJS API already follows modular NestJS. Implement cancel order now. The contract-phase test expects 200 and status CANCELED. The order row must change only when its status is still OPEN. The audit event must commit with the status change. An unknown id and an order in another context must both return 404.", + "expected_output": "An implementation that uses one transaction, a conditional update, a module not-found exception, and no ORM import in the service.", + "files": [], + "expectations": [ + "The command calls TransactionRunner.run once and passes that context to the repository and the audit write.", + "The status change is a conditional update on OPEN, not a read-check-write.", + "A missing row and a row outside the active context both become the module not-found exception.", + "The repository stays private to the module, returns an entity or a boolean, and the service converts the result to the contract type.", + "Does not add @ManyToMany, a DTO class, a NestJS HTTP exception, or a skipped test." + ] + }, + { + "id": 3, + "prompt": "We have an existing NestJS app that uses class-validator DTOs, a shared src/modules folder, and Prisma. Add one field to the existing cats update DTO. Do not adopt a new architecture.", + "expected_output": "A small change that follows the existing DTO layout and does not rewrite the application into modular NestJS.", + "files": [], + "expectations": [ + "Keeps the existing DTO, folder, and Prisma patterns.", + "Does not introduce a contracts package, TransactionRunner, Zod schemas, or a new module layout.", + "States that modular NestJS was not applied because the repository has not adopted it and the user did not ask for a conversion." + ] + } + ] +} diff --git a/plugins/engineering-kit/skills/modular-nestjs/evals/trigger_queries.json b/plugins/engineering-kit/skills/modular-nestjs/evals/trigger_queries.json new file mode 100644 index 0000000..6022d75 --- /dev/null +++ b/plugins/engineering-kit/skills/modular-nestjs/evals/trigger_queries.json @@ -0,0 +1,74 @@ +[ + { + "query": "Add POST /api/users/:id/deactivate using the modular NestJS rules. Put the files where the URL says they go.", + "should_trigger": true + }, + { + "query": "Where do the orders repository, entity, and contract schema live in a modular NestJS API?", + "should_trigger": true + }, + { + "query": "Scaffold the foundation for a new NestJS API that follows the modular NestJS guide, before the first feature.", + "should_trigger": true + }, + { + "query": "The contract phase for products is next. Add the Zod schema, the service stub, and the failing use-case test.", + "should_trigger": true + }, + { + "query": "Review this NestJS module against the modular NestJS file and transaction rules.", + "should_trigger": true + }, + { + "query": "This users service is over 300 lines. Split it into a modular NestJS topic without splitting by verb.", + "should_trigger": true + }, + { + "query": "A command writes a user and an audit event. How should the transaction and the module boundary work?", + "should_trigger": true + }, + { + "query": "Replace this @ManyToMany with the join entity the modular NestJS guide requires.", + "should_trigger": true + }, + { + "query": "Choose NestJS or Hono for the new public API and record the decision.", + "should_trigger": false + }, + { + "query": "Write an ADR for whether orders and payments share a database.", + "should_trigger": false + }, + { + "query": "Add one optional field to our existing class-validator DTO. Keep the current NestJS layout.", + "should_trigger": false + }, + { + "query": "Fix the empty-state copy on the React orders page.", + "should_trigger": false + }, + { + "query": "Turn the approved payment idempotency spec into an implementation plan. Do not place files yet.", + "should_trigger": false + }, + { + "query": "Execute the plan in docs/plans/cancel-order.md and commit each task.", + "should_trigger": false + }, + { + "query": "Review this pull request for bugs and missing tests.", + "should_trigger": false + }, + { + "query": "Write the business vocabulary and rules for order cancellation in SBVR.", + "should_trigger": false + }, + { + "query": "The checkout test fails only in CI. Find the cause.", + "should_trigger": false + }, + { + "query": "Create a product requirements document for the new export feature.", + "should_trigger": false + } +] diff --git a/plugins/engineering-kit/skills/modular-nestjs/references/contracts-and-delivery.md b/plugins/engineering-kit/skills/modular-nestjs/references/contracts-and-delivery.md new file mode 100644 index 0000000..1c10d68 --- /dev/null +++ b/plugins/engineering-kit/skills/modular-nestjs/references/contracts-and-delivery.md @@ -0,0 +1,121 @@ +# Contracts, tests, and delivery + +## Contracts package + +Browser-safe Zod schemas live in `packages/contracts`. The API and the web client import the same schemas. Every module has a folder with its name, even for one file. + +The package imports only `zod`. It never imports NestJS, TypeORM, Node built-ins, or environment variables. + +```text +packages/contracts/src/ +├── index.ts +├── common/ +│ ├── page.schema.ts +│ ├── list-query.schema.ts +│ ├── audit-fields.schema.ts +│ ├── api-error.schema.ts +│ └── common-error-codes.schema.ts +└── users/ + ├── user.schema.ts + ├── user-create.schema.ts + └── users-error-codes.schema.ts +``` + +| Kind | Name | Example | +| --- | --- | --- | +| Request body | `RequestSchema` | `userCreateRequestSchema` | +| Query | `ListQuerySchema` | `userListQuerySchema` | +| Record | `RecordSchema` | `userRecordSchema` | +| Command result | `ResultSchema` | `userStatusChangeResultSchema` | +| Page | `PageSchema` | `userPageSchema` | +| Error codes | `ErrorCodeSchema` | `usersErrorCodeSchema` | +| Inferred type | Schema name without `Schema` | `UserCreateRequest` | + +- A record schema extends `auditFieldsSchema`. +- A command result holds only the values the command submitted or changed. +- A request or query schema never contains audit fields. +- A limit shared by the contract and the database is an exported `UPPER_SNAKE` constant in the schema file. The entity imports it. The migration copies the number. +- Do not add a schema for a use case that an open question blocks. +- Each schema file has a `.spec.ts` beside it. +- The web client uses each schema to validate a form, to type the response, and to parse the response at run time. +- There is no DTO class. + +## Tests + +| Kind | Suffix | Location | Proves | +| --- | --- | --- | --- | +| Unit | `.spec.ts` | Beside the file | One rule, with a fake repository | +| Use case | `.e2e-spec.ts` | `/e2e/` | One route: HTTP, database, and audit event | +| Requirement | `.e2e-spec.ts` | `apps/api/tests/requirements/` | One requirement, across modules | +| Flow | `.e2e-spec.ts` | `apps/api/tests/flows/` | One user scenario | + +- A use-case file is `-.e2e-spec.ts`. Its `describe` title names the use case and the requirement identifiers the project uses. +- A use-case file calls only its own module and `/api/auth` routes. Other records come from fixtures. +- Write one `it` for each rule and each denied case: no session (`401`), missing permission (`403`), unknown or foreign identifier (`404`), wrong context (`404`), unknown or read-only field (`400`), oversized input (`400`), and concurrent change (`409`) on a write. A case that does not apply is `Not applicable: ` in the plan. +- A refused write checks that nothing changed. A change checks its audit event. +- Tests import `it` from the application fixture and `describe` and `expect` from `vitest`. Do not use globals. +- Fixtures are `environment`, `app` (one per file), `signIn`, `anonymous`, and `records`. +- A fixture replaces only an adapter port, with `overrideProvider().useClass(InMemory)`. It never overrides a service. +- Record builders write through the TypeORM repository API. Each test creates its own records. End-to-end files run one at a time. +- Do not use `skip`, `only`, `todo`, expected failures, or retries. +- Coverage of the API and the contracts package stays at or above 80% of lines, branches, functions, and statements. Exclude migrations, `*.module.ts`, and `main.ts`. +- Every service, guard, pipe, filter, hook, utils file, adapter implementation, and contract schema has a `.spec.ts`. A contract-phase stub and an adapter port do not. + +### Acceptance ratchet + +End-to-end tests exist before their behavior. The failing tests on the main branch are the missing features. + +- `docs/acceptance-baseline.json` lists every end-to-end test that passes. +- Continuous integration fails when a listed test fails, and when a test passes but is not listed. +- A failing test that is not listed is a missing feature. Integration reports it and does not fail. +- A test leaves the baseline only when the plan lists it under removals. +- A file that fails to load fails integration. + +## Delivery + +```text +requirement → use cases → contract phase → implementation, one use case at a time +``` + +| Phase | Output | Tests | +| --- | --- | --- | +| Contract | Schemas, entities, migration, module, controllers, service stubs, end-to-end tests, OpenAPI | Success tests fail | +| Implementation | Repositories, rules, exceptions, unit tests | Those tests pass | + +- A service stub throws `UseCaseNotImplementedException`, so the response is `501`. +- A `401`, `403`, or `400` test may already pass, because guards and validation exist. It proves a boundary, not the use case. +- Each use case has one success test that fails until the use case works. +- The contract phase may merge. The ratchet keeps integration green. +- Pin the requirements version in the plan. If requirements change, reopen the plan before more code. +- A feature plan does not include foundation work. Land the foundation first. +- List every route, test, constraint, or file the change deletes. +- A use case blocked as a whole has no route. A test proves the route is absent. +- A use case with one blocked rule still has its route. The blocked rule has no behavior until the question closes. + +### Contract-phase controller and stub + +```ts +@Controller("api/users") +export class UsersController { + constructor(@Inject(UsersService) private readonly users: UsersService) {} + + @Post(":id/deactivate") + @HttpCode(HttpStatus.OK) + @RequirePermission(Permission.USERS.EDIT) + @ApiOkResponse({ standardSchema: userStatusChangeResultSchema }) + deactivate( + @CurrentPrincipal() principal: Principal, + @Param("id", { schema: z.uuid() }) id: string, + ) { + return this.users.deactivate(principal, id); + } +} +``` + +```ts +deactivate(_principal: Principal, _id: string): Promise { + throw new UseCaseNotImplementedException(); +} +``` + +The controller has no condition, no loop, and no data access. The actor and the active context come from the session, not from the body. diff --git a/plugins/engineering-kit/skills/modular-nestjs/references/http.md b/plugins/engineering-kit/skills/modular-nestjs/references/http.md new file mode 100644 index 0000000..d4b9125 --- /dev/null +++ b/plugins/engineering-kit/skills/modular-nestjs/references/http.md @@ -0,0 +1,115 @@ +# HTTP, errors, and logs + +## Request flow + +1. A global authentication guard denies every route by default. +2. `@Public()` is allowed only in `auth/` and `health/`. `@Authenticated()` means a session without a permission. `@RequirePermission(...)` names the permission. +3. The guard reads the session cookie and loads the `Principal`: user, role, permissions, scopes, and active context. +4. Guards read decorators on the route method only. A decorator on the controller class is ignored, so do not put one there. +5. The controller receives the principal through `@CurrentPrincipal()` and passes it to the service. +6. The service checks record-level rules. A command checks them inside the transaction. A query applies them in `where`. + +Rules: + +- The actor and the active context come from the session. A body or query never supplies them. +- Context selection is `POST /api/auth/context`. It is a command. The server checks the selection against the user's scopes and stores it in the session. +- A user-facing method takes `(principal, input)`. A method called inside another module's transaction takes `(transaction, input)`. +- The active context filters every read and change of context-owned data. No active context means no such data. +- A context command without an active context throws `ContextRequiredException` (`403`). +- Only auth controllers use `@Res({ passthrough: true })`, to set or clear the session cookie. +- A state-changing request needs the session cookie and a CSRF token from that session. +- A development sign-in may exist for local work. It is disabled in production, and a test proves that. + +```text +auth/ +├── auth.module.ts +├── controllers/ +│ ├── auth-session.controller.ts +│ └── auth-context.controller.ts +├── services/ +├── guards/ +│ ├── authentication.guard.ts +│ ├── permission.guard.ts +│ ├── csrf.guard.ts +│ └── rate-limit.guard.ts +├── decorators/ +│ ├── public.decorator.ts +│ ├── authenticated.decorator.ts +│ ├── require-permission.decorator.ts +│ └── current-principal.decorator.ts +├── principal.interface.ts +└── e2e/ +``` + +## Validation and OpenAPI + +Register one `StandardSchemaValidationPipe` with `APP_PIPE`. + +- Every `@Body`, `@Query`, and `@Param` declares `schema`. A parameter without one is not checked. +- The pipe's `exceptionFactory` throws `ValidationFailedException` with the field list. +- Do not write a custom validation pipe. Use `@Param("id", { schema: z.uuid() })` instead of `ParseUUIDPipe`. +- Request bodies, path parameters, and queries come from that `schema` option. Responses come from `standardSchema` on the response decorators. +- Error responses use the shared API error schema. +- Outside production, Swagger serves `/api/docs`. +- Export OpenAPI from the compiled application in NestJS preview mode, so the export needs no database. Fail the check when the committed document differs. + +## Fixed values + +- Use `z.uuid()`, `z.email()`, `z.iso.datetime()`, and `z.enum()`. +- Declare each value list once, in the contracts package. +- Permission codes come from one grouped constant, such as `Permission.USERS.EDIT`. Error codes come from the module enum. +- API-only limits go in `.constants.ts`. A limit the contract also enforces is exported by the schema file. +- An entity column that stores a value list uses the contract type. Its `CHECK` constraint lists the same values. +- Only `config/` reads `process.env`. Feature code reads configuration through `@nestjs/config`. + +## Exceptions + +`ApplicationException` holds the code, HTTP status, message, and optional field list. It does not extend `HttpException`. + +The code format is `_`. The prefix is the module folder name with hyphens turned into underscores: `users` gives `USERS_`, `order-items` gives `ORDER_ITEMS_`. The code comes from the module error-code enum. + +| Exception | Code | HTTP | +| --- | --- | --- | +| `ValidationFailedException` | `COMMON_VALIDATION_FAILED` | 400 | +| `MalformedRequestException` | `COMMON_MALFORMED_REQUEST` | 400 | +| `UnauthenticatedException` | `COMMON_UNAUTHENTICATED` | 401 | +| `PermissionDeniedException` | `COMMON_PERMISSION_DENIED` | 403 | +| `CsrfInvalidException` | `COMMON_CSRF_INVALID` | 403 | +| `ContextRequiredException` | `COMMON_CONTEXT_REQUIRED` | 403 | +| `RouteNotFoundException` | `COMMON_ROUTE_NOT_FOUND` | 404 | +| `ConcurrentChangeException` | `COMMON_CONCURRENT_CHANGE` | 409 | +| `PayloadTooLargeException` | `COMMON_PAYLOAD_TOO_LARGE` | 413 | +| `UnsupportedMediaTypeException` | `COMMON_UNSUPPORTED_MEDIA_TYPE` | 415 | +| `RateLimitedException` | `COMMON_RATE_LIMITED` | 429 | +| `InternalErrorException` | `COMMON_INTERNAL_ERROR` | 500 | +| `UseCaseNotImplementedException` | `COMMON_USE_CASE_NOT_IMPLEMENTED` | 501 | + +- Services, repositories, and adapters throw only application exceptions. They never import exception classes from `@nestjs/common`. +- Name an exception `Exception`, not after a NestJS exception. +- A controller does not catch exceptions. +- A unique violation becomes a module conflict exception. +- A record outside the actor's context is "not found", never a permission error. +- An unknown identifier in the body or query is `400` with `__NOT_FOUND` and the field in the field list. +- A message tells the user what to do. It never contains a stack trace, SQL, a foreign identifier, or a secret. + +One exception filter, registered with `APP_FILTER`, maps an `ApplicationException` to its contract and any other error to `COMMON_INTERNAL_ERROR`. A framework `HttpException` maps by status: `400`, `404`, `413`, `415`, and `429` become the matching common exception. The readiness route is the only route that sets its own status, for its `503` health body. + +## Logs + +Logs are JSON lines on standard output. Create the NestJS `ConsoleLogger` with `json` and `flattenParams`. Each class uses `new Logger(ClassName.name)`. Never use `console`. + +| Field | Content | +| --- | --- | +| `timestamp` | Time of the entry | +| `level` | `error`, `warn`, `log`, or `debug` | +| `context` | Class name | +| `message` | Short fixed text. Variable values are fields | +| `userId` | Signed-in user, when one exists | +| `errorCode` | Exception code, when one caused the line | + +- An `onResponse` hook writes one line per request, including requests a guard refuses. +- The filter logs the error code. A `500` also logs the stack trace. +- Slow queries log the query and the duration, never the parameters. +- `error` is a `500` or a failure a person must handle. `warn` is a refused security check, a slow query, or a repeated `4xx`. `debug` is off in production. +- Do not log passwords, tokens, cookies, secrets, full bodies, or unneeded personal data. Do not log inside a loop. +- A log is not an audit event. The audit event is business history, saved in the same transaction as the change. diff --git a/plugins/engineering-kit/skills/modular-nestjs/references/persistence.md b/plugins/engineering-kit/skills/modular-nestjs/references/persistence.md new file mode 100644 index 0000000..63c9fc2 --- /dev/null +++ b/plugins/engineering-kit/skills/modular-nestjs/references/persistence.md @@ -0,0 +1,112 @@ +# Persistence and transactions + +## Boundary + +Persistence files are every file in `database/`, every `*.repository.ts`, and every `*.entity.ts`. + +| Rule | Reason | +| --- | --- | +| Only persistence files import `typeorm`, `pg`, or `@nestjs/typeorm` | Other layers stay free of the ORM | +| Only persistence files import entities as values. A service may use `import type` | The service never runs ORM code | +| A repository returns entities or parsed rows, never `UpdateResult` or similar | ORM types stay inside the repository | +| A repository translates database errors into module exceptions | The filter knows only application exceptions | +| A repository receives page, sort, and filters in contract form | ORM options stay inside the repository | + +## Commands and queries + +Every command runs in one transaction. Every query runs without a transaction. + +- A command method calls `TransactionRunner.run` once. A query method never calls `run`. +- A command that calls an external adapter may run one short transaction before the call and one after it, never during it. +- A command uses a transaction even when it writes one row today. +- `TransactionRunner` is the only class that uses the ORM transaction API. `DatabaseModule` is global and exports it. Inject the class: `@Inject(TransactionRunner)`. +- The signature is `run(principal, work, options?)`. `work` receives an opaque `TransactionContext`. +- `principal` is `TransactionPrincipal`: `userId`, scopes, and active context. The auth `Principal` extends it, so `database/` never imports `auth/`. +- A system process calls `run` with the system principal. + +Write methods require a transaction at compile time: + +- A command method takes the transaction context first and uses `writer(transaction)`. Reads inside a command do too. +- A query method has no transaction parameter and uses `reader`. +- When both need the same read, use two methods, such as `findById(id)` and `findForCommand(transaction, id)`. Never use an optional transaction parameter. +- An exported method that another module calls inside a transaction ends with `ForCommand` and takes `(transaction, input)`. + +## Transaction rules + +1. Every transaction starts with `run`. No other file opens one. +2. A service called for a write receives the caller's transaction context. Both writes commit, or neither does. +3. A nested `run` in the same call chain fails. Detect it with `AsyncLocalStorage`. +4. A context stops working after commit or rollback. +5. A transaction contains database work only. HTTP, e-mail, and queue messages run before it or after commit. +6. Prefer one conditional statement to read-check-write. `update({ id, status: "ACTIVE" }, { status: "INACTIVE" })` returns the changed-row count. If none changed, a read separates "not found" from "wrong status". +7. Lock a row only when the new value depends on a value the command reads. +8. The application connection sets `statement_timeout`. +9. PostgreSQL `40001` and `40P01` become `ConcurrentChangeException` (`409`). Do not retry automatically. +10. Background work opens its own transaction. +11. Seeds use `TransactionRunner` with the system principal. Migrations use their own transaction. + +## Repository supertype + +Every repository extends `TypeOrmRepository`. The supertype has no public operation. + +| Protected member | Use | +| --- | --- | +| `reader` | Ordinary connection, for reads | +| `writer(transaction)` | Inside the transaction, for writes | +| `readerOf(Entity)` | Another entity of the same module, ordinary connection | +| `writerOf(transaction, Entity)` | Another entity of the same module, inside the transaction | +| `pageOptions(page, sort)` | `order`, `skip`, `take`, with `id` as the last sort key | +| `actorId(transaction)` | Actor user id, for audit columns | + +- This table is the complete list. +- A repository serves its own module. It reads another module's table only through a join and never writes it. +- Do not add `findAll`, `delete`, or any other public operation to the supertype. +- There is no base controller and no base service. +- A repository without an entity, such as the readiness query, injects `DataSource` directly. + +A command method takes `(transaction, input)`. A query method takes `(principal, input)`. Public methods use entities and contract types, never `FindOptionsWhere` or `UpdateResult`. + +```ts +@Module({ + controllers: [UsersController], + providers: [UsersService, UsersRepository], + exports: [UsersService], +}) +export class UsersModule {} +``` + +The module exports services, never the repository. A unit test replaces the repository with `{ provide: UsersRepository, useValue: fake }` and does not cast the fake. + +## Lists + +The list-query builder supplies `page`, `pageSize`, `sort`, and `order`. The page builder supplies the response. The repository calls `reader.findAndCount` with filters and `pageOptions`. The controller and the service pass the parsed query through unchanged. + +## Service rules + +A query: + +1. Receives `(principal, input)`. +2. Calls reads that filter by the active context. +3. Throws the module "not found" exception when no row matches. +4. Converts entities to contract types. + +A command, inside one `run(principal, ...)`: + +1. Receives `(principal, input)`. +2. Checks rules that need no database. +3. Reads and changes the target through command methods filtered by the transaction's context. +4. Uses one conditional statement where it can. +5. Records the audit event in the same transaction. +6. Returns only the fields of the result contract. + +## Style + +- One responsibility per function. A block that needs a "what" comment becomes a private method. +- Return early. Do not mutate a received object. Await every promise. Use named exports. +- No `any`. Parse `unknown` with Zod at a boundary. Do not use `as` to hide a type error. +- Public service and repository methods declare parameter and return types. +- Comments explain why. Delete dead code. +- A method past 40 lines splits into private methods. +- A private method needed by two classes in one module moves to `.utils.ts` as a pure function. +- A function needed by two modules moves to `common/` when it has no business rule. Otherwise callers use the owner's service. +- Every constructor parameter declares `@Inject()`. diff --git a/plugins/engineering-kit/skills/modular-nestjs/references/quality.md b/plugins/engineering-kit/skills/modular-nestjs/references/quality.md new file mode 100644 index 0000000..24b83d1 --- /dev/null +++ b/plugins/engineering-kit/skills/modular-nestjs/references/quality.md @@ -0,0 +1,122 @@ +# Security, gates, foundation, and checklist + +## Security + +| Principle | Rule | +| --- | --- | +| Deny by default | A route without a declared access decorator is denied | +| Least privilege | Each user, role, database role, and integration job gets only the access its task needs | +| Defense in depth | Check access in the guard, the service, and the database | +| Fail closed | An error, a timeout, or a missing value denies the operation | +| Trust no input | Parse every request part with Zod. Read the actor and the context from the session | +| Minimize data | Collect, store, return, and log only what the use case needs | +| No secrets in code | Secrets come from the runtime secret store | +| Secure by default | Production settings are the defaults | + +Map the OWASP API risks as follows: object checks against the principal and context (`404` for a foreign identifier); `HttpOnly` `Secure` `SameSite=Strict` cookies, CSRF, and a throttled sign-in; strict request objects; a maximum page size, body limit, rate limits, and statement timeouts; an access decorator on every route; rate limits and audit events on sensitive flows; no fetch of a client-supplied URL; security headers, a CORS allowlist, and no Swagger in production; the OpenAPI document lists every route; external responses are parsed with Zod and have timeouts. + +- Mark a personal-data field with `.meta({ personalData: true })`. Personal data never appears in a URL, a log, an error, or a metric. +- Responses set `Strict-Transport-Security`, `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY`, `Referrer-Policy: no-referrer`, a restrictive content security policy, and `Cache-Control: no-store`. +- CORS allows configured origins only. Never allow `*` with credentials. +- Validate configuration at startup. Production has no default secret, no development sign-in, and no Swagger. +- Pin exact versions. Install with the frozen lock file. Audit high and critical findings on every pull request. Pin integration actions to a commit SHA. +- The application role owns no table and has no `BYPASSRLS`. Migrations and seeds use the migrator role. The application connection sets `statement_timeout`. Multi-tenant tables add row-level security to the service checks. + +Endpoint checklist: + +- The route declares its access decorator. +- Every request part has a strict Zod schema with limits. +- The service checks the target against the principal and the active context. +- A foreign or unknown identifier gives the same `404`. +- The response holds only contract fields. +- A list has a maximum page size and a stable order. +- A sensitive flow has a rate limit. +- Every change writes an audit event in the same transaction. +- End-to-end tests cover each denied case. + +## Gates + +| Rule | Enforced by | +| --- | --- | +| File suffixes, kind folders, one module file and one constants file | Structure check | +| Route owner, route protection, schema on every body, query, and param | Structure check | +| Import allowlist, private repositories, ORM boundary, transaction owner | Structure check | +| No NestJS exceptions in services, error-code prefix, contracts import only `zod` | Structure check | +| No `@ManyToMany`, `eager`, or `cascade`; entities extend a base entity | Structure check | +| 300 lines per controller, service, repository, or adapter; 40 lines per method | Structure check | +| No `console`, no `any`, named exports, no `process.env` outside `config/`, no skipped tests | Linter | +| Transaction context on write methods | TypeScript | +| Module cycles, OpenAPI drift, schema drift, acceptance ratchet, 80% coverage | Continuous integration | + +TypeScript uses `strict`, `isolatedModules`, and `verbatimModuleSyntax`. + +Useful scripts: `check` (lint, format, typecheck, module cycles, structure, OpenAPI), `test`, `test:e2e`, `test:coverage`, `acceptance:update`, `openapi:export`, `check:schema`. + +Integration runs migrate twice, seed twice, the end-to-end suite with the ratchet, coverage, and the schema check. One required status check aggregates the jobs. + +## Foundation, before the first feature + +Build these in order, each with its own tests: + +1. Workspace, catalog, TypeScript, lint, and format. +2. Contracts `common/` schemas: page, list query, audit fields, API error, common error codes. +3. Validated configuration and the JSON logger. +4. Data source, base entities, transaction runner, lock and error helpers, and the first migration with the system user. +5. Application exception, common exceptions, exception filter, and validation pipe. +6. Health routes. +7. Security headers, CORS allowlist, body limit, rate limits, and `statement_timeout`. +8. Auth: session, context, guards, decorators, and `Principal`. +9. OpenAPI export and drift check. +10. Test fixtures, end-to-end config, coverage, and the acceptance ratchet. +11. Structure check. +12. Continuous integration. +13. API and migration containers. + +Add features only after the foundation passes its verification and integration. + +## Anti-patterns + +| Do not | Do this | +| --- | --- | +| One module per table | One module per resource, the first URL segment | +| A domain folder above the modules | Modules at the top of `src/` | +| A base controller, or a base repository with public methods | Protected helpers on `TypeOrmRepository` only | +| A business rule in a controller | The rule in the service | +| The actor or the context in the body | Read them from the session | +| A service that injects a TypeORM `Repository` | Inject the module repository class | +| A service that mutates an entity and expects a save | Call a repository write method | +| An entity in a response | Convert it to the contract type | +| A DTO class or a custom validation pipe | Zod with `StandardSchemaValidationPipe` | +| A transaction outside the runner, or around a query | `run` for a command; `reader` for a query | +| Read, check, and write when one statement is enough | One conditional `update` | +| An HTTP call inside a transaction | Before `run` or after commit | +| `@ManyToMany` | A join entity with two `@ManyToOne` relations | +| A kind folder with one file | Keep the file loose | +| A regular expression for an identifier or an email | `z.uuid()` or `z.email()` | +| A permission or error code as a raw string | The contracts enum or constant | +| A skipped test, or a test edited to match the code | Keep it failing until the use case works | + +## New-feature checklist + +Contract phase: + +- Each use case has its requirement identifiers. +- The module folder is the first URL segment. +- Schemas and the error-code enum are in `packages/contracts/src//`. +- The entities and their migration exist. +- The module file, controllers, and service stubs exist. +- Each route has an access decorator. Each body, query, and param has a schema. +- Each stub throws `UseCaseNotImplementedException`. +- Each use case has one end-to-end file, with one test per rule and per denied case. +- Each success test fails. +- The plan lists denied cases, removals, and the requirements version, and it contains no foundation work. +- The OpenAPI document shows every new route. + +Implementation phase, for each use case: + +- The repository extends `TypeOrmRepository` and is not exported. +- Module exceptions use codes from the enum. +- The service uses one transaction and writes the audit event in it. +- The use-case tests pass without edits to the tests, and the baseline lists them. +- The endpoint checklist passes. +- Verification, end-to-end tests, and coverage pass. diff --git a/plugins/engineering-kit/skills/modular-nestjs/references/structure.md b/plugins/engineering-kit/skills/modular-nestjs/references/structure.md new file mode 100644 index 0000000..c34d57a --- /dev/null +++ b/plugins/engineering-kit/skills/modular-nestjs/references/structure.md @@ -0,0 +1,189 @@ +# Structure + +## Monorepo + +```text +/ +├── docs/ +│ ├── openapi.json +│ ├── acceptance-baseline.json +│ ├── plans/ +│ └── decisions/ +├── packages/ +│ └── contracts/ +└── apps/ + ├── api/ + └── web/ +``` + +Pin exact versions. Keep shared versions in the pnpm catalog. + +| Component | Package | +| --- | --- | +| HTTP | `@nestjs/platform-fastify` | +| Configuration | `@nestjs/config` | +| OpenAPI | `@nestjs/swagger` | +| ORM | `@nestjs/typeorm`, `typeorm`, PostgreSQL | +| Contracts | `zod` | +| Tests | `vitest`, `@nestjs/testing` | + +## API tree + +```text +apps/api/src/ +├── main.ts +├── app.module.ts +├── common/ exceptions, exception filter, validation pipe, security headers +├── config/ validated environment and configuration factories +├── database/ data source, entity registry, transaction runner, migrations, seeds +├── logging/ JSON logger and the request log hook +├── health/ /health/live and /health/ready +├── auth/ /api/auth/** +└── / /api//** +``` + +Infrastructure folders follow the same file-type rules as modules. Only `database/` and other persistence files import the ORM. Do not name a module after a NestJS keyword such as `providers`. + +The web client mirrors module names at `apps/web/src/features//`. This skill does not define component or state rules. + +## File types + +Every source file has one of these suffixes. The only other allowed source files are `main.ts`, `config/environment.ts`, the contracts `index.ts`, migrations, and tool configuration at a package root. + +| Suffix | Content | Kind folder | Export | +| --- | --- | --- | --- | +| `.module.ts` | Wires providers. Never runs a query | never | `Module` | +| `.controller.ts` | One controller | `controllers/` | `Controller` | +| `.service.ts` | One service | `services/` | `Service` | +| `.repository.ts` | One repository | `repositories/` | `Repository` | +| `.adapter.ts` | One port or one external-service implementation | `adapters/` | `Adapter` | +| `.entity.ts` | One entity or view entity | `entities/` | `Entity` | +| `.exception.ts` | One exception | `exceptions/` | `Exception` | +| `.interface.ts` | One interface | `interfaces/` | PascalCase of the file name | +| `.type.ts` | One type alias | `types/` | PascalCase of the file name | +| `.guard.ts` | One guard | `guards/` | `Guard` | +| `.decorator.ts` | One decorator | `decorators/` | PascalCase of the file name | +| `.filter.ts` | One exception filter | never | `Filter` | +| `.pipe.ts` | One pipe | never | `Pipe` | +| `.logger.ts` | One logger | never | `Logger` | +| `.runner.ts` | Transaction or seed runner, `database/` only | never | `Runner` | +| `.datasource.ts` | Data source options, `database/` only | never | camelCase functions | +| `.config.ts` | One configuration factory, `config/` only | never | camelCase constant | +| `.constants.ts` | Fixed values of one module | never | `UPPER_SNAKE` | +| `.utils.ts` | Pure functions, no state or database access | `utils/` | camelCase functions | +| `.hook.ts` | One Fastify hook | never | camelCase function | +| `.registry.ts` | Entity list, `database/` only | never | `UPPER_SNAKE` | +| `.seed.ts` | One seed, `database/seeds/` only | never | camelCase function | +| `.fixture.ts` | One fixture or record builder, tests only | `fixtures/` | camelCase, `InMemory` | +| `.spec.ts` | Unit tests of the sibling file | beside the file | — | +| `.e2e-spec.ts` | One use case, requirement, or flow | `e2e/` or a suite folder | — | +| `.schema.ts` | Zod schemas, contracts only | module folder | see contracts reference | + +`` is the PascalCase form of the file name before the suffix. `users-access.service.ts` exports `UsersAccessService`. + +Migrations keep TypeORM names: `database/migrations/-.ts`. They are the only files without a role suffix. + +### Kind folders + +1. Two or more files of one kind go in the kind folder. +2. One file of a kind stays loose in the module folder. +3. A `.spec.ts` file sits beside its source file and does not count toward rule 1. +4. Every module has `.module.ts`. A module with a controller has `e2e/`, even for one test file. +5. A suffix marked "never" never goes in a kind folder. A folder has at most one `.module.ts` and one `.constants.ts`. +6. A kind folder holds one kind only. + +### Topics + +Topics apply to controllers, services, and repositories. + +- Start with one of each. Add a second only as a topic. +- A topic is a group of routes with its own rules, such as `/api/users/:id/role`. +- The topic name is `-` in every layer: `users-access.controller.ts`, `users-access.service.ts`, `users-access.repository.ts`. +- Split by subject, never by verb. `create-user.service.ts` is not a topic. +- Create a topic when a controller, service, or repository passes 300 lines. +- When an adapter passes 300 lines, split its port by external capability. + +### Adapters + +An adapter calls one external service. It lives in the module that owns that service, never in an infrastructure folder. + +- The port is one abstract class with abstract members only. +- Each implementation is its own file that extends the port. +- The module binds the port: `{ provide: EmailSenderAdapter, useClass: SmtpEmailSenderAdapter }`. +- An implementation reads settings through `@nestjs/config`, sets a timeout, parses each reply with its own Zod schema, and maps external errors to module exceptions. +- No external type or error leaves the adapter. The adapter is private to its module. +- The end-to-end fake is `InMemory` in the test fixtures. Application code never imports it. +- When several modules need one external service, one module owns it and exports a service that wraps the adapter. + +## Module shape + +Several tables that change together stay in one module: + +```text +users/ +├── users.module.ts +├── users.constants.ts +├── controllers/ +│ ├── users.controller.ts +│ └── users-access.controller.ts +├── services/ +├── repositories/ +├── entities/ +│ ├── user.entity.ts +│ └── user-role.entity.ts +├── exceptions/ +└── e2e/ +``` + +`user_role` stays in `users/` because the routes that change it start with `/api/users`, and the row does not exist without its user. A catalog with its own routes, such as `roles/`, is its own module. + +One table stays flat: + +```text +products/ +├── products.module.ts +├── products.controller.ts +├── products.service.ts +├── products.service.spec.ts +├── products.repository.ts +├── product.entity.ts +├── product-not-found.exception.ts +└── e2e/ +``` + +A repository returns entities. The service converts an entity to a contract type in one private method, such as `toRecord`. The service treats the entity as read-only, imports it with `import type`, never imports `typeorm`, and never returns an entity. + +## Where each thing goes + +| Thing | Location | +| --- | --- | +| Endpoint | Controller of the module named by the first URL segment | +| Business rule | Service of that module | +| Query | Repository of that module | +| External call | Adapter of that module | +| Table | Entity of the module whose routes change it | +| Transaction | `TransactionRunner.run`, called by a service | +| Schema | `packages/contracts/src//` | +| Error code | `-error-codes.schema.ts` in that folder | +| Permission code | `packages/contracts/src/permissions/` | +| Use-case test | `/e2e/-.e2e-spec.ts` | +| Call to another module | That module's exported service | + +## Imports between modules + +A file may import another folder only from this list: + +| May import | Condition | +| --- | --- | +| `common/`, `config/`, `database/`, `logging/` | Persistence rules still apply | +| `auth` decorators | Controllers and services | +| `Principal` | Controllers, services, and repositories | +| Another module's `*.module.ts` | Only from a module file, in `imports` | +| Another module's exported service | Only a service that module exports | +| Another module's entity | Only from an entity, for a relation, and from the entity registry | +| Another module's interface | Only `import type`, when an exported method returns it | +| The contracts package | Any file | + +A module never imports another module's repository, controller, or exception. An exported method returns a contract type, a primitive, or an interface of its own module. + +Modules call each other in process. They never call each other over HTTP. A cycle is an error: move the shared rule to the module that owns the data. diff --git a/plugins/engineering-kit/skills/modular-nestjs/references/typeorm.md b/plugins/engineering-kit/skills/modular-nestjs/references/typeorm.md new file mode 100644 index 0000000..16e513f --- /dev/null +++ b/plugins/engineering-kit/skills/modular-nestjs/references/typeorm.md @@ -0,0 +1,79 @@ +# TypeORM + +## Entities + +- One entity per file. A table entity extends `AuditedEntity`. An insert-only table extends `CreatedEntity`. A view entity extends neither. +- Do not name a base class `BaseEntity`. TypeORM exports a class with that name. +- `AuditedEntity` adds `id`, `created_at`, `updated_at`, `created_by_user_id`, and `updated_by_user_id`. `CreatedEntity` adds `id`, `created_at`, and `created_by_user_id`. +- Actor foreign keys use `@ForeignKey("UserEntity")` with a string target, so the base class does not import the user entity. +- The repository fills actor columns with `actorId(transaction)`. They never come from the request. +- A system process uses the system user that the first migration creates. +- An archivable table also has `archived_at` and `archived_by_user_id`. +- Table names are singular `snake_case`. Quote a reserved word, such as `"user"`, in hand-written SQL. +- Columns are `snake_case` in the database and `camelCase` in the entity, with the `name` option. Declare an explicit `type` on every column. +- Identifiers are UUIDs from `gen_random_uuid()`. Time is `timestamptz`. Money is `numeric`, handled as a string. Never use floating point for money. +- Declare every constraint on the entity and in the migration: primary key, foreign keys, unique, index, and check. +- Name a constraint only when a repository translates its violation into a module exception. +- Every foreign-key column has an index. Foreign keys use `ON DELETE NO ACTION`. Never use `ON DELETE CASCADE`. Never enable `synchronize`. + +## Relations + +- Declare the foreign key as a column, with `@ManyToOne` and `@JoinColumn` on that column. +- An entity may import another module's entity for a relation. The relation is read-only across modules. +- Add `@OneToMany` only when a repository reads through it. +- Do not use `eager` or `cascade`. + +## Many-to-many + +Never use `@ManyToMany`. Create a join entity: + +```text +role ──< role_permission >── permission + id + role_id + permission_id + UNIQUE (role_id, permission_id) +``` + +The join entity extends `AuditedEntity`, has two `@ManyToOne` relations and a unique constraint on the pair, and belongs to the module whose routes change it. The link can then gain columns, audit events, and locks. + +## Queries + +Use the repository API first. Use the query builder when that API cannot express the query or a measured query is too slow. + +| Need | Use | +| --- | --- | +| One row | `reader.findOneBy` or `reader.findOne({ where, select })` | +| List, filters, page, total | `reader.findAndCount` with `pageOptions` | +| Read and lock | `writer(transaction).findOne({ where, lock: { mode: "pessimistic_write" } })` | +| Insert | `writer(transaction).save` or `insert` | +| Conditional update | `writer(transaction).update`; check `affected` | +| A join the repository API cannot express | `createQueryBuilder` with named parameters | +| Grouping or aggregates | Query builder; parse raw rows into a named interface | +| A reused read model | A view mapped with `@ViewEntity` | +| A PostgreSQL feature TypeORM lacks | `query()` with numbered parameters, in a repository only | + +- Pass values as parameters. Never build SQL by joining strings with values. +- Escape `%`, `_`, and `\` before `ILike`. +- Select only the columns the use case needs. +- Load a list and its related rows in one query or one extra `In(...)` query. Never run one query per row. +- Prefer a conditional update to a lock. When a lock is required, lock rows in ascending identifier order. Name the locked tables in a join. +- An advisory lock goes through the database lock helper, called only from a repository or a seed. +- A report lives in the `-reports` topic of the module that owns the data, and it applies the same context rules as a list. + +## Migrations + +- Migrations are forward only. Each keeps the previous application version working during a deployment. +- Generate a migration from the entities, then review it. Add views, functions, grants, and exclusion constraints by hand. +- A migration never imports application code. Copy each constant it needs. +- Fail the schema check when the entities and the migrated schema differ. +- An effective period is `valid_from` and `valid_until` as a half-open range. An overlap rule is an exclusion constraint, declared on the entity with the same name. +- Each migration sets a short `lock_timeout`. +- The API never runs migrations at startup. + +## Seeds + +- A seed is an idempotent upsert keyed by a business code, never by a generated identifier. +- Reference data that the business edits after release is insert-only. +- Seeds reach entity classes only through the entity registry, validate fixture data against the contracts, and run in one transaction under an advisory lock with the system principal. +- Seeds hold synthetic or controlled reference data only. They do not use raw SQL for data. diff --git a/tests/test_packaging.py b/tests/test_packaging.py index 49cb000..770442a 100644 --- a/tests/test_packaging.py +++ b/tests/test_packaging.py @@ -10,8 +10,9 @@ 'competitive-brief', 'ux-friction-research', 'write-prd', 'write-wbs'}, 'engineering-kit': {'adversarial-change-review', 'ai-slop-review', 'architecture', 'clean-sheet-review', 'code-simplifier', 'executing-plans', - 'pull-request-authoring', 'reference-implementation', 'sbvr', - 'webapp-verification', 'writing-plans'}, + 'modular-nestjs', 'pull-request-authoring', + 'reference-implementation', 'sbvr', 'webapp-verification', + 'writing-plans'}, }