@polymorphism-tech/morph-spec 4.2.0 → 4.3.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 (132) hide show
  1. package/bin/morph-spec.js +283 -8
  2. package/bin/validate.js +4 -4
  3. package/docs/{v3.0 → next-generation}/AGENTS.md +1 -1
  4. package/docs/next-generation/CONTEXT-OPTIMIZATION.md +267 -0
  5. package/docs/next-generation/EXECUTION-FLOW.md +274 -0
  6. package/docs/next-generation/META-PROMPTS.md +235 -0
  7. package/docs/next-generation/MIGRATION-GUIDE.md +253 -0
  8. package/docs/next-generation/THREAD-MANAGEMENT.md +240 -0
  9. package/package.json +5 -5
  10. package/src/commands/agents/agents-fuse.js +96 -0
  11. package/src/commands/agents/micro-agent.js +112 -0
  12. package/src/commands/agents/spawn-team.js +69 -4
  13. package/src/commands/agents/squad-template.js +146 -0
  14. package/src/commands/analytics/analytics.js +176 -0
  15. package/src/commands/context/context-prime.js +63 -0
  16. package/src/commands/context/core-four.js +54 -0
  17. package/src/commands/mcp/mcp.js +102 -0
  18. package/src/commands/project/detect-agents.js +1 -1
  19. package/src/commands/project/doctor.js +573 -356
  20. package/src/commands/project/init.js +1 -1
  21. package/src/commands/project/update.js +1 -1
  22. package/src/commands/state/advance-phase.js +433 -416
  23. package/src/commands/templates/template-render.js +80 -1
  24. package/src/commands/threads/thread-template.js +103 -0
  25. package/src/commands/threads/threads.js +261 -0
  26. package/src/commands/trust/trust.js +205 -0
  27. package/src/{orchestrator.js → core/orchestrator.js} +8 -8
  28. package/src/core/state/state-manager.js +18 -2
  29. package/src/core/workflows/workflow-detector.js +100 -2
  30. package/src/lib/agents/micro-agent-factory.js +161 -0
  31. package/src/lib/analytics/analytics-engine.js +345 -0
  32. package/src/lib/checkpoints/checkpoint-hooks.js +293 -258
  33. package/src/lib/context/context-bundler.js +240 -0
  34. package/src/lib/context/context-optimizer.js +212 -0
  35. package/src/lib/context/context-tracker.js +273 -0
  36. package/src/lib/context/core-four-tracker.js +201 -0
  37. package/src/lib/context/mcp-optimizer.js +200 -0
  38. package/src/lib/execution/fusion-executor.js +304 -0
  39. package/src/lib/execution/parallel-executor.js +270 -0
  40. package/src/lib/generators/context-generator.js +3 -3
  41. package/src/lib/generators/recap-generator.js +2 -2
  42. package/src/lib/hooks/hook-executor.js +169 -0
  43. package/src/lib/hooks/stop-hook-executor.js +286 -0
  44. package/src/lib/hops/hop-composer.js +221 -0
  45. package/src/lib/threads/thread-coordinator.js +238 -0
  46. package/src/lib/threads/thread-manager.js +317 -0
  47. package/src/lib/tracking/artifact-trail.js +202 -0
  48. package/src/lib/trust/trust-manager.js +269 -0
  49. package/src/lib/validators/design-system/design-system-validator.js +2 -2
  50. package/src/lib/validators/validation-runner.js +6 -6
  51. package/stacks/blazor-azure/.morph/config/agents.json +72 -3
  52. package/stacks/nextjs-supabase/.morph/config/agents.json +3 -3
  53. package/CLAUDE.md +0 -993
  54. package/docs/llm-interaction-config.md +0 -735
  55. package/docs/v3.0/EXECUTION-FLOW.md +0 -1304
  56. package/src/commands/utils/migrate-state.js +0 -158
  57. package/src/commands/utils/upgrade.js +0 -346
  58. package/src/lib/validators/architecture-validator.js +0 -60
  59. package/src/lib/validators/content-validator.js +0 -164
  60. package/src/lib/validators/package-validator.js +0 -61
  61. package/src/lib/validators/ui-contrast-validator.js +0 -44
  62. package/stacks/blazor-azure/.claude/commands/morph-apply.md +0 -221
  63. package/stacks/blazor-azure/.claude/commands/morph-archive.md +0 -79
  64. package/stacks/blazor-azure/.claude/commands/morph-deploy.md +0 -529
  65. package/stacks/blazor-azure/.claude/commands/morph-infra.md +0 -209
  66. package/stacks/blazor-azure/.claude/commands/morph-preflight.md +0 -227
  67. package/stacks/blazor-azure/.claude/commands/morph-proposal.md +0 -122
  68. package/stacks/blazor-azure/.claude/commands/morph-status.md +0 -86
  69. package/stacks/blazor-azure/.claude/commands/morph-troubleshoot.md +0 -122
  70. package/stacks/blazor-azure/.claude/skills/level-0-meta/README.md +0 -7
  71. package/stacks/blazor-azure/.claude/skills/level-0-meta/code-review.md +0 -226
  72. package/stacks/blazor-azure/.claude/skills/level-0-meta/morph-checklist.md +0 -117
  73. package/stacks/blazor-azure/.claude/skills/level-0-meta/simulation-checklist.md +0 -77
  74. package/stacks/blazor-azure/.claude/skills/level-1-workflows/README.md +0 -7
  75. package/stacks/blazor-azure/.claude/skills/level-1-workflows/morph-replicate.md +0 -213
  76. package/stacks/blazor-azure/.claude/skills/level-1-workflows/phase-clarify.md +0 -131
  77. package/stacks/blazor-azure/.claude/skills/level-1-workflows/phase-design.md +0 -213
  78. package/stacks/blazor-azure/.claude/skills/level-1-workflows/phase-setup.md +0 -106
  79. package/stacks/blazor-azure/.claude/skills/level-1-workflows/phase-tasks.md +0 -164
  80. package/stacks/blazor-azure/.claude/skills/level-1-workflows/phase-uiux.md +0 -169
  81. package/stacks/blazor-azure/.claude/skills/level-2-domains/README.md +0 -14
  82. package/stacks/blazor-azure/.claude/skills/level-2-domains/ai-agents/ai-system-architect.md +0 -192
  83. package/stacks/blazor-azure/.claude/skills/level-2-domains/architecture/po-pm-advisor.md +0 -197
  84. package/stacks/blazor-azure/.claude/skills/level-2-domains/architecture/prompt-engineer.md +0 -189
  85. package/stacks/blazor-azure/.claude/skills/level-2-domains/architecture/seo-growth-hacker.md +0 -320
  86. package/stacks/blazor-azure/.claude/skills/level-2-domains/architecture/standards-architect.md +0 -156
  87. package/stacks/blazor-azure/.claude/skills/level-2-domains/backend/api-designer.md +0 -59
  88. package/stacks/blazor-azure/.claude/skills/level-2-domains/backend/dotnet-senior.md +0 -77
  89. package/stacks/blazor-azure/.claude/skills/level-2-domains/backend/ef-modeler.md +0 -58
  90. package/stacks/blazor-azure/.claude/skills/level-2-domains/backend/hangfire-orchestrator.md +0 -126
  91. package/stacks/blazor-azure/.claude/skills/level-2-domains/backend/ms-agent-expert.md +0 -45
  92. package/stacks/blazor-azure/.claude/skills/level-2-domains/frontend/blazor-builder.md +0 -210
  93. package/stacks/blazor-azure/.claude/skills/level-2-domains/frontend/nextjs-expert.md +0 -154
  94. package/stacks/blazor-azure/.claude/skills/level-2-domains/frontend/ui-ux-designer.md +0 -191
  95. package/stacks/blazor-azure/.claude/skills/level-2-domains/infrastructure/azure-architect.md +0 -142
  96. package/stacks/blazor-azure/.claude/skills/level-2-domains/infrastructure/azure-deploy-specialist.md +0 -699
  97. package/stacks/blazor-azure/.claude/skills/level-2-domains/infrastructure/bicep-architect.md +0 -126
  98. package/stacks/blazor-azure/.claude/skills/level-2-domains/infrastructure/container-specialist.md +0 -131
  99. package/stacks/blazor-azure/.claude/skills/level-2-domains/infrastructure/devops-engineer.md +0 -119
  100. package/stacks/blazor-azure/.claude/skills/level-2-domains/integrations/asaas-financial.md +0 -130
  101. package/stacks/blazor-azure/.claude/skills/level-2-domains/integrations/azure-identity.md +0 -142
  102. package/stacks/blazor-azure/.claude/skills/level-2-domains/integrations/clerk-auth.md +0 -108
  103. package/stacks/blazor-azure/.claude/skills/level-2-domains/integrations/hangfire-orchestrator.md +0 -64
  104. package/stacks/blazor-azure/.claude/skills/level-2-domains/integrations/resend-email.md +0 -119
  105. package/stacks/blazor-azure/.claude/skills/level-2-domains/quality/code-analyzer.md +0 -235
  106. package/stacks/blazor-azure/.claude/skills/level-2-domains/quality/testing-specialist.md +0 -126
  107. package/stacks/blazor-azure/.claude/skills/level-3-technologies/README.md +0 -7
  108. package/stacks/blazor-azure/.claude/skills/level-4-patterns/README.md +0 -7
  109. package/stacks/blazor-azure/.morph/archive/.gitkeep +0 -25
  110. package/stacks/blazor-azure/.morph/features/.gitkeep +0 -25
  111. package/stacks/blazor-azure/.morph/schemas/agent.schema.json +0 -296
  112. package/stacks/blazor-azure/.morph/schemas/tasks.schema.json +0 -220
  113. package/stacks/blazor-azure/.morph/specs/.gitkeep +0 -20
  114. package/stacks/blazor-azure/.morph/test-infra/example.bicep +0 -59
  115. package/stacks/nextjs-supabase/.claude/commands/morph-apply.md +0 -221
  116. package/stacks/nextjs-supabase/.claude/commands/morph-archive.md +0 -79
  117. package/stacks/nextjs-supabase/.claude/commands/morph-deploy.md +0 -529
  118. package/stacks/nextjs-supabase/.claude/commands/morph-infra.md +0 -209
  119. package/stacks/nextjs-supabase/.claude/commands/morph-preflight.md +0 -227
  120. package/stacks/nextjs-supabase/.claude/commands/morph-proposal.md +0 -122
  121. package/stacks/nextjs-supabase/.claude/commands/morph-status.md +0 -86
  122. package/stacks/nextjs-supabase/.claude/commands/morph-troubleshoot.md +0 -122
  123. package/stacks/nextjs-supabase/.claude/settings.local.json +0 -6
  124. package/stacks/nextjs-supabase/.claude/skills/level-2-domains/backend/dotnet-supabase.md +0 -244
  125. package/stacks/nextjs-supabase/.claude/skills/level-2-domains/frontend/nextjs-supabase.md +0 -335
  126. package/stacks/nextjs-supabase/.claude/skills/level-2-domains/infrastructure/easypanel-deployer.md +0 -189
  127. package/stacks/nextjs-supabase/.claude/skills/level-2-domains/integrations/supabase-expert.md +0 -50
  128. /package/docs/{v3.0 → next-generation}/ANALYSIS.md +0 -0
  129. /package/docs/{v3.0 → next-generation}/ARCHITECTURE.md +0 -0
  130. /package/docs/{v3.0 → next-generation}/FEATURES.md +0 -0
  131. /package/docs/{v3.0 → next-generation}/README.md +0 -0
  132. /package/docs/{v3.0 → next-generation}/ROADMAP.md +0 -0
@@ -1,1304 +0,0 @@
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*