@polymorphism-tech/morph-spec 6.0.0 → 7.1.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 (114) hide show
  1. package/README.md +367 -366
  2. package/docs/CHEATSHEET.md +3 -3
  3. package/docs/QUICKSTART.md +4 -4
  4. package/framework/CLAUDE.md +13 -0
  5. package/framework/MORPH.md +57 -36
  6. package/framework/agents.json +132 -127
  7. package/framework/commands/morph-apply.md +4 -21
  8. package/framework/commands/morph-archive.md +1 -1
  9. package/framework/commands/morph-proposal.md +2 -0
  10. package/framework/hooks/claude-code/core/enforce-phase-writes.js +1 -1
  11. package/framework/hooks/claude-code/core/protect-spec-files.js +1 -1
  12. package/framework/hooks/claude-code/core/state-sync.js +212 -0
  13. package/framework/hooks/shared/phase-utils.js +5 -4
  14. package/framework/hooks/shared/state-reader.js +1 -1
  15. package/framework/phases.json +1 -1
  16. package/framework/rubrics/backend.json +41 -36
  17. package/framework/rules/ai-agents-standards.md +45 -15
  18. package/framework/rules/morph-workflow.md +15 -34
  19. package/framework/rules/neon-standards.md +25 -26
  20. package/framework/schemas/tasks.schema.json +35 -0
  21. package/framework/skills/core/morph-apply/SKILL.md +154 -0
  22. package/framework/skills/core/morph-brainstorming/SKILL.md +53 -30
  23. package/framework/skills/core/morph-implement/SKILL.md +25 -14
  24. package/framework/skills/core/morph-plan/SKILL.md +91 -23
  25. package/framework/skills/core/morph-proposal/SKILL.md +137 -0
  26. package/framework/skills/core/morph-review/SKILL.md +43 -7
  27. package/framework/skills/core/morph-stack-scan/SKILL.md +40 -1
  28. package/framework/standards/STANDARDS.json +1729 -1134
  29. package/framework/standards/ai-agents/agent-session.md +160 -0
  30. package/framework/standards/ai-agents/batching.md +193 -0
  31. package/framework/standards/ai-agents/context-providers.md +188 -0
  32. package/framework/standards/ai-agents/mcp-server.md +250 -0
  33. package/framework/standards/ai-agents/mcp-tools.md +197 -0
  34. package/framework/standards/ai-agents/middleware-patterns.md +207 -0
  35. package/framework/standards/ai-agents/modalities-image-gen.md +173 -0
  36. package/framework/standards/ai-agents/modalities-speech-to-text.md +171 -0
  37. package/framework/standards/ai-agents/modalities-text-to-speech.md +181 -0
  38. package/framework/standards/ai-agents/modalities-vision.md +201 -0
  39. package/framework/standards/ai-agents/multi-agent-patterns.md +155 -0
  40. package/framework/standards/ai-agents/production.md +114 -258
  41. package/framework/standards/ai-agents/prompts-in-db.md +214 -0
  42. package/framework/standards/ai-agents/providers/model-registry.md +158 -0
  43. package/framework/standards/ai-agents/rag-custom-pgvector.md +243 -0
  44. package/framework/standards/ai-agents/service-tier-flex.md +135 -0
  45. package/framework/standards/ai-agents/setup.md +142 -316
  46. package/framework/standards/ai-agents/structured-output.md +249 -0
  47. package/framework/standards/ai-agents/sweet-spot.md +109 -0
  48. package/framework/standards/ai-agents/workflows.md +114 -284
  49. package/framework/standards/architecture/vertical-slice/vertical-slice.md +433 -429
  50. package/framework/standards/backend/api/validation.md +92 -88
  51. package/framework/standards/backend/database/postgresql/database.md +336 -332
  52. package/framework/standards/backend/database/vector-search-rag.md +599 -541
  53. package/framework/standards/backend/dotnet/fluent-validation-vsa.md +4 -0
  54. package/framework/standards/backend/dotnet/result-pattern.md +4 -0
  55. package/framework/standards/backend/dotnet/scalar-ui.md +176 -172
  56. package/framework/standards/backend/dotnet/scrutor.md +4 -0
  57. package/framework/standards/backend/dotnet/vsa-handler-patterns.md +278 -274
  58. package/framework/standards/backend/integrations/asaas/asaas-api.md +260 -216
  59. package/framework/standards/backend/integrations/hangfire/hangfire-jobs.md +354 -350
  60. package/framework/standards/backend/integrations/neon-auth/neon-auth.md +30 -19
  61. package/framework/standards/backend/integrations/resend/resend-email.md +400 -385
  62. package/framework/standards/data/nosql/cache/redis.md +106 -97
  63. package/framework/standards/data/nosql/cosmos-db.md +127 -118
  64. package/framework/standards/data/vector-search/rag-chunking.md +113 -104
  65. package/framework/standards/frontend/design-system/ai-image-generation.md +4 -0
  66. package/framework/standards/frontend/design-system/animations.md +164 -160
  67. package/framework/standards/frontend/design-system/naming.md +68 -64
  68. package/framework/standards/frontend/gsap/gsap-core.md +14 -8
  69. package/framework/standards/frontend/gsap/gsap-plugins.md +26 -21
  70. package/framework/standards/frontend/gsap/gsap-scrolltrigger.md +9 -7
  71. package/framework/standards/frontend/nextjs/app-router.md +127 -123
  72. package/framework/standards/frontend/nextjs/components.md +136 -132
  73. package/framework/standards/frontend/nextjs/data-fetching.md +130 -126
  74. package/framework/standards/frontend/nextjs/forms.md +134 -128
  75. package/framework/standards/frontend/nextjs/motion-patterns.md +328 -322
  76. package/framework/standards/frontend/nextjs/naming-conventions.md +71 -67
  77. package/framework/standards/frontend/nextjs/nextjs-patterns.md +229 -225
  78. package/framework/standards/frontend/nextjs/project-structure.md +106 -102
  79. package/framework/standards/frontend/nextjs/state-management.md +76 -72
  80. package/framework/standards/frontend/nextjs/testing.md +115 -111
  81. package/framework/standards/infrastructure/docker/easypanel-deploy.md +196 -192
  82. package/framework/standards/infrastructure/neon/neon-pgrag.md +6 -2
  83. package/framework/standards/infrastructure/neon/neon-pgvector.md +4 -0
  84. package/framework/standards/infrastructure/neon/neon-setup.md +5 -1
  85. package/framework/standards/integration/mcp/mcp-tools.md +471 -462
  86. package/framework/templates/REGISTRY.json +1745 -1239
  87. package/framework/templates/code/dotnet/ai-agents/AgentBootstrap.cs.template +39 -0
  88. package/framework/templates/code/dotnet/ai-agents/EmbeddingService.cs.template +68 -0
  89. package/framework/templates/code/dotnet/ai-agents/ModelRegistry.cs.template +117 -0
  90. package/framework/templates/code/dotnet/ai-agents/PromptRepository.cs.template +95 -0
  91. package/framework/templates/code/dotnet/ai-agents/ResilientToolMiddleware.cs.template +61 -0
  92. package/framework/templates/code/dotnet/ai-agents/VectorSearchTool.cs.template +107 -0
  93. package/framework/templates/code/dotnet/ai-agents/model-registry.json.template +58 -0
  94. package/framework/templates/code/sql/ai-agents/agent-prompts-migration.sql.template +58 -0
  95. package/framework/templates/code/sql/ai-agents/pgvector-embeddings-migration.sql.template +91 -0
  96. package/framework/templates/docs/onboarding.md +4 -4
  97. package/framework/templates/tasks.template.json +17 -0
  98. package/package.json +89 -83
  99. package/src/commands/project/init.js +16 -0
  100. package/src/commands/validation/validate-feature.js +1 -1
  101. package/src/core/paths/output-schema.js +6 -6
  102. package/src/core/state/state-manager.js +1 -1
  103. package/src/core/templates/template-registry.js +289 -256
  104. package/src/lib/detectors/design-system-detector.js +1 -1
  105. package/src/lib/generators/context-generator.js +516 -518
  106. package/src/lib/generators/scaffold-generator.js +23 -26
  107. package/src/lib/installers/memory-installer.js +138 -0
  108. package/src/lib/phase-chain/phase-validator.js +4 -4
  109. package/src/lib/risk-detector.js +80 -0
  110. package/src/lib/tasks/tasks-json-parser.js +185 -0
  111. package/src/scripts/setup-infra.js +25 -0
  112. package/src/utils/hooks-installer.js +59 -10
  113. package/framework/standards/infrastructure/neon/neon-semantic-kernel.md +0 -310
  114. package/framework/templates/integrations/semantic-kernel-neon.cs +0 -125
@@ -0,0 +1,39 @@
1
+ // TEMPLATE: AgentBootstrap.cs
2
+ // PURPOSE: Extension method to register ModelRegistry + a default agent in DI.
3
+ // READS STANDARDS: ai-agents-setup, ai-agents-providers-model-registry
4
+ // PLACEHOLDERS:
5
+ // {{PROJECT_NAMESPACE}} — root namespace of the project
6
+ // {{DEFAULT_AGENT_NAME}} — first agent name (e.g., "DefaultAssistant")
7
+ // {{DEFAULT_INSTRUCTIONS}} — system prompt for default agent (1 line)
8
+ // LAST-VERIFIED: 2026-05-19 (MAF 1.0 GA)
9
+
10
+ using Microsoft.Agents.AI;
11
+ using Microsoft.Extensions.AI;
12
+ using Microsoft.Extensions.DependencyInjection;
13
+
14
+ namespace {{PROJECT_NAMESPACE}}.AI;
15
+
16
+ public static class AgentBootstrap
17
+ {
18
+ /// <summary>
19
+ /// Register ModelRegistry (singleton) and the default agent.
20
+ /// Additional agents register themselves via builder.AddAIAgent("Name", ...).
21
+ /// </summary>
22
+ public static WebApplicationBuilder AddMafAgents(this WebApplicationBuilder builder)
23
+ {
24
+ // Single source of truth for model selection
25
+ builder.Services.AddSingleton<ModelRegistry>();
26
+
27
+ // Default agent — uses the default alias from model-registry.json
28
+ builder.Services.AddKeyedSingleton<AIAgent>("{{DEFAULT_AGENT_NAME}}", (sp, _) =>
29
+ {
30
+ var registry = sp.GetRequiredService<ModelRegistry>();
31
+ var chatClient = registry.GetChatClient(registry.DefaultAlias);
32
+ return chatClient.AsAIAgent(
33
+ instructions: "{{DEFAULT_INSTRUCTIONS}}",
34
+ name: "{{DEFAULT_AGENT_NAME}}");
35
+ });
36
+
37
+ return builder;
38
+ }
39
+ }
@@ -0,0 +1,68 @@
1
+ // TEMPLATE: EmbeddingService.cs
2
+ // PURPOSE: Generates embeddings for RAG indexing and query, via IEmbeddingGenerator.
3
+ // READS STANDARD: ai-agents-rag-custom-pgvector
4
+ // PLACEHOLDERS:
5
+ // {{PROJECT_NAMESPACE}} — root namespace of the project (e.g., MyProject)
6
+ // LAST-VERIFIED: 2026-05-19
7
+ //
8
+ // IMPORTANT — IEmbeddingGenerator registration (in Program.cs of the project):
9
+ // The project must register IEmbeddingGenerator<string, Embedding<float>> in DI.
10
+ // Example for OpenAI text-embedding-3-small (the canonical "embeddings" alias):
11
+ //
12
+ // builder.Services.AddSingleton<IEmbeddingGenerator<string, Embedding<float>>>(sp =>
13
+ // {
14
+ // var cfg = sp.GetRequiredService<IConfiguration>();
15
+ // return new OpenAIClient(cfg["OpenAI:ApiKey"]!)
16
+ // .GetEmbeddingClient("text-embedding-3-small")
17
+ // .AsIEmbeddingGenerator();
18
+ // });
19
+ //
20
+ // For other providers (Google, Anthropic, Ollama) adapt the client construction —
21
+ // see ai-agents-providers-model-registry §providers for verified SDKs.
22
+
23
+ using Microsoft.Extensions.AI;
24
+
25
+ namespace {{PROJECT_NAMESPACE}}.AI;
26
+
27
+ /// <summary>
28
+ /// Generates text embeddings for RAG indexing and query.
29
+ /// Wraps <see cref="IEmbeddingGenerator{TInput,TEmbedding}"/> so the rest of the project
30
+ /// does not take a direct dependency on the underlying provider SDK.
31
+ /// </summary>
32
+ public sealed class EmbeddingService(IEmbeddingGenerator<string, Embedding<float>> generator)
33
+ {
34
+ /// <summary>
35
+ /// Generates an embedding vector for a single text (used at query time).
36
+ /// </summary>
37
+ /// <param name="text">The text to embed.</param>
38
+ /// <param name="ct">Cancellation token.</param>
39
+ /// <returns>The embedding vector as <see cref="ReadOnlyMemory{T}"/> of float.</returns>
40
+ public async Task<ReadOnlyMemory<float>> EmbedAsync(
41
+ string text,
42
+ CancellationToken ct = default)
43
+ {
44
+ // GenerateAsync is the verified API: returns GeneratedEmbeddings<Embedding<float>>.
45
+ // Each Embedding<float>.Vector is a ReadOnlyMemory<float>.
46
+ // Source: Microsoft Learn — microsoft-extensions-ai (verified 2026-05-19).
47
+ GeneratedEmbeddings<Embedding<float>> result =
48
+ await generator.GenerateAsync([text], cancellationToken: ct);
49
+
50
+ return result[0].Vector;
51
+ }
52
+
53
+ /// <summary>
54
+ /// Generates embedding vectors for a batch of texts (used during document indexing).
55
+ /// </summary>
56
+ /// <param name="texts">The texts to embed.</param>
57
+ /// <param name="ct">Cancellation token.</param>
58
+ /// <returns>Embedding vectors in the same order as the input texts.</returns>
59
+ public async Task<IReadOnlyList<ReadOnlyMemory<float>>> EmbedBatchAsync(
60
+ IReadOnlyList<string> texts,
61
+ CancellationToken ct = default)
62
+ {
63
+ GeneratedEmbeddings<Embedding<float>> result =
64
+ await generator.GenerateAsync(texts, cancellationToken: ct);
65
+
66
+ return [.. result.Select(e => e.Vector)];
67
+ }
68
+ }
@@ -0,0 +1,117 @@
1
+ // TEMPLATE: ModelRegistry.cs
2
+ // PURPOSE: Reads config/model-registry.json at startup and exposes IChatClient by alias.
3
+ // READS STANDARD: ai-agents-providers-model-registry
4
+ // PROVIDERS: openai + ollama implemented below. To add google / anthropic / azure-openai,
5
+ // follow the same pattern — see ai-agents-providers-model-registry §providers
6
+ // (that standard is the source of truth for provider SDKs).
7
+ // PLACEHOLDERS:
8
+ // {{PROJECT_NAMESPACE}} — root namespace of the project (e.g., MyProject)
9
+ // {{REGISTRY_PATH}} — path to model-registry.json relative to app base
10
+ // (default: "config/model-registry.json")
11
+ // LAST-VERIFIED: 2026-05-19 (MAF 1.0 GA, OpenAI SDK 2.x)
12
+
13
+ using System.ClientModel;
14
+ using System.Text.Json;
15
+ using Microsoft.Extensions.AI;
16
+ using Microsoft.Extensions.Configuration;
17
+ using Microsoft.Extensions.Hosting;
18
+ using OpenAI;
19
+ using OpenAI.Chat;
20
+
21
+ namespace {{PROJECT_NAMESPACE}}.AI;
22
+
23
+ public sealed class ModelRegistry
24
+ {
25
+ private readonly Dictionary<string, ModelAlias> _aliases;
26
+ private readonly Dictionary<string, IChatClient> _chatClientCache = new();
27
+ private readonly IConfiguration _config;
28
+ private readonly object _lock = new();
29
+
30
+ public ModelRegistry(IConfiguration config, IHostEnvironment env)
31
+ {
32
+ _config = config;
33
+ var path = Path.Combine(env.ContentRootPath, "{{REGISTRY_PATH}}");
34
+ if (!File.Exists(path))
35
+ throw new InvalidOperationException($"Model registry not found at {path}");
36
+
37
+ var json = File.ReadAllText(path);
38
+ var doc = JsonSerializer.Deserialize<RegistryDocument>(json, JsonOpts)
39
+ ?? throw new InvalidOperationException("Empty model-registry.json");
40
+ _aliases = doc.Aliases;
41
+ DefaultAlias = doc.DefaultAlias;
42
+ }
43
+
44
+ /// <summary>The alias used when a caller does not specify one (from model-registry.json).</summary>
45
+ public string DefaultAlias { get; }
46
+
47
+ public IChatClient GetChatClient(string alias)
48
+ {
49
+ if (!_aliases.TryGetValue(alias, out var spec))
50
+ throw new InvalidOperationException($"Unknown model alias: {alias}");
51
+
52
+ lock (_lock)
53
+ {
54
+ if (_chatClientCache.TryGetValue(alias, out var cached))
55
+ return cached;
56
+
57
+ var client = spec.Provider switch
58
+ {
59
+ "openai" => BuildOpenAI(spec),
60
+ "ollama" => BuildOllama(spec),
61
+ // To add a provider, implement Build<Provider>(spec) following the
62
+ // pattern below and add a case here. Confirm the NuGet SDK first —
63
+ // see ai-agents-providers-model-registry §providers.
64
+ // "google" => BuildGoogle(spec),
65
+ // "anthropic" => BuildAnthropic(spec),
66
+ // "azure-openai" => BuildAzureOpenAI(spec),
67
+ _ => throw new NotSupportedException(
68
+ $"Provider '{spec.Provider}' has no branch. Add it following " +
69
+ $"the pattern in ai-agents-providers-model-registry.")
70
+ };
71
+
72
+ _chatClientCache[alias] = client;
73
+ return client;
74
+ }
75
+ }
76
+
77
+ private IChatClient BuildOpenAI(ModelAlias spec)
78
+ {
79
+ var apiKey = _config["OpenAI:ApiKey"]
80
+ ?? throw new InvalidOperationException("OpenAI:ApiKey not configured");
81
+ return new ChatClient(spec.Model, apiKey).AsIChatClient();
82
+ }
83
+
84
+ private IChatClient BuildOllama(ModelAlias spec)
85
+ {
86
+ // Ollama exposes an OpenAI-compatible endpoint — reuse the OpenAI ChatClient.
87
+ var endpoint = spec.Options?.GetValueOrDefault("endpoint")?.ToString()
88
+ ?? "http://localhost:11434/v1";
89
+ return new ChatClient(
90
+ spec.Model,
91
+ new ApiKeyCredential("ollama"), // any non-empty string
92
+ new OpenAIClientOptions { Endpoint = new Uri(endpoint) })
93
+ .AsIChatClient();
94
+ }
95
+
96
+ private static readonly JsonSerializerOptions JsonOpts = new()
97
+ {
98
+ PropertyNameCaseInsensitive = true,
99
+ ReadCommentHandling = JsonCommentHandling.Skip,
100
+ AllowTrailingCommas = true
101
+ };
102
+
103
+ // NOTE: Fallback is parsed but not yet acted on. Implementing automatic
104
+ // provider failover (retry on rate-limit/outage) is reserved for a later wave.
105
+ private sealed record RegistryDocument(
106
+ string Version,
107
+ string DefaultAlias,
108
+ Dictionary<string, ModelAlias> Aliases,
109
+ Dictionary<string, string>? Fallback
110
+ );
111
+
112
+ public sealed record ModelAlias(
113
+ string Provider,
114
+ string Model,
115
+ Dictionary<string, object>? Options
116
+ );
117
+ }
@@ -0,0 +1,95 @@
1
+ // TEMPLATE: PromptRepository.cs
2
+ // PURPOSE: Loads agent system prompts from the agent_prompts table, with in-memory caching.
3
+ // READS STANDARD: ai-agents-prompts-in-db
4
+ // PLACEHOLDERS:
5
+ // {{PROJECT_NAMESPACE}} — root namespace of the project
6
+ // LAST-VERIFIED: 2026-05-19
7
+
8
+ using Microsoft.EntityFrameworkCore;
9
+ using Microsoft.Extensions.Caching.Memory;
10
+
11
+ namespace {{PROJECT_NAMESPACE}}.AI;
12
+
13
+ // ---------------------------------------------------------------------------
14
+ // Entity — map this to the agent_prompts table (EF Core convention mapping).
15
+ // Alternatively, configure via Fluent API in your DbContext.OnModelCreating.
16
+ // ---------------------------------------------------------------------------
17
+
18
+ /// <summary>
19
+ /// EF Core entity for the agent_prompts table.
20
+ /// Content is immutable once written — use INSERT + flip is_active for versioning.
21
+ /// </summary>
22
+ public sealed class AgentPrompt
23
+ {
24
+ public Guid Id { get; init; } = Guid.CreateVersion7();
25
+ public required string AgentKey { get; init; }
26
+ public int Version { get; init; }
27
+ public required string Content { get; init; }
28
+ public bool IsActive { get; set; }
29
+ public DateTimeOffset CreatedAt { get; init; } = DateTimeOffset.UtcNow;
30
+ }
31
+
32
+ // ---------------------------------------------------------------------------
33
+ // Interface
34
+ // ---------------------------------------------------------------------------
35
+
36
+ /// <summary>
37
+ /// Provides the active system-prompt content for a named agent.
38
+ /// </summary>
39
+ public interface IPromptRepository
40
+ {
41
+ /// <summary>
42
+ /// Returns the content of the currently active prompt for <paramref name="agentKey"/>.
43
+ /// </summary>
44
+ /// <exception cref="InvalidOperationException">
45
+ /// Thrown when no row with <c>is_active = true</c> exists for <paramref name="agentKey"/>.
46
+ /// </exception>
47
+ Task<string> GetActivePromptAsync(string agentKey, CancellationToken ct = default);
48
+ }
49
+
50
+ // ---------------------------------------------------------------------------
51
+ // Implementation
52
+ // ---------------------------------------------------------------------------
53
+
54
+ // NOTE: Register in Program.cs (or a bootstrap extension):
55
+ // builder.Services.AddMemoryCache();
56
+ // builder.Services.AddScoped<IPromptRepository, PromptRepository>();
57
+ //
58
+ // The DbContext must expose: public DbSet<AgentPrompt> AgentPrompts { get; set; }
59
+ // Replace YourDbContext below with the actual DbContext type of the project.
60
+
61
+ /// <summary>
62
+ /// Reads the active agent prompt from the database with an in-memory cache
63
+ /// (default TTL: 5 minutes sliding). Cache invalidation is time-based;
64
+ /// for immediate invalidation after a prompt update call
65
+ /// <c>IMemoryCache.Remove($"agent_prompt:{agentKey}")</c>.
66
+ /// </summary>
67
+ public sealed class PromptRepository(YourDbContext db, IMemoryCache cache) : IPromptRepository
68
+ {
69
+ private static readonly TimeSpan CacheTtl = TimeSpan.FromMinutes(5);
70
+
71
+ public async Task<string> GetActivePromptAsync(string agentKey, CancellationToken ct = default)
72
+ {
73
+ var cacheKey = $"agent_prompt:{agentKey}";
74
+
75
+ if (cache.TryGetValue(cacheKey, out string? cached) && cached is not null)
76
+ return cached;
77
+
78
+ var content = await db.AgentPrompts
79
+ .Where(p => p.AgentKey == agentKey && p.IsActive)
80
+ .Select(p => p.Content)
81
+ .FirstOrDefaultAsync(ct);
82
+
83
+ if (content is null)
84
+ throw new InvalidOperationException(
85
+ $"No active prompt found for agent '{agentKey}'. " +
86
+ "Insert a row in agent_prompts with is_active = true for this agent_key.");
87
+
88
+ cache.Set(cacheKey, content, new MemoryCacheEntryOptions
89
+ {
90
+ SlidingExpiration = CacheTtl
91
+ });
92
+
93
+ return content;
94
+ }
95
+ }
@@ -0,0 +1,61 @@
1
+ // TEMPLATE: ResilientToolMiddleware.cs
2
+ // PURPOSE: Function-calling middleware — retry/rate-limit resilience + anti-hallucination arg validation.
3
+ // READS STANDARD: ai-agents-middleware-patterns
4
+ // PLACEHOLDERS:
5
+ // {{PROJECT_NAMESPACE}} — root namespace of the project
6
+ // LAST-VERIFIED: 2026-05-19
7
+
8
+ using Microsoft.Agents.AI;
9
+ using Microsoft.Extensions.AI;
10
+
11
+ namespace {{PROJECT_NAMESPACE}}.AI;
12
+
13
+ /// <summary>
14
+ /// Function-calling middleware that provides resilience (rate-limit + timeout handling)
15
+ /// and anti-hallucination argument validation.
16
+ ///
17
+ /// Registration:
18
+ /// agent.AsBuilder().Use(ResilientToolMiddleware.Handle).Build();
19
+ /// </summary>
20
+ public static class ResilientToolMiddleware
21
+ {
22
+ public static async ValueTask<object?> Handle(
23
+ AIAgent agent,
24
+ FunctionInvocationContext context,
25
+ Func<FunctionInvocationContext, CancellationToken, ValueTask<object?>> next,
26
+ CancellationToken cancellationToken)
27
+ {
28
+ // ─── Anti-hallucination: validate LLM-generated arguments BEFORE calling the tool ───
29
+ // If an argument is malformed, return a descriptive error string — the agent will
30
+ // self-correct on the next iteration without needing an external retry.
31
+ //
32
+ // Example: validate 'date' is ISO 8601
33
+ if (context.Arguments.TryGetValue("date", out var dateArg)
34
+ && !DateTime.TryParse(dateArg?.ToString(), out _))
35
+ {
36
+ return $"Invalid date format for '{context.Function.Name}'. Expected ISO 8601 (e.g. 2026-01-31).";
37
+ }
38
+ //
39
+ // Add additional argument validations here following the same pattern:
40
+ // if (context.Arguments.TryGetValue("argName", out var val) && <invalid condition>)
41
+ // return $"Descriptive error for '{context.Function.Name}': <what was wrong>.";
42
+
43
+ // ─── Resilience: execute tool and handle failures ───
44
+ try
45
+ {
46
+ return await next(context, cancellationToken);
47
+ }
48
+ catch (HttpRequestException ex) when (ex.StatusCode == System.Net.HttpStatusCode.TooManyRequests)
49
+ {
50
+ return "Service is temporarily busy. Please try again in a moment.";
51
+ }
52
+ catch (TimeoutException)
53
+ {
54
+ return $"Tool '{context.Function.Name}' timed out. Try a simpler query.";
55
+ }
56
+ catch (Exception ex)
57
+ {
58
+ return $"Error in {context.Function.Name}: {ex.Message}";
59
+ }
60
+ }
61
+ }
@@ -0,0 +1,107 @@
1
+ // TEMPLATE: VectorSearchTool.cs
2
+ // PURPOSE: A typed MAF tool that retrieves relevant chunks from the pgvector knowledge base.
3
+ // READS STANDARD: ai-agents-rag-custom-pgvector
4
+ // PLACEHOLDERS:
5
+ // {{PROJECT_NAMESPACE}} — root namespace of the project (e.g., MyProject)
6
+ // LAST-VERIFIED: 2026-05-19
7
+ //
8
+ // SECURITY NOTE — tenant_id:
9
+ // tenant_id is resolved from the injected ITenantContext (or equivalent auth accessor),
10
+ // NEVER from a tool parameter visible to the LLM. A model-facing tenant parameter would
11
+ // allow prompt-injection to cross tenant boundaries.
12
+ //
13
+ // NPGSQL + PGVECTOR PARAMETER BINDING:
14
+ // This template uses NpgsqlDataSource (raw SQL) for the cosine-distance query.
15
+ // The project must call dataSourceBuilder.UseVector() before building the data source
16
+ // so Npgsql can map the vector type — see infrastructure-neon-pgvector.
17
+ //
18
+ // // VERIFY: The exact Npgsql parameter binding for a pgvector type has been written
19
+ // // conservatively below using new Pgvector.Vector(float[]).
20
+ // // Confirmed pattern from neon-pgvector standard (Pgvector package):
21
+ // // cmd.Parameters.AddWithValue("queryVec", new Pgvector.Vector(embedding.ToArray()));
22
+ // // If the project uses a different Npgsql/Pgvector version, verify the parameter API.
23
+ //
24
+ // REGISTRATION (in agent setup code):
25
+ // var tool = sp.GetRequiredService<VectorSearchTool>();
26
+ // var agent = modelRegistry.GetChatClient("text-default")
27
+ // .AsAIAgent(
28
+ // instructions: systemPrompt,
29
+ // tools: [AIFunctionFactory.Create(tool.SearchAsync)]);
30
+ //
31
+ // ALTERNATIVE — EF Core:
32
+ // If the project already wires pgvector through EF Core (UseVector(), HasMethod("hnsw")),
33
+ // replace the NpgsqlDataSource usage with db.Database.SqlQuery<string>() per
34
+ // infrastructure-neon-pgvector. The tool method signature stays identical.
35
+
36
+ using System.ComponentModel;
37
+ using Npgsql;
38
+ using Pgvector;
39
+
40
+ namespace {{PROJECT_NAMESPACE}}.AI;
41
+
42
+ /// <summary>
43
+ /// MAF tool: searches the knowledge base for chunks semantically similar to a query.
44
+ /// Registered on an agent via <c>AIFunctionFactory.Create(tool.SearchAsync)</c>.
45
+ /// The agent calls this autonomously when it needs grounding context.
46
+ /// </summary>
47
+ public sealed class VectorSearchTool(
48
+ EmbeddingService embeddingService,
49
+ NpgsqlDataSource dataSource,
50
+ ITenantContext tenantContext) // Resolved from DI — scoped to the authenticated request.
51
+ // Replace with Guid currentTenantId if a simpler accessor is preferred.
52
+ {
53
+ private const int DefaultTopK = 5;
54
+
55
+ /// <summary>
56
+ /// Searches the knowledge base for context relevant to a question.
57
+ /// </summary>
58
+ /// <param name="query">The natural-language search query.</param>
59
+ /// <param name="ct">Cancellation token.</param>
60
+ /// <returns>
61
+ /// Concatenated text of the top matching chunks, separated by double newlines.
62
+ /// Returns an empty string if no results are found.
63
+ /// </returns>
64
+ [Description("Searches the knowledge base for context relevant to a question")]
65
+ public async Task<string> SearchAsync(
66
+ [Description("the natural-language search query")] string query,
67
+ CancellationToken ct = default)
68
+ {
69
+ // 1. Embed the query at search time.
70
+ ReadOnlyMemory<float> queryVector = await embeddingService.EmbedAsync(query, ct);
71
+
72
+ // 2. Resolve tenant from auth context — never from a model-supplied parameter.
73
+ Guid tenantId = tenantContext.CurrentTenantId;
74
+
75
+ // 3. Run parameterized cosine-distance query.
76
+ // ORDER BY embedding <=> @queryVec sorts ascending by distance (most similar first).
77
+ const string sql = """
78
+ SELECT content
79
+ FROM kb_embeddings
80
+ WHERE tenant_id = @tenant
81
+ ORDER BY embedding <=> @queryVec
82
+ LIMIT @topK
83
+ """;
84
+
85
+ var chunks = new List<string>(DefaultTopK);
86
+
87
+ await using var conn = await dataSource.OpenConnectionAsync(ct);
88
+ await using var cmd = new NpgsqlCommand(sql, conn);
89
+
90
+ cmd.Parameters.AddWithValue("tenant", tenantId);
91
+
92
+ // VERIFY: Pgvector.Vector wraps a float[] for Npgsql parameter binding.
93
+ // The project must have called dataSourceBuilder.UseVector() on NpgsqlDataSourceBuilder.
94
+ // NuGet: Pgvector (matches the Pgvector.EntityFrameworkCore used in neon-pgvector.md).
95
+ cmd.Parameters.AddWithValue("queryVec", new Vector(queryVector.ToArray()));
96
+
97
+ cmd.Parameters.AddWithValue("topK", DefaultTopK);
98
+
99
+ await using var reader = await cmd.ExecuteReaderAsync(ct);
100
+ while (await reader.ReadAsync(ct))
101
+ {
102
+ chunks.Add(reader.GetString(0));
103
+ }
104
+
105
+ return string.Join("\n\n", chunks);
106
+ }
107
+ }
@@ -0,0 +1,58 @@
1
+ // TEMPLATE: model-registry.json (place in project at config/model-registry.json)
2
+ // PURPOSE: Single source of truth for model selection. Agents reference aliases, not models.
3
+ // READS STANDARD: ai-agents-providers-model-registry
4
+ // PROVIDERS: openai + ollama work out-of-the-box with the ModelRegistry template.
5
+ // For google / anthropic, add a provider branch first (see the standard).
6
+ // PLACEHOLDERS:
7
+ // {{PROJECT_DEFAULT_ALIAS}} — alias used when none specified (default: "text-default")
8
+ // LAST-VERIFIED: 2026-05-19
9
+ {
10
+ "$schema": "./model-registry.schema.json",
11
+ "version": "1.0",
12
+ "defaultAlias": "{{PROJECT_DEFAULT_ALIAS}}",
13
+ "aliases": {
14
+ "text-default": {
15
+ "provider": "openai",
16
+ "model": "gpt-4o-mini",
17
+ "options": { "temperature": 0.7 }
18
+ },
19
+ "text-heavy": {
20
+ "provider": "openai",
21
+ "model": "gpt-4o",
22
+ "options": { "temperature": 0.5 }
23
+ },
24
+ "reasoning": {
25
+ "provider": "openai",
26
+ "model": "o3-mini",
27
+ "options": { "reasoningEffort": "medium" }
28
+ },
29
+ "long-form": {
30
+ "provider": "anthropic",
31
+ "model": "claude-sonnet-4-6",
32
+ "options": {}
33
+ },
34
+ "vision": {
35
+ "provider": "google",
36
+ "model": "gemini-2.5-flash",
37
+ "options": {}
38
+ },
39
+ "embeddings": {
40
+ "provider": "openai",
41
+ "model": "text-embedding-3-small",
42
+ "options": { "dimensions": 1536 }
43
+ },
44
+ "local-dev": {
45
+ "provider": "ollama",
46
+ "model": "llama3.2:3b",
47
+ "options": { "endpoint": "http://localhost:11434/v1" }
48
+ },
49
+ "transcription": {
50
+ "provider": "openai",
51
+ "model": "whisper-1",
52
+ "options": {}
53
+ }
54
+ },
55
+ "fallback": {
56
+ "text-default": "ollama/llama3.2:3b"
57
+ }
58
+ }
@@ -0,0 +1,58 @@
1
+ -- TEMPLATE: agent-prompts-migration.sql
2
+ -- PURPOSE: Creates the agent_prompts table for runtime-editable, versioned agent instructions.
3
+ -- READS STANDARD: ai-agents-prompts-in-db
4
+ -- PLACEHOLDERS:
5
+ -- {{SCHEMA}} — target schema (default: public)
6
+ -- LAST-VERIFIED: 2026-05-19
7
+
8
+ -- ============================================================
9
+ -- 1. TABLE
10
+ -- ============================================================
11
+
12
+ CREATE TABLE {{SCHEMA}}.agent_prompts (
13
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
14
+ agent_key text NOT NULL,
15
+ version int NOT NULL,
16
+ content text NOT NULL,
17
+ is_active boolean NOT NULL DEFAULT false,
18
+ created_at timestamptz NOT NULL DEFAULT now()
19
+ );
20
+
21
+ COMMENT ON TABLE {{SCHEMA}}.agent_prompts IS 'Runtime-editable, versioned system prompts for AI agents.';
22
+ COMMENT ON COLUMN {{SCHEMA}}.agent_prompts.agent_key IS 'Logical identifier for the agent (e.g. ''proposal-agent'').';
23
+ COMMENT ON COLUMN {{SCHEMA}}.agent_prompts.version IS 'Monotonically increasing per agent_key. Never reuse a version number.';
24
+ COMMENT ON COLUMN {{SCHEMA}}.agent_prompts.content IS 'Immutable system-prompt text. UPDATE of this column is forbidden — insert a new row instead.';
25
+ COMMENT ON COLUMN {{SCHEMA}}.agent_prompts.is_active IS 'Exactly one row per agent_key may have is_active = true (enforced by ix_agent_prompts_active).';
26
+ COMMENT ON COLUMN {{SCHEMA}}.agent_prompts.created_at IS 'Audit timestamp. Set at insert time, never updated.';
27
+
28
+ -- ============================================================
29
+ -- 2. INDEXES
30
+ -- ============================================================
31
+
32
+ -- Unique partial index: enforces at DB level that only one active prompt
33
+ -- exists per agent_key. Any attempt to INSERT a second active row for the
34
+ -- same key will fail with a unique-constraint violation.
35
+ CREATE UNIQUE INDEX ix_agent_prompts_active
36
+ ON {{SCHEMA}}.agent_prompts (agent_key)
37
+ WHERE is_active;
38
+
39
+ -- Regular index for the PromptRepository lookup (agent_key + is_active filter).
40
+ CREATE INDEX ix_agent_prompts_agent_key
41
+ ON {{SCHEMA}}.agent_prompts (agent_key);
42
+
43
+ -- Unique index: prevents duplicate version numbers per agent_key.
44
+ CREATE UNIQUE INDEX ix_agent_prompts_agent_key_version
45
+ ON {{SCHEMA}}.agent_prompts (agent_key, version);
46
+
47
+ -- ============================================================
48
+ -- 3. SEED (optional — remove if managed via backoffice)
49
+ -- ============================================================
50
+
51
+ -- INSERT INTO {{SCHEMA}}.agent_prompts (agent_key, version, content, is_active)
52
+ -- VALUES ('my-agent', 1, 'You are a helpful assistant.', true);
53
+
54
+ -- ============================================================
55
+ -- ROLLBACK
56
+ -- ============================================================
57
+
58
+ -- DROP TABLE IF EXISTS {{SCHEMA}}.agent_prompts CASCADE;