Skip to content

🧱 Module Blueprint

🧭 What Is a Module Blueprint?

A Module Blueprint is a design-time specification for a reusable, encapsulated unit of functionality in the ConnectSoft AI Software Factory. It defines a module’s purpose, structure, dependencies, export contracts, and integration hooks, serving as a foundational artifact for non-runtime or embedded logic components.

Unlike microservices or services, a module is not deployed independently β€” it is composed, imported, and reused across services, libraries, or frontend components.


🧩 Role in the Factory

Modules are building blocks of reuse and clean separation. They enable:

  • Cross-service logic reuse (e.g., domain rules, API contracts, validators)
  • Unified tooling and consistency (e.g., Observability SDK, Localization library)
  • Plugin-style extensions (e.g., payment provider adapter modules)
  • Shared models across service boundaries (e.g., ReferralDto, StatusEnum)

They are generated, versioned, validated, and stored just like services β€” but consumed as dependencies.


πŸ—οΈ Module Examples

Module Type Example Name Purpose
Domain Logic ReferralRulesEngine Encodes decision-making and workflows
API Contracts Shared.ReferralModels Shared DTOs, enums, error codes
Infra Adapter SendgridEmailAdapter Sends transactional emails via SendGrid
Frontend Lib UI.LocalizationHelpers Provides translation utilities for Blazor
Validation InsuranceEligibilityRules Validates constraints on entities

🧠 Produced By Agents

The Module Blueprint is generated by one or more of:

  • Module Generator Agent (primary)
  • Domain Modeling Agent
  • Adapter Orchestrator Agent
  • Documentation Agent

It defines the API and behavior of a reusable unit, along with all supporting metadata to allow traceability, testing, and versioning.


πŸ“ Output Formats

Each blueprint produces:

Format Purpose
.md Developer-facing module spec
.json Agent-consumable module structure
embedding Vector memory for semantic retrieval

File location:

blueprints/modules/{module-name}/module-blueprint.md

🧠 In short, a Module Blueprint is the DNA of reusable, traceable logic β€” powering consistency, efficiency, and observability across the Factory’s software genome.


πŸ—οΈ Types of Modules

In the AI Software Factory, modules are composable code units organized by their function and usage context. Each module adheres to specific contracts, initialization patterns, and dependency rules, and is classified into one or more of the following types.

This classification helps agents understand how to generate, wire, reuse, and validate modules across services and environments.


πŸ”’ Classification of Module Types

Type Purpose / Characteristics
Domain Logic Module Implements business rules, workflows, policies, calculators, rules engines
Infrastructure Adapter Implements technical interfaces: email, SMS, payment, search, etc.
Shared API Models DTOs, enums, contracts reused across microservices or frontend-backend boundaries
Validation Module Reusable constraint and business rule validators
Frontend Library UI components, i18n utilities, form builders, event hubs (Blazor, Angular)
Test Utility Module Builders, fakes, mocks, shared test assertions
Telemetry / Observability Module Logs, metrics, diagnostics, tracing contracts (e.g., AuditContext, SpanTags)
Security & Auth Helpers Claim resolvers, token validators, permissions mappers
Configuration Module Strongly-typed options, value resolvers, configuration policies
Factory Internal SDK Helpers for Factory agents to load, transform, analyze other components

🧱 Example: Backend-Domain Module

{
  "name": "ReferralRulesEngine",
  "type": "domain-logic",
  "exports": ["CalculateNextStatus", "IsReferralCompletable", "ValidateClinicEligibility"],
  "consumedBy": ["ReferralService", "TestRunnerAgent"]
}

🧱 Example: Frontend-Shared UI Module

{
  "name": "UI.LocalizationHelpers",
  "type": "frontend-library",
  "exports": ["translate", "localizeDate", "switchLocale"],
  "consumedBy": ["VetReferralApp", "CalendarWidget"]
}

πŸ” Multi-Type Modules

Modules can support multiple roles by exporting clearly defined namespaces:

module: Shared.Billing
β”œβ”€β”€ domain/
β”‚   └── InvoiceValidator.cs
β”œβ”€β”€ contracts/
β”‚   └── InvoiceDto.cs
β”œβ”€β”€ adapters/
β”‚   └── StripeAdapter.cs

These are still modeled as one blueprint, with multiple type tags.


🧠 Used By Agents For:

Agent Role
Microservice Generator Agent Pulls module dependencies into generated service code
Orchestration Agent Composes services using internal and external module maps
Test Generator Agent Uses test utility modules for mocking and scenario generation
Documentation Agent Documents exports, init flows, usage examples

🧩 The type of a module determines how it is generated, where it’s used, and what responsibilities it carries within the Factory ecosystem.


🧬 Blueprint Inputs & Generation Flow

The Module Blueprint is not written manually β€” it is generated automatically by the ConnectSoft AI Software Factory from upstream signals, agent interactions, and domain context.

This cycle describes how the blueprint is created, what it consumes, and how it fits into the larger blueprint generation pipeline.


πŸ” Generation Pipeline Overview

flowchart TD
  Product["πŸ“˜ Product Blueprint"]
  Domain["🧠 Domain Model Agent"]
  Feature["✨ Feature Signals"]
  AdapterMap["πŸ”Œ Adapter Registry"]
  Generator["🧠 Module Generator Agent"]
  Blueprint["πŸ“˜ Module Blueprint"]

  Product --> Generator
  Domain --> Generator
  Feature --> Generator
  AdapterMap --> Generator
  Generator --> Blueprint
Hold "Alt" / "Option" to enable pan & zoom

πŸ“₯ Inputs Used by the Module Generator Agent

Input Source Purpose
Product Blueprint Provides feature-level references to shared logic
Domain Model Suggests aggregates, rules, or mappers that need isolation
Feature Scenarios Identify reusable logic that appears across services
Adapter Mapping Links integration contracts to adapter module needs
Blueprint Catalog Prevents duplicate module generation (reuse existing)
System Constraints E.g., cross-platform limits, team preferences

πŸ› οΈ Blueprint Generation Steps

  1. Extract Functional Need Agents detect reused logic, DTOs, validators, or adapters referenced in more than one scope.

  2. Check for Existing Modules Search catalog to avoid regeneration or duplication.

  3. Draft Module Interface Based on patterns: exports, init, DI hints, traits (retryable, secure).

  4. Render Blueprint Markdown + JSON representation of module, trace-linked to inputs.

  5. Memory Embed & Catalog Registration Embed into vector DB and update module registry.


πŸ”„ Regeneration Logic

Module Blueprints are recomputed automatically if:

  • A new feature references the same logic
  • A domain signal indicates shared behavior
  • An upstream agent emits a module-related trace
  • A developer or agent requests regeneration with override

🧠 Agents That Trigger Generation

Agent Trigger Action
Feature Decomposer Agent Identifies shared logic across user stories
Domain Model Agent Tags reusable rules and validators
Integration Mapper Agent Recognizes need for external system adapters
Microservice Generator Agent Requests contracts from shared modules

🧠 Module blueprints are emergent artifacts, distilled from reuse patterns, not manually designed up front.


πŸ“¦ Structure of a Module

Every module in the AI Software Factory follows a structured layout and adheres to a consistent internal blueprinting model. This structure defines what a module exposes, how it integrates, and what dependencies it declares β€” ensuring that all modules are agent-readable, testable, and composable.


πŸ“ Typical Module Layout

modules/
  ReferralRulesEngine/
    src/
      CalculateNextStatus.cs
      ReferralStatusTransitions.cs
    tests/
      ReferralRulesEngine.Tests/
        CalculateNextStatusTests.cs
    docs/
      module-blueprint.md
      exports.md
    README.md
    .factory.module.json

πŸ“˜ Blueprint Structure

{
  "moduleId": "ReferralRulesEngine",
  "type": "domain-logic",
  "namespace": "Modules.ReferralRulesEngine",
  "exports": [
    "CalculateNextStatus",
    "IsReferralCompletable",
    "ValidateClinicEligibility"
  ],
  "dependencies": [
    "Shared.Kernel",
    "Domain.Enums.ReferralStatus"
  ],
  "init": {
    "requiresConfiguration": true,
    "registersWithDI": true
  },
  "consumedBy": [
    "ReferralService",
    "ScenarioTestRunner"
  ]
}

🧩 Key Blueprint Sections

Section Description
moduleId Unique identifier across the Factory
type Classification (domain-logic, adapter, api-contracts, etc.)
namespace Root namespace for code structure
exports Public APIs (classes, interfaces, methods, helpers)
dependencies Internal or external modules/libraries it consumes
init Configuration, DI requirements, runtime registration details
consumedBy What systems or services use this module

🧠 Export Contracts

Exports are machine-indexed and semantically embedded:

  • Functions (e.g., CalculatePremium)
  • Static classes (e.g., AuditPolicyProvider)
  • Interfaces (e.g., IPaymentProviderAdapter)
  • DTOs, validators, enums

Each export is traceable to:

  • Code location
  • Documentation stub
  • Generator agent origin

πŸ”Œ DI Initialization

Modules declare how they’re bootstrapped:

Property Meaning
requiresConfiguration Accepts strongly-typed options via IOptions<T>
registersWithDI Auto-registers using reflection or AddXyz()
hasPluginLoader Optional runtime plugin discovery

πŸ”Ž Observability Hooks (Optional)

Modules may optionally export:

  • Diagnostic tags
  • Metrics initialization
  • Log scopes

These are declared in a section like:

"observability": {
  "tags": ["referral-rule-eval"],
  "emits": ["RuleEvaluationResultMetric", "RuleFailedLog"]
}

πŸ“¦ The structure of a module is declarative, traceable, and designed to be introspected by any Factory agent at any point in its lifecycle.


🧱 Domain Module Example

Domain modules encapsulate business rules, policies, and decisions that are central to the system’s problem space. They model logic close to the core domain, but remain isolated and reusable β€” allowing services to delegate responsibility to these clean, testable components.


🧠 Purpose

  • Model business invariants and transitions
  • Isolate decision engines or state machines
  • Enable shared validation rules and status logic
  • Support traceable reasoning and behavioral drift prevention

πŸ“˜ Example: ReferralRulesEngine

Property Value
moduleId ReferralRulesEngine
type domain-logic
namespace Modules.ReferralRulesEngine
consumedBy ReferralService, ScenarioTestRunner
exports CalculateNextStatus, ValidateClinicEligibility, IsReferralCompletable
dependencies Shared.Kernel, Enums.ReferralStatus

πŸ“„ Export: CalculateNextStatus

public static class ReferralRulesEngine
{
    public static ReferralStatus CalculateNextStatus(Referral referral)
    {
        if (referral.IsCanceled) return ReferralStatus.Canceled;
        if (!referral.HasVetAssigned) return ReferralStatus.PendingAssignment;
        if (referral.IsApproved) return ReferralStatus.ReadyToBook;
        return ReferralStatus.UnderReview;
    }
}

πŸ“Ž Used By

Consumer How it's used
ReferralService Applies status change logic before emit
Tests Validates rule transitions across scenarios

πŸ§ͺ Tests

Each exported function is tested in its own *.Tests.cs file:

ReferralRulesEngine.Tests/
β”œβ”€β”€ CalculateNextStatusTests.cs
β”œβ”€β”€ EligibilityValidationTests.cs

🧠 Blueprint JSON Snippet

{
  "moduleId": "ReferralRulesEngine",
  "type": "domain-logic",
  "exports": [
    "CalculateNextStatus",
    "IsReferralCompletable",
    "ValidateClinicEligibility"
  ],
  "dependencies": ["Shared.Kernel", "Enums.ReferralStatus"],
  "consumedBy": ["ReferralService"]
}

πŸ” Benefits of Domain Modules

  • Enables centralization of business logic
  • Improves unit test coverage and maintainability
  • Supports traceable behavioral reasoning
  • Promotes DRY practices across bounded contexts

🧱 Domain modules are the smart bricks of your architecture β€” self-contained, testable, traceable, and declarative in behavior.


πŸ”Œ Adapter Module Example

Adapter modules encapsulate integration logic with third-party systems, external APIs, or infrastructure services. They follow the port-and-adapter pattern, enabling microservices to interact with the outside world via stable interfaces, while isolating vendor-specific implementations.


🧠 Purpose

  • Abstract away third-party libraries or APIs (e.g., Stripe, SendGrid, Segment)
  • Enforce consistent interfaces (ISmsSender, IPaymentProvider)
  • Provide fallback, retries, and circuit-breaking logic
  • Support plug-and-play behavior with mock/test adapters

πŸ“˜ Example: SendgridEmailAdapter

Property Value
moduleId SendgridEmailAdapter
type infra-adapter
namespace Adapters.Email.Sendgrid
implements IEmailSenderAdapter
consumedBy NotificationService, AuditService
registersWithDI true
configurable Uses SendgridOptions (API key, sender name)

πŸ“„ Interface + Implementation

public interface IEmailSenderAdapter
{
    Task SendAsync(EmailMessage message, CancellationToken ct = default);
}

public class SendgridEmailAdapter : IEmailSenderAdapter
{
    private readonly HttpClient client;
    private readonly SendgridOptions options;

    public SendgridEmailAdapter(HttpClient client, IOptions<SendgridOptions> options)
    {
        this.client = client;
        this.options = options.Value;
    }

    public async Task SendAsync(EmailMessage message, CancellationToken ct = default)
    {
        var payload = new { /* SendGrid JSON payload */ };
        await client.PostAsJsonAsync("/v3/mail/send", payload, ct);
    }
}

πŸ“‚ Folder Layout

SendgridEmailAdapter/
β”œβ”€β”€ IEmailSenderAdapter.cs
β”œβ”€β”€ SendgridEmailAdapter.cs
β”œβ”€β”€ SendgridOptions.cs
β”œβ”€β”€ SendgridEmailAdapterTests.cs
β”œβ”€β”€ module-blueprint.md

πŸ§ͺ Testable Adapter Contracts

Adapters can be swapped in tests using fake implementations:

public class FakeEmailSender : IEmailSenderAdapter
{
    public List<EmailMessage> Sent = new();
    public Task SendAsync(EmailMessage msg, CancellationToken ct = default)
    {
        Sent.Add(msg);
        return Task.CompletedTask;
    }
}

πŸ“˜ Blueprint JSON Fragment

{
  "moduleId": "SendgridEmailAdapter",
  "type": "infra-adapter",
  "namespace": "Adapters.Email.Sendgrid",
  "implements": "IEmailSenderAdapter",
  "consumedBy": ["NotificationService"],
  "init": {
    "requiresConfiguration": true,
    "registersWithDI": true
  }
}

🧠 Agent Behaviors

Agent Role
Microservice Generator Injects interface and DI config if blueprint consumed
Adapter Mapper Agent Ensures vendor/contract alignment
Test Generator Agent Generates fake/mock variants if flagged in blueprint

πŸ”Œ Adapter modules give the Factory safe and flexible connectivity β€” decoupling logic from implementation with clean, testable contracts.


πŸ“œ API Module Example

API modules define shared contracts for request/response types, enumerations, error codes, and data transfer objects (DTOs). They are crucial for ensuring strongly typed, versioned communication between microservices, frontend applications, and external consumers.


🧠 Purpose

  • Centralize DTOs and contract definitions
  • Avoid duplication of models across services
  • Enable compile-time validation across project boundaries
  • Support OpenAPI/gRPC schema generation and documentation
  • Provide stable, shared interface surfaces in the Factory

πŸ“˜ Example: Shared.ReferralModels

Property Value
moduleId Shared.ReferralModels
type api-contracts
namespace Contracts.Referral
exports ReferralDto, ReferralStatusEnum, ErrorCode
consumedBy ReferralService, VetReferralApp, QA Agents

πŸ“„ Export: ReferralDto

public class ReferralDto
{
    public Guid Id { get; set; }
    public string ClinicName { get; set; }
    public string Status { get; set; }
    public DateTime CreatedUtc { get; set; }
}

πŸ“„ Export: ReferralStatusEnum

public enum ReferralStatusEnum
{
    Pending,
    Assigned,
    Approved,
    Rejected,
    Canceled
}

πŸ“ Folder Structure

Shared.ReferralModels/
β”œβ”€β”€ Dtos/
β”‚   └── ReferralDto.cs
β”œβ”€β”€ Enums/
β”‚   └── ReferralStatusEnum.cs
β”œβ”€β”€ Errors/
β”‚   └── ErrorCode.cs
β”œβ”€β”€ module-blueprint.md
β”œβ”€β”€ README.md

πŸ“˜ Blueprint JSON Snippet

{
  "moduleId": "Shared.ReferralModels",
  "type": "api-contracts",
  "namespace": "Contracts.Referral",
  "exports": [
    "ReferralDto",
    "ReferralStatusEnum",
    "ErrorCode"
  ],
  "consumedBy": ["ReferralService", "QA Agent", "VetReferralApp"]
}

πŸ§ͺ Why It Matters

Benefit Description
🧬 Consistency All services use the same definitions
πŸ§ͺ Test Stability Validates DTO compatibility across versions
🧠 Semantic Traceability DTOs and enums are indexed in vector memory
πŸ“š Documentation Drives OpenAPI and agent-based documentation generation

🧠 Factory Role

Used By Purpose
Microservice Generator Agent Links contracts during scaffolding
Test Generator Agent Uses shared contracts for mocks
Documentation Agent Produces schema and usage docs

πŸ“œ API modules are the shared vocabulary of your system β€” expressive, reusable, and enforceable across all touchpoints.


πŸ–₯️ Frontend Module Example

Frontend modules provide shared UI components, helpers, and utilities for applications built with Blazor, Angular, or other frontend stacks used in the Factory. They support a consistent look, feel, and behavior, and can be shared across multiple frontend apps or widgets.


🧠 Purpose

  • Promote DRY principles across frontend projects
  • Standardize layout, components, error messages, date/locale formatting
  • Enable reuse of complex UI widgets (e.g., CalendarPicker, AddressForm)
  • Serve as feature-level building blocks (e.g., shared PatientCard)

πŸ“˜ Example: UI.LocalizationHelpers

Property Value
moduleId UI.LocalizationHelpers
type frontend-library
namespace Frontend.Helpers.Localization
exports translate(), formatDate(), switchLocale()
consumedBy VetReferralApp, BookingWidget, AdminDashboard

πŸ“„ Example Export: translate()

export function translate(key: string, locale: string): string {
    const dictionary = localizationResources[locale] || {};
    return dictionary[key] || key;
}

πŸ“„ Example Export: formatDate()

export function formatDate(date: Date, locale: string): string {
    return new Intl.DateTimeFormat(locale, { dateStyle: 'long' }).format(date);
}

πŸ“ Folder Layout

UI.LocalizationHelpers/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ translate.ts
β”‚   β”œβ”€β”€ formatDate.ts
β”‚   └── switchLocale.ts
β”œβ”€β”€ tests/
β”‚   β”œβ”€β”€ translate.spec.ts
β”‚   └── formatDate.spec.ts
β”œβ”€β”€ module-blueprint.md
β”œβ”€β”€ README.md

πŸ”§ Framework-Aware Modules

Modules are tagged with their target UI framework:

Tag Meaning
blazor Razor-based reusable C# components
angular Typescript/HTML-based components
web Framework-agnostic utilities (TS/JS)

Declared in blueprint:

"tags": ["frontend", "localization", "blazor"]

πŸ“˜ Blueprint JSON Snippet

{
  "moduleId": "UI.LocalizationHelpers",
  "type": "frontend-library",
  "framework": "blazor",
  "exports": ["translate", "formatDate", "switchLocale"],
  "consumedBy": ["VetReferralApp", "BookingWidget"]
}

🧠 Used By

Agent Role
Frontend Generator Imports shared modules when scaffolding Blazor
Test Generator Generates UI-level test cases
Localization Agent Injects localization initialization hooks

πŸ–₯️ Frontend modules drive the UX coherence and localization power of applications built with the Factory β€” enabling UI reuse across tenants, brands, and channels.


πŸ§ͺ Test Utility Module Example

Test utility modules provide reusable helpers, mocks, fakes, builders, and scenario scaffolding logic to enable high-quality automated testing across the Factory. These modules are consumed by agents and services to ensure consistency and correctness in unit, integration, and scenario-level tests.


🧠 Purpose

  • Promote consistent testing practices across services
  • Reduce boilerplate in test initialization and assertions
  • Provide shared test data generators and mock adapters
  • Enable agents to auto-generate tests using trusted patterns

πŸ“˜ Example: TestUtils.ReferralBuilders

Property Value
moduleId TestUtils.ReferralBuilders
type test-utility
namespace Tests.Builders.Referral
exports ReferralBuilder, ReferralScenarioHelper
consumedBy ReferralService.Tests, Test Generator Agent

πŸ“„ Export: ReferralBuilder

public class ReferralBuilder
{
    private Referral referral = new Referral();

    public ReferralBuilder WithStatus(string status)
    {
        referral.Status = status;
        return this;
    }

    public ReferralBuilder WithClinic(string name)
    {
        referral.ClinicName = name;
        return this;
    }

    public Referral Build() => referral;
}

πŸ“„ Export: ReferralScenarioHelper

public static class ReferralScenarioHelper
{
    public static Referral CreateApprovedReferral()
    {
        return new ReferralBuilder()
            .WithStatus("Approved")
            .WithClinic("Wellness Vet")
            .Build();
    }
}

πŸ“ Folder Layout

TestUtils.ReferralBuilders/
β”œβ”€β”€ ReferralBuilder.cs
β”œβ”€β”€ ReferralScenarioHelper.cs
β”œβ”€β”€ module-blueprint.md
β”œβ”€β”€ README.md

πŸ“˜ Blueprint JSON Snippet

{
  "moduleId": "TestUtils.ReferralBuilders",
  "type": "test-utility",
  "namespace": "Tests.Builders.Referral",
  "exports": ["ReferralBuilder", "ReferralScenarioHelper"],
  "consumedBy": ["ReferralService.Tests", "Test Generator Agent"]
}

🧠 Used By Agents

Agent Role
Test Generator Agent Uses module for test case generation
Microservice Generator Includes builders in default test projects
Scenario QA Agent Builds real-world flow simulations

πŸ§ͺ Traits of a Good Test Utility Module

  • Deterministic: No randomness unless explicit
  • Resettable: Isolated setup per test
  • Discoverable: Exported API is minimal and expressive
  • Tagged: Annotated for purpose (builder, mock, scenario)

πŸ§ͺ Test utility modules are the training ground for validation β€” empowering agents and humans to verify correctness efficiently and reliably.


🧠 Used By (Consumers and Contracts)

Every module in the ConnectSoft AI Software Factory exists to serve specific consumers β€” agents, services, or apps that rely on its exported logic or contracts. This section documents how modules are consumed, who uses them, and what obligations are implied by that consumption.


🧾 Consumption Relationships

Each Module Blueprint includes a consumedBy section that reflects:

  • Services importing and using the module
  • Frontend apps referencing its APIs or helpers
  • Agents depending on it for code generation or testing
  • Infrastructure (pipelines, observability) needing module-specific hooks

πŸ“˜ Blueprint Snippet

"consumedBy": [
  "ReferralService",
  "VetReferralApp",
  "Test Generator Agent"
]

πŸ“¦ Common Consumers

Consumer Type Description
Microservice Injects logic via DI, uses exports directly
Frontend App Imports UI or localization helpers
Test Project Uses builders, fakes, or scenario helpers
Generation Agent Reads blueprint to scaffold or validate generated code
Observability Agent Connects diagnostics, tags, or spans from module

🀝 Consumption Contracts

Consumers are expected to:

Responsibility Description
Respect APIs Only use documented exports, avoid internals
Pin Versions Declare semantic versions in dependency declarations
Initialize Properly Provide configuration if requiresConfiguration = true
Tag Use in Logs Tag emitted logs/metrics with module ID if emitting via observability hooks

🧠 Memory and Traceability

Each consumer relationship is stored in:

  • Memory Graph: Links between services, modules, agents
  • Trace ID: Which feature or scenario caused the relationship
  • Module Registry: Who uses what, and why

This allows reverse lookup:

β€œWhat modules does NotificationService rely on?” β†’ [AuditAdapter], [EmailValidator], [Shared.NotificationModels]


πŸ“Š Visualization Example

graph TD
  ReferralService --> Shared.ReferralModels
  ReferralService --> ReferralRulesEngine
  VetReferralApp --> Shared.ReferralModels
  TestAgent --> TestUtils.ReferralBuilders
Hold "Alt" / "Option" to enable pan & zoom

🧠 Every module is valuable only to the extent it’s used β€” and usage is not just tracked, but indexed, visualized, and agent-accessible across the Factory.


πŸ” Dependency Management

Modules within the AI Software Factory declare and resolve dependencies explicitly, allowing agents to reason about coupling, versioning, compatibility, and reuse across services. This makes modules predictable, composable, and traceable at scale.


🎯 Why Manage Dependencies?

  • Prevent tight coupling across bounded contexts
  • Enable agent-based dependency validation and reuse
  • Allow automatic graph-based impact analysis
  • Support version-aware module regeneration

πŸ“˜ Blueprint Fragment

"dependencies": [
  "Shared.Kernel",
  "Enums.ReferralStatus",
  "TestUtils.ReferralBuilders"
]

🧱 Types of Dependencies

Type Examples Notes
Internal Module ReferralRulesEngine Declared by moduleId
API Contracts Shared.ReferralModels Used for DTOs and enums
Test Utility TestUtils.ReferralBuilders Only valid in test-utility type modules
External Library FluentValidation, Serilog Usually registered in NuGet-level deps
Domain Enums Enums.ReferralStatus Treated as lightweight modules

πŸ“ Dependency Block in Blueprint

"dependencies": [
  {
    "moduleId": "Shared.ReferralModels",
    "version": "1.2.0",
    "required": true
  },
  {
    "moduleId": "TestUtils.ReferralBuilders",
    "scope": "test-only"
  }
]

⚠️ Dependency Validation

Agents validate:

Rule Reason
Only public exports are used Avoids breaking changes on internal logic
No circular imports Prevents infinite dependency loops
Version is pinned or inferred Ensures reproducibility
Usage aligns with module type e.g., infra-adapter cannot depend on UI

🧠 Agent Collaboration

Agent Role
Microservice Generator Agent Pulls transitive modules into solution template
Module Validator Agent Flags illegal or outdated dependencies
Documentation Agent Renders full module dependency graph for humans and agents
Pipeline Optimizer Agent Analyzes cross-module impact on CI speed and test scope

πŸ“Š Example Mermaid Graph

graph TD
  Shared.ReferralModels --> Enums.ReferralStatus
  ReferralRulesEngine --> Shared.ReferralModels
  ReferralService --> ReferralRulesEngine
Hold "Alt" / "Option" to enable pan & zoom

πŸ” Explicit dependency modeling turns module reuse into a safe, observable, and scalable operation β€” giving agents complete control over complexity.


πŸ” Security and Configuration Requirements

Modules in the AI Software Factory may declare security, permissions, secrets, and configuration requirements directly in their blueprints. This ensures secure-by-default behavior and enables the platform to automatically inject, validate, and audit sensitive operations and runtime inputs.


πŸ” When Security is Relevant

A module declares security metadata if it:

  • Uses secrets (API keys, tokens, certificates)
  • Applies authorization checks
  • Performs cryptographic operations
  • Emits or processes personally identifiable information (PII)
  • Is part of an audit trail

πŸ“˜ Example: Secure Adapter Module

"security": {
  "requiresSecrets": true,
  "secrets": ["Sendgrid:ApiKey"],
  "authorizationScope": null,
  "emitsAuditTrail": true,
  "handlesPII": true
}

πŸ”§ Configuration Block Example

"configuration": {
  "requiresConfiguration": true,
  "optionsClass": "SendgridOptions",
  "optionsProperties": [
    "ApiKey",
    "SenderName",
    "UseSandbox"
  ],
  "loadedVia": "IOptions<SendgridOptions>"
}

🧠 Why It Matters

Aspect Purpose
secrets Injected via Azure Key Vault / User Secrets
optionsClass Enables structured DI and validation
authorizationScope Ensures proper policy-based access in runtime
handlesPII Enables downstream agents to apply obfuscation, redaction, or audits
emitsAuditTrail Connects module output to audit pipelines

🧠 Used By Agents

Agent Role
Security Agent Validates secrets, audit trail, and permissions
Pipeline Generator Injects configuration source bindings
Observability Agent Tags logs/metrics as sensitive if handling PII
QA Agent Generates secure test data injection points

πŸ“¦ Factory Behaviors

  • If requiresSecrets = true, an env.yaml or KeyVault binding is created
  • If emitsAuditTrail = true, telemetry is automatically enriched with context
  • If handlesPII = true, logs are checked for redaction or suppression markers

πŸ” Security-aware modules ensure that automation and compliance are aligned β€” with no need for humans to manually secure what the blueprint already declares.


🧠 Blueprint Memory and Versioning

Every module blueprint is embedded into the Factory's memory graph, enabling semantic search, traceability, reuse, and validation across generations. Modules are also versioned explicitly, allowing agents to reason about changes over time, enforce compatibility, and manage upgrades.


🧠 Memory Embedding

When a module is created or updated:

  • The blueprint is vector-embedded for similarity search and LLM retrieval
  • A trace lineage is created, linking back to the prompt, feature, and consuming system
  • Tags, skills, and use-cases are indexed for reusability and explainability

πŸ“˜ Example Memory Index

"memory": {
  "traceId": "ftr-notification-routing",
  "embeddingId": "module:TestUtils.ReferralBuilders:v2",
  "skills": ["builder", "referral", "test-scenario"],
  "linkedFeatures": ["scenario-test-infra"],
  "relatedModules": ["ReferralService", "ReferralRulesEngine"]
}

πŸ”– Versioning Practices

Rule Purpose
Semantic versioning (v1.0.0) Allows compatibility reasoning across consumers
Stored with Git tags Enables agent-managed branching and merges
Compared by diff agents Tracks drift between blueprint and actual code
Blueprint-to-code hash linkage Prevents ghost or stale modules

Blueprint example:

"version": "2.1.0",
"status": "approved"

🧠 Agent Consumers of Version Data

Agent Use of Versioning
Diff & Drift Detector Finds untracked changes across module generations
Code Sync Validator Checks code vs blueprint for blueprint staleness
Dependency Planner Agent Resolves compatibility before inserting as dependency
Memory Search Agent Filters by skill, version, trace, or consumer match

πŸ“‚ Versioned File Names

modules/TestUtils.ReferralBuilders/module-blueprint.v2.md
modules/TestUtils.ReferralBuilders/module-blueprint.v2.json

πŸ” Regeneration and Snapshot

Modules can be:

  • Rebuilt from scratch with the same prompt and upstream blueprints
  • Revalidated for diff between stored and current source
  • Snapshotted in pipeline runs and QA plans

🧠 Version-aware memory of modules is the living knowledge base of the software factory β€” enabling fast, explainable, and safe regeneration.


βš™οΈ Lifecycle: Generation, Consumption, Evolution

Modules in the AI Software Factory follow a traceable, agent-governed lifecycle β€” from first generation to active usage, through evolution and eventual replacement or deprecation. Each phase is observable, versioned, and influenceable by upstream prompts, blueprint changes, and feedback from usage.


🧬 Phase 1: Generation

Step Description
Prompt interpreted From feature, service, or template request
Agent decides module type Based on pattern (e.g., adapter, test util, contract, etc.)
Blueprint created With shape, exports, dependencies, metadata
Memory stored Vector embedding + trace indexing

➑️ Agent: Module Generator Agent


πŸ“¦ Phase 2: Consumption

Consumer How it uses the module
Microservice Injects via DI or calls exported logic
Frontend App Imports TS/JS helpers or shared styles
Other Modules Link via declared dependencies
Test Projects Use builders, mocks, scenarios

➑️ Agent: Microservice Generator, Test Generator, Frontend Generator


πŸ” Phase 3: Evolution

Trigger Response
Blueprint is edited Agents diff code vs. blueprint, suggest or auto-patch
New feature emerges Existing modules can be linked or extended
Consumer version changes Compatibility and semantic versioning are validated
Drift detected Blueprint status marked as outdated, triggers validation run

➑️ Agent: Drift Detector, Blueprint Validator, Module Evolution Agent


☠️ Phase 4: Deprecation or Replacement

Reason Example
Library is deprecated Switch from RestSharpAdapter to HttpClientAdapter
Service is retired No consumers remain β†’ module archived
Pattern is outdated Replace rule-based engine with ML agent logic

Blueprint updated with:

"status": "deprecated",
"replacedBy": "NewModuleId"

🧠 Lifecycle Metadata

"lifecycle": {
  "generatedBy": "Microservice Generator Agent",
  "firstSeen": "2024-06-03",
  "lastUsedBy": ["TestAgent", "ReferralService"],
  "driftStatus": "clean",
  "version": "1.3.0"
}

πŸ”„ Regeneration Flow

graph TD
  Prompt --> ModuleGenerator
  ModuleGenerator --> Blueprint
  Blueprint --> Memory
  Memory --> GeneratorAgent
  GeneratorAgent --> Implementation
  Implementation --> DriftDetector
  DriftDetector --> Validator
Hold "Alt" / "Option" to enable pan & zoom

βš™οΈ Treating modules as living agents with a lifecycle allows for sustainable, trackable, and safe long-term evolution of software systems.


🧱 Module Folder Structure and Files

Each module generated by the Factory is materialized as a fully structured folder, designed to support development, testing, observability, and documentation β€” all driven by the module blueprint.


πŸ“ Standard Folder Layout

modules/
└── MyModule/
    β”œβ”€β”€ src/
    β”‚   └── MyModule.cs
    β”œβ”€β”€ tests/
    β”‚   └── MyModuleTests.cs
    β”œβ”€β”€ module-blueprint.md
    β”œβ”€β”€ module-blueprint.json
    β”œβ”€β”€ README.md
    β”œβ”€β”€ LICENSE
    └── .editorconfig

πŸ“‚ Key File Descriptions

File Purpose
module-blueprint.md Human-readable module specification (Studio, docs site)
module-blueprint.json Machine-readable agent interface
src/ Implementation files (C#, TS, Razor, etc.)
tests/ Co-located unit/integration/contract tests
README.md Developer overview of the module
LICENSE Optional; if the module is reusable/public
.editorconfig Optional coding style enforcement for consistency

πŸ“˜ Blueprint as Executable Artifact

Agents use the module-blueprint.json file as:

  • 🧭 A contract to scaffold or validate files in src/
  • πŸ”Ž A source for semantic embedding and trace linking
  • πŸ§ͺ A test generation contract for tests/ folder creation
  • 🧠 An origin for regeneration and lifecycle tracking

πŸ”„ Example: Module Regeneration Flow

If a change is made to the ReferralDto structure:

  1. Blueprint updated β†’ module-blueprint.v2.json
  2. Diff Agent analyzes changes vs src/
  3. Module Generator Agent proposes or applies regeneration in src/ and tests/

βœ… Optional Extensions

Depending on the module type, additional folders may exist:

  • docs/: Generated documentation from comments or blueprint metadata
  • locales/: Language packs for frontend libraries
  • schemas/: JSON or YAML schemas for DTO validation
  • mocks/: For fakes, simulations, sandboxing

🧠 Memory Hooks

Each file (especially blueprint, exports, and tests) is embedded and linked via:

  • traceId, moduleId, featureId
  • Semantic tags (e.g., dto, adapter, builder)
  • File checksum hashes for drift detection

🧱 Each module folder is more than a code container β€” it's a self-contained, observable unit of software behavior, tightly coupled to its blueprint and traceable across the Factory.


🧠 Agent Collaboration Patterns for Modules

Modules are not built or maintained in isolation β€” they are the result of intentional collaboration across multiple agents, orchestrated in real-time or asynchronously throughout the Factory lifecycle. Each agent contributes to the definition, generation, validation, or usage of modules.


🧩 Collaboration Roles

Agent Role in Module Lifecycle
Feature Planner Agent Suggests new modules based on feature decomposition
Module Generator Agent Creates blueprint and scaffolds folder/files
Test Generator Agent Adds scenario tests and builders tied to module structure
Drift Detector Agent Monitors module vs. code alignment over time
Observability Agent Embeds spans, metrics, and log patterns into module exports
Dependency Validator Agent Ensures proper import/export contracts, versioning, licenses
Security Agent Flags secrets, auth, or PII references for mitigation
Documentation Agent Converts blueprint + exports into Studio and MkDocs outputs

πŸ€– Orchestration Flow (Typical)

sequenceDiagram
    participant Planner
    participant Generator
    participant TestGen
    participant Drift
    participant Doc
    participant DevOps

    Planner->>Generator: Propose Module (from feature blueprint)
    Generator->>Generator: Generate Blueprint + Folder
    Generator->>TestGen: Emit test metadata
    TestGen->>Generator: Inject tests
    Generator->>Drift: Register for monitoring
    Generator->>Doc: Register for rendering
    Generator->>DevOps: Register for CI/CD hooks
Hold "Alt" / "Option" to enable pan & zoom

πŸ” Event Triggers

Modules may be updated or revalidated by:

Event Source Triggering Agent
Blueprint Drift Drift Detector Agent β†’ triggers re-sync suggestion
New Consumer Usage Service Generator β†’ updates consumedBy list
Feature Expansion Feature Planner β†’ creates derivative modules
Pipeline Validation Error CI Agent β†’ flags incorrect usage or missing exports

🧠 Memory Linkage

All agent-module interactions are:

  • Captured in the memory graph
  • Indexed by agentId, eventType, moduleId, version
  • Traceable by downstream agents via semantic lookups

πŸ“Š Example Graph View

graph TD
  Planner -->|suggests| ModuleGenerator
  ModuleGenerator -->|creates| ModuleBlueprint
  ModuleBlueprint --> TestGenerator
  ModuleBlueprint --> DriftDetector
  ModuleBlueprint --> ObservabilityAgent
Hold "Alt" / "Option" to enable pan & zoom

🧠 Collaboration is not optional in the Factory β€” every module is born and evolves as part of a multi-agent, multi-cycle system with feedback and trace.


πŸ“œ Module Prompt Patterns and Templates

The generation of a module begins with a well-structured system prompt, tailored to the intended type (e.g., utility, adapter, builder, domain contract) and context (e.g., related microservice, feature, or test). These prompts serve as the entry point for the Module Generator Agent, allowing deterministic blueprint creation.


🧠 Prompt Inputs

Input Description
featureId Tied to the originating Product or Vision blueprint
serviceId ID of the consuming or related microservice
moduleType adapter, utility, test-helper, domain-model, dto, etc.
expectedExports Key classes, functions, or contracts to be created
dependencies Optional: existing modules or libraries required
agentPersona Persona-specific guidance (e.g., Test Agent vs. Microservice Agent)

πŸ“˜ Sample Prompt Template – C# Adapter Module

You are the Module Generator Agent.
Generate a reusable C# adapter module that connects to the Sendgrid Email API.
It should expose `SendEmailAsync()` and `BuildMessage()`, and use DI and IOptions<SendgridOptions>.
The module should be tagged as `adapter`, `email`, and support configuration/secret injection.

Expected consumers: NotificationService, Test Generator Agent

πŸ“˜ Sample Prompt Template – Test Builder Module

Generate a test utility module called `TestUtils.ReferralBuilders`.
It should expose builders for `Referral` and `VetClinic`, with sample scenarios.
Mark it as `test-utility`, scoped only for test projects, and consumed by ReferralService.Tests.

πŸ”€ Prompt β†’ Blueprint Mapping

Prompt Concept Blueprint Field
module name moduleId
exported methods exports[]
tags tags[]
type type (adapter, dto, etc.)
target consumers consumedBy[]
requires config configuration.requiresConfiguration
uses secret security.requiresSecrets

🧠 Prompt Expansion by Agent

Before blueprint generation, the Module Generator Agent may:

  • Enrich with prior module usage patterns
  • Infer tags, memory links, and observability behaviors
  • Reuse naming conventions and folder structures

Prompts aren’t static β€” they are semantic starting points that drive structured generation logic.


πŸ“˜ Prompt Storage

Each prompt is stored in:

  • The blueprint (blueprint.prompt.original)
  • The memory graph (originPrompt)
  • The module’s Git metadata (.prompt.json)

πŸ“œ Structured prompts are the seed input of the Factory β€” and every module starts with a repeatable, explainable reasoning path.


🧠 Embedded Semantics, Tags, and Skills

Each module is enriched with semantic metadata, including skills, tags, and vector embeddings that empower agents to discover, reuse, explain, and reason about modules during generation and validation.


🧠 Purpose of Embedded Semantics

  • πŸ” Enable semantic search across modules
  • 🧠 Provide agents with functional capabilities linked to exports
  • πŸ” Detect overlap or duplication across the system
  • 🧩 Auto-suggest modules for composition, testing, or orchestration

πŸ“˜ Example Embedded Semantics Block

"semantics": {
  "tags": ["adapter", "email", "sendgrid", "async", "external-api"],
  "skills": ["send_email", "build_message", "log_failure", "use_ioptions"],
  "embeddingId": "module:SendgridAdapter:v1",
  "vectorIndex": "core-modules",
  "traceId": "notif-email-sendgrid"
}

πŸ”– Tags

Tag Type Examples Used For
type adapter, test-utility, builder Structural classification
domain referral, email, auth Domain-aware composition
behavior async, resilient, uses-config Code and runtime behavior description
agent-affinity qa-ready, observable, infra-link Agent-targeted discovery and reuse

βš™οΈ Skills

Skills describe what a module does, not what it is. They are verbs and function-level capabilities.

Example Skill Meaning
send_email Handles async sending of email
generate_scenario Produces simulated test scenario
map_domain_to_dto Translates aggregate to transport object
validate_input Performs validation logic
deserialize_event Parses message from event stream

Skills power composability β€” enabling agents to select modules by intent, not by name.


🧠 Agent Usage of Semantics

Agent Semantic Use Case
Module Generator Agent Searches by skill to avoid duplication
Test Generator Agent Identifies test modules with builder, scenario tags
Diff Detector Alerts if skills disappear across versions
Blueprint Validator Flags mismatch between claimed and implemented skills
Memory Search Agent Powers "Find module that can ___" queries

🧠 Embedding Shape

Modules are embedded as:

  • πŸ“¦ Structured JSON (blueprint)
  • 🧬 Vector embeddings (OpenAI, Azure Cognitive Search, etc.)
  • πŸ”– Enriched metadata objects (indexed in module registry)

🧠 Semantic tagging transforms the module registry into a functional API β€” searchable, composable, and explainable for both agents and humans.


πŸ“¦ Packaging, NuGet, and Distribution Patterns

Modules are often published and consumed as internal NuGet packages in the Factory ecosystem, enabling modular reuse, stable versioning, and clear contracts between services and components. This cycle defines how modules are packaged, distributed, and tracked across microservices and frontend/backend consumers.


πŸ“ When a Module Becomes a Package

A module is packaged if:

  • It is marked as distributable: true
  • It is consumed by more than one microservice or app
  • It implements a stable API or contract (e.g., shared models, adapters)
  • It is versioned and validated for reuse across bounded contexts

πŸ“˜ Blueprint Snippet

"packaging": {
  "distributable": true,
  "packageId": "ConnectSoft.Shared.ReferralModels",
  "nuget": {
    "enabled": true,
    "version": "1.5.2",
    "publishTarget": "azure-artifacts"
  }
}

🎯 Distribution Channels

Channel Description
Azure Artifacts Primary internal distribution registry
GitHub Packages Optional external/public module hosting
Local Dev Feed For local development/test consumption

πŸ—οΈ NuGet Metadata

When nuget.enabled = true, agents auto-generate:

  • .nuspec or equivalent .csproj tags
  • README.md for NuGet UI description
  • Source link + version tag
  • Dependencies declared via PackageReference

All aligned with blueprint metadata and traceable from module ID.


🧠 Agent Responsibilities

Agent Role in Packaging
Packaging Agent Builds .nupkg, signs, pushes to registry
CI Pipeline Generator Adds publish stage to azure-pipelines.yml
Dependency Validator Ensures no private/internal refs are leaked
Diff Detector Triggers rebuild if blueprint or implementation has changed

πŸ“¦ Consumption in Microservices

<ItemGroup>
  <PackageReference Include="ConnectSoft.Shared.ReferralModels" Version="1.5.2" />
</ItemGroup>

Module Generator Agent automatically links blueprint-defined packageId to generated .csproj.


πŸ“Š Observability

  • Each published package is tagged in the memory graph with version, consumedBy, and traceId
  • Consumption graph can be rendered: β†’ β€œWhich services use v1.3.2 of ReferralModels?”

🧠 Benefits

  • πŸ”„ Modules can be safely reused without copy-paste
  • βœ… Version control and diffability at package level
  • πŸš€ Accelerates onboarding, test coverage, and QA stability

πŸ“¦ Treating modules as packages makes reuse explicit, traceable, and reliable β€” and lets agents manage propagation and compatibility automatically.


πŸ“Š Observability and Diagnostics Interfaces

Modules may emit logs, metrics, traces, or health signals, especially if they contain critical logic, adapters, or infrastructure behaviors. Declaring observability intent in the blueprint allows the Factory to automatically integrate diagnostics hooks, enrich telemetry, and align with distributed tracing.


🎯 Observability-Enabled Modules

A module should define observability if it:

  • Handles external APIs, retries, or fallbacks
  • Performs validation, transformation, or enrichment
  • Affects user experience or error flows
  • Processes sensitive or auditable data

πŸ“˜ Blueprint Snippet

"observability": {
  "emitsLogs": true,
  "logScope": "referral.rules",
  "hasMetrics": true,
  "metricPrefix": "referral_rules_engine",
  "emitsTraceSpans": true,
  "isHealthContributor": false
}

🧱 Log Pattern Example

_logger.LogInformation("[referral.rules] Evaluated {RuleCount} rules for case {CaseId}");
  • Scoped log keys derived from logScope
  • Auto-enriched with traceId, moduleId, and featureId by pipeline

πŸ“ˆ Metric Generation

Blueprints with hasMetrics: true trigger:

  • Auto-registration of counters, histograms, timers
  • Namespace prefixing via metricPrefix
  • Test verification via QA metrics scaffolds

πŸ§ͺ Tracing Hooks

Modules marked with emitsTraceSpans will:

  • Auto-inject ActivitySource entries
  • Link to broader feature trace
  • Participate in end-to-end service call diagrams

🧠 Agent Collaboration

Agent Use of Observability Declarations
Observability Agent Scaffolds logs/metrics/traces and maps tags
QA Agent Uses metrics to assert behavior under test load
Security Agent Flags unsafe logging of PII or secrets
Memory Visualizer Includes logs/metrics in memory-linked dashboards

πŸ“¦ Health Integration

If isHealthContributor: true, module exports:

public class ReferralEngineHealthCheck : IHealthCheck { ... }
  • Registered in service-level /health endpoint
  • Used in CI smoke tests and live readiness probes

πŸ“Š Modules are not silent blocks β€” they are instrumented, observable units of logic, fully integrated into the Factory’s telemetry mesh.


πŸ§ͺ Testing, Testability, and QA Readiness

Every module in the Factory is treated as a testable unit. Blueprint declarations define the testing scope, patterns, and test utilities that enable both automated test generation and manual validation strategies.


πŸ§ͺ Testability Flags in Blueprint

"testing": {
  "unitTested": true,
  "hasTestScenarios": true,
  "requiresMocks": true,
  "testFramework": "MSTest",
  "exposedTestHooks": ["ReferralBuilder", "FakeEmailSender"]
}

🧬 Test Types Supported

Type Description
Unit Tests For internal logic, exports, condition handling
Scenario Tests Simulate high-level flow (e.g., SendEmail + StoreLog)
Contract Tests Validate DTOs, event shapes, API schemas
Health Probes For modules exposing health indicators

πŸ“ Folder Structure

modules/MyAdapter/
β”œβ”€β”€ src/
β”‚   └── MyAdapter.cs
└── tests/
    β”œβ”€β”€ MyAdapterTests.cs
    └── MyAdapterScenarioTests.cs

πŸ“˜ Test Generator Agent Responsibilities

  • 🧠 Reads blueprint exports[], skills[], and type
  • πŸ§ͺ Autogenerates:
    • Unit test stubs
    • Builder-based test helpers
    • Fake/mock injection setups
  • πŸ”„ Runs tests during CI for every module version update

βœ… QA Readiness Fields

"qaReadiness": {
  "hasScenarioCoverage": true,
  "qaAgentValidated": false,
  "lastCoverageScore": 82.5,
  "testRiskLevel": "medium"
}
  • Enables QA Planner Agent to prioritize test generation or manual QA for high-risk modules.

🧠 Memory and Test Traceability

  • All tests are tagged and indexed under the module's traceId
  • QA agents link test results directly to the original blueprint
  • Diff detectors can trigger re-test if code or blueprint drifts

πŸ’‘ Example Use Case

A module ReferralRulesEngine is updated with new logic. Diff Agent flags change, Test Generator Agent regenerates updated tests, QA Agent revalidates coverage, and CI pipeline confirms pass.


πŸ§ͺ Every module is designed to be test-aware, test-ready, and test-traceable β€” so quality isn’t bolted on, it’s built in.


πŸ” Security Rules and Enforcement Strategies

Modules may introduce security concerns β€” especially those that handle secrets, access control, user data, or external integration. The blueprint explicitly declares security posture, risks, and requirements, enabling agents to enforce policies, scan for violations, and inject mitigations during code generation.


πŸ” Blueprint Security Block

"security": {
  "requiresSecrets": true,
  "secrets": ["SendgridApiKey"],
  "requiresAuthentication": false,
  "handlesPII": true,
  "threatLevel": "medium",
  "sanitizationRequired": true
}

🚨 Security Tags Explained

Field Meaning
requiresSecrets Module accesses environment config or vault-based secrets
handlesPII Processes personal info (e.g., name, email, IP)
requiresAuthentication Requires caller validation before module can act
sanitizationRequired Must scrub or mask inputs/outputs in logs or external flows
threatLevel low, medium, high – used by Security Agent for prioritization

🧠 Agent Involvement

Agent Action
Security Agent Scans module blueprint + code for declared/undeclared risks
Drift Detector Flags if actual code adds risky logic not declared in blueprint
Observability Agent Validates that logs do not leak secrets or PII
Pipeline Agent Injects secret sanitization steps in CI/CD

πŸ§ͺ Example Enforcement: Sendgrid Adapter

public class SendgridAdapter {
    public SendgridAdapter(IOptions<SendgridOptions> options) {
        if (string.IsNullOrWhiteSpace(options.Value.ApiKey)) 
            throw new SecurityException("Missing Sendgrid API Key");
    }
}
  • Blueprint: requiresSecrets: true
  • Logs: Automatically scrub ApiKey
  • Pipelines: Fail if secret is hardcoded or unprotected

πŸ” Blueprint Validation Status

"securityValidation": {
  "lastScan": "2025-06-06",
  "issuesFound": 0,
  "scanTool": "FactorySecLint"
}

πŸ“¦ Secure-by-Design Principles

  • No module can be packaged if it violates blueprint-defined security policy
  • Secure coding templates (e.g., DI, config validation) are injected automatically
  • Risk is surfaced early to Product and QA agents via threatLevel

πŸ” Security is not inferred, it’s declared, enforced, and explainable β€” with full traceability from blueprint to deployment.


🧩 Module Relationships, Dependencies, and Composition

Modules are not isolated silos β€” they exist within a dependency graph that supports modular composition, avoids tight coupling, and allows agents to detect architectural violations or opportunities for reuse. Each blueprint explicitly captures incoming and outgoing relationships.


πŸ“˜ Dependency Block Example

"relationships": {
  "dependsOn": ["ConnectSoft.Shared.Logging", "ConnectSoft.Security.Crypto"],
  "usedBy": ["NotificationService", "EmailTestUtility"],
  "moduleCompositionGroup": "referral-notifications",
  "isComposable": true
}

πŸ”— Types of Relationships

Type Purpose
dependsOn Direct module references via DI or method calls
usedBy Consumers (microservices, test modules, pipelines)
compositionGroup Logical grouping for feature or domain alignment
peerModules Modules that are commonly composed together

πŸ“¦ Dependency Enforcement

Agents validate that:

  • No cyclical dependencies exist between modules
  • Public APIs of consumed modules are stable and versioned
  • Test-only modules do not leak into production scope

πŸ”„ Dynamic Composition Patterns

If isComposable: true, the module supports:

  • DI-based injection with interface bindings
  • Plugin discovery or reflection-based composition
  • Runtime extension points (e.g., hooks, policies, pipelines)

This enables runtime flexibility, especially in test engines, adapters, or builders.


🧠 Memory Linkage Across Modules

All dependencies are:

  • Indexed in the memory graph
  • Traceable with metadata like importStrength, changeImpact, lastUsed
  • Visualized via composition trees or service/module DAGs

🧱 Composition Example: Referral Notification Flow

graph LR
  ReferralService --> ReferralBuilder
  ReferralBuilder --> EmailPayloadGenerator
  EmailPayloadGenerator --> SendgridAdapter
Hold "Alt" / "Option" to enable pan & zoom

Each arrow is backed by dependsOn, exportedBy, and semantic skill matching.


🧠 Agent Use Cases

Agent Use of Relationships
Dependency Validator Flags broken, unstable, or unused dependencies
Module Generator Suggests composition patterns from usage graph
QA Agent Auto-stubs or mocks dependencies for isolated module testing
Doc Generator Agent Produces composition and usage diagrams from blueprint graphs

🧩 Relationship metadata enables the Factory to treat modules as LEGO-style components β€” buildable, swappable, traceable.


πŸ” Versioning, Diffing, and Change Management

Modules evolve β€” but change must be intentional, observable, and reversible. The Factory enforces blueprint-aware versioning, enabling precise tracking of modifications, compatibility across consumers, and safe regeneration when required.


πŸ“Œ Version Metadata Block

"versioning": {
  "currentVersion": "1.3.0",
  "previousVersion": "1.2.4",
  "versionStrategy": "semantic",
  "breakingChange": false,
  "lastUpdatedBy": "Module Generator Agent",
  "changeReason": "Added email fallback logic"
}

🧠 Version Strategy Types

Strategy Purpose
semantic Standard SemVer (MAJOR.MINOR.PATCH)
date-based Useful for rapid iteration modules
auto-increment Used when integrated with GitOps agents

🧬 Diff-Aware Blueprinting

When a module blueprint changes:

  1. A BlueprintDiffAgent compares old vs new
  2. Highlights changes in:

  3. exports[]

  4. skills[]
  5. security, observability, configuration
  6. Triggers:

  7. Regeneration of tests

  8. CI impact analysis
  9. Consumer alert if breaking change

πŸ“ Change History Log

Each module tracks history in memory and optionally in Git metadata:

"changeHistory": [
  {
    "version": "1.2.0",
    "date": "2025-05-12",
    "reason": "Initial implementation of SendEmailAsync"
  },
  {
    "version": "1.3.0",
    "date": "2025-06-08",
    "reason": "Fallback logic, new metric emitted"
  }
]

πŸ”’ Locked Versions in Consumers

Microservices or other modules may declare version locks:

"dependencies": {
  "ConnectSoft.Email.SendgridAdapter": "1.2.*"
}

Agents ensure compatibility or flag misalignment during CI.


πŸ“’ Breaking Change Flag

If breakingChange: true, this will:

  • Prevent automated publishing until approved
  • Trigger consumer validation from dependent modules
  • Alert product and QA agents for re-review

πŸ“¦ Version Tagging in Registry

  • All .nupkg or .dll outputs are tagged with matching version metadata
  • Memory and observability events are version-scoped (v1.3.0)
  • Documentation and prompts can retrieve versioned diffs

πŸ” Versioning in the Factory is not just for code β€” it’s for intent, structure, and change traceability at blueprint and behavior level.


πŸ“„ Documentation, Studio Integration, and Blueprint Visibility

Modules are not only code β€” they are intelligent components with explainable purpose, context, and usage. The blueprint enables deep integration with documentation systems, visualization tools, and the AI Factory Studio, making every module discoverable, browsable, and explainable.


πŸ“˜ Markdown Blueprint Output

Each module produces a rich .md file:

modules/{module-name}/module-blueprint.md

This document includes:

  • πŸ“¦ Overview (name, purpose, skills)
  • πŸ”— Dependencies
  • βš™οΈ Exports and Configuration
  • 🧠 Semantics and Tags
  • πŸ›‘οΈ Security and Observability
  • πŸ”¬ QA readiness and Test Patterns
  • πŸ“¦ Packaging and Consumption

🌐 Studio Embedding and Display

In ConnectSoft AI Studio:

  • Modules are shown as cards or expandable trees
  • Filtered by:
    • skills
    • usedBy
    • observability
    • featureId
  • Visual diffing available (across versions)
  • Click-to-view source, prompt, test links, metrics

πŸ” MkDocs / Docs-as-Code Integration

Modules are injected into:

  • πŸ“š /docs/modules/ folder with auto-generated TOC
  • Cross-linked to:
    • Features
    • Microservices
    • Pipelines
  • Updated on every blueprint regeneration

Example:

docs/modules/sendgrid-adapter/module-blueprint.md

🧠 Agent Interaction in Docs

Agent Action in Documentation
Doc Generator Agent Builds markdown with structured headers and Mermaid diagrams
Memory Visualizer Agent Adds graphs, usage maps, and composition chains
Prompt Recovery Agent Links to original prompt that created the module

🧩 Blueprint Visibility in Git

All blueprints are committed to the module folder:

modules/MyAdapter/
β”œβ”€β”€ module-blueprint.md
β”œβ”€β”€ module-blueprint.json
β”œβ”€β”€ src/
└── tests/

Includes README, test coverage, diff summaries, and tags.


πŸ“ˆ Telemetry and Studio Metrics

Modules show up in dashboards:

  • πŸ“Š Usage stats: by consumers, test runs, pipelines
  • πŸ”„ Update frequency
  • ❗ Risk score (security + test + drift)

πŸ“„ A module isn’t hidden behind code β€” it’s documented, versioned, queryable, and explainable by humans and agents alike.