@workingpayload/agent-skills 1.0.0 → 2.0.0

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 (80) hide show
  1. package/APIForge/skill.md +150 -17
  2. package/AccessPlus/skill.md +122 -18
  3. package/AlgoMaster/skill.md +110 -17
  4. package/Architekt AI/skill.md +125 -17
  5. package/AuthCraft/skill.md +129 -17
  6. package/AutoScriptor/skill.md +122 -17
  7. package/BoilerCore/skill.md +121 -17
  8. package/BugHunter Pro/skill.md +118 -17
  9. package/ChangeScribe/skill.md +98 -17
  10. package/CodeSage/skill.md +148 -17
  11. package/CommitCraft/skill.md +97 -16
  12. package/CoverageMax/skill.md +145 -16
  13. package/CronGenius/skill.md +141 -16
  14. package/DataPolish/skill.md +126 -16
  15. package/DataWeaver/skill.md +135 -16
  16. package/DockMaster/skill.md +142 -16
  17. package/DocuGenie/skill.md +122 -16
  18. package/EdgeGuard/skill.md +144 -16
  19. package/EnvWizard/skill.md +140 -16
  20. package/ErrorMedic/skill.md +136 -16
  21. package/FeatureSmith/skill.md +123 -16
  22. package/FlexiLayout/skill.md +128 -16
  23. package/FlowTester/skill.md +138 -16
  24. package/FunctionForge/skill.md +120 -16
  25. package/InputShield/skill.md +128 -16
  26. package/IssueForge/skill.md +132 -16
  27. package/KubeCrafter/skill.md +133 -16
  28. package/LogicLens/skill.md +116 -16
  29. package/MockSmith/skill.md +130 -16
  30. package/ModelSensei/skill.md +122 -16
  31. package/PRMentor/skill.md +103 -32
  32. package/PerfDetective/skill.md +90 -32
  33. package/PipelinePro/skill.md +146 -32
  34. package/PolyglotShift/skill.md +94 -32
  35. package/PromptForge/skill.md +118 -32
  36. package/QueryPulse/skill.md +123 -32
  37. package/README.md +416 -329
  38. package/ReadMeCraft/skill.md +127 -32
  39. package/RefactorX/skill.md +84 -32
  40. package/RenderBoost/skill.md +148 -32
  41. package/SEOMancer/skill.md +140 -16
  42. package/ScrapeMaster/skill.md +157 -32
  43. package/SecretSniffer/skill.md +107 -16
  44. package/SecureScan/skill.md +114 -16
  45. package/ServiceSplitter/skill.md +137 -16
  46. package/SpeedSmith/skill.md +139 -16
  47. package/StackWise/skill.md +139 -16
  48. package/TaskOrchestrator/skill.md +119 -16
  49. package/TestCrafter/skill.md +142 -16
  50. package/TraceMind/skill.md +127 -16
  51. package/UISmith/skill.md +115 -16
  52. package/bin/cli.js +377 -0
  53. package/extension-extender/SKILL.md +122 -0
  54. package/fastapi-furious/SKILL.md +148 -0
  55. package/package.json +41 -28
  56. package/python-master/SKILL.md +108 -0
  57. package/react-ranger/SKILL.md +93 -0
  58. package/scripts/build_index.py +282 -0
  59. package/scripts/doctor.py +541 -0
  60. package/scripts/install.py +397 -0
  61. package/scripts/route.py +348 -0
  62. package/scripts/score.py +355 -0
  63. package/scripts/test_skill.py +473 -0
  64. package/scripts/validate.py +254 -0
  65. package/skills-routing.json +1131 -0
  66. package/skills.json +3261 -0
  67. package/Extension-Extender/SKILL.md +0 -41
  68. package/Extension-Extender/references/ui-guidelines.md +0 -26
  69. package/Fastapi-Furious/README.md +0 -16
  70. package/Fastapi-Furious/SKILL.md +0 -37
  71. package/Python-Master/README.md +0 -11
  72. package/Python-Master/SKILL.md +0 -37
  73. package/React-Ranger/README.md +0 -17
  74. package/React-Ranger/SKILL.md +0 -37
  75. package/cli.js +0 -181
  76. package/parse_skills.py +0 -44
  77. /package/{Extension-Extender → extension-extender}/assets/manifest.json +0 -0
  78. /package/{Extension-Extender → extension-extender}/assets/popup.css +0 -0
  79. /package/{Extension-Extender → extension-extender}/assets/popup.html +0 -0
  80. /package/{Extension-Extender → extension-extender}/assets/popup.js +0 -0
@@ -1,32 +1,149 @@
1
1
  ---
2
2
  name: kubecrafter
3
- description: Perfects tasks related to writing Kubernetes manifests, configuring Helm charts, and managing cluster deployments and scaling rules. Use when a user asks to handle devops or requires assistance with k8s configs..
3
+ description: Writes production-ready Kubernetes manifests and Helm chart patterns including Deployments, Services, Ingress, HPA, resource limits, security contexts, liveness/readiness probes, and Pod Security Standards. Use when a user needs help with k8s configs, Helm values, cluster autoscaling, or hardening workloads.
4
4
  ---
5
5
 
6
6
  # KubeCrafter
7
7
 
8
8
  ## Overview
9
9
 
10
- The KubeCrafter skill specializes in writing Kubernetes manifests, configuring Helm charts, and managing cluster deployments and scaling rules. It is designed to be the perfect, flawless assistant for devops, providing robust, industry-standard solutions.
10
+ Produces complete, hardened Kubernetes manifests and Helm chart structures following Pod Security Standards (Restricted profile), with proper resource requests/limits, health probes, security contexts, and HPA configurations. Every manifest is `kubectl apply` ready.
11
11
 
12
12
  ## Workflow
13
13
 
14
- When asked to work on devops or related tasks, follow these steps:
14
+ ### 1. Gather Requirements
15
15
 
16
- ### 1. Analysis & Pre-flight
17
- - Analyze the user's request thoroughly.
18
- - Identify the core requirements for writing Kubernetes manifests, configuring Helm charts, and managing cluster deployments and scaling rules.
19
- - Ensure all context and preconditions are understood.
16
+ Before generating manifests, confirm: container image/tag (never `latest`), replica bounds, CPU/memory baseline, exposed ports, config/secrets, ingress hostname + TLS, namespace, and RBAC constraints.
20
17
 
21
- ### 2. Execution & Implementation
22
- - Apply the core logic of KubeCrafter perfectly.
23
- - Prioritize clean architecture, high efficiency, and robust error handling.
24
- - Strive for a flawless, comprehensive solution that directly addresses the user's needs.
18
+ ### 2. Deployment Manifest
25
19
 
26
- ### 3. Validation & Polish
27
- - Review the generated output against industry best practices for devops.
28
- - Ensure the result perfectly resolves the user's request without omissions.
20
+ ```yaml
21
+ apiVersion: apps/v1
22
+ kind: Deployment
23
+ metadata:
24
+ name: my-app
25
+ namespace: production
26
+ labels:
27
+ app.kubernetes.io/name: my-app
28
+ app.kubernetes.io/version: "1.4.2"
29
+ spec:
30
+ replicas: 3
31
+ selector:
32
+ matchLabels:
33
+ app.kubernetes.io/name: my-app
34
+ strategy:
35
+ type: RollingUpdate
36
+ rollingUpdate: { maxSurge: 1, maxUnavailable: 0 }
37
+ template:
38
+ metadata:
39
+ labels:
40
+ app.kubernetes.io/name: my-app
41
+ spec:
42
+ automountServiceAccountToken: false
43
+ securityContext:
44
+ runAsNonRoot: true
45
+ runAsUser: 1000
46
+ fsGroup: 1000
47
+ seccompProfile:
48
+ type: RuntimeDefault
49
+ containers:
50
+ - name: my-app
51
+ image: my-org/my-app:1.4.2
52
+ imagePullPolicy: IfNotPresent
53
+ ports: [{ name: http, containerPort: 8080 }]
54
+ securityContext:
55
+ allowPrivilegeEscalation: false
56
+ readOnlyRootFilesystem: true
57
+ capabilities: { drop: ["ALL"] }
58
+ resources:
59
+ requests: { cpu: "100m", memory: "128Mi" }
60
+ limits: { cpu: "500m", memory: "256Mi" }
61
+ livenessProbe:
62
+ httpGet: { path: /healthz, port: http }
63
+ initialDelaySeconds: 10
64
+ periodSeconds: 15
65
+ readinessProbe:
66
+ httpGet: { path: /readyz, port: http }
67
+ initialDelaySeconds: 5
68
+ periodSeconds: 10
69
+ volumeMounts:
70
+ - { name: tmp, mountPath: /tmp }
71
+ volumes:
72
+ - { name: tmp, emptyDir: {} }
73
+ topologySpreadConstraints:
74
+ - { maxSkew: 1, topologyKey: kubernetes.io/hostname, whenUnsatisfiable: DoNotSchedule,
75
+ labelSelector: { matchLabels: { app.kubernetes.io/name: my-app } } }
76
+ ```
29
77
 
30
- ## Resources
78
+ ### 3. Service, Ingress, and HPA
31
79
 
32
- - **`references/best-practices.md`**: Core principles for devops.
80
+ Service: `type: ClusterIP`; expose via Ingress with `cert-manager.io/cluster-issuer: letsencrypt-prod` and `nginx.ingress.kubernetes.io/ssl-redirect: "true"`.
81
+
82
+ HPA (autoscaling/v2): target `averageUtilization: 70` for CPU, `80` for memory. Set `scaleDown.stabilizationWindowSeconds: 300` to prevent thrashing.
83
+
84
+ ### 4. StatefulSet for Stateful Workloads
85
+
86
+ Use `StatefulSet` instead of `Deployment` when pods need stable network identity or persistent storage:
87
+
88
+ ```yaml
89
+ apiVersion: apps/v1
90
+ kind: StatefulSet
91
+ metadata: { name: my-db, namespace: production }
92
+ spec:
93
+ serviceName: my-db
94
+ replicas: 3
95
+ selector: { matchLabels: { app.kubernetes.io/name: my-db } }
96
+ template:
97
+ metadata: { labels: { app.kubernetes.io/name: my-db } }
98
+ spec:
99
+ containers:
100
+ - name: my-db
101
+ image: postgres:16
102
+ volumeMounts: [{ name: data, mountPath: /var/lib/postgresql/data }]
103
+ volumeClaimTemplates:
104
+ - metadata: { name: data }
105
+ spec: { accessModes: [ReadWriteOnce], storageClassName: fast-ssd,
106
+ resources: { requests: { storage: 20Gi } } }
107
+ ```
108
+
109
+ Each pod gets its own PVC (`data-my-db-0`, `data-my-db-1`, …). PVCs persist after StatefulSet deletion — clean up manually.
110
+
111
+ ### 5. Helm Chart Structure
112
+
113
+ Standard layout: `Chart.yaml`, `values.yaml`, `values-production.yaml`, `templates/` containing `_helpers.tpl`, `deployment.yaml`, `service.yaml`, `ingress.yaml`, `hpa.yaml`, `serviceaccount.yaml`. Override image tag at deploy time: `helm upgrade --install my-app ./charts/my-app --set image.tag=$SHA`.
114
+
115
+ ### 6. Pod Security Standards
116
+
117
+ ```yaml
118
+ metadata:
119
+ labels:
120
+ pod-security.kubernetes.io/enforce: restricted
121
+ pod-security.kubernetes.io/warn: restricted
122
+ ```
123
+
124
+ Restricted profile requires: `runAsNonRoot: true`, `readOnlyRootFilesystem: true`, `allowPrivilegeEscalation: false`, `capabilities.drop: [ALL]`, `seccompProfile.type: RuntimeDefault`.
125
+
126
+ ## Output Format
127
+
128
+ Deliver: YAML manifests in named files, Helm values file if chart-based, `kubectl apply` or `helm upgrade --install` command, and a checklist of replaceable values (image tags, hostnames, secrets).
129
+
130
+ ## Edge Cases
131
+
132
+ **`readOnlyRootFilesystem: true` writable path discovery:** Enable in staging first. Check logs for `Read-only file system` errors. For deeper discovery: `kubectl exec <pod> -- strace -e trace=file <app-cmd>` to capture all filesystem writes, then add `emptyDir` volumes for each identified path.
133
+
134
+ **Resource limits causing OOMKilled:** Increase `limits.memory` to 2× the p99 observed `container_memory_working_set_bytes`. Set `requests` equal to p50 usage. Never remove limits entirely.
135
+
136
+ **HPA + ArgoCD/Flux `replicas` conflict:** Remove `replicas` from the Deployment manifest (let HPA own it), or configure `ignoreDifferences` in ArgoCD to avoid sync overwriting HPA-managed replica counts:
137
+ ```yaml
138
+ # argocd Application spec
139
+ ignoreDifferences:
140
+ - group: apps
141
+ kind: Deployment
142
+ jsonPointers:
143
+ - /spec/replicas
144
+ - group: apps
145
+ kind: StatefulSet
146
+ jsonPointers:
147
+ - /spec/replicas
148
+ ```
149
+ Add additional `jsonPointers` for any other fields ArgoCD overwrites (e.g., `/spec/template/metadata/annotations` for injected sidecars).
@@ -1,32 +1,132 @@
1
1
  ---
2
2
  name: logiclens
3
- description: Perfects tasks related to deconstructing complex business logic, simplifying nested conditionals, and refactoring convoluted code paths. Use when a user asks to handle code, summary or requires assistance with summarizes code functionality..
3
+ description: Analyzes complex code for cyclomatic complexity, deeply nested conditionals, and convoluted logic, then refactors using guard clauses, extract method, and the strategy pattern. Use when a user wants to simplify business logic, reduce cognitive complexity, or get a flowchart and before/after complexity metrics for a function.
4
4
  ---
5
5
 
6
6
  # LogicLens
7
7
 
8
8
  ## Overview
9
9
 
10
- The LogicLens skill specializes in deconstructing complex business logic, simplifying nested conditionals, and refactoring convoluted code paths. It is designed to be the perfect, flawless assistant for code, summary, providing robust, industry-standard solutions.
10
+ Measures cyclomatic and cognitive complexity of a function or module, produces a Mermaid flowchart of the logic, then refactors using guard clauses, extract method, and strategy/policy patterns. Outputs before/after complexity metrics for every change.
11
11
 
12
12
  ## Workflow
13
13
 
14
- When asked to work on code, summary or related tasks, follow these steps:
14
+ ### 1. Measure Baseline Complexity
15
15
 
16
- ### 1. Analysis & Pre-flight
17
- - Analyze the user's request thoroughly.
18
- - Identify the core requirements for deconstructing complex business logic, simplifying nested conditionals, and refactoring convoluted code paths.
19
- - Ensure all context and preconditions are understood.
16
+ Before touching any code, compute:
20
17
 
21
- ### 2. Execution & Implementation
22
- - Apply the core logic of LogicLens perfectly.
23
- - Prioritize clean architecture, high efficiency, and robust error handling.
24
- - Strive for a flawless, comprehensive solution that directly addresses the user's needs.
18
+ **Cyclomatic Complexity (CC):** Count decision points + 1.
19
+ - Each `if`, `else if`, `switch case`, `for`, `while`, `do`, `catch`, `&&`, `||`, `??`, ternary `?` = +1
20
+ - Starting score = 1
25
21
 
26
- ### 3. Validation & Polish
27
- - Review the generated output against industry best practices for code, summary.
28
- - Ensure the result perfectly resolves the user's request without omissions.
22
+ | CC Score | Rating |
23
+ |---|---|
24
+ | 1–5 | Simple, low risk |
25
+ | 6–10 | Moderate, review recommended |
26
+ | 11–15 | High, refactor recommended |
27
+ | 16+ | Untestable, must refactor |
29
28
 
30
- ## Resources
29
+ **Cognitive Complexity (per SonarSource model):** Penalizes nesting depth. A nested `if` inside a loop scores higher than a flat `if`. Use this as the primary human-readability metric.
31
30
 
32
- - **`references/best-practices.md`**: Core principles for code, summary.
31
+ Report both scores: `CC: 14, Cognitive: 22 — refactor required`.
32
+
33
+ ### 2. Generate a Flowchart
34
+
35
+ Produce a Mermaid flowchart to visualize the logic before refactoring:
36
+
37
+ ```mermaid
38
+ flowchart TD
39
+ A[Start: processOrder] --> B{order.status == 'pending'?}
40
+ B -- No --> C[Return: skip]
41
+ B -- Yes --> D{user.isVerified?}
42
+ D -- No --> E[Throw: UnverifiedUser]
43
+ D -- Yes --> F{inventory.hasStock?}
44
+ F -- No --> G[Emit: OutOfStock event]
45
+ F -- Yes --> H[Reserve inventory]
46
+ H --> I{payment.process}
47
+ I -- Failure --> J[Release inventory\nThrow: PaymentFailed]
48
+ I -- Success --> K[Update order status\nReturn: OrderConfirmed]
49
+ ```
50
+
51
+ This makes deeply nested conditionals visible and identifies paths for test coverage.
52
+
53
+ ### 3. Apply Guard Clauses (Early Returns)
54
+
55
+ Replace nested happy-path conditionals with early returns for all failure/guard cases:
56
+
57
+ **Before (CC: 9, 4-deep nesting):** Nested `if (pending) { if (verified) { if (hasStock) { ... } } }` — silent fall-through risk.
58
+
59
+ **After (CC: 5, flat):**
60
+ ```typescript
61
+ function processOrder(order: Order, user: User, inventory: Inventory): OrderConfirmation {
62
+ if (order.status !== 'pending') return;
63
+ if (!user.isVerified) throw new UnverifiedUserError();
64
+ if (!inventory.hasStock(order.productId)) throw new OutOfStockError();
65
+ if (!inventory.reserve(order.productId, order.qty)) throw new ReservationFailedError();
66
+ return confirmOrder(order);
67
+ }
68
+ ```
69
+
70
+ ### 4. Extract Methods
71
+
72
+ When a function does more than one thing, extract named functions that explain *what*, not *how*. If you need a comment to explain what a block does, it should be a named function:
73
+ ```typescript
74
+ // After: orchestrator + focused helpers
75
+ function generateReport(data: ReportData): Report {
76
+ return formatReport(aggregateMetrics(filterReportData(data)));
77
+ }
78
+ ```
79
+
80
+ ### 5. Apply Strategy Pattern for Branching on Type
81
+
82
+ Replace `if/else`/`switch` chains on type/variant with a strategy map — CC stays flat as new types are added:
83
+ ```typescript
84
+ const paymentProcessors: Record<PaymentMethod, PaymentProcessor> = {
85
+ card: processCard, paypal: processPayPal, crypto: processCrypto,
86
+ };
87
+ function processPayment(method: PaymentMethod, amount: number): PaymentResult {
88
+ const processor = paymentProcessors[method];
89
+ if (!processor) throw new UnsupportedPaymentMethodError(method);
90
+ return processor(amount);
91
+ }
92
+ ```
93
+
94
+ ### 6. Class/Module-Level Analysis
95
+
96
+ When analyzing a file or module (not just a single function):
97
+ 1. List all methods sorted by cyclomatic complexity descending — **tackle the worst method first**.
98
+ 2. Identify **God class** symptoms: >10 methods, >300 lines, >3 unrelated responsibilities, or direct access to >5 other domain objects.
99
+ 3. Decompose God classes by extracting cohesive groups of methods + their fields into new, focused classes. Name each class after its single responsibility: `OrderValidator`, `OrderPricer`, `OrderNotifier`.
100
+
101
+ ### 7. Report Before/After Metrics
102
+
103
+ Always output a metrics table after refactoring:
104
+
105
+ ```
106
+ ## Complexity Report
107
+
108
+ | Metric | Before | After | Change |
109
+ |---|---|---|---|
110
+ | Cyclomatic Complexity | 14 | 5 | -64% |
111
+ | Cognitive Complexity | 22 | 8 | -64% |
112
+ | Max nesting depth | 5 | 2 | -60% |
113
+ | Lines of code (fn) | 48 | 12 | -75% |
114
+ | Testable paths | 6 | 6 | 0% (preserved) |
115
+ ```
116
+
117
+ ## Output Format
118
+
119
+ Deliver in order:
120
+ 1. Baseline complexity scores (CC + Cognitive) with explanation.
121
+ 2. Mermaid flowchart of original logic.
122
+ 3. Refactored code with inline comments on each technique applied.
123
+ 4. Before/after metrics table.
124
+ 5. New unit test cases enabled by the refactor (one per logical path).
125
+
126
+ ## Edge Cases
127
+
128
+ **Inherently complex logic:** Some complexity is genuine (state machines, protocol parsers). Do not force guard clauses — document with a flowchart, ensure full test coverage, and add a complexity warning comment.
129
+
130
+ **Side effects inside conditionals:** Flag all side effects (DB writes, event emissions) before refactoring. Verify extracted methods preserve the original call sequence.
131
+
132
+ **Polymorphism vs. strategy map:** Use a strategy map for stateless, pure variants. Use class-based polymorphism with a factory when variants need different constructor dependencies or stateful config.
@@ -1,32 +1,146 @@
1
1
  ---
2
2
  name: mocksmith
3
- description: Perfects tasks related to generating realistic mock data, stubbing API responses, and creating fake environments for robust frontend testing. Use when a user asks to handle testing or requires assistance with creates mock data..
3
+ description: Generates realistic, schema-driven mock data using Faker.js or factory_boy, stubs API responses with MSW, and produces edge-case datasets from OpenAPI specs or TypeScript interfaces. Use when a user needs test fixtures, factory functions, referentially consistent seed data, or browser/Node API mocking.
4
4
  ---
5
5
 
6
6
  # MockSmith
7
7
 
8
8
  ## Overview
9
9
 
10
- The MockSmith skill specializes in generating realistic mock data, stubbing API responses, and creating fake environments for robust frontend testing. It is designed to be the perfect, flawless assistant for testing, providing robust, industry-standard solutions.
10
+ Produces deterministic, realistic mock data from OpenAPI specs or TypeScript/Python type definitions using Faker.js (JS/TS) or factory_boy (Python). Stubs HTTP APIs at the network layer using Mock Service Worker (MSW). Ensures referential integrity across related entities and covers edge-case data.
11
11
 
12
12
  ## Workflow
13
13
 
14
- When asked to work on testing or related tasks, follow these steps:
14
+ ### 1. Derive the Schema First
15
15
 
16
- ### 1. Analysis & Pre-flight
17
- - Analyze the user's request thoroughly.
18
- - Identify the core requirements for generating realistic mock data, stubbing API responses, and creating fake environments for robust frontend testing.
19
- - Ensure all context and preconditions are understood.
16
+ Before generating any data, extract or confirm the schema from an OpenAPI spec (`components/schemas`), TypeScript interface, or user description. Never invent field names or types.
20
17
 
21
- ### 2. Execution & Implementation
22
- - Apply the core logic of MockSmith perfectly.
23
- - Prioritize clean architecture, high efficiency, and robust error handling.
24
- - Strive for a flawless, comprehensive solution that directly addresses the user's needs.
18
+ ### 2. Build Factory Functions (TypeScript / Faker.js)
25
19
 
26
- ### 3. Validation & Polish
27
- - Review the generated output against industry best practices for testing.
28
- - Ensure the result perfectly resolves the user's request without omissions.
20
+ ```typescript
21
+ // factories/user.factory.ts
22
+ import { faker } from '@faker-js/faker';
29
23
 
30
- ## Resources
24
+ export function createUser(overrides: Partial<User> = {}): User {
25
+ return {
26
+ id: faker.string.uuid(),
27
+ email: faker.internet.email().toLowerCase(),
28
+ displayName: faker.person.fullName(),
29
+ role: faker.helpers.arrayElement(['admin', 'editor', 'viewer']),
30
+ createdAt: faker.date.past({ years: 2 }).toISOString(),
31
+ isActive: true,
32
+ ...overrides,
33
+ };
34
+ }
31
35
 
32
- - **`references/best-practices.md`**: Core principles for testing.
36
+ export const createUsers = (n: number, overrides: Partial<User> = {}) =>
37
+ Array.from({ length: n }, () => createUser(overrides));
38
+ ```
39
+
40
+ **Deterministic CI output:** `faker.seed(12345)` — same seed → same data every run.
41
+
42
+ **Per-worker seeding for parallel tests:** Seed with the worker ID so each worker produces unique but reproducible data:
43
+ ```typescript
44
+ faker.seed((Number(process.env.TEST_WORKER_INDEX) ?? 0) * 1000);
45
+ ```
46
+
47
+ ### 3. Build Factory Functions (Python / factory_boy)
48
+
49
+ ```python
50
+ class UserFactory(factory.django.DjangoModelFactory):
51
+ class Meta:
52
+ model = User
53
+ id = factory.LazyFunction(uuid.uuid4)
54
+ email = Faker('email')
55
+ display_name = Faker('name')
56
+ role = factory.Iterator(['admin', 'editor', 'viewer'])
57
+ is_active = True
58
+ # Usage: UserFactory(role='admin') | UserFactory.create_batch(10, is_active=False)
59
+ ```
60
+
61
+ ### 4. Maintain Referential Integrity
62
+
63
+ Use sub-factories — never generate orphaned foreign keys:
64
+ ```typescript
65
+ export function createOrder(overrides: Partial<Order> = {}): Order {
66
+ const user = overrides.user ?? createUser();
67
+ return { id: faker.string.uuid(), userId: user.id, user, status: 'pending', ...overrides };
68
+ }
69
+ ```
70
+
71
+ ### 5. Generate Edge-Case Data
72
+
73
+ ```typescript
74
+ export const edgeCaseUsers = {
75
+ emptyDisplayName: createUser({ displayName: '' }),
76
+ unicodeName: createUser({ displayName: '田中 太郎' }),
77
+ sqlInjection: createUser({ displayName: "'; DROP TABLE users; --" }),
78
+ xssPayload: createUser({ displayName: '<script>alert(1)</script>' }),
79
+ inactiveAdmin: createUser({ role: 'admin', isActive: false }),
80
+ };
81
+ ```
82
+
83
+ ### 6. Stub APIs with MSW
84
+
85
+ ```typescript
86
+ // mocks/handlers.ts
87
+ export const handlers = [
88
+ http.get('/api/users', ({ request }) => {
89
+ const count = Number(new URL(request.url).searchParams.get('limit') ?? 10);
90
+ return HttpResponse.json({ data: createUsers(count), total: 100 });
91
+ }),
92
+ http.get('/api/users/:id', ({ params }) =>
93
+ HttpResponse.json(createUser({ id: params.id as string }))
94
+ ),
95
+ http.post('/api/users', async ({ request }) =>
96
+ HttpResponse.json(createUser(await request.json() as Partial<User>), { status: 201 })
97
+ ),
98
+ ];
99
+ ```
100
+
101
+ **Timeout and network error simulation:**
102
+ ```typescript
103
+ import { delay } from 'msw';
104
+ http.get('/api/slow', async () => { await delay(3000); return HttpResponse.json({}); }),
105
+ http.get('/api/offline', () => HttpResponse.error()), // simulates network failure
106
+ ```
107
+
108
+ ```typescript
109
+ // mocks/server.ts
110
+ export const server = setupServer(...handlers);
111
+ beforeAll(() => server.listen({ onUnhandledRequest: 'error' }));
112
+ afterEach(() => server.resetHandlers());
113
+ afterAll(() => server.close());
114
+ ```
115
+
116
+ ### 7. Polymorphic Schema Factories (`oneOf` / `anyOf`)
117
+
118
+ When an OpenAPI schema uses `oneOf`/`anyOf`, generate a factory per variant and a union factory:
119
+ ```typescript
120
+ type Shape = Circle | Rectangle;
121
+ function createCircle(o: Partial<Circle> = {}): Circle {
122
+ return { type: 'circle', radius: faker.number.float({ min: 1, max: 100 }), ...o };
123
+ }
124
+ function createRectangle(o: Partial<Rectangle> = {}): Rectangle {
125
+ return { type: 'rectangle', width: faker.number.int({ min: 1, max: 200 }),
126
+ height: faker.number.int({ min: 1, max: 200 }), ...o };
127
+ }
128
+ const createShape = (): Shape =>
129
+ faker.helpers.arrayElement([createCircle, createRectangle])();
130
+ ```
131
+
132
+ ### 8. Generate from OpenAPI Spec
133
+
134
+ Parse `components/schemas`. Map types: `string/email` → `faker.internet.email()`, `string/uuid` → `faker.string.uuid()`, `string/date-time` → `faker.date.recent().toISOString()`. Respect `minimum`, `maximum`, `minLength`, `maxLength`, `enum`, `pattern`. Generate one factory per schema object.
135
+
136
+ ## Output Format
137
+
138
+ Deliver: factory files in `tests/factories/`, MSW `mocks/handlers.ts` and `mocks/server.ts`, edge-case fixtures export, and Vitest/Jest setup snippet.
139
+
140
+ ## Edge Cases
141
+
142
+ **Circular references:** Break cycles with a depth guard: `manager: depth < 2 ? createUser({}, depth + 1) : null`.
143
+
144
+ **Date consistency:** Generate `createdAt` first, then `updatedAt = faker.date.between({ from: createdAt, to: new Date() })`.
145
+
146
+ **MSW in SSR / Next.js:** Use `msw/node` `setupServer` for API route tests and `msw/browser` `setupWorker` for client-side tests. Share handler definitions in a single `handlers.ts`.
@@ -1,32 +1,138 @@
1
1
  ---
2
2
  name: modelsensei
3
- description: Perfects tasks related to designing domain-driven data models, ORM mappings, and enforcing strong typing across application layers. Use when a user asks to handle ml or requires assistance with model selection..
3
+ description: Designs domain-driven data models using DDD aggregates and value objects, produces ORM mappings for SQLAlchemy/Prisma/ActiveRecord, prevents N+1 queries, and generates database migration files. Use when a user needs help with data modeling, ORM schema design, query optimization, or database migrations.
4
4
  ---
5
5
 
6
6
  # ModelSensei
7
7
 
8
8
  ## Overview
9
9
 
10
- The ModelSensei skill specializes in designing domain-driven data models, ORM mappings, and enforcing strong typing across application layers. It is designed to be the perfect, flawless assistant for ml, providing robust, industry-standard solutions.
10
+ Designs data models using Domain-Driven Design (DDD) tactical patterns — aggregates, entities, value objects, repositories — then maps them to ORM schemas (SQLAlchemy, Prisma, ActiveRecord). Identifies N+1 problems and generates migration files.
11
11
 
12
12
  ## Workflow
13
13
 
14
- When asked to work on ml or related tasks, follow these steps:
14
+ ### 1. Model the Domain First (DDD Tactical Patterns)
15
15
 
16
- ### 1. Analysis & Pre-flight
17
- - Analyze the user's request thoroughly.
18
- - Identify the core requirements for designing domain-driven data models, ORM mappings, and enforcing strong typing across application layers.
19
- - Ensure all context and preconditions are understood.
16
+ - **Aggregate Root:** Entry point for a cluster of related objects. All external references go through the root.
17
+ - **Entity:** Has unique identity that persists over time (`Order`, `User`).
18
+ - **Value Object:** Defined by attributes, no identity, immutable (`Money`, `Address`).
20
19
 
21
- ### 2. Execution & Implementation
22
- - Apply the core logic of ModelSensei perfectly.
23
- - Prioritize clean architecture, high efficiency, and robust error handling.
24
- - Strive for a flawless, comprehensive solution that directly addresses the user's needs.
20
+ ```typescript
21
+ class Money { // Value Object
22
+ constructor(readonly amount: number, readonly currency: 'USD' | 'EUR') {
23
+ if (amount < 0) throw new DomainError('Amount cannot be negative');
24
+ }
25
+ add(other: Money): Money {
26
+ if (other.currency !== this.currency) throw new DomainError('Currency mismatch');
27
+ return new Money(this.amount + other.amount, this.currency);
28
+ }
29
+ }
30
+ class Order { // Aggregate Root
31
+ private _items: OrderItem[] = [];
32
+ addItem(item: OrderItem): void {
33
+ if (this._status !== 'draft') throw new DomainError('Cannot modify non-draft order');
34
+ this._items.push(item);
35
+ }
36
+ }
37
+ ```
25
38
 
26
- ### 3. Validation & Polish
27
- - Review the generated output against industry best practices for ml.
28
- - Ensure the result perfectly resolves the user's request without omissions.
39
+ Aggregate rules: only the root has a repository; external aggregates reference each other by ID only; keep aggregates small.
29
40
 
30
- ## Resources
41
+ ### 2. Map to ORM Schema
31
42
 
32
- - **`references/best-practices.md`**: Core principles for ml.
43
+ **Prisma:**
44
+ ```prisma
45
+ model Order {
46
+ id String @id @default(uuid())
47
+ customerId String
48
+ customer Customer @relation(fields: [customerId], references: [id])
49
+ status OrderStatus @default(DRAFT)
50
+ totalAmount Decimal @db.Decimal(12, 2)
51
+ items OrderItem[]
52
+ createdAt DateTime @default(now())
53
+ updatedAt DateTime @updatedAt
54
+ @@index([customerId, status])
55
+ }
56
+ ```
57
+
58
+ **SQLAlchemy:** Use `selectinload` for collections, `joinedload` for single relations. **ActiveRecord:** Use `includes(:items, :customer)`.
59
+
60
+ ### 3. Prevent N+1 Queries
61
+
62
+ Detect N+1 by finding queries inside loops. Fix with eager loading:
63
+ ```typescript
64
+ // Prisma fix — 2 queries instead of 1+N
65
+ const orders = await prisma.order.findMany({
66
+ include: { items: true, customer: { select: { id: true, name: true } } },
67
+ where: { status: 'pending' }, take: 50,
68
+ });
69
+ ```
70
+ Rule: `joinedload`/`joins` for to-one; `selectinload`/`includes` for to-many.
71
+
72
+ ### 4. Generate Migrations
73
+
74
+ ```bash
75
+ npx prisma migrate dev --name add_order_currency_index
76
+ alembic revision --autogenerate -m "add_order_currency_index"
77
+ rails generate migration AddCurrencyIndexToOrders
78
+ ```
79
+
80
+ Migration rules: always provide a `downgrade`/`down` method; never drop a column in the same migration that removes it from code; large table index additions must use `CONCURRENTLY` (Postgres).
81
+
82
+ **Zero-downtime NOT NULL column addition on large tables:** Never add `NOT NULL` with a `DEFAULT` in a single migration on a large table — it locks the table for the full backfill. Instead:
83
+ 1. Add the column as nullable: `ALTER TABLE orders ADD COLUMN notes TEXT`.
84
+ 2. Backfill in batches: `UPDATE orders SET notes = '' WHERE id BETWEEN $1 AND $2`.
85
+ 3. Add the `NOT NULL` constraint using `NOT VALID` to skip historical rows: `ALTER TABLE orders ADD CONSTRAINT orders_notes_not_null CHECK (notes IS NOT NULL) NOT VALID`.
86
+ 4. Validate in a separate transaction: `ALTER TABLE orders VALIDATE CONSTRAINT orders_notes_not_null`.
87
+
88
+ ### 5. Hierarchical Data Modeling
89
+
90
+ Choose the right pattern for tree/hierarchy data:
91
+
92
+ | Pattern | Best for | Recursive CTE? |
93
+ |---|---|---|
94
+ | Adjacency list (`parent_id`) | Simple, shallow trees; easy updates | Yes (`WITH RECURSIVE`) |
95
+ | Closure table | Fast ancestor/descendant queries | No |
96
+ | Nested sets (left/right) | Frequent reads, infrequent writes | No |
97
+
98
+ ```sql
99
+ -- Adjacency list with recursive CTE (Postgres)
100
+ WITH RECURSIVE tree AS (
101
+ SELECT id, name, parent_id, 0 AS depth FROM categories WHERE parent_id IS NULL
102
+ UNION ALL
103
+ SELECT c.id, c.name, c.parent_id, t.depth + 1
104
+ FROM categories c JOIN tree t ON c.parent_id = t.id
105
+ )
106
+ SELECT * FROM tree ORDER BY depth, name;
107
+ ```
108
+
109
+ ### 6. Outbox Pattern for Reliable Domain Events
110
+
111
+ Never publish domain events directly inside a transaction — the event may fire even if the DB commit fails. Use the outbox pattern:
112
+
113
+ 1. Within the same DB transaction that modifies the aggregate, insert a row into an `outbox_events` table.
114
+ 2. A background poller (or Debezium CDC) reads unpublished outbox rows and publishes them to the message broker.
115
+ 3. Mark rows as `published_at = NOW()` after successful broker acknowledgement.
116
+
117
+ ```sql
118
+ CREATE TABLE outbox_events (
119
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
120
+ aggregate TEXT NOT NULL,
121
+ event_type TEXT NOT NULL,
122
+ payload JSONB NOT NULL,
123
+ created_at TIMESTAMPTZ DEFAULT NOW(),
124
+ published_at TIMESTAMPTZ
125
+ );
126
+ ```
127
+
128
+ ## Output Format
129
+
130
+ Deliver: domain model (plain classes, no ORM dependency), ORM schema, migration file(s) with up/down, index strategy justification, and N+1 risks with fixes.
131
+
132
+ ## Edge Cases
133
+
134
+ **Value objects in relational DBs:** Map as embedded columns on the owning entity (`money_amount`, `money_currency`), not separate tables. Only extract to a table if the value object is queried independently.
135
+
136
+ **Soft delete:** Add a partial unique index to exclude soft-deleted rows: `CREATE UNIQUE INDEX ON users (email) WHERE deleted_at IS NULL`.
137
+
138
+ **Oversized aggregates:** If an `Order` could have thousands of `OrderItem` rows, split into a separate aggregate and enforce cross-aggregate invariants asynchronously via domain events.