Skip to content

🧠 Backend Developer Agent Specification

πŸ” Introduction

The Backend Developer Agent is the execution engine for functional implementation in the ConnectSoft software factory.

Where the Microservice Generator Agent scaffolds the structure, and the Domain Modeler Agent defines aggregates β€” the Backend Developer Agent is responsible for implementing use case handlers, populating DTOs, and ensuring business-aligned backend logic adheres to Clean Architecture.

It acts as the developer persona, translating architectural contracts into concrete code across the ApplicationModel and ServiceModel layers.


🎯 Purpose

The Backend Developer Agent transforms abstract definitions into real backend logic:

  • βœ… Implements handler classes that fulfill blueprint-defined input ports
  • βœ… Injects and wires domain services and repositories correctly
  • βœ… Enriches and validates DTOs
  • βœ… Applies trace metadata and error handling patterns
  • βœ… Works closely with the Tech Lead Agent to pass architectural validation
  • βœ… Produces testable, compliant, and agent-compatible backend logic

🧱 It turns β€œblueprint + port + domain” into functional service behavior β€” clean, layered, and traceable.


🧠 Strategic Role in the Engineering Flow

flowchart TD
  MicroserviceGenerator --> BackendDeveloper
  DomainModeler --> BackendDeveloper
  AdapterGenerator --> BackendDeveloper
  BackendDeveloper --> TechLead
  BackendDeveloper --> CodeCommitter
  BackendDeveloper --> QAAgent
Hold "Alt" / "Option" to enable pan & zoom
  • Receives ports, aggregates, and service scaffolds
  • Emits fully wired handlers with test stubs
  • Triggers downstream test and PR activity
  • Enables full-circle agentic delivery

πŸ›  Agent Responsibilities Summary

Domain Responsibility
ApplicationModel Generate and populate handler logic from port definitions
DTO Layer Create and annotate input/output models
Validation Enforce input constraints and structure via FluentValidation
Traceability Annotate code and events with trace_id, blueprint_id
Authorization Ensure security via [Authorize], tenant enforcement, and scoped roles
Testing Emit test scaffolds and annotations to QA/Test Agents
Refactorability Allow Tech Lead to suggest improvements and retry logic

πŸ‘€ Emulated Persona

This agent behaves like a senior backend engineer who:

  • Understands Clean Architecture
  • Collaborates with the tech lead and architect
  • Produces consistent, testable, and readable code
  • Avoids cross-layer violations or architecture shortcuts
  • Documents their changes clearly for downstream agents

🧠 What This Agent Does Not Do

  • ❌ Define domain aggregates (done by Domain Modeler Agent)
  • ❌ Generate entire services (done by Microservice Generator Agent)
  • ❌ Create adapters for external systems (done by Adapter Generator Agent)
  • ❌ Decide architectural structure (done by Application Architect Agent)

πŸ“ Use Case Lifecycle Placement

The Backend Developer Agent typically acts after generation, before commit:

sequenceDiagram
    participant Generator
    participant BackendDev
    participant TechLead
    participant Committer

    Generator->>BackendDev: Emit use case port and structure
    BackendDev->>BackendDev: Generate handler + DTO
    BackendDev-->>TechLead: Send for validation
    TechLead-->>Committer: Approve and route for PR
Hold "Alt" / "Option" to enable pan & zoom

βœ… Summary

The Backend Developer Agent is the bridge between blueprint and backend logic, producing:

  • Clean handler implementations
  • Validated DTOs
  • Authorization and trace hooks
  • Compliant code ready for PR, test, and observability

It ensures the software factory executes features as designed β€” traceable, testable, and production-ready.


🎯 Primary Responsibility

The Backend Developer Agent is responsible for taking blueprint-defined use cases and port contracts and turning them into complete, validated, and traceable handler implementations, DTOs, and backend logic.

It ensures the backend is:

  • βœ… Functionally correct
  • βœ… Layered per Clean Architecture
  • βœ… Testable and observable
  • βœ… Secure and traceable
  • βœ… Ready for Tech Lead validation and PR creation

πŸ“‹ Responsibility Matrix

Responsibility Area Description
🧱 Use Case Handler Implementation Implement IHandle<T> or port-mapped handler with domain orchestration
πŸ“¦ DTO Creation and Mapping Create Input/Output models with validation rules
πŸ§ͺ Validation Logic Attach FluentValidation validators for all DTOs
🧠 Traceability Injection Ensure trace_id, correlation_id, and blueprint_id are injected and logged
πŸ” Authorization Enforcement Decorate secure endpoints or handlers with [Authorize], roles, and tenant checks
πŸ§ͺ Test Stub Emission Generate unit test shell with test case starter for each handler
πŸ”§ Code Conventions Compliance Match Clean Architecture folder layout, naming, and DI injection strategy
πŸ“€ Output Signature Attach trace metadata, comments, and output event to trigger QA/Test/PR agents

πŸ›  Key Functions Performed

1. implementHandler(CreateInvoiceInput)

  • Writes logic in CreateInvoiceHandler.cs
  • Injects IInvoiceRepository or service ports
  • Uses aggregate root from DomainModel
  • Returns result object

2. generateDTO(CreateInvoiceInput)

  • Places in ServiceModel/DTO
  • Adds [Required], MaxLength, etc. annotations
  • Supports versioned DTO if --EnableApiVersioning

3. generateValidator(CreateInvoiceValidator)

  • Places in ApplicationModel/Validation
  • Implements AbstractValidator<CreateInvoiceInput>

4. applySecurity(CreateInvoiceHandler)

  • Adds [Authorize(Roles = "...")] based on authorization-map.yaml
  • Injects ITenantContext and verifies TenantId matches

5. emitTestScaffold()

  • Adds CreateInvoiceHandlerTests.cs in Tests/UnitTests
  • Prepares for MSTest + Coverlet
  • Tagged with trace_id and use case name

6. annotateWithTrace()

  • Adds header comments:
// Generated by: backend-developer-agent
// Blueprint ID: usecase-9241
// Trace ID: invoice-2025-0194
  • Injects trace info into logs and telemetry spans

πŸ” Optional Responsibilities (Based on Blueprint Flags)

Feature Additional Action
UseOpenTelemetry Instrument handler with ActivitySource
UseFeatureFlags Wrap feature logic with IFeatureManager
UseBotFramework Enables endpoint stubs for AI-triggered backends
EnableSoftDeletes Injects metadata markers into domain commands

βœ… Summary

The Backend Developer Agent is accountable for:

  • Clean, complete, and secure handler code
  • Valid DTOs and validators
  • Traceable outputs and metadata
  • Agent-consumable test scaffolds
  • Code that is compliant, observable, and production-grade

This makes it the core executor of functional service logic in the autonomous factory.


πŸ“¦ Core Inputs

The Backend Developer Agent consumes structured inputs from upstream agents (blueprint, domain, architecture, and trace), enabling it to generate complete handler logic, DTOs, validators, and trace-aware output files.

It operates only when a valid context exists, and is strictly driven by explicit service blueprint metadata and port definitions.

Input Source Agent Description
blueprint.yaml Application Architect Agent Defines the service name, trace ID, use cases, roles, hosting
input-ports.json Microservice Generator Agent Declares port interface contracts (e.g., IHandle<CreateInvoiceInput>)
domain-model.schema.json Domain Modeler Agent Entity structure, aggregate roots, and types
authorization-map.yaml Security Policy Agent Roles, scopes, and tenant rules for each use case
generation-metadata.yaml Generator Agent Flags like UseOpenTelemetry, UseFeatureFlags, etc.
trace-validation-log.json Trace Agent / Generator Previously assigned trace identifiers
test-metadata.yaml Tech Lead / Generator Existing or missing test scaffolds for handlers
service structure Inferred from solution layout File paths, layer boundaries, naming conventions
retry-log.json Planner / Retry Loop Previous failures for this trace ID, with fix suggestions

🧾 Example: input-ports.json

[
  {
    "name": "CreateInvoice",
    "interface": "IHandle<CreateInvoiceInput>",
    "handler": "CreateInvoiceHandler",
    "blueprint_id": "usecase-9241"
  }
]

🧠 Example: blueprint.yaml

service_name: BillingService
trace_id: invoice-2025-0194
blueprint_id: usecase-9241
features:
  - UseOpenTelemetry
  - UseAuthorization
  - UseFeatureFlags
aggregate: Invoice

πŸ›‘ Example: authorization-map.yaml

ports:
  - name: CreateInvoice
    requires_auth: true
    roles: ["FinanceManager"]
    tenant_required: true

Used to apply:

  • [Authorize(Roles = "...")]
  • ITenantContext injection and guards

πŸ“˜ Domain Model Input (schema.json)

{
  "aggregate": "Invoice",
  "entityFields": [
    { "name": "InvoiceId", "type": "Guid", "key": true },
    { "name": "Amount", "type": "decimal" },
    { "name": "CustomerId", "type": "Guid" }
  ]
}

Used to reference domain object inside the handler:

var invoice = Invoice.Create(command.CustomerId, command.Amount);

🧠 Trace Context Injection

The agent uses the following from trace input files:

Field Purpose
trace_id Included in logs, telemetry, and file headers
blueprint_id Tags handler for PR traceability
execution_id Optional run-time ID from Planner
agent_origin backend-developer-agent

βœ… This allows downstream Tech Lead Agent and PR annotator to validate lineage and context


πŸ” Retry Context (optional)

If the agent was invoked in a retry loop, it receives:

{
  "trace_id": "invoice-2025-0194",
  "last_error": "Handler lacks port binding",
  "retry_attempt": 2,
  "suggested_fix": "implement IHandle<CreateInvoiceInput>"
}

This enables targeted regeneration, not full rework.


πŸ”§ Configuration Inference

The agent infers the following by scanning the generated project structure:

  • ServiceModel/Controllers/
  • ApplicationModel/UseCases/
  • DomainModel/Entities/
  • Tests/UnitTests/

βœ… This ensures proper file placement, naming, and layer compliance.


βœ… Summary

The Backend Developer Agent uses inputs from architecture, domain, generator, and planner agents to:

  • Implement port-bound handlers
  • Enrich DTOs and validators
  • Apply traceability, security, and observability
  • Trigger test and PR flows

These inputs ensure the agent executes with full architectural context and trace lineage, ready to extend the service in a compliant and observable way.


πŸ“‚ Core Output Artifacts

The Backend Developer Agent produces a set of structured, traceable, and agent-consumable outputs that:

  • βœ… Implement declared input ports (handlers)
  • βœ… Generate service-layer DTOs and validators
  • βœ… Support test and PR generation
  • βœ… Enable observability, traceability, and validation
  • βœ… Activate downstream agent workflows

These outputs are always aligned with Clean Architecture, traceable by ID, and observable across the platform.

Output File Location Description
CreateInvoiceHandler.cs ApplicationModel/UseCases/ Implements use case logic for port contract
CreateInvoiceInput.cs ServiceModel/DTO/ Input DTO bound to port and handler
CreateInvoiceValidator.cs ApplicationModel/Validation/ FluentValidation rule set for input DTO
handler-trace.json AgentMetadata/ Links handler to trace_id, blueprint_id, use case
handler-annotated.md Docs/AgentSummary/ Markdown description of the logic created
CreateInvoiceHandlerTests.cs Tests/UnitTests/ MSTest stub with basic test method
developer-output.event.json AgentMetadata/Events/ Event to signal agent success and trigger QA or Tech Lead
generation.log.json AgentLogs/ Detailed output of file paths, decisions, injected metadata

βœ… Sample: CreateInvoiceHandler.cs

// Generated by: backend-developer-agent
// Trace ID: invoice-2025-0194
// Blueprint ID: usecase-9241

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

    public async Task<Result> Handle(CreateInvoiceInput input)
    {
        var invoice = Invoice.Create(input.CustomerId, input.Amount);
        await _repo.Save(invoice);
        return Result.Success(invoice.Id);
    }
}

βœ… Compliant with Clean Architecture βœ… Trace metadata injected via header comment βœ… Observable by span generation and logs


πŸ“¦ DTO Example: CreateInvoiceInput.cs

public class CreateInvoiceInput
{
    [Required]
    public Guid CustomerId { get; set; }

    [Range(0.01, double.MaxValue)]
    public decimal Amount { get; set; }

    public string? Memo { get; set; }
}

βœ… Used by REST/gRPC endpoint βœ… Also referenced in validation, test, and telemetry


πŸ“ Validator Example: CreateInvoiceValidator.cs

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

βœ… Auto-registered in Startup.cs βœ… Enforced on controller via model validation


πŸ§ͺ Test Output: CreateInvoiceHandlerTests.cs

[TestClass]
public class CreateInvoiceHandlerTests
{
    [TestMethod]
    public async Task Handle_Should_Create_Invoice_When_Input_Valid()
    {
        // Arrange
        var handler = new CreateInvoiceHandler(...);

        // Act
        var result = await handler.Handle(new CreateInvoiceInput { ... });

        // Assert
        Assert.IsTrue(result.Success);
    }
}

βœ… Used by QA and Tech Lead Agent to verify test traceability βœ… Connected to trace_id via test-metadata.yaml


πŸ“‘ Agent Event: developer-output.event.json

{
  "event": "HandlerImplementationComplete",
  "handler": "CreateInvoiceHandler",
  "trace_id": "invoice-2025-0194",
  "blueprint_id": "usecase-9241",
  "agent_origin": "backend-developer-agent",
  "output": [
    "ApplicationModel/UseCases/CreateInvoiceHandler.cs",
    "ServiceModel/DTO/CreateInvoiceInput.cs",
    "ApplicationModel/Validation/CreateInvoiceValidator.cs"
  ],
  "timestamp": "2025-05-04T15:01Z"
}

βœ… Consumed by:

  • Tech Lead Agent
  • Pull Request Agent
  • QA/Test Agent
  • Retry Planner (for audit)

πŸ“˜ Annotated Summary: handler-annotated.md

# 🧠 Handler: CreateInvoiceHandler

- πŸ“¦ Implements: IHandle<CreateInvoiceInput>
- πŸ” Requires: Authorization, Tenant Validation
- 🧱 Uses: Invoice aggregate
- πŸ§ͺ Covered By: CreateInvoiceHandlerTests.cs
- πŸ“ Trace ID: invoice-2025-0194
- 🧠 Generated By: backend-developer-agent

Used in PR annotation and agent dashboards.


βœ… Summary

The Backend Developer Agent outputs:

  • 🧱 Use case handler with injected domain logic
  • πŸ“¦ DTO and validation structure
  • πŸ§ͺ Test stub with metadata linkage
  • πŸ“‘ Trace and event files for downstream agents
  • 🧠 Annotated summaries for human-readable traceability

Every output is layered, traceable, and production-ready, enabling seamless collaboration and validation across the software factory.


🎯 Knowledge Base

The Backend Developer Agent executes its tasks by relying on a well-defined internal knowledge base, composed of:

  • 🧱 Code generation templates and patterns
  • 🧠 Domain-Driven Design and Clean Architecture principles
  • πŸ“š Project structure schemas and agent collaboration rules
  • πŸ“œ Validation rules, naming conventions, and trace formatting
  • πŸ” Authorization policy mapping and security strategy

This knowledge base ensures that all implementations are:

  • βœ… Consistent across all services
  • βœ… Aligned with ConnectSoft architecture contracts
  • βœ… Testable, observable, and ready for agent collaboration

πŸ“š Core Knowledge Domains

Domain Description
Clean Architecture Layering, separation of concerns, DI setup
Domain-Driven Design Aggregate usage, repository patterns, rich domain modeling
Port-to-Handler Mapping Blueprint-defined interface ➝ concrete implementation
DTO and Validator Scaffolding Templates for structure, annotations, FluentValidation
Traceability Contracts Use of trace_id, blueprint_id, agent_origin in code, events, logs
Security & Authorization Usage of [Authorize], scoped roles, tenant checks
Testing Patterns Structure of unit/integration tests, coverage tagging
Telemetry Injection OpenTelemetry spans and Serilog usage patterns
Error Handling Result pattern, failure propagation, exception rules

πŸ“˜ Knowledge Artifacts (Preloaded)

Document / Asset Purpose
clean-architecture.md Defines valid layering and project structure
handler-template.cs Handler code scaffold pattern
dto-template.cs Input DTO pattern with attribute annotations
validator-template.cs FluentValidation class template
trace-spec.yaml Required fields and formatting for trace ID propagation
authorization-map.yaml Maps ports to roles, scopes, tenant constraints
repository-pattern.md How to interact with domain repositories via ports
test-template.cs Basic MSTest scaffold with Arrange/Act/Assert
logging-standards.md How to enrich logs with trace/tenant/request context

These are loaded statically or injected via the planner during initialization.


🧠 Embedded Code Templates (Excerpt)

Handler

public class {{handler_name}} : IHandle<{{dto_name}}>
{
    private readonly I{{repo}}Repository _repo;

    public async Task<Result> Handle({{dto_name}} input)
    {
        var entity = {{aggregate}}.Create(...);
        await _repo.Save(entity);
        return Result.Success(entity.Id);
    }
}

Validator

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

βœ… Templates are parameterized via SK or MCP-compatible execution flow


πŸ“¦ Memory and Reuse Patterns

  • Recalls how similar use cases were implemented
  • Reuses patterns for:
    • Result handling
    • Error propagation
    • Auth decorators
    • Validation logic
    • Domain behavior orchestration

🧠 Example Memory Vector Query

"What handler structure was used for usecase-9241 with multi-tenant enforcement?"

Returns:

  • Prior handler snippet
  • Auth/tenant guard strategy
  • Validator and DTO composition
  • Related test and trace files

πŸ“Š Validation Rules Enforced

Rule ID Description
HND001 All ports must map to one handler per trace_id
DTO002 No domain entity used as DTO or returned in service model
SEC005 [Authorize] required for all sensitive use cases
TEN001 If tenant_required: true, inject and verify ITenantContext
VAL003 Validator class must match DTO name and reside in Validation folder

βœ… Summary

The Backend Developer Agent is powered by a rich knowledge base that includes:

  • Structural patterns
  • Architectural contracts
  • Security policies
  • Validation and traceability specs
  • Code templates and naming conventions

This allows it to produce consistent, standards-compliant, testable backend logic across all ConnectSoft microservices.


πŸ”„ Process Flow Overview

This cycle documents the step-by-step execution flow that the Backend Developer Agent follows when triggered to implement a use case.

The process is deterministic, traceable, and designed for safe orchestration within agent clusters. Each phase builds on validated inputs from previous agents (e.g., Generator, Domain Modeler) and prepares output for downstream validators (e.g., Tech Lead, QA Agent).


πŸ” High-Level Process Flow

flowchart TD
  Start([1️⃣ Receive Use Case Port + Trace Context])
  Parse[2️⃣ Parse Input DTO & Domain Model]
  Validate[3️⃣ Validate Port/Handler Mapping]
  GenerateHandler[4️⃣ Implement Use Case Handler]
  GenerateDTO[5️⃣ Create Input DTO + Annotations]
  GenerateValidator[6️⃣ Create Validator]
  InjectTrace[7️⃣ Add trace_id, blueprint_id, agent_origin]
  CreateTestStub[8️⃣ Emit MSTest Scaffold]
  EmitMetadata[9️⃣ Emit trace logs + metadata files]
  Notify[πŸ”Ÿ Trigger downstream agents]

  Start --> Parse --> Validate --> GenerateHandler
  GenerateHandler --> GenerateDTO --> GenerateValidator
  GenerateValidator --> InjectTrace --> CreateTestStub
  CreateTestStub --> EmitMetadata --> Notify
Hold "Alt" / "Option" to enable pan & zoom

πŸ“‹ Step-by-Step Breakdown

1️⃣ Receive Use Case Port + Trace Context

Triggered by:

  • Microservice Generator Agent
  • Planner
  • Human Operator (CLI/UI)

Includes:

  • input-ports.json
  • blueprint.yaml
  • trace_id + blueprint_id
  • Optional retry metadata

2️⃣ Parse Input DTO & Domain Model

  • Load:
    • Domain aggregate schema
    • Port definition and naming
    • Authorization map (if required)

Prepares handler + DTO naming conventions and injects service context.


3️⃣ Validate Port/Handler Mapping

  • Ensures port is not already implemented
  • Checks Clean Architecture constraints (e.g., handler in correct layer)
  • Confirms aggregate or repository injection point exists

4️⃣ Generate Use Case Handler

  • Uses internal handler-template.cs
  • Populates:
    • Aggregate orchestration
    • Repository call
    • Result object return

Always follows IHandle<T> or equivalent input port contract.


5️⃣ Create Input DTO

  • Defines input properties
  • Applies [Required], [Range], [MaxLength], etc.
  • Places in ServiceModel/DTO/

6️⃣ Create Validator

  • Scaffolds AbstractValidator<T> class
  • Mirrors input DTO
  • Adds FluentValidation rules
  • Validates tenant or customer IDs if authorization-map.yaml defines them

7️⃣ Inject Trace Metadata

Adds trace_id, blueprint_id, agent_origin to:

  • Code comments (header)
  • Log fields (Serilog)
  • Span tags (OpenTelemetry)

8️⃣ Emit MSTest Stub

  • CreateInvoiceHandlerTests.cs in Tests/UnitTests/
  • test-metadata.yaml updated
  • Tagged with handler name and trace

9️⃣ Emit Metadata Files

Includes:

File Description
handler-trace.json Maps handler to trace and blueprint ID
developer-output.event.json Triggers Tech Lead and QA Agent
handler-annotated.md Human-readable summary for PRs

πŸ”Ÿ Notify Downstream Agents

Event emission triggers:

  • Tech Lead Agent (validation)
  • QA Agent (test generation or coverage check)
  • Code Committer Agent (PR staging)
  • Trace Agent (trace lineage validation)

🧠 Execution Modes

Mode Trigger
initial_generation Planner or Generator triggers first handler for blueprint
correction_mode Tech Lead requested retry with fix
resume_from_retry Human/operator fixed input metadata
batch_implementation Implements multiple use cases in sequence

βœ… Summary

The Backend Developer Agent follows a structured, 10-step process that:

  • Parses ports and domain schema
  • Implements handler, DTO, and validator
  • Ensures traceability and testability
  • Emits metadata and agent events
  • Triggers validation and review

This guarantees clean, compliant, and traceable backend feature implementation.


🎯 Skills and Kernel Functions

The Backend Developer Agent uses a modular set of Semantic Kernel (SK) skills and agent-native functions to transform blueprint contracts into complete, validated backend code.

Each skill encapsulates a specific transformation, validation, or generation task. Skills are executed in a chain or selectively invoked by a planner based on context.


πŸ›  Skill Categories

Category Skills
πŸ“¦ Use Case Implementation implementHandler, mapPortToHandler, injectDomainCalls
πŸ“„ DTO and Validation generateDTO, createValidator, applyValidationRules
πŸ” Security and Tenant Logic applyAuthorization, enforceTenantGuard
🧠 Trace Injection injectTraceMetadata, annotateWithTraceId
πŸ§ͺ Test Integration emitTestStub, tagTestWithTraceId
πŸ“€ Metadata and Events emitMetadataFiles, notifyTechLead, triggerQAReview

πŸ“˜ Kernel Function Definitions

πŸ”§ implementHandler(port: string, aggregate: string)

  • Locates port interface (IHandle<CreateInvoiceInput>)
  • Generates handler class with:
    • Constructor injection
    • Domain orchestration
    • Return type: Result<T>

🧾 generateDTO(fields[])

  • Creates input model from domain blueprint
  • Applies:
    • [Required], [Range]
    • XML docs and source mapping
    • Trace annotations

πŸ§ͺ createValidator(dto: string)

  • Generates AbstractValidator<T> using FluentValidation
  • Mirrors DTO properties
  • Injects tenant validation if required

πŸ” applyAuthorization(handler: string)

  • Injects [Authorize] attribute
  • Sets Roles if defined in authorization-map.yaml
  • Adds ITenantContext checks if tenant_required: true

πŸ“Œ injectTraceMetadata(traceId: string, blueprintId: string)

  • Adds trace fields to:
    • Header comment in each file
    • ILogger context (logger.ForContext(...))
    • OpenTelemetry span tags (Activity.Current?.SetTag(...))

πŸ§ͺ emitTestStub(handler: string)

  • Adds MSTest file to UnitTests/
  • Includes:
    • Basic test method
    • Arrange/Act/Assert skeleton
    • trace_id tag for test observability

πŸ“€ emitMetadataFiles()

Outputs:

  • handler-trace.json
  • developer-output.event.json
  • handler-annotated.md
  • Updates test-metadata.yaml

βœ… All metadata used by:

  • Tech Lead Agent
  • Pull Request Agent
  • QA/Test Agents

🧠 Sample Skill Chain

plan:
  - mapPortToHandler
  - generateDTO
  - createValidator
  - implementHandler
  - applyAuthorization
  - injectTraceMetadata
  - emitTestStub
  - emitMetadataFiles

Used in initial_generation mode from blueprint/planner


βš™οΈ Runtime Features

Capability Mechanism
Skill chaining SK planner or static sequence
Prompt injection Trace + port context
Retry injection Planner hints via retry_reason
Escalation trigger Skill suggestHumanReview() if inputs are invalid
Logging Serilog + OTEL integration from SkillExecutionContext

βœ… Summary

The Backend Developer Agent exposes a powerful set of modular skills that:

  • Implement backend logic from blueprint definitions
  • Scaffold handlers, DTOs, validators, and tests
  • Apply security, traceability, and agent integration patterns
  • Emit structured output for validation, observability, and escalation

Each skill is composable, observable, and auditable β€” enabling dynamic execution in agent chains or planner workflows.


🎯 Use Case Implementation Logic

This cycle describes how the Backend Developer Agent translates a port contract into a concrete handler implementation using:

  • Clean Architecture patterns
  • Aggregate orchestration
  • Dependency injection
  • Tenant and authorization guards
  • Result-based return handling

Every handler must follow a predictable, traceable, and testable structure, ensuring it fits seamlessly into the ConnectSoft ecosystem.


🧱 Clean Architecture Alignment

Ports (Interfaces)  -->  UseCase (Handler)  -->  Domain (Entities)
                                 ↓
                         Result<T> / Event
  • The handler lives in ApplicationModel/UseCases
  • Implements IHandle<TInput> or equivalent port interface
  • Interacts only with abstract ports and aggregates
  • Emits Result or raises domain events

🧩 Input Example (from input-ports.json)

{
  "name": "CreateInvoice",
  "interface": "IHandle<CreateInvoiceInput>",
  "handler": "CreateInvoiceHandler",
  "aggregate": "Invoice",
  "blueprint_id": "usecase-9241"
}

🧠 Code Generation Strategy

πŸ”§ Step 1: Resolve Repository and Aggregate

  • Locate domain entity in DomainModel/Entities/Invoice.cs
  • Locate or generate IInvoiceRepository port in ApplicationModel/Ports

πŸ”§ Step 2: Create Handler

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

    public CreateInvoiceHandler(IInvoiceRepository repo)
    {
        _repo = repo;
    }

    public async Task<Result<Guid>> Handle(CreateInvoiceInput input)
    {
        var invoice = Invoice.Create(input.CustomerId, input.Amount);
        await _repo.Save(invoice);
        return Result.Success(invoice.Id);
    }
}

βœ… Returns Result<T> to allow for error propagation, failure cases

βœ… Uses aggregate logic only (no logic inside the handler)


πŸ” Optional Guards (if required)

If authorization-map.yaml defines:

CreateInvoice:
  requires_auth: true
  roles: ["FinanceManager"]
  tenant_required: true

Then the handler:

  • Enforces [Authorize(Roles = "FinanceManager")]
  • Injects ITenantContext and verifies:
if (input.TenantId != _tenantContext.TenantId)
    return Result.Failure("Invalid tenant context.");

🧾 DTO Naming and Typing Convention

Artifact Pattern
DTO CreateInvoiceInput.cs
Validator CreateInvoiceValidator.cs
Test CreateInvoiceHandlerTests.cs

Consistent naming ensures agent discovery, tracing, and test generation compatibility.


πŸ§ͺ Result Handling Template

All handlers follow the Result<T> pattern:

if (invalid)
    return Result.Failure("...");

return Result.Success(value);

βœ… Enables clean error tracking βœ… Compatible with telemetry and Tech Lead Agent validation flow


πŸ’‘ Logic Decomposition Strategy

If the use case grows beyond 30–50 LOC:

  • Move orchestration to domain service
  • Keep handler as thin controller
Handler ➝ Domain Service ➝ Aggregate ➝ Event/Result

🧠 Sample Trace Comment Block

// Blueprint ID: usecase-9241
// Trace ID: invoice-2025-0194
// Agent Origin: backend-developer-agent

Injected automatically at the top of each handler.


βœ… Summary

The Backend Developer Agent implements use cases by:

  • Creating handler classes that fulfill port contracts
  • Delegating logic to aggregates or domain services
  • Ensuring authorization, traceability, and tenant safety
  • Using standardized error/result handling
  • Following Clean Architecture rules for DI and layering

This ensures feature logic is correct, compliant, and fully traceable within the ConnectSoft AI Factory.


🎯 DTO & Input Model Enrichment

This cycle defines how the Backend Developer Agent:

  • βœ… Constructs input and output DTOs (Data Transfer Objects)
  • βœ… Applies validation annotations and guards
  • βœ… Connects DTOs to port interfaces and test scaffolds
  • βœ… Ensures every DTO is traceable, well-typed, and cleanly separated from domain entities

DTOs are the primary boundary interface between clients, adapters, and backend logic in Clean Architecture.


πŸ“¦ DTO Responsibilities

Concern Enforced Rule
Separation DTOs must not reference domain entities directly
Validation Must include attribute and FluentValidation rules
Serialization Decorated for JSON (System.Text.Json or Newtonsoft)
Naming Suffix Input / Output for clarity
Versioning Optional via folder structure or namespaces (e.g., V1/, V2/)
Traceability Annotated with trace_id, blueprint_id metadata

πŸ“„ Generated DTO Example: CreateInvoiceInput.cs

/// <summary>
/// Input model for creating a new invoice
/// Blueprint ID: usecase-9241 | Trace ID: invoice-2025-0194
/// </summary>
public class CreateInvoiceInput
{
    [Required]
    public Guid CustomerId { get; set; }

    [Range(0.01, double.MaxValue)]
    public decimal Amount { get; set; }

    [MaxLength(255)]
    public string? Memo { get; set; }

    public Guid TenantId { get; set; }
}

βœ… Decorated with attributes βœ… Never references Invoice aggregate or EntityBase


πŸ§ͺ Validator: CreateInvoiceValidator.cs

public class CreateInvoiceValidator : AbstractValidator<CreateInvoiceInput>
{
    public CreateInvoiceValidator()
    {
        RuleFor(x => x.CustomerId).NotEmpty();
        RuleFor(x => x.Amount).GreaterThan(0);
        RuleFor(x => x.Memo).MaximumLength(255);
        RuleFor(x => x.TenantId).NotEmpty();
    }
}
  • Registered in DI (services.AddValidatorsFromAssembly(...))
  • Tied to input model via naming and agent metadata
  • Passed through to Tech Lead Agent for test validation

πŸ“¦ Folder Placement

File Path
DTO ServiceModel/DTO/CreateInvoiceInput.cs
Validator ApplicationModel/Validation/CreateInvoiceValidator.cs

βœ… Clear separation of input contract vs validation logic βœ… Enables adapter and controller generation from DTO schema


🧠 Trace and Blueprint Metadata

Every DTO includes trace context in header:

// Blueprint ID: usecase-9241
// Trace ID: invoice-2025-0194
// Generated by: backend-developer-agent

Also emits to:

  • handler-trace.json
  • test-metadata.yaml
  • dto-index.yaml (optional for large systems)

🧾 Optional Enrichment Flags

Feature Behavior
UseOpenAPI Adds XML doc comments, tags for Swagger
UseVersioning Places DTOs in versioned namespaces
UseBotFramework Adds user-facing fields and summary annotations
UseLocalization Decorates error messages with resource keys

πŸ”„ DTO ↔ Adapter Linkage

DTOs generated here are later used by:

  • Adapter Generator Agent (e.g., HTTP/JSON β†’ DTO)
  • Test Agent (e.g., sample payload generation)
  • API Gateway documentation (e.g., OpenAPI)

βœ… The agent ensures that all DTOs are self-documenting, validatable, and ready for pipeline interaction


πŸ“Š Observability

DTO-level validation and failure telemetry includes:

{
  "event": "dto_validation_failed",
  "trace_id": "invoice-2025-0194",
  "field": "Amount",
  "error": "Must be greater than 0"
}

βœ… Emitted by QA or runtime instrumentation, traceable back to agent output


βœ… Summary

The Backend Developer Agent generates:

  • 🧾 Traceable, well-typed input models (DTOs)
  • βœ… FluentValidation validators for all inputs
  • πŸ“ Proper folder and namespace structure
  • πŸ“‘ Trace metadata for downstream agents
  • πŸ›‘οΈ Security, tenant, and structural safeguards

This guarantees port-aligned, observable, and adapter-friendly service boundaries.


πŸ” Authorization & Tenant Enforcement

This cycle outlines how the Backend Developer Agent:

  • Applies security decorators and guards to handlers and DTOs
  • Enforces multi-tenant isolation
  • Validates role-based access controls (RBAC)
  • Ensures every use case adheres to authorization policies defined in the blueprint or authorization-map.yaml

πŸ” Security is first-class: every handler that accesses protected data or actions must be explicitly secured, validated, and traceable.


πŸ“¦ Input: authorization-map.yaml

Example:

ports:
  - name: CreateInvoice
    requires_auth: true
    roles: ["FinanceManager"]
    tenant_required: true

βœ… Parsed and injected by the agent to control:

  • Authorization attributes
  • Tenant context enforcement
  • Optional escalation if no map provided

πŸ›‘οΈ Decorator Injection: [Authorize(...)]

πŸ“˜ On controller or handler class:

[Authorize(Roles = "FinanceManager")]
public class CreateInvoiceHandler : IHandle<CreateInvoiceInput>
{
    ...
}
  • If requires_auth: true, adds [Authorize]
  • If roles defined, injects Roles = "..."
  • If scopes (optional), adds policy-based [Authorize(Policy = "...")]

🧠 Tenant Enforcement (Multi-Tenancy)

If tenant_required: true, the agent:

  1. Injects ITenantContext into handler constructor
  2. Verifies that input.TenantId == _tenantContext.TenantId
  3. Returns failure if mismatch

πŸ”’ Sample:

if (input.TenantId != _tenantContext.TenantId)
    return Result.Failure("Invalid tenant context.");

βœ… Prevents cross-tenant data leakage βœ… Traceable via Tech Lead Agent and trace logs


🧩 Tenant Injection Pattern

public class CreateInvoiceHandler : IHandle<CreateInvoiceInput>
{
    private readonly ITenantContext _tenantContext;

    public CreateInvoiceHandler(ITenantContext tenantContext, ...)
    {
        _tenantContext = tenantContext;
    }
}
  • Works for REST, gRPC, Azure Function handlers
  • ITenantContext is registered globally in DI

πŸ” Planner-Aware Behavior

If no authorization-map.yaml is provided:

  • Agent queries Planner for policy defaults
  • Fallback: emits AuthorizationMissing warning in metadata:
{
  "event": "AuthorizationHintMissing",
  "handler": "CreateInvoiceHandler",
  "trace_id": "invoice-2025-0194"
}

βœ… Prevents insecure scaffolds from merging undetected


πŸ” Summary of Enforcement Rules

Rule ID Rule
SEC001 [Authorize] must be applied to all secure handlers
SEC002 Roles or policies must match those in authorization-map.yaml
SEC003 Multi-tenant use cases must include TenantId validation
SEC004 No domain entity may be returned directly to a controller
SEC005 If authorization metadata is missing, emit escalation or warning

πŸ“‹ Trace Metadata in Secure Handlers

All secure handlers include:

// Blueprint ID: usecase-9241
// Secured: βœ… Roles: FinanceManager
// Tenant Enforced: βœ…

Also logged via Serilog with:

{
  "event": "use_case_executed",
  "secured": true,
  "roles": ["FinanceManager"],
  "tenant_validated": true
}

πŸ“ Folder Placement

Concern Folder
Handler with [Authorize] ApplicationModel/UseCases/
Validator for TenantId ApplicationModel/Validation/
Multi-tenant config (optional) Config/TenantPolicies/

βœ… Summary

The Backend Developer Agent enforces:

  • Role-based [Authorize] usage
  • Multi-tenant input validation using ITenantContext
  • Secure handler construction with metadata injection
  • Traceable, observable enforcement across code, logs, and test scaffolds

Security is never an afterthought β€” it is baked into every handler and decision the agent makes.


🎯 Test Implementation & Agent Collaboration

This cycle defines how the Backend Developer Agent ensures that every handler it implements is testable and:

  • βœ… Emits a corresponding unit test scaffold
  • βœ… Tags all tests with trace_id and blueprint_id
  • βœ… Enables downstream agents (QA Agent, Tech Lead Agent, PR Agent) to evaluate coverage and correctness
  • βœ… Ensures full traceability and CI/CD readiness across the test lifecycle

πŸ§ͺ Responsibilities

Task Description
βœ… Generate test class CreateInvoiceHandlerTests.cs in Tests/UnitTests
🧩 Match handler signature Input, handler name, output contract
🧠 Trace metadata Inject trace_id, blueprint_id, and agent_origin
πŸ§ͺ Test coverage reporting Emit/update test-metadata.yaml
πŸ” Retry-ready Flag handlers missing test coverage during correction mode
πŸ€– Agent compatibility Outputs are consumable by QA, Tech Lead, and PR Agents

πŸ“‚ File Structure

BillingService/
β”œβ”€β”€ ApplicationModel/UseCases/CreateInvoiceHandler.cs
β”œβ”€β”€ Tests/UnitTests/CreateInvoiceHandlerTests.cs
└── test-metadata.yaml

πŸ§ͺ Sample: CreateInvoiceHandlerTests.cs

[TestClass]
public class CreateInvoiceHandlerTests
{
    [TestMethod]
    public async Task Handle_Should_CreateInvoice_WhenInputIsValid()
    {
        // Arrange
        var handler = new CreateInvoiceHandler(...);
        var input = new CreateInvoiceInput
        {
            CustomerId = Guid.NewGuid(),
            Amount = 120.00M
        };

        // Act
        var result = await handler.Handle(input);

        // Assert
        Assert.IsTrue(result.Success);
    }
}

βœ… MSTest-based βœ… Uses Arrange / Act / Assert pattern βœ… Easy for QA Agent to enrich or complete


🧠 Traceable Test Metadata

πŸ“˜ test-metadata.yaml

trace_id: invoice-2025-0194
blueprint_id: usecase-9241
handler: CreateInvoiceHandler
unit_test: CreateInvoiceHandlerTests.cs
covered: true
test_type: "unit"

Used by:

  • QA Agent β†’ coverage validation and enrichment
  • Tech Lead Agent β†’ rule enforcement
  • PR Agent β†’ annotation and quality scoring

πŸ“€ Agent Event Output

{
  "event": "TestScaffoldCreated",
  "handler": "CreateInvoiceHandler",
  "trace_id": "invoice-2025-0194",
  "test_file": "Tests/UnitTests/CreateInvoiceHandlerTests.cs",
  "agent_origin": "backend-developer-agent",
  "timestamp": "2025-05-04T15:18Z"
}

βœ… Notifies QA and Tech Lead Agents βœ… Logged to observability stream for audit


πŸ“¦ Test Enrichment Triggers

The Backend Developer Agent triggers additional test behavior:

Agent Trigger
QA Agent Receives TestScaffoldCreated and suggests/enriches additional tests
Tech Lead Agent Checks for unit_test entry in test-metadata.yaml
PR Agent Uses test trace metadata to annotate PR coverage score
Planner May re-invoke emitTestStub() if previous test was invalid or incomplete

πŸ”„ Retry Scenario Example

If a Tech Lead Agent later issues a correction:

β€œCreateInvoiceHandler lacks assertion for domain event publication”

Then the agent:

  • Updates CreateInvoiceHandlerTests.cs
  • Appends to test-metadata.yaml
  • Resends event: TestScaffoldUpdated

βœ… Summary

The Backend Developer Agent ensures every use case handler is:

  • πŸ§ͺ Accompanied by a test scaffold
  • 🧠 Traceable and tagged with relevant IDs
  • πŸ“‘ Registered in test metadata and trace events
  • 🀝 Connected to QA and Tech Lead Agent review flows
  • βœ… Ready for validation, enrichment, and CI/CD gating

Tests are not optional β€” they are part of the output contract.


🎯 Traceability Metadata Injection

This cycle defines how the Backend Developer Agent ensures every output β€” code, tests, events, and metadata β€” is enriched with traceability context, enabling:

  • πŸ”— Full lifecycle trace from blueprint β†’ code β†’ test β†’ deployment
  • 🧠 Agent attribution (agent_origin) for observability and audit
  • πŸ“¦ Metadata-based collaboration with other agents (Tech Lead, QA, PR, Planner)

Traceability is fundamental to autonomous coordination, auditability, and safe delivery in ConnectSoft.


🧩 Required Trace Fields

Field Description
trace_id Unique ID per use case or handler, used across logs and artifacts
blueprint_id ID of the source feature/use case definition
agent_origin Identity of agent that generated or modified the file
execution_id Optional orchestration-specific run ID
timestamp ISO UTC when the artifact was generated or emitted

πŸ“„ Code Header Injection (Handlers, DTOs, Validators)

Each generated file includes a trace block:

// Generated by: backend-developer-agent
// Trace ID: invoice-2025-0194
// Blueprint ID: usecase-9241
// Agent Origin: backend-developer-agent

βœ… Injected into:

  • CreateInvoiceHandler.cs
  • CreateInvoiceInput.cs
  • CreateInvoiceValidator.cs
  • CreateInvoiceHandlerTests.cs

πŸ§ͺ Metadata File Injection

πŸ“˜ handler-trace.json

{
  "handler": "CreateInvoiceHandler",
  "trace_id": "invoice-2025-0194",
  "blueprint_id": "usecase-9241",
  "agent_origin": "backend-developer-agent",
  "output": [
    "ApplicationModel/UseCases/CreateInvoiceHandler.cs",
    "ServiceModel/DTO/CreateInvoiceInput.cs"
  ]
}

πŸ“˜ test-metadata.yaml

trace_id: invoice-2025-0194
blueprint_id: usecase-9241
unit_test: CreateInvoiceHandlerTests.cs
covered: true
agent_origin: backend-developer-agent

🧠 Serilog Log Enrichment

Injected into logs:

{
  "level": "Information",
  "message": "Handler executed successfully",
  "trace_id": "invoice-2025-0194",
  "blueprint_id": "usecase-9241",
  "agent_origin": "backend-developer-agent"
}

βœ… Enables OTEL dashboards, PR validation scoring, and audit trails


πŸ“€ Emitted Events

πŸ“˜ developer-output.event.json

{
  "event": "HandlerImplementationComplete",
  "trace_id": "invoice-2025-0194",
  "blueprint_id": "usecase-9241",
  "agent_origin": "backend-developer-agent",
  "handler": "CreateInvoiceHandler",
  "timestamp": "2025-05-04T15:23Z"
}

βœ… Triggers Tech Lead, QA, and Pull Request Agent workflows


πŸ“Ž GitOps/CI Integration

Trace ID and blueprint ID are added to:

  • Git commit messages
  • PR titles/descriptions
  • CI pipeline variables
  • Docker labels (via generation-metadata.yaml)

πŸ“¦ Optional: .generated.by.yaml

For human/operator awareness:

trace_id: invoice-2025-0194
blueprint_id: usecase-9241
generated_by: backend-developer-agent
time: 2025-05-04T15:23Z

πŸ” Retry and Correction Integration

If the agent is invoked in retry mode, it updates:

  • handler-trace.json β†’ retry_count
  • Adds last_attempt_time
  • Logs reason for correction in correction-log.json

βœ… Summary

The Backend Developer Agent guarantees 100% traceable outputs via:

  • Code-level metadata injection
  • Structured trace metadata files
  • Enriched logs and events
  • Cross-agent discoverable files for validation, audit, and orchestration

Traceability is not a feature β€” it is the protocol.


πŸ” Retry and Correction Loop

This cycle defines how the Backend Developer Agent handles:

  • ✏️ Invalid or incomplete handler generation
  • πŸ§ͺ Missing tests or validation coverage
  • πŸ”„ Correction requests from the Tech Lead Agent
  • πŸ™‹ Human overrides (if required)

The agent supports intelligent retry, context-aware fixes, and traceable correction history.


πŸ”„ Retry Triggers

Scenario Trigger Source
❌ Missing handler file Tech Lead Agent (handler not found)
🚫 Invalid port mapping Planner β†’ Retry injection
⚠️ DTO validation failure QA Agent β†’ Test scaffold incomplete
πŸ§ͺ No test coverage Tech Lead or PR Agent
🧱 Cross-layer violation Human override or Planner flag
🧠 Conflict with previous attempt Trace log (retry_count > 1)

🧠 Retry Strategy

flowchart TD
  Start([Failed Validation or Output])
  ParseFix{{Has correction hint?}}
  ApplyFix[Apply fix to handler/DTO/test]
  ReEmit[Regenerate output and metadata]
  Escalate[Escalate to Planner/Human]
  End([Updated trace + retry metadata])

  Start --> ParseFix
  ParseFix -->|Yes| ApplyFix --> ReEmit --> End
  ParseFix -->|No| Escalate --> End
Hold "Alt" / "Option" to enable pan & zoom

πŸ“„ Retry Input Example

{
  "trace_id": "invoice-2025-0194",
  "handler": "CreateInvoiceHandler",
  "retry_count": 1,
  "last_error": "DTO lacks required validation",
  "correction_suggestion": "Add [Required] and validator"
}

βœ… Injected by Tech Lead Agent or Planner


πŸ›  Retry Actions Supported

Correction Fix
🧾 Add missing [Required] Update DTO and re-emit validator
πŸ“¦ Regenerate handler Rewrite from port and aggregate contract
πŸ§ͺ Add test Emit or update unit test stub
πŸ” Add [Authorize] or TenantId check Inject decorator and guard
πŸ“„ Update metadata Re-emit handler-trace.json, developer-output.event.json

πŸ“˜ Correction Log Entry

correction-log.json:

{
  "trace_id": "invoice-2025-0194",
  "attempt": 2,
  "fixed": true,
  "fields_corrected": ["DTO validation", "Handler retry"],
  "timestamp": "2025-05-04T15:31Z"
}

βœ… Used by Tech Lead to confirm resolution βœ… Used by Planner to suppress repeat errors


πŸ“€ Retry Metadata Injection

Updates to:

  • handler-trace.json β†’ retry_count
  • test-metadata.yaml β†’ status: fixed
  • developer-output.event.json β†’ retry: true

🧠 Agent Memory Influence

If this handler was corrected before:

  • Agent checks prior fixes in vector memory
  • Adjusts output accordingly
  • Avoids regenerating incorrect patterns

πŸ™‹ Human Escalation Option

If correction fails again or is ambiguous:

{
  "event": "DeveloperEscalationRequired",
  "reason": "Multiple failed handler regeneration attempts",
  "trace_id": "invoice-2025-0194",
  "attempts": 3,
  "last_agent": "backend-developer-agent"
}

Routed to:

  • Planner
  • Human Reviewer Agent
  • Developer Dashboard

βœ… Summary

The Backend Developer Agent supports:

  • Retry-aware handler regeneration
  • Auto-correction of missing/invalid logic
  • Full traceable metadata for correction history
  • Collaboration with Tech Lead and Planner agents
  • Optional escalation if automation cannot continue safely

The correction loop ensures the factory is resilient, adaptive, and trace-consistent.


🎯 Domain Service Integration

This cycle defines how the Backend Developer Agent interacts with domain services, aggregates, and repositories when implementing use case handlers.

It ensures that all business logic:

  • 🧱 Resides in the domain layer
  • βœ… Is orchestrated via clean interfaces
  • πŸ”„ Maintains separation between application and domain logic
  • πŸ” Honors tenant and security boundaries

🧩 Domain-Centric Design

[Handler (ApplicationModel)] 
        ↓
[Domain Service (DomainModel.Services)]
        ↓
[Aggregate (DomainModel.Entities)]
  • The handler orchestrates
  • The domain performs the business logic
  • No logic leaks into adapters or DTOs

πŸ“˜ Repository Injection Example

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

    public async Task<Result<Guid>> Handle(CreateInvoiceInput input)
    {
        var invoice = Invoice.Create(input.CustomerId, input.Amount);
        await _repo.Save(invoice);
        return Result.Success(invoice.Id);
    }
}

βœ… The handler depends on the port IInvoiceRepository, not on infrastructure


🧠 Domain Service Usage (If Logic is Complex)

If orchestration involves multiple aggregates or steps:

Inject domain service:

private readonly IInvoiceService _invoiceService;

Invoke logic:

var result = await _invoiceService.CreateFromInput(input);
return result;

βœ… Keeps the handler thin βœ… Moves invariants and workflows into reusable services


🧱 Domain Service Generation Pattern

File Placement
InvoiceService.cs DomainModel/Services/
IInvoiceService.cs ApplicationModel/Ports/
Implementation Bound in Startup.cs via DI

πŸ“‚ Expected Folder Integration

Component Folder
Aggregate DomainModel/Entities/Invoice.cs
Domain Service DomainModel/Services/InvoiceService.cs
Handler ApplicationModel/UseCases/CreateInvoiceHandler.cs
Repository Interface ApplicationModel/Ports/IInvoiceRepository.cs
Adapter InfrastructureModel/Adapters/InvoiceRepository.cs

πŸ“Ž Common Patterns Used

Pattern Example
🧱 Factory Method Invoice.Create(...)
πŸ§ͺ Domain Event InvoiceCreatedDomainEvent
πŸ” Entity Modification invoice.ApplyDiscount(...)
πŸ’Ύ Repository Save _repo.Save(invoice)

πŸ” Event Raising

If domain events are used:

invoice.AddDomainEvent(new InvoiceCreated(...));

Then domain event dispatcher (in adapter or background worker) will:

  • Log
  • Trace
  • Emit outbound message

πŸ”’ Tenant Context Propagation

Domain methods that require multi-tenant logic receive:

TenantId tenant = new(input.TenantId);

Used for:

  • Partition key enforcement
  • Guard conditions
  • Domain event tagging

βœ… Summary

The Backend Developer Agent integrates domain logic by:

  • Orchestrating aggregate and service interactions cleanly
  • Using port abstractions for repository and service access
  • Delegating core logic to domain services if complexity grows
  • Ensuring security, layering, and Clean Architecture principles are upheld

This guarantees business logic is centralized, composable, and agent-ready.


🎯 Memory and Learning from History

This cycle defines how the Backend Developer Agent uses:

  • πŸ”„ Long-term memory (vector or structured)
  • 🧠 Historical trace logs and retry feedback
  • πŸ“Š Learned code patterns and architectural corrections

…to become smarter, more context-aware, and better aligned with prior implementation standards.

The agent doesn’t start fresh every time β€” it learns from past services, failed validations, and approved patterns.


🧠 Memory Sources

Source Description
generation-history.json Track of all handlers generated per trace ID
retry-log.json List of corrections, retry reasons, and fix actions
vector memory (SK or Azure AI Search) Code snippets, event logs, prompts, metadata
handler-trace.json archives Links previous handlers to blueprint metadata
annotated.md files Human/agent summaries from prior services
planner memory Learned prompt β†’ handler β†’ validator β†’ test chains

πŸ” How Memory Is Used

Task Memory-Aided Behavior
Port-to-Handler Mapping Reuses naming, injection, DTO formatting from similar use cases
Trace Inference Avoids duplicate trace_id conflicts, auto-resolves blueprint lineage
Correction Avoidance Prevents repeated generation errors (e.g., missing test, auth)
Test Scaffold Enrichment Suggests edge cases based on prior similar use cases
DTO/Validator Pairing Reuses validator pattern for fields like Amount, TenantId, Email
Logging/Telemetry Format Applies consistent OTEL and Serilog patterns
Authorization Enforcement Detects that all financial handlers require [Authorize] with FinanceManager role

πŸ“˜ Example Memory Vector Entry

{
  "handler": "CreateInvoiceHandler",
  "trace_id": "invoice-2025-0194",
  "auth_roles": ["FinanceManager"],
  "validator_pattern": "Amount > 0",
  "test_case_count": 3,
  "last_review_result": "Approved by TechLeadAgent"
}

βœ… Queried when generating a similar use case: UpdateInvoiceHandler


🧠 Correction-Driven Learning

If the Tech Lead Agent rejects a handler due to:

  • Invalid DTO mapping
  • Missing tenant check
  • Test without assertion

🧠 The agent stores:

{
  "trace_id": "order-2025-0321",
  "correction": {
    "field": "TenantId",
    "fix": "Add tenant guard and validator rule",
    "status": "resolved"
  }
}

Next time, this correction is applied automatically, avoiding the same issue.


πŸ“¦ Memory Indexing Tags

Dimension Example
domain Invoice, Order, Customer
use_case Create, Update, Cancel, Approve
handler_complexity Simple, Orchestrated, Multi-Aggregate
retry_count 0–3+
review_status Passed, Escalated, Failed, Corrected

Used by Planner and QA Agents to improve score and insight.


πŸ” Update on Each Run

After each generation or retry:

  • Memory is enriched with:
    • Handler metadata
    • Correction outcome
    • Generated file hashes
    • Test method count
  • This becomes part of the agent skill evolution loop

πŸ” Optional Memory Access by Other Agents

Agents that can read or suggest from this memory:

  • Planner Agent β†’ auto-plan missing use cases
  • Tech Lead Agent β†’ validate conformance to past decisions
  • QA Agent β†’ enrich test coverage based on memory
  • Human Reviewer Agent β†’ view past failures and escalation stats

βœ… Summary

The Backend Developer Agent continuously learns from:

  • Prior outputs and trace metadata
  • Corrections and agent feedback
  • Similar use cases and domain entities

It uses memory to produce smarter, safer, more consistent output β€” avoiding redundant mistakes, improving architectural fidelity, and accelerating autonomous development.


🀝 Integration with Other Agents

This cycle defines how the Backend Developer Agent collaborates and synchronizes with other agents in the ConnectSoft ecosystem to:

  • Receive triggers
  • Share metadata
  • Respond to validation or retry feedback
  • Enable autonomous downstream actions (tests, PRs, trace updates)

It operates as a central engineering executor but functions within a multi-agent orchestration mesh.


🌐 Key Agent Collaborators

Agent Interaction
Microservice Generator Agent Provides initial structure, port definitions, blueprint context
Domain Modeler Agent Supplies aggregates and schemas
Planner Agent Triggers use case implementation, retry, or parallel generation
Tech Lead Agent Validates output, requests corrections
QA Agent Consumes test scaffolds, enriches test coverage
Trace Agent Tracks span coverage and propagation for handlers
Pull Request Agent Publishes code to repo, annotates with metadata
Human Reviewer Agent Receives escalations, reviews unclear or failed implementations

πŸ“‘ Event Contract Output

Emits event to notify other agents:

developer-output.event.json

{
  "event": "HandlerImplementationComplete",
  "handler": "CreateInvoiceHandler",
  "trace_id": "invoice-2025-0194",
  "blueprint_id": "usecase-9241",
  "agent_origin": "backend-developer-agent",
  "output": [
    "UseCaseHandler",
    "DTO",
    "Validator",
    "Test"
  ],
  "timestamp": "2025-05-04T15:40Z"
}

βœ… Consumed by Tech Lead, QA, PR, and Planner Agents


🧾 Emitted Metadata for Collaboration

File Consumed By Description
handler-trace.json Tech Lead, Trace Agent Links handler to blueprint, domain, and trace ID
test-metadata.yaml QA, Tech Lead Indicates unit test presence and mapping
correction-log.json Planner Captures correction attempts, used in retry logic
handler-annotated.md PR Agent, Human Markdown summary of what was generated

πŸ§ͺ QA Agent Collaboration

  • Receives TestScaffoldCreated event
  • Uses test-metadata.yaml to check handler-to-test alignment
  • Suggests/enriches additional tests (BDD, edge cases)

πŸ§ͺ Tech Lead Agent Collaboration

  • Validates:
    • Handler logic structure
    • DTO compliance
    • Trace injection
    • Security enforcement
  • Issues correction feedback via:
{
  "event": "CorrectionRequired",
  "reason": "DTO lacks validation rules",
  "target_agent": "backend-developer-agent"
}

βœ… Triggered retry via planner


πŸ” Planner Collaboration

  • Initiates:
    • Handler generation for uncovered ports
    • Correction rounds
    • Multi-agent workflows (e.g., generate ➝ validate ➝ commit)
  • Consumes:
    • Handler trace metadata
    • Correction logs
    • Execution telemetry

πŸ“€ PR Agent Integration

  • Consumes metadata to:
    • Populate PR description
    • Annotate commits with trace ID
    • Tag files as handler/DTO/test

πŸ™‹ Human Reviewer Agent

If multiple attempts fail or ambiguity exists, emits:

{
  "event": "EscalationSuggested",
  "trace_id": "order-2025-0341",
  "reason": "Conflicting authorization role definitions"
}

βœ… Exposes full handler-annotated.md and correction history


πŸ“Ž Workflow Snapshot

flowchart TD
  Planner --> BackendDev
  MicroserviceGen --> BackendDev
  DomainModeler --> BackendDev
  BackendDev --> TechLead
  BackendDev --> QA
  BackendDev --> TraceAgent
  BackendDev --> PR_Agent
  BackendDev --> HumanReviewer
Hold "Alt" / "Option" to enable pan & zoom

βœ… Summary

The Backend Developer Agent is a collaborative executor, integrating with:

  • Structural agents (Microservice Generator, Domain Modeler)
  • Validation agents (Tech Lead, QA, Trace)
  • Orchestration agents (Planner)
  • Delivery agents (PR, Human Reviewer)

Its outputs are designed to be consumed and validated across all downstream workflows in the ConnectSoft platform.


🎯 System Prompt

This cycle defines the immutable system prompt that bootstraps the Backend Developer Agent’s behavior.

It encodes the agent’s identity, scope, rules, and collaboration expectations, ensuring that its actions are:

  • Deterministic
  • Aligned with Clean Architecture
  • Traceable and safe
  • Compatible with other agents and orchestrators

🧾 System Prompt (Full Definition)

You are the **Backend Developer Agent** in the ConnectSoft AI Software Factory.

Your job is to implement backend logic for application use cases using Clean Architecture, Domain-Driven Design, and traceable agent collaboration patterns.

You MUST:

βœ… Implement use case handlers based on input port definitions (e.g., IHandle<CreateXInput>)
βœ… Create DTOs for each handler input and apply validation rules (Required, Range, etc.)
βœ… Generate matching FluentValidation classes for all DTOs
βœ… Use only domain entities or services for orchestration (do not invent business logic)
βœ… Inject [Authorize] decorators and tenant checks where required
βœ… Emit unit test scaffolds for each handler
βœ… Annotate all outputs with trace_id, blueprint_id, and agent_origin
βœ… Emit metadata files (handler-trace.json, test-metadata.yaml, developer-output.event.json)
βœ… Trigger Tech Lead, QA, and PR agents via event payloads

You MUST NOT:

❌ Return or inject infrastructure components directly
❌ Leak domain entities into ServiceModel (e.g., expose Invoice directly as a DTO)
❌ Create logic that violates Clean Architecture layering
❌ Skip test, validation, or traceability outputs

Always return:

- Code files (Handler, DTO, Validator, Test)
- Metadata files and trace summaries
- An event JSON file to notify downstream agents

Maintain a safe, auditable, and agent-composable implementation process.

πŸ” Role Binding

Attribute Value
agent_name backend-developer-agent
agent_type software.engineer.implementation
requires_trace_id βœ…
requires_blueprint_id βœ…
outputs_trigger_event βœ…
traceable_in_memory βœ…
retry_capable βœ…
human_escalation_hooks βœ…

🧠 How System Prompt Is Used

  • Loaded at initialization (e.g., via Semantic Kernel or MCP runtime)
  • Ensures all SK planner chains or orchestrator workflows produce consistent, contract-aligned output
  • Allows downstream validators (e.g., Tech Lead Agent) to assume structure and metadata availability

βœ… Summary

The System Prompt of the Backend Developer Agent defines:

  • Its scope: implement port-mapped backend logic
  • Its rules: Clean Architecture, DDD, traceability
  • Its required outputs: handler, DTO, validator, test, metadata, event
  • Its coordination model: event-driven agent triggering, retry and escalation ready

This ensures the agent behaves predictably, safely, and autonomously within the ConnectSoft platform.


🎯 Input Prompt Template

This cycle defines the standard input format used to invoke the Backend Developer Agent.

The prompt template is used by:

  • 🧠 Planners (SK or custom orchestrators)
  • πŸ› οΈ Other agents (e.g., Microservice Generator, Domain Modeler)
  • πŸ™‹ Human operators (via CLI, chat, or UI)

It ensures that invocations are consistent, declarative, and traceable, supporting multiple service types, blueprints, and retry contexts.


πŸ“₯ Prompt Template Format (YAML/Text Hybrid)

# πŸ”§ Request to Implement Use Case Handler
agent: backend-developer-agent

trace_id: {{trace_id}}
blueprint_id: {{blueprint_id}}
execution_id: {{optional_execution_id}}

handler:
  name: {{handler_name}}                # e.g., CreateInvoiceHandler
  interface: {{port_interface}}         # e.g., IHandle<CreateInvoiceInput>
  domain_aggregate: {{aggregate_name}}  # e.g., Invoice

dto_fields:
  - name: CustomerId
    type: Guid
    required: true
  - name: Amount
    type: decimal
    required: true
    constraints:
      - greater_than: 0
  - name: Memo
    type: string
    max_length: 255

authorization:
  required: true
  roles: ["FinanceManager"]
  tenant_required: true

features:
  - UseOpenTelemetry
  - UseAuthorization
  - UseFeatureFlags

test:
  enabled: true
  framework: MSTest

trigger_agents_after:
  - tech-lead-agent
  - qa-agent
  - pull-request-agent

🧩 Notes on Template Fields

Field Description
trace_id Used in all metadata and trace injection
blueprint_id Links handler to originating use case
handler.name Output filename + class name
dto_fields Determines input DTO properties and validation rules
authorization Adds [Authorize] decorator and tenant checks
features Enables telemetry, feature flags, bot integrations, etc.
trigger_agents_after Declares downstream orchestration steps

πŸ“˜ Full Example

agent: backend-developer-agent

trace_id: invoice-2025-0194
blueprint_id: usecase-9241

handler:
  name: CreateInvoiceHandler
  interface: IHandle<CreateInvoiceInput>
  domain_aggregate: Invoice

dto_fields:
  - name: CustomerId
    type: Guid
    required: true
  - name: Amount
    type: decimal
    required: true
    constraints:
      - greater_than: 0
  - name: Memo
    type: string
    max_length: 255

authorization:
  required: true
  roles: ["FinanceManager"]
  tenant_required: true

features:
  - UseOpenTelemetry
  - UseAuthorization

test:
  enabled: true
  framework: MSTest

trigger_agents_after:
  - tech-lead-agent
  - qa-agent

πŸ’‘ Human-Friendly Prompt Version (Chat)

Please generate the CreateInvoiceHandler for trace ID invoice-2025-0194.

- It implements IHandle<CreateInvoiceInput>
- Fields: CustomerId (Guid, required), Amount (decimal > 0), Memo (string, max 255)
- Requires authorization for FinanceManager role and tenant validation
- Use domain aggregate: Invoice
- Add FluentValidation and test scaffold (MSTest)
- Enable OpenTelemetry and authorization hooks

βœ… Ideal for chatbot-based orchestration or CLI workflows


πŸ” Retry Support

Can include:

retry_context:
  previous_attempt: 1
  last_error: "DTO lacked validator"
  retry_reason: "Tech Lead Agent requested validation rules"

βœ… Summary

The Backend Developer Agent’s input prompt:

  • Provides structured, declarative intent
  • Includes security, trace, test, and validation flags
  • Supports agent orchestration and retry context
  • Is compatible with both planners and human tools

This prompt format guarantees safe, repeatable, traceable backend code generation.


🎯 Observability and Telemetry

This cycle defines how the Backend Developer Agent:

  • πŸ“ˆ Emits metrics, traces, and structured logs during execution
  • πŸ“€ Enriches outputs with observability metadata
  • πŸ“‘ Supports real-time monitoring, validation, and debugging by other agents and humans

Observability is not optional β€” it’s how autonomous systems remain safe, auditable, and debuggable at scale.


πŸ“Š Observability Outputs

Channel Type
πŸ”­ OpenTelemetry Distributed tracing via spans
πŸ“‹ Serilog Structured logs with correlation fields
πŸ“ˆ Prometheus (via OTEL) Metrics counters and timers
πŸ“ Trace metadata Emitted into output files and events

πŸ”­ OpenTelemetry Integration

  • Each phase of agent execution emits OTEL Activity spans
  • Example spans:
    • backend_dev.handler.generate
    • backend_dev.dto.validate
    • backend_dev.test.emit

Span Example

{
  "name": "backend_dev.handler.generate",
  "trace_id": "invoice-2025-0194",
  "attributes": {
    "blueprint_id": "usecase-9241",
    "handler": "CreateInvoiceHandler",
    "agent_origin": "backend-developer-agent"
  },
  "duration_ms": 86
}

βœ… Exportable to Jaeger, Zipkin, Azure Monitor, or Lightstep


πŸ“ˆ Prometheus Metrics

Exposed via OpenTelemetry or directly with metric exporter:

Metric Description
backend_dev_handler_generated_total Total number of handler classes generated
backend_dev_retry_total Number of retry attempts for a handler
backend_dev_test_coverage_ratio Ratio of use cases with test stubs
backend_dev_duration_seconds Duration histogram for generation

βœ… Supports Grafana dashboards or custom agent monitoring tools


πŸ“‹ Serilog Logging

All actions logged with:

  • trace_id, blueprint_id, handler, agent_origin
  • Severity levels: Information, Warning, Error

Log Entry Example

{
  "message": "Handler generated successfully",
  "handler": "CreateInvoiceHandler",
  "trace_id": "invoice-2025-0194",
  "blueprint_id": "usecase-9241",
  "agent_origin": "backend-developer-agent",
  "level": "Information"
}

βœ… Outputs go to:

  • Console
  • File
  • Optional external sink (Azure Log Analytics, Loki)

πŸ“ Metadata Injection

Every file generated by the agent includes:

// Trace ID: invoice-2025-0194
// Blueprint ID: usecase-9241
// Agent Origin: backend-developer-agent
  • Present in handler, DTO, validator, test
  • Ensures trace-based routing in downstream analysis tools

πŸ“€ Observability Event Output

Sample developer-output.event.json:

{
  "event": "HandlerImplementationComplete",
  "handler": "CreateInvoiceHandler",
  "trace_id": "invoice-2025-0194",
  "metrics": {
    "execution_time_ms": 102,
    "retry_count": 0,
    "lines_of_code": 84
  },
  "agent_origin": "backend-developer-agent",
  "timestamp": "2025-05-04T15:45Z"
}

βœ… Consumed by Tech Lead, QA, Trace Agent, PR Agent


πŸ” CI/PR Observability Integration

Metadata is forwarded to:

  • GitHub PR annotations (test coverage, trace link)
  • Azure DevOps pipeline dashboards
  • Internal dashboards via dashboards.json or metrics endpoint

βœ… Summary

The Backend Developer Agent is fully observable via:

  • 🧠 Distributed tracing (OpenTelemetry)
  • πŸ“ˆ Structured metrics (Prometheus-compatible)
  • πŸ“‹ Serilog logs for debugging and audit
  • πŸ“ Metadata in generated code and trace files
  • πŸ“€ Event payloads for agent orchestration and review

This ensures every handler implementation is trackable, debuggable, and auditable across the software factory lifecycle.


πŸ™‹ Human Escalation Hooks

This final cycle defines how the Backend Developer Agent:

  • Detects when automation is unsafe or ambiguous
  • Escalates issues to humans or supervisory agents
  • Provides full context and traceable artifacts for rapid resolution

Autonomy is powerful β€” but ConnectSoft’s factory is designed to safely involve humans where required, without halting overall system progress.


🚨 Escalation Triggers

Scenario Example
❌ Ambiguous blueprint Missing port β†’ handler mapping
πŸ” Repeated failed retries 3+ correction attempts without successful Tech Lead validation
πŸ” Inconsistent security map Conflicting roles in authorization-map.yaml
⚠️ Invalid domain reference Aggregate not found, or entity missing required methods
❓ Unsupported planner operation Planner provided an unknown flag or instruction
πŸ‘€ Explicit human override Human requested manual review

🧠 Detection Mechanism

Before finalizing output, the agent runs:

- validateBlueprintConsistency
- checkRetryThresholdExceeded
- detectUnresolvableConflicts
- confirmDomainArtifactPresence

If any fail with a critical flag, escalation is triggered.


πŸ“€ Escalation Event Payload

developer-escalation.event.json

{
  "event": "DeveloperEscalationRequired",
  "trace_id": "invoice-2025-0194",
  "blueprint_id": "usecase-9241",
  "reason": "Handler retry failed after 3 attempts. Validator pattern still invalid.",
  "agent_origin": "backend-developer-agent",
  "last_attempt_timestamp": "2025-05-04T15:50Z"
}

βœ… Routed to:

  • Human Reviewer Agent
  • Planner Agent
  • Developer dashboard or Slack bot

πŸ“‹ Human-Friendly Review Markdown

handler-annotated.md

## 🚨 Escalation Notice: Handler Implementation Failed

- **Handler**: CreateInvoiceHandler  
- **Trace ID**: invoice-2025-0194  
- **Blueprint**: usecase-9241  
- **Agent**: backend-developer-agent  
- **Attempts**: 3  
- **Issue**: Validation rules not accepted by Tech Lead Agent  
- **Recommendation**: Manual intervention or blueprint correction  

πŸ§ͺ Optional Escalation Fix Plan (Suggested by Planner)

plan:
  - manual_review_required
  - fix_validator_pattern("Amount must be > 0")
  - re_trigger_backend_dev_agent

🧠 What Human Agents Can Do

Role Action
Human Reviewer Agent Views annotated files, accepts or rewrites logic
Architect Agent Suggests corrections to blueprint or security schema
Tech Lead Agent Approves patch manually or recommends retry plan
PR Agent Waits until escalation is resolved or force merge approved

βœ… Summary of Escalation Handling

  • βœ‹ Automatic halts only when confidence is too low
  • πŸ™‹ Escalations are traceable, explainable, reversible
  • 🧠 Human intervention is structured and guided, not chaotic
  • πŸ”„ Upon resolution, Planner re-invokes the agent with improved inputs