@polymorphism-tech/morph-spec 11.1.1 → 11.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 (166) hide show
  1. package/README.md +3 -2
  2. package/bin/morph-spec.js +13 -23
  3. package/docs/CHEATSHEET.md +3 -3
  4. package/docs/QUICKSTART.md +1 -1
  5. package/framework/CLAUDE.md +3 -1
  6. package/framework/MORPH.md +8 -3
  7. package/framework/agents.json +4 -4
  8. package/framework/docs/CLI.md +28 -18
  9. package/framework/evals/review-checklist.md +35 -18
  10. package/framework/hooks/README.md +18 -11
  11. package/framework/hooks/claude-code/core/README.md +2 -2
  12. package/framework/hooks/claude-code/core/chain.js +9 -25
  13. package/framework/hooks/claude-code/core/comment-guard.js +3 -9
  14. package/framework/hooks/claude-code/core/conventional-commit.js +3 -3
  15. package/framework/hooks/claude-code/core/graph-refresh-kick.js +6 -6
  16. package/framework/hooks/claude-code/core/masked-exit.js +4 -3
  17. package/framework/hooks/claude-code/core/pre-bash-denylist.js +2 -2
  18. package/framework/hooks/claude-code/core/protect-spec-files.js +2 -4
  19. package/framework/hooks/claude-code/core/stack-changed.js +5 -4
  20. package/framework/hooks/claude-code/core/validate-completion.js +15 -12
  21. package/framework/hooks/shared/contract.js +22 -1
  22. package/framework/hooks/shared/git-paths.js +6 -0
  23. package/framework/hooks/shared/graph-freshness.js +3 -3
  24. package/framework/hooks/shared/graph-refresh.js +5 -10
  25. package/framework/hooks/shared/hook-response.js +1 -18
  26. package/framework/hooks/shared/payload-utils.js +12 -1
  27. package/framework/hooks/shared/phase-utils.js +4 -52
  28. package/framework/hooks/shared/report-progress.js +1 -1
  29. package/framework/mcp/registry.json +16 -32
  30. package/framework/rules/ai-agents-standards.md +9 -1
  31. package/framework/rules/dotnet-templates.md +32 -33
  32. package/framework/rules/gsap-standards.md +8 -0
  33. package/framework/rules/infrastructure-standards.md +9 -9
  34. package/framework/rules/mcp-standards.md +10 -0
  35. package/framework/rules/neon-standards.md +4 -4
  36. package/framework/rules/nextjs-templates.md +10 -11
  37. package/framework/rules/ui-design.md +2 -2
  38. package/framework/schemas/config.schema.json +11 -0
  39. package/framework/skills/core/create-umbraco-lp/SKILL.md +1 -1
  40. package/framework/skills/core/migrate-lp-to-umbraco/SKILL.md +1 -1
  41. package/framework/skills/core/morph-apply/SKILL.md +6 -4
  42. package/framework/skills/core/morph-plan/SKILL.md +1 -1
  43. package/framework/skills/core/morph-uiux/SKILL.md +5 -5
  44. package/framework/standards/STANDARDS.json +8 -4
  45. package/framework/standards/STANDARDS.meta.json +1 -1
  46. package/framework/standards/ai-agents/agent-archetypes.md +1 -1
  47. package/framework/standards/ai-agents/middleware-patterns.md +0 -2
  48. package/framework/standards/ai-agents/prompt-sources.md +2 -2
  49. package/framework/standards/ai-agents/providers/model-registry.md +9 -12
  50. package/framework/standards/ai-agents/rag-custom-pgvector.md +2 -9
  51. package/framework/standards/frontend/design-system/ai-image-generation.md +1 -1
  52. package/framework/standards/infrastructure/docker/local-compose-isolation.md +2 -2
  53. package/framework/standards/integration/mcp/mcp-tools.md +125 -267
  54. package/framework/templates/README.md +52 -82
  55. package/framework/templates/REGISTRY.json +1 -281
  56. package/framework/templates/code/sql/ai-agents/agent-prompts-migration.sql.template +3 -4
  57. package/framework/templates/context/design-system.md +1 -1
  58. package/framework/templates/docs/plan.md +2 -2
  59. package/framework/templates/dotnet/ai-kit/src/Morph.AiKit/Providers/model-registry.v2.json +1 -1
  60. package/framework/templates/dotnet/ai-kit/tests/Morph.AiKit.Tests/MediaDisclosureTests.cs +1 -1
  61. package/framework/templates/dotnet/ai-kit/tests/Morph.AiKit.Tests/Morph.AiKit.Tests.csproj +3 -5
  62. package/framework/templates/frontend/nextjs/gsap-scroll-section.tsx.hbs +13 -17
  63. package/framework/templates/infrastructure/docker/docker-compose.template.yml +15 -16
  64. package/framework/templates/infrastructure/github/README.md +10 -13
  65. package/package.json +7 -16
  66. package/src/commands/graph/build.js +2 -2
  67. package/src/commands/mcp/manual-setup.js +95 -0
  68. package/src/commands/mcp/mcp-setup.js +26 -192
  69. package/src/commands/project/doctor.js +48 -142
  70. package/src/commands/project/env.js +2 -1
  71. package/src/commands/project/init-contract.js +2 -2
  72. package/src/commands/project/init.js +34 -294
  73. package/src/commands/project/stack-scan.js +6 -14
  74. package/src/commands/project/stack-set.js +3 -1
  75. package/src/commands/project/standards.js +1 -2
  76. package/src/commands/project/update.js +87 -205
  77. package/src/commands/scaffold/scaffold.js +43 -5
  78. package/src/commands/validation/check.js +12 -10
  79. package/src/commands/validation/prove-red.js +61 -22
  80. package/src/core/paths/output-schema.js +8 -27
  81. package/src/core/templates/template-registry.js +8 -43
  82. package/src/core/templates/template-renderer.js +3 -200
  83. package/src/lib/ai/ai-checks.js +1 -1
  84. package/src/lib/ai/ai-project-scan.js +2 -5
  85. package/src/lib/ai/code-audit.js +3 -8
  86. package/src/lib/ai/registry-audit.js +2 -1
  87. package/src/lib/check/signals.js +25 -7
  88. package/src/lib/config/project-config.js +3 -2
  89. package/src/lib/contract/apply.js +2 -1
  90. package/src/lib/contract/defaults.js +2 -2
  91. package/src/lib/contract/merge.js +1 -0
  92. package/src/lib/contract/scan.js +5 -5
  93. package/src/lib/detectors/claude-config-detector.js +44 -98
  94. package/src/lib/detectors/mcp-config.js +2 -1
  95. package/src/lib/diff/diff-lines.js +4 -9
  96. package/src/lib/generators/scaffold-generator.js +5 -17
  97. package/src/lib/git/default-branch.js +5 -13
  98. package/src/lib/graph/graph-health.js +1 -1
  99. package/src/lib/graph/graph-loader.js +2 -1
  100. package/src/lib/graph/graphifyignore.js +5 -5
  101. package/src/lib/graph/sanitize.js +2 -2
  102. package/src/lib/installers/effects.js +0 -13
  103. package/src/lib/installers/install-manifest.js +56 -0
  104. package/src/lib/installers/mcp-installer.js +16 -19
  105. package/src/lib/installers/memory-installer.js +5 -8
  106. package/src/lib/installers/rules-installer.js +9 -15
  107. package/src/lib/installers/stack-assets.js +54 -7
  108. package/src/lib/installers/stack-sync.js +16 -16
  109. package/src/lib/installers/stack-tooling.js +4 -3
  110. package/src/lib/json-file.js +9 -0
  111. package/src/lib/plan/artifact-vocabulary.js +1 -1
  112. package/src/lib/plan/checks.js +4 -3
  113. package/src/lib/plan/media.js +6 -6
  114. package/src/lib/plan/plan-parser.js +6 -11
  115. package/src/lib/review-reports.js +13 -18
  116. package/src/lib/scan/worktree-dirs.js +1 -3
  117. package/src/lib/specs/adr-index.js +4 -4
  118. package/src/lib/specs/revocations.js +3 -3
  119. package/src/lib/stack/stack-scan.js +4 -4
  120. package/src/lib/standards/registry.js +1 -1
  121. package/src/lib/standards/verified-against.js +3 -3
  122. package/src/lib/tests-audit/audit.js +3 -3
  123. package/src/lib/text.js +5 -0
  124. package/src/scripts/global-install.js +41 -19
  125. package/src/scripts/setup-infra.js +68 -187
  126. package/src/utils/agents-installer.js +21 -60
  127. package/src/utils/claude-md-injector.js +16 -50
  128. package/src/utils/claude-settings-manager.js +29 -27
  129. package/src/utils/file-copier.js +3 -4
  130. package/src/utils/hooks-installer.js +83 -62
  131. package/src/utils/skills-installer.js +18 -78
  132. package/src/utils/version-checker.js +2 -31
  133. package/CLAUDE.md +0 -118
  134. package/framework/commands/create-umbraco-lp.md +0 -37
  135. package/framework/commands/migrate-lp-to-umbraco.md +0 -35
  136. package/framework/commands/morph-apply.md +0 -14
  137. package/framework/hooks/shared/spawn-command.js +0 -23
  138. package/framework/templates/CLAUDE.md.core.guide.md +0 -29
  139. package/framework/templates/CLAUDE.md.core.template +0 -22
  140. package/framework/templates/IDE-SNIPPETS.md +0 -262
  141. package/framework/templates/code/dotnet/ai-agents/AgentBootstrap.cs.template +0 -26
  142. package/framework/templates/code/dotnet/ai-agents/EmbeddingService.cs.template +0 -28
  143. package/framework/templates/code/dotnet/ai-agents/ModelRegistry.cs.template +0 -99
  144. package/framework/templates/code/dotnet/ai-agents/ResilientToolMiddleware.cs.template +0 -40
  145. package/framework/templates/code/dotnet/ai-agents/VectorSearchTool.cs.template +0 -54
  146. package/framework/templates/code/dotnet/ai-agents/model-registry.json.template +0 -53
  147. package/framework/templates/code/dotnet/contracts/README.md +0 -74
  148. package/framework/templates/code/dotnet/database/vector-entity.cs +0 -49
  149. package/framework/templates/code/sql/ai-agents/pgvector-embeddings-migration.sql.template +0 -91
  150. package/framework/templates/code/sql/postgresql-migration.template.sql +0 -108
  151. package/framework/templates/code/typescript/contracts.ts +0 -140
  152. package/framework/templates/context/ARCHITECTURE.md +0 -106
  153. package/framework/templates/examples/design-system-examples.md +0 -354
  154. package/framework/templates/infrastructure/docker/Dockerfile.template +0 -58
  155. package/framework/templates/infrastructure/github/actions/docker-build-push/action.yml.hbs +0 -45
  156. package/framework/templates/infrastructure/github/actions/health-check/action.yml.hbs +0 -27
  157. package/framework/templates/integrations/asaas-client.cs +0 -332
  158. package/framework/templates/integrations/asaas-webhook.cs +0 -290
  159. package/framework/templates/integrations/neon-auth-config.cs +0 -170
  160. package/framework/templates/ui/design-system.css +0 -226
  161. package/src/commands/context/context-refresh.js +0 -63
  162. package/src/lib/detectors/index.js +0 -178
  163. package/src/lib/generators/architecture-scanner.js +0 -543
  164. package/src/lib/generators/settings-generator.js +0 -97
  165. package/src/lib/graph/god-nodes.js +0 -65
  166. package/src/lib/installers/templates-reconcile.js +0 -26
@@ -1,262 +0,0 @@
1
- # IDE Snippets for MORPH Templates
2
-
3
- > Boost your productivity with IDE snippets for Handlebars template syntax
4
-
5
- ---
6
-
7
- ## 📦 Installation
8
-
9
- ### VS Code
10
-
11
- **Option 1: Project Snippets (Recommended)**
12
-
13
- Snippets are already configured in `framework/templates/.vscode/morph-templates.code-snippets`.
14
-
15
- To use them:
16
- 1. Open your project in VS Code
17
- 2. Snippets auto-activate when editing template files
18
- 3. Type a prefix (e.g., `morph-pascal`) and press `Tab`
19
-
20
- **Option 2: Global Snippets**
21
-
22
- To use snippets across all projects:
23
- 1. Open VS Code
24
- 2. Go to `File > Preferences > Configure User Snippets`
25
- 3. Select `New Global Snippets file...`
26
- 4. Name it `morph-templates.code-snippets`
27
- 5. Copy content from `framework/templates/.vscode/morph-templates.code-snippets`
28
-
29
- ---
30
-
31
- ### JetBrains IDEs (Rider, WebStorm, IntelliJ IDEA)
32
-
33
- **Installation:**
34
-
35
- 1. Open your IDE
36
- 2. Go to `File > Settings > Editor > Live Templates`
37
- 3. Click the `⚙️` gear icon → `Import Settings...`
38
- 4. Select `framework/templates/.idea/morph-templates.xml`
39
- 5. Click `OK` to import
40
-
41
- **Activation:**
42
-
43
- Snippets will be available in the "MORPH Templates" group. Type the prefix and press `Tab`.
44
-
45
- ---
46
-
47
- ## 🎯 Available Snippets
48
-
49
- ### Handlebars Helpers (Case Transformations)
50
-
51
- | Prefix | Output | Example Result |
52
- |--------|--------|----------------|
53
- | `morph-pascal` | `{{pascalCase FEATURE_NAME}}` | `UserAuthentication` |
54
- | `morph-camel` | `{{camelCase FEATURE_NAME}}` | `userAuthentication` |
55
- | `morph-snake` | `{{snakeCase FEATURE_NAME}}` | `user_authentication` |
56
- | `morph-title` | `{{titleCase FEATURE_NAME}}` | `User Authentication` |
57
- | `morph-kebab` | `{{kebabCase FEATURE_NAME}}` | `user-authentication` |
58
- | `morph-upper-snake` | `{{upperSnakeCase FEATURE_NAME}}` | `USER_AUTHENTICATION` |
59
-
60
- ### Handlebars Control Flow
61
-
62
- | Prefix | Description | Example |
63
- |--------|-------------|---------|
64
- | `morph-if` | If block | `{{#if condition}}...{{/if}}` |
65
- | `morph-if-else` | If-else block | `{{#if condition}}...{{else}}...{{/if}}` |
66
- | `morph-each` | Loop over array | `{{#each items}}{{this.name}}{{/each}}` |
67
- | `morph-unless` | Unless block | `{{#unless condition}}...{{/unless}}` |
68
-
69
- ### .NET Templates
70
-
71
- | Prefix | Template | File Extension |
72
- |--------|----------|----------------|
73
- | `morph-service` | Service class (business logic) | `.cs` |
74
- | `morph-repository` | Repository class (data access) | `.cs` |
75
- | `morph-migration` | EF Core migration | `.cs` |
76
- | `morph-job` | Hangfire background job | `.cs` |
77
-
78
- ### TypeScript Templates
79
-
80
- | Prefix | Template | File Extension |
81
- |--------|----------|----------------|
82
- | `morph-ts-contract` | TypeScript interfaces (DTOs) | `.ts` |
83
-
84
- ---
85
-
86
- ## 🚀 Usage Examples
87
-
88
- ### Example 1: Creating a Service Template
89
-
90
- **Steps:**
91
- 1. Create new file: `UserService.cs`
92
- 2. Type `morph-service` → Press `Tab`
93
- 3. Result:
94
- ```csharp
95
- namespace {{NAMESPACE}}.Application.Features.{{pascalCase FEATURE_NAME}}.Services;
96
-
97
- public class {{pascalCase FEATURE_NAME}}Service(
98
- I{{pascalCase FEATURE_NAME}}Repository repository,
99
- ILogger<{{pascalCase FEATURE_NAME}}Service> logger) : I{{pascalCase FEATURE_NAME}}Service
100
- {
101
- public async Task<{{pascalCase FEATURE_NAME}}Dto?> GetByIdAsync(int id, CancellationToken cancellationToken = default)
102
- {
103
- // Cursor here
104
- }
105
- }
106
- ```
107
-
108
- ### Example 2: Using Case Helpers
109
-
110
- **Scenario:** Convert `user-authentication` to different cases
111
-
112
- ```handlebars
113
- // Type: morph-pascal → Tab
114
- {{pascalCase FEATURE_NAME}} // Output: UserAuthentication
115
-
116
- // Type: morph-camel → Tab
117
- {{camelCase FEATURE_NAME}} // Output: userAuthentication
118
-
119
- // Type: morph-snake → Tab
120
- {{snakeCase FEATURE_NAME}} // Output: user_authentication
121
- ```
122
-
123
- ### Example 3: Conditional Rendering
124
-
125
- **Scenario:** Show different content based on stack
126
-
127
- ```handlebars
128
- // Type: morph-if-else → Tab
129
- {{#if (eq STACK "Nextjs")}}
130
- // Next.js-specific code
131
- {{else}}
132
- // Generic code
133
- {{/if}}
134
- ```
135
-
136
- ### Example 4: Looping Over Items
137
-
138
- **Scenario:** Generate multiple DTOs
139
-
140
- ```handlebars
141
- // Type: morph-each → Tab
142
- {{#each entities}}
143
- public class {{pascalCase this.name}}Dto
144
- {
145
- // Properties
146
- }
147
- {{/each}}
148
- ```
149
-
150
- ---
151
-
152
- ## 📝 Customizing Snippets
153
-
154
- ### VS Code
155
-
156
- Edit `framework/templates/.vscode/morph-templates.code-snippets`:
157
-
158
- ```json
159
- {
160
- "MORPH Template - Custom": {
161
- "prefix": "morph-custom",
162
- "body": [
163
- "// Your custom template",
164
- "$1"
165
- ],
166
- "description": "Your description"
167
- }
168
- }
169
- ```
170
-
171
- ### JetBrains IDEs
172
-
173
- 1. Go to `File > Settings > Editor > Live Templates`
174
- 2. Select "MORPH Templates" group
175
- 3. Click `+` → `Live Template`
176
- 4. Set abbreviation (prefix), description, and template text
177
-
178
- ---
179
-
180
- ## 🎨 Snippet Scopes
181
-
182
- | Snippet | VS Code Scope | JetBrains Scope |
183
- |---------|---------------|-----------------|
184
- | Handlebars helpers | All files | All files |
185
- | .NET templates | `.cs`, `.razor` | C#, HTML |
186
- | TypeScript templates | `.ts`, `.tsx` | TypeScript |
187
-
188
- ---
189
-
190
- ## 💡 Best Practices
191
-
192
- **1. Use Helpers Over Pre-computed Variables**
193
-
194
- ```handlebars
195
- ✅ GOOD: {{pascalCase FEATURE_NAME}}Service
196
- ❌ BAD: {{FEATURE_NAME_PASCAL}}Service // Deprecated
197
- ```
198
-
199
- **2. Chain Helpers for Complex Transformations**
200
-
201
- ```handlebars
202
- // Pluralize a PascalCase name
203
- {{pascalCase (pluralize FEATURE_NAME)}} // Users, Orders, etc.
204
- ```
205
-
206
- **3. Use Conditional Blocks for Stack-Specific Code**
207
-
208
- ```handlebars
209
- {{#if (eq STACK "Nextjs")}}
210
- import { useRouter } from 'next/navigation';
211
- {{/if}}
212
- ```
213
-
214
- **4. Extract Common Patterns to Snippets**
215
-
216
- If you find yourself typing the same template code repeatedly, create a custom snippet!
217
-
218
- ---
219
-
220
- ## 🔧 Troubleshooting
221
-
222
- ### Snippets Not Showing Up (VS Code)
223
-
224
- **Solution:**
225
- 1. Check file extension matches snippet scope (e.g., `.cs` for C# snippets)
226
- 2. Reload VS Code: `Ctrl+Shift+P` → `Developer: Reload Window`
227
- 3. Verify snippet file location: `framework/templates/.vscode/morph-templates.code-snippets`
228
-
229
- ### Snippets Not Showing Up (JetBrains)
230
-
231
- **Solution:**
232
- 1. Verify import: `File > Settings > Editor > Live Templates` → Check "MORPH Templates" group exists
233
- 2. Check snippet scope: Click snippet → Verify "Applicable in" contexts
234
- 3. Restart IDE
235
-
236
- ### Tab Not Expanding Snippet
237
-
238
- **Solution:**
239
- - **VS Code:** Ensure `editor.tabCompletion` is enabled in settings
240
- - **JetBrains:** Ensure `Tab` is set as expansion key in `Settings > Editor > Live Templates`
241
-
242
- ---
243
-
244
- ## 📚 Related Documentation
245
-
246
- - [Template System README](framework/templates/README.md) - Complete template system documentation
247
- - [Handlebars Helpers](framework/templates/README.md#handlebars-helpers) - Full list of available helpers
248
- - [CLI Template Commands](CLAUDE.md#templates) - Command-line template management
249
-
250
- ---
251
-
252
- ## 🎁 Contributing Custom Snippets
253
-
254
- Have a useful snippet? Share it!
255
-
256
- 1. Add snippet to appropriate file (`.vscode/` or `.idea/`)
257
- 2. Document it in this README (add row to tables)
258
- 3. Submit PR with description of use case
259
-
260
- ---
261
-
262
- *MORPH-SPEC Template Snippets by Polymorphism Tech*
@@ -1,26 +0,0 @@
1
- // READS STANDARDS: ai-agents-setup, ai-agents-providers-model-registry
2
-
3
- using Microsoft.Agents.AI;
4
- using Microsoft.Extensions.AI;
5
- using Microsoft.Extensions.DependencyInjection;
6
-
7
- namespace {{PROJECT_NAMESPACE}}.AI;
8
-
9
- public static class AgentBootstrap
10
- {
11
- public static WebApplicationBuilder AddMafAgents(this WebApplicationBuilder builder)
12
- {
13
- builder.Services.AddSingleton<ModelRegistry>();
14
-
15
- builder.Services.AddKeyedSingleton<AIAgent>("{{DEFAULT_AGENT_NAME}}", (sp, _) =>
16
- {
17
- var registry = sp.GetRequiredService<ModelRegistry>();
18
- var chatClient = registry.GetChatClient(registry.DefaultAlias);
19
- return chatClient.AsAIAgent(
20
- instructions: "{{DEFAULT_INSTRUCTIONS}}",
21
- name: "{{DEFAULT_AGENT_NAME}}");
22
- });
23
-
24
- return builder;
25
- }
26
- }
@@ -1,28 +0,0 @@
1
- // READS STANDARD: ai-agents-rag-custom-pgvector
2
-
3
- using Microsoft.Extensions.AI;
4
-
5
- namespace {{PROJECT_NAMESPACE}}.AI;
6
-
7
- public sealed class EmbeddingService(IEmbeddingGenerator<string, Embedding<float>> generator)
8
- {
9
- public async Task<ReadOnlyMemory<float>> EmbedAsync(
10
- string text,
11
- CancellationToken ct = default)
12
- {
13
- GeneratedEmbeddings<Embedding<float>> result =
14
- await generator.GenerateAsync([text], cancellationToken: ct);
15
-
16
- return result[0].Vector;
17
- }
18
-
19
- public async Task<IReadOnlyList<ReadOnlyMemory<float>>> EmbedBatchAsync(
20
- IReadOnlyList<string> texts,
21
- CancellationToken ct = default)
22
- {
23
- GeneratedEmbeddings<Embedding<float>> result =
24
- await generator.GenerateAsync(texts, cancellationToken: ct);
25
-
26
- return [.. result.Select(e => e.Vector)];
27
- }
28
- }
@@ -1,99 +0,0 @@
1
- // READS STANDARD: ai-agents-providers-model-registry
2
-
3
- using System.ClientModel;
4
- using System.Text.Json;
5
- using Microsoft.Extensions.AI;
6
- using Microsoft.Extensions.Configuration;
7
- using Microsoft.Extensions.Hosting;
8
- using OpenAI;
9
- using OpenAI.Chat;
10
-
11
- namespace {{PROJECT_NAMESPACE}}.AI;
12
-
13
- public sealed class ModelRegistry
14
- {
15
- private readonly Dictionary<string, ModelAlias> _aliases;
16
- private readonly Dictionary<string, IChatClient> _chatClientCache = new();
17
- private readonly IConfiguration _config;
18
- private readonly object _lock = new();
19
-
20
- public ModelRegistry(IConfiguration config, IHostEnvironment env)
21
- {
22
- _config = config;
23
- var path = Path.Combine(env.ContentRootPath, "{{REGISTRY_PATH}}");
24
- if (!File.Exists(path))
25
- throw new InvalidOperationException($"Model registry not found at {path}");
26
-
27
- var json = File.ReadAllText(path);
28
- var doc = JsonSerializer.Deserialize<RegistryDocument>(json, JsonOpts)
29
- ?? throw new InvalidOperationException("Empty model-registry.json");
30
- _aliases = doc.Aliases;
31
- DefaultAlias = doc.DefaultAlias;
32
- }
33
-
34
- public string DefaultAlias { get; }
35
-
36
- public IChatClient GetChatClient(string alias)
37
- {
38
- if (!_aliases.TryGetValue(alias, out var spec))
39
- throw new InvalidOperationException($"Unknown model alias: {alias}");
40
-
41
- lock (_lock)
42
- {
43
- if (_chatClientCache.TryGetValue(alias, out var cached))
44
- return cached;
45
-
46
- var client = spec.Provider switch
47
- {
48
- "openai" => BuildOpenAI(spec),
49
- "ollama" => BuildOllama(spec),
50
- _ => throw new NotSupportedException(
51
- $"Provider '{spec.Provider}' has no branch. Add it following " +
52
- $"the pattern in ai-agents-providers-model-registry.")
53
- };
54
-
55
- _chatClientCache[alias] = client;
56
- return client;
57
- }
58
- }
59
-
60
- private IChatClient BuildOpenAI(ModelAlias spec)
61
- {
62
- var apiKey = _config["OpenAI:ApiKey"]
63
- ?? throw new InvalidOperationException("OpenAI:ApiKey not configured");
64
- return new ChatClient(spec.Model, apiKey).AsIChatClient();
65
- }
66
-
67
- private IChatClient BuildOllama(ModelAlias spec)
68
- {
69
- var endpoint = spec.Options?.GetValueOrDefault("endpoint")?.ToString()
70
- ?? "http://localhost:11434/v1";
71
- // Ollama speaks the OpenAI protocol and ignores the key, but the SDK rejects an empty one.
72
- return new ChatClient(
73
- spec.Model,
74
- new ApiKeyCredential("ollama"),
75
- new OpenAIClientOptions { Endpoint = new Uri(endpoint) })
76
- .AsIChatClient();
77
- }
78
-
79
- private static readonly JsonSerializerOptions JsonOpts = new()
80
- {
81
- PropertyNameCaseInsensitive = true,
82
- ReadCommentHandling = JsonCommentHandling.Skip,
83
- AllowTrailingCommas = true
84
- };
85
-
86
- // Fallback is parsed but nothing fails over to it yet.
87
- private sealed record RegistryDocument(
88
- string Version,
89
- string DefaultAlias,
90
- Dictionary<string, ModelAlias> Aliases,
91
- Dictionary<string, string>? Fallback
92
- );
93
-
94
- public sealed record ModelAlias(
95
- string Provider,
96
- string Model,
97
- Dictionary<string, object>? Options
98
- );
99
- }
@@ -1,40 +0,0 @@
1
- // READS STANDARD: ai-agents-middleware-patterns
2
-
3
- using Microsoft.Agents.AI;
4
- using Microsoft.Extensions.AI;
5
-
6
- namespace {{PROJECT_NAMESPACE}}.AI;
7
-
8
- public static class ResilientToolMiddleware
9
- {
10
- public static async ValueTask<object?> Handle(
11
- AIAgent agent,
12
- FunctionInvocationContext context,
13
- Func<FunctionInvocationContext, CancellationToken, ValueTask<object?>> next,
14
- CancellationToken cancellationToken)
15
- {
16
- // Return the error as text, not an exception: the agent reads it and fixes the arguments on its next turn.
17
- if (context.Arguments.TryGetValue("date", out var dateArg)
18
- && !DateTime.TryParse(dateArg?.ToString(), out _))
19
- {
20
- return $"Invalid date format for '{context.Function.Name}'. Expected ISO 8601 (e.g. 2026-01-31).";
21
- }
22
-
23
- try
24
- {
25
- return await next(context, cancellationToken);
26
- }
27
- catch (HttpRequestException ex) when (ex.StatusCode == System.Net.HttpStatusCode.TooManyRequests)
28
- {
29
- return "Service is temporarily busy. Please try again in a moment.";
30
- }
31
- catch (TimeoutException)
32
- {
33
- return $"Tool '{context.Function.Name}' timed out. Try a simpler query.";
34
- }
35
- catch (Exception ex)
36
- {
37
- return $"Error in {context.Function.Name}: {ex.Message}";
38
- }
39
- }
40
- }
@@ -1,54 +0,0 @@
1
- // READS STANDARD: ai-agents-rag-custom-pgvector
2
-
3
- using System.ComponentModel;
4
- using Npgsql;
5
- using Pgvector;
6
-
7
- namespace {{PROJECT_NAMESPACE}}.AI;
8
-
9
- public sealed class VectorSearchTool(
10
- EmbeddingService embeddingService,
11
- NpgsqlDataSource dataSource,
12
- ITenantContext tenantContext)
13
- {
14
- private const int DefaultTopK = 5;
15
-
16
- [Description("Searches the knowledge base for context relevant to a question")]
17
- public async Task<string> SearchAsync(
18
- [Description("the natural-language search query")] string query,
19
- CancellationToken ct = default)
20
- {
21
- ReadOnlyMemory<float> queryVector = await embeddingService.EmbedAsync(query, ct);
22
-
23
- // Tenant comes from auth, never a tool parameter: the model could be prompt-injected into another tenant.
24
- Guid tenantId = tenantContext.CurrentTenantId;
25
-
26
- const string sql = """
27
- SELECT content
28
- FROM kb_embeddings
29
- WHERE tenant_id = @tenant
30
- ORDER BY embedding <=> @queryVec
31
- LIMIT @topK
32
- """;
33
-
34
- var chunks = new List<string>(DefaultTopK);
35
-
36
- await using var conn = await dataSource.OpenConnectionAsync(ct);
37
- await using var cmd = new NpgsqlCommand(sql, conn);
38
-
39
- cmd.Parameters.AddWithValue("tenant", tenantId);
40
-
41
- // VERIFY: binding Pgvector.Vector needs dataSourceBuilder.UseVector(); confirm against the project's Npgsql/Pgvector versions.
42
- cmd.Parameters.AddWithValue("queryVec", new Vector(queryVector.ToArray()));
43
-
44
- cmd.Parameters.AddWithValue("topK", DefaultTopK);
45
-
46
- await using var reader = await cmd.ExecuteReaderAsync(ct);
47
- while (await reader.ReadAsync(ct))
48
- {
49
- chunks.Add(reader.GetString(0));
50
- }
51
-
52
- return string.Join("\n\n", chunks);
53
- }
54
- }
@@ -1,53 +0,0 @@
1
- // READS STANDARD: ai-agents-providers-model-registry
2
- // Goes in config/model-registry.json. ModelRegistry only builds openai and ollama:
3
- // the anthropic and google aliases throw until a provider branch is added there.
4
- {
5
- "$schema": "./model-registry.schema.json",
6
- "version": "1.0",
7
- "defaultAlias": "{{PROJECT_DEFAULT_ALIAS}}",
8
- "aliases": {
9
- "text-default": {
10
- "provider": "openai",
11
- "model": "gpt-4o-mini",
12
- "options": { "temperature": 0.7 }
13
- },
14
- "text-heavy": {
15
- "provider": "openai",
16
- "model": "gpt-4o",
17
- "options": { "temperature": 0.5 }
18
- },
19
- "reasoning": {
20
- "provider": "openai",
21
- "model": "o3-mini",
22
- "options": { "reasoningEffort": "medium" }
23
- },
24
- "long-form": {
25
- "provider": "anthropic",
26
- "model": "claude-sonnet-4-6",
27
- "options": {}
28
- },
29
- "vision": {
30
- "provider": "google",
31
- "model": "gemini-2.5-flash",
32
- "options": {}
33
- },
34
- "embeddings": {
35
- "provider": "openai",
36
- "model": "text-embedding-3-small",
37
- "options": { "dimensions": 1536 }
38
- },
39
- "local-dev": {
40
- "provider": "ollama",
41
- "model": "llama3.2:3b",
42
- "options": { "endpoint": "http://localhost:11434/v1" }
43
- },
44
- "transcription": {
45
- "provider": "openai",
46
- "model": "whisper-1",
47
- "options": {}
48
- }
49
- },
50
- "fallback": {
51
- "text-default": "ollama/llama3.2:3b"
52
- }
53
- }
@@ -1,74 +0,0 @@
1
- # Contracts - {{titleCase FEATURE_NAME}}
2
-
3
- > Estrutura de contracts para features complexas
4
-
5
- ## Estrutura
6
-
7
- ```
8
- contracts/
9
- ├── README.md # Este arquivo (índice)
10
- ├── Entities/ # Entidades de domínio
11
- │ └── I{{pascalCase FEATURE_NAME}}Entity.cs
12
- ├── Commands/ # Commands (CQRS)
13
- │ └── I{{pascalCase FEATURE_NAME}}Commands.cs
14
- ├── Queries/ # Queries (CQRS)
15
- │ └── I{{pascalCase FEATURE_NAME}}Queries.cs
16
- ├── DTOs/ # Data Transfer Objects
17
- │ └── {{pascalCase FEATURE_NAME}}Dto.cs
18
- ├── Events/ # Domain Events
19
- │ └── {{pascalCase FEATURE_NAME}}Events.cs
20
- └── Services/ # Service Interfaces
21
- └── I{{pascalCase FEATURE_NAME}}Service.cs
22
- ```
23
-
24
- ## Quando usar pasta vs arquivo único
25
-
26
- | Cenário | Usar |
27
- |---------|------|
28
- | < 5 interfaces/DTOs | `contracts.cs` (arquivo único) |
29
- | 5-15 interfaces/DTOs | `contracts/` (pasta organizada) |
30
- | > 15 interfaces/DTOs | `contracts/` + subpastas por domínio |
31
-
32
- ## Convenções
33
-
34
- 1. **Prefixo `I`** para interfaces: `IOrderService`, `IPaymentGateway`
35
- 2. **Sufixo `Dto`** para DTOs: `OrderDto`, `OrderCreateDto`
36
- 3. **Sufixo `Command`** para commands: `CreateOrderCommand`
37
- 4. **Sufixo `Query`** para queries: `GetOrderByIdQuery`
38
- 5. **Sufixo `Event`** para eventos: `OrderCreatedEvent`
39
-
40
- ## Índice de Contracts
41
-
42
- ### Entidades
43
-
44
- | Interface | Descrição | Arquivo |
45
- |-----------|-----------|---------|
46
- | _A ser preenchido_ | | |
47
-
48
- ### Commands
49
-
50
- | Command | Handler | Descrição |
51
- |---------|---------|-----------|
52
- | _A ser preenchido_ | | |
53
-
54
- ### Queries
55
-
56
- | Query | Handler | Descrição |
57
- |-------|---------|-----------|
58
- | _A ser preenchido_ | | |
59
-
60
- ### DTOs
61
-
62
- | DTO | Usado em | Descrição |
63
- |-----|----------|-----------|
64
- | _A ser preenchido_ | | |
65
-
66
- ### Services
67
-
68
- | Interface | Implementação | Descrição |
69
- |-----------|---------------|-----------|
70
- | _A ser preenchido_ | | |
71
-
72
- ---
73
-
74
- _Gerado por MORPH-SPEC Framework_
@@ -1,49 +0,0 @@
1
- using System.ComponentModel.DataAnnotations.Schema;
2
- using Microsoft.EntityFrameworkCore;
3
- using Microsoft.EntityFrameworkCore.Metadata.Builders;
4
- using Pgvector;
5
-
6
- #nullable disable
7
-
8
- namespace {{NAMESPACE}}.Domain.Entities;
9
-
10
- public class {{pascalCase FEATURE_NAME}}
11
- {
12
- public Guid Id { get; set; }
13
- public string Title { get; set; } = string.Empty;
14
- public string Content { get; set; } = string.Empty;
15
- public string? Metadata { get; set; }
16
-
17
- // 1536 é a dimensão do text-embedding-3-small; troca junto com o modelo, aqui e na configuração
18
- [Column(TypeName = "vector(1536)")]
19
- public Vector? Embedding { get; set; }
20
-
21
- public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow;
22
- public DateTimeOffset? UpdatedAt { get; set; }
23
- }
24
-
25
- namespace {{NAMESPACE}}.Infrastructure.Data.Configurations;
26
-
27
- // Exige UseVector() no AddNpgsql e HasPostgresExtension("vector") no OnModelCreating
28
- public class {{pascalCase FEATURE_NAME}}Configuration : IEntityTypeConfiguration<{{pascalCase FEATURE_NAME}}>
29
- {
30
- public void Configure(EntityTypeBuilder<{{pascalCase FEATURE_NAME}}> builder)
31
- {
32
- builder.ToTable("{{snakeCase FEATURE_NAME}}s");
33
- builder.HasKey(e => e.Id);
34
- builder.Property(e => e.Id).HasDefaultValueSql("gen_random_uuid()");
35
- builder.Property(e => e.Title).IsRequired().HasMaxLength(200);
36
- builder.Property(e => e.Content).IsRequired();
37
- builder.Property(e => e.Metadata).HasColumnType("jsonb");
38
- builder.Property(e => e.Embedding).HasColumnType("vector(1536)");
39
- builder.Property(e => e.CreatedAt).HasDefaultValueSql("now()");
40
-
41
- builder.HasIndex(e => e.Embedding)
42
- .HasMethod("hnsw")
43
- .HasOperators("vector_cosine_ops")
44
- .HasStorageParameter("m", 16)
45
- .HasStorageParameter("ef_construction", 64);
46
-
47
- builder.HasIndex(e => e.Title);
48
- }
49
- }