@polymorphism-tech/morph-spec 3.1.0 → 4.2.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 (333) hide show
  1. package/CLAUDE.md +882 -3
  2. package/README.md +79 -18
  3. package/bin/detect-agents.js +1 -1
  4. package/bin/morph-spec.js +163 -26
  5. package/bin/task-manager.cjs +101 -7
  6. package/bin/validate.js +1 -1
  7. package/docs/cli-auto-detection.md +219 -0
  8. package/docs/getting-started.md +0 -5
  9. package/docs/llm-interaction-config.md +735 -0
  10. package/docs/troubleshooting.md +269 -0
  11. package/docs/v3.0/AGENTS.md +521 -0
  12. package/docs/v3.0/ANALYSIS.md +555 -0
  13. package/docs/v3.0/ARCHITECTURE.md +436 -0
  14. package/docs/v3.0/EXECUTION-FLOW.md +1304 -0
  15. package/docs/v3.0/FEATURES.md +688 -0
  16. package/docs/v3.0/README.md +231 -0
  17. package/docs/v3.0/ROADMAP.md +801 -0
  18. package/docs/validation-checklist.md +0 -1
  19. package/package.json +5 -1
  20. package/src/commands/agents/index.js +4 -0
  21. package/src/commands/agents/spawn-team.js +172 -0
  22. package/src/commands/{create-story.js → feature/create-story.js} +357 -354
  23. package/src/commands/feature/index.js +6 -0
  24. package/src/commands/{shard-spec.js → feature/shard-spec.js} +2 -2
  25. package/src/commands/{sprint-status.js → feature/sprint-status.js} +1 -1
  26. package/src/commands/{generate-context.js → generation/generate-context.js} +40 -40
  27. package/src/commands/{generate.js → generation/generate.js} +130 -3
  28. package/src/commands/generation/index.js +5 -0
  29. package/src/commands/index.js +16 -0
  30. package/src/commands/learning/capture-pattern.js +121 -0
  31. package/src/commands/learning/index.js +5 -0
  32. package/src/commands/learning/search-patterns.js +126 -0
  33. package/src/commands/{detect-agents.js → project/detect-agents.js} +178 -178
  34. package/src/commands/project/detect-workflow.js +174 -0
  35. package/src/commands/{detect.js → project/detect.js} +104 -104
  36. package/src/commands/{doctor.js → project/doctor.js} +356 -356
  37. package/src/commands/project/index.js +10 -0
  38. package/src/commands/{init.js → project/init.js} +305 -258
  39. package/src/commands/{sync.js → project/sync.js} +167 -167
  40. package/src/commands/{update.js → project/update.js} +240 -204
  41. package/src/commands/{advance-phase.js → state/advance-phase.js} +416 -266
  42. package/src/commands/state/approve.js +221 -0
  43. package/src/commands/state/index.js +8 -0
  44. package/src/commands/{rollback-phase.js → state/rollback-phase.js} +185 -185
  45. package/src/commands/{state.js → state/state.js} +334 -334
  46. package/src/commands/{validate-phase.js → state/validate-phase.js} +221 -221
  47. package/src/commands/tasks/index.js +4 -0
  48. package/src/commands/{task.js → tasks/task.js} +78 -78
  49. package/src/commands/templates/index.js +8 -0
  50. package/src/commands/templates/template-customize.js +101 -0
  51. package/src/commands/templates/template-list.js +128 -0
  52. package/src/commands/templates/template-render.js +95 -0
  53. package/src/commands/templates/template-show.js +131 -0
  54. package/src/commands/templates/template-validate.js +91 -0
  55. package/src/commands/utils/index.js +7 -0
  56. package/src/commands/utils/migrate-state.js +158 -0
  57. package/src/commands/{session-summary.js → utils/session-summary.js} +291 -291
  58. package/src/commands/{troubleshoot.js → utils/troubleshoot.js} +222 -222
  59. package/src/commands/utils/upgrade.js +346 -0
  60. package/src/commands/{analyze-blazor-concurrency.js → validation/analyze-blazor-concurrency.js} +193 -193
  61. package/src/commands/validation/index.js +8 -0
  62. package/src/commands/{lint-fluent.js → validation/lint-fluent.js} +352 -352
  63. package/src/commands/{validate-blazor-state.js → validation/validate-blazor-state.js} +210 -210
  64. package/src/commands/{validate-blazor.js → validation/validate-blazor.js} +156 -156
  65. package/src/commands/{validate-css.js → validation/validate-css.js} +84 -84
  66. package/src/core/index.js +10 -0
  67. package/src/core/registry/command-registry.js +302 -0
  68. package/src/core/registry/index.js +8 -0
  69. package/src/core/registry/validator-registry.js +204 -0
  70. package/src/core/state/index.js +8 -0
  71. package/src/core/state/phase-state-machine.js +214 -0
  72. package/src/{lib → core/state}/state-manager.js +572 -414
  73. package/src/core/templates/index.js +9 -0
  74. package/src/core/templates/template-data-sources.js +325 -0
  75. package/src/core/templates/template-registry.js +335 -0
  76. package/src/core/templates/template-renderer.js +477 -0
  77. package/src/core/templates/template-validator.js +296 -0
  78. package/src/core/workflows/index.js +7 -0
  79. package/src/core/workflows/workflow-detector.js +354 -0
  80. package/src/generator/config-generator.js +206 -0
  81. package/src/generator/templates/config.json.template +40 -0
  82. package/src/generator/templates/project.md.template +67 -0
  83. package/src/lib/{complexity-analyzer.js → analysis/complexity-analyzer.js} +441 -441
  84. package/src/lib/analysis/index.js +7 -0
  85. package/src/lib/checkpoints/checkpoint-hooks.js +258 -0
  86. package/src/lib/checkpoints/index.js +7 -0
  87. package/src/lib/detectors/config-detector.js +223 -223
  88. package/src/lib/detectors/conversation-analyzer.js +163 -163
  89. package/src/lib/{design-system-detector.js → detectors/design-system-detector.js} +187 -187
  90. package/src/lib/detectors/index.js +87 -84
  91. package/src/lib/detectors/standards-generator.js +275 -275
  92. package/src/lib/detectors/structure-detector.js +245 -245
  93. package/src/lib/{context-generator.js → generators/context-generator.js} +526 -516
  94. package/src/lib/generators/index.js +10 -0
  95. package/src/lib/generators/metadata-extractor.js +387 -0
  96. package/src/lib/{recap-generator.js → generators/recap-generator.js} +205 -205
  97. package/src/lib/learning/index.js +7 -0
  98. package/src/lib/orchestration/index.js +7 -0
  99. package/src/lib/{team-orchestrator.js → orchestration/team-orchestrator.js} +323 -323
  100. package/src/lib/stacks/index.js +7 -0
  101. package/src/lib/{stack-resolver.js → stacks/stack-resolver.js} +180 -148
  102. package/src/lib/standards/index.js +7 -0
  103. package/src/lib/{standards-context-injector.js → standards/standards-context-injector.js} +298 -288
  104. package/src/lib/troubleshooting/index.js +8 -0
  105. package/src/lib/{troubleshoot-grep.js → troubleshooting/troubleshoot-grep.js} +204 -204
  106. package/src/lib/{troubleshoot-index.js → troubleshooting/troubleshoot-index.js} +144 -144
  107. package/src/lib/validators/architecture/architecture-validator.js +387 -0
  108. package/src/lib/validators/architecture/index.js +7 -0
  109. package/src/lib/validators/architecture-validator.js +40 -367
  110. package/src/lib/{blazor-concurrency-analyzer.js → validators/blazor/blazor-concurrency-analyzer.js} +277 -288
  111. package/src/lib/{blazor-state-validator.js → validators/blazor/blazor-state-validator.js} +279 -291
  112. package/src/lib/{blazor-validator.js → validators/blazor/blazor-validator.js} +369 -374
  113. package/src/lib/validators/blazor/index.js +9 -0
  114. package/src/lib/validators/content/content-validator.js +351 -0
  115. package/src/lib/validators/content/index.js +7 -0
  116. package/src/lib/validators/content-validator.js +164 -0
  117. package/src/lib/validators/{contract-compliance-validator.js → contracts/contract-compliance-validator.js} +273 -273
  118. package/src/lib/validators/contracts/index.js +7 -0
  119. package/src/lib/{css-validator.js → validators/css/css-validator.js} +352 -352
  120. package/src/lib/validators/css/index.js +7 -0
  121. package/src/lib/validators/{design-system-validator.js → design-system/design-system-validator.js} +231 -231
  122. package/src/lib/validators/design-system/index.js +7 -0
  123. package/src/lib/validators/package-validator.js +41 -340
  124. package/src/lib/validators/packages/index.js +7 -0
  125. package/src/lib/validators/packages/package-validator.js +360 -0
  126. package/src/lib/validators/shared/index.js +12 -0
  127. package/src/lib/validators/shared/issue-counter.js +18 -0
  128. package/src/lib/validators/shared/result-formatter.js +124 -0
  129. package/src/lib/{spec-validator.js → validators/spec-validator.js} +258 -258
  130. package/src/lib/validators/ui/index.js +7 -0
  131. package/src/lib/validators/ui/ui-contrast-validator.js +422 -0
  132. package/src/lib/validators/ui-contrast-validator.js +31 -409
  133. package/src/lib/{validation-runner.js → validators/validation-runner.js} +286 -284
  134. package/src/llm/analyzer.js +215 -0
  135. package/src/llm/environment-detector.js +43 -0
  136. package/src/llm/few-shot-examples.js +216 -0
  137. package/src/llm/project-config-schema.json +188 -0
  138. package/src/llm/prompt-builder.js +96 -0
  139. package/src/orchestrator.js +206 -0
  140. package/src/sanitizer/context-sanitizer.js +221 -0
  141. package/src/sanitizer/patterns.js +163 -0
  142. package/src/scanner/project-scanner.js +242 -0
  143. package/src/ui/diff-display.js +91 -0
  144. package/src/ui/interactive-wizard.js +96 -0
  145. package/src/ui/user-review.js +211 -0
  146. package/src/ui/wizard-questions.js +188 -0
  147. package/src/utils/color-utils.js +70 -0
  148. package/src/utils/file-copier.js +188 -189
  149. package/src/utils/process-handler.js +97 -0
  150. package/src/writer/file-writer.js +86 -0
  151. package/stacks/blazor-azure/.claude/skills/level-2-domains/ai-agents/ai-system-architect.md +3 -3
  152. package/stacks/blazor-azure/.claude/skills/level-2-domains/backend/api-designer.md +59 -0
  153. package/stacks/blazor-azure/.claude/skills/level-2-domains/backend/dotnet-senior.md +45 -255
  154. package/stacks/blazor-azure/.claude/skills/level-2-domains/backend/ef-modeler.md +33 -88
  155. package/stacks/blazor-azure/.claude/skills/level-2-domains/backend/ms-agent-expert.md +25 -89
  156. package/stacks/blazor-azure/.claude/skills/level-2-domains/integrations/hangfire-orchestrator.md +64 -0
  157. package/stacks/blazor-azure/.morph/config/agents.json +879 -764
  158. package/stacks/blazor-azure/.morph/hooks/{pre-commit-tests.sh → pre-commit/tests-csharp.sh} +3 -2
  159. package/stacks/blazor-azure/.morph/templates/.gitkeep +0 -0
  160. package/stacks/blazor-azure/.morph/templates/infrastructure/github/workflows/cd-prod.yml.hbs +41 -0
  161. package/stacks/blazor-azure/.morph/templates/infrastructure/github/workflows/cd-staging.yml.hbs +24 -0
  162. package/stacks/blazor-azure/.morph/templates/infrastructure/github/workflows/ci-build.yml.hbs +23 -0
  163. package/stacks/nextjs-supabase/.claude/commands/morph-apply.md +221 -0
  164. package/stacks/nextjs-supabase/.claude/commands/morph-archive.md +79 -0
  165. package/stacks/nextjs-supabase/.claude/commands/morph-deploy.md +529 -0
  166. package/stacks/nextjs-supabase/.claude/commands/morph-infra.md +209 -0
  167. package/stacks/nextjs-supabase/.claude/commands/morph-preflight.md +227 -0
  168. package/stacks/nextjs-supabase/.claude/commands/morph-proposal.md +122 -0
  169. package/stacks/nextjs-supabase/.claude/commands/morph-status.md +86 -0
  170. package/stacks/nextjs-supabase/.claude/commands/morph-troubleshoot.md +122 -0
  171. package/stacks/nextjs-supabase/.claude/settings.local.json +6 -0
  172. package/stacks/nextjs-supabase/.claude/skills/level-2-domains/integrations/supabase-expert.md +30 -150
  173. package/stacks/nextjs-supabase/.morph/config/agents.json +345 -345
  174. package/stacks/nextjs-supabase/.morph/hooks/pre-commit/tests-typescript.sh +61 -0
  175. package/stacks/nextjs-supabase/.morph/templates/.gitkeep +0 -0
  176. package/stacks/nextjs-supabase/.morph/templates/infrastructure/github/workflows/cd-prod.yml.hbs +22 -0
  177. package/stacks/nextjs-supabase/.morph/templates/infrastructure/github/workflows/cd-staging.yml.hbs +22 -0
  178. package/stacks/nextjs-supabase/.morph/templates/infrastructure/github/workflows/ci-build.yml.hbs +35 -0
  179. package/stacks/nextjs-supabase/README.md +6 -15
  180. package/bin/render-template.js +0 -303
  181. package/bin/semantic-detect-agents.js +0 -247
  182. package/bin/validate-agents-skills.js +0 -257
  183. package/bin/validate-agents.js +0 -70
  184. package/bin/validate-phase.js +0 -263
  185. package/docs/examples.md +0 -328
  186. package/scripts/reorganize-skills.cjs +0 -175
  187. package/scripts/validate-agents-structure.cjs +0 -52
  188. package/scripts/validate-skills.cjs +0 -180
  189. package/src/commands/deploy.js +0 -780
  190. package/src/lib/continuous-validator.js +0 -421
  191. package/src/lib/decision-constraint-loader.js +0 -109
  192. package/src/lib/design-system-scaffolder.js +0 -299
  193. package/src/lib/hook-executor.js +0 -257
  194. package/src/lib/mockup-generator.js +0 -366
  195. package/src/lib/ui-detector.js +0 -350
  196. package/stacks/blazor-azure/.azure/README.md +0 -293
  197. package/stacks/blazor-azure/.azure/docs/azure-devops-setup.md +0 -454
  198. package/stacks/blazor-azure/.azure/docs/branch-strategy.md +0 -398
  199. package/stacks/blazor-azure/.azure/docs/local-development.md +0 -515
  200. package/stacks/blazor-azure/.azure/pipelines/pipeline-variables.yml +0 -34
  201. package/stacks/blazor-azure/.azure/pipelines/prod-pipeline.yml +0 -319
  202. package/stacks/blazor-azure/.azure/pipelines/staging-pipeline.yml +0 -234
  203. package/stacks/blazor-azure/.azure/pipelines/templates/build-dotnet.yml +0 -75
  204. package/stacks/blazor-azure/.azure/pipelines/templates/deploy-app-service.yml +0 -94
  205. package/stacks/blazor-azure/.azure/pipelines/templates/deploy-container-app.yml +0 -120
  206. package/stacks/blazor-azure/.azure/pipelines/templates/infra-deploy.yml +0 -90
  207. package/stacks/blazor-azure/.claude/settings.local.json +0 -15
  208. package/stacks/blazor-azure/.morph/docs/STORY-DRIVEN-DEVELOPMENT.md +0 -392
  209. package/stacks/blazor-azure/.morph/docs/workflows/design-impl.md +0 -37
  210. package/stacks/blazor-azure/.morph/docs/workflows/enforcement-pipeline.md +0 -668
  211. package/stacks/blazor-azure/.morph/docs/workflows/fast-track.md +0 -29
  212. package/stacks/blazor-azure/.morph/docs/workflows/full-morph.md +0 -76
  213. package/stacks/blazor-azure/.morph/docs/workflows/standard.md +0 -44
  214. package/stacks/blazor-azure/.morph/docs/workflows/ui-refresh.md +0 -39
  215. package/stacks/blazor-azure/.morph/examples/api-nextjs/README.md +0 -241
  216. package/stacks/blazor-azure/.morph/examples/api-nextjs/contracts.ts +0 -307
  217. package/stacks/blazor-azure/.morph/examples/api-nextjs/spec.md +0 -399
  218. package/stacks/blazor-azure/.morph/examples/api-nextjs/tasks.md +0 -168
  219. package/stacks/blazor-azure/.morph/examples/micro-saas/README.md +0 -125
  220. package/stacks/blazor-azure/.morph/examples/micro-saas/contracts.cs +0 -358
  221. package/stacks/blazor-azure/.morph/examples/micro-saas/decisions.md +0 -246
  222. package/stacks/blazor-azure/.morph/examples/micro-saas/spec.md +0 -236
  223. package/stacks/blazor-azure/.morph/examples/micro-saas/tasks.md +0 -150
  224. package/stacks/blazor-azure/.morph/examples/multi-agent/README.md +0 -309
  225. package/stacks/blazor-azure/.morph/examples/multi-agent/contracts.cs +0 -433
  226. package/stacks/blazor-azure/.morph/examples/multi-agent/spec.md +0 -479
  227. package/stacks/blazor-azure/.morph/examples/multi-agent/tasks.md +0 -185
  228. package/stacks/blazor-azure/.morph/examples/scheduled-reports/decisions.md +0 -158
  229. package/stacks/blazor-azure/.morph/examples/scheduled-reports/proposal.md +0 -95
  230. package/stacks/blazor-azure/.morph/examples/scheduled-reports/spec.md +0 -267
  231. package/stacks/blazor-azure/.morph/examples/state-v3.json +0 -188
  232. package/stacks/blazor-azure/.morph/hooks/README.md +0 -348
  233. package/stacks/blazor-azure/.morph/hooks/pre-commit-agents.sh +0 -24
  234. package/stacks/blazor-azure/.morph/hooks/pre-commit-all.sh +0 -48
  235. package/stacks/blazor-azure/.morph/hooks/pre-commit-specs.sh +0 -49
  236. package/stacks/blazor-azure/.morph/hooks/task-completed.js +0 -73
  237. package/stacks/blazor-azure/.morph/hooks/teammate-idle.js +0 -68
  238. package/stacks/blazor-azure/.morph/standards/agent-framework-blazor-ui.md +0 -359
  239. package/stacks/blazor-azure/.morph/standards/agent-framework-production.md +0 -410
  240. package/stacks/blazor-azure/.morph/standards/agent-framework-setup.md +0 -413
  241. package/stacks/blazor-azure/.morph/standards/agent-framework-workflows.md +0 -349
  242. package/stacks/blazor-azure/.morph/standards/agent-teams-workflow.md +0 -474
  243. package/stacks/blazor-azure/.morph/standards/architecture.md +0 -325
  244. package/stacks/blazor-azure/.morph/standards/azure.md +0 -605
  245. package/stacks/blazor-azure/.morph/standards/coding.md +0 -377
  246. package/stacks/blazor-azure/.morph/standards/dotnet10-migration.md +0 -520
  247. package/stacks/blazor-azure/.morph/standards/fluent-ui-setup.md +0 -590
  248. package/stacks/blazor-azure/.morph/standards/migration-guide.md +0 -514
  249. package/stacks/blazor-azure/.morph/standards/passkeys-auth.md +0 -423
  250. package/stacks/blazor-azure/.morph/standards/vector-search-rag.md +0 -536
  251. package/stacks/blazor-azure/.morph/templates/CONTEXT-FEATURE.md +0 -276
  252. package/stacks/blazor-azure/.morph/templates/CONTEXT.md +0 -170
  253. package/stacks/blazor-azure/.morph/templates/FluentDesignTheme.cs +0 -149
  254. package/stacks/blazor-azure/.morph/templates/MudTheme.cs +0 -281
  255. package/stacks/blazor-azure/.morph/templates/agent.cs +0 -163
  256. package/stacks/blazor-azure/.morph/templates/clarify-questions.md +0 -159
  257. package/stacks/blazor-azure/.morph/templates/component.razor +0 -239
  258. package/stacks/blazor-azure/.morph/templates/contracts/Commands.cs +0 -74
  259. package/stacks/blazor-azure/.morph/templates/contracts/Entities.cs +0 -25
  260. package/stacks/blazor-azure/.morph/templates/contracts/Queries.cs +0 -74
  261. package/stacks/blazor-azure/.morph/templates/contracts/README.md +0 -74
  262. package/stacks/blazor-azure/.morph/templates/contracts.cs +0 -217
  263. package/stacks/blazor-azure/.morph/templates/decisions.md +0 -123
  264. package/stacks/blazor-azure/.morph/templates/design-system.css +0 -226
  265. package/stacks/blazor-azure/.morph/templates/infra/.dockerignore.example +0 -89
  266. package/stacks/blazor-azure/.morph/templates/infra/Dockerfile.example +0 -82
  267. package/stacks/blazor-azure/.morph/templates/infra/README.md +0 -286
  268. package/stacks/blazor-azure/.morph/templates/infra/app-insights.bicep +0 -63
  269. package/stacks/blazor-azure/.morph/templates/infra/app-service.bicep +0 -164
  270. package/stacks/blazor-azure/.morph/templates/infra/azure-pipelines-deploy.yml +0 -480
  271. package/stacks/blazor-azure/.morph/templates/infra/container-app-env.bicep +0 -49
  272. package/stacks/blazor-azure/.morph/templates/infra/container-app.bicep +0 -156
  273. package/stacks/blazor-azure/.morph/templates/infra/deploy-checklist.md +0 -426
  274. package/stacks/blazor-azure/.morph/templates/infra/deploy.ps1 +0 -229
  275. package/stacks/blazor-azure/.morph/templates/infra/deploy.sh +0 -208
  276. package/stacks/blazor-azure/.morph/templates/infra/key-vault.bicep +0 -91
  277. package/stacks/blazor-azure/.morph/templates/infra/main.bicep +0 -189
  278. package/stacks/blazor-azure/.morph/templates/infra/parameters.dev.json +0 -29
  279. package/stacks/blazor-azure/.morph/templates/infra/parameters.prod.json +0 -29
  280. package/stacks/blazor-azure/.morph/templates/infra/parameters.staging.json +0 -29
  281. package/stacks/blazor-azure/.morph/templates/infra/sql-database.bicep +0 -103
  282. package/stacks/blazor-azure/.morph/templates/infra/storage.bicep +0 -106
  283. package/stacks/blazor-azure/.morph/templates/integrations/asaas-client.cs +0 -387
  284. package/stacks/blazor-azure/.morph/templates/integrations/asaas-webhook.cs +0 -351
  285. package/stacks/blazor-azure/.morph/templates/integrations/azure-identity-config.cs +0 -288
  286. package/stacks/blazor-azure/.morph/templates/integrations/clerk-config.cs +0 -258
  287. package/stacks/blazor-azure/.morph/templates/job.cs +0 -171
  288. package/stacks/blazor-azure/.morph/templates/migration.cs +0 -83
  289. package/stacks/blazor-azure/.morph/templates/proposal.md +0 -141
  290. package/stacks/blazor-azure/.morph/templates/recap.md +0 -94
  291. package/stacks/blazor-azure/.morph/templates/repository.cs +0 -141
  292. package/stacks/blazor-azure/.morph/templates/saas/subscription.cs +0 -347
  293. package/stacks/blazor-azure/.morph/templates/saas/tenant.cs +0 -338
  294. package/stacks/blazor-azure/.morph/templates/service.cs +0 -139
  295. package/stacks/blazor-azure/.morph/templates/simulation.md +0 -353
  296. package/stacks/blazor-azure/.morph/templates/spec.md +0 -149
  297. package/stacks/blazor-azure/.morph/templates/sprint-status.yaml +0 -68
  298. package/stacks/blazor-azure/.morph/templates/state.template.json +0 -222
  299. package/stacks/blazor-azure/.morph/templates/story.md +0 -143
  300. package/stacks/blazor-azure/.morph/templates/tasks.md +0 -257
  301. package/stacks/blazor-azure/.morph/templates/test.cs +0 -239
  302. package/stacks/blazor-azure/.morph/templates/ui-components.md +0 -362
  303. package/stacks/blazor-azure/.morph/templates/ui-design-system.md +0 -286
  304. package/stacks/blazor-azure/.morph/templates/ui-flows.md +0 -336
  305. package/stacks/blazor-azure/.morph/templates/ui-mockups.md +0 -133
  306. package/stacks/nextjs-supabase/.morph/docs/easypanel-setup.md +0 -169
  307. package/stacks/nextjs-supabase/.morph/docs/supabase-mcp-setup.md +0 -247
  308. package/stacks/nextjs-supabase/.morph/examples/crud-nextjs-supabase/README.md +0 -697
  309. package/stacks/nextjs-supabase/.morph/examples/crud-nextjs-supabase/spec.md +0 -85
  310. package/stacks/nextjs-supabase/.morph/examples/crud-nextjs-supabase/tasks.md +0 -86
  311. package/stacks/nextjs-supabase/.morph/examples/saas-nextjs-supabase/README.md +0 -498
  312. package/stacks/nextjs-supabase/.morph/examples/saas-nextjs-supabase/decisions.md +0 -121
  313. package/stacks/nextjs-supabase/.morph/examples/saas-nextjs-supabase/spec.md +0 -138
  314. package/stacks/nextjs-supabase/.morph/examples/saas-nextjs-supabase/tasks.md +0 -162
  315. package/stacks/nextjs-supabase/.morph/standards/easypanel-deploy.md +0 -191
  316. package/stacks/nextjs-supabase/.morph/standards/nextjs-patterns.md +0 -193
  317. package/stacks/nextjs-supabase/.morph/standards/supabase-auth.md +0 -171
  318. package/stacks/nextjs-supabase/.morph/standards/supabase-pgvector.md +0 -164
  319. package/stacks/nextjs-supabase/.morph/standards/supabase-rls.md +0 -179
  320. package/stacks/nextjs-supabase/.morph/standards/supabase-storage.md +0 -148
  321. package/stacks/nextjs-supabase/.morph/templates/contracts.cs +0 -173
  322. package/stacks/nextjs-supabase/.morph/templates/contracts.ts +0 -168
  323. package/stacks/nextjs-supabase/.morph/templates/decisions.md +0 -115
  324. package/stacks/nextjs-supabase/.morph/templates/dockerfile-api.dockerfile +0 -38
  325. package/stacks/nextjs-supabase/.morph/templates/dockerfile-web.dockerfile +0 -48
  326. package/stacks/nextjs-supabase/.morph/templates/proposal.md +0 -145
  327. package/stacks/nextjs-supabase/.morph/templates/recap.md +0 -134
  328. package/stacks/nextjs-supabase/.morph/templates/rls-policy.sql +0 -57
  329. package/stacks/nextjs-supabase/.morph/templates/spec.md +0 -231
  330. package/stacks/nextjs-supabase/.morph/templates/supabase-migration.sql +0 -100
  331. package/stacks/nextjs-supabase/.morph/templates/tasks.md +0 -257
  332. /package/src/lib/{design-system-generator.js → generators/design-system-generator.js} +0 -0
  333. /package/src/lib/{learning-system.js → learning/learning-system.js} +0 -0
@@ -0,0 +1,1304 @@
1
+ # MORPH-SPEC v3.0 - Execution Flow & Code Architecture
2
+
3
+ > How the finished framework will actually work: runtime flows, code execution paths, and concrete examples
4
+
5
+ **Status:** Technical Design ✅
6
+ **Last Updated:** 2026-02-18
7
+
8
+ ---
9
+
10
+ ## Table of Contents
11
+
12
+ - [Runtime Architecture](#runtime-architecture)
13
+ - [Execution Scenarios](#execution-scenarios)
14
+ - [Code Flow Examples](#code-flow-examples)
15
+ - [State Management Flow](#state-management-flow)
16
+ - [Key Classes & Interfaces](#key-classes--interfaces)
17
+
18
+ ---
19
+
20
+ ## Runtime Architecture
21
+
22
+ ### Component Interaction Map
23
+
24
+ ```
25
+ ┌─────────────────────────────────────────────────────────────────┐
26
+ │ MORPH-SPEC v3.0 Runtime │
27
+ └─────────────────────────────────────────────────────────────────┘
28
+
29
+ USER COMMAND: morph-spec feature create user-auth --request "..."
30
+
31
+ ┌──────────────────────────────────────────────────────────────────┐
32
+ │ CLI Layer (src/commands/feature-create.js) │
33
+ ├──────────────────────────────────────────────────────────────────┤
34
+ │ 1. Parse arguments │
35
+ │ 2. Validate inputs │
36
+ │ 3. Load project context (state.json, agents.json) │
37
+ └──────────────────────────────────────────────────────────────────┘
38
+
39
+ ┌──────────────────────────────────────────────────────────────────┐
40
+ │ Workflow Detection Layer (src/lib/workflow-detector.js) │
41
+ ├──────────────────────────────────────────────────────────────────┤
42
+ │ 1. Analyze request keywords │
43
+ │ 2. Estimate complexity (files, lines) │
44
+ │ 3. Check trust history (state.json) │
45
+ │ 4. Score workflows (fast-track/standard/full-morph/fusion/etc.) │
46
+ │ 5. Return: { workflow: 'full-morph', confidence: 0.92 } │
47
+ └──────────────────────────────────────────────────────────────────┘
48
+
49
+ ┌──────────────────────────────────────────────────────────────────┐
50
+ │ Thread Manager (src/lib/thread-manager.js) │
51
+ ├──────────────────────────────────────────────────────────────────┤
52
+ │ 1. Create feature entry in state.json │
53
+ │ 2. Determine thread type (parallel/fusion/long-running) │
54
+ │ 3. Initialize thread metrics tracking │
55
+ │ 4. Create thread instances: │
56
+ │ - If P-Thread → spawn 3-5 parallel threads │
57
+ │ - If F-Thread → spawn N fusion threads │
58
+ │ - If base → single thread │
59
+ │ 5. Register threads in state.json │
60
+ └──────────────────────────────────────────────────────────────────┘
61
+
62
+ ┌──────────────────────────────────────────────────────────────────┐
63
+ │ Context Optimizer (src/lib/context-optimizer.js) │
64
+ ├──────────────────────────────────────────────────────────────────┤
65
+ │ 1. Detect feature type (feature/bug/refactor/design/infra) │
66
+ │ 2. Load appropriate prime file (.morph/context/*-prime.md) │
67
+ │ 3. Select relevant standards (3-5 files vs all 71) │
68
+ │ 4. Select relevant agents (domain-specific) │
69
+ │ 5. Check for context bundles (resume from checkpoint?) │
70
+ │ 6. Return optimized context (~500 tokens vs 23K) │
71
+ └──────────────────────────────────────────────────────────────────┘
72
+
73
+ ┌──────────────────────────────────────────────────────────────────┐
74
+ │ Agent Executor (src/lib/agent-executor.js) │
75
+ ├──────────────────────────────────────────────────────────────────┤
76
+ │ 1. Load agents.json hierarchy │
77
+ │ 2. Identify required agents (workflow-detector output) │
78
+ │ 3. For each agent: │
79
+ │ a. Render HOP template (meta-prompts/squad-leader.md) │
80
+ │ b. Inject context (primed context from optimizer) │
81
+ │ c. Inject standards (selective list) │
82
+ │ d. Inject tasks (from tasks.json) │
83
+ │ 4. Return agent configuration objects │
84
+ └──────────────────────────────────────────────────────────────────┘
85
+
86
+ ┌──────────────────────────────────────────────────────────────────┐
87
+ │ Parallel Executor (src/lib/parallel-executor.js) - IF P-THREAD │
88
+ ├──────────────────────────────────────────────────────────────────┤
89
+ │ 1. Analyze task dependencies (tasks.json) │
90
+ │ 2. Create parallel groups: │
91
+ │ - PG001: [T001, T002, T003] (independent) │
92
+ │ - PG002: [T004, T005] (depends on PG001) │
93
+ │ 3. For each parallel group: │
94
+ │ a. Spawn N threads (max-concurrent=3) │
95
+ │ b. Execute simultaneously │
96
+ │ c. Collect results in thread-coordinator │
97
+ │ 4. Wait for all threads in group before next group │
98
+ └──────────────────────────────────────────────────────────────────┘
99
+
100
+ ┌──────────────────────────────────────────────────────────────────┐
101
+ │ Fusion Aggregator (src/lib/fusion-executor.js) - IF F-THREAD │
102
+ ├──────────────────────────────────────────────────────────────────┤
103
+ │ 1. Spawn 3 agents with same prompt (different models) │
104
+ │ 2. Execute in parallel (sandbox environments) │
105
+ │ 3. Collect 3 design outputs │
106
+ │ 4. Score each output: │
107
+ │ - Checkpoint pass rate (40%) │
108
+ │ - Code quality (30%) │
109
+ │ - Completeness (30%) │
110
+ │ 5. Aggregate results: │
111
+ │ - best-of-n: Pick highest score │
112
+ │ - consensus: Merge common elements │
113
+ │ - manual-select: Present all to user │
114
+ │ 6. Return winning design │
115
+ └──────────────────────────────────────────────────────────────────┘
116
+
117
+ ┌──────────────────────────────────────────────────────────────────┐
118
+ │ Validators Layer (Tier 4 Agents) │
119
+ ├──────────────────────────────────────────────────────────────────┤
120
+ │ HOOK TRIGGER: After each tool call, every 3 tasks, pre-commit │
121
+ │ │
122
+ │ 1. architecture-expert: │
123
+ │ - Check DI patterns (IDbContextFactory vs DbContext) │
124
+ │ - Validate async/await usage │
125
+ │ - Verify lifecycle scopes │
126
+ │ │
127
+ │ 2. security-expert: │
128
+ │ - Scan for SQL injection patterns │
129
+ │ - Check for XSS vulnerabilities │
130
+ │ - Detect exposed secrets │
131
+ │ │
132
+ │ 3. packages-validator: │
133
+ │ - Check NuGet package conflicts │
134
+ │ - Verify .NET 10 compatibility │
135
+ │ │
136
+ │ 4. design-system-validator: │
137
+ │ - Validate CSS palette compliance │
138
+ │ - Check spacing and typography │
139
+ │ │
140
+ │ Return: { passed: true/false, violations: [...] } │
141
+ └──────────────────────────────────────────────────────────────────┘
142
+
143
+ ┌──────────────────────────────────────────────────────────────────┐
144
+ │ Checkpoint Manager (Every 3 tasks) │
145
+ ├──────────────────────────────────────────────────────────────────┤
146
+ │ 1. Detect checkpoint trigger (task count % 3 === 0) │
147
+ │ 2. Run all validators in parallel │
148
+ │ 3. Collect results │
149
+ │ 4. If failures: │
150
+ │ a. Save artifact trail (screenshots, logs) │
151
+ │ b. Mark task as NOT done │
152
+ │ c. Provide feedback to agent │
153
+ │ d. Retry (max 3 times) │
154
+ │ 5. If success: │
155
+ │ a. Update state.json (checkpointPassRate) │
156
+ │ b. Create context bundle (compress checkpoint) │
157
+ │ c. Continue to next tasks │
158
+ └──────────────────────────────────────────────────────────────────┘
159
+
160
+ ┌──────────────────────────────────────────────────────────────────┐
161
+ │ Stop Hook Executor (IF L-THREAD) │
162
+ ├──────────────────────────────────────────────────────────────────┤
163
+ │ TRIGGER: Agent attempts to stop after 30 min of work │
164
+ │ │
165
+ │ 1. Agent sends stop signal │
166
+ │ 2. Stop hook intercepts: │
167
+ │ framework/hooks/agent-stop/validate-and-continue.js │
168
+ │ 3. Run validation: │
169
+ │ a. Execute checkpoint validators │
170
+ │ b. Check task completion │
171
+ │ c. Verify deliverables │
172
+ │ 4. Decision: │
173
+ │ - If valid → return { action: 'complete' } │
174
+ │ - If invalid → return { action: 'continue', feedback: '...' } │
175
+ │ 5. Agent continues with feedback (loop up to 5 times) │
176
+ │ 6. Enables hours-long autonomous runs │
177
+ └──────────────────────────────────────────────────────────────────┘
178
+
179
+ ┌──────────────────────────────────────────────────────────────────┐
180
+ │ Trust Manager (src/lib/trust-manager.js) │
181
+ ├──────────────────────────────────────────────────────────────────┤
182
+ │ 1. Track checkpoint pass rates per feature │
183
+ │ 2. Calculate trust level: │
184
+ │ - <80% pass rate → low │
185
+ │ - 80-90% → medium │
186
+ │ - 90-95% → high │
187
+ │ - >95% → maximum │
188
+ │ 3. Update state.json trustConfig │
189
+ │ 4. Enable auto-approvals based on trust: │
190
+ │ - medium → auto-approve design gate │
191
+ │ - high → auto-approve design + tasks gates │
192
+ │ - maximum → zero-touch workflow │
193
+ └──────────────────────────────────────────────────────────────────┘
194
+
195
+ ┌──────────────────────────────────────────────────────────────────┐
196
+ │ Approval Gates (src/commands/advance-phase.js) │
197
+ ├──────────────────────────────────────────────────────────────────┤
198
+ │ 1. Check current phase (design/tasks) │
199
+ │ 2. Query trust-manager for trust level │
200
+ │ 3. Decision: │
201
+ │ - If trust >= threshold → AUTO-APPROVE │
202
+ │ • Log: "Auto-approved (high trust, 95% pass rate)" │
203
+ │ • Advance phase immediately │
204
+ │ - If trust < threshold → PAUSE │
205
+ │ • Present outputs to user │
206
+ │ • Wait for approval │
207
+ │ 4. Update state.json approval status │
208
+ └──────────────────────────────────────────────────────────────────┘
209
+
210
+ ┌──────────────────────────────────────────────────────────────────┐
211
+ │ Analytics Engine (Continuous) │
212
+ ├──────────────────────────────────────────────────────────────────┤
213
+ │ RUNS IN BACKGROUND: Tracks metrics throughout execution │
214
+ │ │
215
+ │ 1. Thread Analytics: │
216
+ │ - Tool calls count (Read, Write, Edit, Bash) │
217
+ │ - Thread duration (start to completion) │
218
+ │ - Parallel efficiency (actual vs theoretical) │
219
+ │ │
220
+ │ 2. Context Analytics: │
221
+ │ - Token usage per thread (peak, average) │
222
+ │ - Optimization opportunities detection │
223
+ │ - MCP server usage tracking │
224
+ │ │
225
+ │ 3. Project Analytics: │
226
+ │ - Feature completion trends │
227
+ │ - Agent performance (pass rates) │
228
+ │ - Trust level progression │
229
+ │ │
230
+ │ 4. Real-time Updates: │
231
+ │ - Update state.json threadMetrics │
232
+ │ - Generate recommendations │
233
+ │ - Trigger alerts (if efficiency < 50%) │
234
+ └──────────────────────────────────────────────────────────────────┘
235
+
236
+ ┌──────────────────────────────────────────────────────────────────┐
237
+ │ Learning System (Post-completion) │
238
+ ├──────────────────────────────────────────────────────────────────┤
239
+ │ 1. Analyze feature outcome (success/failure) │
240
+ │ 2. Extract patterns: │
241
+ │ - What worked? (capture as 'success' pattern) │
242
+ │ - What failed? (capture as 'avoid' pattern) │
243
+ │ - Any optimizations? (capture as 'optimization' pattern) │
244
+ │ 3. Update framework/memory/patterns-learned.md │
245
+ │ 4. Promote patterns to standards if repeated 3+ times │
246
+ └──────────────────────────────────────────────────────────────────┘
247
+
248
+ OUTPUT: Feature Complete + Analytics + Patterns
249
+ ```
250
+
251
+ ---
252
+
253
+ ## Execution Scenarios
254
+
255
+ ### Scenario 1: Standard Feature (Sequential Execution)
256
+
257
+ **User Request:** `morph-spec feature create user-pagination --request "add pagination to users table"`
258
+
259
+ #### Step-by-Step Execution:
260
+
261
+ ```javascript
262
+ // 1. CLI Entry Point
263
+ // src/commands/feature-create.js
264
+ async function createFeature(name, request) {
265
+ const projectState = await loadState();
266
+
267
+ // 2. Workflow Detection
268
+ const workflow = await workflowDetector.analyze({
269
+ request,
270
+ keywords: extractKeywords(request), // ['pagination', 'users', 'table']
271
+ estimatedFiles: 5,
272
+ estimatedLines: 200
273
+ });
274
+
275
+ console.log(`✓ Detected workflow: ${workflow.type} (${workflow.confidence}% confidence)`);
276
+ // Output: ✓ Detected workflow: standard (87% confidence)
277
+
278
+ // 3. Create Feature State
279
+ const feature = await stateManager.createFeature({
280
+ name: 'user-pagination',
281
+ workflow: workflow.type,
282
+ phase: 'proposal',
283
+ request
284
+ });
285
+
286
+ // 4. Context Optimization
287
+ const context = await contextOptimizer.prime({
288
+ featureType: 'feature', // detected from request
289
+ domain: 'backend', // detected from 'pagination' keyword
290
+ standards: [
291
+ 'backend/dotnet/core.md',
292
+ 'backend/api/minimal-api.md',
293
+ 'frontend/blazor/state.md'
294
+ ]
295
+ });
296
+
297
+ console.log(`✓ Context optimized: ${context.tokens} tokens (vs 23K baseline)`);
298
+ // Output: ✓ Context optimized: 4,200 tokens (vs 23K baseline)
299
+
300
+ // 5. Thread Creation (Base Thread - Sequential)
301
+ const thread = await threadManager.createThread({
302
+ feature: feature.name,
303
+ type: 'base',
304
+ agent: 'dotnet-senior',
305
+ context
306
+ });
307
+
308
+ // 6. Agent Execution
309
+ const agentConfig = await agentExecutor.configure({
310
+ agent: 'dotnet-senior',
311
+ hopTemplate: 'meta-prompts/backend-squad.md',
312
+ variables: {
313
+ SQUAD_NAME: 'Backend',
314
+ MISSION: 'Implement pagination for users table',
315
+ STANDARDS: context.standards,
316
+ TASKS: [] // Will be populated after TASKS phase
317
+ }
318
+ });
319
+
320
+ // 7. Execute Workflow Phases
321
+ await executePhase('proposal', agentConfig);
322
+ // Creates: .morph/features/user-pagination/proposal.md
323
+
324
+ await executePhase('design', agentConfig);
325
+ // Creates: spec.md, contracts, decisions.md
326
+
327
+ // 8. Approval Gate (Design)
328
+ const trustLevel = await trustManager.getTrustLevel(feature.name);
329
+ if (trustLevel === 'high' || trustLevel === 'maximum') {
330
+ console.log('✓ Design auto-approved (high trust, 94% historical pass rate)');
331
+ await stateManager.approveGate(feature.name, 'design');
332
+ } else {
333
+ console.log('⏸️ Paused for design approval (medium trust)');
334
+ return; // User must approve manually
335
+ }
336
+
337
+ await executePhase('tasks', agentConfig);
338
+ // Creates: tasks.json with dependency graph
339
+
340
+ // 9. Approval Gate (Tasks)
341
+ // Same logic as design gate
342
+
343
+ await executePhase('implement', agentConfig);
344
+ // Executes tasks sequentially: T001 → T002 → T003 → ...
345
+
346
+ // 10. Checkpoints (Every 3 tasks)
347
+ // After T003, T006, T009:
348
+ await checkpointManager.validate({
349
+ feature: feature.name,
350
+ validators: ['architecture-expert', 'security-expert', 'packages-validator']
351
+ });
352
+
353
+ // 11. Analytics Update (Continuous)
354
+ await analyticsEngine.recordMetrics({
355
+ feature: feature.name,
356
+ threadId: thread.id,
357
+ toolCalls: 87,
358
+ duration: '1h 23m',
359
+ checkpointPassRate: 1.0
360
+ });
361
+
362
+ console.log('✅ Feature complete: user-pagination');
363
+ }
364
+ ```
365
+
366
+ ---
367
+
368
+ ### Scenario 2: Parallel Feature (P-Thread Execution)
369
+
370
+ **User Request:** `morph-spec feature create user-auth --request "implement complete authentication system with JWT"`
371
+
372
+ #### Step-by-Step Execution:
373
+
374
+ ```javascript
375
+ // 1. Workflow Detection
376
+ const workflow = await workflowDetector.analyze({
377
+ request: "implement complete authentication system with JWT",
378
+ keywords: ['authentication', 'complete', 'system'],
379
+ estimatedFiles: 15,
380
+ estimatedLines: 800
381
+ });
382
+
383
+ console.log(`✓ Detected workflow: ${workflow.type}`);
384
+ // Output: ✓ Detected workflow: full-morph (92% confidence)
385
+
386
+ // 2. Thread Manager Decision
387
+ const threadType = await threadManager.determineType({
388
+ workflow: 'full-morph',
389
+ complexity: 'high',
390
+ estimatedFiles: 15
391
+ });
392
+
393
+ console.log(`✓ Thread type: ${threadType}`);
394
+ // Output: ✓ Thread type: parallel (P-Thread with 3 squads)
395
+
396
+ // 3. Parallel Executor Setup
397
+ const parallelConfig = {
398
+ maxConcurrent: 3,
399
+ squads: [
400
+ {
401
+ name: 'Backend',
402
+ leader: 'dotnet-senior',
403
+ members: ['ef-modeler', 'api-designer', 'event-architect'],
404
+ tasks: ['T001', 'T002', 'T003', 'T004', 'T005'] // Backend tasks
405
+ },
406
+ {
407
+ name: 'Frontend',
408
+ leader: 'blazor-builder',
409
+ members: ['css-specialist'],
410
+ tasks: ['T006', 'T007', 'T008'] // UI tasks
411
+ },
412
+ {
413
+ name: 'Infrastructure',
414
+ leader: 'bicep-architect',
415
+ members: ['azure-architect'],
416
+ tasks: ['T009', 'T010'] // Infra tasks
417
+ }
418
+ ]
419
+ };
420
+
421
+ // 4. Spawn Parallel Threads
422
+ const threads = await parallelExecutor.spawn(parallelConfig);
423
+
424
+ console.log(`✓ Spawned ${threads.length} parallel threads:`);
425
+ // Output:
426
+ // ✓ Spawned 3 parallel threads:
427
+ // - thread-001: Backend (dotnet-senior) - 5 tasks
428
+ // - thread-002: Frontend (blazor-builder) - 3 tasks
429
+ // - thread-003: Infrastructure (bicep-architect) - 2 tasks
430
+
431
+ // 5. Execute Squads in Parallel
432
+ await Promise.all([
433
+ executeSquad(threads[0]), // Backend: async, parallel execution
434
+ executeSquad(threads[1]), // Frontend: async, parallel execution
435
+ executeSquad(threads[2]) // Infrastructure: async, parallel execution
436
+ ]);
437
+
438
+ // 6. Real-time Monitoring
439
+ // Analytics engine tracks all threads simultaneously:
440
+ setInterval(async () => {
441
+ const status = await threadManager.getStatus('user-auth');
442
+ console.log(`
443
+ 📊 Parallel Execution Status:
444
+ - Backend: ${status.threads[0].progress}% (T003/T005 complete)
445
+ - Frontend: ${status.threads[1].progress}% (T007/T008 complete)
446
+ - Infrastructure: ${status.threads[2].progress}% (T010/T010 complete ✅)
447
+ - Parallel Efficiency: ${status.parallelEfficiency}%
448
+ `);
449
+ }, 30000); // Every 30 seconds
450
+
451
+ // 7. Thread Coordination
452
+ // When one squad finishes early, it can help others:
453
+ await threadCoordinator.balanceLoad({
454
+ feature: 'user-auth',
455
+ strategy: 'work-stealing' // Idle threads pick up remaining tasks
456
+ });
457
+
458
+ // 8. Aggregation
459
+ await threadCoordinator.waitAll('user-auth');
460
+
461
+ console.log('✅ All squads complete. Merging results...');
462
+
463
+ const results = await threadCoordinator.mergeResults({
464
+ threads: threads,
465
+ conflictResolution: 'last-write-wins' // or 'manual-review'
466
+ });
467
+
468
+ // 9. Final Validation
469
+ await checkpointManager.validate({
470
+ feature: 'user-auth',
471
+ validators: ['architecture-expert', 'security-expert'],
472
+ scope: 'full' // Check all files, not just deltas
473
+ });
474
+
475
+ console.log('✅ Feature complete: user-auth');
476
+ console.log(`📊 Metrics:
477
+ - Total Duration: 47 minutes
478
+ - Tool Calls: 247 (82/checkpoint avg)
479
+ - Parallel Efficiency: 78% (3 concurrent threads)
480
+ - Improvement: 2.8x faster than sequential
481
+ `);
482
+ ```
483
+
484
+ ---
485
+
486
+ ### Scenario 3: Fusion Feature (F-Thread for High Confidence)
487
+
488
+ **User Request:** `morph-spec feature create auth-system --request "design authentication (need high confidence)" --workflow=fusion`
489
+
490
+ #### Step-by-Step Execution:
491
+
492
+ ```javascript
493
+ // 1. Fusion Executor Setup
494
+ const fusionConfig = {
495
+ agentCount: 3,
496
+ models: ['opus-4.6', 'sonnet-4.5', 'sonnet-4.5'],
497
+ aggregationStrategy: 'best-of-n',
498
+ criteria: {
499
+ checkpointPassRate: 0.4, // 40% weight
500
+ codeQuality: 0.3, // 30% weight
501
+ completeness: 0.3 // 30% weight
502
+ }
503
+ };
504
+
505
+ // 2. Spawn 3 Fusion Threads
506
+ const fusionThreads = await fusionExecutor.spawn({
507
+ feature: 'auth-system',
508
+ phase: 'design',
509
+ prompt: 'Design authentication system with JWT tokens and refresh token rotation',
510
+ config: fusionConfig
511
+ });
512
+
513
+ console.log(`✓ Spawned ${fusionThreads.length} fusion threads (best-of-3)`);
514
+
515
+ // 3. Execute in Parallel (Sandboxed)
516
+ const designs = await Promise.all([
517
+ executeFusionThread(fusionThreads[0], 'opus-4.6'), // Agent 1: Approach A
518
+ executeFusionThread(fusionThreads[1], 'sonnet-4.5'), // Agent 2: Approach B
519
+ executeFusionThread(fusionThreads[2], 'sonnet-4.5') // Agent 3: Approach C
520
+ ]);
521
+
522
+ console.log(`✓ Generated 3 design approaches:`);
523
+ console.log(` - Design A (Opus): JWT with HttpOnly cookies + CSRF`);
524
+ console.log(` - Design B (Sonnet): JWT in Authorization header + XSS protection`);
525
+ console.log(` - Design C (Sonnet): Session-based with Redis`);
526
+
527
+ // 4. Validation & Scoring
528
+ const scores = await Promise.all(
529
+ designs.map(async (design, index) => {
530
+ // Run validators on each design
531
+ const validation = await checkpointManager.validate({
532
+ feature: `auth-system-design-${index}`,
533
+ validators: ['architecture-expert', 'security-expert'],
534
+ files: design.files
535
+ });
536
+
537
+ // Calculate scores
538
+ const checkpointScore = validation.passed ? 1.0 : 0.0;
539
+ const qualityScore = await codeAnalyzer.analyze(design.files);
540
+ const completenessScore = calculateCompleteness(design);
541
+
542
+ const totalScore =
543
+ checkpointScore * fusionConfig.criteria.checkpointPassRate +
544
+ qualityScore * fusionConfig.criteria.codeQuality +
545
+ completenessScore * fusionConfig.criteria.completeness;
546
+
547
+ return {
548
+ design,
549
+ scores: { checkpoint: checkpointScore, quality: qualityScore, completeness: completenessScore },
550
+ totalScore
551
+ };
552
+ })
553
+ );
554
+
555
+ console.log(`📊 Scoring Results:`);
556
+ scores.forEach((result, i) => {
557
+ console.log(` Design ${String.fromCharCode(65 + i)}: ${(result.totalScore * 100).toFixed(1)}%`);
558
+ console.log(` - Checkpoint: ${(result.scores.checkpoint * 100).toFixed(0)}%`);
559
+ console.log(` - Quality: ${(result.scores.quality * 100).toFixed(0)}%`);
560
+ console.log(` - Completeness: ${(result.scores.completeness * 100).toFixed(0)}%`);
561
+ });
562
+
563
+ // 5. Aggregation (best-of-n)
564
+ const winner = scores.reduce((best, current) =>
565
+ current.totalScore > best.totalScore ? current : best
566
+ );
567
+
568
+ console.log(`✅ Winner: Design ${String.fromCharCode(65 + scores.indexOf(winner))} (${(winner.totalScore * 100).toFixed(1)}% score)`);
569
+
570
+ // 6. Apply Winning Design
571
+ await stateManager.saveDesign({
572
+ feature: 'auth-system',
573
+ design: winner.design,
574
+ metadata: {
575
+ fusionStrategy: 'best-of-n',
576
+ candidates: designs.length,
577
+ winnerScore: winner.totalScore,
578
+ alternatives: scores.filter(s => s !== winner).map(s => ({
579
+ score: s.totalScore,
580
+ files: s.design.files
581
+ }))
582
+ }
583
+ });
584
+
585
+ // 7. Continue with Standard Workflow
586
+ console.log('✓ Design selected. Continuing with implementation...');
587
+ await executePhase('implement', {
588
+ design: winner.design,
589
+ context: optimizedContext
590
+ });
591
+ ```
592
+
593
+ ---
594
+
595
+ ### Scenario 4: Long-Running Autonomous (L-Thread with Stop Hooks)
596
+
597
+ **User Request:** `morph-spec feature create large-refactor --request "refactor entire data layer (autonomous, run for hours)"`
598
+
599
+ #### Step-by-Step Execution:
600
+
601
+ ```javascript
602
+ // 1. Workflow Detection
603
+ const workflow = await workflowDetector.analyze({
604
+ request: "refactor entire data layer (autonomous, run for hours)",
605
+ keywords: ['autonomous', 'entire', 'hours', 'refactor'],
606
+ estimatedFiles: 25,
607
+ estimatedLines: 1200
608
+ });
609
+
610
+ console.log(`✓ Detected workflow: long-running (95% confidence)`);
611
+
612
+ // 2. L-Thread Setup with Stop Hooks
613
+ const lThreadConfig = {
614
+ maxDuration: '4 hours',
615
+ stopHookInterval: '30min',
616
+ maxRetries: 5,
617
+ validationCommand: 'morph-spec validate feature large-refactor',
618
+ autonomousMode: true
619
+ };
620
+
621
+ // 3. Start L-Thread
622
+ const thread = await threadManager.createThread({
623
+ feature: 'large-refactor',
624
+ type: 'long-running',
625
+ config: lThreadConfig
626
+ });
627
+
628
+ console.log('✓ L-Thread started. Running autonomously...');
629
+ console.log(' - Stop hooks enabled (every 30 min)');
630
+ console.log(' - Max duration: 4 hours');
631
+ console.log(' - You will be notified only when complete or if critical issues arise');
632
+
633
+ // 4. Autonomous Execution Loop
634
+ let iteration = 0;
635
+ let continueExecution = true;
636
+
637
+ while (continueExecution && iteration < 8) { // Max 8 iterations (4 hours / 30 min)
638
+ iteration++;
639
+ console.log(`\n🔄 Iteration ${iteration} started (${new Date().toLocaleTimeString()})`);
640
+
641
+ // Agent works for 30 minutes
642
+ const workResult = await agentExecutor.executeAutonomous({
643
+ thread: thread.id,
644
+ duration: '30min',
645
+ tasks: getRemainingTasks('large-refactor')
646
+ });
647
+
648
+ console.log(` ✓ Work completed: ${workResult.tasksCompleted} tasks, ${workResult.toolCalls} tool calls`);
649
+
650
+ // 5. Stop Hook Triggered (After 30 min)
651
+ console.log(` 🪝 Stop hook triggered...`);
652
+
653
+ const validation = await stopHookExecutor.execute({
654
+ feature: 'large-refactor',
655
+ hookPath: 'framework/hooks/agent-stop/validate-and-continue.js',
656
+ context: {
657
+ iteration,
658
+ tasksCompleted: workResult.tasksCompleted,
659
+ totalTasks: getTotalTasks('large-refactor')
660
+ }
661
+ });
662
+
663
+ // 6. Validation Decision
664
+ if (validation.action === 'complete') {
665
+ console.log(` ✅ Validation passed. Feature complete!`);
666
+ continueExecution = false;
667
+ } else if (validation.action === 'continue') {
668
+ console.log(` ⚠️ Validation failed. Continuing with feedback:`);
669
+ console.log(` ${validation.feedback}`);
670
+
671
+ // Inject feedback into next iteration
672
+ await agentExecutor.injectFeedback({
673
+ thread: thread.id,
674
+ feedback: validation.feedback
675
+ });
676
+
677
+ // Check retry limit
678
+ if (validation.retries >= lThreadConfig.maxRetries) {
679
+ console.log(` ❌ Max retries (${lThreadConfig.maxRetries}) reached. Pausing for user intervention.`);
680
+ continueExecution = false;
681
+ await notifyUser('large-refactor', 'Max retries reached, manual review needed');
682
+ }
683
+ }
684
+
685
+ // 7. Analytics Update
686
+ await analyticsEngine.recordMetrics({
687
+ feature: 'large-refactor',
688
+ iteration,
689
+ toolCalls: workResult.toolCalls,
690
+ checkpointPassRate: validation.action === 'complete' ? 1.0 : 0.0
691
+ });
692
+ }
693
+
694
+ // 8. Final Report
695
+ const finalMetrics = await analyticsEngine.getFeatureMetrics('large-refactor');
696
+ console.log(`\n✅ L-Thread Complete`);
697
+ console.log(`📊 Final Metrics:`);
698
+ console.log(` - Total Duration: ${finalMetrics.duration}`);
699
+ console.log(` - Iterations: ${iteration}`);
700
+ console.log(` - Tool Calls: ${finalMetrics.totalToolCalls}`);
701
+ console.log(` - Autonomous Runtime: ${finalMetrics.autonomousPercentage}%`);
702
+ console.log(` - User Intervention: ${finalMetrics.userInterventions} times`);
703
+ ```
704
+
705
+ ---
706
+
707
+ ## Code Flow Examples
708
+
709
+ ### Example 1: Thread Manager Core Logic
710
+
711
+ ```javascript
712
+ // src/lib/thread-manager.js
713
+
714
+ class ThreadManager {
715
+ constructor(stateManager, analyticsEngine) {
716
+ this.stateManager = stateManager;
717
+ this.analyticsEngine = analyticsEngine;
718
+ this.activeThreads = new Map();
719
+ }
720
+
721
+ /**
722
+ * Create a new thread for a feature
723
+ * @param {Object} options - Thread configuration
724
+ * @returns {Promise<Thread>}
725
+ */
726
+ async createThread(options) {
727
+ const { feature, type, agent, context, config = {} } = options;
728
+
729
+ // Generate unique thread ID
730
+ const threadId = `thread-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
731
+
732
+ // Create thread object
733
+ const thread = {
734
+ id: threadId,
735
+ feature,
736
+ agent,
737
+ type, // 'base' | 'parallel' | 'fusion' | 'long-running' | 'zero-touch'
738
+ status: 'pending',
739
+ startedAt: new Date().toISOString(),
740
+ completedAt: null,
741
+ metrics: {
742
+ toolCalls: 0,
743
+ duration: null,
744
+ estimatedCompletion: this.estimateCompletion(type, context)
745
+ },
746
+ config
747
+ };
748
+
749
+ // Store in active threads map
750
+ this.activeThreads.set(threadId, thread);
751
+
752
+ // Persist to state.json
753
+ await this.stateManager.update({
754
+ threads: {
755
+ [threadId]: thread
756
+ }
757
+ });
758
+
759
+ // Start analytics tracking
760
+ await this.analyticsEngine.startTracking(threadId);
761
+
762
+ return thread;
763
+ }
764
+
765
+ /**
766
+ * Determine thread type based on workflow and complexity
767
+ * @param {Object} criteria - Decision criteria
768
+ * @returns {Promise<string>} Thread type
769
+ */
770
+ async determineType(criteria) {
771
+ const { workflow, complexity, estimatedFiles, parallelizable = true } = criteria;
772
+
773
+ // Decision tree for thread type
774
+ if (workflow === 'fusion' || criteria.highConfidenceNeeded) {
775
+ return 'fusion';
776
+ }
777
+
778
+ if (workflow === 'long-running' || criteria.autonomousMode) {
779
+ return 'long-running';
780
+ }
781
+
782
+ if (workflow === 'zero-touch' || criteria.trustLevel === 'maximum') {
783
+ return 'zero-touch';
784
+ }
785
+
786
+ // Check if parallel execution is beneficial
787
+ if (parallelizable && estimatedFiles >= 10 && complexity === 'high') {
788
+ return 'parallel';
789
+ }
790
+
791
+ // Default to base thread (sequential)
792
+ return 'base';
793
+ }
794
+
795
+ /**
796
+ * Get status of all threads for a feature
797
+ * @param {string} featureName - Feature name
798
+ * @returns {Promise<Object>} Status object
799
+ */
800
+ async getStatus(featureName) {
801
+ const state = await this.stateManager.getFeature(featureName);
802
+ const threads = Object.values(state.threads || {}).filter(
803
+ t => t.feature === featureName
804
+ );
805
+
806
+ // Calculate aggregated metrics
807
+ const totalToolCalls = threads.reduce((sum, t) => sum + t.metrics.toolCalls, 0);
808
+ const avgParallelThreads = threads.length > 1 ? threads.length : 1;
809
+
810
+ return {
811
+ feature: featureName,
812
+ threads: threads.map(t => ({
813
+ id: t.id,
814
+ agent: t.agent,
815
+ status: t.status,
816
+ progress: this.calculateProgress(t),
817
+ metrics: t.metrics
818
+ })),
819
+ aggregated: {
820
+ totalToolCalls,
821
+ avgParallelThreads,
822
+ parallelEfficiency: this.calculateEfficiency(threads)
823
+ }
824
+ };
825
+ }
826
+
827
+ /**
828
+ * Calculate parallel execution efficiency
829
+ * @param {Array<Thread>} threads - Thread instances
830
+ * @returns {number} Efficiency percentage (0-100)
831
+ */
832
+ calculateEfficiency(threads) {
833
+ if (threads.length <= 1) return 100; // Sequential is 100% efficient by definition
834
+
835
+ const maxDuration = Math.max(...threads.map(t => this.parseDuration(t.metrics.duration)));
836
+ const totalDuration = threads.reduce((sum, t) => sum + this.parseDuration(t.metrics.duration), 0);
837
+
838
+ // Theoretical speedup: totalDuration / maxDuration
839
+ // Actual speedup accounts for coordination overhead
840
+ const theoreticalSpeedup = totalDuration / maxDuration;
841
+ const actualSpeedup = threads.length; // Number of parallel threads
842
+
843
+ return Math.round((actualSpeedup / theoreticalSpeedup) * 100);
844
+ }
845
+
846
+ async killThread(threadId) {
847
+ const thread = this.activeThreads.get(threadId);
848
+ if (!thread) throw new Error(`Thread ${threadId} not found`);
849
+
850
+ thread.status = 'killed';
851
+ thread.completedAt = new Date().toISOString();
852
+
853
+ await this.stateManager.update({
854
+ threads: {
855
+ [threadId]: thread
856
+ }
857
+ });
858
+
859
+ this.activeThreads.delete(threadId);
860
+ }
861
+ }
862
+
863
+ export default ThreadManager;
864
+ ```
865
+
866
+ ---
867
+
868
+ ### Example 2: Context Optimizer Implementation
869
+
870
+ ```javascript
871
+ // src/lib/context-optimizer.js
872
+
873
+ class ContextOptimizer {
874
+ constructor(mcpOptimizer, standardsLoader, templateRegistry) {
875
+ this.mcpOptimizer = mcpOptimizer;
876
+ this.standardsLoader = standardsLoader;
877
+ this.templateRegistry = templateRegistry;
878
+ }
879
+
880
+ /**
881
+ * Prime context for a feature
882
+ * @param {Object} options - Priming options
883
+ * @returns {Promise<Object>} Optimized context
884
+ */
885
+ async prime(options) {
886
+ const { featureType, domain, agents = [], standards = [] } = options;
887
+
888
+ // 1. Select appropriate prime file
889
+ const primeFile = this.selectPrimeFile(featureType);
890
+ const primeContent = await fs.readFile(primeFile, 'utf-8');
891
+
892
+ // 2. MCP Hygiene - Remove unused servers
893
+ const activeMcpServers = await this.mcpOptimizer.detectActive();
894
+ const unusedServers = await this.mcpOptimizer.findUnused();
895
+
896
+ console.log(` MCP Hygiene: ${activeMcpServers.length} active, ${unusedServers.length} unused`);
897
+
898
+ // 3. Selective Standards Loading
899
+ const relevantStandards = standards.length > 0
900
+ ? standards
901
+ : await this.selectStandards(domain, featureType);
902
+
903
+ const standardsContent = await Promise.all(
904
+ relevantStandards.map(s => this.standardsLoader.load(s))
905
+ );
906
+
907
+ // 4. Select Agents
908
+ const relevantAgents = agents.length > 0
909
+ ? agents
910
+ : await this.selectAgents(domain, featureType);
911
+
912
+ // 5. Calculate token counts
913
+ const tokens = {
914
+ prime: this.countTokens(primeContent),
915
+ standards: standardsContent.reduce((sum, s) => sum + this.countTokens(s), 0),
916
+ agents: relevantAgents.length * 50, // Estimate
917
+ total: 0
918
+ };
919
+ tokens.total = tokens.prime + tokens.standards + tokens.agents;
920
+
921
+ console.log(` Context Optimized:`);
922
+ console.log(` - Prime file: ${tokens.prime} tokens`);
923
+ console.log(` - Standards: ${tokens.standards} tokens (${relevantStandards.length} files)`);
924
+ console.log(` - Agents: ${tokens.agents} tokens (${relevantAgents.length} agents)`);
925
+ console.log(` - Total: ${tokens.total} tokens (vs 23K baseline = ${Math.round((1 - tokens.total/23000) * 100)}% reduction)`);
926
+
927
+ return {
928
+ prime: primeContent,
929
+ standards: relevantStandards,
930
+ standardsContent,
931
+ agents: relevantAgents,
932
+ mcpServers: activeMcpServers,
933
+ tokens
934
+ };
935
+ }
936
+
937
+ /**
938
+ * Select prime file based on feature type
939
+ * @param {string} featureType - Type of feature (feature/bug/refactor/design/infra)
940
+ * @returns {string} Path to prime file
941
+ */
942
+ selectPrimeFile(featureType) {
943
+ const primeFiles = {
944
+ feature: '.morph/context/feature-prime.md',
945
+ bug: '.morph/context/bug-prime.md',
946
+ refactor: '.morph/context/refactor-prime.md',
947
+ design: '.morph/context/design-prime.md',
948
+ infra: '.morph/context/infra-prime.md'
949
+ };
950
+
951
+ return primeFiles[featureType] || primeFiles.feature;
952
+ }
953
+
954
+ /**
955
+ * Select relevant standards based on domain
956
+ * @param {string} domain - Primary domain (backend/frontend/infrastructure/etc.)
957
+ * @param {string} featureType - Feature type
958
+ * @returns {Promise<Array<string>>} List of standard file paths
959
+ */
960
+ async selectStandards(domain, featureType) {
961
+ const domainMap = {
962
+ backend: [
963
+ 'core/coding.md',
964
+ 'core/architecture.md',
965
+ 'backend/dotnet/core.md',
966
+ 'backend/api/minimal-api.md'
967
+ ],
968
+ frontend: [
969
+ 'core/coding.md',
970
+ 'frontend/blazor/lifecycle.md',
971
+ 'frontend/design-system/naming.md'
972
+ ],
973
+ infrastructure: [
974
+ 'core/coding.md',
975
+ 'infrastructure/azure/bicep-patterns.md',
976
+ 'infrastructure/docker/dockerfile.md'
977
+ ],
978
+ data: [
979
+ 'core/coding.md',
980
+ 'backend/database/ef-core.md',
981
+ 'backend/database/migrations.md'
982
+ ]
983
+ };
984
+
985
+ return domainMap[domain] || domainMap.backend;
986
+ }
987
+
988
+ /**
989
+ * Create context bundle for checkpoint
990
+ * @param {string} featureName - Feature name
991
+ * @param {number} checkpoint - Checkpoint number
992
+ * @returns {Promise<Object>} Bundle metadata
993
+ */
994
+ async createBundle(featureName, checkpoint) {
995
+ const state = await stateManager.getFeature(featureName);
996
+
997
+ // Compress context into bundle
998
+ const bundle = {
999
+ bundleId: `${featureName}-checkpoint-${checkpoint}`,
1000
+ timestamp: new Date().toISOString(),
1001
+ compressedContext: {
1002
+ decisions: state.decisions || [],
1003
+ artifacts: state.artifacts || [],
1004
+ tasksCompleted: state.tasks.filter(t => t.status === 'done').map(t => t.id),
1005
+ nextSteps: state.tasks.filter(t => t.status === 'pending').slice(0, 3)
1006
+ },
1007
+ fullContextPath: `.morph/bundles/${featureName}-checkpoint-${checkpoint}.json`,
1008
+ replayTokens: 0 // Will be calculated
1009
+ };
1010
+
1011
+ // Save full context to file
1012
+ await fs.writeFile(
1013
+ bundle.fullContextPath,
1014
+ JSON.stringify(state, null, 2),
1015
+ 'utf-8'
1016
+ );
1017
+
1018
+ // Calculate replay tokens (compressed vs full)
1019
+ const fullTokens = this.countTokens(JSON.stringify(state));
1020
+ const compressedTokens = this.countTokens(JSON.stringify(bundle.compressedContext));
1021
+
1022
+ bundle.replayTokens = compressedTokens;
1023
+ bundle.savings = Math.round((1 - compressedTokens / fullTokens) * 100);
1024
+
1025
+ console.log(` ✓ Context bundle created: ${bundle.bundleId}`);
1026
+ console.log(` - Full context: ${fullTokens} tokens`);
1027
+ console.log(` - Compressed: ${compressedTokens} tokens`);
1028
+ console.log(` - Savings: ${bundle.savings}%`);
1029
+
1030
+ return bundle;
1031
+ }
1032
+
1033
+ countTokens(text) {
1034
+ // Rough estimation: 1 token ≈ 4 characters
1035
+ return Math.ceil(text.length / 4);
1036
+ }
1037
+ }
1038
+
1039
+ export default ContextOptimizer;
1040
+ ```
1041
+
1042
+ ---
1043
+
1044
+ ## State Management Flow
1045
+
1046
+ ### state.json Structure (Runtime)
1047
+
1048
+ ```json
1049
+ {
1050
+ "version": "3.0.0",
1051
+ "project": {
1052
+ "name": "MyApp",
1053
+ "type": "blazor-server",
1054
+ "createdAt": "2026-02-18T10:00:00Z",
1055
+ "updatedAt": "2026-02-18T14:30:00Z"
1056
+ },
1057
+
1058
+ "threads": {
1059
+ "thread-001": {
1060
+ "id": "thread-001",
1061
+ "feature": "user-auth",
1062
+ "agent": "dotnet-senior",
1063
+ "type": "parallel",
1064
+ "status": "running",
1065
+ "startedAt": "2026-02-18T10:05:00Z",
1066
+ "completedAt": null,
1067
+ "metrics": {
1068
+ "toolCalls": 42,
1069
+ "duration": null,
1070
+ "estimatedCompletion": "2026-02-18T11:30:00Z"
1071
+ }
1072
+ },
1073
+ "thread-002": {
1074
+ "id": "thread-002",
1075
+ "feature": "user-auth",
1076
+ "agent": "blazor-builder",
1077
+ "type": "parallel",
1078
+ "status": "running",
1079
+ "startedAt": "2026-02-18T10:05:00Z",
1080
+ "completedAt": null,
1081
+ "metrics": {
1082
+ "toolCalls": 28,
1083
+ "duration": null,
1084
+ "estimatedCompletion": "2026-02-18T11:15:00Z"
1085
+ }
1086
+ }
1087
+ },
1088
+
1089
+ "features": {
1090
+ "user-auth": {
1091
+ "name": "user-auth",
1092
+ "workflow": "full-morph",
1093
+ "phase": "implement",
1094
+ "status": "active",
1095
+ "request": "implement complete authentication system with JWT",
1096
+ "createdAt": "2026-02-18T10:00:00Z",
1097
+
1098
+ "threadMetrics": {
1099
+ "totalToolCalls": 247,
1100
+ "threadDuration": "2h 15m",
1101
+ "maxParallelThreads": 3,
1102
+ "avgParallelThreads": 2.1,
1103
+ "checkpointPassRate": 1.0
1104
+ },
1105
+
1106
+ "trustConfig": {
1107
+ "level": "high",
1108
+ "autoApprove": {
1109
+ "design": true,
1110
+ "tasks": false
1111
+ },
1112
+ "reason": "95% checkpoint pass rate on similar features",
1113
+ "history": [
1114
+ { "feature": "product-catalog", "passRate": 1.0, "timestamp": "2026-02-15T14:00:00Z" },
1115
+ { "feature": "order-mgmt", "passRate": 0.95, "timestamp": "2026-02-16T16:00:00Z" }
1116
+ ]
1117
+ },
1118
+
1119
+ "contextBundles": [
1120
+ {
1121
+ "bundleId": "user-auth-checkpoint-1",
1122
+ "checkpoint": 1,
1123
+ "timestamp": "2026-02-18T11:00:00Z",
1124
+ "path": ".morph/bundles/user-auth-checkpoint-1.json",
1125
+ "replayTokens": 12000,
1126
+ "savings": 85
1127
+ }
1128
+ ],
1129
+
1130
+ "tasks": [
1131
+ {
1132
+ "id": "T001",
1133
+ "description": "Create User entity",
1134
+ "status": "done",
1135
+ "agent": "ef-modeler",
1136
+ "thread": "thread-001",
1137
+ "completedAt": "2026-02-18T10:30:00Z"
1138
+ },
1139
+ {
1140
+ "id": "T002",
1141
+ "description": "Create AuthController",
1142
+ "status": "in_progress",
1143
+ "agent": "api-designer",
1144
+ "thread": "thread-001",
1145
+ "startedAt": "2026-02-18T10:31:00Z"
1146
+ }
1147
+ ],
1148
+
1149
+ "approvals": {
1150
+ "design": {
1151
+ "status": "auto-approved",
1152
+ "reason": "high trust level (95% pass rate)",
1153
+ "timestamp": "2026-02-18T10:45:00Z"
1154
+ },
1155
+ "tasks": {
1156
+ "status": "pending",
1157
+ "reason": "awaiting user approval",
1158
+ "timestamp": null
1159
+ }
1160
+ }
1161
+ }
1162
+ },
1163
+
1164
+ "metadata": {
1165
+ "totalFeatures": 12,
1166
+ "completedFeatures": 9,
1167
+ "activeFeatures": 3,
1168
+ "totalCostEstimated": 0,
1169
+ "totalTimeSpent": 0,
1170
+ "lastUpdated": "2026-02-18T14:30:00Z"
1171
+ }
1172
+ }
1173
+ ```
1174
+
1175
+ ### State Transitions
1176
+
1177
+ ```javascript
1178
+ // State machine for feature phases
1179
+ const phaseTransitions = {
1180
+ 'proposal': ['setup'],
1181
+ 'setup': ['uiux', 'design'],
1182
+ 'uiux': ['design'],
1183
+ 'design': ['clarify'], // Only if approved
1184
+ 'clarify': ['tasks'],
1185
+ 'tasks': ['implement'], // Only if approved
1186
+ 'implement': ['sync', 'archived'],
1187
+ 'sync': ['archived']
1188
+ };
1189
+
1190
+ // State updates flow
1191
+ async function advancePhase(featureName, nextPhase) {
1192
+ const state = await stateManager.getFeature(featureName);
1193
+
1194
+ // 1. Validate transition
1195
+ if (!phaseTransitions[state.phase].includes(nextPhase)) {
1196
+ throw new Error(`Invalid transition: ${state.phase} → ${nextPhase}`);
1197
+ }
1198
+
1199
+ // 2. Check approval gates
1200
+ if (nextPhase === 'clarify' && state.approvals.design.status !== 'approved') {
1201
+ throw new Error('Design gate not approved');
1202
+ }
1203
+
1204
+ if (nextPhase === 'implement' && state.approvals.tasks.status !== 'approved') {
1205
+ throw new Error('Tasks gate not approved');
1206
+ }
1207
+
1208
+ // 3. Update state
1209
+ await stateManager.update({
1210
+ features: {
1211
+ [featureName]: {
1212
+ phase: nextPhase,
1213
+ updatedAt: new Date().toISOString()
1214
+ }
1215
+ }
1216
+ });
1217
+
1218
+ console.log(`✓ Phase advanced: ${state.phase} → ${nextPhase}`);
1219
+ }
1220
+ ```
1221
+
1222
+ ---
1223
+
1224
+ ## Key Classes & Interfaces
1225
+
1226
+ ### Core Interfaces
1227
+
1228
+ ```typescript
1229
+ // src/types/thread.ts
1230
+ interface Thread {
1231
+ id: string;
1232
+ feature: string;
1233
+ agent: string;
1234
+ type: 'base' | 'parallel' | 'fusion' | 'long-running' | 'zero-touch';
1235
+ status: 'pending' | 'running' | 'completed' | 'failed' | 'killed';
1236
+ startedAt: string; // ISO8601
1237
+ completedAt: string | null;
1238
+ metrics: ThreadMetrics;
1239
+ config?: Record<string, any>;
1240
+ }
1241
+
1242
+ interface ThreadMetrics {
1243
+ toolCalls: number;
1244
+ duration: string | null;
1245
+ estimatedCompletion: string | null;
1246
+ }
1247
+
1248
+ // src/types/context.ts
1249
+ interface OptimizedContext {
1250
+ prime: string;
1251
+ standards: string[];
1252
+ standardsContent: string[];
1253
+ agents: string[];
1254
+ mcpServers: string[];
1255
+ tokens: {
1256
+ prime: number;
1257
+ standards: number;
1258
+ agents: number;
1259
+ total: number;
1260
+ };
1261
+ }
1262
+
1263
+ // src/types/analytics.ts
1264
+ interface FeatureMetrics {
1265
+ feature: string;
1266
+ totalToolCalls: number;
1267
+ threadDuration: string;
1268
+ maxParallelThreads: number;
1269
+ avgParallelThreads: number;
1270
+ checkpointPassRate: number;
1271
+ }
1272
+ ```
1273
+
1274
+ ---
1275
+
1276
+ ## Summary
1277
+
1278
+ This execution flow document shows how MORPH-SPEC v3.0 will work in practice:
1279
+
1280
+ **Runtime Components:**
1281
+ - Thread Manager orchestrates concurrent execution
1282
+ - Context Optimizer reduces tokens by 30-40%
1283
+ - Parallel/Fusion Executors enable 3-5x throughput
1284
+ - Stop Hooks enable hours-long autonomous runs
1285
+ - Trust Manager enables 50% auto-approvals
1286
+ - Analytics Engine tracks everything in real-time
1287
+
1288
+ **State Flow:**
1289
+ - Centralized in state.json (single source of truth)
1290
+ - State machine enforces valid phase transitions
1291
+ - Approval gates check trust levels for auto-approval
1292
+ - Context bundles enable efficient session replay
1293
+
1294
+ **Code Architecture:**
1295
+ - Modular classes with clear responsibilities
1296
+ - Async/await throughout for parallel execution
1297
+ - Event-driven hooks for validation
1298
+ - Real-time metrics tracking
1299
+
1300
+ The finished framework will be a **highly orchestrated, data-driven system** that scales through parallelization, optimizes through context engineering, and improves through analytics - all while maintaining backward compatibility with v2.x.
1301
+
1302
+ ---
1303
+
1304
+ *MORPH-SPEC v3.0 Execution Flow - by Polymorphism Tech*