Skip to content

πŸ”Œ 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

🧾 Sample: UsersController.cs (REST Input Adapter)

[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

1️⃣ Input Loading & Validation

  • 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

πŸ“„ 5. Metadata & Output Coordination

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)

πŸ› οΈ Core Libraries and Tools

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

πŸ“¦ Code Generation and Output Format

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

πŸ” Output Metadata & Tracing

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

πŸ“¦ Plugin Format

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

πŸ“˜ metadata.yaml Example

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"
}

πŸ”– Tags Applied

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

  • adapters-manifest.json included in build artifacts
  • Each adapter file stamped with:

    • trace_id
    • generated_at
    • port_name
    • agent_version
  • Supports:

    • Code diff detection
    • Test stub matching
    • Span continuity validation

πŸ“Š 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.