Skip to content

Backend Library Generator Agent (Factory-Compliant Microservice) Tasks

[BLGA-EPIC] Backend Library Generator Agent (Factory-Compliant Microservice)

Project Title: Backend Library Generator Agent (BLGA) Repository/Solution: ConnectSoft.Factory.BackendLibraryGeneratorAgent

Executive Summary

BLGA is a factory-compliant microservice that converts Backend Library Blueprints + DSLs into fully realized .NET libraries with code, tests, docs, CI/CD, and governed Azure DevOps PRs. It orchestrates workspace preparation, template rendering, quality enforcement, and delivery to a target repo under strict security, observability, and policy controls. BLGA’s outputs are deterministic, idempotent, and auditable, enabling repeatable library creation across ConnectSoft’s Software Factory.

Problem Statement

Creating production-grade libraries is slow and error-prone when done manually: standards drift, CI gaps, and inconsistent documentation increase time-to-value and total cost. BLGA codifies ConnectSoft’s patterns (anemic DDD, Clean Architecture, testing, observability-first) into a governed, automated pipeline that turns intent (blueprints + DSL) into ready-to-merge contributions.

Mission & Outcomes

  • Mission: Reduce library creation cycle time from weeks to hours while raising quality, increasing consistency, and preserving governance.
  • Primary Outcomes:
    • Deterministic generation of libraries aligned to Factory standards.
    • CI-green PRs with required reviewers, labels, and policy checks.
    • Measurable quality gates (build, test, coverage) and security baselines.
    • Full traceability from blueprint → patch → PR → release artifacts.

Business Value

  • Speed: Standardized scaffolds and automation compress lead time.
  • Quality: Embedded gates (coverage, analyzers, style) prevent regressions.
  • Governance: Policy-driven branching, reviewers, compliance logs.
  • Reusability: Common contracts (GitOps/PR orchestration, QA runner) for other Generator Agents.

Scope (What BLGA Does)

  • Ingests: Backend Library Blueprints & DSLs (intent, ports, policies).
  • Renders: Projects, .csproj (multi-TFM), solution structure, analyzers, Directory.Build.*, unit/integration test scaffolds, README, pipeline YAML, docs skeletons.
  • Orchestrates: Workspace prep → render → local quality → push branch → open PR → report status.
  • Enforces: Coverage floor, code style, license/third-party allow-lists, secret redaction.
  • Observes: OTel traces/metrics/logs; correlation across saga steps; artifact fingerprints.
  • Delivers: Deterministic patches, CI-passing PRs, and indexed artifacts (for reasoning/knowledge).

Out of Scope (for this Epic)

  • Publishing to public package feeds (nuget.org) beyond internal feeds.
  • Non-.NET language renderers (tracked as future variants).
  • Organization-wide policy authoring (BLGA consumes—doesn’t author—global policy).

Target Users & Personas

  • Vision/Solution Architects: encode patterns into blueprints and policy packs.
  • Backend Developers: request new libraries; review and merge PRs.
  • Platform/DevEx: maintain templates, gates, infra, and governance.
  • QA/Release Engineers: verify CI gates, coverage, and promotion readiness.
  • Agentic Orchestrators: other agents invoking BLGA as a tool.

Key Capabilities (High-Level)

  • Contract-First Interfaces: gRPC (StartGeneration, GetRunStatus), Bus (commands/events), MCP tools (library.start_generation, library.get_status).
  • Determinism & Idempotency: correlation keys + blueprint/patch SHAs; replay-safe orchestration.
  • Quality Built-In: build/test/coverage checks, analyzers, structured validators (README/YAML/.csproj).
  • Governed PRs: branch naming, labels, required reviewers, PR comments/status checks.
  • Security Baseline: Managed Identity, Key Vault, redaction, RBAC, least-privilege Git ops.
  • Observability-First: OTel spans per step, metrics (success rate/latency/retries), structured logs, trace↔PR linkage.
  • Sandbox Mode: dry-run (no-PR) preview with TTL cleanup and Studio visibility.

Architecture Overview

  • Style: Anemic DDD + Clean Architecture layers (Domain, Application/Use-Cases, Ports/Adapters, Persistence).
  • Orchestration: Saga state machine drives stepwise generation with compensations and retries.
  • Persistence: NHibernate for state/outbox/audit; FluentMigrator for schema/migrations.
  • Messaging: MassTransit for commands/events; outbox for reliable delivery.
  • Interfaces: gRPC for service calls; MCP for agent/tooling interop; ADO PR adapter for delivery.
  • Runtime: Containerized service (non-root), Azure Container Apps; Pulumi-provisioned infra (ACR, ACA, SB, KV).
  • Observability: OpenTelemetry → App Insights/Log Analytics; optional Grafana/Workbooks.

Inputs & Outputs

  • Inputs: Blueprint + DSL docs (intent, structure, policies), policy packs (coverage floor, reviewers, branch/prefix, license allow-list), template assets.
  • Outputs: Deterministic patch/branch, PR with artifacts (logs, coverage, diff report), generated docs/tests, CI pipeline, trace and audit records.

Quality & Security Guardrails

  • Quality Gates: Build=pass; Unit/Integration tests=pass; Coverage ≥ platform floor; analyzers clean or triaged.
  • Security: No secrets in code/logs; KV-backed credentials; redaction of PII/secrets; repo/branch allow-lists; rate limits; role-based access to operations.

SLOs & KPIs

  • SLO: P95 generation (render→PR opened) ≤ 15 min in sandbox with standard blueprint.
  • KPIs: PR success rate, coverage %, retry counts, mean review time, rollback/compensation incidence, determinism (patch reproducibility).

Compliance & Auditability

  • Audit Trail: Correlated events for each step; UTC timestamps; PR/branch actions logged.
  • Reproducibility: Same blueprint + policy + template version ⇒ same patch (byte-for-byte or controlled deltas).

Risks & Mitigations

  • Template Drift: Centralized templates with version pinning; smoke tests per version.
  • Policy Conflicts: Policy validation early; descriptive error surfaces; human-in-loop escalation.
  • External Service Limits (ADO/Git): Backoff + jitter; DLQ + replay; clear operator guidance.

Dependencies

  • Azure DevOps (Repos, Pipelines, Boards), Azure Key Vault, Azure Container Registry/Apps, Azure Service Bus.
  • Template/Blueprint repositories; Company policy packs; Observability stack (OTel receivers).

Deliverables (Epic Level)

  • Working Service exposing gRPC & MCP; message contracts published.
  • Governed PR Flow producing CI-green PRs with policy labels/reviewers.
  • Docs & Runbook: overview, architecture, API, operations, troubleshooting.
  • IaC Stack: Pulumi for ACR/ACA/SB/KV; reproducible environments.
  • Dashboards: traces/metrics/logs with correlation to PRs.

Acceptance Criteria (Epic)

  • A standard blueprint run creates a deterministic branch & PR with green CI and required governance (labels/reviewers).
  • All quality/security gates enforced; observability shows correlated traces/metrics/logs.
  • A new engineer can read the runbook and complete a sandbox generation within one day.
  • Demo evidence recorded; decision log/ADRs merged.

[BLGA-FEAT-01] Foundations & Repo Scaffolding

Outcome: A factory-compliant repository and solution for Backend Library Generator Agent is created by generating from the ConnectSoft.MicroserviceTemplate (no separate “template pack”). The resulting solution is named ConnectSoft.Factory.BackendLibraryGeneratorAgent and includes all cross-cutting features prewired (tests, analyzers, configuration, health checks, OpenTelemetry, metrics, validation, mapping, resiliency, logging, feature flags, etc.). All standard projects are created at once exactly as defined in the Solution Structure document; only business logic remains for future features.


Scope

In scope

  • Generate the solution from ConnectSoft.MicroserviceTemplate with the solution name ConnectSoft.Factory.BackendLibraryGeneratorAgent.
  • Ensure exact project names and layout per the Solution Structure document (no deviations or renames).
  • Bring up CI on PRs into master (build/test/coverage artifacts) and set branch protections (required status check + reviewer).
  • Author developer bootstrap docs (Getting Started, local run with fakes, structure map).

Out of scope

  • Business use-cases, orchestration, external adapters (covered in later features).
  • Cloud provisioning/CD beyond PR validation (introduced in Delivery Engineering).

Deliverables

  • Repository & Solution: ConnectSoft.Factory.BackendLibraryGeneratorAgent generated from the microservice template; compiles and runs locally with health endpoints.
  • Cross-cutting features enabled by default: analyzers, centralized package mgmt, configuration, health checks, OpenTelemetry, metrics, resiliency, structured logging, feature flags, unit/acceptance/architecture tests, AutoMapper, FluentValidation.
  • CI (PR validation) on master: Azure Pipelines YAML with build/test/coverage, artifacts, and a temporary coverage floor (70%).
  • Docs: README.md, docs/getting-started.md, docs/local-run.md, docs/solution-structure-map.md.

Dependencies

  • Azure DevOps project/repo + build pool access.
  • Internal NuGet feeds and analyzer packages reachable from the pipeline.
  • Agreement on initial coverage floor (70%) for PR gate.

Tasks

[BLGA-TASK-01.1] End-to-End — Generate Solution, Verify Structure, Baselines, Health

Intent Produce the actual BLGA solution by running ConnectSoft.MicroserviceTemplate, enforcing the precise project tree and enabling all cross-cutting features out of the box.

Steps

  1. Generate the solution using ConnectSoft.MicroserviceTemplate with solution name: ConnectSoft.Factory.BackendLibraryGeneratorAgent.
  2. Verify exact project names & folders against the Solution Structure document (no missing/extra/renamed projects).
  3. Build baselines:
    • Directory.Build.props/targets with deterministic builds, Nullable=enable, TreatWarningsAsErrors=true.
    • Analyzers/style rules and central package management wired.
  4. Health endpoints: ensure /health/live and /health/ready return 200; logs are structured with correlation IDs.
  5. Cross-cutting verification checklist: analyzers on, tests compile, configuration binds, OpenTelemetry hooks present, metrics exposed, resiliency policies configured, logging sinks/options present, feature flags resolvable.

Artifacts

  • Committed, compiling solution; local host runs with health green.
  • Completed structure verification checklist stored in docs/solution-structure-map.md (links each project to its purpose).

Acceptance Criteria

  • A clean machine can restore → build → run; health endpoints pass; structured logs appear at startup.
  • All expected projects from Solution Structure exist with exact names, and all cross-cutting features are present/enabled.

[BLGA-TASK-01.2] End-to-End — CI Bootstrap (PR build/test/coverage) & Branch Protections on master

Intent Guarantee consistent validation on every PR to master, without using CODEOWNERS.

Pipeline (azure-pipelines.yml)

  • Trigger: pr to master (paths: /src, /tests, /docs, /build, pipeline file).
  • Jobs: restore → build (Release) → test (MSTest) → publish Cobertura coverage + test results; upload artifacts (logs/coverage).
  • Gate: coverage floor ≥ 70% (temporary); failing tests/coverage block merge.

Branch Protections (ADO)

  • Default branch master.
  • Required status check = the CI pipeline.
  • Require ≥ 1 reviewer (no CODEOWNERS).

Steps

  1. Add/commit pipeline YAML; run once to validate artifacts and coverage publishing.
  2. Configure branch policies on master (required status check + reviewer).
  3. Add a PR template (tests/docs/security checklist) and default labels.

Artifacts

  • Passing CI run with artifacts linked in PRs.
  • Screenshot or short doc of branch policy settings saved to docs/governance.md.

Acceptance Criteria

  • Any PR to master runs CI; failing build/tests/coverage prevent merge.
  • Reviewer requirement and required status check are active on PRs.

[BLGA-TASK-01.3] End-to-End — Developer Bootstrap Docs (Getting Started, Local Run, Structure Map)

Intent Enable a new engineer to clone, build, run locally, and understand the generated solution’s layout and cross-cutting features within one day.

Documentation set

  • README.md — purpose, quickstart, repo conventions.
  • docs/getting-started.md — prerequisites, devcontainer/CLI steps, build/test, run host, validate health.
  • docs/local-run.mdappsettings.Development.json config, sample commands, log examples, troubleshooting.
  • docs/solution-structure-map.mdmaps each project (exact names) to its role, highlights that all projects are created at once, lists always-on cross-cutting features, and clarifies what remains (business logic).

Dev experience

  • .devcontainer with SDK, Git, Node (for docs build) and test tools.
  • dotnet-tools.json for formatters and coverage viewers.
  • Optional Makefile/justfile targets (build/test/run/format).

Acceptance Criteria

  • A new dev follows docs and builds → tests → runs host without assistance.
  • They can point to docs/solution-structure-map.md to explain exact project names, the all-at-once generation, and the cross-cutting features that are already wired.

Governance & Policy Hooks (for this feature)

  • Quality: analyzers enabled, warnings-as-errors, coverage reports published.
  • Security: no secrets in repo; (Key Vault/MI introduced later).
  • Observability: structured logs from day one; OTel hooks present (activated later).
  • Compliance: PR checklist adopted; branch policies enforced on master.

Acceptance (Feature)

  • The repo compiles and runs with health probes; CI on PR to master is green.
  • Branch protections on master are active (required status check + reviewer).
  • Docs allow a newcomer to succeed in ≤ 1 day.
  • The solution generated from ConnectSoft.MicroserviceTemplate is named ConnectSoft.Factory.BackendLibraryGeneratorAgent, has exact project names per Solution Structure, and has all cross-cutting features enabled.

[BLGA-FEAT-02] Domain Model & Value Objects (Anemic DDD)

Outcome: The Domain group is modeled precisely in the template-generated solution using the exact projects and names from the Solution Structure: ConnectSoft.Factory.BackendLibraryGeneratorAgent.EntityModel, …DomainModel, …DomainModel.Impl (no deviations). The LibraryGeneration aggregate with owned components (Workspace, Quality, GitOutcome, PullRequest) and Value Objects (VOs) is introduced in EntityModel, with an anemic style (state + contracts), and thin domain services in DomainModel.Impl for validations and mapping helpers. Enumerations are implemented as lookup-code based rich Enumeration classes (not primitive enum), ready to map to database lookups in the next feature. Unit tests validate identity, VO equality, and sample state transitions via an in-memory repository.


Scope

In scope

  • Model Aggregate Root LibraryGeneration with owned components and metadata in …EntityModel. Lifecycle is expressed as status via Enumeration classes and codes (no primitive enums). Owned components are flattened conceptually for persistence later.
  • Introduce Value Objects: CorrelationId, BlueprintSha/PatchSha (fingerprints), RepoRef, BranchName, CommitMessage, Coverage, GitPatchFingerprint, Path, HttpUrl, WorkItemRef. Equality is by value and all VOs are immutable.
  • Define Rich Enumerations (lookup-code backed) for: LibraryGenerationStatus, QualityStatus, PullRequestState, SourceControlProvider. Provide codes aligned to later DDL seeding.
  • Add thin domain services in …DomainModel.Impl for transition policies and idempotency helpers (anemic style; orchestration stays in saga later).
  • Provide in-memory repository + specs for sample queries (ByCorrelationId, ByStatus, Recent).

Out of scope

  • Database schema/mappings (NHibernate + migrations) — covered in FEAT-03.
  • Saga orchestration and external adapters — covered later.

Deliverables

  • EntityModel:

  • LibraryGeneration (Aggregate Root) with fields: Id(Guid), CorrelationId(Guid), BlueprintSha, PatchSha, Status (LibraryGenerationStatus), timestamps (CreatedUtc, UpdatedUtc, CompletedUtc), LastError, RowVersion (concurrency token). Owned components (as owned value structures in the model layer):

    • Workspace: WorkspaceRoot, WorkspaceScratch.
    • Quality: QualityStatus, CoveragePercent, QualityReportUrl.
    • GitOutcome: SourceControlProvider, RepoFullName, BranchName, CommitId, GitPatchFingerprint.
    • PullRequest: PullRequestState, PrNumber, PrUrl.
    • Value Objects implemented with value-based equality + immutability.
    • Enumerations (classes) with Id, Code, Name + static catalogs and FromCode/FromId helpers for: LibraryGenerationStatus, QualityStatus, PullRequestState, SourceControlProvider. Codes prepared for later lookup seeding (e.g., QualityStatus: Unknown/Pass/Fail; PullRequestState: None/Open/Merged/Closed/Abandoned; SourceControlProvider: Ado/GitHub).
    • DomainModel: Contracts for simple use cases (StartGeneration, GetRunStatus) and validation results (no orchestration).
    • DomainModel.Impl: Thin services for state transition validation and idempotency checks (e.g., duplicate CorrelationId, identical BlueprintSha+PatchSha).
    • Unit tests in …UnitTests for: entity identity semantics, VO equality, enumeration parsing, deterministic BranchName and CommitMessage formation, and sample transitions using an in-memory repository.

Tasks

[BLGA-TASK-02.1] End-to-End — Model LibraryGeneration Aggregate + Owned Components + VOs; Unit Tests

Intent Create the domain backbone in EntityModel following ConnectSoft modeling guidance (identity-focused Entities, immutable VOs, small Aggregate boundaries).

Steps

  1. Aggregate & Entities

  2. Add LibraryGeneration with identity + timestamps and owned component properties for Workspace, Quality, GitOutcome, PullRequest. Keep Aggregate boundary small and interactions controlled through the root (anemic: no behavior methods, only state + guards used by services).

  3. Value Objects

  4. Implement VOs (CorrelationId, BlueprintSha, PatchSha, RepoRef, BranchName, CommitMessage, Coverage, GitPatchFingerprint, Path, HttpUrl, WorkItemRef) with immutability and value-based equality using the shared ValueObject base pattern.

  5. Domain Contracts

  6. In …DomainModel, define minimal contracts (DTOs + interfaces) for StartGeneration and GetRunStatus that reference VOs and enumeration types (not primitives).

  7. Unit Tests

  8. Add tests verifying: VO equality, BranchName and CommitMessage determinism, correlation uniqueness, and that a newly created aggregate defaults to Status=Pending and valid owned-component defaults.

Artifacts

  • …EntityModel classes for Aggregate, owned components, and VOs.
  • …DomainModel contracts for start/status.
  • Unit tests passing for equality, defaults, and deterministic formatting.

Acceptance Criteria

  • Aggregate compiles, VO equality passes, no domain → infra references (architecture test).
  • A new LibraryGeneration created via factory sets Pending, has valid owned components, and serializes cleanly.

[BLGA-TASK-02.2] End-to-End — Replace Enums with Lookup-Code Enumerations + Transition Helpers + Sample In-Memory Runs

Intent Implement class-based Enumerations with Id/Code/Name, plus transition policies and idempotency guards in …DomainModel.Impl. Provide an in-memory repository + specifications to run sample transitions without a database.

Steps

  1. Enumeration Classes (Catalogs)
    • Implement LibraryGenerationStatus, QualityStatus, PullRequestState, SourceControlProvider as rich enumerations with static lists, FromId/FromCode, and helper predicates (e.g., IsTerminal, IsOpen). Codes aligned to later seeded lookups (e.g., QualityStatus: Unknown/Pass/Fail, PullRequestState: None/Open/Merged/Closed/Abandoned, SourceControlProvider: Ado/GitHub).
  2. Transition & Idempotency Helpers (Anemic Services)
    • Add LibraryGenerationPolicies service that validates legal transitions (Pending → WorkspaceReady → Generated → QualityPassed/QualityFailed → BranchPushed → PROpened → Completed/Failed), enforces idempotency (same BlueprintSha + PatchSha ⇒ duplicate run), and computes deterministic BranchName from VO inputs.
  3. In-Memory Repository + Specifications
    • Provide an in-memory ILibraryGenerationRepository + specs: ByCorrelationId, ByStatus, Recent. Demonstrate a sample flow (create → set workspace → mark generated → quality pass → branch pushed → PR opened → completed) with assertions.
  4. Docs
    • Add docs/domain-model.md describing Aggregate, VOs, Enumeration codes and the anemic stance for this service (behavior orchestrated externally later).

Artifacts

  • Enumeration classes + catalogs with codes.
  • LibraryGenerationPolicies and helpers.
  • In-memory repo + specs; sample scenario test.

Acceptance Criteria

  • All enumeration parsing/lookup tests pass (FromCode, FromId, IsTerminal).
  • Sample in-memory run completes along the allowed path; illegal transitions are rejected.
  • Duplicate (BlueprintSha + PatchSha) runs are identified and flagged by policy.

Dependencies

  • Solution and project structure from FEAT-01 (already generated from template with exact names).
  • Downstream features for persistence mappings and migrations (FEAT-03), where these enumerations will map to seeded lookup tables.

Notes

  • Keep Domain anemic on purpose here (behaviors coordinated later by Saga/Flow), yet still apply ConnectSoft modeling rigor for identity/VOs/enumerations and boundaries.

[BLGA-FEAT-03] Database & Model Layer (Schema + Migrations + NHibernate)

Outcome: A production-ready relational model for SQL Server with FluentMigrator migrations and NHibernate (mapping-by-code) is delivered for the LibraryGeneration aggregate. The model uses UTC datetimeoffset, nvarchar for text, lookup tables for rich enumerations, and optimistic concurrency via rowversion. A tactical Repository + Specification path is implemented. Integration tests run against a local SQL Server (no containers).


Scope

In scope

  • Physical schema for LibraryGeneration with owned components flattened.
  • Lookup tables + seed data for: LibraryGenerationStatus, QualityStatus, PullRequestState, SourceControlProvider.
  • Migrations (Up/Down) with strict naming conventions, indices, and constraints.
  • NHibernate mapping classes (no attributes in domain).
  • Repository APIs (ILibraryGenerationRepository) with Specification support.
  • Integration tests using local SQL Server (LocalDB or Developer Edition).

Out of scope

  • Outbox/Audit tables (provided elsewhere) — excluded here.
  • Distributed transactions and multi-DB concerns.

Deliverables

  • Projects (names as in solution structure):

    • ConnectSoft.Factory.BackendLibraryGeneratorAgent.DatabaseModel.Migrations
    • ConnectSoft.Factory.BackendLibraryGeneratorAgent.PersistenceModel
    • ConnectSoft.Factory.BackendLibraryGeneratorAgent.PersistenceModel.NHibernate
    • Tests under ConnectSoft.Factory.BackendLibraryGeneratorAgent.AcceptanceTests (local SQL Server)
  • Schema (SQL Server) LibraryGenerations

  • Id uniqueidentifier (PK)

  • CorrelationId uniqueidentifier (UNIQUE)
  • BlueprintSha nvarchar(128) NOT NULL
  • PatchSha nvarchar(128) NOT NULL
  • StatusId int (FK → LibraryGenerationStatusLkp) NOT NULL
  • CreatedUtc datetimeoffset(7) NOT NULL (default sysutcdatetime())
  • UpdatedUtc datetimeoffset(7) NOT NULL (default sysutcdatetime())
  • CompletedUtc datetimeoffset(7) NULL
  • LastError nvarchar(max) NULL
  • RowVersion rowversion (for optimistic concurrency)

Flattened owned components

  • Workspace: WorkspaceRoot nvarchar(512) NULL, WorkspaceScratch nvarchar(512) NULL
  • Quality: QualityStatusId int (FK → QualityStatusLkp) NOT NULL, CoveragePercent decimal(5,2) NULL, QualityReportUrl nvarchar(2048) NULL
  • GitOutcome: SourceControlProviderId int (FK → SourceControlProviderLkp) NOT NULL, RepoFullName nvarchar(256) NULL, BranchName nvarchar(128) NULL, CommitId nvarchar(64) NULL, PatchFingerprint nvarchar(128) NULL
  • PullRequest: PullRequestStateId int (FK → PullRequestStateLkp) NOT NULL, PrNumber int NULL, PrUrl nvarchar(2048) NULL

LibraryGenerationStatusLkp(Id int PK, Code nvarchar(32) UNIQUE, Name nvarchar(64), IsActive bit) QualityStatusLkp(Id int PK, Code nvarchar(32) UNIQUE, Name nvarchar(64), IsActive bit) PullRequestStateLkp(Id int PK, Code nvarchar(32) UNIQUE, Name nvarchar(64), IsActive bit) SourceControlProviderLkp(Id int PK, Code nvarchar(32) UNIQUE, Name nvarchar(64), IsActive bit)

  • Indices

    • UX_LibraryGenerations_CorrelationId (unique)
    • IX_LibraryGenerations_StatusId_CreatedUtc
    • IX_LibraryGenerations_Repo_Branch on (RepoFullName,BranchName)
  • Migrations

    • FluentMigrator versioned migrations with Up/Down for schema, FKs, defaults, and seed rows for lookup tables.
    • Auto-run on startup (dev/CI) gated by config (ApplyMigrationsOnStartup = true).
  • NHibernate mapping-by-code

    • LibraryGenerationMap (ClassMapping<T>), version mapping to SQL Server rowversion.
    • Enum/rich-enumeration handling via FK to Lkp tables.
    • Converters for common VOs (e.g., RepoFullName, BranchName, BlueprintSha) as strings with length constraints.
  • Repository + Specification

    • ILibraryGenerationRepository with aggregate-centric methods (GetByIdAsync, AddAsync, UpdateAsync, DeleteAsync, FindAsync(ISpecification<LibraryGeneration>) its come from infrastructure).
    • NHibernate implementation translating Specifications to LINQ/Criteria.
  • Integration tests (local SQL Server)

    • Use LocalDB (Windows) or developer SQL Server instance.
    • Connection string provided via BLGA__Tests__SqlServer__ConnectionString (env var or appsettings config).
    • Tests cover: migrations up/down, CRUD round-trip, optimistic concurrency (stale update throws), index usage smoke on common queries.

Dependencies

  • Domain model from [BLGA-FEAT-02] (aggregate/VOs/enumerations).
  • CI from [BLGA-FEAT-01] (pipeline on master) — consider a Windows agent for LocalDB.

Tasks

[BLGA-TASK-03.1] End-to-End — Relational schema (UTC datetimeoffset, nvarchar, lookups) + FluentMigrator + migrations + ERD in docs

Intent Design the SQL Server schema and ship versioned migrations with deterministic migrations data for all lookup tables; capture an ERD for documentation.

Steps

  1. Author migrations for LibraryGenerations + all lookup tables, FKs, defaults (sysutcdatetime()), unique/covering indices, and rowversion.
  2. Add seed rows for each Lkp table (Codes consistent with Domain enumerations).
  3. Implement a small migration host/wrapper to auto-apply migrations on startup when enabled.
  4. Generate ERD (Mermaid/PlantUML) and add to docs/erd/ with a short rationale for flattened components.

Artifacts

  • …DatabaseModel.Migrations with Up/Down code and a Migration1(*).cs.
  • ERD diagram + brief narrative.

Acceptance Criteria

  • Fresh database migrates up/down cleanly; lookup codes seeded.
  • Unique and FK constraints enforce domain invariants; indices exist.
  • ERD renders in docs pipeline artifact.

[BLGA-TASK-03.2] End-to-End — NHibernate mapping-by-code; mapping of lookups; local SQL Server integration tests

Intent Map the aggregate to the physical schema using mapping classes and validate it against local SQL Server (no Testcontainers/SQLite).

Steps

  1. Implement LibraryGenerationMap with:
    • Id(x => x.Id, m => m.Generator(Generators.GuidComb))
    • Version(x => x.RowVersion, m => { m.Type(NHibernateUtil.Timestamp); m.Generated(VersionGeneration.Never); }) (mapped to rowversion)
    • Components or simple properties for flattened members with proper lengths/nullability
    • Many-to-one to Lkp tables for enumeration properties
  2. Build a small SessionFactory bootstrap for tests (reads connection string from env/runsettings).
  3. Write integration tests:
    • Apply migrations → open Session → CRUD round-trip
    • Concurrency: read entity twice, update both, verify stale update raises
    • Verify mapped lengths (e.g., truncation guarded by validation)

Artifacts

  • Mapping classes in …PersistenceModel.NHibernate
  • Passing integration tests on a local SQL Server

Acceptance Criteria

  • Round-trip CRUD passes; stale update fails with concurrency exception.
  • Mappings align with migration column definitions (lengths, nullability).

[BLGA-TASK-03.3] End-to-End — Repository APIs + optimistic concurrency (rowversion) + indices; perf smoke

Intent Provide a slim, aggregate-centric Repository that composes with Specifications; verify basic performance characteristics on common access paths.

Repository

  • ILibraryGenerationRepository: GetByIdAsync, AddAsync, UpdateAsync, DeleteAsync, FindAsync(ISpecification<LibraryGeneration>).
  • NHibernate implementation applies Specifications via Criteria/LINQ; no IQueryable leakage.

Indices & Perf

  • Verify the hot path queries use indices (StatusId + CreatedUtc, CorrelationId).
  • Perf smoke: create ~1,000 rows, query recent by status, P95 within an agreed budget on a developer machine.
  • Add minimal DB hints/covering indexes only if necessary (document rationale).

Acceptance Criteria

  • Repository API reviewed and approved (aggregate-centric, persistence-ignorant domain).
  • Optimistic concurrency enforced on UpdateAsync.
  • Perf smoke completes within the agreed local budget and documents observations.

Governance & Policy Hooks

  • Persistence ignorance: Domain remains free of ORM attributes/types.
  • Naming conventions: Tables PascalCase plural, columns PascalCase; UTC time via datetimeoffset.
  • Safety: Migrations are idempotent; destructive changes require explicit Down review.
  • CI/PR: Pipeline runs migrations against a scratch DB when enabled; integration tests target local SQL Server on Windows agents (or are opt-in via variable).

Acceptance (Feature)

  • Migrations apply cleanly; lookup seeds present; ERD committed.
  • NHibernate maps validate against local SQL Server; CRUD round-trip succeeds; rowversion concurrency works.
  • Repository + Specification path is proven; indices assist hot paths; perf smoke documented.
  • CI on PR to master remains green, and artifacts (ERD, migration logs) are published.

[BLGA-FEAT-04] Contracts — Bus, gRPC (C#), MCP

Establish versioned service contracts (gRPC), durable bus contracts (commands/events) with correlation, and MCP tools so external agents can start a generation and read its status. Follow the template’s code-first service model, naming rules, and transport-agnostic MassTransit setup.


[BLGA-TASK-04.1] End-to-End: Service model + gRPC DTOs (StartGeneration, GetRunStatus) with versioned namespaces; host + sample client

Deliverables

  • Service contract (code-first, C#): ConnectSoft.Factory.BackendLibraryGeneratorAgent.ServiceModel.ILibraryGenerationService with:
    • StartGeneration(StartGenerationRequest) → StartGenerationResponse
    • GetRunStatus(GetRunStatusRequest) → GetRunStatusResponse Names use the Request/Response pattern per the template’s Service Model rules. Namespace: ConnectSoft.Factory.BackendLibraryGeneratorAgent.ServiceModel.v1 (reserve v2 later). Faults: use standard fault contracts mapped by the template’s gRPC guidance (validation, not found, conflict, etc.).
  • DTOs: request/response records for both operations (CorrelationId, BlueprintSnapshotId, optional PatchSha; and Status, CurrentStep, Errors[]).
  • gRPC implementation: ConnectSoft.Factory.BackendLibraryGeneratorAgent.ServiceModel.Grpc.GrpcLibraryGenerationService implements the interface and delegates to Application layer. Keep it code-first as in the template (no .proto in this project).
  • Hosting & wiring: register the service in the API host; enable gRPC health checks per template.
  • Sample client: a console app validating both calls against the local dev host using GrpcChannel (mirrors the template’s acceptance test approach).
  • Docs: “Service Model (v1)” page describing operations, DTOs, faults, and versioning guidelines.

Projects & Folders

  • ConnectSoft.Factory.BackendLibraryGeneratorAgent.ServiceModel
  • ConnectSoft.Factory.BackendLibraryGeneratorAgent.ServiceModel.Grpc (Structure mirrors the template’s ServiceModel projects.)

Acceptance

  • Local e2e: StartGeneration returns an accepted CorrelationId; GetRunStatus transitions from PendingRunning (fake)→Completed.
  • Health endpoint green; sample client prints responses for both operations.
  • Contracts follow naming conventions (Request/Response).

Notes

  • Use versioned namespaces now to avoid breaking changes later.
  • Keep DTOs flat and binary-friendly; prefer primitives/strings over nested types.

[BLGA-TASK-04.2] End-to-End: MassTransit commands/events (Start/Prepare/RunTemplate/RunQuality/Push/OpenPR) + correlation

Deliverables

  • Messaging contracts in ConnectSoft.Factory.BackendLibraryGeneratorAgent.MessagingModel (pure POCOs):
    • Commands: StartLibraryGenerationCommand, PrepareWorkspaceCommand, RunTemplateCommand, RunQualityCommand, PushChangesCommand, OpenPullRequestCommand.
    • Events: LibraryGenerationStartedEvent, WorkspacePreparedEvent, TemplateRenderedEvent, QualityCompletedEvent, ChangesPushedEvent, PullRequestOpenedEvent. Use Command/Event suffixes per messaging naming rules.
  • Correlation: every message includes Guid CorrelationId; set global correlation mapping. (MassTransit supports correlation; configure by convention.)
  • Bus wiring: register the bus per template with transport from configuration (RabbitMQ by default; ASB/SQL supported by parameters).
  • Consumers (skeletons): one consumer per command that raises the next event; no saga state here (orchestration comes later).
  • Integration smoke: publish StartLibraryGenerationCommand → observe ordered events via logs and test harness.

Projects & Folders

  • ConnectSoft.Factory.BackendLibraryGeneratorAgent.MessagingModel (contracts)
  • ConnectSoft.Factory.BackendLibraryGeneratorAgent.FlowModel.MassTransit (consumers & bus registration) (Aligned to template’s Flow/Messaging model layout.)

Acceptance

  • Bus starts successfully with configured transport; consumers receive commands; events published in sequence.
  • CorrelationId preserved across all messages (asserted in test).
  • Contracts pass analyzers and follow naming rules.

Notes

  • Do not introduce Outbox/Audit here (provided elsewhere in platform).
  • Keep contracts backward compatible; add fields with defaults, never remove/rename in v1.

[BLGA-TASK-04.3] End-to-End: MCP tools library.start_generation, library.get_status; CLI/agent harness

Deliverables

  • MCP server tools project: ConnectSoft.Factory.BackendLibraryGeneratorAgent.ModelContextProtocol.
    • Class marked with [McpServerToolType] and each tool with [McpServerTool], following the template’s MCP pattern.
    • library.start_generation(text blueprintRef, bool dryRun=false) → invokes gRPC StartGeneration.
    • library.get_status(string correlationId) → invokes gRPC GetRunStatus.
    • Optional: expose a prompt provider like the template’s StringFormatPrompt pattern for templated PR titles/bodies (future).
  • CLI/agent harness: minimal console that calls the MCP tools to prove discovery & execution.
  • Docs: “MCP Tools” reference with examples and JSON schemas for inputs/outputs.

Projects & Folders

  • ConnectSoft.Factory.BackendLibraryGeneratorAgent.ModelContextProtocol (tools & prompts)

Acceptance

  • MCP runtime lists both tools; calling them results in successful gRPC round-trips and printed outputs.
  • Tool metadata (names, descriptions) visible via discovery; arguments validated.

Notes

  • Keep tool inputs minimal; offload validation to service model (consistent error mapping via gRPC faults).

[BLGA-FEAT-05] Orchestration — Saga & Policies

Implement the end-to-end orchestration of a LibraryGeneration run using a MassTransit state machine (saga) with strict correlation and deterministic idempotency. Persist saga state, model success/failure transitions, and encode cross-cutting operational policies (timeouts, retries, redelivery, escalation). The design follows the template’s MassTransit state machine approach, event correlation, and fault/compensation patterns.


[BLGA-TASK-05.1] End-to-End: Saga state machine (Pending → WorkspaceReady → TemplateRendered → QualityEvaluated → ChangesPushed → PullRequestOpened → Completed / Failed), idempotency via CorrelationId + Blueprint/Patch SHAs

Deliverables

  • Saga & state (Flow layer):
    • ConnectSoft.Factory.BackendLibraryGeneratorAgent.FlowModel.MassTransit.LibraryGenerationLifeCycleSaga
    • ConnectSoft.Factory.BackendLibraryGeneratorAgent.FlowModel.MassTransit.LibraryGenerationLifeCycleSagaState Define states and transitions using the template’s MassTransit state machine pattern (InstanceState, event definitions, transitions).
  • Correlation & idempotency:
    • Correlate every command/event by CorrelationId and business IDs (e.g., LibraryGenerationId), inserting on initial and factory-creating state as in the template’s example.
    • Store BlueprintSha and PatchSha in saga state; ignore duplicates where both SHAs match the stored pair (deterministic run).
    • Preserve timestamps: StartedAt, LastTransitionAt. (Template shows timestamp capture on transition.)
  • Persistence:
    • Persist saga state via MassTransit NHibernate mapping (SQL Server), following the template’s SagaClassMapping example (nullable/length/unique) and optimistic concurrency version.
    • Optinal saga state via MongoDB**.
  • Contracts & naming: Use existing commands/events from FEAT-04; ensure names follow Command/Event suffix conventions.
  • Policies (built-in to orchestration):
    • Retries & delayed redelivery on transient steps (workspace prep, quality) at the bus level.
    • Timeouts per step (e.g., template render 5m, quality 20m).
    • Idempotent transitions: if an event for a completed step replays, the handler no-ops.
  • Docs: “LibraryGeneration Saga v1” diagram + table of states, events, commands, timeouts, and retry rules.

Transitions (representative)

  • Pending —(PrepareWorkspaceCommand → WorkspacePreparedEvent)→ WorkspaceReady
  • WorkspaceReady —(RunTemplateCommand → TemplateRenderedEvent)→ TemplateRendered
  • TemplateRendered —(RunQualityCommand → QualityCompletedEvent[Passed/Failed])→ QualityEvaluated
  • QualityEvaluated —(PushChangesCommand → ChangesPushedEvent)→ ChangesPushed
  • ChangesPushed —(OpenPullRequestCommand → PullRequestOpenedEvent)→ PullRequestOpened
  • PullRequestOpenedCompleted

Implementation mirrors the template’s pattern for event correlation and transitions.

Projects & Folders

  • ConnectSoft.Factory.BackendLibraryGeneratorAgent.FlowModel.MassTransit (saga + mappings)
  • ConnectSoft.Factory.BackendLibraryGeneratorAgent.MessagingModel (contracts already defined in FEAT-04; reused)

Acceptance

  • Starting from StartLibraryGenerationCommand, the saga creates state, timestamps StartedAt, and advances through all states on the happy path.
  • Duplicate (CorrelationId, BlueprintSha, PatchSha) publish results in no additional transitions (idempotent).
  • NHibernate mapping compiles and persists state to SQL Server (CurrentState not null; ObjectId unique; Version present).

Notes

  • Follow naming rules for commands/events and keep saga logic orchestration-only (no domain mutations inside the saga).

[BLGA-TASK-05.2] End-to-End: Five failure scenarios (template error, coverage fail, push rejected, PR rate-limit, delivery delay) with compensations; E2E harness

Deliverables

  • Fault & compensation wiring: Handle Fault<T> for every step event/command; transition to Failed with structured logging and compensations, following the template’s DuringAny(When(Fault<T>)) → … → FaultedState pattern.
  • Scenarios & compensations
    1. Template render error → mark TemplateError, add saga note, post failure status (no workspace deletion yet).
    2. Quality gate failed (coverage below gate) → label “quality-failed”, attach report link, remain resumable (manual override allowed later).
    3. Git push rejected (non-fast-forward / permission) → retry with backoff; if still failing, label and stop at ChangesPushFailed.
    4. PR rate-limited → delayed redelivery; if max exceeded, emit status + label “pr-rate-limited”.
    5. Delivery delay (e.g., platform outbox/broker lag) → rely on retry + delayed redelivery; if execution window exceeded, surface timeout to status and halt.
  • Policies:
    • Configure retry + delayed redelivery per step; timeouts mapped to states; all failures produce a single terminal Failed (or resumable) outcome with correlation logging.
  • Observability hooks: Structured logs around transitions and faults (BeginScope with IDs) as in the template’s saga processing methods.
  • E2E harness:
    • In-memory bus tests assert: message published, consumed, saga created, state transitions, and Fault<T> handling per scenario (MassTransit test harness).
    • Include happy path and the five negative paths with assertions on final state and emitted labels/notes.

Projects & Folders

  • ConnectSoft.Factory.BackendLibraryGeneratorAgent.FlowModel.MassTransit (fault handlers, compensation transitions)
  • ConnectSoft.Factory.BackendLibraryGeneratorAgent.AcceptanceTests (harness tests)

Acceptance

  • Each of the five scenarios triggers expected Fault handling and transitions to Failed (or a named failed sub-state) with logged exception details and retained correlation metadata.
  • Harness verifies Published/Consumed and ContainsInState for both success and failure paths.

Notes

  • “Delivery delay” refers to platform-level dispatch lag (e.g., outbox/broker). The microservice does not implement its own outbox tables; it only reacts using retries/redelivery and fault policies. (Keep saga state small/serializable and correlate by business IDs.)

[BLGA-FEAT-06] Ports & Adapters (MCP FS/Git, ADO PR, Quality, AI)

Outcome: Introduce one new project per port (strict separation) and dedicated adapter projects that implement them. Each adapter ships with a Fake for E2E tests. File/Git operations are allow-listed, patch fingerprints are deterministic, PR operations are provider-safe, and quality/AI services have reproducible fallbacks. All names follow the solution structure; the solution remains ConnectSoft.Factory.BackendLibraryGeneratorAgent.

New projects (added to the solution):

  • Ports (interfaces & contracts)
    • ConnectSoft.Factory.BackendLibraryGeneratorAgent.Ports.McpFilesystem
    • ConnectSoft.Factory.BackendLibraryGeneratorAgent.Ports.McpGit
    • ConnectSoft.Factory.BackendLibraryGeneratorAgent.Ports.AdoPullRequests
    • ConnectSoft.Factory.BackendLibraryGeneratorAgent.Ports.QualityRunner
    • ConnectSoft.Factory.BackendLibraryGeneratorAgent.Ports.AiServices
  • Adapters (implementations)
    • ConnectSoft.Factory.BackendLibraryGeneratorAgent.Adapters.McpFilesystem
    • ConnectSoft.Factory.BackendLibraryGeneratorAgent.Adapters.McpGit
    • ConnectSoft.Factory.BackendLibraryGeneratorAgent.Adapters.AdoPullRequests
    • ConnectSoft.Factory.BackendLibraryGeneratorAgent.Adapters.QualityRunner
    • ConnectSoft.Factory.BackendLibraryGeneratorAgent.Adapters.AiServices
  • Fakes (test doubles)
    • ConnectSoft.Factory.BackendLibraryGeneratorAgent.Adapters.Fakes.McpFilesystem
    • ConnectSoft.Factory.BackendLibraryGeneratorAgent.Adapters.Fakes.McpGit
    • ConnectSoft.Factory.BackendLibraryGeneratorAgent.Adapters.Fakes.AdoPullRequests
    • ConnectSoft.Factory.BackendLibraryGeneratorAgent.Adapters.Fakes.QualityRunner
    • ConnectSoft.Factory.BackendLibraryGeneratorAgent.Adapters.Fakes.AiServices

All adapters expose IOptions<>-backed configuration, honor master branch naming, and log CorrelationId on every call. Secrets are not embedded; token retrieval is abstracted (Key Vault wiring lands in Security feature).


[BLGA-TASK-06.1] End-to-End — IMcpFilesystem + IMcpGit adapters (allow-lists; patch SHA); fakes; workspace lifecycle + deterministic patch tests

Intent Provide a secure workspace layer and Git seam for the orchestrator. Guarantee that the same inputs produce the same patch fingerprint; ensure only allow-listed files/paths are read/written.

Deliverables

  • Ports

    • IMcpFilesystem (Ports.McpFilesystem):

    public interface IMcpFilesystem {
      Task<WorkspaceInfo> CreateWorkspaceAsync(WorkspaceRequest req, CancellationToken ct);
      Task<IReadOnlyList<VfsChange>> ApplyChangesAsync(WorkspaceId id, IEnumerable<VfsOp> ops, CancellationToken ct);
      Task<UnifiedDiff> DiffAsync(WorkspaceId id, DiffScope scope, CancellationToken ct);
      Task<PatchFingerprint> ComputePatchFingerprintAsync(UnifiedDiff diff, CancellationToken ct);
      Task<bool> ExistsAsync(WorkspaceId id, VfsPath path, CancellationToken ct);
      Task DeleteWorkspaceAsync(WorkspaceId id, CancellationToken ct);
    }
    
    * Allow-lists: root, subpaths, glob patterns; deny by default. * Normalization: line endings, file ordering, and path casing normalized before diff/fingerprint. * IMcpGit (Ports.McpGit): clone/shallow fetch, checkout/create branch (deterministic naming), apply diff, commit, push, return CommitId. * Adapters * Filesystem adapter (Adapters.McpFilesystem): operates under a temp workspace root with TTL tags, honors allow-lists, and emits UnifiedDiff. * Git adapter (Adapters.McpGit): supports ADO Git; accepts an ITokenCredentialProvider abstraction (later bound to Key Vault/MI). Computes PatchFingerprint as SHA256 over normalized diff bytes. * Fakes * In-memory FS & Git fakes that simulate diff/apply/commit/push (no network). * Workspace lifecycle * Create → Apply → Diff → Fingerprint → (later) Apply in repo; cleanup on completion or when TTL expires (cleanup job later).

Tests

  • Determinism: multiple Apply+Diff cycles over the same logical changes yield the same PatchFingerprint.
  • Allow-lists: attempts to read/write outside allow-listed paths fail with security error.
  • Branch naming: feature/blga/{CorrelationId|short}/{PatchFingerprintShort} is stable (document exact pattern to match repo rules).

Artifacts

  • Ports, adapters, fakes projects with compiling code and XML docs.
  • Test suite under …Tests.Unit & …Tests.Integration (local file system & a personal ADO sandbox optional).

Acceptance Criteria

  • ComputePatchFingerprintAsync is order-insensitive and newline-stable.
  • Disallowed paths are blocked; workspace cleanup leaves no residue.
  • Pushing via Git adapter (against a sandbox) produces a commit with the expected message/branch pattern (optional live smoke).

[BLGA-TASK-06.2] End-to-End — IAdoPullRequests (create PR, comment, label, status checks) via Key Vault; fakes

Intent Isolate Azure DevOps PR operations behind a dedicated port; provide a production adapter that uses token credentials abstracted (Key Vault/Managed Identity wired in the Security feature), plus a Fake for tests.

Deliverables

  • Port

    • IAdoPullRequests (Ports.AdoPullRequests):

    public interface IAdoPullRequests {
      Task<PullRequestId> CreateAsync(RepoRef repo, BranchName source, BranchName target, PrTitle title, PrDescription body, CancellationToken ct);
      Task AddCommentAsync(PullRequestId pr, PrComment comment, CancellationToken ct);
      Task AddLabelsAsync(PullRequestId pr, IEnumerable<PrLabel> labels, CancellationToken ct);
      Task SetStatusCheckAsync(PullRequestId pr, PrStatusCheck check, CancellationToken ct);
      Task<PrDetails> GetAsync(PullRequestId pr, CancellationToken ct);
    }
    
    * Contracts use VOs from Domain/ServiceModel (e.g., RepoRef, BranchName). * Adapter

    • Adapters.AdoPullRequests implementing the ADO REST APIs:
      • Create PR (source→target master by default), assign reviewers (optional), attach labels, and post an initial status check (quality/pending).
      • Credential source: ITokenCredentialProvider abstraction (no secrets in code).
      • Robust error mapping (rate limit → retryable; validation → non-retryable).
    • Fake
    • Adapters.Fakes.AdoPullRequests stores PRs in memory; returns deterministic PullRequestIds; supports comment/label/status calls.

Tests

  • PR create/comment/label/status flows with the Fake.
  • Optional live smoke against a dev project (if credentials present via env).

Acceptance Criteria

  • PR creation returns a valid ID; subsequent operations reflect in GetAsync.
  • Status checks are idempotent; adding an existing label does not duplicate.
  • No adapter method leaks token/secret to logs; every call logs CorrelationId.

[BLGA-TASK-06.3] End-to-End — IQualityRunner (build/test/coverage) + containerized mode; IAiServices (commit/PR body/docs) with deterministic fallbacks

Intent Standardize quality execution and AI-assisted text generation behind ports. Provide a local runner for build/test/coverage and a containerized mode for hermetic runs. Ensure AI outputs are deterministic when AI is unavailable (or disabled) to keep pipelines reproducible.

Deliverables

  • Ports

    • IQualityRunner (Ports.QualityRunner):
    public interface IQualityRunner {
      Task<QualityResult> RunAsync(QualityRequest request, CancellationToken ct);
    }
    
    * `QualityRequest`: repo/workspace path, test categories, coverage profile, optional container image reference.
    * `QualityResult`: `CoveragePercent`, `ReportPath/Url`, `Passed`, diagnostics.
    
    • IAiServices (Ports.AiServices):

    public interface IAiServices {
      Task<CommitMessage> GenerateCommitMessageAsync(GenerationContext ctx, CancellationToken ct);
      Task<PrBody> GeneratePullRequestBodyAsync(GenerationContext ctx, CancellationToken ct);
      Task<DocSection> GenerateDocsSectionAsync(GenerationContext ctx, CancellationToken ct);
    }
    
    * Adapters * Adapters.QualityRunner: * Local mode: invokes dotnet build/test with coverage (Cobertura), parses results, returns QualityResult. * Container mode: executes the same via docker (image from config); collects artifacts to a known folder. * Emits a status check payload contract that FEAT-04 can post to the PR. * Adapters.AiServices: * Primary path can call configured AI (wired later). * Deterministic fallback: template-driven (string.Format/mustache) with fixed sections, producing reproducible outputs for commit message and PR body (e.g., includes PatchFingerprintShort and top-N changed paths). * Fakes * Adapters.Fakes.QualityRunner always yields a fixed CoveragePercent (configurable) and produces a small synthetic report file. * Adapters.Fakes.AiServices returns constant, test-friendly strings.

Tests

  • Run IQualityRunner locally on a sample workspace; verify CoveragePercent extraction and Passed flag against the gate.
  • Verify fallback outputs are byte-for-byte stable for a given GenerationContext.
  • Contract tests for all adapters (ports satisfied; no throw on valid inputs).

Acceptance Criteria

  • Quality runs succeed locally; containerized mode optional behind config.
  • Fallback PR body includes the exact, deterministic sections and references (e.g., correlation, patch fingerprint, changed projects).
  • No secrets in logs; all calls include CorrelationId and emit structured telemetry.

Governance & Policy Hooks

  • Security: allow-listed FS paths only; no secrets in adapter code; credentials injected via ITokenCredentialProvider (Key Vault/MI wired in Security feature).
  • Determinism: patch fingerprints and AI fallbacks are stable across runs.
  • Observability: adapters emit structured logs and OTel spans; all operations tag CorrelationId.
  • CI: unit/integration tests run on PR to master; failures block merge.

Dependencies

  • Domain/VOs from FEAT-02, Persistence from FEAT-03, Contracts from FEAT-04.
  • Saga from FEAT-05 will call these ports to enact steps.

Acceptance (Feature)

  • All Ports and Adapters projects compile and are referenced from the Host/Flow as appropriate.
  • E2E happy-path (with Fakes) performs: workspace create → changes apply → fingerprint → commit/push → PR create → quality run → AI commit/PR text generation.
  • Deterministic tests for patch fingerprint and AI fallback pass; PR and Quality ports exhibit idempotent behavior.

[BLGA-FEAT-07] Domain Services (Reusable Core Behaviors)

Stateless business logic that doesn’t belong to a single entity/aggregate, exposed via interfaces in DomainModel and implemented in DomainModel.Impl, so the same services can be invoked from Saga, Jobs, gRPC handlers, or CLI harnesses. In LGA, Domain Services remain pure domain code (no infra), follow naming conventions, and are validated with FluentValidation where useful.


[BLGA-TASK-07.1] End-to-End — Introduce LGA Domain Services (Contracts, Impl, DI, Tests)

Intent Provide a reusable set of domain-level operations for generation runs: branch naming, commit text, PR content, idempotency checks, policy evaluation, patch fingerprinting, and status projection — all stateless and infrastructure-free.

Projects & Namespaces

  • ConnectSoft.Factory.BackendLibraryGeneratorAgent.DomainModel — define service interfaces (e.g., IBranchNamingService, ICommitMessageService, IPrDescriptionService, IIdempotencyService, IPolicyEvaluationService, IPatchFingerprintService, IRunStatusProjectionService).
  • ConnectSoft.Factory.BackendLibraryGeneratorAgent.DomainModel.Implimplementations (stateless classes) + validators where needed; follow VerbNounService naming (e.g., BuildBranchNameService).
  • ConnectSoft.Factory.BackendLibraryGeneratorAgent.UnitTests — focused unit tests.

What’s inside (examples)

  • IBranchNamingService → deterministic branch names: feature/lga/{blueprintId}/{blueprintVersion}/{correlationShort}.
  • ICommitMessageService → conventional commits for library generation (feat(libgen): …).
  • IPrDescriptionService → stable markdown body (sections: Summary, Inputs, Diff Highlights, Quality Summary).
  • IIdempotencyService → compute an idempotency key from {BlueprintSnapshotSHA, PatchSHA, InputsHash} and compare.
  • IPolicyEvaluationService → map DSL/blueprint policy to internal QualityGate VOs (coverage floor, test pass required, allowlists).
  • IPatchFingerprintService → deterministic SHA-256 over ordered path list + content hash.
  • IRunStatusProjectionService → reduce events/states → LibraryGenerationStatus VO.

Steps

  1. Add interfaces in DomainModel; implement in DomainModel.Impl as stateless services; register via ApplicationModel DI extension method AddDomainServices() (single place).
  2. Apply naming guidance (PascalCase, domain contract naming for inputs/outputs where used).
  3. Add validators for service inputs (FluentValidation, fail-fast config respected).
  4. Author unit tests for each service covering positive/negative and determinism paths.

Artifacts

  • Compiling solution with DI extension and service classes.
  • docs/domain-services.md summarizing contracts, invariants, and examples.
  • Unit tests covering each service (~90%+ lines for DomainModel.Impl services).

Acceptance Criteria

  • Services are pure domain (no bus, no DB, no HTTP).
  • Repeated calls with same inputs yield identical outputs (determinism).
  • DI exposes all services to Application/Saga layers.

[BLGA-TASK-07.2] End-to-End — Determinism & Idempotency (Keys, Fingerprints, Policies)

Intent Guarantee that repeated “Start Generation” with the same blueprint & patch does not duplicate work and always produces identical branch/commit/PR text artifacts.

Design

  • Idempotency Key: IdemKey = SHA256(BlueprintSnapshotSHA + PatchSHA + InputsHash) computed by IIdempotencyService.
  • Patch Fingerprint: IPatchFingerprintService orders paths lexicographically, normalizes line endings, hashes content → PatchSHA.
  • Branch Naming: IBranchNamingService derives a stable path from {blueprintId, blueprintVersion, correlationId} (no time components).
  • Validation: Fail-fast for missing/invalid inputs via FluentValidation (class-level and rule-level cascade).

Steps

  1. Implement fingerprint & idempotency logic with VOs (IdempotencyKey, PatchFingerprint).
  2. Extend validators for inputs (e.g., non-empty blueprint id/version; correlation format).
  3. Unit tests: same inputs → same outputs; single-field change → different key; mixed-order files → same fingerprint.
  4. Wire IRunStatusProjectionService that reduces domain events/states into a stable LibraryGenerationStatus snapshot (no infra).

Artifacts

  • VOs + services with exhaustive tests.
  • Examples in docs/idempotency-and-determinism.md.

Acceptance Criteria

  • Idempotency key equality gates orchestrations in Saga/Application (consumers only use the service).
  • All determinism tests pass on CI and block merge to master on failure.

[BLGA-TASK-07.3] End-to-End — Policy Evaluation & Orchestration Helpers (Pure Domain)

Intent Translate Blueprint/DSL policy into actionable, domain-level decisions and a Run Plan that Saga/Jobs can follow without duplicating business rules.

Design

  • IPolicyEvaluationService maps blueprint’s quality/review policy → QualityGate/BranchPolicy VOs.
  • IRunPlanBuilder (interface + impl) returns a pure domain plan: Prepare → Render → Quality → Push → OpenPR with decision points (e.g., “fail on coverage < gate”).
  • Inputs/Outputs follow Domain Model contract naming for clarity (EvaluatePolicyInput/Output, etc.).
  • Specifications remain in PersistenceModel (when querying is required), but rules stay explicit in domain.

Steps

  1. Define VOs (QualityGate, BranchPolicy, RunStep, RunPlan) + interfaces in DomainModel; implement in DomainModel.Impl.
  2. Implement RunPlanBuilder to assemble a plan from policy + inputs (no IO).
  3. Add validators for policy inputs; unit tests for policy edge cases (e.g., coverage unset → default gate).
  4. Publish samples in docs/run-plans.md showing how Saga consumes the plan.

Artifacts

  • Policy evaluators, plan builder, tests, and docs.
  • Example RunPlan JSONs committed under samples/.

Acceptance Criteria

  • Saga can consume RunPlan/QualityGate without additional mapping.
  • Changing policy in blueprint affects only domain outputs; no infra changes necessary.

Definition of Done (feature)

  • All domain services are stateless, deterministic, and fully unit-tested; inputs/outputs named per conventions.
  • Validators enforce correctness; fail-fast behavior is configurable and honored.
  • Saga/Jobs/gRPC can import these services via DI without additional wiring.
  • Documentation added under docs/ with examples and invariants.

[BLGA-FEAT-08] DSL & Blueprint Integration + Template Renderer

Goal: Wire the Backend Library Blueprint + DSL control-plane into the agent, then render a complete .NET library (code, tests, docs, CI) deterministically from the validated inputs. Blueprints are the execution contract; DSLs are reusable fragments referenced by the blueprint.


[BLGA-TASK-08.1] End-to-End: Blueprint/DSL schema + validation (intent, triggers, ports, policies, allow-lists)

  • Implement ingestion + validation for Backend Library Blueprints and referenced DSLs:
    • Load blueprints/libraries/**/library-blueprint.yaml (+ options.yaml, features.md, overview.md, use-cases.md, runbook.md) into the Application layer validator pipeline.
    • Enforce schema + semantic rules for DSLs (DDD, Event, Pipeline, Adapter, Test) using centrally versioned JSON Schemas; block execution when invalid and emit structured errors/events.
    • Require $meta (e.g., dslType, dslRef, context, traceId, status) for routability/observability and cross-file linking from the blueprint.
    • Normalize multi-TFM targets, DI/logging/options toggles, and CI metadata from the blueprint so downstream renderers are deterministic.
  • Emit validation lifecycle events (DslValidated, DslValidationFailed) and block saga orchestration until success; record metrics (latency, failures) via OpenTelemetry.
  • Persist the validated snapshot (Blueprint + DSL refs) under LibraryGeneration.BlueprintSnapshot and attach to CorrelationId.
  • Acceptance: invalid inputs are rejected with precise diagnostics; valid inputs produce a normalized, versioned snapshot used by the renderer; events + metrics visible in Studio/trace views.

[BLGA-TASK-08.2] End-to-End: Template Renderer — .csproj (multi-TFM), README, pipeline YAML, tests; dry-run with diff/patch artifacts

  • Build a deterministic renderer that transforms a validated blueprint (+ linked DSLs) into a full library scaffold:
    • Projects & code: generate library project + DI extensions + options class exactly as specified; include MSTest test project.
    • Multi-TFM .csproj: inject TargetFrameworks from targets (e.g., net8.0;net9.0;netstandard2.1) and enable nullable/implicit usings.
    • Documentation: render README.md + docs/overview.md, features.md, runbook.md, use-cases.md from blueprint metadata; wire regeneration hooks.
    • CI pipeline: generate azure-pipelines.yml from ci metadata with build/test/pack/publish stages and coverage; set trigger to master (override default).
    • Output layout: src/ConnectSoft.MyLibrary/**, tests/ConnectSoft.MyLibrary.Tests/**, docs/**; all artifacts are traceable to their blueprint sections.
  • Provide a dry-run mode that renders to a workspace and emits diff/patch artifacts + content hash (renderer seed + blueprint version) for determinism.
  • Acceptance: running the renderer on the same snapshot yields identical hashes; the generated solution builds and tests locally and in CI across all TFMs; README/docs present DI usage and options exactly as modeled.

[BLGA-TASK-08.3] End-to-End: Policy mapping (coverage gates, reviewers, branch naming); deterministic output checks

  • Map policy fields from blueprint → enforcement:
    • Coverage thresholds & test execution → pipeline conditions/gates and success criteria.
    • Quality/observability/security toggles → template switches, analyzers, and doc sections (e.g., logging, spans, exception handling).
    • Branch & PR policy: branch naming feature/library-{shortsha}; open PR to master; attach trace metadata to PR body; add status checks aligned with blueprint CI stages.
  • Deterministic checks: golden-files tests against known blueprints; per-file content hashing; drift detection that proposes regeneration (docs/CI) when outputs diverge.
  • Acceptance: pipeline enforces coverage ≥ blueprint threshold; PRs show traceable provenance (dslRef/blueprintId/traceId); drift signals trigger remediation; NuGet packing/publish occurs only when all gates pass.

Notes

  • Separation of concerns: DSLs define what; renderer + recipes decide how; memories/docs carry why—kept explicit in the flow.
  • Factory compliance: blueprint → artifacts (code, tests, CI, docs, NuGet) is a single, traceable chain suitable for replay and audit.

Done when: Valid blueprint + DSLs produce a reproducible patch that, when applied, yields a compiling, multi-TFM library with passing tests, generated docs, and an ADO pipeline ready to run on master with coverage gates and NuGet publishing per blueprint.


[BLGA-FEAT-09] Quality Strategy & Gates (Unit, Integration, Generation QA)

Outcome: A factory-compliant test & quality regime that (a) proves core logic with fast unit suites, (b) validates the end-to-end orchestration against fakes + local SQL Server, and © enforces generation QA on rendered libraries (build/test/coverage, validators) with results published and gated in CI. We follow the template’s testing guidance (Unit/Integration/E2E + BDD option) and wire coverage to Azure Pipelines.


[BLGA-TASK-09.1] End-to-End — Unit suites (idempotency, retries, symbol resolution, branch naming, VOs)

Intent Author fast, isolated tests that lock down deterministic behavior and invariants across VOs and domain services (branch naming, idempotency), plus policy/retry helpers. Use MSTest + FluentAssertions + Moq; follow the template’s structure and best practices.

Projects & Scope

  • ConnectSoft.Factory.BackendLibraryGeneratorAgent.UnitTests
    • Determinism/Idempotency: same inputs → same keys/fingerprints.
    • Branch naming: stable, collision-free format; reserved characters rejected.
    • VOs: strict validation & equality semantics.
    • Symbol resolution: DI/service-model wiring guards (lightweight architecture assertions).
    • Retry policies: classify transient vs. non-transient; backoff sequences unit-tested.

Acceptance

  • All unit tests run green and fast (seconds), isolated from IO, in every PR.
  • Coverage from unit+integration is computed and published in CI; gate is enforced via Cobertura summary.

[BLGA-TASK-09.2] End-to-End — Integration E2E (Start→Completed) without fakes; NH mappings/migrations tests; bus delivery

Intent Prove the happy path across the service surface and flow using fakes for Ports (FS/Git/PR/Quality/AI), local SQL Server for persistence & migrations, and in-memory bus harness for messaging publish/consume. (We do not implement a custom outbox here; only deliverability via the bus/harness is validated.)

Projects & Scope

  • ConnectSoft.Factory.BackendLibraryGeneratorAgent.AcceptanceTests
    • E2E smoke: gRPC StartGeneration → saga drives steps → Completed.
    • Persistence: apply migrations, CRUD round-trip, optimistic concurrency with local SQL Server.
    • Bus: assert published/consumed messages and correlation flow (harness assertions).
    • API face: optional TestServer gRPC client execution (request/response shape).
    • Diagnostics: structured log assertions for correlation and state transitions.

Acceptance

  • A single BDD-style or MSTest scenario executes the Start→Completed flow with (or without) fakes.
  • NHibernate mappings match schema; concurrency conflict test throws as expected.
  • Bus assertions confirm all required messages were published/consumed in order.

[BLGA-TASK-09.3] End-to-End — Generation QA on rendered outputs (build/test/coverage ≥ gate; README/YAML/.csproj validators); CI coverage publishing

Intent Treat the rendered library as an artifact under test: compile it, run its tests, compute coverage, validate docs/CI files, and enforce gates in CI.

Projects & Scope

  • ConnectSoft.Factory.BackendLibraryGeneratorAgent.AcceptanceTests.GenerationQA
    • Render & Build: produce the workspace via the Template Renderer; dotnet build/test across TFMs.
    • Coverage: compute Cobertura and publish to Azure Pipelines; enforce MinCoveragePct.
    • Validators:
      • README.md contains required sections and DI/Options snippets.
      • azure-pipelines.yml contains build/test/coverage steps per blueprint toggles.
      • .csproj matches multi-TFM & analyzer settings modeled by the blueprint.
    • Drift detection: golden-files & per-file hash checks; diff reports emitted on mismatch.

CI Wiring

  • Publish coverage with PublishCodeCoverageResults@2 and fail the build if below threshold (Cobertura).
  • Keep tests on the PR pipeline; artifacts archived for review (reports + diffs).

Acceptance

  • Re-running Generation QA on the same snapshot yields identical hashes.
  • The generated pipeline includes test + coverage stages and passes the configured gate.

Governance & Policy Hooks

  • Follow the testing pyramid: emphasize unit tests, then integration, then E2E; keep tests isolated and fast.
  • Adopt BDD where it helps collaboration (Reqnroll optional), but keep suites lean.
  • Coverage is a gate in PR CI; results are published and visible.

[BLGA-FEAT-10] Delivery Engineering (Containers, Pipelines, IaC)

Outcome: The service is containerized with a multi-stage, non-root Dockerfile and local Docker Compose environment; the Azure DevOps PR pipeline builds/tests/publishes coverage and packages; CD uses Pulumi to provision and deploy (ACR, Container Apps, Service Bus, Key Vault). A smoke gRPC/MCP check validates deployments. Guidance aligns with the Microservice Template’s containerization and IaC practices.


[BLGA-TASK-10.1] End-to-End — Multi-stage Dockerfile (non-root, health probes) + image build; push to ACR

Intent Create a lean, secure image using multi-stage .NET build (SDK → ASP.NET runtime), run as non-root, expose /health/live and /health/ready, and push to Azure Container Registry (ACR). Align names to the BLGA solution.

Deliverables

  • Dockerfile at src/ConnectSoft.Factory.BackendLibraryGeneratorAgent.Host/:
    • Build stage: mcr.microsoft.com/dotnet/sdk:8.0 → restore, build, publish (ReadyToRun, deterministic).
    • Runtime stage: mcr.microsoft.com/dotnet/aspnet:8.0; add non-root user; copy published bits; set ASPNETCORE_URLS=http://+:8080.
    • Health probes: document GET /health/live and /health/ready (wired in Host).
  • Image tags: $(ACR)/blga:$(Build.BuildNumber) and $(ACR)/blga:latest.
  • Docker Compose additions for local dev (docker-compose.yml + override): BLGA service + dependencies (SQL Server, RabbitMQ, OTel Collector, Prometheus, Grafana, Jaeger, Elastic, Kibana) to mirror the template’s dev stack.

Steps

  1. Author Dockerfile (multi-stage, non-root) and verify docker build locally.
  2. Add docker-compose.yml services + network/volumes; provide override for local env values (e.g., ASPNETCORE_ENVIRONMENT=Docker).
  3. In Azure DevOps, create a service connection and ACR variable group; docker login to ACR, then docker build/docker push.

Acceptance Criteria

  • Local container runs and returns 200 on /health/live and /health/ready.
  • Image built in CI and pushed to ACR with both versioned and latest tags.
  • docker-compose up -d starts BLGA + dependencies; basic logs/metrics visible (Prometheus/Grafana/Jaeger/Kibana).

[BLGA-TASK-10.2] End-to-End — ADO PR pipeline (build/test/coverage/pack) + CD (Pulumi: ACR, Container Apps, SB, KV); smoke gRPC/MCP

Intent PR validation enforces build + test + coverage + pack, then CD deploys infra and app with Pulumi. After deploy, run smoke checks: gRPC GetRunStatus and MCP tool discovery.

Deliverables

  • PR Pipeline (azure-pipelines.yml, trigger pr to master):
    • dotnet restore/build/test (MSTest), publish Cobertura and test results.
    • dotnet pack (publish BLGA SDK packages if any).
    • docker build image (optional on PR), publish as pipeline artifact for CD. (ACR push on protected branches.)
  • CD (Pulumi) Pipeline:
    • Pulumi stack (C# or TS) for ACR, Azure Container Apps, Service Bus, Key Vault; image revision update on deploy.
    • Pulumi config and secure state handling as per template guidance.
  • Smoke tests post-deploy:
    • gRPC: call GetRunStatus on a test CorrelationId to verify ingress and wiring.
    • MCP: list tools and invoke library.get_status against the live endpoint.

Steps

  1. Author PR pipeline: restore → build (Release) → test → PublishCodeCoverageResults → pack; on protected refs, also docker build + docker push to ACR.
  2. Create ConnectSoft.Factory.BackendLibraryGeneratorAgent.InfrastructureModel Pulumi project (stack: dev/test/prod) and write components for ACR, Container Apps, SB, KV; wire inputs via Pulumi config.
  3. CD job: pulumi loginpulumi stack selectpulumi up -y; pass image tag, env, and secrets (via Key Vault/MI).
  4. Script smoke gRPC/MCP check (PowerShell or .NET console) and publish logs/artifacts.

Acceptance Criteria

  • PR pipeline fails on test or coverage regressions and publishes coverage to the build summary.
  • CD provisions infra and deploys new revision; smoke checks succeed; deploy logs/artifacts are persisted.
  • Pulumi state kept in the configured backend; configs are parameterized per environment.

[BLGA-TASK-10.3] End-to-End — Release readiness (SBOM optional), roll-forward/rollback playbook

Intent Codify the criteria for promoting a revision to “ready,” optionally attach an SBOM, and document safe roll-forward/rollback.

Deliverables

  • Release Readiness checklist (in repo):
    • PR CI green; coverage ≥ gate; image non-root; health probes; resource limits; readiness probe stable; secrets via Key Vault; traces/metrics/logs confirmed.
    • Optional: container SBOM generated (e.g., syft) and stored with build artifacts.
  • Playbook (docs/release-playbook.md):
    • Roll-forward: create new ACR tag, pulumi up to new revision; monitor; switch traffic.
    • Rollback: pin previous image tag; pulumi up to prior revision; confirm health & smoke.

Acceptance Criteria

  • Release checklists exist and are referenced by the CD pipeline.
  • Roll-forward/rollback executed in dev and documented with timestamps and outcomes.
  • If SBOM is enabled, artifact is uploaded alongside the image.

Governance & Policy Hooks

  • Containerization: multi-stage, small runtime, non-root, health endpoints; Compose stack for local parity (SQL, RabbitMQ, OTel, Prometheus, Grafana, Jaeger, Elastic/Kibana).
  • IaC: all cloud resources defined as code; environment isolation via Pulumi stacks and configuration; CI/CD integration.
  • CI/CD: PR on master enforces coverage gate; CD artifacts (deploy logs, smoke results) retained.

Dependencies

  • Prior features (contracts, ports/adapters, saga) available for smoke checks.
  • ACR and Azure subscription access; Azure DevOps service connections.

Definition of Done: Dockerfile + Compose ready; PR pipeline publishes coverage and (on protected branches) builds/pushes the image; Pulumi CD provisions ACR/Container Apps/SB/KV and deploys BLGA; smoke gRPC/MCP calls succeed; release checklist + rollback playbook committed.


[BLGA-FEAT-11] Security & Governance

Outcome: BLGA runs with zero secrets in code, retrieves credentials from Azure Key Vault via Managed Identity, enforces RBAC + scopes + rate limits on gRPC/MCP, applies allow-lists for repos/paths/licenses, and emits compliance logs with UTC timestamps and correlation IDs for all PR/branch actions. Security is testable, observable, and documented; defaults are secure-by-default and compatible with branch master.


[BLGA-TASK-11.1] End-to-End — Key Vault via Managed Identity (ADO PAT, AI keys); secret redaction; zero secrets in code

Intent Make secrets retrieval declarative and centralized (Key Vault + Managed Identity). Ensure adapters (Ado PR, AI, Git) consume credentials via an ITokenCredentialProvider abstraction; logs and traces redact anything secret-like; pipelines never echo sensitive values.

Deliverables

  • Infrastructure & Config
    • Key Vault secrets: ado.pat, git.token (if needed), ai.apiKey (optional), any provider-specific tokens.
    • App settings toggle: Security:KeyVault:Enabled=true, KeyVault:Name, KeyVault:SecretNames:*.
    • Managed Identity (system-assigned) with get/list permissions scoped only to required secrets.
  • Runtime
    • TokenCredentialProvider (impl): uses DefaultAzureCredential → Key Vault SecretClient to fetch; in-memory cache with short TTL + proactive refresh; jitter to avoid thundering herd.
    • Logging redaction policy: redact values matching secret patterns (GUID-like PATs, JWTs, bearer tokens, base64-ish > N chars). Apply to structured logging + exception filters.
    • gRPC & MassTransit logging scopes include CorrelationId but never raw tokens.
  • Pipelines
    • Replace any pipeline secret variables with Key Vault references.
    • Verify docker build and Pulumi deploy use MI/Key Vault and never inline secrets.

Steps

  1. Wire Key Vault client and TokenCredentialProvider in DI; replace direct token reads in Adapters.* with the provider.
  2. Add redaction middleware for logs; unit tests with representative tokens.
  3. Run a security smoke: attempt adapter operations with invalidated/rotated secrets to validate failure surfaces.
  4. Update docs: “Secret Handling & Rotation” (rotation procedure, blast radius, fallbacks).

Acceptance Criteria

  • No secrets exist in code or configuration files; runtime obtains tokens from Key Vault via MI.
  • Logs/traces contain no raw secrets; redaction tests pass.
  • Adapters operate correctly after rotation (token cache refresh works without restart).

[BLGA-TASK-11.2] End-to-End — RBAC for gRPC/MCP (roles/scopes/rate limits; allow-listed repos/paths/licenses); security tests

Intent Guard external surfaces (gRPC + MCP tools) with role-based authorization and scoped access; throttle calls; enforce allow-lists for repos, filesystem paths, and third-party licenses.

Deliverables

  • AuthN/AuthZ
    • gRPC: interceptor validates caller identity (e.g., JWT/MTLS/header token per environment).
    • Authorization policy maps identities → roles: LibraryGen.Admin, LibraryGen.Writer, LibraryGen.Reader.
    • Scopes per operation:
      • StartGeneration requires LibraryGen.Writer + repo/path allow-list pass.
      • GetRunStatus allowed for Reader and above.
  • Rate Limiting
    • Global and per-caller limits (e.g., status: 30/min; start: 10/hour/caller); burst + token bucket with retry-after headers/metadata.
  • Allow-lists
    • Repos: Security:AllowList:Repos = [org/project/repo, patterns].
    • Paths: /src/**, /tests/**, /docs/** only; deny writes to root or hidden system locations.
    • Licenses (for generated dependencies): Security:AllowList:Licenses = ["MIT","Apache-2.0","BSD-2-Clause","BSD-3-Clause"].
  • MCP
    • Tools library.start_generation & library.get_status check the same roles/scopes/limits; MCP responses include short, anonymized error messages.
  • Security Tests
    • Unit: policy evaluation (role/scope matrix), repo/path/license allow-list checks.
    • Integration: gRPC calls with missing/invalid/insufficient scopes; rate-limit behavior; MCP tool discovery & denial cases.
    • Negative: path traversal attempts; oversized payloads; invalid blueprint causing early deny.

Steps

  1. Add AuthorizationHandler(s) and gRPC/MCP interceptors; centralize policy evaluation service.
  2. Implement rate limiter (ASP.NET Core limiter for gRPC + MCP adapter).
  3. Encode allow-lists in options; use fail-closed defaults.
  4. Author tests; create security matrix in docs (who can call what, from where).

Acceptance Criteria

  • Unauthorized/forbidden calls are blocked with auditable denials; authorized calls succeed.
  • Rate limits emit consistent retry-after; limits are configurable per environment.
  • Writes outside allow-listed paths or non-approved licenses fail fast.

[BLGA-TASK-11.3] End-to-End — Compliance logging (PR/branch actions with UTC stamps + correlation IDs); policy docs

Intent Provide an audit trail across Git/PR activities and lifecycle events, stamped in UTC and tied to CorrelationId. Operators can trace from a PR back to inputs (blueprint snapshot, patch fingerprint, roles involved).

Deliverables

  • Compliance Events (structured)
    • Compliance.PrCreated {CorrelationId, Repo, SourceBranch, TargetBranch, PrId, Actor, Roles[], Utc, PatchFingerprint}
    • Compliance.PrCommented {PrId, CommentId, Actor, Utc}
    • Compliance.PrLabeled {PrId, Labels[], Actor, Utc}
    • Compliance.BranchPushed {Repo, Branch, CommitId, Actor, Utc}
    • Compliance.GenerationCompleted {CorrelationId, Status, Coverage, Utc}
  • Emission
    • Log as structured entries (OTel logs) + optional event bus topic (if configured).
    • Mask/omit any PII/secrets; keep event size bounded.
  • Dashboards
    • Workbook/Grafana panels that filter by CorrelationId, Repo, or PrId; show time-ordered trail.
  • Policy Docs
    • docs/security-governance.md: roles & scopes, rate limits, allow-lists, retention, incident response.
    • docs/compliance-events.md: event schema, examples, and consumer guidance.

Steps

  1. Instrument adapters and saga transitions to emit the compliance events (one place per action).
  2. Add correlation propagation to PR body/description (short correlation, patch fingerprint).
  3. Create dashboards/queries; document usage for audits and incident drills.

Acceptance Criteria

  • Creating a PR produces PrCreated with correct UTC and correlation; subsequent comment/label/status changes produce matching events.
  • Operators can reconstruct a full trail for a run using dashboards/queries.
  • Policy docs merged and referenced from the runbook.

Governance & Policy Hooks

  • Secure by default: deny on missing roles/scopes; allow-lists required to enable write operations.
  • Zero trust posture: all external calls authenticated; per-call correlation + minimal disclosure in errors.
  • Compliance: UTC-only timestamps; stable event schemas; documented retention & rotation.
  • Pipelines: security tests run on PR to master; failures block merge.

Dependencies

  • Key Vault, Managed Identity, and Pulumi-provisioned infra from earlier features.
  • Ports & Adapters (Ado PR, Git, Filesystem, Quality, AI) wired to token provider.

Definition of Done: Secrets pulled from Key Vault via MI; logs are redacted; gRPC/MCP enforce RBAC + scopes + rate limits; repo/path/license allow-lists active; compliance events emitted & visualized; policy docs merged; security tests green and gate merges to master.


[BLGA-FEAT-12] Observability & Knowledge Hooks

Goal: Wire first-class observability (logs, metrics, traces) and “knowledge hooks” into the agent so every generation run is fully traceable (from request → saga steps → PR), measurable (success rate, latency, retries), and searchable (artifacts indexed for downstream reasoning agents). Context: The service is scaffolded from ConnectSoft.MicroserviceTemplate and already includes cross-cutting plumbing. In this feature we specialize instrumentation for ConnectSoft.Factory.BackendLibraryGeneratorAgent, add domain metrics, emit correlation signals, and index generated artifacts for semantic lookup.

Projects added to the solution:

  • ConnectSoft.Factory.BackendLibraryGeneratorAgent.Observability — OpenTelemetry/metrics wiring, structured logging helpers, correlation conventions, dashboards/examples.
  • ConnectSoft.Factory.BackendLibraryGeneratorAgent.Knowledge — artifact extraction, chunking, embeddings (via IAiServices seam), vector store adapters, and a minimal query API for reasoning agents.

Scope & decisions:

  • Keep OTel as the single telemetry SDK; export to Console in dev, OTLP/App Insights in envs; no body logging; redact secrets via existing logging conventions.
  • Standard dimensions across all signals: CorrelationId, TraceId, SagaState, BlueprintSha, PatchSha, Repo, Branch, PrUrl, RunId.
  • Index rendered outputs (README, .csproj, pipelines YAML), and runtime artifacts (PR comments/bodies, generation report) into a vector store through an adapter seam; no back-end vendor lock (implement one in-memory/dev adapter + interface for prod).

[BLGA-TASK-12.1] End-to-End: OpenTelemetry spans per saga step; domain metrics (success rate, latency, retries); structured logs

What we deliver

  • Instrument the full run path with named spans for each saga step: Pending, WorkspaceReady, TemplateRendered, QualityRan, Pushed, PullRequestOpened, Completed|Failed.
  • Attach span attributes: run.id, blueprint.sha, patch.sha, repo, branch, pr.url (when available), attempt, retry.count, coverage.value, coverage.gate.
  • Define domain metrics in BackendLibraryGeneratorAgent.Observability:
    • blga_generation_runs_total (counter, labels: result, reason)
    • blga_generation_latency_ms (histogram, labels: stage)
    • blga_quality_coverage (gauge, labels: target)
    • blga_retries_total (counter, labels: stage, reason)
  • Provide structured logging helpers (extension methods / scope pushers) to stamp Flow, SagaState, RunId, CorrelationId consistently across API, saga handlers, ports/adapters.
  • Dev profile: Console exporter + Prometheus scrape endpoint; Prod: OTLP/App Insights via config (no code changes).

Done when

  • Local run shows trace tree for a complete run with all stages and attributes.
  • Metrics endpoint exports the counters/histograms; CI asserts presence of metric names.
  • Logs include TraceId/CorrelationId and SagaState without leaking secrets.
  • A short dashboard JSON (dev folder) demonstrates latency per stage & success rate.

What we deliver

  • On quality completion, emit a compact Generation Result event (internal app event) carrying:
    • RunId, BlueprintSha, PatchSha, CoveragePercent, TestsPassed/Failed, ArtifactsPath, Repo, Branch.
  • When PR is opened/updated, enrich current span and subsequent logs with:
    • pr.id, pr.url, pr.title, pr.reviewers (count only), commit.sha.
  • Create a trace ↔ PR correlation helper:
    • Writes a one-line PR comment: “Trace: <TraceId> / Run: <RunId>
    • Adds a PR status/markdown block summarizing coverage & gate result.
  • Add sample Kusto/OTel queries (docs) to jump from RunId or TraceId to PR and vice versa.

Done when

  • A completed run shows: PR contains the correlation comment; the trace spans include pr.url; logs/metrics carry BlueprintSha & PatchSha.
  • A scripted E2E in CI demonstrates Start → Completed with correlation populated.

[BLGA-TASK-12.3] End-to-End: Index artifacts (docs, YAML, PR comments) to vector store; query API for reasoning agents

What we deliver

  • BackendLibraryGeneratorAgent.Knowledge library with:
    • IArtifactExtractor — collects canonical artifacts from the workspace & results folder: README.md, .csproj, pipelines YAML, generation report, PR body/comments (via IAdoPullRequests read APIs), and key snippets from rendered code headers (limited, no wholesale source ingestion).
    • IChunkingStrategy — deterministic chunking (by heading/code region) with metadata: runId, path, kind, blueprint.sha, patch.sha, pr.url.
    • IVectorStore — abstraction; implement InMemoryVectorStore for dev; include an interface ready for Azure/Open-source providers (no vendor hard-code).
    • IEmbedder — uses existing IAiServices seam; provide a deterministic fallback (hash-based pseudo-vector) for tests/offline mode.
    • IKnowledgeIndexer — orchestrates extract → chunk → embed → upsert.
  • Background hook in the saga after PR opened (or Completed on no-PR flows) to invoke IKnowledgeIndexer.
  • Minimal query API (gRPC read-only or internal handler) to search by RunId, BlueprintSha, PatchSha, path, or semantic query returning snippet + metadata + source link (e.g., PR URL, file path).
  • Fakes and E2E tests: start → render → index; assert at least N chunks; search returns README & pipeline YAML chunks with proper metadata.

Done when

  • A dry-run creates an index with README/YAML/.csproj snippets; querying by RunId and a semantic phrase (e.g., “coverage gate”) returns the expected chunk and PR link.
  • Indexing is idempotent (re-run with same SHAs does not duplicate).
  • All indexing flows respect redaction rules (no secrets; PR comments included but tokens/headers excluded).

Out of scope (here):

  • Selecting a production vector DB or long-term retention policy.
  • Organization-wide dashboards; we only provide dev JSON samples.
  • Human approval workflows for knowledge publishing (covered later under governance).

Definition of Done (feature):

  • Telemetry shows a full span tree for a run; domain metrics exported; structured logs enriched consistently.
  • PRs are correlated with traces/runs; coverage/test results emitted and visible.
  • Artifacts from generated outputs are indexed and retrievable through the query API.
  • All code, tests, docs, and pipeline wiring updated on master; documentation added under /docs/observability and /docs/knowledge.

[BLGA-FEAT-13] Error Handling & Resilience

Outcome: BLGA treats failures as first-class signals. We centralize exception handling, apply resilience policies (timeouts, retries with exponential backoff + jitter, circuit breaker, bulkhead), surface DLQ faults, and provide human-in-the-loop controls to resume/abort runs safely. Health probes, structured logs, and metrics make failures observable and auditable.


[BLGA-TASK-13.1] End-to-End — Retry policies (expo backoff/jitter; transient categorization) + DLQ surfacing; Options-driven

Intent Introduce Options-driven resilience for all outbound calls (Git/FS/PR/AI/Quality, DB, bus) and categorize failures (transient vs. permanent). Configure DLQ surfacing for message handling so poisoned/permanently failing messages are visible, queryable, and alertable.

Deliverables

  • ResilienceOptions (appsettings.* + IOptions<ResilienceOptions>):
    • Retries:{MaxAttempts,BaseDelayMs,JitterMs,TransientHttpCodes[]}
    • Timeouts:{GrpcMs,ExternalHttpMs,DbMs}
    • CircuitBreaker:{FailuresBeforeBreak,BreakDurationSec,SamplingWindowSec}
    • Bulkhead:{MaxParallel,MaxQueue}
  • Polly policy pack registered once (typed HttpClient, gRPC clients, AI/Quality calls) with exponential backoff + jitter, timeouts, circuit breaker, bulkhead.
  • NHibernate/SQL transient handling: command timeout + retry-on-deadlock; optimistic concurrency already covered separately.
  • Bus consumer pipeline:
    • Retries for transient exceptions; immediate fault → DLQ for domain/validation failures.
    • On MoveToError/DLQ, emit structured Compliance + Observability events (dlq.reason, messageId, CorrelationId).
  • Docs: matrix of error categories → policy (retry vs. fail fast); defaults are conservative and fail-closed.

Steps

  1. Add ResilienceOptions + configuration binder; wire policy handlers (Polly) for outbound clients.
  2. Decorate adapters (Git/PR/Filesystem/AI/Quality) with typed clients using the shared policies.
  3. Configure consumer retry/DLQ behavior; attach telemetry/log scopes for CorrelationId, SagaState.
  4. Provide a small /docs/resilience.md with examples and thresholds.

Acceptance Criteria

  • Forced HTTP 503 / transient socket errors are retried with expo-backoff + jitter, then short-circuit via circuit breaker if sustained.
  • Domain/validation errors do not retry; messages land in DLQ and create a compliance event.
  • Timeouts enforced per channel; bulkhead limits observable under load tests.

[BLGA-TASK-13.2] End-to-End — Compensations (PR comment/label on failure, workspace cleanup, optional work item)

Intent When a run fails after side effects (branch created, commits pushed, PR opened), apply compensations so humans have context and the repo/workspace is tidy. Exceptions are mapped centrally; compensations are idempotent and correlated.

Deliverables

  • CompensationService (Application layer) that, given RunId/CorrelationId and failure reason:
    • PR comment: short incident note including TraceId, BlueprintSha, PatchSha, gate results; redact secrets.
    • PR labels: generation-failed, plus a stable reason code (e.g., quality-gate, push-rejected, pr-policy).
    • Workspace cleanup: delete temp workspace and ephemeral artifacts; preserve diagnostics/patch in artifacts store.
    • Optional ADO work item: if enabled in options, open a Bug linked to PR with auto-filled repro (disabled by default).
  • Idempotency: compensation operations are safe to re-run.
  • Docs: compensation decision table (when/what to run).

Steps

  1. Implement ICompensationService and hook from saga Failed transition.
  2. Use existing PR adapter to comment/label; update logs with pr.url + stable reason code.
  3. Add CompensationOptions (enable flags; label names; work-item template); write unit & integration tests for idempotency.

Acceptance Criteria

  • On simulated failures (template error, quality gate fail, push rejected, PR rate-limit, bus/DLQ), a PR comment + label appears with correct UTC timestamp & correlation; workspace is cleaned; optional work item created when enabled.

[BLGA-TASK-13.3] End-to-End — Human-in-the-loop (alerts, dashboards, manual resume/abort); run test matrix

Intent Enable operations to see failures, get alerts, and intervene safely: resume from a known saga state or abort and compensate. Provide a test matrix that exercises representative failure modes regularly.

Deliverables

  • Alerts (environment-specific):
    • DLQ depth, circuit-breaker open rate, retry surge, failing health checks.
  • Dashboards: latency per saga stage, success ratio, retry counts, DLQ trend, top failure reasons; link out to PRs/runs.
  • Manual controls (Admin role only):
    • gRPC admin ops: Admin.ResumeGeneration(runId, fromStage?), Admin.AbortGeneration(runId) with guardrails (only allowed in Failed|Stuck states; all operations audited).
  • Test matrix (automated in CI Nightly):
    • Template render error → fast fail, compensation, no retries.
    • Quality gate fail → pass/fail surfaced; no retries; compensation.
    • Push rejected (non-fast-forward/ACL) → retry (bounded), then compensate.
    • PR rate-limit → backoff/jitter then give up → compensate.
    • Bus fault / DLQ → verify DLQ surfacing + alert; manual resume after fix.

Steps

  1. Add Prometheus/OTel counters & histograms for retries, failures, DLQ; wire alert rules.
  2. Build a small Operations dashboard JSON (dev) + doc on importing to Grafana/App Insights.
  3. Implement gRPC admin service + RBAC (Admin only); log/audit every action with UTC stamps.
  4. Add CI job resilience-matrix.yml to run fault-injected scenarios nightly and publish reports.

Acceptance Criteria

  • Alerts fire on DLQ growth/circuit opens; dashboards show top reasons.
  • Operators can resume a failed run and it completes; abort triggers compensations safely.
  • Nightly matrix runs produce artifacts and historical trend lines; failures block promotion.

Governance & Policy Hooks

  • Centralized exception mapping for gRPC/HTTP ensures clean client contracts; logs contain correlation but no secrets.
  • Health endpoints are monitored (/health, /alive) and used as readiness/liveness probes in Container Apps.
  • Operational excellence: dashboards/runbooks live in repo; alerts are actionable and low-noise.

Definition of Done: Resilience policies are Options-driven and applied to all outbound calls; DLQ surfacing and alerts are active; compensations (PR comment/label, cleanup, optional work item) execute idempotently; admin resume/abort flows are RBAC-gated and audited; the test matrix runs automatically with artifacts and trends.


[BLGA-FEAT-14] Jobs & Scheduling (Hangfire)

Outcome: Add an optional jobs host with Hangfire (server + dashboard) to run operational/maintenance tasks on a UTC schedule. Schedules are config-driven, policies are persisted in DB (enable/disable, retries, backoff), and every job is idempotent with full telemetry (traces, metrics, structured logs) and auditable execution logs. The solution includes a dedicated project: ConnectSoft.Factory.BackendLibraryGeneratorAgent.SchedulerModel.Hangfire.


[BLGA-TASK-14.1] End-to-End — Jobs host & dashboard; UTC CRON; DB policies (enable/disable, retries); telemetry

Deliverables

  • Project & Host wiring
    • Add ConnectSoft.Factory.BackendLibraryGeneratorAgent.SchedulerModel.Hangfire and compose Hangfire in the host (AddHangfire + AddHangfireServer), using SQL Server storage; keep the dashboard off by default and secure it when enabled.
  • Registration (UTC)
    • Central registrar that loads CRON from config and registers recurring jobs using TimeZoneInfo.Utc.
  • DB Policies (runtime knobs)
    • Add migrations for lga.JobPolicy and lga.JobExecutionLog (UTC datetimeoffset, nvarchar, lookups), enabling runtime toggle, CRON override, max retries, backoff; track execution log with outcome and error summary.
  • Telemetry
    • Enable Hangfire health checks, tag jobs/spans with job.code, executionId, status, and export metrics for success/failures.
  • Config
    • appsettings.Jobs.json with UTC timezone default and per-job blocks; allow Pulumi overrides for environments.

Acceptance

  • AddHangfire/UseHangfireServer run with SQL Server storage; dashboard reachable only when explicitly enabled and secured.
  • Recurring jobs register with UTC schedules pulled from config; toggling Jobs.Enabled=false disables all.
  • Health checks report green with at least one worker; metrics/logs include job attributes.

[BLGA-TASK-14.2] End-to-End — Outbox dispatch, DLQ replay, nightly quality sweep, workspace cleanup, PR stale check; sandbox E2E

Deliverables

  • Job catalog (first wave) implemented as recurring jobs; all use UTC CRON and are idempotent:
    • outbox-dispatch — drain platform outbox → publish integration events.
    • dlq-replay — replay messages from Service Bus DLQ back to main queue with safety rules.
    • quality-nightly-sweep — re-run quality for stale/failed runs and update PR status.
    • workspace-cleanup — remove stale workspaces under allow-listed roots.
    • pr-stale-check — label/comment stale PRs, ensure status checks present.
  • Job registration (config-driven) RecurringJob.AddOrUpdate<TJob>(code, j => j.RunAsync(ctx), cron, TimeZoneInfo.Utc, queue) with per-job queues (e.g., maintenance).
  • Shared base & logging
    • JobExecutionContext and LgaJobBase.RunGuardedAsync record start/finish UTC, counts, and errors to JobExecutionLog; integrate with ILogger and emit correlation.
  • Idempotency & concurrency
    • Use Hangfire attributes like [DisableConcurrentExecution] where needed (e.g., outbox) and job-level idempotency keys.
  • Sandbox E2E
    • A scripted run registers all jobs with relaxed CRONs, executes one full cycle, and asserts outcomes/logs.

Acceptance

  • Each job runs on schedule, writes an execution log row with StartedUtc/FinishedUtc, and produces expected side-effects; UTC schedule is verified.
  • DLQ replay and outbox dispatch are safe and idempotent; stale PRs get labeled/commented as expected.

[BLGA-TASK-14.3] End-to-End — Pulumi/Config wiring for toggles; idempotent job logs + lookup statuses

Deliverables

  • Pulumi bindings for per-environment toggles/CRON overrides (e.g., slower sandbox cadence).
  • Policy precedence
    • Runtime DB policy (lga.JobPolicy) overrides appsettings; add unique constraint on JobPolicy.Code.
  • Statuses & lookups
    • Seed lga_lu.JobExecutionStatus: Succeeded, Failed, Partial, Skipped.
  • Idempotent logs
    • Ensure repeated executions with the same key do not duplicate outcome; keep details JSON for diagnostics.

Acceptance

  • Changing Pulumi config changes CRON without rebuild; DB policy toggles take effect at runtime.
  • Execution logs show correct status mapping and correlation; duplicate runs coalesce per job key.

Governance & Policy Hooks

  • Security: Dashboard disabled by default; when enabled, protect with authZ filter/SSO.
  • Observability: Health checks for Hangfire enabled; logs are structured and redacted per platform guidance.
  • Standards: All schedules and persisted times are UTC; strings are nvarchar; statuses use lookup tables.

Definition of Done (feature):

  • Hangfire server + (secure) dashboard integrated; UTC CRON registration in place.
  • DB policy + execution log migrations applied; job catalog implemented and scheduled; telemetry and health checks green.
  • Pulumi/config toggles operational; sandbox E2E proves jobs run and logs are idempotent and queryable.

[BLGA-FEAT-15] Actor/Grain Integration (Orleans) — Optional Orchestration Variant

Outcome: Provide an optional, production-ready Orleans-based orchestration path for ConnectSoft.Factory.BackendLibraryGeneratorAgent that can be toggled on/off at runtime. The variant introduces a GenerationGrain (virtual actor) keyed by CorrelationId to coordinate the library generation lifecycle with durable state, reminder-driven timeouts, deterministic inputs/outputs via surrogates, and first-class observability. Grains process one message at a time (no shared state, no locks) and auto-activate/deactivate within a silo, aligning with the virtual actor model.

Projects created/updated (Solution structure–aligned):

  • ConnectSoft.Factory.BackendLibraryGeneratorAgent.ActorModel — actor contracts (grain interfaces), surrogate DTOs, converters.
  • ConnectSoft.Factory.BackendLibraryGeneratorAgent.ActorModel.Orleans — grain implementations, state persistence, reminders, configuration glue (UseMicroserviceOrleans), DI wiring.
  • ConnectSoft.Factory.BackendLibraryGeneratorAgent.ActorModel.Tests — unit + acceptance tests for grain flows, surrogates, reminders.

Feature flags & defaults: Features:OrleansOrchestration:Enabled=false (primary path remains Saga/MassTransit). Toggle can be switched per environment without redeploy.


[BLGA-TASK-15.1] End-to-End: GenerationGrain (virtual actor) + State + Surrogates + API surface

What we’ll build

  • Grain contract: IGenerationGrain : IGrainWithStringKey with methods:
    • StartAsync(GenerationStartSurrogate input),
    • GetStatusAsync() (returns GenerationStatusSurrogate),
    • ApplyPolicyAsync(PolicyPatchSurrogate patch),
    • AbortAsync(string reason).
  • Actor state: GenerationActorState (status, blueprint SHA, patch SHA, branch, PR id/url, timestamps). Persist via IPersistentState<GenerationActorState> mapped to configured storage (local SQL Server in dev).
  • Surrogate DTOs + converters for all grain inputs/outputs using [GenerateSerializer] + [Id(n)] attributes; isolate Orleans-boundary types from rich domain objects.
  • Serialization rules: forbid passing domain entities/VOs across the grain boundary; require additive versioning in surrogates.
  • Storage config: Add Orleans:Storage and Orleans:GrainStorage:Generation entries to appsettings.Development.json pointing at local SQL Server (same dev DB family as the service).
  • Silo bootstrap: enable Orleans host via builder.Host.UseMicroserviceOrleans(configuration).

Deliverables

  • Contracts + surrogates + converters with tests (converter round-trips, versioning additivity).
  • Grain implementation with persisted state CRUD and idempotent StartAsync (guard by CorrelationId + SHAs).
  • Docs: “Why Surrogates” + “Versioning rules” + “State schema”.

Acceptance

  • Start → GetStatus returns progressing states; state persists on restart.
  • Surrogate round-trip tests pass; no domain types leak into actor boundary.
  • Local silo runs from the service process; Orleans Dashboard reachable at http://localhost:8080.

[BLGA-TASK-15.2] End-to-End: Dual-mode orchestration (Saga primary, Actor optional) + Backpressure + Timeouts

What we’ll build

  • Mode toggle: Application layer orchestrator selects Saga (MassTransit) or Actor (Orleans) by flag.
  • Backpressure: use stateless worker grains for CPU-bound steps (e.g., rendering/QA) and enforce concurrency by key; use queueing in Saga path otherwise.
  • Timeouts & recovery: implement Orleans Reminders for long-running steps (e.g., quality, PR open) to drive retries/compensation when a step stalls.
  • Contracts: grain emits domain events to the bus when in Actor mode (co-existence with MassTransit eventing).

Deliverables

  • Orchestrator policy that routes requests to grains when enabled, otherwise to Saga.
  • Reminder registration per in-flight generation; timeout callbacks trigger state transitions and compensations.
  • Docs: mode comparison table (latency, throughput, failure semantics) + operational runbook.

Acceptance

  • With flag off: system behaves exactly as Saga build (no regressions).
  • With flag on: end-to-end Start→Completed succeeds through the grain; simulated stalls wake via reminder and recover.
  • Load test with N parallel generations demonstrates serialized execution per CorrelationId.

[BLGA-TASK-15.3] End-to-End: Actor Observability, Failure Handling & Comparison Docs

What we’ll build

  • Instrumentation: OTel spans for every grain method, attributes for correlation, blueprint/patch SHAs; emit duration/error metrics; enable Orleans Dashboard.
  • Structured logs around state writes and reminder callbacks; log reminder IDs and transitions.
  • Failure handling: retry on transient storage errors; surface terminal failures to PR/comments consistent with existing policies.
  • Comparison: decision record documenting Saga vs. Actor, placement choices, and when to switch (feature toggle guidance). Include examples of stream/consumer patterns if needed later.

Deliverables

  • Metrics + traces visible in existing stack; dashboard instructions.
  • “Actor Mode” operational doc: how to read dashboard, common issues, safe rollback to Saga.
  • Tests: reminder scheduling/triggering, persistent state write failures, idempotent message handling.

Acceptance

  • PR/branch correlation visible from traces → PR URL (as in prior observability feature).
  • Orleans dashboard shows live calls, activation counts, and errors during test runs.
  • All actor tests green under Debug and Release.

Governance & toggles

  • Features:OrleansOrchestration:Enabled (bool) — default false; environment-scoped.
  • Orleans:Storage:* configuration owned by platform; prod uses managed SQL/Redis/Azure Table providers per environment.
  • Security relies on existing service authN/Z at the face layer; grains trust the application boundary.

Definition of Done (for this feature)

  • Actor path is functionally equivalent to Saga path for the generation happy path; no change to external gRPC/MCP contracts.
  • Deterministic outputs preserved; state durable; reminder-driven timeouts operational.
  • Observability + dashboard in place; docs/runbook enable rollback to Saga within minutes.

Notes

  • This feature does not replace Saga; it provides an optional orchestration variant optimized for concurrency and backpressure in high fan-out scenarios.

[BLGA-FEAT-16] Sandbox & Factory-Wide Reuse

Outcome: Teams can run no-PR, ephemeral preview generations in a safe sandbox; artifacts (build/test/coverage, diffs, docs) are published to the Studio and indexed for reasoning agents. Common GitOps/PR Orchestration and Quality Runner seams are documented and reusable across generator agents.

Scope

In scope

  • Ephemeral sandbox run that renders a backend library (all projects at once), builds/tests/validates locally, but does not push a PR.
  • Time-boxed TTL workspaces with automatic cleanup.
  • Indexing of generated docs/YAML/PR comment templates to the vector store for cross-agent reuse; add minimal query API surface. (Aligns to our DSL/Blueprint knowledge model.)
  • Reference docs for shared contracts (GitOps, PR orchestration, Quality Runner).

Out of scope

  • New DSLs—use current blueprint/DSL set; only wire integrations.

Deliverables

  • Sandbox Mode: CLI flag and gRPC/MCP switch to run no-PR workflows; publishes diff/patch, build logs, test/coverage reports.
  • Studio Artifacts: Markdown docs, ERD, pipeline YAML, and deterministic diff/patch persisted under artifacts/sandbox/<correlation> and surfaced in Studio.
  • Reuse Docs: docs/contracts/gitops.md, docs/contracts/quality-runner.md; cookbook of 5 patterns for other agents.
  • Indexing & Query: Background indexer that ingests markdown/YAML/comment templates into a vector store and exposes GET /knowledge?q= for internal agents.

Dependencies

  • Existing Knowledge/Observability setup (events, traces, PR correlation) and the DSL/Blueprint contracts.

Tasks

[BLGA-TASK-16.1] End-to-End — Sandbox preview runs (no-PR) + TTL cleanup

Intent Provide a frictionless dry-run: generate → render → build/test/coverage → publish artifacts → auto-clean. Steps

  1. Workspace lifecycle: create ephemeral working dir; enforce allow-lists; compute patch SHA for provenance.
  2. Render & compile: generate all projects (solution-wide) and assets; run unit + generation-QA and record coverage.
  3. Artifacts: write diff.patch, render.report.json, coverage.xml, logs to artifacts/sandbox/<correlation>.
  4. TTL cleanup: add scheduled job to purge sandboxes older than N hours (configurable). Acceptance

  5. Running sandbox via CLI/MCP yields a deterministic diff and green local build/test with coverage ≥ gate; sandbox dir auto-deleted after TTL.

[BLGA-TASK-16.2] End-to-End — Shared GitOps/PR Orchestration & Quality Runner contracts

Intent Stabilize seams so other generator agents can plug in the same PR/quality mechanics. Steps

  1. Extract interfaces from adapters into a small contracts package: IGitOpsOrchestrator, IPrDraftBuilder, IQualityRunner (message shapes and error taxonomy aligned with naming conventions).
  2. Sample implementations: wire BLGA’s adapters behind those interfaces.
  3. Contract tests: verify command/event and result shapes (success/failure codes, retryable vs non-retryable).
  4. Docs: author docs/contracts/*.md with sequence diagrams and examples (YAML + C# snippets). Acceptance

  5. Contract packages published to internal feed; a “hello-world” consumer service passes the contract tests against a fake Git host and fake runner.

[BLGA-TASK-16.3] End-to-End — Cross-agent cookbook + indexing for reasoning agents

Intent Make successful patterns repeatable and discoverable. Steps

  1. Cookbook: 5 end-to-end patterns (e.g., “Multi-TFM library,” “Docs-first PR body,” “Coverage gate on generated tests,” “Deterministic patch verification,” “Sandbox to PR promotion”).
  2. Indexing: emit markdown/YAML and PR comment templates to the vector store and link them to run traces (trace ↔ artifact) so agents can cite exemplars.
  3. Query API: GET /knowledge?q= returns top-K snippets with source refs for Studio/agents. Acceptance

  4. Queries like “PR body template for .NET multi-TFM” return cookbook snippets and working examples in <200 ms.


(Optional Backlog) [BLGA-FEAT-17] Extensibility & Variants

Outcome: BLGA can target additional Git providers and faces (REST/GraphQL/SignalR) with the same use-case layer; groundwork for future Java/Kotlin renderers.

Tasks

  • [BLGA-TASK-17.1] End-to-End — Pluggable Git providers (ADO today; add GitHub/GitLab behind the IMcpGit seam). Contract tests ensure identical behavior across providers.
  • [BLGA-TASK-17.2] End-to-End — Additional faces (read-only REST/GraphQL/SignalR projecting GetRunStatus with the same Service Model shape).
  • [BLGA-TASK-17.3] End-to-End — Multi-language renderer prep (strategy interface, golden-file tests that will later host Java/Kotlin).

(Optional Backlog) [BLGA-FEAT-18] Cost & Performance Optimizations

Outcome: Lower run time and infra cost with parallelism, caching, and right-sizing.

Tasks

  • [BLGA-TASK-18.1] End-to-End — Parallel generation & build graph (safe parallel stages with bounded concurrency; measure critical path).
  • [BLGA-TASK-18.2] End-to-End — Caching & reuse (NuGet cache, renderer cache keyed by blueprint/patch SHA; skip unchanged assets).
  • [BLGA-TASK-18.3] End-to-End — Ephemeral runners & right-sizing (container resource limits, throttle policies; add perf smoke + SLOs).