π Projects Management¶
π§ Domain Overview¶
The Projects Management Domain serves as the foundational entry point into the ConnectSoft AI Software Factory lifecycle. It captures the intent to build a software system and provides the system-of-record for all project-related metadata, statuses, and traceability references.
This domain enables users (human or agent) to initialize, track, and manage projects across their full lifecycle β from drafting an idea, to triggering orchestration, to validating successful delivery.
π― Strategic Responsibilities¶
- Store canonical project metadata
- Define and persist project lifecycle state
- Correlate orchestration flows via
traceId - Track ownership (user or agent) and creation origin
- Maintain linkages to templates, features, services, and artifacts
π§± Relation to Other Domains¶
flowchart TD
subgraph ProjectManagement
P1(ProjectContext)
P2(TemplateCatalogContext)
P3(ProjectLifecycleContext)
P4(TraceabilityContext)
end
subgraph OrchestrationLayer
O1(ProjectOrchestrator)
O2(AgentLifecycleTracker)
end
subgraph DevOps
D1(GitProvisioner)
D2(WorkItemPublisher)
end
P1 --> O1
O1 --> D1
O1 --> D2
O2 --> P3
P4 --> O2
π§© Architectural Position¶
| Role | Description |
|---|---|
| Source of Truth | Manages all projects and their lifecycle state |
| Event Emitter | Emits domain events to trigger orchestration agents |
| Reference Anchor | Used by downstream services to correlate artifacts and lifecycles |
| Agent-Ready Interface | Provides REST/gRPC endpoints for agent and human interaction |
ποΈ Components¶
| Subdomain Context | Purpose |
|---|---|
ProjectContext |
Manages project entity and core commands |
TemplateCatalogContext |
Lists and applies templates (e.g., microservice, gateway, auth) |
ProjectLifecycleContext |
Tracks state machine and transitions |
TraceabilityContext |
Correlates all generated services and agents via traceId |
ProjectAssignmentContext |
Links human users and agents to project phases |
π Interactions¶
- Triggered via: Studio UI, REST API, or upstream Platform Service
- Downstream actions: Emits
ProjectInitializedto orchestration - Related flows: Git repo creation, Boards setup, service scaffolding
π Security and Access Control¶
- All APIs are multi-tenant aware
- Supports RBAC: Users can only access projects they own or are assigned to
- Agents authenticate using machine credentials with scoped permissions
β Summary¶
The Projects Management Domain acts as the anchor point of the entire software generation lifecycle. It provides structure, status, and traceability around every ConnectSoft-created SaaS or microservice project.
It is isolated from orchestration logic and instead publishes events to drive orchestration, aligning with clean, event-driven DDD principles.
π§ Bounded Contexts in Projects Management¶
In the context of Domain-Driven Design (DDD), a bounded context defines the boundary within which a particular domain model is valid. Each context encapsulates its own language, rules, logic, and services, and interacts with other contexts through well-defined contracts (typically via events or APIs).
π§© Bounded Contexts in the Projects Domain¶
The Projects Management Domain is composed of five core bounded contexts, each serving a distinct functional and architectural role.
1οΈβ£ ProjectContext¶
Purpose: Manages the lifecycle-independent metadata and identity of a software project.
Responsibilities:
- Store project name, description, creator, tags
- Assign template
- Emit domain events like
ProjectCreatedorProjectUpdated
Key Aggregates:
ProjectProjectId
APIs/Commands:
CreateProjectUpdateProjectMetadataAssignTemplateToProject
2οΈβ£ TemplateCatalogContext¶
Purpose: Exposes the available solution templates (e.g., microservice, gateway, authentication server) that users or agents can choose from.
Responsibilities:
- Maintain a registry of templates
- Provide metadata like supported runtime, architecture, optional flags
- Validate template availability during project creation
Key Aggregates:
SolutionTemplateTemplateId
APIs/Queries:
ListAvailableTemplatesGetTemplateByIdPreviewTemplateStructure
3οΈβ£ ProjectLifecycleContext¶
Purpose: Owns the state machine governing project generation, including orchestration hooks, retries, and transitions.
Responsibilities:
- Track project lifecycle status (
Draft β Initialized β Generating β Committed) - Emit
ProjectStatusUpdatedevents - Allow retries and manual overrides
Key Concepts:
ProjectStatusenumLifecycleTransitionLog
Commands:
StartProjectGenerationUpdateProjectStatusRetryFailedProject
4οΈβ£ TraceabilityContext¶
Purpose: Correlates agent activities, generated services, and orchestration outputs to the initiating project.
Responsibilities:
- Generate and store
traceId,sessionId - Link artifacts (repos, files, services) to a trace
- Enable full audit paths
Key Entities:
TraceLinkProjectTraceMetadata
APIs:
GenerateTraceIdGetTraceArtifactsByProjectIdListAgentsByTraceId
5οΈβ£ ProjectAssignmentContext¶
Purpose: Assigns responsibility for project lifecycle phases to users or agents.
Responsibilities:
- Track which agent handles which phase (e.g., Vision Architect, DevOps, QA)
- Manage human-team collaboration on same project
- Support ownership audits and access logic
Key Aggregates:
ProjectAssignmentLifecyclePhase
APIs:
AssignAgentToProjectPhaseGetProjectAssignments
π Communication Between Contexts¶
These bounded contexts do not directly reference each other in code. Instead, they communicate via:
- Domain Events (published via event bus or outbox)
- Query APIs (read-only access to projections)
- Application Service calls (where permitted)
π§ Alignment with ConnectSoft Principles¶
| Principle | Implementation in Contexts |
|---|---|
| Clean Architecture | Each context maps to a clean service with distinct application and domain layers |
| DDD | Each context owns its own ubiquitous language and aggregates |
| Event-Driven | Contexts emit and react to domain events |
| Observability | TraceId and context-aware metrics are included in all transitions |
| Multi-Tenant SaaS | All contexts are tenant-aware and RBAC-enforced |
β Summary¶
The Projects Management Domain is modularized into 5 bounded contexts to enforce clear ownership, modularity, and event-driven execution. Each context supports autonomous scaling and direct collaboration with engineering, orchestration, and DevOps agents.
π§© Aggregate: Project¶
The Project aggregate is the central entity in the ProjectContext. It represents a software initiative being initiated, configured, and executed via the ConnectSoft AI Software Factory.
This aggregate is the anchor for all other contexts, and is identified by a globally unique ProjectId, with a TraceId used to correlate events, agents, and outputs.
π§± Project Properties¶
| Property | Type | Description |
|---|---|---|
Id |
ProjectId |
Aggregate root identifier (GUID-based) |
Name |
string |
Human-friendly project name |
Slug |
string |
URL-safe version of the project name |
Description |
string? |
Optional description (business and technical context) |
DomainTags |
List<string> |
Tags like SaaS, Healthcare, CRM, AI, etc. |
Industry |
string? |
Optional industry taxonomy (e.g., Legal, Finance, Insurance) |
CreatedBy |
UserId |
ID of the initiating user or system |
CreatedAt |
DateTime |
UTC timestamp of creation |
Status |
ProjectStatus |
Enum defining current lifecycle stage |
TemplateId |
TemplateId? |
Optional reference to selected solution template |
TraceId |
TraceId |
System-wide correlation identifier |
LifecycleLog |
List<StatusChange> |
Records all status changes with timestamps and actor |
AgentAssignments |
List<ProjectAssignment> |
Optional β who handles which lifecycle phase |
π§Ύ Enumeration: ProjectStatus¶
π Lifecycle Transitions¶
| From | To | Trigger Event / Command |
|---|---|---|
Draft |
Initialized |
ProjectInitialized (agent orchestration begins) |
Initialized |
Generating |
StartProjectGeneration command |
Generating |
Committed |
ProjectGenerationCompleted event |
Generating |
Failed |
ProjectFailed event |
Failed |
RetryRequested |
RetryFailedProject command |
RetryRequested |
Generating |
Internal retry logic |
π Domain Events Emitted¶
| Event Name | Description |
|---|---|
ProjectCreated |
Emitted after successful initialization of a project |
ProjectInitialized |
Indicates project is ready for orchestration |
ProjectStatusUpdated |
Fired on every status change |
ProjectTemplateAssigned |
Triggered when template metadata is bound |
ProjectFailed |
Emitted if generation or orchestration fails |
ProjectGenerationCompleted |
Marks the successful end of autonomous delivery |
π§ͺ Invariants & Rules¶
Namemust be unique per tenantTraceIdis required and immutableStatusmust follow valid transition flowTemplateIdcan only be assigned once unless inDraftstateCreatedBymust always be non-null (validated by app layer)
π§ Sample C# Declaration (simplified)¶
public class Project : AggregateRoot<ProjectId>
{
public string Name { get; private set; }
public string Slug { get; private set; }
public string? Description { get; private set; }
public List<string> DomainTags { get; private set; }
public string? Industry { get; private set; }
public UserId CreatedBy { get; private set; }
public DateTime CreatedAt { get; private set; }
public ProjectStatus Status { get; private set; }
public TemplateId? TemplateId { get; private set; }
public TraceId TraceId { get; private set; }
public List<StatusChange> LifecycleLog { get; private set; }
}
π Why It Matters¶
The Project aggregate:
- Is the source of all orchestration triggers
- Serves as the backbone of traceability
- Provides status-driven hooks for other agents and services
- Supports cross-cutting audit, testing, and documentation layers
β Summary¶
The Project aggregate encapsulates all core metadata, traceability, and status transitions that power the autonomous software generation lifecycle. It is domain-pure, cleanly layered, and event-driven β and its state changes are the basis of every orchestration phase downstream.
π Project Lifecycle & State Machine¶
The Project Lifecycle defines the allowed state transitions of a project from its inception to successful delivery (or failure). This lifecycle is critical for controlling orchestration timing, agent triggers, and observability checkpoints.
It is modeled as a finite state machine, implemented within the ProjectLifecycleContext.
π State Machine Diagram¶
stateDiagram-v2
[*] --> Draft
Draft --> Initialized : ProjectInitialized
Initialized --> Generating : StartProjectGeneration
Generating --> Committed : ProjectGenerationCompleted
Generating --> Failed : ProjectFailed
Failed --> RetryRequested : RetryFailedProject
RetryRequested --> Generating : RestartAgentOrchestration
π¦ States and Their Semantics¶
| State | Description |
|---|---|
Draft |
Initial project entry; metadata may be incomplete |
Initialized |
Project has passed validation and emitted orchestration-ready signal |
Generating |
Agents are actively building out the project components |
Committed |
Project has been fully generated and pushed to version control |
Failed |
An error occurred during generation or orchestration |
RetryRequested |
User or agent requested retry after failure |
π¦ Transition Events¶
| Event | Triggers Transition From β To |
|---|---|
ProjectInitialized |
Draft β Initialized |
StartProjectGeneration |
Initialized β Generating |
ProjectGenerationCompleted |
Generating β Committed |
ProjectFailed |
Generating β Failed |
RetryFailedProject |
Failed β RetryRequested |
RestartAgentOrchestration |
RetryRequested β Generating |
π οΈ Internal Handling Rules¶
- Projects in
Failedstate can only be retried once unless explicitly overridden - Transition timestamps are logged in
LifecycleLog - Each transition triggers domain events and optionally orchestration notifications
- Agents are never directly triggered from lifecycle logic; they subscribe to emitted events
π§© Status-Coupled Actions¶
| Status | Side Effects or Signals Sent |
|---|---|
Initialized |
Triggers orchestration event for Vision Architect Agent |
Generating |
Monitors multi-agent execution and trace progress |
Committed |
Final state β Git repos created, PRs merged |
Failed |
Notifies Studio UI and marks trace ID as incomplete |
RetryRequested |
Instructs orchestrator to replay agent phases |
π Observability Hooks¶
All transitions are observable via:
ProjectStatusUpdateddomain event- OTEL span:
project.lifecycle.transitionwith attributes:trace_idproject_idfrom_stateto_stateactor_idtimestamp
π Sample Audit Entry¶
{
"projectId": "proj-13f2",
"traceId": "trace-b84c",
"from": "Generating",
"to": "Failed",
"reason": "Vision Architect agent timeout",
"timestamp": "2025-05-05T14:15:02Z",
"initiatedBy": "agent:vision-arch-01"
}
β Summary¶
The Project Lifecycle State Machine ensures safe, predictable, and auditable transitions across each stage of software generation. By isolating transition logic, it supports automation, retry strategies, and full traceability β without tightly coupling to orchestration mechanics.
π§ Use Cases β ProjectContext¶
The ProjectContext is the core bounded context responsible for capturing and evolving the foundational metadata of a software project. These use cases are exposed through both UI and API interfaces, and form the entry point to all downstream orchestration and delivery workflows.
This context owns the Project aggregate, and all changes here emit domain events and are traceable.
π§© Primary Use Cases¶
| Use Case | Description |
|---|---|
CreateProject |
Initializes a new project in the Draft state |
UpdateProjectMetadata |
Edits properties like name, description, tags |
AssignTemplateToProject |
Binds the project to a known solution template |
GetProjectById |
Retrieves full metadata for a given project |
ListProjectsByUser |
Lists all accessible projects owned or assigned to the current user |
DeleteProject |
Soft-deletes a project (only in Draft or Failed state) |
π Use Case: CreateProject¶
π§ Input¶
{
"name": "VetSaaS Booking System",
"description": "Online appointment booking for veterinary clinics",
"domainTags": ["SaaS", "Healthcare", "Booking"],
"industry": "Healthcare"
}
β Behavior¶
- Creates a new
Projectaggregate inDraftstate - Generates
ProjectId,TraceId,Slug, andCreatedAt - Emits
ProjectCreatedevent
π Output¶
{
"projectId": "proj-38fb",
"status": "Draft",
"traceId": "trace-a9d4",
"createdAt": "2025-05-05T10:45:00Z"
}
π Use Case: UpdateProjectMetadata¶
π§ Input¶
β Behavior¶
- Validates if project is not in
Committedstate - Updates mutable fields
- Emits
ProjectUpdatedevent
π Use Case: AssignTemplateToProject¶
π§ Input¶
β Behavior¶
- Verifies template exists via
TemplateCatalogContext - Binds
TemplateIdto the project - Emits
ProjectTemplateAssignedevent
π Use Case: GetProjectById¶
- Retrieves the full metadata, including status, lifecycle log, and trace ID
- Often used by Studio UI or orchestration dashboards
π Use Case: ListProjectsByUser¶
- Filters projects where user is the creator or explicitly assigned (from
AssignmentContext) - Supports pagination and status filters
π Use Case: DeleteProject¶
- Only allowed if project is in
DraftorFailed - Performs soft-delete by marking
IsDeleted = true - All downstream services ignore deleted projects
π Validation Rules¶
| Rule | Applies To |
|---|---|
Name must be unique per tenant |
CreateProject |
TemplateId cannot be reassigned once set |
AssignTemplateToProject |
Only editable if status < Committed |
UpdateProjectMetadata |
| Only deletable in non-final states | DeleteProject |
π Emitted Domain Events¶
| Event Name | Triggered By |
|---|---|
ProjectCreated |
CreateProject |
ProjectUpdated |
UpdateProjectMetadata |
ProjectTemplateAssigned |
AssignTemplateToProject |
β Summary¶
The ProjectContext is where all project creation and setup begins. It offers a simple but critical API surface for interacting with the Project aggregate, setting the stage for orchestration, agent activation, and traceability.
π§ Use Cases β TemplateCatalogContext¶
The TemplateCatalogContext manages the set of solution templates available in the ConnectSoft AI Software Factory. Templates define the starting structure for a project β including architecture style, programming language, runtime integrations, and scaffold configuration.
This context is read-heavy and optimized for availability and reuse by both humans (Studio UI) and agents.
π§© Primary Use Cases¶
| Use Case | Description |
|---|---|
ListAvailableTemplates |
Returns all templates registered in the catalog |
GetTemplateById |
Fetches details of a specific template by ID |
PreviewTemplateStructure |
Visualizes the folder/file structure scaffolded by the template |
ListTemplatesByTag |
Filters templates by tags like Microservice, Gateway, Auth, etc. |
ValidateTemplateUsability |
Ensures a template is compatible with selected options (e.g., transport) |
π¦ Template Metadata Structure¶
{
"templateId": "tpl-microservice-cleanarch-v1",
"name": "Microservice - Clean Architecture (v1)",
"type": "Microservice",
"language": "C#",
"architecture": "Clean",
"runtime": "ASP.NET Core 8",
"tags": ["Microservice", "NHibernate", "MassTransit"],
"generator": "MicroserviceGeneratorAgent",
"supports": ["REST", "gRPC", "EventBus"],
"defaultConfig": {
"healthCheck": true,
"observability": true,
"featureFlags": true
}
}
π Use Case: ListAvailableTemplates¶
- Returns all templates with minimal metadata
- Can be cached for performance
- Used by Studio UI dropdown or agent pre-check
π Use Case: GetTemplateById¶
- Returns full metadata for one specific template
- Verifies template exists before assignment to project
π Use Case: PreviewTemplateStructure¶
- Returns a JSON or Mermaid-style preview of what files/folders are generated
{
"structure": [
"src/",
"src/MyService.Api/",
"src/MyService.Application/",
"src/MyService.Domain/",
"tests/MyService.Tests/",
"infra/helm/",
"infra/bicep/"
]
}
- Used by UI previews and orchestration visualization tools
π Use Case: ListTemplatesByTag¶
- Allows filtering by
type,tag, orcapability - Useful for targeting templates for specific use cases (e.g., mobile app, auth service)
π Use Case: ValidateTemplateUsability¶
- Ensures the selected template supports the transport (e.g., REST, MassTransit)
- Prevents invalid assignments in
AssignTemplateToProject
π§ Agent Usage¶
- Agents like
MicroserviceGeneratorAgentandGatewayGeneratorAgentquery this context to:- Get compatible templates for generation
- Retrieve config flags for scaffold conditionals
- Confirm agent compatibility (e.g.,
.NET only,Blazor supported)
π No Domain Events¶
This context is read-only from the factory perspective. Templates are added or updated by platform maintainers β not by user/agent workflows β and do not emit domain events.
π οΈ Internal Storage¶
- Backed by a static registry or configuration file (YAML, JSON)
- Optionally versioned (e.g.,
tpl-cleanarch-v1,tpl-cleanarch-v2) - May integrate with a future Template Management Platform
β Summary¶
The TemplateCatalogContext is a foundational dependency for both users and agents, providing visibility into available architectural templates. It ensures that every generated service starts from a known, tested, and composable scaffold β aligning with ConnectSoftβs principles of Clean Architecture and automation.
π§ Use Cases β ProjectLifecycleContext¶
The ProjectLifecycleContext governs all state transitions and status management of a project across its lifecycle β from creation to orchestration, completion, failure, and recovery.
It acts as the state gatekeeper for agent orchestration flows and observability pipelines.
This context does not own the project metadata itself β instead, it reacts to events and commands from other bounded contexts (especially ProjectContext) and updates or validates status transitions.
π§© Primary Use Cases¶
| Use Case | Description |
|---|---|
StartProjectGeneration |
Transitions project to Generating and signals orchestration kickoff |
UpdateProjectStatus |
Applies a valid status change from agents or orchestrators |
RetryFailedProject |
Allows resuming a previously failed project generation phase |
MarkProjectCommitted |
Marks final successful state, post PR submission |
FailProjectGeneration |
Records failure and emits audit trail |
π Status Enum Reference¶
π Use Case: StartProjectGeneration¶
- Preconditions: Project must be in
Initializedstate - Actions:
- Transition to
Generating - Emit
ProjectStatusUpdated - Send
ProjectInitializedevent to Orchestration Layer
- Transition to
π Use Case: UpdateProjectStatus¶
- Applies status transition with audit metadata
- Validates that transition is allowed via lifecycle map
- Updates lifecycle log (e.g., actor, timestamp, reason)
{
"projectId": "proj-273f",
"from": "Generating",
"to": "Failed",
"reason": "Test failures in Backend Service",
"actor": "agent:qa-validator"
}
π Use Case: RetryFailedProject¶
- Preconditions: Project must be in
Failed - Transitions to
RetryRequested - Orchestration Layer will pick it up and rerun agents
- Prevents duplicate execution if already retried once
π Use Case: MarkProjectCommitted¶
- Final successful state
- Preconditions: Project must be in
Generating - Signals that all services have been generated, tested, and submitted
π Use Case: FailProjectGeneration¶
- Triggers transition to
Failed - Emits
ProjectFailedevent - Records
failedReasonand optionally stack trace / agent logs
π Event Emission¶
| Event Name | Triggered By |
|---|---|
ProjectStatusUpdated |
Any valid transition |
ProjectGenerationStarted |
On entry to Generating |
ProjectGenerationCompleted |
On successful Committed |
ProjectFailed |
On transition to Failed |
All events contain:
projectIdfrom,totraceIdactorIdtimestamp
π Observability Hooks¶
All lifecycle changes produce:
- OTEL span:
project.lifecycle.transition - Structured audit log entries (used in dashboards)
- Optionally trigger Discord/Slack/Email notifications
π Validation Rules¶
| Rule | Enforcement Stage |
|---|---|
| Invalid transitions are rejected | At command handler level |
Project in Committed or Deleted is locked |
All lifecycle APIs |
| Retry allowed only once per failure | RetryFailedProject |
β Summary¶
The ProjectLifecycleContext enforces status consistency, agent-safe transitions, and full observability across the project lifecycle. It is event-driven, compliant with Clean Architecture, and serves as the authoritative gateway for lifecycle automation and error recovery.
π§ Use Cases β TraceabilityContext¶
The TraceabilityContext enables system-wide correlation of activities, artifacts, and agents related to a given project. It establishes and manages a TraceId for every initiated project, which acts as a universal linkage key across microservices, agents, CI/CD systems, and documentation.
This context ensures full observability, auditability, and agent accountability across the software generation lifecycle.
π Why Traceability Matters¶
- Every generated file, repo, or build is linked back to a
traceId - Each agent's execution logs are grouped by this trace
- Project delivery reports and dashboards rely on this context
- CI/CD systems use trace IDs to group logs and tests per project
π§© Primary Use Cases¶
| Use Case | Description |
|---|---|
GenerateTraceId |
Generates a globally unique trace ID at project creation |
GetTraceArtifactsByProjectId |
Lists all services, files, PRs, and agents involved in a trace |
ListAgentsByTraceId |
Shows which agents executed under this trace |
GetExecutionTimeline |
Returns chronological execution path of the entire lifecycle |
TraceAuditTrail |
Returns full metadata for auditing and debugging |
π Use Case: GenerateTraceId¶
- Called during
CreateProjectcommand - Produces a UUID-formatted ID (e.g.,
trace-a84cdd2a) - Stored in both
ProjectandTraceRegistry
{
"traceId": "trace-a84cdd2a",
"createdBy": "user-dmitry",
"projectId": "proj-172",
"createdAt": "2025-05-05T11:45:00Z"
}
π Use Case: GetTraceArtifactsByProjectId¶
- Aggregates and returns:
- Repositories created
- Services scaffolded
- Agent execution logs
- Generated files
- API specifications
- Helm/Bicep manifests
π Use Case: ListAgentsByTraceId¶
- Returns a log like:
[
{ "agent": "VisionArchitectAgent", "status": "Completed", "startedAt": "...", "duration": "12s" },
{ "agent": "BackendDeveloperAgent", "status": "Completed" },
{ "agent": "QAValidatorAgent", "status": "Failed" }
]
- Useful for debugging and reporting execution progress
π Use Case: GetExecutionTimeline¶
- Returns ordered list of events (from all agents and services) tagged with the trace ID
- Enables timeline reconstruction, span navigation, and performance audits
[
{ "timestamp": "2025-05-05T11:48:01Z", "event": "ProjectInitialized" },
{ "timestamp": "2025-05-05T11:48:04Z", "event": "VisionArchitectAgent Started" },
...
]
π Use Case: TraceAuditTrail¶
- Full metadata for compliance, security, and debugging
- Includes IPs, agent versions, actor identities, status transitions, PR diffs, etc.
π οΈ Internal Model¶
| Entity | Description |
|---|---|
TraceId |
Unique identifier (1:1 with project) |
ProjectId |
Linked to project aggregate |
AgentExecution[] |
Log of agents that participated in this trace |
Artifacts[] |
Repos, files, manifests, pull requests, Helm charts, etc. |
LifecycleEvents[] |
Emitted events with timestamps and actor IDs |
π Observability¶
Each trace ID is:
- Injected as baggage and span attributes in all OpenTelemetry traces
- Used as folder/tag in logging systems
- Cross-linked in dashboards and generated documentation
π¦ Example OTEL Span Attributes¶
trace_id: trace-3a1fb9
project_id: proj-84dd
agent: BackendDeveloperAgent
file: /src/MyService.Application/Handlers/CreatePetHandler.cs
event: FileGenerated
β Summary¶
The TraceabilityContext guarantees end-to-end linkage and insight across all generated artifacts, orchestration phases, and agent actions. It is the foundation of observability and audit in the ConnectSoft AI Software Factory, and supports compliance, reporting, and debugging for thousands of autonomous builds.
π§ Use Cases β ProjectAssignmentContext¶
The ProjectAssignmentContext manages responsibility and access control for each projectβs lifecycle phases. It allows mapping of:
- Human users (e.g., platform operators, developers)
- Agents (e.g.,
VisionArchitectAgent,BackendDeveloperAgent) to specific roles, phases, or tasks within a given project.
This context is essential for:
- Controlled execution of agent workflows
- Ensuring visibility and ownership in multi-agent collaboration
- Providing per-phase auditability and traceability
π§© Primary Use Cases¶
| Use Case | Description |
|---|---|
AssignAgentToProjectPhase |
Links an agent to a specific lifecycle phase of a project |
AssignUserToProject |
Grants a user (e.g., architect, QA) permissions and roles on a project |
GetProjectAssignments |
Returns all agents/users and their roles/phases assigned to the project |
GetAssignmentsByUser |
Lists all projects where a user has active participation |
RevokeAssignment |
Removes a user or agent from a project or phase |
π₯ Assignment Model¶
| Field | Type | Description |
|---|---|---|
projectId |
ProjectId |
Reference to the project |
actorId |
string |
User ID or agent name |
actorType |
enum |
Human, Agent |
role |
string |
Architect, QA, Orchestrator, etc. |
phase |
string? |
Optional: the project phase assigned |
assignedAt |
DateTime |
Timestamp of assignment |
assignedBy |
string |
Who performed the assignment |
π Use Case: AssignAgentToProjectPhase¶
- Assigns an agent to execute a specific phase (e.g.,
SolutionModeling,ServiceGeneration) - Used by orchestrators at project init
- Prevents agents from running phases they arenβt assigned to
{
"projectId": "proj-71f2",
"actorId": "agent:VisionArchitectAgent",
"actorType": "Agent",
"role": "VisionArchitect",
"phase": "DomainModeling"
}
π Use Case: AssignUserToProject¶
- Grants user access as:
Owner(creator)CollaboratorReviewer
- Determines visibility in Studio UI and permission scope
{
"projectId": "proj-71f2",
"actorId": "user-dmitry",
"actorType": "Human",
"role": "Architect",
"assignedBy": "user-admin"
}
π Use Case: GetProjectAssignments¶
- Lists all assigned agents and users for a given project
- Often used by:
- Studio UI
- Agent Lifecycle Tracker
- Orchestration dashboards
π Use Case: GetAssignmentsByUser¶
- Returns a list of
ProjectId,Role, andPhasewhere the user is assigned - Enables personal dashboard views
π Use Case: RevokeAssignment¶
- Soft-deletes assignment
- May trigger notification to orchestration system to halt an agentβs phase
- Ensures access is always intentional and traceable
π Internal Rules¶
| Rule | Description |
|---|---|
Owner role is implicitly assigned at creation |
Cannot be revoked |
| Agent must be explicitly assigned to a phase | Agents cannot act on projects they are not assigned to |
| Duplicate assignments are prevented | Same actor-role-project combo is unique |
π§ Agent Usage¶
Before executing, every agent checks:
If not, the orchestration layer denies execution and logs an error.
β Summary¶
The ProjectAssignmentContext ensures controlled, observable participation in software delivery workflows β whether by human collaborators or autonomous agents. Itβs a vital context for security, collaboration, and accountability in the AI Software Factory.
π§ Domain Events Reference¶
Domain events in the Projects Management Domain capture meaningful state changes that occur as a result of commands or internal processing. They are published by aggregates and application services to notify other contexts, services, and the orchestration layer about key lifecycle transitions.
This section documents the canonical set of domain events that serve as the backbone of ConnectSoftβs event-driven workflows.
π¦ Event Format¶
All domain events follow this structure:
{
"eventType": "ProjectInitialized",
"projectId": "proj-71f2",
"traceId": "trace-b9124",
"actorId": "user-dmitry",
"timestamp": "2025-05-05T11:57:00Z",
"payload": { ... }
}
π Core Domain Events¶
| Event Name | Emitted By | Description |
|---|---|---|
ProjectCreated |
ProjectContext |
Project was created in Draft state |
ProjectUpdated |
ProjectContext |
Metadata (name, tags, etc.) was modified |
ProjectTemplateAssigned |
ProjectContext |
A template was linked to the project |
ProjectInitialized |
ProjectLifecycleContext |
Signals orchestration layer to begin agent workflows |
ProjectStatusUpdated |
ProjectLifecycleContext |
Lifecycle state changed (e.g., Generating β Failed) |
ProjectGenerationStarted |
ProjectLifecycleContext |
Active generation phase has begun |
ProjectGenerationCompleted |
ProjectLifecycleContext |
All phases complete; project is marked Committed |
ProjectFailed |
ProjectLifecycleContext |
Generation or orchestration encountered unrecoverable error |
ProjectRetryRequested |
ProjectLifecycleContext |
Retry was triggered by user or orchestrator |
ProjectDeleted |
ProjectContext |
Project was soft-deleted (only allowed in Draft or Failed) |
AssignmentAdded |
ProjectAssignmentContext |
User or agent assigned to project/phase |
AssignmentRevoked |
ProjectAssignmentContext |
User or agent removed from project/phase |
π§ Event Consumers¶
| Event | Consumed By |
|---|---|
ProjectInitialized |
OrchestrationLayer β starts Vision Agent |
ProjectGenerationCompleted |
DevOpsAgent, StudioUI, Notification |
ProjectFailed |
NotificationService, StudioUI |
ProjectStatusUpdated |
TraceabilityContext, AuditLogService |
AssignmentAdded |
StudioUI, AccessControlContext |
π Sample Event: ProjectGenerationCompleted¶
{
"eventType": "ProjectGenerationCompleted",
"projectId": "proj-71f2",
"traceId": "trace-b9124",
"timestamp": "2025-05-05T12:21:00Z",
"actorId": "agent:Orchestrator",
"payload": {
"status": "Committed",
"servicesGenerated": 7,
"docsGenerated": true,
"finalGitCommit": "abc1234"
}
}
π¦ Event Versioning & Format¶
- All events are versioned (e.g.,
v1,v2) to allow backward compatibility - Emitted via outbox pattern and published to internal event bus
- All events carry:
eventTypeprojectIdtraceIdactorId(user or agent)timestamppayload(event-specific data)
π§© Integration with Observability¶
All events are:
- Correlated via
traceId - Logged into project audit logs
- Monitored via OpenTelemetry event spans
- Indexed in event store for historical replay
β Summary¶
Domain events in the Projects Management Domain represent a contract of intent and change. They enable orchestration, observability, agent collaboration, and auditability β forming the essential backbone of ConnectSoftβs autonomous and event-driven platform.
π§ API Reference β REST¶
The Projects Management Domain exposes a set of RESTful HTTP APIs that enable:
- Human and system users to interact with projects
- Agents and orchestrators to query project state or metadata
- External systems to integrate with ConnectSoft workflows
These APIs follow RESTful conventions, support multi-tenancy, and enforce RBAC policies.
π ProjectContext APIs¶
πΈ POST /api/projects¶
Create a new project
Request:
{
"name": "VetClinic Scheduler",
"description": "Booking system for veterinary clinics",
"domainTags": ["Healthcare", "SaaS"],
"industry": "Healthcare"
}
Response:
πΈ PATCH /api/projects/{id}¶
Update project metadata (name, description, tags)
πΈ POST /api/projects/{id}/template¶
Assign a solution template
πΈ GET /api/projects/{id}¶
Get full metadata of a specific project
πΈ GET /api/projects¶
List all projects for the current user (paginated)
Optional query params:
status=Generatingtag=Healthcareowned=true
πΈ DELETE /api/projects/{id}¶
Soft-delete project (only in Draft or Failed states)
π TemplateCatalogContext APIs¶
πΈ GET /api/templates¶
List available solution templates
πΈ GET /api/templates/{id}¶
Get full details of a specific template
πΈ GET /api/templates/{id}/structure¶
Preview generated folder structure
π ProjectLifecycleContext APIs¶
πΈ POST /api/projects/{id}/start¶
Start project generation (transition to Generating)
πΈ POST /api/projects/{id}/fail¶
Manually mark project as failed
Optional body:
πΈ POST /api/projects/{id}/retry¶
Retry failed project (transition to RetryRequested)
π TraceabilityContext APIs¶
πΈ GET /api/projects/{id}/trace¶
Get trace metadata and execution summary
πΈ GET /api/trace/{traceId}/agents¶
List all agents that executed under this trace
πΈ GET /api/trace/{traceId}/timeline¶
View ordered timeline of events in the trace
π ProjectAssignmentContext APIs¶
πΈ POST /api/projects/{id}/assignments¶
Assign user or agent to project
πΈ GET /api/projects/{id}/assignments¶
List all actors assigned to a project
π Security & Access¶
- All endpoints enforce OAuth2 (via OpenIddict)
- RBAC applied to allow:
Owner: full accessCollaborator: read + updateAgent: scoped per phase
- All endpoints are tenant-aware and scoped to tenant ID in JWT claims
π API Design Notes¶
| Feature | Supported |
|---|---|
| OpenAPI / Swagger Docs | β |
API Versioning (v1) |
β |
| Rate Limiting | β |
| CORS for agent systems | β |
| Retry-safe | β (idempotent commands where needed) |
β Summary¶
The REST APIs for the Projects Management Domain offer a clean, secure, and complete surface for driving project creation, orchestration, assignment, and traceability. They are used by both human users (via Studio UI) and autonomous agents/orchestrators throughout the software generation lifecycle.
π§ OpenAPI & Swagger UI Examples¶
This section illustrates how the Projects Management Domain APIs are defined and exposed using OpenAPI (Swagger). These definitions are used to:
- Generate client SDKs for agents and orchestration services
- Visualize endpoints and request/response schemas
- Validate requests in automated tests and CI/CD pipelines
All ConnectSoft APIs conform to OpenAPI 3.0+, with clean tagging and schema references for reuse.
π Project API Example (OpenAPI 3.0)¶
openapi: 3.0.3
info:
title: Projects API
version: v1
description: API for managing AI-generated software projects
servers:
- url: https://api.connectsoft.dev
tags:
- name: Projects
description: Core project operations
- name: Templates
description: Template catalog access
- name: Lifecycle
description: Lifecycle transitions
paths:
/api/projects:
post:
tags: [Projects]
summary: Create a new project
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/CreateProjectRequest'
responses:
'201':
description: Project created
content:
application/json:
schema:
$ref: '#/components/schemas/CreateProjectResponse'
/api/projects/{id}/template:
post:
tags: [Projects]
summary: Assign a template to a project
parameters:
- in: path
name: id
required: true
schema:
type: string
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/AssignTemplateRequest'
responses:
'200':
description: Template assigned
components:
schemas:
CreateProjectRequest:
type: object
required: [name]
properties:
name:
type: string
description:
type: string
domainTags:
type: array
items:
type: string
industry:
type: string
CreateProjectResponse:
type: object
properties:
projectId:
type: string
traceId:
type: string
status:
type: string
AssignTemplateRequest:
type: object
required: [templateId]
properties:
templateId:
type: string
π Swagger UI Preview¶
When served via Swagger UI (e.g., /swagger/index.html), users see:
- Endpoint summaries (e.g.,
POST /api/projects) - Interactive "Try it out" sections for manual testing
- JSON schema previews of request/response payloads
- Grouping by
tags: Projects, Templates, Lifecycle, Traceability
π§ Swagger UI Customizations¶
| Feature | Status |
|---|---|
| API version selector | β |
| Bearer token auth panel | β |
| Pre-filled examples | β |
| Collapsible sections | β |
| Links to external docs | β |
π¦ OpenAPI Usage by Agents¶
Autonomous agents (e.g., ProjectTrackerAgent, OrchestrationAgent) use OpenAPI specs to:
- Validate API compatibility
- Auto-generate HTTP clients (e.g., using NSwag / Refit / Kiota)
- Detect schema changes via CI
This allows agent teams to remain decoupled and backward-compatible even as APIs evolve.
π Secured Endpoints in Swagger¶
All endpoints in Swagger UI:
- Require OAuth 2.0 Bearer token (scoped)
- Respect RBAC permissions (e.g., owner-only for deletion)
- Can be used in test environments via pre-seeded sandbox tenants
π οΈ Generator Tooling¶
| Tool | Purpose |
|---|---|
Swashbuckle.AspNetCore |
Generates OpenAPI docs from ASP.NET Core |
NSwag |
Generates C# client SDKs for agents |
Kiota |
Supports multi-language client generation |
β Summary¶
The Projects Management Domain provides a clear, modern OpenAPI interface with Swagger UI for developers, agents, and testers. It supports automation, introspection, testing, and SDLC integration β aligning with ConnectSoftβs vision of intelligent and autonomous software delivery.
π§ Service Architecture¶
This section describes the internal architecture of services within the Projects Management Domain, following Clean Architecture and DDD principles. Each service is designed for modularity, testability, and separation of concerns, enabling autonomous agents and orchestrators to interact cleanly.
All services in this domain are implemented as modular .NET microservices, using the ConnectSoft Microservice Template.
π§± Layered Architecture (Clean Architecture)¶
flowchart TD
UI[API Layer (REST/gRPC)] --> App[Application Layer]
App --> Dom[Domain Layer]
App --> Infra[Infrastructure Layer]
Infra --> Ext[External Services (Bus, DB, Identity)]
| Layer | Description |
|---|---|
| API Layer | RESTful HTTP endpoints, gRPC contracts, versioning, auth |
| Application Layer | Use cases, command/query handlers, validation, orchestration boundaries |
| Domain Layer | Aggregates, value objects, domain services, events |
| Infrastructure Layer | DB access, messaging, API gateways, third-party adapters |
π§© Key Services¶
| Service | Role |
|---|---|
ProjectService |
Manages Project aggregate lifecycle and metadata |
TemplateCatalogService |
Provides access to available templates |
ProjectLifecycleService |
Handles lifecycle transitions and emits status change events |
TraceabilityService |
Correlates project trace IDs with agents, artifacts, and events |
ProjectAssignmentService |
Manages user/agent participation in projects |
βοΈ Internal Technologies Used¶
| Concern | Technology |
|---|---|
| DI & Composition | Microsoft.Extensions.DependencyInjection |
| REST API | ASP.NET Core 8 |
| Messaging | MassTransit + Azure Service Bus |
| Storage | PostgreSQL with NHibernate ORM |
| Event Persistence | Outbox Pattern with internal message bus |
| Validation | FluentValidation |
| OpenAPI | Swashbuckle |
| Telemetry | OpenTelemetry + Serilog |
| Configuration | Options Pattern + Key Vault |
| Security | OAuth2/OpenIddict JWT |
π§ͺ Testing Layers¶
| Layer | Testing Strategy |
|---|---|
| Domain | Pure unit tests for aggregates and value objects |
| Application | Command handler tests with mocks |
| API Layer | Integration tests via TestServer |
| Messaging | Consumer contract tests |
π οΈ Sample Structure (ProjectService)¶
/src/ProjectService
βββ Application
β βββ Commands
β βββ Queries
β βββ Validators
βββ Domain
β βββ Aggregates
β βββ Events
β βββ ValueObjects
βββ Infrastructure
β βββ Persistence
β βββ Messaging
β βββ Integrations
βββ Api
β βββ Controllers
β βββ Contracts
β βββ Middleware
βββ Tests
β βββ Unit
β βββ Integration
β»οΈ Extensibility & Agent Integration¶
- All commands can be invoked by agents using REST or gRPC
- TraceId and ActorId are accepted as headers or claims
- Domain events allow orchestration to react without coupling
- Feature toggles can enable/disable generation behaviors per agent
β Summary¶
Each service in the Projects Management Domain follows modular, event-driven, clean architecture principles β enabling autonomous generation, easy testing, and scalable collaboration with agents and humans alike. Services are loosely coupled through events and tightly aligned through consistent boundaries.
π§ Microservices Involved¶
This section identifies the independent microservices that collectively implement the Projects Management Domain. Each service is responsible for one or more bounded contexts, and communicates via domain events, REST/gRPC APIs, and the event bus.
All services conform to ConnectSoft standards: Clean Architecture, Event-Driven, Secure, and Multi-Tenant.
π§© Projects Management Microservices¶
| Microservice Name | Description | Bounded Contexts Covered |
|---|---|---|
ProjectService |
Core project aggregate management, metadata, status, templates | ProjectContext |
TemplateCatalogService |
Manages available templates and structural previews | TemplateCatalogContext |
ProjectLifecycleService |
Handles lifecycle state transitions and emits orchestration triggers | ProjectLifecycleContext |
TraceabilityService |
Tracks traceId, artifacts, and agent execution for a project | TraceabilityContext |
ProjectAssignmentService |
Assigns users/agents to lifecycle phases and enforces access policies | ProjectAssignmentContext |
π Microservice Interactions¶
graph TD
UI[Studio UI] --> API[API Gateway]
API --> PS(ProjectService)
API --> TS(TemplateCatalogService)
API --> LS(ProjectLifecycleService)
API --> TR(TraceabilityService)
API --> AS(ProjectAssignmentService)
PS -->|Event: ProjectInitialized| LS
LS -->|Event: ProjectGenerationStarted| ORCH(Orchestration Layer)
LS -->|Event: ProjectStatusUpdated| TR
ORCH -->|AgentProgressed| TR
π¦ Communication Types¶
| From β To | Type | Purpose |
|---|---|---|
ProjectService β ProjectLifecycleService |
Event (e.g., ProjectInitialized) |
|
LifecycleService β Orchestration Layer |
Event (e.g., ProjectGenerationStarted) |
|
All β TraceabilityService |
REST/gRPC for trace correlation | |
Studio UI β All services |
REST API via API Gateway |
π Security Boundaries¶
- Each service validates tenant ID and actor identity
- Assignment enforcement is handled at service boundaries
- Agents must be assigned before allowed to mutate any state
π§ Agent Integration¶
| Agent Role | Invokes Microservice(s) |
|---|---|
VisionArchitectAgent |
ProjectService, TraceabilityService |
BackendDeveloperAgent |
TemplateCatalogService, ProjectLifecycleService |
QAValidatorAgent |
TraceabilityService, ProjectLifecycleService |
DevOpsAgent |
ProjectLifecycleService, ProjectAssignmentService |
π Deployment Considerations¶
| Characteristic | Value |
|---|---|
| Language | C# (.NET 8) |
| Protocols | REST, gRPC, MassTransit Events |
| Observability | OpenTelemetry + Serilog |
| Auth | OpenIddict JWT + Role Scopes |
| Hosting | Kubernetes + Helm (multi-tenant) |
β Summary¶
The Projects Management Domain is implemented via 5 specialized microservices, each owning a bounded context. This separation supports scalability, clear ownership, fault isolation, and parallel team development, while remaining event-connected for unified orchestration.
π§ Agent Orchestration Flow¶
This section explains how the Projects Management Domain triggers and coordinates autonomous agents through the Orchestration Layer. Projects do not directly call agents β instead, they emit domain events that are picked up by orchestration services that activate agents with full context.
The flow is event-driven, observable, and traceable via traceId.
βοΈ High-Level Flow¶
sequenceDiagram
participant User
participant ProjectService
participant EventBus
participant OrchestrationLayer
participant VisionArchitectAgent
participant TraceabilityService
User->>ProjectService: CreateProject
ProjectService-->>EventBus: ProjectInitialized
EventBus-->>OrchestrationLayer: (subscribed handler)
OrchestrationLayer->>VisionArchitectAgent: StartDomainModeling(traceId)
VisionArchitectAgent-->>TraceabilityService: LogExecution(traceId)
VisionArchitectAgent-->>OrchestrationLayer: AgentCompleted(phase)
OrchestrationLayer-->>EventBus: ProjectGenerationCompleted
π§© Phased Agent Execution¶
Each project progresses through phases, where one or more agents are assigned and executed:
| Phase Name | Responsible Agent(s) | Triggering Event |
|---|---|---|
DomainModeling |
VisionArchitectAgent |
ProjectInitialized |
ServiceDesign |
EnterpriseArchitectAgent |
VisionModelConfirmed |
MicroserviceScaffolding |
BackendDeveloperAgent |
ServiceDesignCompleted |
Deployment |
DevOpsAgent |
AllServicesGenerated |
Validation |
QAValidatorAgent |
DeploymentCompleted |
Each agent receives:
traceIdprojectIdphaseName- Optional
assignmentContext
π Agent Lifecycle Events¶
| Event Emitted | Description |
|---|---|
AgentStarted |
Agent picked up phase (with timestamp) |
AgentProgressed |
Partial progress log (e.g., βScaffolding ⅖β) |
AgentFailed |
Failure occurred (includes logs, errors) |
AgentCompleted |
Phase finished successfully |
These are all correlated by traceId and stored in TraceabilityService.
π§ Orchestration Strategies¶
The Orchestration Layer determines:
- Which agents to trigger based on current
ProjectStatusand phase - If multiple agents should run concurrently or in sequence
- How to handle retries or fallbacks
- Whether a human approval is needed between phases
Agents are decoupled from each other, and orchestration enforces dependencies.
π¦ Project-Driven Entry Point¶
The lifecycle transition:
triggers the first orchestration cycle, handled by:
ProjectOrchestratorServiceAgentLifecycleTrackerAgentDispatcher
π Access & Identity¶
- All agents must be assigned to the project in
ProjectAssignmentContext - JWT or token includes:
actorId:agent:VisionArchitectAgenttraceId: scope for observabilitypermissions: phase-limited
π Observability Hooks¶
- All orchestration operations emit:
- OpenTelemetry spans:
agent.phase.execution - Events:
AgentCompleted,PhaseStarted,PhaseFailed
- OpenTelemetry spans:
- Studio UI and Ops dashboards use these for:
- Phase visualization
- Failure recovery
- Execution timelines
β Summary¶
The Agent Orchestration Flow enables autonomous, modular execution of software delivery phases via loosely-coupled agents. Projects emit events, orchestration reacts, agents act β and the entire process remains observable, traceable, and retry-safe.
π§ Traceability and Audit Logs¶
This section focuses on how every action, decision, and artifact across the project lifecycle is captured via traceability and audit logs. These logs ensure that:
- All agent activities are accountable
- Generated artifacts are linked to origins
- Debugging, compliance, and forensics are always possible
The TraceabilityContext owns this infrastructure, and its outputs are visualized in Studio UI, dashboards, and observability platforms.
π What is a Trace?¶
- A Trace is a system-wide correlation record, identified by
traceId, created per project. - It connects:
- Events (domain, orchestration)
- Agent activities
- Generated files, services, docs
- Failures and retries
- Timestamps, actors, transitions
π¦ Trace Record Model¶
| Field | Type | Description |
|---|---|---|
traceId |
Guid |
Unique for each project |
projectId |
ProjectId |
Linked to project aggregate |
createdBy |
string |
User or agent that initiated the project |
timeline |
List<EventLog> |
Ordered events from all services/agents |
artifacts |
List<Artifact> |
Files, services, repos, manifests, etc. |
agents |
List<AgentLog> |
Who did what, when, and how |
π Audit Timeline Example¶
[
{ "timestamp": "2025-05-05T12:00:01Z", "actor": "user-dmitry", "event": "ProjectCreated" },
{ "timestamp": "2025-05-05T12:01:12Z", "actor": "agent:VisionArchitectAgent", "event": "DomainModelGenerated" },
{ "timestamp": "2025-05-05T12:02:45Z", "actor": "agent:BackendDeveloperAgent", "event": "ServiceScaffolded:Appointments" },
{ "timestamp": "2025-05-05T12:06:20Z", "actor": "agent:DevOpsAgent", "event": "HelmChartGenerated" }
]
π§© Artifact Trace Linking¶
Each file or artifact has:
| Field | Description |
|---|---|
path |
File path or repo link |
generatedBy |
Agent ID |
phase |
Phase of project when generated |
traceId |
Global correlation ID |
sha256 |
Hash for integrity check |
Example:
{
"path": "src/Appointments.Application/Handlers/CreateAppointmentHandler.cs",
"generatedBy": "agent:BackendDeveloperAgent",
"traceId": "trace-4738a9",
"phase": "MicroserviceScaffolding"
}
π Security & Compliance¶
- Every transition, assignment, and command is logged with:
actorIdactionTyperesulttimestampclientIp(if human)
- Tamper-resistant via append-only log structure
- Immutable traces are persisted for audit trails
π§ How Agents Use Trace Logs¶
Agents:
- Query their own logs for
retryconditions - Emit structured logs and execution spans
- Push custom key-value tags into
TraceMetadata
π Dashboard Integration¶
Trace logs are visualized in:
- Studio UI β Project Timeline tab
- Grafana β Agent Execution Dashboard
- Kibana β Artifact + Span Explorer
- DevOps Reports β CI/CD trace view
π οΈ Technical Implementation¶
| Component | Tool/Pattern |
|---|---|
| Trace Store | PostgreSQL + ElasticSearch index |
| Log Aggregation | Serilog β Seq or Loki |
| OTEL Integration | OpenTelemetry trace exporters |
| Timeline API | GET /api/trace/{traceId}/timeline |
β Summary¶
Traceability and audit logs provide end-to-end visibility, accountability, and security across the autonomous software delivery lifecycle. They are essential for debugging, proving compliance, optimizing orchestration, and enabling multi-agent coordination at scale.
π§ Testing Strategy for Projects Management Domain¶
This section outlines the multi-layered testing strategy used to ensure the correctness, reliability, and regression safety of all components in the Projects Management Domain. The strategy aligns with ConnectSoftβs Clean Architecture and autonomous agent orchestration approach, covering both human-triggered and AI-driven workflows.
π― Testing Goals¶
- Validate correctness of project lifecycle transitions
- Ensure agents trigger only when authorized and assigned
- Guarantee traceability and auditability of all operations
- Confirm template scaffolds and status events emit correctly
- Support event-driven testing, not just request/response
π§ͺ Test Pyramid¶
graph TD
Unit[Unit Tests]
App[Application Tests]
Integration[Service Integration Tests]
Event[Event Contract Tests]
E2E[End-to-End (Agent Orchestration)]
Unit --> App
App --> Integration
Integration --> Event
Event --> E2E
π§© Test Types and Targets¶
| Type | Targets | Tools & Frameworks |
|---|---|---|
| Unit Tests | Aggregates, value objects, domain logic | xUnit / NUnit + FluentAssertions |
| Application Tests | Use cases, command/query handlers | Moq, FakeItEasy |
| Integration Tests | REST APIs, DB interactions, validations | ASP.NET TestHost + SQLite / Testcontainers |
| Event Contract Tests | Event payload structure & behavior | MassTransit TestHarness, ApprovalTests |
| E2E Agent Orchestration | Multi-agent lifecycle simulation | SpecFlow + Fake Orchestrator + Trace Mocks |
𧬠Sample Test: Project Lifecycle Transition¶
[Fact]
public async Task Project_Should_Transition_From_Draft_To_Initialized()
{
var projectId = await _client.CreateProject("Booking App");
await _client.InitializeProject(projectId);
var status = await _client.GetProjectStatus(projectId);
status.Should().Be(ProjectStatus.Initialized);
}
π§ Agent Simulation Tests¶
We use a fake orchestrator harness to:
- Simulate project phase transitions
- Inject fake agent responses
- Assert that only assigned agents execute
- Verify emission of
AgentCompletedβProjectGenerationCompleted
π Event Contract Test Example¶
[Fact]
public void ProjectInitialized_Should_Emit_Valid_Domain_Event()
{
var evt = ProjectEvents.ProjectInitialized(projectId, traceId);
evt.EventType.Should().Be("ProjectInitialized");
evt.Payload.ProjectId.Should().Be(projectId);
}
π Security & Access Control Tests¶
- Ensure unassigned agents/users cannot:
- Start transitions
- Write to protected endpoints
- Use JWT mocks with scopes:
actorId=agent:Xpermissions=ServiceScaffolding
- Validate enforcement of
ProjectAssignmentContexton all writes
π CI Integration¶
| Layer Tested | Trigger |
|---|---|
| Unit + App Layer | On every commit to any project microservice |
| Integration + API | On every push to develop or PR |
| E2E (Orchestration) | Nightly and pre-release pipelines |
| Event Contract | On schema or message version changes |
β Summary¶
The Projects Management Domain uses a robust, layered testing strategy to validate everything from domain logic to full lifecycle orchestration. This ensures safe multi-agent coordination, traceable state evolution, and continuous confidence in the platformβs autonomous SaaS factory behavior.
π§ Observability and Monitoring¶
This section describes the observability and monitoring infrastructure for the Projects Management Domain. It ensures all services, events, transitions, and agent executions are traceable, measurable, and diagnosable in real time β forming the backbone of platform transparency and system health.
π Observability Goals¶
- Trace project execution across all microservices and agents
- Monitor project status transitions, errors, and retries
- Visualize agent execution timelines and performance
- Alert on failed orchestration or prolonged inactivity
- Capture full event flow from trigger to commit
π Observability Stack¶
| Concern | Tool / Integration |
|---|---|
| Distributed Tracing | OpenTelemetry (OTEL) |
| Logs | Serilog β Seq / Loki / Elastic |
| Metrics | Prometheus + Grafana |
| Dashboards | Grafana Dashboards |
| Alerts | Grafana Alerts / Azure Monitor |
| Agent Monitoring | TraceabilityService + OTEL spans |
π Key OTEL Spans & Attributes¶
Example Span: project.lifecycle.transition¶
{
"traceId": "trace-abc123",
"span": "project.lifecycle.transition",
"attributes": {
"project_id": "proj-71f2",
"from_state": "Generating",
"to_state": "Committed",
"actor_id": "agent:Orchestrator",
"status": "Success"
}
}
Other important spans:¶
agent.execution.startedagent.execution.completedtemplate.scaffold.generatedartifact.pushed.gitproject.orchestration.retry_attempt
π₯οΈ Grafana Dashboards¶
| Dashboard Name | Description |
|---|---|
Project Lifecycle |
Shows real-time project state transitions |
Agent Activity Timeline |
Visualizes agent execution duration + status |
Event Bus Flow |
Shows domain event throughput and failure rate |
Template Usage |
Tracks most-used templates and scaffold types |
Retry & Failure Rate |
Alerts on frequent failures or stalled states |
π§ Traceability Integration¶
- Each agent request, file generated, event emitted includes
traceId - Allows stitching together full story of a project across services
- Studio UI shows
Project Timelineusing these logs and spans
π¨ Alerting Examples¶
| Alert Condition | Action Taken |
|---|---|
Project in Generating > 30 mins |
Notify dev team via Slack / Email |
AgentFailed events > threshold |
Open incident, alert DevOps |
| Missed domain events from orchestrator | Restart orchestration / emit retry |
| Git push missing post-commit | Trace artifact pipeline for errors |
π§© Metrics Examples¶
| Metric Name | Type | Description |
|---|---|---|
projects_created_total |
Counter | Projects created (by tenant, tag) |
project_lifecycle_transitions |
Counter | Count of state changes |
agent_execution_duration_secs |
Histogram | How long each agent takes per phase |
project_generation_failures |
Counter | Total failures in lifecycle |
active_traces_total |
Gauge | Traces in progress across all services |
β Summary¶
Observability and monitoring in the Projects Management Domain ensures end-to-end visibility across lifecycle states, agents, and automation flows. It enables rapid detection, root cause analysis, and continuous feedback β critical for operating ConnectSoftβs autonomous SaaS factory at scale.
π§ Failure Handling & Retry Logic¶
This section explains how the Projects Management Domain detects, records, and recovers from failures across orchestration, agents, and project states. Built-in retry logic, observability hooks, and human overrides ensure resilience in an autonomous agent-driven system.
π₯ Failure Types¶
| Failure Type | Examples | Source |
|---|---|---|
| Agent execution failure | Timeout, unhandled exception, output invalid | Agent runtime |
| Scaffold failure | Missing template file, generator misconfig | Template engine |
| Infrastructure error | Git push failed, file storage error | DevOps tools, Git, cloud storage |
| Domain constraint error | Illegal state transition, unassigned actor | Domain services |
| Orchestration fault | Unexpected message order, duplicate phase triggers | Orchestration Layer |
π Failure Capture Mechanisms¶
- All errors are reported to
TraceabilityContext - Events like
AgentFailed,ProjectFailed,RetryRequestedare emitted - Lifecycle state transitions to
Failed - Root cause is stored in
FailureLog
{
"traceId": "trace-9cda",
"projectId": "proj-913f",
"failedPhase": "MicroserviceScaffolding",
"agent": "BackendDeveloperAgent",
"reason": "Template config missing 'ServiceBus'",
"retryAvailable": true
}
π Retry Process¶
Manual Retry¶
Triggered via:
- Studio UI
POST /api/projects/{id}/retry- Command-line orchestrator
Flow:
- Validate project is in
Failed - Transition to
RetryRequested - Emit
ProjectRetryRequestedevent - Orchestration Layer replays failed phase(s)
- TraceId remains the same; retry history appended
Auto-Retry (configurable)¶
- Optional per-agent config (e.g., allow 1 retry on network timeout)
- Max retries per agent-phase (e.g., 1 or 2 retries max)
- Backoff strategy (exponential with jitter)
π§© Failure Recovery Strategies¶
| Scenario | Recovery Strategy |
|---|---|
| Agent failure | Retry same agent with fresh context |
| Orchestration loop stuck | Heartbeat detection + circuit breaker reset |
| Resource misconfig (e.g., Git) | Notify DevOpsAgent for reconciliation |
| Illegal transition | Log audit, skip to human approval or escalation |
π¨ Failure Notification Paths¶
- Domain events trigger:
- Slack / Discord alerts
- Ops dashboard highlights
- Studio UI status banners
- Trace dashboard shows failed step with context and logs
- Failure logs retained per
traceIdand exportable for audit
π Safety Constraints¶
- Retry only allowed from
FailedorRetryRequestedstates - Retry is idempotent (same
traceId) - Cannot retry phases out of order (validated by orchestrator)
- Forced overrides require elevated permissions (e.g., admin)
β Summary¶
Failure handling in the Projects Management Domain is designed to be resilient, observable, and retry-safe. Combined with audit trails and orchestration intelligence, it ensures that autonomous agents can fail gracefully, recover deterministically, and notify stakeholders in real time.
π§ Security & Access Control¶
This section defines how the Projects Management Domain enforces multi-tenant isolation, fine-grained authorization, and secure agent execution. It ensures that all REST, event, and agent-triggered actions are traceable, permission-bound, and identity-aware.
Security is built into all interactions across:
- Microservices
- Agents
- Users
- Events
- Artifacts
π Identity and Authentication¶
| Concern | Implementation |
|---|---|
| Human users | OAuth 2.0 / OpenID Connect via OpenIddict |
| Agents | JWT tokens with actorId=agent:* + scopes |
| Service-to-service | Mutual TLS + signed tokens (internal only) |
All JWT tokens include:
sub(subject = user or agent ID)tenant_idroles(e.g., Owner, Collaborator, Orchestrator)scopes(e.g.,project.write,agent.phase.execute)
π§© Role-Based Access Control (RBAC)¶
| Role | Permissions |
|---|---|
Owner |
Full control over project (create, update, delete) |
Collaborator |
View + modify metadata (no delete or commit) |
Agent |
Limited to assigned phase only |
Admin |
Override status, retry failed flows, full visibility |
Assignments are managed in ProjectAssignmentContext.
π Phase-Level Execution Control¶
Agents must satisfy:
- Assigned to the project and phase
- Authenticated via token (
actorId=agent:X) - Holding required scope (
agent.phase.execute) - Project is in a compatible state (e.g.,
Generating)
Failing any of these will return HTTP 403 Forbidden or event rejection.
π‘οΈ API Layer Protections¶
| Protection | Mechanism |
|---|---|
| Endpoint access | [Authorize(Roles = "Owner")] |
| Tenant isolation | Tenant ID from JWT claim |
| Input validation | FluentValidation + Anti-XSS/SQL checks |
| Rate limiting | IP + identity-aware throttling |
| CORS | Dynamic origins (agent + studio access) |
| Replay prevention | Idempotency keys on commands |
π Audit & Forensics¶
Every sensitive action logs:
actorId(user or agent)action(e.g., AssignTemplate, TransitionPhase)targetProjectIdtraceIdtimestampclientIp(if human)
Logs are routed to:
TraceabilityContextSecurityAuditService- SIEM connectors (future)
π Secrets Handling¶
- Agents never receive API keys or credentials directly
- Tokens expire quickly (e.g., 5 min) with refresh logic
- Secret parameters (e.g., Git tokens) injected via:
- Vault-backed config (e.g., Azure Key Vault)
- Scoped, encrypted message envelopes (WIP)
π§ͺ Security Test Coverage¶
| Test Type | Examples |
|---|---|
| Token spoofing prevention | Reject invalid actorId, tenant mismatches |
| Access control validation | Ensure phase execution requires assignment |
| Multi-tenant isolation | User from Tenant A cannot access Tenant B data |
| Agent impersonation | Must have agent identity, not human JWT |
β Summary¶
The Projects Management Domain enforces security by design, combining RBAC, token-based agent auth, and multi-tenant isolation. Every action is scoped, validated, and audit-logged β enabling safe collaboration between humans and agents in an enterprise-grade AI software factory.
π§ Event Bus Integration & Messaging Contracts¶
This section documents how the Projects Management Domain integrates with the internal event bus, defines messaging contracts, and supports agent orchestration, inter-service communication, and observability-first execution. The event bus is a backbone for loosely coupled microservices and autonomous agent flows.
π Event Bus Overview¶
| Feature | Implementation |
|---|---|
| Message transport | MassTransit + Azure Service Bus / RabbitMQ |
| Event pattern | Domain Events + Integration Events |
| Message format | CloudEvents (JSON) |
| Serialization | Newtonsoft.Json + versioned contracts |
| Dispatch mechanism | Outbox Pattern (guaranteed delivery) |
π¦ Key Message Types¶
πΉ Domain Events (Emitted Internally)¶
| Event Name | Source Microservice | Purpose |
|---|---|---|
ProjectInitialized |
ProjectService | Start orchestration |
ProjectGenerationStarted |
ProjectLifecycleService | Notify agents/orchestrator |
ProjectStatusUpdated |
ProjectLifecycleService | Notify dashboards / observability tools |
AgentCompleted |
Orchestration Layer | Phase success trigger |
AgentFailed |
Orchestration Layer | Failure handling and retry logic |
ProjectGenerationCompleted |
ProjectLifecycleService | Final state reached, ready to commit |
π§© Integration Events (Cross-Domain or Agent Use)¶
| Event Name | Purpose |
|---|---|
TemplatePreviewRequested |
Trigger rendering for Studio UI |
TraceAuditRequest |
Request full trace from another service |
ProjectAssignmentChanged |
Update cache or agent routing |
These events are published with topic-based routing by service or tenant ID.
π§Ύ Messaging Contract Sample¶
{
"type": "ProjectGenerationStarted",
"specversion": "1.0",
"source": "projects-lifecycle-service",
"id": "evt-7128a91f",
"time": "2025-05-05T13:42:00Z",
"datacontenttype": "application/json",
"data": {
"projectId": "proj-84dd",
"traceId": "trace-3a1fb9",
"status": "Generating",
"actorId": "agent:Orchestrator"
}
}
π Subscriptions & Routing¶
| Subscriber Service | Subscribed Events |
|---|---|
Orchestration Layer |
ProjectInitialized, RetryRequested |
TraceabilityService |
All project lifecycle & agent events |
Studio UI Notifications |
ProjectFailed, AgentCompleted |
DevOpsAgent |
ProjectGenerationCompleted |
SecurityAuditService |
AssignmentChanged, ProjectDeleted |
Topic naming:
π§ͺ Message Contract Testing¶
- Use MassTransit TestHarness for consumer contract tests
- Approval tests for event payload snapshots
- Fuzz tests for event schema resilience
- Consumer validation logic (e.g., traceId must be present)
π Retry & Deduplication¶
- All events support idempotency via message ID
- Retry policies for transient failures (e.g., max 3)
- Poison queue for persistent consumer errors
- DLQ alerting to observability layer
π§ Agent Event Usage¶
Agents listen for:
ProjectGenerationStartedβ to begin phaseAgentExecutionAbortedβ to cancel phaseTraceDataRequestedβ for debugging support
Agents emit:
AgentStarted,AgentCompleted,AgentFailed(with payload)
All events are wrapped in CloudEvent envelope with standard fields for traceability.
β Summary¶
Event Bus Integration enables real-time, decoupled, observable communication between all components in the Projects Management Domain. It supports domain-event-driven orchestration, robust failure handling, and flexible agent interaction β aligning with ConnectSoft's principles of scalability and modularity.
π§ Project Domain Summary & README Section Draft¶
This final cycle consolidates all 21 previous section into a concise summary and starter README section for the Projects Management Domain. It can be reused in internal documentation, repository READMEs, or developer portals to provide a clear overview.
π Projects Management Domain β Summary¶
The Projects Management Domain is a core component of the ConnectSoft AI Software Factory. It enables users and intelligent agents to collaboratively:
- Create, configure, and manage software generation projects
- Assign solution templates and manage metadata
- Trigger and track multi-phase, agent-driven software delivery
- Enforce lifecycle state transitions with observability and control
- Trace every artifact, agent action, and status change across the lifecycle
It supports modular, multi-tenant, event-driven, and secure workflows, enabling fully autonomous SaaS solution generation.
π§© Key Bounded Contexts¶
| Context | Purpose |
|---|---|
ProjectContext |
Manages core project metadata, template selection |
TemplateCatalogContext |
Exposes solution templates and previews |
ProjectLifecycleContext |
Governs project state transitions (Draft β Committed) |
ProjectAssignmentContext |
Controls user/agent assignments and access per phase |
TraceabilityContext |
Links traceId to agents, artifacts, and events |
βοΈ Architecture Highlights¶
- Clean Architecture and DDD principles in all microservices
- Stateless REST + gRPC APIs with OpenAPI definitions
- MassTransit + Azure Service Bus for event-driven communication
- Fully observable via OpenTelemetry, Prometheus, Serilog, and Grafana
- Agent-safe execution and role-based access control (RBAC)
π§ Agent Collaboration¶
Agents do not interact directly with each other. Instead:
- Each phase is triggered via orchestration events
- Agents receive traceId,
projectId, and assigned phase - Progress and outcomes are published back as events
TraceabilityServiceprovides full cross-phase insight
β
README Section: README.md¶
# π§ Projects Management Domain β ConnectSoft AI Software Factory
This microservice domain manages the lifecycle of autonomous software generation projects. It enables human users and AI agents to:
- Initialize new projects with clean architecture templates
- Trigger agent-based orchestration for modeling, scaffolding, and deployment
- Monitor status transitions from Draft β Committed
- Assign users/agents to specific project phases securely
- Trace every artifact and decision via traceId
## π§ Technology Stack
- .NET 8 (ASP.NET Core + Clean Architecture)
- MassTransit + Azure Service Bus (Event-Driven)
- PostgreSQL + NHibernate (Persistence)
- OpenTelemetry + Prometheus + Grafana (Observability)
- OpenIddict (OAuth2 / OpenID Connect Auth)
## π§© Microservices
- `ProjectService`
- `ProjectLifecycleService`
- `TemplateCatalogService`
- `ProjectAssignmentService`
- `TraceabilityService`
## π Security
- Role-based access control (Owner, Collaborator, Agent)
- Phase-specific execution enforcement
- Tenant-isolated JWT authentication
## π Documentation
Full documentation available in the [Platform Docs](https://docs.connectsoft.dev/projects).