contextos-agents 2.1.0 → 2.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (191) hide show
  1. package/.agents/adapters/aider/export.js +2 -2
  2. package/.agents/adapters/claude/export.js +53 -2
  3. package/.agents/adapters/drift-detector.js +6 -3
  4. package/.agents/adapters/pure-compiler.js +18 -6
  5. package/.agents/ctx.js +4 -4
  6. package/.agents/plugins.js +100 -4
  7. package/.agents/profiles.js +32 -11
  8. package/README.md +2 -2
  9. package/bin/commands/hook.js +50 -12
  10. package/bin/commands/scan.js +10 -3
  11. package/bin/index.js +8 -2
  12. package/bin/lib/git-snapshot.js +70 -43
  13. package/bin/lib/scan.js +108 -27
  14. package/catalog/skills/adapters/EXAMPLES.md +19 -0
  15. package/catalog/skills/adapters/SKILL.md +101 -0
  16. package/catalog/skills/adapters/TROUBLESHOOTING.md +7 -0
  17. package/catalog/skills/adapters/VALIDATION.json +12 -0
  18. package/catalog/skills/adapters/skill.yaml +13 -0
  19. package/catalog/skills/api-design/EXAMPLES.md +91 -0
  20. package/catalog/skills/api-design/SKILL.md +63 -0
  21. package/catalog/skills/api-design/TROUBLESHOOTING.md +54 -0
  22. package/catalog/skills/api-design/VALIDATION.json +11 -0
  23. package/catalog/skills/api-design/skill.yaml +14 -0
  24. package/catalog/skills/architecture-diagrams/SKILL.md +108 -0
  25. package/catalog/skills/architecture-diagrams/VALIDATION.json +12 -0
  26. package/catalog/skills/architecture-diagrams/skill.yaml +9 -0
  27. package/catalog/skills/brutalist-design/EXAMPLES.md +59 -0
  28. package/catalog/skills/brutalist-design/SKILL.md +150 -0
  29. package/catalog/skills/brutalist-design/VALIDATION.json +12 -0
  30. package/catalog/skills/brutalist-design/skill.yaml +10 -0
  31. package/catalog/skills/ci-cd/EXAMPLES.md +79 -0
  32. package/catalog/skills/ci-cd/SKILL.md +69 -0
  33. package/catalog/skills/ci-cd/TROUBLESHOOTING.md +52 -0
  34. package/catalog/skills/ci-cd/VALIDATION.json +11 -0
  35. package/catalog/skills/ci-cd/skill.yaml +13 -0
  36. package/catalog/skills/database/EXAMPLES.md +74 -0
  37. package/catalog/skills/database/SKILL.md +101 -0
  38. package/catalog/skills/database/TROUBLESHOOTING.md +18 -0
  39. package/catalog/skills/database/VALIDATION.json +11 -0
  40. package/catalog/skills/database/skill.yaml +14 -0
  41. package/catalog/skills/ddd/EXAMPLES.md +42 -0
  42. package/catalog/skills/ddd/SKILL.md +247 -0
  43. package/catalog/skills/ddd/TROUBLESHOOTING.md +19 -0
  44. package/catalog/skills/ddd/VALIDATION.json +12 -0
  45. package/catalog/skills/ddd/skill.yaml +14 -0
  46. package/catalog/skills/decisions/EXAMPLES.md +35 -0
  47. package/catalog/skills/decisions/SKILL.md +90 -0
  48. package/catalog/skills/decisions/TROUBLESHOOTING.md +13 -0
  49. package/catalog/skills/decisions/VALIDATION.json +12 -0
  50. package/catalog/skills/decisions/skill.yaml +13 -0
  51. package/catalog/skills/docker/EXAMPLES.md +56 -0
  52. package/catalog/skills/docker/SKILL.md +169 -0
  53. package/catalog/skills/docker/TROUBLESHOOTING.md +18 -0
  54. package/catalog/skills/docker/VALIDATION.json +11 -0
  55. package/catalog/skills/docker/skill.yaml +13 -0
  56. package/catalog/skills/fastapi/EXAMPLES.md +36 -0
  57. package/catalog/skills/fastapi/SKILL.md +171 -0
  58. package/catalog/skills/fastapi/TROUBLESHOOTING.md +19 -0
  59. package/catalog/skills/fastapi/VALIDATION.json +12 -0
  60. package/catalog/skills/fastapi/skill.yaml +14 -0
  61. package/catalog/skills/generators/EXAMPLES.md +19 -0
  62. package/catalog/skills/generators/SKILL.md +110 -0
  63. package/catalog/skills/generators/TROUBLESHOOTING.md +7 -0
  64. package/catalog/skills/generators/VALIDATION.json +12 -0
  65. package/catalog/skills/generators/skill.yaml +22 -0
  66. package/catalog/skills/generators/templates/API.md +77 -0
  67. package/catalog/skills/generators/templates/ARCHITECTURE.md +70 -0
  68. package/catalog/skills/generators/templates/DATABASE.md +42 -0
  69. package/catalog/skills/generators/templates/DECISION.md +46 -0
  70. package/catalog/skills/generators/templates/PRD.md +67 -0
  71. package/catalog/skills/generators/templates/PROJECT_GRAPH.md +56 -0
  72. package/catalog/skills/generators/templates/ROADMAP.md +51 -0
  73. package/catalog/skills/generators/templates/TASKS.md +43 -0
  74. package/catalog/skills/generators/templates/UI.md +73 -0
  75. package/catalog/skills/graphify/EXAMPLES.md +73 -0
  76. package/catalog/skills/graphify/SKILL.md +130 -0
  77. package/catalog/skills/graphify/VALIDATION.json +12 -0
  78. package/catalog/skills/graphify/skill.yaml +13 -0
  79. package/catalog/skills/impeccable-design/EXAMPLES.md +26 -0
  80. package/catalog/skills/impeccable-design/SKILL.md +201 -0
  81. package/catalog/skills/impeccable-design/TROUBLESHOOTING.md +19 -0
  82. package/catalog/skills/impeccable-design/VALIDATION.json +12 -0
  83. package/catalog/skills/impeccable-design/skill.yaml +15 -0
  84. package/catalog/skills/interview-me/SKILL.md +97 -0
  85. package/catalog/skills/interview-me/VALIDATION.json +12 -0
  86. package/catalog/skills/interview-me/skill.yaml +9 -0
  87. package/catalog/skills/microservices/EXAMPLES.md +38 -0
  88. package/catalog/skills/microservices/SKILL.md +164 -0
  89. package/catalog/skills/microservices/TROUBLESHOOTING.md +19 -0
  90. package/catalog/skills/microservices/VALIDATION.json +12 -0
  91. package/catalog/skills/microservices/skill.yaml +14 -0
  92. package/catalog/skills/minimalist-design/EXAMPLES.md +58 -0
  93. package/catalog/skills/minimalist-design/SKILL.md +113 -0
  94. package/catalog/skills/minimalist-design/VALIDATION.json +12 -0
  95. package/catalog/skills/minimalist-design/skill.yaml +10 -0
  96. package/catalog/skills/nestjs/EXAMPLES.md +40 -0
  97. package/catalog/skills/nestjs/SKILL.md +139 -0
  98. package/catalog/skills/nestjs/TROUBLESHOOTING.md +19 -0
  99. package/catalog/skills/nestjs/VALIDATION.json +12 -0
  100. package/catalog/skills/nestjs/skill.yaml +14 -0
  101. package/catalog/skills/nextjs/EXAMPLES.md +40 -0
  102. package/catalog/skills/nextjs/SKILL.md +163 -0
  103. package/catalog/skills/nextjs/TROUBLESHOOTING.md +19 -0
  104. package/catalog/skills/nextjs/VALIDATION.json +12 -0
  105. package/catalog/skills/nextjs/skill.yaml +14 -0
  106. package/catalog/skills/node/EXAMPLES.md +80 -0
  107. package/catalog/skills/node/SKILL.md +128 -0
  108. package/catalog/skills/node/TROUBLESHOOTING.md +19 -0
  109. package/catalog/skills/node/VALIDATION.json +12 -0
  110. package/catalog/skills/node/skill.yaml +14 -0
  111. package/catalog/skills/performance/EXAMPLES.md +30 -0
  112. package/catalog/skills/performance/SKILL.md +75 -0
  113. package/catalog/skills/performance/TROUBLESHOOTING.md +19 -0
  114. package/catalog/skills/performance/VALIDATION.json +12 -0
  115. package/catalog/skills/performance/skill.yaml +14 -0
  116. package/catalog/skills/react/EXAMPLES.md +79 -0
  117. package/catalog/skills/react/SKILL.md +132 -0
  118. package/catalog/skills/react/TROUBLESHOOTING.md +19 -0
  119. package/catalog/skills/react/VALIDATION.json +12 -0
  120. package/catalog/skills/react/skill.yaml +14 -0
  121. package/catalog/skills/react-best-practices/SKILL.md +158 -0
  122. package/catalog/skills/react-best-practices/VALIDATION.json +12 -0
  123. package/catalog/skills/react-best-practices/skill.yaml +13 -0
  124. package/catalog/skills/redesign-audit/SKILL.md +117 -0
  125. package/catalog/skills/redesign-audit/VALIDATION.json +12 -0
  126. package/catalog/skills/redesign-audit/skill.yaml +9 -0
  127. package/catalog/skills/security-audit/EXAMPLES.md +79 -0
  128. package/catalog/skills/security-audit/SKILL.md +91 -0
  129. package/catalog/skills/security-audit/TROUBLESHOOTING.md +46 -0
  130. package/catalog/skills/security-audit/VALIDATION.json +11 -0
  131. package/catalog/skills/security-audit/skill.yaml +14 -0
  132. package/catalog/skills/soft-design/EXAMPLES.md +51 -0
  133. package/catalog/skills/soft-design/SKILL.md +108 -0
  134. package/catalog/skills/soft-design/VALIDATION.json +12 -0
  135. package/catalog/skills/soft-design/skill.yaml +10 -0
  136. package/catalog/skills/state-management/EXAMPLES.md +56 -0
  137. package/catalog/skills/state-management/SKILL.md +168 -0
  138. package/catalog/skills/state-management/TROUBLESHOOTING.md +18 -0
  139. package/catalog/skills/state-management/VALIDATION.json +11 -0
  140. package/catalog/skills/state-management/skill.yaml +14 -0
  141. package/catalog/skills/subagent-orchestrator/SKILL.md +117 -0
  142. package/catalog/skills/subagent-orchestrator/VALIDATION.json +12 -0
  143. package/catalog/skills/subagent-orchestrator/skill.yaml +9 -0
  144. package/catalog/skills/system-design/EXAMPLES.md +75 -0
  145. package/catalog/skills/system-design/SKILL.md +419 -0
  146. package/catalog/skills/system-design/TROUBLESHOOTING.md +19 -0
  147. package/catalog/skills/system-design/VALIDATION.json +12 -0
  148. package/catalog/skills/system-design/skill.yaml +14 -0
  149. package/catalog/skills/terraform/EXAMPLES.md +74 -0
  150. package/catalog/skills/terraform/SKILL.md +55 -0
  151. package/catalog/skills/terraform/TROUBLESHOOTING.md +53 -0
  152. package/catalog/skills/terraform/VALIDATION.json +11 -0
  153. package/catalog/skills/terraform/skill.yaml +14 -0
  154. package/catalog/skills/testing/EXAMPLES.md +122 -0
  155. package/catalog/skills/testing/SKILL.md +70 -0
  156. package/catalog/skills/testing/TROUBLESHOOTING.md +18 -0
  157. package/catalog/skills/testing/VALIDATION.json +11 -0
  158. package/catalog/skills/testing/skill.yaml +14 -0
  159. package/catalog/skills/typescript/EXAMPLES.md +64 -0
  160. package/catalog/skills/typescript/SKILL.md +112 -0
  161. package/catalog/skills/typescript/TROUBLESHOOTING.md +19 -0
  162. package/catalog/skills/typescript/VALIDATION.json +12 -0
  163. package/catalog/skills/typescript/skill.yaml +14 -0
  164. package/catalog/skills/ui-design/EXAMPLES.md +21 -0
  165. package/catalog/skills/ui-design/SKILL.md +124 -0
  166. package/catalog/skills/ui-design/TROUBLESHOOTING.md +19 -0
  167. package/catalog/skills/ui-design/VALIDATION.json +12 -0
  168. package/catalog/skills/ui-design/skill.yaml +16 -0
  169. package/catalog/skills/ui-ux-pro/EXAMPLES.md +62 -0
  170. package/catalog/skills/ui-ux-pro/SKILL.md +418 -0
  171. package/catalog/skills/ui-ux-pro/TROUBLESHOOTING.md +19 -0
  172. package/catalog/skills/ui-ux-pro/VALIDATION.json +12 -0
  173. package/catalog/skills/ui-ux-pro/skill.yaml +14 -0
  174. package/catalog/skills/ux-design/EXAMPLES.md +36 -0
  175. package/catalog/skills/ux-design/SKILL.md +116 -0
  176. package/catalog/skills/ux-design/TROUBLESHOOTING.md +19 -0
  177. package/catalog/skills/ux-design/VALIDATION.json +12 -0
  178. package/catalog/skills/ux-design/skill.yaml +16 -0
  179. package/catalog/skills/vercel-optimize/SKILL.md +83 -0
  180. package/catalog/skills/vercel-optimize/VALIDATION.json +12 -0
  181. package/catalog/skills/vercel-optimize/scripts/collect-signals.mjs +131 -0
  182. package/catalog/skills/vercel-optimize/scripts/gate-investigations.mjs +142 -0
  183. package/catalog/skills/vercel-optimize/scripts/merge-signals.mjs +143 -0
  184. package/catalog/skills/vercel-optimize/scripts/scan-codebase.mjs +174 -0
  185. package/catalog/skills/vercel-optimize/skill.yaml +15 -0
  186. package/catalog/skills/web-accessibility/EXAMPLES.md +39 -0
  187. package/catalog/skills/web-accessibility/SKILL.md +151 -0
  188. package/catalog/skills/web-accessibility/TROUBLESHOOTING.md +19 -0
  189. package/catalog/skills/web-accessibility/VALIDATION.json +12 -0
  190. package/catalog/skills/web-accessibility/skill.yaml +14 -0
  191. package/package.json +3 -2
@@ -0,0 +1,52 @@
1
+ # CI/CD - Troubleshooting & Common Edge Cases
2
+
3
+ ## Common Diagnostic Scenarios
4
+
5
+ ### 1. Flaky Integration Tests in CI Environments
6
+
7
+ - **Symptom**: Test suite randomly fails in GitHub Actions but always passes on developer machines.
8
+ - **Root Cause**: Race conditions, port collisions, unawaited background tasks, or timezone dependencies (`new Date().getHours()`) differing between UTC runners and local environments.
9
+ - **Fix Protocol**:
10
+ 1. Fix runner timezones to UTC in CI setup steps (`TZ: 'UTC'`).
11
+ 2. Eliminate hardcoded ports in integration tests; use ephemeral ports (`0`) or testcontainers.
12
+ 3. Ensure all asynchronous operations and database transactions are explicitly awaited before asserting and tearing down.
13
+ 4. Never use `retry` plugins to mask flaky tests; isolate the asynchronous race condition.
14
+
15
+ ---
16
+
17
+ ### 2. GitHub Actions Token Permission Denied (`Resource not accessible by integration`)
18
+
19
+ - **Symptom**: CI workflow fails at the checkout, comment, or release stage with an authorization error.
20
+ - **Root Cause**: The repository enforces secure defaults with read-only tokens, but the workflow needs to write statuses, PR comments, or packages.
21
+ - **Fix Protocol**:
22
+ - Declare explicit, least-privilege permissions at the job level rather than granting global admin rights:
23
+ ```yaml
24
+ jobs:
25
+ comment-pr:
26
+ runs-on: ubuntu-latest
27
+ permissions:
28
+ contents: read
29
+ pull-requests: write
30
+ ```
31
+
32
+ ---
33
+
34
+ ### 3. Exceeded Runner Minutes & Slow CI Builds
35
+
36
+ - **Symptom**: Workflow takes > 15 minutes to run, exhausting GitHub Actions free-tier minutes.
37
+ - **Root Cause**: Running `npm install` without package manager caching, sequential execution of independent checks, and missing concurrency cancellation.
38
+ - **Fix Protocol**:
39
+ 1. Use `actions/setup-node@v4` with `cache: 'npm'` to reuse cached node_modules across runs.
40
+ 2. Split monolithic jobs into parallel jobs: run lint, type-check, and unit tests concurrently.
41
+ 3. Add `concurrency` cancellation to cancel stale builds when a developer pushes new commits to an open PR.
42
+
43
+ ---
44
+
45
+ ### 4. Bundle Size Budget Check Failures
46
+
47
+ - **Symptom**: PR fails on `bundlesize` check with `Bundle size exceeded by 4.2 KB`.
48
+ - **Root Cause**: An imported third-party library pulled in heavy un-treeshaken dependencies or large date/locale libraries.
49
+ - **Fix Protocol**:
50
+ 1. Inspect the bundle visualizer or source map explorer.
51
+ 2. Replace broad root imports (`import { map } from 'lodash'`) with direct submodule imports (`import map from 'lodash/map'`).
52
+ 3. Dynamically import heavy UI widgets (modals, charts, rich text editors) using `React.lazy()` or `next/dynamic`.
@@ -0,0 +1,11 @@
1
+ {
2
+ "skill": "ci-cd",
3
+ "version": "1.0.0",
4
+ "checks": [
5
+ "Shift-left quality gates pipeline implemented in order",
6
+ "Least-privilege token permissions declared (contents: read)",
7
+ "Deterministic dependency installation enforced with frozen lockfile",
8
+ "Concurrency cancellation configured for PR branch updates",
9
+ "Unskippable gates invariant enforced without disabling rules"
10
+ ]
11
+ }
@@ -0,0 +1,13 @@
1
+ schemaVersion: 2
2
+ name: ci-cd
3
+ description: Shift-left CI/CD pipeline automation inspired by Addy Osmani. Enforces unskippable quality gates, least-privilege token permissions, and deterministic GitHub Actions workflows.
4
+ version: 1.0.0
5
+ category: devops
6
+ type: instruction-only
7
+ requires:
8
+ - engineering-workflow
9
+ resources:
10
+ - EXAMPLES.md
11
+ - SKILL.md
12
+ - TROUBLESHOOTING.md
13
+ - VALIDATION.json
@@ -0,0 +1,74 @@
1
+ # Database Examples - Anti-patterns vs ContextOS Standard
2
+
3
+ ## Example 1: Solving the N+1 Query Problem
4
+
5
+ ### Anti-pattern: Anti-pattern (N+1 database queries in a loop)
6
+
7
+ ```typescript
8
+ // BAD: 1 query for users + N queries for posts!
9
+ const users = await prisma.user.findMany();
10
+ const usersWithPosts = [];
11
+ for (const user of users) {
12
+ const posts = await prisma.post.findMany({ where: { userId: user.id } }); // N queries!
13
+ usersWithPosts.push({ ...user, posts });
14
+ }
15
+ ```
16
+
17
+ ### Best practice: ContextOS Standard (Batch query or relational include)
18
+
19
+ ```typescript
20
+ // GOOD: 1 single optimized batch query
21
+ const usersWithPosts = await prisma.user.findMany({
22
+ where: { isActive: true },
23
+ select: {
24
+ id: true,
25
+ name: true,
26
+ email: true,
27
+ posts: {
28
+ where: { published: true },
29
+ select: { id: true, title: true, createdAt: true },
30
+ take: 5
31
+ }
32
+ }
33
+ });
34
+ ```
35
+
36
+ ---
37
+
38
+ ## Example 2: Safe Atomic Transactions with Locking
39
+
40
+ ### Anti-pattern: Anti-pattern (Unprotected read-modify-write race condition)
41
+
42
+ ```typescript
43
+ // BAD: race condition between reading balance and updating
44
+ const account = await prisma.account.findUnique({ where: { id } });
45
+ if (account.balance >= amount) {
46
+ await prisma.account.update({
47
+ where: { id },
48
+ data: { balance: account.balance - amount }
49
+ });
50
+ }
51
+ ```
52
+
53
+ ### Best practice: ContextOS Standard (Atomic conditional update in transaction)
54
+
55
+ ```typescript
56
+ // GOOD: atomic database transaction with invariant check
57
+ export async function deductBalance(accountId: string, amount: number) {
58
+ return await prisma.$transaction(async (tx) => {
59
+ const updated = await tx.account.updateMany({
60
+ where: {
61
+ id: accountId,
62
+ balance: { gte: amount }
63
+ },
64
+ data: {
65
+ balance: { decrement: amount }
66
+ }
67
+ });
68
+
69
+ if (updated.count === 0) {
70
+ throw new InsufficientFundsError(accountId);
71
+ }
72
+ });
73
+ }
74
+ ```
@@ -0,0 +1,101 @@
1
+ ---
2
+ name: database
3
+ description: Database architecture, schema design, Prisma, Drizzle ORM, indexing strategies, migrations, and N+1 query resolution.
4
+ ---
5
+
6
+ # database
7
+
8
+ ## Overview
9
+
10
+ Relational database design, query optimization, migration safety, connection pooling in serverless environments, and ORM usage across PostgreSQL, Prisma, and Drizzle.
11
+
12
+ ## When to Use
13
+
14
+ Activate for tasks involving database schema design, migrations, indexing, relational models, ORM queries, transactions, or query performance tuning.
15
+
16
+ ## Rules & Patterns
17
+
18
+ ### Negative Constraints (What NOT to Do)
19
+
20
+ 1. **NEVER do `SELECT *` in production**: Always select explicit columns required by the caller to minimize memory bandwidth and lock footprint.
21
+ 2. **NEVER run destructive migrations without backward compatibility**: Always follow expand-and-contract (Phase 1: add new column as nullable; Phase 2: backfill; Phase 3: make non-nullable & remove old column).
22
+ 3. **NEVER execute queries in loops (The N+1 Anti-Pattern)**: Always use batch loading (`inArray`, `DataLoader`, or relational `include` / `JOIN`).
23
+ 4. **NEVER leave foreign keys without indexes**: In PostgreSQL/MySQL, child foreign key columns must always have an index to prevent table-level locking on cascade deletes.
24
+ 5. **NEVER perform multi-entity writes without a database transaction**: Any operation touching multiple records must use `prisma.$transaction` or `db.transaction`.
25
+ 6. **NEVER open unpooled database connections in Serverless / Edge functions**: Serverless scale-outs will instantly exhaust PostgreSQL's `max_connections`.
26
+
27
+ ---
28
+
29
+ ### Zero-Downtime Migrations (Expand-and-Contract)
30
+
31
+ When modifying schemas with zero downtime:
32
+
33
+ 1. **Phase 1 (Expand)**: Add the new column as `NULLABLE` (or with a default value). Deploy the application code that reads from old column and writes to both old and new.
34
+ 2. **Phase 2 (Backfill)**: Run an asynchronous batch migration job in chunks (e.g. 1000 rows at a time) to populate data from old column to new column.
35
+ 3. **Phase 3 (Contract)**: Update application code to read and write exclusively from the new column.
36
+ 4. **Phase 4 (Cleanup)**: Once traffic is fully shifted, remove the old column and mark the new column as `NOT NULL` in a separate migration.
37
+
38
+ ---
39
+
40
+ ### Serverless & Edge Connection Pooling
41
+
42
+ In serverless environments (AWS Lambda, Vercel Functions):
43
+
44
+ - Always connect via a connection pooler:
45
+ - **Prisma**: Use Prisma Accelerate or configure transaction mode connection URLs.
46
+ - **Drizzle / Node-Postgres**: Use `@neondatabase/serverless` or connect to PgBouncer pooler port (`6543`) with `max: 1` per serverless container.
47
+ - Set strict statement timeouts (e.g. `statement_timeout = '5000'`) to prevent hanging queries from exhausting pool capacity.
48
+
49
+ ---
50
+
51
+ ### Indexing & Performance Rules
52
+
53
+ - **B-Tree Indexes**: For high-cardinality filters (`status`, `user_id`, `created_at`).
54
+ - **Composite Indexes**: When querying multiple columns together (`WHERE organization_id = ? AND status = ?`), order columns in index by equality first, range second.
55
+ - **Partial Indexes**: For sparse boolean flags (`WHERE is_processed = false`).
56
+ - **Covering Indexes**: Include frequently selected columns (`INCLUDE (title, created_at)`) to enable index-only scans without table heap access.
57
+
58
+ ---
59
+
60
+ ## Code Examples
61
+
62
+ ### Zero-Downtime Column Rename (Drizzle ORM)
63
+
64
+ ```typescript
65
+ // Step 1 (Expand): Keep old column, add new column
66
+ export const users = pgTable('users', {
67
+ id: uuid('id').primaryKey().defaultRandom(),
68
+ fullName: varchar('full_name', { length: 255 }), // new column
69
+ name: varchar('name', { length: 255 }), // old column kept during transition
70
+ });
71
+
72
+ // App write logic during transition:
73
+ await db.insert(users).values({
74
+ name: input.name,
75
+ fullName: input.name
76
+ });
77
+ ```
78
+
79
+ ---
80
+
81
+ ## Validation Checklist
82
+
83
+ - [ ] All database queries select explicit required columns (no `SELECT *`).
84
+ - [ ] Foreign keys have matching indexes on child tables.
85
+ - [ ] Multi-table writes wrapped in ACID transactions.
86
+ - [ ] No N+1 queries in loops.
87
+ - [ ] Schema migrations tested against expand-and-contract pattern.
88
+ - [ ] Serverless database connection string uses pooling proxy.
89
+
90
+ ---
91
+
92
+ ## Common Mistakes
93
+
94
+ - **Missing pagination limits**: Unbounded `findMany()` calls leading to Out-Of-Memory crashes under production volume.
95
+ - **Locking entire tables**: Adding `NOT NULL` columns with heavy compute defaults in PostgreSQL without concurrent index creation.
96
+
97
+ ---
98
+
99
+ ## Integration Notes
100
+
101
+ - Interacts with `system-design`, `ddd`, and `security` (multi-tenant tenantId scoping).
@@ -0,0 +1,18 @@
1
+ # Database Troubleshooting Guide
2
+
3
+ ## Common Issues & Fixes
4
+
5
+ ### 1. Connection Pool Exhaustion in Serverless / Edge
6
+
7
+ - **Cause**: Creating a new PrismaClient / DB connection instance on every serverless function invocation.
8
+ - **Fix**: Declare PrismaClient as a global singleton across warm lambdas, and enable PgBouncer or Prisma Accelerate.
9
+
10
+ ### 2. Slow Queries on Large Tables
11
+
12
+ - **Cause**: Missing composite index on filtered and ordered columns.
13
+ - **Fix**: Run `EXPLAIN ANALYZE <query>` and add targeted indexes matching the WHERE and ORDER BY columns.
14
+
15
+ ### 3. Database Deadlocks during Concurrent Transactions
16
+
17
+ - **Cause**: Different transactions updating resources in different orders.
18
+ - **Fix**: Always acquire locks and update entities in a deterministic alphabetical or ID-ordered sequence.
@@ -0,0 +1,11 @@
1
+ {
2
+ "skill": "database",
3
+ "version": "1.0.0",
4
+ "checks": [
5
+ "No SELECT * in application queries",
6
+ "All foreign keys indexed",
7
+ "Multi-table writes enclosed in database transactions",
8
+ "No N+1 queries in loops",
9
+ "Safe expand-and-contract migration strategy"
10
+ ]
11
+ }
@@ -0,0 +1,14 @@
1
+ schemaVersion: 2
2
+ name: database
3
+ description: Database architecture, schema design, Prisma, Drizzle ORM, indexing strategies, migrations, and N+1 query resolution.
4
+ version: 1.0.0
5
+ category: backend
6
+ type: instruction-only
7
+ requires:
8
+ - system-design
9
+ - typescript
10
+ resources:
11
+ - EXAMPLES.md
12
+ - SKILL.md
13
+ - TROUBLESHOOTING.md
14
+ - VALIDATION.json
@@ -0,0 +1,42 @@
1
+ # ddd Examples - Anti-patterns vs ContextOS Standard
2
+
3
+ ## Example 1: Domain Entities vs Anemic Models
4
+
5
+ ### Anti-pattern: Anemic Domain Model with Leaky Setters
6
+
7
+ ```typescript
8
+ // BAD: Zero business invariants; any caller can corrupt state
9
+ class BankAccount {
10
+ public balance: number = 0;
11
+ public isFrozen: boolean = false;
12
+ }
13
+
14
+ // Logic leaked into controller or service
15
+ account.balance -= 500; // Overdraft not checked!
16
+ ```
17
+
18
+ ### Best practice: ContextOS Standard (Rich Domain Model with Guarded Invariants)
19
+
20
+ ```typescript
21
+ // GOOD: Invariants strictly enforced inside Aggregate Root
22
+ class BankAccount {
23
+ private _balance: number;
24
+ private _isFrozen: boolean;
25
+
26
+ constructor(id: string, initialDeposit: Money) {
27
+ this._balance = initialDeposit.amount;
28
+ this._isFrozen = false;
29
+ }
30
+
31
+ public withdraw(amount: Money): void {
32
+ if (this._isFrozen) {
33
+ throw new AccountFrozenException('Cannot withdraw from a frozen account');
34
+ }
35
+ if (this._balance < amount.amount) {
36
+ throw new InsufficientFundsException('Insufficient funds for withdrawal');
37
+ }
38
+ this._balance -= amount.amount;
39
+ this.addDomainEvent(new MoneyWithdrawnEvent(this.id, amount));
40
+ }
41
+ }
42
+ ```
@@ -0,0 +1,247 @@
1
+ ---
2
+ name: Domain-Driven Design
3
+ description: >
4
+ ContextOS skill for Domain-Driven Design
5
+ ---
6
+
7
+ # Domain-Driven Design
8
+
9
+ ## Overview
10
+
11
+ Domain-Driven Design standard for robust business software. Enforces separation between domain logic (Entities, Value Objects, Aggregates, Domain Events) and infrastructure frameworks, preventing leaky abstractions.
12
+
13
+ ## When to Use
14
+
15
+ Activate when designing core business domain models, transactional consistency boundaries, enterprise APIs, or complex aggregate hierarchies.
16
+
17
+ ## Rules & Patterns
18
+ <!-- Source: ddd.md -->
19
+
20
+ ## Domain-Driven Design - Patterns & Practices
21
+
22
+ ## When to Use DDD
23
+
24
+ **Use when:**
25
+
26
+ - Complex business logic that goes beyond CRUD
27
+ - Multiple domain experts with different vocabularies
28
+ - The domain model is the competitive advantage
29
+ - Enterprise-grade applications
30
+
31
+ **Don't use when:**
32
+
33
+ - Simple CRUD applications
34
+ - Hackathon/MVP (overkill)
35
+ - No domain expert available
36
+
37
+ ## Strategic Design
38
+
39
+ ### Bounded Contexts
40
+
41
+ The single most important DDD concept. A Bounded Context is a boundary within which a particular model is defined and applicable.
42
+
43
+ **Example - E-Commerce:**
44
+
45
+ ```
46
+ [Order Context] [Payment Context] [Shipping Context]
47
+ - Order - Payment - Shipment
48
+ - OrderItem - Transaction - TrackingNumber
49
+ - Customer (ref) - Refund - Address
50
+ - Address (value) - Invoice - Carrier
51
+ ```
52
+
53
+ `Customer` means different things in each context:
54
+
55
+ - Order Context: name, email, shipping preference
56
+ - Payment Context: billing info, payment methods
57
+ - Support Context: ticket history, satisfaction score
58
+
59
+ ### Context Map
60
+
61
+ ```
62
+ [Order] ←→ [Payment] # Partnership
63
+ [Order] → [Shipping] # Customer-Supplier
64
+ [Order] → [Legacy CRM] # Anti-Corruption Layer
65
+ ```
66
+
67
+ ## Tactical Design
68
+
69
+ ### Entities
70
+
71
+ Objects with identity. Two entities with the same attributes but different IDs are different.
72
+
73
+ ```typescript
74
+ class User {
75
+ readonly id: UserId;
76
+ name: string;
77
+ email: Email; // Value Object
78
+ }
79
+ ```
80
+
81
+ ### Value Objects
82
+
83
+ Objects defined by their attributes, not identity. Immutable.
84
+
85
+ ```typescript
86
+ class Email {
87
+ constructor(readonly value: string) {
88
+ if (!isValidEmail(value)) throw new InvalidEmailError(value);
89
+ }
90
+ equals(other: Email): boolean {
91
+ return this.value === other.value;
92
+ }
93
+ }
94
+ ```
95
+
96
+ ### Aggregates
97
+
98
+ A cluster of entities and value objects with a single root entity (Aggregate Root). All access goes through the root.
99
+
100
+ ```typescript
101
+ class Order { // Aggregate Root
102
+ private items: OrderItem[] = [];
103
+
104
+ addItem(product: ProductRef, quantity: number): void {
105
+ // Business logic HERE, not in a service
106
+ if (quantity <= 0) throw new InvalidQuantityError();
107
+ this.items.push(new OrderItem(product, quantity));
108
+ }
109
+
110
+ get total(): Money {
111
+ return this.items.reduce((sum, item) => sum.add(item.subtotal), Money.zero());
112
+ }
113
+ }
114
+ ```
115
+
116
+ **Aggregate Rules:**
117
+
118
+ 1. Reference other aggregates by ID only
119
+ 2. One aggregate per transaction
120
+ 3. Eventual consistency between aggregates
121
+
122
+ ### Domain Events
123
+
124
+ Something that happened in the domain that domain experts care about.
125
+
126
+ ```typescript
127
+ class OrderPlaced implements DomainEvent {
128
+ constructor(
129
+ readonly orderId: OrderId,
130
+ readonly customerId: CustomerId,
131
+ readonly total: Money,
132
+ readonly occurredAt: Date
133
+ ) {}
134
+ }
135
+ ```
136
+
137
+ ### Domain Services
138
+
139
+ Business logic that doesn't naturally belong to an entity or value object.
140
+
141
+ ```typescript
142
+ class PricingService {
143
+ calculatePrice(order: Order, customer: Customer, promotions: Promotion[]): Money {
144
+ // Complex pricing logic involving multiple aggregates
145
+ }
146
+ }
147
+ ```
148
+
149
+ ### Repositories
150
+
151
+ Abstraction over data access. One repository per aggregate root.
152
+
153
+ ```typescript
154
+ interface OrderRepository {
155
+ findById(id: OrderId): Promise<Order | null>;
156
+ save(order: Order): Promise<void>;
157
+ delete(id: OrderId): Promise<void>;
158
+ }
159
+ ```
160
+
161
+ ## Directory Structure (DDD)
162
+
163
+ ```
164
+ src/
165
+ ├── modules/
166
+ │ └── orders/ # Bounded Context
167
+ │ ├── domain/
168
+ │ │ ├── entities/
169
+ │ │ │ └── order.ts # Aggregate Root
170
+ │ │ ├── value-objects/
171
+ │ │ │ └── money.ts
172
+ │ │ ├── events/
173
+ │ │ │ └── order-placed.ts
174
+ │ │ ├── services/
175
+ │ │ │ └── pricing.ts
176
+ │ │ └── repositories/
177
+ │ │ └── order.repository.ts # Interface
178
+ │ ├── application/
179
+ │ │ ├── commands/
180
+ │ │ │ └── place-order.ts
181
+ │ │ ├── queries/
182
+ │ │ │ └── get-order.ts
183
+ │ │ └── handlers/
184
+ │ │ └── place-order.handler.ts
185
+ │ └── infrastructure/
186
+ │ ├── persistence/
187
+ │ │ └── order.repository.impl.ts # Implementation
188
+ │ └── api/
189
+ │ └── orders.controller.ts
190
+ ```
191
+
192
+ ### The Clean Architecture Dependency Rule
193
+
194
+ In DDD, dependencies **MUST strictly point inward**:
195
+
196
+ ```
197
+ [ Frameworks & Drivers (Web, DB, UI) ]
198
+ └──▶ [ Interface Adapters (Controllers, Gateways) ]
199
+ └──▶ [ Application (Use Cases, CQRS Handlers) ]
200
+ └──▶ [ Domain (Entities, Value Objects) ]
201
+ ```
202
+
203
+ - The **Domain layer** has ZERO dependencies on ORMs (Prisma, TypeORM), HTTP frameworks (Express, NestJS), or external SDKs.
204
+ - Repositories are defined as interfaces in the domain/application layer and implemented in the infrastructure layer.
205
+
206
+ ### Domain Events vs Integration Events
207
+
208
+ 1. **Domain Events**: Represent state changes inside a single Bounded Context.
209
+ - Raised directly inside the Aggregate Root (`order.addItem(...)` raises `OrderItemAdded`).
210
+ - Dispatched in-process before transaction commit.
211
+ 2. **Integration Events**: Published across Bounded Context boundaries to communicate with other services.
212
+ - Dispatched via Transactional Outbox pattern to message brokers.
213
+ - Must use backward-compatible schemas with versioning.
214
+
215
+ ### Anti-Corruption Layer (ACL)
216
+
217
+ When consuming data from an external bounded context or 3rd-party vendor API (e.g. Stripe, Salesforce):
218
+
219
+ - NEVER import external domain models directly into your domain.
220
+ - Create an **ACL Translator / Adapter** in the infrastructure layer to convert external DTOs into your own Value Objects and Entities.
221
+
222
+ ---
223
+
224
+ ## Anti-Patterns
225
+
226
+ - [FAIL] Anemic domain model - entities with only getters/setters, all logic in services
227
+ - [FAIL] Big aggregate - aggregates should be small, focused on invariants
228
+ - [FAIL] Cross-aggregate transactions - use eventual consistency
229
+ - [FAIL] DDD everywhere - use DDD only where complexity justifies it
230
+ - [FAIL] ORM entities leaking into Domain - domain entities must not depend on `@Entity()` or ORM decorators
231
+
232
+
233
+ ## Code Examples
234
+
235
+ See `EXAMPLES.md` for detailed code examples.
236
+
237
+ ## Validation Checklist
238
+
239
+ What to verify during the review phase before completing the task.
240
+
241
+ ## Common Mistakes
242
+
243
+ Anti-patterns and things to explicitly avoid. See `TROUBLESHOOTING.md`.
244
+
245
+ ## Integration Notes
246
+
247
+ How this skill interacts with other skills.
@@ -0,0 +1,19 @@
1
+ # ddd Troubleshooting & Common Mistakes
2
+
3
+ ## 1. God Aggregates
4
+
5
+ - **Symptom**: Aggregate Root contains 20 child entities and loading it requires joining dozens of tables.
6
+ - **Root Cause**: Treating ERD tables as aggregate boundaries rather than transactional consistency units.
7
+ - **Fix**: Design small aggregates. Reference other aggregates by ID only, not by object reference.
8
+
9
+ ## 2. Leaking Infrastructure into Domain Layer
10
+
11
+ - **Symptom**: Domain entities import Prisma, TypeORM decorators, or Express Request objects.
12
+ - **Root Cause**: Inverting Clean Architecture boundaries.
13
+ - **Fix**: The Domain layer must be pure TypeScript with zero external framework dependencies.
14
+
15
+ ## 3. Transaction Spanning Multiple Aggregates
16
+
17
+ - **Symptom**: High database lock contention and deadlocks under concurrent transactions.
18
+ - **Root Cause**: Modifying multiple aggregate roots within the same database transaction.
19
+ - **Fix**: Rule of thumb: Exactly one Aggregate Root modified per transaction. Use Domain Events for eventual consistency across other aggregates.
@@ -0,0 +1,12 @@
1
+ {
2
+ "$schema": "http://json-schema.org/draft-07/schema#",
3
+ "type": "object",
4
+ "properties": {
5
+ "rules_followed": {
6
+ "type": "boolean"
7
+ }
8
+ },
9
+ "required": [
10
+ "rules_followed"
11
+ ]
12
+ }
@@ -0,0 +1,14 @@
1
+ schemaVersion: 2
2
+ id: ddd
3
+ name: Domain-Driven Design
4
+ category: architecture
5
+ type: instruction-only
6
+ requires: []
7
+ optional: [microservices, system-design]
8
+ conflicts: []
9
+ weight: 6
10
+ resources:
11
+ - EXAMPLES.md
12
+ - SKILL.md
13
+ - TROUBLESHOOTING.md
14
+ - VALIDATION.json
@@ -0,0 +1,35 @@
1
+ # decisions Examples - Anti-patterns vs ContextOS Standard
2
+
3
+ ## Example 1: Documenting Tech Choices
4
+
5
+ ### Anti-pattern: Tribal Knowledge & Undocumented Decisions
6
+
7
+ ```text
8
+ "We switched to Redis for session storage last month because Dan said so on Slack."
9
+ Three months later, Dan leaves and nobody knows why the config is set up this way.
10
+ ```
11
+
12
+ ### Best practice: ContextOS Standard (MADR Architecture Decision Record)
13
+
14
+ ```markdown
15
+ # ADR 0003: Use Redis for Distributed Session Storage
16
+
17
+ ## Context and Problem Statement
18
+ Our application is transitioning from a single server to horizontally auto-scaled instances.
19
+ Sticky sessions on load balancer cause uneven distribution and drop sessions on node recycling.
20
+
21
+ ## Considered Options
22
+ 1. PostgreSQL session table
23
+ 2. Redis cluster
24
+ 3. JWT stateless tokens in cookies
25
+
26
+ ## Decision Outcome
27
+ Chosen option: "Redis cluster", because:
28
+ - Sub-millisecond read/write latency compared to relational DB queries.
29
+ - Built-in TTL automatically handles session expiration without cron cleanup.
30
+ - Avoids security risks of client-stored JWT revocation.
31
+
32
+ ## Consequences
33
+ - Positive: Stateless web tier, zero session drops on deployment.
34
+ - Negative: Adds operational dependency on Redis cluster infrastructure.
35
+ ```