@polymorphism-tech/morph-spec 4.6.0 → 4.7.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 (239) hide show
  1. package/README.md +414 -700
  2. package/docs/ARCHITECTURE.md +331 -0
  3. package/docs/CHEATSHEET.md +221 -0
  4. package/docs/COMMAND-FLOWS.md +368 -0
  5. package/docs/QUICKSTART.md +212 -0
  6. package/docs/examples/order-management/contracts.cs +84 -0
  7. package/docs/examples/order-management/proposal.md +24 -0
  8. package/docs/examples/order-management/spec.md +162 -0
  9. package/docs/plans/2026-02-23-ddd-architecture-refactor.md +1153 -0
  10. package/docs/plans/2026-02-23-ddd-nextsteps.md +682 -0
  11. package/docs/plans/2026-02-23-infra-architect-refactor.md +437 -0
  12. package/docs/plans/2026-02-23-nextjs-code-review-design.md +156 -0
  13. package/docs/plans/2026-02-23-nextjs-code-review-impl.md +1254 -0
  14. package/docs/plans/2026-02-23-nextjs-standards-design.md +149 -0
  15. package/docs/plans/2026-02-23-nextjs-standards-impl.md +1846 -0
  16. package/framework/agents/README.md +14 -14
  17. package/framework/agents/architecture/standards-architect.md +159 -159
  18. package/framework/agents/frontend/nextjs-expert.md +87 -127
  19. package/framework/agents/infrastructure/azure-architect.md +147 -147
  20. package/framework/agents/infrastructure/infra-architect.md +45 -0
  21. package/framework/agents.json +1145 -278
  22. package/framework/rules/frontend-standards.md +0 -3
  23. package/framework/rules/nextjs-standards.md +17 -0
  24. package/framework/skills/level-0-meta/code-review-nextjs/SKILL.md +147 -0
  25. package/framework/skills/level-0-meta/code-review-nextjs/references/review-example-nextjs.md +254 -0
  26. package/framework/skills/level-0-meta/tool-usage-guide/SKILL.md +3 -3
  27. package/framework/skills/level-1-workflows/phase-design/SKILL.md +45 -9
  28. package/framework/skills/level-1-workflows/phase-tasks/SKILL.md +38 -0
  29. package/framework/standards/STANDARDS.json +121 -0
  30. package/framework/standards/architecture/ddd/bounded-contexts.md +105 -0
  31. package/framework/standards/architecture/ddd/complexity-levels.md +108 -0
  32. package/framework/standards/architecture/ddd/ubiquitous-language.md +58 -0
  33. package/framework/standards/frontend/nextjs/app-router.md +123 -0
  34. package/framework/standards/frontend/nextjs/components.md +132 -0
  35. package/framework/standards/frontend/nextjs/data-fetching.md +126 -0
  36. package/framework/standards/frontend/nextjs/forms.md +128 -0
  37. package/framework/standards/frontend/nextjs/naming-conventions.md +67 -0
  38. package/framework/standards/frontend/nextjs/project-structure.md +102 -0
  39. package/framework/standards/frontend/nextjs/state-management.md +72 -0
  40. package/framework/standards/frontend/nextjs/testing.md +111 -0
  41. package/framework/templates/REGISTRY.json +538 -142
  42. package/framework/templates/code/dotnet/contracts/contracts-level1.cs +69 -0
  43. package/framework/templates/code/dotnet/contracts/contracts-level2.cs +86 -0
  44. package/framework/templates/code/dotnet/contracts/contracts-level3.cs +41 -0
  45. package/framework/templates/docs/spec.md +49 -0
  46. package/framework/templates/frontend/nextjs/Dockerfile.nextjs.hbs +43 -0
  47. package/framework/templates/frontend/nextjs/client-component.tsx.hbs +26 -0
  48. package/framework/templates/frontend/nextjs/env.mjs.hbs +32 -0
  49. package/framework/templates/frontend/nextjs/feature-form.tsx.hbs +56 -0
  50. package/framework/templates/frontend/nextjs/page.tsx.hbs +22 -0
  51. package/framework/templates/frontend/nextjs/tsconfig.json.hbs +26 -0
  52. package/framework/templates/frontend/nextjs/use-feature.ts.hbs +54 -0
  53. package/framework/templates/project-structure/dotnet-ddd.md +70 -0
  54. package/framework/workflows/docs/enforcement-pipeline.md +2 -1
  55. package/package.json +1 -1
  56. package/scripts/scan-nextjs.mjs +169 -0
  57. package/src/commands/project/doctor.js +52 -1
  58. package/src/commands/project/init.js +15 -1
  59. package/src/commands/project/update.js +6 -1
  60. package/src/lib/standards/standards-context-injector.js +5 -0
  61. package/src/lib/validators/nextjs/index.js +6 -0
  62. package/src/lib/validators/nextjs/next-component-validator.js +181 -0
  63. package/src/lib/validators/validation-runner.js +5 -0
  64. package/src/utils/agents-installer.js +14 -2
  65. package/.morph/.morphversion +0 -5
  66. package/.morph/analytics/threads-log.jsonl +0 -6
  67. package/.morph/config/config.json +0 -8
  68. package/.morph/framework/agents.json +0 -948
  69. package/.morph/framework/standards/STANDARDS.json +0 -812
  70. package/.morph/framework/standards/ai-agents/blazor-ui.md +0 -364
  71. package/.morph/framework/standards/ai-agents/production.md +0 -415
  72. package/.morph/framework/standards/ai-agents/setup.md +0 -418
  73. package/.morph/framework/standards/ai-agents/team-orchestration.md +0 -479
  74. package/.morph/framework/standards/ai-agents/workflows.md +0 -354
  75. package/.morph/framework/standards/architecture/ddd/aggregates.md +0 -120
  76. package/.morph/framework/standards/architecture/ddd/entities.md +0 -99
  77. package/.morph/framework/standards/architecture/ddd/value-objects.md +0 -124
  78. package/.morph/framework/standards/backend/api/minimal-api.md +0 -494
  79. package/.morph/framework/standards/backend/api/rest.md +0 -492
  80. package/.morph/framework/standards/backend/api/validation.md +0 -88
  81. package/.morph/framework/standards/backend/authentication/passkeys.md +0 -428
  82. package/.morph/framework/standards/backend/database/ef-core.md +0 -199
  83. package/.morph/framework/standards/backend/database/migrations.md +0 -393
  84. package/.morph/framework/standards/backend/database/postgresql/database.md +0 -352
  85. package/.morph/framework/standards/backend/database/repository-patterns.md +0 -528
  86. package/.morph/framework/standards/backend/database/vector-search-rag.md +0 -541
  87. package/.morph/framework/standards/backend/dotnet/async.md +0 -366
  88. package/.morph/framework/standards/backend/dotnet/core.md +0 -117
  89. package/.morph/framework/standards/backend/dotnet/di.md +0 -439
  90. package/.morph/framework/standards/backend/dotnet/program-cs-checklist.md +0 -92
  91. package/.morph/framework/standards/backend/integrations/asaas/asaas-api.md +0 -216
  92. package/.morph/framework/standards/backend/integrations/clerk/clerk-auth.md +0 -290
  93. package/.morph/framework/standards/backend/integrations/hangfire/hangfire-jobs.md +0 -350
  94. package/.morph/framework/standards/backend/integrations/resend/resend-email.md +0 -385
  95. package/.morph/framework/standards/context/analytics.md +0 -96
  96. package/.morph/framework/standards/context/bundles.md +0 -110
  97. package/.morph/framework/standards/context/priming.md +0 -78
  98. package/.morph/framework/standards/core/architecture.md +0 -185
  99. package/.morph/framework/standards/core/coding.md +0 -214
  100. package/.morph/framework/standards/core/git-branching-strategy.md +0 -403
  101. package/.morph/framework/standards/core/git.md +0 -185
  102. package/.morph/framework/standards/core/testing.md +0 -295
  103. package/.morph/framework/standards/data/nosql/blob-storage.md +0 -102
  104. package/.morph/framework/standards/data/nosql/cache/redis.md +0 -97
  105. package/.morph/framework/standards/data/nosql/cosmos-db.md +0 -118
  106. package/.morph/framework/standards/data/vector-search/azure-ai-search.md +0 -121
  107. package/.morph/framework/standards/data/vector-search/rag-chunking.md +0 -104
  108. package/.morph/framework/standards/frontend/blazor/design-checklist.md +0 -222
  109. package/.morph/framework/standards/frontend/blazor/fluent-ui-setup.md +0 -595
  110. package/.morph/framework/standards/frontend/blazor/fluent-ui.md +0 -137
  111. package/.morph/framework/standards/frontend/blazor/html-conversion.md +0 -184
  112. package/.morph/framework/standards/frontend/blazor/lifecycle.md +0 -195
  113. package/.morph/framework/standards/frontend/blazor/pitfalls.md +0 -198
  114. package/.morph/framework/standards/frontend/blazor/state.md +0 -191
  115. package/.morph/framework/standards/frontend/design-system/animations.md +0 -151
  116. package/.morph/framework/standards/frontend/design-system/naming.md +0 -64
  117. package/.morph/framework/standards/frontend/nextjs/nextjs-patterns.md +0 -215
  118. package/.morph/framework/standards/infrastructure/azure/azure.md +0 -624
  119. package/.morph/framework/standards/infrastructure/azure/bicep/bicep-patterns.md +0 -422
  120. package/.morph/framework/standards/infrastructure/azure/devops/azure-devops-setup.md +0 -516
  121. package/.morph/framework/standards/infrastructure/azure/devops/local-development.md +0 -520
  122. package/.morph/framework/standards/infrastructure/azure/services/functions.md +0 -486
  123. package/.morph/framework/standards/infrastructure/azure/services/service-bus.md +0 -459
  124. package/.morph/framework/standards/infrastructure/azure/services/storage.md +0 -407
  125. package/.morph/framework/standards/infrastructure/docker/easypanel-deploy.md +0 -196
  126. package/.morph/framework/standards/infrastructure/supabase/mcp-setup.md +0 -252
  127. package/.morph/framework/standards/infrastructure/supabase/supabase-auth.md +0 -176
  128. package/.morph/framework/standards/infrastructure/supabase/supabase-pgvector.md +0 -169
  129. package/.morph/framework/standards/infrastructure/supabase/supabase-rls.md +0 -184
  130. package/.morph/framework/standards/infrastructure/supabase/supabase-storage.md +0 -153
  131. package/.morph/framework/standards/integration/api/graphql.md +0 -91
  132. package/.morph/framework/standards/integration/api/grpc.md +0 -114
  133. package/.morph/framework/standards/integration/api/rest-design.md +0 -95
  134. package/.morph/framework/standards/integration/event-driven/cqrs.md +0 -101
  135. package/.morph/framework/standards/integration/event-driven/event-sourcing.md +0 -124
  136. package/.morph/framework/standards/integration/event-driven/service-bus.md +0 -95
  137. package/.morph/framework/standards/integration/mcp/mcp-tools.md +0 -384
  138. package/.morph/framework/standards/observability/logging.md +0 -131
  139. package/.morph/framework/standards/observability/metrics.md +0 -121
  140. package/.morph/framework/standards/observability/monitoring.md +0 -114
  141. package/.morph/framework/standards/observability/tracing.md +0 -132
  142. package/.morph/framework/standards/workflows/parallel-execution.md +0 -112
  143. package/.morph/framework/standards/workflows/thread-management.md +0 -113
  144. package/.morph/framework/templates/.idea/morph-templates.xml +0 -92
  145. package/.morph/framework/templates/.vscode/morph-templates.code-snippets +0 -186
  146. package/.morph/framework/templates/IDE-SNIPPETS.md +0 -266
  147. package/.morph/framework/templates/README.md +0 -814
  148. package/.morph/framework/templates/REGISTRY.json +0 -1492
  149. package/.morph/framework/templates/code/dotnet/backend/repository.cs +0 -141
  150. package/.morph/framework/templates/code/dotnet/backend/service.cs +0 -139
  151. package/.morph/framework/templates/code/dotnet/contracts/Commands.cs +0 -74
  152. package/.morph/framework/templates/code/dotnet/contracts/Entities.cs +0 -25
  153. package/.morph/framework/templates/code/dotnet/contracts/Queries.cs +0 -74
  154. package/.morph/framework/templates/code/dotnet/contracts/README.md +0 -74
  155. package/.morph/framework/templates/code/dotnet/contracts/api-contracts.cs +0 -173
  156. package/.morph/framework/templates/code/dotnet/contracts/contracts.cs +0 -217
  157. package/.morph/framework/templates/code/dotnet/contracts/contracts.cs.hbs +0 -172
  158. package/.morph/framework/templates/code/dotnet/database/migration.cs +0 -83
  159. package/.morph/framework/templates/code/dotnet/frontend/component.razor +0 -239
  160. package/.morph/framework/templates/code/dotnet/jobs/agent.cs +0 -163
  161. package/.morph/framework/templates/code/dotnet/jobs/job.cs +0 -171
  162. package/.morph/framework/templates/code/dotnet/test.cs +0 -239
  163. package/.morph/framework/templates/code/sql/rls-policy.sql +0 -57
  164. package/.morph/framework/templates/code/sql/supabase-migration.sql +0 -100
  165. package/.morph/framework/templates/code/sql/supabase-migration.template.sql +0 -113
  166. package/.morph/framework/templates/code/typescript/contracts.ts +0 -168
  167. package/.morph/framework/templates/context/CONTEXT-FEATURE.md +0 -276
  168. package/.morph/framework/templates/context/CONTEXT.md +0 -181
  169. package/.morph/framework/templates/docs/clarifications.md +0 -253
  170. package/.morph/framework/templates/docs/onboarding.md +0 -123
  171. package/.morph/framework/templates/docs/proposal.md +0 -182
  172. package/.morph/framework/templates/docs/schema-analysis.md +0 -119
  173. package/.morph/framework/templates/docs/spec.md +0 -149
  174. package/.morph/framework/templates/docs/ui-components.md +0 -124
  175. package/.morph/framework/templates/docs/ui-design-system.md +0 -76
  176. package/.morph/framework/templates/docs/ui-flows.md +0 -167
  177. package/.morph/framework/templates/docs/ui-mockups.md +0 -98
  178. package/.morph/framework/templates/docs/user-stories.md +0 -34
  179. package/.morph/framework/templates/examples/design-system-examples.md +0 -357
  180. package/.morph/framework/templates/examples/spec-examples.md +0 -90
  181. package/.morph/framework/templates/feature/decisions.md +0 -187
  182. package/.morph/framework/templates/feature/recap.md +0 -146
  183. package/.morph/framework/templates/feature/tasks.md +0 -199
  184. package/.morph/framework/templates/infrastructure/azure/Dockerfile.example +0 -82
  185. package/.morph/framework/templates/infrastructure/azure/README.md +0 -286
  186. package/.morph/framework/templates/infrastructure/azure/app-insights.bicep +0 -63
  187. package/.morph/framework/templates/infrastructure/azure/app-service.bicep +0 -164
  188. package/.morph/framework/templates/infrastructure/azure/container-app-env.bicep +0 -49
  189. package/.morph/framework/templates/infrastructure/azure/container-app.bicep +0 -156
  190. package/.morph/framework/templates/infrastructure/azure/deploy-checklist.md +0 -426
  191. package/.morph/framework/templates/infrastructure/azure/deploy.ps1 +0 -229
  192. package/.morph/framework/templates/infrastructure/azure/deploy.sh +0 -208
  193. package/.morph/framework/templates/infrastructure/azure/key-vault.bicep +0 -91
  194. package/.morph/framework/templates/infrastructure/azure/main.bicep +0 -189
  195. package/.morph/framework/templates/infrastructure/azure/parameters.dev.json +0 -29
  196. package/.morph/framework/templates/infrastructure/azure/parameters.prod.json +0 -29
  197. package/.morph/framework/templates/infrastructure/azure/parameters.staging.json +0 -29
  198. package/.morph/framework/templates/infrastructure/azure/sql-database.bicep +0 -103
  199. package/.morph/framework/templates/infrastructure/azure/storage.bicep +0 -106
  200. package/.morph/framework/templates/infrastructure/docker/Dockerfile.template +0 -58
  201. package/.morph/framework/templates/infrastructure/docker/docker-compose.template.yml +0 -67
  202. package/.morph/framework/templates/infrastructure/docker/dockerfile-api.dockerfile +0 -38
  203. package/.morph/framework/templates/infrastructure/docker/dockerfile-web.dockerfile +0 -48
  204. package/.morph/framework/templates/infrastructure/docker/easypanel.template.json +0 -54
  205. package/.morph/framework/templates/infrastructure/github/README.md +0 -593
  206. package/.morph/framework/templates/infrastructure/github/actions/azure-auth/action.yml.hbs +0 -22
  207. package/.morph/framework/templates/infrastructure/github/actions/docker-build-push/action.yml.hbs +0 -45
  208. package/.morph/framework/templates/infrastructure/github/actions/health-check/action.yml.hbs +0 -27
  209. package/.morph/framework/templates/infrastructure/github/workflows/deploy-azure-app-service.yml.hbs +0 -61
  210. package/.morph/framework/templates/infrastructure/github/workflows/deploy-easypanel.yml.hbs +0 -31
  211. package/.morph/framework/templates/infrastructure/github/workflows/docker-build-push.yml.hbs +0 -59
  212. package/.morph/framework/templates/infrastructure/github/workflows/dotnet-build.yml.hbs +0 -39
  213. package/.morph/framework/templates/integrations/asaas-client.cs +0 -387
  214. package/.morph/framework/templates/integrations/asaas-webhook.cs +0 -351
  215. package/.morph/framework/templates/integrations/azure-identity-config.cs +0 -288
  216. package/.morph/framework/templates/integrations/clerk-config.cs +0 -258
  217. package/.morph/framework/templates/meta-prompts/fusion/fusion-agent.md +0 -76
  218. package/.morph/framework/templates/meta-prompts/fusion/fusion-aggregator.md +0 -100
  219. package/.morph/framework/templates/meta-prompts/hops/hop-retry.md +0 -78
  220. package/.morph/framework/templates/meta-prompts/hops/hop-validation.md +0 -97
  221. package/.morph/framework/templates/meta-prompts/hops/hop-wrapper.md +0 -36
  222. package/.morph/framework/templates/meta-prompts/parallel-workers/parallel-coordinator.md +0 -113
  223. package/.morph/framework/templates/meta-prompts/parallel-workers/parallel-worker.md +0 -80
  224. package/.morph/framework/templates/meta-prompts/squad-leaders/backend-squad.md +0 -90
  225. package/.morph/framework/templates/meta-prompts/squad-leaders/frontend-squad.md +0 -126
  226. package/.morph/framework/templates/meta-prompts/squad-leaders/squad-leader.md +0 -43
  227. package/.morph/framework/templates/meta-prompts/validators/checkpoint-validator.md +0 -107
  228. package/.morph/framework/templates/meta-prompts/validators/pre-commit-validator.md +0 -95
  229. package/.morph/framework/templates/saas/subscription.cs +0 -347
  230. package/.morph/framework/templates/saas/tenant.cs +0 -338
  231. package/.morph/framework/templates/state.template.json +0 -17
  232. package/.morph/framework/templates/ui/FluentDesignTheme.cs +0 -149
  233. package/.morph/framework/templates/ui/MudTheme.cs +0 -281
  234. package/.morph/framework/templates/ui/design-system.css +0 -226
  235. package/.morph/logs/tool-failures.log +0 -7
  236. package/.morph/memory/pre-compact-2026-02-23T15-43-03-521Z.json +0 -16
  237. package/.morph/state.json +0 -48
  238. package/framework/templates/code/dotnet/contracts/contracts.cs +0 -217
  239. package/framework/templates/code/dotnet/contracts/contracts.cs.hbs +0 -172
@@ -0,0 +1,1254 @@
1
+ # Next.js Code Review & Scan Implementation Plan
2
+
3
+ > **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
4
+
5
+ **Goal:** Add full Next.js code review coverage to morph-spec — wire the existing validator into the auto-validation pipeline, build a CLI scan script, and create the `code-review-nextjs` skill with a reference example.
6
+
7
+ **Architecture:** Three-layer system. Layer 1 (auto): `nextjs-component` validator wired into `validation-runner.js` via `agents.json`, runs automatically on `morph-spec validate`. Layer 2 (CLI): `scripts/scan-nextjs.mjs` wraps `validateNextComponent` + adds extra checks, usable in CI. Layer 3 (LLM): `code-review-nextjs` skill references the scan script first, then manual checklist covering all 8 Next.js standards.
8
+
9
+ **Tech Stack:** Node.js/ESM, `glob` package, `node:test` + `node:assert/strict`, `node:fs/promises`, `node:os`, chalk
10
+
11
+ ---
12
+
13
+ ## Key Context
14
+
15
+ - `validateNextComponent(content, filePath)` is in `src/lib/validators/nextjs/next-component-validator.js`
16
+ - Returns `{ type: 'error'|'warning', message, suggestion, file, line? }[]`
17
+ - Currently exports only `validateNextComponent` — no project-level scanner
18
+ - `validation-runner.js:runSingleValidator()` uses a `switch` on validatorId and expects `{ errors, warnings, issues: [{level, message, file, line?, solution?}] }`
19
+ - `agents.json` `nextjs-expert.validators` currently = `["packages"]` — bug, missing `nextjs-component`
20
+ - `glob` package is available in package.json
21
+ - Skills installer copies entire directory trees from `framework/skills/level-0-meta/{name}/` → `.claude/skills/{name}/`
22
+
23
+ ---
24
+
25
+ ### Task 1: Wire nextjs-component validator (bug fix + TDD)
26
+
27
+ **Files:**
28
+ - Modify: `src/lib/validators/nextjs/next-component-validator.js` (add project-level scanner)
29
+ - Modify: `src/lib/validators/nextjs/index.js` (export new function)
30
+ - Modify: `src/lib/validators/validation-runner.js` (add case)
31
+ - Modify: `framework/agents.json` (fix validators array)
32
+ - Create: `test/validators/nextjs/next-component-files-validator.test.js`
33
+
34
+ **Step 1: Write failing tests first**
35
+
36
+ Create `test/validators/nextjs/next-component-files-validator.test.js`:
37
+
38
+ ```js
39
+ import { test, describe, beforeEach, afterEach } from 'node:test';
40
+ import assert from 'node:assert/strict';
41
+ import { mkdirSync, writeFileSync, rmSync } from 'node:fs';
42
+ import { join } from 'node:path';
43
+ import { tmpdir } from 'node:os';
44
+ import { validateNextComponentFiles } from '../../../src/lib/validators/nextjs/next-component-validator.js';
45
+
46
+ describe('validateNextComponentFiles', () => {
47
+ let tempDir;
48
+
49
+ beforeEach(() => {
50
+ tempDir = join(tmpdir(), `morph-nextjs-files-test-${Date.now()}`);
51
+ mkdirSync(join(tempDir, 'src', 'components'), { recursive: true });
52
+ });
53
+
54
+ afterEach(() => {
55
+ rmSync(tempDir, { recursive: true, force: true });
56
+ });
57
+
58
+ test('returns { errors: 0, warnings: 0, issues: [] } for a clean project', async () => {
59
+ writeFileSync(
60
+ join(tempDir, 'src', 'components', 'user-card.tsx'),
61
+ `'use client';\nimport { useState } from 'react';\nexport function UserCard() { const [x] = useState(0); return <div>{x}</div>; }`
62
+ );
63
+ const result = await validateNextComponentFiles(tempDir, {});
64
+ assert.equal(result.errors, 0);
65
+ assert.equal(result.warnings, 0);
66
+ assert.equal(result.issues.length, 0);
67
+ });
68
+
69
+ test('returns error when useState used without use client', async () => {
70
+ writeFileSync(
71
+ join(tempDir, 'src', 'components', 'broken.tsx'),
72
+ `import { useState } from 'react';\nexport function Broken() { const [x] = useState(0); return <div>{x}</div>; }`
73
+ );
74
+ const result = await validateNextComponentFiles(tempDir, {});
75
+ assert.ok(result.errors > 0, 'should have errors');
76
+ assert.ok(result.issues.length > 0, 'should have issues');
77
+ assert.equal(result.issues[0].level, 'error');
78
+ });
79
+
80
+ test('returns warning when use client has no interactivity', async () => {
81
+ writeFileSync(
82
+ join(tempDir, 'src', 'components', 'static.tsx'),
83
+ `'use client';\nexport function Static() { return <div>Hello</div>; }`
84
+ );
85
+ const result = await validateNextComponentFiles(tempDir, {});
86
+ assert.ok(result.warnings > 0, 'should have warnings');
87
+ assert.equal(result.issues[0].level, 'warning');
88
+ });
89
+
90
+ test('maps ValidationIssue.suggestion to issue.solution', async () => {
91
+ writeFileSync(
92
+ join(tempDir, 'src', 'components', 'static.tsx'),
93
+ `'use client';\nexport function Static() { return <div>Hello</div>; }`
94
+ );
95
+ const result = await validateNextComponentFiles(tempDir, {});
96
+ assert.ok(result.issues[0].solution, 'solution should be populated from suggestion');
97
+ });
98
+
99
+ test('returns { errors: 0, warnings: 0 } for empty src/ directory', async () => {
100
+ const result = await validateNextComponentFiles(tempDir, {});
101
+ assert.equal(result.errors, 0);
102
+ assert.equal(result.warnings, 0);
103
+ });
104
+
105
+ test('scans multiple files and accumulates issues', async () => {
106
+ // file 1: useState without use client (error)
107
+ writeFileSync(
108
+ join(tempDir, 'src', 'components', 'bad-a.tsx'),
109
+ `import { useState } from 'react';\nexport function BadA() { const [x] = useState(0); return <div>{x}</div>; }`
110
+ );
111
+ // file 2: unnecessary use client (warning)
112
+ writeFileSync(
113
+ join(tempDir, 'src', 'components', 'bad-b.tsx'),
114
+ `'use client';\nexport function BadB() { return <div>Static</div>; }`
115
+ );
116
+ const result = await validateNextComponentFiles(tempDir, {});
117
+ assert.ok(result.errors >= 1, 'should have at least 1 error from bad-a');
118
+ assert.ok(result.warnings >= 1, 'should have at least 1 warning from bad-b');
119
+ assert.ok(result.issues.length >= 2, 'should have issues from both files');
120
+ });
121
+ });
122
+ ```
123
+
124
+ **Step 2: Run tests to confirm they FAIL (module not found)**
125
+
126
+ ```bash
127
+ cd "R:/Polymorphism Tech/repos/morph-spec-framework" && node --test test/validators/nextjs/next-component-files-validator.test.js 2>&1 | head -10
128
+ ```
129
+
130
+ Expected: Error — `validateNextComponentFiles is not exported`
131
+
132
+ **Step 3: Add `validateNextComponentFiles` to `next-component-validator.js`**
133
+
134
+ Add after the existing `validateNextComponent` function (after the `toKebabCase` helper):
135
+
136
+ ```js
137
+ // ============================================
138
+ // PROJECT-LEVEL SCANNER
139
+ // ============================================
140
+
141
+ /**
142
+ * Validates all Next.js component files in a project directory.
143
+ * Wraps validateNextComponent for use in validation-runner.js.
144
+ *
145
+ * @param {string} projectPath - Root path of the project
146
+ * @param {Object} options - Validator options
147
+ * @returns {{ errors: number, warnings: number, issues: Array }}
148
+ */
149
+ export async function validateNextComponentFiles(projectPath, options = {}) {
150
+ const { glob } = await import('glob');
151
+ const { readFileSync } = await import('node:fs');
152
+ const { join } = await import('node:path');
153
+
154
+ const result = { errors: 0, warnings: 0, issues: [] };
155
+
156
+ // Find all .tsx and .ts files under src/
157
+ const srcDir = join(projectPath, 'src');
158
+ const pattern = `${srcDir.replace(/\\/g, '/')}/**/*.{tsx,ts}`;
159
+ const files = await glob(pattern, { ignore: ['**/node_modules/**', '**/.next/**'] });
160
+
161
+ for (const filePath of files) {
162
+ let content;
163
+ try {
164
+ content = readFileSync(filePath, 'utf8');
165
+ } catch {
166
+ continue;
167
+ }
168
+
169
+ // Make path relative for cleaner output
170
+ const relPath = filePath.replace(projectPath.replace(/\\/g, '/') + '/', '').replace(/\\/g, '/');
171
+ const fileIssues = validateNextComponent(content, relPath);
172
+
173
+ for (const issue of fileIssues) {
174
+ result.issues.push({
175
+ level: issue.type, // 'error' | 'warning' → validation-runner format
176
+ message: issue.message,
177
+ file: issue.file,
178
+ line: issue.line,
179
+ solution: issue.suggestion,
180
+ });
181
+ if (issue.type === 'error') result.errors++;
182
+ else result.warnings++;
183
+ }
184
+ }
185
+
186
+ return result;
187
+ }
188
+ ```
189
+
190
+ **Step 4: Export from index.js**
191
+
192
+ Edit `src/lib/validators/nextjs/index.js` — add:
193
+ ```js
194
+ export { validateNextComponent, validateNextComponentFiles } from './next-component-validator.js';
195
+ ```
196
+
197
+ **Step 5: Add case to validation-runner.js**
198
+
199
+ In `src/lib/validators/validation-runner.js`, inside `runSingleValidator()` switch, add before the `default:` case:
200
+
201
+ ```js
202
+ case 'nextjs-component': {
203
+ const { validateNextComponentFiles } = await import('./nextjs/next-component-validator.js');
204
+ return await validateNextComponentFiles(projectPath, options);
205
+ }
206
+ ```
207
+
208
+ **Step 6: Fix agents.json**
209
+
210
+ Find `"nextjs-expert"` entry, change:
211
+ ```json
212
+ "validators": ["packages"]
213
+ ```
214
+ to:
215
+ ```json
216
+ "validators": ["packages", "nextjs-component"]
217
+ ```
218
+
219
+ **Step 7: Validate JSON**
220
+
221
+ ```bash
222
+ cd "R:/Polymorphism Tech/repos/morph-spec-framework" && node -e "JSON.parse(require('fs').readFileSync('framework/agents.json','utf8')); console.log('OK')"
223
+ ```
224
+
225
+ **Step 8: Run the new tests — must all pass**
226
+
227
+ ```bash
228
+ cd "R:/Polymorphism Tech/repos/morph-spec-framework" && node --test test/validators/nextjs/next-component-files-validator.test.js 2>&1
229
+ ```
230
+
231
+ Expected: 6/6 pass
232
+
233
+ **Step 9: Run full test suite**
234
+
235
+ ```bash
236
+ cd "R:/Polymorphism Tech/repos/morph-spec-framework" && npm test 2>&1 | tail -8
237
+ ```
238
+
239
+ Expected: 0 failures (652+ pass)
240
+
241
+ **Step 10: Commit**
242
+
243
+ ```bash
244
+ cd "R:/Polymorphism Tech/repos/morph-spec-framework" && git add src/lib/validators/nextjs/ test/validators/nextjs/next-component-files-validator.test.js framework/agents.json src/lib/validators/validation-runner.js && git commit -m "fix(validators): wire nextjs-component validator — add validateNextComponentFiles, register in validation-runner, fix agents.json"
245
+ ```
246
+
247
+ ---
248
+
249
+ ### Task 2: Create scan-nextjs.mjs (E2E TDD with real temp dirs)
250
+
251
+ **Files:**
252
+ - Create: `scripts/scan-nextjs.mjs`
253
+ - Create: `test/scripts/scan-nextjs.test.mjs`
254
+
255
+ **Step 1: Write failing tests FIRST — real temp dirs, real user cases**
256
+
257
+ Create `test/scripts/scan-nextjs.test.mjs`:
258
+
259
+ ```js
260
+ import { test, describe, beforeEach, afterEach } from 'node:test';
261
+ import assert from 'node:assert/strict';
262
+ import { mkdirSync, writeFileSync, rmSync } from 'node:fs';
263
+ import { join } from 'node:path';
264
+ import { tmpdir } from 'node:os';
265
+ import { execSync } from 'node:child_process';
266
+
267
+ const SCAN_SCRIPT = join(process.cwd(), 'scripts', 'scan-nextjs.mjs');
268
+
269
+ /**
270
+ * Run scan-nextjs.mjs against a temp dir.
271
+ * Returns { stdout, stderr, exitCode }
272
+ */
273
+ function runScan(targetDir, extraArgs = '') {
274
+ try {
275
+ const stdout = execSync(
276
+ `node "${SCAN_SCRIPT}" "${targetDir}" ${extraArgs}`,
277
+ { encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'] }
278
+ );
279
+ return { stdout, stderr: '', exitCode: 0 };
280
+ } catch (err) {
281
+ return {
282
+ stdout: err.stdout || '',
283
+ stderr: err.stderr || '',
284
+ exitCode: err.status ?? 1,
285
+ };
286
+ }
287
+ }
288
+
289
+ describe('scan-nextjs.mjs — E2E with real temp directories', () => {
290
+ let tempDir;
291
+
292
+ beforeEach(() => {
293
+ tempDir = join(tmpdir(), `morph-scan-nextjs-${Date.now()}`);
294
+ mkdirSync(join(tempDir, 'src', 'components'), { recursive: true });
295
+ mkdirSync(join(tempDir, 'src', 'features', 'users', 'components'), { recursive: true });
296
+ mkdirSync(join(tempDir, 'src', 'app'), { recursive: true });
297
+ });
298
+
299
+ afterEach(() => {
300
+ rmSync(tempDir, { recursive: true, force: true });
301
+ });
302
+
303
+ // =============================================
304
+ // User case 1: Clean project — developer did everything right
305
+ // =============================================
306
+ test('user case: clean project with correctly written components → 0 issues, exit 0', () => {
307
+ writeFileSync(
308
+ join(tempDir, 'src', 'features', 'users', 'components', 'user-card.tsx'),
309
+ `'use client';\nimport { useState } from 'react';\nexport function UserCard({ user }) {\n const [open, setOpen] = useState(false);\n return <div onClick={() => setOpen(!open)}>{user.name}</div>;\n}`
310
+ );
311
+ writeFileSync(
312
+ join(tempDir, 'src', 'app', 'page.tsx'),
313
+ `export default async function Page() {\n return <div>Home</div>;\n}`
314
+ );
315
+ const { stdout, exitCode } = runScan(tempDir);
316
+ assert.equal(exitCode, 0, `Expected exit 0, got ${exitCode}. stdout: ${stdout}`);
317
+ assert.ok(stdout.includes('0 issues') || stdout.includes('No issues'), `Expected 0 issues in output: ${stdout}`);
318
+ });
319
+
320
+ // =============================================
321
+ // User case 2: Developer forgot 'use client' on interactive component
322
+ // =============================================
323
+ test('user case: useState without use client → CRITICAL finding, exit 1', () => {
324
+ writeFileSync(
325
+ join(tempDir, 'src', 'components', 'counter.tsx'),
326
+ `import { useState } from 'react';\nexport function Counter() {\n const [count, setCount] = useState(0);\n return <button onClick={() => setCount(c => c+1)}>{count}</button>;\n}`
327
+ );
328
+ const { stdout, exitCode } = runScan(tempDir);
329
+ assert.equal(exitCode, 1, 'Should exit 1 when errors found');
330
+ assert.ok(stdout.toLowerCase().includes('critical') || stdout.toLowerCase().includes('error'), `Expected CRITICAL in output: ${stdout}`);
331
+ assert.ok(stdout.includes('use client'), `Expected 'use client' mention: ${stdout}`);
332
+ });
333
+
334
+ // =============================================
335
+ // User case 3: Developer added 'use client' defensively to all components
336
+ // =============================================
337
+ test('user case: unnecessary use client on static component → HIGH warning, exit 0', () => {
338
+ writeFileSync(
339
+ join(tempDir, 'src', 'components', 'static-badge.tsx'),
340
+ `'use client';\nexport function StaticBadge({ label }) {\n return <span className="badge">{label}</span>;\n}`
341
+ );
342
+ const { stdout, exitCode } = runScan(tempDir);
343
+ // Warnings alone should NOT fail (exit 0)
344
+ assert.equal(exitCode, 0, 'Warnings should not cause exit 1');
345
+ assert.ok(stdout.toLowerCase().includes('warning') || stdout.toLowerCase().includes('high'), `Expected warning in output: ${stdout}`);
346
+ });
347
+
348
+ // =============================================
349
+ // User case 4: Developer created component file with PascalCase name
350
+ // =============================================
351
+ test('user case: PascalCase filename → HIGH warning in output', () => {
352
+ writeFileSync(
353
+ join(tempDir, 'src', 'components', 'UserList.tsx'),
354
+ `export function UserList() { return <ul/>; }`
355
+ );
356
+ const { stdout } = runScan(tempDir);
357
+ assert.ok(stdout.includes('UserList') || stdout.toLowerCase().includes('kebab'), `Expected file name mention: ${stdout}`);
358
+ });
359
+
360
+ // =============================================
361
+ // User case 5: Developer used useEffect to fetch data (anti-pattern)
362
+ // =============================================
363
+ test('user case: useEffect for data fetching → CRITICAL finding', () => {
364
+ writeFileSync(
365
+ join(tempDir, 'src', 'components', 'user-list.tsx'),
366
+ `'use client';\nimport { useEffect, useState } from 'react';\nexport function UserList() {\n const [users, setUsers] = useState([]);\n useEffect(() => {\n fetch('/api/users').then(r => r.json()).then(setUsers);\n }, []);\n return <ul>{users.map(u => <li key={u.id}>{u.name}</li>)}</ul>;\n}`
367
+ );
368
+ const { stdout } = runScan(tempDir);
369
+ assert.ok(
370
+ stdout.toLowerCase().includes('useeffect') || stdout.toLowerCase().includes('fetch') || stdout.toLowerCase().includes('tanstack'),
371
+ `Expected useEffect/fetch warning in output: ${stdout}`
372
+ );
373
+ });
374
+
375
+ // =============================================
376
+ // User case 6: Mixed project — some clean, some violations
377
+ // =============================================
378
+ test('user case: mixed project — correct count in summary', () => {
379
+ // Clean file
380
+ writeFileSync(
381
+ join(tempDir, 'src', 'app', 'layout.tsx'),
382
+ `export default function RootLayout({ children }) { return <html><body>{children}</body></html>; }`
383
+ );
384
+ // Error: useState without use client
385
+ writeFileSync(
386
+ join(tempDir, 'src', 'components', 'bad-component.tsx'),
387
+ `import { useState } from 'react';\nexport function Bad() { const [x] = useState(0); return <div>{x}</div>; }`
388
+ );
389
+ const { stdout, exitCode } = runScan(tempDir);
390
+ assert.equal(exitCode, 1);
391
+ // Should mention file count
392
+ assert.ok(/\d+ file/.test(stdout), `Expected file count in output: ${stdout}`);
393
+ });
394
+
395
+ // =============================================
396
+ // User case 7: --json flag for CI integration
397
+ // =============================================
398
+ test('--json flag produces valid JSON output', () => {
399
+ writeFileSync(
400
+ join(tempDir, 'src', 'components', 'good.tsx'),
401
+ `'use client';\nimport { useState } from 'react';\nexport function Good() { const [x] = useState(0); return <div onClick={() => {}}>{x}</div>; }`
402
+ );
403
+ const { stdout, exitCode } = runScan(tempDir, '--json');
404
+ assert.equal(exitCode, 0);
405
+ let parsed;
406
+ assert.doesNotThrow(() => { parsed = JSON.parse(stdout); }, 'Output must be valid JSON');
407
+ assert.ok(typeof parsed.files === 'number', 'JSON must have files count');
408
+ assert.ok(Array.isArray(parsed.issues), 'JSON must have issues array');
409
+ assert.ok(typeof parsed.errors === 'number', 'JSON must have errors count');
410
+ assert.ok(typeof parsed.warnings === 'number', 'JSON must have warnings count');
411
+ assert.ok(typeof parsed.exitCode === 'number', 'JSON must have exitCode');
412
+ });
413
+
414
+ // =============================================
415
+ // User case 8: Empty src/ directory
416
+ // =============================================
417
+ test('empty src/ directory → 0 files scanned, exit 0', () => {
418
+ const { stdout, exitCode } = runScan(tempDir);
419
+ assert.equal(exitCode, 0);
420
+ assert.ok(stdout.includes('0 file') || stdout.includes('No files') || stdout.includes('0 issues'), `Expected 0 files or 0 issues: ${stdout}`);
421
+ });
422
+
423
+ // =============================================
424
+ // User case 9: Non-existent path → graceful error
425
+ // =============================================
426
+ test('non-existent path → exit 2, error message', () => {
427
+ const { stdout, stderr, exitCode } = runScan(join(tempDir, 'does-not-exist'));
428
+ assert.equal(exitCode, 2, `Expected exit 2, got ${exitCode}`);
429
+ const combined = stdout + stderr;
430
+ assert.ok(combined.toLowerCase().includes('error') || combined.toLowerCase().includes('not found') || combined.toLowerCase().includes('does not exist'), `Expected error message: ${combined}`);
431
+ });
432
+ });
433
+ ```
434
+
435
+ **Step 2: Run tests to confirm they all FAIL**
436
+
437
+ ```bash
438
+ cd "R:/Polymorphism Tech/repos/morph-spec-framework" && node --test test/scripts/scan-nextjs.test.mjs 2>&1 | head -15
439
+ ```
440
+
441
+ Expected: `Cannot find module` or all fail with script not found.
442
+
443
+ **Step 3: Implement `scripts/scan-nextjs.mjs`**
444
+
445
+ Create `scripts/scan-nextjs.mjs`:
446
+
447
+ ```js
448
+ #!/usr/bin/env node
449
+ /**
450
+ * scan-nextjs.mjs
451
+ *
452
+ * CLI scan for Next.js CRITICAL/HIGH violations.
453
+ * Runs automatically before code-review-nextjs skill for mechanical checks.
454
+ *
455
+ * Usage:
456
+ * node scripts/scan-nextjs.mjs [path] # defaults to src/
457
+ * node scripts/scan-nextjs.mjs --json # JSON output for CI
458
+ *
459
+ * Exit codes: 0 = clean, 1 = errors found, 2 = scan failed
460
+ */
461
+
462
+ import { readFileSync, existsSync } from 'node:fs';
463
+ import { join, resolve } from 'node:path';
464
+ import { validateNextComponent } from '../src/lib/validators/nextjs/next-component-validator.js';
465
+
466
+ // ============================================
467
+ // CLI ARGUMENT PARSING
468
+ // ============================================
469
+
470
+ const args = process.argv.slice(2);
471
+ const jsonMode = args.includes('--json');
472
+ const pathArg = args.find(a => !a.startsWith('--'));
473
+ const targetPath = pathArg ? resolve(pathArg) : resolve('src');
474
+
475
+ // ============================================
476
+ // ADDITIONAL CHECKS (beyond validateNextComponent)
477
+ // ============================================
478
+
479
+ /**
480
+ * Check for useEffect used for data fetching anti-pattern.
481
+ * @param {string} content
482
+ * @param {string} filePath
483
+ * @returns {import('../src/lib/validators/nextjs/next-component-validator.js').ValidationIssue[]}
484
+ */
485
+ function checkUseEffectFetch(content, filePath) {
486
+ const issues = [];
487
+ // Pattern: useEffect containing fetch() or axios() call
488
+ if (/useEffect\s*\(\s*\(\s*\)\s*=>/.test(content) && /\bfetch\s*\(/.test(content)) {
489
+ issues.push({
490
+ type: 'error',
491
+ message: "useEffect used for data fetching — use Server Components or TanStack Query (useQuery) instead",
492
+ suggestion: "Replace with a Server Component fetch or TanStack Query useQuery hook",
493
+ file: filePath,
494
+ });
495
+ }
496
+ return issues;
497
+ }
498
+
499
+ /**
500
+ * Check for default exports on non-special files (should use named exports).
501
+ * @param {string} content
502
+ * @param {string} filePath
503
+ * @returns {import('../src/lib/validators/nextjs/next-component-validator.js').ValidationIssue[]}
504
+ */
505
+ function checkDefaultExport(content, filePath) {
506
+ const issues = [];
507
+ const fileName = filePath.split('/').pop() ?? '';
508
+ const SPECIAL = ['page.tsx', 'layout.tsx', 'loading.tsx', 'error.tsx', 'not-found.tsx'];
509
+ if (!SPECIAL.includes(fileName) && /^export\s+default\s+/m.test(content) && fileName.endsWith('.tsx')) {
510
+ issues.push({
511
+ type: 'warning',
512
+ message: `Default export in '${fileName}' — prefer named exports for easier refactoring`,
513
+ suggestion: "Change to: export function ComponentName() {}",
514
+ file: filePath,
515
+ });
516
+ }
517
+ return issues;
518
+ }
519
+
520
+ // ============================================
521
+ // FILE WALKER
522
+ // ============================================
523
+
524
+ /**
525
+ * Recursively find all .tsx and .ts files in a directory.
526
+ * @param {string} dir
527
+ * @returns {string[]}
528
+ */
529
+ function findTsxFiles(dir) {
530
+ const { readdirSync, statSync } = await import('node:fs');
531
+ // Use sync version since we imported at top
532
+ const results = [];
533
+ const entries = readdirSync(dir, { withFileTypes: true });
534
+ for (const entry of entries) {
535
+ const fullPath = join(dir, entry.name);
536
+ if (entry.name === 'node_modules' || entry.name === '.next' || entry.name === 'dist') continue;
537
+ if (entry.isDirectory()) {
538
+ results.push(...findTsxFiles(fullPath));
539
+ } else if (entry.name.endsWith('.tsx') || entry.name.endsWith('.ts')) {
540
+ results.push(fullPath);
541
+ }
542
+ }
543
+ return results;
544
+ }
545
+
546
+ // ============================================
547
+ // MAIN
548
+ // ============================================
549
+
550
+ function main() {
551
+ // Validate path exists
552
+ if (!existsSync(targetPath)) {
553
+ const msg = `Error: Path does not exist: ${targetPath}`;
554
+ if (jsonMode) {
555
+ process.stdout.write(JSON.stringify({ error: msg, exitCode: 2 }) + '\n');
556
+ } else {
557
+ process.stderr.write(msg + '\n');
558
+ }
559
+ process.exit(2);
560
+ }
561
+
562
+ // Find all files
563
+ let files;
564
+ try {
565
+ files = findTsxFiles(targetPath);
566
+ } catch (err) {
567
+ const msg = `Error scanning directory: ${err.message}`;
568
+ if (jsonMode) {
569
+ process.stdout.write(JSON.stringify({ error: msg, exitCode: 2 }) + '\n');
570
+ } else {
571
+ process.stderr.write(msg + '\n');
572
+ }
573
+ process.exit(2);
574
+ }
575
+
576
+ // Run validators
577
+ const allIssues = [];
578
+ for (const filePath of files) {
579
+ let content;
580
+ try {
581
+ content = readFileSync(filePath, 'utf8');
582
+ } catch {
583
+ continue;
584
+ }
585
+ const relPath = filePath.replace(targetPath, '').replace(/\\/g, '/').replace(/^\//, '');
586
+ const issues = [
587
+ ...validateNextComponent(content, relPath),
588
+ ...checkUseEffectFetch(content, relPath),
589
+ ...checkDefaultExport(content, relPath),
590
+ ];
591
+ allIssues.push(...issues);
592
+ }
593
+
594
+ const errors = allIssues.filter(i => i.type === 'error');
595
+ const warnings = allIssues.filter(i => i.type === 'warning');
596
+
597
+ // ---- JSON output mode ----
598
+ if (jsonMode) {
599
+ process.stdout.write(JSON.stringify({
600
+ files: files.length,
601
+ issues: allIssues.map(i => ({ severity: i.type, message: i.message, file: i.file, line: i.line ?? null, suggestion: i.suggestion ?? null })),
602
+ errors: errors.length,
603
+ warnings: warnings.length,
604
+ exitCode: errors.length > 0 ? 1 : 0,
605
+ }, null, 2) + '\n');
606
+ process.exit(errors.length > 0 ? 1 : 0);
607
+ }
608
+
609
+ // ---- Human-readable output ----
610
+ console.log(`\n🔍 Scanning ${targetPath.replace(process.cwd(), '.')} (${files.length} file${files.length !== 1 ? 's' : ''})...\n`);
611
+
612
+ if (allIssues.length === 0) {
613
+ console.log(`✅ No issues found — ${files.length} file${files.length !== 1 ? 's' : ''} scanned\n`);
614
+ console.log(`Summary: ${files.length} files scanned | 0 issues (0 critical, 0 high, 0 medium)\n`);
615
+ process.exit(0);
616
+ }
617
+
618
+ if (errors.length > 0) {
619
+ console.log(`CRITICAL (${errors.length})`);
620
+ for (const issue of errors) {
621
+ const loc = issue.line ? `:${issue.line}` : '';
622
+ console.log(` ${issue.file}${loc} — ${issue.message}`);
623
+ if (issue.suggestion) console.log(` → ${issue.suggestion}`);
624
+ }
625
+ console.log('');
626
+ }
627
+
628
+ if (warnings.length > 0) {
629
+ console.log(`HIGH/MEDIUM (${warnings.length})`);
630
+ for (const issue of warnings) {
631
+ console.log(` ${issue.file} — ${issue.message}`);
632
+ }
633
+ console.log('');
634
+ }
635
+
636
+ const clean = files.length - new Set(allIssues.map(i => i.file)).size;
637
+ if (clean > 0) console.log(`✅ No issues found in ${clean} file${clean !== 1 ? 's' : ''}\n`);
638
+
639
+ console.log(`Summary: ${files.length} files scanned | ${allIssues.length} issue${allIssues.length !== 1 ? 's' : ''} (${errors.length} critical, ${warnings.length} high/medium)\n`);
640
+ process.exit(errors.length > 0 ? 1 : 0);
641
+ }
642
+
643
+ main();
644
+ ```
645
+
646
+ **NOTE FOR IMPLEMENTER:** The `findTsxFiles` function above uses `import` inside a regular function which won't work. Fix it to use the top-level `readdirSync` and `statSync` that are already imported at the top of the file. Replace the body of `findTsxFiles` with a synchronous version using `readdirSync`/`statSync` directly (they were imported at the top with `readFileSync`):
647
+
648
+ ```js
649
+ import { readFileSync, existsSync, readdirSync, statSync } from 'node:fs';
650
+ ```
651
+
652
+ And `findTsxFiles`:
653
+ ```js
654
+ function findTsxFiles(dir) {
655
+ const results = [];
656
+ const entries = readdirSync(dir, { withFileTypes: true });
657
+ for (const entry of entries) {
658
+ const fullPath = join(dir, entry.name);
659
+ if (['node_modules', '.next', 'dist'].includes(entry.name)) continue;
660
+ if (entry.isDirectory()) {
661
+ results.push(...findTsxFiles(fullPath));
662
+ } else if (entry.name.endsWith('.tsx') || entry.name.endsWith('.ts')) {
663
+ results.push(fullPath);
664
+ }
665
+ }
666
+ return results;
667
+ }
668
+ ```
669
+
670
+ **Step 4: Run tests — all 9 should pass**
671
+
672
+ ```bash
673
+ cd "R:/Polymorphism Tech/repos/morph-spec-framework" && node --test test/scripts/scan-nextjs.test.mjs 2>&1
674
+ ```
675
+
676
+ Expected: 9/9 pass
677
+
678
+ **Step 5: Smoke-test the scan script manually**
679
+
680
+ ```bash
681
+ cd "R:/Polymorphism Tech/repos/morph-spec-framework" && node scripts/scan-nextjs.mjs scripts/ 2>&1
682
+ ```
683
+
684
+ Expected: clean output (scripts/ has no .tsx files so 0 files scanned)
685
+
686
+ ```bash
687
+ node scripts/scan-nextjs.mjs scripts/ --json 2>&1
688
+ ```
689
+
690
+ Expected: valid JSON with `{ "files": 0, "issues": [], "errors": 0, ... }`
691
+
692
+ **Step 6: Run full test suite**
693
+
694
+ ```bash
695
+ cd "R:/Polymorphism Tech/repos/morph-spec-framework" && npm test 2>&1 | tail -8
696
+ ```
697
+
698
+ Expected: 0 failures
699
+
700
+ **Step 7: Commit**
701
+
702
+ ```bash
703
+ cd "R:/Polymorphism Tech/repos/morph-spec-framework" && git add scripts/scan-nextjs.mjs test/scripts/scan-nextjs.test.mjs && git commit -m "feat(scripts): add scan-nextjs.mjs — CLI scan for use-client, hooks, kebab-case, useEffect-fetch violations"
704
+ ```
705
+
706
+ ---
707
+
708
+ ### Task 3: Create code-review-nextjs skill + reference example
709
+
710
+ **Files:**
711
+ - Create: `framework/skills/level-0-meta/code-review-nextjs/SKILL.md`
712
+ - Create: `framework/skills/level-0-meta/code-review-nextjs/references/review-example-nextjs.md`
713
+
714
+ **Note:** No unit tests needed for content files. The skills-installer test suite already validates skill directory structure. We verify installation in Task 4.
715
+
716
+ **Step 1: Create the directory structure**
717
+
718
+ ```bash
719
+ mkdir -p "R:/Polymorphism Tech/repos/morph-spec-framework/framework/skills/level-0-meta/code-review-nextjs/references"
720
+ ```
721
+
722
+ **Step 2: Create `SKILL.md`**
723
+
724
+ Create `framework/skills/level-0-meta/code-review-nextjs/SKILL.md`:
725
+
726
+ ```markdown
727
+ ---
728
+ name: code-review-nextjs
729
+ description: Next.js code review checklist covering naming conventions, component architecture (Server vs Client), data fetching patterns, form implementation, state management, TypeScript/Zod discipline, feature boundaries, and testing. Use after implementing Next.js code, before creating PRs, or when reviewing TSX/TS code for compliance with MORPH-SPEC Next.js standards.
730
+ user-invocable: true
731
+ allowed-tools: Read, Write, Edit, Bash, Glob, Grep
732
+ ---
733
+
734
+ # Next.js Code Review Checklist
735
+
736
+ > Comprehensive checklist for Next.js code review: naming, component architecture, data fetching, forms, state, TypeScript, structure, and testing.
737
+ > **Ref:** `framework/standards/frontend/nextjs/naming-conventions.md`
738
+ > **Ref:** `framework/standards/frontend/nextjs/app-router.md`
739
+ > **Ref:** `framework/standards/frontend/nextjs/components.md`
740
+ > **Ref:** `framework/standards/frontend/nextjs/data-fetching.md`
741
+ > **Ref:** `framework/standards/frontend/nextjs/forms.md`
742
+ > **Ref:** `framework/standards/frontend/nextjs/state-management.md`
743
+ > **Ref:** `framework/standards/frontend/nextjs/testing.md`
744
+ > **Example:** `references/review-example-nextjs.md` — filled-in review showing expected finding format.
745
+ > **Script:** `scripts/scan-nextjs.mjs` — automated scan for CRITICAL/HIGH violations before manual review.
746
+
747
+ ---
748
+
749
+ ## Step 1 — Run automated scan first
750
+
751
+ ```bash
752
+ node scripts/scan-nextjs.mjs src/
753
+ ```
754
+
755
+ Review and address CRITICAL findings before proceeding with the manual checklist below. Warnings can be addressed during review.
756
+
757
+ ---
758
+
759
+ ## Naming & Style (ref: naming-conventions.md)
760
+
761
+ - [ ] `[CRITICAL]` File names use kebab-case (`user-card.tsx`, NOT `UserCard.tsx`)
762
+ - [ ] `[HIGH]` Components exported as named exports (`export function UserCard`, NOT `export default function UserCard`)
763
+ - [ ] `[HIGH]` Hook files named `use-{action}.ts` and export `use{Action}()`
764
+ - [ ] `[HIGH]` Schema files named `{feature}.schemas.ts` with Zod exports
765
+ - [ ] `[HIGH]` Type files named `{feature}.types.ts` with `z.infer<>` derived types
766
+ - [ ] `[MEDIUM]` No abbreviations in public API names (`repository` not `repo`)
767
+ - [ ] `[MEDIUM]` Feature folder uses kebab-case (`features/user-management/`, NOT `features/userManagement/`)
768
+
769
+ ---
770
+
771
+ ## Component Architecture (ref: app-router.md, components.md)
772
+
773
+ ### Server vs Client Discipline
774
+ - [ ] `[CRITICAL]` `'use client'` only on components that use hooks or event handlers
775
+ - [ ] `[CRITICAL]` No `useEffect(() => { fetch(...) }, [])` for data fetching — use Server Components or TanStack Query
776
+ - [ ] `[HIGH]` Server Components used for initial page data (no `'use client'` on page files)
777
+ - [ ] `[HIGH]` `loading.tsx`, `error.tsx` co-located with every `page.tsx`
778
+ - [ ] `[HIGH]` No business logic in `app/` route files — import from `features/`
779
+
780
+ ### Three-Tier Hierarchy
781
+ - [ ] `[CRITICAL]` No edits to `components/ui/` files — shadcn primitives are never modified
782
+ - [ ] `[HIGH]` `components/` (Tier 2) has no imports from `features/` — no domain knowledge
783
+ - [ ] `[HIGH]` Feature components (`features/*/components/`) do not import from other features
784
+ - [ ] `[MEDIUM]` Feature cross-dependencies extracted to `components/` or `lib/`
785
+
786
+ ---
787
+
788
+ ## Data Fetching (ref: data-fetching.md)
789
+
790
+ - [ ] `[CRITICAL]` No `useEffect` + `useState` pattern for API data — use `useQuery`
791
+ - [ ] `[HIGH]` TanStack Query v5 syntax: `useQuery({ queryKey: [...], queryFn: async () => {} })`
792
+ - [ ] `[HIGH]` Query key factory pattern used (`userKeys.lists()`, NOT hardcoded `['users']`)
793
+ - [ ] `[HIGH]` `useMutation` used for POST/PUT/DELETE — not inline `fetch` in handlers
794
+ - [ ] `[HIGH]` API responses validated with Zod before use
795
+ - [ ] `[MEDIUM]` `onSuccess` in `useMutation` invalidates relevant query keys
796
+ - [ ] `[MEDIUM]` `QueryClientProvider` wraps app in `app/layout.tsx`, not per-component
797
+
798
+ ---
799
+
800
+ ## Forms (ref: forms.md)
801
+
802
+ - [ ] `[CRITICAL]` Zod schema defined BEFORE TypeScript type — type derived with `z.infer<>`
803
+ - [ ] `[HIGH]` `useForm` uses `zodResolver(schema)` — NOT manual validation
804
+ - [ ] `[HIGH]` shadcn `<Form>`, `<FormField>`, `<FormItem>`, `<FormLabel>`, `<FormControl>`, `<FormMessage>` used
805
+ - [ ] `[HIGH]` Form submission uses `useMutation` — NOT direct `fetch` in `onSubmit`
806
+ - [ ] `[MEDIUM]` `isPending` used for loading state — NOT `isLoading` (v5 renamed)
807
+ - [ ] `[MEDIUM]` Root-level errors displayed: `form.formState.errors.root`
808
+ - [ ] `[MEDIUM]` No `useState` for individual form fields — react-hook-form handles this
809
+
810
+ ---
811
+
812
+ ## State Management (ref: state-management.md)
813
+
814
+ - [ ] `[HIGH]` No Zustand/Redux installed without documented justification
815
+ - [ ] `[HIGH]` No React Context used for server state (API data) — use TanStack Query
816
+ - [ ] `[MEDIUM]` Local UI state (open/closed, selected) in `useState` — not global store
817
+ - [ ] `[MEDIUM]` Context only for truly global UI: theme, auth user, locale
818
+ - [ ] `[LOW]` No prop drilling beyond 3 levels — consider Context or co-location
819
+
820
+ ---
821
+
822
+ ## TypeScript Discipline
823
+
824
+ - [ ] `[CRITICAL]` No `any` type — use `unknown` and narrow, or fix the actual type
825
+ - [ ] `[HIGH]` Types derived from Zod schemas (`type User = z.infer<typeof userSchema>`)
826
+ - [ ] `[HIGH]` No duplicate type definitions — if the server returns it, define it once with Zod
827
+ - [ ] `[MEDIUM]` API response types come from the shared schema, not manually written
828
+ - [ ] `[MEDIUM]` `noUncheckedIndexedAccess` respected — array accesses use optional chaining
829
+ - [ ] `[LOW]` No type assertions (`as User`) without validation
830
+
831
+ ---
832
+
833
+ ## Feature Structure (ref: project-structure.md)
834
+
835
+ - [ ] `[HIGH]` Feature exposes public API via `features/{name}/index.ts` — no deep path imports
836
+ - [ ] `[HIGH]` Consumers import from index: `from '@/features/users'` NOT `from '@/features/users/components/user-list'`
837
+ - [ ] `[MEDIUM]` New features create: `components/`, `hooks/`, `types/` subdirectories
838
+ - [ ] `[MEDIUM]` TanStack Query hooks in `features/{name}/hooks/` — NOT co-located with components
839
+ - [ ] `[MEDIUM]` Zod schemas in `features/{name}/types/{name}.schemas.ts`
840
+ - [ ] `[LOW]` Feature index only exports what external consumers actually need (no over-exposure)
841
+
842
+ ---
843
+
844
+ ## Testing (ref: testing.md)
845
+
846
+ - [ ] `[HIGH]` Test files co-located with source (`user-card.test.tsx` next to `user-card.tsx`)
847
+ - [ ] `[HIGH]` `@testing-library/user-event` used — NOT `fireEvent`
848
+ - [ ] `[HIGH]` API calls mocked with MSW — NOT `jest.mock('fetch')` or `global.fetch = jest.fn()`
849
+ - [ ] `[MEDIUM]` Hook tests use `QueryClientWrapper` helper with `retry: false`
850
+ - [ ] `[MEDIUM]` Tests cover happy path + one error path per component
851
+ - [ ] `[LOW]` No snapshot tests — use `expect(screen.getByText(...))`
852
+
853
+ ---
854
+
855
+ ## Quick Pre-Merge Checklist
856
+
857
+ ```
858
+ [ ] node scripts/scan-nextjs.mjs src/ — 0 CRITICAL findings
859
+ [ ] File names are kebab-case (UserCard.tsx → user-card.tsx)
860
+ [ ] 'use client' only on interactive components (hooks or event handlers)
861
+ [ ] No useEffect for data fetching — Server Component or useQuery
862
+ [ ] Zod schema defined first, type derived with z.infer<>
863
+ [ ] zodResolver connected to useForm, useMutation for submit
864
+ [ ] Query key factory used (userKeys.lists() not ['users'])
865
+ [ ] Feature public API via features/{name}/index.ts
866
+ [ ] components/ui/ files untouched (shadcn CLI only)
867
+ [ ] Tests: userEvent not fireEvent, MSW not mock fetch
868
+ ```
869
+
870
+ ---
871
+
872
+ *Covers: naming-conventions.md + app-router.md + components.md + data-fetching.md + forms.md + state-management.md + testing.md + project-structure.md*
873
+ *MORPH-SPEC by Polymorphism Tech*
874
+ ```
875
+
876
+ **Step 3: Create `references/review-example-nextjs.md`**
877
+
878
+ Create `framework/skills/level-0-meta/code-review-nextjs/references/review-example-nextjs.md`:
879
+
880
+ ```markdown
881
+ # Code Review Report — User Management Feature
882
+
883
+ > Example of a well-structured Next.js code review output. Filled-in reference — not a template.
884
+
885
+ **Scope:** `src/features/users/` + `src/app/(dashboard)/users/page.tsx`
886
+ **Date:** 2026-02-23
887
+ **Reviewer:** code-review-nextjs skill
888
+
889
+ ---
890
+
891
+ ## Automated Scan Results
892
+
893
+ ```bash
894
+ $ node scripts/scan-nextjs.mjs src/features/users/
895
+
896
+ CRITICAL (1)
897
+ features/users/components/UserList.tsx:1 — React hooks used (useState) without 'use client'
898
+
899
+ HIGH/MEDIUM (2)
900
+ features/users/components/UserList.tsx — PascalCase filename (should be user-list.tsx)
901
+ features/users/components/user-form.tsx — 'use client' directive present but no interactivity detected
902
+
903
+ Summary: 8 files scanned | 3 issues (1 critical, 2 high/medium)
904
+ ```
905
+
906
+ ---
907
+
908
+ ## Findings by Severity
909
+
910
+ | Severity | Count |
911
+ |----------|-------|
912
+ | CRITICAL | 2 |
913
+ | HIGH | 3 |
914
+ | MEDIUM | 2 |
915
+ | LOW | 1 |
916
+
917
+ ---
918
+
919
+ ### [CRITICAL] Missing 'use client' on interactive component
920
+
921
+ **File:** `src/features/users/components/UserList.tsx:1`
922
+
923
+ **Current code:**
924
+ ```tsx
925
+ import { useState } from 'react';
926
+
927
+ export function UserList() {
928
+ const [selected, setSelected] = useState<string | null>(null);
929
+ return <div onClick={() => setSelected('test')}>...</div>;
930
+ }
931
+ ```
932
+
933
+ **Suggested fix:**
934
+ ```tsx
935
+ 'use client';
936
+
937
+ import { useState } from 'react';
938
+ // ... rest unchanged
939
+ ```
940
+
941
+ **Why:** React hooks (`useState`) require `'use client'`. Without it, Next.js treats this as a Server Component and the `useState` call fails at runtime.
942
+
943
+ ---
944
+
945
+ ### [CRITICAL] useEffect for data fetching
946
+
947
+ **File:** `src/features/users/components/user-list.tsx:8`
948
+
949
+ **Current code:**
950
+ ```tsx
951
+ 'use client';
952
+ import { useEffect, useState } from 'react';
953
+
954
+ export function UserList() {
955
+ const [users, setUsers] = useState([]);
956
+ useEffect(() => {
957
+ fetch('/api/users').then(r => r.json()).then(setUsers);
958
+ }, []);
959
+ return <ul>{users.map(u => <li key={u.id}>{u.name}</li>)}</ul>;
960
+ }
961
+ ```
962
+
963
+ **Suggested fix:**
964
+ ```tsx
965
+ // Option A — Server Component (no 'use client' needed)
966
+ // app/(dashboard)/users/page.tsx
967
+ async function getUsers() {
968
+ const res = await fetch(`${process.env.API_URL}/api/users`, { next: { revalidate: 30 } });
969
+ return res.json();
970
+ }
971
+ export default async function UsersPage() {
972
+ const users = await getUsers();
973
+ return <UserList initialData={users} />;
974
+ }
975
+
976
+ // Option B — TanStack Query (when client interactivity needed)
977
+ 'use client';
978
+ import { useUsers } from '@/features/users/hooks/use-users';
979
+ export function UserList() {
980
+ const { data: users = [], isLoading } = useUsers();
981
+ if (isLoading) return <div>Loading...</div>;
982
+ return <ul>{users.map(u => <li key={u.id}>{u.name}</li>)}</ul>;
983
+ }
984
+ ```
985
+
986
+ **Why:** `useEffect` + `useState` for fetching: (1) doubles renders, (2) no caching, (3) no SSR, (4) no error/loading states, (5) can't be cancelled. TanStack Query or Server Components solve all five.
987
+
988
+ ---
989
+
990
+ ### [HIGH] PascalCase file name
991
+
992
+ **File:** `src/features/users/components/UserList.tsx`
993
+
994
+ **Suggested fix:** Rename to `user-list.tsx`
995
+
996
+ **Why:** Linux servers are case-sensitive. `UserList.tsx` and `user-list.tsx` are different files on the server but the same on macOS/Windows, causing import failures in production.
997
+
998
+ ---
999
+
1000
+ ### [HIGH] Default export on non-page component
1001
+
1002
+ **File:** `src/features/users/components/user-card.tsx:3`
1003
+
1004
+ **Current code:**
1005
+ ```tsx
1006
+ export default function UserCard({ user }: { user: User }) {
1007
+ ```
1008
+
1009
+ **Suggested fix:**
1010
+ ```tsx
1011
+ export function UserCard({ user }: { user: User }) {
1012
+ ```
1013
+
1014
+ **Why:** Named exports are refactor-safe — IDEs track renames automatically. Default exports are anonymous in imports (`import X from './user-card'` allows `X` to be anything).
1015
+
1016
+ ---
1017
+
1018
+ ### [HIGH] Type defined manually instead of deriving from Zod schema
1019
+
1020
+ **File:** `src/features/users/types/user.types.ts:1`
1021
+
1022
+ **Current code:**
1023
+ ```ts
1024
+ export type User = {
1025
+ id: string;
1026
+ name: string;
1027
+ email: string;
1028
+ role: 'admin' | 'user';
1029
+ };
1030
+ ```
1031
+
1032
+ **Suggested fix:**
1033
+ ```ts
1034
+ // user.schemas.ts — single source of truth
1035
+ export const userSchema = z.object({
1036
+ id: z.string(),
1037
+ name: z.string(),
1038
+ email: z.string().email(),
1039
+ role: z.enum(['admin', 'user']),
1040
+ });
1041
+
1042
+ // user.types.ts — derived, never written manually
1043
+ export type User = z.infer<typeof userSchema>;
1044
+ ```
1045
+
1046
+ **Why:** Manually written types drift from API responses. `z.infer<>` ensures the TypeScript type is always in sync with the runtime validation.
1047
+
1048
+ ---
1049
+
1050
+ ### [MEDIUM] Deep path import instead of feature index
1051
+
1052
+ **File:** `src/app/(dashboard)/users/page.tsx:2`
1053
+
1054
+ **Current code:**
1055
+ ```tsx
1056
+ import { UserList } from '@/features/users/components/user-list';
1057
+ ```
1058
+
1059
+ **Suggested fix:**
1060
+ ```tsx
1061
+ import { UserList } from '@/features/users';
1062
+ ```
1063
+
1064
+ **Why:** Deep path imports expose internal structure. When `user-list.tsx` moves or is renamed, every consumer breaks. The feature index is the stable public API.
1065
+
1066
+ ---
1067
+
1068
+ ### [MEDIUM] Query key not using factory pattern
1069
+
1070
+ **File:** `src/features/users/hooks/use-users.ts:8`
1071
+
1072
+ **Current code:**
1073
+ ```ts
1074
+ return useQuery({
1075
+ queryKey: ['users'],
1076
+ ```
1077
+
1078
+ **Suggested fix:**
1079
+ ```ts
1080
+ // query-keys.ts
1081
+ export const userKeys = {
1082
+ all: ['users'] as const,
1083
+ lists: () => [...userKeys.all, 'list'] as const,
1084
+ };
1085
+
1086
+ // use-users.ts
1087
+ return useQuery({
1088
+ queryKey: userKeys.lists(),
1089
+ ```
1090
+
1091
+ **Why:** Hardcoded `['users']` cannot be selectively invalidated. `queryClient.invalidateQueries({ queryKey: userKeys.lists() })` correctly invalidates only list queries, not detail queries with the same prefix.
1092
+
1093
+ ---
1094
+
1095
+ ### [LOW] Test uses fireEvent instead of userEvent
1096
+
1097
+ **File:** `src/features/users/components/user-card.test.tsx:14`
1098
+
1099
+ **Current code:**
1100
+ ```tsx
1101
+ fireEvent.click(screen.getByRole('button', { name: /edit/i }));
1102
+ ```
1103
+
1104
+ **Suggested fix:**
1105
+ ```tsx
1106
+ await userEvent.click(screen.getByRole('button', { name: /edit/i }));
1107
+ ```
1108
+
1109
+ **Why:** `fireEvent.click` dispatches a synthetic event. `userEvent.click` simulates the full browser interaction sequence (pointerdown, mousedown, focus, click, etc.) — closer to real user behaviour.
1110
+
1111
+ ---
1112
+
1113
+ ## Top Priorities
1114
+
1115
+ 1. `UserList.tsx:1` — CRITICAL missing `'use client'` (2 min fix)
1116
+ 2. `user-list.tsx:8` — CRITICAL useEffect fetch → useQuery (15 min)
1117
+ 3. `UserList.tsx` — HIGH rename to `user-list.tsx` (2 min)
1118
+ 4. `user-card.tsx:3` — HIGH named export (2 min)
1119
+ 5. `user.types.ts:1` — HIGH derive from Zod (10 min)
1120
+
1121
+ ---
1122
+
1123
+ ## Passed Checks ✅
1124
+
1125
+ - `components/ui/` files untouched
1126
+ - `zodResolver` correctly wired in `user-form.tsx`
1127
+ - `isPending` used (v5 correct — not `isLoading`)
1128
+ - `loading.tsx` and `error.tsx` present in `app/(dashboard)/users/`
1129
+ - Feature has `index.ts` re-exporting public API
1130
+ - Test file co-located with component
1131
+
1132
+ ---
1133
+
1134
+ *MORPH-SPEC by Polymorphism Tech*
1135
+ ```
1136
+
1137
+ **Step 4: Verify files exist**
1138
+
1139
+ ```bash
1140
+ ls "R:/Polymorphism Tech/repos/morph-spec-framework/framework/skills/level-0-meta/code-review-nextjs/"
1141
+ ```
1142
+
1143
+ Expected: `SKILL.md` + `references/` directory
1144
+
1145
+ **Step 5: Commit**
1146
+
1147
+ ```bash
1148
+ cd "R:/Polymorphism Tech/repos/morph-spec-framework" && git add framework/skills/level-0-meta/code-review-nextjs/ && git commit -m "feat(skills): add code-review-nextjs skill — 9-category checklist + filled review example"
1149
+ ```
1150
+
1151
+ ---
1152
+
1153
+ ### Task 4: Install skill + final end-to-end verification
1154
+
1155
+ **Files:**
1156
+ - Modified: `.claude/skills/code-review-nextjs/` (installed by running installSkills)
1157
+ - No test changes needed — existing skills-installer tests will cover the new skill
1158
+
1159
+ **Step 1: Check if skills-installer test count needs updating**
1160
+
1161
+ The existing `test/utils/skills-installer.test.js` likely has a count assertion for level-0-meta skills. Check:
1162
+
1163
+ ```bash
1164
+ grep -n "level-0-meta\|skill.*count\|\.length" "R:/Polymorphism Tech/repos/morph-spec-framework/test/utils/skills-installer.test.js" | head -20
1165
+ ```
1166
+
1167
+ If there's an assertion like `skills.length === N` for level-0-meta, update it to `N+1` since we added `code-review-nextjs`.
1168
+
1169
+ **Step 2: Manually install the skill to .claude/skills/**
1170
+
1171
+ ```bash
1172
+ cd "R:/Polymorphism Tech/repos/morph-spec-framework" && node -e "
1173
+ import('./src/utils/skills-installer.js').then(m => m.installSkills('.', 'framework')).then(r => console.log('Installed:', r.installed, 'skills'))
1174
+ " --input-type=module
1175
+ ```
1176
+
1177
+ **Step 3: Verify skill is installed**
1178
+
1179
+ ```bash
1180
+ ls ".claude/skills/code-review-nextjs/" 2>/dev/null && echo "INSTALLED" || echo "NOT FOUND"
1181
+ ```
1182
+
1183
+ Expected: `INSTALLED`, with `SKILL.md` and `references/` present.
1184
+
1185
+ **Step 4: Run full test suite — 0 failures**
1186
+
1187
+ ```bash
1188
+ cd "R:/Polymorphism Tech/repos/morph-spec-framework" && npm test 2>&1 | tail -10
1189
+ ```
1190
+
1191
+ Expected: 0 failures (659+ tests pass)
1192
+
1193
+ **Step 5: E2E smoke test — run the full pipeline manually**
1194
+
1195
+ ```bash
1196
+ # Create a realistic temp project with real violations
1197
+ node -e "
1198
+ import { mkdirSync, writeFileSync } from 'node:fs';
1199
+ import { join } from 'node:path';
1200
+ const dir = '/tmp/morph-review-e2e-demo';
1201
+ mkdirSync(join(dir, 'src/features/users/components'), { recursive: true });
1202
+ mkdirSync(join(dir, 'src/app/(dashboard)/users'), { recursive: true });
1203
+
1204
+ // Bad: useState without use client
1205
+ writeFileSync(join(dir, 'src/features/users/components/UserList.tsx'),
1206
+ \`import { useState } from 'react';
1207
+ export function UserList() {
1208
+ const [users, setUsers] = useState([]);
1209
+ return <ul/>;
1210
+ }\`);
1211
+
1212
+ // Bad: useEffect fetch
1213
+ writeFileSync(join(dir, 'src/features/users/components/user-form.tsx'),
1214
+ \`'use client';
1215
+ import { useEffect, useState } from 'react';
1216
+ export function UserForm() {
1217
+ const [data, setData] = useState(null);
1218
+ useEffect(() => { fetch('/api/users').then(r => r.json()).then(setData); }, []);
1219
+ return <form/>;
1220
+ }\`);
1221
+
1222
+ // Good: clean server component
1223
+ writeFileSync(join(dir, 'src/app/(dashboard)/users/page.tsx'),
1224
+ \`export default async function UsersPage() { return <div>Users</div>; }\`);
1225
+
1226
+ console.log('Demo project created at', dir);
1227
+ " --input-type=module
1228
+
1229
+ node scripts/scan-nextjs.mjs /tmp/morph-review-e2e-demo/src/
1230
+ ```
1231
+
1232
+ Expected output: Shows CRITICAL findings for `UserList.tsx` (useState without use client) and `user-form.tsx` (useEffect fetch), clean pass for `page.tsx`.
1233
+
1234
+ **Step 6: Test --json flag**
1235
+
1236
+ ```bash
1237
+ node scripts/scan-nextjs.mjs /tmp/morph-review-e2e-demo/src/ --json | node -e "const d=require('fs').readFileSync('/dev/stdin','utf8'); const j=JSON.parse(d); console.log('files:', j.files, '| errors:', j.errors, '| warnings:', j.warnings, '| exitCode:', j.exitCode)"
1238
+ ```
1239
+
1240
+ Expected: valid JSON with correct counts.
1241
+
1242
+ **Step 7: Commit final state**
1243
+
1244
+ ```bash
1245
+ cd "R:/Polymorphism Tech/repos/morph-spec-framework" && git add .claude/skills/code-review-nextjs/ && git commit -m "feat(skills): install code-review-nextjs to .claude/skills/ — available as /code-review-nextjs"
1246
+ ```
1247
+
1248
+ **Step 8: Final git log**
1249
+
1250
+ ```bash
1251
+ cd "R:/Polymorphism Tech/repos/morph-spec-framework" && git log --oneline -6
1252
+ ```
1253
+
1254
+ Expected: 4 clean commits covering all 4 tasks.