Skip to content

πŸ“˜ 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
Hold "Alt" / "Option" to enable pan & zoom

🧩 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 ProjectInitialized to 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 ProjectCreated or ProjectUpdated

Key Aggregates:

  • Project
  • ProjectId

APIs/Commands:

  • CreateProject
  • UpdateProjectMetadata
  • AssignTemplateToProject

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:

  • SolutionTemplate
  • TemplateId

APIs/Queries:

  • ListAvailableTemplates
  • GetTemplateById
  • PreviewTemplateStructure

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 ProjectStatusUpdated events
  • Allow retries and manual overrides

Key Concepts:

  • ProjectStatus enum
  • LifecycleTransitionLog

Commands:

  • StartProjectGeneration
  • UpdateProjectStatus
  • RetryFailedProject

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:

  • TraceLink
  • ProjectTraceMetadata

APIs:

  • GenerateTraceId
  • GetTraceArtifactsByProjectId
  • ListAgentsByTraceId

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:

  • ProjectAssignment
  • LifecyclePhase

APIs:

  • AssignAgentToProjectPhase
  • GetProjectAssignments

πŸ” 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

public enum ProjectStatus
{
    Draft,
    Initialized,
    Generating,
    Committed,
    Failed,
    RetryRequested
}

πŸ”„ 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

  • Name must be unique per tenant
  • TraceId is required and immutable
  • Status must follow valid transition flow
  • TemplateId can only be assigned once unless in Draft state
  • CreatedBy must 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
Hold "Alt" / "Option" to enable pan & zoom

πŸ“¦ 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 Failed state 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:

  • ProjectStatusUpdated domain event
  • OTEL span: project.lifecycle.transition with attributes:
    • trace_id
    • project_id
    • from_state
    • to_state
    • actor_id
    • timestamp

πŸ“‹ 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 Project aggregate in Draft state
  • Generates ProjectId, TraceId, Slug, and CreatedAt
  • Emits ProjectCreated event

πŸ” Output

{
  "projectId": "proj-38fb",
  "status": "Draft",
  "traceId": "trace-a9d4",
  "createdAt": "2025-05-05T10:45:00Z"
}

πŸ“Œ Use Case: UpdateProjectMetadata

πŸ”§ Input

{
  "name": "VetSaaS Scheduler",
  "description": "Updated to reflect expanded scheduling scope"
}

βœ… Behavior

  • Validates if project is not in Committed state
  • Updates mutable fields
  • Emits ProjectUpdated event

πŸ“Œ Use Case: AssignTemplateToProject

πŸ”§ Input

{
  "templateId": "tpl-microservice-cleanarch-v1"
}

βœ… Behavior

  • Verifies template exists via TemplateCatalogContext
  • Binds TemplateId to the project
  • Emits ProjectTemplateAssigned event

πŸ“Œ 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 Draft or Failed
  • 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
GET /api/templates

πŸ“Œ Use Case: GetTemplateById

  • Returns full metadata for one specific template
  • Verifies template exists before assignment to project
GET /api/templates/tpl-microservice-cleanarch-v1

πŸ“Œ 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, or capability
  • Useful for targeting templates for specific use cases (e.g., mobile app, auth service)
GET /api/templates?tag=Auth

πŸ“Œ Use Case: ValidateTemplateUsability

  • Ensures the selected template supports the transport (e.g., REST, MassTransit)
  • Prevents invalid assignments in AssignTemplateToProject

🧠 Agent Usage

  • Agents like MicroserviceGeneratorAgent and GatewayGeneratorAgent query 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

public enum ProjectStatus
{
    Draft,
    Initialized,
    Generating,
    Committed,
    Failed,
    RetryRequested
}

πŸ“Œ Use Case: StartProjectGeneration

  • Preconditions: Project must be in Initialized state
  • Actions:
    • Transition to Generating
    • Emit ProjectStatusUpdated
    • Send ProjectInitialized event to Orchestration Layer

πŸ“Œ 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 ProjectFailed event
  • Records failedReason and 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:

  • projectId
  • from, to
  • traceId
  • actorId
  • timestamp

πŸ“‹ 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 CreateProject command
  • Produces a UUID-formatted ID (e.g., trace-a84cdd2a)
  • Stored in both Project and TraceRegistry
{
  "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)
    • Collaborator
    • Reviewer
  • 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, and Phase where 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:

Is this agent assigned to the current project’s active phase?

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:
    • eventType
    • projectId
    • traceId
    • actorId (user or agent)
    • timestamp
    • payload (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:

{
  "projectId": "proj-91af",
  "traceId": "trace-c102",
  "status": "Draft"
}

πŸ”Έ PATCH /api/projects/{id}

Update project metadata (name, description, tags)


πŸ”Έ POST /api/projects/{id}/template

Assign a solution template

{
  "templateId": "tpl-microservice-cleanarch-v1"
}

πŸ”Έ 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=Generating
  • tag=Healthcare
  • owned=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:

{
  "reason": "QA validator agent timeout"
}

πŸ”Έ 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

{
  "actorId": "agent:BackendDeveloperAgent",
  "role": "Developer",
  "phase": "ServiceScaffolding"
}

πŸ”Έ 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 access
    • Collaborator: read + update
    • Agent: 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)]
Hold "Alt" / "Option" to enable pan & zoom
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
Hold "Alt" / "Option" to enable pan & zoom

πŸ“¦ 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
Hold "Alt" / "Option" to enable pan & zoom

🧩 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:

  • traceId
  • projectId
  • phaseName
  • 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 ProjectStatus and 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:

ProjectCreated β†’ ProjectInitialized β†’ ProjectGenerationStarted

triggers the first orchestration cycle, handled by:

  • ProjectOrchestratorService
  • AgentLifecycleTracker
  • AgentDispatcher

πŸ” Access & Identity

  • All agents must be assigned to the project in ProjectAssignmentContext
  • JWT or token includes:
    • actorId: agent:VisionArchitectAgent
    • traceId: scope for observability
    • permissions: phase-limited

πŸ” Observability Hooks

  • All orchestration operations emit:
    • OpenTelemetry spans: agent.phase.execution
    • Events: AgentCompleted, PhaseStarted, PhaseFailed
  • 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:
    • actorId
    • actionType
    • result
    • timestamp
    • clientIp (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 retry conditions
  • 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
Hold "Alt" / "Option" to enable pan & zoom

🧩 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:X
    • permissions=ServiceScaffolding
  • Validate enforcement of ProjectAssignmentContext on 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.started
  • agent.execution.completed
  • template.scaffold.generated
  • artifact.pushed.git
  • project.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 Timeline using 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, RetryRequested are 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:

  1. Validate project is in Failed
  2. Transition to RetryRequested
  3. Emit ProjectRetryRequested event
  4. Orchestration Layer replays failed phase(s)
  5. 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 traceId and exportable for audit

πŸ” Safety Constraints

  • Retry only allowed from Failed or RetryRequested states
  • 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_id
  • roles (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:

  1. Assigned to the project and phase
  2. Authenticated via token (actorId=agent:X)
  3. Holding required scope (agent.phase.execute)
  4. 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)
  • targetProjectId
  • traceId
  • timestamp
  • clientIp (if human)

Logs are routed to:

  • TraceabilityContext
  • SecurityAuditService
  • 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:

projects.events.{eventType}.{tenantId}

πŸ§ͺ 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 phase
  • AgentExecutionAborted β†’ to cancel phase
  • TraceDataRequested β†’ 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
  • TraceabilityService provides 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).