@workingpayload/agent-skills 1.0.1 → 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 (129) hide show
  1. package/APIForge/skill.md +165 -0
  2. package/AccessPlus/skill.md +136 -0
  3. package/AlgoMaster/skill.md +125 -0
  4. package/Architekt AI/skill.md +140 -0
  5. package/AuthCraft/skill.md +144 -0
  6. package/AutoScriptor/skill.md +137 -0
  7. package/BoilerCore/skill.md +136 -0
  8. package/BugHunter Pro/skill.md +133 -0
  9. package/ChangeScribe/skill.md +113 -0
  10. package/CodeSage/skill.md +163 -0
  11. package/CommitCraft/skill.md +113 -0
  12. package/CoverageMax/skill.md +161 -0
  13. package/CronGenius/skill.md +157 -0
  14. package/DataPolish/skill.md +142 -0
  15. package/DataWeaver/skill.md +151 -0
  16. package/DockMaster/skill.md +158 -0
  17. package/DocuGenie/skill.md +138 -0
  18. package/EdgeGuard/skill.md +160 -0
  19. package/EnvWizard/skill.md +156 -0
  20. package/ErrorMedic/skill.md +152 -0
  21. package/FeatureSmith/skill.md +139 -0
  22. package/FlexiLayout/skill.md +144 -0
  23. package/FlowTester/skill.md +154 -0
  24. package/FunctionForge/skill.md +136 -0
  25. package/InputShield/skill.md +144 -0
  26. package/IssueForge/skill.md +148 -0
  27. package/KubeCrafter/skill.md +149 -0
  28. package/LogicLens/skill.md +132 -0
  29. package/MockSmith/skill.md +146 -0
  30. package/ModelSensei/skill.md +138 -0
  31. package/PRMentor/skill.md +103 -0
  32. package/PerfDetective/skill.md +90 -0
  33. package/PipelinePro/skill.md +146 -0
  34. package/PolyglotShift/skill.md +94 -0
  35. package/PromptForge/skill.md +118 -0
  36. package/QueryPulse/skill.md +123 -0
  37. package/README.md +416 -329
  38. package/ReadMeCraft/skill.md +127 -0
  39. package/RefactorX/skill.md +84 -0
  40. package/RenderBoost/skill.md +148 -0
  41. package/SEOMancer/skill.md +156 -0
  42. package/ScrapeMaster/skill.md +157 -0
  43. package/SecretSniffer/skill.md +123 -0
  44. package/SecureScan/skill.md +130 -0
  45. package/ServiceSplitter/skill.md +153 -0
  46. package/SpeedSmith/skill.md +155 -0
  47. package/StackWise/skill.md +155 -0
  48. package/TaskOrchestrator/skill.md +135 -0
  49. package/TestCrafter/skill.md +158 -0
  50. package/TraceMind/skill.md +143 -0
  51. package/UISmith/skill.md +131 -0
  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 -32
  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/cli.js +0 -181
  68. package/skills/APIForge/skill.md +0 -32
  69. package/skills/AccessPlus/skill.md +0 -32
  70. package/skills/AlgoMaster/skill.md +0 -32
  71. package/skills/Architekt AI/skill.md +0 -32
  72. package/skills/AuthCraft/skill.md +0 -32
  73. package/skills/AutoScriptor/skill.md +0 -32
  74. package/skills/BoilerCore/skill.md +0 -32
  75. package/skills/BugHunter Pro/skill.md +0 -32
  76. package/skills/ChangeScribe/skill.md +0 -32
  77. package/skills/CodeSage/skill.md +0 -32
  78. package/skills/CommitCraft/skill.md +0 -32
  79. package/skills/CoverageMax/skill.md +0 -32
  80. package/skills/CronGenius/skill.md +0 -32
  81. package/skills/DataPolish/skill.md +0 -32
  82. package/skills/DataWeaver/skill.md +0 -32
  83. package/skills/DockMaster/skill.md +0 -32
  84. package/skills/DocuGenie/skill.md +0 -32
  85. package/skills/EdgeGuard/skill.md +0 -32
  86. package/skills/EnvWizard/skill.md +0 -32
  87. package/skills/ErrorMedic/skill.md +0 -32
  88. package/skills/Extension-Extender/SKILL.md +0 -41
  89. package/skills/Extension-Extender/references/ui-guidelines.md +0 -26
  90. package/skills/Fastapi-Furious/README.md +0 -16
  91. package/skills/Fastapi-Furious/SKILL.md +0 -37
  92. package/skills/FeatureSmith/skill.md +0 -32
  93. package/skills/FlexiLayout/skill.md +0 -32
  94. package/skills/FlowTester/skill.md +0 -32
  95. package/skills/FunctionForge/skill.md +0 -32
  96. package/skills/InputShield/skill.md +0 -32
  97. package/skills/IssueForge/skill.md +0 -32
  98. package/skills/KubeCrafter/skill.md +0 -32
  99. package/skills/LogicLens/skill.md +0 -32
  100. package/skills/MockSmith/skill.md +0 -32
  101. package/skills/ModelSensei/skill.md +0 -32
  102. package/skills/PRMentor/skill.md +0 -32
  103. package/skills/PerfDetective/skill.md +0 -32
  104. package/skills/PipelinePro/skill.md +0 -32
  105. package/skills/PolyglotShift/skill.md +0 -32
  106. package/skills/PromptForge/skill.md +0 -32
  107. package/skills/Python-Master/README.md +0 -11
  108. package/skills/Python-Master/SKILL.md +0 -37
  109. package/skills/QueryPulse/skill.md +0 -32
  110. package/skills/React-Ranger/README.md +0 -17
  111. package/skills/React-Ranger/SKILL.md +0 -37
  112. package/skills/ReadMeCraft/skill.md +0 -32
  113. package/skills/RefactorX/skill.md +0 -32
  114. package/skills/RenderBoost/skill.md +0 -32
  115. package/skills/SEOMancer/skill.md +0 -32
  116. package/skills/ScrapeMaster/skill.md +0 -32
  117. package/skills/SecretSniffer/skill.md +0 -32
  118. package/skills/SecureScan/skill.md +0 -32
  119. package/skills/ServiceSplitter/skill.md +0 -32
  120. package/skills/SpeedSmith/skill.md +0 -32
  121. package/skills/StackWise/skill.md +0 -32
  122. package/skills/TaskOrchestrator/skill.md +0 -32
  123. package/skills/TestCrafter/skill.md +0 -32
  124. package/skills/TraceMind/skill.md +0 -32
  125. package/skills/UISmith/skill.md +0 -32
  126. /package/{skills/Extension-Extender → extension-extender}/assets/manifest.json +0 -0
  127. /package/{skills/Extension-Extender → extension-extender}/assets/popup.css +0 -0
  128. /package/{skills/Extension-Extender → extension-extender}/assets/popup.html +0 -0
  129. /package/{skills/Extension-Extender → extension-extender}/assets/popup.js +0 -0
@@ -0,0 +1,148 @@
1
+ ---
2
+ name: issueforge
3
+ description: Creates detailed, well-structured bug reports and feature requests for GitHub Issues and Jira. Use when a user wants to file a bug, write a feature request, define reproduction steps, assign severity/priority, or generate acceptance criteria for an issue tracker.
4
+ ---
5
+
6
+ # IssueForge
7
+
8
+ ## Overview
9
+
10
+ Produces complete, actionable issue tickets for GitHub and Jira: bug reports with reproduction steps and environment details, feature requests with acceptance criteria, and correct severity/priority classification. Output is copy-paste ready for the target tracker.
11
+
12
+ ## Workflow
13
+
14
+ ### 1. Classify the Issue Type
15
+
16
+ Determine the issue type from the user's description:
17
+ - **Bug:** Something is broken or behaves contrary to specification.
18
+ - **Feature Request:** New capability that does not exist yet.
19
+ - **Task / Chore:** Engineering work without direct user-facing change (migration, refactor, dependency update).
20
+ - **Spike:** Time-boxed investigation to reduce uncertainty.
21
+
22
+ Ask for missing information before drafting — a bug report without reproduction steps is not actionable.
23
+
24
+ ### 2. Bug Report Template
25
+
26
+ ```markdown
27
+ ## Bug Report
28
+
29
+ **Summary:** <One-line description — what is wrong, not what the user expected>
30
+
31
+ **Severity:** Critical | High | Medium | Low
32
+ **Priority:** P1 | P2 | P3 | P4
33
+ **Component:** <Frontend / Backend / API / Infrastructure / etc.>
34
+ **Assignee:** <leave blank if unknown>
35
+
36
+ ---
37
+
38
+ ### Description
39
+ <2–3 sentence explanation of the problem and its impact on users/business.>
40
+
41
+ ### Environment
42
+ | Field | Value |
43
+ |---|---|
44
+ | App version | v2.4.1 |
45
+ | Browser/OS | Chrome 123 / macOS 14.4 |
46
+ | API env | Production / Staging / Local |
47
+ | User role | Admin / Free tier |
48
+ | Feature flags | List active flags/experiments and their variant (e.g., `checkout-v2=enabled`, `experiment-price-display=control`) |
49
+
50
+ ### Steps to Reproduce
51
+ 1. Navigate to `<URL or feature>`
52
+ 2. <Action>
53
+ 3. <Action>
54
+ 4. Observe: <what actually happens>
55
+
56
+ ### Expected Behavior
57
+ <What should happen per spec/design.>
58
+
59
+ ### Actual Behavior
60
+ <What actually happens. Include error message verbatim if applicable.>
61
+
62
+ ### Evidence
63
+ - [ ] Screenshot / screen recording attached
64
+ - [ ] Console error log attached
65
+ - [ ] Network request/response attached (redact auth tokens)
66
+
67
+ ### Possible Cause / Hypothesis
68
+ <Optional — include if known. Do not guess without evidence.>
69
+
70
+ ### Workaround
71
+ <If one exists, document it to unblock affected users.>
72
+ ```
73
+
74
+ ### 3. Feature Request Template
75
+
76
+ ```markdown
77
+ ## Feature Request
78
+ **Summary:** <Imperative verb + outcome>
79
+ **Priority:** P1–P4 | **Component:** <team> | **Epic:** <link>
80
+
81
+ ### Problem Statement
82
+ When <situation>, users want to <motivation>, so they can <outcome>.
83
+
84
+ ### Proposed Solution
85
+ <Experience description — not an implementation spec.>
86
+
87
+ ### Acceptance Criteria
88
+ Scenario: <happy path>
89
+ Given <precondition> / When <action> / Then <outcome>
90
+
91
+ ### Out of Scope
92
+ - <What this issue does NOT cover>
93
+
94
+ ### Success Metric
95
+ <e.g., "Export used by >20% of dashboard visitors">
96
+ ```
97
+
98
+ ### 4. Assign Severity and Priority
99
+
100
+ **Severity** (impact of the defect):
101
+ | Level | Definition |
102
+ |---|---|
103
+ | Critical | Data loss, security breach, complete feature outage with no workaround |
104
+ | High | Major feature broken, workaround exists but is unacceptable |
105
+ | Medium | Feature degraded; workaround available |
106
+ | Low | Cosmetic issue, minor inconvenience |
107
+
108
+ **Priority** (urgency of fix):
109
+ | Level | SLA |
110
+ |---|---|
111
+ | P1 | Fix and deploy within 24 hours |
112
+ | P2 | Fix in current sprint |
113
+ | P3 | Scheduled for next sprint or backlog grooming |
114
+ | P4 | Nice-to-have; fix when capacity allows |
115
+
116
+ Severity and priority are independent: a Low severity bug can be P2 if it affects a key sales demo flow.
117
+
118
+ ### 5. GitHub vs. Jira Formatting Differences
119
+
120
+ **GitHub Issues:** Use Markdown headers, task lists, and code fences. Apply labels (`bug`, `priority: high`, `component: auth`). Reference related issues with `#N`; use `Closes #N` in the PR description, not the issue.
121
+
122
+ **Jira:** Use structured fields (`Issue Type`, `Priority`, `Component`, `Fix Version`, `Sprint`) — do not embed them in the description body. Link with `blocks`, `is blocked by`, `relates to`, `duplicates`. Story points go in the `Story Points` field.
123
+
124
+ ## Output Format
125
+
126
+ Ask the user: "Is this for GitHub or Jira?" before generating the final ticket. Then output the complete ticket body formatted for that tracker, ready to paste.
127
+
128
+ Include a one-line **PR/branch name suggestion**: `fix/auth-token-expiry-redirect` or `feat/csv-export-reports`.
129
+
130
+ ## Edge Cases
131
+
132
+ **Duplicate detection:** Before finalizing, ask the user if they searched the tracker for existing issues. If they provide a similar issue URL, add a `Duplicate of #<N>` reference or a "Related Issues" section rather than creating a new ticket.
133
+
134
+ **Security vulnerabilities:** If the bug involves a potential security issue (auth bypass, data exposure, injection), do NOT file it as a public GitHub issue. Output a note instructing the user to use the repository's private security advisory (`https://github.com/<org>/<repo>/security/advisories/new`) or the organization's responsible disclosure process instead.
135
+
136
+ **Insufficient reproduction steps:** If the user cannot reliably reproduce the bug, label it `needs-repro` and add a comment template asking for: browser console output, network tab HAR export, and the exact data/state when the issue occurred. Do not assign P1/P2 to an unreproducible bug.
137
+
138
+ **Performance regression fields:** For performance bugs, add a dedicated section:
139
+ ```
140
+ ### Performance Regression
141
+ | Metric | Baseline (last release) | Current |
142
+ |---|---|---|
143
+ | p50 latency | 120 ms | 890 ms |
144
+ | p99 latency | 340 ms | 4,200 ms |
145
+ | Throughput | 850 req/s | 210 req/s |
146
+
147
+ **Profiling data:** Attach flamegraph or profiler output. Note the profiling tool and sampling duration.
148
+ ```
@@ -0,0 +1,149 @@
1
+ ---
2
+ name: kubecrafter
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
+ ---
5
+
6
+ # KubeCrafter
7
+
8
+ ## Overview
9
+
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
+
12
+ ## Workflow
13
+
14
+ ### 1. Gather Requirements
15
+
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.
17
+
18
+ ### 2. Deployment Manifest
19
+
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
+ ```
77
+
78
+ ### 3. Service, Ingress, and HPA
79
+
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).
@@ -0,0 +1,132 @@
1
+ ---
2
+ name: logiclens
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
+ ---
5
+
6
+ # LogicLens
7
+
8
+ ## Overview
9
+
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
+
12
+ ## Workflow
13
+
14
+ ### 1. Measure Baseline Complexity
15
+
16
+ Before touching any code, compute:
17
+
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
21
+
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 |
28
+
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.
30
+
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.
@@ -0,0 +1,146 @@
1
+ ---
2
+ name: mocksmith
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
+ ---
5
+
6
+ # MockSmith
7
+
8
+ ## Overview
9
+
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
+
12
+ ## Workflow
13
+
14
+ ### 1. Derive the Schema First
15
+
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.
17
+
18
+ ### 2. Build Factory Functions (TypeScript / Faker.js)
19
+
20
+ ```typescript
21
+ // factories/user.factory.ts
22
+ import { faker } from '@faker-js/faker';
23
+
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
+ }
35
+
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`.