π Adapter Generator Agent Specification
π― Purpose
The Adapter Generator Agent automates the creation of infrastructure adapters that implement the boundaries between the application layer (use cases) and the outside world β including:
Controllers (REST/gRPC)
Messaging consumers (event bus, service bus, Kafka, etc.)
Persistence adapters (repositories, blob access, NoSQL, SQL)
Outbound clients (HTTP, SOAP, gRPC, SDK-based integrations)
It transforms abstract port definitions from the Application Layer into production-grade, pluggable, observable code .
π§± Why This Agent Is Critical
Without this agent:
Developers must manually write boilerplate for each port and external integration
Clean Architecture separation may be violated (logic leaking into controllers/repos)
Cross-cutting concerns like logging, retries, security, tracing may be forgotten
Testing and mocking of adapters becomes inconsistent
Infrastructure code diverges across microservices
With this agent:
β
All external boundary implementations are consistent, observable, testable
β
Adapters follow ConnectSoftβs Clean Architecture and domain-layer contracts
β
Services are immediately runnable , with REST, gRPC, bus listeners, or repositories in place
β
External system connectors (e.g., Stripe, Segment, Azure Blob, CRM) are auto-wired
β
All adapters are span-traced , exception-logged , and resilience-enabled
π§ Examples of Adapter Generation
Input
Output
CreateUserUseCase input port
POST /users controller with DI + validation
GetInvoiceQuery input port
GET /invoices/{id} handler
SendEmailCommand output port
IEmailSender β concrete SMTP or API client
UserRegisteredEvent input port
Kafka consumer + message mapper + forwarder
UserRepository output port
NHibernate-backed repository implementation
External CRM client
HTTP client with retry + circuit breaker adapter scaffolded
π§ Architectural Placement
flowchart TD
Domain --> Application
Application --> AdapterGenerator
AdapterGenerator --> Controllers
AdapterGenerator --> EventConsumers
AdapterGenerator --> Repositories
AdapterGenerator --> ExternalClients
Hold "Alt" / "Option" to enable pan & zoom
π Adapter Generatorβs Strategic Role
Area
Impact
Clean Architecture Enforcement
Adapters never leak domain/application logic
Microservice Readiness
Services have working endpoints and persistence from day one
Dev Acceleration
Eliminates repetitive boilerplate for every service
Platform Compliance
Tracing, logging, security, and testability are enforced
Extensibility
New adapters (e.g., Redis, third-party SaaS) added by plugin or template override
π‘ Scope of Influence
The Adapter Generator Agent controls the generation of all infrastructure-side adapter implementations required to connect domain logic to external systems or transport layers.
It respects Clean Architecture boundaries by implementing input ports (infrastructure β application) and output ports (application β infrastructure).
π§± What This Agent Owns
Adapter Type
Description
REST Controllers
ASP.NET Core HTTP endpoints for commands and queries
gRPC Services
Service handlers for gRPC-defined contracts
Message Consumers
MassTransit consumers, Azure Service Bus, Kafka listeners
Persistence Adapters
NHibernate/EF repositories, NoSQL clients, blob storage
API Clients
Typed HTTP clients with retry policies, OAuth2/OIDC, headers, and resilience
External SDK Adapters
Wrappers for third-party SDKs (Stripe, Segment, Hubspot)
Test Doubles & Mocks
In-memory or mock implementations of output ports
π§© Adapter Placement in Clean Architecture
flowchart TD
ExternalSystems[External Systems] --> InboundAdapters[Inbound Adapters: REST, gRPC, Kafka]
InboundAdapters --> Application[Application Layer]
Application --> OutboundAdapters[Outbound Adapters: Repos, Clients, Message Brokers]
OutboundAdapters --> ExternalSystems
Hold "Alt" / "Option" to enable pan & zoom
π§ What This Agent Does Not Own
Component
Responsible Agent
Use case interactor logic
Application Architect Agent
Port interface definitions
Microservice Generator / App Layer
OpenAPI/gRPC contract generation
API Designer Agent
Infrastructure provisioning (DBs, endpoints)
Infrastructure Architect Agent
Domain modeling (Aggregates, Entities)
Domain Modeler Agent
βοΈ Supported Transport & Infrastructure Types
Layer
Technologies
HTTP
ASP.NET Core MVC, REST, Swagger, OpenAPI
gRPC
gRPC ServiceHost in .NET
Messaging
MassTransit, Azure Service Bus, RabbitMQ, Kafka
Storage
NHibernate, Entity Framework, Dapper, MongoDB
File/Blob
Azure Blob Storage, Amazon S3
External APIs
HttpClientFactory, OpenIdConnect auth, SDK integration
Observability
Serilog, OTEL spans, resilience policies (Polly)
𧬠Adapter Classification (by Direction)
Type
Adapter Role
Input Adapters
Serve requests into the application: controllers, handlers, consumers
Output Adapters
Send messages, persist data, call external services
Hybrid Adapters
Perform both (e.g., message transformer + HTTP caller combo)
π Dynamic Composition
Adapters are generated per:
Port β transport pair (GetUser β REST GET)
Configuration hints (requires OAuth2, retries: 3, emit_span: true)
Template selection (default, custom template override, plugin-bound)
Infrastructure capabilities (MassTransit, Serilog, Azure Blob, PostgreSQL)
π Core Responsibilities
The Adapter Generator Agent is responsible for transforming abstract port definitions from the application layer into ready-to-use infrastructure adapter implementations that align with Clean Architecture, support observability, and integrate seamlessly into the ConnectSoft microservice ecosystem.
β
1. Adapter Scaffolding from Port Definitions
Task
Output
Map input-ports.json to controllers, gRPC handlers, message consumers
e.g., CreateUserCommand β POST /users
Map output-ports.json to repositories, clients, message publishers
e.g., IEmailSender β SMTPAdapter.cs
Add DI container registrations, naming conventions, and interfaces
Updates Startup.cs or AdaptersRegistry.cs
π 2. Transport-Specific Adapter Generation
Transport
Output
HTTP/REST
ASP.NET Core controller with routing, model binding, validation
gRPC
gRPC service inheriting from generated base classes
Kafka / Service Bus / RabbitMQ
Message consumer using MassTransit handler
Azure Blob / S3
Adapter using blob client with injected configuration
OpenId Connect APIs
OAuth2-backed HttpClient using ConnectSoft.Extensions.Http.OpenIdConnect
π 3. Boundary Enforcement
Rule
Enforcement
Adapter must depend only on port (interface) β not domain or app internals
β
No business logic in controllers or consumers
β
All side effects (IO, messaging, calls) handled in adapter
β
Port-based inversion: all outbound dependencies go through injected interfaces
β
π 4. Cross-Cutting Concern Injection
All adapters must support:
β
Structured logging (e.g., Serilog)
β
OpenTelemetry spans and baggage propagation
β
Polly-based retry, timeout, and circuit-breaker policies
β
Security (e.g., authorization attributes, API keys, OAuth2 tokens)
β
CancellationToken propagation and timeout enforcement
β
Structured error handling (ProblemDetails for REST)
π 5. Testability Enforcement
Each adapter will generate or expose:
β
Interface-first design (IUserRepository, IExternalCrmClient)
β
In-memory or mockable implementations for test harnesses
β
Unit test scaffold (if test generation is enabled)
β
Fake data sources (for repositories and outbound services)
π¦ 6. Modular Output Integration
Generated adapters are:
π§© Written into the Infrastructure project of the service
π Organized by port type (Controllers/, Consumers/, Persistence/, Clients/)
π§ Registered via dependency injection templates or .AddAdapters() helpers
π§ͺ Optionally accompanied by test scaffolding and usage hints
π§ Adapter Examples
Port
Adapter Generated
ICustomerRepository
CustomerRepository.cs (EF/NH + LINQ impl)
IAnalyticsService
MixpanelAdapter.cs with retry + circuit-breaker
INotificationClient
HttpNotificationClient.cs using typed HttpClient
IUserCommandHandler
UsersController.cs (REST) or UserService.cs (gRPC)
π Responsibility to Span Relationship
Responsibility
Span
Adapter generated
adapter_generated
Port matched
adapter_port_resolved
Transport resolved
adapter_transport_matched
Retry logic applied
adapter_resilience_applied
Controller/handler injected
adapter_registered
π€ Core Output Overview
The Adapter Generator Agent emits production-ready, testable, Clean Architecture-compliant code files that implement the input and output ports of the application layer β turning abstract contracts into operational interfaces.
Adapters are code-generated , observable , and optionally accompanied by unit test scaffolds , interface contracts , and DI wiring .
π¦ Output Artifact Types
Type
Output
Input Adapters
REST controllers, gRPC handlers, MassTransit consumers, etc.
Output Adapters
HTTP clients, repository implementations, blob storage, SDK wrappers
Wiring Code
AdaptersRegistry.cs, DI entries, IServiceCollection.AddAdapters()
Policy Decorators
Retry handlers, Polly wrappers, circuit breakers
Tracing Hooks
ActivitySource-based span injection, baggage propagation
Tests (optional)
In-memory adapters, mocks, unit test templates
Manifest
adapters-manifest.json: maps port β adapter β file paths
π Example Output Directory Structure
/Infrastructure
/Adapters
/Controllers
- UsersController.cs
- InvoicesController.cs
/Consumers
- UserRegisteredConsumer.cs
/Repositories
- UserRepository.cs
/Clients
- CrmClient.cs
/Blobs
- UserPhotoBlobStorage.cs
/Registrations
- AdaptersRegistry.cs
/tests
/Infrastructure.Adapters.Tests
- UsersControllerTests.cs
- CrmClientTests.cs
[ApiController]
[Route("api/users")]
public class UsersController : ControllerBase
{
private readonly ICreateUserHandler _handler ;
public UsersController ( ICreateUserHandler handler )
{
_handler = handler ;
}
[HttpPost]
public async Task < IActionResult > CreateUser ([ FromBody ] CreateUserDto dto , CancellationToken ct )
{
using var activity = ActivitySource . StartActivity ( "CreateUser" );
var result = await _handler . HandleAsync ( dto , ct );
return Ok ( result );
}
}
π§Ύ Sample: CrmClient.cs (Output Adapter)
public class CrmClient : ICrmClient
{
private readonly HttpClient _httpClient ;
private readonly ILogger < CrmClient > _logger ;
public CrmClient ( HttpClient httpClient , ILogger < CrmClient > logger )
{
_httpClient = httpClient ;
_logger = logger ;
}
public async Task PostContactAsync ( ContactDto contact , CancellationToken ct )
{
using var activity = ActivitySource . StartActivity ( "PostContactToCRM" );
var response = await _httpClient . PostAsJsonAsync ( "/contacts" , contact , ct );
response . EnsureSuccessStatusCode ();
}
}
π Sample: adapters-manifest.json
{
"service" : "UserService" ,
"environment" : "Production" ,
"input_adapters" : [
{
"port" : "CreateUserCommand" ,
"type" : "REST" ,
"file" : "UsersController.cs"
}
],
"output_adapters" : [
{
"port" : "ICrmClient" ,
"type" : "REST" ,
"file" : "CrmClient.cs"
}
],
"generated_at" : "2025-05-02T03:36:00Z" ,
"trace_id" : "trace-adapter-78210" ,
"agent_version" : "1.2.0"
}
π Output Validation Rules
Rule
Description
All generated files must include trace_id in metadata/header
β
Controller and handler classes must respect port names
β
REST/gRPC mappings must match route/method defined in OpenAPI
β
Retry/timeout must match adapter-policies.yaml
β
OTEL spans must be wrapped around all async entrypoints
β
π§ͺ Optional Generated Tests
UsersControllerTests.cs β controller wiring, HTTP routing
CrmClientTests.cs β client mocking, HTTP expectation
UserRepositoryTests.cs β NHibernate test with in-memory DB
π§ Knowledge Base Overview
The Adapter Generator Agent is backed by a structured and extensible knowledge base that enables it to:
Generate infrastructure adapters for a wide variety of transports and technologies
Apply consistent patterns across REST, gRPC, messaging, persistence, and client integrations
Enforce observability, error handling, retry, and Clean Architecture boundaries
Map abstract application ports to platform-aligned, testable implementations
π Adapter Template Knowledge Base
Category
Examples
REST Input
ApiControllerTemplate, PostHandlerWithDTO, QueryControllerWithRouteBinding
gRPC
GrpcUnaryHandlerTemplate, GrpcStreamHandlerTemplate
Messaging Consumers
MassTransitConsumerTemplate, ServiceBusTriggerTemplate, KafkaConsumerTemplate
Repositories
NHibernateRepositoryTemplate, EfCoreRepositoryTemplate, MongoRepositoryTemplate
External API Clients
HttpClientAdapterTemplate, OAuthClientWithRetryTemplate
Blob Storage
AzureBlobAdapterTemplate, S3AdapterTemplate
OpenTelemetry Integration
TracingWrapperTemplate, SpanInjectedMethodBlock
Unit Tests
ControllerTestTemplate, HttpClientTestTemplate, RepositoryTestHarness
π Port-to-Template Matching Rules
Input Port Metadata
Mapped Template
transport: REST + method: POST
PostHandlerWithDTO.cs.template
transport: Kafka + input: UserRegisteredMessage
MassTransitConsumerTemplate
outputPort.type: HttpClient + auth: OAuth2
OAuthClientWithRetryTemplate
outputPort.type: Persistence + type: NHibernate
NHibernateRepositoryTemplate
π§ Semantic Memory Classification
Port metadata is stored in memory by:
Port type: input, output, event-driven
Transport: REST, gRPC, Kafka, ServiceBus, Storage, HttpClient
Domain entity: linked to aggregate, event, or value object
Policy tier: resilience: high, auth: none, timeout: strict, logging: verbose
Return semantics: async, task with result, void, event-only
π‘ Inferred Behaviors from Memory
Heuristic
Result
Ports with Create* or Add* names β generate POST REST endpoint
transport: REST + openapi.yaml β route + HTTP status auto-aligned
If port returns Task and has no response DTO β assume 204 NoContent
Output ports referencing Blob β generate Azure Blob client + interface
Any adapter using HttpClient β inject retry policy and circuit breaker
π Template Library Source
Templates are resolved from:
/Templates/Adapters/
- Rest/
- ApiControllerTemplate.cs
- PostHandlerWithDTO.cs
- Messaging/
- MassTransitConsumerTemplate.cs
- Persistence/
- NHibernateRepositoryTemplate.cs
- Clients/
- HttpClientAdapterTemplate.cs
- OAuthClientWithRetryTemplate.cs
- Observability/
- TracingWrapperTemplate.cs
Each template supports parameterized substitution of:
Class name
Port/interface name
DTOs
Transport-specific options (route, headers, topics, keys)
Span trace logic
DI and namespace imports
β»οΈ Versioned Knowledge Reuse
Mechanism
Example
Template versioning
PostHandlerWithDTO.v2.cs.template
Policy versioning
Retry policies based on adapter-policies.yaml@1.2.0
Transport fallback logic
If gRPC not enabled β fallback to REST controller template
DTO reuse
Types resolved from api-library.csproj or domain-types.dtos.cs
π§© Extensibility
New templates can be added per team/domain (/Templates/Finance/KafkaInvoiceConsumer.cs.template)
Override templates per port if needed (custom-template-id: CrmRetryClientV3)
Injectable formatters for naming, test doubles, OpenAPI expectations
π End-to-End Adapter Generation Flow
The Adapter Generator Agent executes a deterministic, policy-driven generation process that transforms abstract port declarations into fully functional adapter code β consistent with Clean Architecture and ConnectSoft platform standards.
This flow is observable, traceable, and testable end-to-end.
π Step-by-Step Generation Pipeline
Load:
input-ports.json
output-ports.json
transport-config.yaml
openapi.yaml (optional)
adapter-policies.yaml
Validate:
Port β DTO match
Supported transports enabled
Forbidden adapter types blocked
OpenAPI/gRPC routes and methods match expected format
2οΈβ£ Port Classification and Routing
Classification
Result
CreateOrderCommand β REST
REST controller template
UserRegisteredEvent β Kafka
Messaging consumer template
ICustomerRepository β NHibernate
Repository template
IPaymentGatewayClient β REST (OAuth2)
Client adapter with token injection
Each port is routed to the appropriate template generator .
3οΈβ£ Template Rendering
Resolve:
DTOs and method signatures
Transports (HTTP, Kafka, gRPC)
Span injection (if otel_tracing: true)
Retry/circuit breaker policies
Naming and namespace conventions
Render output files:
Controllers
Repositories
Clients
Messaging consumers
Test doubles
4οΈβ£ Infrastructure Wiring
Create or update:
AdaptersRegistry.cs for DI container registration
IServiceCollection.AddAdapters() method (auto-discovered adapters)
Policy decorators for retries/timeouts
Route mapping (if REST), topic binding (if Kafka), client settings (if HTTP)
5οΈβ£ Test Harness Injection (Optional)
Generate:
Test class stubs per adapter (UsersControllerTests.cs)
Mocks or in-memory fakes (FakeUserRepository.cs)
Contract validation tests (e.g., OpenAPI-based verification)
6οΈβ£ Tracing and Observability Hooks
Inject:
ActivitySource.StartActivity("AdapterX") in every entrypoint
Baggage/context propagation
Serilog logs and structured error handling
Optional correlation ID headers or OTEL exporters
7οΈβ£ Manifest & Lifecycle Emission
Emit:
adapters-manifest.json with all generated files
AdapterGenerationPlanPublished event
OTEL spans:
adapter_generated
adapter_transport_matched
adapter_policy_applied
π§ Flowchart: Adapter Generation
flowchart TD
A[Parse Port Definitions] --> B[Match Template]
B --> C[Render Adapter Files]
C --> D[Generate Registry & Wiring]
D --> E[Add OTEL + Retry Policies]
E --> F[Emit Manifest & Spans]
F --> G[Publish Lifecycle Event]
Hold "Alt" / "Option" to enable pan & zoom
π Auto-Correction & Resilience Logic
Condition
Correction
No transport declared
Default to REST
Retry policy missing
Use platform default from adapter-policies.yaml
DTOs missing in API lib
Emit stub with TODO marker
Forbidden adapter type
Block and emit AdapterGenerationBlocked
OTEL not enabled but inject_otel: true
Inject default spans into controller + client
π Telemetry Spans Emitted
Span
Trigger
adapter_generated
Each adapter successfully scaffolded
adapter_test_stub_created
Test output included
adapter_transport_mapped
Transport matched and rendered
adapter_resilience_applied
Retry/timeouts inserted
π οΈ Semantic Kernel Skills Overview
The Adapter Generator Agent is composed of modular Semantic Kernel (.NET) skills that handle:
Port classification and template resolution
Adapter code generation and decoration
Policy injection
Observability wiring
Test scaffold emission
Manifest and trace reporting
All skills are observable, reusable, and configured through the ConnectSoft platform.
π§© Core Skills Used
π§± 1. Port & Transport Mapping
Skill
Purpose
PortClassifierSkill
Determines if port is REST, gRPC, messaging, or persistence
TransportTemplateRouterSkill
Resolves the correct template for each adapter type
DtoBinderSkill
Finds and validates input/output DTO types for the adapter
OpenApiRouteMapperSkill
Extracts REST path/method from openapi.yaml
π§° 2. Adapter Generator Skills
Skill
Purpose
RestControllerGeneratorSkill
Generates controller from REST port
GrpcHandlerGeneratorSkill
Generates gRPC service with contract bindings
MessagingConsumerGeneratorSkill
Creates Kafka, MassTransit, or ServiceBus handlers
RepositoryAdapterGeneratorSkill
Implements abstract repositories using NHibernate or EF
HttpClientAdapterGeneratorSkill
Generates typed client with policies and auth decorators
π 3. Policy & Tracing Injectors
Skill
Purpose
RetryPolicyDecoratorSkill
Applies Polly-based retries and circuit breakers
OtelSpanInjectorSkill
Wraps key methods with ActivitySource spans
AuthorizationWrapperSkill
Adds attribute-based authorization for REST/gRPC
ExceptionHandlerGeneratorSkill
Generates try/catch + ProblemDetails responses
π§ͺ 4. Test Scaffold and Fakes
Skill
Purpose
TestStubWriterSkill
Emits xUnit/MSTest/NUnit test templates per adapter
FakeAdapterScaffolderSkill
In-memory mocks for repositories and outbound clients
ContractValidatorSkill
Generates OpenAPI/gRPC test assertions for controllers and clients
Skill
Purpose
AdaptersManifestWriterSkill
Emits adapters-manifest.json with output trace metadata
LifecycleEventPublisherSkill
Emits AdapterGenerationPlanPublished event
TelemetrySpanEmitterSkill
Traces key lifecycle events during generation
OutputTraceTaggerSkill
Injects headers into generated files (trace_id, environment, version)
π§ Example: Semantic Memory Lookup
{
"type" : "input-port" ,
"name" : "GetUserByIdQuery" ,
"transport" : "REST" ,
"method" : "GET" ,
"route" : "/users/{id}" ,
"dto" : "UserDto" ,
"tracing_enabled" : true
}
β Routed to:
- RestControllerGeneratorSkill
- OtelSpanInjectorSkill
- OpenApiRouteMapperSkill
π Fallback and Retry Behavior
Skill
Fallback Trigger
Recovery
DtoBinderSkill
DTO missing
Emit scaffold with TODO comment and warning
HttpClientAdapterGeneratorSkill
No retry config
Use default: 3 retries, 2s timeout
GrpcHandlerGeneratorSkill
gRPC not supported
Downgrade to REST controller
TestStubWriterSkill
Test output disabled
Skip generation without error
π Metrics Emitted Per Skill
Metric
Purpose
adapters_generated_total
Total generated input/output adapters
transport_coverage_ratio
% of ports with valid transport mapping
otel_wrapped_adapter_ratio
OTEL span coverage in adapters
test_templates_emitted_total
Total unit test stubs created
π§° Technology Stack Overview
The Adapter Generator Agent produces real-world infrastructure adapters using technologies aligned with ConnectSoftβs clean architecture platform . These technologies ensure every adapter is secure , observable , testable , and deployment-ready β across multiple transports.
π Supported Transport Technologies
Transport
Technology
REST (HTTP)
ASP.NET Core MVC Controllers, FluentValidation, ProblemDetails
gRPC
gRPC Service Bindings via Grpc.AspNetCore.Server
Messaging
MassTransit (Kafka, RabbitMQ, Azure Service Bus), AutoSubscriber, MessageConsumers
Blob/File
Azure Blob Storage SDK, S3 SDK (AWSSDK.S3), ConnectSoft.BlobAdapter.*
SQL/ORM
NHibernate, Entity Framework Core, Dapper
External APIs
HttpClientFactory, Refit, ConnectSoft.Extensions.Http.OpenIdConnect
NoSQL
MongoDB.Driver, CosmosDB SDK (planned)
Layer
Library / Tool
Dependency Injection
Microsoft.Extensions.DependencyInjection
Resilience
Polly for retries, timeouts, circuit breakers
Logging
Serilog, ILogger<T>, structured log fields
Tracing
OpenTelemetry, ActivitySource, Baggage, TraceContextPropagator
Configuration
IOptions<T>, environment config bindings
API Modeling
FluentValidation, System.ComponentModel.DataAnnotations
Security
AuthorizeAttribute, OIDC token handlers, OAuth2 client credentials
π§ͺ Testing Technologies
Type
Tool
Unit Testing
MSTest, xUnit, NUnit (templated)
Mocking
Moq, NSubstitute, in-memory test adapters
Contract Tests
HttpClientMock, OpenAPI verifiers (e.g., NSwag)
Integration Stubs
WireMock.Net, TestServer, Docker Compose for isolated adapters
Output
Details
Adapters
C# classes with DI-conformant constructor injection
Tests
Separate test project or folder, mocks, test harness
Manifests
adapters-manifest.json with trace_id, adapter paths, timestamps
Telemetry
Spans and logs embedded in adapters
DI Registration
AdaptersRegistry.cs or .AddAdapters() extension
π§© Template Engine & DSLs
Component
Description
Template Format
Mustache / Razor Light / Scriban (plug-in support)
Parameter Substitution
Port name, DTOs, namespace, class suffixes
Policy Injection Points
Retry, circuit breaker, tracing, cancellation, auth decorators
Plugin Architecture
Custom template sets per domain/team/microservice cluster
𧬠Cross-Cutting Feature Support
Feature
Mechanism
Tracing
OpenTelemetry spans inside each method block
Retry
Polly wrapped inside HttpClientFactory or outbound adapter
Logging
ILogger<T> injected into each adapter
Cancellation
All async methods receive CancellationToken
Authentication
Adapters support API Key, OAuth2, Azure AD (per adapter-policies.yaml)
Output Traceability
Code comments include trace_id, generated_at, agent_version
β
Integration Compatibility
Works With
Example
Microservice Template
Injected into Infrastructure layer (or Adapters/)
API Library Generator
Resolves DTOs/interfaces from shared NuGet/API project
DevOps Pipelines
Manifests emitted for test runs, traceability, regression
Observability Stack
Span context linked to service-wide OTEL collector
Adapter Registry
Uses reflection or convention-based scan to inject adapters
π Resolution Algorithm Overview
1οΈβ£ Determine Direction
From Input
Result
input-ports.json β request entrypoints
β Generate controller , gRPC handler , or consumer
output-ports.json β application dependencies
β Generate repository , client , publisher , or blob adapter
2οΈβ£ Resolve Transport Type
From Input
Decision
transport: REST β controller or HTTP client
transport: gRPC β service handler or gRPC client
transport: Kafka, ServiceBus, etc. β MassTransit consumer
transport: Persistence β NHibernate or EF repository
transport: Blob β AzureBlob or S3 adapter
transport: SDK or HttpClient β typed client adapter
3οΈβ£ Map to Template Type
Port Metadata
Template Used
method: POST, dto: CreateUserDto
PostHandlerWithDTO
type: NHibernate, entity: Invoice
NHibernateRepositoryTemplate
auth: OAuth2, base_url:
OAuthClientWithRetryTemplate
transport: Kafka, topic:
MassTransitConsumerTemplate
4οΈβ£ Inject Decorators Based on Policy
Adapter Hint
Decorator
otel_tracing: true
Inject ActivitySource span blocks
retries > 0
Wrap outbound calls with Polly retry logic
timeout_seconds > 0
Add timeout wrapper with cancellation
auth: OAuth2
Add token handler via ConnectSoft.Extensions.Http.OpenIdConnect
logging_enabled: true
Inject ILogger<T> and structured logs
π§ Resolution Example
{
"name" : "SendInvoiceCommand" ,
"transport" : "REST" ,
"method" : "POST" ,
"route" : "/invoices/send" ,
"input" : "SendInvoiceDto" ,
"output" : "InvoiceDto" ,
"otel_tracing" : true ,
"retries" : 2 ,
"timeout_seconds" : 10
}
β Results in:
Template: PostHandlerWithDTO
Output: InvoicesController.cs
Decorators: OTEL spans + retry wrapper + timeout token
Registered in: AdaptersRegistry.cs and adapters-manifest.json
π§Ύ Resolution Manifest Snapshot
{
"port" : "ICrmClient" ,
"transport" : "REST" ,
"type" : "outbound" ,
"template_used" : "OAuthClientWithRetryTemplate" ,
"policy_applied" : [ "retry" , "timeout" , "auth" ],
"generated_file" : "CrmClient.cs" ,
"trace_id" : "trace-adapter-88319"
}
π¦ Class Name & File Path Conventions
Rule
Format
REST controller β input port CreateUser
UsersController.cs under Adapters/Controllers/
gRPC service β port GetOrders
OrdersGrpcService.cs under Adapters/Grpc/
Kafka consumer β port OrderPlacedEvent
OrderPlacedConsumer.cs under Adapters/Consumers/
Repo β output port IUserRepository
UserRepository.cs under Adapters/Repositories/
Client β output port INotificationClient
NotificationClient.cs under Adapters/Clients/
π Output Naming Variants
Source Port
Output Adapter
IInvoiceRepository
InvoiceRepository.cs
IPaymentProcessor
PaymentProcessorClient.cs
CreateUserCommand
UsersController.cs
UserRegisteredEvent
UserRegisteredConsumer.cs
IBlobStorageAdapter
UserBlobStorage.cs
π§± Scaffolding Strategy Overview
The Adapter Generator Agent emits adapters following a strict directory structure , naming pattern , and Clean Architecture layering β ensuring that:
Each adapter is placed in the right infrastructure folder
All adapters implement a port interface defined in the application layer
DI registration is clean, grouped, and auto-resolvable
Output code is testable , traceable , and extensible
π Directory & Namespace Structure
ποΈ Standard Folder Layout (within Infrastructure/Adapters/)
Subfolder
Content
Controllers/
REST API controllers for input ports
Grpc/
gRPC service handlers
Consumers/
Messaging event consumers
Repositories/
Concrete implementations of repositories (NHibernate, EF)
Clients/
External service API clients
Blob/
Adapters for blob/file storage
Mocks/
In-memory fakes for testing or sandbox
Registrations/
DI container registration (AdaptersRegistry.cs)
π§ Namespace Structure
For a service named BillingService:
namespace BillingService.Infrastructure.Adapters.Controllers
{
public class InvoicesController : ControllerBase { ... }
}
This ensures:
Logical grouping of all adapter types
Easy discoverability for developers and tools
Compatibility with ConnectSoft reflection-based .AddAdapters() loaders
π§© Class Naming Conventions
Port Type
Adapter Class Name
Input port β CreateUserCommand
UsersController (REST) or UserService (gRPC)
Output port β IUserRepository
UserRepository
Output port β ICrmClient
CrmClient
Event β UserRegisteredEvent
UserRegisteredConsumer
Output β IBlobStorageService
UserPhotoBlobAdapter
πͺ Internal Class Template Structure
Every generated adapter follows this internal structure:
// Header
// trace_id, generated_by, timestamp
namespace BillingService.Infrastructure.Adapters.Repositories
{
public class UserRepository : IUserRepository
{
private readonly ISession _session ;
private readonly ILogger < UserRepository > _logger ;
public UserRepository ( ISession session , ILogger < UserRepository > logger )
{
_session = session ;
_logger = logger ;
}
public async Task < User ?> FindByIdAsync ( Guid id , CancellationToken ct )
{
using var span = ActivitySource . StartActivity ( "UserRepository.FindByIdAsync" );
return await _session . GetAsync < User > ( id , ct );
}
}
}
π οΈ Constructor Pattern (DI-Ready)
All adapters are constructor-injected:
Required dependencies (e.g., ILogger<T>, HttpClient, ISession)
Policy-wrapped clients (IPolicyWrappedHttpClient)
DTO mappers, value resolvers
Token providers, cache accessors if needed
π§ Registration Strategy
Mechanism
Output
AdaptersRegistry.cs
Explicit .AddTransient<IUserRepository, UserRepository>()
.AddAdapters() extension
Auto-scans namespace and registers adapters by convention
adapters-manifest.json
Lists DI registrations for audit and downstream CI/CD injection
π§Ύ Sample: AdaptersRegistry.cs
public static class AdaptersRegistry
{
public static IServiceCollection AddAdapters ( this IServiceCollection services )
{
services . AddTransient < IUserRepository , UserRepository > ();
services . AddHttpClient < ICrmClient , CrmClient > ();
services . AddMassTransitConsumer < UserRegisteredConsumer > ();
return services ;
}
}
π Optional: Test Folder Strategy
Adapters may generate test stubs into:
/tests
/BillingService.Infrastructure.Adapters.Tests
- UsersControllerTests.cs
- CrmClientTests.cs
- UserRepositoryTests.cs
Each adapter includes a header block like:
// Generated by Adapter Generator Agent v1.2.0
// trace_id: trace-adapter-55191
// service: BillingService
// environment: Production
// generated_at: 2025-05-02T03:45:00Z
π Extensibility Strategy
The Adapter Generator Agent is designed to support extensibility at multiple levels , enabling teams to introduce:
New transport types (e.g., Redis Pub/Sub, MQTT, GraphQL)
Custom organization-specific templates
Domain-specific adapter variants (e.g., healthcare, finance)
Runtime or compile-time overrides (plugin-based injection)
This ensures ConnectSoftβs AI Software Factory can adapt across industries, teams, and cloud environments.
π§© Adapter Plugin Architecture
A plugin is a self-contained directory with:
/Plugins/CustomKafkaAdapter/
- template.cs # The code template
- metadata.yaml # Port/transport match rules
- decorators.cs # Optional behavior injection
transport : kafka
port_suffix : Event
custom_namespace : Acme.Finance.Adapters
target_template : CustomKafkaConsumerTemplate.cs
decorators :
- tracing
- json-deserialization
- error-logging
π Supported Extension Points
Layer
Extensible?
Mechanism
Templates
β
Plug-in folders or template registry
Decorator behavior
β
Decorator chain injected before rendering
DI registration logic
β
Plugin can override .AddAdapters() entries
Port-to-transport mapping
β
Metadata rules or YAML configuration
DTO formatting or binding
β
Pluggable DTO formatters
Test strategy
β
Custom TestStubWriterSkill injection
π οΈ Transport Type Extensions (Examples)
Transport
Plugin Type
Notes
Redis Streams
RedisConsumerTemplate
Used for telemetry events
GraphQL
GraphQLMutationControllerTemplate
Maps Create*Command ports to mutations
MQTT
MqttHandlerTemplate
Supports IoT adapters in medical and smart building microservices
AWS Lambda
LambdaFunctionTemplate
Generates handler for serverless mode
Azure Functions
ServiceBusTriggerFunctionTemplate
Used in cost-optimized async pipelines
𧬠Template Override Rules
Behavior
Rule
Global override
override_template: true in adapter-policies.yaml
Per-port override
template_id: CustomKafkaInvoiceConsumer in output-ports.json
Per-service plugin path
plugins: ["./Plugins/Healthcare/"] in transport-config.yaml
Environment-specific
Fallback to dev template if env != Production
π§ͺ Dynamic Template Evaluation (If Enabled)
Supports Scriban or RazorLight engines
Can evaluate conditionals: {{ if transport == "Kafka" }} ... {{ end }}
DTOs, method names, and policy values passed as variables
Enables on-the-fly template mutation based on policy metadata
π§± Custom Transport Definition Example
custom_transports :
- name : redis-pubsub
input_type : RedisMessage
adapter_template : RedisPubSubConsumerTemplate.cs
options :
deserialize_json : true
span_wrapping : true
ack_mode : manual
π§° Adapter Test Strategy Extensions
Option
Description
generate_test_stubs: true
Default behavior β emits MSTest/xUnit files
template_id: InMemoryClientTestTemplate
Uses domain-specific test format
plugin_test_writer: HealthcareContractValidator
Injects external test strategy
mocking_framework: NSubstitute
Overrides default Moq usage
π§© Collaboration With Plugin Registry
Adapters can register plugin templates centrally using:
plugin-registry.yaml (global across platform)
Per-domain plugin packs (e.g., /Finance/, /EHR/, /Retail/)
β
Validation and Test-Readiness Overview
The Adapter Generator Agent enforces rigorous validation and emits test-scaffolded, production-grade infrastructure adapters. Its goal is to ensure that every adapter:
Implements a valid application port
Matches the declared transport and method
Compiles cleanly and passes linting/static analysis
Is unit-testable by design
Optionally includes test harnesses, mocks, or contract tests
π§ͺ Validation Phases
1οΈβ£ Port & Transport Validation
Rule
Check
Port exists in application layer
β
Interface resolved
Transport is supported and enabled
β
Checked against transport-config.yaml
Method/route matches OpenAPI (if REST)
β
Route β controller signature verification
Input/Output DTOs are valid and serializable
β
Reflection-based check if DTOs are found in API/library
2οΈβ£ Template & Decorator Resolution
Rule
Check
Template file exists and matches transport
β
Enforced before render
Required decorators (span, retry, etc.) are injectable
β
Checked against adapter-policies.yaml
OTEL span wrapping adheres to platform format
β
ActivitySource injection validated
3οΈβ£ Code Safety Rules
Rule
Enforced Behavior
Constructor DI only β no static or service locator
β
Template-generated only via DI
Exception handling required on all outbound I/O
β
Try-catch + ProblemDetails required for REST
CancellationToken must be propagated
β
All methods check ct.IsCancellationRequested
Logging via ILogger<T> is structured
β
All logs use LogContext, Serilog formatting
π Testability Checks
Validation
Description
Adapter implements testable interface
e.g., IUserRepository, ICrmClient
Mockable dependencies injected via DI
No static clients or new calls inside
DTOs are POCO and serializer-safe
Checks JSON compatibility and constructor validity
Span names are stable and traceable
e.g., UserRepository.FindById should emit OTEL span with tag adapter_name
Retry/circuit-breaker parameters mockable
All resilience features testable with mocks or overrides
π§ͺ Optional: Test Stub Emission
Feature
Output
Unit Test Class
xUnit/MSTest/NUnit stub with [Fact] / [TestMethod]
Fake Repository
InMemoryUserRepository.cs for in-memory persistence
Mock Registration
services.AddMock<ICrmClient>(new CrmClientStub());
TestData DTO
SampleUserDtoFactory.cs for test models
π§Ύ Sample: UsersControllerTests.cs
[TestClass]
public class UsersControllerTests
{
[TestMethod]
public async Task CreateUser_ShouldReturnOk ()
{
var mockHandler = new Mock < ICreateUserHandler > ();
mockHandler . Setup ( x => x . HandleAsync ( It . IsAny < CreateUserDto > (), It . IsAny < CancellationToken > ()))
. ReturnsAsync ( new UserDto ());
var controller = new UsersController ( mockHandler . Object );
var result = await controller . CreateUser ( new CreateUserDto (), CancellationToken . None );
Assert . IsInstanceOfType ( result , typeof ( OkObjectResult ));
}
}
π Manifest Validation Example
{
"port" : "ICrmClient" ,
"status" : "validated" ,
"test_ready" : true ,
"compiled" : true ,
"otel_wrapped" : true ,
"trace_id" : "trace-adapter-99333"
}
π§ Auto-Correction Examples
Validation Failure
Auto-Fix
Missing retry policy
Inject default from adapter-policies.yaml
Port not found in app layer
Emit warning + skip adapter
DTO not found
Emit placeholder DTO with // TODO: Implement
gRPC not enabled
Fallback to REST controller adapter
CancellationToken not passed
Auto-inject into method signature
π‘ Observability Strategy
The Adapter Generator Agent injects OpenTelemetry spans , structured logging , and resilience telemetry into every generated adapter β enabling full end-to-end traceability across microservices, message pipelines, and third-party integrations.
It ensures adapters are not black boxes, but fully instrumented infrastructure boundaries .
π OpenTelemetry Span Injection
β
Core Behavior
Adapter Type
Span Behavior
Controllers
Wrap HTTP handler in ActivitySource.StartActivity()
gRPC Handlers
Trace UnaryServerMethod<T> via Activity
Message Consumers
Trace ConsumeContext<T> from MassTransit or Kafka
Repositories
Trace each method (FindByIdAsync, SaveAsync) with entity tag
API Clients
Trace each outbound call, including retries and circuit breakers
Blob Storage
Span for UploadAsync, DownloadAsync, tagged with blob type/key
π Span Fields
Each span includes:
{
"adapter_name" : "UserRepository" ,
"adapter_type" : "repository" ,
"transport" : "persistence" ,
"port" : "IUserRepository" ,
"trace_id" : "trace-adapter-11209" ,
"retry_attempts" : 1 ,
"circuit_open" : false ,
"duration_ms" : 17 ,
"otel_status" : "OK"
}
Tag
Source
service.name
Microservice context
adapter.name
Class name
adapter.port
Port interface
adapter.transport
REST, Kafka, Persistence, etc.
span.kind
server or client
trace_id
From input-ports.json or injected
π Structured Logging
Logger injected into every adapter via ILogger<T>
Logs tagged with:
trace_id, span_id
adapter_name, port_name
correlation_id (if inbound message has one)
_logger . LogInformation ( "Sending invoice to CRM {@InvoiceId}" , invoice . Id );
π§ͺ Tracing for Resilience Features
Feature
Span Annotation
Retry
retry_attempts, retry_policy_name
Timeout
timeout_duration, cancelled
Circuit Breaker
circuit_open: true/false
Failure
otel_status: Error, with exception details
π§ Sample: Adapter-Level Span in Controller
using var activity = ActivitySource . StartActivity ( "CreateUserHandler" );
activity ?. SetTag ( "adapter.name" , "UsersController" );
activity ?. SetTag ( "port" , "CreateUserCommand" );
activity ?. SetTag ( "transport" , "REST" );
π Output Integration
otel-agent-config.yaml updated with required exporters if missing
Adapters respect existing Activity.Current β preserve parent span from upstream requests
Logs/metrics sent to:
OTLP exporter (default)
Azure Monitor / Application Insights (via OTEL bridge)
Custom sinks if declared in policies
π Validation & Auto-Correction
Check
Behavior
Span missing in method
Auto-inject ActivitySource block
No ILogger<T> present
Inject logger + log startup and error
Missing correlation ID
Attempt to extract from headers/context
OTEL exporter not defined
Inject default OTLP export config into otel-agent-config.yaml
Retry not emitting span
Wrap retry in span child block with attempt counter
π’ Span Emission Lifecycle
Event
Span
Adapter generation complete
adapter_generated
Span successfully injected
adapter_span_ready
Retry triggered
adapter_retry_attempted
Failure captured
adapter_error
β
Output Guarantees
Feature
Included
ActivitySource span in each adapter
β
ILogger<T> for all logging
β
Policy telemetry via OTEL
β
Structured logging fields
β
Optional integration to App Insights / Grafana / Jaeger
β
(via config)
π€ Collaboration Overview
The Adapter Generator Agent sits at the convergence point between architecture (ports) and infrastructure (transport) . It collaborates with upstream agents to resolve ports and policies, and serves downstream agents by delivering adapters ready for execution, testing, deployment, and tracing.
πΌ Upstream Collaborators
Agent
Provides
Application Architect Agent
input-ports.json, output-ports.json, domain boundaries
API Designer Agent
openapi.yaml, grpc.proto, transport surface hints
Library Generator Agent
DTOs and interfaces used inside adapters
Solution Architect Agent
Environment-level policies and transport-config.yaml
Security Architect Agent
Authentication strategy (e.g., OAuth2, API Key), scope injection
Observability Agent
OTEL config, span routing strategy
Platform Configuration Service
Default retry/timeouts from adapter-policies.yaml
π½ Downstream Consumers
Agent
Consumes
Microservice Generator
Integrates generated adapters into Infrastructure project layout
DevOps Architect Agent
Uses adapters-manifest.json for test validation, CI/CD injection
Observability Agent
Extends or adjusts OTEL span mapping, trace IDs, exporters
Test Generator Agent
Uses adapter metadata to generate or validate test coverage
Runtime Orchestrator
Auto-registers adapters via .AddAdapters() or reflection scanning
Security Compliance Agent
Audits outbound adapters for token usage, scope policies
π§ Shared Artifacts & Interfaces
Artifact
Shared With
AdaptersRegistry.cs
DevOps, Runtime Agent
adapters-manifest.json
DevOps, Test Agent, Observability Agent
otel-agent-config.yaml (extended)
Observability Agent
trace_id in file headers
Used by all tracing + validation agents
controller, repository, and client class names
Used by Microservice Generator for integration
π§ Agent Integration Flow
flowchart TD
AppArchitect --> AdapterGen
ApiDesigner --> AdapterGen
SolutionArchitect --> AdapterGen
SecurityArchitect --> AdapterGen
ObservabilityAgent --> AdapterGen
AdapterGen --> MicroserviceGenerator
AdapterGen --> DevOpsAgent
AdapterGen --> ObservabilityAgent
AdapterGen --> TestGeneratorAgent
Hold "Alt" / "Option" to enable pan & zoom
π§© DI Integration Points
Mechanism
Used By
AdaptersRegistry.cs
Service-level composition root
.AddAdapters()
Reflection-based scanning of namespace
IServiceCollection.AddHttpClient<T>
Outbound adapter registration
services.AddMassTransitConsumer<T>()
Message consumer registration
ConfigureAdapterPolicies()
Injects retry/timeouts per policy YAML
π’ Event Signals & Span Interfaces
Signal
Sent To
AdapterGenerationPlanPublished
Orchestrator, DevOps
AdapterTransportMismatch
Validation and API Designer Agent
AdapterTraceInjected
Observability and OTEL Agent
AdapterTestReady
Test Generator Agent
π Traceability & Cross-Agent Flow
Every adapter includes:
trace_id (aligned across lifecycle)
agent_version
generated_at
port β adapter β file mapping
registered_services metadata
π‘ Observability & Oversight
The Adapter Generator Agent is fully instrumented and monitored through OpenTelemetry , event signals , and metadata tracking , ensuring all infrastructure adapters are:
Traceable
Testable
Auditable
Recoverable
CI/CD-ready
π Spans Emitted During Execution
Span
Description
adapter_generated
Emitted per adapter created (controller, consumer, repo, client)
adapter_template_matched
Logs the port-to-template mapping decision
adapter_retry_policy_applied
Marks retry/circuit injection in outbound adapters
adapter_tracing_wrapped
Confirms OTEL ActivitySource inserted
adapter_manifest_emitted
When adapters-manifest.json is created and validated
All spans include:
trace_id
agent_version
port_name, adapter_type, transport
duration_ms, template_id, output_path
π Lifecycle Event Signals
Event
Consumers
AdapterGenerationPlanPublished
Microservice Generator, DevOps Agent
AdapterTransportMismatch
API Designer Agent (surface mismatch)
AdapterGenerationBlocked
Platform Orchestrator (e.g., forbidden adapter type)
AdapterTestStubEmitted
Test Generator Agent
AdapterOTELTraceReady
Observability Agent
AdapterValidationSummaryReady
DevOps Pipeline Validator
π§ͺ CI/CD Pipeline Integration
π Dashboard Integration
Metric
Visualization
Adapters by transport type
Pie or stacked bar chart
Retry/circuit-breaker coverage
Ratio, trendline
Adapter test readiness score
Pass/fail by adapter
OTEL span coverage
% of adapters wrapped
Compliance adapters generated
Count by auth method (API Key, OAuth2, etc.)
π‘οΈ Security Oversight
Adapter policies enforce authentication decorators ([Authorize], OAuth2Handler)
Logs redacted of sensitive info (PII, secrets)
Adapters generating external calls include:
Token injection tracing
Endpoint logging with domain-level tagging
Enforced timeouts and circuit policies
π Example Audit Trace (Snippet)
{
"trace_id" : "trace-adapter-44418" ,
"port" : "ICrmClient" ,
"adapter_class" : "CrmClient" ,
"transport" : "REST" ,
"template" : "OAuthClientWithRetryTemplate" ,
"otel_wrapped" : true ,
"retries" : 3 ,
"test_stub_created" : true ,
"status" : "success"
}
β
Agent Impact Summary
Capability
Delivered
π§ Clean Architecture adapter generation
β
π REST, gRPC, Kafka, Storage, API clients
β
π Retry, circuit breaker, timeout injection
β
π Full OTEL and structured logging support
β
π§ͺ Testability and CI/CD integration
β
π’ Lifecycle events and traceability
β
βοΈ Plugin-based extensibility and overrides
β
π§© DI, manifest, and environment readiness
β
π§ Final Thought
The Adapter Generator Agent enables the ConnectSoft platform to produce fully connected , policy-compliant , and infrastructure-ready microservices β transforming abstract ports into production-ready, test-validated adapters across protocols, clouds, and integration boundaries.
It acts as the bridge between clean architecture and real-world deployment β ensuring consistency, resilience, and observability at scale.