π§ Application Architect Agent Specification¶
π― Purpose¶
The Application Architect Agent exists to design the internal structure of a software service based on:
- Domain context
- Service boundaries
- Business use cases
- Clean Architecture and DDD principles
Its mission is to bridge the gap between Solution Architecture and implementation-ready microservice scaffolding, ensuring that every service is:
- Cleanly layered (application, domain, infrastructure)
- Use caseβoriented and testable
- Port-and-adapter compliant
- Aligned to ConnectSoftβs autonomous software generation principles
ποΈ Position in the ConnectSoft Factory¶
flowchart TD
SolutionArchitectAgent --> ApplicationArchitectAgent
DomainModelerAgent --> ApplicationArchitectAgent
ApplicationArchitectAgent --> MicroserviceGeneratorAgent
ApplicationArchitectAgent --> AdapterGeneratorAgent
- Upstream: Consumes service definitions, domain models, and APIs
- Downstream: Provides application service blueprints, orchestration patterns, and port interfaces
π§ Agentβs Core Objectives¶
| Objective | Description |
|---|---|
| π― Use Case-Driven Decomposition | Define core application services as use case handlers |
| π§± Layered Architecture Enforcement | Enforce separation between application, domain, infrastructure, transport |
| π Port & Adapter Mapping | Model incoming/outgoing boundaries: repositories, event buses, APIs |
| π Event and Workflow Orchestration | Structure how domain logic, policies, and integrations are coordinated |
| β Testability and Modularity | Output clean, isolated, mockable code structures |
| βοΈ Autonomous Readiness | Generate outputs that are directly consumable by scaffolding and CI agents |
β¨ Why the Application Architect Agent Matters¶
Without it:
- Business logic becomes tangled with infrastructure
- Use cases emerge inconsistently across services
- Ports are ad-hoc, not decoupled
- Testing becomes hard and brittle
- Developers face steep ramp-up costs
- Agent-based code generation lacks structure
With it:
- Services are clean, maintainable, and extensible
- Application flows are traceable and explainable
- Domain logic stays isolated and expressive
- Code generation becomes predictable and safe
ποΈ Typical Use Case¶
βGiven a
BillingServicewith use cases like βGenerate Invoiceβ, βApply Discountβ, and domain entities likeInvoiceandPayment,
generate the Clean Architecture structure including:
- Application services
- Use case handlers
- Interfaces (ports) forIInvoiceRepository,INotificationSender
- Dependency injection plan
- Entry points for REST and Event adapters.β
π§ Guiding Principles¶
The Application Architect Agent adheres to the following guiding principles to ensure that the design remains modular, testable, and aligned with Clean Architecture and DDD:
- π§± Clean Architecture: Enforces separation of concerns between application, domain, and infrastructure.
- π¦ Port & Adapter (Hexagonal): Ensures that communication between components is through well-defined interfaces (e.g., input ports, output ports).
- π§ Single Responsibility: Every application service is responsible for a single business use case.
- π§ͺ Test-First Friendly: Focuses on designing components that are easy to test and mock.
- π‘οΈ Modular Contracts: Defines interfaces for every boundary, enabling flexibility and decoupling.
ποΈ Scope of Influence¶
The Application Architect Agent governs the internal structure of services and how application logic is orchestrated, ensuring modularity, traceability, and alignment with ConnectSoft's Clean Architecture and DDD standards.
Its influence spans multiple architectural layers within a service, defining how use cases are handled, how services depend on domain logic, and how external systems are integrated.
π Domains and Layers Under Control¶
π§± 1. Application Layer Design¶
| Area | Description |
|---|---|
| Application Services | Designs orchestrators that coordinate domain logic, validate inputs, and call external ports |
| Use Case Handlers | Models business processes as single-responsibility handlers with consistent interfaces |
| Cross-Cutting Concern Embedding | Plans injection of validation, authorization, logging, metrics at the application layer |
| Policy Coordination | Coordinates use cases with policies, workflows, conditional paths, and retry logic where needed |
π‘ 2. Input and Output Port Mapping¶
| Area | Description |
|---|---|
| Input Ports (Controllers, Message Handlers) | Defines how requests are received β REST, gRPC, events, commands |
| Output Ports (Repositories, Message Senders, APIs) | Declares interfaces the application uses to call infrastructure β messaging, persistence, integrations |
| Dependency Inversion Contracts | Models interfaces (ports) without binding to external concerns β driving testable, mockable design |
π¦ 3. Adapter Context Alignment¶
| Area | Description |
|---|---|
| Transport Adapters | Maps input ports to controllers or event listeners |
| Infrastructure Adapters | Maps output ports to actual implementations β DB repositories, HTTP clients, event publishers |
| Event-Driven Orchestration Handoff | Ensures handlers can emit or consume events via mapped ports without violating boundaries |
π 4. Domain & Application Boundary Guarding¶
| Area | Description |
|---|---|
| Application β Domain Rules | Ensures the application layer calls domain logic but never the other way around |
| No Infrastructure Leakage | Prevents infrastructure dependencies from bleeding into the application or domain core |
| DTO Mapping Contracts | Defines mappings between external models (DTOs) and internal domain objects via mappers or translators |
π― What the Agent Does Not Govern¶
| Out of Scope | Reason |
|---|---|
| Actual infrastructure adapter implementations | Handled by Adapter Generator Agent |
| CI/CD pipeline generation | Owned by DevOps Architect Agent |
| API schema surface (OpenAPI, routes) | Modeled by API Designer Agent |
| Entity definitions | Defined by Domain Modeler Agent |
| Event schema design | Provided by Event-Driven Architect Agent |
π§ Summary Table: Layer Responsibilities¶
| Layer | Owned by This Agent? | Deliverables |
|---|---|---|
| Application | β Yes | Application services, use case handlers, input/output ports |
| Domain | β Consumes | Uses entities, aggregates from Domain Modeler |
| Infrastructure | β Coordinates | Defines interfaces, not implementations |
| Presentation | β Partially | Maps entry points, doesnβt define full transport |
π Scope Visualization¶
graph TD
subgraph "Application Layer"
A1[Use Case Handler: ApplyDiscount]
A2[Service: BillingAppService]
A3[Input Port: IApplyDiscountCommand]
A4[Output Port: IInvoiceRepository]
A5[Output Port: IEventBus]
end
subgraph "Domain Layer"
D1[Entity: Invoice]
D2[ValueObject: Discount]
end
subgraph "Infrastructure"
I1[SQLRepository: InvoiceRepo]
I2[ServiceBus: EventPublisher]
end
A1 --> A2
A2 --> D1
A2 --> A4
A2 --> A5
A4 --> I1
A5 --> I2
π Core Responsibilities¶
The Application Architect Agent is responsible for modeling the internal structure of each microservice or application, ensuring:
- Modular, testable, cleanly layered design
- Use caseβoriented orchestration logic
- Consistent application of Clean Architecture, DDD, and Port-and-Adapter principles
- Compatibility with autonomous code generation and runtime frameworks
Its outputs are consumed by downstream Microservice Generator, Adapter Generator, and Test Automation Agents.
π οΈ Primary Responsibilities¶
π§± 1. Application Service & Use Case Modeling¶
| Task | Description |
|---|---|
| Identify Use Cases | Analyze service responsibilities and domain models to define atomic business processes (e.g., ApproveInvoice, CancelBooking) |
| Generate Application Services | Group related use cases into services that mediate domain logic, validation, and external coordination |
| Define Execution Flow | Map step-by-step interaction: validation β policy check β entity call β output port trigger |
π 2. Port Design (Input/Output)¶
| Task | Description |
|---|---|
| Input Port Contracts | Define how external triggers (REST, event, RPC) are received and routed to the correct handler |
| Output Port Interfaces | Create application-facing abstractions for calling infrastructure (e.g., INotificationSender, IUserRepository) |
| Align Ports with Use Cases | Bind input/output ports to use case handlers without leakage across layers |
π§ 3. Application-Oriented Dependency Mapping¶
| Task | Description |
|---|---|
| Dependency Inversion Planning | Ensure application depends only on interfaces (not concrete infra) |
| Define Constructor Injection Plans | Prepare for DI in generated code (e.g., constructor injection, decorator chains) |
| Map Cross-Cutting Concerns | Inject behaviors such as logging, metrics, error handling without breaking modularity |
π§ͺ 4. Testability Enforcement¶
| Task | Description |
|---|---|
| Design Mockable Interfaces | Ensure all output ports are suitable for test double generation |
| Scenario Sketching | Define recommended test case boundaries and behavioral expectations per use case |
| Validation Contracts | Annotate expected input validations and failure paths for test generation agents |
π§© 5. Coordination with Domain & Infrastructure Layers¶
| Task | Description |
|---|---|
| Orchestrate Domain Logic | Drive aggregates, entities, and policies via application services |
| Delegate to Adapters | Ensure that calling infrastructure (e.g., DB, event bus, HTTP client) happens via output ports only |
| Mapper Guidance | Specify where and how to map DTOs β Domain objects to maintain purity |
π€ 6. Output Artifact Generation¶
| Deliverables | Description |
|---|---|
- application-architecture.md |
Application layer blueprint |
- use-cases.yaml |
Structured use case definitions |
- input-ports.json / output-ports.json |
Interface contracts |
| - Class skeletons | (e.g., InvoiceAppService.cs, IInvoiceRepository.cs) |
| - Diagrams | Mermaid diagrams showing orchestration and layering |
| - Observability Hints | OpenTelemetry annotations for use case span instrumentation |
β Summary Table¶
| Area | Responsibility |
|---|---|
| Use Case Mapping | β |
| Application Services | β |
| Port Interface Contracts | β |
| Dependency Flow | β |
| DTO Translation Guidance | β |
| Observability Hints | β |
| Testability Planning | β |
π₯ Core Inputs¶
To design the internal application architecture for a service,
the Application Architect Agent consumes structured upstream artifacts that describe:
- The service's responsibilities
- Domain model structure
- Events it produces/consumes
- External interfaces (APIs, messages)
- Non-functional requirements (e.g., performance, modularity, compliance)
These inputs ensure clean layering, correct orchestration boundaries, and fully aligned application logic design.
π Required Inputs¶
| Artifact | Source | Required |
|---|---|---|
| Solution Blueprint | Solution Architect Agent | β |
| Domain Model Specification | Domain Modeler Agent | β |
| Bounded Context & Service Metadata | System Blueprint | β |
| API Surface Summary | API Designer Agent | β |
| Domain Events Catalog | Event-Driven Architect Agent | β |
| Compliance & NFR Tags | Architecture Blueprint | β |
π§© Input Fields and Roles¶
π· 1. Service Responsibility Definition¶
| Field | Example |
|---|---|
service_name |
BillingService |
bounded_context |
Billing |
responsibilities |
GenerateInvoice, ApplyCredit, SendReminder |
edition_constraints |
Pro, Enterprise only |
This defines what the application is expected to handle β foundational for use case detection.
π· 2. Domain Model (Entities, Aggregates, VOs)¶
| Field | Example |
|---|---|
entities |
Invoice, Payment, DiscountPolicy |
aggregates |
Invoice |
domain_services |
TaxCalculator, RefundPolicyEvaluator |
Enables orchestration flows to be correctly mapped to aggregates and services.
π· 3. Domain Events¶
| Field | Example |
|---|---|
produced_events |
InvoiceCreated, DiscountApplied |
consumed_events |
PaymentSucceeded, SubscriptionExpired |
Used to design event handler input ports and event-driven coordination flows.
π· 4. API Surface Summary¶
| Field | Example |
|---|---|
endpoints |
POST /billing/invoice, PATCH /billing/invoice/{id} |
methods |
CreateInvoice, UpdateInvoiceStatus |
auth_required |
true |
Used to align controller adapters to input ports, ensuring proper Clean Architecture separation.
π· 5. Non-Functional Requirements (NFRs)¶
| Field | Example |
|---|---|
latency_budget_ms |
300 |
audit_required |
true |
authorization_required |
true |
testability_required |
true |
Used to embed cross-cutting concerns like validation, logging, security decorators, and tracing spans.
π§ Semantic Memory Integration (Optional)¶
The agent may also retrieve from memory:
- Past application service patterns for similar use cases
- Reusable output port interfaces for common infrastructure (e.g.,
INotificationSender) - Common input validation contracts (e.g., address format, date range policies)
π Validation Checklist¶
| Input | Requirement |
|---|---|
service_name |
β |
responsibilities |
β |
domain_model.entities |
β |
api_surface.endpoints |
β |
domain_events.produced |
Optional (required for event-sourced contexts) |
nfrs.latency, audit_required |
Strongly Recommended |
β Input Summary Table¶
| Input | Role |
|---|---|
| Solution Blueprint | Defines high-level structure and bounded context |
| Domain Model | Enables orchestration of rich business logic |
| Events | Enables async workflows and handler generation |
| API Surface | Maps external entry points to input ports |
| NFRs | Influences decorators, observability, validation injection |
π€ Core Outputs¶
The Application Architect Agent produces a set of structured, modular, and testable artifacts that define the internal logic and orchestration structure of each service.
These outputs are used by:
- β Microservice Generator Agent to scaffold code
- β Adapter Generator Agent to wire controllers, repositories, and events
- β Test Case Generator Agent to create unit/integration test templates
All outputs are Clean Architectureβcompliant, traceable, and agent-consumable.
π Key Output Artifacts¶
π§± 1. Application Architecture Blueprint¶
| Attribute | Description |
|---|---|
| File | application-architecture.md |
| Sections | - Service Overview: A high-level description of the service, its purpose, and key responsibilities. |
| - Application Services & Use Cases: A list of application services and their associated use cases. | |
| - Input Ports: Interfaces for incoming requests, such as commands, queries, and events. | |
| - Output Ports: Interfaces for outgoing dependencies, such as repositories, event buses, and external services. | |
| - Dependency Flow: A detailed mapping of dependencies between different layers of the system (e.g., application, domain, infrastructure). | |
| - Cross-Cutting Concerns: Shared concerns such as validation, logging, authorization, and others. | |
| - Observability Points: Recommendations for metrics, spans, and logging for effective monitoring and diagnostics. | |
| - Testability Notes: Guidelines for testing use cases, ports, and how to ensure the architecture supports testability. | |
- Trace Metadata: Includes important identifiers such as trace_id, project_id, and bounded_context for traceability. |
π 2. Use Case Definitions¶
Use case definitions describe the specific business processes or actions within the application. Each use case outlines its triggering events, actors involved, the data models it interacts with, the ports it communicates with, and other cross-cutting concerns such as validation and security.
File¶
use-cases.yaml
Structure¶
The following is an example of how a use case definition is structured:
use_cases:
- name: CreateInvoice
triggers: [POST /invoice, InvoiceRequestedEvent]
actor: "BillingAdmin"
aggregates_used: [Invoice, Payment]
output_ports: [IInvoiceRepository, IEventBus]
cross_cutting: [validation, auth, tracing]
emits_events: [InvoiceCreated]
test_cases:
- "valid invoice β invoice persisted + event emitted"
- "invalid tax input β validation failure"
Explanation:
- name: Name of the use case (e.g., CreateInvoice).
- triggers: Defines what triggers the use case, such as HTTP requests or domain events.
- actor: The user or system that initiates the use case (e.g., BillingAdmin).
- aggregates_used: The domain models (aggregates) involved in the use case (e.g., Invoice, Payment).
- output_ports: Interfaces that the use case interacts with for output (e.g., IInvoiceRepository, IEventBus).
- cross_cutting: Shared concerns that affect the use case (e.g., validation, authentication, tracing).
- emits_events: List of events that the use case emits after execution (e.g., InvoiceCreated).
- test_cases: Example test cases to ensure the use case works as expected.
π 3. Port Interface Contracts¶
Port interfaces define the boundaries between the application layer and external systems or components (e.g., repositories, event buses). They ensure that the system is modular and decoupled, allowing for easy maintenance and testing.
Files and Example Port Interfaces¶
input-ports.json: Defines the input ports (e.g., command handlers, event listeners).- Example:
ICreateInvoiceCommandHandler,IPaymentSucceededEventHandler
- Example:
output-ports.json: Defines the output ports (e.g., repositories, event senders).- Example:
IInvoiceRepository,INotificationSender,IEventBus
- Example:
Structure Example¶
The following is an example of how a port interface is structured:
{
"interface": "IInvoiceRepository",
"methods": [
{
"name": "Add",
"input": "Invoice",
"output": "Task"
},
{
"name": "GetById",
"input": "Guid",
"output": "Invoice"
}
],
"layer": "application",
"bound_to": "infrastructure_adapter"
}
Explanation:
- interface: Name of the interface (e.g., IInvoiceRepository).
- methods: List of methods available within the interface, including their input types and output types.
- layer: The architectural layer to which the interface belongs (e.g., application).
- bound_to: Specifies where the interface is implemented (e.g., infrastructure_adapter).
π¦ 4. Class & Contract Skeletons (optional downstream)¶
Class and contract skeletons represent the initial scaffolding of code for services, handlers, and repositories that are emitted either as stubs or abstract templates. These skeletons provide the foundational structure that can be further developed, depending on the downstream build mode (e.g., scaffold or abstract).
Files¶
InvoiceAppService.cs(or template for the application service)CreateInvoiceHandler.cs(for handling the creation of invoices)IInvoiceRepository.cs(for defining the repository contract)
Description¶
These files are optionally emitted as code skeletons or DSL templates based on the downstream build mode:
- Scaffold Mode: The files are generated as complete code stubs that can be directly implemented or extended.
- Abstract Mode: The files are emitted with abstract definitions and placeholders for the developer to fill in the logic.
These skeletons help provide consistency in the architecture and design patterns, ensuring that all generated components follow the correct structure while enabling flexibility during development.
π 5. Observability Metadata¶
Observability Metadata defines the monitoring, logging, and metrics used to ensure that the system is observable in terms of performance, reliability, and overall health. This includes span mapping, metrics collection, and logging guidelines for specific use cases, enabling efficient monitoring and tracing.
File¶
application-observability.yaml
Includes¶
- Span Mapping: Defines the span for tracing individual operations within the system.
-
Example:
CreateInvoice β span.create_invoice.handler -
Metric Recommendations: Provides key metrics to track the performance and health of the system.
- Example:
invoice_created_total: Counter for tracking the total number of invoices created.invoice_creation_duration_ms: Histogram for tracking the duration of invoice creation in milliseconds.
- Example:
-
Logging Guidelines: Defines consistent logging practices for each use case to ensure traceability and debugging.
- Example: Ensure that logs related to invoice creation include relevant metadata like
invoice_id,user_id, andtimestampto allow traceability across services.
- Example: Ensure that logs related to invoice creation include relevant metadata like
π 6. Application Layer Diagrams¶
Application Layer Diagrams provide visual representations of key interactions and processes within the application. These diagrams help map the flow of information and actions between services, ports, and external actors. They are essential for understanding use case orchestration, port mapping, and dependency inversion within the system.
Format¶
- Mermaid Class/Sequence Diagrams: Use Mermaid syntax for generating sequence and class diagrams that represent application behavior and structure.
Types of Diagrams¶
- Use Case Orchestration: Illustrates the flow of actions triggered by use cases.
- Input/Output Port Mapping: Shows how input and output ports interact with services and external systems.
- Dependency Inversion Overview: Depicts how dependencies are inverted to allow for decoupling and testability.
Example Sequence Diagram¶
The following Mermaid sequence diagram shows the orchestration of the CreateInvoice use case:
sequenceDiagram
actor API
API ->> ICreateInvoiceHandler: Execute(command)
ICreateInvoiceHandler ->> InvoiceAppService: Create()
InvoiceAppService ->> IInvoiceRepository: Add()
InvoiceAppService ->> IEventBus: Publish(InvoiceCreated)
Explanation:
- API: The external actor triggering the use case by sending a command.
- ICreateInvoiceHandler: The handler that processes the request.
- InvoiceAppService: The service that orchestrates the creation of the invoice.
- IInvoiceRepository: The output port used to persist the invoice in the repository.
- IEventBus: The output port that publishes events (e.g.,
InvoiceCreated).
π‘ 7. Emitted Event: ApplicationArchitectureBlueprintCreated¶
This event is emitted when the Application Architecture Blueprint has been successfully created. It carries essential metadata about the service and its architecture blueprint, including a traceId, project ID, and a timestamp.
Format¶
- JSON
Event Structure¶
The following is an example of the ApplicationArchitectureBlueprintCreated event structure:
{
"event": "ApplicationArchitectureBlueprintCreated",
"service": "BillingService",
"projectId": "connectsoft-saas",
"blueprintUrl": "https://.../application-architecture.md",
"traceId": "app-arch-98a4",
"timestamp": "2025-05-01T17:42:00Z"
}
Explanation:
- event: The name of the emitted event (e.g., ApplicationArchitectureBlueprintCreated).
- service: The name of the service for which the architecture blueprint was created (e.g., BillingService).
- projectId: The ID of the project associated with the architecture (e.g., connectsoft-saas).
- blueprintUrl: The URL pointing to the location of the generated architecture blueprint document (e.g., application-architecture.md).
- traceId: A unique identifier for the event, used for tracing and debugging (e.g., app-arch-98a4).
- timestamp: The date and time the event was emitted, formatted in ISO 8601 (e.g., 2025-05-01T17:42:00Z).
β Output Summary Table¶
| Output | Format | Target |
|---|---|---|
| Application Blueprint | Markdown | Internal documentation, downstream agents |
| Use Cases | YAML | Microservice + Test Generator |
| Ports | JSON | Adapter Generator |
| Class Skeletons | Code / DSL | Scaffolding engines |
| Observability Map | YAML | Observability Agent |
| Blueprint Event | JSON | System Bus, trace logs |
π‘οΈ Output Validation Rules¶
| Rule | Description |
|---|---|
| Trace metadata embedded in all files | β |
| Ports match domain and infrastructure plans | β |
| Use cases include test scenarios | β |
| All layers respected (no cross-invocation) | β |
| Diagrams render and validate | β |
π Knowledge Base¶
The Application Architect Agent builds its decisions using a rich ConnectSoft-curated architectural knowledge base, enabling it to:
- Generate consistent, testable, cleanly layered application structures
- Reuse proven application patterns from prior solutions
- Avoid architectural anti-patterns and enforce best practices
- Adjust reasoning dynamically based on project type, NFRs, or compliance needs
The knowledge base includes both static patterns/templates and semantic memory embeddings of prior blueprint executions.
π Knowledge Categories¶
π§± 1. Clean Architecture Templates¶
| Resource | Use |
|---|---|
| Application Layer Schemas | How to model application services, use cases, orchestrators |
| Port & Adapter Rules | Rules for input/output ports, DTO separation, handler mapping |
| Layer Dependency Diagrams | Pre-defined dependency graphs showing allowed flow |
| Testability Contracts | What makes a handler/service mockable, testable, injectable |
π¦ 2. Use Case Design Patterns¶
| Pattern | Example |
|---|---|
| Request β Validate β Execute β Emit Event | CreateInvoice, RegisterUser, BookAppointment |
| Event Handler β Entity Load β Aggregate Update | PaymentSucceeded β Invoice.ApplyPayment() |
| Workflow Orchestration β Saga Trigger | CancelSubscription with rollback or timed events |
Stored as reusable YAML fragments, DSLs, or embedded blueprints that the agent can extract and adapt.
π 3. Port Contract Catalog¶
| Resource | Purpose |
|---|---|
| Standard Ports | Common patterns like IRepository<T>, INotificationSender, IEventBus, IUserContextProvider |
| Compliance-Aware Ports | Output ports that enforce logging, audit, encryption tagging |
| Retry-Enabled Ports | Contracts with idempotency support, retry semantics, circuit breaker compatibility |
π‘ 4. Cross-Cutting Concern Embedding Patterns¶
| Concern | Pattern |
|---|---|
| Validation | FluentValidation-compatible request validators |
| Authorization | Role-based or policy-based decorators |
| Observability | Span injection wrappers around handlers |
| Resilience | Fallback/retry design hints for output port implementations |
These are embedded as concern strategies that the agent attaches to use cases via cross_cutting: annotations.
π§ 5. Semantic Memory Retrieval¶
The agent retrieves embedded past blueprint fragments based on:
| Vector Query Type | Returns |
|---|---|
use_case + bounded_context + domain_model |
Matching application-service layout from past project |
event + aggregate |
Reusable event handler blueprint |
port + environment |
Proven contract for similar services (e.g., IEmailSender for Basic edition) |
NFR: testability + latency |
Patterns emphasizing lightweight orchestration and validation flow isolation |
π‘οΈ Governance & Validation Rules for Knowledge Base¶
| Rule | Enforcement |
|---|---|
| Only approved patterns reused | Marked with approvedForReuse: true |
| All reused outputs traceable | Linked to source blueprint, project ID, and execution hash |
| Patterns version-controlled | Semantic memory stores pattern_version and deprecated = false flag |
| Anti-pattern exclusion list enforced | E.g., βrepositories with async void methodsβ, βcontroller logic in application serviceβ |
π Memory Access Flow¶
flowchart TD
A[Start Use Case Modeling] --> B[Query Semantic Memory]
B --> C[Load Prior Pattern Matches]
C --> D[Compose Application Layer]
D --> E[Log Used Patterns + Confidence]
β Knowledge Base Benefits¶
- β Reduces design duplication
- β Speeds up high-quality architecture generation
- β Enforces ConnectSoftβs architectural integrity across 3000+ services
- β Allows adaptive learning via pattern improvement feedback loop
π Internal Execution Flow¶
The Application Architect Agent executes a structured, traceable, and modular pipeline
to transform solution-level service definitions into well-layered, testable application architecture blueprints.
Each phase is powered by composable Semantic Kernel skills, supports partial retries, and emits OpenTelemetry spans for full traceability.
π Step-by-Step Process Phases¶
| Phase | Description |
|---|---|
π₯ 1. Input Validation and Memory Retrieval¶
- Ensure all required artifacts are present:
- Solution Blueprint
- Domain Model
- API Surface
- Event Catalog
- Query semantic memory for reusable use case/port patterns
π§ 2. Use Case Discovery¶
- Analyze service responsibilities and API/event triggers
- Break down each into atomic use cases (e.g.,
CreateInvoice,ApplyDiscount) - Generate use case metadata: triggers, output ports, events, actor, conditions
π§± 3. Application Service Construction¶
- Group related use cases under an Application Service class
- Define service boundaries: e.g.,
InvoiceAppService,BookingAppService - Map orchestration flow per use case:
- Validate β Domain Call β Port Call β Emit Event
π 4. Port Interface Design¶
- Define input ports (commands, queries, event handlers)
- Define output ports (repositories, services, integrations)
- Align all ports with inversion-of-control constraints
- Tag ports with cross-cutting concern requirements (e.g., retryable, secure, loggable)
π 5. DTO Mapping Guidance¶
- Identify translation boundaries:
- External DTOs β Application Inputs
- Domain Objects β Application Outputs
- Specify mapping contracts or helpers needed
π§ͺ 6. Testability and Observability Mapping¶
- Annotate test scenarios for each use case
- Specify mockable points (every output port)
- Generate OpenTelemetry span suggestions per handler or orchestrator
π€ 7. Blueprint Assembly¶
- Compile:
application-architecture.mduse-cases.yamlinput-ports.json,output-ports.json- Optional: code scaffolding templates
- Mermaid diagrams (use case orchestration, port flows)
β 8. Validation and Emission¶
- Validate schema, renderability of diagrams, and completeness
- Emit
ApplicationArchitectureBlueprintCreatedevent - Link outputs to trace logs and project context for downstream agents
π Flow Diagram¶
flowchart TD
A[Start Session] --> B[Validate Inputs]
B --> C[Retrieve Memory + Use Case Patterns]
C --> D[Define Use Cases]
D --> E[Model Application Services]
E --> F[Define Input/Output Ports]
F --> G[Generate Observability + Testability Metadata]
G --> H[Assemble Blueprint]
H --> I[Validate and Emit]
π Retry and Correction Logic¶
| Phase | Retry Trigger | Action |
|---|---|---|
| Use Case Discovery | Missing actors or aggregates | Retry with simplified pattern |
| Port Mapping | Unresolvable port conflicts | Re-evaluate role β interface mapping |
| Observability Plan | Missing spans or probes | Fallback to default span plan |
| DTO Mapping | No match in domain model | Retry with suggestion from similar services |
π‘ Telemetry per Phase¶
Each step emits:
| Metric | Example |
|---|---|
app_arch_skill_duration_ms{name} |
e.g., PortMapperSkill β 30ms |
retry_count_by_phase |
e.g., Use Case Discovery: 1 |
blueprint_validation_status |
Pass / Partial / Retry Needed |
port_contract_count |
Count of input/output interfaces generated |
telemetry_coverage_score |
Ratio of span-covered use cases to total use cases |
π οΈ Core Skills and Semantic Kernel Functions¶
The Application Architect Agent is built from modular, reusable Semantic Kernel skills,
each responsible for a distinct architectural task.
These skills are:
- Atomic: focused on a single responsibility
- Composable: chained into higher-order reasoning flows
- Retryable: isolated recovery in case of failure
- Traceable: emitting OpenTelemetry spans for observability
π Primary Skills¶
| Skill Name | Purpose |
|---|---|
π§ Input Processing¶
| InputValidatorSkill | Verifies required artifacts: Solution Blueprint, Domain Model, Events, API Specs |
| MemoryPatternRetrieverSkill | Loads reusable application patterns (use cases, port maps, service layering) |
π Use Case & Service Modeling¶
| UseCaseDiscoverySkill | Analyzes service responsibilities, domain entities, and APIs to extract use cases |
| UseCaseMetaBuilderSkill | Attaches triggers, actors, inputs/outputs, aggregates used, emitted events |
| AppServiceComposerSkill | Groups use cases into cohesive application services (e.g., InvoiceAppService) |
π Port & Adapter Architecture¶
| InputPortMapperSkill | Designs command/query/event handler interfaces aligned to entry points |
| OutputPortDesignerSkill | Generates abstract output port contracts for repository, messaging, and integrations |
| CrossCuttingAnnotatorSkill | Tags ports or handlers with required decorators (auth, validation, logging) |
π§± DTO and Layer Mapping¶
| DtoMapperDesignerSkill | Specifies DTO β Domain object mappers, translator helper classes |
| LayerBoundaryValidatorSkill | Ensures calls stay within Application β Domain β Port rules (no cross-layer leaks) |
π§ͺ Testability and Observability¶
| TestabilityHintEmitterSkill | Outlines recommended test boundaries, mock points, and sample test cases |
| TelemetrySpanPlannerSkill | Injects trace span annotations for each use case handler and output port call |
| ValidationContractMapperSkill | Links to FluentValidation-compatible validators or suggests contract schemas |
π€ Blueprint Assembly¶
| ApplicationBlueprintAssemblerSkill | Combines use cases, ports, services, cross-cutting concerns into markdown and YAML artifacts |
| MermaidDiagramEmitterSkill | Produces clean architecture diagrams, port flow maps, use case call sequences |
π‘ Event Emission & Logging¶
| BlueprintEmitterSkill | Emits ApplicationArchitectureBlueprintCreated event with output URLs and metadata |
| ExecutionTracerSkill | Emits OpenTelemetry spans per skill execution with trace_id, status, and execution_time_ms |
π§ Skill Composition Flow¶
flowchart TD
ValidateInputs --> RetrieveMemory
RetrieveMemory --> DiscoverUseCases
DiscoverUseCases --> BuildUseCaseMeta
BuildUseCaseMeta --> ComposeAppServices
ComposeAppServices --> MapInputPorts
MapInputPorts --> MapOutputPorts
MapOutputPorts --> PlanObservability
PlanObservability --> AssembleBlueprint
AssembleBlueprint --> EmitBlueprint
π Retry Resilience¶
| Skill | Common Retry Reason |
|---|---|
UseCaseDiscoverySkill |
No actor or aggregate match β retry with hint |
OutputPortDesignerSkill |
Domain interface mismatch β fall back to generic port |
TelemetrySpanPlannerSkill |
Missing handler metadata β default span injected |
π§± Skill Design Principles¶
| Principle | Description |
|---|---|
| Governed | Skills reference ConnectSoft rules for layering, DTO boundaries, DDD style |
| Composable | Any skill can be executed standalone or as part of pipeline |
| Validatable | Each skill emits validation-ready artifacts |
| Traceable | All activity emits OpenTelemetry spans and status logs for dashboards and debugging |
π οΈ Core Technologies¶
The Application Architect Agent uses a modular, traceable, and cloud-native technology stack aligned with ConnectSoft's principles:
- Clean Architecture
- DDD and Port-Adapter pattern
- .NET/C# code generation
- Semantic Kernel orchestration
- OpenTelemetry observability
- YAML/Markdown-based specification interoperability
π Key Technology Components¶
π§ Semantic Reasoning and Skill Orchestration¶
| Component | Purpose |
|---|---|
| Semantic Kernel (.NET) | Skill composition, memory recall, and reasoning flow management |
| Azure OpenAI (GPT-4) | Natural language planning, fallback heuristics, layered design suggestions |
| ConnectSoft SkillPack: ApplicationLayerDesign | Modular skill library for use case mapping, service grouping, and port construction |
βοΈ Application Design Standards and Code Scaffolding¶
| Component | Purpose |
|---|---|
| ConnectSoft.CleanArchitecture.Templates | Reference C# project layouts for application/domain/infrastructure separation |
| Port-and-Adapter Skeletons (Hexagonal) | Patterns for DTO handlers, repositories, and asynchronous adapters |
| Use Case YAML Contracts | Standard structure for input/output validation and test stub generation |
π Artifact & Blueprint Formats¶
| Format | Purpose |
|---|---|
Markdown (application-architecture.md) |
Human-readable application design documentation |
YAML (use-cases.yaml, observability.yaml) |
Use case structure, test hints, trace span plans |
JSON (ports.json, events.json) |
Port interface declarations and event mapping contracts |
| Mermaid diagrams | Sequence and architecture visualization for validation and sharing |
π Semantic Memory and Pattern Embedding¶
| Component | Purpose |
|---|---|
| Vector Database (e.g., Azure Cognitive Search / Pinecone) | Stores reusable fragments of use case orchestration and handler-port structures |
| Blueprint Retrieval Engine | Loads prior agent outputs tagged by domain, NFRs, or service names to accelerate new generation |
π‘ Observability and Execution Tracing¶
| Component | Purpose |
|---|---|
| OpenTelemetry (.NET SDK) | Emits spans per skill and blueprint output with trace_id/project_id metadata |
| ConnectSoft Agent Dashboard | Centralized visualization of span logs, retries, validation outcomes |
| Azure Application Insights | Logs and metrics backend (agent health, latency, blueprint delivery time) |
π» Runtime Code Alignment¶
| Component | Usage |
|---|---|
| .NET 8.0 + C# 12 | Final implementation layer for scaffolding and generated classes |
| FluentValidation.NET | Used to generate and align validation hints from ValidationContractMapperSkill |
| MediatR | Port handler style generation: IRequestHandler<TCommand, TResult> |
| MassTransit or Azure.Messaging.ServiceBus | Event handler input port compatibility for Consume<T> structure |
β Stack Compliance with ConnectSoft Principles¶
| Principle | Technology Support |
|---|---|
| Clean Architecture | Layer templates, dependency control, interface-first output |
| DDD | Aggregates mapped to orchestrators, rich entities modeled via Domain Modeler |
| Port & Adapter | Output/input ports declared in JSON, used by downstream Adapter Generator Agent |
| Testability | Contracts are mockable, handlers are injectable, test case YAMLs generated |
| Observability | Every use case linked to span, metrics, logging outputs |
π¦ Output Distribution¶
| Channel | Tool |
|---|---|
| Artifact Blob Store | Stores application blueprints and structured specs |
| Event Grid / Agent Bus | Delivers ApplicationArchitectureBlueprintCreated for downstream orchestration |
| GitHub / Azure DevOps Repos | Final output can be pushed as project templates or class scaffolds with trace metadata |
π System Prompt (Bootstrapping Instruction)¶
The System Prompt defines the initial operating contract for the Application Architect Agent.
It ensures the agent performs its task aligned with ConnectSoftβs Clean Architecture, DDD, and modular automation standards.
This prompt is used to initialize the agent with:
- Target service context
- Required architectural responsibilities
- Expected outputs and structure
- Enforced constraints and collaboration expectations
π Full System Prompt (YAML + Instruction)¶
You are the **Application Architect Agent** within the **ConnectSoft AI Software Factory**.
Your mission is to analyze a single microservice or application unit and define its **internal application architecture**, ensuring that:
β
Each use case is modeled as a clean, testable handler
β
Port and adapter boundaries are respected
β
Domain logic is orchestrated, not implemented, at the application layer
β
All input/output ports are defined as interfaces (no infrastructure references)
β
Use cases are documented with triggers, outputs, policies, test scenarios
β
Cross-cutting concerns (validation, auth, logging, tracing) are injected using decorators or helper interfaces
β
The final structure is compatible with downstream code generation agents
---
## π You must:
1. Validate the presence of:
- `solution-blueprint.md`
- `domain-model.yaml`
- `api-surface.yaml`
- `event-catalog.yaml`
- trace metadata
2. Query semantic memory to reuse prior application structures or patterns
3. Decompose the `service_responsibilities` into atomic use cases:
- e.g., `CreateInvoice`, `ApplyDiscount`, `CancelBooking`
4. For each use case:
- Define handler signature
- Identify input/output ports
- Describe validation and failure paths
- Specify emitted events or integration actions
5. Group related use cases into `Application Services` (e.g., `InvoiceAppService`)
6. Define:
- Input Port Contracts (commands, queries, event consumers)
- Output Port Interfaces (repositories, buses, clients)
- DTO β Domain translation boundaries
- Observability span annotations
- Testability metadata
7. Emit the following outputs:
- `application-architecture.md`
- `use-cases.yaml`
- `input-ports.json`, `output-ports.json`
- Optional: handler and service class skeletons
- Mermaid diagrams (sequence + dependency flows)
8. Emit `ApplicationArchitectureBlueprintCreated` event with URLs to generated artifacts
---
## π¦ Output Format Requirements:
- Clean Architecture layout (application β domain β ports only)
- Ports must be interface-based and serializable
- Artifacts must be validatable via ConnectSoft schema validators
- Diagrams must render successfully in Mermaid format
- Every artifact must include:
- `trace_id`
- `project_id`
- `bounded_context`
- `agent_version`
π‘οΈ Prompt Governance Constraints¶
| Constraint | Enforced Behavior |
|---|---|
| Testable Output Only | All use cases must produce handler code or specs that support mocking |
| No Infrastructure Coupling | Output ports are always abstract β never reference infrastructure directly |
| Compliance-Ready | Events, logs, and integration points must support audit hooks and tracing spans |
| Observability Embedded | Every use case must emit OpenTelemetry span metadata or fallback tags |
| Cross-Layer Safety | Only the application layer can orchestrate domain logic β no leakage allowed |
β Outcomes¶
This system prompt ensures that the agent:
- Aligns with Clean Architecture by default
- Builds for testability, separation of concerns, and observability
- Produces output usable by scaffolding, documentation, and governance tools
- Enables fast, compliant service rollout with full traceability
π₯ Input Prompt Template¶
The Input Prompt Template defines the structured task assignment format provided to the Application Architect Agent.
It guarantees the agent receives all necessary inputs to build the application layer in alignment with ConnectSoft's architecture.
This prompt is passed either:
- From the orchestration layer (e.g., Agent Coordinator)
- Or directly via a domain-specific agent-to-agent call (e.g., from Solution Architect Agent)
π YAML Input Prompt Format¶
assignment: "application-architecture-design"
project:
project_id: "connectsoft-saas-2025"
trace_id: "trace-4562-apparch"
vision_id: "vision-core-2025"
bounded_context: "Billing"
service_name: "BillingService"
agent_version: "1.1.0"
inputs:
solution_blueprint_url: "https://artifacts.connectsoft.dev/.../solution-blueprint.md"
domain_model_url: "https://artifacts.connectsoft.dev/.../domain-model.yaml"
api_surface_url: "https://artifacts.connectsoft.dev/.../api.yaml"
event_catalog_url: "https://artifacts.connectsoft.dev/.../events.yaml"
nfr_url: "https://artifacts.connectsoft.dev/.../nfr.yaml"
metadata:
source_language: "csharp"
architecture_style: "clean-architecture"
output_mode: "dsl+markdown"
output_format: [markdown, yaml, json, mermaid]
goals:
- "Generate testable use case handlers with input/output ports"
- "Map application services to use cases"
- "Define port contracts aligned to DDD and Clean Architecture"
- "Inject observability spans and validation metadata"
π Field Breakdown¶
| Field | Description |
|---|---|
assignment |
Task type: always "application-architecture-design" |
project_id, trace_id, vision_id |
Mandatory for traceability and metadata tagging |
bounded_context, service_name |
Scope of architectural modeling |
inputs.* |
Required upstream artifacts from prior agents |
source_language |
Used to tailor output class/interface naming |
output_mode |
"dsl+markdown" enables both spec docs and generation-ready files |
goals |
Used by agent to optimize output priorities (testability, reuse, clarity, etc.) |
β Input Validation Rules¶
| Field | Required | Description |
|---|---|---|
trace_id, project_id, bounded_context |
β | Traceability and versioning metadata |
solution_blueprint_url, domain_model_url |
β | Must contain service responsibilities and domain entity references |
api_surface_url, event_catalog_url |
β | Required for mapping entry/exit points |
nfr_url |
β οΈ Recommended | Guides cross-cutting concern injection |
output_format |
β | Agent must support rendering in all specified formats |
source_language |
Optional | Used for naming conventions and code generation compatibility |
π Typical Input Prompt Scenario¶
βDesign the application architecture for the
BillingService,
based on these APIs and events, using Clean Architecture with C#,
outputting YAML specs and handler diagrams.β
The above maps directly to the structured prompt,
allowing the Application Architect Agent to proceed autonomously and deterministically.
π§ Semantic Memory Option¶
The input may optionally include a memory_context_tag, such as:
This allows the agent to retrieve relevant past patterns for reuse.
π€ Output Expectations¶
The Application Architect Agent produces clean, layered, testable, and reusable artifacts that represent the application layer blueprint of a service, structured for both:
- Autonomous microservice scaffolding
- Human validation and review
- Downstream AI agent consumption
Each output is Clean Architectureβcompliant, schema-valid, and traceable by default.
π 1. application-architecture.md¶
| Format | Markdown |
| Sections |
- Service Overview (name, bounded context, responsibilities)
- Use Case List with groupings
- Application Services and their handlers
- Port Definitions (input/output)
- DTO Mapping Notes
- Dependency Flow Rules
- Observability Hints
- Testability Highlights
- Trace Metadata
π§© 2. use-cases.yaml¶
| Format | YAML |
| Fields |
- name, trigger (e.g., API/command/event)
- input_ports, output_ports
- aggregates_used, domain_services_called
- emitted_events, validation_rules
- test_scenarios, latency_budget, auth_required
- telemetry_span_id
π 3. input-ports.json & output-ports.json¶
| Format | JSON |
| Purpose |
- Explicit contract for controller, event handler, consumer input ports
- Interface-style output ports to repositories, event buses, external systems
- Includes method names, input/output types, location (app/infrastructure)
{
"interface": "IInvoiceRepository",
"methods": [
{
"name": "Add",
"input": "Invoice",
"output": "Task"
}
],
"trace_id": "trace-abc-1234",
"service": "BillingService"
}
π§± 4. Optional Class Skeletons¶
| Format | DSL or C# |
| Files |
- CreateInvoiceHandler.cs
- InvoiceAppService.cs
- IInvoiceRepository.cs
- IEventBus.cs (stub)
These are ready for Microservice Generator Agent to transform into runnable services.
π 5. application-observability.yaml¶
| Format | YAML |
| Fields |
- use_case_spans: map of use case to OpenTelemetry span name
- metrics: e.g., invoice_created_total, use_case_error_rate
- log_annotations: important log contexts per handler
- tracing_boundary_notes: guidance for adapter agents
π 6. Mermaid Diagrams¶
| Files |
- use-case-orchestration.mmd
- port-layer-flow.mmd
- clean-architecture-boundaries.mmd
sequenceDiagram
participant Controller
participant Handler
participant Domain
participant EventBus
Controller->>Handler: Handle(CreateInvoice)
Handler->>Domain: Aggregate.Apply()
Handler->>EventBus: Publish(InvoiceCreated)
π‘ 7. ApplicationArchitectureBlueprintCreated Event¶
| Format | JSON | | Fields |
{
"event": "ApplicationArchitectureBlueprintCreated",
"projectId": "connectsoft-saas",
"boundedContext": "Billing",
"blueprintUrl": "https://.../application-architecture.md",
"traceId": "app-arch-xyz-456",
"service": "BillingService",
"timestamp": "2025-05-01T19:12:00Z"
}
β Output Completeness Rules¶
| Rule | Requirement |
|---|---|
| Trace metadata in all files | β |
| Every use case linked to at least one input and output port | β |
| Ports declared as interfaces, not implementations | β |
| Use case scenarios include test guidance | β |
| At least one Mermaid diagram successfully renders | β |
| Output artifacts conform to ConnectSoft schemas | β |
π― Output Summary Table¶
| Artifact | Format | Purpose |
|---|---|---|
| Application Blueprint | Markdown | Design documentation and agent orchestration |
| Use Cases | YAML | Use case specs, test input |
| Ports | JSON | Input/output interface definitions |
| Class Skeletons | C#/DSL | Microservice generation |
| Observability | YAML | Metrics, spans, logs |
| Diagrams | Mermaid | Visual reference and dependency tracing |
| Emitted Event | JSON | Triggers downstream agents (codegen, adapter, test) |
π§ Memory Architecture¶
The Application Architect Agent leverages both short-term session memory and a rich long-term semantic memory
to deliver adaptive, consistent, reusable application blueprints across ConnectSoft projects.
This enables:
- High-quality reuse of proven design patterns
- Context-aware orchestration
- Self-correction and validation recall
- Avoidance of anti-patterns
π₯ Short-Term Memory (Session Context)¶
| Purpose | Description |
|---|---|
| Use Case Context | Tracks each use case, its dependencies, actors, events, and state during current session |
| Port Definitions | Retains declared input/output port contracts as theyβre discovered |
| Skill Execution Cache | Records intermediate outputs (e.g., inferred handler structure, testability rating) |
| Validation Warnings | Stores runtime flags for rule violations or retry candidates |
Short-term memory is cleared after blueprint finalization but included in OpenTelemetry spans and execution metadata.
π§ Long-Term Memory (Semantic Vector Memory)¶
| Content Type | Description |
|---|---|
π§± 1. Use Case Blueprints¶
- Embedded representations of past
use-cases.yamlandapplication-architecture.mdfiles - Indexed by: domain model, trigger type, actor, and port usage pattern
- Used to recreate or adapt similar structures when matching patterns are found
π 2. Port Contracts Library¶
- Common interface contracts (
IInvoiceRepository,INotificationSender,IEventBus) - Includes decorator variants (e.g.,
ILoggedInvoiceRepository) - Tagged by compliance level, testability, idempotency
π¦ 3. Application Service Grouping Patterns¶
- Reusable layouts for grouping handlers into application services (e.g.,
InvoiceAppService,BookingAppService) - Includes constructor signature templates, injection strategy, test stub examples
π‘οΈ 4. Anti-Pattern Memory¶
- Detects and blocks previously rejected or deprecated patterns:
- Application logic leaking into domain layer
- Output ports that reference concrete implementations
- Missing validation contracts for critical use cases
π 5. Observability Reference Library¶
- Span mapping templates per use case type (event-driven, command-driven, saga)
- Metric definitions per handler category
- Logging enrichment strategies (e.g., include traceId, actorId)
π§ Memory Retrieval Capabilities¶
| Trigger | Memory Match |
|---|---|
use_case: CreateInvoice + actor: Admin |
Retrieves use case YAML with validated handler + span + ports |
output_port: EventBus + emits: InvoiceCreated |
Suggests contract and retry decorator |
domain_aggregate: Payment |
Returns best-fit IPaymentHandler interface template from prior projects |
π§ Storage + Retrieval Layer¶
| Component | Purpose |
|---|---|
| Vector DB (e.g., Pinecone or Azure Cognitive Search) | Embeds blueprint fragments and skill outputs for semantic similarity queries |
| ConnectSoft Artifact Memory API | Enables tagged search by bounded_context, trace_id, aggregate, nfr |
| Governance Labels | Only memory with governance_verified: true is reused without human review |
π‘οΈ Trust & Governance Rules¶
| Rule | Enforcement |
|---|---|
| Reused fragments include source trace_id + project_id | β |
Only pattern_version: approved entries are auto-injected |
β |
Anti-patterns rejected via PatternFilterSkill |
β |
Execution reasoning logs every match used with match_confidence_score |
β |
π Memory Query Lifecycle (Execution Flow)¶
flowchart TD
A[Start Use Case Discovery] --> B[Query Semantic Memory]
B --> C[Return Blueprint Fragments + Contracts]
C --> D[Score Matches + Filter by Governance Rules]
D --> E[Inject Port/Service Patterns into Current Design]
β Benefits of Memory-Driven Design¶
- β Reuse of proven high-quality design patterns
- β Reduced design time and higher first-pass accuracy
- β Continuous learning across thousands of microservices
- β Traceable blueprint lineage
β Validation and Correction Framework¶
The Application Architect Agent enforces strict Clean Architecture compliance, port-layer integrity, and output completeness through a multi-phase validation pipeline.
It can detect and resolve:
- Invalid use case structure
- Port misalignments
- Domain-layer violations
- Missing metadata, tracing, or cross-cutting tags
- Schema violations in output files
The agent supports modular retries, fallback generation, and human escalation in edge cases.
π Validation Phases¶
| Phase | Description |
|---|---|
π₯ 1. Input Completeness Validation¶
- Ensure presence of:
- Solution Blueprint
- Domain Model
- Event Catalog
- API Surface
- Required metadata fields (
trace_id,service_name, etc.)
π§ 2. Use Case Structural Validation¶
- Ensure each use case includes:
- At least one input trigger (API, command, or event)
- Declared output ports or domain interaction
- Clear test scenario or validation annotation
π 3. Port Boundary Enforcement¶
- Validate:
- No domain logic depends on infrastructure
- All ports are interface-based, not concrete classes
- Output ports properly aligned with domain services or entity boundaries
π§ͺ 4. Cross-Cutting Concern Check¶
- Ensure each handler includes (if required):
- Validation layer
- Authorization logic
- Tracing span annotation
- Logging guidance
π 5. Artifact Schema Validation¶
- Check:
- YAML and JSON outputs conform to ConnectSoft schemas
- Mermaid diagrams render correctly
- Markdown includes all required metadata blocks
π Retry and Correction Logic¶
| Issue | Retry Action |
|---|---|
| Use case lacks test metadata | Regenerate with TestabilityHintEmitterSkill |
| Output port misaligned with entity | Trigger OutputPortDesignerSkill with corrected aggregate context |
| Invalid interface format | Run PortSchemaValidatorSkill + regenerate as generic base |
| Missing span or cross-cutting concern | Re-invoke TelemetrySpanPlannerSkill or CrossCuttingAnnotatorSkill |
All retries are logged with
retry_reason,skill_retried, andresolved = true/false
π‘ Observability and Trace Emissions¶
| Telemetry | Description |
|---|---|
validation_failures_total{name} |
Aggregated failures by phase |
retry_count_by_skill{name} |
Number of retries per module |
schema_validation_time_ms |
Latency of output artifact validation |
port_contract_violations_detected |
Instances where Clean Architecture boundaries were violated |
telemetry_span_missing_count |
Handlers missing span annotations |
All telemetry includes:
trace_idproject_idservice_nameagent_version
π§ Sample Validation Flow Diagram¶
flowchart TD
A[Use Case + Port Generation] --> B[Run ValidatorChain]
B --> C{Is Valid?}
C -- Yes --> D[Emit Final Blueprint]
C -- No --> E[Retry Offending Skill]
E --> F{Fixed?}
F -- Yes --> D
F -- No --> G[Emit HumanInterventionRequired]
β οΈ Human Escalation Triggers¶
| Trigger | Escalation Type |
|---|---|
| Retry loop failed 2+ times | Emit ApplicationArchitectureValidationFailed event |
| Use case triggers unclear | Escalate to Enterprise or Solution Architect |
| Output port overlap with another service | Flag for manual domain realignment review |
| Critical schema violation (e.g., missing bounded context) | Halt and notify Orchestration Layer |
π€ Collaboration Interfaces¶
The Application Architect Agent operates as a mid-pipeline architect agent within the ConnectSoft AI Software Factory.
It consumes upstream architectural blueprints and passes application-layer specifications to downstream agents responsible for scaffolding, adapter generation, and testing.
Its interfaces are event-driven, schema-based, and traceable, enabling autonomous yet coordinated design propagation.
π‘ Upstream Interfaces (Inputs Received)¶
| Agent | Interface |
|---|---|
| Solution Architect Agent | |
- Event: SolutionBlueprintCreated |
|
| - Inputs: service name, responsibilities, bounded context, APIs, events |
| Domain Modeler Agent |
- Event: DomainModelPublished
- Inputs: entities, aggregates, value objects, domain services |
| Event-Driven Architect Agent |
- Input: Event catalog for consumed/produced events |
| API Designer Agent |
- Input: API surface definitions (REST/gRPC commands, queries) |
π¦ Downstream Interfaces (Outputs Produced)¶
| Agent | Interface |
|---|---|
π§± Microservice Generator Agent¶
- Consumes:
use-cases.yamlapplication-architecture.mdinput-ports.json,output-ports.json- Optional: C# DSL or class skeletons
- Uses output to scaffold folder structure, DI wiring, and handler classes
π§ͺ Test Generator Agent¶
- Consumes:
use-cases.yamlβ test scenariosoutput-ports.jsonβ mock points
- Generates:
- Unit and integration test templates
- BDD/SpecFlow features (if configured)
π Adapter Generator Agent¶
- Consumes:
input-ports.jsonβ maps to controller or message handler endpointsoutput-ports.jsonβ generates repositories, publishers, client adapters
- Outputs:
- Infrastructure and transport adapter implementations
π Observability Agent¶
- Consumes:
application-observability.yaml
- Uses to:
- Add span mapping
- Suggest metrics, logs, and distributed tracing pipelines
π¨ Emitted Event: ApplicationArchitectureBlueprintCreated¶
| Format | JSON |
| Contains |
- service, bounded_context, trace_id
- Artifact URLs
- Status = completed or partial
- Metadata for downstream agents
{
"event": "ApplicationArchitectureBlueprintCreated",
"service": "BillingService",
"boundedContext": "Billing",
"projectId": "connectsoft-saas",
"traceId": "trace-xyz-999",
"blueprintUrl": "https://.../application-architecture.md",
"useCasesUrl": "https://.../use-cases.yaml",
"portsUrl": "https://.../output-ports.json",
"observabilityUrl": "https://.../application-observability.yaml",
"timestamp": "2025-05-01T19:30:00Z"
}
π¦ Artifact Sync and API Contracts¶
| Interface | Role |
|---|---|
| Artifact Storage API | Publishes blueprint artifacts to blob storage with versioning and metadata |
| ConnectSoft Event Schema Registry | Validates emitted events and supports downstream routing |
| Governance Dashboard | Visualizes blueprint lineage, skill usage, port statistics |
π Coordination Summary¶
flowchart TD
SolutionArchitect -->|SolutionBlueprintCreated| ApplicationArchitect
DomainModeler -->|DomainModelPublished| ApplicationArchitect
ApplicationArchitect -->|ApplicationArchitectureBlueprintCreated| MicroserviceGenerator
ApplicationArchitect -->|...| AdapterGenerator
ApplicationArchitect -->|...| TestGenerator
ApplicationArchitect -->|...| ObservabilityAgent
β Collaboration Principles¶
| Principle | Description |
|---|---|
| Loose Coupling | Communication via events and artifacts, not direct calls |
| Schema-Governed | All interfaces validated via ConnectSoft artifact contracts |
| Traceable | Each transaction logs trace_id, agent_version, and status |
| Composable | Supports partial outputs and staged downstream triggering |
π‘ Observability Hooks¶
The Application Architect Agent emits comprehensive observability data to support:
- Real-time monitoring of agent health and execution flow
- Post-hoc trace analysis of architecture design decisions
- Compliance with ConnectSoftβs audit, retry, and escalation protocols
All telemetry is aligned with OpenTelemetry, and supports dashboards, alerting, and retry heatmaps.
π Emitted Telemetry¶
| Metric | Description |
|---|---|
app_arch_skill_duration_ms{name} |
Duration per skill (e.g., UseCaseDiscoverySkill) |
port_contract_generated_total |
Number of input/output ports declared |
retry_count_by_skill |
How many times a skill retried due to validation or reasoning failure |
span_coverage_percent |
% of use cases with observability span mapping |
blueprint_validation_status |
Final validation result: success, partial, fail |
use_case_count |
Total modeled use cases for the service |
handler_testability_score |
Score based on mocking, isolation, validation contract presence |
π Dashboards¶
| Dashboard | Purpose |
|---|---|
| Blueprint Generation Summary | Track number of use cases, output ports, handlers per service |
| Retry Heatmap | Identify high-failure areas by skill (e.g., port mapping) |
| Span Coverage Grid | Visualize observability completeness |
| Downstream Trigger Map | Track which downstream agents acted on emitted blueprint events |
π§ Human Oversight & Intervention Triggers¶
Although designed to be autonomous, the agent supports manual intervention escalation in edge cases:
| Trigger | Escalation |
|---|---|
| β Excessive retries on use case mapping or port misalignment | Flagged for Solution Architect Agent |
| β Output port overlaps or domain violations | Flagged for Domain Modeler Agent |
| β Critical schema failure in final blueprint | Emits ApplicationArchitectureValidationFailed |
| β Missing or ambiguous actor/event trigger in use case | Pauses generation and surfaces intervention-required status |
All escalations are tagged in observability output and reflected in the eventβs status = "partial" or "manual_review_required".
β Conclusion¶
The Application Architect Agent is a foundational component of the ConnectSoft AI Software Factory.
It transforms high-level service definitions into executable, testable, layered application structures, delivering:
π§ Intelligent design¶
- Use caseβdriven architecture
- Port-based modularity
- DTO-domain boundaries
- Test and telemetry readiness
ποΈ Scaffolding-ready outputs¶
- YAML + JSON + Markdown specifications
- Interface contracts
- Diagrams
- Optional class skeletons
π Full automation compatibility¶
- Downstream microservice, adapter, test generator agents
- Clean Architecture compliance
- Reusability across 1000s of services
π¦ Final Output Package¶
| Artifact | Format |
|---|---|
application-architecture.md |
Markdown |
use-cases.yaml |
YAML |
input-ports.json, output-ports.json |
JSON |
observability.yaml |
YAML |
*.mmd |
Mermaid diagrams |
ApplicationArchitectureBlueprintCreated |
JSON Event |
| (Optional) Class Stubs | DSL / C# |
π― Summary: Why It Matters¶
β
Prevents application-domain-infra entanglement
β
Enables testable, scalable, observable services
β
Shortens ramp-up time for teams and agents
β
Propagates governance through every generated service
β
Makes Clean Architecture enforceable and measurable at scale