Skip to content

🧱 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

aggregate: Booking
command: BookAppointment
layer: Application
output: BookAppointmentHandler.cs

β†’ 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:

/modules/
  Booking/
    /Application/
    /Domain/
    /Infrastructure/
    /Tests/
    /Docs/
    /Contracts/

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-developer cannot 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:

  • AppointmentBooked
  • InvoiceGenerated
  • UserRegistered

They are emitted by aggregates and consumed by:

  • 🧠 Other domain models
  • βš™οΈ Coordinators and agents
  • πŸ§ͺ Test validators
  • πŸš€ Pipelines and deployment triggers

πŸ“¦ Blueprint β†’ Aggregate β†’ Event Flow

aggregate: Booking
command: BookAppointment
emitsEvent: AppointmentBooked

β†’ Used by Domain Modeler Agent to create:

  • BookingAggregate.cs
  • Appointment.cs
  • AppointmentBooked.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:

  1. Orchestrator receives AppointmentBooked
  2. Notification Agent, Analytics Agent, or QA Agent are triggered
  3. CI pipeline may generate release if event == ReleaseReady
  4. 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 tenantId injection 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

public record PetName(string First, string Last);

βœ… 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

  1. Agent reads blueprint or prompt containing domain vocabulary
  2. Matches terms to modeling templates (e.g., entity, value object, aggregate)
  3. Validates field types and modifiers
  4. Injects guard clauses or invariant checks
  5. Emits artifacts with metadata (traceId, skillId, contextId)
  6. 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.cs
  • GetAppointmentsByDateQuery.cs
  • Optional AppointmentsByDateHandler.cs if 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:

event: AppointmentBooked
context: Booking
traceId: abc123
source: BookingAggregate

β†’ Which triggers:

  • Notification Agent
  • Analytics Agent
  • Deployment 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
Hold "Alt" / "Option" to enable pan & zoom

βœ… No hardcoding, only event-contract-driven automation.


πŸ“¦ Blueprint β†’ Event Mapping

events:
  emits:
    - AppointmentBooked.v1
    - AppointmentCancelled.v1
  consumes:
    - UserRegistered.v1

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:

state: awaitingTest
on:
  - event: TestSuitePassed
    transitionTo: readyForRelease

Or trigger agent workflows:

onEvent: AppointmentBooked
invoke:
  - NotifyClientAgent
  - UpdateCalendarAgent

βœ… 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
Hold "Alt" / "Option" to enable pan & zoom

β†’ 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., GenerateHandler must match command section)
  • Missing section detection (e.g., handler exists but event not 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
Hold "Alt" / "Option" to enable pan & zoom

β†’ 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

/modules/
  Booking/
    /Domain/
    /Application/
    /Infrastructure/
    /API/
    /Tests/
    execution-metadata.json

β†’ 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 layer in 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.cs
  • AppointmentPublisher.cs
  • NhBookingMapping.hbm.xml or Bicep modules
  • QueueBindings.json for 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 ServiceBus with EventGrid β†’ generate new transport binding
  • βœ… Add TenantFilter to 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 tenantId or 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, and blueprintSection
  • 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, or TestSuiteFailed events
  • 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 tenantId and projectId
  • 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, AppointmentCancelled events
  • Emit projections (AppointmentsReadModel)
  • Use handlers like IRequestHandler<Command> and IRequestHandler<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, or EventStoreDB
  • 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
Hold "Alt" / "Option" to enable pan & zoom

βœ… 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.cs
  • ContactDto β†’ ClientUpdatedEvent mapper
  • ClientUpdated.cs domain event
  • IntegrationTest_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:

/Infrastructure/Adapters/ExternalCRM/
  - CrmClient.cs
  - CrmToDomainMapper.cs
  - CrmConfig.cs

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, ExternalCallFailed events 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, and layeredSections
  • Use cases are defined via commands, queries, and expectedEvents

βœ… 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, and layer
  • 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.