Skip to content

🧠 Domain Modeler Agent Specification

🎯 Purpose

The Domain Modeler Agent is responsible for transforming business language, bounded contexts, and use case responsibilities into a structured, expressive, and implementation-ready Domain Model, grounded in Domain-Driven Design (DDD) and Clean Architecture.

Its purpose is to define the semantic core of a service, enabling:

  • Accurate representation of real-world business concepts
  • Isolation of domain logic from application/infrastructure concerns
  • Safe reuse of invariants, rules, and entities across the platform
  • Domain understanding shared by agents, developers, and testers

πŸ—οΈ Strategic Role in ConnectSoft Factory

flowchart TD
    EnterpriseArchitect --> SystemArchitect
    SystemArchitect --> SolutionArchitect
    SolutionArchitect --> DomainModeler
    DomainModeler --> ApplicationArchitect
    DomainModeler --> MicroserviceGenerator
    DomainModeler --> EventDrivenArchitect
    DomainModeler --> TestGenerator
Hold "Alt" / "Option" to enable pan & zoom
  • The Domain Modeler Agent receives architectural context and bounded context definitions
  • It becomes the source of truth for all domain logic used across services, events, and behaviors

🧠 Core Objectives

Objective Description
πŸ“¦ Define Domain Language Model entities, aggregates, value objects, domain events using a ubiquitous and precise vocabulary
🧱 Establish Domain Boundaries Encapsulate invariants, lifecycles, rules, and business workflows per bounded context
πŸ” Enable Autonomous Execution Emit clear models usable by Application Architect and downstream agents without human intervention
πŸ§ͺ Support Testability and Simulation Produce stubs, diagrams, and invariants for testing and validation agents
πŸ“ Drive Consistency Across Services Standardize reuse of enums, identities, currencies, states, and behavior markers

πŸ’‘ Why It Matters

Without the Domain Modeler Agent:

  • Agents downstream rely on ad-hoc or inconsistent domain assumptions
  • Event names, entities, and use cases may drift apart
  • Invariants and rules are lost in application glue code
  • Testing becomes less meaningful, validation is shallow
  • Business logic becomes implementation-driven rather than domain-driven

With the Domain Modeler Agent:

  • Domain becomes explicit, traceable, and contract-first
  • Clean separation of concerns is maintained
  • Teams and agents share a common language
  • The platform supports scale, reuse, and evolution

πŸ” Example Output Scenario

For the Billing bounded context, model:
- Invoice (aggregate root with lifecycle states)
- InvoiceLineItem (value object)
- InvoiceStatus (enum)
- ApplyDiscount and InvoiceCreated (domain events)
- TaxPolicyEvaluator (domain service)

Outputs:

  • domain-model.yaml
  • Invoice.cs, InvoiceStatus.cs, TaxPolicyEvaluator.cs
  • invoice-lifecycle.mmd (state diagram)
  • Semantic hint tags (e.g., aggregate_root: true)

🧭 Agent Design Principles

  • 🧱 Tactical DDD First
  • πŸ” Isolated Aggregates
  • βœ… Invariant Enforcement
  • πŸ“„ Artifact-First Modeling
  • πŸ§ͺ Validation-Driven Design

πŸ›οΈ Scope of Influence

The Domain Modeler Agent governs the core domain layer of every service within a bounded context.
Its scope is centered on the tactical building blocks of Domain-Driven Design, which form the foundation of:

  • Business logic
  • Invariant enforcement
  • Entity lifecycles
  • Event emission
  • Internal service behavior

It ensures that the semantic backbone of each microservice is expressive, correct, reusable, and consistent.


πŸ“‹ Layers and Components the Agent Owns

πŸ“¦ 1. Aggregates and Entities

Element Description
Aggregate Roots Main access point to clustered entities enforcing invariants (e.g., Invoice, Order, Customer)
Entities Objects with identity, lifecycle, and business behavior within an aggregate
Relationships Parent-child, one-to-many, composed-by (e.g., Invoice β†’ LineItems)

🎯 2. Value Objects (VOs)

Element Description
Immutability Represent concepts without identity (e.g., Money, Address, TaxCode)
Equality Compared by value not by reference
Reuse Encouraged across bounded contexts where ubiquitous meaning applies

πŸ“Š 3. Enumerations and Specifications

Element Description
Enums Define known states/variants (e.g., InvoiceStatus, SubscriptionTier)
Specifications Encapsulate query rules or policies (e.g., HasOverdueBalance, EligibleForUpgrade)

πŸ” 4. Domain Services

Element Description
Domain Services Stateless operations that coordinate multiple aggregates or external domain logic
Policies Algorithms, pricing rules, or eligibility engines that don't belong to a single entity

πŸ“’ 5. Domain Events

Element Description
Internal Events Triggered within aggregates to signal state changes (e.g., InvoiceCreated, DiscountApplied)
Externalizable Events May be promoted by downstream agents into integration events
Event Metadata Correlation IDs, traceability, invariants enforced when emitted

πŸ“ 6. Supporting DSL and Diagrams

Artifact Purpose
domain-model.yaml Machine-readable structure describing aggregates, VOs, entities, and rules
*.cs or DSL skeletons Class/interface/enum/value object stubs
*.mmd diagrams State machines, class diagrams, entity hierarchies
validation-matrix.yaml Rules per entity field (e.g., Amount must be > 0)

🚫 Out of Scope

Item Handled By
Application service orchestration βœ… Application Architect Agent
API design and surface definition βœ… API Designer Agent
External adapters, persistence βœ… Microservice Generator + Adapter Agent
Infrastructure layer decisions βœ… Infrastructure Architect Agent
Non-functional requirements βœ… Solution Architect Agent
Business glossary / definitions βœ… Ubiquitous Language Agent

🧭 Domain Modeler Boundary Map

flowchart TD
    subgraph "Owned by Domain Modeler Agent"
      A1[Aggregate Roots]
      A2[Entities]
      A3[Value Objects]
      A4[Enumerations]
      A5[Domain Services]
      A6[Domain Events]
    end

    subgraph "Used by Others"
      B1[Application Architect Agent]
      B2[Test Generator Agent]
      B3[Microservice Generator Agent]
    end

    A1 --> B1
    A2 --> B3
    A6 --> B2
Hold "Alt" / "Option" to enable pan & zoom

🧠 Summary

The Domain Modeler Agent owns the domain layer, but its influence spans every downstream agent.
It is the semantic contract keeper of ConnectSoft services, providing the deepest source of truth for business behavior.


πŸ“‹ Core Responsibilities

The Domain Modeler Agent is responsible for designing the rich, invariant-driven, and reusable domain layer within each bounded context.
Its outputs serve as the semantic foundation for all downstream agents.


🧱 1. Aggregate and Entity Modeling

Task Description
Identify Aggregates Determine root entities responsible for enforcing business invariants and lifecycle boundaries
Define Entities Structure objects with identity, behavior, and relationships (e.g., Invoice, Customer, Payment)
Model Relationships Parent-child hierarchies, composition patterns, internal collections
Lifecycle and State Define lifecycle states, transitions, and versioning controls if needed

πŸ“¦ 2. Value Object Definition

Task Description
Model Concepts Without Identity Immutable objects such as Money, EmailAddress, Address, PhoneNumber
Embed into Aggregates Used as properties within entities (not referenced externally)
Ensure Equality and Reusability Enforce by-value equality and encourage reuse across services

πŸ“Š 3. Enumeration & Specification Design

Task Description
Enumerations Define controlled vocabularies or states (e.g., InvoiceStatus, UserRole, RiskLevel)
Specifications Create boolean rules for filtering, policies, or validation (e.g., HasOverdueBalance, IsEligibleForFreeTrial)
Use within Aggregates Allow aggregates to apply specifications internally during commands or lifecycle decisions

🧠 4. Domain Service and Policy Modeling

Task Description
Extract Complex Logic Externalize logic that doesn’t naturally belong to an entity (e.g., pricing, scoring, eligibility)
Coordinate Aggregates Allow multi-aggregate orchestration with invariant checking
Model as Stateless Services Output as interface-based contracts that can be unit-tested or decorated by downstream agents

πŸ“’ 5. Domain Event Generation

Task Description
Emit Internal Events Define rich events emitted from domain logic (e.g., InvoiceCreated, PaymentFailed, CustomerBlacklisted)
Define Payload Contracts Include entity references, value object snapshots, correlation IDs
Categorize as Internal or Externalizable Mark events that may need to be promoted to integration events
Support Replay and Event Sourcing (optional) If event-sourced, structure events to allow reconstruction of entity state

πŸ“ 6. Output Artifact Assembly

Artifact Description
domain-model.yaml Main structure of domain definitions in DSL
.cs stubs Optional generated files for Entity, VO, Enum, Specification, and DomainService
validation-map.yaml Rules for fields (e.g., DueDate must be β‰₯ IssueDate)
entity-lifecycle.mmd Mermaid state diagrams for aggregate states
domain-events.json Catalog of internal event types emitted by the model

πŸ§ͺ 7. Validation & Consistency Enforcement

Task Description
Enforce Aggregate Rules No direct access to child entities from outside aggregate root
Ensure Immutability of VOs Prevent mutation after instantiation
Field Validation Rules Embed validation constraints for downstream validator generation
Semantic Duplication Prevention Detect duplicate concept naming across services (via memory)

πŸ“ˆ 8. Emission and Collaboration

Task Description
Emit DomainModelPublished Event Trigger downstream agents with blueprint references
Coordinate with App & Event Agents Expose aggregate behaviors, events, and specifications for orchestration
Support Test Generator Tag testable behaviors, rules, edge cases

βœ… Responsibility Summary

Area Responsibilities
Aggregates βœ… Identity, lifecycle, invariant holders
Entities βœ… Structure, relationships, behaviors
VOs βœ… Embedded immutables with equality
Enums/Specs βœ… Controlled vocabularies, boolean logic
Domain Services βœ… Stateless orchestrators for complex logic
Events βœ… Internal messages emitted by domain behaviors
Outputs βœ… YAML, JSON, DSL, C#, Diagrams
Collaboration βœ… Downstream trigger events, shared contracts

πŸ“₯ Core Inputs

The Domain Modeler Agent synthesizes domain structures from explicit business knowledge, bounded context blueprints, and service responsibilities defined upstream.

These inputs allow it to:

  • Extract ubiquitous terms
  • Identify candidate aggregates
  • Define entities, value objects, and rules
  • Align with use cases, events, and external behaviors

πŸ“‹ Required Inputs

Artifact Source Required
Solution Blueprint Solution Architect Agent βœ…
Bounded Context Definition System or Enterprise Architect Agent βœ…
Service Responsibilities Application Architect Agent βœ…
Ubiquitous Language Glossary (Optional) Ubiquitous Language Agent ⚠️ Strongly recommended
Event Catalog Event-Driven Architect Agent βœ…
API Surface (Input Triggers) API Designer Agent βœ…
NFR/Compliance Tags Solution Blueprint βœ… (for auditability, immutability, and edge modeling)

🧩 Input Field Mapping

🧠 1. Bounded Context Metadata

Field Purpose
bounded_context Defines model boundary for aggregates/entities
core_responsibilities Used to infer domain behavior
service_name Maps to folder/project/namespace prefix

πŸ“˜ 2. Glossary & Language Hints

Field Purpose
term: Invoice Suggests candidate aggregate
term: Money, Address, Email Suggests candidate Value Objects
term: InvoiceCreated, DiscountApplied Suggests domain event names and use case triggers

🧩 3. Use Cases and Commands

Field Purpose
CreateInvoice β†’ Invoice + AddLineItem Determines aggregate + root methods
ApplyDiscount Suggests entity method + value object
SendReminder May involve multiple aggregates or services

πŸ“¦ 4. API Surface and Event Catalog

Field Purpose
POST /invoice Implies new Invoice aggregate root
InvoiceCreatedEvent Triggered inside aggregate lifecycle
PaymentSucceededEvent Consumed event may cause state transition

Field Purpose
immutable_fields: [invoiceTotal] Field must not mutate after creation
auditable: true Domain events must capture before/after states or include causality metadata
data_sensitivity: high May require pseudonymization or masking in test stubs and logs

🧠 Semantic Memory Use (Optional)

Query Match Result
"Invoice" + "ApplyDiscount" Prior Invoice aggregate YAML with ApplyDiscount() method, Discount VO
"Subscription" + "Cancel" Returns matching lifecycle diagram and past domain events (SubscriptionCancelled)
"Money" Returns canonical VO with formatting, currency, arithmetic, and equality rules

πŸ“„ Example Input Template (Simplified YAML)

assignment: "generate-domain-model"
project_id: "connectsoft-saas"
trace_id: "domain-32991"
bounded_context: "Billing"
service: "BillingService"

responsibilities:
  - "Create Invoice"
  - "Apply Discount"
  - "Calculate Tax"
  - "Send Reminder"

glossary:
  - term: Invoice
    type: Aggregate
  - term: InvoiceStatus
    type: Enumeration
  - term: Money
    type: ValueObject

events:
  - InvoiceCreated
  - PaymentSucceeded

βœ… Input Validation Checklist

Input Required
bounded_context, service βœ…
responsibilities βœ…
event_catalog, api_surface βœ…
glossary ⚠️ Optional but improves accuracy
nfr.tags, compliance.hints βœ… if compliance required

πŸ“€ Core Outputs

The Domain Modeler Agent produces a complete, normalized, and clean Domain Model Blueprint that serves as the semantic foundation for all downstream agents.
Its outputs are traceable, testable, and aligned with Domain-Driven Design (DDD) and Clean Architecture.


πŸ“‹ Key Artifacts and Structures

πŸ“˜ 1. domain-model.yaml

Attribute Description
Format YAML (ConnectSoft DSL)
Purpose Centralized DSL representation of all domain structures.
Sections - aggregates: Names, methods, child entities, rules.
- entities: Nested definitions or shared components.
- value_objects: Immutable, by-value domain concepts.
- enumerations: Controlled vocabularies or states.
- specifications: Predicates for decision logic.
- domain_services: Stateless logic helpers.
- domain_events: Event definitions, emitters, payloads.
- validation_rules: Constraints for properties or transitions.

Used by Application Architect, Test Generator, Microservice Generator, and Domain Event agents


🧱 2. .cs Domain Skeletons (optional)

Files Description
- Invoice.cs – aggregate root
- InvoiceLineItem.cs – entity
- Discount.cs, Money.cs – value objects
- InvoiceStatus.cs – enum
- TaxPolicyEvaluator.cs – domain service
- InvoiceCreated.cs – domain event class

Structured for .NET 8 / Clean Architecture with internal, interface, and immutability enforcement


🧩 3. validation-map.yaml

| Format | YAML | | Purpose | Defines invariants and rules per field/entity for test & validator agents |

Invoice:
  Amount:
    - rule: "must be greater than 0"
    - rule: "must equal sum of line items"
  DueDate:
    - rule: "must be after IssueDate"

πŸ“’ 4. domain-events.json

| Format | JSON | | Fields | - event_name
- emitted_by
- triggered_by_method
- payload_fields
- is_externalizable
- trace_id

Used by Event-Driven Architect Agent to decide promotion to integration events


πŸ“Š 5. Domain Diagrams (Mermaid)

| File Types | - entity-hierarchy.mmd
- invoice-lifecycle.mmd
- vo-relationship.mmd

| Example |

stateDiagram-v2
    [*] --> Draft
    Draft --> Issued: Issue()
    Issued --> Paid: RecordPayment()
    Issued --> Cancelled: Cancel()
Hold "Alt" / "Option" to enable pan & zoom


πŸ“¦ 6. Output Metadata

| File | domain-blueprint-metadata.yaml | | Fields | - trace_id, project_id, bounded_context, agent_version
- aggregate_count, vo_count, event_count
- compliance_notes: (e.g., fields_requiring_masking, auditable_events)
- reuse_tags: VO/enums reusable across services


πŸ“¨ 7. Emitted Event: DomainModelPublished

| Format | JSON | | Fields |

{
  "event": "DomainModelPublished",
  "boundedContext": "Billing",
  "projectId": "connectsoft-saas",
  "traceId": "domain-arch-2031",
  "blueprintUrl": "https://.../domain-model.yaml",
  "entityDiagramUrl": "https://.../entity-hierarchy.mmd",
  "timestamp": "2025-05-01T20:08:00Z"
}


βœ… Output Validation Criteria

Rule Description
domain-model.yaml is schema-compliant βœ…
All aggregates have unique root names βœ…
Value objects are immutable and by-value βœ…
Events contain correlation metadata βœ…
At least one entity or aggregate emits a domain event βœ…
Diagrams render and match structure βœ…
Skeletons align with Clean Architecture standards βœ…

πŸ“ˆ Output Summary Table

Output Format Target Agents
Domain Model YAML Application Architect, Code Generator
Class Stubs C# / DSL Microservice Generator
Events Catalog JSON Event Architect, Integration Modeler
Validation Rules YAML Validator + Test Generator
Diagrams Mermaid Human oversight + documentation
Blueprint Event JSON ConnectSoft Agent Bus

πŸ“š Knowledge Base

The Domain Modeler Agent leverages a powerful hybrid knowledge base consisting of:

  • βš™οΈ Tactical DDD modeling patterns
  • πŸ’‘ Reusable value objects, enums, and specifications
  • πŸ” Prior domain models and aggregate designs
  • 🚫 Anti-pattern libraries for avoiding incorrect modeling
  • πŸ“– Ubiquitous language semantic mappings to maintain term consistency

This knowledge base is versioned, traceable, and filterable by bounded context, domain concept, and reuse tags.


🧱 1. Tactical DDD Patterns Repository

Pattern Description
Aggregate Lifecycle Templates Examples of modeling lifecycles using state transitions and invariant guards
Entity Composition Strategies Patterns for composing rich aggregates vs referencing ID-only entities
Value Object Equality Pre-defined IEquatable<T> implementations and immutability templates
Event Emission Within Aggregates Triggering, queuing, and registering domain events from entity state changes
Specifications as Policies Boolean business rule objects modeled as reusable, testable predicates

πŸ“¦ 2. Reusable Domain Elements Library

Type Examples
Value Objects Money, EmailAddress, PhoneNumber, Percentage, Coordinates
Enumerations InvoiceStatus, PaymentMethod, UserRole, SubscriptionTier
Common Specifications HasOverdueBalance, IsWithinGeoFence, IsActiveMember

Each entry is tagged with:

  • reusable: true
  • bounded_context_scope
  • version
  • compliance_sensitive: true/false

πŸ”„ 3. Prior Model Fragments

Retrieved By Used For
"Invoice" + "ApplyDiscount" Match known aggregate structure, reuse VO patterns
"Subscription" + "Cancel" Retrieve state machine + event cascade pattern
"Customer + create" Suggest base aggregate structure with validation, creation event, and status enum

Frags are vectorized and stored using Azure Cognitive Search, Pinecone, or equivalent.


πŸ“• 4. Glossary-to-Model Mapping Memory

Term Mapped Output
Invoice Aggregate with AddLineItem, ApplyDiscount, Issue() methods
Discount Value object with Percentage, Reason, and AppliesTo
SubscriptionStatus Enum + lifecycle transitions
TaxPolicyEvaluator Domain service used by Invoice.CalculateTax()

Also used to normalize naming across agents and avoid duplication.


🚫 5. Anti-Pattern Prevention Rules

Anti-Pattern Rejection Reason
Mutable value objects Break equality and validation guarantees
β€œFat enums” with logic Violates SRP β€” should use Specification
Overloaded aggregates with unrelated responsibilities Breaks cohesion β€” split into multiple aggregates
Domain event with raw DTO as payload Violates domain encapsulation and forward compatibility
Repositories returning IQueryable Breaks encapsulation and allows query leakage

If any are detected, a warning or auto-correction will trigger via DomainValidationSkill.


🧠 Semantic Memory Retrieval Examples

Query Memory Match
Money + Amount Money VO with currency code, decimal amount, math ops, equality contract
CreateInvoice Invoice aggregate skeleton with line item collection, status enum, domain event
Email + confirmation EmailAddress VO + EmailConfirmed domain event
TimeZone TimeZoneOffset VO or ZonedDateTime VO pattern with NodaTime-like behavior

πŸ“œ Governance and Reuse Rules

Rule Enforcement
Reused pattern must have pattern_version: approved βœ…
Reuse must emit source trace (origin_trace_id, reuse_confidence) βœ…
Compliance-tagged fields (e.g., SSN) must be masked in test stubs βœ…
Domain event reuse allowed only if payload_version: compatible βœ…

πŸ“ˆ Memory Integration Diagram

flowchart TD
    A[Start Modeling] --> B[Query Semantic Memory]
    B --> C[Get Patterns, Reusable VOs, Enums]
    C --> D[Inject into Model Draft]
    D --> E[Log Source Trace + Confidence Score]
Hold "Alt" / "Option" to enable pan & zoom

πŸ”„ Execution Flow

The Domain Modeler Agent follows a modular, validated, and memory-augmented pipeline
to convert bounded context definitions, ubiquitous language, and use case triggers into a rich, DDD-aligned Domain Model Blueprint.

Each step is powered by a specific skill, validated independently, and emits observability data for traceability.


πŸ“‹ Execution Phases

Phase Description

1️⃣ Input Validation & Semantic Memory Retrieval

  • Validate presence of:
    • bounded_context
    • service_responsibilities
    • glossary, event_catalog
  • Retrieve matching domain models, reusable VOs, enums from vector memory
  • Match glossary terms to model elements (aggregate, VO, event)

2️⃣ Aggregate Root Identification

  • Analyze service responsibilities and triggers
  • Group related behaviors under potential root entities (e.g., Invoice, Customer)
  • Detect composition needs: child entities, collections, VO dependencies

3️⃣ Entity and Value Object Modeling

  • Define entity properties, identities, and relationships
  • Generate value objects for immutable concepts (Money, DateRange, EmailAddress)
  • Apply equality contracts and immutability hints

4️⃣ Enumeration and Specification Design

  • Infer enums from field types and business states (InvoiceStatus, RiskLevel)
  • Model common validation/filtering rules as specifications (IsEligibleForUpgrade)
  • Suggest cross-context reuse of well-known enums/specs

5️⃣ Domain Service & Policy Extraction

  • Detect stateless logic or multi-aggregate operations
  • Define interfaces for rule engines, pricing calculators, eligibility checks
  • Annotate compliance-critical logic

6️⃣ Domain Event Inference

  • Identify behaviors that transition state or trigger workflows
  • Emit internal events tied to methods (e.g., IssueInvoice β†’ InvoiceIssued)
  • Annotate with payload fields, correlation hints, is_externalizable flag

7️⃣ Validation & Invariant Mapping

  • Apply validation rules:
    • Required fields
    • Type constraints
    • Temporal or business logic conditions
  • Emit validation-map.yaml for use by validator and test agents

8️⃣ Artifact Assembly & Emission

  • Compose:
    • domain-model.yaml
    • .cs skeletons (optional)
    • domain-events.json
    • Mermaid diagrams (entity-hierarchy.mmd, state-machine.mmd)
    • domain-blueprint-metadata.yaml
  • Emit DomainModelPublished event with artifact links and trace info

πŸ“ˆ Observability Emissions

Telemetry Example
aggregate_discovery_count 3
value_object_reuse_count 5
validation_rule_count 12
semantic_memory_reuse_confidence_avg 0.87
output_schema_validation_status pass

πŸ” Retry/Correction Paths

Phase Error Action
VO modeling Mutable VO detected Regenerate with immutability rule
Event design Payload missing Retry with fallback contract template
Enum overlap Conflict in glossary Trigger namespace prefixing
Invalid YAML Structure mismatch Run SchemaFixerSkill with auto-patch hints

🧠 Process Flow Diagram

flowchart TD
    A[Validate Inputs] --> B[Retrieve Glossary & Memory]
    B --> C[Identify Aggregates]
    C --> D[Model Entities + VOs]
    D --> E[Define Enums + Specs]
    E --> F[Create Domain Services + Policies]
    F --> G[Emit Domain Events]
    G --> H[Validate Rules + Invariants]
    H --> I[Assemble Artifacts]
    I --> J[Emit DomainModelPublished Event]
Hold "Alt" / "Option" to enable pan & zoom

πŸ› οΈ Core Skills and Kernel Functions

The Domain Modeler Agent operates through a well-structured set of Semantic Kernel skills, each responsible for a single modeling responsibility.

These skills are:

  • πŸ” Retryable β€” Each skill can be retriggered individually if its output is invalid or incomplete
  • πŸ“ Schema-bound β€” Outputs must conform to domain-modeling schemas and validators
  • πŸ“‘ Observable β€” All executions are traceable via OpenTelemetry with metadata and telemetry spans

πŸ“‹ Key Skills Overview

Skill Name Responsibility

πŸ“₯ Input & Memory Skills

| InputValidatorSkill | Confirms required input artifacts and metadata (bounded_context, service, trace_id) | | SemanticMemoryRetrieverSkill | Retrieves reusable value objects, enums, specs, and prior aggregate structures | | GlossaryMapperSkill | Maps business terms to modeling primitives (e.g., β€œInvoice” β†’ Aggregate) |


🧱 Aggregate & Entity Modeling

| AggregateBuilderSkill | Discovers candidate aggregates, models lifecycles, and assigns commands | | EntityComposerSkill | Builds entity structures, fields, relationships, and versioning metadata | | LifecycleStatePlannerSkill | Models aggregate state transitions using methods and state machines |


πŸ“¦ Value Object & Enumeration Design

| ValueObjectGeneratorSkill | Produces immutable, by-value domain concept classes (e.g., Money, TaxCode) | | EnumerationModelerSkill | Structures enums with state mappings, usage hints, and validation rules | | SpecificationCreatorSkill | Builds Boolean logic filters as reusable predicates (e.g., IsOverdue) |


πŸ” Domain Services & Policy Skills

| DomainServiceExtractorSkill | Identifies externalized stateless business logic (e.g., DiscountEvaluator) | | PolicyAnnotatorSkill | Tags compliance-sensitive or rule-based operations for auditing or review |


πŸ“’ Event Emission & Rule Mapping

| DomainEventEmitterSkill | Attaches events to methods (ApplyDiscount β†’ DiscountAppliedEvent) and defines payloads | | ValidationRuleBuilderSkill | Extracts field rules and invariant mappings (DueDate must be β‰₯ IssueDate) |


πŸ“€ Output Assembly & Emission

| DomainArtifactAssemblerSkill | Compiles YAML/JSON spec files and emits final artifacts | | MermaidDiagramEmitterSkill | Generates class diagrams, lifecycle state machines, and VO/entity relationship graphs | | BlueprintEventEmitterSkill | Emits DomainModelPublished with trace metadata and artifact URLs |


🧠 Skill Chaining and Dependencies

flowchart TD
    InputValidator --> GlossaryMapper
    GlossaryMapper --> SemanticMemoryRetriever
    SemanticMemoryRetriever --> AggregateBuilder
    AggregateBuilder --> EntityComposer
    EntityComposer --> ValueObjectGenerator
    ValueObjectGenerator --> DomainEventEmitter
    DomainEventEmitter --> ValidationRuleBuilder
    ValidationRuleBuilder --> DomainArtifactAssembler
    DomainArtifactAssembler --> BlueprintEventEmitter
Hold "Alt" / "Option" to enable pan & zoom

πŸ” Retry Path Hooks

Skill Retry Trigger
ValueObjectGeneratorSkill VO missing immutability or equality contract
DomainEventEmitterSkill Event lacks required field or cannot link to method
SpecificationCreatorSkill Output fails predicate validation test
EnumerationModelerSkill Duplicate enum values or missing mapping

Each retry emits:

  • skill_name
  • retry_attempt
  • trace_id
  • outcome: success | failed

🧠 Skill Design Principles

Principle Description
Single Responsibility Each skill models only one construct (e.g., entity, VO, enum)
Schema-Driven Outputs validated against ConnectSoft domain-modeling schemas
Composable Skills can be run sequentially or independently (supports partial modeling)
Traceable Execution spans, input parameters, and retries are all logged

πŸ› οΈ Core Technologies and Tools

The Domain Modeler Agent is powered by a modular, schema-governed, memory-augmented toolchain tailored for Domain-Driven Design (DDD), Clean Architecture, and ConnectSoft’s automation ecosystem.

The stack supports:

  • Structured domain modeling in YAML and C#
  • AI-assisted reasoning and prompt orchestration
  • Semantic memory retrieval and validation
  • Diagram generation and event emission
  • End-to-end traceability and governance

πŸ“‹ Core Technologies and Roles

🧠 1. Semantic Reasoning and Orchestration

Component Role
Semantic Kernel (.NET) Orchestrates skill composition and memory access
Azure OpenAI (GPT-4) Powers naming, heuristics, pattern matching, and fallback generation
ConnectSoft SkillPack: DomainModeling Plug-and-play skill modules for aggregates, VOs, enums, events

πŸ“„ 2. Domain Modeling Language & Output

Component Role
ConnectSoft DSL (YAML-based) Used for domain model declaration (aggregates, VOs, events)
.cs code skeleton templates Optional class/interface outputs for C#-based domain layers
Domain Modeling Schema Validator Ensures generated YAML and JSON files conform to ConnectSoft’s structure contracts

πŸ“ˆ 3. Observability & Tracing

Component Role
OpenTelemetry SDK (.NET) Emits spans, durations, retry counts, and skill traces
Azure Application Insights Stores telemetry logs and metrics for review
ConnectSoft Dashboard Visual UI for aggregate count, reuse index, validation status, and diagram links

πŸ” 4. Memory, Reuse, and Governance

Component Role
Pinecone / Azure Cognitive Search Stores reusable pattern embeddings (VOs, Enums, Domain Events)
Semantic Retrieval API Enables context-aware model suggestion based on bounded context + term +
behavior
Governance Engine Prevents use of blacklisted anti-patterns (e.g., mutable VOs, anemic aggregates)

πŸ“Š 5. Diagram Generation

Tool Output
Mermaid.js Generator
- entity-hierarchy.mmd
- aggregate-lifecycle.mmd
- vo-relationship.mmd
PlantUML (optional) Alternative to Mermaid for enterprise-level integration
ConnectSoft Diagram Validator Ensures renderability and completeness of diagrams emitted

πŸ§ͺ 6. Testing, Validation, and Compliance Integration

Component Role
ValidationMapEmitterSkill + YAML Outputs invariant maps used by Test Generator and Validation Agent
Compliance Tagger Annotates fields (e.g., PII, financial data) with security and governance hints
Immutable Structure Validator Prevents value object mutation and enforces by-value equality patterns

πŸ“‘ 7. Artifact Publishing and Emission

Component Role
Artifact Storage API Saves all blueprint artifacts (YAML, JSON, C#, diagrams) with versioning
ConnectSoft Event Bus (Azure Event Grid) Emits DomainModelPublished for downstream agents
Schema Registry Validates event payloads and domain model contracts

βœ… Stack Alignment to ConnectSoft Principles

Principle Supported by
🧱 DDD First YAML DSL, reusable modeling primitives
πŸ§ͺ Test-First Invariant map + specification structure
πŸ“ Clean Architecture Aggregate-centric model with strict layering
πŸ” Reuse Memory + versioned contract store
🧩 Modularity Skill composition, diagram separation, output layering
πŸ“‘ Observability Full OpenTelemetry instrumentation
πŸ›‘οΈ Governance Schema validation, anti-pattern prevention, audit tagging

πŸ“¦ Output Format Matrix

Output Type Format
Domain Blueprint domain-model.yaml
Class Templates .cs
Domain Events .json
Validation Rules validation-map.yaml
Diagrams .mmd (Mermaid)
Event DomainModelPublished (JSON)

πŸ“œ System Prompt (Bootstrapping Instruction)

The System Prompt defines the intent, responsibilities, and constraints of the Domain Modeler Agent.
It ensures every modeling session aligns with ConnectSoft’s principles of DDD, Clean Architecture, governance, and agent interoperability.

This prompt is invoked at agent startup and serves as the operational contract for autonomous domain generation.


βœ… Full Prompt Definition (YAML + Natural Language)

You are the **Domain Modeler Agent** of the ConnectSoft AI Software Factory.

Your responsibility is to generate a complete, consistent, and reusable **domain model blueprint**  
for a single service within a bounded context.

You must analyze the service’s responsibilities, glossary, event triggers, and known use cases  
to model its **aggregates, entities, value objects, enums, specifications, domain services, and events**.

---

## You must:

1. Validate that all required inputs are available:
   - Bounded Context metadata
   - Service name and responsibilities
   - Glossary or Ubiquitous Language definitions (optional but preferred)
   - Event catalog
   - API input triggers (for behavior inference)

2. Discover one or more **aggregate roots** based on behavioral clustering and lifecycle scope.

3. For each aggregate, model:
   - Entities and relationships
   - State transitions and invariants
   - Lifecycle behaviors and validations

4. Define:
   - Value Objects (immutable, by-value)
   - Enumerations (finite sets of known variants)
   - Specifications (Boolean business rules)
   - Domain Services (stateless logic orchestrators)

5. Emit **internal domain events** that reflect state transitions, business workflows, or triggers.

6. Produce the following output artifacts:
   - `domain-model.yaml` (main DSL model)
   - `*.cs` skeletons (optional class templates)
   - `validation-map.yaml` (invariant rules)
   - `domain-events.json` (event definitions)
   - Mermaid diagrams (state machines, class maps)
   - Metadata file with counts, version, compliance hints

7. Ensure:
   - No infrastructure or application logic leaks into the domain layer
   - No mutable value objects
   - All events are traceable to specific behaviors
   - Output conforms to ConnectSoft schemas

8. Emit a `DomainModelPublished` event with links to all artifacts.

---

## Output Constraints

- Value Objects must be **immutable** and **implement equality by value**
- Aggregates must **enforce invariants** through methods, not passive properties
- Domain Events must **contain correlation metadata** and structured payloads
- Enumerations must be **closed sets** β€” no unbounded expansion

---

## Output Format Expectations

- YAML-based DSL (`domain-model.yaml`)
- Optional C# skeletons (for `.NET 8`)
- Mermaid diagrams for human and governance review
- All outputs include: `trace_id`, `project_id`, `bounded_context`, `agent_version`

---

## Observability Requirements

- Emit OpenTelemetry spans per skill execution
- Log reuse from memory (`pattern_source`, `confidence_score`)
- Track retry attempts, validation outcomes, and diagram compilation

---

## Success Criteria

βœ… Clean, layered domain structure  
βœ… Artifacts validatable and downstream-consumable  
βœ… Events, VOs, specs reusable and versioned  
βœ… Fully traceable and observable execution  
βœ… Zero anti-patterns detected (mutable VO, anemic domain, rule leakage)

πŸ” Prompt Governance Guarantees

Rule Enforced
Schema validation of all artifacts βœ…
Memory reuse traced and versioned βœ…
Output tagged with trace metadata βœ…
Retry or failure triggers event escalation βœ…

πŸ“ˆ Example Initialization Context

"You are modeling the domain for BillingService in the Billing bounded context.
You received 4 responsibilities (CreateInvoice, ApplyDiscount, SendReminder, IssueInvoice)
and a glossary with Invoice, Discount, and Money.
Event triggers include InvoiceCreated, PaymentSucceeded.
Your goal is to emit a fully validated domain-model package, with diagrams, validation rules, and C# stubs."


πŸ“₯ Input Prompt Template

The Domain Modeler Agent receives a structured prompt containing all the data necessary to synthesize a rich, bounded, and validated domain model.

This prompt is generated by upstream agents (e.g., Solution Architect, Ubiquitous Language Agent, Application Architect) or manually by a domain expert.


βœ… Prompt Format (YAML)

assignment: "generate-domain-model"

project:
  project_id: "connectsoft-saas-2025"
  trace_id: "domain-billing-9832"
  bounded_context: "Billing"
  service_name: "BillingService"
  agent_version: "1.1.0"

inputs:
  glossary_url: "https://artifacts.connectsoft.dev/glossary/billing.yaml"
  responsibilities_url: "https://artifacts.connectsoft.dev/services/billing/responsibilities.yaml"
  api_surface_url: "https://artifacts.connectsoft.dev/apis/billing-api.yaml"
  event_catalog_url: "https://artifacts.connectsoft.dev/events/billing-events.json"
  nfr_url: "https://artifacts.connectsoft.dev/nfrs/billing-nfr.yaml"

settings:
  output_format: [yaml, json, cs, mermaid]
  language: "csharp"
  generate_diagrams: true
  include_class_stubs: true
  reuse_patterns: true

🧩 Field Breakdown

πŸ”· assignment

Always set to "generate-domain-model"


πŸ”· project metadata

Field Description
project_id Unique solution reference
trace_id Full traceability for spans, events, storage
bounded_context Bounded domain scope
service_name Maps output to the owning microservice
agent_version Tracks which version of the agent produced the outputs

πŸ”· inputs

Artifact Purpose
glossary_url Terminology-to-model mapping
responsibilities_url Use case clustering for aggregates
api_surface_url Behavior inference (commands/queries)
event_catalog_url Event-driven transition discovery
nfr_url Edge constraints (immutability, auditing, sensitivity)

πŸ”· settings

Field Description
output_format Accepted: yaml, json, cs, mermaid, markdown
language Used to structure .cs class generation or future Kotlin/F#
generate_diagrams Whether Mermaid state and hierarchy diagrams are included
include_class_stubs Whether .cs domain types are emitted
reuse_patterns If enabled, agent queries memory for reusable VOs, Enums, etc.

🧠 Example Prompt (Minimal)

assignment: generate-domain-model
project:
  project_id: connectsoft-payments
  trace_id: domain-4314
  bounded_context: Payments
  service_name: PaymentService

inputs:
  glossary_url: https://.../glossary.yaml
  responsibilities_url: https://.../payments-responsibilities.yaml
  api_surface_url: https://.../payments-api.yaml
  event_catalog_url: https://.../events.json

πŸ§ͺ Validation Rules (Input Layer)

Rule Enforcement
bounded_context, service_name, trace_id required βœ…
At least one of glossary, responsibilities, or event_catalog must be provided βœ…
If generate_diagrams = true, ensure diagram rendering engine is enabled βœ…
URLs must be accessible, schema-validated, and signed or trusted βœ…

πŸ” Interoperability Notes

  • Input prompt aligns with MKDocs trace metadata, allowing documentation linking
  • Downstream agents (Test Generator, App Architect) subscribe to outputs via DomainModelPublished event
  • Settings flags map to output content and verbosity, controlling downstream load

πŸ“€ Output Expectations

The Domain Modeler Agent produces a suite of structured, traceable, and reusable artifacts that define the semantic core of a microservice.

Outputs are designed for autonomous consumption by downstream agents (Application Architect, Test Generator, Microservice Generator), as well as for developer onboarding, validation, and documentation.

All artifacts must conform to ConnectSoft DDD schema specifications, be versioned, and include traceability metadata.


πŸ“˜ 1. domain-model.yaml (Primary Blueprint)

| Format | YAML (ConnectSoft DSL) | | Sections | - aggregates: names, methods, child entities, rules
- entities: nested definitions or shared components
- value_objects: immutable, by-value concepts
- enumerations: enums with values and usage hints
- domain_services: stateless logic helpers
- specifications: predicates for decision logic
- domain_events: event definitions, emitters, payloads
- validation_rules: constraints for properties or transitions

βœ… Must pass ConnectSoft Domain Model Schema Validator


🧱 2. Class Skeletons (.cs)

| Format | C# (.NET 8 clean architecture convention) | | Emitted Files | - Invoice.cs, InvoiceLineItem.cs
- Money.cs, TaxCode.cs
- InvoiceStatus.cs, PaymentMethod.cs
- TaxPolicyEvaluator.cs, EligibilitySpecification.cs
- InvoiceCreatedEvent.cs, PaymentAppliedEvent.cs

βœ… Optional based on include_class_stubs flag
βœ… Stub methods use TODO markers and type annotations


πŸ“Š 3. validation-map.yaml

| Format | YAML | | Purpose | Captures invariants and validation logic for all domain elements |

Invoice:
  TotalAmount:
    - rule: must be greater than 0
    - rule: must equal sum of line items
  DueDate:
    - rule: must be after IssueDate

βœ… Used by Validation Agent and Test Generator to scaffold contract tests


πŸ“’ 4. domain-events.json

| Format | JSON | | Fields | - event_name
- emitted_by_method
- aggregate
- payload_schema
- correlation_fields
- is_externalizable
- trace_id, bounded_context, event_version

βœ… Must validate against ConnectSoft.EventContractSchema


πŸ“ 5. Diagrams (*.mmd Mermaid Files)

| Files | - entity-hierarchy.mmd β€” shows relationships
- aggregate-lifecycle.mmd β€” state transitions
- vo-map.mmd β€” dependencies and reuse

βœ… Must render successfully and link to entity names declared in the YAML model


πŸ“¦ 6. domain-blueprint-metadata.yaml

| Purpose | Metadata bundle for observability and trace lineage | | Fields | - trace_id, project_id, agent_version
- aggregate_count, vo_count, event_count, spec_count
- governance_warnings: anti-patterns corrected or flagged
- reused_elements: from prior blueprints (VOs, Enums, Specs)


πŸ“¨ 7. Emitted Event: DomainModelPublished

| Format | JSON | | Sample |

{
  "event": "DomainModelPublished",
  "boundedContext": "Billing",
  "service": "BillingService",
  "projectId": "connectsoft-saas",
  "traceId": "domain-xyz-4812",
  "modelUrl": "https://.../domain-model.yaml",
  "eventsUrl": "https://.../domain-events.json",
  "metadataUrl": "https://.../domain-blueprint-metadata.yaml",
  "timestamp": "2025-05-01T20:30:00Z"
}

βœ… This event is required for downstream orchestration to begin


πŸ“ˆ Output Validation Rules

Rule Description
All YAML/JSON files must pass schema validation βœ…
All diagrams must compile successfully βœ…
At least one aggregate must be present βœ…
All emitted domain events must link to emitting methods βœ…
All VOs must declare equality + immutability flags βœ…
Output traceability metadata required in all files βœ…

πŸ“Š Output Summary Table

Output Format Used By
Domain Model Blueprint domain-model.yaml App Architect, Generator, Validator
Class Skeletons .cs Microservice Generator
Validation Map validation-map.yaml Validator, Test Generator
Domain Events .json Event Architect, Messaging Layer
Diagrams .mmd Docs, Governance UI
Metadata .yaml Dashboards, Audits
Event DomainModelPublished All subscribers in Agent Bus

🧠 Memory Strategy Overview

The Domain Modeler Agent uses a hybrid memory model to ensure consistency, reuse, correctness, and learning over time.
It supports:

  • πŸ” Reusing proven VOs, enums, and event patterns
  • 🧠 Contextual adaptation from prior services
  • 🚫 Avoidance of anti-patterns
  • πŸ” Traceable reuse with governance validation

🧠 Short-Term Memory (Session-Scoped)

Memory Area Description
Aggregate Discovery Log Tracks which aggregates were inferred from which responsibilities or glossary terms
VO Generation Cache Temporary map of VOs created, reused, or restructured within the current service
Entity Relationship Tree In-memory graph of entity β†’ child relationships and embedding VOs
Retry Journal Stores corrections applied after skill validation errors (e.g., VO mutation fix)

Used to assemble coherent output, handle dependency resolution, and enable incremental retries.


πŸ—ƒοΈ Long-Term Memory (Semantic Memory)

Stored in vector embeddings and governed via reuse metadata, this memory allows the agent to bootstrap modeling using prior patterns.

πŸ“¦ 1. Reusable Value Objects

Example Metadata Tags
Money immutable: true, used_by: [Invoice, Subscription], currency_aware: true
Address supports_validation: true, type: billing | shipping, used_by: Customer
TaxCode has_enum_constraint: true, compliance_tag: finance.tax

🧩 2. Enums and Specifications

Memory Example Use
InvoiceStatus Suggests enum values (Draft, Issued, Paid, Cancelled) with transitions
HasOverdueBalance Boolean rule specification based on DueDate < Today and Outstanding > 0

πŸ” 3. Prior Aggregates

Query Result
"Subscription" + "Cancel" Returns reusable Subscription.cs structure with Cancel(), Resume(), and Status enum
"Customer + Onboarding" Suggests entity graph for Customer, Profile, Account

πŸ“’ 4. Domain Event Catalog

Query Response
"InvoiceCreated" Returns structured event with known payload, emitting method (Issue()), and event version
"PaymentApplied" Matches event for ApplyPayment() in Invoice aggregate
"DiscountApplied" Matches to event and VO Discount with known structure (percentage, appliesTo)

🧱 5. Reuse Confidence and Governance Filtering

Each memory hit includes:

  • pattern_source_trace_id
  • pattern_confidence_score (0.0–1.0)
  • governance_verified: true/false
  • last_used_by: service_name / agent_version

⚠️ Only patterns with governance_verified: true and confidence β‰₯ 0.80 are reused autonomously.


πŸ” Memory Retrieval Workflow

flowchart TD
    A[Start Session] --> B[Glossary + Term Analysis]
    B --> C[Query Semantic Memory]
    C --> D[Match Aggregates, VOs, Enums, Events]
    D --> E[Inject into Current Model]
    E --> F[Log Pattern Use with Confidence Score + Trace ID]
Hold "Alt" / "Option" to enable pan & zoom

πŸ§ͺ Anti-Pattern Filtering

The agent maintains an internal blacklist (also retrieved from governance memory) of dangerous patterns:

Anti-Pattern Example
❌ Mutable value objects Money.Amount += x
❌ Overloaded aggregate root Customer managing Subscription, Invoice, BillingMethod
❌ Enum with unknown variant fallback Status = -1 β†’ Unknown
❌ Domain event that wraps external DTO UserCreatedEvent { RawUserDto }

These are blocked or automatically corrected during generation.


πŸ› οΈ Feedback to Memory

When a reused VO or Enum is included in final output, the agent emits a reuse confirmation span, including:

  • pattern_id, used_in_project, agent_version, confidence_score, usage_success: true/false

This feedback loop supports memory pruning, pattern promotion, and self-governing reuse.


βœ… Benefits of Memory-Driven Modeling

Capability Benefit
Semantic Reuse Reduces modeling effort, increases consistency
Pattern Learning Improves over time with real-world usage
Governance Control Prevents reuse of deprecated or invalid structures
Traceability Every reused structure is linkable and explainable
Cross-Agent Coherence Shared modeling elements across services (e.g., Money, Status enums)

βœ… Validation and Correction Framework

The Domain Modeler Agent applies a multi-phase validation pipeline to ensure:

  • Schema conformance of all artifacts
  • DDD best practices are respected (e.g., VO immutability, aggregate boundaries)
  • Model completeness and correctness
  • Prevention of architectural anti-patterns

When errors are detected, the agent triggers skill-specific retries, fallback logic, or flags items for manual escalation.


πŸ“‹ Validation Phases

1️⃣ Input Validation

| Checks | - Are bounded_context, service_name, and trace_id present?
- Are responsibilities, glossary, or triggers included?
- Are URLs resolvable and accessible?
- Are glossary terms mappable?

❌ If failed: Retry with InputValidatorSkill; escalate if unresolved.


2️⃣ Structural Model Validation

Artifact Rules Enforced
domain-model.yaml Must match schema, include β‰₯1 aggregate, reference trace_id
Aggregates Must expose at least one behavior (method)
Entities Must have unique identity and no orphan status
VOs Must be immutable and implement equality
Events Must include emitted_by, payload, correlation_id
Enums Must define β‰₯2 values, no duplicates

❌ If failed: Retry appropriate modeling skill (e.g., AggregateBuilderSkill, ValueObjectGeneratorSkill)


3️⃣ Dependency Graph Validation

| Checks | - Are entity β†’ VO β†’ enum relationships consistent?
- Are cyclic relationships avoided?
- Are aggregates not overloaded with unrelated behavior?
- Do child entities exist only within a single aggregate root?

❌ If failed: Execute correction skill or emit warning via GovernanceValidationSkill


4️⃣ Invariant & Rule Validation

Artifact Rules
validation-map.yaml Must include β‰₯1 rule per aggregate
Constraint syntax must match supported DSL (must be > 0, must be after date)
Events tied to method transitions must emit at valid state points

❌ If failed: Retry with ValidationRuleBuilderSkill


5️⃣ Reuse & Memory Validation

Rule Enforced
Memory items must have governance_verified: true βœ…
Reused fragments must embed source_trace_id, reuse_score β‰₯ 0.80 βœ…
Reused VOs/specs must be compatible with current aggregate version βœ…

❌ If failed: Skip reuse or fallback to internal DSL fragment


πŸ” Retry and Correction Logic

Phase Retry Skill
VO mutation detected ValueObjectGeneratorSkill (force readonly, With(...) method pattern)
Enum overlap or conflict EnumerationModelerSkill (prefix or split strategy)
Event missing correlation fields DomainEventEmitterSkill (inject TraceId, EntityId)
Validation syntax issue ValidationRuleBuilderSkill (patch malformed constraint)

Each retry emits:

  • retry_type
  • skill_name
  • attempt_number
  • resolved: true/false
  • trace_id

πŸ“ˆ Observability Outputs (Validation Phase)

Metric Description
domain_validation_passed True if all phases succeeded
retry_count_by_skill Aggregate count of retries per skill
schema_validation_status Pass/fail per artifact
anti_pattern_blocked_count Detected and auto-corrected design flaws
output_structure_score % of model components with required metadata and correctness

πŸ” Example Validation Trace (Event)

{
  "trace_id": "domain-8741",
  "agent": "DomainModeler",
  "skill": "ValueObjectGeneratorSkill",
  "retry": true,
  "reason": "VO is mutable",
  "correction_applied": "added 'readonly' to all fields",
  "resolved": true
}

🧠 Escalation Triggers (Manual Review Required)

Condition Action
Unable to infer any aggregates Flag for Solution Architect Agent
Event contract fails schema 2+ times Emit DomainModelValidationFailed
Non-resolvable ambiguity in glossary term Emit ManualGlossaryMappingRequired
Large retry loop (>3 cycles) on VO conflict Escalate to Platform Governance Officer

🀝 Collaboration Interfaces

The Domain Modeler Agent plays a central role in the ConnectSoft AI Software Factory’s agentic design chain, providing the semantic contract for all services.

It collaborates upstream with architect agents for context and business vocabulary, and downstream with implementation and runtime agents for scaffolding, testing, and orchestration.


πŸ“‘ Upstream Collaboration

Upstream Agent Interface
Solution Architect Agent
- Input: solution-blueprint.md
- Provides: service responsibilities, bounded context, trace metadata

| Ubiquitous Language Agent |
- Input: glossary.yaml
- Provides: business terms mapped to domain elements (Aggregate, VO, Event, etc.) |

| API Designer Agent |
- Input: api-surface.yaml
- Provides: inferred use cases and domain commands from REST/gRPC structure |

| Event-Driven Architect Agent |
- Input: event-catalog.json
- Provides: behavior triggers and emitted events used in domain method mapping |


πŸ“¦ Downstream Collaboration

Downstream Agent Consumes

🧱 Application Architect Agent

  • domain-model.yaml
  • validation-map.yaml
  • domain-events.json

    Uses: entity structures, aggregate logic, port boundaries, method-to-event mapping


πŸ§ͺ Test Generator Agent

  • validation-map.yaml
  • domain-model.yaml
  • *.cs skeletons

    Uses: aggregate rules, VO structure, event emission, lifecycle validation


πŸ—οΈ Microservice Generator Agent

  • *.cs domain skeletons
  • domain-model.yaml

    Uses: pre-scaffolded aggregates/entities for code generation


πŸ“’ Event-Driven Architect Agent

  • domain-events.json
  • aggregate.event_emissions[]

    Uses: internal events as candidates for promotion to integration events


πŸ“¨ Emitted Event: DomainModelPublished

| Format | JSON | | Triggers |
- Microservice Generation
- Test Generation
- Application Architecture
- Diagram Rendering
- Compliance Checks

{
  "event": "DomainModelPublished",
  "service": "BillingService",
  "boundedContext": "Billing",
  "projectId": "connectsoft-saas",
  "traceId": "domain-arch-0923",
  "blueprintUrl": "https://.../domain-model.yaml",
  "timestamp": "2025-05-01T20:45:00Z"
}

πŸ” Orchestration Flow Diagram

flowchart TD
    SolutionArchitect --> DomainModeler
    UbiquitousLanguage --> DomainModeler
    APIDesigner --> DomainModeler
    EventDrivenArchitect --> DomainModeler

    DomainModeler --> ApplicationArchitect
    DomainModeler --> TestGenerator
    DomainModeler --> MicroserviceGenerator
    DomainModeler --> EventDrivenArchitect
Hold "Alt" / "Option" to enable pan & zoom

πŸ“¦ Shared Artifact APIs

API Role
Artifact Storage API Stores all outputs (domain-model.yaml, diagrams, stubs) with version tags
ConnectSoft Event Bus Transmits blueprint lifecycle events (DomainModelPublished)
Schema Registry Validates YAML/JSON outputs and event payloads
Glossary Mapping API Allows terms from glossary to be resolved dynamically or flagged for ambiguity

πŸ“‘ Metadata Tracing Standards

All emitted artifacts and events must include:

  • trace_id, project_id, bounded_context, service_name, agent_version
  • pattern_reuse (if applicable)
  • governance_score and validation_status for downstream dashboards

πŸ“‘ Observability Hooks

The Domain Modeler Agent is fully instrumented using OpenTelemetry to provide deep traceability and runtime diagnostics.
It emits metrics, spans, and structured logs at each stage of the modeling pipeline.


πŸ“ˆ Telemetry Emissions

Metric Description
domain_modeling_duration_ms Total time taken for the modeling session
aggregate_discovery_count Number of aggregates modeled
vo_reuse_count Number of value objects reused from semantic memory
event_emission_total Number of domain events defined
validation_passed Boolean outcome of final artifact validation
retry_count_by_skill{name} Retries triggered per skill
anti_pattern_blocked_count Violations caught and corrected automatically

All telemetry entries are tagged with:
trace_id, project_id, bounded_context, agent_version, skill_name


πŸ“Š Observability Dashboards

Dashboard Purpose
Domain Blueprint Overview Aggregates, entities, VOs, events, complexity map
Retry Heatmap Frequency and type of retries per skill
Semantic Reuse Index Memory-driven design effectiveness
Governance Compliance Panel Scorecards for anti-patterns, completeness, trace metadata

🧍 Human Oversight Hooks

Although autonomous, the Domain Modeler Agent includes manual intervention safeguards:

Trigger Action
❗ No aggregates discovered Escalate to Solution Architect Agent
❗ Conflicting glossary mappings Emit ManualGlossaryResolutionRequired
❗ VO reusability score < threshold Skip reuse, emit warning
❗ Structural schema validation fails > 1 retry Emit DomainModelValidationFailed

All escalations are visible in ConnectSoft governance dashboards with supporting telemetry.


🧾 Compliance and Traceability

Enforced
Output traceability in all artifacts (trace_id, agent_version, reuse source)
Compliance hints in metadata for sensitive fields or audit-required events
Immutable artifact publishing with artifact hash and schema version

βœ… Conclusion

The Domain Modeler Agent defines the semantic and structural foundation of every ConnectSoft microservice.
It guarantees that services are not just operational, but meaningful, cohesive, and correctly bounded.


πŸ”‘ Strategic Outcomes

βœ… DDD-aligned, clean, reusable models
βœ… Agent-to-agent interoperability via YAML/JSON
βœ… Test and code generation readiness
βœ… Traceability for every modeling decision
βœ… Platform-wide domain consistency
βœ… Governance-ready and audit-proof


πŸ“¦ Final Artifact Summary

Artifact Format
domain-model.yaml YAML
domain-events.json JSON
.cs skeletons (optional) C#
validation-map.yaml YAML
Diagrams (*.mmd) Mermaid
Metadata (domain-blueprint-metadata.yaml) YAML
Emitted Event (DomainModelPublished) JSON