Skip to content
Purview Dev logo

Use cases

Use cases

59 concrete examples of what the projects do, tagged by who each one speaks to. Every example shows the code involved and what you get back; follow the guide link for the full detail.

0 use cases

Developer Telemetry SourceGenerator

Tracing, logging, and metrics from a single interface

You want OpenTelemetry activities, structured logs, and metrics around an order service, but you do not want to hand-write the ActivitySource, ILogger, and Meter wiring in every class.

csharp
[ActivitySource]
[Logger]
[Meter]
public interface IOrderServiceTelemetry
{
    [Activity]
    [Info]
    [AutoCounter]
    Activity? PlacingOrder(int orderId, [Baggage] string region);
}

What you get: The generator emits the implementation and an AddOrderServiceTelemetry() DI extension; you register it once and inject the interface wherever telemetry is needed.

One interface replaces the ActivitySource, ILogger, and Meter boilerplate you would otherwise repeat in every service.

Read the guide →
Architect Telemetry SourceGenerator

Standardise telemetry names across services

You want consistent OpenTelemetry meter and activity-source names across many services instead of ad-hoc string literals scattered through the codebase.

csharp
builder.AddServiceDefaults(
    TelemetryNames.MeterNames,
    TelemetryNames.ActivitySourceNames);

What you get: A generated TelemetryNames static class holds the names, so registration happens once at startup rather than in every service.

Naming conventions are generated, so snake_case tags and hierarchical metrics stay consistent without a review checklist.

Read Generation Options →
Developer Event Sourcing

An aggregate that persists as events

You want aggregate-based event sourcing without hand-writing the event stream, snapshot, and transaction plumbing.

csharp
[Aggregate]
public partial class OrderAggregate : AggregateBase
{
    public string CustomerId { get; private set; } = default!;
    public decimal Total { get; private set; }

    [Event]
    public partial void CreateOrder(string customerId);

    [Event]
    public partial void AddLineItem(string productId, string productName, int quantity, decimal unitPrice);
}

What you get: The source generator produces the aggregate plumbing; provider packages add stores for SQL Server, PostgreSQL, MongoDB, Azure Storage, Cosmos DB, or in-memory.

One [Aggregate] declaration, and switching storage means swapping a provider package rather than rewriting the domain.

Read Solution Design Guide →
Architect Event Sourcing

Choose the store late, keep the domain stable

You need to start on one database and move providers later, but you do not want persistence choices to leak into the domain model.

csharp
builder.Services.AddSqlServerEventStore();
builder.Services.AddSqlServerSnapshotQueryableEventStore();

What you get: Domain code depends on provider-agnostic facades, while concrete stores live behind separate packages and registration extensions.

SQL Server, PostgreSQL, MongoDB, Azure Storage, and Cosmos DB are interchangeable at the registration level, so the domain never references a store.

Read SQL Server Event and Snapshot Stores →
Developer Unions

Match a value-type union without boxing a case

A method returns one of a handful of value-type outcomes, and the caller must branch on which one it received — but the union keyword boxes every value-type case on entry and again while matching.

csharp
[GenerateUnion(typeof(int), typeof(string))]
public readonly partial struct IntOrString;

IntOrString value = 42;

var message = value switch
{
    int number => $"int {number}",
    string text => $"string {text}",
    null => "empty",
};

What you get: The compiler treats the generated type as a union, so implicit conversions, exhaustive switch and is/null patterns all work, while construction, TryGetValue, is and switch never allocate.

The committed BenchmarkDotNet suite measures construction, both TryGetValue directions, the miss path, HasValue, is and both switch shapes at 0 B; only reading Value allocates the 24-byte box for the int case, which is inherent to the union contract.

Read Performance →
Developer Unions

Declare a union whose cases are type parameters

You want a generic option or outcome type, but typeof(T) is not a legal attribute argument, so an ordinary [GenerateUnion(typeof(…))] list cannot name a type parameter.

csharp
[GenerateUnion]
public readonly partial struct Option<T>
{
    internal static partial Option<T> Some(Some<T> value);
    internal static partial Option<T> None(None value);
}

What you get: Each partial factory signature names a case, the generator supplies the bodies and derives the public constructors from them, and the compiler reports CS0416 only if you try to use a typeof(T) list instead.

A generic union must name its cases in source because CS0416 rejects typeof(T) in an attribute; a typeof list on a generic union is reported as UNI0011.

Read Union design →
Architect Unions

Let a second source generator see the union's cases

Another Purview generator — Results, or the telemetry generator unwrapping a parameter — must read the case list, but Roslyn generators never see each other's generated output.

csharp
[GenerateUnion]
public readonly partial struct Outcome<T> : Outcome<T>.IUnionMembers
{
    public interface IUnionMembers
    {
        static Outcome<T> Create(T? value) => Outcome<T>.CreateCase0(value);
        static Outcome<T> Create(Exception? error) => Outcome<T>.CreateCase1(error);

        bool TryGetValue(out T value);
        bool TryGetValue(out Exception value);
    }
}

What you get: A public nested IUnionMembers provider exposes the case list in the source the other generator compiles against, while this generator still emits the storage and CreateCaseN methods.

Purview.Telemetry.SourceGenerator 6.0.0 reads the source-visible case list in the same order as this package, and a [GenerateUnion] target with no source-visible case list is reported as UNI0003 rather than unwrapped.

Read Interop →
Contributor Unions

Fail fast on a malformed union declaration

A union is declared without partial, with a duplicate case, or with a case type less accessible than the union, and the generated shape cannot be emitted coherently.

plaintext
error UNI0001: The union declaration is not partial
error UNI0004: Duplicate case type
error UNI0005: A case type is less accessible than the union

What you get: Every error blocks its union's output rather than emitting a partial shape, and the package ships code fixes for the common declarations — add partial (UNI0001), widen an inaccessible case type (UNI0005), add [Union] on the fallback path (UNI0007).

UNI0015 (a single-case union) is the only warning; every other UNI rule blocks emission, so a malformed union fails the build instead of producing half a type.

Read Diagnostics →
Developer ZodSharp

Validate input without exceptions or allocations

You need to validate values at an application boundary and prefer a result you can inspect over exception-driven control flow.

csharp
var nameSchema = Z.String().Min(3).Max(50);
var result = nameSchema.Validate("John");

if (result.IsSuccess)
    Console.WriteLine($"Valid name: {result.Value}");

What you get: Validate/SafeParse return a ValidationResult<T> with no exceptions, while Parse still throws ZodException when you want that behaviour.

Validation is zero-allocation on every valid input path, so the performance claim is a property of the code rather than an aspiration.

Read Fluent Schema API →
Team lead ZodSharp

Return standard ProblemDetails for invalid requests

You want failed validation in ASP.NET Core to surface as standard ProblemDetails payloads rather than a bespoke error shape that clients must learn.

bash
dotnet add package Purview.ZodSharp.AspNetCore

What you get: The AspNetCore adapter converts failed validation results into the standard ProblemDetails / HttpValidationProblemDetails payloads.

One adapter package, and API consumers keep the error contract they already expect.

Read ASP.NET Core Integration →
Developer Value Objects

A domain scalar without the boilerplate

You want a strong EmailAddress type with normalisation and validation, without hand-writing factories, equality, conversions, and a JSON converter.

csharp
[Scalar]
public readonly partial record struct EmailAddress
{
    public string Value { get; }

    static partial void OnNormalize(ref string value)
        => value = value?.Trim().ToLowerInvariant()!;
}

What you get: The generator adds Create, Hydrate, TryCreate, and Empty, plus equality, comparison, implicit conversions, and a JSON converter.

One declaration replaces the factory, equality, comparison, conversion, and serialization code you would otherwise maintain by hand.

Read Value Object Design →
Developer Value Objects

Map a value object onto an Entity Framework column

You use a value object in your domain and want it to persist transparently instead of writing converters at every mapping site.

csharp
var email = EmailAddress.Create("  [email protected]  ");
// email.Value == "[email protected]"

bool ok = EmailAddress.TryCreate("not-an-email", out _);
// ok == false

What you get: Value objects serialize as their underlying value and map onto Entity Framework JSON columns, with optional Purview.ZodSharp validation.

Persistence and serialization come from the generated type, so mapping code is not duplicated per entity.

Read Entity Framework →
Contributor SourceGenerator Framework

Build an incremental generator on typed foundations

You are writing a non-trivial incremental C# source generator and need typed attribute models, structured code output, and packaging that Roslyn will actually load.

xml
<ProjectReference
  Include="..\MyGenerator\MyGenerator.csproj"
  PrivateAssets="all"
  OutputItemType="Analyzer"
  ReferenceOutputAssembly="false"
/>

What you get: The framework supplies attribute-data models, a structured code writer, a type library, and packaging helpers so the generator stays focused on its own logic.

The Purview generators themselves are built on the framework, so it is exercised by real generators rather than being an untested abstraction.

Read Source Generator & Analyser Best Practices →
Contributor SourceGenerator Framework

Verify incremental behaviour in tests

You need to prove a generator is incremental and produces the code you expect, without assembling a Roslyn driver by hand in every test.

What you get: The testing package provides SourceGeneratorTestRunner<TGenerator>, a framework-agnostic test base, and assertions such as AssertSingleGeneratedSource and AssertNoCompilationErrors.

Step-cache tests and a TUnit integration ship alongside the runner, so incremental regressions surface in CI.

Read Testing →
Developer Results

Return expected failures as values

You call a store that can fail in ways you expect — not found, disabled, already exists — and you do not want a thrown exception or a generic error string to be the only way the caller learns what happened.

csharp
Result<Tenant, TenantError> GetTenant(TenantId tenantId) =>
    _tenants.TryGet(tenantId, out var tenant)
        ? Result<Tenant, TenantError>.Success(tenant)
        : new TenantNotFound(tenantId).AsFailure<Tenant>();

What you get: The caller branches on the error value itself, so TenantNotFound keeps carrying its TenantId instead of being flattened into a message.

The core package has no dependencies: it ships the result type, its factories, and IResultValue without pulling anything else in.

Read Core Concepts →
Developer Results

Generate the failure helper for every union case

You model errors as a C# 15 union and need each case to become the failure side of a result without writing one conversion helper per case by hand.

csharp
[GenerateResult]
public readonly union TenantError(TenantNotFound, TenantDisabled, TenantAlreadyExists);

What you get: The generator emits AsFailure<TValue>() for every case of an annotated union, plus a code fix and a CA1815 suppression, so the declaration needs no pragma.

C# forbids the implicit conversion a bare case value would need — no operators in static classes, no conversion operators in extension members, one user-defined conversion per sequence — which is why the helper is per case.

Read Union Errors →
Architect Results

Map one error union onto HTTP responses

The same domain error union surfaces from many minimal-API endpoints, and you do not want a hand-written switch deciding the status code at each one.

csharp
builder.Services.AddResultsHttp(options => options
    .Map<TenantNotFound>(error => TypedResults.NotFound())
    .Map<TenantError>(error => TypedResults.Problem(statusCode: StatusCodes.Status409Conflict))
);

app.MapGet("/tenants/{id:int}", (int id) => GetTenant(id)).WithResultsHttp();

What you get: The mapping is declared once at startup, WithResultsHttp() applies it to the endpoints, and a host can replace IResultsHttpMapper when it needs different behaviour.

Mappings resolve in declaration order — any mapping or failure mapper the host declared earlier always wins — so the most specific rule is registered first.

Read ASP.NET Core Integration →
Team lead Results

Let ZodSharp validation failures become validation problems

Endpoints validate input with ZodSharp, and a failed validation should reach the client as the standard ASP.NET Core validation-problem payload rather than an error shape the API has to document separately.

json
{
  "title": "One or more validation errors occurred.",
  "status": 400,
  "errors": { "TenantId": ["Required field 'TenantId' is null"] },
  "issues": [{ "code": "missing_field", "path": ["TenantId"], "message": "Required field 'TenantId' is null" }]
}

What you get: A failure that implements IValidationErrorCarrier becomes HttpValidationProblemDetails without the host mapping it, unless a per-code or per-category rule answers that failure first.

The response is ASP.NET Core's own HttpValidationProblemDetails contract, so API clients keep the error shape they already parse.

Read ZodSharp Problem Details →
Architect Aspire ResourceKit

Typed, testable resource groups in a large AppHost

A large Aspire AppHost accumulates procedural resource wiring and configuration that is hard to test and easy to misconfigure.

csharp
[HostKit]
partial class ShopHostKit;

[ResourceDefinition<Projects.Example_Service>("api")]
partial class ApiResourceKit
{
    protected override IResourceBuilder<ProjectResource> BuildResource(
        IDistributedApplicationBuilder builder)
        => builder.AddProject<Projects.Example_Service>(Name);
}

What you get: Resource definitions become strongly typed, source-generated classes with generated host wiring and typed options.

One [HostKit] plus one [ResourceDefinition] per resource replaces procedural AppHost code, and the analyzer validates the wiring at compile time.

Read Examples: Generated vs Manual →
Team lead Aspire ResourceKit

Configure and toggle resources without editing the AppHost

You want enablement rules and configuration to be declarative and discoverable instead of buried in the AppHost entry point.

What you get: Typed options and enablement toggles are generated for each resource kit, so behaviour is configured rather than coded.

Resource kits can be unit tested with the testing helpers, independent of a running AppHost.

Read Configuration and options →
Developer AspireC4

A live architecture diagram with three lines of code

You already describe your distributed application in Aspire and do not want to maintain a separate architecture diagram that drifts from reality.

csharp
var builder = DistributedApplication.CreateBuilder(args);

builder.AddAspireC4();

builder.Build().Run();

What you get: AspireC4 writes the generated LikeC4 model, starts the LikeC4 sidecar, and refreshes the diagram whenever the Aspire application changes.

The diagram is derived from the running resource graph, so it cannot silently fall out of date the way a hand-drawn one can.

Read Dashboard Integration →
Architect AspireC4

Validate architectural metadata at compile time

You want tags, kinds, groups, and metadata in your architecture model checked before the application even runs.

What you get: A Roslyn source generator validates the architectural metadata while the AppHost compiles.

Architectural metadata mistakes fail the build instead of surfacing in a diagram nobody reads.

Read Generated Output →
Team lead Build

One reusable pipeline for every repository

You maintain several repositories that each repeat the same build, test, pack, and release logic, and the copies drift apart.

yaml
# .github/workflows/pr.yml
jobs:
  build:
    uses: purview-dev/build/.github/workflows/purview-build.yml@main
    secrets: inherit

What you get: Consumers reference the reusable workflow or composite action and configure behaviour with purview-build.json instead of owning pipeline source.

Pipeline code lives in one repository; a consuming repository is a short workflow file plus configuration.

Read Repository CI/CD →
Contributor Build

Dogfood the same pipeline the organisation uses

You want local commands, pull-request CI, and releases to run the exact same tool and conventions, rather than three approximations.

What you get: The pipeline is a Modular Pipelines .NET tool packaged as a pinned dotnet tool, callable from a composite action, reusable workflows, or the local command line.

Purview's own repositories use the published pipeline, so the tool is exercised on every build.

Read Pipeline Modules →
Developer OpenAPI XmlComments

Keep the generator on and filter only what collides

/openapi/v1.json answers 500 with "An item with the same key has already been added" because a type your API documents is also documented in more than one referenced project, and the only workaround you have found turns the XML-comment generator off.

xml
<!-- the project that calls AddOpenApi() -->
<PackageReference Include="Purview.OpenAPI.XmlComments" Version="1.0.0" PrivateAssets="all" />

What you get: Every colliding documentation ID is removed from the referenced documentation before compile, the generator runs on the filtered copies, and the description of every other endpoint and schema stays in the document.

Every occurrence of a colliding ID goes, not all but the first, because the API usually declares the injected type as well: keeping a reference's copy would still collide with it. A duplicated ID is ambient code rather than API surface, and a copy is only rewritten when its content changes, so a no-change build still skips CoreCompile.

Read the guide →
Developer OpenAPI XmlComments

List every colliding ID rather than the first one

The exception names one documentation ID, and the build says nothing about the rest, so you do not know whether one exclude is enough or whether the generator fails again on the next build.

powershell
pwsh skills/purview-openapi-xmlcomments-duplicates/scripts/find-duplicate-documentation-ids.ps1 `
  -Project path/to/Api

What you get: The script asks MSBuild for exactly the documentation files the generator reads and reports every colliding ID, where each copy comes from, whether the current configuration already handles it, and the item to add when it does not.

Each finding is classified: BetweenReferences is handled automatically by the package, while ReferenceAndProject needs the PurviewOpenAPIXmlCommentExclude item the script prints. It exits 0 when nothing would throw, 1 when something would, and 2 when it could not inspect the project.

Read Troubleshooting →
Team lead OpenAPI XmlComments

Fail the build on a collision instead of a 500 in production

The overlap is only visible after the API compiles, so a warning is easy to ship, and the failure then surfaces as a 500 on the OpenAPI document rather than as a red build.

xml
<PropertyGroup>
  <!-- fail the build instead of leaving the collision to run time -->
  <MSBuildWarningsAsErrors>$(MSBuildWarningsAsErrors);POAX001</MSBuildWarningsAsErrors>
</PropertyGroup>

What you get: POAX001 fails the build and names the exact PurviewOpenAPIXmlCommentExclude item to add, so an unhandled collision is a pull-request failure instead of a runtime error.

The check runs after CoreCompile and compares the API's fresh documentation file with the filtered reference documentation, which is the one case the before-compile pass cannot see: an ID documented in the API and in exactly one referenced project.

Read Diagnostics →
Architect OpenAPI XmlComments

One repository-wide reference that costs nothing at run time

Several API projects in the same repository reference the same generators, and you do not want per-project wiring or a build fix that becomes a runtime dependency.

xml
<!-- Directory.Packages.props: once for every project in the repository -->
<GlobalPackageReference Include="Purview.OpenAPI.XmlComments" Version="1.0.0" />

What you get: One declaration covers every project and does nothing in a project that does not reference Microsoft.AspNetCore.OpenApi, so libraries in the same repository need no exemption.

The package ships only props, targets and a netstandard2.0 task assembly under tasks/; lib/, ref/ and runtimes/ are forbidden by pack validation, so it adds no runtime dependency and copies nothing into the consumer's build output.

Read Configuration →
Team lead Build SDK

Apply repository-wide defaults from one declaration

You want standard .NET project defaults, code-style enforcement, test wiring, and central package management without repeating the same properties in every project.

json
{
  "msbuild-sdks": {
    "Purview.BuildSdk": "1.0.0"
  }
}

What you get: Install the SDK once via global.json and Directory.Build.props; every project beneath the repository root inherits everything automatically.

One versioned SDK declaration replaces per-project property groups, so conventions are upgraded in one place.

Read Configuration Reference →
Contributor Build SDK

Bootstrap a new repository

You are starting a repository and want the organisation's conventions in place before the first project exists.

What you get: The SDK can bootstrap a global.json at the repository root when one is missing, then applies project-type detection, analyzers, and test wiring.

Repository bootstrap, analyzers, and testing wiring are documented and generated, not copied between repos by hand.

Read Repository Bootstrap →
Developer AstroC4

A diagram and the prose around it in the same diff

A page explains a request path, and the diagram beside it lives in a design tool that nobody updates when the path changes, so the two disagree and a reviewer cannot see it.

mdx
````mdx
---
title: Request path
---

```likec4 title="Request path" height=360
specification { element box }
model {
  browser = box 'Browser'
  api = box 'API'
  store = box 'Postgres'
  browser -> api 'GET /orders'
  api -> store 'select'
}
views { view index { include * } }
```
````

What you get: The diagram is the page: the fence is compiled and laid out during the build, the layout is passed to the island as serialised JSON, and a change to the model is a line in the pull request a reviewer can read next to the prose.

The fence runs LikeC4.fromSource plus layoutedModel at build time, so nothing is laid out in the browser; a typo fails astro build with the file name and parser message rather than shipping a blank frame, and layouts are memoised by a hash of the snippet so a page re-rendered on every dev edit pays for it once. The same fence in a .md page stays a code block deliberately, because Astro cannot put a component there.

Read the guide →
Developer AstroC4

The same diagrams in a plain Astro site, without Starlight

The documentation site is plain Astro rather than Starlight, so a Starlight plugin would be inert there and the diagrams have no way to reach the page.

js
// astro.config.mjs
import { defineConfig } from 'astro/config';
import mdx from '@astrojs/mdx';
import expressiveCode from 'astro-expressive-code';
import astroc4 from '@purview-dev/astroc4/integration';

export default defineConfig({
  integrations: [astroc4(), expressiveCode(), mdx()],
});

What you get: The same <LikeC4View> component and likec4 fences work without Starlight: the integration compiles the site's .c4 model, appends the fence transform to the Markdown processor, and pre-bundles what the React island needs. The site keeps the parts that are its own decision — @astrojs/mdx and, when it wants c4 highlighting, Expressive Code with an ec.config.mjs that registers likec4Language.

Both entry points call the same likec4Integration(): the plain-Astro example in the repository builds with astro check and astro build, and its dev server is driven in a browser to prove the island hydrates. @astrojs/react is the one integration AstroC4 adds itself when the site has not — the islands are client:only="react" — and React is not added twice when the site already configures it. What a plain site gives up is documented: Astro.locals.t is Starlight's, so the components render English, and the highlighting option exists only on the Starlight plugin.

Read the guide →
Developer AstroC4

Highlighting that follows LikeC4, with no ec.config.mjs

You want c4 and likec4 fences coloured in your docs, but Shiki has no LikeC4 grammar and the community TextMate file is missing the shapes and keywords upstream added this year.

js
// astro.config.mjs — there is no ec.config.mjs anywhere in the site
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';
import react from '@astrojs/react';
import astroc4 from '@purview-dev/astroc4';

export default defineConfig({
  integrations: [
    starlight({ plugins: [astroc4({ highlighting: { ref: 'v1.60.0' } })] }),
    react(),
  ],
});

What you get: The plugin derives a TextMate grammar from likec4/likec4's Langium language definition and injects it into Starlight's Expressive Code options from the config:setup hook, so every LikeC4 fence is coloured and an existing ec.config.mjs keeps its own languages untouched.

Only the word lists are generated; the structure (comments, triple-quoted strings, #tag versus #hex, tech:astro icons, -[https]-> connectors) is a curated layer on top. The difference is testable: ElementShape gained agent after v1.59.4, so a build pinned to that tag paints agent as a plain identifier while main paints it as a shape. Expressive Code concatenates shiki.langs, which is why a site with its own grammar ends up with both.

Read the guide →
Architect AstroC4

One model in the repository, many diagram views in the docs

Several documentation pages describe different slices of the same system, and you want them to read from one model so a change to a dependency cannot leave three diagrams telling three stories.

mdx
```mdx
---
title: Deployment
---

import LikeC4View from '@purview-dev/astroc4/components/LikeC4View.astro';

<LikeC4View viewId="production" projectId="platform" height={560} />
```

What you get: The .c4 model lives in src/likec4 and each page selects a view of it; the model is compiled once by LikeC4's Vite plugin, and every page hydrates the same islands, so a view cannot describe a system the model does not contain.

The plugin compiles every likec4.config.json project under the site root into likec4:model, likec4:icons and likec4:projects virtual modules, and the first project found is the default for a view that omits projectId — which is also the failure mode, since a vendored example model can silently become the default. An unresolvable element kind fails the build instead of rendering a partial diagram.

Read the guide →
Team lead AstroC4

Prove the diagrams actually hydrate before calling the docs built

A static build exits 0 even when every island fails to hydrate, so the pipeline is green and the published page shows empty frames.

shell
bun run build
bun scripts/smoke.ts http://localhost:4321
bun run test:site

What you get: The browser smoke test and the packed-consumer build are the evidence: one drives a real page and checks hydration, icons, highlighting and translations, the other installs the tarball into a throwaway Starlight site so publishing mistakes surface before npm does.

The smoke test asserts at least four distinct colour variables per highlighted block, counts prerendered pack icons and <img> icons, and fails on a file:// URL in an <img src> — the build-machine path that LikeC4's imageAliases bakes into the bundle. test:site catches the cases the playground cannot see: a file missing from files, an exports subpath pointing at an unpublished file, or an undeclared peer dependency.

Read Troubleshooting →
Contributor AstroC4

Regenerate the grammar instead of hand-editing it

Upstream LikeC4 adds a shape or a keyword, and the highlighting has to follow without someone patching a TextMate JSON file and hoping the next release does not overwrite it.

shell
bun run grammar:sync                 # from main
bun run grammar:sync --ref v1.60.0   # or pin the tag you ship against
bun run grammar:check                # fail if the committed snapshot is stale

What you get: The Langium snapshot and the TextMate grammar are generated artefacts: the working tree says so, grammar:check fails when they drift from the pinned ref, and the next upstream addition reaches highlighting without a code change.

src/grammar/likec4.tmLanguage.json is re-derived from the committed Langium text on every run (single-digit milliseconds), and snapshot.test.ts re-derives it again and compares, so a change to the derivation that is not followed by a regeneration fails bun run test. Because the icon packs come from LikeC4's LIB_ICON terminal, a pack upstream adds is highlighted and rendered without an edit here either.

Read the guide →
Developer Logging Source Generators

Move to the supported successor

You depend on the original interface-based logging generator and want logging, activities, and metrics generated together.

What you get: Telemetry SourceGenerator generates logging alongside Activities and Metrics from the same interfaces, with DI registration and multi-targeting.

This project is archived and no longer developed; the successor covers a superset of its behaviour from one interface.

Developer Architests

The whole rule set from a policy file and one derived class

You want your layering enforced by the build, but you do not want to hand-write the same dependency-direction and forbidden-reference tests in every repository.

csharp
// .config/architecture-policy.json declares the responsibilities.
// This is the entire test suite.
[InheritsTests]
public sealed class ArchitectureTests : PurviewArchitectureTests;

What you get: One policy file plus one derived test class is the whole suite. Each rule is a separate test, so a failure names the rule rather than collapsing the set into one assertion.

The base class ships twelve rule ids as separate [Test]s — graph discovery, naming, discouraged name, dependency matrix, assembly matrix, sibling independence, composition boundary, forbidden package, forbidden framework, cycle, test reference and waiver integrity — plus a schema-validation test that runs first. [InheritsTests] is required: without it TUnit discovers nothing, the run is green and nothing is enforced, which TUnit's own analyzer reports as TUnit0030.

Read Getting started →
Developer Architests

Catch a type-level dependency a ProjectReference never shows

A project file only shows declared ProjectReferences. A type that arrives transitively through another project, or through a package, is invisible to a project-level check.

json
"assemblyRules": {
  "enabled": true,
  "assemblyRoots": [],
  "assemblyGlobs": ["*.dll"]
}

What you get: The same mayDependOn/mustNotDependOn matrix is applied to the types each compiled assembly actually references. An empty assemblyRoots scans the test output directory, which already holds every project the test project references.

The reader opens each assembly with System.Reflection.Metadata and walks the TypeReference table — nothing is loaded, executed, or resolved through a probing path, so a type initialiser never runs. Enabling the rule with no production assemblies found is a failure, not a silent pass.

Read Type-level rules →
Architect Architests

A dependency the policy is silent about is a violation, not permission

Your layering is agreed and documented, and you want a reference that points the wrong way to fail the build rather than erode the design one reasonable-looking reference at a time.

json
{
  "version": 2,
  "sourceRoots": ["src"],
  "responsibilities": [
    {
      "name": "Domain",
      "category": "domain",
      "purpose": "The domain model, its invariants and its rules.",
      "mayDependOn": [],
      "mustNotDependOn": ["Application", "Persistence", "Composition"]
    }
  ]
}

What you get: The matrix is applied three ways: the same responsibility is always allowed, mustNotDependOn is a violation, and a reference the matrix neither permits nor forbids is also a violation — so a gap in the policy is surfaced instead of passing.

A project name is classified by its first segment only, so Persistence.SqlServer and Persistence follow the same rules and qualification is a naming choice rather than a different set of rules.

Read Policy reference →
Team lead Architests

A reviewed waiver instead of switching a rule off

One project legitimately departs from the architecture policy, and you do not want to answer that by disabling the rule for the whole repository.

json
{
  "waivers": [
    {
      "project": "Persistence.Legacy",
      "mapsTo": "Persistence",
      "rules": ["forbiddenPackage"],
      "reason": "The legacy EF6 store is being replaced and still needs EntityFramework.",
      "reviewedOn": "2026-10-16"
    }
  ]
}

What you get: The departure is per project, carries a reason and a review date, keeps every other rule in force, and is itself checked. SkipRule opts a whole repository out with no record, so a waiver is the narrower choice.

Any rule id may be waived, including siblingIndependence and assemblyDependencyMatrix, but an unknown id is a waiverIntegrity failure — a typo cannot silently excuse nothing — and only graphDiscovery and waiverIntegrity are not waivable.

Read Policy reference →
Contributor Architests

Add a bespoke rule to the same reporting and waiver model

You need a repository-specific check — a banned API, a required convention — and do not want a second architecture framework to maintain alongside the standard set.

csharp
[InheritsTests]
public sealed class ArchitectureTests : PurviewArchitectureTests
{
    protected override IReadOnlyList<IArchitectureRule> AdditionalRules => [new NoConsoleLoggingRule()];

    sealed class NoConsoleLoggingRule : IArchitectureRule
    {
        public string Rule => "noConsoleLogging";

        public IReadOnlyList<ArchitectureViolation> Evaluate(ArchitectureContext context) =>
            context.Projects.Values
                .Where(project => !project.IsTestProject)
                .Select(project => new ArchitectureViolation(Rule, project.Name, "Console logging is banned here."))
                .ToArray();
    }
}

What you get: An additional rule runs as its own test, honours SkipRule by its rule id, and is excused by a matching waiver without any extra plumbing — the same reporting the built-in rules use.

The evaluator takes the parsed policy, the project graph and the assemblies as constructor arguments, so a rule is testable as a small in-memory fixture rather than a repository on disk — which is how the package's own rules are tested.

Read Extending →
Developer Containers

The same test on WSL Containers or Docker

Your integration suite needs real infrastructure, but the machines it runs on differ: a Windows developer laptop with WSL Containers and a Linux CI runner with a Docker daemon.

csharp
await using var container = new ContainerBuilder()
    .WithImage("docker.io/library/redis:latest")
    .WithPortBinding(6379, assignRandomHostPort: true)
    .WithWaitStrategy(Wait.ForTcpPort(6379))
    .Build();

await container.StartAsync();
ushort port = container.GetMappedPublicPort(6379);

What you get: The test never names a backend. Automatic selection prefers WSLC where it is usable and falls through to Docker everywhere else; PURVIEW_CONTAINERS_BACKEND pins one (wsl or docker) when a job should fail loudly instead of falling back.

One API, two backends: the same builder, wait strategies, and connection-string helpers run on both Purview.Containers.Wsl and Purview.Containers.Docker with no code change.

Read Backends: WSL Containers or Docker →
Developer Containers

Zero-config tests that pick a backend themselves

You want real PostgreSQL and Redis in your tests and would rather not choose a container runtime, add a backend package explicitly, or write any registration or environment configuration.

csharp
await using var postgres = new PostgreSqlBuilder().WithDatabase("app").Build();
await postgres.StartAsync();                         // waits for pg_isready

await using var connection = new NpgsqlConnection(postgres.GetConnectionString());
await connection.OpenAsync();

What you get: Add the umbrella Purview.Containers to a plain net10.0 project: each backend package's buildTransitive assets generate the registration in your assembly, so WSLC is used on a Windows machine and Docker everywhere else with no code or configuration.

Each backend package ships buildTransitive assets that generate a module initializer in the consumer's assembly, so no registration line and no environment variable are required; those assets flow transitively through the umbrella.

Read Using it in your tests (auto) →
Developer Containers

A typed service module instead of a bare image

You need a throwaway PostgreSQL (or Redis, SQL Server, MySQL, RabbitMQ, Azurite, NATS) and do not want to look up its image, port, environment, and readiness probe every time.

csharp
await using var postgres = new PostgreSqlBuilder()
    .WithDatabase("tests")
    .WithPassword("postgres")
    .Build();

await postgres.StartAsync();   // returns once pg_isready succeeds

What you get: The module supplies the default image, port mapping, and readiness wait strategy, so StartAsync() returns once the instance is genuinely ready, and GetConnectionString() points at the mapped host port — the same shape Testcontainers modules use.

Seven service modules ship (PostgreSQL, Redis, SQL Server, MySQL, RabbitMQ, Azurite, NATS), and a module contributes only its image, ports, environment, wait strategy, and connection string — never the shared runtime.

Read Modules →
Architect Containers

One Windows prerequisite, Docker in CI

You want integration tests that use real infrastructure on Windows developer machines and CI agents, without making Docker Desktop a requirement of the minimum Windows toolchain.

csharp
foreach (var backend in await ContainerBackends.ProbeAllAsync())
{
    Console.WriteLine($"{backend.Name}: usable={backend.IsUsable} version={backend.Version}");
}

What you get: The abstractions and modules are portable net10.0, so a platform-neutral project binds the WSLC facade on Windows and behaves as Docker-only everywhere else; ProbeAllAsync() reports exactly which runtime a machine has before a test runs.

Purview.Containers.Wsl ships a portable net10.0 facade and a net10.0-windows10.0.19041.0 implementation, and the repository builds twenty-one throwaway consumer projects to prove the target-framework contract and the PCC0001/PCC0002 guards.

Read Consumer Requirements →
Contributor Containers

Add a service module

You want to add a module for another service, or fix one of the existing seven, and need to know exactly what a module is allowed to contribute.

What you get: A module supplies only the default image, ports, environment, its own WithXxx configuration, a wait strategy, and connection-string helpers; the generic builder snapshots the accumulated state into an immutable configuration, so modules never duplicate container runtime infrastructure.

Every module references Purview.Containers.Core only — never a backend package — which is what lets one module package run on WSLC or Docker, and each module has its own unit and integration test project to prove itself.

Read Contributing a module →
Developer Engineering Playbook

A repository that satisfies every convention on its first build

You are starting a repository and want the project defaults, code style, test wiring and assembly identity to be right from the first commit, instead of discovering the conventions one review comment at a time.

json
{
  "sdk": { "version": "LATEST", "allowPrerelease": false },
  "msbuild-sdks": { "Purview.BuildSdk": "LATEST" },
  "test": { "runner": "Microsoft.Testing.Platform" }
}

What you get: A pinned SDK plus a Directory.Build.props that sets one namespace prefix is the whole of the repository's build configuration. Every project beneath it inherits the target framework, language version, nullable context, analyzers and assembly identity, so a project file is two lines and a test project file is empty. LATEST is the playbook's own placeholder for the newest version the runtime supports — the file requires a number, so the snippet shows a lookup rather than a claim that expires with the next release.

Getting Started walks the steps in the order you would create the files, and every repository-level file has a copy-paste version in the templates folder with a comment explaining the one thing about it that is easy to get wrong.

Read Getting Started →
Architect Engineering Playbook

Architecture that fails the build when a dependency points the wrong way

Your layering is documented and agreed, and you want it to stay true — rather than being eroded one convenient project reference at a time, each of which looks reasonable in isolation.

csharp
[Test]
public async Task Application_GivenItsReferences_DependsOnTheDomainAndNotOnInfrastructure()
{
    // Arrange
    var application = typeof(ConventionCatalogue).Assembly;

    // Act
    var referenced = ReferencedAssemblyNames(application);

    // Assert
    await Assert.That(referenced).Contains($"{RepositoryPrefix}.Domain");
    await Assert.That(referenced).DoesNotContain($"{RepositoryPrefix}.Infrastructure");
}

What you get: The allowed dependency directions are data in a test that reads the compiled assemblies' metadata references, so a reference that points the wrong way fails the build with the offending assembly named — no diagram to keep in step and no separate tool to run.

The reference implementation's Architecture.UnitTests project asserts four rules against three real assemblies and is built by the same pipeline as everything else. The page also records the two traps found by writing it, including a source generator that emits public types into its own namespace.

Read the guide →
Team lead Engineering Playbook

A verification gate that stays credible

The pull-request build has started needing a database and four minutes of waiting, and somebody is about to make it optional — at which point nothing is gated at all.

json
{
  "Build": {
    "Solution": "src/Acme.slnx",
    "TestRoot": "src/tests",
    "TestPatterns": "*UnitTests.csproj",
    "TestFilter": "/*/*/*/*[Category=Unit]"
  }
}

What you get: Tiers are expressed by where a test lives rather than by an attribute: the SDK reads the test project's name suffix and emits the assembly-level category the pipeline filters on, so adding a slow suite keeps it out of the fast tier without editing a filter or remembering an attribute.

The verification model page documents the shared workflow's inputs, the configuration probe order, and the two ways a repository and the shared workflow quietly disagree about what a green build means — and names the repository that runs its container-backed suites as a second job on the same runner.

Read the guide →
Developer Engineering Playbook

One builder for every test's domain content

You are writing a test, need a domain object, and do not want to spell out a constructor that will change — nor leave the reader guessing which of the values you passed actually matter to the assertion.

csharp
public static Domain.Convention Convention(
    Domain.ConventionId? id = null,
    string? title = null,
    VerificationTier? tier = null,
    bool? enforcedByBuild = null) =>
    Domain.Convention.Create(
        id ?? ConventionId(),
        title ?? Faker.Lorem.Sentence(4),
        tier ?? Faker.Random.Enum<VerificationTier>(),
        enforcedByBuild ?? Faker.Random.Bool());

What you get: An omitted argument is generated and a supplied argument is used exactly, so a test reads as a list of the values it is actually proving and everything else is realistic without the test saying so. One constructor change is one edit rather than a repository-wide one.

TestBuilder lives in a shared testing project the SDK references from every test project automatically. The page also explains the two SDK rules that shaped its flat, ungrouped shape, and the value-object exception where a test must name the rejected input itself.

Read the guide →
Contributor Engineering Playbook

A repository an agent can work in without hand-holding

You want a coding agent to make a change that follows the repository's conventions rather than confidently generalising from whichever pattern it found first.

markdown
| Path | Purpose |
| -- | -- |
| src/src/Domain | The reference implementation's value objects and aggregate |
| src/src/Application | The port and the service that owns the rules |
| src/tests/Architecture.UnitTests | Dependency-direction rules; a wrong reference fails the build |

What you get: AGENTS.md states the purpose, the layout, the conventions and the definition of done, and the build mirrors the SDK's own skills into the repository so the agent-facing guidance tracks the SDK version rather than the repository's memory of it.

The agent enablement page documents the layout of the agent folder, why the SDK's mirror writes a generated .gitignore that lists exactly the files it owns, and why the guidance that makes a repository obvious to an agent is the same guidance that makes it obvious to a new joiner.

Read the guide →
Architect Engineering Playbook

Take only the part of the playbook that fits

You are convinced by some of the conventions and not others, and you want to know which ones are worth the cost in a repository the size of yours — rather than adopting everything and discovering the ceremony.

What you get: Three profiles — one project, a few layers, several packages — each list what to take and what to leave, and every page ends with an "at your scale" section that names the smaller version of the rule explicitly. The templates are mapped to the profile that needs them.

The playbook also documents what not to adopt early, with the reason each one is more expensive out of order, and a migration order for an existing repository that keeps each step cheap and the build green.

Read the guide →
Team lead Engineering Playbook

Data that crosses a boundary once, and is trusted after that

Inbound payloads are validated in several places, an identifier is a string in one layer and a type in another, and expected failures are thrown as exceptions that callers catch by message.

csharp
[Scalar]
public readonly partial record struct EmailAddress
{
    public string Value { get; }

    static partial void OnNormalize(ref string value) => value = value?.Trim().ToLowerInvariant()!;
}

What you get: A value is a type rather than a primitive, Create validates at the boundary and Hydrate trusts everything past it, normalisation runs before validation so there is exactly one canonical form, and expected failures are values while exceptional circumstances still throw.

The contracts page names the three public repositories that implement the rules — source-generated value objects, result types with union errors, and a schema layer that also exports and imports JSON Schema — and shows how a validation result is read rather than parsed.

Read the guide →
Contributor Engineering Playbook

Extend the playbook without turning it into a second source of truth

You have found a convention that is real, enforced and not written down, and you want to add it without duplicating something the SDK already documents.

What you get: Four tests decide whether a rule belongs: it came from a real repository and a real failure, it is reusable at more than one size, it is not the SDK's to state, and it is either enforced or explicitly labelled a review obligation.

The contributing page also sets the expectations for changing an existing rule — update every page that states it, check the reference implementation still demonstrates it, and re-check whether the enforcement moved between the build and review.

Read the guide →
Developer PM Skills

Capture a bug or an idea in one line, mid-task

You are in the middle of an implementation when you spot an unrelated bug, or an idea arrives that you cannot act on now but do not want to lose.

plaintext
park this: the export button does nothing in Safari

Parked: planning/inbox/2026-11-01-0912-export-button-safari.md (bug). Back to step 3.

What you get: One inbox file is written under the configured planning directory and the reply is a single line, so the agent resumes the step it was on. Only capture (pm-park, pm-risk) and checkpoint writes may run during an active workflow, so nothing else interrupts the build.

pm-park writes in the main worktree rather than the current feature worktree, and its Output section allows exactly one line plus — only when no workflow is active — a single choice question, Shape "<title>" now, or keep it parked?, whose recommended answer is to keep it parked.

Read the guide →
Team lead PM Skills

A board and a roadmap that come from the same files

You want to see what is in progress, what the agent will pick up next, and what is waiting on you, without maintaining a second copy of the plan in a tracker.

markdown
| Column | ID | Title | Owner | Size | Detail |
| --- | --- | --- | --- | --- | --- |
| Now | R-007 | Tenant billing | agent | M | execute, 4/9 steps |
| Next (agent) | R-008 | Invoice email | agent | S | ready |
| For you | R-009 | Open a Stripe account | user | S | blocks R-008 |
| Waiting | R-010 | Usage export | agent | M | needs R-008 |
| Done | R-006 | Tenant model | agent | M | 2026-10-28 |

What you get: pm-board, pm-roadmap, and pm-status render the task board, the milestone roadmap, or just your own queue from the same state files the agent works from, and viewing is read-only: asking for the board or the status never changes the plan.

The board's "For you" column is every Owner: user item in Next plus the open questions, and "Waiting" names the blocking item — the same roadmap items pm-next claims work from, so the board cannot drift from what is actually being built.

Read the guide →
Architect PM Skills

The idea is challenged before it reaches the roadmap

An idea sounds obviously good, and you want it argued with — the alternatives, the ramifications across data, security, performance, cost and maintenance, and the smallest version that still delivers the outcome — before it becomes work.

markdown
## Who and evidence
## Alternatives considered
## Challenges and answers
## Ramifications
## Proposal
## Done when
## Open questions
## Decision

What you get: A brief is written to the planning directory after every answer, so the discussion survives compaction and a later session resumes it from the first empty heading, and the run ends with one decision: add to Next, add to Later, build it now, keep it parked, or drop it.

pm-shape writes at least three alternatives — do nothing, the smallest version, and the full idea — and completes a ramifications row for each of the eight Challenge protocol areas, writing "none found" rather than leaving one out; a dropped idea appends its reason to Dropped in LOG.md.

Read the guide →
Contributor PM Skills

Add a skill without breaking the consistency checks

You want to add a new pm-* skill, and the repository has to stay consistent: the README table, the managed section, the pm-setup inventory and the pm-help guide all have to describe the same set.

bash
just validate
just lint-check

What you get: Adding a skill is a directory plus the four listings that reference it. just validate checks skill frontmatter, the README and managed-section tables, the pm-setup inventory, the section markers and the template placeholders, and fails when one listing is missed.

CI runs the same checks on every push and pull request to main, and lefthook runs commitlint on commit and just lint-check on push, so a half-registered skill cannot be merged.

Read the guide →

Looking for the tools themselves?

Browse the project catalogue for the full family, or the documentation portal for the complete guides behind each example.