@joktec/skills 0.1.3 → 0.1.7

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 (101) hide show
  1. package/README.md +4 -2
  2. package/dist/claude/skills/advanced-typescript-design/SKILL.md +60 -0
  3. package/dist/claude/skills/advanced-typescript-design/agents/openai.yaml +4 -0
  4. package/dist/claude/skills/advanced-typescript-design/references/advanced.md +219 -0
  5. package/dist/claude/skills/advanced-typescript-design/references/simple.md +149 -0
  6. package/dist/claude/skills/joktec-adapter-skill/SKILL.md +1 -0
  7. package/dist/claude/skills/joktec-adapter-skill/references/adapters.md +28 -0
  8. package/dist/claude/skills/joktec-broker-skill/SKILL.md +1 -0
  9. package/dist/claude/skills/joktec-broker-skill/references/brokers.md +29 -0
  10. package/dist/claude/skills/joktec-common-skill/SKILL.md +1 -0
  11. package/dist/claude/skills/joktec-common-skill/references/core.md +56 -0
  12. package/dist/claude/skills/joktec-common-skill/references/utils-cron.md +28 -0
  13. package/dist/claude/skills/joktec-database-extended-skill/SKILL.md +1 -0
  14. package/dist/claude/skills/joktec-database-extended-skill/references/extended-databases.md +24 -0
  15. package/dist/claude/skills/joktec-framework-skill/SKILL.md +1 -0
  16. package/dist/claude/skills/joktec-framework-skill/references/framework-map.md +34 -0
  17. package/dist/claude/skills/joktec-integration-skill/SKILL.md +1 -0
  18. package/dist/claude/skills/joktec-integration-skill/references/integrations.md +29 -0
  19. package/dist/claude/skills/joktec-mongo-skill/SKILL.md +9 -1
  20. package/dist/claude/skills/joktec-mongo-skill/references/repository.md +46 -0
  21. package/dist/claude/skills/joktec-mongo-skill/references/schema-and-plugins.md +65 -0
  22. package/dist/claude/skills/joktec-mysql-skill/SKILL.md +6 -1
  23. package/dist/claude/skills/joktec-mysql-skill/references/entities.md +109 -1
  24. package/dist/claude/skills/joktec-mysql-skill/references/repository.md +63 -0
  25. package/dist/claude/skills/joktec-tool-skill/SKILL.md +1 -0
  26. package/dist/claude/skills/joktec-tool-skill/references/tools.md +36 -0
  27. package/dist/codex/skills/advanced-typescript-design/SKILL.md +60 -0
  28. package/dist/codex/skills/advanced-typescript-design/agents/openai.yaml +4 -0
  29. package/dist/codex/skills/advanced-typescript-design/references/advanced.md +219 -0
  30. package/dist/codex/skills/advanced-typescript-design/references/simple.md +149 -0
  31. package/dist/codex/skills/joktec-adapter-skill/SKILL.md +1 -0
  32. package/dist/codex/skills/joktec-adapter-skill/references/adapters.md +28 -0
  33. package/dist/codex/skills/joktec-broker-skill/SKILL.md +1 -0
  34. package/dist/codex/skills/joktec-broker-skill/references/brokers.md +29 -0
  35. package/dist/codex/skills/joktec-common-skill/SKILL.md +1 -0
  36. package/dist/codex/skills/joktec-common-skill/references/core.md +56 -0
  37. package/dist/codex/skills/joktec-common-skill/references/utils-cron.md +28 -0
  38. package/dist/codex/skills/joktec-database-extended-skill/SKILL.md +1 -0
  39. package/dist/codex/skills/joktec-database-extended-skill/references/extended-databases.md +24 -0
  40. package/dist/codex/skills/joktec-framework-skill/SKILL.md +1 -0
  41. package/dist/codex/skills/joktec-framework-skill/references/framework-map.md +34 -0
  42. package/dist/codex/skills/joktec-integration-skill/SKILL.md +1 -0
  43. package/dist/codex/skills/joktec-integration-skill/references/integrations.md +29 -0
  44. package/dist/codex/skills/joktec-mongo-skill/SKILL.md +9 -1
  45. package/dist/codex/skills/joktec-mongo-skill/references/repository.md +46 -0
  46. package/dist/codex/skills/joktec-mongo-skill/references/schema-and-plugins.md +65 -0
  47. package/dist/codex/skills/joktec-mysql-skill/SKILL.md +6 -1
  48. package/dist/codex/skills/joktec-mysql-skill/references/entities.md +109 -1
  49. package/dist/codex/skills/joktec-mysql-skill/references/repository.md +63 -0
  50. package/dist/codex/skills/joktec-tool-skill/SKILL.md +1 -0
  51. package/dist/codex/skills/joktec-tool-skill/references/tools.md +36 -0
  52. package/dist/copilot/.github/copilot-instructions.md +1003 -3
  53. package/dist/cursor/.cursor/rules/advanced-typescript-design.mdc +437 -0
  54. package/dist/cursor/.cursor/rules/joktec-adapter-skill.mdc +29 -0
  55. package/dist/cursor/.cursor/rules/joktec-broker-skill.mdc +30 -0
  56. package/dist/cursor/.cursor/rules/joktec-common-skill.mdc +85 -0
  57. package/dist/cursor/.cursor/rules/joktec-database-extended-skill.mdc +25 -0
  58. package/dist/cursor/.cursor/rules/joktec-framework-skill.mdc +35 -0
  59. package/dist/cursor/.cursor/rules/joktec-integration-skill.mdc +30 -0
  60. package/dist/cursor/.cursor/rules/joktec-mongo-skill.mdc +120 -1
  61. package/dist/cursor/.cursor/rules/joktec-mysql-skill.mdc +178 -2
  62. package/dist/cursor/.cursor/rules/joktec-tool-skill.mdc +37 -0
  63. package/dist/gemini/GEMINI.md +1005 -3
  64. package/dist/windsurf/.windsurf/rules/advanced-typescript-design.md +433 -0
  65. package/dist/windsurf/.windsurf/rules/joktec-adapter-skill.md +29 -0
  66. package/dist/windsurf/.windsurf/rules/joktec-broker-skill.md +30 -0
  67. package/dist/windsurf/.windsurf/rules/joktec-common-skill.md +85 -0
  68. package/dist/windsurf/.windsurf/rules/joktec-database-extended-skill.md +25 -0
  69. package/dist/windsurf/.windsurf/rules/joktec-framework-skill.md +35 -0
  70. package/dist/windsurf/.windsurf/rules/joktec-integration-skill.md +30 -0
  71. package/dist/windsurf/.windsurf/rules/joktec-mongo-skill.md +120 -1
  72. package/dist/windsurf/.windsurf/rules/joktec-mysql-skill.md +178 -2
  73. package/dist/windsurf/.windsurf/rules/joktec-tool-skill.md +37 -0
  74. package/package.json +6 -3
  75. package/scripts/sync-pack-version.mjs +38 -0
  76. package/skill-pack.json +35 -1
  77. package/skills/advanced-typescript-design/SKILL.md +60 -0
  78. package/skills/advanced-typescript-design/agents/openai.yaml +4 -0
  79. package/skills/advanced-typescript-design/references/advanced.md +219 -0
  80. package/skills/advanced-typescript-design/references/simple.md +149 -0
  81. package/skills/joktec-adapter-skill/SKILL.md +1 -0
  82. package/skills/joktec-adapter-skill/references/adapters.md +28 -0
  83. package/skills/joktec-broker-skill/SKILL.md +1 -0
  84. package/skills/joktec-broker-skill/references/brokers.md +29 -0
  85. package/skills/joktec-common-skill/SKILL.md +1 -0
  86. package/skills/joktec-common-skill/references/core.md +56 -0
  87. package/skills/joktec-common-skill/references/utils-cron.md +28 -0
  88. package/skills/joktec-database-extended-skill/SKILL.md +1 -0
  89. package/skills/joktec-database-extended-skill/references/extended-databases.md +24 -0
  90. package/skills/joktec-framework-skill/SKILL.md +1 -0
  91. package/skills/joktec-framework-skill/references/framework-map.md +34 -0
  92. package/skills/joktec-integration-skill/SKILL.md +1 -0
  93. package/skills/joktec-integration-skill/references/integrations.md +29 -0
  94. package/skills/joktec-mongo-skill/SKILL.md +9 -1
  95. package/skills/joktec-mongo-skill/references/repository.md +46 -0
  96. package/skills/joktec-mongo-skill/references/schema-and-plugins.md +65 -0
  97. package/skills/joktec-mysql-skill/SKILL.md +6 -1
  98. package/skills/joktec-mysql-skill/references/entities.md +109 -1
  99. package/skills/joktec-mysql-skill/references/repository.md +63 -0
  100. package/skills/joktec-tool-skill/SKILL.md +1 -0
  101. package/skills/joktec-tool-skill/references/tools.md +36 -0
@@ -24,6 +24,7 @@ Start here when a task mentions JokTec generally, multiple `@joktec/*` packages,
24
24
  - Prefer config-driven module setup and `conId` when a package supports multiple clients.
25
25
  - Preserve NestJS module boundaries, dependency injection, lifecycle hooks, and exported package APIs.
26
26
  - Do not invent behavior for unfinished or missing packages.
27
+ - If a focused skill is loaded without this entrypoint, still apply source-first lookup before assuming APIs.
27
28
 
28
29
  ## Reference
29
30
 
@@ -35,6 +36,25 @@ Read `references/framework-map.md` when the task needs package selection, depend
35
36
 
36
37
  # JokTec Framework Map
37
38
 
39
+ ## Source-First Operating Protocol
40
+
41
+ Treat this skill pack as curated guidance, not the final implementation truth. When a task is unclear, or when a package API seems different from the skill text:
42
+
43
+ 1. Inspect the consumer project first to understand the package versions and local usage pattern.
44
+ 2. Prefer local framework source at `../joktec-framework` when available.
45
+ 3. Read package `README.md`, nearest `AGENTS.md`, and `src/index.ts` before changing code.
46
+ 4. If local source is unavailable, use `https://github.com/joktec/joktec-framework` as fallback.
47
+ 5. Do not invent behavior that is not visible in framework source or package docs.
48
+ 6. If package docs and source conflict, source code wins and the mismatch should be treated as documentation drift.
49
+
50
+ High-value source files:
51
+
52
+ - `AGENTS.md` and `docs/agents/*` for framework-level architecture and runtime policy.
53
+ - `packages/<family>/AGENTS.md` for family boundaries.
54
+ - `packages/<family>/<package>/README.md` for developer-facing usage.
55
+ - `packages/<family>/<package>/src/index.ts` for public API.
56
+ - Package config/module/service/repository files for real runtime behavior.
57
+
38
58
  ## Package Families
39
59
 
40
60
  - `@joktec/core`: bootstrap, config, logger, metrics, guards, base abstractions, transports, pagination, Bull.
@@ -52,6 +72,12 @@ Read `references/framework-map.md` when the task needs package selection, depend
52
72
 
53
73
  Consumer apps depend on concrete `@joktec/*` packages. Concrete packages usually depend on `@joktec/core` and `@joktec/utils`. Keep app-specific schemas, handlers, and business semantics outside reusable packages.
54
74
 
75
+ Do not reverse the dependency direction:
76
+
77
+ - reusable packages must not import from `apps/`
78
+ - `common` packages must not depend on concrete adapters/brokers/databases
79
+ - consumer apps own business workflows, DTO composition, schemas/entities, queue names, topics, and provider credentials
80
+
55
81
  ## Common Consumer App Pattern
56
82
 
57
83
  1. Register package modules in the app module or repository module.
@@ -59,6 +85,15 @@ Consumer apps depend on concrete `@joktec/*` packages. Concrete packages usually
59
85
  3. Extend the package repository base class when the package provides one.
60
86
  4. Use `BaseService`, `BaseController`, or transport helpers from `@joktec/core` when the app follows standard CRUD or message patterns.
61
87
 
88
+ ## Skill Selection
89
+
90
+ - Use `joktec-common-skill` for BaseController/BaseService/config/pagination/client lifecycle/utils/cron.
91
+ - Use `joktec-mongo-skill` when the resource uses Mongo schemas, MongoRepo, Typegoose decorators, plugins, or ObjectId-safe queries.
92
+ - Use `joktec-mysql-skill` when the resource uses TypeORM entities, MysqlRepo, SQL dialect behavior, transactions, or schema-first column decorators.
93
+ - Use broker/adapter/integration/tool skills for provider wiring; keep business semantics in the consumer app.
94
+
95
+ When using the ecosystem `npx skills` installer, install `joktec-framework-skill` and `joktec-common-skill` together with any focused package skill. The current ecosystem installer does not auto-resolve dependencies from frontmatter.
96
+
62
97
  ---
63
98
 
64
99
  ## JokTec Common Skill
@@ -79,6 +114,7 @@ Use this skill for shared framework primitives, low-level helpers, cron utilitie
79
114
  - Use page, offset, or cursor pagination contracts from core; let database packages execute storage-specific pagination.
80
115
  - Use `AbstractClientService` patterns for client packages that need config, lifecycle, retry, and `conId`.
81
116
  - Use `@joktec/utils` for shared helpers instead of duplicating conversion, validation, hashing, or UUID logic.
117
+ - If guidance is insufficient, read this skill's references and inspect `../joktec-framework` package source or GitHub fallback before assuming APIs.
82
118
 
83
119
  ## References
84
120
 
@@ -91,24 +127,80 @@ Use this skill for shared framework primitives, low-level helpers, cron utilitie
91
127
 
92
128
  # Common Core Usage
93
129
 
130
+ ## Source Lookup
131
+
132
+ When blocked, inspect these framework files before guessing:
133
+
134
+ - `packages/common/core/README.md`
135
+ - `packages/common/core/AGENTS.md`
136
+ - `packages/common/core/src/index.ts`
137
+ - `packages/common/core/src/abstractions/*`
138
+ - `packages/common/core/src/models/base.request.ts`
139
+ - `packages/common/core/src/models/base.response.ts`
140
+ - `packages/common/core/src/models/paginations/*`
141
+ - `packages/common/core/src/client/abstract-client.service.ts`
142
+ - `packages/common/core/src/infras/application.ts`
143
+ - `packages/common/core/src/modules/*`
144
+
94
145
  ## Runtime Bootstrap
95
146
 
96
147
  Use the application bootstrap helpers from `@joktec/core` for gateway and microservice runtimes. Keep runtime behavior config-driven.
97
148
 
149
+ Best practice:
150
+
151
+ - Use `Application.bootstrap(AppModule)` instead of hand-rolling Nest bootstrap unless the consumer app has a specific runtime reason.
152
+ - Keep gateway-only behavior in gateway runtime modules and microservice-only behavior in micro runtime modules.
153
+ - Register framework modules through their dynamic module APIs when provided.
154
+ - Do not duplicate config parsing, logger setup, metrics setup, or process lifecycle hooks in consumer apps.
155
+
98
156
  ## CRUD Abstractions
99
157
 
100
158
  - `BaseController` creates standard REST CRUD endpoints for DTO-backed resources.
101
159
  - `BaseService` delegates repository operations through the shared repository contract.
102
160
  - `ClientController` and `ClientService` provide generated microservice CRUD patterns.
103
161
 
162
+ Use BaseController/BaseService when the resource follows standard CRUD. Avoid them when the endpoint has domain-specific command semantics, multi-step transactions, or non-standard authorization that would make the generic abstraction obscure behavior.
163
+
164
+ Controller checklist:
165
+
166
+ - choose the DTO/entity class intentionally
167
+ - set `paginationMode` for the representative Swagger response shape
168
+ - use `customDto.paginationDto` only when the built-in page/offset/cursor response does not represent the API
169
+ - keep auth/guards/interceptors consistent with app conventions
170
+ - avoid putting business branching in controller methods when it belongs in the service
171
+
104
172
  ## Pagination
105
173
 
106
174
  Request priority is cursor, then offset, then page. `BaseController.paginationMode` affects Swagger response shape; runtime selection remains request-driven unless the app service narrows it.
107
175
 
176
+ Best practice:
177
+
178
+ - Use page pagination for admin tables and simple back-office views.
179
+ - Use offset pagination for mobile-style load-more when the data set is moderate and stable enough.
180
+ - Use cursor pagination for feeds, timelines, frequently inserted lists, or large tables.
181
+ - Do not document cursor support for a resource unless the underlying repository package actually supports it.
182
+ - When using cursor mode, ensure the database layer has stable sort keys and tie-breakers.
183
+
108
184
  ## Client Lifecycle
109
185
 
110
186
  Use `ClientConfig`, `AbstractClientService`, and `conId` when building or consuming packages that support multiple client connections.
111
187
 
188
+ Client package checklist:
189
+
190
+ - config class validates all required runtime options
191
+ - service startup fails clearly when the native client cannot initialize
192
+ - shutdown closes native connections only when initialized
193
+ - `conId` is preserved through service/repository calls
194
+ - logs do not leak credentials or full connection strings
195
+ - retries and debug behavior are config-driven
196
+
197
+ ## Do Not
198
+
199
+ - Do not import concrete package or app code into `@joktec/core`.
200
+ - Do not bypass shared pagination contracts with ad-hoc response shapes for standard CRUD.
201
+ - Do not add new public symbols without exporting them through `src/index.ts`.
202
+ - Do not silently swallow bootstrap/client initialization failures.
203
+
112
204
  ### references/utils-cron.md
113
205
 
114
206
  # Utils And Cron Usage
@@ -119,12 +211,40 @@ Use `@joktec/utils` for common generators, validators, converters, hashing helpe
119
211
 
120
212
  Prefer package helpers over app-local reimplementation when behavior should stay consistent across services.
121
213
 
214
+ Source lookup:
215
+
216
+ - `packages/common/utils/README.md`
217
+ - `packages/common/utils/src/index.ts`
218
+ - `packages/common/utils/src/helpers/*`
219
+ - `packages/common/utils/src/validators/*`
220
+ - `packages/common/utils/src/constants/*`
221
+
222
+ Best practice:
223
+
224
+ - Use shared validators from `@joktec/utils` when building schema-first entity/schema decorators.
225
+ - Use shared generators for IDs, tokens, random values, and hashes when consistency matters.
226
+ - Keep utility usage deterministic in tests; mock time/randomness where needed.
227
+ - Do not add framework-level dependencies to `utils`.
228
+
122
229
  ## Cron
123
230
 
124
231
  Use `@joktec/cron` when a consumer app needs scheduled jobs, job worker contracts, or decorator-driven cron registration.
125
232
 
126
233
  Keep job business logic in the consumer app. The package provides scheduling abstractions, not domain behavior.
127
234
 
235
+ Source lookup:
236
+
237
+ - `packages/common/cron/README.md`
238
+ - `packages/common/cron/src/index.ts`
239
+ - cron decorators, models, scheduler services, and worker contracts under `src/`
240
+
241
+ Best practice:
242
+
243
+ - Keep job names, schedules, concurrency, and retry behavior visible in the consumer app.
244
+ - Make cron handlers idempotent.
245
+ - Avoid enabling the same cron owner in multiple processes unless the package/app has explicit locking semantics.
246
+ - Treat cron runtime as infrastructure orchestration; domain writes still belong in app services/repositories.
247
+
128
248
  ## Types
129
249
 
130
250
  Use `@joktec/types` when a consumer workflow needs generated JokTec package config schema/type artifacts. Treat the framework repository as source-of-truth for the generated schema shape.
@@ -141,8 +261,16 @@ Use this skill for MongoDB-backed resources that rely on JokTec's Mongoose/Typeg
141
261
  - Keep schema classes, app repositories, and app-specific queries in the consumer app.
142
262
  - Extend `MongoRepo<T, ID>` for app repositories.
143
263
  - Preserve `conId` when the app has multiple Mongo connections.
144
- - Use schema-first decorators when a schema class should be reused as a DTO source.
264
+ - Use schema-first decorators when a schema class should be reused as a DTO source; wrappers should reduce repeated Typegoose, validator, transformer, and Swagger stacks.
265
+ - Use `RefId<T>` for stored reference id fields and `PopulatedRef<T>` for populated virtual fields.
266
+ - Use `@Schema({ kind: 'embedded' })` for value objects without `_id` or timestamps.
267
+ - Use `@Schema({ kind: 'subdocument' })` for embedded documents that need their own `_id` and timestamps.
268
+ - Use `@Prop({ kind: 'virtual', mode: 'getter' })` for computed getters that need expose/Swagger metadata without persistence.
269
+ - Use `@Prop({ ref: () => Target, foreignField, localField })` for populate-one virtuals when inferred defaults are enough.
270
+ - Use `@Prop({ type: () => [Target], ref: () => Target, foreignField, localField })` for populate-array virtuals.
271
+ - Use `@Prop({ kind: 'map', type: Object })` for map/snapshot payloads that must keep their raw shape.
145
272
  - Treat ObjectId casting and regex behavior as safety-sensitive.
273
+ - For real migrations, inspect `node_modules/@joktec/mongo` first, then installed README or GitHub package docs, then GitHub source before assuming APIs.
146
274
 
147
275
  ## References
148
276
 
@@ -155,14 +283,46 @@ Use this skill for MongoDB-backed resources that rely on JokTec's Mongoose/Typeg
155
283
 
156
284
  # Mongo Repository Usage
157
285
 
286
+ ## Source Lookup
287
+
288
+ When blocked, inspect:
289
+
290
+ - Consumer project first: `node_modules/@joktec/mongo`.
291
+ - Installed docs next: `node_modules/@joktec/mongo/README.md`.
292
+ - GitHub docs next: `https://github.com/joktec/joktec-framework/tree/main/packages/databases/mongo`.
293
+ - GitHub source fallback:
294
+ - `packages/databases/mongo/src/index.ts`
295
+ - `packages/databases/mongo/src/mongo.module.ts`
296
+ - `packages/databases/mongo/src/mongo.service.ts`
297
+ - `packages/databases/mongo/src/mongo.repo.ts`
298
+ - `packages/databases/mongo/src/helpers/mongo.helper.ts`
299
+ - `packages/databases/mongo/src/helpers/mongo.pipeline.ts`
300
+ - `packages/databases/mongo/src/helpers/mongo.utils.ts`
301
+ - `packages/databases/mongo/src/models/*`
302
+
158
303
  ## Module Setup
159
304
 
160
305
  Register schemas with `MongoModule.forRoot({ conId, models: [...] })`. Use the same `conId` in app repositories when using non-default connections.
161
306
 
307
+ Best practice:
308
+
309
+ - Register app schema classes in the consumer app repository module.
310
+ - Use one owner process for index creation in multi-process deployments.
311
+ - Preserve `conId` through service/repo constructors for multi-connection apps.
312
+ - Do not rely on the global mongoose model registry when `MongoService` provides connection-aware resolution.
313
+
162
314
  ## Repository Pattern
163
315
 
164
316
  Extend `MongoRepo` and pass the schema class to the base constructor. Services can then use `BaseService` from `@joktec/core`.
165
317
 
318
+ Repository checklist:
319
+
320
+ - Keep schema-specific query helpers in the app repository, not in controllers.
321
+ - Use repository methods for standard reads so query parsing, soft delete, populate, and pagination stay consistent.
322
+ - Pass transaction/session options through read-modify-write flows when the app uses transactions.
323
+ - Repository read paths should return schema class instances with normalized ObjectId/string values, including populated and deep-populated values.
324
+ - Code that needs raw Mongoose documents should use `MongoService.getModel(...)` or Typegoose/Mongoose APIs directly.
325
+
166
326
  ## Query Safety
167
327
 
168
328
  - Root `id` can act as an API alias for `_id` in query conditions.
@@ -170,30 +330,109 @@ Extend `MongoRepo` and pass the schema class to the base constructor. Services c
170
330
  - `$like`, `$begin`, and `$end` escape regex input by default.
171
331
  - Do not rely on broad conversion when storing raw snapshots, maps, or nested subdocuments.
172
332
 
333
+ Anti-patterns:
334
+
335
+ - Do not convert every nested `id` key into `_id`; only API-facing query aliases should be converted.
336
+ - Do not cast every 24-character hex string into ObjectId; fields like `externalId`, `code`, and `slug` may be strings.
337
+ - Do not inject soft-delete conditions into unknown nested aggregate branches unless the target collection is known.
338
+
173
339
  ## Pagination
174
340
 
175
341
  `MongoRepo.paginate` supports page, offset, and cursor responses. Cursor mode defaults to `_id`; custom `cursorKey` appends `_id` as a tie-breaker.
176
342
 
343
+ Cursor checklist:
344
+
345
+ - Use `_id` for default Mongo cursor ordering.
346
+ - Use `createdAt` or another indexed stable key when the product requires chronological cursor behavior.
347
+ - Append `_id` as a tie-breaker for non-unique cursor keys.
348
+ - Fetch `limit + 1` records and generate `nextCursor` only when another page exists.
349
+ - Treat cursor tokens as opaque; clients should not parse them.
350
+
177
351
  ### references/schema-and-plugins.md
178
352
 
179
353
  # Mongo Schema And Plugins
180
354
 
355
+ ## Source Lookup
356
+
357
+ When blocked, inspect:
358
+
359
+ - Consumer project first: `node_modules/@joktec/mongo`.
360
+ - Package docs next: `node_modules/@joktec/mongo/README.md`.
361
+ - GitHub docs next: `https://github.com/joktec/joktec-framework/tree/main/packages/databases/mongo`.
362
+ - GitHub source fallback:
363
+ - `packages/databases/mongo/src/decorators/schema.decorator.ts`
364
+ - `packages/databases/mongo/src/decorators/schema.options.ts`
365
+ - `packages/databases/mongo/src/decorators/prop.decorator.ts`
366
+ - `packages/databases/mongo/src/decorators/props/*`
367
+ - `packages/databases/mongo/src/models/mongo.ref.ts`
368
+ - `packages/databases/mongo/src/models/object-id.ts`
369
+ - `packages/databases/mongo/src/models/mongo.schema.ts`
370
+ - `packages/databases/mongo/src/plugins/paranoid.plugin.ts`
371
+ - `packages/databases/mongo/src/plugins/strict-reference.plugin.ts`
372
+ - `packages/databases/mongo/src/plugins/transform.plugin.ts`
373
+
181
374
  ## Schema Decorators
182
375
 
183
376
  Use `@Schema` and `@Prop` wrappers from `@joktec/mongo` for Typegoose schema metadata plus validation, transform, and Swagger metadata.
184
377
 
185
378
  Avoid mutating shared option objects across multiple properties.
186
379
 
380
+ Best practice:
381
+
382
+ - Use schema-first decorators when the schema should be reused by DTO mapped types.
383
+ - Keep raw `@prop` or raw Mongoose decorators only when the wrapper cannot express the behavior.
384
+ - Pass custom validators/transforms explicitly rather than adding hidden global behavior.
385
+ - Keep maps, snapshots, and dynamic objects explicit so helper conversion does not alter their shape.
386
+ - Keep app-level reference semantics visible; strict reference plugin checks existence, but the app still owns domain rules.
387
+ - Use `RefId<T>` for persisted id fields and `PopulatedRef<T>` for populated virtual instance fields.
388
+ - Use lazy `type` resolvers such as `type: () => User` or `type: () => [User]` when the wrapper cannot infer the runtime class.
389
+ - Use `@Schema({ kind: 'embedded' })` for value objects without `_id` or timestamps.
390
+ - Use `@Schema({ kind: 'subdocument' })` for embedded documents that need `_id` and timestamps but should not create a collection.
391
+ - Use `@Prop({ kind: 'virtual', mode: 'getter', comment, optional, hidden, expose, swagger })` for computed getters that only need class-transformer and Swagger metadata.
392
+ - Use `@Prop({ ref: () => User, foreignField, localField })` for populate-one virtuals when inferred defaults are enough.
393
+ - Use `@Prop({ type: () => [User], ref: () => User, foreignField, localField })` for populate-array virtuals.
394
+ - Use `@Prop({ kind: 'map', type: Object })` for raw maps/snapshots instead of passing `PropType.MAP` at the call site.
395
+
396
+ Common mappings:
397
+
398
+ | Use case | Preferred shape |
399
+ | --- | --- |
400
+ | Stored single reference id | `fieldId?: RefId<User>` with `@Prop({ type: ObjectId, ref: () => User })` |
401
+ | Stored reference id array | `fieldIds?: RefId<User>[]` with `@Prop({ type: [ObjectId], ref: () => User })` |
402
+ | Embedded value object | `@Schema({ kind: 'embedded' })` on the nested class |
403
+ | Embedded document | `@Schema({ kind: 'subdocument' })` on the nested class |
404
+ | Raw map/snapshot | `@Prop({ kind: 'map', type: Object })` |
405
+ | Populated single virtual | `field?: PopulatedRef<User>` with `@Prop({ ref: () => User, foreignField: '_id', localField: 'fieldId' })` |
406
+ | Populated virtual array | `fields?: PopulatedRef<User>[]` with `@Prop({ type: () => [User], ref: () => User, foreignField: '_id', localField: 'fieldIds' })` |
407
+ | Computed getter | `@Prop({ kind: 'virtual', mode: 'getter', comment: '...' }) get value() { ... }` |
408
+
409
+ Populate inference:
410
+
411
+ - `ref` + `localField` + `foreignField` marks the field as virtual populate.
412
+ - Populate-one can fallback to the same class from `ref`.
413
+ - Populate arrays still need `type: () => [Target]` because runtime reflection only sees `Array`.
414
+ - `justOne` defaults to `true` for non-array populate fields.
415
+ - Swagger examples default to `{}` or `[]` for populated fields unless explicitly overridden.
416
+
187
417
  ## Plugins
188
418
 
189
419
  - Paranoid plugin handles soft delete filtering and must respect aggregate first-stage constraints such as `$geoNear`.
190
420
  - Strict reference plugin validates referenced documents and must resolve models through the active connection.
191
421
  - Transform plugin centralizes common document transformation and should not break Mongo update operators.
192
422
 
423
+ Plugin checklist:
424
+
425
+ - Paranoid aggregate injection must not come before `$geoNear`.
426
+ - Strict reference checks must be connection-aware in multi-connection apps.
427
+ - Transform behavior must preserve update operators such as `$set`, `$inc`, `$push`, and `$addToSet`.
428
+ - Do not treat plugins as a replacement for app authorization or domain validation.
429
+
193
430
  ## Debug Output
194
431
 
195
432
  Use `mongoDebug(collection, method, ...args)` when a Mongoose debug callback should be rendered as a Mongo shell-friendly command.
196
433
 
434
+ Debug output is for developer diagnostics. Do not log credentials or sensitive document payloads in production logs.
435
+
197
436
  ---
198
437
 
199
438
  ## JokTec MySQL Skill
@@ -208,11 +447,16 @@ Use this skill for relational resources backed by JokTec's TypeORM wrapper.
208
447
  - Treat `mysql`, `mariadb`, and `postgres` as the first-class dialects.
209
448
  - Keep `sync` explicit and normally enabled only by an owner process or development bootstrap.
210
449
  - Do not add new behavior to deprecated `MysqlFinder`; use `MysqlRepo.qb()` and `MysqlHelper` paths.
450
+ - Use schema-first `@Column`, `@PrimaryColumn`, and `@TimestampColumn` wrappers when an entity also acts as DTO metadata.
451
+ - Use `@Column({ kind: 'virtual' })` for computed getters that need expose/Swagger metadata without persistence.
452
+ - Use `immutable` for API read-only metadata; TypeORM `update: false` remains storage write behavior and is also inferred as Swagger read-only when `immutable` is not set.
453
+ - Do not use `@joktec/mysql` for Mongo/ObjectId columns, even though TypeORM has Mongo-related APIs.
454
+ - For real migrations, inspect the installed `@joktec/mysql` source in the consumer project's `node_modules` first. If that is insufficient, read GitHub package docs, then GitHub source. Use the local `../joktec-framework` checkout only when you are working inside the JokTec development workspace.
211
455
 
212
456
  ## References
213
457
 
214
458
  - Read `references/repository.md` for connection lifecycle, repository usage, query safety, transaction, and cursor behavior.
215
- - Read `references/entities.md` for `@Tables`, `@Column`, `@PrimaryColumn`, uuidv7, and dialect guidance.
459
+ - Read `references/entities.md` for `@Tables`, `@Column`, `@PrimaryColumn`, uuidv7, dialect guidance, and legacy decorator migration rules.
216
460
 
217
461
  ## Bundled References
218
462
 
@@ -220,15 +464,123 @@ Use this skill for relational resources backed by JokTec's TypeORM wrapper.
220
464
 
221
465
  # MySQL Entity Decorators
222
466
 
467
+ ## Source Lookup
468
+
469
+ When blocked in a consumer project, inspect the installed package first:
470
+
471
+ - `node_modules/@joktec/mysql/README.md`
472
+ - `node_modules/@joktec/mysql/AGENTS.md` when published with the package
473
+ - `node_modules/@joktec/mysql/dist/index.d.ts`
474
+ - `node_modules/@joktec/mysql/dist/decorators/column.decorator.d.ts`
475
+ - `node_modules/@joktec/mysql/dist/decorators/columns/column.type.d.ts`
476
+ - `node_modules/@joktec/mysql/dist/decorators/timestamp.decorator.d.ts`
477
+
478
+ If the installed package is missing enough detail, use the GitHub package docs next:
479
+
480
+ - `https://github.com/joktec/joktec-framework/tree/main/packages/databases/mysql`
481
+
482
+ Use GitHub source only after package docs and installed types are not enough:
483
+
484
+ - `packages/databases/mysql/src/decorators/table.decorator.ts`
485
+ - `packages/databases/mysql/src/decorators/column.decorator.ts`
486
+ - `packages/databases/mysql/src/decorators/columns/column.type.ts`
487
+ - `packages/databases/mysql/src/decorators/columns/column.factory.ts`
488
+ - `packages/databases/mysql/src/decorators/columns/primary.column.ts`
489
+ - `packages/databases/mysql/src/decorators/columns/timestamp.column.ts`
490
+ - `packages/databases/mysql/src/decorators/columns/virtual.column.ts`
491
+ - `packages/databases/mysql/src/decorators/columns/object.column.ts`
492
+ - `packages/databases/mysql/src/decorators/columns/string.column.ts`
493
+ - `packages/databases/mysql/src/decorators/columns/number.column.ts`
494
+ - `packages/databases/mysql/src/decorators/columns/transform.column.ts`
495
+ - `packages/databases/mysql/src/decorators/columns/swagger.column.ts`
496
+
223
497
  ## Schema-First Entity Pattern
224
498
 
225
- Use `@Tables`, `@Column`, and `@PrimaryColumn` from `@joktec/mysql` when an entity should also act as the source class for mapped DTOs.
499
+ Use `@Tables`, `@Column`, `@PrimaryColumn`, and `@TimestampColumn` from `@joktec/mysql` when an entity should also act as the source class for mapped DTOs.
500
+
501
+ The new decorators are not thin TypeORM aliases. They are schema-first wrappers that compose:
502
+
503
+ - TypeORM column/primary column metadata.
504
+ - `class-validator` behavior through `@joktec/utils` validators.
505
+ - `class-transformer` expose/exclude behavior.
506
+ - Swagger property metadata.
507
+
508
+ The wrapper can also represent virtual computed getters and nested JSON/jsonb class payloads. Do not use this package for Mongo/ObjectId columns.
509
+
510
+ Wrapper philosophy:
511
+
512
+ - prefer one schema declaration that carries persistence, validation, transform, and Swagger metadata
513
+ - use wrapper options before duplicating `@ApiProperty`, `@Expose`, `@Type`, or common validators
514
+ - use raw TypeORM only for advanced cases that the wrapper does not model cleanly
515
+ - keep storage write behavior and API documentation behavior distinct when needed
516
+
517
+ ## Current Decorator Capabilities
518
+
519
+ Use the package README and actual installed source for full migration details. This skill only keeps the common mappings that help an agent recognize old patterns.
520
+
521
+ Common mappings:
522
+
523
+ | Legacy decorators | New decorator shape |
524
+ | --- | --- |
525
+ | `@PrimaryGeneratedColumn()` | `@PrimaryColumn('increment')` |
526
+ | `@PrimaryGeneratedColumn('uuid')` | `@PrimaryColumn('uuid')` |
527
+ | app-generated ordered UUID id | `@PrimaryColumn('uuidv7')` |
528
+ | `@CreateDateColumn(...)` | `@TimestampColumn('create', ...)` |
529
+ | `@UpdateDateColumn(...)` | `@TimestampColumn('update', ...)` |
530
+ | `@DeleteDateColumn(...)` | `@TimestampColumn('delete', ...)` |
531
+ | TypeORM `@VersionColumn(...)` | `@Column({ kind: 'version', ... })` |
532
+ | TypeORM `@VirtualColumn(...)` | `@Column({ kind: 'virtual', mode: 'sql', query, ... })` |
533
+ | TypeORM `@ViewColumn(...)` | `@Column({ kind: 'view', ... })` |
534
+ | `@Column(...)` | `@Column(...)` from `@joktec/mysql` |
535
+ | `@RelationId(...)` | `@Column({ kind: 'relation-id', relationId })` |
536
+ | `@IsNotEmpty()` | `@Column({ required: true })` |
537
+ | `@IsOptional()` | `@Column({ required: false })` or nullable TypeORM option when storage allows null |
538
+ | `@IsEmail()` | `@Column({ isEmail: true })` |
539
+ | `@IsMobilePhone()` | `@Column({ isPhone: true })` |
540
+ | `@IsInt()` | `@Column({ isInt: true })` or an integer column type |
541
+ | `@IsUUID()` | `@Column({ isUUID: true })` |
542
+ | `@IsObject()` | `@Column({ isObject: true })` or a JSON column |
543
+ | `@IsHexColor()` | `@Column({ isHexColor: true })` |
544
+ | `@IsUrl()` | `@Column({ isUrl: true })` |
545
+ | `@MinLength(n)` | `@Column({ minLength: n })` |
546
+ | `@MaxLength(n)` | `@Column({ maxLength: n })` |
547
+ | `@Min(n)` | `@Column({ min: n })` |
548
+ | `@Max(n)` | `@Column({ max: n })` |
549
+ | `@Expose()` | default behavior of `@Column(...)` |
550
+ | `@Expose({ groups })` | `@Column({ groups })` |
551
+ | `@Exclude({ toPlainOnly: true })` plus hidden Swagger | `@Column({ hidden: true })` |
552
+ | `@ApiProperty(...)` | `@Column({ swagger: ... })`, or native options such as `example`, `comment`, `deprecated`, `min`, `max`, `minLength`, `maxLength` |
553
+ | `@ValidateNested()` + `@Type(() => Preference)` | `@Column('jsonb', { nested: Preference })` |
554
+ | `@ValidateNested({ each: true })` + `@Type(() => Preference)` | `@Column('jsonb', { nested: Preference, each: true })` |
555
+ | `@Expose()` + `@ApiProperty(...)` on a getter | `@Column({ kind: 'virtual', ... })` |
556
+ | Swagger `readOnly: true` | `@Column({ immutable: true })` or TypeORM `update: false` when ORM updates must also be blocked |
557
+
558
+ ## Read-Only Metadata
559
+
560
+ `immutable` is the API read-only hint used by the JokTec MySQL wrapper. TypeORM `update: false` is the ORM write behavior. The wrapper maps both to Swagger `readOnly` when appropriate:
561
+
562
+ - `immutable` has priority over `update: false`
563
+ - `update: false` implies Swagger `readOnly` only when `immutable` is not set
564
+ - `swagger.readOnly` remains the final explicit override
565
+
566
+ Some field kinds default to API read-only because they are system-managed or computed:
567
+
568
+ - primary keys
569
+ - timestamp columns
570
+ - version columns
571
+ - view columns
572
+ - virtual getter and SQL virtual columns
573
+ - relation-id columns
574
+ - tree level columns
226
575
 
227
576
  ## Primary Keys
228
577
 
229
578
  - Prefer numeric auto-increment keys for write-heavy MySQL tables.
230
579
  - Use UUIDs when the app needs globally unique or public identifiers.
231
580
  - Prefer `uuidv7` over random UUIDs when the id participates in ordered indexes or cursor-like access.
581
+ - When switching from UUID v4 to uuidv7, verify downstream code does not assume random UUID ordering.
582
+
583
+ Do not blindly convert every primary key to uuidv7. Keep numeric increment keys when the table is internal, write-heavy, and does not need public/global identifiers.
232
584
 
233
585
  ## Dialects
234
586
 
@@ -238,28 +590,91 @@ The stable dialects are MySQL, MariaDB, and Postgres. Dialect capabilities own d
238
590
 
239
591
  # MySQL Repository Usage
240
592
 
593
+ ## Source Lookup
594
+
595
+ When blocked in a consumer project, inspect installed package docs and types first:
596
+
597
+ - `node_modules/@joktec/mysql/README.md`
598
+ - `node_modules/@joktec/mysql/AGENTS.md` when published with the package
599
+ - `node_modules/@joktec/mysql/dist/index.d.ts`
600
+ - `node_modules/@joktec/mysql/dist/mysql.module.d.ts`
601
+ - `node_modules/@joktec/mysql/dist/mysql.service.d.ts`
602
+ - `node_modules/@joktec/mysql/dist/mysql.repo.d.ts`
603
+ - `node_modules/@joktec/mysql/dist/models/mysql.request.d.ts`
604
+
605
+ If the installed package is insufficient, read GitHub package docs next:
606
+
607
+ - `https://github.com/joktec/joktec-framework/tree/main/packages/databases/mysql`
608
+
609
+ Use GitHub source only after installed types and package docs are not enough:
610
+
611
+ - `packages/databases/mysql/README.md`
612
+ - `packages/databases/mysql/AGENTS.md`
613
+ - `packages/databases/mysql/src/index.ts`
614
+ - `packages/databases/mysql/src/mysql.module.ts`
615
+ - `packages/databases/mysql/src/mysql.service.ts`
616
+ - `packages/databases/mysql/src/mysql.repo.ts`
617
+ - `packages/databases/mysql/src/helpers/mysql.helper.ts`
618
+ - `packages/databases/mysql/src/helpers/mysql.finder.ts`
619
+ - `packages/databases/mysql/src/services/mysql.dialect.ts`
620
+ - `packages/databases/mysql/src/models/*`
621
+
241
622
  ## Module Setup
242
623
 
243
624
  Register entities with `MysqlModule.forRoot({ conId, models: [...] })`. Use `conId` for multiple DataSources.
244
625
 
626
+ Best practice:
627
+
628
+ - Register consumer app entities in an app repository module.
629
+ - Keep `sync` disabled in request-facing processes unless the app intentionally owns schema sync.
630
+ - Use one controlled owner process for schema sync/migration in multi-process deployments.
631
+ - Preserve `conId` when resolving repositories or transaction-scoped managers.
632
+
245
633
  ## Repository Pattern
246
634
 
247
635
  Extend `MysqlRepo` and pass the entity class to the base constructor. Services can use `BaseService` when CRUD behavior follows the shared contract.
248
636
 
637
+ Repository checklist:
638
+
639
+ - Keep entity-specific SQL helpers in the app repository, not in controllers.
640
+ - Use `MysqlRepo.qb()` and repository methods for standard reads so field validation, relation loading, soft delete, and pagination stay consistent.
641
+ - Do not add new behavior to `MysqlFinder`; it is deprecated compatibility code.
642
+ - Keep read/write operations in the same transaction context when the app passes a manager or query runner.
643
+
249
644
  ## Query Safety
250
645
 
251
646
  - Validate field paths against TypeORM metadata before interpolating SQL identifiers.
252
647
  - Use parameter binding for values.
253
648
  - Keep logical operators such as `$and` and `$or` grouped through QueryBuilder behavior.
254
649
 
650
+ Anti-patterns:
651
+
652
+ - Do not interpolate user-provided field names or relation names into SQL without TypeORM metadata validation.
653
+ - Do not assume MySQL-only syntax when the package supports MySQL, MariaDB, and Postgres.
654
+ - Do not use a relation/populate path unless it maps to entity metadata.
655
+
255
656
  ## Pagination
256
657
 
257
658
  `MysqlRepo.paginate` supports page, offset, and cursor responses. Cursor mode defaults to `createdAt` plus primary key columns. Custom cursor keys must be mapped columns.
258
659
 
660
+ Cursor checklist:
661
+
662
+ - Use `createdAt + primary key` as the default stable cursor.
663
+ - Add primary keys as tie-breakers for non-unique cursor keys.
664
+ - Ensure cursor keys are indexed for hot list endpoints.
665
+ - Validate cursor payload shape before building SQL.
666
+ - Treat cursor tokens as opaque; clients should not parse them.
667
+
259
668
  ## Transactions
260
669
 
261
670
  When using transaction-scoped operations, pass the manager or query runner through repository options so pre-read and write operations use the same context.
262
671
 
672
+ Transaction checklist:
673
+
674
+ - Use one manager/query runner for read-modify-write flows.
675
+ - Rollback tests should prove that both pre-read dependent writes and writes are transaction-scoped.
676
+ - Avoid mixing default repositories and transaction-scoped repositories in one operation.
677
+
263
678
  ---
264
679
 
265
680
  ## JokTec Broker Skill
@@ -279,6 +694,7 @@ Use this skill for message broker packages.
279
694
  - Use broker decorators for transport wiring, not for domain policy.
280
695
  - Preserve config-driven client selection and `conId` when available.
281
696
  - Keep topic, queue, and routing names explicit in app configuration or decorators.
697
+ - If guidance is insufficient, read this skill's references and inspect `../joktec-framework` package source or GitHub fallback before assuming APIs.
282
698
 
283
699
  ## Reference
284
700
 
@@ -290,10 +706,22 @@ Read `references/brokers.md` for setup and package-specific notes.
290
706
 
291
707
  # Broker Usage
292
708
 
709
+ ## Source Lookup
710
+
711
+ When blocked, inspect:
712
+
713
+ - `packages/brokers/README.md`
714
+ - `packages/brokers/AGENTS.md`
715
+ - `packages/brokers/<package>/README.md`
716
+ - `packages/brokers/<package>/src/index.ts`
717
+ - package decorators, loaders, config, and service files under `src/`
718
+
293
719
  ## Runtime Pattern
294
720
 
295
721
  Broker services follow `AbstractClientService` lifecycle. Loader classes discover decorator metadata after module initialization. Apps define producers, consumers, and message semantics.
296
722
 
723
+ Use broker packages for transport wiring, not for business workflow ownership. The consuming app owns event names, payload contracts, idempotency, retry policy, dead-letter behavior, and handler semantics.
724
+
297
725
  ## Package Notes
298
726
 
299
727
  - Kafka: check topic existence and broker advertised listeners in local development.
@@ -301,6 +729,23 @@ Broker services follow `AbstractClientService` lifecycle. Loader classes discove
301
729
  - SQS: local ElasticMQ-style environments may require queues to exist before consumers start.
302
730
  - Redcast: use Redis-backed list, stream, or pub/sub behavior when a lightweight broker is enough.
303
731
 
732
+ ## Best Practices
733
+
734
+ - Start consumers only in processes that should own subscriptions.
735
+ - Keep producer and consumer payload DTOs versionable and explicit.
736
+ - Use config paths or module options for topic/queue names when supported.
737
+ - Make handlers idempotent; brokers may redeliver.
738
+ - Add observable effects for consumer tests rather than asserting log text.
739
+ - Keep broker health/preflight checks separate from business request handling.
740
+ - In local stacks, verify broker-specific infrastructure: Kafka topics, Rabbit exchanges/queues, SQS queues, Redis password/db.
741
+
742
+ ## Anti-Patterns
743
+
744
+ - Do not hide domain workflows inside decorators or broker package services.
745
+ - Do not assume auto-create topic/queue behavior unless the package and local broker support it.
746
+ - Do not run the same consumer group/queue owner in every process by accident.
747
+ - Do not swallow message handling errors without retry/dead-letter visibility.
748
+
304
749
  ---
305
750
 
306
751
  ## JokTec Adapter Skill
@@ -320,6 +765,7 @@ Use this skill for pluggable external capability adapters.
320
765
  - Use validated config and `conId` where supported.
321
766
  - Keep secrets and credentials in app config or runtime environment, never in code.
322
767
  - Prefer adapter services over direct SDK usage in app services.
768
+ - If guidance is insufficient, read this skill's references and inspect `../joktec-framework` package source or GitHub fallback before assuming APIs.
323
769
 
324
770
  ## Reference
325
771
 
@@ -331,10 +777,22 @@ Read `references/adapters.md` for setup and package-specific notes.
331
777
 
332
778
  # Adapter Usage
333
779
 
780
+ ## Source Lookup
781
+
782
+ When blocked, inspect:
783
+
784
+ - `packages/adapters/README.md`
785
+ - `packages/adapters/AGENTS.md`
786
+ - `packages/adapters/<package>/README.md`
787
+ - `packages/adapters/<package>/src/index.ts`
788
+ - package module/config/service files under `src/`
789
+
334
790
  ## Runtime Pattern
335
791
 
336
792
  Adapters are global Nest modules. Services own native client creation and expose package-specific operations.
337
793
 
794
+ Most adapters follow `AbstractClientService`: config is validated, native clients are created by the service, `conId` selects the connection, and shutdown/retry/debug behavior should remain package-owned.
795
+
338
796
  ## Package Notes
339
797
 
340
798
  - Cacher: choose local, Redis, or Memcached stores based on runtime config.
@@ -342,6 +800,22 @@ Adapters are global Nest modules. Services own native client creation and expose
342
800
  - Notifier: keep push provider configuration outside app business logic.
343
801
  - Storage: keep storage metadata and object operations behind the adapter service.
344
802
 
803
+ ## Best Practices
804
+
805
+ - Import adapter modules in the application layer, then inject services into domain services.
806
+ - Keep provider credentials, endpoints, bucket names, SMTP secrets, and push credentials in runtime config.
807
+ - Keep business payload composition in the consuming app. The adapter should send/cache/store, not decide product semantics.
808
+ - Use `conId` for multiple providers or tenants instead of creating ad-hoc service instances.
809
+ - Normalize provider errors at the package/app boundary so controllers do not branch on SDK-specific messages.
810
+ - Mock SDK clients in unit tests; run live provider checks only in explicit integration or consumer harness tests.
811
+
812
+ ## Anti-Patterns
813
+
814
+ - Do not put email template business rules inside `@joktec/mailer`.
815
+ - Do not hardcode S3 buckets, Redis URLs, SMTP credentials, or notification tokens in source.
816
+ - Do not bypass adapter services by importing provider SDK clients directly throughout the app.
817
+ - Do not assume every adapter has identical method names; read each package README/source before calling.
818
+
345
819
  ---
346
820
 
347
821
  ## JokTec Extended Database Skill
@@ -360,6 +834,7 @@ Use this skill for database clients that are not Mongo or MySQL.
360
834
  - Use package services for client lifecycle and connection config.
361
835
  - Do not claim parity with Mongo/MySQL repository behavior unless the package implements it.
362
836
  - Use package README and source as final truth before adding advanced behavior.
837
+ - If guidance is insufficient, read this skill's references and inspect `../joktec-framework` package source or GitHub fallback before assuming APIs.
363
838
 
364
839
  ## Reference
365
840
 
@@ -371,6 +846,16 @@ Read `references/extended-databases.md` for package boundaries and usage notes.
371
846
 
372
847
  # Extended Database Usage
373
848
 
849
+ ## Source Lookup
850
+
851
+ When blocked, inspect:
852
+
853
+ - `packages/databases/README.md`
854
+ - `packages/databases/AGENTS.md`
855
+ - `packages/databases/<package>/README.md`
856
+ - `packages/databases/<package>/src/index.ts`
857
+ - package config/module/service files under `src/`
858
+
374
859
  ## Package Boundaries
375
860
 
376
861
  Extended database packages expose reusable clients and helpers for specific data systems. They should not contain consumer app schemas or business-specific query policy.
@@ -381,6 +866,20 @@ Extended database packages expose reusable clients and helpers for specific data
381
866
  - Arango and BigQuery are separate client packages; verify the README/source before assuming repository-like CRUD support.
382
867
  - Use local package tests or consumer harnesses only when the target service stack is available.
383
868
 
869
+ ## Best Practices
870
+
871
+ - Treat these packages as client wrappers unless source explicitly exposes a repository abstraction.
872
+ - Keep index names, dataset names, query templates, and domain-specific projections in the consumer app.
873
+ - Validate credentials and endpoints through config; never commit service account data.
874
+ - Keep retries, timeouts, and debug logging visible in config.
875
+ - Use provider-specific tests/mocks for package logic and live stack tests only when credentials/services are intentionally available.
876
+
877
+ ## Anti-Patterns
878
+
879
+ - Do not apply MongoRepo/MysqlRepo assumptions to Elastic/Arango/BigQuery.
880
+ - Do not introduce app schemas or business query policy into reusable database clients.
881
+ - Do not claim support for a provider feature unless the package source or README shows it.
882
+
384
883
  ---
385
884
 
386
885
  ## JokTec Integration Skill
@@ -398,6 +897,7 @@ Use this skill for third-party integration packages.
398
897
  - Use package services instead of direct SDK initialization in app code.
399
898
  - Preserve app-neutral service behavior; consumer apps own domain workflows.
400
899
  - Verify current package README/source before relying on advanced provider features.
900
+ - If guidance is insufficient, read this skill's references and inspect `../joktec-framework` package source or GitHub fallback before assuming APIs.
401
901
 
402
902
  ## Reference
403
903
 
@@ -409,14 +909,43 @@ Read `references/integrations.md` for provider-specific notes.
409
909
 
410
910
  # Integration Usage
411
911
 
912
+ ## Source Lookup
913
+
914
+ When blocked, inspect:
915
+
916
+ - `packages/integrations/README.md`
917
+ - `packages/integrations/AGENTS.md`
918
+ - `packages/integrations/<package>/README.md`
919
+ - `packages/integrations/<package>/src/index.ts`
920
+ - package config/module/service files under `src/`
921
+
412
922
  ## Firebase
413
923
 
414
924
  Use the integration module and service to initialize Firebase Admin clients from validated config. Keep credential files local or environment-provided.
415
925
 
926
+ Best practice:
927
+
928
+ - Keep service account JSON, private keys, and project credentials out of git.
929
+ - Prefer environment-specific config or ignored local credential files.
930
+ - Keep notification/user/storage/product semantics in the consumer app.
931
+ - Mock Firebase Admin SDK in package tests; use live credentials only in explicit integration environments.
932
+
416
933
  ## GPT
417
934
 
418
935
  Use the integration package for reusable GPT client setup. Keep prompt/business policy in the consumer app, not in the generic package.
419
936
 
937
+ Best practice:
938
+
939
+ - Keep prompts, model choice policy, tool schemas, and product safety rules in the consumer app.
940
+ - Keep API keys in secret management or environment config.
941
+ - Verify current package completeness before relying on advanced APIs; `@joktec/gpt` may lag behind provider SDK changes.
942
+
943
+ ## Anti-Patterns
944
+
945
+ - Do not commit real credential files.
946
+ - Do not encode product-specific prompts or notification logic into the reusable integration package.
947
+ - Do not assume provider SDK behavior without checking package source and provider docs when APIs are unstable.
948
+
420
949
  ---
421
950
 
422
951
  ## JokTec Tool Skill
@@ -435,6 +964,7 @@ Use this skill for reusable utility services.
435
964
  - Use config-driven clients instead of direct ad hoc setup in app code.
436
965
  - Preserve retry, metrics, proxy, and upload behavior where the package exposes it.
437
966
  - Keep alert tokens and webhook URLs in runtime config only.
967
+ - If guidance is insufficient, read this skill's references and inspect `../joktec-framework` package source or GitHub fallback before assuming APIs.
438
968
 
439
969
  ## Reference
440
970
 
@@ -446,14 +976,484 @@ Read `references/tools.md` for package-specific usage notes.
446
976
 
447
977
  # Tool Usage
448
978
 
979
+ ## Source Lookup
980
+
981
+ When blocked, inspect:
982
+
983
+ - `packages/tools/README.md`
984
+ - `packages/tools/AGENTS.md`
985
+ - `packages/tools/<package>/README.md`
986
+ - `packages/tools/<package>/src/index.ts`
987
+ - package config/module/service/helper files under `src/`
988
+
449
989
  ## HTTP
450
990
 
451
991
  Use `@joktec/http` for Axios-backed requests, uploads, proxy agent support, retry config, and metrics where exposed.
452
992
 
993
+ Best practice:
994
+
995
+ - Use the package service for outbound HTTP so retry/proxy/metrics behavior stays centralized.
996
+ - Keep external endpoint URLs and credentials in runtime config.
997
+ - Be careful with ESM/CommonJS import changes in HTTP/Axios ecosystem packages.
998
+ - `HttpService.buildAgent(proxy, opts)` expects proxy identity in `HttpProxyConfig` and agent tuning in Node `AgentOptions`; inspect the installed source before adapting to proxy-agent major-version changes.
999
+ - Test request behavior with mocks unless the test is an explicit consumer integration scenario.
1000
+
453
1001
  ## File
454
1002
 
455
1003
  Use `@joktec/file` for shared file helpers and classification behavior instead of duplicating local utility code.
456
1004
 
1005
+ Best practice:
1006
+
1007
+ - Keep filesystem paths and temporary directories environment-specific.
1008
+ - Validate upload/file inputs before passing them into business workflows.
1009
+ - Use package helpers for MIME/classification behavior when consistency matters across services.
1010
+
457
1011
  ## Alert
458
1012
 
459
1013
  Use `@joktec/alert` for Slack-compatible webhook alerts. Keep webhook URLs and credentials out of source control.
1014
+
1015
+ Best practice:
1016
+
1017
+ - Treat alert messages as operational notifications, not business workflows.
1018
+ - Do not leak secrets, tokens, connection strings, or personal data into alert payloads.
1019
+ - `@joktec/alert` is present but less complete than core database/client packages; inspect source before depending on advanced behavior.
1020
+
1021
+ ## Anti-Patterns
1022
+
1023
+ - Do not scatter raw Axios instances across the app when `@joktec/http` should own shared behavior.
1024
+ - Do not commit webhook URLs or proxy credentials.
1025
+ - Do not use tool packages as hidden places for app business rules.
1026
+
1027
+ ---
1028
+
1029
+ ## Advanced TypeScript Design
1030
+
1031
+ ## Overview
1032
+
1033
+ Act as a TypeScript architecture partner. Choose the simplest design that preserves clear boundaries, runtime correctness, and useful compile-time guarantees.
1034
+
1035
+ Use design patterns as vocabulary and pressure tests, not as decoration. Prefer local project conventions, readable APIs, and low-friction extension points before adding type-level machinery.
1036
+
1037
+ ## Architectural Mindset
1038
+
1039
+ - Start from the domain boundary: identify entity, request/response, service, repository, client, decorator, loader, and integration responsibilities.
1040
+ - Keep public APIs narrow and stable. Make extension explicit through interfaces, abstract classes, generic constraints, or composition.
1041
+ - Use classes when lifecycle, inheritance hooks, decorators, or framework reflection matter. Use plain functions/types when behavior is stateless or purely transformational.
1042
+ - Let runtime validation and compile-time types reinforce each other. Do not pretend TypeScript types validate untrusted runtime data.
1043
+ - Do not assume TypeScript generics, interfaces, unions, or array element types exist at runtime through `reflect-metadata`.
1044
+ - Escalate type complexity only when it removes real duplication, prevents invalid states, or makes an API substantially safer.
1045
+ - Check existing code before inventing a new pattern; mirror the repository's style when it already solves the same class of problem.
1046
+
1047
+ ## Public API Compatibility
1048
+
1049
+ - Treat exported types, classes, decorators, config objects, modules, and provider APIs as public contracts.
1050
+ - Prefer additive changes over breaking renames, deleted fields, changed generic parameter order, or narrower accepted input shapes.
1051
+ - Before changing exported generic types, check downstream inference from normal call sites and verify that common extension patterns still compile.
1052
+ - If a breaking type or runtime contract change is unavoidable, report migration impact explicitly and include the smallest migration path.
1053
+
1054
+ ## Pattern Vocabulary
1055
+
1056
+ Use the classic catalog as shared language, including the TypeScript examples catalog from Refactoring.Guru.
1057
+
1058
+ - Creational Patterns: Abstract Factory, Builder, Factory Method, Prototype, Singleton.
1059
+ - Structural Patterns: Adapter, Bridge, Composite, Decorator, Facade, Flyweight, Proxy.
1060
+ - Behavioral Patterns: Chain of Responsibility, Iterator, Memento, State, Template Method, Command, Mediator, Observer, Strategy, Visitor.
1061
+
1062
+ Treat pattern names as a starting point for design discussion. Validate whether the implementation needs the pattern's tradeoffs, or whether a direct function, data object, or interface is enough.
1063
+
1064
+ ## Agent Workflow
1065
+
1066
+ 1. Inspect local code first when working inside a repository. Look for existing abstractions, decorators, DTO types, factory functions, lifecycle hooks, and tests.
1067
+ 2. Classify the task:
1068
+ - Use `references/simple.md` for everyday TypeScript, OOP, data modeling, classes, interfaces, types, records, maps, arrays, simple decorators, and pragmatic refactors.
1069
+ - Use `references/advanced.md` for generic framework code, recursive mapped types, `infer`, distributed/deferred conditional types, reflection metadata, advanced decorators, type-safe builders, plugin architectures, or expert pattern selection.
1070
+ 3. Choose the least complex pattern that solves the force in front of you. Record why a simpler alternative was not enough when choosing advanced machinery.
1071
+ 4. Design the public surface before implementation: inputs, outputs, extension points, error behavior, lifecycle, and type inference experience.
1072
+ 5. Implement incrementally. Keep runtime behavior testable, and add focused type-level checks when exported generic or decorator behavior is subtle.
1073
+ 6. Review for overengineering: remove unused generic parameters, speculative base classes, unnecessary inheritance, and type utilities that do not protect a real API.
1074
+
1075
+ ## Repository Signals
1076
+
1077
+ In JokTec-style TypeScript, expect patterns such as:
1078
+
1079
+ - Generic request/query types with recursive conditions and sort/populate typing.
1080
+ - Factory functions that return decorated NestJS classes.
1081
+ - Abstract services and clients with template methods for lifecycle-specific behavior.
1082
+ - Decorator factories that compose validation, Swagger, transformation, metrics, and integration metadata.
1083
+ - Loader/registry patterns that collect decorator metadata and wire runtime behavior during module initialization.
1084
+
1085
+ ## Bundled References
1086
+
1087
+ ### references/advanced.md
1088
+
1089
+ # Advanced TypeScript Design Guidance
1090
+
1091
+ Use this reference for framework-level TypeScript, generic libraries, decorator infrastructure, metadata-driven loaders, and APIs where compile-time inference is part of the product experience.
1092
+
1093
+ ## Escalation Criteria
1094
+
1095
+ Reach for advanced TypeScript only when at least one is true:
1096
+
1097
+ - The API is reused widely and type inference prevents real misuse.
1098
+ - The runtime model is already generic, recursive, or metadata-driven.
1099
+ - The abstraction eliminates repeated boilerplate across many entities, DTOs, repositories, services, clients, or transports.
1100
+ - The type-level design mirrors a stable domain contract, not a speculative future.
1101
+ - Tests or examples can prove both runtime behavior and developer ergonomics.
1102
+
1103
+ If the advanced type exists only to feel clever, delete it.
1104
+
1105
+ ## Infer, Conditional, and Deferred Types
1106
+
1107
+ - Use `infer` to extract return types, payloads, entity types, DTO shapes, tuple elements, and callback signatures from source contracts.
1108
+ - Control distributive conditional types intentionally. Wrap operands in tuples, such as `[T] extends [U]`, when union distribution is not wanted.
1109
+ - Prefer named intermediate aliases when nested conditionals exceed two branches.
1110
+ - Use `never` as a filter, but verify that it cannot erase useful error information from public APIs.
1111
+ - Treat deferred conditional types and generic inference as public UX: callers should get helpful autocomplete and errors without manual type arguments.
1112
+
1113
+ ## Recursive and Mapped Types
1114
+
1115
+ - Use recursive mapped types for query languages, nested sort/select/populate APIs, deep partials, and entity graph traversal.
1116
+ - Add clear stop conditions for primitives, dates, arrays, functions, and branded values.
1117
+ - Use branded or opaque types for special primitives such as `ObjectId`, `UserId`, tenant IDs, cursors, or external reference IDs when plain strings would blur domain boundaries.
1118
+ - Avoid infinite or overly expensive type recursion. Keep recursion shallow enough for editor performance.
1119
+ - Preserve optionality and readonly modifiers intentionally with `+?`, `-?`, `readonly`, and `-readonly`.
1120
+ - Separate query operator typing from entity typing so the operator model remains testable and reusable.
1121
+
1122
+ ## Reflection and Decorators
1123
+
1124
+ - Use `reflect-metadata` only when runtime type information materially improves the API: schema generation, validation composition, serialization, dependency injection, or loader registration.
1125
+ - Remember that reflected TypeScript types are lossy at runtime. Arrays, unions, generics, and interfaces need explicit options or factories.
1126
+ - Prefer decorator factories that normalize options, resolve type factories, compose framework decorators, and define one clear metadata contract.
1127
+ - Keep advanced decorators thin at the call site and explicit internally: clone options, sanitize runtime-only fields, then compose validators, transformers, docs, and persistence metadata.
1128
+ - For method decorators, preserve `this`, return values, thrown errors, and async behavior unless the decorator explicitly changes them.
1129
+ - Use function source parsing only as a last-resort runtime technique for decorator infrastructure, such as mapping method argument names. Keep it isolated, deterministic, and covered by tests because minification, transpilation, defaults, destructuring, and comments can break it.
1130
+ - Test decorator behavior through a class that uses it, especially for metadata, wrapping behavior, and dependency injection.
1131
+
1132
+ ## Type-Level Verification
1133
+
1134
+ - Add type-level tests when changing exported generic utilities, query DSLs, decorators, builders, or public inference-heavy APIs.
1135
+ - Prefer the project's existing compile/type test setup. If available, use `tsd`, `expect-type`, `vitest`/`jest` type helpers, or a dedicated `tsc --noEmit` fixture.
1136
+ - Include positive inference examples from normal call sites, not only explicit generic arguments.
1137
+ - Include negative examples with `@ts-expect-error` when an invalid state must stay rejected.
1138
+ - Verify runtime tests separately when decorators, reflection metadata, validation, transformation, or loaders are involved.
1139
+
1140
+ ## Expert Pattern Selection
1141
+
1142
+ - Abstract Factory fits families of related clients, repositories, or transport adapters that must be created consistently.
1143
+ - Builder fits fluent configuration with required-step guarantees; type-state builders can enforce completeness but should stay readable.
1144
+ - Factory Method fits framework hooks that create DTOs, pagination wrappers, controllers, or provider instances.
1145
+ - Prototype fits cloning configured objects when construction is expensive or stateful.
1146
+ - Singleton should usually be delegated to the DI container; avoid hand-rolled global state.
1147
+ - Adapter fits third-party client normalization and migration layers.
1148
+ - Bridge fits separating abstraction from implementation, such as transport-agnostic messaging APIs over Rabbit, Kafka, or Redis.
1149
+ - Composite fits tree-shaped filters, pipelines, menu/routes, or nested query conditions.
1150
+ - Decorator fits metrics, retries, circuit breakers, serialization, validation, or publishing side effects around existing behavior.
1151
+ - Facade fits a stable service hiding multiple low-level collaborators.
1152
+ - Flyweight fits large repeated metadata or schema objects only after measuring memory pressure.
1153
+ - Proxy fits lazy clients, caching, access control, retries, and remote boundaries.
1154
+ - Chain of Responsibility fits validation, middleware, parsing, and request pipelines.
1155
+ - Command fits queued work, replayable operations, and undoable actions.
1156
+ - Iterator fits cursor pagination and collection traversal without exposing storage details.
1157
+ - Mediator fits module coordination where direct dependencies would become tangled.
1158
+ - Memento fits snapshots, rollbacks, and state restoration.
1159
+ - Observer fits event streams and pub/sub, with explicit unsubscribe and error policy.
1160
+ - State fits lifecycle-heavy clients, jobs, or connections with mode-specific behavior.
1161
+ - Strategy fits interchangeable algorithms selected by config or runtime context.
1162
+ - Template Method fits abstract base services/clients that own lifecycle while subclasses implement `init`, `start`, `stop`, `validate`, or `transform` steps.
1163
+ - Visitor fits operations over stable object structures when adding new operations is more common than adding new node types.
1164
+
1165
+ ## Symbolic Examples
1166
+
1167
+ Use examples like these as compact templates for thinking. Keep production implementations smaller or larger depending on the actual force.
1168
+
1169
+ ### Type-Safe Event Map
1170
+
1171
+ ```typescript
1172
+ type EventMap = {
1173
+ "user.created": { id: string };
1174
+ "invoice.paid": { invoiceId: string; amount: number };
1175
+ };
1176
+
1177
+ class EventBus<TEvents extends Record<string, unknown>> {
1178
+ on<K extends keyof TEvents>(event: K, handler: (payload: TEvents[K]) => void) {}
1179
+ emit<K extends keyof TEvents>(event: K, payload: TEvents[K]) {}
1180
+ }
1181
+
1182
+ const bus = new EventBus<EventMap>();
1183
+ bus.emit("invoice.paid", { invoiceId: "inv_1", amount: 100 });
1184
+ ```
1185
+
1186
+ Use this for Observer/Mediator-style APIs where event names and payloads must stay coupled.
1187
+
1188
+ ### API Contract Inference
1189
+
1190
+ ```typescript
1191
+ type Endpoint = {
1192
+ "/users/:id": {
1193
+ GET: { params: { id: string }; response: User };
1194
+ PATCH: { params: { id: string }; body: Partial<User>; response: User };
1195
+ };
1196
+ };
1197
+
1198
+ type ResponseOf<T> = T extends { response: infer R } ? R : never;
1199
+
1200
+ class ApiClient<TContract extends Record<string, any>> {
1201
+ request<Path extends keyof TContract, Method extends keyof TContract[Path]>(
1202
+ path: Path,
1203
+ method: Method,
1204
+ ): Promise<ResponseOf<TContract[Path][Method]>> {
1205
+ return null as any;
1206
+ }
1207
+ }
1208
+ ```
1209
+
1210
+ Use this when a contract object should drive call-site inference.
1211
+
1212
+ ### Type-State Builder
1213
+
1214
+ ```typescript
1215
+ type With<K extends string> = Record<K, true>;
1216
+
1217
+ class JobBuilder<State = {}> {
1218
+ queue(name: string): JobBuilder<State & With<"queue">> {
1219
+ return this as any;
1220
+ }
1221
+
1222
+ handler(fn: () => Promise<void>): JobBuilder<State & With<"handler">> {
1223
+ return this as any;
1224
+ }
1225
+
1226
+ build(this: State extends With<"queue"> & With<"handler"> ? JobBuilder<State> : never) {
1227
+ return {};
1228
+ }
1229
+ }
1230
+ ```
1231
+
1232
+ Use this when incomplete configuration is common and worth rejecting at compile time.
1233
+
1234
+ ### Recursive Query Shape
1235
+
1236
+ ```typescript
1237
+ type Primitive = string | number | boolean | Date;
1238
+ type FieldOp<T> = T | { $eq?: T; $in?: T[] };
1239
+ type Brand<T, Name extends string> = T & { readonly __brand: Name };
1240
+ type ObjectId = Brand<string, "ObjectId">;
1241
+
1242
+ type Query<T> = {
1243
+ [K in keyof T]?: T[K] extends Primitive
1244
+ ? FieldOp<T[K]>
1245
+ : T[K] extends Array<infer U>
1246
+ ? Query<U>
1247
+ : Query<T[K]>;
1248
+ } & {
1249
+ $or?: Query<T>[];
1250
+ };
1251
+ ```
1252
+
1253
+ Use this for Composite-style nested filters, but add stop conditions before expanding it.
1254
+
1255
+ ### Opaque ID Boundary
1256
+
1257
+ ```typescript
1258
+ type Brand<T, Name extends string> = T & { readonly __brand: Name };
1259
+ type UserId = Brand<string, "UserId">;
1260
+ type PostId = Brand<string, "PostId">;
1261
+
1262
+ function asUserId(value: string): UserId {
1263
+ return value as UserId;
1264
+ }
1265
+
1266
+ function findUser(id: UserId) {}
1267
+
1268
+ findUser(asUserId("u_1"));
1269
+ // @ts-expect-error raw strings are not accepted here
1270
+ findUser("u_1");
1271
+ ```
1272
+
1273
+ Use this when a domain primitive crosses many generic/query layers and accidental mixing would be costly.
1274
+
1275
+ ### Decorator Wrapper with Preserved Method Contract
1276
+
1277
+ ```typescript
1278
+ function Around(run: (next: () => unknown) => unknown): MethodDecorator {
1279
+ return (_, __, descriptor) => {
1280
+ const original = descriptor.value;
1281
+
1282
+ descriptor.value = function (...args: unknown[]) {
1283
+ return run(() => original.apply(this, args));
1284
+ };
1285
+ };
1286
+ }
1287
+ ```
1288
+
1289
+ Use this for metrics, retry, logging, or publishing side effects; preserve `this`, args, return values, and thrown errors.
1290
+
1291
+ ## JokTec-Style Signals to Reuse
1292
+
1293
+ - Recursive query typing can combine entity properties with operator unions, nested entity traversal, and logical `$or`/`$and` shapes.
1294
+ - Base services and clients commonly use Template Method: the base class owns lifecycle and shared behavior while subclasses provide specific implementation steps.
1295
+ - Controller factories can return decorated classes to avoid repetitive NestJS endpoint scaffolding while preserving DTO-specific metadata.
1296
+ - Decorator infrastructure often composes Swagger, validation, transformation, persistence, and metric behavior from one options object.
1297
+ - Rabbit loaders show a metadata registry plus module-init loader pattern: decorators declare intent; loaders resolve providers and connect runtime consumers.
1298
+
1299
+ ## Advanced Review Checklist
1300
+
1301
+ - Does every generic parameter appear in the public contract or implementation?
1302
+ - Can inference succeed from normal call-site arguments?
1303
+ - Does the type-level model match runtime validation and transformation?
1304
+ - Are metadata keys centralized and collision-resistant?
1305
+ - Are decorator side effects documented by tests?
1306
+ - Is editor performance acceptable after adding recursive or conditional types?
1307
+ - Is there a simpler Strategy, Adapter, or function-based design that would provide the same value?
1308
+
1309
+ ### references/simple.md
1310
+
1311
+ # Simple TypeScript Design Guidance
1312
+
1313
+ Use this reference for ordinary application and library work where readability, stable APIs, and maintainable TypeScript matter more than type-level cleverness.
1314
+
1315
+ ## Default Practices
1316
+
1317
+ - Prefer explicit, small interfaces for public boundaries and concrete classes for runtime behavior with lifecycle, dependency injection, or decorators.
1318
+ - Use `type` for unions, mapped shapes, conditional aliases, and composition. Use `interface` for object contracts intended to be implemented or extended.
1319
+ - Keep primitive aliases meaningful. A `UserId` alias can clarify intent, but it does not add runtime safety unless paired with validation or branding.
1320
+ - Model data with plain objects when behavior is absent. Add classes when construction, methods, inheritance hooks, decorators, or framework reflection are required.
1321
+ - Keep DTOs, entities, requests, and responses separate when they have different validation, persistence, or transport concerns.
1322
+ - Avoid `any` at public boundaries. Use `unknown` for untrusted data, then narrow or validate it.
1323
+ - Prefer narrow generic constraints such as `T extends Entity` over unconstrained `T` when the implementation depends on object semantics.
1324
+
1325
+ ## Classes, Interfaces, and OOP
1326
+
1327
+ - Use abstract classes for shared runtime behavior, protected hooks, and constructor-injected dependencies.
1328
+ - Use interfaces for contracts that should not carry runtime behavior.
1329
+ - Prefer composition over inheritance when variants differ by collaborator rather than lifecycle.
1330
+ - Keep protected hooks purposeful: `afterInit`, `transform`, `validate`, and `map` are good when subclasses are expected to customize one stable step.
1331
+ - Avoid deep inheritance chains. If a third level appears, consider Strategy, Adapter, or composition.
1332
+
1333
+ ## Common Data Structures
1334
+
1335
+ - Use `Record<K, V>` when the key set is known or constrained.
1336
+ - Use `{ [key: string]: V }` when the object is truly open-ended.
1337
+ - Use `Map<K, V>` when keys are not strings, insertion order matters, or frequent add/remove operations are central.
1338
+ - Use arrays for ordered collections and tuples for fixed positional contracts.
1339
+ - Use discriminated unions for state or command variants instead of loose booleans.
1340
+ - Keep hash-like caches private unless callers need iteration, eviction, or explicit lifecycle.
1341
+
1342
+ ## Basic Types and Utilities
1343
+
1344
+ - Use union literals for finite options: status, mode, operation, direction.
1345
+ - Use `Pick`, `Omit`, `Partial`, `Required`, `Readonly`, `Record`, `Extract`, and `Exclude` before writing custom utilities.
1346
+ - Use `keyof` and indexed access types for property-safe APIs.
1347
+ - Use overloads sparingly; prefer a single options object when overloads become hard to read.
1348
+ - Keep mapped types shallow unless the data is truly nested and the API benefits from deep transformation.
1349
+
1350
+ ## Simple Decorators
1351
+
1352
+ - Use decorator factories to attach framework metadata or compose existing decorators.
1353
+ - Keep decorator options serializable and explicit where possible.
1354
+ - Separate metadata collection from runtime execution. A decorator should usually register intent; a loader/service should execute it later.
1355
+ - Avoid parsing function source in ordinary decorators. If runtime argument-name mapping truly requires it, escalate to `advanced.md` and isolate the parser behind tests.
1356
+ - Test decorators at the behavior boundary, not only by checking metadata keys.
1357
+
1358
+ ## Pattern Choices
1359
+
1360
+ - Use Factory Method or simple factory functions when object creation varies by type or config.
1361
+ - Use Builder for stepwise configuration only when partially built objects are common or order matters.
1362
+ - Use Adapter to normalize third-party APIs behind project interfaces.
1363
+ - Use Facade to simplify a noisy subsystem for callers.
1364
+ - Use Decorator when behavior should wrap a method/object without changing its public contract.
1365
+ - Use Template Method when a base class owns an algorithm and subclasses fill in specific steps.
1366
+ - Use Strategy when an algorithm family changes independently from the caller.
1367
+ - Use Observer or Mediator for event-style communication, but keep ownership and error handling explicit.
1368
+
1369
+ ## Symbolic Examples
1370
+
1371
+ Use examples like these to reason about shape and tradeoffs. Keep final code adapted to the repository style.
1372
+
1373
+ ### Strategy with a Narrow Interface
1374
+
1375
+ ```typescript
1376
+ interface PriceStrategy {
1377
+ total(items: CartItem[]): number;
1378
+ }
1379
+
1380
+ class RetailPrice implements PriceStrategy {
1381
+ total(items: CartItem[]) {
1382
+ return items.reduce((sum, item) => sum + item.price, 0);
1383
+ }
1384
+ }
1385
+
1386
+ class WholesalePrice implements PriceStrategy {
1387
+ total(items: CartItem[]) {
1388
+ return items.reduce((sum, item) => sum + item.price * 0.9, 0);
1389
+ }
1390
+ }
1391
+
1392
+ class CheckoutService {
1393
+ constructor(private readonly strategy: PriceStrategy) {}
1394
+
1395
+ quote(items: CartItem[]) {
1396
+ return this.strategy.total(items);
1397
+ }
1398
+ }
1399
+ ```
1400
+
1401
+ Use this when the caller should not know which algorithm is active.
1402
+
1403
+ ### Adapter for Third-Party Boundaries
1404
+
1405
+ ```typescript
1406
+ interface MessageBus {
1407
+ publish(topic: string, payload: unknown): Promise<void>;
1408
+ }
1409
+
1410
+ class RabbitBusAdapter implements MessageBus {
1411
+ constructor(private readonly rabbit: RabbitClient) {}
1412
+
1413
+ publish(topic: string, payload: unknown) {
1414
+ return this.rabbit.sendToQueue(topic, JSON.stringify(payload));
1415
+ }
1416
+ }
1417
+ ```
1418
+
1419
+ Use this when external clients have noisy or unstable APIs.
1420
+
1421
+ ### Template Method for Lifecycle Hooks
1422
+
1423
+ ```typescript
1424
+ abstract class ManagedClient<TConfig, TClient> {
1425
+ async connect(config: TConfig) {
1426
+ const client = await this.create(config);
1427
+ await this.start(client);
1428
+ return client;
1429
+ }
1430
+
1431
+ protected abstract create(config: TConfig): Promise<TClient>;
1432
+ protected abstract start(client: TClient): Promise<void>;
1433
+ }
1434
+ ```
1435
+
1436
+ Use this when the base class owns lifecycle order and subclasses fill the variable steps.
1437
+
1438
+ ### Simple Decorator Metadata
1439
+
1440
+ ```typescript
1441
+ const HANDLER_KEY = "app:handler";
1442
+
1443
+ function Handler(name: string): MethodDecorator {
1444
+ return (_, __, descriptor) => {
1445
+ Reflect.defineMetadata(HANDLER_KEY, name, descriptor.value);
1446
+ };
1447
+ }
1448
+ ```
1449
+
1450
+ Use this when methods declare intent and another loader executes it later.
1451
+
1452
+ ## Practical Review Checklist
1453
+
1454
+ - Can a teammate understand the public API without reading private helpers?
1455
+ - Does the type design represent real runtime rules?
1456
+ - Are names domain-specific enough to explain intent?
1457
+ - Is the pattern solving current duplication or variability?
1458
+ - Are validation, transformation, persistence, and transport concerns separated?
1459
+ - Are tests focused on behavior that the abstraction promises to preserve?