@polymorphism-tech/morph-spec 4.6.0 → 4.7.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 (239) hide show
  1. package/README.md +394 -700
  2. package/docs/ARCHITECTURE.md +331 -0
  3. package/docs/CHEATSHEET.md +221 -0
  4. package/docs/COMMAND-FLOWS.md +368 -0
  5. package/docs/QUICKSTART.md +212 -0
  6. package/docs/examples/order-management/contracts.cs +84 -0
  7. package/docs/examples/order-management/proposal.md +24 -0
  8. package/docs/examples/order-management/spec.md +162 -0
  9. package/docs/plans/2026-02-23-ddd-architecture-refactor.md +1153 -0
  10. package/docs/plans/2026-02-23-ddd-nextsteps.md +682 -0
  11. package/docs/plans/2026-02-23-infra-architect-refactor.md +437 -0
  12. package/docs/plans/2026-02-23-nextjs-code-review-design.md +156 -0
  13. package/docs/plans/2026-02-23-nextjs-code-review-impl.md +1254 -0
  14. package/docs/plans/2026-02-23-nextjs-standards-design.md +149 -0
  15. package/docs/plans/2026-02-23-nextjs-standards-impl.md +1846 -0
  16. package/framework/agents/README.md +14 -14
  17. package/framework/agents/architecture/standards-architect.md +159 -159
  18. package/framework/agents/frontend/nextjs-expert.md +87 -127
  19. package/framework/agents/infrastructure/azure-architect.md +147 -147
  20. package/framework/agents/infrastructure/infra-architect.md +45 -0
  21. package/framework/agents.json +1145 -278
  22. package/framework/rules/frontend-standards.md +0 -3
  23. package/framework/rules/nextjs-standards.md +17 -0
  24. package/framework/skills/level-0-meta/code-review-nextjs/SKILL.md +147 -0
  25. package/framework/skills/level-0-meta/code-review-nextjs/references/review-example-nextjs.md +254 -0
  26. package/framework/skills/level-0-meta/tool-usage-guide/SKILL.md +3 -3
  27. package/framework/skills/level-1-workflows/phase-design/SKILL.md +45 -9
  28. package/framework/skills/level-1-workflows/phase-tasks/SKILL.md +38 -0
  29. package/framework/standards/STANDARDS.json +121 -0
  30. package/framework/standards/architecture/ddd/bounded-contexts.md +105 -0
  31. package/framework/standards/architecture/ddd/complexity-levels.md +108 -0
  32. package/framework/standards/architecture/ddd/ubiquitous-language.md +58 -0
  33. package/framework/standards/frontend/nextjs/app-router.md +123 -0
  34. package/framework/standards/frontend/nextjs/components.md +132 -0
  35. package/framework/standards/frontend/nextjs/data-fetching.md +126 -0
  36. package/framework/standards/frontend/nextjs/forms.md +128 -0
  37. package/framework/standards/frontend/nextjs/naming-conventions.md +67 -0
  38. package/framework/standards/frontend/nextjs/project-structure.md +102 -0
  39. package/framework/standards/frontend/nextjs/state-management.md +72 -0
  40. package/framework/standards/frontend/nextjs/testing.md +111 -0
  41. package/framework/templates/REGISTRY.json +538 -142
  42. package/framework/templates/code/dotnet/contracts/contracts-level1.cs +69 -0
  43. package/framework/templates/code/dotnet/contracts/contracts-level2.cs +86 -0
  44. package/framework/templates/code/dotnet/contracts/contracts-level3.cs +41 -0
  45. package/framework/templates/docs/spec.md +49 -0
  46. package/framework/templates/frontend/nextjs/Dockerfile.nextjs.hbs +43 -0
  47. package/framework/templates/frontend/nextjs/client-component.tsx.hbs +26 -0
  48. package/framework/templates/frontend/nextjs/env.mjs.hbs +32 -0
  49. package/framework/templates/frontend/nextjs/feature-form.tsx.hbs +56 -0
  50. package/framework/templates/frontend/nextjs/page.tsx.hbs +22 -0
  51. package/framework/templates/frontend/nextjs/tsconfig.json.hbs +26 -0
  52. package/framework/templates/frontend/nextjs/use-feature.ts.hbs +54 -0
  53. package/framework/templates/project-structure/dotnet-ddd.md +70 -0
  54. package/framework/workflows/docs/enforcement-pipeline.md +2 -1
  55. package/package.json +1 -1
  56. package/scripts/scan-nextjs.mjs +169 -0
  57. package/src/commands/project/doctor.js +52 -1
  58. package/src/commands/project/init.js +15 -1
  59. package/src/commands/project/update.js +6 -1
  60. package/src/lib/standards/standards-context-injector.js +5 -0
  61. package/src/lib/validators/nextjs/index.js +6 -0
  62. package/src/lib/validators/nextjs/next-component-validator.js +181 -0
  63. package/src/lib/validators/validation-runner.js +5 -0
  64. package/src/utils/agents-installer.js +14 -2
  65. package/.morph/.morphversion +0 -5
  66. package/.morph/analytics/threads-log.jsonl +0 -6
  67. package/.morph/config/config.json +0 -8
  68. package/.morph/framework/agents.json +0 -948
  69. package/.morph/framework/standards/STANDARDS.json +0 -812
  70. package/.morph/framework/standards/ai-agents/blazor-ui.md +0 -364
  71. package/.morph/framework/standards/ai-agents/production.md +0 -415
  72. package/.morph/framework/standards/ai-agents/setup.md +0 -418
  73. package/.morph/framework/standards/ai-agents/team-orchestration.md +0 -479
  74. package/.morph/framework/standards/ai-agents/workflows.md +0 -354
  75. package/.morph/framework/standards/architecture/ddd/aggregates.md +0 -120
  76. package/.morph/framework/standards/architecture/ddd/entities.md +0 -99
  77. package/.morph/framework/standards/architecture/ddd/value-objects.md +0 -124
  78. package/.morph/framework/standards/backend/api/minimal-api.md +0 -494
  79. package/.morph/framework/standards/backend/api/rest.md +0 -492
  80. package/.morph/framework/standards/backend/api/validation.md +0 -88
  81. package/.morph/framework/standards/backend/authentication/passkeys.md +0 -428
  82. package/.morph/framework/standards/backend/database/ef-core.md +0 -199
  83. package/.morph/framework/standards/backend/database/migrations.md +0 -393
  84. package/.morph/framework/standards/backend/database/postgresql/database.md +0 -352
  85. package/.morph/framework/standards/backend/database/repository-patterns.md +0 -528
  86. package/.morph/framework/standards/backend/database/vector-search-rag.md +0 -541
  87. package/.morph/framework/standards/backend/dotnet/async.md +0 -366
  88. package/.morph/framework/standards/backend/dotnet/core.md +0 -117
  89. package/.morph/framework/standards/backend/dotnet/di.md +0 -439
  90. package/.morph/framework/standards/backend/dotnet/program-cs-checklist.md +0 -92
  91. package/.morph/framework/standards/backend/integrations/asaas/asaas-api.md +0 -216
  92. package/.morph/framework/standards/backend/integrations/clerk/clerk-auth.md +0 -290
  93. package/.morph/framework/standards/backend/integrations/hangfire/hangfire-jobs.md +0 -350
  94. package/.morph/framework/standards/backend/integrations/resend/resend-email.md +0 -385
  95. package/.morph/framework/standards/context/analytics.md +0 -96
  96. package/.morph/framework/standards/context/bundles.md +0 -110
  97. package/.morph/framework/standards/context/priming.md +0 -78
  98. package/.morph/framework/standards/core/architecture.md +0 -185
  99. package/.morph/framework/standards/core/coding.md +0 -214
  100. package/.morph/framework/standards/core/git-branching-strategy.md +0 -403
  101. package/.morph/framework/standards/core/git.md +0 -185
  102. package/.morph/framework/standards/core/testing.md +0 -295
  103. package/.morph/framework/standards/data/nosql/blob-storage.md +0 -102
  104. package/.morph/framework/standards/data/nosql/cache/redis.md +0 -97
  105. package/.morph/framework/standards/data/nosql/cosmos-db.md +0 -118
  106. package/.morph/framework/standards/data/vector-search/azure-ai-search.md +0 -121
  107. package/.morph/framework/standards/data/vector-search/rag-chunking.md +0 -104
  108. package/.morph/framework/standards/frontend/blazor/design-checklist.md +0 -222
  109. package/.morph/framework/standards/frontend/blazor/fluent-ui-setup.md +0 -595
  110. package/.morph/framework/standards/frontend/blazor/fluent-ui.md +0 -137
  111. package/.morph/framework/standards/frontend/blazor/html-conversion.md +0 -184
  112. package/.morph/framework/standards/frontend/blazor/lifecycle.md +0 -195
  113. package/.morph/framework/standards/frontend/blazor/pitfalls.md +0 -198
  114. package/.morph/framework/standards/frontend/blazor/state.md +0 -191
  115. package/.morph/framework/standards/frontend/design-system/animations.md +0 -151
  116. package/.morph/framework/standards/frontend/design-system/naming.md +0 -64
  117. package/.morph/framework/standards/frontend/nextjs/nextjs-patterns.md +0 -215
  118. package/.morph/framework/standards/infrastructure/azure/azure.md +0 -624
  119. package/.morph/framework/standards/infrastructure/azure/bicep/bicep-patterns.md +0 -422
  120. package/.morph/framework/standards/infrastructure/azure/devops/azure-devops-setup.md +0 -516
  121. package/.morph/framework/standards/infrastructure/azure/devops/local-development.md +0 -520
  122. package/.morph/framework/standards/infrastructure/azure/services/functions.md +0 -486
  123. package/.morph/framework/standards/infrastructure/azure/services/service-bus.md +0 -459
  124. package/.morph/framework/standards/infrastructure/azure/services/storage.md +0 -407
  125. package/.morph/framework/standards/infrastructure/docker/easypanel-deploy.md +0 -196
  126. package/.morph/framework/standards/infrastructure/supabase/mcp-setup.md +0 -252
  127. package/.morph/framework/standards/infrastructure/supabase/supabase-auth.md +0 -176
  128. package/.morph/framework/standards/infrastructure/supabase/supabase-pgvector.md +0 -169
  129. package/.morph/framework/standards/infrastructure/supabase/supabase-rls.md +0 -184
  130. package/.morph/framework/standards/infrastructure/supabase/supabase-storage.md +0 -153
  131. package/.morph/framework/standards/integration/api/graphql.md +0 -91
  132. package/.morph/framework/standards/integration/api/grpc.md +0 -114
  133. package/.morph/framework/standards/integration/api/rest-design.md +0 -95
  134. package/.morph/framework/standards/integration/event-driven/cqrs.md +0 -101
  135. package/.morph/framework/standards/integration/event-driven/event-sourcing.md +0 -124
  136. package/.morph/framework/standards/integration/event-driven/service-bus.md +0 -95
  137. package/.morph/framework/standards/integration/mcp/mcp-tools.md +0 -384
  138. package/.morph/framework/standards/observability/logging.md +0 -131
  139. package/.morph/framework/standards/observability/metrics.md +0 -121
  140. package/.morph/framework/standards/observability/monitoring.md +0 -114
  141. package/.morph/framework/standards/observability/tracing.md +0 -132
  142. package/.morph/framework/standards/workflows/parallel-execution.md +0 -112
  143. package/.morph/framework/standards/workflows/thread-management.md +0 -113
  144. package/.morph/framework/templates/.idea/morph-templates.xml +0 -92
  145. package/.morph/framework/templates/.vscode/morph-templates.code-snippets +0 -186
  146. package/.morph/framework/templates/IDE-SNIPPETS.md +0 -266
  147. package/.morph/framework/templates/README.md +0 -814
  148. package/.morph/framework/templates/REGISTRY.json +0 -1492
  149. package/.morph/framework/templates/code/dotnet/backend/repository.cs +0 -141
  150. package/.morph/framework/templates/code/dotnet/backend/service.cs +0 -139
  151. package/.morph/framework/templates/code/dotnet/contracts/Commands.cs +0 -74
  152. package/.morph/framework/templates/code/dotnet/contracts/Entities.cs +0 -25
  153. package/.morph/framework/templates/code/dotnet/contracts/Queries.cs +0 -74
  154. package/.morph/framework/templates/code/dotnet/contracts/README.md +0 -74
  155. package/.morph/framework/templates/code/dotnet/contracts/api-contracts.cs +0 -173
  156. package/.morph/framework/templates/code/dotnet/contracts/contracts.cs +0 -217
  157. package/.morph/framework/templates/code/dotnet/contracts/contracts.cs.hbs +0 -172
  158. package/.morph/framework/templates/code/dotnet/database/migration.cs +0 -83
  159. package/.morph/framework/templates/code/dotnet/frontend/component.razor +0 -239
  160. package/.morph/framework/templates/code/dotnet/jobs/agent.cs +0 -163
  161. package/.morph/framework/templates/code/dotnet/jobs/job.cs +0 -171
  162. package/.morph/framework/templates/code/dotnet/test.cs +0 -239
  163. package/.morph/framework/templates/code/sql/rls-policy.sql +0 -57
  164. package/.morph/framework/templates/code/sql/supabase-migration.sql +0 -100
  165. package/.morph/framework/templates/code/sql/supabase-migration.template.sql +0 -113
  166. package/.morph/framework/templates/code/typescript/contracts.ts +0 -168
  167. package/.morph/framework/templates/context/CONTEXT-FEATURE.md +0 -276
  168. package/.morph/framework/templates/context/CONTEXT.md +0 -181
  169. package/.morph/framework/templates/docs/clarifications.md +0 -253
  170. package/.morph/framework/templates/docs/onboarding.md +0 -123
  171. package/.morph/framework/templates/docs/proposal.md +0 -182
  172. package/.morph/framework/templates/docs/schema-analysis.md +0 -119
  173. package/.morph/framework/templates/docs/spec.md +0 -149
  174. package/.morph/framework/templates/docs/ui-components.md +0 -124
  175. package/.morph/framework/templates/docs/ui-design-system.md +0 -76
  176. package/.morph/framework/templates/docs/ui-flows.md +0 -167
  177. package/.morph/framework/templates/docs/ui-mockups.md +0 -98
  178. package/.morph/framework/templates/docs/user-stories.md +0 -34
  179. package/.morph/framework/templates/examples/design-system-examples.md +0 -357
  180. package/.morph/framework/templates/examples/spec-examples.md +0 -90
  181. package/.morph/framework/templates/feature/decisions.md +0 -187
  182. package/.morph/framework/templates/feature/recap.md +0 -146
  183. package/.morph/framework/templates/feature/tasks.md +0 -199
  184. package/.morph/framework/templates/infrastructure/azure/Dockerfile.example +0 -82
  185. package/.morph/framework/templates/infrastructure/azure/README.md +0 -286
  186. package/.morph/framework/templates/infrastructure/azure/app-insights.bicep +0 -63
  187. package/.morph/framework/templates/infrastructure/azure/app-service.bicep +0 -164
  188. package/.morph/framework/templates/infrastructure/azure/container-app-env.bicep +0 -49
  189. package/.morph/framework/templates/infrastructure/azure/container-app.bicep +0 -156
  190. package/.morph/framework/templates/infrastructure/azure/deploy-checklist.md +0 -426
  191. package/.morph/framework/templates/infrastructure/azure/deploy.ps1 +0 -229
  192. package/.morph/framework/templates/infrastructure/azure/deploy.sh +0 -208
  193. package/.morph/framework/templates/infrastructure/azure/key-vault.bicep +0 -91
  194. package/.morph/framework/templates/infrastructure/azure/main.bicep +0 -189
  195. package/.morph/framework/templates/infrastructure/azure/parameters.dev.json +0 -29
  196. package/.morph/framework/templates/infrastructure/azure/parameters.prod.json +0 -29
  197. package/.morph/framework/templates/infrastructure/azure/parameters.staging.json +0 -29
  198. package/.morph/framework/templates/infrastructure/azure/sql-database.bicep +0 -103
  199. package/.morph/framework/templates/infrastructure/azure/storage.bicep +0 -106
  200. package/.morph/framework/templates/infrastructure/docker/Dockerfile.template +0 -58
  201. package/.morph/framework/templates/infrastructure/docker/docker-compose.template.yml +0 -67
  202. package/.morph/framework/templates/infrastructure/docker/dockerfile-api.dockerfile +0 -38
  203. package/.morph/framework/templates/infrastructure/docker/dockerfile-web.dockerfile +0 -48
  204. package/.morph/framework/templates/infrastructure/docker/easypanel.template.json +0 -54
  205. package/.morph/framework/templates/infrastructure/github/README.md +0 -593
  206. package/.morph/framework/templates/infrastructure/github/actions/azure-auth/action.yml.hbs +0 -22
  207. package/.morph/framework/templates/infrastructure/github/actions/docker-build-push/action.yml.hbs +0 -45
  208. package/.morph/framework/templates/infrastructure/github/actions/health-check/action.yml.hbs +0 -27
  209. package/.morph/framework/templates/infrastructure/github/workflows/deploy-azure-app-service.yml.hbs +0 -61
  210. package/.morph/framework/templates/infrastructure/github/workflows/deploy-easypanel.yml.hbs +0 -31
  211. package/.morph/framework/templates/infrastructure/github/workflows/docker-build-push.yml.hbs +0 -59
  212. package/.morph/framework/templates/infrastructure/github/workflows/dotnet-build.yml.hbs +0 -39
  213. package/.morph/framework/templates/integrations/asaas-client.cs +0 -387
  214. package/.morph/framework/templates/integrations/asaas-webhook.cs +0 -351
  215. package/.morph/framework/templates/integrations/azure-identity-config.cs +0 -288
  216. package/.morph/framework/templates/integrations/clerk-config.cs +0 -258
  217. package/.morph/framework/templates/meta-prompts/fusion/fusion-agent.md +0 -76
  218. package/.morph/framework/templates/meta-prompts/fusion/fusion-aggregator.md +0 -100
  219. package/.morph/framework/templates/meta-prompts/hops/hop-retry.md +0 -78
  220. package/.morph/framework/templates/meta-prompts/hops/hop-validation.md +0 -97
  221. package/.morph/framework/templates/meta-prompts/hops/hop-wrapper.md +0 -36
  222. package/.morph/framework/templates/meta-prompts/parallel-workers/parallel-coordinator.md +0 -113
  223. package/.morph/framework/templates/meta-prompts/parallel-workers/parallel-worker.md +0 -80
  224. package/.morph/framework/templates/meta-prompts/squad-leaders/backend-squad.md +0 -90
  225. package/.morph/framework/templates/meta-prompts/squad-leaders/frontend-squad.md +0 -126
  226. package/.morph/framework/templates/meta-prompts/squad-leaders/squad-leader.md +0 -43
  227. package/.morph/framework/templates/meta-prompts/validators/checkpoint-validator.md +0 -107
  228. package/.morph/framework/templates/meta-prompts/validators/pre-commit-validator.md +0 -95
  229. package/.morph/framework/templates/saas/subscription.cs +0 -347
  230. package/.morph/framework/templates/saas/tenant.cs +0 -338
  231. package/.morph/framework/templates/state.template.json +0 -17
  232. package/.morph/framework/templates/ui/FluentDesignTheme.cs +0 -149
  233. package/.morph/framework/templates/ui/MudTheme.cs +0 -281
  234. package/.morph/framework/templates/ui/design-system.css +0 -226
  235. package/.morph/logs/tool-failures.log +0 -7
  236. package/.morph/memory/pre-compact-2026-02-23T15-43-03-521Z.json +0 -16
  237. package/.morph/state.json +0 -48
  238. package/framework/templates/code/dotnet/contracts/contracts.cs +0 -217
  239. package/framework/templates/code/dotnet/contracts/contracts.cs.hbs +0 -172
@@ -1,131 +0,0 @@
1
- # Observability Standard: Logging
2
-
3
- ## Overview
4
- Structured logging with Serilog, enrichers, sinks, and log level configuration.
5
-
6
- ## Serilog Setup
7
-
8
- ### Package Installation
9
- ```xml
10
- <PackageReference Include="Serilog.AspNetCore" Version="8.*" />
11
- <PackageReference Include="Serilog.Enrichers.Environment" Version="3.*" />
12
- <PackageReference Include="Serilog.Enrichers.Process" Version="3.*" />
13
- <PackageReference Include="Serilog.Enrichers.Thread" Version="4.*" />
14
- <PackageReference Include="Serilog.Sinks.ApplicationInsights" Version="4.*" />
15
- ```
16
-
17
- ### Program.cs Configuration
18
- ```csharp
19
- Log.Logger = new LoggerConfiguration()
20
- .ReadFrom.Configuration(builder.Configuration)
21
- .Enrich.FromLogContext()
22
- .Enrich.WithEnvironmentName()
23
- .Enrich.WithMachineName()
24
- .Enrich.WithProcessId()
25
- .Enrich.WithThreadId()
26
- .WriteTo.Console(outputTemplate:
27
- "[{Timestamp:HH:mm:ss} {Level:u3}] {SourceContext}: {Message:lj}{NewLine}{Exception}")
28
- .WriteTo.ApplicationInsights(
29
- builder.Configuration["ApplicationInsights:ConnectionString"],
30
- TelemetryConverter.Traces)
31
- .CreateLogger();
32
-
33
- builder.Host.UseSerilog();
34
- ```
35
-
36
- ### appsettings.json Level Configuration
37
- ```json
38
- {
39
- "Serilog": {
40
- "MinimumLevel": {
41
- "Default": "Information",
42
- "Override": {
43
- "Microsoft": "Warning",
44
- "Microsoft.Hosting.Lifetime": "Information",
45
- "System": "Warning",
46
- "Microsoft.EntityFrameworkCore": "Warning"
47
- }
48
- }
49
- }
50
- }
51
- ```
52
-
53
- ## Structured Logging Patterns
54
-
55
- ### Correct: Structured Properties
56
- ```csharp
57
- // ✅ Use structured logging — properties are searchable in App Insights
58
- logger.LogInformation("User {UserId} created order {OrderId} for {Amount:C}",
59
- userId, orderId, amount);
60
-
61
- // ✅ Log exceptions with context
62
- logger.LogError(ex, "Failed to process payment for order {OrderId} (attempt {Attempt}/{MaxAttempts})",
63
- orderId, attempt, maxAttempts);
64
- ```
65
-
66
- ### Wrong: String Interpolation
67
- ```csharp
68
- // ❌ Never use string interpolation — loses structured properties
69
- logger.LogInformation($"User {userId} created order {orderId}");
70
-
71
- // ❌ Never concatenate
72
- logger.LogError("Failed for order " + orderId);
73
- ```
74
-
75
- ## Log Scopes
76
- ```csharp
77
- // Add correlation context for a request scope
78
- using (logger.BeginScope(new Dictionary<string, object>
79
- {
80
- ["CorrelationId"] = correlationId,
81
- ["UserId"] = userId,
82
- ["Feature"] = "checkout"
83
- }))
84
- {
85
- // All logs within this scope include the properties above
86
- await ProcessCheckoutAsync(cart);
87
- }
88
- ```
89
-
90
- ## Log Categories — What to Log
91
-
92
- | Level | When |
93
- |-------|------|
94
- | `Trace` | Never in production (dev only) |
95
- | `Debug` | Detailed flow, timing — disabled in prod |
96
- | `Information` | Business events: order created, user signed in, job started |
97
- | `Warning` | Degraded state: retry, rate limit, cache miss cascade |
98
- | `Error` | Handled exceptions: payment failed, validation error |
99
- | `Critical` | System failures: database unavailable, startup failure |
100
-
101
- ## Sensitive Data — NEVER Log
102
- - Passwords or hashed passwords
103
- - Credit card numbers or CVV
104
- - Social security numbers
105
- - JWT tokens or API keys
106
- - Full connection strings
107
- - PII beyond user ID (no email, phone, address)
108
-
109
- ## Performance Logging Pattern
110
- ```csharp
111
- public class PerformanceLoggingBehavior<TRequest, TResponse>
112
- : IPipelineBehavior<TRequest, TResponse>
113
- {
114
- private readonly ILogger<PerformanceLoggingBehavior<TRequest, TResponse>> _logger;
115
-
116
- public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken ct)
117
- {
118
- var sw = Stopwatch.StartNew();
119
- var response = await next();
120
- sw.Stop();
121
-
122
- if (sw.ElapsedMilliseconds > 500)
123
- {
124
- _logger.LogWarning("Slow request {RequestName} took {ElapsedMs}ms",
125
- typeof(TRequest).Name, sw.ElapsedMilliseconds);
126
- }
127
-
128
- return response;
129
- }
130
- }
131
- ```
@@ -1,121 +0,0 @@
1
- # Observability Standard: Metrics
2
-
3
- ## Overview
4
- Custom metrics with .NET Meters API and Azure Monitor integration.
5
-
6
- ## Metrics Setup
7
-
8
- ### Packages
9
- ```xml
10
- <PackageReference Include="System.Diagnostics.DiagnosticSource" Version="9.*" />
11
- <PackageReference Include="OpenTelemetry.Instrumentation.Runtime" Version="0.*" />
12
- ```
13
-
14
- ### Meter Definition (per feature/service)
15
- ```csharp
16
- // Define meters as static singletons
17
- public static class AppMetrics
18
- {
19
- private static readonly Meter Meter = new("MyApp.Business", "1.0.0");
20
-
21
- // Counters (monotonically increasing)
22
- public static readonly Counter<long> OrdersCreated =
23
- Meter.CreateCounter<long>("orders.created", "orders", "Total orders created");
24
-
25
- public static readonly Counter<long> PaymentsFailed =
26
- Meter.CreateCounter<long>("payments.failed", "failures", "Total payment failures");
27
-
28
- // Histograms (distributions)
29
- public static readonly Histogram<double> OrderProcessingTime =
30
- Meter.CreateHistogram<double>("orders.processing_time", "ms", "Order processing duration");
31
-
32
- // Gauges (current value)
33
- public static readonly ObservableGauge<int> ActiveConnections =
34
- Meter.CreateObservableGauge<int>("connections.active", GetActiveConnections, "connections");
35
-
36
- private static int GetActiveConnections() => ConnectionPool.ActiveCount;
37
- }
38
- ```
39
-
40
- ### Recording Metrics
41
- ```csharp
42
- // Counter increment
43
- AppMetrics.OrdersCreated.Add(1, new TagList
44
- {
45
- { "status", "success" },
46
- { "payment_method", order.PaymentMethod }
47
- });
48
-
49
- // Histogram measurement
50
- var sw = Stopwatch.StartNew();
51
- await ProcessOrderAsync(order);
52
- AppMetrics.OrderProcessingTime.Record(sw.ElapsedMilliseconds, new TagList
53
- {
54
- { "order_type", order.Type },
55
- { "region", order.Region }
56
- });
57
- ```
58
-
59
- ### Register with OpenTelemetry
60
- ```csharp
61
- builder.Services.AddOpenTelemetry()
62
- .WithMetrics(metrics =>
63
- {
64
- metrics
65
- .AddAspNetCoreInstrumentation()
66
- .AddHttpClientInstrumentation()
67
- .AddRuntimeInstrumentation()
68
- .AddMeter("MyApp.Business")
69
- .AddAzureMonitorMetricExporter(opts =>
70
- {
71
- opts.ConnectionString = config["ApplicationInsights:ConnectionString"];
72
- });
73
- });
74
- ```
75
-
76
- ## Required Business Metrics
77
-
78
- | Metric | Type | Tags | Why |
79
- |--------|------|------|-----|
80
- | `requests.total` | Counter | route, method, status | Request volume |
81
- | `requests.duration` | Histogram | route, status | Latency distribution |
82
- | `errors.total` | Counter | type, severity | Error rate |
83
- | `{domain}.operations` | Counter | operation, result | Business KPIs |
84
- | `db.query_duration` | Histogram | table, operation | DB performance |
85
- | `queue.depth` | Gauge | queue_name | Backlog monitoring |
86
- | `cache.hit_rate` | Gauge | cache_name | Cache effectiveness |
87
-
88
- ## KQL Metric Queries
89
-
90
- ### Request Volume by Endpoint
91
- ```kql
92
- customMetrics
93
- | where name == "requests.total" and timestamp > ago(1h)
94
- | summarize total = sum(value) by bin(timestamp, 5m), tostring(customDimensions["route"])
95
- | render timechart
96
- ```
97
-
98
- ### P50/P95/P99 Latency
99
- ```kql
100
- customMetrics
101
- | where name == "requests.duration" and timestamp > ago(1h)
102
- | summarize
103
- p50 = percentile(value, 50),
104
- p95 = percentile(value, 95),
105
- p99 = percentile(value, 99)
106
- by bin(timestamp, 5m)
107
- | render timechart
108
- ```
109
-
110
- ## Naming Conventions
111
-
112
- | Pattern | Example | Description |
113
- |---------|---------|-------------|
114
- | `{domain}.{noun}.{verb}` | `orders.items.created` | Domain event count |
115
- | `{resource}.{metric}` | `db.query_duration` | Resource measurement |
116
- | `{service}.{noun}.active` | `connections.sockets.active` | Current state |
117
-
118
- Rules:
119
- - Lowercase with dots as separators
120
- - Use consistent units: `ms` for duration, `bytes` for size, `count` for dimensionless
121
- - Include relevant tags (avoid high-cardinality tags like userId)
@@ -1,114 +0,0 @@
1
- # Observability Standard: Monitoring
2
-
3
- ## Overview
4
- Application Insights configuration and KQL query patterns for production monitoring.
5
-
6
- ## Application Insights Setup
7
-
8
- ### Connection String (not Instrumentation Key)
9
- ```csharp
10
- // appsettings.json — use connection string, not key
11
- {
12
- "ApplicationInsights": {
13
- "ConnectionString": "InstrumentationKey=..." // from Key Vault
14
- }
15
- }
16
-
17
- // Program.cs
18
- builder.Services.AddApplicationInsightsTelemetry(
19
- builder.Configuration["ApplicationInsights:ConnectionString"]);
20
- ```
21
-
22
- ### Sampling Configuration
23
- ```csharp
24
- builder.Services.Configure<TelemetryConfiguration>(config =>
25
- {
26
- var sampler = new AdaptiveSamplingTelemetryProcessor(null!);
27
- sampler.MaxTelemetryItemsPerSecond = 5; // Limit volume
28
- sampler.ExcludedTypes = "Request"; // Don't sample requests
29
- config.TelemetryProcessorChainBuilder.Use(_ => sampler).Build();
30
- });
31
- ```
32
-
33
- ### Dependency Tracking
34
- ```csharp
35
- // Auto-tracked: HTTP, SQL, Azure SDK calls
36
- // Manual tracking for custom operations:
37
- using var operation = telemetryClient.StartOperation<DependencyTelemetry>("ServiceBus.Send");
38
- operation.Telemetry.Type = "Azure Service Bus";
39
- operation.Telemetry.Target = queueName;
40
- try
41
- {
42
- await sender.SendMessageAsync(message);
43
- operation.Telemetry.Success = true;
44
- }
45
- catch (Exception ex)
46
- {
47
- operation.Telemetry.Success = false;
48
- telemetryClient.TrackException(ex);
49
- throw;
50
- }
51
- ```
52
-
53
- ## KQL Queries — Common Scenarios
54
-
55
- ### Request Success Rate (last 24h)
56
- ```kql
57
- requests
58
- | where timestamp > ago(24h)
59
- | summarize
60
- total = count(),
61
- failed = countif(success == false),
62
- successRate = round(100.0 * countif(success == true) / count(), 2)
63
- | project total, failed, successRate
64
- ```
65
-
66
- ### Slow Requests (> 2s)
67
- ```kql
68
- requests
69
- | where duration > 2000 and timestamp > ago(1h)
70
- | project timestamp, name, url, duration, resultCode, cloud_RoleInstance
71
- | order by duration desc
72
- | take 20
73
- ```
74
-
75
- ### Exception Summary
76
- ```kql
77
- exceptions
78
- | where timestamp > ago(24h)
79
- | summarize count() by type, outerMessage
80
- | order by count_ desc
81
- | take 10
82
- ```
83
-
84
- ### Dependency Failures
85
- ```kql
86
- dependencies
87
- | where success == false and timestamp > ago(1h)
88
- | project timestamp, name, type, target, duration, resultCode, data
89
- | order by timestamp desc
90
- ```
91
-
92
- ### User Activity Heatmap
93
- ```kql
94
- customEvents
95
- | where timestamp > ago(7d)
96
- | summarize events = count() by bin(timestamp, 1h), name
97
- | render timechart
98
- ```
99
-
100
- ## Alerting Rules
101
-
102
- | Alert | Condition | Severity |
103
- |-------|-----------|----------|
104
- | High error rate | `requests` failure rate > 5% for 5 min | Critical |
105
- | Slow response | P95 latency > 3s for 10 min | Warning |
106
- | Exception spike | Exception count > 100/min | Critical |
107
- | Dependency failure | Any dependency > 10 failures/min | Warning |
108
-
109
- ## Dashboard Required Sections
110
- - Request volume + success rate (1h/24h/7d)
111
- - Top slow endpoints
112
- - Exception breakdown by type
113
- - Dependency health grid
114
- - Active user count
@@ -1,132 +0,0 @@
1
- # Observability Standard: Distributed Tracing
2
-
3
- ## Overview
4
- OpenTelemetry distributed tracing for cross-service correlation and performance analysis.
5
-
6
- ## OpenTelemetry Setup
7
-
8
- ### Packages
9
- ```xml
10
- <PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.*" />
11
- <PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.*" />
12
- <PackageReference Include="OpenTelemetry.Instrumentation.Http" Version="1.*" />
13
- <PackageReference Include="OpenTelemetry.Instrumentation.SqlClient" Version="1.*" />
14
- <PackageReference Include="Azure.Monitor.OpenTelemetry.AspNetCore" Version="1.*" />
15
- ```
16
-
17
- ### Program.cs Configuration
18
- ```csharp
19
- builder.Services.AddOpenTelemetry()
20
- .WithTracing(tracing =>
21
- {
22
- tracing
23
- .AddAspNetCoreInstrumentation(opts =>
24
- {
25
- opts.RecordException = true;
26
- opts.Filter = ctx => !ctx.Request.Path.StartsWithSegments("/health");
27
- })
28
- .AddHttpClientInstrumentation()
29
- .AddSqlClientInstrumentation(opts => opts.SetDbStatementForText = true)
30
- .AddSource(ActivitySource.Name) // Custom activities
31
- .AddAzureMonitorTraceExporter(opts =>
32
- {
33
- opts.ConnectionString = config["ApplicationInsights:ConnectionString"];
34
- });
35
- });
36
-
37
- // Custom ActivitySource for domain operations
38
- public static class Telemetry
39
- {
40
- public static readonly ActivitySource ActivitySource = new("MyApp", "1.0.0");
41
- }
42
- ```
43
-
44
- ## Custom Span Creation
45
-
46
- ### Service Method Tracing
47
- ```csharp
48
- public async Task<Order> ProcessOrderAsync(CreateOrderCommand command)
49
- {
50
- using var activity = Telemetry.ActivitySource.StartActivity("ProcessOrder");
51
- activity?.SetTag("order.userId", command.UserId.ToString());
52
- activity?.SetTag("order.itemCount", command.Items.Count.ToString());
53
-
54
- try
55
- {
56
- var order = await _repository.CreateAsync(command);
57
- activity?.SetTag("order.id", order.Id.ToString());
58
- activity?.SetStatus(ActivityStatusCode.Ok);
59
- return order;
60
- }
61
- catch (Exception ex)
62
- {
63
- activity?.SetStatus(ActivityStatusCode.Error, ex.Message);
64
- activity?.RecordException(ex);
65
- throw;
66
- }
67
- }
68
- ```
69
-
70
- ### Baggage (Cross-Service Context)
71
- ```csharp
72
- // Set correlation ID in baggage (propagates across HTTP calls)
73
- Activity.Current?.SetBaggage("correlationId", correlationId);
74
- Activity.Current?.SetBaggage("userId", userId.ToString());
75
-
76
- // Read baggage downstream
77
- var correlationId = Activity.Current?.GetBaggageItem("correlationId");
78
- ```
79
-
80
- ## Trace Context Propagation
81
-
82
- ### HTTP Client (auto-propagated)
83
- ```csharp
84
- // HttpClient automatically propagates W3C trace context
85
- // Configure in DI:
86
- builder.Services.AddHttpClient("ExternalApi")
87
- .AddOpenTelemetryInstrumentation();
88
- ```
89
-
90
- ### Service Bus (manual propagation)
91
- ```csharp
92
- // Sender: inject trace context into message properties
93
- var message = new ServiceBusMessage(body);
94
- var activity = Activity.Current;
95
- if (activity != null)
96
- {
97
- message.ApplicationProperties["traceparent"] = activity.Id;
98
- message.ApplicationProperties["tracestate"] = activity.TraceStateString;
99
- }
100
-
101
- // Receiver: restore trace context from message
102
- if (message.ApplicationProperties.TryGetValue("traceparent", out var traceparent))
103
- {
104
- using var linkedActivity = Telemetry.ActivitySource.StartActivity(
105
- "ProcessMessage",
106
- ActivityKind.Consumer,
107
- parentId: traceparent.ToString()!);
108
- await ProcessAsync(message);
109
- }
110
- ```
111
-
112
- ## Trace Sampling Strategy
113
-
114
- | Environment | Strategy | Rate |
115
- |-------------|----------|------|
116
- | Development | Always | 100% |
117
- | Staging | Adaptive | 10% + errors |
118
- | Production | Adaptive | 5% + errors |
119
-
120
- ```csharp
121
- // Production adaptive sampling (errors always sampled)
122
- .AddAspNetCoreInstrumentation(opts =>
123
- {
124
- opts.Enrich = (activity, eventName, obj) =>
125
- {
126
- if (obj is HttpResponse response && response.StatusCode >= 400)
127
- {
128
- activity.SetSampled(true); // Always sample errors
129
- }
130
- };
131
- })
132
- ```
@@ -1,112 +0,0 @@
1
- # Workflow Standard: Parallel Execution
2
-
3
- ## When to Use Parallel Execution
4
-
5
- | Condition | Decision |
6
- |-----------|----------|
7
- | 5+ independent tasks | Use P-Threads |
8
- | Multi-domain (backend + frontend + infra) | Use P-Threads with squad templates |
9
- | 15+ files to create | Use P-Threads |
10
- | Tasks have zero dependency overlap | Use P-Threads |
11
- | Tasks share file scope | Do NOT parallelize |
12
- | Sequential data flow required | Do NOT parallelize |
13
-
14
- ## Parallelization Planning
15
-
16
- ### Step 1: Dependency Analysis
17
- ```bash
18
- morph-spec detect-workflow user-auth
19
-
20
- # Identifies: parallelizable tasks, sequential chains, waves
21
- ```
22
-
23
- ### Step 2: File Scope Assignment
24
- Assign exclusive file ownership to each parallel worker:
25
-
26
- ```
27
- Worker A (Backend): Entities/, Services/, Controllers/, DTOs/
28
- Worker B (Frontend): Pages/, Components/, CSS/
29
- Worker C (Infra): infra/bicep/, .github/workflows/
30
- ```
31
-
32
- No overlap allowed. If overlap is unavoidable, make it sequential.
33
-
34
- ### Step 3: Choose Squad Template
35
- ```bash
36
- morph-spec squad-template use full-stack --feature=user-auth
37
-
38
- # Creates execution plan based on full-stack.json template:
39
- # - dotnet-senior (backend lead)
40
- # - blazor-builder (frontend lead)
41
- # - bicep-architect (infra lead)
42
- # - thread-orchestrator (coordinator)
43
- ```
44
-
45
- ## Execution Flow
46
-
47
- ```
48
- Orchestrator
49
-
50
- ├── spawn parallel: Worker A (files: Entities/, Services/)
51
- ├── spawn parallel: Worker B (files: Pages/, Components/)
52
- └── spawn parallel: Worker C (files: infra/)
53
-
54
- │ [Workers execute concurrently — no interaction]
55
-
56
- ├── wait-all (poll or explicit sync)
57
-
58
- ├── merge results (check for conflicts)
59
- ├── run integration validation
60
- └── report consolidated output
61
- ```
62
-
63
- ## Conflict Resolution
64
-
65
- ### File Conflicts (two workers wrote same file)
66
- ```bash
67
- # This should NOT happen if scopes are properly defined
68
- # If it does:
69
- morph-spec agents review aggregate user-auth \
70
- --agents=dotnet-senior,blazor-builder \
71
- --strategy=best-of-n
72
- ```
73
-
74
- ### Interface Mismatches (A expects contract B didn't fulfill)
75
- - Document the mismatch in the coordinator report
76
- - Fix in post-merge sequential step
77
- - Update contracts.cs to reflect actual implementation
78
-
79
- ## Fusion vs Parallel
80
-
81
- | Aspect | Parallel (P-Thread) | Fusion (F-Thread) |
82
- |--------|--------------------|--------------------|
83
- | Goal | Divide scope | Compete on same scope |
84
- | Output | Different files | Same files, best one wins |
85
- | Workers collaborate? | No | No |
86
- | Merge | Combine all files | Select best implementation |
87
- | Use case | Large features | Design decisions, quality optimization |
88
-
89
- ## Configuration
90
- ```json
91
- // llm-interaction.json
92
- {
93
- "parallelExecution": {
94
- "enabled": true,
95
- "maxConcurrent": 3,
96
- "defaultStrategy": "best-of-n"
97
- }
98
- }
99
- ```
100
-
101
- ## Squad Templates
102
-
103
- Pre-defined squad configurations in `framework/squad-templates/`:
104
- - `full-stack.json` — Backend + Frontend + Infra (6 agents)
105
- - `backend-only.json` — Backend specialists only (4 agents)
106
- - `frontend-only.json` — Frontend specialists only (3 agents)
107
-
108
- ```bash
109
- morph-spec squad-template list
110
- morph-spec squad-template show full-stack
111
- morph-spec squad-template use full-stack --feature=user-auth
112
- ```