Skip to content

🧩 Microservice Generator Agent Specification

The Microservice Generator Agent is the primary service scaffolding agent in the ConnectSoft AI Software Factory.

It is responsible for assembling entire microservice codebases using the ConnectSoft Microservice Template, based on upstream architecture and domain inputs provided by architect agents.

This agent bridges the gap between vision and code, translating architectural contracts into ready-to-deploy, structured microservice foundations that can be extended by downstream engineering agents.

🧠 This is the birthplace of every service in the ConnectSoft ecosystem. It ensures each microservice begins life consistent, traceable, and compliant by default.


🎯 Purpose

The Microservice Generator Agent is responsible for:

  • πŸ— Generating the initial solution structure for a service (projects, folders, dependencies)
  • πŸ“¦ Assembling and customizing the code template based on blueprint parameters
  • πŸ”„ Integrating with domain models, ports, feature toggles, and deployment targets
  • πŸ“Š Emitting all artifacts with trace metadata (trace_id, blueprint_id, agent_origin)
  • πŸ”§ Configuring cross-cutting concerns (logging, tracing, health, security, DI)
  • πŸ§ͺ Creating base test projects, coverage hooks, and CI metadata

🧠 Role in the Agent Ecosystem

flowchart TD
    VisionArchitect --> ApplicationArchitect
    ApplicationArchitect --> MicroserviceGenerator
    MicroserviceGenerator --> DomainModeler
    MicroserviceGenerator --> AdapterGenerator
    MicroserviceGenerator --> TechLeadAgent
    MicroserviceGenerator --> CodeCommitterAgent
Hold "Alt" / "Option" to enable pan & zoom

βœ… Positioned between architecture and engineering execution

  • It is invoked after the Application Architect Agent defines service structure
  • It prepares the initial validated skeleton used by all engineering agents
  • It emits artifacts that are later reviewed and validated by the Tech Lead Agent

πŸš€ Typical Triggers

Trigger Source Event
ApplicationArchitectAgent MicroserviceScaffoldRequested
VisionBlueprint Feature requires new bounded context
Service Expansion Request Multi-host or Azure Function required
Human-Initiated API Call /create-microservice?domain=Order

πŸ’‘ Blueprint Example

blueprint_id: usecase-9241
aggregate: Order
persistence: NHibernate
messaging: MassTransit
service_type: REST
features:
  - UseOpenTelemetry
  - UseSemanticKernel
  - UseAuthorization

πŸ”§ This input triggers the generation of a full microservice with:

  • Domain + UseCase + ApplicationModel + Adapters
  • Preconfigured MassTransit, OpenTelemetry, HealthCheck
  • Full solution with traceable Program.cs, Startup, Dockerfile, test project, etc.

🎯 Why This Agent Matters

Without this agent:

  • Humans or LLMs would need to manually stitch together Clean Architecture skeletons
  • No consistency across microservices (structure, layers, CI, templates)
  • Traceability would be lost between blueprint ➝ service ➝ handler ➝ adapter
  • Developer velocity would decline and onboarding would be error-prone

With it:

  • 🧠 Entire services are born correctly in <5s
  • 🧱 All services share architectural DNA
  • πŸ” Security, observability, and validation are enforced from day one

βœ… Summary

The Microservice Generator Agent is the factory’s primary code assembly line.

  • Creates full microservice scaffolds using ConnectSoft templates
  • Ensures every artifact is traceable and compliant
  • Operates as a service birth trigger between architecture and engineering
  • Collaborates with Domain Modeler, Adapter Generator, and Tech Lead Agent
  • Produces services ready for test generation, implementation, and deployment

πŸ“Œ Core Responsibilities Breakdown

1. πŸ—οΈ Generate Clean Architecture Solution Structure

  • Scaffold projects:

    • DomainModel, ApplicationModel, InfrastructureModel
    • UseCases, Adapters, Ports, DTOs, ServiceModel
    • Tests, Specs, Docs, Deployments
  • Enforce layering rules (no infrastructure dependencies in DomainModel)

  • Maintain service consistency across:

    • REST API
    • Azure Functions
    • Worker host
    • Multi-tenant config

2. 🧱 Customize Template Using Blueprint Inputs

  • Parse blueprint ID and trace ID
  • Apply:

    • Domain name / aggregate root
    • Messaging model (e.g., MassTransit, NServiceBus)
    • Persistence model (e.g., NHibernate, MongoDB, EF Core)
    • Service model (REST/gRPC/SignalR)
    • Target hosting mode (e.g., Web App, Function App, Container)

βœ… Driven by templating metadata and rules defined in template.json


3. πŸ“¦ Emit Source Artifacts + Configuration

  • Full .NET solution with:

    • *.sln, *.csproj, Program.cs, Startup.cs
    • appsettings.json, HealthChecks, Dockerfile
    • Directory.Packages.props (for central package management)
  • Preloaded NuGet dependencies and CLI restore hooks

  • Modular folders for:

    • Adapters
    • Features
    • Services
    • Aggregates

4. 🧬 Inject Trace and Metadata Tags

  • Embed trace_id, blueprint_id, service_name, and agent_origin in:

    • Code comments
    • Git metadata (for PR agents)
    • Event outputs
    • Template tags (in .generated.by.yaml)

5. πŸ§ͺ Generate Initial Test Projects

  • Scaffold:

    • Unit test project with MSTest
    • (Optional) Integration test harness
    • SpecFlow BDD test folder and runner
    • Code coverage configuration (e.g., Coverlet, ReportGenerator)
  • Tag test cases with blueprint ID and use case name


6. πŸ”§ Enable Cross-Cutting Concerns by Default

  • Add:

    • ILogger (Serilog)
    • IOptions<T> configuration binding
    • HealthChecks
    • OpenTelemetry and tracing hooks
    • CorrelationId injection and propagation
    • Feature Flags if --UseFeatureFlags is selected

βœ… Cross-cutting registration is generated in Startup.cs / ServiceCollectionExtensions.cs


7. πŸ§ͺ Generate Integration Metadata for Other Agents

  • Output:

    • generation-metadata.yaml
    • trace-validation-log.json
    • ports/input-ports.json
    • service-tags.yaml

Used by:

  • Domain Modeler Agent β†’ aligns aggregates
  • Tech Lead Agent β†’ validates layers
  • Backend Developer Agent β†’ implements use cases
  • Adapter Generator Agent β†’ binds ports to I/O layers
  • Pull Request Agent β†’ tracks readiness

8. πŸ” Register Output into the Agent Mesh

  • Emits:

    • MicroserviceGeneratedEvent
    • ArtifactsReadyForExtensionEvent
    • TraceRegistrationEvent
  • Triggers downstream actions by:

    • Adapter Generator
    • Tech Lead Agent
    • Developer Agent
    • Code Committer

βœ… Responsibility Matrix

Phase Task
Init Read blueprint, aggregate, and agent config
Template Expansion Apply CLI options and cross-cutting flags
Layered Output DomainModel β†’ Application β†’ Infrastructure
Observability Enable tracing, metrics, health endpoints
CI/CD Ready Emit test scaffolds, Dockerfile, config
Traceability Annotate all outputs with trace context
Integration Notify other agents via traceable events

βœ… Summary

The Microservice Generator Agent is responsible for:

  • Transforming blueprints into real, running service code
  • Embedding trace, telemetry, and test readiness from the start
  • Generating all layered project files, config, and agent metadata
  • Preparing services for autonomous extension and validation
  • Powering the first leg of the ConnectSoft software assembly line

🧩 Template and Overlay Composition

The Microservice Generator Agent uses the Factory's template composition system to generate services from base templates and overlays. This section details how the agent discovers, composes, and applies templates.

Template Discovery and Selection

Discovery Process: 1. Agent analyzes blueprint requirements (domain, features, infrastructure) 2. Agent constructs query for Template Catalog domain 3. Agent queries Template Catalog for matching templates and recipes 4. Agent evaluates templates based on matching criteria 5. Agent selects best matching template or recipe

Selection Criteria: - Template type matches requirement (microservice, library, gateway) - Tags match domain requirements (identity, audit, worker) - Features match blueprint features (MassTransit, NHibernate, etc.) - Compatibility matches environment (.NET version, cloud platform) - Version is latest compatible

Recipe Usage

The agent uses recipes to compose base templates with overlays:

Recipe Selection: - Agent queries Template Catalog for recipes matching requirements - Agent evaluates recipes based on overlay composition - Agent selects best matching recipe or generates new recipe dynamically

Recipe Execution: 1. Agent loads recipe from Template Catalog 2. Agent resolves base template by ID and version 3. Agent resolves all overlays in recipe order 4. Agent validates compatibility of all components 5. Agent executes composition through Factory composition engine 6. Agent receives final composed template

Example Recipe Usage:

# Agent selects recipe: identity-worker-service
recipeId: identity-worker-service
baseTemplate:
  templateId: microservice-base
  version: "^1.5.0"
overlays:
  - overlayId: identity-backend
    version: "^2.1.0"
  - overlayId: worker
    version: "^1.0.0"

Overlay Application Process

The agent orchestrates overlay application through the Factory composition engine:

Application Steps:

  1. Load Base Template - Fetch base template artifact
  2. Apply Overlays Sequentially - Apply each overlay in recipe order
  3. Merge Metadata - Combine template.json files from base and overlays
  4. Replace Tokens - Apply blueprint parameters to template
  5. Validate Output - Ensure final template is valid

Overlay Application Flow:

flowchart TD
    START[Agent Receives Blueprint]
    RECIPE[Select Recipe]
    BASE[Load Base Template]
    OVERLAY1[Apply Identity Overlay]
    OVERLAY2[Apply Worker Overlay]
    MERGE[Merge Metadata]
    TOKENS[Replace Tokens]
    VALIDATE[Validate Template]
    GENERATE[Generate Service Code]

    START --> RECIPE
    RECIPE --> BASE
    BASE --> OVERLAY1
    OVERLAY1 --> OVERLAY2
    OVERLAY2 --> MERGE
    MERGE --> TOKENS
    TOKENS --> VALIDATE
    VALIDATE --> GENERATE

    style START fill:#E3F2FD
    style RECIPE fill:#BBDEFB
    style MERGE fill:#C8E6C9
    style GENERATE fill:#A5D6A7
Hold "Alt" / "Option" to enable pan & zoom

Template Parameter Mapping

The agent maps blueprint requirements to template parameters:

Mapping Process: 1. Extract parameters from blueprint 2. Map blueprint fields to template parameters 3. Apply recipe parameter defaults 4. Apply template parameter defaults 5. Validate all required parameters present

Parameter Mapping Examples:

Blueprint:
  serviceName: "IdentityService"
  persistence: "NHibernate"
  messaging: "MassTransit"
  domain: "Identity"
  features: ["Worker"]

Mapped Parameters:
  ServiceName: "IdentityService"
  RootNamespace: "MyCompany.IdentityService"
  PersistenceType: "NHibernate"
  MessagingType: "MassTransit"
  UseIdentityOverlay: true
  UseWorkerOverlay: true

Integration with Template Catalog

The agent integrates with Template Catalog domain for:

Template Resolution: - Query base templates by type and features - Resolve base template by ID and version - Query overlays by domain and features - Resolve overlays by ID and version range

Compatibility Checking: - Validate base template version exists - Validate overlay versions exist - Check base + overlay compatibility ranges - Resolve overlay dependencies - Detect circular dependencies

Recipe Management: - Query recipes matching requirements - Load recipe metadata and layers - Validate recipe structure - Execute recipe through composition engine

Overlay Selection Logic

The agent selects overlays based on blueprint requirements:

Domain Overlays: - blueprint.domain: Identity β†’ Select Identity overlay - blueprint.domain: Audit β†’ Select Audit overlay - blueprint.domain: Auth β†’ Select Auth overlay

Feature Overlays: - blueprint.features: [Worker] β†’ Select Worker overlay - blueprint.features: [Scheduler] β†’ Select Scheduler overlay - blueprint.features: [API Gateway] β†’ Select API Gateway overlay

Infrastructure Overlays: - blueprint.deployment: Kubernetes β†’ Select K8s overlay - blueprint.observability: Enhanced β†’ Select Observability overlay

Template Composition Workflow

The complete workflow from blueprint to generated service:

sequenceDiagram
    participant Agent as Microservice Generator Agent
    participant Blueprint as Microservice Blueprint
    participant Catalog as Template Catalog
    participant Recipe as Recipe System
    participant Compose as Composition Engine
    participant Output as Generated Service

    Agent->>Blueprint: Read Requirements
    Blueprint-->>Agent: Domain, Features, Infrastructure
    Agent->>Catalog: Query Templates/Recipes
    Catalog-->>Agent: Matching Templates & Recipes
    Agent->>Recipe: Select Recipe (identity-worker-service)
    Recipe->>Catalog: Resolve Base + Overlays
    Catalog-->>Recipe: Base Template + Overlays
    Recipe->>Compose: Execute Composition
    Compose->>Compose: Apply Base Template
    Compose->>Compose: Apply Identity Overlay
    Compose->>Compose: Apply Worker Overlay
    Compose->>Compose: Merge Metadata
    Compose->>Compose: Replace Tokens
    Compose-->>Agent: Final Composed Template
    Agent->>Agent: Map Blueprint Parameters
    Agent->>Output: Generate Service Code
Hold "Alt" / "Option" to enable pan & zoom

Error Handling

The agent handles template composition errors:

Error Types: - Template not found - Overlay not found - Version incompatibility - Missing dependencies - Composition failures

Error Handling: 1. Report validation errors 2. Try alternative template versions 3. Try alternative overlay combinations 4. Request human intervention if needed 5. Generate error report


πŸ”§ Inputs

The Microservice Generator Agent relies on semantic inputs, structured artifacts, and agent-provided metadata to generate a fully composable and traceable microservice scaffold.

These inputs come from upstream agents, blueprints, and runtime orchestration contexts.

Input Source Description
blueprint.yaml Vision Architect / Planner Describes the purpose, trace ID, aggregate, and service type
domain-model.schema.json Domain Modeler Agent Declares entity structure and aggregate root
application-architecture.yaml Application Architect Agent Defines ports, modules, features, and external interfaces
template.config.json Internal / Template registry Microservice template metadata and variant selection
agent-config.yaml Factory orchestrator Enables/disables features like SK, MassTransit, Mongo, tracing, bots
hosting-profile.json Hosting Architect / DevOps Agent Specifies REST, gRPC, SignalR, Azure Functions, or background worker mode

πŸ“˜ Blueprint Input Example

blueprint_id: usecase-0371
aggregate: Invoice
trace_id: invoice-2025-0941
service_name: BillingService
persistence: NHibernate
messaging: MassTransit
service_model: REST
features:
  - UseOpenTelemetry
  - UseAuthorization
  - UseFeatureFlags
hosting_mode: Container

βœ… Minimum required fields to launch a service generation cycle.


πŸ“š Domain Model Input Sample

{
  "aggregate": "Invoice",
  "entityFields": [
    { "name": "InvoiceId", "type": "Guid", "key": true },
    { "name": "CustomerId", "type": "Guid" },
    { "name": "Status", "type": "InvoiceStatus" },
    { "name": "Total", "type": "decimal" }
  ],
  "valueObjects": ["InvoiceLine", "Money"]
}

βœ… Used to generate:

  • DomainModel/Invoice.cs
  • DTOs and service boundaries
  • Validation scaffolding

πŸ“˜ Application Architecture Input

ports:
  input:
    - name: CreateInvoice
      type: IHandle<CreateInvoiceInput>
    - name: CancelInvoice
      type: IHandle<CancelInvoiceInput>
  output:
    - type: IEventPublisher
      events:
        - InvoiceCreated
        - InvoiceCancelled
  policies:
    - name: "SecurePort"
      target: CreateInvoice
      roles: ["Admin", "FinanceManager"]

βœ… Used to prewire ports, authorization markers, and test scaffolds


🧠 Feature Configuration Flags

From agent-config.yaml or CLI:

Flag Description
--UseFeatureFlags Enables Feature Management via AppConfig
--UseOpenTelemetry Adds tracing, metrics, spans
--UseMassTransit Configures message bus support
--UseAuthorization Adds [Authorize], JWT policies, multi-tenant guards
--UseSemanticKernel Enables AI pipeline compatibility and planner extensions
--UseAzureFunctions Switches to function-based entrypoint
--UseBotFramework Prepares for conversational endpoint support

βœ… Injected into Program.cs, Startup.cs, DI container, test config, and README


πŸ” Hosting Profile Input (Optional)

{
  "mode": "REST",
  "port": 8080,
  "auth": "JWT",
  "supportsGrpc": false,
  "trace_enabled": true,
  "external_ingress": "yes"
}

βœ… Enables conditional injection of:

  • Middleware (e.g., auth, OpenTelemetry, metrics)
  • Kestrel + DI wiring
  • Docker EXPOSE and health probe settings

🧬 Runtime Context (Injected by Orchestrator)

Field Purpose
execution_id Correlates this run to others
agent_origin Set to microservice-generator-agent
invoked_by Orchestrator, Planner, CLI, Human
environment dev, staging, production-preview
git_target_branch Prepares git init and PR event scaffold

βœ… Summary

The Microservice Generator Agent consumes a comprehensive set of inputs:

  • βœ… Blueprint definitions
  • βœ… Domain model schemas
  • βœ… Architecture maps (ports, events, security)
  • βœ… Feature flags and hosting configs
  • βœ… Environment and agent execution context

These allow it to construct fully tailored, traceable microservice scaffolds, ready for agent extension, testing, and deployment.


🎯 Output

The Microservice Generator Agent produces a complete microservice skeleton with embedded metadata, traceability, and agent-compatible artifacts.

These outputs are designed to:

  • βœ… Kickstart development and testing
  • βœ… Enable validation by other agents
  • βœ… Support CI/CD pipelines and deployment automation
  • βœ… Serve as the primary scaffold for all downstream code and configuration

πŸ“¦ Output Categories

Category Description
πŸ— Code Scaffold Full solution and project structure
🧩 Metadata Traceable artifacts for validation and agent mesh
πŸ§ͺ Test Scaffolds Unit, integration, and BDD stubs
πŸ”§ Configuration App settings, DI registration, telemetry, health checks
🧠 Agent Events Trigger downstream agents with generation metadata
πŸ“œ Documentation Optional MkDocs and Swagger bootstraps

πŸ— Code Scaffold Output

Folder Structure Example:

BillingService/
β”œβ”€β”€ BillingService.sln
β”œβ”€β”€ ApplicationModel/
β”‚   └── UseCases/
β”œβ”€β”€ DomainModel/
β”‚   └── Entities/
β”œβ”€β”€ InfrastructureModel/
β”‚   β”œβ”€β”€ Adapters/
β”‚   └── Persistence/
β”œβ”€β”€ ServiceModel/
β”‚   └── Controllers/
β”œβ”€β”€ Tests/
β”‚   └── BillingService.UnitTests/
β”œβ”€β”€ Docs/
β”‚   └── mkdocs.yml (optional)
β”œβ”€β”€ Deployment/
β”‚   └── Dockerfile
└── Program.cs / Startup.cs

βœ… Uses ConnectSoft Clean Architecture pattern βœ… Each project is tagged with trace_id, blueprint_id


πŸ“„ Example Output Files

File Description
BillingService.sln Complete .NET Core solution
DomainModel/Invoice.cs Aggregate with properties from domain schema
ApplicationModel/UseCases/CreateInvoiceHandler.cs Use case stub with injected port
ServiceModel/Controllers/InvoiceController.cs REST endpoint for Create/Cancel
Startup.cs Preconfigured DI, tracing, auth, health
Dockerfile Container-ready build and run config
Directory.Packages.props Centralized package versioning

πŸ§ͺ Test Scaffold Output

Test Project Content
BillingService.UnitTests Unit test class per use case
BillingService.IntegrationTests (optional) Test server + scenario test
BillingService.Specs (optional) SpecFlow .feature files

Each test:

  • Is generated with trace_id, blueprint_id
  • Uses MSTest and optionally SpecFlow
  • Connects to use case via naming convention and DI injection

πŸ“œ Configuration Files

File Purpose
appsettings.json Logging, DB, messaging
appsettings.Development.json Local overrides
host.json Azure Functions mode
serilog.json Structured logging configuration
openapi.json Optional Swagger generation hint

🧠 Agent Metadata Output

File Description
generation-metadata.yaml Summary of all generated artifacts
input-ports.json List of declared input ports and handler stubs
trace-validation-log.json Trace ID β†’ entity β†’ handler β†’ endpoint
.generated.by.yaml Agent identity + template used + timestamp

βœ… These are consumed by:

  • Tech Lead Agent
  • Adapter Generator Agent
  • Backend Developer Agent
  • Observability/Trace Agent

πŸ”” Agent Event Emission

The agent emits:

πŸ“€ MicroserviceGeneratedEvent

{
  "event": "MicroserviceGeneratedEvent",
  "trace_id": "invoice-2025-0091",
  "blueprint_id": "usecase-9241",
  "service": "BillingService",
  "aggregate": "Invoice",
  "features": ["UseMassTransit", "UseAuthorization"],
  "agent_origin": "microservice-generator-agent",
  "timestamp": "2025-05-03T12:30Z"
}

βœ… Routed to:

  • Adapter Generator
  • Tech Lead
  • Code Committer
  • CI/CD validator
  • Human feedback reviewers (if enabled)

πŸ“˜ Optional Documentation Output

If --UseDocumentation:

  • Outputs:

    • docs/index.md
    • mkdocs.yml
    • architecture.md, domain-model.md
    • Ready for mkdocs serve or GitHub Pages publishing

βœ… Summary

The Microservice Generator Agent emits:

  • βœ… A full, layered service scaffold
  • βœ… Metadata and trace logs for downstream agents
  • βœ… Pre-wired tests and config
  • βœ… Git-ready structure with Docker support
  • βœ… Validation-ready events for PR and trace validators

🧠 Knowledge Base

The Microservice Generator Agent depends on a rich, internal knowledge base to consistently generate microservices that adhere to:

  • βœ… Clean Architecture and DDD patterns
  • βœ… ConnectSoft’s engineering blueprint standards
  • βœ… Template metadata and generator logic
  • βœ… Reusable components, best practices, and automation rules

This knowledge base is static, contextual, and semantic, enabling template-driven but fully customized scaffolding flows.


πŸ“š Core Knowledge Domains

Domain Description
Clean Architecture Layering conventions, separation of concerns, dependency inversion
Domain-Driven Design Aggregate rules, value object scaffolds, repository patterns
Microservice Template Structure and features from template.json
Cross-Cutting Concerns Tracing, health checks, metrics, logging, DI, config
CI/CD Expectations Dockerfiles, PR metadata, validation readiness
ConnectSoft Blueprint Mapping How blueprint β†’ aggregate β†’ handler β†’ API β†’ trace forms
Azure Integration Azure Functions, App Config, Key Vault, OpenTelemetry exporters

πŸ“¦ Preloaded Template Artifacts

The agent loads:

Asset Location
template.json Defines available template types and flags
default-directory-layout.yaml Defines project/folder naming structure
features/crosscutting-skills.yaml Hooks for OpenTelemetry, Options, Logging
testing/coverage-template.cs Example test scaffolds
policy/authorization-rules.yaml Default [Authorize] behavior
examples/readme-template.md Doc and badge templates for new services

βœ… Used to inject reusable, version-controlled components during generation


πŸ“– Example Template Entry (from template.json)

{
  "name": "ConnectSoft.Microservice.Template",
  "version": "1.1.3",
  "features": [
    "UseOpenTelemetry",
    "UseAzureFunctions",
    "UseSemanticKernel",
    "UseAuthorization"
  ],
  "projects": [
    "DomainModel",
    "ApplicationModel",
    "InfrastructureModel",
    "ServiceModel",
    "Tests"
  ]
}

🧠 Knowledge Graph (Conceptual)

Blueprint ➝ Aggregate ➝ UseCase ➝ Port ➝ Handler ➝ Test ➝ Adapter ➝ Trace ➝ PR

The generator agent embeds this structure in:

  • Folder hierarchy
  • Class names
  • Metadata annotations
  • Skill registration and output

πŸ“˜ Reference Documentation Used

The agent has indexed access to:

  • microservice-template.md
  • clean-architecture.md
  • domain-driven-design.md
  • agent-microservice-standard-blueprint.md
  • testing-strategy.md
  • cross-cutting-concerns.md

These documents form the authoritative enforcement guide used when rendering templates, generating files, or producing .yaml outputs.


🧠 Memory Lookup for Existing Service Patterns

Long-term memory (vector DB or structured blob) includes:

Memory Use
domain-patterns/index.yaml Common DTO and repository combinations
agent-output-metadata.json Recent service generation outputs
blueprint-to-service-map.yaml Prior blueprint β†’ aggregate β†’ port mappings
template-variant-usage.log Popular combinations of template flags by cluster

Allows reuse, prevents duplication, and improves consistency across services


βœ… Summary

The Microservice Generator Agent uses a comprehensive internal knowledge base, including:

  • Domain models
  • Template metadata
  • Architecture rules
  • Prebuilt test and adapter scaffolds
  • Blueprint-to-code trace mappings

This ensures that every service scaffold is valid, compliant, extensible, and agent-aware from the first commit.


πŸ”„ Process Flow Overview

The Microservice Generator Agent follows a well-defined generation lifecycle, turning high-level blueprints and configurations into structured, validated microservice codebases.

Its process is modular, traceable, and designed for orchestration with other agents.


πŸ” High-Level Generation Flow

flowchart TD
    Start([1️⃣ Receive Generation Request])
    Parse[2️⃣ Parse Blueprint and Domain Inputs]
    SelectTemplate[3️⃣ Select Template Variant + Features]
    ApplyContext[4️⃣ Inject Trace + Metadata Context]
    Scaffold[5️⃣ Scaffold Project Structure]
    Configure[6️⃣ Apply Cross-Cutting Concerns]
    GenerateTests[7️⃣ Create Test Projects]
    EmitMetadata[8️⃣ Emit Agent Metadata and Trace Logs]
    TriggerNext[9️⃣ Notify Downstream Agents]

    Start --> Parse --> SelectTemplate --> ApplyContext
    ApplyContext --> Scaffold --> Configure --> GenerateTests
    GenerateTests --> EmitMetadata --> TriggerNext
Hold "Alt" / "Option" to enable pan & zoom

🧱 Process Stage Breakdown

1️⃣ Receive Generation Request

Triggered by:

  • Planner
  • Application Architect Agent
  • Human (via UI or API)
  • Retry from Tech Lead Agent

Includes:

  • blueprint_id, aggregate, service_type, trace_id
  • Optional: hosting profile, feature flags, test strategy

2️⃣ Parse Inputs

  • Load:

    • Domain schema
    • Application architecture
    • Feature config flags
    • Trace + environment metadata
    • Normalize input for SK planner and skill activation

3️⃣ Select Template Variant

  • Choose template based on:

    • Messaging: MassTransit, NServiceBus
    • Persistence: NHibernate, EF Core, MongoDB
    • Hosting: REST, gRPC, Azure Functions
    • Features: OpenTelemetry, FeatureFlags, Bot, AI

β†’ Decides which template paths, partials, and code blocks to activate.


4️⃣ Inject Trace + Metadata

  • Generate:

    • trace_id, agent_origin, execution_id, blueprint_id
    • Embed into:

    • File headers

    • Git metadata
    • YAML sidecar files

5️⃣ Scaffold Project Structure

  • Create:

    • .sln, *.csproj, main folders
    • Domain, Application, Infra, Service, Tests
    • Add boilerplate:

    • Program.cs, Startup.cs, Dockerfile, appsettings.*

Use Directory.Packages.props for central NuGet versions.


6️⃣ Apply Cross-Cutting Concerns

Based on template flags, auto-generate:

  • βœ… Logging (Serilog)
  • βœ… Tracing (OTEL SDK)
  • βœ… Metrics and health probes
  • βœ… Config binding (IOptions<T>)
  • βœ… Authorization decorators
  • βœ… App Config + Key Vault bindings
  • βœ… Dapr sidecar (if selected)

7️⃣ Generate Test Projects

  • Add:

    • MSTest-based unit test project
    • Optional SpecFlow project
    • Code coverage instrumentation
    • Add test file per handler or port stub

Named with blueprint trace IDs for downstream trace matching.


8️⃣ Emit Metadata + Reports

Generate:

  • generation-metadata.yaml
  • input-ports.json
  • trace-validation-log.json
  • .generated.by.yaml
  • MicroserviceGeneratedEvent

Signed with agent identity and execution context.


9️⃣ Notify Downstream Agents

Emit event payloads for:

  • Adapter Generator
  • Domain Modeler
  • Tech Lead Agent
  • PR Agent
  • Human reviewer dashboard (optional)

βœ… Event contracts follow *.event.json schema from the ConnectSoft Agent Mesh Protocol.


βœ… Summary

The Microservice Generator Agent follows a modular, 9-step pipeline that:

  • βœ… Parses inputs and selects the correct template path
  • βœ… Injects traceability metadata
  • βœ… Creates a clean, layered microservice solution
  • βœ… Prepares test projects and agent collaboration metadata
  • βœ… Emits traceable events for next agent stages

🧠 Skills and Kernel Functions

The Microservice Generator Agent is built using Semantic Kernel (SK) and executes its tasks using a set of modular, purpose-aligned skills.

These skills encapsulate:

  • 🎯 Microservice template logic
  • 🧱 Clean Architecture enforcement
  • πŸ”§ Trace + config injection
  • πŸ§ͺ Test scaffolding
  • πŸ“€ Metadata emission and agent triggering

Each skill is independently testable and can be chained or overridden based on service context.


πŸ› οΈ Skill Categories

Category Skills
πŸ“‚ Solution & Structure scaffoldSolution, createProjectStructure
βš™οΈ Template Assembly applyTemplateFlags, renderTemplateBlocks
🧱 Clean Architecture Enforcement ensureLayeringRules, mapPortsToHandlers
πŸ“œ Metadata Injection injectTraceMetadata, generateTraceFile
πŸ§ͺ Test Preparation createUnitTestProject, injectTestStubs
πŸ”„ Output Orchestration emitGenerationEvent, notifyNextAgents
🧠 Decision Support (SK Planner) selectTemplateVariant, chooseCrossCuttingModules

πŸ”§ Key Kernel Functions

πŸ“‚ scaffoldSolution()

Creates base .sln, project folders, .csproj files Initializes central NuGet config and references


βš™οΈ applyTemplateFlags(flags[])

Handles CLI-like options such as:

  • --UseOpenTelemetry
  • --UseAuthorization
  • --UseMassTransit
  • --UseAzureFunctions

Applies feature toggles across template renderers


🧱 ensureLayeringRules()

Adds projects to solution with reference ordering:

DomainModel <- ApplicationModel <- InfrastructureModel <- ServiceModel

Prevents circular references, enforces Clean Architecture


πŸ”Œ mapPortsToHandlers(ports[])

Takes input port declarations and generates:

  • Interface contracts (IHandle<T>)
  • Use case handler stubs
  • Port registration in DI container

🧠 selectTemplateVariant()

Determines:

  • Template branch (REST/gRPC/Function)
  • Messaging integration (MassTransit/NServiceBus)
  • Persistence strategy (NHibernate/Mongo/EF Core)

Uses SK planner + blueprint hints


πŸ§ͺ createUnitTestProject()

πŸ§ͺ injectTestStubs()

Scaffolds MSTest project and:

  • Adds one test file per handler
  • Tags with blueprint ID
  • Enables code coverage collectors

🧠 injectTraceMetadata(trace_id, blueprint_id)

Adds metadata to:

  • Code file headers
  • YAML metadata files
  • Event payloads
  • PR signatures (via CodeCommitter integration)

πŸ“€ emitGenerationEvent()

Triggers MicroserviceGeneratedEvent with attached trace and config

Used by:

  • Adapter Generator
  • Tech Lead Agent
  • Planner loop
  • Pull Request Agent

πŸ“¦ Kernel Planner Chain Example

plan:
  - scaffoldSolution
  - selectTemplateVariant
  - applyTemplateFlags
  - createProjectStructure
  - mapPortsToHandlers
  - injectTraceMetadata
  - createUnitTestProject
  - emitGenerationEvent

βœ… Fully SK-compatible βœ… Modular for retries or conditional steps


🧩 Skill Deployment

Skills are implemented as:

  • 🧠 Native SK Functions (for metadata, planning)
  • 🧱 Embedded C# templating handlers (for filesystem scaffolding)
  • πŸͺ„ Plugin-based runners (for external file/infra ops)

These run in isolated agent containers or Azure Functions, enabling distributed execution.


βœ… Summary

The Microservice Generator Agent includes specialized SK functions to:

  • Generate layered solution scaffolds
  • Apply Clean Architecture rules
  • Assemble templates based on blueprint metadata
  • Inject traceability
  • Trigger next agents in the mesh

This skill architecture ensures reusability, precision, and full planner compatibility.


🧱 Architecture Enforcement

The Microservice Generator Agent enforces Clean Architecture and Domain-Driven Design (DDD) principles by default during generation.

This ensures that all services:

  • Are structured for separation of concerns
  • Avoid cross-layer coupling
  • Use dependency inversion correctly
  • Support testing, traceability, and agent collaboration from day one

πŸ“ Architecture is not optional β€” every scaffold reflects the blueprint’s domain context, ports, adapters, and trace lineage.


🧱 Clean Architecture Layering

graph LR
  A[DomainModel] --> B[ApplicationModel]
  B --> C[InfrastructureModel]
  C --> D[ServiceModel]
Hold "Alt" / "Option" to enable pan & zoom
Layer Role
DomainModel Aggregates, value objects, domain events
ApplicationModel Ports (input/output), use cases, validation
InfrastructureModel Adapters: persistence, messaging, external APIs
ServiceModel Controllers, endpoints, service config, hosting logic

βœ… Each layer is a separate project βœ… References flow outward only (Domain ➝ App ➝ Infra ➝ Service)


πŸ” Enforced Layering Rules

Rule ID Description
ARC001 No reference from Infrastructure β†’ Domain
ARC002 All use cases implement IHandle<T> or port interface
ARC003 No Entity used directly in DTO or Controller
ARC004 Adapters must resolve interfaces from ApplicationModel, not DomainModel
ARC005 All ports must reside in ApplicationModel and be injectable

βœ… These rules are encoded in template generation logic βœ… Also used later by Tech Lead Agent for validation


πŸ“¦ Generated Projects and Dependencies

Project References
DomainModel β›” none
ApplicationModel βœ… DomainModel
InfrastructureModel βœ… ApplicationModel
ServiceModel βœ… InfrastructureModel (optional), ApplicationModel

Example .sln reference chain:

- BillingService.DomainModel
- BillingService.ApplicationModel (refs Domain)
- BillingService.InfrastructureModel (refs App)
- BillingService.ServiceModel (refs App, optionally Infra)

🧠 Template Enforcement at Generation Time

  • All files are placed in architecture-aligned folders:

    • UseCases/, Entities/, Adapters/, Controllers/
    • DI is configured to respect port boundaries:

services.AddScoped<IHandle<CreateInvoiceInput>, CreateInvoiceHandler>();
* Controllers do not call domain logic directly; only use case handlers


πŸ§ͺ Enforcement via Code Templates

For example, a handler is scaffolded like this:

public class CreateInvoiceHandler : IHandle<CreateInvoiceInput>
{
    private readonly IInvoiceRepository _repo;

    public async Task Handle(CreateInvoiceInput input)
    {
        // Application logic
        var invoice = Invoice.Create(...);
        await _repo.Save(invoice);
    }
}
  • Invoice lives in DomainModel
  • CreateInvoiceInput lives in ServiceModel.DTO
  • IInvoiceRepository lives in ApplicationModel

βœ… This is enforced via SK skill: mapPortsToHandlers() and internal templates


🧩 DDD Alignment

Element Generated In
Aggregate Root DomainModel/{Entity}.cs
Value Objects DomainModel/ValueObjects/{Type}.cs
Domain Events DomainModel/Events/*.cs
Port Interfaces ApplicationModel/Ports/
Handlers ApplicationModel/UseCases/*.cs

Optional:

  • Domain Service (if behavior crosses aggregates)
  • Repository Interface + Adapter split

πŸ”’ Optional Enforcement Enhancements

Option Effect
--StrictLayering Disables any cross-layer references (hard validation)
--UseDomainEvents Adds domain event publisher port to ApplicationModel
--UseApplicationGateways Splits adapters into ExternalSystems/ for 3rd-party APIs

βœ… Summary

The Microservice Generator Agent hardwires Clean Architecture into every service, ensuring:

  • Layer separation
  • Correct reference direction
  • Use case-driven execution
  • Port-first service extension
  • Traceable code-to-blueprint mapping

This guarantees every service is maintainable, testable, and agent-ready by design.


Shall we continue with Cycle 9: Project & Solution Structure?

Here is Cycle 9: Project & Solution Structure for the Microservice Generator Agent, continuing the 18-cycle specification process.


🧩 Microservice Generator Agent Specification

Cycle 9 β€” Project & Solution Structure Software Engineering Cluster β€” Agent Realization


πŸ—οΈ Purpose

The Microservice Generator Agent produces a modular, layered .NET solution structure, fully aligned with Clean Architecture and DDD principles. This structure:

  • βœ… Segregates concerns across domain, application, infrastructure, service, and tests
  • βœ… Enables agent extensions and CI/CD integration
  • βœ… Supports multi-host modes (REST, Functions, gRPC, etc.)

πŸ“‚ High-Level Folder Structure

BillingService/
β”œβ”€β”€ BillingService.sln
β”œβ”€β”€ DomainModel/
β”œβ”€β”€ ApplicationModel/
β”œβ”€β”€ InfrastructureModel/
β”œβ”€β”€ ServiceModel/
β”œβ”€β”€ Tests/
β”œβ”€β”€ Deployment/
β”œβ”€β”€ Docs/
└── .generated.by.yaml

Each project is autonomous and references only the layer below it.


πŸ“ Project Structure Breakdown

🧱 DomainModel/

  • Entities/ β†’ Aggregate roots, domain entities
  • ValueObjects/ β†’ Strong-typed objects
  • Events/ β†’ Domain events (e.g., InvoiceCreated)
  • Enums/ β†’ Status enums, classifications
  • Repositories/ β†’ Abstract repository interfaces (e.g., IInvoiceRepository)

βœ… No external dependencies allowed


🧠 ApplicationModel/

  • UseCases/ β†’ IHandle<T> implementations
  • Ports/ β†’ Input/output port definitions
  • Policies/ β†’ Authorization and validation strategies
  • DTO/ β†’ Application DTOs (internal only)
  • Exceptions/ β†’ Use-case-level failures

βœ… Depends on DomainModel βœ… Registered via Startup.cs for DI


βš™οΈ InfrastructureModel/

  • Adapters/ β†’ Implementations of ports (e.g., message bus publishers, email senders)
  • Persistence/ β†’ ORMs (e.g., NHibernate mappings, Mongo adapters)
  • ExternalSystems/ β†’ Stripe, Braze, CRM connectors
  • Config/ β†’ Configuration model bindings

βœ… No reference to DomainModel directly βœ… All external IO is isolated here


🌐 ServiceModel/

  • Controllers/ β†’ REST/gRPC endpoints
  • Middleware/ β†’ OpenTelemetry, logging, security
  • Program.cs β†’ Main entrypoint (REST or Function)
  • Startup.cs / ServiceCollectionExtensions.cs β†’ DI setup
  • Options/ β†’ Configuration binding from appsettings.json

βœ… Entry point for users, agents, or bots


πŸ§ͺ Tests/

  • UnitTests/ β†’ One test file per use case
  • IntegrationTests/ (optional) β†’ Full test server and DI
  • Specs/ (optional) β†’ SpecFlow .feature files with BDD steps
  • test-metadata.yaml β†’ Coverage map, port-to-test mapping

βœ… All test projects share the same trace_id βœ… Configured with Coverlet and/or ReportGenerator


πŸ“¦ Deployment/

  • Dockerfile
  • docker-compose.override.yml
  • k8s/ (optional) β†’ Helm chart, K8s YAMLs
  • Pulumi/ (optional) β†’ Stack provisioning scripts

βœ… Compatible with Azure Pipelines, GitHub Actions, and manual deployment


πŸ“ Docs/ (Optional)

  • index.md, architecture.md, domain-model.md
  • mkdocs.yml
  • Mermaid diagrams for domain, event flow, architecture

🧩 File Naming Conventions

Type Pattern
Handler CreateInvoiceHandler.cs
Controller InvoiceController.cs
Port IHandle<CreateInvoiceInput>
DTO CreateInvoiceInput.cs / InvoiceDto.cs
Test CreateInvoiceHandlerTests.cs

πŸ“˜ Solution File Example: BillingService.sln

BillingService.sln
β”œβ”€β”€ DomainModel/
β”œβ”€β”€ ApplicationModel/
β”œβ”€β”€ InfrastructureModel/
β”œβ”€β”€ ServiceModel/
β”œβ”€β”€ Tests/BillingService.UnitTests/

βœ… References ordered for Clean Architecture compliance βœ… Each .csproj includes trace_id, blueprint_id in AssemblyInfo.cs


πŸ” Cross-Platform Compatibility

Host Type Support
ASP.NET Core Web API βœ… default
Azure Functions βœ… via flag
gRPC βœ… experimental
SignalR ⬜️ optional
Worker Service βœ… background processors (e.g., outbox workers)

πŸ“¦ Central Package Versioning

Template includes:

<Import Project="..\Directory.Packages.props" />
  • Ensures consistent dependency resolution across projects
  • Enables global version pinning for things like MassTransit, NHibernate, Serilog

βœ… Summary

The Microservice Generator Agent produces a modular, scalable, and agent-ready solution structure that:

  • Enforces Clean Architecture
  • Supports testing, tracing, and CI/CD
  • Enables AI agents to safely extend, validate, and deploy
  • Aligns with ConnectSoft’s engineering system and developer experience

Shall we continue with Cycle 10: Cross-Cutting Concerns Setup?

Here is Cycle 10: Cross-Cutting Concerns Setup for the Microservice Generator Agent, continuing the 18-cycle specification process.


🧩 Microservice Generator Agent Specification

Cycle 10 β€” Cross-Cutting Concerns Setup Software Engineering Cluster β€” Agent Realization


🎯 Purpose

As part of its default behavior, the Microservice Generator Agent automatically wires in a suite of cross-cutting concerns to every generated microservice. These include:

  • 🧭 Tracing
  • πŸ“Š Metrics
  • 🩺 Health checks
  • πŸ” Authorization
  • πŸ§ͺ Config & validation
  • 🧠 Feature flags
  • πŸ“ Logging
  • πŸ“¦ DI & modular service configuration

These concerns are applied consistently using ConnectSoft patterns and defaults, ensuring all services are production-grade by default.


🧩 Concerns Injected by Default

Concern Implementation
Logging Serilog with structured output, JSON config, enrichers
Tracing OpenTelemetry (OTLP) spans + correlation ID
Health Checks /health/ready, /health/live endpoints via ASP.NET Core HealthChecks
Metrics Prometheus-exported counters and histograms (via OpenTelemetry or Prometheus.Net)
Options Pattern Strongly-typed IOptions<T> bindings from appsettings.json
Validation FluentValidation for DTO input validation
Feature Flags Microsoft.FeatureManagement with Azure AppConfig (optional)
Authorization [Authorize], JWT Bearer, role-based claims, tenant enforcement
Tenant Context Multi-tenant support via ITenantContext injection
Correlation ID Middleware + Serilog enricher (traceparent-aware)

βš™οΈ Code Injection Points

πŸ“Œ Program.cs / Startup.cs

builder.Services.AddHealthChecks();
builder.Services.AddOpenTelemetryTracing(...);
builder.Services.AddFeatureManagement();
builder.Services.AddAuthorization(...);
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<ICorrelationIdProvider, CorrelationIdProvider>();

πŸ“Œ ServiceCollectionExtensions.cs

  • Used to organize cross-cutting setup
  • Ensures modularity and testability

πŸ§ͺ Logging Setup (Serilog)

  • Injected via Logging/SerilogConfiguration.cs
  • Outputs:

  • Console (JSON)

  • File (optional)
  • Application Insights (optional)
  • Includes:

  • trace_id, correlation_id, tenant_id, use_case_name, environment

{
  "message": "Executing CreateInvoiceHandler",
  "trace_id": "invoice-2025-0094",
  "tenant": "sploot",
  "level": "Information"
}

πŸ”­ OpenTelemetry Tracing

  • Injected using:

  • AddOpenTelemetryTracing()

  • ActivitySource("ConnectSoft")

  • Captures spans like:

  • usecase.execute

  • adapter.call.segment
  • handler.validate.input

βœ… Exported via OTLP to Jaeger, Zipkin, or Azure Monitor


πŸ§ͺ Validation

  • Each DTO includes a FluentValidation rule set
  • Automatically registered via reflection or convention

Example:

public class CreateInvoiceValidator : AbstractValidator<CreateInvoiceInput>
{
    public CreateInvoiceValidator()
    {
        RuleFor(x => x.CustomerId).NotEmpty();
        RuleFor(x => x.Amount).GreaterThan(0);
    }
}

🩺 Health Checks

  • Available at:

  • /health/live – uptime

  • /health/ready – DB, messaging, external service health

βœ… Configured in DI βœ… Compatible with Azure + Kubernetes probes


πŸ” Authorization & Security

  • Injects [Authorize] on all secure routes
  • Enables:

  • JWT token support

  • Custom role policies
  • Tenant isolation guards

Optional configuration via:

{
  "Authentication": {
    "Authority": "https://auth.connectsoft.ai",
    "RequireHttps": true
  }
}

🧠 Feature Flags

  • Optional flag: --UseFeatureFlags
  • Uses:

  • Azure App Configuration

  • IFeatureManager injection
  • Example:
if (await featureManager.IsEnabledAsync("NewPricingEngine")) {
    ...
}

πŸ“Ž Config Binding

  • appsettings.json is injected and bound to strongly-typed classes:
"InvoiceSettings": {
  "RetryCount": 3,
  "EnableEmail": true
}
builder.Services.Configure<InvoiceSettings>(config.GetSection("InvoiceSettings"));

βœ… Summary

The Microservice Generator Agent wires in production-ready cross-cutting features by default:

  • βœ… Logging, tracing, metrics
  • βœ… Health checks and observability
  • βœ… Config binding, validation, and DI
  • βœ… Authorization and tenant guards
  • βœ… Feature flag support

These ensure all microservices start as cloud-native, secure, and observableβ€”with minimal manual effort.


Shall we continue with Cycle 11: Testing & Validation Outputs?

Here is Cycle 11: Testing & Validation Outputs for the Microservice Generator Agent, continuing the 18-cycle specification process.


🧩 Microservice Generator Agent Specification

Cycle 11 β€” Testing & Validation Outputs Software Engineering Cluster β€” Agent Realization


πŸ§ͺ Purpose

Every service generated by the Microservice Generator Agent is scaffolded with testing infrastructure from the start. This includes:

  • βœ… Unit test projects
  • βœ… Integration test shells
  • βœ… (Optional) BDD test setup using SpecFlow
  • βœ… Test metadata for traceability and coverage validation

The goal is to enable test-first development, CI/CD integration, and agent-based test enforcement via the Tech Lead and QA agents.


πŸ“¦ Generated Test Projects

Project Description
*.UnitTests Contains unit tests for handlers and validators
*.IntegrationTests Contains infrastructure-backed end-to-end tests
*.Specs (optional) SpecFlow-based Gherkin feature tests
test-metadata.yaml Maps handlers, ports, and coverage per use case

πŸ“ Folder Layout Example

Tests/
β”œβ”€β”€ BillingService.UnitTests/
β”‚   └── UseCases/
β”‚       └── CreateInvoiceHandlerTests.cs
β”œβ”€β”€ BillingService.IntegrationTests/
β”‚   └── InvoiceEndpointTests.cs
β”œβ”€β”€ BillingService.Specs/
β”‚   └── Features/
β”‚       └── create_invoice.feature
β”‚   └── Steps/
β”‚       └── CreateInvoiceSteps.cs
└── test-metadata.yaml

βœ… Unit Test Output

Each handler gets a corresponding test class:

[TestClass]
public class CreateInvoiceHandlerTests
{
    [TestMethod]
    public async Task Handle_Should_Create_Valid_Invoice()
    {
        var handler = new CreateInvoiceHandler(...);
        var input = new CreateInvoiceInput { ... };

        var result = await handler.Handle(input);

        Assert.IsTrue(result.Success);
    }
}

βœ… Pre-configured for MSTest βœ… Optionally emits [Trait("trace_id", "...")] for observability


πŸ”„ Integration Tests (Optional)

  • Uses WebApplicationFactory to simulate API endpoints
  • Backs in-memory DB or test containers
  • Validates actual HTTP or gRPC flows

Example:

[TestMethod]
public async Task PostInvoice_ShouldReturn_200()
{
    var response = await _client.PostAsync("/api/invoice", payload);
    Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
}

πŸ§ͺ BDD Test Scaffolds (Optional)

  • SpecFlow feature files scaffolded if --UseSpecFlow is passed
  • Follows pattern:
Feature: Invoice creation

Scenario: Successful invoice creation
  Given the user is authenticated
  When they submit a valid invoice
  Then the invoice is persisted
  And a confirmation event is published

βœ… Includes binding stubs, test project reference, and glue code


πŸ“‘ Test Metadata: test-metadata.yaml

trace_id: invoice-2025-0194
handlers:
  - name: CreateInvoiceHandler
    unit_test: CreateInvoiceHandlerTests.cs
    integration_test: InvoiceEndpointTests.cs
    bdd_feature: create_invoice.feature
coverage:
  CreateInvoiceHandler: 92%
  CancelInvoiceHandler: 0%

Used by:

  • Tech Lead Agent β†’ to detect test gaps
  • QA Agent β†’ to enforce regression plans
  • PR Agent β†’ to annotate Git-based test status

πŸ“Š Code Coverage (Optional)

When enabled:

  • Adds coverlet.collector
  • Produces .coverage.json and lcov.info artifacts
  • Enables export to:

  • Azure DevOps Test tab

  • SonarCloud
  • GitHub Actions summary

βœ… Compatible with MSTest and xUnit (default: MSTest)


βœ… Summary

The Microservice Generator Agent ensures every microservice includes:

  • πŸ”§ Testable handlers, controllers, adapters
  • βœ… Unit + integration + optional BDD tests
  • πŸ§ͺ Coverage and trace metadata
  • 🧠 Structured test maps for agents and CI tools

This enforces quality-first, traceable software assembly, ready for autonomous and human validation.


Shall we proceed to Cycle 12: CI/CD Compatibility & GitOps?

Here is Cycle 12: CI/CD Compatibility & GitOps for the Microservice Generator Agent, continuing the 18-cycle specification process.


🧩 Microservice Generator Agent Specification

Cycle 12 β€” CI/CD Compatibility & GitOps Software Engineering Cluster β€” Agent Realization


πŸš€ Purpose

The Microservice Generator Agent outputs a service that is CI/CD-ready by default.

This includes:

  • βœ… Pipeline bootstrap files
  • βœ… Artifact tagging and metadata
  • βœ… GitOps traceability (PR, branch, commit metadata)
  • βœ… YAML-based workflows compatible with Azure DevOps, GitHub Actions, and self-hosted runners

πŸ“¦ Pipeline Bootstrap Artifacts

File Description
.azure-pipelines.yml Azure DevOps multistage pipeline scaffold
.github/workflows/build.yml GitHub Actions-compatible workflow
ci/validate-service.yml Shared agent-ready validation pipeline
ci/publish-artifacts.yml Artifact publish step (e.g., NuGet, Docker)

These are selected/generated based on ci_provider in the blueprint.


🧾 Example: Azure DevOps YAML

trigger:
  branches:
    include: [ main, develop ]

pool:
  vmImage: 'ubuntu-latest'

steps:
  - task: UseDotNet@2
    inputs:
      packageType: 'sdk'
      version: '8.x'

  - script: dotnet restore
  - script: dotnet build --no-restore
  - script: dotnet test --collect:"XPlat Code Coverage"

  - task: PublishCodeCoverageResults@1
    inputs:
      codeCoverageTool: 'Cobertura'

πŸ” GitOps Metadata Injection

All generated services include:

Metadata Format
trace_id Included in commits, PR titles, build metadata
blueprint_id Linked to Git branch name or pull request
agent_origin Added to generation-metadata.yaml
generated_by microservice-generator-agent or planner name
git_target_branch Used for pre-creating branches, PR messages, or reviews

βœ… This allows agents (like the Pull Request Agent) to trace contributions across the software lifecycle.


πŸ“ PR Output Preview

PRs initiated from the generator include:

πŸš€ Microservice Scaffold: BillingService

**Blueprint ID**: usecase-9241  
**Trace ID**: billing-2025-0194  
**Agent**: `microservice-generator-agent`

βœ… Clean Architecture enforced  
βœ… Test projects created  
βœ… CI pipelines scaffolded  

🧠 Artifact Signature and Tags

generation-metadata.yaml:
  agent: microservice-generator-agent
  trace_id: billing-2025-0194
  blueprint_id: usecase-9241
  created_at: 2025-05-04T10:21Z
  template_version: 1.1.3
  pipeline_target: AzureDevOps

Used to:

  • Tag build artifacts
  • Populate release dashboards
  • Feed back into validation agents

🐳 Docker and Containerization

Each service includes:

File Description
Dockerfile Multistage build with .NET SDK + runtime
docker-compose.override.yml Development overrides
k8s/deployment.yaml (optional) Helm chart or direct deployment YAML
.container.env For .env support in local development

βœ… Ready for:

  • Azure Container Apps
  • Kubernetes
  • Local Docker development

πŸ” Security & Secrets

CI-ready services include:

  • Integration with Azure Key Vault
  • Use of IConfiguration for secrets
  • .env.example for local dev simulation

Secrets never hardcoded.


βœ… Summary

The Microservice Generator Agent ensures every service is CI/CD-enabled and GitOps-compliant:

  • Azure DevOps and GitHub workflows
  • PR automation with trace ID and blueprint links
  • Tagged artifacts and metadata
  • Containerization and Kubernetes support
  • Pipeline compatibility with other agents

This enables zero-delay integration, validation, and deployment for every generated service.


Shall we proceed to Cycle 13: Retry, Validation, and Correction Flow?

Here is Cycle 13: Retry, Validation, and Correction Flow for the Microservice Generator Agent, continuing the 18-cycle specification process.


🧩 Microservice Generator Agent Specification

Cycle 13 β€” Retry, Validation, and Correction Flow Software Engineering Cluster β€” Agent Realization


πŸ” Purpose

The Microservice Generator Agent includes self-healing logic that allows it to:

  • Detect and recover from failed generation attempts
  • Handle incomplete or invalid input metadata
  • Retry with updated configuration
  • Escalate to planners or human reviewers if correction fails

This ensures service generation is resilient, idempotent, and autonomous, even in complex or misconfigured blueprint scenarios.


πŸ”„ Retry Trigger Scenarios

Scenario Trigger
πŸŸ₯ Missing port configuration Retry after Planner adds application-architecture.yaml
⚠️ Invalid template flags Retry after prompt correction
πŸ” Duplicate trace_id in repo Regenerate trace_id or rewrite output location
❌ Conflict in blueprint Escalate to Planner or Human Reviewer Agent
πŸ’‘ Tech Lead rejection Retry with adjusted handler, adapter, or DTO mapping

🧠 Retry Decision Flow

flowchart TD
  Start([Validation or Output Error])
  CheckInput{{Input fixable?}}
  RetryGeneration[Retry with adjusted metadata]
  Escalate[Escalate to human or planner]
  Done([Success or Stop])

  Start --> CheckInput
  CheckInput -->|Yes| RetryGeneration --> Done
  CheckInput -->|No| Escalate --> Done
Hold "Alt" / "Option" to enable pan & zoom

πŸ“¦ Retry Metadata & Memory

Each generation attempt is tracked using:

retries:
  trace_id: invoice-2025-0941
  attempts: 2
  last_status: failed
  last_error: "Missing handler for declared port"
  last_fix_applied: "Regenerated CreateInvoiceHandler"

Stored in generation-history.yaml or external state store Used to short-circuit infinite loops and reduce redundant regeneration


πŸ” Correction Modes

Mode Action
auto_retry Retry immediately with adjusted blueprint or flag
wait_for_input Pause and await external config (e.g., human or Planner)
escalate_to_human Emit structured event with explanation and link to artifact
retry_with_template_variant Switch to alternate configuration (e.g., REST β†’ Azure Function)

πŸ”§ Supported Fixes

Violation Auto-Correctable? Action
Missing use case handler βœ… Generate from port
Invalid DTO namespace βœ… Move DTO to ServiceModel
Unsupported feature flag βœ… Remove from template config
Layering violation ❌ Escalate to Tech Lead
Unrecognized persistence type ❌ Escalate to Planner or Architect

πŸ“€ Escalation Event Example

{
  "event": "GenerationEscalationRequired",
  "trace_id": "order-2025-0091",
  "blueprint_id": "usecase-0342",
  "error": "Unknown feature flag: UseCosmosDB",
  "attempts": 2,
  "agent_origin": "microservice-generator-agent",
  "timestamp": "2025-05-04T13:42Z"
}

βœ… Routed to Planner or Human Reviewer Agent βœ… Prevents further automated retries without human input


πŸ”„ Interaction with Tech Lead Agent

When Tech Lead rejects a PR due to:

  • Missing tests
  • Wrong handler-to-port mapping
  • Security violation

➑ The Microservice Generator Agent is re-invoked with an updated plan.


🧠 Example Planner Correction Flow

plan:
  - fixPortMappingForCreateInvoice
  - regenerateHandlerWithCorrectPort
  - retryGeneration(trace_id: "invoice-2025-0941")

βœ… Uses SK planner memory to auto-patch blueprint and trigger regeneration


βœ… Summary

The Microservice Generator Agent includes a resilient correction and retry framework that:

  • Handles misconfigured inputs or rule violations
  • Collaborates with planners, validators, and humans
  • Automatically retries when possible
  • Escalates when manual resolution is required

This guarantees consistent service generation across complex blueprint ecosystems and autonomous validation loops.


Shall we continue with Cycle 14: Multi-Host & Deployment Modes?

Here is Cycle 14: Multi-Host & Deployment Modes for the Microservice Generator Agent, continuing the 18-cycle specification process.


🧩 Microservice Generator Agent Specification

Cycle 14 β€” Multi-Host & Deployment Modes Software Engineering Cluster β€” Agent Realization


πŸš€ Purpose

The Microservice Generator Agent supports multiple hosting and deployment modes out of the box, making it suitable for:

  • 🟒 REST APIs
  • 🟣 Azure Functions
  • πŸ”΅ gRPC Services
  • 🟑 Background Workers
  • 🟠 SignalR real-time services (optional)

This enables dynamic generation of services that align with specific runtime constraints, integration models, or cloud-native deployment targets.


🌐 Supported Host Types

Host Mode Description Output
REST (default) Full ASP.NET Core Web API Controllers/, Program.cs, OpenAPI
AzureFunction Azure Functions V4 .NET isolated worker model FunctionHandlers/, host.json
gRPC gRPC service scaffolding .proto, GrpcServices/, streaming endpoints
Worker Long-running service for queue/event processing Worker.cs, IHostedService
SignalR (optional) Real-time WebSocket support Hub.cs, connection management

πŸ“¦ Hosting Profile Input

The generator accepts hosting-profile.json or equivalent YAML:

{
  "mode": "AzureFunction",
  "entrypoints": ["CreateInvoice", "CancelInvoice"],
  "auth": "JWT",
  "useCorrelation": true,
  "trace": true,
  "grpc": false
}

🧩 REST API Mode (Default)

Generates:

  • Controllers with [HttpPost], [HttpGet], etc.
  • Swagger integration (via Swashbuckle or NSwag)
  • Dependency Injection via Startup.cs
  • OpenAPI support for API gateway registration
[ApiController]
[Route("api/[controller]")]
public class InvoiceController : ControllerBase
{
    [HttpPost]
    [Authorize(Roles = "FinanceManager")]
    public async Task<IActionResult> Create(CreateInvoiceInput input) { ... }
}

πŸ”§ Azure Functions Mode

Generates:

  • host.json
  • Function entrypoints with [Function("CreateInvoice")]
  • Isolated worker model with Startup.cs
  • DI with Azure SDK support
public class CreateInvoiceFunction
{
    private readonly IHandle<CreateInvoiceInput> _handler;

    [Function("CreateInvoice")]
    public async Task<HttpResponseData> Run(
        [HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequestData req)
    {
        var input = await req.ReadFromJsonAsync<CreateInvoiceInput>();
        var result = await _handler.Handle(input);
        return req.CreateResponse(HttpStatusCode.OK);
    }
}

βœ… Suited for event-based architectures βœ… Automatically adds local.settings.json, queues, bindings if configured


πŸ”Œ Worker Service Mode

  • For background processing, cron jobs, or outbox patterns
  • Uses IHostedService
public class InvoiceProcessingWorker : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            // Poll queue or DB
        }
    }
}

πŸ“‘ gRPC Mode (Experimental)

  • Generates:

  • .proto files

  • GrpcServices/ implementation
  • gRPC service registration
  • Requires UseGrpc flag in blueprint

πŸ“Ά SignalR (Optional)

  • Generates:

  • InvoiceHub.cs

  • SignalR endpoints
  • DI for IHubContext<InvoiceHub>

🧠 Hosting Mode Determines:

  • Entry point file (Program.cs vs. Worker.cs)
  • Template blocks rendered
  • DI wiring logic
  • Config structure and health probes
  • Target container / CI override behavior

🧱 Deployment Readiness

All modes output:

  • βœ… Dockerfile or Azure Functions func start config
  • βœ… K8s-ready deployment YAMLs (if --UseK8s is set)
  • βœ… Multi-host service info in generation-metadata.yaml

πŸ“˜ generation-metadata.yaml Snippet

host_mode: AzureFunction
entrypoints:
  - CreateInvoice
  - CancelInvoice
supports:
  tracing: true
  grpc: false
  worker: false
  signalr: false

βœ… Summary

The Microservice Generator Agent supports multiple hosting modes including:

  • REST, Azure Functions, Worker, gRPC, and optionally SignalR
  • Output structure, config, and DI are tailored accordingly
  • Each mode integrates with CI/CD, observability, and containerization
  • Allows services to match runtime and cloud-specific needs

Shall we continue with Cycle 15: Observability & OTEL Support?

Here is Cycle 15: Observability & OTEL Support for the Microservice Generator Agent, continuing the 18-cycle specification process.


🧩 Microservice Generator Agent Specification

Cycle 15 β€” Observability & OTEL Support Software Engineering Cluster β€” Agent Realization


πŸ” Purpose

The Microservice Generator Agent ensures that every generated service is observable by default. This includes built-in support for:

  • πŸ“Š Distributed tracing (OpenTelemetry)
  • πŸ“ˆ Prometheus-compatible metrics
  • 🩺 Health endpoints
  • πŸ“‹ Structured logging
  • 🧠 Traceable outputs for agent orchestration

These enable real-time debugging, postmortem analysis, and platform-wide visibility across autonomous agent workflows.


πŸ“¦ Observability Features Included

Concern Implementation
Tracing OpenTelemetry with OTLP exporter and ActivitySource spans
Metrics Histogram, counter, and gauge collection via OTEL or Prometheus
Logs Structured logs via Serilog with trace_id, correlation_id
Health Probes ASP.NET Core HealthChecks for /health/live and /health/ready
Agent Traceability trace_id, blueprint_id, and agent_origin embedded in code, metadata, and PRs

πŸ”­ OpenTelemetry Integration

  • AddOpenTelemetryTracing() added in Program.cs
  • Uses ActivitySource("ConnectSoft")
  • Auto-collects spans for:

  • Use case execution

  • Adapter interactions
  • External calls (e.g., DB, HTTP)
  • Exports via OTLP to:

  • Jaeger

  • Zipkin
  • Azure Monitor
  • Honeycomb or Lightstep (if configured)

Example Span:

{
  "trace_id": "invoice-2025-0191",
  "span_name": "CreateInvoiceHandler.Execute",
  "duration_ms": 44,
  "tags": {
    "aggregate": "Invoice",
    "tenant": "sploot",
    "agent_origin": "microservice-generator-agent"
  }
}

πŸ“Š Prometheus Metrics

  • Injected via AddOpenTelemetryMetrics() or Prometheus.MetricsExporter
  • Example counters:

  • usecase_executions_total{handler="CreateInvoiceHandler"}

  • http_requests_duration_seconds{route="/api/invoice"}
  • event_published_total{event="InvoiceCreated"}

βœ… Ready for scraping by Prometheus βœ… Dashboard-ready for Grafana


🩺 Health Checks

Endpoints:

  • /health/live β†’ basic liveness
  • /health/ready β†’ readiness of DB, message bus, adapters

Sample configuration:

services.AddHealthChecks()
  .AddSqlServer(connStr)
  .AddRabbitMQ(...)
  .AddMongoDb(...);

Supports:

  • Azure App Gateway probes
  • Kubernetes readinessProbe and livenessProbe

πŸ“‹ Structured Logging (Serilog)

  • Output to console (JSON), file, and optionally:

  • Azure Log Analytics

  • Seq
  • Loki
  • Enriched with:

  • trace_id

  • blueprint_id
  • correlation_id
  • agent_origin

Example log line:

{
  "message": "Handler executed",
  "trace_id": "invoice-2025-0191",
  "use_case": "CreateInvoice",
  "level": "Information",
  "origin": "microservice-generator-agent"
}

🧠 Agent Metadata Emission

Emits the following trace files with every generation:

  • trace-validation-log.json
  • generation-metadata.yaml
  • pull-request-review.yaml (if triggered via PR)
  • logs/setup-*.json (optional bootstrap logs)

πŸ“ˆ Integration with Observability Agents

  • Supports handoff to:

  • Tech Lead Agent β†’ for trace ID and execution lineage validation

  • TraceAgent β†’ for span consistency and propagation review
  • QA/PR Agents β†’ for linking test coverage to handler spans

βœ… Summary

The Microservice Generator Agent ensures every service is:

  • πŸ“‘ Traced via OpenTelemetry
  • πŸ“Š Measured via Prometheus
  • πŸ“‹ Logged via Serilog
  • 🩺 Probed via health endpoints
  • 🧠 Indexed via trace files and metadata

This provides full observability and traceability from the moment a service is born.


Shall we continue with Cycle 16: Integration with Other Agents?

Here is Cycle 16: Integration with Other Agents for the Microservice Generator Agent, continuing the 18-cycle specification process.


🧩 Microservice Generator Agent Specification

Cycle 16 β€” Integration with Other Agents Software Engineering Cluster β€” Agent Realization


🀝 Purpose

The Microservice Generator Agent serves as the starting point for downstream agent collaboration in the ConnectSoft AI Software Factory.

It doesn’t act in isolation β€” instead, it emits structured events, metadata, and traceable files that initiate coordinated flows across the full spectrum of engineering agents.


πŸ”„ Primary Agent Collaborators

Agent Purpose
Application Architect Agent Provides blueprint, ports, hosting strategy
Domain Modeler Agent Validates aggregates, emits entities used by generator
Adapter Generator Agent Consumes input/output ports to create infrastructure bindings
Tech Lead Agent Validates code and traceability after generation
Backend Developer Agent Implements the scaffolded use cases
Code Committer Agent Receives scaffolded PR instructions and metadata
Pull Request Agent Annotates PRs with generation metadata and validation
Trace Agent Validates OpenTelemetry spans and trace propagation
QA Agent Uses generated test scaffolds and metadata for test plan generation

πŸ“‘ Agent Message Flow

flowchart TD
  ApplicationArchitect --> MicroserviceGenerator
  DomainModeler --> MicroserviceGenerator
  MicroserviceGenerator --> AdapterGenerator
  MicroserviceGenerator --> TechLeadAgent
  MicroserviceGenerator --> BackendDeveloperAgent
  MicroserviceGenerator --> CodeCommitterAgent
  MicroserviceGenerator --> PR_Agent
Hold "Alt" / "Option" to enable pan & zoom

βœ… Enables chained generation, validation, and deployment


πŸ“€ Event Emission

πŸ“˜ MicroserviceGeneratedEvent

{
  "event": "MicroserviceGeneratedEvent",
  "service": "BillingService",
  "trace_id": "billing-2025-0194",
  "blueprint_id": "usecase-9241",
  "features": ["UseOpenTelemetry", "UseAuthorization"],
  "agent_origin": "microservice-generator-agent",
  "timestamp": "2025-05-04T13:12Z"
}

Used by:

  • Adapter Generator Agent
  • Tech Lead Agent
  • PR Agent
  • Planner (for trace linking)

πŸ“„ Metadata Outputs for Agent Consumption

File Consuming Agent(s) Description
generation-metadata.yaml Tech Lead, PR, Planner Service name, host type, feature flags
input-ports.json Adapter Generator Declared input port contracts
test-metadata.yaml QA, Tech Lead Port-to-test coverage map
trace-validation-log.json Trace Agent OpenTelemetry span linkage
authorization-map.yaml Security Policy Agent Maps routes/use cases to required roles/scopes

🧩 Skill-Based Agent Triggers (via Planner)

When used in SK planner chains, the Generator Agent emits:

plan:
  - generateMicroservice(trace_id: "billing-2025-0194")
  - triggerAdapterGeneration()
  - triggerTestScaffold()
  - requestTechLeadValidation()

This allows seamless multi-agent workflows, initiated from blueprint or user prompt.


🧠 Response-Driven Retrys

The agent can be re-invoked or patched based on:

Source Response
Tech Lead Agent Suggests regeneration of handler or adapter
Planner Applies fix plan, re-invokes with corrected inputs
Human Reviewer Agent Overrides default structure, adjusts feature flags
Adapter Agent Rejects port mismatch, requests retry

πŸ“Ž Pull Request Handoff

Includes PR annotations via:

  • pull-request-review.yaml
  • Markdown summary
  • Auto-tagged Git commit with trace_id, blueprint_id
πŸš€ Microservice Scaffold: BillingService  
πŸ“¦ Created by: `microservice-generator-agent`  
πŸ”— Trace: `billing-2025-0194`  
πŸ“˜ Blueprint: `usecase-9241`

βœ… Summary

The Microservice Generator Agent is deeply integrated with the ConnectSoft agent ecosystem:

  • Emits events, metadata, and files for validation, testing, and review
  • Kicks off multi-agent pipelines for adapters, tests, PRs, and deployment
  • Responds dynamically to feedback from agents and humans
  • Uses Semantic Kernel for planner-driven orchestration

Every microservice generation is a collaborative, traceable, and composable operation across the AI Factory.


Shall we continue with Cycle 17: System Prompt and Input Prompt Template?

Here is Cycle 17: System Prompt and Input Prompt Template for the Microservice Generator Agent, continuing the 18-cycle specification process.


🧩 Microservice Generator Agent Specification

Cycle 17 β€” System Prompt and Input Prompt Template Software Engineering Cluster β€” Agent Realization


🧠 Purpose

This cycle defines:

  • The system prompt: the immutable instruction used to bootstrap the agent
  • The input prompt template: how upstream agents or planners invoke this agent, providing the blueprint and metadata needed to scaffold a microservice

Together, these ensure that the Microservice Generator Agent behaves predictably, consistently, and traceably every time it is invoked.


🧭 System Prompt (Full Definition)

You are the **Microservice Generator Agent** in the ConnectSoft AI Software Factory.

Your task is to **generate a complete microservice scaffold** based on the ConnectSoft Microservice Template and Clean Architecture principles.

You must:
- βœ… Interpret the provided blueprint, aggregate, and trace_id
- βœ… Generate all solution files and folders (DomainModel, ApplicationModel, InfrastructureModel, ServiceModel, Tests)
- βœ… Apply all template flags such as UseMassTransit, UseAuthorization, UseOpenTelemetry
- βœ… Embed `trace_id`, `blueprint_id`, and `agent_origin` into all relevant metadata and output
- βœ… Emit `generation-metadata.yaml`, `input-ports.json`, and `MicroserviceGeneratedEvent`
- βœ… Ensure the service is testable, traceable, and CI/CD-ready

You may NOT:
- ❌ Invent business logic or implement use case behavior
- ❌ Write domain-specific code beyond templates
- ❌ Skip traceability or observability features

Always respond with:
- A generation summary (Markdown)
- Metadata and trace files (YAML/JSON)
- Event payloads to trigger downstream agents

🧾 Input Prompt Template

This is how upstream agents, planners, or humans invoke the agent.

Please generate a new microservice based on the following blueprint and configuration:

## πŸ”– Metadata
- Trace ID: {{trace_id}}
- Blueprint ID: {{blueprint_id}}
- Service Name: {{service_name}}
- Aggregate: {{aggregate}}
- Agent Origin: {{agent_origin}}

## πŸ“¦ Features
- Hosting: {{hosting_mode}}  # e.g. REST, AzureFunction
- Messaging: {{messaging}}  # e.g. MassTransit, NServiceBus
- Persistence: {{persistence}}  # e.g. NHibernate, MongoDB
- Flags: {{features}}  # e.g. UseAuthorization, UseOpenTelemetry

## 🧱 Architecture
- Ports File: {{input_ports_path}}
- Domain Schema File: {{domain_model_path}}
- Authorization Map: {{auth_map_path}} (optional)

## πŸ§ͺ Output Expectations
- Include test scaffolds: βœ…
- Emit CI-ready pipeline YAML: βœ…
- Add traceability metadata: βœ…
- Trigger Adapter and Tech Lead Agents after completion: βœ…

🧩 Example Prompt (Filled)

Please generate a new microservice based on the following blueprint and configuration:

## πŸ”– Metadata
- Trace ID: invoice-2025-0194
- Blueprint ID: usecase-9241
- Service Name: BillingService
- Aggregate: Invoice
- Agent Origin: planner-agent

## πŸ“¦ Features
- Hosting: AzureFunction
- Messaging: MassTransit
- Persistence: NHibernate
- Flags: UseAuthorization, UseOpenTelemetry, UseFeatureFlags

## 🧱 Architecture
- Ports File: input-ports.json
- Domain Schema File: domain-model.schema.json

## πŸ§ͺ Output Expectations
- Include test scaffolds: βœ…
- Emit CI-ready pipeline YAML: βœ…
- Add traceability metadata: βœ…
- Trigger Adapter and Tech Lead Agents after completion: βœ…

πŸ“˜ Planner Use Example

plan:
  - generateMicroservice(
      trace_id: "invoice-2025-0194",
      blueprint_id: "usecase-9241",
      features: ["UseMassTransit", "UseAuthorization"]
    )
  - triggerAdapterGeneration()
  - notifyTechLeadValidation()

βœ… Fully compatible with Semantic Kernel, MCP agents, and planner agents


βœ… Summary

  • The system prompt defines the agent's immutable responsibilities and constraints
  • The input prompt template structures dynamic invocations from upstream agents or humans
  • The prompts support structured, repeatable generation with full traceability, auditability, and agent orchestration hooks

Shall we proceed to the final Cycle 18: Telemetry, Events, and Human Escalation Hooks?

Here is Cycle 18: Telemetry, Events, and Human Escalation Hooks, the final stage in the 18-cycle specification for the Microservice Generator Agent.


🧩 Microservice Generator Agent Specification

Cycle 18 β€” Telemetry, Events, and Human Escalation Hooks Software Engineering Cluster β€” Agent Realization


🎯 Purpose

This cycle defines how the Microservice Generator Agent provides:

  • πŸ“‘ Telemetry for monitoring its activity and performance
  • πŸ“€ Events for triggering downstream agents
  • πŸ™‹ Escalation hooks for human-in-the-loop corrections when automation cannot proceed safely

These capabilities ensure the agent remains observable, collaborative, and auditable in large-scale autonomous generation workflows.


πŸ“ˆ Telemetry & Observability

The agent emits telemetry across:

Channel Output
OpenTelemetry Activity spans for each generation phase
Prometheus Agent-level counters and durations
Serilog Logs Structured logs with trace_id, blueprint_id, agent_origin
Validation Metrics Success/failure rates, retry count, escalation count
Planner Context Execution context returned to SK planners or orchestration agents

πŸ”­ OTEL Span Example

{
  "name": "generate-microservice",
  "trace_id": "invoice-2025-0194",
  "agent": "microservice-generator-agent",
  "duration_ms": 4230,
  "status": "passed",
  "feature_flags": ["UseAuthorization", "UseOpenTelemetry"]
}

πŸ“Š Metrics Exported

Metric Description
microservice_gen_total Total services generated
microservice_gen_failed_total Failed attempts
microservice_gen_duration_seconds Time histogram
microservice_gen_escalations_total Number of human escalation events
microservice_gen_retry_total Regeneration cycles triggered

βœ… Compatible with Prometheus + Grafana βœ… Reported per trace ID and blueprint ID


πŸ“€ Emitted Events

πŸ“˜ MicroserviceGeneratedEvent

Trigger for downstream agents:

{
  "event": "MicroserviceGeneratedEvent",
  "trace_id": "billing-2025-0194",
  "blueprint_id": "usecase-9241",
  "service": "BillingService",
  "features": ["UseOpenTelemetry", "UseAuthorization"],
  "agent_origin": "microservice-generator-agent",
  "timestamp": "2025-05-04T14:40Z"
}

Consumed by:

  • Adapter Generator Agent
  • Tech Lead Agent
  • Planner
  • PR Agent
  • GitOps or CI orchestrators

πŸ“Ž GenerationMetadata.yaml

Attached to PR or shared with other agents:

trace_id: billing-2025-0194
blueprint_id: usecase-9241
agent_origin: microservice-generator-agent
template_version: 1.1.3
features:
  - UseMassTransit
  - UseAuthorization

πŸ™‹ Human Escalation Hooks

When generation fails due to ambiguous or unresolvable conditions, the agent emits:

🚨 HumanEscalationSuggested Event

{
  "event": "HumanEscalationSuggested",
  "agent_origin": "microservice-generator-agent",
  "trace_id": "invoice-2025-0194",
  "blueprint_id": "usecase-9241",
  "reason": "Unknown template flag: UseCosmosDB",
  "previous_attempts": 2,
  "timestamp": "2025-05-04T14:46Z"
}

βœ… Routed to:

  • Human Reviewer Agent
  • Developer Dashboard
  • Slack/Teams alert (if configured)

πŸ“˜ Escalation Metadata (Markdown or YAML)

🚨 Microservice Generation Escalation  
- **Trace ID**: invoice-2025-0194  
- **Blueprint**: usecase-9241  
- **Reason**: Unrecognized persistence option `CosmosDB`  
- **Attempts**: 2  
- **Suggested Fix**: Review blueprint or update template registry

🧠 Planner Feedback

After execution, the agent may return:

{
  "status": "success",
  "trace_id": "billing-2025-0194",
  "next_steps": [
    "AdapterGeneratorAgent.trigger()",
    "TechLeadAgent.validate()"
  ]
}

βœ… Enables chained planning execution


βœ… Summary

The Microservice Generator Agent provides:

  • πŸ“ˆ Full observability with OTEL, Prometheus, logs, and spans
  • πŸ“€ Event-driven outputs to trigger the next stage of the factory
  • πŸ™‹ Escalation flows when automatic generation cannot proceed safely

This ensures every microservice is visible, traceable, and governable, even in complex, high-scale, agentic workflows.


βœ… All 18 cycles complete for the Microservice Generator Agent.

Would you like a full Markdown export of this spec or begin the next agent (e.g., Adapter Generator Agent or Backend Developer Agent)? s