@mrciphersmith/keryx 0.4.28 → 0.4.30

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 (132) hide show
  1. package/dist/cli.js +4916 -3655
  2. package/dist/core.js +91 -28
  3. package/dist/keryx-general-worker-entry.js +413 -240
  4. package/package.json +1 -1
  5. package/src/gdskills/bundled/install-manifest.json +3 -0
  6. package/src/gdskills/bundled/rules/core/api-contracts.mdc +21 -136
  7. package/src/gdskills/bundled/rules/core/async-patterns.mdc +18 -171
  8. package/src/gdskills/bundled/rules/core/clean-architecture.mdc +40 -150
  9. package/src/gdskills/bundled/rules/core/cli-interface-design.mdc +63 -194
  10. package/src/gdskills/bundled/rules/core/code-style-patterns.mdc +36 -48
  11. package/src/gdskills/bundled/rules/core/concurrency-patterns.mdc +32 -0
  12. package/src/gdskills/bundled/rules/core/database-patterns.mdc +26 -148
  13. package/src/gdskills/bundled/rules/core/error-handling.mdc +57 -109
  14. package/src/gdskills/bundled/rules/core/frontend-assistant.mdc +14 -29
  15. package/src/gdskills/bundled/rules/core/layout-rendering.mdc +51 -0
  16. package/src/gdskills/bundled/rules/core/mobx-store-template.mdc +69 -511
  17. package/src/gdskills/bundled/rules/core/nestjs-dto.mdc +18 -36
  18. package/src/gdskills/bundled/rules/core/playwright-testing.mdc +35 -308
  19. package/src/gdskills/bundled/rules/core/security-baseline.mdc +18 -140
  20. package/src/gdskills/bundled/rules/core/skill-authoring.mdc +190 -0
  21. package/src/gdskills/bundled/rules/core/skills-storage-workflow.mdc +5 -0
  22. package/src/gdskills/bundled/rules/core/solid-principles.mdc +70 -121
  23. package/src/gdskills/bundled/rules/core/storybook-guidelines.mdc +20 -22
  24. package/src/gdskills/bundled/rules/core/tdd-workflow.mdc +37 -74
  25. package/src/gdskills/bundled/rules/core/ui-anti-slop.mdc +48 -37
  26. package/src/gdskills/bundled/skills/orchestration/task-implementer/SKILL.md +2 -2
  27. package/src/gdskills/bundled/skills/quality/deprecation-path/SKILL.md +1 -1
  28. package/src/gdskills/bundled/skills/quality/tests-creator/SKILL.md +1 -1
  29. package/src/gdskills/bundled/skills/review/review-architecture/SKILL.md +25 -61
  30. package/src/gdskills/bundled/skills/review/review-backend/SKILL.md +15 -69
  31. package/src/gdskills/bundled/skills/review/review-clean-code/SKILL.md +84 -418
  32. package/src/gdskills/bundled/skills/review/review-core-boundaries/SKILL.md +2 -2
  33. package/src/gdskills/bundled/skills/review/review-degradation/SKILL.md +1 -1
  34. package/src/gdskills/bundled/skills/review/review-flow-graph/SKILL.md +1 -1
  35. package/src/gdskills/bundled/skills/review/review-frontend/SKILL.md +17 -311
  36. package/src/gdskills/bundled/skills/review/review-frontend-conventions/SKILL.md +8 -22
  37. package/src/gdskills/bundled/skills/review/review-highload/SKILL.md +84 -228
  38. package/src/gdskills/bundled/skills/review/review-layout/SKILL.md +22 -28
  39. package/src/gdskills/bundled/skills/review/review-logic/SKILL.md +9 -10
  40. package/src/gdskills/bundled/skills/review/review-performance/SKILL.md +16 -38
  41. package/src/gdskills/bundled/skills/review/review-premise/SKILL.md +1 -1
  42. package/src/gdskills/bundled/skills/review/review-regression/SKILL.md +1 -1
  43. package/src/gdskills/bundled/skills/review/review-security-code/SKILL.md +8 -8
  44. package/src/gdskills/bundled/skills/review/review-style/SKILL.md +49 -88
  45. package/src/gdskills/bundled/skills/review/review-testing-practices/SKILL.md +22 -40
  46. package/src/gdskills/bundled/skills/review/review-ui-ux/SKILL.md +42 -82
  47. package/src/gdskills/bundled/stacks/angular/rules/coding-style.mdc +15 -57
  48. package/src/gdskills/bundled/stacks/angular/rules/patterns.mdc +16 -60
  49. package/src/gdskills/bundled/stacks/angular/rules/security.mdc +11 -49
  50. package/src/gdskills/bundled/stacks/angular/rules/testing.mdc +13 -52
  51. package/src/gdskills/bundled/stacks/c-cpp/rules/coding-style.mdc +33 -57
  52. package/src/gdskills/bundled/stacks/c-cpp/rules/patterns.mdc +35 -62
  53. package/src/gdskills/bundled/stacks/c-cpp/rules/security.mdc +35 -62
  54. package/src/gdskills/bundled/stacks/c-cpp/rules/testing.mdc +34 -54
  55. package/src/gdskills/bundled/stacks/ci-github-gitlab/rules/patterns.mdc +27 -56
  56. package/src/gdskills/bundled/stacks/ci-github-gitlab/rules/security.mdc +51 -119
  57. package/src/gdskills/bundled/stacks/csharp-dotnet/rules/coding-style.mdc +42 -74
  58. package/src/gdskills/bundled/stacks/csharp-dotnet/rules/patterns.mdc +45 -83
  59. package/src/gdskills/bundled/stacks/csharp-dotnet/rules/security.mdc +34 -59
  60. package/src/gdskills/bundled/stacks/csharp-dotnet/rules/testing.mdc +33 -62
  61. package/src/gdskills/bundled/stacks/django/rules/coding-style.mdc +15 -56
  62. package/src/gdskills/bundled/stacks/django/rules/patterns.mdc +16 -68
  63. package/src/gdskills/bundled/stacks/django/rules/security.mdc +13 -71
  64. package/src/gdskills/bundled/stacks/django/rules/testing.mdc +16 -62
  65. package/src/gdskills/bundled/stacks/docker-k8s-terraform/rules/coding-style.mdc +30 -53
  66. package/src/gdskills/bundled/stacks/docker-k8s-terraform/rules/patterns.mdc +20 -56
  67. package/src/gdskills/bundled/stacks/docker-k8s-terraform/rules/security.mdc +52 -122
  68. package/src/gdskills/bundled/stacks/docker-k8s-terraform/rules/testing.mdc +23 -42
  69. package/src/gdskills/bundled/stacks/fastapi/rules/coding-style.mdc +13 -47
  70. package/src/gdskills/bundled/stacks/fastapi/rules/patterns.mdc +18 -81
  71. package/src/gdskills/bundled/stacks/fastapi/rules/security.mdc +13 -75
  72. package/src/gdskills/bundled/stacks/fastapi/rules/testing.mdc +14 -58
  73. package/src/gdskills/bundled/stacks/flutter-dart/rules/coding-style.mdc +36 -74
  74. package/src/gdskills/bundled/stacks/flutter-dart/rules/patterns.mdc +30 -66
  75. package/src/gdskills/bundled/stacks/flutter-dart/rules/security.mdc +33 -67
  76. package/src/gdskills/bundled/stacks/flutter-dart/rules/testing.mdc +41 -73
  77. package/src/gdskills/bundled/stacks/go/rules/coding-style.mdc +36 -57
  78. package/src/gdskills/bundled/stacks/go/rules/patterns.mdc +27 -42
  79. package/src/gdskills/bundled/stacks/go/rules/security.mdc +26 -43
  80. package/src/gdskills/bundled/stacks/go/rules/testing.mdc +23 -41
  81. package/src/gdskills/bundled/stacks/java-kotlin-spring/rules/coding-style.mdc +21 -40
  82. package/src/gdskills/bundled/stacks/java-kotlin-spring/rules/patterns.mdc +26 -43
  83. package/src/gdskills/bundled/stacks/java-kotlin-spring/rules/security.mdc +25 -37
  84. package/src/gdskills/bundled/stacks/java-kotlin-spring/rules/testing.mdc +34 -50
  85. package/src/gdskills/bundled/stacks/kotlin-android/rules/coding-style.mdc +28 -65
  86. package/src/gdskills/bundled/stacks/kotlin-android/rules/patterns.mdc +34 -78
  87. package/src/gdskills/bundled/stacks/kotlin-android/rules/security.mdc +35 -68
  88. package/src/gdskills/bundled/stacks/kotlin-android/rules/testing.mdc +34 -68
  89. package/src/gdskills/bundled/stacks/mobx/rules/coding-style.mdc +18 -64
  90. package/src/gdskills/bundled/stacks/mobx/rules/patterns.mdc +13 -66
  91. package/src/gdskills/bundled/stacks/mobx/rules/security.mdc +8 -35
  92. package/src/gdskills/bundled/stacks/mobx/rules/testing.mdc +10 -39
  93. package/src/gdskills/bundled/stacks/nestjs/rules/coding-style.mdc +32 -45
  94. package/src/gdskills/bundled/stacks/nestjs/rules/patterns.mdc +40 -60
  95. package/src/gdskills/bundled/stacks/nestjs/rules/security.mdc +30 -50
  96. package/src/gdskills/bundled/stacks/nestjs/rules/testing.mdc +27 -47
  97. package/src/gdskills/bundled/stacks/nextjs-nuxt/rules/coding-style.mdc +14 -48
  98. package/src/gdskills/bundled/stacks/nextjs-nuxt/rules/patterns.mdc +15 -67
  99. package/src/gdskills/bundled/stacks/nextjs-nuxt/rules/security.mdc +12 -50
  100. package/src/gdskills/bundled/stacks/nextjs-nuxt/rules/testing.mdc +11 -43
  101. package/src/gdskills/bundled/stacks/php-laravel/rules/coding-style.mdc +17 -58
  102. package/src/gdskills/bundled/stacks/php-laravel/rules/patterns.mdc +15 -56
  103. package/src/gdskills/bundled/stacks/php-laravel/rules/security.mdc +13 -50
  104. package/src/gdskills/bundled/stacks/php-laravel/rules/testing.mdc +14 -55
  105. package/src/gdskills/bundled/stacks/python/rules/coding-style.mdc +13 -41
  106. package/src/gdskills/bundled/stacks/python/rules/patterns.mdc +20 -61
  107. package/src/gdskills/bundled/stacks/python/rules/security.mdc +15 -57
  108. package/src/gdskills/bundled/stacks/python/rules/testing.mdc +16 -50
  109. package/src/gdskills/bundled/stacks/react/rules/coding-style.mdc +14 -40
  110. package/src/gdskills/bundled/stacks/react/rules/patterns.mdc +15 -55
  111. package/src/gdskills/bundled/stacks/react/rules/security.mdc +13 -49
  112. package/src/gdskills/bundled/stacks/react/rules/testing.mdc +10 -37
  113. package/src/gdskills/bundled/stacks/ruby-rails/rules/coding-style.mdc +15 -48
  114. package/src/gdskills/bundled/stacks/ruby-rails/rules/patterns.mdc +18 -67
  115. package/src/gdskills/bundled/stacks/ruby-rails/rules/security.mdc +11 -60
  116. package/src/gdskills/bundled/stacks/ruby-rails/rules/testing.mdc +14 -65
  117. package/src/gdskills/bundled/stacks/rust/rules/coding-style.mdc +39 -65
  118. package/src/gdskills/bundled/stacks/rust/rules/patterns.mdc +33 -60
  119. package/src/gdskills/bundled/stacks/rust/rules/security.mdc +35 -57
  120. package/src/gdskills/bundled/stacks/rust/rules/testing.mdc +29 -52
  121. package/src/gdskills/bundled/stacks/sql-db/rules/coding-style.mdc +12 -48
  122. package/src/gdskills/bundled/stacks/sql-db/rules/patterns.mdc +22 -113
  123. package/src/gdskills/bundled/stacks/sql-db/rules/security.mdc +11 -56
  124. package/src/gdskills/bundled/stacks/sql-db/rules/testing.mdc +14 -59
  125. package/src/gdskills/bundled/stacks/swift-ios/rules/coding-style.mdc +29 -65
  126. package/src/gdskills/bundled/stacks/swift-ios/rules/patterns.mdc +41 -88
  127. package/src/gdskills/bundled/stacks/swift-ios/rules/security.mdc +28 -53
  128. package/src/gdskills/bundled/stacks/swift-ios/rules/testing.mdc +32 -65
  129. package/src/gdskills/bundled/stacks/vue/rules/coding-style.mdc +17 -52
  130. package/src/gdskills/bundled/stacks/vue/rules/patterns.mdc +17 -63
  131. package/src/gdskills/bundled/stacks/vue/rules/security.mdc +11 -41
  132. package/src/gdskills/bundled/stacks/vue/rules/testing.mdc +16 -48
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mrciphersmith/keryx",
3
- "version": "0.4.28",
3
+ "version": "0.4.30",
4
4
  "description": "Version-controlled project context for AI coding agents: code graph, architecture wiki, project memory, relevant tests, quality signals, and task flows.",
5
5
  "private": false,
6
6
  "publishConfig": {
@@ -370,6 +370,7 @@
370
370
  "src/gdskills/bundled/rules/core/code-review-learned-profile.mdc",
371
371
  "src/gdskills/bundled/rules/core/code-style-patterns.mdc",
372
372
  "src/gdskills/bundled/rules/core/commit-message-formatting.mdc",
373
+ "src/gdskills/bundled/rules/core/concurrency-patterns.mdc",
373
374
  "src/gdskills/bundled/rules/core/database-patterns.mdc",
374
375
  "src/gdskills/bundled/rules/core/definition-of-done.mdc",
375
376
  "src/gdskills/bundled/rules/core/documentation-management.mdc",
@@ -381,6 +382,7 @@
381
382
  "src/gdskills/bundled/rules/core/implementation-doc-mandate.mdc",
382
383
  "src/gdskills/bundled/rules/core/implementation-plans.mdc",
383
384
  "src/gdskills/bundled/rules/core/jobs-documentation.mdc",
385
+ "src/gdskills/bundled/rules/core/layout-rendering.mdc",
384
386
  "src/gdskills/bundled/rules/core/model-selection.mdc",
385
387
  "src/gdskills/bundled/rules/core/playwright-testing.mdc",
386
388
  "src/gdskills/bundled/rules/core/requirements-management.mdc",
@@ -389,6 +391,7 @@
389
391
  "src/gdskills/bundled/rules/core/security-baseline.mdc",
390
392
  "src/gdskills/bundled/rules/core/session-plan-bridge.mdc",
391
393
  "src/gdskills/bundled/rules/core/shared-definitions.mdc",
394
+ "src/gdskills/bundled/rules/core/skill-authoring.mdc",
392
395
  "src/gdskills/bundled/rules/core/skills-storage-workflow.mdc",
393
396
  "src/gdskills/bundled/rules/core/solid-principles.mdc",
394
397
  "src/gdskills/bundled/rules/core/storybook-guidelines.mdc",
@@ -1,151 +1,36 @@
1
1
  ---
2
- description: "API contract rules: OpenAPI-first design, semantic versioning, no breaking changes without major version bump, contract testing. Use when designing, modifying, or consuming HTTP APIs."
2
+ description: "API contract standard shared by code writers and reviewers, with the severities reviewers use: spec first, no breaking change without a new major version, one error envelope, 400 for validation failures, idempotency keys on creating mutations, paginated list envelopes. Use when designing, changing or consuming HTTP APIs."
3
3
  alwaysApply: false
4
4
  stack_requires: "http-server"
5
5
  ---
6
6
 
7
7
  # API Contracts
8
8
 
9
- ## Purpose
10
- Prevent silent breaking changes, version drift, and undocumented API behaviour. Enforce OpenAPI-first design and strict versioning discipline.
11
-
12
- ## When To Apply
13
- Apply when creating new API endpoints, modifying existing endpoints, changing DTOs/schemas, or writing API client code.
14
-
15
- ---
16
-
17
- ## Core Principle: Contract Before Code
18
-
19
- The OpenAPI spec (or equivalent schema) is the source of truth. Code is generated from or validated against the spec — not the other way around.
20
-
21
- ```
22
- 1. Design the endpoint in OpenAPI/schema first
23
- 2. Review the contract for breaking changes
24
- 3. Generate or update types/validators from the spec
25
- 4. Implement the handler
26
- 5. Write contract tests that validate the spec is honoured
27
- ```
28
-
29
- ---
9
+ Canon applies: OpenAPI 3, RFC 9110 status-code semantics, semantic versioning. This rule holds only this project's decisions.
30
10
 
31
11
  ## Rules
32
12
 
33
- ### Rule 1: OpenAPI-First for New Endpoints
34
- Every new HTTP endpoint MUST have an OpenAPI 3.x definition before the handler is implemented:
35
-
36
- ```yaml
37
- # Required fields for every endpoint definition
38
- paths:
39
- /users/{id}:
40
- get:
41
- operationId: getUser # unique, stable identifier
42
- summary: Get user by ID
43
- parameters:
44
- - name: id
45
- in: path
46
- required: true
47
- schema: { type: string, format: uuid }
48
- responses:
49
- '200':
50
- description: User found
51
- content:
52
- application/json:
53
- schema: { $ref: '#/components/schemas/User' }
54
- '404':
55
- $ref: '#/components/responses/NotFound'
56
- '401':
57
- $ref: '#/components/responses/Unauthorized'
58
- ```
59
-
60
- **Required for every endpoint:**
61
- - `operationId` (stable, unique)
62
- - All path/query/header parameters documented
63
- - All response codes documented (including 4xx, 5xx)
64
- - Request body schema referenced (not inlined) for reuse
65
-
66
- ### Rule 2: Semantic Versioning for APIs
67
-
68
- | Change Type | Version Impact | Action Required |
69
- |---|---|---|
70
- | Add optional field to response | None / patch | Safe — backwards compatible |
71
- | Add optional field to request | None / patch | Safe — old clients omit it |
72
- | Add new endpoint | Minor bump | Document in changelog |
73
- | Make optional field required | **Major bump** | Breaking change |
74
- | Remove field from response | **Major bump** | Breaking change |
75
- | Rename field | **Major bump** | Breaking change |
76
- | Change field type | **Major bump** | Breaking change |
77
- | Remove endpoint | **Major bump** | Deprecate first, remove in next major |
78
-
79
- **Breaking change protocol:**
80
- 1. Add deprecation notice to old version (`deprecated: true` in OpenAPI)
81
- 2. Implement new version at `/v{N+1}/...` or with new operationId
82
- 3. Run old version in parallel for ≥1 release cycle
83
- 4. Remove old version only after clients have migrated
84
-
85
- ### Rule 3: Contract Testing
86
- Every public API endpoint MUST have at least one contract test that:
87
- - Validates the response shape matches the OpenAPI schema
88
- - Tests the error responses (at minimum: 400, 404, 401 where applicable)
89
- - Uses schema validation, not string matching
90
-
91
- ```typescript
92
- // Example: contract test using a schema validator
93
- describe('GET /users/:id contract', () => {
94
- it('returns User schema on 200', async () => {
95
- const res = await request(app).get('/users/valid-id');
96
- expect(res.status).toBe(200);
97
- expect(res.body).toMatchSchema(UserSchema); // validated against OpenAPI
98
- });
99
-
100
- it('returns 404 with NotFound schema on unknown id', async () => {
101
- const res = await request(app).get('/users/nonexistent');
102
- expect(res.status).toBe(404);
103
- expect(res.body).toMatchSchema(NotFoundSchema);
104
- });
105
- });
106
- ```
107
-
108
- ### Rule 4: No Undocumented Fields
109
- Every field in a request or response body MUST appear in the schema. Fields not in the schema must be stripped from responses (`additionalProperties: false` in JSON Schema).
110
-
111
- ### Rule 5: Consistent Error Schema
112
- All error responses must use the same envelope schema:
113
-
114
- ```typescript
115
- interface ApiError {
116
- code: string; // machine-readable, e.g. "USER_NOT_FOUND"
117
- message: string; // human-readable
118
- details?: unknown; // optional structured context
119
- requestId: string; // for traceability
120
- }
121
- ```
122
-
123
- Never return raw Error objects, stack traces, or ORM error messages to API consumers.
124
-
125
- ### Rule 6: Idempotency Keys for Mutations
126
- POST/PUT/PATCH endpoints that create or modify state MUST support idempotency via `Idempotency-Key` header or a stable `clientId` in the body. This prevents duplicate operations on network retry.
127
-
128
- ---
129
-
130
- ## The three that are not negotiable
131
-
132
- Of the rules above, three carry consequences that outlive the change: no breaking
133
- change ships without a major version bump and a deprecation period; the OpenAPI
134
- spec is updated before the implementation, not after it as documentation; and
135
- error responses use the standard `ApiError` envelope — never a raw exception or
136
- an ad-hoc shape.
13
+ 1. **Spec first.** A new or changed endpoint is in the OpenAPI spec (or the project's equivalent schema) in the same change, before the handler: a stable `operationId`, every parameter, every response code including 4xx, request bodies by reference.
14
+ 2. **No breaking change inside a major version.** Removing, renaming or retyping a field, making an optional field required, removing an endpoint or changing what a status code means ships at `/v{N+1}` next to the old version, which is marked `deprecated` and kept for at least one release. Adding an optional field or a new endpoint is not breaking.
15
+ 3. **Every field in a request or response is in the schema**; undocumented response fields are stripped (`additionalProperties: false`).
16
+ 4. **One error envelope:** `{ code, message, details?, requestId }` for every error response. Never a raw exception, stack trace or ORM message. A validation failure answers `400`.
17
+ 5. **Creating mutations accept an `Idempotency-Key`** (POST that creates a record, moves money or reserves stock). A transition that is idempotent by itself (repeating it leaves the same state) needs none; say so in a comment.
18
+ 6. **Lists** return the same envelope as the API's other lists (e.g. `{ data, meta }`) and are paginated unless the list is bounded small by construction.
19
+ 7. **Contract tests:** each public endpoint has a test that validates its response and its error responses against the schema.
137
20
 
138
21
  ---
139
22
 
140
- ## Red Flags — Stop and re-read this rule if you are thinking:
23
+ ## Review severities (shared with reviewers)
141
24
 
142
- | Rationalization | Why it's wrong |
143
- |---|---|
144
- | "It's just adding a field, that's not breaking" | Removing a field later will be breaking — document it now to establish the contract |
145
- | "The spec can wait, I'll document it later" | Specs written after code document what the code does, not what it should do — bugs get documented too |
146
- | "Renaming a field is internal, consumers will adapt" | Consumers have no way to know a field was renamed — this silently breaks every client |
147
- | "I'll use v2 later if needed, for now v1 is fine" | Delaying versioning means v1 can never be changed without breaking consumers |
148
- | "Contract tests slow down development" | Contract tests catch breaking changes before they reach consumers — not after |
149
- | "The error format doesn't matter as long as the status code is right" | Status codes alone are insufficient for automated error handling — codes and schemas matter |
25
+ `review-backend` rates these patterns by this table. Change a row here, never in a reviewer.
150
26
 
151
- **IRON LAW: A BREAKING CHANGE WITHOUT A VERSION BUMP IS A PRODUCTION INCIDENT WAITING TO HAPPEN.**
27
+ | Signal | A finding when | Default | Not a finding |
28
+ |---|---|---|---|
29
+ | Breaking change inside a major version (Rule 2) | the endpoint is published or clients are generated | `major` | an endpoint with no released consumer |
30
+ | Endpoint, parameter or field missing from the spec (Rules 1, 3) | always | `major` when clients are generated from the spec; else `minor` | — |
31
+ | Error response outside the envelope (Rule 4) | it reaches a client | `major`; a leaked stack trace or ORM message is rated by `review-security-code` | — |
32
+ | Validation failure answered with a status other than `400` (Rule 4) | always | `minor` | — |
33
+ | Creating mutation with no idempotency key (Rule 5) | a retry duplicates money, stock or a record users see | `major`; `minor` for other records | a transition idempotent by itself |
34
+ | List with a different envelope from its siblings (Rule 6) | always | `minor`; changing an existing list's shape is Rule 2 | — |
35
+ | Unbounded list with no pagination (Rule 6) | the size grows with stored data | `major`; `blocker` where an attacker-reachable request exhausts memory | a list bounded small by construction, with the bound read |
36
+ | Public endpoint with no contract test (Rule 7) | always | `minor` | — |
@@ -1,185 +1,32 @@
1
1
  ---
2
- description: "Async patterns: Promise.all for parallelism, no unhandled rejections, mandatory timeouts for external calls, no blocking the event loop. Use when writing async/await code, parallel operations, or queue consumers."
2
+ description: "Async patterns standard shared by code writers and reviewers, with the severities reviewers use: independent awaits run in parallel, a timeout on every external call, bounded fan-out, no event-loop blocking. Use when writing or reviewing async/await code, parallel operations, or queue consumers."
3
3
  alwaysApply: false
4
4
  ---
5
5
 
6
6
  # Async Patterns
7
7
 
8
- ## Purpose
9
- Prevent common async pitfalls: sequential execution where parallel is safe, unhandled promise rejections, missing timeouts, and event loop blockage.
10
-
11
- ## When To Apply
12
- Apply when writing any `async`/`await` code, calling external services, processing queues, or coordinating multiple async operations.
13
-
14
- ---
8
+ Canon applies: `Promise.all` / `allSettled` semantics (MDN), the Node.js "Don't Block the Event Loop" guide, `@typescript-eslint/no-floating-promises`. This rule holds only this project's decisions.
15
9
 
16
10
  ## Rules
17
11
 
18
- ### Rule 1: Use Promise.all for Independent Operations
19
-
20
- Sequential await for independent operations wastes time. Run them in parallel.
21
-
22
- ```typescript
23
- // BAD — sequential: takes 300ms (100 + 100 + 100)
24
- const user = await fetchUser(id);
25
- const orders = await fetchOrders(id);
26
- const prefs = await fetchPreferences(id);
27
-
28
- // GOOD — parallel: takes 100ms (max of 100, 100, 100)
29
- const [user, orders, prefs] = await Promise.all([
30
- fetchUser(id),
31
- fetchOrders(id),
32
- fetchPreferences(id),
33
- ]);
34
- ```
35
-
36
- **Rule:** If operation B does not depend on the result of operation A, they MUST run in parallel.
37
-
38
- ### Rule 2: Use Promise.allSettled When Partial Failure is Acceptable
39
-
40
- ```typescript
41
- // BAD — one failure cancels all
42
- const results = await Promise.all([criticalOp(), optionalOp()]); // if optionalOp rejects, criticalOp result is lost
43
-
44
- // GOOD — each result handled independently
45
- const [critical, optional] = await Promise.allSettled([criticalOp(), optionalOp()]);
46
- if (critical.status === 'rejected') throw critical.reason;
47
- if (optional.status === 'rejected') logger.warn('optional failed', optional.reason);
48
- ```
49
-
50
- Use `Promise.all` when ALL operations are required. Use `Promise.allSettled` when SOME can fail gracefully.
51
-
52
- ### Rule 3: Every External Call Has a Timeout
53
-
54
- Network calls without timeouts hang indefinitely, blocking resources.
55
-
56
- ```typescript
57
- // BAD — hangs forever if service is down
58
- const response = await fetch('https://api.external.com/data');
59
-
60
- // GOOD — fails fast after 5 seconds
61
- const controller = new AbortController();
62
- const timeout = setTimeout(() => controller.abort(), 5_000);
63
- try {
64
- const response = await fetch('https://api.external.com/data', { signal: controller.signal });
65
- // ...
66
- } finally {
67
- clearTimeout(timeout);
68
- }
69
-
70
- // GOOD — with a utility wrapper
71
- const response = await fetchWithTimeout('https://api.external.com/data', { timeout: 5_000 });
72
- ```
73
-
74
- **Default timeouts:**
75
- - Internal service calls: 3s
76
- - External API calls: 10s
77
- - Long-running operations (file processing, ML): 60s with progress events
78
- - Database queries: configure at connection pool level
79
-
80
- ### Rule 4: No Unhandled Promise Rejections
81
-
82
- Every promise must have a `.catch()` or be `await`-ed inside a `try/catch`.
83
-
84
- ```typescript
85
- // BAD — fire-and-forget without error handling
86
- sendNotification(userId, message); // rejection is swallowed silently
87
-
88
- // BAD — floating promise in Express handler
89
- app.get('/data', (req, res) => {
90
- loadData(); // not awaited, errors don't propagate to response
91
- res.json({ ok: true });
92
- });
93
-
94
- // GOOD — fire-and-forget with explicit error handling
95
- sendNotification(userId, message).catch(err => {
96
- logger.error('notification failed', { userId, err });
97
- });
98
-
99
- // GOOD — awaited in async handler
100
- app.get('/data', async (req, res) => {
101
- const data = await loadData();
102
- res.json(data);
103
- });
104
- ```
105
-
106
- ### Rule 5: No CPU-Blocking Operations on the Event Loop
107
-
108
- Operations that block the event loop starve all other concurrent requests:
109
- - `JSON.parse` / `JSON.stringify` on payloads > 1MB → use streaming
110
- - Synchronous file reads in hot paths → use `fs.promises.*`
111
- - CPU-intensive loops → offload to worker threads
112
- - Synchronous crypto operations → use `crypto.subtle` or async equivalents
113
-
114
- ```typescript
115
- // BAD — blocks event loop for large payload
116
- app.post('/import', (req, res) => {
117
- const data = JSON.parse(req.body.payload); // synchronous, large payload blocks
118
- });
119
-
120
- // GOOD — streaming parse
121
- import { pipeline } from 'stream/promises';
122
- app.post('/import', async (req, res) => {
123
- await pipeline(req, new JSONStreamParser(), new DataProcessor());
124
- });
125
- ```
126
-
127
- ### Rule 6: Batch Async Operations with Controlled Concurrency
128
-
129
- Running N async operations at once can overwhelm downstream services. Use a concurrency limiter:
130
-
131
- ```typescript
132
- // BAD — 1000 parallel requests to an API
133
- await Promise.all(items.map(item => processItem(item)));
134
-
135
- // GOOD — max 10 concurrent operations
136
- import PLimit from 'p-limit';
137
- const limit = PLimit(10);
138
- await Promise.all(items.map(item => limit(() => processItem(item))));
139
- ```
140
-
141
- ### Rule 7: Async Initialization Pattern
142
-
143
- Classes with async setup must not use the constructor for initialization:
144
-
145
- ```typescript
146
- // BAD — constructor cannot be async
147
- class DatabasePool {
148
- constructor() {
149
- this.pool = await createPool(); // syntax error
150
- }
151
- }
152
-
153
- // GOOD — factory method pattern
154
- class DatabasePool {
155
- private constructor(private readonly pool: Pool) {}
156
-
157
- static async create(): Promise<DatabasePool> {
158
- const pool = await createPool();
159
- return new DatabasePool(pool);
160
- }
161
- }
162
- const db = await DatabasePool.create();
163
- ```
164
-
165
- ---
166
-
167
- ## Iron Laws
168
-
169
- **IRON LAW 1: Sequential await for independent operations is a performance bug. Use Promise.all.**
170
- **IRON LAW 2: Every external HTTP call must have an explicit timeout configured.**
171
- **IRON LAW 3: A floating promise (not awaited, no .catch) is an unhandled rejection waiting to crash the process.**
12
+ 1. **Independent awaits run in parallel.** If B does not depend on A, use `Promise.all`; use `Promise.allSettled` when some results are optional, and handle each rejection.
13
+ 2. **Every external call has a timeout**, set with `AbortSignal.timeout(ms)`. Defaults: internal service 3s, external API 10s, long-running work 60s with progress events; database queries at the connection-pool level.
14
+ 3. **Bound fan-out.** Mapping a large collection to promises uses a concurrency limit; default 10.
15
+ 4. **Do not block the event loop.** `JSON.parse` / `JSON.stringify` of a payload over 1MB, sync file reads in hot paths and CPU-heavy loops go to a stream, `fs.promises` or a worker thread.
16
+ 5. **Rejections** are handled per `error-handling.mdc` Rule 4.
172
17
 
173
18
  ---
174
19
 
175
- ## Red Flags — Stop and re-read this rule if you are thinking:
20
+ ## Review severities (shared with reviewers)
176
21
 
177
- | Rationalization | Why it's wrong |
178
- |---|---|
179
- | "I'll add a timeout later if it's needed" | Missing timeouts are invisible until a downstream service hangs — add them when the call is written |
180
- | "The operation is fast, sequential await is fine" | Sequential operations that are "fast" become bottlenecks under load |
181
- | "I don't need to await this, it's just a side effect" | Fire-and-forget without `.catch` silently loses errors that may indicate data corruption |
182
- | "Promise.allSettled is verbose, I'll use Promise.all and handle errors in each function" | Promise.all cancels all operations on first rejection — allSettled gives you full control |
183
- | "Concurrency limiting adds complexity" | Uncontrolled concurrency causes rate limit errors, OOM, and cascading failures downstream |
22
+ `review-logic` rates these patterns by this table. Change a row here, never in a reviewer.
184
23
 
185
- **IRON LAW: AN ASYNC FUNCTION THAT CAN HANG INDEFINITELY IS A DENIAL-OF-SERVICE VULNERABILITY.**
24
+ | Signal | A finding when | Default | Not a finding |
25
+ |---|---|---|---|
26
+ | Sequential independent awaits (Rule 1) | always | `minor`; `major` on a hot path or when the calls are many | an ordering the code depends on |
27
+ | `Promise.all` where an optional result's failure discards a required one (Rule 1) | a named optional call can reject | `major` | all results required |
28
+ | External call with no timeout (Rule 2) | the call can hang a request or worker | `major` | a timeout set at the client or pool |
29
+ | Timeout built from `AbortController` + `setTimeout` (Rule 2) | always | `minor` | — |
30
+ | Unbounded fan-out over a caller-sized collection (Rule 3) | the size is not fixed small | `major` on a hot path, else `minor` | a collection of known small size |
31
+ | Event-loop blocking on a request path (Rule 4) | a named input size or path reaches it | `major` | startup or one-off scripts |
32
+ | Unhandled rejection (Rule 5) | per `error-handling.mdc` **Review severities** | as there | as there |
@@ -6,158 +6,48 @@ alwaysApply: false
6
6
  # Clean Architecture
7
7
 
8
8
  ## Purpose
9
- Enforce correct dependency direction across architectural layers. Business logic must not depend on frameworks, databases, or UI. Changes to infrastructure must not require changes to domain logic.
9
+ Backend layering follows Clean Architecture (Robert C. Martin): presentation, application,
10
+ domain and infrastructure, with dependencies pointing inward and a domain that imports no
11
+ framework, ORM or external SDK. This rule holds only what that name leaves open.
10
12
 
11
13
  ## When To Apply
12
- Apply when creating new modules, services, or features; when deciding where to place a new class or function; when wiring up dependencies between layers.
14
+ Apply to backend code when creating new modules, services, or features; when deciding where to place a new class or function; when wiring up dependencies between layers. Frontend layering (service → store → component, business logic in the store) is `code-style-patterns.mdc`, not this rule.
15
+
16
+ ## Mandatory Behavior
17
+
18
+ - **Business rules live in domain entities and domain services**, not in use cases. A use
19
+ case coordinates repositories and domain services and owns the transaction; a controller
20
+ parses input, calls one use case and formats the output.
21
+ - **A controller that queries the database is a layer violation**: there is no
22
+ thin-controller exception, and it is rated by Review severities below.
23
+ - **A repository is the I/O boundary that gets an interface** (`solid-principles.mdc`,
24
+ D): the interface is declared in the domain, the implementation lives in infrastructure.
25
+ - **Each boundary maps its own types.** A persistence row never reaches a controller, and a
26
+ request DTO never enters a domain entity. Request DTOs belong to presentation, use-case
27
+ input and output to application, persistence models to infrastructure.
28
+ - **A use case or transaction that changes more than 2 domain aggregates is split.**
29
+ - **A module's public API is its index exports.** Importing another module's internal files
30
+ (`b/internal/...`) crosses its boundary.
31
+ - **Project size is not an exemption**: the layers apply to a small service too.
32
+ - **Layout:** follow the project's existing layout. With none, use
33
+ `src/{domain,application,infrastructure,presentation}/<module>/`.
34
+
35
+ The check for a change: replacing the database or the transport changes no domain file.
13
36
 
14
37
  ---
15
38
 
16
- ## Layer Model
17
-
18
- ```
19
- ┌─────────────────────────────────────┐
20
- │ Presentation Layer │ Controllers, API handlers, CLI commands
21
- ├─────────────────────────────────────┤
22
- │ Application Layer │ Use cases, orchestration, DTOs
23
- ├─────────────────────────────────────┤
24
- │ Domain Layer │ Entities, value objects, domain services
25
- ├─────────────────────────────────────┤
26
- │ Infrastructure Layer │ DB, HTTP clients, queues, filesystem
27
- └─────────────────────────────────────┘
28
- ```
29
-
30
- **The Dependency Rule:** Dependencies point INWARD only.
31
- - Infrastructure → Domain (ok)
32
- - Application → Domain (ok)
33
- - Presentation → Application (ok)
34
- - Domain → Infrastructure (FORBIDDEN)
35
- - Domain → Framework (FORBIDDEN)
36
-
37
- ---
38
-
39
- ## Rules
40
-
41
- ### Rule 1: Domain Layer Has No Framework Imports
42
- The domain layer must import nothing from:
43
- - ORM packages (`prisma`, `typeorm`, `mongoose`)
44
- - HTTP frameworks (`express`, `fastapi`, `nestjs`)
45
- - External SDKs (AWS SDK, Stripe, etc.)
46
-
47
- ```typescript
48
- // BAD — domain entity knows about Prisma
49
- import { Prisma } from '@prisma/client';
50
- class Order {
51
- static fromPrisma(row: Prisma.OrderGetPayload<{}>): Order {}
52
- }
53
-
54
- // GOOD — domain is pure TypeScript
55
- class Order {
56
- constructor(
57
- readonly id: OrderId,
58
- readonly status: OrderStatus,
59
- readonly lines: OrderLine[],
60
- ) {}
61
- }
62
- ```
63
-
64
- ### Rule 2: Repositories Are Interfaces in Domain, Implementations in Infrastructure
65
-
66
- ```typescript
67
- // Domain layer — interface only
68
- export interface OrderRepository {
69
- findById(id: OrderId): Promise<Order | null>;
70
- save(order: Order): Promise<void>;
71
- }
72
-
73
- // Infrastructure layer — concrete implementation
74
- export class PrismaOrderRepository implements OrderRepository {
75
- constructor(private readonly prisma: PrismaClient) {}
76
- async findById(id: OrderId) { /* ... */ }
77
- async save(order: Order) { /* ... */ }
78
- }
79
- ```
80
-
81
- ### Rule 3: DTOs Live at Layer Boundaries
82
- - **Request DTOs** (validation) → Presentation layer
83
- - **Application DTOs** (use-case input/output) → Application layer
84
- - **Domain objects** → Domain layer
85
- - **Persistence models** → Infrastructure layer
86
-
87
- Never pass a Prisma row directly to a controller, or a request DTO directly into a domain entity.
88
-
89
- ### Rule 4: Use Cases Orchestrate, Domain Encapsulates Logic
90
- - Use cases (Application layer): coordinate repositories and domain services, handle transactions
91
- - Domain entities: contain business rules, invariants, validations
92
- - Controllers: parse input, call use case, format output — nothing else
93
-
94
- ```typescript
95
- // BAD — business logic leaking into controller
96
- app.post('/orders', async (req, res) => {
97
- if (req.body.items.length === 0) { /* domain rule in controller */ }
98
- const discounted = req.body.total * 0.9; /* domain logic */
99
- await db.orders.create({ data: req.body }); /* infrastructure in controller */
100
- });
101
-
102
- // GOOD — controller delegates everything
103
- app.post('/orders', async (req, res) => {
104
- const dto = parseCreateOrderDto(req.body);
105
- const result = await createOrderUseCase.execute(dto);
106
- res.status(201).json(formatOrderResponse(result));
107
- });
108
- ```
109
-
110
- ### Rule 5: No God Services
111
- A service that touches more than 2 domain aggregates is doing too much. Split it.
112
-
113
- ### Rule 6: Module Boundaries Are Enforced by Imports
114
- If module A imports from module B's internal files (`b/internal/...`), that is a boundary violation. Public APIs of modules are their index exports only.
115
-
116
- ---
117
-
118
- ## Directory Structure Pattern
119
-
120
- ```
121
- src/
122
- ├── domain/
123
- │ ├── order/
124
- │ │ ├── Order.ts # entity
125
- │ │ ├── OrderRepository.ts # interface
126
- │ │ └── OrderService.ts # domain service
127
- ├── application/
128
- │ ├── order/
129
- │ │ ├── CreateOrderUseCase.ts
130
- │ │ └── dto/
131
- │ │ ├── CreateOrderDto.ts
132
- │ │ └── OrderResponseDto.ts
133
- ├── infrastructure/
134
- │ ├── persistence/
135
- │ │ └── PrismaOrderRepository.ts
136
- │ └── http/
137
- │ └── StripePaymentGateway.ts
138
- └── presentation/
139
- └── http/
140
- └── OrderController.ts
141
- ```
142
-
143
- ---
144
-
145
- ## Iron Laws
146
-
147
- **IRON LAW 1: The domain layer has zero framework imports. If it imports Prisma, Express, or any SDK — fix it.**
148
- **IRON LAW 2: Business rules live in the domain layer, not in controllers or use cases.**
149
- **IRON LAW 3: A controller that queries the database directly violates the architecture unconditionally.**
150
-
151
- ---
152
-
153
- ## Red Flags — Stop and re-read this rule if you are thinking:
154
-
155
- | Rationalization | Why it's wrong |
156
- |---|---|
157
- | "It's a small project, layers are overkill" | Layerless code becomes unmaintainable the moment it needs testing or a second database |
158
- | "I'll just pass the Prisma object through, it's easier" | The domain now depends on Prisma — every Prisma version upgrade potentially breaks business logic |
159
- | "The use case is thin, I'll put the logic in the controller" | Controllers are discarded when the transport changes (HTTP → gRPC, REST → GraphQL) |
160
- | "I'll clean up the layers after the feature ships" | Features shipped with wrong architecture become the foundation for future features |
161
- | "The repository interface is just ceremony" | The interface enables testing without a database — eliminating it eliminates testability |
162
-
163
- **IRON LAW: IF CHANGING THE DATABASE REQUIRES CHANGING BUSINESS LOGIC, THE ARCHITECTURE IS WRONG.**
39
+ ## Review severities (shared with reviewers)
40
+
41
+ `review-architecture` rates layer and dependency-direction findings by this table; `review-backend` uses the same rating for the same condition. Change a row here, never in a reviewer. A layer violation is a maintenance cost, so it is `minor`; `major` needs a named defect (a trigger and a wrong outcome), never size or a project preference.
42
+
43
+ | Signal | A finding when | Default | Not a finding |
44
+ |---|---|---|---|
45
+ | Controller queries the database or holds business rules | always | `minor`; `major` only with a named defect | parsing input, calling one use case, formatting output |
46
+ | Business rule added to a use case instead of the domain | the change adds the rule to a use case | `minor` | coordination and transaction ownership |
47
+ | Domain imports infrastructure, framework, ORM or SDK | always | `minor`; `major` only with a named defect | — |
48
+ | Persistence row reaches a controller, or a request DTO enters a domain entity | always | `minor`; `major` only with a named defect | — |
49
+ | Repository without a domain interface, or an interface with no I/O or substitution boundary | the repository is an I/O boundary with no interface, or the interface has one internal implementation | `minor` | a plain helper or value object |
50
+ | Use case or transaction changes more than 2 domain aggregates | always | `minor`; `major` only with a named defect (for example lost consistency) | — |
51
+ | Another module's internal files imported instead of its index exports | the path bypasses the index | `minor`; `major` only with a named defect | — |
52
+ | Core or shared module imports feature code | always | `minor`; `major` only with a named defect | — |
53
+ | Circular import between modules | always | `minor`; `blocker` when an import resolves to `undefined` on a path the change reaches | — |