Skip to content

πŸ” Template Catalog

🧭 Purpose

The TemplateCatalog Domain is a foundational pillar of the ConnectSoft AI Software Factory, enabling autonomous agents and users to select and apply reusable, versioned, and validated solution templates.

It acts as the source of truth for generation blueprints, powering everything from microservices to gateways, infrastructure, libraries, and shared modules.


🧩 Core Objectives

  • Catalog and manage templates for .NET-based SaaS solutions
  • Provide structured metadata for discovery and intelligent selection
  • Offer preview and validation capabilities before application
  • Enable automated consumption by agents during project generation
  • Track template versions, usage, and validation status

πŸ‘₯ Consumers of the Domain

Consumer Type Description
Autonomous Agents Select, preview, and apply templates during code generation phases
Human Users Browse templates in Studio UI when configuring projects
Orchestrators Validate that required templates are available before phase execution
Validators & CI Perform template linting, structure validation, and output testing

🎯 Business Capabilities

Capability Example
Discover reusable templates β€œList all templates for Event-Driven Microservices”
Preview template structure β€œShow folders and tokens in template-cleanarch-microservice”
Validate template metadata β€œEnsure each template has semantic version and compatibility tag”
Apply template via command β€œGenerate project using template-authserver-v2.1.0”
Audit template usage β€œTrack how many times template-gateway-v1.0.0 was used”

πŸ—‚οΈ Template Types

Type Description
Microservice DDD + CleanArch + EventBus powered service scaffold
Library Shared reusable packages for validation, tracing, etc.
API Gateway Reverse proxy templates with routing and versioning
Auth Server OpenIddict-based identity provider scaffold
Infrastructure IaC (Bicep, Terraform), pipelines, Helm charts

🧱 Domain Placement in the Platform

flowchart TD
  Studio[Studio UI] --> Catalog[TemplateCatalog Domain]
  Agent[DeveloperAgent / VisionArchitectAgent] --> Catalog
  Orchestrator --> Catalog
  Catalog --> ProjectService
  Catalog --> TraceabilityService
Hold "Alt" / "Option" to enable pan & zoom

πŸ” Security Model

  • Only authorized users/agents can register or publish templates
  • Read operations (list/preview) scoped to tenant + visibility (public/private)
  • RBAC enforced via OpenIddict-scoped tokens

🌐 Interfaces

Interface Purpose
REST APIs List, preview, fetch metadata
Internal Events TemplatePublished, TemplateValidated
Studio UI Panels Browse/search/select templates
Agent Protocols Minimal preview API for fast agent consumption

🧠 Alignment with AI Agents

The domain supports:

  • Template resolution by tag, type, domain
  • Auto-completion for agent prompt engineering
  • Context-rich token maps for intelligent scaffolding

The TemplateCatalog Domain transforms static code templates into a dynamic, intelligent catalog for scalable software generation. It supports ConnectSoft’s AI agents with machine-readable metadata, phase-safe validation, and version-aware templating, forming the library of blueprints for building modular SaaS platforms.


🧭 Bounded Contexts

This cycle defines the bounded contexts within the TemplateCatalog Domain. These contexts group related responsibilities, data models, and services, enabling clear separation of concerns, scalability, and modular ownership.


🧩 Bounded Contexts Overview

Context Name Responsibility
TemplateRegistryContext Store and manage template definitions, metadata, versions
TemplateStructureContext Provide real-time preview of the template folder/file structure
TemplateValidationContext Ensure templates are syntactically and semantically valid
TemplateSearchContext Handle queries, filtering, and recommendations for template discovery
TemplateAnalyticsContext Track template usage, popularity, and performance insights

🧱 1. TemplateRegistryContext

Description

Central registry of all templates, including:

  • Template ID
  • Type (Microservice, Gateway, etc.)
  • Tags, domain areas, compatible tech stacks
  • Visibility (public/private)
  • Version history

Primary Entity

Template {
  TemplateId,
  Name,
  Type,
  CurrentVersion,
  TenantId,
  Visibility,
  Tags[],
  DomainAreas[],
  CompatibilityMatrix
}

πŸ“‚ 2. TemplateStructureContext

Description

Provides a previewable virtual file structure:

  • Folder hierarchy
  • Placeholders (e.g., {{ProjectName}})
  • Token resolution metadata
  • File type classifications

Examples

  • Show rendered structure of a template in Studio UI
  • Identify all tokens required to scaffold

βœ”οΈ 3. TemplateValidationContext

Description

Validates templates before publication:

  • Check token syntax ({{TokenName}})
  • Validate required files (README, config)
  • Ensure compatibility fields are present
  • Output structure verification (dry-run generation)

Events Emitted

  • TemplateValidated
  • TemplateValidationFailed

πŸ” 4. TemplateSearchContext

Description

Enables search, filtering, and intelligent discovery:

  • Fuzzy name search
  • Tag matching
  • Domain-specific filtering
  • Recommendation model (agent-persona aligned)

Search Parameters

{
  "type": "microservice",
  "tags": ["event-driven", "nhibernate"],
  "compatibleWith": ".NET 8"
}

πŸ“ˆ 5. TemplateAnalyticsContext

Description

Tracks usage and success metrics:

  • How often a template is used
  • Agent vs human initiators
  • Failure rate during generation
  • Most popular templates per tag/domain

Metrics Examples

  • template_usage_total
  • template_validation_failures
  • template_selection_by_agent

πŸ“¦ Interactions Across Contexts

flowchart TD
  TemplateRegistry --> Validation
  Validation --> TemplateRegistry
  TemplateRegistry --> Structure
  Structure --> UI
  TemplateRegistry --> Search
  TemplateRegistry --> Analytics
  Analytics --> Dashboards
Hold "Alt" / "Option" to enable pan & zoom

Each context is independently deployable but shares common tenant isolation and traceability contracts.


🧠 Benefits of Context Separation

  • Each context can evolve independently
  • Easier CI/CD pipelines per capability
  • Different teams or agents can own different flows
  • Improves testability and observability

The TemplateCatalog Domain is decomposed into five focused bounded contexts, covering everything from registration and structure preview to search, validation, and analytics. This design supports modularity, automation, and high-performance consumption by AI agents and human users alike.


βœ… Cycle 2 Completed

Shall we continue to Cycle 3: Template Types and Use Cases?

Let's continue with:


πŸ” Cycle 3: TemplateCatalog Domain – Template Types and Use Cases

🧭 Purpose

This cycle catalogs the different types of templates supported by the ConnectSoft TemplateCatalog Domain and maps them to the use cases they enable across projects, agents, and domains.

These templates are the foundational blueprints for autonomously generating full-stack, secure, clean-architecture SaaS systems.


πŸ“¦ Template Categories

Type Description
Microservice DDD-aligned service templates (domain, app, infra, API)
Library Shared, reusable class libraries (e.g., logging, validation, auth)
API Gateway Reverse proxy and API composition templates
Identity Server Auth server templates (OpenIddict-based)
Infrastructure Infrastructure-as-code: Bicep, Terraform, Docker, Helm, pipelines
Frontend Optional UI templates (Blazor, Angular, etc.)
Orchestration Agent Agent behavior templates (agent personas with skills and toolchains)
CI/CD Templates for GitHub/Azure DevOps pipelines, environments, stages

🧠 Supported Template Technologies

Stack / Feature Support Notes
.NET 8 / CleanArch βœ… Core backend stack for all code-based templates
NHibernate / MassTransit βœ… Supported via template tokens
OpenTelemetry / Serilog βœ… Built-in for observability templates
Azure Key Vault / Bicep βœ… Infra templates include secure cloud-native setup
SpecFlow / MSTest βœ… Included in microservice + test scaffold
Blazor / Angular βœ… Frontend templates available in preview

🧩 Use Case Mappings

Use Case Template Type(s) Involved
Bootstrap a new project with 3 DDD services Microservice templates (template-cleanarch-*)
Add OpenIddict-based auth to a project Identity Server + Auth Scaffolding templates
Create shared logging library with Serilog Library template (template-shared-logging)
Define infrastructure for deployment Bicep / Helm templates (template-infra-*)
Build a CI/CD pipeline with quality gates CI/CD pipeline template (template-pipeline-azdev)
Launch a message-based service Microservice + MassTransit + DomainEvent template
Scaffold new Orchestrator Agent persona Agent orchestration persona template

πŸ§‘β€πŸ’» Persona Examples

Persona Consumed Template Types
BackendDeveloperAgent Microservice, Library, Message Templates
DevOpsAgent Infra, Bicep, CI/CD, Helm
QAValidatorAgent Test templates, CI/CD, Metrics collectors
VisionArchitectAgent Domain-first template recommendation engine
Studio User Manually selects templates in Studio UI

🧠 Template Composition Rules

Templates can be:

  • Standalone: Full-featured templates used independently (e.g., template-authserver)
  • Composable: Small modules that plug into others (e.g., template-shared-validation)
  • Parameterized: Tokens like {{ServiceName}}, {{Domain}}, {{HasBus}} control structure

πŸ§ͺ Example: Microservice Template Use

Template ID: template-cleanarch-microservice

Capability Included
Clean Architecture βœ… Yes
Event Bus βœ… Optional via token
NHibernate Integration βœ… Toggle via UseNHibernate token
Unit Testing Setup βœ… SpecFlow + MSTest
OpenAPI Support βœ… Swashbuckle
Health Checks / Logging βœ… Built-in

βœ… Summary

The TemplateCatalog Domain supports a diverse, extensible set of template types, powering the entire AI software factory. These templates enable reusable, consistent, and secure code and infrastructure generation across the entire SDLC, for both humans and autonomous agents.


βœ… Cycle 3 Completed

Shall we continue with Cycle 4: Template Registration Workflow?

Here is the regenerated Cycle 4, fully aligned with NuGet-based template registration via Azure Artifacts, in addition to traditional ZIP uploads:


πŸ” Cycle 4: TemplateCatalog Domain – Template Registration Workflow (with NuGet Support)

🧭 Purpose

This cycle describes how templates are registered into the TemplateCatalog, supporting both:

  • Traditional ZIP-based templates (manual or Studio UI uploads)
  • NuGet-hosted templates from Azure Artifacts, aligning with ConnectSoft’s internal DevOps practices

The system supports versioning, validation, preview, and agent-safe consumption for both formats.


πŸ“¦ Template Registration Inputs

Input Type Supported Source Typical Use Case
ZIP Upload Manual Studio UI / Agent API Non-code assets or prototype templates
NuGet Package Azure Artifacts feed Production-ready code, pipelines, libraries

πŸ”— Unified Registration API

POST /api/templates/register

JSON Payload Example: NuGet Source

{
  "source": "nuget",
  "packageId": "ConnectSoft.Templates.Microservice.CleanArch",
  "packageVersion": "2.3.1",
  "feed": "https://pkgs.dev.azure.com/connectsoft/_packaging/PlatformTemplates/nuget/v3/index.json"
}

JSON Payload Example: ZIP Upload

{
  "source": "zip",
  "file": "<Base64EncodedZIP>",
  "metadata": {
    "type": "microservice",
    "tags": ["ddd", "cleanarch", "event-driven"],
    "visibility": "private"
  }
}

🧱 Required Template Structure

Inside .nupkg or .zip:

template/
β”œβ”€β”€ .template.json         # Template descriptor
β”œβ”€β”€ tokens.json            # Required tokens and types
β”œβ”€β”€ README.md              # Description for UI/agents
└── src/                   # File structure for generation

βœ… These files are extracted from content/template/ in .nupkg or root of ZIP.


πŸ” Registration Flow

sequenceDiagram
  participant Dev as Studio/Agent
  participant Registry as TemplateRegistryService
  participant Nuget as NuGetClient
  participant Validator as TemplateValidationService
  participant Preview as TemplateStructureService
  participant Bus as EventBus

  Dev->>Registry: RegisterTemplate (source = nuget or zip)
  alt source == nuget
    Registry->>Nuget: Fetch .nupkg (from Azure Artifacts)
    Nuget-->>Registry: Returns extracted /template/
  end
  Registry->>Validator: ValidateTemplate
  Validator-->>Registry: ValidationResult βœ…
  Registry->>Preview: ExtractStructure()
  Registry-->>Bus: Emit TemplatePublished
  Registry-->>Dev: 201 Created + TemplateId
Hold "Alt" / "Option" to enable pan & zoom

πŸ›‘οΈ Validation Rules

Rule Description
.template.json required Declares type, version, tags, compatibility
tokens.json must match file tokens Prevents generation errors
Version follows SemVer Required for upgradeability
Compatibility declared .NET, OS, agent skill alignment
Folder layout valid At least one src/ folder with valid files

🧠 NuGet Integration Details

  • Uses NuGet.Protocol / NuGet.Client to pull from:

  • Azure Artifacts feed

  • Any authenticated private feed
  • Supports:

  • .nupkg download + extraction

  • PAT or Azure CLI token for secure auth
  • Auto-retry and caching of packages

πŸ“¦ Events Emitted

Event Name Trigger
TemplatePublished After validation and preview generation
TemplateValidated Structural validation success
TemplateValidationFailed Failed structure or metadata check
TemplatePreviewReady Preview file tree ready for Studio UI

❌ If Validation Fails

  • Template is marked with status: invalid
  • Agents cannot consume until re-upload or fix
  • Detailed feedback returned and emitted in event

βœ… After Registration

  • Template visible in Studio UI (searchable by type, tag, compatibility)
  • Agents can apply using:
    • templateId:version
    • Metadata queries (e.g., type=microservice&tags=event-driven)
  • Usage is logged into TemplateAnalyticsContext

πŸ” Security Considerations

Concern Mechanism
Authenticated Feed Use PAT, Managed Identity, or Token Cache
RBAC on template Ownership, visibility, tenant scope
Replay Prevention Package hash + template version uniqueness

βœ… Summary

ConnectSoft supports dual-mode template registration, allowing NuGet-based templates from Azure Artifacts as first-class citizens alongside ZIP uploads. This enables high-quality, versioned, CI/CD-tested scaffolds to power autonomous software generation reliably and securely.


βœ… Cycle 4 (Regenerated with NuGet Support) Completed

Would you like to proceed with Cycle 5: Metadata and Tagging Model next?

Let's move forward with:


πŸ” Cycle 5: TemplateCatalog Domain – Metadata and Tagging Model

🧭 Purpose

This cycle defines the metadata schema and tagging conventions used in the TemplateCatalog Domain to support:

  • Agent discovery
  • Studio filtering
  • Compatibility matching
  • Intelligent scaffolding decisions

Metadata is central to enabling templates to be searchable, composable, and context-aware.


🧾 Metadata Schema

Each template includes a .template.json file with the following structure:

{
  "id": "template-cleanarch-microservice",
  "version": "2.3.1",
  "name": "Clean Architecture Microservice",
  "type": "microservice",
  "description": "Domain-Driven microservice template with NHibernate and MassTransit",
  "visibility": "public",
  "tags": ["cleanarch", "ddd", "event-driven", "nhibernate"],
  "compatibleWith": [".NET 8", "Azure", "OpenTelemetry"],
  "entryPoint": "src",
  "author": "connectsoft-devteam",
  "tenantId": "connectsoft"
}

🏷️ Tagging Model

πŸ”Ή Tag Types

Tag Group Purpose Examples
Architecture Identify core design patterns cleanarch, modular, ddd
Tech Stack Indicate supported platforms & libraries .NET 8, nhibernate, serilog
Domain Tags Functional domain alignment identity, ecommerce, booking
Tooling Associated dev tools specflow, opentelemetry, bicep
Runtime Tags Infrastructure and cloud compatibility azure, kubernetes, serverless

βœ… Tags are normalized and validated at registration (lowercase, no spaces, 3–32 characters)


🧠 Agent Query Matching

Agents use metadata to discover templates:

{
  "type": "microservice",
  "tags": ["event-driven", "ddd"],
  "compatibleWith": ".NET 8"
}

The system responds with a ranked list of template IDs with version info and descriptions.


πŸ” Studio UI Filtering

Studio UI provides users with:

  • Faceted search by tag group
  • Auto-complete on tag input
  • Visual indicators for compatibility and tech stack

🧩 Compatibility Field

The compatibleWith array defines:

  • .NET versions
  • Hosting platform (e.g., Azure, Kubernetes)
  • DevOps environment (e.g., GitHub Actions, Azure Pipelines)

This ensures:

  • Agent execution environments match template requirements
  • Scaffolded output will integrate cleanly with surrounding services

πŸ“š Example Template Metadata

ConnectSoft.Templates.Library.Validation

{
  "id": "template-validation-lib",
  "type": "library",
  "tags": ["fluentvalidation", "shared", "crosscutting"],
  "compatibleWith": [".NET 6", ".NET 8"]
}

ConnectSoft.Templates.Infra.CICD.AzurePipeline

{
  "type": "ci-pipeline",
  "tags": ["azure-pipelines", "multistage", "devops"],
  "compatibleWith": ["Azure DevOps"]
}

πŸ” Visibility Model

Visibility Value Access Scope
public Visible to all tenants and agents
private Visible only to the creator (user/agent/tenant)
internal Visible to ConnectSoft platform agents only

πŸ“Š Indexing & Search Storage

Metadata is indexed in:

  • TemplateCatalogDB (PostgreSQL)
  • Optionally synced to TemplateSearchService (Elastic/Lucene-style index)
  • Tags and compatibility fields are stored as searchable arrays

πŸ“¦ Agent Matching Logic (Pseudocode)

var matches = catalog
  .Where(t => t.Type == "microservice")
  .Where(t => t.Tags.Intersect(["event-driven", "cleanarch"]).Count() >= 2)
  .Where(t => t.CompatibleWith.Contains(".NET 8"));

βœ… Summary

The metadata and tagging model enables rich, intelligent interaction between humans, agents, and templates. It powers search, filtering, validation, compatibility matching, and analytics β€” forming the semantic backbone of the TemplateCatalog.


βœ… Cycle 5 Completed

Shall we proceed with Cycle 6: Template Structure & Tokens?

Let’s move forward with:


πŸ” Cycle 6: TemplateCatalog Domain – Template Structure & Tokens

🧭 Purpose

This cycle defines how templates are structured on disk, how dynamic content is represented using tokens, and how agents or scaffolders use this structure to generate real, project-specific output.

Template structure is what transforms abstract metadata into real code and configuration.


πŸ“ Template Structure

Templates are typically rooted in a src/ directory (or a declared entryPoint), containing a full solution scaffold, including:

template/
β”œβ”€β”€ .template.json           # Metadata
β”œβ”€β”€ tokens.json              # Declares dynamic tokens
β”œβ”€β”€ README.md                # Optional - shown in UI
└── src/
    β”œβ”€β”€ Domain/
    β”‚   └── {{EntityName}}.cs
    β”œβ”€β”€ Application/
    β”œβ”€β”€ Infrastructure/
    β”œβ”€β”€ Api/
    β”‚   └── Controllers/
    β”‚       └── {{EntityName}}Controller.cs
    └── Tests/

βœ… File and folder names, as well as contents, may include dynamic tokens like {{EntityName}}, {{ProjectName}}, {{HasMassTransit}}


🧩 Token System

πŸ”Ή Token Definition File: tokens.json

{
  "ProjectName": {
    "type": "string",
    "description": "Name of the generated project"
  },
  "EntityName": {
    "type": "string",
    "description": "Primary domain entity (e.g., Order, Product)"
  },
  "UseMassTransit": {
    "type": "boolean",
    "description": "Should the microservice be event-driven?"
  }
}

Agents or humans supply values for these tokens at generation time.


πŸ› οΈ Token Usage Locations

Location Examples
πŸ“„ Filenames src/Domain/{{EntityName}}.cs
πŸ“ Folder names src/Api/Controllers/{{EntityName}}
πŸ“ File contents namespace {{ProjectName}}.Domain.Entities;
πŸ” Conditional blocks #if (UseMassTransit) ... #endif (for C# or template DSL)

πŸ§ͺ Token Evaluation Process

  1. Token extraction during registration
  2. Token validation against tokens.json
  3. User/agent provides values via prompt or UI
  4. Template engine applies tokens (via TemplateScaffolderService)
  5. Resulting structure is written into target project directory

πŸ”„ Example Transformation

Template:

src/Api/Controllers/{{EntityName}}Controller.cs

Input:

{ "EntityName": "Customer" }

Generated:

src/Api/Controllers/CustomerController.cs

And inside file:

public class CustomerController : ControllerBase { ... }

πŸ’‘ Advanced Token Features (Planned/Future)

Feature Description
Token value inference Agents can infer tokens from project context (e.g., Domain)
Token dependencies Conditional visibility or requirements based on others
Collections Allow iterating over a list of tokens (e.g., entities[])
Multilingual tokens For localized templates (future multi-market support)

πŸ“š Token Usage Guidelines

  • All tokens must be declared in tokens.json
  • Avoid inline logic in token names (no {{IfFeatureFlag}})
  • Prefer camelCase or PascalCase to align with code usage
  • Document optional vs required tokens clearly

πŸ” Studio and Agent Support

Consumer Usage
Studio UI Shows prompts based on tokens.json + autofill suggestions
Agents Read schema, map from context, submit values to scaffolder
Validator Ensures all tokens are declared and resolved

βœ… Summary

Template structure and tokens provide a powerful, declarative system for transforming generic scaffolds into context-specific, production-ready codebases. Tokens drive agent personalization, ensure consistency, and allow total automation of SaaS scaffolding at scale.


βœ… Cycle 6 Completed

Shall we proceed with Cycle 7: Preview and Inspection Features?

Let’s proceed with:


πŸ” Cycle 7: TemplateCatalog Domain – Preview and Inspection Features

🧭 Purpose

This cycle defines how the TemplateCatalog Domain supports previewing templates before applying them. It allows agents and human users to inspect the file structure, token requirements, and core metadata β€” enabling safe, informed, and testable generation.

Previewing ensures transparency and confidence in what will be scaffolded.


πŸ” Preview Capabilities

Preview Feature Description
File Structure View Display the full folder and file hierarchy
Token Requirements Show which tokens are needed to apply the template
Token Types & Defaults Include descriptions, types, and optional/default values
Metadata Summary Show version, tags, type, compatibility, and description
Example Output Simulation (WIP) Sample output with demo token values

🧾 Preview API Contract

GET /api/templates/{templateId}/preview

Response Example

{
  "templateId": "template-cleanarch-microservice",
  "version": "2.3.1",
  "entryPoint": "src",
  "fileTree": [
    "src/Domain/{{EntityName}}.cs",
    "src/Application/Services/{{EntityName}}Service.cs",
    "src/Api/Controllers/{{EntityName}}Controller.cs"
  ],
  "tokens": [
    {
      "name": "EntityName",
      "type": "string",
      "description": "Primary domain entity"
    },
    {
      "name": "UseMassTransit",
      "type": "boolean",
      "description": "Enable event-driven architecture"
    }
  ],
  "tags": ["ddd", "cleanarch", "event-driven"],
  "compatibleWith": [".NET 8"]
}

🧠 Agent Usage

Agents query this endpoint to:

  • Verify token requirements before attempting generation
  • Match structure against expected project layout
  • Auto-suggest token values (e.g., infer EntityName from domain model)

Example Flow

1. VisionArchitectAgent selects `template-cleanarch-microservice`
2. Calls `/preview`
3. Sees token: `EntityName`
4. Uses DomainKnowledge to select `Customer`
5. Applies template with `{ EntityName: "Customer" }`

πŸ–₯️ Studio UI Support

Studio allows users to:

  • Browse file/folder hierarchy
  • Preview rendered file paths with fake token values
  • See token input UI based on schema
  • View metadata (description, tags, compatibility)

βœ… This improves user trust and helps avoid misapplication of templates.


πŸ§ͺ Internals: Structure Extraction Logic

Process (ZIP or NuGet-based):

  1. Extract src/ or entryPoint/ folder
  2. Walk directory and collect:

  3. Relative paths

  4. Token placeholders in file names
  5. Read tokens.json for token schema
  6. Build normalized preview response

πŸ“Š Observability

  • All preview requests are logged with:

  • templateId

  • traceId
  • Requestor (user or agent)
  • Usage metrics tracked in TemplateAnalyticsContext

🚧 Edge Cases & Validation

Scenario Handling
Missing tokens.json Preview still shows file tree; marks tokens unknown
Tokens not used in files Warn during validation
Empty structure Warn as invalid or unusable template

βœ… Summary

The preview and inspection features allow users and agents to see before they generate, ensuring templates are applied safely and predictably. This capability supports Studio UI, intelligent agents, and traceable generation workflows β€” a key enabler of autonomous trust in code generation.


βœ… Cycle 7 Completed

Shall we move to Cycle 8: Template Versioning Strategy?

Let’s continue with:


πŸ” Cycle 8: TemplateCatalog Domain – Template Versioning Strategy

🧭 Purpose

This cycle defines how the TemplateCatalog Domain handles template versioning, ensuring agents and users can:

  • Select specific versions
  • Avoid breaking changes
  • Apply safe upgrades
  • Roll back or lock templates as needed

Versioning is key to stability, reproducibility, and controlled evolution of the software factory.


πŸ”’ Semantic Versioning (SemVer)

All templates must follow the SemVer 2.0.0 format:

MAJOR.MINOR.PATCH[-prerelease][+buildmetadata]

Examples

  • 1.0.0 β†’ First stable release
  • 1.2.0 β†’ New features (non-breaking)
  • 2.0.0 β†’ Breaking change (e.g., renamed tokens, major tech switch)
  • 2.1.3-beta β†’ Pre-release for internal use/testing

πŸ—‚οΈ Template Registry Model

Template {
  TemplateId,
  Type,
  Name,
  TenantId,
  Visibility,
  Versions: List<TemplateVersion>
}

TemplateVersion {
  Version,
  SourceType,       // zip or nuget
  RegisteredAt,
  EntryPointPath,
  TokenSchema,
  ValidationStatus,
  PreviewHash
}

Multiple versions can coexist and be queried independently.


πŸ”„ Version Resolution Options

Mode Behavior
Latest Default if no version specified (non-prerelease)
Exact Required for reproducible agent workflows
Compatible Agents may accept >=1.0.0 <2.0.0 if flexible
Pinned Project may store version for audit/future use

🎯 Use Case Examples

Scenario Versioning Behavior
User scaffolds using default version latest stable version is selected
Agent uses pinned blueprint template-authserver@1.4.2 is resolved
Migration to v2.x Requires explicit upgrade + change logs
Use pre-release from dev feed Allowed with AllowPreRelease = true config

🧠 Agent Support

Agents can specify:

{
  "templateId": "template-cleanarch-microservice",
  "version": "1.2.0"
}

Or:

{
  "type": "microservice",
  "tags": ["event-driven"],
  "compatibleWith": [".NET 8],
  "versionConstraint": ">=1.0.0 <2.0.0"
}

Version resolution is handled server-side, with matching logic and warnings on ambiguous results.


πŸ› οΈ Studio UI Features

  • Version dropdown for manual selection
  • What's New panel with changelogs
  • Highlight deprecated or unstable versions

πŸ§ͺ Validation Rules

Rule Enforced During Registration?
Version must be valid SemVer βœ… Yes
Duplicate version not allowed βœ… Yes (unless override by admin)
Pre-release must have suffix βœ… Yes (1.4.0-beta)
Upgrade path checks (optional) 🚧 Future roadmap

πŸ“œ Change Log and Documentation (Optional)

Templates may include a CHANGELOG.md with each version. This will:

  • Be displayed in Studio UI
  • Allow agents to auto-detect token changes, feature shifts

🧩 Example: NuGet-Based Version Handling

NuGet packages can publish multiple versions (1.0.0, 1.1.0, 2.0.0) to Azure Artifacts. Registry pulls .nupkg based on specified version in registration or resolution step.


βœ… Summary

The TemplateCatalog enforces a robust, flexible versioning strategy using SemVer, enabling controlled, repeatable generation across thousands of agent-driven SaaS projects. It supports human selection, agent pinning, safe upgrades, and CI-compatible workflows.


βœ… Cycle 8 Completed

Would you like to continue to Cycle 9: Validation Engine?

Let’s proceed with:


πŸ” Cycle 9: TemplateCatalog Domain – Validation Engine

🧭 Purpose

This cycle defines how the TemplateValidationContext ensures every template is structurally, syntactically, and semantically valid before it becomes active in the system. Validation is critical for agent safety, runtime stability, and project integrity.


πŸ§ͺ When Validation Happens

Stage Trigger
⏫ During registration New ZIP/NuGet template uploaded
πŸ” During update A new version is pushed or republished
πŸ§‘ On-demand Manual revalidation (via Studio or API)
πŸ€– CI pipelines Pre-publish check from Azure DevOps

πŸ” Validation Categories

Category Description
Metadata Validation Ensure .template.json has valid structure, required fields
Token Validation All tokens used in file paths or contents must be declared in tokens.json
Structure Validation Must contain files in entry point, e.g. src/
Compatibility Check compatibleWith must be non-empty and syntactically valid
Versioning Rules SemVer format, no duplicate versions per template
Dangerous Token Detection Reject inline logic or unsafe tokens ({{Eval}})
Lint Rules (optional) Warn if unused tokens, missing README, or dead folders

βœ… Pass Criteria

A template is considered valid if:

  • It has valid SemVer version
  • It contains .template.json, tokens.json, and a non-empty entry point
  • All declared tokens are used (or documented as optional)
  • There are no unresolved {{token}} in static files
  • There are no critical lint errors

🧾 Validation Result Example

{
  "status": "valid",
  "templateId": "template-cleanarch-microservice",
  "version": "1.3.0",
  "issues": [],
  "warnings": [
    {
      "type": "lint",
      "message": "Token 'RepositoryName' declared but not used."
    }
  ]
}

Validation status is stored per templateId:version, and referenced in preview, discovery, and generation APIs.


πŸ“¦ Events Emitted

Event Emitted By Purpose
TemplateValidated ValidationEngine Valid template now live
TemplateValidationFailed ValidationEngine Blocked template; notify Studio/user
TemplateStructureUpdated Registry/PreviewService Structure changed post-validation

🧠 Agent Benefit

Agents only consume templates with:

  • status = valid
  • Fully declared token schema
  • Safe defaults or resolution strategy for optional tokens

This prevents generation errors and mismatches during scaffold execution.


πŸ–₯️ Studio UI Feedback

  • Red banner for invalid templates
  • Yellow badge for warnings
  • Allow user to download validation report or fix locally
  • Disable generate button until validation passes

πŸ› οΈ Validation Pipeline (Internal Logic)

flowchart TD
  Load[Load template archive] --> ParseTemplate
  ParseTemplate --> ValidateMetadata
  ValidateMetadata --> ValidateTokens
  ValidateTokens --> ValidateStructure
  ValidateStructure --> LintRules
  LintRules --> Result[Emit result + issues/warnings]
Hold "Alt" / "Option" to enable pan & zoom

All validation runs inside isolated sandbox or container for safety.


πŸ§ͺ Optional Advanced Rules (Planned)

Rule Description
Token type inference Check if string tokens match naming conventions
Dependency graph analysis Detect invalid cross-folder references
Test scaffolding simulation Run dry scaffold and check for broken paths
Duplicate file detection Detect multiple tokens resolving to same file

βœ… Summary

The TemplateCatalog’s Validation Engine ensures every template meets ConnectSoft's standards for safety, clarity, and usability. It protects agents and users from misconfigured templates and enables high-confidence automation at scale.


βœ… Cycle 9 Completed

Shall we move forward with Cycle 10: Template Application Rules?

Here is:


πŸ” Cycle 10: TemplateCatalog Domain – Template Application Rules

🧭 Purpose

This cycle defines the rules and constraints governing how and when a template can be applied during project generation. These rules protect users and agents from invalid scaffolding, ensure compatibility, and enable safe, contextual template usage in ConnectSoft AI Software Factory.


🧠 Application Workflow (Simplified)

sequenceDiagram
  participant Agent/User
  participant Catalog as TemplateCatalogService
  participant Validator
  participant Generator as TemplateScaffolderService

  Agent/User->>Catalog: Request to Apply Template (with Token Inputs)
  Catalog->>Validator: Check Template Validity
  Validator-->>Catalog: OK or Rejection
  Catalog->>Generator: GenerateStructure(templateId, version, tokens)
  Generator-->>Agent/User: Resulting files + status
Hold "Alt" / "Option" to enable pan & zoom

βœ… Prerequisites for Application

A template can only be applied if:

Requirement Enforced by Description
Template is validated Validator status = valid is required
Tokens are fully resolved TemplateScaffolder All required tokens must be supplied
Version is available Catalog Service The specified or default version exists
Compatibility is matched Orchestration/Agent Optional: agents may require .NET 8, etc.
Project state is eligible ProjectLifecycle E.g., Draft β†’ Initializing is allowed

βš™οΈ Token Validation at Application Time

All declared tokens in tokens.json must be:

  • Present in the request
  • Type-compatible (e.g., boolean, string)
  • Non-empty (if required = true)
  • Matching constraints (optional: regex, allowed values)

Example check:

"EntityName": {
  "type": "string",
  "required": true,
  "pattern": "^[A-Z][a-zA-Z0-9]+$"
}

❌ Missing or invalid tokens β†’ TemplateApplicationFailed event + error response


🧩 Application Scope

Level Example
Project-wide Generate entire microservice into a fresh project root
Module Add a new domain module or library into an existing service
Phase-specific Only apply template during ArchitecturePhase or InfrastructurePhase

Controlled by allowedPhases or allowedScopes fields in .template.json (future roadmap)


πŸ” Access Control Rules

Rule Enforced In
Agent or user must have permission Auth/ProjectAssignmentContext
Private templates limited to owner Catalog query and apply filters
Restricted phases enforce isolation Orchestrator / Phase policy

🧠 Agent vs Human Application

Trigger Type Application Method Token Inputs Source
Agent ApplyTemplateCommand Inferred or prompted via planner
Studio UI Submit form to /apply API Human-filled fields based on schema
Orchestrator Automated on lifecycle event Pulled from PhaseContext config

πŸ› οΈ Output & Feedback

Output Description
Generated file structure Fully rendered output (resolved tokens)
Scaffolding summary Count of files, folders, tokens used
Trace ID linkage Applied as part of TraceabilityContext
Warnings or notes (optional) E.g., unused optional tokens, skipped folders

🚫 Application Failure Scenarios

Error Type Cause
InvalidTemplateStatus Template is not validated
UnresolvedTokens Missing or incompatible token input
VersionMismatch Specified version not found or unpublished
PhaseNotAllowed Trying to apply template in wrong lifecycle phase

These raise TemplateApplicationFailed events with rich error context.


πŸ“Š Observability

All application requests are logged:

  • projectId, traceId
  • templateId:version
  • Token payload hash (not raw values)
  • Duration, result (success/failure)
  • Agent or user that initiated it

This enables postmortem analysis, rollback planning, and analytics.


βœ… Summary

Template application is a guarded, validated, and traceable process. It ensures the right template is used at the right time by the right persona with the right inputs. These rules form the safety net around the automation engine of the ConnectSoft AI Software Factory.


βœ… Cycle 10 Completed

Would you like to continue to Cycle 11: Event Model & Contracts?

Let’s continue with:


πŸ” Cycle 11: TemplateCatalog Domain – Event Model & Contracts

🧭 Purpose

This cycle defines the event-driven architecture of the TemplateCatalog Domain. All key lifecycle actionsβ€”such as registration, validation, preview generation, and applicationβ€”emit domain events. These events ensure traceability, automation, observability, and collaboration between agents, orchestrators, and services.


πŸ“£ Event-Driven Design Principles

  • Templates are first-class event emitters in the platform
  • All events are correlated with traceId, projectId, agentId, and templateId
  • Consumers include: orchestration engines, analytics, Studio UI, audit logs, and agent gateways

πŸ”” Core Events

Event Name Trigger Purpose
TemplatePublished Successful registration Notify catalog & agents that a new template version is available
TemplateValidationFailed Failed validation Alert Studio/owner, block downstream use
TemplateValidated Validation passed Promote to usable state
TemplatePreviewReady File structure extracted Enable Studio + agent inspection
TemplateApplied Template successfully scaffolded Trigger project lifecycle update / trace
TemplateApplicationFailed Token error or version issue Error context for rollback / audit

🧾 Standard Event Schema

All events share this common contract:

{
  "eventType": "TemplatePublished",
  "timestamp": "2025-05-05T13:22:11Z",
  "templateId": "template-cleanarch-microservice",
  "version": "2.3.1",
  "tenantId": "connectsoft",
  "traceId": "7e0f7b9c-df44-4bde-930f-04a4fdc44e19",
  "projectId": "proj-abc123",
  "initiator": {
    "type": "agent",
    "id": "vision-architect-agent"
  },
  "metadata": {
    "validated": true,
    "previewHash": "f4ae8c1",
    "tokenCount": 4
  }
}

πŸ“€ Event Emission Transport

Transport Type Notes
Azure Service Bus Default in cloud deployment
MassTransit Events For local/test/dev scaffolding
OpenTelemetry Spans Tracing all event emission and subscriber handling
Outbox Pattern Ensures reliable emission after DB commit (via event log)

🧩 Consumer Examples

Consumer Purpose
ProjectLifecycleService Update status after scaffolding
OrchestratorAgent Track when template is ready or applied
AuditTrailService Store immutable event logs for compliance
StudioDashboard Update UI for publish, validation, or preview result
AnalyticsEngine Track usage patterns, adoption rate, failure hot spots

πŸ§ͺ Example: TemplatePublished Event

{
  "eventType": "TemplatePublished",
  "templateId": "template-api-gateway",
  "version": "1.0.0",
  "tenantId": "connectsoft",
  "timestamp": "2025-05-05T11:45:00Z",
  "initiator": { "type": "user", "id": "dmitry" },
  "metadata": {
    "type": "gateway",
    "tags": ["reverse-proxy", "http"],
    "compatibleWith": [".NET 8"]
  }
}

πŸ” Security and Traceability

  • All events are signed with initiatorId (user or agent)
  • Events are stored in append-only log for audit purposes
  • Events include traceId, tenantId, templateId, and projectId when applicable

πŸ“Š Observability Integration

  • Events generate OTEL spans with:

  • Template ID and version

  • Token validation count
  • Agent or user ID
  • Application duration and outcome
  • Exposed via dashboards in Grafana/Kibana or Azure Monitor

βœ… Summary

The TemplateCatalog emits a comprehensive set of domain events to ensure platform-wide reactivity, observability, and reliability. These events allow other systems (orchestration, analytics, Studio UI, agents) to collaborate in real-time across the AI Software Factory lifecycle.


βœ… Cycle 11 Completed

Shall we move forward to Cycle 12: State Machine and Orchestration Phases?

Let’s proceed with:


πŸ” Cycle 12: TemplateCatalog Domain – Agent Interactions

🧭 Purpose

This cycle describes how ConnectSoft AI Agents interact with the TemplateCatalog Domain. Agents use the catalog to discover, preview, select, and apply templates during autonomous software generation workflows.

These interactions are optimized for machine efficiency, traceability, and semantic flexibility.


πŸ€– Primary Agent Personas Involved

Agent Role in Template Use
VisionArchitectAgent Recommends templates based on project type/domain
DeveloperAgent Selects and applies templates based on design specification
DevOpsAgent Applies infra templates (e.g., CI/CD, Bicep, Helm)
QAValidatorAgent Validates template application outcome (build/test success)
OrchestratorAgent Triggers template application during specific lifecycle phases

πŸ“ž Agent Access Points

Action API or Contract Used
Discover templates GET /api/templates/search?type=...&tags=...
Preview structure + tokens GET /api/templates/{id}/preview
Apply template POST /api/templates/apply
Subscribe to events Service Bus / MassTransit bus (TemplatePublished, etc.)

🧠 Agent Query Strategy

Agents often use semantic queries to find templates. Example:

{
  "type": "microservice",
  "tags": ["ddd", "event-driven"],
  "compatibleWith": [".NET 8"],
  "preferredVendors": ["ConnectSoft"],
  "requiredTokens": ["EntityName"]
}

Templates are ranked by:

  • Match score
  • Validation status
  • Usage success rate (analytics)
  • Compatibility with current ProjectContext

🧩 Agent Execution Flow

flowchart TD
  Agent --> Search[Template Search API]
  Search --> Preview[Preview Structure + Tokens]
  Agent --> TokenPlan[Determine Token Values]
  TokenPlan --> Apply[POST /apply with tokens]
  Apply --> Result[Success or Failure]
  Result --> Events[Emit Application Outcome Event]
Hold "Alt" / "Option" to enable pan & zoom

πŸ§ͺ Token Mapping Logic

Agents map tokens using:

  • Project context (e.g., ProjectName, Domain)
  • Domain language (e.g., from requirement spec)
  • Prior knowledge base (e.g., prompt-engineered memory)

Example:

{
  "EntityName": "Invoice",
  "UseMassTransit": true,
  "HasAuditTrail": true
}

πŸ” Agent Permissions

Agents must be:

  • Scoped to the project or tenant
  • Allowed to apply templates of the requested type
  • Authenticated via internal AgentContext with role-based access (scaffold, validate, search, etc.)

🧭 Example: DeveloperAgent Microservice Flow

  1. VisionArchitectAgent recommends template-cleanarch-microservice
  2. DeveloperAgent previews structure
  3. Agent resolves tokens:

  4. EntityName = "Customer"

  5. UseMassTransit = true
  6. Agent applies template and emits traceable event
  7. OrchestratorAgent proceeds to Infrastructure phase

πŸ“Š Usage Feedback Loop

Agent interactions are logged to:

  • TemplateAnalyticsContext
  • AgentScaffoldHistory
  • Traceability stream (per project/task)

Metrics collected:

  • Template success/failure rate
  • Average application time
  • Token mismatch trends
  • Template popularity per agent

βœ… Summary

Agents are first-class consumers of the TemplateCatalog, leveraging its metadata, structure, token system, and versioning to autonomously scaffold high-quality software. The platform provides clear, validated, and traceable contracts optimized for multi-agent orchestration.


βœ… Cycle 12 Completed

Would you like to continue to Cycle 13: TemplateCatalogService API?

Here is:


πŸ” Cycle 13: TemplateCatalog Domain – TemplateCatalogService API

🧭 Purpose

This cycle defines the public API surface of the TemplateCatalogService, which powers agent and human interaction with the catalog. It provides RESTful, versioned, and secure endpoints for searching, previewing, registering, validating, and applying templates.


🌐 API Overview

Action HTTP Method & Route
πŸ” Search templates GET /api/templates/search
πŸ“„ Get metadata GET /api/templates/{id}
πŸ“‚ Preview structure GET /api/templates/{id}/preview
πŸ§ͺ Validate manually POST /api/templates/{id}/validate
⬆️ Register new template POST /api/templates/register
🧬 Apply template POST /api/templates/apply
πŸ“œ Get available versions GET /api/templates/{id}/versions
πŸ”” Subscribe to events (Service Bus or webhook endpoint - internal)

πŸ” 1. Search Templates

Endpoint

GET /api/templates/search?type=microservice&tags=ddd,event-driven

Query Parameters

  • type: microservice, library, gateway, etc.
  • tags: comma-separated string
  • compatibleWith: .NET 8, Azure, etc.
  • visibility: public | private | all (admin)
  • validated: true/false

Response

[
  {
    "templateId": "template-cleanarch-microservice",
    "version": "2.3.1",
    "description": "DDD microservice scaffold with NHibernate",
    "tags": ["cleanarch", "event-driven"],
    "validated": true
  }
]

πŸ“‚ 2. Preview Structure

Endpoint

GET /api/templates/{templateId}/preview

Response

{
  "fileTree": [
    "src/Domain/{{EntityName}}.cs",
    "src/Application/Handlers/{{EntityName}}Handler.cs"
  ],
  "tokens": [
    {
      "name": "EntityName",
      "type": "string",
      "description": "The core domain entity"
    }
  ]
}

🧾 3. Register New Template

Endpoint

POST /api/templates/register

Payload Options

ZIP Mode

{
  "source": "zip",
  "file": "<base64 ZIP>",
  "metadata": {
    "type": "library",
    "tags": ["validation", "shared"],
    "visibility": "private"
  }
}

NuGet Mode

{
  "source": "nuget",
  "packageId": "ConnectSoft.Templates.CleanArch",
  "packageVersion": "2.0.0",
  "feed": "https://pkgs.dev.azure.com/connectsoft/_packaging/PlatformTemplates/nuget/v3/index.json"
}

πŸ§ͺ 4. Validate Template

Endpoint

POST /api/templates/{id}/validate

Validates the structure, metadata, token declarations, and entry point presence.


🧬 5. Apply Template

Endpoint

POST /api/templates/apply

Payload

{
  "templateId": "template-cleanarch-microservice",
  "version": "2.3.1",
  "tokens": {
    "EntityName": "Customer",
    "UseMassTransit": true
  },
  "projectId": "proj-23ffca"
}

Response

  • List of rendered paths
  • Generation summary
  • traceId and scaffoldSessionId

πŸ“œ 6. Get Available Versions

Endpoint

GET /api/templates/{templateId}/versions

Returns:

["1.0.0", "1.1.0", "2.0.0", "2.3.1"]

πŸ” Security & Context

  • All APIs require:

  • Authenticated user or agent token

  • Tenant scoping
  • Role-based access control (register, apply, search)
  • All write operations include:

  • traceId

  • initiatorId
  • Project context (if applicable)

πŸ“Š Monitoring

  • Each endpoint emits OTEL traces
  • Slow template applications are flagged
  • Studio UI and agents can subscribe to API failure events via internal bus

βœ… Summary

The TemplateCatalogService API is a central integration layer for the AI factory platform, exposing consistent, secure, and observable endpoints for managing and consuming templates. It supports both human interaction (Studio) and intelligent agent orchestration.


βœ… Cycle 13 Completed

Shall we proceed to Cycle 14: Traceability and Audit Logging?

Let’s continue with:


πŸ” Cycle 14: TemplateCatalog Domain – Traceability and Audit Logging

🧭 Purpose

This cycle defines how all actions in the TemplateCatalog Domain are traced, logged, and audited across services and agents. Traceability ensures that every template operationβ€”from registration to applicationβ€”can be fully monitored, debugged, and audited for compliance, diagnostics, and usage analysis.


🧩 Core Traceability Concepts

Concept Description
traceId Global correlation ID across all actions and events
scaffoldSessionId Per-template-application unique ID for each generation instance
initiator Who triggered the action (user or agent with ID and type)
projectId Which project context the action was performed in
templateId Which template and version was involved

πŸ“œ Audit Log Format

All relevant actions generate structured audit records:

{
  "timestamp": "2025-05-05T14:03:55Z",
  "action": "TemplateApplied",
  "templateId": "template-cleanarch-microservice",
  "version": "2.3.1",
  "traceId": "5e17a8ac-a7f4-4982-9d92-8d13a06e4df0",
  "initiator": {
    "type": "agent",
    "id": "developer-agent"
  },
  "projectId": "proj-12aa1b",
  "scaffoldSessionId": "session-983bc0d",
  "status": "success",
  "tokensUsed": ["EntityName", "UseMassTransit"]
}

πŸ” Traced Operations

Operation Logged/Audited? Span Created?
Template registration βœ… βœ…
Template validation βœ… βœ…
Template preview βœ… βœ…
Template application βœ… βœ…
Token mismatch / failure βœ… βœ…
Version selection & resolution βœ… βœ…
Access by unauthorized agent/user βœ… βœ…

πŸ“Š Telemetry Integration (OpenTelemetry)

All template events and API calls emit OpenTelemetry spans with:

  • templateId and version
  • traceId
  • scaffoldSessionId
  • agentId or userId
  • Duration and status
  • Failure reasons (if any)

βœ… These are viewable in centralized tracing platforms (Grafana, Azure Monitor, Jaeger)


πŸ” Audit Retention and Export

Feature Support Level
Retention duration Configurable (default: 90 days)
Export to blob or SIEM Supported (JSON or CSV)
Encrypted at rest βœ… Yes (via platform data layer)
Tenant-segregated logs βœ… Yes
GDPR/DSAR audit extract βœ… Agent/user-specific filters

πŸ“ Audit Storage Model

Stored in:

  • TemplateAuditLogTable (e.g., PostgreSQL / Cosmos DB)
  • TraceabilityStream for reactive subscriptions
  • ProjectHistoryContext for timeline integration

πŸ”„ Cross-Domain Correlation

Trace IDs allow correlation between:

Source Domain Example Trace Flow
ProjectLifecycle Detect when a project entered scaffolding phase
TemplateCatalog Know which templates were applied with what input
Orchestration Connect template usage to orchestration decisions
AgentGateway Trace actions back to specific agents and goals

βœ… Summary

The TemplateCatalog Domain implements full traceability and audit logging, allowing ConnectSoft to observe, understand, and govern the usage of every template across the platform. It enables safe automation, compliance reporting, and root-cause diagnostics at scale.


βœ… Cycle 14 Completed

Shall we move forward to Cycle 15: Error Handling and Recovery Scenarios?

Let’s proceed with:


πŸ” Cycle 15: TemplateCatalog Domain – Error Handling and Recovery Scenarios

🧭 Purpose

This cycle defines how the TemplateCatalog Domain detects, reports, and recovers from errors at each stage of the template lifecycle. Errors are surfaced via structured responses, domain events, trace logs, and retry mechanisms to support self-healing, observability, and agent resilience.


πŸ”₯ Common Error Scenarios

Stage Error Type Example Cause
Template Registration InvalidMetadata Missing .template.json or bad version format
Template Validation UnresolvedTokens Tokens used in filenames not declared in tokens.json
Template Application TokenMismatch Required token not supplied by user/agent
NuGet Pull PackageFetchFailed Auth issue or feed unavailable
Version Conflict DuplicateVersion Version already exists for template ID
Incompatible Environment PlatformMismatch Template requires .NET 8 but project is on .NET 6

🚫 Error Response Contract (REST)

{
  "status": "error",
  "errorCode": "TokenMismatch",
  "message": "Required token 'EntityName' is missing.",
  "templateId": "template-cleanarch-microservice",
  "version": "2.3.1",
  "traceId": "85ca57c3-bc4a-42b8-9a2b-3d2f41ab43f0"
}

🧠 Agent-Oriented Error Handling

Agents receiving errors can:

  • Retry (e.g., after recovering token values)
  • Report via AgentGateway (AgentTaskFailed)
  • Trigger fallback plans via Orchestrator
  • Escalate to VisionArchitectAgent or StudioUser

Errors are non-fatal by designβ€”agents are expected to adapt.


πŸ“€ Error Events Emitted

Event Name Emitted When
TemplateValidationFailed Failed during ZIP or NuGet structure checks
TemplateApplicationFailed Apply command failed due to tokens/version
TemplateFetchError NuGet pull failed (network, version)
TemplateConflictDetected Duplicate ID:Version during registration

Event Example: TemplateApplicationFailed

{
  "eventType": "TemplateApplicationFailed",
  "templateId": "template-shared-auth",
  "version": "1.0.1",
  "error": {
    "code": "UnresolvedToken",
    "message": "Missing required token: IssuerUrl"
  },
  "projectId": "proj-abc123",
  "traceId": "e432fda3-541b-4b5a-a617-01f77cfa45b3",
  "initiator": { "type": "agent", "id": "devops-agent" }
}

πŸ” Recovery Strategies

Scenario Recovery Pattern
Agent missed a required token Planner re-prompts or uses default
NuGet download failed Retry with exponential backoff
Version conflict on publish Prompt user to bump patch or overwrite
Template is invalid Mark as draft and notify Studio
Missing preview structure Trigger regeneration from archive

🧰 Developer & Studio Feedback

  • Studio UI shows structured error messages
  • Includes quick "Fix & Retry" options for users
  • Developer logs include full exception + traceId
  • Agents log in their local state/error stream

πŸ›‘οΈ Resilience Techniques

Technique Applied To
Circuit Breaker (optional) NuGet registry access, Studio file uploads
Retry with delay All external feeds (Azure Artifacts, Git)
Idempotent operations Registration, version push, validation
Outbox + Event replay Template events stored and recoverable

πŸ” Security Failures

Case Handling
Unauthorized template apply 403 error + audit log entry
Template visibility mismatch Redacted from catalog query result
Agent applies restricted template Blocked + emits AccessDeniedEvent

βœ… Summary

The TemplateCatalog Domain provides comprehensive error detection and recovery strategies across every phase of its lifecycle. Errors are structured, traceable, and agent-safe, enabling ConnectSoft’s multi-agent platform to operate reliably and autonomously under real-world conditions.


βœ… Cycle 15 Completed

Would you like to proceed to Cycle 16: Template Lifecycle States?

Let’s continue with:


πŸ” Cycle 16: TemplateCatalog Domain – Template Lifecycle States

🧭 Purpose

This cycle defines the lifecycle model for templates within the TemplateCatalog Domain. Templates evolve through distinct statesβ€”from draft to published to deprecatedβ€”governing how they can be discovered, validated, applied, and upgraded across the ConnectSoft platform.

Lifecycle states are critical for maintaining quality control, backward compatibility, and release governance.


πŸ” Core Lifecycle States

State Description
Draft Template is registered but not yet validated
Validated Passed validation checks and available for preview
Published Approved and available for use by agents and Studio
Deprecated Marked as obsolete; discouraged from new use
Disabled Hidden from all queries; blocked from use without deletion

πŸ”‚ State Transitions

stateDiagram-v2
  [*] --> Draft
  Draft --> Validated : validation passed
  Validated --> Published : manually promoted or auto-publish
  Published --> Deprecated : manual lifecycle decision
  Any --> Disabled : admin action or security incident
Hold "Alt" / "Option" to enable pan & zoom

πŸ› οΈ Transition Triggers

Trigger Source/Actor Target State
Validation passes ValidatorEngine Validated
Studio user confirms Manual (UI/API) Published
Agent auto-promotes Based on quality metrics Published (optional)
Manual deprecation Admin or template owner Deprecated
Security or broken state Admin/system policy Disabled

πŸ” Visibility by State

State Visible in Studio? Searchable via API? Usable by Agents?
Draft Only by owner ❌ No ❌ No
Validated Yes (restricted) βœ… Yes βœ… Yes (with caution)
Published βœ… Full βœ… Full βœ… Full
Deprecated βœ… (warning shown) βœ… (marked) ⚠️ Allowed with notice
Disabled ❌ No ❌ No ❌ No

πŸ§ͺ Example Template Record

{
  "templateId": "template-identity-service",
  "version": "2.0.0",
  "state": "Published",
  "validatedAt": "2025-05-05T11:32:00Z",
  "publishedAt": "2025-05-06T00:00:00Z",
  "deprecated": false
}

🧠 Agent Behavior by State

Template State Agent Behavior
Draft Ignored in queries or marked invalid
Validated Used only if explicitly requested
Published Default in generation workflows
Deprecated Still used if pinned; warning logged
Disabled Blocked with TemplateAccessDenied error

πŸ–₯️ Studio UI Indicators

State Icon/Style Message Example
Draft 🚧 Grey tag β€œNot ready for use”
Validated βœ… Yellow badge β€œReady but not yet published”
Published 🟒 Green badge β€œApproved and active”
Deprecated ⚠️ Orange badge β€œDeprecated – consider newer alternatives”
Disabled πŸ”’ Red alert β€œBlocked by admin or system policy”

πŸ“œ State Change Audit Trail

All state transitions are:

  • Logged to TemplateAuditLog
  • Emitted as domain events (TemplatePublished, TemplateDeprecated, etc.)
  • Exposed via traceability tools for forensic and lifecycle analysis

βœ… Summary

Template lifecycle states govern how templates move from idea to automation. This structured model enables ConnectSoft to deliver safe, maintainable, and observable scaffolding capabilities for thousands of autonomous software projectsβ€”by both humans and agents.


βœ… Cycle 16 Completed

Shall we move to Cycle 17: Template Analytics and Usage Metrics?

Let’s continue with:


πŸ” Cycle 16: TemplateCatalog Domain – Template Lifecycle States

🧭 Purpose

This cycle defines the lifecycle model for templates within the TemplateCatalog Domain. Templates evolve through distinct statesβ€”from draft to published to deprecatedβ€”governing how they can be discovered, validated, applied, and upgraded across the ConnectSoft platform.

Lifecycle states are critical for maintaining quality control, backward compatibility, and release governance.


πŸ” Core Lifecycle States

State Description
Draft Template is registered but not yet validated
Validated Passed validation checks and available for preview
Published Approved and available for use by agents and Studio
Deprecated Marked as obsolete; discouraged from new use
Disabled Hidden from all queries; blocked from use without deletion

πŸ”‚ State Transitions

stateDiagram-v2
  [*] --> Draft
  Draft --> Validated : validation passed
  Validated --> Published : manually promoted or auto-publish
  Published --> Deprecated : manual lifecycle decision
  Any --> Disabled : admin action or security incident
Hold "Alt" / "Option" to enable pan & zoom

πŸ› οΈ Transition Triggers

Trigger Source/Actor Target State
Validation passes ValidatorEngine Validated
Studio user confirms Manual (UI/API) Published
Agent auto-promotes Based on quality metrics Published (optional)
Manual deprecation Admin or template owner Deprecated
Security or broken state Admin/system policy Disabled

πŸ” Visibility by State

State Visible in Studio? Searchable via API? Usable by Agents?
Draft Only by owner ❌ No ❌ No
Validated Yes (restricted) βœ… Yes βœ… Yes (with caution)
Published βœ… Full βœ… Full βœ… Full
Deprecated βœ… (warning shown) βœ… (marked) ⚠️ Allowed with notice
Disabled ❌ No ❌ No ❌ No

πŸ§ͺ Example Template Record

{
  "templateId": "template-identity-service",
  "version": "2.0.0",
  "state": "Published",
  "validatedAt": "2025-05-05T11:32:00Z",
  "publishedAt": "2025-05-06T00:00:00Z",
  "deprecated": false
}

🧠 Agent Behavior by State

Template State Agent Behavior
Draft Ignored in queries or marked invalid
Validated Used only if explicitly requested
Published Default in generation workflows
Deprecated Still used if pinned; warning logged
Disabled Blocked with TemplateAccessDenied error

πŸ–₯️ Studio UI Indicators

State Icon/Style Message Example
Draft 🚧 Grey tag β€œNot ready for use”
Validated βœ… Yellow badge β€œReady but not yet published”
Published 🟒 Green badge β€œApproved and active”
Deprecated ⚠️ Orange badge β€œDeprecated – consider newer alternatives”
Disabled πŸ”’ Red alert β€œBlocked by admin or system policy”

πŸ“œ State Change Audit Trail

All state transitions are:

  • Logged to TemplateAuditLog
  • Emitted as domain events (TemplatePublished, TemplateDeprecated, etc.)
  • Exposed via traceability tools for forensic and lifecycle analysis

βœ… Summary

Template lifecycle states govern how templates move from idea to automation. This structured model enables ConnectSoft to deliver safe, maintainable, and observable scaffolding capabilities for thousands of autonomous software projectsβ€”by both humans and agents.


βœ… Cycle 16 Completed

Shall we move to Cycle 17: Template Analytics and Usage Metrics?

Let’s move forward with:


πŸ” Cycle 17: TemplateCatalog Domain – Template Analytics and Usage Metrics

🧭 Purpose

This cycle defines how the TemplateCatalog collects and exposes real-time analytics and historical usage metrics to monitor, optimize, and evolve template usage. These metrics serve both operational (performance, failures) and strategic (adoption, impact) goals across the platform.


πŸ“Š Key Metrics Collected

Metric Name Description
templateUsageCount How many times a template was applied (per version)
templateFailureRate Ratio of failed applications to total attempts
averageApplicationDuration Time taken to apply template end-to-end
topUsedTemplates Most frequently applied templates (global or per tenant)
agentTemplateMapping Which agents use which templates (e.g., DeveloperAgent favorites)
templateSearchHits Templates returned in search vs. selected
validationFailureReasons Most common validation issues across all templates

πŸ“¦ Analytics Data Model

{
  "templateId": "template-api-gateway",
  "version": "1.3.2",
  "usageCount": 122,
  "successRate": 0.94,
  "averageDurationMs": 1480,
  "lastUsedBy": "developer-agent",
  "tags": ["reverse-proxy", "openapi"],
  "createdAt": "2025-04-01T12:00:00Z"
}

🧠 Aggregation Dimensions

Analytics are grouped by:

  • templateId
  • templateVersion
  • tenantId
  • agentId (if applicable)
  • projectId (for fine-grained audit)

πŸ“Š Dashboard Views

1. Studio UI – Admin Analytics Panel

  • Heatmap of template usage
  • Top failing templates
  • Time-to-apply chart by type (e.g., microservice, pipeline)

2. Agent Feedback Loop

  • DeveloperAgent prefers templates with:

  • 90% success rate

  • Used >10 times in current tenant
  • Low average token mismatch score

3. Ops Monitoring Dashboard (Grafana / Azure Monitor)

  • Time-series plots for:

  • templateApplications/hour

  • validationFailures/day
  • agent-template distribution

πŸ“€ Event-Based Metrics Collection

Collected from emitted domain events:

  • TemplateApplied
  • TemplateApplicationFailed
  • TemplatePublished
  • TemplateValidated
  • TemplatePreviewRequested

Each includes:

  • traceId
  • agentId or userId
  • Token map hash
  • Duration and outcome

πŸ“Œ Example Metric Rule (for Orchestrator)

β€œIf failure rate of a published template exceeds 30% in the last 7 days, auto-deprecate and notify owner.”

This supports automated lifecycle governance.


πŸ” Data Access and Retention

Concern Implementation
Tenant-scoped analytics Data only accessible within tenant boundary
Agent-based access Agents see only own interactions (unless admin)
Retention policy 180 days default, configurable per template

πŸš€ Planned Enhancements

Feature Status
Token-level usage frequency πŸ”œ In design
Heatmap of token resolution πŸ”œ In design
Top agent-template affinity πŸ”œ In design
Template rating system πŸ”œ Future UX

βœ… Summary

The TemplateCatalog collects a rich stream of actionable metrics that power everything from agent decision-making to Studio insights and automated governance. These analytics are foundational to ConnectSoft’s ability to scale, evolve, and optimize autonomous SaaS generation.


βœ… Cycle 17 Completed

Shall we move to Cycle 18: Template Type System and Classification?

Let’s continue with:


πŸ” Cycle 18: TemplateCatalog Domain – Template Type System and Classification

🧭 Purpose

This cycle defines the type system and classification taxonomy used to categorize templates in the TemplateCatalog Domain. It ensures consistent organization, filtering, compatibility resolution, and orchestration rules across human and agent workflows.


🧩 Core Template Types

Type Description
microservice Full-featured backend service with domain logic, APIs, integration layers
library Shared code library, often reusable (e.g., validation, observability)
api-gateway Edge-layer service for routing and API composition
identity-service User and auth management microservice
event-processor Background worker, consumer, or integration adapter
infrastructure Bicep/ARM scripts, Terraform modules, Dockerfiles, Kubernetes manifests
ci-pipeline YAML pipeline templates for Azure DevOps, GitHub Actions, etc.
test-suite SpecFlow/BDD or xUnit test automation templates
documentation MkDocs, Swagger, or README scaffold templates
function Serverless function (e.g., Azure Function template)

🧾 Metadata Format

{
  "templateId": "template-cleanarch-microservice",
  "type": "microservice",
  "tags": ["ddd", "event-driven", "mass-transit"],
  "compatibleWith": [".NET 8", "Azure"],
  "scopes": ["project", "module"]
}

🧠 Agent Usage of Type

Query Example

{
  "type": "microservice",
  "tags": ["cleanarch", "ddd"],
  "compatibleWith": [".NET 8"]
}

Behavior:

  • VisionArchitectAgent filters by type to match intent
  • DeveloperAgent determines build integration strategy
  • DevOpsAgent ensures infrastructure and CI/CD types are installed in correct phase

🧱 Subtype and Scope (Optional Fields)

scopes (applicability)

Scope Description
project Whole new project root
module Subfolder or add-on to existing app
phase Limited to orchestration phase step

category (future field)

Category Examples
backend microservice, function, worker
frontend Blazor component, Angular shell
integration connectors, bridges, adapters
observability logs, metrics, tracing

🧾 Studio UI Classification UX

View Template Breakdown
Tree by type Sidebar filtering (microservice, lib, infra)
Icon set Type icons per template (e.g., 🧱 for library)
Multi-select Filter by multiple types/tags simultaneously

πŸ” Rules Based on Type

Type Special Validation or Behavior
microservice Must include full src/ structure, domain layer required
ci-pipeline YAML syntax validation, agent restricted usage
infrastructure Executable-only via DevOpsAgent or admin UI
event-processor Must support MassTransit, Azure Service Bus, or RabbitMQ

πŸ“Š Analytics by Type

Types are used for:

  • Aggregating usage stats
  • Orchestration phase alignment
  • Project scaffolding analytics
  • Auto-deprecation by type (e.g., unused documentation types)

🧩 Example Usage Matrix

Type Studio UI Agents Project Root? Tokenized?
microservice βœ… βœ… βœ… βœ…
library βœ… βœ… ❌ βœ…
ci-pipeline βœ… βœ… ❌ βœ…
documentation βœ… βœ… ❌ βœ…
infrastructure ⚠️ Admin βœ… ❌ Optional

βœ… Summary

The Template Type System classifies and normalizes templates across ConnectSoft’s AI Software Factory, ensuring consistent discovery, orchestration, validation, and usability across thousands of composable building blocks.


βœ… Cycle 18 Completed

Shall we continue to Cycle 19: Security, Access, and Visibility Controls?

Let’s continue with:


πŸ” Cycle 19: TemplateCatalog Domain – Security, Access, and Visibility Controls

🧭 Purpose

This cycle defines how templates in the TemplateCatalog Domain are protected through access control, visibility rules, and multi-tenant isolation. It ensures that only authorized users, agents, and tenants can register, view, or apply templatesβ€”enforcing ConnectSoft’s Security-First and Multi-Tenant SaaS principles.


πŸ” Key Security Dimensions

Dimension Description
Visibility Controls which users/tenants can discover the template
Access Control Defines who can register, apply, or manage templates
Ownership Each template is owned by a user, team, or agent identity
Tenant Isolation Templates are logically scoped per tenant (optional shared)

πŸ‘οΈ Visibility Levels

Level Who Can See It
private Only owner and authorized collaborators
tenant Anyone in the same tenant (default)
public All tenants (typically ConnectSoft global templates)

In Metadata

{
  "visibility": "tenant",
  "owner": { "type": "user", "id": "dmitry" }
}

βœ… Permissions Matrix

Operation Requires Role(s)
Search templates reader, scaffolder, admin
Register template creator, admin
Apply template scaffolder, orchestrator, admin
Deprecate/disable admin only
Manage ownership admin or current owner

🧩 Agent Scoping Model

Agents operate under scoped permissions:

{
  "agentId": "developer-agent",
  "tenantId": "connectsoft",
  "scopes": ["template:apply", "template:preview"],
  "allowedTypes": ["microservice", "library"]
}

Agents cannot:

  • Access private templates outside their tenant
  • Apply templates they don’t have access to by type or phase
  • Register or delete templates unless explicitly granted

πŸ”„ Ownership Transfer

Templates may be:

  • Transferred between users within the same tenant
  • Reassigned from user β†’ agent (for automation ownership)
  • Inheritable by TeamId in a future collaboration model

Ownership changes are logged in audit trail and gated by admin role.


🚨 Access Violation Handling

Scenario Outcome
Agent applies unauthorized template 403 Forbidden + AccessDeniedEvent
User views private template of another Template redacted from result set
Unauthorized registration attempt API rejected + audit log recorded

πŸ” Token Sensitivity Flag (Optional)

Tokens may be marked:

{
  "name": "DbAdminPassword",
  "type": "string",
  "sensitive": true
}

Studio UI and agents must:

  • Mask these in logs and preview
  • Never display in full in error responses
  • Exclude from telemetry hashes

πŸ›‘οΈ Tenant Isolation Enforcement

  • Templates are always logically scoped to a tenantId
  • Public templates are replicated or abstracted into tenant views
  • All template events, logs, metrics include tenantId for traceability

🧠 Studio UI Enforcement

Feature Behavior
Visibility toggle User selects private, tenant, or public if allowed
Access denial indicators β€œYou do not have access to this template” banner
Role-based UI actions Hide register/delete buttons if unauthorized

βœ… Summary

Security and access control in the TemplateCatalog Domain ensure that only the right people and agents can see, manage, and use templates, in alignment with strict tenant and role-based policies. This enables safe, compliant scaling of the software factory across many clients and industries.


βœ… Cycle 19 Completed

Shall we move on to Cycle 20: Cross-Domain Integration with Orchestration and Lifecycle?

Let’s continue with:


πŸ” Cycle 20: TemplateCatalog Domain – Cross-Domain Integration with Orchestration and Lifecycle

🧭 Purpose

This cycle defines how the TemplateCatalog integrates with the Orchestration and ProjectLifecycle domains to enable autonomous, phase-aligned template generation. It allows agents and orchestrators to apply the right template at the right time with the right context.


πŸ” Integration Targets

Domain Purpose
Orchestration Triggers template application in response to project phase transitions
ProjectLifecycle Determines allowed template types per phase (e.g., Init, Infra, QA)
AgentSystem Executes scaffold tasks and sends status via TemplateCatalog events

πŸ”‚ Lifecycle-Aware Template Application

Each project follows a lifecycle state machine. Example:

New β†’ Initialized β†’ InfrastructureReady β†’ ServicesScaffolded β†’ QAReady β†’ Completed

Templates are bound to phases via metadata:

{
  "allowedPhases": ["InfrastructurePhase", "ScaffoldingPhase"],
  "type": "microservice"
}

Only allowed templates are usable in that lifecycle phase.


πŸ“œ Orchestration Task Contract

{
  "taskType": "ApplyTemplate",
  "templateId": "template-cleanarch-microservice",
  "version": "2.0.0",
  "projectId": "proj-123abc",
  "tokens": {
    "EntityName": "Customer",
    "UseMassTransit": true
  },
  "requestedBy": "orchestrator-agent"
}

Task is sent by OrchestratorAgent to TemplateScaffolderService.


🧠 Triggering via Phase Transition

Lifecycle Phase Triggered Template Types
InitializationPhase project, ci-pipeline, infra
ScaffoldingPhase microservice, library
InfrastructurePhase bicep, function, gateway
ObservabilityPhase monitoring, tracing, alerts
TestPhase test-suite, specflow

πŸ” Event Chain: From Phase to Template to Agent

sequenceDiagram
  participant Lifecycle
  participant Orchestrator
  participant TemplateCatalog
  participant ScaffolderAgent

  Lifecycle->>Orchestrator: Phase Changed: ScaffoldingPhase
  Orchestrator->>TemplateCatalog: Get valid templates for phase
  Orchestrator->>ScaffolderAgent: ApplyTemplateCommand(template + tokens)
  ScaffolderAgent->>TemplateCatalog: POST /apply
  TemplateCatalog-->>All: Emit TemplateApplied event
Hold "Alt" / "Option" to enable pan & zoom

πŸ” Template Discovery by Phase

TemplateCatalogService supports:

GET /api/templates/search?phase=ScaffoldingPhase&projectId=...

Filters templates by:

  • Lifecycle phase
  • Project context (e.g., .NET 8, Azure, domain model)
  • Agent compatibility

πŸ§ͺ Example Use Case

As the project enters InfrastructurePhase, the OrchestratorAgent applies:

  • template-k8s-deployment
  • template-azure-monitor-bicep
  • template-secrets-injection

All chosen automatically based on:

  • Phase
  • Project architecture metadata
  • Token availability

πŸ“Š Observability & Traceability

Each cross-domain interaction emits:

  • TraceId
  • PhaseId
  • TemplateId
  • AgentId
  • Outcome (success/failure)
  • ScaffoldSessionId

Available in dashboards for orchestrators and lifecycle stewards.


🧩 Agent Collaboration Context

Templates applied in a phase may trigger:

  • New agent tasks (e.g., QAValidatorAgent)
  • Conditional execution paths
  • Coordination across multiple template types (e.g., API + Test suite)

βœ… Summary

Cross-domain integration with Orchestration and Lifecycle enables intent-driven, context-aware, and agent-coordinated scaffolding of templates. This turns the TemplateCatalog into a fully automated blueprint executor within the AI Software Factory ecosystem.


βœ… Cycle 20 Completed

Would you like to proceed to Cycle 21: CLI and Dev Experience for Template Developers?

Let’s continue with:


πŸ” Cycle 21: TemplateCatalog Domain – CLI and Developer Experience for Template Authors

🧭 Purpose

This cycle defines the tools, workflows, and developer experience (DX) for creating, validating, testing, and publishing templates to the TemplateCatalog using a Command-Line Interface (CLI) or CI-integrated process.

It empowers internal and external template authors to contribute confidently, reproducibly, and securely to the AI Software Factory.


🧰 Developer Workflow Overview

graph TD
  A[Scaffold Template Locally] --> B[Define tokens.json + template.json]
  B --> C[Run CLI Validate]
  C --> D[Test Apply with Sample Tokens]
  D --> E[Package ZIP or NuGet]
  E --> F[Publish to Catalog (CLI/API/CI)]
  F --> G[Await Validation + Preview]
Hold "Alt" / "Option" to enable pan & zoom

🧾 CLI Commands (Proposed)

Command Description
connectsoft-template init Scaffold a starter template skeleton
connectsoft-template validate Run full local validation on structure, metadata
connectsoft-template preview Render file tree and required tokens locally
connectsoft-template apply Test-apply locally with mock tokens
connectsoft-template publish Publish to catalog (requires API token)
connectsoft-template login Authenticate to ConnectSoft API

πŸ“¦ Template File Structure Example

my-template/
β”œβ”€β”€ template.json
β”œβ”€β”€ tokens.json
β”œβ”€β”€ README.md
└── src/
    β”œβ”€β”€ Application/
    β”‚   └── Services/{{EntityName}}Service.cs
    └── Domain/
        └── {{EntityName}}.cs

πŸ§ͺ Local Validation

connectsoft-template validate ./my-template
  • Ensures:

  • Valid SemVer

  • Required files exist
  • All tokens declared are used
  • No syntax errors in placeholders

Output:

βœ” Valid structure
βœ” tokens.json parsed (3 tokens)
⚠ Unused token: UseFeatureToggle

🧬 Test Apply Locally

connectsoft-template apply --tokens tokens.sample.json

Result:

  • Outputs rendered file structure into /tmp/rendered/
  • Useful for pre-publish verification
  • Can run CI test scaffolding jobs (e.g., diff + build check)

πŸš€ Publish from CLI

connectsoft-template publish --source ./my-template --visibility tenant

Requires:

  • Authenticated CLI session (login command)
  • Proper ownership metadata in template.json
  • Optional tags: --type microservice --tags ddd,event-driven

πŸ”— CI Integration Option

Templates can be packaged and published via Azure DevOps pipeline using:

  • dotnet pack (for NuGet)
  • REST API to /api/templates/register
  • CLI wrapped in CI shell script

πŸ‘¨β€πŸ’» DX Enhancements (Planned)

Feature Status
VS Code Extension πŸ”œ Prototype
Template linter plugin πŸ”œ Planned
Token schema auto-complete πŸ”œ Planned
Template unit tests (dry run rules) πŸ”œ Future roadmap

πŸ” Developer Permissions

Template authors must:

  • Be authenticated (CLI or API token)
  • Belong to a tenantId
  • Be granted template:register permission (via RBAC)
  • Pass validation to make template available

πŸ“Š Dev Telemetry (Opt-In)

CLI may report:

  • Usage counts per command
  • Validation errors (anonymized)
  • Common token naming trends

This improves DX and promotes standardization.


βœ… Summary

The CLI and DX model enables fast, testable, and secure template authoring and publishing. It supports both casual creators and professional developers contributing to ConnectSoft’s composable, autonomous software generation platform.


βœ… Cycle 21 Completed

Would you like to complete the series with Cycle 22: Governance, Quality Standards, and Template Review Process?

Let’s complete the series with:


πŸ” Cycle 22: TemplateCatalog Domain – Governance, Quality Standards, and Review Process

🧭 Purpose

This final cycle defines the governance model that ensures all templates meet ConnectSoft’s standards for security, maintainability, semantic consistency, and compatibility. It establishes a review, approval, and lifecycle management process that scales across thousands of templates and contributors.


πŸ›‘οΈ Why Governance Matters

  • Prevents broken or insecure scaffolds
  • Ensures templates align with Clean Architecture & DDD principles
  • Guarantees semantic compatibility with agents and orchestrators
  • Enables automation without human oversight

πŸ“ Template Quality Standards

Category Rule
Naming Template ID must follow kebab-case; version must be SemVer
Structure Must include entry point folder (src/, infrastructure/, etc.)
Token Declaration All {{token}} placeholders must be defined in tokens.json
Token Naming Use PascalCase; no abbreviations; type-safe declarations
Documentation README.md required; must describe usage, intent, and sample tokens
Compatibility Must declare .NET, Azure, or other compatibility fields
Security No embedded credentials or unsafe shell commands
Validation Pass All templates must pass automated validation before becoming usable

πŸ” Review Workflow (if enabled)

flowchart TD
  Author --> Submit[Submit Template via CLI/API]
  Submit --> AutoValidate
  AutoValidate --> ManualReview{Is Review Required?}
  ManualReview -->|Yes| ReviewerQueue
  ReviewerQueue --> Approve[Approved β†’ Published]
  ReviewerQueue --> Reject[Rejected β†’ Feedback to Author]
  ManualReview -->|No| AutoPublish[Validated β†’ Published]
Hold "Alt" / "Option" to enable pan & zoom

Admins can toggle auto-publish or enforce mandatory peer review via policy config.


πŸ§‘β€βš–οΈ Reviewer Roles and Criteria

Reviewers are:

  • Assigned per tenant or globally
  • Granted template:review permission
  • Required to validate:

  • Token coverage and consistency

  • DDD compliance (if applicable)
  • Observability hooks (if required)
  • Correct usage of ConnectSoft libraries or base classes

πŸ“œ Governance Policy Configuration (per Tenant)

Example:

{
  "autoPublish": false,
  "requiredTags": ["domain", "versioned"],
  "forbidUnsafeTokens": true,
  "defaultVisibility": "tenant",
  "enforceLinter": true
}

πŸ§ͺ Governance Linter (Planned)

Linter runs pre-publish:

  • Checks token conventions
  • Flags unused or excessive optional tokens
  • Suggests structure alignment to reference templates
  • Detects duplication across similar templates

πŸ” Governance Events

Event Trigger
TemplateReviewRequested Auto-validation passed, review required
TemplateApproved Reviewer accepts
TemplateRejected Reviewer provides structured feedback
TemplateGovernanceViolation Validation failed due to policy (e.g., forbidden pattern)

πŸ” Immutable Audit Trail

All governance actions are logged:

  • Who reviewed, what changed, when
  • All prior versions retained
  • Linked to traceId and tenantId

πŸ“Š Governance Metrics

Metric Use Case
Average time to publish Developer DX and automation tracking
Most common rejection reasons Author education and template quality
Rejection-to-acceptance ratio Process health and policy tuning
Review load per reviewer Load balancing and automation planning

πŸ” Overlay Management and Composition

The Template Catalog domain manages overlays as first-class entities, enabling composition of base templates with specialized overlays to create complex, domain-specific templates.

Overlay Storage

Overlays are stored in the Template Catalog with the following structure:

Overlay Artifacts: - Code files (domain-specific projects, classes, interfaces) - Documentation files (domain-specific documentation) - Metadata files (template.extend.json, overlay.json) - Test files (domain-specific test projects)

Overlay Metadata: - Overlay ID and version - Base template compatibility range - Overlay dependencies - Display name and description - Tags and classifications

Overlay Resolution

The Template Catalog resolves overlays through the TemplateRegistryContext:

Resolution Process: 1. Query overlay by ID and version range 2. Load overlay artifact from storage 3. Load overlay metadata and manifest 4. Validate overlay structure 5. Return overlay to composition engine

Resolution API:

GET /api/templates/overlays/{overlayId}?version={versionRange}

Base Template and Overlay Compatibility

The Template Catalog validates compatibility between base templates and overlays:

Compatibility Checking: - Base template version exists - Overlay version exists - Base + overlay compatibility ranges match - Overlay dependencies resolved - No circular dependencies

Compatibility Matrix: The Template Catalog maintains a compatibility matrix tracking: - Base template version ↔ Overlay version compatibility - Overlay ↔ Overlay dependency compatibility - Version ranges for each compatibility relationship

Compatibility Validation:

flowchart TD
    REQUEST[Composition Request]
    BASE[Resolve Base Template]
    OVERLAYS[Resolve Overlays]
    CHECK[Check Compatibility Matrix]
    DEPS[Resolve Dependencies]
    VALIDATE[Validate All Compatible]
    COMPOSE[Compose Template]

    REQUEST --> BASE
    REQUEST --> OVERLAYS
    BASE --> CHECK
    OVERLAYS --> CHECK
    CHECK --> DEPS
    DEPS --> VALIDATE
    VALIDATE --> COMPOSE

    style REQUEST fill:#E3F2FD
    style CHECK fill:#FFF9C4
    style VALIDATE fill:#C8E6C9
    style COMPOSE fill:#A5D6A7
Hold "Alt" / "Option" to enable pan & zoom

Recipe Storage and Execution

The Template Catalog stores and manages recipes for template composition:

Recipe Storage: - Recipe metadata (ID, version, description) - Recipe layers (base template + overlays) - Recipe parameters (defaults, overrides) - Recipe validation rules

Recipe Execution: 1. Load recipe from catalog 2. Validate recipe structure 3. Resolve base template 4. Resolve all overlays 5. Validate compatibility 6. Execute composition 7. Return composed template

Recipe API:

GET /api/templates/recipes/{recipeId}?version={version}
POST /api/templates/recipes/execute

Version Resolution

The Template Catalog resolves template and overlay versions automatically:

Version Resolution Process: 1. Parse version requirements from recipe 2. Query available versions from catalog 3. Filter compatible versions 4. Select latest compatible version 5. Validate all dependencies compatible

Version Resolution Rules: - Use semantic versioning (SemVer) - Support version ranges (^, ~, >=, <) - Prefer latest compatible version - Validate dependency chains

Template Catalog Domain Interaction with Overlays

flowchart TB
    subgraph Catalog[Template Catalog Domain]
        Registry[TemplateRegistryContext]
        Structure[TemplateStructureContext]
        Validation[TemplateValidationContext]
        Search[TemplateSearchContext]
        Analytics[TemplateAnalyticsContext]
    end

    subgraph OverlaySystem[Overlay System]
        OverlayStorage[Overlay Storage]
        Compatibility[Compatibility Matrix]
        RecipeSystem[Recipe System]
    end

    Registry --> OverlayStorage
    Registry --> Compatibility
    Validation --> Compatibility
    Search --> RecipeSystem
    Analytics --> OverlayStorage

    style Catalog fill:#BBDEFB
    style OverlaySystem fill:#C8E6C9
Hold "Alt" / "Option" to enable pan & zoom

Integration with Template Architecture

The Template Catalog integrates with the template architecture system:

Integration Points: - Base template resolution - Overlay resolution and composition - Recipe management and execution - Compatibility validation - Version resolution

Related Components: - Template Composition Engine - Recipe System - Agent Template Integration - Template Architecture Implementation


πŸš€ Future Enhancements

Feature Status
Reviewer suggestion engine (AI-based) πŸ”œ Design
Contributor leaderboard πŸ”œ Roadmap
Automatic template promotion scoring πŸ”œ Planned

βœ… Summary

This governance framework ensures that only high-quality, safe, and compatible templates enter the factory pipeline. It enables trustworthy automation at scale, promotes best practices, and empowers contributors to grow the ConnectSoft ecosystem with confidence.


βœ… Cycle 22 Completed

πŸŽ‰ The full 22-cycle series for the TemplateCatalog Domain is now complete.

Would you like to:

  • Export this as a single .md documentation file?
  • Start a similar 22-cycle plan for ProjectLifecycle or Orchestration domains?
  • Begin implementing the CLI and API elements defined above?