π§± Strategic Use of Domain-Driven Design & Clean Architecture¶
π§ Introduction¶
In ConnectSoft, Domain-Driven Design (DDD) and Clean Architecture are not merely coding patterns β they are strategic execution principles. These principles provide the structure, boundaries, and semantics that intelligent agents need to autonomously generate safe, scalable, and modular software systems.
βWithout domain boundaries and clean layering, agents produce chaos. With them, they produce composable systems.β
This document outlines how and why these principles are applied throughout the platform β to support agent collaboration, blueprint alignment, tenant isolation, and event-driven automation.
π§© Why These Principles Matter¶
| Capability | Enabled by DDD / Clean Architecture |
|---|---|
| β Agent-Oriented Generation | Clear layering guides code and test output per agent |
| β Blueprint-to-Code Mapping | Domain models align with bounded contexts and service contracts |
| β Multi-Agent Safety | Domain events and aggregates prevent logic scattering |
| β Observability and Testability | Each layer has traceable responsibilities |
| β Tenant-Scoped Automation | Contexts remain isolated and cleanly injectable |
π§± DDD in ConnectSoft = Strategic Boundaries¶
Domain-Driven Design provides:
- Bounded Contexts β Modular blueprints and service segmentation
- Aggregates β Safety and encapsulation of core logic
- Value Objects β Repeatable templates across services
- Domain Events β Signal generation for orchestration
- Ubiquitous Language β Structured AI input for accurate modeling
These patterns make it possible for agents to generate domain-centric services, not just technical scaffolds.
π§Ό Clean Architecture = Agent-Friendly Layering¶
Clean Architecture enables:
- Clear separation of concerns
- Dependency inversion (no leakage between infrastructure and domain)
- Scaffolding by layer (app, domain, infra)
- Replacement of adapters and ports by agents without risk
- Deterministic file placement and artifact verification per skill
"The structure exists so that agents donβt need to think β they only need to follow contracts."
π¦ Outcome: Software Thatβs Modular, Maintainable, and Machine-Generated¶
Using DDD and Clean Architecture:
- Every blueprint knows where each artifact belongs
- Every agent knows what layer it can modify
- Every coordinator knows when to trigger each skill
- Every artifact is aligned with purpose, context, and lifecycle phase
π Covered in This Document¶
In the following cycles, weβll explore:
- How DDD shapes modular blueprints
- How Clean layering is enforced by templates
- How agents generate domain models, test logic, and contracts
- How CQRS, specifications, events, and anti-corruption layers are used to preserve modularity
β Summary¶
- ConnectSoft uses DDD and Clean Architecture as automation enablers, not just developer discipline
- These principles define how blueprints are structured, how agents behave, and how flows scale safely
- Every module, service, and tenant is powered by these patterns
π€ Strategic Role in AI-First Automation¶
In ConnectSoft, DDD and Clean Architecture arenβt used to make life easier for developers β theyβre used to make life possible for AI agents. Without these principles, agents canβt operate autonomously, consistently, or safely.
βAgents donβt guess where to put logic β they follow architectural rules that enforce structure and meaning.β
These principles allow the platform to scale intelligent automation across hundreds of services, because they define predictable, constraint-driven environments that agents can understand, navigate, and execute in.
π§ Why AI Needs Structure¶
AI agents operate based on:
- Prompts
- Skills
- Contracts
- Blueprint mappings
- Domain context
If those inputs are unstructured, inconsistent, or chaotic, agent outputs become:
- Brittle
- Duplicated
- Misplaced
- Invalid
- Dangerous (e.g., broken multi-tenant boundaries)
Clean Architecture and DDD solve that problem at the source.
π§© Strategic Advantages for AI-Driven Automation¶
| Capability | Enabled by DDD & Clean |
|---|---|
| π§± Blueprint-to-code mapping | Bounded contexts β service structure β folders β agents |
| βοΈ Skill-to-layer mapping | GenerateHandler β App Layer, EmitDomainEvent β Domain Layer |
| π‘ Scoped decision boundaries | No agent emits logic outside its assigned layer or context |
| π§ͺ Automated validation | Schema validators, contract matchers, and blueprint linter rules |
| π¦ Artifact traceability | Every output linked to layer, skill, traceId, and DDD concept |
| π Retry and regeneration | Idempotent scaffolds via deterministic structure |
| π§ Prompt precision | βGenerate command handler in App layer for Booking aggregateβ β 100% precise |
π Example: Blueprint Line β Agent Skill Mapping¶
β Backend Developer Agent executes GenerateHandler skill, emitting the correct class in the correct folder using known architectural constraints.
π Architecture as an Enforcement Engine¶
Without DDD/Clean:
- Agents would overlap responsibility
- Output folders would be inconsistent
- Business logic would leak into infrastructure
- Domain contracts would drift from blueprints
- Prompt reuse and skill reuse would break down
β Clean Architecture solves this by ensuring each agent owns a lane and never crosses it.
π§ Orchestrator Benefits¶
Clean layering and DDD modeling allows the orchestration layer to:
- Compose execution plans by blueprint layer
- Retry skills based on layer-specific errors (e.g., test β domain logic β fix)
- Block release if a layerβs outputs are missing or unverified
- Generate dependency graphs (e.g., App depends on Domain, Infra is last)
β Summary¶
- DDD and Clean Architecture enable AI-first automation by creating clear boundaries, safe scaffolds, and predictable mappings
- They ensure agents can work independently but consistently across modules
- These principles are embedded into every ConnectSoft template, blueprint, and coordinator
π§© Domain-Driven Modularization¶
In ConnectSoft, bounded contexts are the foundation of modularity. They define the scope of autonomy for a module, microservice, or blueprint β and they align perfectly with the goals of scalable, agent-driven software generation.
βThe bounded context is the unit of generation, testing, deployment, and ownership.β
This makes Domain-Driven Design (DDD) not just a modeling strategy β but a modularization engine for the AI Software Factory.
π§ What Is a Bounded Context?¶
A bounded context is a self-contained domain boundary where:
- Language is consistent and local
- Models are stable and independent
- Integration happens via contracts and events
- No external assumptions leak in
- Code, tests, and flows are owned and isolated
In ConnectSoft, every blueprint, agent flow, and deployment unit maps to a bounded context.
π¦ Module Structure by Context¶
Each bounded context is mapped to:
This lets agents work in bounded subgraphs of the system without needing to understand the whole platform.
π Event-Driven Context Boundaries¶
Bounded contexts:
- Emit domain events that cross boundaries (e.g.,
AppointmentBooked) - Consume external events via anti-corruption layers or message handlers
- Never call each other directly (even via code)
This structure enables agents to be context-local and event-connected β the key to massive agent parallelism.
π Blueprint Example with Context Tag¶
service: BookingService
boundedContext: Booking
domain: Appointments
events:
emits:
- AppointmentBooked
- AppointmentCancelled
β Every agent involved in this module only sees content scoped to Booking.
π Agent and Skill Isolation by Context¶
| Constraint | Purpose |
|---|---|
agentScope.context = Booking |
Prevents an agent from emitting or modifying unrelated modules |
skill.inputContext = Booking |
Ensures prompt injection, blueprint parsing, and artifact generation are scoped |
orchestrator.fsm.context = Booking |
Coordinates only agents and events in that boundary |
β Enables secure, traceable, and parallel-safe automation.
π§© Benefits of Context-Based Modularization¶
| Benefit | Result |
|---|---|
| β Agent Independence | Agents donβt interfere with each otherβs outputs |
| β Safe Parallelism | 100s of agents can work simultaneously across contexts |
| β Blueprint-to-Module Clarity | Each blueprint file maps cleanly to a module path |
| β Scalable Orchestration | Coordinators operate per context with no global state |
| β Event-Driven Integration | Contexts evolve independently and collaborate safely |
β Summary¶
- In ConnectSoft, bounded contexts define modular units for generation, ownership, and orchestration
- All blueprints, prompts, and agent executions are context-scoped
- This enables safe, scalable, and composable automation across thousands of modules
π§Ό Clean Layered Structure¶
In ConnectSoft, every module generated by agents follows a strict, opinionated Clean Architecture layout. This structure enforces separation of concerns, safe extensibility, and agent skill boundaries, while making automation traceable and repeatable.
βClean layering isnβt just good practice β itβs how agents know what belongs where, and why.β
Each layer corresponds to a specific type of concern, a set of agent skills, and a set of blueprint declarations.
π§± The Standard Clean Architecture Layers¶
| Layer | Responsibility | Owned By |
|---|---|---|
| Domain | Business rules, aggregates, entities, value objects, domain events | Domain Modeler Agent, Event-Driven Architect Agent |
| Application | Use cases, command handlers, services, workflows | Backend Developer Agent, QA Agent |
| Infrastructure | External integrations (e.g., DB, messaging, APIs) via adapters | Infrastructure Engineer Agent, Cloud Provisioner Agent |
| Entry Points (API/UI) | Controllers, endpoints, gRPC services, UI views | API Designer Agent, Frontend Developer Agent |
| Tests | Unit, integration, behavior specs | Test Generator Agent, QA Agent |
π Folder Structure Example¶
/BookingService/
/Domain/
Appointment.cs
BookingAggregate.cs
Events/
AppointmentBooked.cs
/Application/
Handlers/
BookAppointmentHandler.cs
Services/
/Infrastructure/
Persistence/
BookingRepository.cs
Messaging/
EventPublisher.cs
/API/
Controllers/
AppointmentsController.cs
/Tests/
Features/
BookAppointment.feature
Unit/
/Contracts/
Events/
OpenAPI/
execution-metadata.json
β All ConnectSoft templates use this layout. Agents read/write only within their assigned layer.
π§ Why This Matters for Agents¶
- Prompts are injected with layer-specific input
- Skills are mapped per layer (e.g.,
EmitDomainEventβ Domain,GenerateHandlerβ Application) - Coordinators know which agent to call based on blueprint layer
- Validators enforce schema and artifact placement correctness
- Reviewers can diff, approve, or reject changes by layer
π§© Skill-to-Layer Alignment¶
| Skill | Layer |
|---|---|
GenerateHandler |
Application |
EmitDomainEventContract |
Domain |
GenerateRepositoryAdapter |
Infrastructure |
GenerateOpenAPIContract |
API |
GenerateSpecFlowTest |
Tests |
π Layer Enforcement in Templates¶
Templates apply:
- Layered path constraints (
outputPath,layerTag) - Layer-specific linting rules (e.g., Application should not reference Infrastructure)
- Agent-level access control (e.g.,
frontend-developercannot modify/Domain) - Skill scoping (
skillId: GenerateHandler,layer: Application)
π§ͺ Benefits of Layered Structure¶
| Benefit | Outcome |
|---|---|
| β Agent modularity | Agents only operate in their assigned layer |
| β Traceability | Artifacts link back to skill + layer |
| β Validated generation | Validators can enforce layer contracts |
| β Diff isolation | Reviewers see changes per layer and purpose |
| β Safe evolution | You can regenerate one layer without touching others |
β Summary¶
- ConnectSoft enforces a strict layered architecture, enabling agents to generate code safely and deterministically
- Layers map to skills, prompts, and agent scopes
- This structure underpins traceability, validation, and agent collaboration
βοΈ Use Cases and Application Services¶
The Application Layer in ConnectSoft is where agents generate orchestrated, intent-driven workflows β typically as command or query handlers, application services, or invocable policies.
This layer is the βglueβ between domain logic and infrastructure β and the execution core of modular agent output.
βThe Application Layer is where blueprints become behavior β and agents become action.β
It represents user intent and business workflows without leaking infrastructure or persistence concerns.
π§ Purpose of the Application Layer¶
| Function | Description |
|---|---|
| Handle commands | Transform input into intent and invoke domain model behavior |
| Coordinate use cases | Glue together multiple domain operations under a single scenario |
| Call domain aggregates | Interact with domain via proper invariants and consistency |
| Emit domain events | Signal state transitions or policy triggers |
| Prepare output models | Return DTOs or responses for the outer layers (e.g., controllers, gRPC) |
π Blueprint Example β Application Layer Mapping¶
useCase: Book Appointment
input:
- petId: Guid
- startTime: DateTime
- duration: int
output: AppointmentBooked
layer: Application
β Agent executes GenerateHandler, producing BookAppointmentHandler.cs under /Application/Handlers.
π§© Agent Skills That Target Application Layer¶
| Agent | Skills |
|---|---|
Backend Developer Agent |
GenerateHandler, GenerateApplicationService, EmitCommandContract |
Test Generator Agent |
GenerateUnitTestForHandler, ScaffoldBDDFeature |
QA Agent |
ValidateApplicationFlow |
Code Reviewer Agent |
DetectAppLayerViolations |
π¦ Standard Structure of a Handler¶
public class BookAppointmentHandler : IRequestHandler<BookAppointmentCommand, AppointmentResult>
{
public async Task<AppointmentResult> Handle(BookAppointmentCommand command, CancellationToken ct)
{
var appointment = BookingAggregate.Book(command.PetId, command.StartTime, command.Duration);
await _repository.SaveAsync(appointment);
_eventPublisher.Publish(new AppointmentBooked(...));
return new AppointmentResult(...);
}
}
β
Generated by backend-developer agent based on blueprint + domain model structure.
π§ Why Application Layer Is Agent-Friendly¶
- Inputs/outputs are well-typed and declarative
- Each use case maps to one skill execution
- Prompt can be deterministically constructed from blueprint section
- Validators can confirm that:
- No infrastructure leakage
- Events are correctly raised
- Domain is invoked through proper aggregate root
- Skill outputs are idempotent and testable
π§ͺ Application-Level Testing¶
Test generators use this layer to:
- Scaffold SpecFlow/BDD scenarios
- Generate unit tests with mocks for domain/services
- Attach tests to the same traceId as handler generation
- Validate alignment between use case input and test flow
π Regeneration Scenarios¶
If the blueprint changes:
- β Only this handler is regenerated
- β Domain, infra, or contracts remain untouched
- β Tests are updated or flagged if drift is detected
β Keeps regeneration localized and safe.
β Summary¶
- The Application Layer is the execution point for agent-generated workflows
- It translates blueprint-defined use cases into handlers and services
- Clean layering and structured prompts allow for safe, deterministic, and traceable code generation
π§± Aggregates and Domain Events¶
At the core of ConnectSoftβs domain modeling lies the aggregate β a consistency boundary for core business rules β and the domain event, which acts as a signal of meaningful state change.
These constructs are not just important for clean design β they are essential to agent-driven generation, modular orchestration, and event-based collaboration across contexts.
βAggregates define what agents protect. Domain events define what agents trigger.β
π§© What Is an Aggregate?¶
An aggregate is:
- A consistency boundary around one or more entities
- The only place in the domain where invariants are enforced
- The source of domain events
- Scoped to a bounded context, versioned, and owned by the domain model
Example:
public class BookingAggregate : AggregateRoot
{
public Appointment BookAppointment(PetId petId, DateTime startTime, int duration)
{
// domain rules
var appointment = new Appointment(...);
AddDomainEvent(new AppointmentBooked(...));
return appointment;
}
}
π Domain Events: Meaningful State Transitions¶
Domain events describe facts in past tense:
AppointmentBookedInvoiceGeneratedUserRegistered
They are emitted by aggregates and consumed by:
- π§ Other domain models
- βοΈ Coordinators and agents
- π§ͺ Test validators
- π Pipelines and deployment triggers
π¦ Blueprint β Aggregate β Event Flow¶
β Used by Domain Modeler Agent to create:
BookingAggregate.csAppointment.csAppointmentBooked.cs(domain event)
π§ Agent Roles in Domain Modeling¶
| Agent | Skills |
|---|---|
Domain Modeler Agent |
GenerateAggregate, EmitDomainEvent, DefineEntityStructure |
Backend Developer Agent |
EmitCommandInvoker, RaiseEventFromAggregate |
Event-Driven Architect Agent |
MapEventContracts, AttachIntegrationPolicy |
π§ͺ Why Aggregates Matter for Agents¶
- They centralize business rules, allowing safe code generation
- Events generated are well-scoped signals, usable across flows
- Output of one agent (handler) becomes input trigger for another
- Validators can confirm that:
- Domain rules exist in one place
- All commands result in events
- Events follow contract structure
π Event Emission β Event-Driven Automation¶
When a domain event is emitted:
- Orchestrator receives
AppointmentBooked - Notification Agent, Analytics Agent, or QA Agent are triggered
- CI pipeline may generate release if event ==
ReleaseReady - Other services consume event via contracts and anti-corruption layers
β This powers autonomous module collaboration.
π Aggregate Rules in Templates¶
- One aggregate per module
- Domain events versioned and namespaced
- Agents never emit events without passing through an aggregate
- All aggregates include
AddDomainEvent()utility method - Domain events are scaffolded with schemas + observability metadata
β Summary¶
- Aggregates protect business logic β domain events expose business state changes
- ConnectSoft agents use these constructs to generate, trigger, and orchestrate flows
- They enable safe, autonomous collaboration and enforce domain boundaries across modules
ποΈ Repositories and Persistence Models¶
In ConnectSoft, persistence logic is treated as an infrastructure concern, separated entirely from the domain and application layers. This separation is enforced via repositories, which agents generate based on domain aggregates and context-aware blueprints.
βAgents donβt care about where data lives β only how itβs accessed and validated via contracts.β
Repositories give agents a stable abstraction to generate testable, swappable, and tenant-aware storage logic without coupling the core domain to any specific database, ORM, or transport layer.
π§ Strategic Role of Repositories¶
| Purpose | Benefit |
|---|---|
| Abstract persistence | Keeps domain and app layers persistence-agnostic |
| Enable mocking | Agents generate test doubles and in-memory implementations |
| Support multitenancy | Tenant filtering can be enforced at adapter layer |
| Prepare for swapability | Easily replace NHibernate, MongoDB, or EF adapters |
| Align with Clean layering | Ensures dependency inversion is respected in generated code |
π§© Blueprint β Repository Mapping¶
aggregate: Booking
repository:
interface: IBookingRepository
entity: Appointment
persistence: nhibernate
multiTenant: true
β Triggers:
IBookingRepository.cs(App layer)BookingRepository.cs(Infra adapter)- NHibernate mappings (if required)
- Tenant scoping logic
π§± Repository Layered Structure¶
| Layer | Artifact | Generator Agent |
|---|---|---|
| Application | IBookingRepository |
Backend Developer Agent |
| Infrastructure | BookingRepository : IBookingRepository |
Infrastructure Engineer Agent |
| Tests | InMemoryBookingRepository |
Test Generator Agent |
β These are scoped per module and traceable via agent metadata.
π§ Clean Repository Contracts¶
public interface IBookingRepository
{
Task<Appointment?> GetByIdAsync(Guid id);
Task SaveAsync(Appointment appointment);
}
β Domain never references infrastructure β only the interface.
π§ͺ Repository Testability¶
Generated repositories support:
- In-memory variants for unit testing
- Fake adapters with assertion hooks
- Integration test stubs with seed data
- Tracing of queries for validation and observability
π Regeneration & Agent Workflow¶
When aggregate or blueprint changes:
- β Repository interface is regenerated
- β Adapter class is diffed or re-emitted
- β Tests regenerate if behavior changes
- β Domain layer remains untouched unless event structure changes
π Repository Constraints in Templates¶
- Naming convention:
<Aggregate>Repository.cs - All adapters respect
tenantIdinjection pattern - Cross-context access prohibited (e.g., Booking repo in Billing context)
- Versioned schema/contract overlays supported (e.g.,
v1,v2) - ORM-specific generation via template flag (
useNHibernate,useMongo, etc.)
π Optional: Specification Pattern Support¶
If enabled, agents can also generate query objects and specifications:
public class AppointmentsByDateSpec : ISpecification<Appointment>
{
public DateTime Date { get; }
public Expression<Func<Appointment, bool>> ToExpression() =>
x => x.StartTime.Date == Date;
}
β Covered more deeply in Specifications and Queries section.
β Summary¶
- Repositories give agents a clean contract to read/write data across contexts
- The domain layer stays pure β agents handle persistence as a separate, swappable concern
- This pattern enables testability, multi-ORM support, and infrastructure modularity
𧬠Entity Modeling for Agents¶
ConnectSoft agents donβt just scaffold code β they model domain realities. Using structured prompts and blueprint data, agents generate entities, value objects, and domain rules that reflect the ubiquitous language of the bounded context.
βEntity modeling is where the blueprint becomes behavior β and the language becomes structure.β
This modeling phase happens primarily in the Domain Layer, led by the Domain Modeler Agent and validated by orchestration flows and contract tests.
π§ What Is an Entity?¶
An entity:
- Has an identity (
Id) - Represents a business concept with behavior
- Evolves over time
- Is compared by identity (not value)
- Lives inside an aggregate or root
Example:
public class Appointment
{
public Guid Id { get; init; }
public DateTime StartTime { get; private set; }
public PetId PetId { get; private set; }
public void Reschedule(DateTime newStartTime)
{
StartTime = newStartTime;
}
}
π Value Object Example¶
β
No identity β compared by value, not reference. Agents generate value objects when isValue: true is declared.
π§© Blueprint β Entity Mapping¶
entities:
- name: Appointment
fields:
- name: Id
type: Guid
- name: StartTime
type: DateTime
- name: PetId
type: PetId
behaviors:
- Reschedule
aggregate: Booking
isValue: false
β Used by Domain Modeler Agent to generate:
Appointment.cs(Entity)PetId.cs(Value Object)Reschedule()method- Blueprint-derived constructor
π€ Agent-Driven Modeling Process¶
- Agent reads blueprint or prompt containing domain vocabulary
- Matches terms to modeling templates (e.g., entity, value object, aggregate)
- Validates field types and modifiers
- Injects guard clauses or invariant checks
- Emits artifacts with metadata (
traceId,skillId,contextId) - Validates output via structural and semantic checks
π§© Skills for Domain Modeling¶
| Agent | Skills |
|---|---|
Domain Modeler Agent |
GenerateEntity, GenerateValueObject, InjectInvariants, AttachToAggregate |
Ubiquitous Language Agent |
ExtractConcepts, MapDomainTermsToModels |
Backend Developer Agent |
UseEntityInHandler, MapDTOs |
π§ͺ Validation and Observability¶
Each generated entity:
- Is schema-validated against the blueprint
- Includes annotations for traceability (source skill, context, field origin)
- Is verified by structural rules (e.g., βall entities must have Idβ)
- Is unit tested via agent-generated specs if behaviors exist
π Regeneration Triggers¶
Regeneration occurs when:
- Blueprint fields or types change
- Aggregates evolve (new domain rules)
- Entity relationships are updated
- Value object flags change (e.g.,
isValue: false β true)
β Only affected models are regenerated β agents work at fine-grained modularity.
π Studio Visualization¶
Studio shows:
- Entity structure and hierarchy per context
- Relationships to aggregates and repositories
- Cross-reference to DTOs, events, and test cases
- Change history and regeneration diffs
β Summary¶
- ConnectSoft agents model domain entities and value objects based on blueprint input and ubiquitous language
- The result is clean, testable, behavior-rich models that reflect business intent
- Modeling is traceable, auditable, and safely regenerable
π Specifications and Queries¶
In ConnectSoft, complex read-side logic is not hardcoded into repositories or scattered across handlers. Instead, the platform supports clean, reusable specifications and query models, which agents can generate, reuse, and validate.
βSpecifications let agents express βwhat to fetchβ without knowing βhow to fetch itβ.β
This pattern enables scalable, testable query logic β fully compatible with Clean Architecture and DDD principles β and allows both command and query flows to be agent-driven.
π§ What Is a Specification?¶
A Specification is:
- A reusable object that expresses a filter or business rule
- Independent of persistence technology
- Composed of predicates (usually LINQ expressions)
- Often used for queries, validations, and guards
Example:
public class AppointmentsByDateSpec : ISpecification<Appointment>
{
public DateTime Date { get; }
public Expression<Func<Appointment, bool>> ToExpression() =>
x => x.StartTime.Date == Date;
}
π§© Blueprint to Specification Mapping¶
queries:
- name: AppointmentsByDate
entity: Appointment
filter:
- field: StartTime
condition: date = Today
output: List<AppointmentDto>
layer: Application
β Used by agents to generate:
AppointmentsByDateSpec.csGetAppointmentsByDateQuery.cs- Optional
AppointmentsByDateHandler.csif CQRS is used
π§° Agent Skills for Query Logic¶
| Agent | Skills |
|---|---|
Backend Developer Agent |
GenerateQueryHandler, AttachSpecification, GenerateDTO |
Domain Modeler Agent |
EmitSpecification |
QA Agent |
ValidateQueryOutput, GenerateQueryTest |
π§© Specification Composition¶
Agents can compose logic using reusable blocks:
var spec = new AppointmentsByDateSpec(DateTime.Today)
.And(new PetTypeSpec("Dog"))
.Or(new StatusSpec("Pending"));
β Supports complex logic using a modular, testable model.
π Query Handlers Example (CQRS)¶
public class GetAppointmentsByDateHandler : IRequestHandler<GetAppointmentsByDateQuery, List<AppointmentDto>>
{
private readonly IAppointmentRepository _repo;
public async Task<List<AppointmentDto>> Handle(GetAppointmentsByDateQuery query, CancellationToken ct)
{
var spec = new AppointmentsByDateSpec(query.Date);
var results = await _repo.ListAsync(spec);
return results.MapToDto();
}
}
β Cleanly separates logic: query β spec β projection.
π§ͺ Agent-Generated Query Tests¶
The Test Generator Agent can:
- Generate test data for query specs
- Verify correctness of filtering logic
- Mock repositories and confirm results
- Create negative test cases (e.g., no matches)
π Regeneration Triggers¶
Specifications and queries are regenerated when:
- Blueprint declares new query patterns
- Entity model changes affect filter logic
- DTO projections are updated
- Repository interface is modified
π¦ Benefits of Specifications in Agent Workflows¶
| Benefit | Outcome |
|---|---|
| β Reusable logic | Shared across queries, validators, and test setups |
| β Layered separation | Clean architecture compliance without leaks |
| β Prompt-based generation | Easy to instruct agents via blueprint or prompt |
| β Testable and composable | Specification = pure function = unit testable |
β Summary¶
- Specifications enable agents to express read logic cleanly and safely
- They align with Clean Architecture and enable CQRS-compatible workflows
- Agent-generated specs, queries, and tests are modular, reusable, and maintainable
π£ Domain Events as Signals¶
In ConnectSoft, domain events are not just internal notifications β they are the primary signals that drive orchestration, downstream agent activation, and cross-context automation.
βA domain event is a fact β one that triggers flows, unlocks dependencies, and enables collaboration.β
These events originate from aggregates, reflect meaningful state changes, and are used to activate agents, trigger CI/CD pipelines, update documentation, or emit integration artifacts.
π§ Strategic Role of Domain Events¶
| Purpose | Impact |
|---|---|
| β Signal state transitions | Tell the system: βSomething important just happenedβ |
| β Decouple workflows | Producers and consumers donβt need to know about each other |
| β Enable orchestration | Coordinators react to domain events via FSM transitions |
| β Trigger agents | Events activate new skills, validation flows, and downstream steps |
| β Emit contracts | Events can be mapped to external schemas or pub/sub endpoints |
π Example: Aggregate β Event β Agent¶
public class BookingAggregate
{
public Appointment Book(...) {
...
AddDomainEvent(new AppointmentBooked(...));
return appointment;
}
}
β This emits:
β Which triggers:
Notification AgentAnalytics AgentDeployment Orchestrator- Studio pipeline trace
π Event Flow Pattern¶
sequenceDiagram
participant BookingAggregate
participant EventBus
participant QA Agent
participant DevOps Coordinator
BookingAggregate->>EventBus: Emit AppointmentBooked
EventBus->>QA Agent: Activate test validation
EventBus->>DevOps Coordinator: Transition to ReadyForRelease
β No hardcoding, only event-contract-driven automation.
π¦ Blueprint β Event Mapping¶
Each emitted event is versioned, documented, and assigned a schema (JSON or C# contract).
π§© Agent Skills for Event Handling¶
| Agent | Skills |
|---|---|
Domain Modeler Agent |
EmitDomainEvent, GenerateEventContract |
Backend Developer Agent |
AttachEventToHandler, RouteCommandToAggregate |
Event-Driven Architect Agent |
MapCrossContextFlows, DesignEventContracts |
QA Agent |
VerifyEventEmission |
Documentation Writer Agent |
IncludeEventInAPIDocs |
π Event Contract Enforcement¶
- All events must have a contract schema (
*.v1.json) - Emitted events are validated at runtime
- Agents must declare emitted events in metadata
- Studio visualizes event topology across modules
- Contracts are versioned (
v1,v2,vN) with compatibility checks
π§ Advanced Use: Orchestration Triggers¶
Domain events trigger state transitions:
Or trigger agent workflows:
β Summary¶
- Domain events are the primary signals for automation, agent activation, and inter-context flow
- Every meaningful change in ConnectSoft produces an event that feeds into orchestration, pipelines, and observability
- Domain events are modeled, versioned, and enforced by contracts β with full traceability
π§ Strategic Blueprint Mapping¶
In ConnectSoft, blueprints are the machine-readable source of truth for what needs to be built, why, and how. They map directly to Clean Architecture layers and DDD concepts, enabling agents to generate code, contracts, and flows with precision and safety.
βBlueprints are not specs β they are execution plans aligned with clean layering and bounded contexts.β
This mapping is what allows agents to function autonomously: a well-structured blueprint eliminates ambiguity and allows precise targeting of skills and outputs.
π Blueprint = Modular Execution Contract¶
Blueprints include structured declarations that guide agent behavior:
module: BookingService
context: Booking
aggregate: Booking
commands:
- BookAppointment
- CancelAppointment
events:
emits:
- AppointmentBooked
- AppointmentCancelled
entities:
- Appointment
queries:
- AppointmentsByDate
infrastructure:
persistence: nhibernate
pubsub: azure-service-bus
Each section maps to:
- A layer in Clean Architecture
- A set of agents
- One or more output artifacts
π§± Blueprint-to-Layer Mapping¶
| Blueprint Section | Clean Architecture Layer | Generated By |
|---|---|---|
commands |
Application | Backend Developer Agent |
aggregate, entities |
Domain | Domain Modeler Agent |
events |
Domain (+ Contracts) | Event-Driven Architect Agent |
queries |
Application | Backend Developer Agent |
infrastructure.persistence |
Infrastructure | Infrastructure Engineer Agent |
api.contracts |
Entry Point | API Designer Agent |
tests |
Test Layer | Test Generator Agent |
π§© Agent Workflow Driven by Blueprint Sections¶
BlueprintCreatedβ triggers agent chain- Each agent reads the section(s) itβs scoped to
- Outputs are saved under layer-aligned folders
- Coordinators verify all required blueprint sections are implemented and validated
π Modular Generation Lifecycle¶
graph TD
Blueprint --> Domain
Blueprint --> Application
Blueprint --> Infrastructure
Blueprint --> Contracts
Blueprint --> Tests
β This modularity allows regeneration of one layer at a time, based on partial blueprint updates.
π§ Multi-Agent Execution by Section¶
| Section | Activated Agents |
|---|---|
commands |
Backend Developer Agent, QA Agent |
aggregate |
Domain Modeler Agent, Event-Driven Architect Agent |
infrastructure |
Infrastructure Engineer Agent, Cloud Provisioner Agent |
tests |
Test Generator Agent, QA Agent |
Each agent uses structured prompt templates mapped to its blueprint domain.
π Traceability & Validation¶
Blueprint mapping supports:
- Skill-level validation (e.g.,
GenerateHandlermust matchcommandsection) - Missing section detection (e.g., handler exists but
eventnot defined) - Studio trace graphs linking blueprint source β agent β output artifact
- Retry/resume per section during orchestrated flows
β Summary¶
- Blueprints are modular execution plans, not freeform documents
- Each section maps to DDD concepts and Clean Architecture layers
- This structured mapping enables safe, partial, and traceable generation across agents and flows
π§± Code Generation by Layer¶
In ConnectSoft, agents donβt emit code blindly β they generate artifacts layer-by-layer, respecting Clean Architecture boundaries and DDD ownership. Each layer has a defined purpose, structure, and a set of agent skills responsible for its outputs.
βLayered generation enforces modularity, separation of concerns, and safe parallel automation.β
This architectural discipline ensures that code is generated in a predictable, validated, and traceable way β with each layer supporting composability, testability, and safe regeneration.
π§± Layer Responsibilities Recap¶
| Layer | Purpose |
|---|---|
| Domain | Core business logic (aggregates, entities, value objects, domain events) |
| Application | Use case orchestration, command/query handlers, DTO mappings |
| Infrastructure | Persistence, messaging, integrations (via adapters) |
| Entry Points | HTTP APIs, gRPC services, controllers, UI ports |
| Tests | Unit, integration, feature, and specification tests |
π€ Agent Code Generation by Layer¶
| Layer | Agent | Skills |
|---|---|---|
| Domain | Domain Modeler Agent |
GenerateAggregate, GenerateEntity, EmitDomainEvent |
| Application | Backend Developer Agent |
GenerateHandler, EmitCommandContract, GenerateApplicationService |
| Infrastructure | Infrastructure Engineer Agent |
GenerateRepositoryAdapter, ConfigureDbContext, EmitQueuePublisher |
| Entry Points | API Designer Agent, Frontend Developer Agent |
GenerateOpenApiContract, ScaffoldController, EmitUIAdapter |
| Tests | Test Generator Agent, QA Agent |
GenerateUnitTest, GenerateSpecFlowFeature, CreateMockRepository |
β Each skill is scoped to a layer, blueprint section, and trace context.
π§© Sample Generation Sequence¶
flowchart TD
Blueprint --> Domain
Domain --> Application
Application --> Infrastructure
Application --> EntryPoints
All --> Tests
β Domain is generated first β Application builds on domain contracts β Infrastructure adapters scaffold for domain interfaces β Entry points expose App layer β Tests wrap around all others
π Folder Output Structure¶
β All artifacts are stored by layer with traceable metadata, versioning, and agent linkage.
π Regeneration and Safety¶
If a blueprint or prompt change affects:
- β
Only
Applicationβ regenerate handler, not domain - β
Only
Infrastructureβ regenerate adapter, not logic - β A shared model β agents update layer-specific projections or adapters
- β Test drift β regenerate tests without impacting implementation
β Partial regeneration is safe and isolated.
π§ͺ Layer-Aware Validation¶
Validators enforce:
- Application must only depend on Domain
- Infrastructure must not reference Domain directly
- Tests must use mocks or contracts
- Event names must match domain event definitions
- Output folders must align to declared
layerin agent output metadata
π§ Benefits of Layered Code Generation¶
| Benefit | Description |
|---|---|
| β Separation of concerns | Prevents cross-layer leakage in AI output |
| β Skill modularity | Skills stay focused and reusable |
| β Safe recomposition | Agents can regenerate or reflow just one layer |
| β Observability | Each artifact is linked to agent, skill, and layer |
| β Governance | Reviewers can focus on one layer per MR or PR phase |
β Summary¶
- Each Clean Architecture layer in ConnectSoft is mapped to agent skills and blueprint sections
- Code is generated in phases, with layer-specific outputs, validation, and traceability
- This ensures high-quality, composable automation with clear separation of concerns
π§° Template Constraints and Conventions¶
In ConnectSoft, code is generated from opinionated templates that enforce architectural correctness, layering discipline, naming standards, and skill-to-folder alignment. These constraints ensure that agents consistently produce clean, valid, and maintainable code β no matter how many modules are generated.
βTemplates are not scaffolds β theyβre guardrails for intelligent automation.β
This cycle describes how templates encode ConnectSoftβs Clean Architecture conventions and how they are enforced during code generation.
π§ Why Constraints Matter for AI Agents¶
Without constraints:
- Agent output drifts from best practices
- Layer boundaries are crossed
- Test coverage becomes inconsistent
- Naming, file paths, and contracts are unpredictable
With constraints:
- Every artifact is where it belongs
- Agents only emit valid, buildable, and auditable code
- Errors are caught at generation time, not during integration
π¦ Layer-Based Template Enforcement¶
| Layer | Enforced Constraints |
|---|---|
| Domain | No infrastructure references; only aggregates, entities, value objects, and domain events allowed |
| Application | Must depend only on Domain; handlers must raise domain events; commands must match contracts |
| Infrastructure | Only adapters and service wiring; no business logic or domain rules |
| Entry Points | Controller actions must call only Application services; no repository access allowed |
| Tests | Must use mocks, stubs, or generated fixtures; each handler must have coverage if testing is enabled |
π§© Naming & File Path Conventions¶
All templates enforce standard naming and file placement:
| Artifact | Convention |
|---|---|
| Aggregate | Domain/Aggregates/{Name}Aggregate.cs |
| Command Handler | Application/Handlers/{CommandName}Handler.cs |
| Repository Interface | Application/Contracts/I{Name}Repository.cs |
| Repository Adapter | Infrastructure/Persistence/{Name}Repository.cs |
| Domain Event | Domain/Events/{EventName}.cs |
| Test File | Tests/Features/{ScenarioName}.feature |
β Ensures predictability and traceability across thousands of modules.
π§ͺ Template-Driven Validation Hooks¶
Each template registers post-generation validators:
- β Structure validator (expected folders and file names)
- β Dependency validator (no illegal references between layers)
- β Blueprint-field match validator (command names, entity fields)
- β Prompt input coverage validator (ensures skill output reflects all inputs)
- β Linter and formatting rules (naming conventions, spacing, casing)
π§ Example: Enforced Handler Output¶
public class BookAppointmentHandler : IRequestHandler<BookAppointmentCommand, AppointmentDto>
{
private readonly IBookingRepository _repo;
private readonly IEventPublisher _eventPublisher;
public async Task<AppointmentDto> Handle(BookAppointmentCommand command, CancellationToken ct)
{
var booking = BookingAggregate.Book(...);
await _repo.SaveAsync(booking);
_eventPublisher.Publish(new AppointmentBooked(...));
return booking.ToDto();
}
}
β Matches layer responsibilities β References domain, not infrastructure β Emits event β Returns DTO, not entity
π Prompt + Template Coupling¶
Prompts are parameterized and tied to templates, not freeform:
skill: GenerateHandler
template: handler/app-layer/v1
input:
command: BookAppointment
aggregate: Booking
outputEvent: AppointmentBooked
β Ensures that agent output always aligns with the factoryβs architecture model.
π§± Build-Phase Enforcement¶
CI/CD pipelines and agents validate that:
- Output files match expected location & naming
- Artifacts are registered in
execution-metadata.json - Code builds successfully before publishing
- Code coverage thresholds are met for testable layers
β Summary¶
- Templates in ConnectSoft enforce Clean Architecture alignment by design
- Every layer has guardrails, validators, and naming rules baked into generation logic
- This ensures that AI agents produce predictable, traceable, and scalable artifacts
ποΈ Infrastructure Independence¶
In ConnectSoft, infrastructure is treated as a secondary concern β essential for execution but never allowed to pollute the core domain. This aligns with Clean Architecture principles and enables AI agents to swap, adapt, or regenerate infrastructure code without touching application or domain logic.
βInfrastructure is where implementation lives β but never where decisions start.β
This principle gives ConnectSoft the ability to generate, validate, and replace persistence, messaging, and external integrations dynamically and modularly.
π§ Why Infrastructure Must Be Independent¶
| Risk if Coupled | Strategic Consequence |
|---|---|
| Infrastructure bleeds into domain | Business logic becomes fragile and non-portable |
| Application knows about DB or queues | Tests become slow, brittle, and complex |
| Regeneration of infra breaks core logic | Increases agent risk and reduces automation safety |
| Multi-tenant layering is compromised | Security and isolation violations occur |
β ConnectSoft treats all infrastructure as pluggable adapters governed by interfaces.
π§© Clean Structure of Infra Layer¶
| Component | Purpose |
|---|---|
| Adapters | Implement IRepository, IQueuePublisher, IExternalServiceClient |
| Factories | Wire dependencies for injection |
| Mappings | Define schema for NHibernate, MongoDB, Dapper, etc. |
| Transport Modules | Handle communication with queues, REST APIs, services |
| Tenant Guards | Enforce per-tenant scoping at adapter boundaries |
π Blueprint β Infra Template Mapping¶
infrastructure:
persistence: nhibernate
pubsub: azure-service-bus
adapters:
- AppointmentPublisher
- BookingRepository
β Triggers:
BookingRepository.csAppointmentPublisher.csNhBookingMapping.hbm.xmlor Bicep modulesQueueBindings.jsonfor messaging configuration
π€ Agent-Driven Infrastructure Generation¶
| Agent | Skills |
|---|---|
Infrastructure Engineer Agent |
GenerateRepositoryAdapter, EmitDbMapping, GenerateServiceClient |
Cloud Provisioner Agent |
GenerateBicepModule, InjectInfraSecrets |
DevOps Engineer Agent |
GenerateTransportBindings, ConfigureConnectionStrings |
π Infrastructure Swap Patterns¶
If blueprint or tenant config changes:
- β Swap NHibernate β MongoDb β regenerate adapter only
- β
Replace
ServiceBuswithEventGridβ generate new transport binding - β
Add
TenantFilterto repository β only adapter is touched
β Domain and App layers are never modified.
π Enforcement Rules¶
Templates and validators ensure:
- Infra code cannot reference domain or application types
- Adapter files must follow
Infrastructure/Adapters/*convention - Connection strings and secrets are injected via config only
- Adapters include built-in
tenantIdor context-scoping guards - All outbound communication is traceable by artifact and event contract
π§ͺ Infra Layer Testability¶
Agents generate:
- In-memory adapters for unit tests
- Mocks and fakes via
Test Generator Agent - Integration tests with test containers or stubs
- Configuration diff reports (e.g.,
infra-config-changes.json)
β Summary¶
- Infrastructure in ConnectSoft is modular, swappable, and strictly separated from core logic
- AI agents treat infrastructure as adapter outputs, never as business dependencies
- This principle enables safe regeneration, tenant isolation, and portability across cloud platforms
π§ͺ Domain-Led Testing¶
In ConnectSoft, testing is not a last step β itβs a first-class citizen of the generation pipeline. Tests are generated based on domain behavior, blueprint-defined use cases, and expected outputs. This results in executable specifications that validate domain logic, use case flows, and system invariants β across all layers.
βIf a use case exists in the blueprint, it has a test. No exceptions.β
The Test Generator Agent and QA Agent collaborate to ensure that every command, event, and scenario is validated through clean, layered, and traceable tests.
π§ Why Domain-Led Testing?¶
| Goal | Enabled By |
|---|---|
| β Verify domain behavior | Aggregates and entities tested via core invariants |
| β Validate use cases | Application services and handlers tested against input/output |
| β Ensure traceability | Test scenarios are linked to blueprint items and agent executions |
| β Support CI/CD automation | Generated tests are part of orchestrated flows and code contracts |
π Blueprint β Test Flow Mapping¶
useCases:
- name: BookAppointment
input:
- petId: Guid
- startTime: DateTime
expectedEvent: AppointmentBooked
test:
name: "Book appointment successfully"
type: BDD
validate: outputEvent
β This triggers generation of:
BookAppointment.feature(SpecFlow)BookAppointmentHandlerTests.cs(unit test)BookingAggregateTests.cs(aggregate test)AppointmentsByDateSpecTests.cs(spec validation)
π§© Agent Skills for Testing¶
| Agent | Skills |
|---|---|
Test Generator Agent |
GenerateSpecFlowTest, GenerateUnitTestForHandler, GenerateAggregateTest |
QA Agent |
ValidateTestCoverage, EmitTestContractResults, FlagMissingTests |
Bug Investigator Agent |
GenerateReproScenario, InjectEdgeCaseTest |
π¦ Types of Tests Generated¶
| Test Type | Target |
|---|---|
| SpecFlow Features | User stories and scenarios from blueprints |
| Unit Tests | Handlers, aggregates, services |
| Integration Tests | Repositories, pub/sub, external API clients |
| Event Flow Assertions | Domain events emitted and consumed |
| Edge Case & Regression Tests | Based on feedback or trace diffs |
π§ͺ Example: Generated Unit Test¶
[Fact]
public async Task BookAppointmentHandler_ShouldEmit_AppointmentBooked()
{
var command = new BookAppointmentCommand(...);
var handler = new BookAppointmentHandler(...);
var result = await handler.Handle(command, default);
_eventPublisherMock.ShouldHavePublished<AppointmentBooked>();
result.ShouldNotBeNull();
}
β Generated alongside the handler, named according to conventions, and fully traceable.
π§ Observability and Validation¶
Each test artifact includes:
traceId,agentId,skillId, andblueprintSection- Links to the use case, event, and entity it validates
- Code coverage tracked and surfaced in Studio
- Diff viewer for test regeneration with semantic output comparison
π Test Regeneration Strategy¶
| Trigger | Result |
|---|---|
| New use case in blueprint | New SpecFlow + unit test |
| Changed output contract | Affected test cases regenerated |
| Refactored aggregate | Only aggregate test regenerated |
| Failed validation | Agent-triggered rerun + feedback captured |
π CI Integration¶
Generated tests:
- Are compiled, executed, and validated in CI/CD pipelines
- Emit
TestSuiteGenerated,TestSuitePassed, orTestSuiteFailedevents - Block release transitions if test coverage or pass rate is below threshold
- Are automatically tagged and traced per orchestrated module build
β Summary¶
- Domain-led testing ensures that every AI-generated flow is verifiable, executable, and traceable
- Tests are linked to blueprints, agents, and prompts β and are generated alongside core logic
- This enables safe automation, quality assurance, and confidence in every module
π’ Multi-Tenant Domain Isolation¶
ConnectSoft is a multi-tenant SaaS factory by design β and Domain-Driven Design (DDD) with Clean Architecture plays a critical role in ensuring that each tenantβs data, logic, and configuration remain isolated.
βIn ConnectSoft, tenants donβt just use modules β they receive isolated, domain-aligned blueprints.β
Domain isolation enables tenant-specific behavior without code duplication, while maintaining architectural purity, automation safety, and observability.
π§ Isolation by Design, Not by Patch¶
| Isolation Concern | Handled By |
|---|---|
| Data | Tenant-scoped repositories, per-tenant DB schemas |
| Logic | Edition-specific blueprint overlays |
| Configuration | Scoped infrastructure adapters (e.g., per-tenant queues, APIs) |
| Events | Tenant-tagged emissions and scoped routing |
| Agent Execution | Per-tenant context injected into prompt, skill, and coordinator |
π Blueprint β Tenant Configuration Mapping¶
tenantId: vetclinic001
module: BookingService
edition: premium
overrides:
- CancelAppointment enabled
- SMSReminders enabled
context: Booking
β Triggers:
- Enriched prompt and blueprint generation
- Edition-specific handler logic
- Infrastructure isolation for outbound integrations
- Tenant-specific testing and trace context
π§© Tenant Isolation Enforcement in Clean Layers¶
| Layer | Isolation Strategy |
|---|---|
| Domain | No tenant logic here β pure rules, reusable across tenants |
| Application | Conditional logic injected based on edition features |
| Infrastructure | Repositories and clients scoped via tenant ID injection |
| Entry Points | Auth & routing filtered by tenant claims |
| Tests | Test scenarios executed per tenant blueprint with injected data |
π Enforcement via Agent Metadata and Templates¶
- Each agent execution is tied to a
tenantIdandprojectId - Prompts include tenant and edition context
- Generated files are tagged and stored in tenant-specific directories
- Infrastructure agents create isolated config files and secrets (e.g., Azure Key Vault per tenant)
- Studio guards regeneration/editing by tenant scope permissions
π€ Agent Skills Supporting Tenant Isolation¶
| Agent | Skills |
|---|---|
Backend Developer Agent |
InjectEditionLogic, MapFeatureToggles |
Cloud Provisioner Agent |
GenerateTenantScopedBicep |
Infrastructure Engineer Agent |
ConfigureTenantDB, GeneratePerTenantQueueBindings |
QA Agent |
RunTenantSpecificTests, ValidateEditionCoverage |
π¦ Folder Structure Example¶
/tenants/
vetclinic001/
/BookingService/
/Domain/
/Application/
/Infrastructure/
/Tests/
booking-service.execution-metadata.json
β Keeps generation, deployment, and traceability scoped per tenant.
π Observability Per Tenant¶
Studio and telemetry dashboards show:
- Module status per tenant
- Test coverage and release metrics scoped by
tenantId - Agent success/failure rates by tenant
- Event flow visualization for per-tenant orchestration
β Summary¶
- Multi-tenancy is achieved via clean isolation, tenant-scoped blueprints, and layered enforcement
- Domain logic remains pure, while tenant-specific adaptations happen in the Application and Infrastructure layers
- This enables safe, scalable, and traceable tenant-specific generation without code duplication
π CQRS and Event Sourcing Support¶
ConnectSoft supports Command Query Responsibility Segregation (CQRS) and Event Sourcing as optional architectural patterns β applied strategically when the domain, blueprint, or scalability requirements justify it.
βCQRS and Event Sourcing are not default β theyβre agent-triggered based on blueprint intent.β
These patterns allow the platform to split read and write concerns, persist source-of-truth events, and automatically generate projections, all while staying aligned with Clean Architecture and DDD boundaries.
π§ When to Use CQRS¶
| Trigger | Rationale |
|---|---|
| High read/write disparity | Optimize read projections independently |
| Complex domain events | Capture immutable history per aggregate |
| Audit/trace required | Persist events instead of just state |
Blueprint explicitly defines cqrs: true |
Enforce command/query split and projection generation |
π Blueprint Example Enabling CQRS¶
cqrs: true
aggregate: Booking
commands:
- BookAppointment
- CancelAppointment
queries:
- AppointmentsByDate
eventSourcing: true
β Triggers agents to:
- Generate event-sourced aggregate methods
- Store
AppointmentBooked,AppointmentCancelledevents - Emit projections (
AppointmentsReadModel) - Use handlers like
IRequestHandler<Command>andIRequestHandler<Query>separately
π§© Code Artifacts per Pattern¶
| Component | Generated File |
|---|---|
| Command Handler | BookAppointmentHandler.cs |
| Event | AppointmentBooked.cs |
| Event Store Adapter | EventStoreRepository.cs |
| Projection | AppointmentsReadModel.cs |
| Query Handler | GetAppointmentsByDateHandler.cs |
β Cleanly separates write path (commands/events) from read path (projections/queries).
π€ Agent Responsibilities in CQRS/ES¶
| Agent | Skills |
|---|---|
Backend Developer Agent |
GenerateCQRSHandlers, EmitProjections, RouteAggregateEventFlow |
Domain Modeler Agent |
GenerateEventSourcedAggregate, ApplyEventMethod |
Infrastructure Engineer Agent |
GenerateEventStoreAdapter, ConfigureProjectionStore |
Test Generator Agent |
GenerateCQRSFlowTests, ValidateProjectionAccuracy |
π§ͺ Example: Event-Sourced Aggregate¶
public class BookingAggregate : AggregateRoot
{
public void Apply(AppointmentBooked e) { ... }
public void Book(...) {
AddDomainEvent(new AppointmentBooked(...));
}
}
β Events are persisted, applied, and used to reconstruct state.
π§± Infrastructure Considerations¶
Agents may emit:
EventStoreRepository.cs(for event persistence)- Bicep modules for
Event Hub,Service Bus, orEventStoreDB - Projection storage (
SQL,Cosmos,Elastic) - Configuration for snapshot intervals, replay boundaries, and retention policies
π CQRS Flow (Simplified)¶
sequenceDiagram
participant Client
participant CommandHandler
participant Aggregate
participant EventStore
participant Projection
Client->>CommandHandler: BookAppointmentCommand
CommandHandler->>Aggregate: Execute
Aggregate->>EventStore: Append AppointmentBooked
EventStore->>Projection: Emit to AppointmentsReadModel
β
All flows are agent-generated, traced, and validated via traceId.
π Studio Support¶
- CQRS mode toggle in module blueprint UI
- Visual split between read and write models
- Projection viewer and event store inspector
- Test coverage per flow (command β event β projection)
β Summary¶
- CQRS and Event Sourcing are first-class supported patterns, but only applied when specified in blueprints
- Agents generate fully separated write/read paths, event stores, and read models
- This provides scalability, auditability, and traceable automation in high-complexity domains
π‘οΈ Strategic Anti-Corruption Layers (ACLs)¶
In ConnectSoft, Anti-Corruption Layers (ACLs) are essential for protecting the integrity of bounded contexts and aggregates. They prevent external systems, third-party APIs, or cross-domain services from introducing concepts that leak into your domain model.
βThe ACL is a semantic firewall β it translates foreign language into your domainβs terms.β
ACLs are generated by agents to ensure that each context remains isolated, pure, and testable, while still integrating safely with the outside world.
π§ Why ACLs Matter in AI-Generated Systems¶
| Risk Without ACL | Consequence |
|---|---|
| External concepts leak into core domain | Domain logic becomes polluted and inconsistent |
| Hardcoded HTTP/API/DB calls in domain layer | Testability and automation reliability break |
| No version protection | Upstream changes cause silent downstream corruption |
| Multi-context integration becomes implicit | Coordination and agent orchestration drift |
β ACLs preserve the semantic clarity and clean layering required for large-scale automation.
π Blueprint Example β ACL Trigger¶
integrations:
- source: ExternalCRM
contract: ContactSynced
mapTo: ClientUpdated
adapter: CrmClient
isolation: anti-corruption
β Triggers agents to generate:
CrmClientAdapter.csContactDto β ClientUpdatedEventmapperClientUpdated.csdomain eventIntegrationTest_CrmSync.feature
π§© Agent Roles in ACL Generation¶
| Agent | Skills |
|---|---|
Infrastructure Engineer Agent |
GenerateIntegrationAdapter, ConfigureHttpClient, SecureOutboundCalls |
Event-Driven Architect Agent |
MapExternalEvent, DefineACLBoundary |
Domain Modeler Agent |
GenerateTranslatedDomainEvent, ProtectAggregateFromExternalLeakage |
Documentation Writer Agent |
DocumentIntegrationContract |
π§± Clean Placement of ACLs¶
ACL artifacts are placed in:
Domain does not know about CRM β all translation occurs via adapter and published domain event.
π ACL Translation Patterns¶
| Source | ConnectSoft Layer |
|---|---|
External Event (e.g., ContactSynced) |
Translated into a DomainEvent (e.g., ClientUpdated) |
| External API Response | Mapped into a ValueObject or DTO |
| External Command | Wrapped by orchestrator β routed to clean App layer |
β This preserves bounded context semantics, even in collaborative flows.
π§ͺ Agent-Generated Tests¶
ACLs include:
- Integration test with stubbed external API
- Mapper unit test: DTO β Event
- Domain event emission test after external call
- Config test for endpoint, timeout, auth headers
π Security and Observability¶
ACLs enforce:
- Isolation of authentication tokens/secrets via config
- TraceId propagation across external requests
- Circuit breakers and retry policies by default
ExternalCallStarted,ExternalCallSucceeded,ExternalCallFailedevents for observability
Studio shows:
- ACL boundary mapping
- Integration health metrics
- Agent skill history for ACL interactions
β Summary¶
- Anti-Corruption Layers in ConnectSoft are automatically generated to protect core domains from upstream system leaks
- ACLs are placed in infrastructure, emit domain-native events, and are fully testable, observable, and secure
- This ensures that integrations are modular, aligned with Clean Architecture, and automation-safe
β οΈ Clean Architecture Anti-Patterns¶
Even in an AI-driven system like ConnectSoft, architectural integrity can be compromised if generated code deviates from core Clean Architecture principles. To ensure consistency, safety, and long-term maintainability, we actively document and defend against a set of Clean Architecture Anti-Patterns.
βArchitectural decay starts with one broken boundary. The platform makes sure it ends there too.β
This cycle catalogs what to avoid when generating, validating, or reviewing AI-generated services in the factory.
β 1. Anemic Domain Models¶
Symptom: Entities contain only properties, no behavior.
Consequence:
- Business rules leak into handlers or infrastructure
- No central enforcement of invariants
- Hard to test and evolve
β Fix: Use aggregates and value objects with rich methods and domain events.
β 2. Logic in Infrastructure¶
Symptom: Business logic inside adapters, mappers, or repositories.
Consequence:
- Coupling to frameworks or external systems
- Hard to trace or test behavior
- Domain becomes passive and infrastructure becomes fragile
β Fix: Keep logic in Domain and Application layers only. Use interface-based adapters.
β 3. Cross-Layer References¶
Symptom: Infrastructure references Application; Application references Infra.
Consequence:
- Violates dependency inversion
- Prevents test isolation
- Breaks modular generation
β
Fix: Only Infrastructure β Application allowed via inversion. Domain is always inward-facing.
β 4. Controller/Handler Bloat¶
Symptom: Controller or command handler performs validation, logic, mapping, and persistence.
Consequence:
- Difficult to test and regenerate safely
- Low reusability
- Confusing agent responsibilities
β Fix: Use separate validators, services, and domain entry points.
β 5. Blueprint Misalignment¶
Symptom: Generated code doesnβt match the blueprint (wrong contracts, events, or paths).
Consequence:
- Coordination flows break
- Orchestrators fail to resume
- Reviewers lose trust in generation quality
β Fix: Enforce traceable mapping between blueprint section β agent skill β generated artifact.
β 6. Test Coverage Gaps¶
Symptom: Tests not generated for use cases, events, or queries.
Consequence:
- Low automation trust
- Uncaught errors in downstream flows
- Broken release confidence
β Fix: Require test suite per command/event. Validate coverage threshold in CI.
β 7. Misplaced Integration Logic¶
Symptom: External API logic placed directly in handlers or application services.
Consequence:
- Breaks bounded context
- Pollutes business workflows
- Reduces tenant isolation and testability
β Fix: Route external interactions through ACLs and infrastructure adapters.
β 8. Ignoring Tenant Context¶
Symptom: Multi-tenant modules with no tenant scoping in repositories or services.
Consequence:
- Data leakage risk
- Invalid deployments
- Failed governance audits
β Fix: Enforce tenantId injection, validation, and partitioning at adapter layer.
β Clean Architecture Guardrails in ConnectSoft¶
| Anti-Pattern | Prevented By |
|---|---|
| Anemic model | Domain Modeler Agent + Blueprint constraints |
| Cross-layer refs | Validators in CI + skill-to-layer metadata |
| Logic leakage | Templates enforce role-based file structure |
| Test gaps | TestSuiteRequired event + Orchestrator gating |
| Tenant violations | TenantScopeRequired enforcement in blueprint schema |
β Summary¶
- Clean Architecture anti-patterns are actively prevented through templates, validators, and agent scoping
- These practices ensure that ConnectSoft-generated modules are maintainable, modular, and testable at scale
- Awareness of anti-patterns helps reviewers, prompt authors, and agent curators build better workflows
β Summary and Design Rules¶
Clean Architecture and Domain-Driven Design (DDD) are foundational principles in ConnectSoft β not for aesthetic reasons, but because they enable AI agents to generate modular, scalable, and safe software autonomously.
Over the previous 19 cycles, weβve shown how these principles empower:
- π¦ Modular generation of thousands of services
- π Agent collaboration through contracts and layering
- π§ Context-aware automation based on domain boundaries
- π‘οΈ Safe regeneration, validation, and governance
- π§ͺ Full test coverage and traceability across flows
π§ Core Principles Recap¶
| Principle | Outcome |
|---|---|
| Bounded Contexts | Agents operate within well-scoped modules and domains |
| Layered Architecture | Prompts, skills, and outputs map cleanly to responsibilities |
| Domain-Centric Modeling | Aggregates, events, and entities reflect business meaning |
| Infrastructure Decoupling | Adapters can be regenerated or replaced without risk |
| Prompt & Skill Alignment | Each output is intentional, traceable, and contract-bound |
| Test as Spec | Every use case, event, and behavior is verifiable |
| Tenant Isolation | Multi-tenant SaaS is secure and maintainable by design |
| Observability | Agents, artifacts, and flows are all tracked by metadata and events |
π Clean Architecture Checklist for ConnectSoft Agents¶
β Blueprint & Structure¶
- Each blueprint has a declared
boundedContext,aggregate, andlayeredSections - Use cases are defined via
commands,queries, andexpectedEvents
β Domain Layer¶
- Aggregates enforce business rules and emit domain events
- Entities contain behavior, not just properties
- No references to infrastructure or application services
β Application Layer¶
- Handlers are thin and use services or aggregates for logic
- Output DTOs and events are mapped clearly
- Prompt-generated handlers are idempotent and testable
β Infrastructure Layer¶
- Repositories and services are adapter-based
- Tenant context is injected and validated
- No domain or application logic lives here
β Entry Points¶
- Controllers and APIs call application handlers only
- OpenAPI contracts match handler signatures
- Routing supports multitenancy and modular deployment
β Testing & Validation¶
- Each use case has a SpecFlow + unit test
- Event flow tests validate event emission and consumption
- Generated tests pass CI with required coverage thresholds
β Governance¶
- Each artifact has
traceId,agentId,skillId, andlayer - Prompt + blueprint β output mappings are recorded
- Orchestrators validate required outputs before release
π¦ Platform-Integrated Enforcements¶
| Enforcement | Where Applied |
|---|---|
| Layer scoping | Templates, orchestrators, Studio validation |
| Agent execution boundaries | Skill metadata + agent manifest |
| Artifact placement | CI validators + execution metadata |
| Test contract enforcement | QA Agent + feedback loop |
| Clean regeneration | FSM-aware re-execution logic |
π§ Final Thought¶
βClean Architecture and DDD make agentic software generation possible β scalable, traceable, and safe.β
With these principles, ConnectSoft transforms prompts into blueprints, blueprints into services, and services into sustainable products β without compromising quality, modularity, or compliance.