π§ 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
- 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
β 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
IInvoiceRepositoryor 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 onauthorization-map.yaml - Injects
ITenantContextand verifiesTenantIdmatches
5. emitTestScaffold()¶
- Adds
CreateInvoiceHandlerTests.csinTests/UnitTests - Prepares for MSTest + Coverlet
- Tagged with
trace_idand 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¶
Used to apply:
[Authorize(Roles = "...")]ITenantContextinjection 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:
π§ 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
π Step-by-Step Breakdown¶
1οΈβ£ Receive Use Case Port + Trace Context¶
Triggered by:
- Microservice Generator Agent
- Planner
- Human Operator (CLI/UI)
Includes:
input-ports.jsonblueprint.yamltrace_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.yamldefines 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.csinTests/UnitTests/test-metadata.yamlupdated- 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>usingFluentValidation - Mirrors DTO properties
- Injects tenant validation if required
π applyAuthorization(handler: string)¶
- Injects
[Authorize]attribute - Sets
Rolesif defined inauthorization-map.yaml - Adds
ITenantContextchecks iftenant_required: true
π injectTraceMetadata(traceId: string, blueprintId: string)¶
- Adds trace fields to:
- Header comment in each file
ILoggercontext (logger.ForContext(...))- OpenTelemetry span tags (
Activity.Current?.SetTag(...))
π§ͺ emitTestStub(handler: string)¶
- Adds MSTest file to
UnitTests/ - Includes:
- Basic test method
Arrange/Act/Assertskeletontrace_idtag for test observability
π€ emitMetadataFiles()¶
Outputs:
handler-trace.jsondeveloper-output.event.jsonhandler-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_generationmode 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¶
- The handler lives in
ApplicationModel/UseCases - Implements
IHandle<TInput>or equivalent port interface - Interacts only with abstract ports and aggregates
- Emits
Resultor 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
IInvoiceRepositoryport inApplicationModel/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:
Then the handler:
- Enforces
[Authorize(Roles = "FinanceManager")] - Injects
ITenantContextand verifies:
π§Ύ 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:
β 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
π§ 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.jsontest-metadata.yamldto-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:
β 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
rolesdefined, injectsRoles = "..." - If
scopes(optional), adds policy-based[Authorize(Policy = "...")]
π§ Tenant Enforcement (Multi-Tenancy)¶
If tenant_required: true, the agent:
- Injects
ITenantContextinto handler constructor - Verifies that
input.TenantId == _tenantContext.TenantId - Returns failure if mismatch
π Sample:¶
β 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
ITenantContextis registered globally in DI
π Planner-Aware Behavior¶
If no authorization-map.yaml is provided:
- Agent queries Planner for policy defaults
- Fallback: emits
AuthorizationMissingwarning 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:
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_idandblueprint_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.csCreateInvoiceInput.csCreateInvoiceValidator.csCreateInvoiceHandlerTests.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
π 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_counttest-metadata.yaml β status: fixeddeveloper-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:¶
Invoke logic:¶
β 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:
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:
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
TestScaffoldCreatedevent - Uses
test-metadata.yamlto 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
β 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
Activityspans - Example spans:
backend_dev.handler.generatebackend_dev.dto.validatebackend_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