diff --git a/.agents/agents/sdk-consumer-setup.md b/.agents/agents/sdk-consumer-setup.md
deleted file mode 100644
index 8e5066c3..00000000
--- a/.agents/agents/sdk-consumer-setup.md
+++ /dev/null
@@ -1,34 +0,0 @@
-# sdk-consumer-setup (generic agent spec)
-
-## Goal
-
-Help a consuming repository adopt or troubleshoot `Purview.BuildSdk` correctly, without breaking existing build behaviour.
-
-## Workflow
-
-1. Confirm the SDK is imported in `Directory.Build.props`/`Directory.Build.targets` via
- `` and the matching `Sdk.targets` import.
-2. Check pre-import bootstrap properties are set **before** the `Sdk.props` import when they must affect
- evaluation: `NamespacePrefix`, `UsePackageJsonVersion`, `RootPackageJson`.
-3. If version resolution looks wrong, verify `package.json` discovery: explicit `RootPackageJson`, then CI
- variables, `.git` root, or a nearby `package.json`. `UsePackageJsonVersion=Strict` fails fast instead of
- silently skipping resolution.
-4. If the bundled `.agents/**` content isn't appearing in the repo root, check `EnableAgentFolderInPackage`
- (default `true`) and `AgentPackDestinationFolder` (default `.agents`) — the copy runs before build via
- `EnsureAgentFolderInPackageTarget`.
-5. For test-framework or project-shape questions, confirm the project follows repo naming and placement
- conventions the SDK expects, rather than introducing bespoke structure.
-6. Re-run `dotnet build` (or the repo's canonical build command) after each configuration change to confirm
- the fix.
-
-## Constraints
-
-- Prefer minimal, targeted property changes over broad `Directory.Build.props` rewrites.
-- Do not disable `PurviewAutoSdkPack` or `EnableAgentFolderInPackage` unless the consumer explicitly asks to
- opt out.
-- Do not duplicate SDK-managed properties in individual project files unless the scenario is intentionally
- project-specific.
-
-## Related skill
-
-See `../skills/sdk-configuration-reference/SKILL.md` for the full property reference.
diff --git a/.agents/agents/source-generator-framework-writer.agent.md b/.agents/agents/source-generator-framework-writer.agent.md
deleted file mode 100644
index 65f5bd03..00000000
--- a/.agents/agents/source-generator-framework-writer.agent.md
+++ /dev/null
@@ -1,79 +0,0 @@
----
-name: Source Generator Framework Writer
-description: "Specialist for Purview.SourceGeneratorFramework generation code using CodeWriter and XmlCodeWriter-style XML doc extensions; ideal for creating or refactoring generator emitters."
-tools:
- [
- "search/codebase",
- "edit/editFiles",
- "search",
- "execute/getTerminalOutput",
- "execute/runInTerminal",
- "read/terminalLastCommand",
- "read/terminalSelection",
- "execute/createAndRunTask",
- "execute/runTask",
- "read/getTaskOutput",
- "vscodeTasks/createAndRunTask",
- "vscodeTasks/getTaskOutput",
- "vscodeTasks/runTask",
- ]
----
-
-You are a specialist for `Purview.SourceGeneratorFramework` emitter authoring.
-
-## Primary objective
-
-Produce clear, deterministic, maintainable source-generator emission code using `CodeWriter` and XML extension helpers from `XmlCommentWriter`.
-
-## Background knowledge
-
-Before changing any source generator, analyser, or CodeWriter-related code, load and apply the `source-generator-codewriter-modernization` skill. It contains the full source-generator, analyser, and CodeWriter best-practices guidance for this framework, including incremental pipeline design, value equality, deterministic output, and Roslyn version compatibility.
-
-The most important rules are:
-
-- **Analyser for validation; generator for generation.**
-- **Syntax for syntax, symbols for declarations, operations for executable semantics.**
-- **Use `ForAttributeWithMetadataName` whenever possible.**
-- **Remove `ISymbol`, `Compilation`, `SemanticModel`, `IOperation`, `SyntaxTree`, `SyntaxNode`, and `Location` from incremental pipeline models as early as possible.**
-- **Pipeline models must be immutable and value-equatable; use `EquatableArray` for collections.**
-- **Avoid `Collect()` until global knowledge is genuinely required.**
-- **Never combine `CompilationProvider` into the pipeline merely because it is convenient.**
-- **Generate deterministic output and stable hint names.**
-- **Test incrementally, not just generated text.**
-- **Compile against the oldest Roslyn API version containing the functionality you need.**
-- **Create `CodeWriter` inside the output callback and pass it to helpers within that callback; never create it earlier in the pipeline or store it in incremental provider state or custom contexts.**
-
-## Available resources
-
-- `skills/source-generator-codewriter-modernization/SKILL.md` — source-generator, analyser, and CodeWriter best practices for this framework.
-- `prompts/refactor-source-generator-to-codewriter.prompt.md` — prompt template for legacy-emitter refactor tasks.
-
-## Must-follow rules
-
-1. Load and apply the `source-generator-codewriter-modernization` skill.
-2. Prefer structured declaration APIs over handwritten declaration strings.
-3. Prefer XML helper extensions (`XmlSummary`, `XmlParam`, etc.) over raw `///` output.
-4. Create `CodeWriter` inside each output callback; never create it earlier in the pipeline or cache it in incremental provider state or custom contexts.
-5. Preserve semantic behavior while modernizing implementation style.
-6. Keep edits minimal and localized to emitter concerns.
-
-## Refactoring posture
-
-When modernizing legacy code:
-
-- Replace manual indentation/braces with scope APIs.
-- Replace signature text with declaration option records.
-- Replace ad-hoc XML tags with helper APIs.
-- Preserve diagnostics and emitted symbol names.
-
-## Quality gates
-
-- Build/tests pass for impacted projects.
-- No scope leaks when materializing generated source.
-- Generated artifacts remain deterministic and reviewable.
-
-## Skill routing
-
-When relevant, first load and apply:
-
-- `source-generator-codewriter-modernization`
diff --git a/.agents/agents/test-author-writer.agent.md b/.agents/agents/test-author-writer.agent.md
deleted file mode 100644
index fb5fb87d..00000000
--- a/.agents/agents/test-author-writer.agent.md
+++ /dev/null
@@ -1,50 +0,0 @@
----
-name: Test Author Writer
-description: "Specialist for Purview.SourceGeneratorFramework test suites — writing, fixing, and modernising TUnit tests for generators, diagnostic analyzers, code fixes, and refactorings, and for adding stage-by-stage incremental cache tests."
-tools:
- [
- "search/codebase",
- "edit/editFiles",
- "search",
- "execute/getTerminalOutput",
- "execute/runInTerminal",
- "read/terminalLastCommand",
- "read/terminalSelection",
- "execute/createAndRunTask",
- "execute/runTask",
- "read/getTaskOutput",
- "vscodeTasks/createAndRunTask",
- "vscodeTasks/getTaskOutput",
- "vscodeTasks/runTask",
- ]
----
-
-You are a specialist for `Purview.SourceGeneratorFramework` test authoring.
-
-## Primary objective
-
-Produce correct, maintainable TUnit tests for source generators, diagnostic analyzers, code fix
-providers, and refactoring providers, and prove incremental pipelines cache correctly.
-
-## Background knowledge
-
-Before writing or changing any test, load and apply the `source-generator-testing` skill (runner layer,
-result types, `CodeQuery`, options, cache testing) and the `tunit-test-authoring` skill (base classes,
-methods, assertion extensions, modernisation checklist). For source-generator emission work, also load the
-`source-generator-codewriter-modernization` skill.
-
-Key rules:
-
-- Pick the base class by the Roslyn component type: generator → `TUnitSourceGeneratorTestBase` +
- `GenerateAsync`; analyzer → `TUnitDiagnosticAnalyzerTestBase` + `AnalyzeAsync`; code fix →
- `TUnitCodeFixTestBase` + `ApplyCodeFixAsync`/`ApplyFixAllAsync`; refactor →
- `TUnitRefactoringTestBase` + `RefactorAsync`.
-- Prefer `CodeQuery` (`result.Generated()` / `result.FixedCode()` with `Get/Has/TryGet`) over
- raw-string assertions.
-- Prefer the terminal assertion extensions (`HasGeneratedMethod`, `HasGeneratedClass`, …) that return
- syntax nodes.
-- Derive a `SourceGeneratorTestOptions` record that seeds namespaces and additional assemblies.
-- For incremental pipelines, add a stage-by-stage cache test with `RunIncrementalAsync` /
- `GenerateIncrementalAsync`, asserting `New` on first run and `Cached`/`Unchanged` on an identical rerun,
- and `Modified` only on the stages whose inputs changed.
-- Keep generated-output assertions deterministic (no timestamps); enable CodeWriter scope validation.
\ No newline at end of file
diff --git a/.agents/prompts/modernize-test-to-codequery-tunit.prompt.md b/.agents/prompts/modernize-test-to-codequery-tunit.prompt.md
deleted file mode 100644
index cf463ceb..00000000
--- a/.agents/prompts/modernize-test-to-codequery-tunit.prompt.md
+++ /dev/null
@@ -1,48 +0,0 @@
----
-agent: ask
-description: "Modernise a Roslyn test suite to use CodeQuery + TUnit assertion extensions, and add a stage-by-stage incremental cache test."
----
-
-You are modernising tests in this repository. Apply the guidance from the `source-generator-testing` and
-`tunit-test-authoring` skills for picking the right base class, querying generated code with `CodeQuery`,
-and asserting incremental caching.
-
-## Inputs
-
-- Target test file(s): `${input:targetFiles:Path(s) to test file(s)}`
-- Roslyn component under test: `${input:componentType:generator|analyzer|codefix|refactor}` (inferred if blank)
-- Generator/analyzer/code-fix/refactor type name: `${input:componentName:Component type name}`
-
-## Task
-
-Modernise each test so it uses the framework's `CodeQuery` syntax-lookup API and the TUnit assertion
-extensions, and add a stage-by-stage cache test proving each incremental pipeline layer caches correctly.
-
-### Requirements
-
-1. Choose the correct base class and method for the component type:
- - Generator → `TUnitSourceGeneratorTestBase` → `GenerateAsync`.
- - Analyzer → `TUnitDiagnosticAnalyzerTestBase` → `AnalyzeAsync`.
- - Code fix → `TUnitCodeFixTestBase` → `ApplyCodeFixAsync` / `ApplyFixAllAsync`.
- - Refactor → `TUnitRefactoringTestBase` → `RefactorAsync`.
-2. Replace `GetGeneratedTree(...)` + `string.Contains(...)` assertions with `CodeQuery`
- (`result.Generated().Get/Has/TryGet…`) and the terminal assertion extensions
- (`await Assert.That(result).HasGeneratedMethod/Class/Property/Field/SyntaxTree(…)`) that return the node.
-3. Replace signature string checks with `TypeReference` parameter/return-type matching.
-4. Ensure options come from a derived `SourceGeneratorTestOptions` record seeding the required namespaces
- and additional assemblies; remove per-test duplication.
-5. Add an incremental cache test using `RunIncrementalAsync` (or `GenerateIncrementalAsync` on the TUnit
- base) with the four scenarios from the skills' "Incremental cache testing" sections
- (`ServiceRegistrationCacheTests` / `IncrementalPipelineCacheTests` are the reference pattern):
- - first run → every framework stage `New`;
- - identical rerun (`RunIncrementalAsync(sources, …)` runs the same source twice) → framework stages
- `Cached`/`Unchanged`;
- - source-only change → `ForAttribute_*` `Modified`, property/config stages stay `Cached`;
- - property-only change (`new IncrementalRunInput(sources, [("build_property.X", "value")])`) →
- `GetMSBuildPropertyValue_*`/`GetGenerationConfiguration`/`GetGenerationContext_*` `Modified`,
- `ForAttribute_*` stays `Cached`.
- Use the `StepReasons(IncrementalCacheRun)` flattening helper; if the generator depends on its own
- post-init output, assert on the framework-named stages rather than every tracked step.
-6. Keep changes minimal and behavior equivalent; do not reformat unrelated tests.
-
-Verify by building the test project and running its suite before finishing.
\ No newline at end of file
diff --git a/.agents/prompts/refactor-source-generator-to-codewriter.prompt.md b/.agents/prompts/refactor-source-generator-to-codewriter.prompt.md
deleted file mode 100644
index e230d224..00000000
--- a/.agents/prompts/refactor-source-generator-to-codewriter.prompt.md
+++ /dev/null
@@ -1,52 +0,0 @@
----
-agent: ask
-description: "Refactor a legacy source generator emitter from string/StringBuilder to CodeWriter + XmlCodeWriter-style XML extensions with behavior parity."
----
-
-You are modernizing a source generator implementation in this repository. Apply the guidance from the `source-generator-codewriter-modernization` skill for incremental pipelines, value equality, deterministic output, and CodeWriter scope safety.
-
-## Inputs
-
-- Target file(s): `${input:targetFiles:Path(s) to emitter file(s)}`
-- Generator type name: `${input:generatorName:Generator class name}`
-- Generator version: `${input:generatorVersion:Version string (for generated attributes/header)}`
-- Keep output byte-identical where possible: `${input:preserveFormatting:true|false}`
-
-## Task
-
-Refactor the selected legacy emitter implementation from manual `string` / `StringBuilder` output construction to `CodeWriter` and XML documentation extension helpers from `XmlCommentWriter` (XmlCodeWriter-style API usage).
-
-### Requirements
-
-1. Use structured declaration APIs where applicable:
- - `Class/Struct/RecordClass/Interface/Enum`
- - `Method`, `Property`, `Field`, `Constructor`
-2. Use XML helper extensions instead of raw `///` composition:
- - `XmlSummary`, `XmlParam`, `XmlReturn`, `XmlRemarks`, `XmlCode` or `XmlCodeBlock`
-3. Use `TypeReference` when type text becomes complex (nullability, generics, arrays).
-4. Ensure writer lifetime is output-scoped (`generationContext.CreateCodeWriter()` inside callback).
-5. Preserve behavior, diagnostics, and generated names.
-6. Keep changes minimal and focused; do not reformat unrelated logic.
-
-### Migration strategy
-
-- Identify emitter phases: header, namespace, type declarations, member declarations.
-- Replace indentation/braces with scoped APIs.
-- Replace signature strings with declaration options.
-- Replace XML comments with XmlCommentWriter extension methods.
-- Keep semantic equivalence; call out any intentional deltas.
-
-### Verification
-
-- Run relevant tests.
-- Confirm generated files still compile.
-- Confirm no `CodeWriter` scope leaks (`OpenScopeCount == 0` when materialized).
-
-### Output format
-
-Return:
-
-1. Files changed
-2. Why each change was necessary
-3. Risks/behavior differences (if any)
-4. Verification performed
diff --git a/.agents/prompts/sdk-diagnose-agent-folder-copy.md b/.agents/prompts/sdk-diagnose-agent-folder-copy.md
deleted file mode 100644
index 85ad4445..00000000
--- a/.agents/prompts/sdk-diagnose-agent-folder-copy.md
+++ /dev/null
@@ -1,26 +0,0 @@
-# sdk-diagnose-agent-folder-copy (generic prompt spec)
-
-Diagnose why the bundled `.agents/**` folder from `Purview.BuildSdk` did not appear at the expected
-destination in a consuming repository.
-
-## Required behaviour
-
-1. Confirm the NuGet package actually contains `.agents/**` content (inspect the `.nupkg` if available).
-2. Confirm the consuming project is packable/buildable and imports the SDK via
- `Sdk.props`/`Sdk.targets`, since the copy runs in `EnsureAgentFolderInPackageTarget` before build.
-3. Check `EnableAgentFolderInPackage` is not set to `false` anywhere in the build (project file,
- `Directory.Build.props`, or command-line `-p:` overrides).
-4. Confirm the destination folder: default is `.agents` at the repo root, overridable per-build with
- `-p:AgentPackDestinationFolder=`.
-5. Verify repo-root discovery succeeded: explicit `RepoRoot`, then a nearby `AGENTS.md`, then source-control
- root metadata.
-6. Re-run the build and confirm the destination folder now contains the copied files (including the
- generated `.gitignore` for skill/prompt/agent subfolders).
-
-## Suggested output
-
-- A short root-cause explanation (missing import, disabled flag, wrong destination override, or repo-root
- discovery miss).
-- The exact command used to reproduce/verify the fix (for example
- `dotnet build -p:AgentPackDestinationFolder=`).
-- Confirmation that the expected files exist at the resolved destination path.
diff --git a/.agents/skills/aspire-apphost-to-resourcekit/.gitignore b/.agents/skills/aspire-apphost-to-resourcekit/.gitignore
deleted file mode 100644
index 27997545..00000000
--- a/.agents/skills/aspire-apphost-to-resourcekit/.gitignore
+++ /dev/null
@@ -1,8 +0,0 @@
-# Ignore all files
-*
-
-# Don't ignore directories, so Git can traverse them
-!*/
-
-# Keep this file
-!.gitignore
\ No newline at end of file
diff --git a/.agents/skills/dotnet-tunit/SKILL.md b/.agents/skills/dotnet-tunit/SKILL.md
deleted file mode 100644
index 4a9dec42..00000000
--- a/.agents/skills/dotnet-tunit/SKILL.md
+++ /dev/null
@@ -1,28 +0,0 @@
----
-name: dotnet-tunit
-description: Use .NET with TUnit-specific test conventions.
-category: dotnet
-roles:
- - dotnet
- - dotnet-tunit
- - coding
-tags:
- - dotnet
- - csharp
- - tunit
- - tests
----
-
-# dotnet-tunit Skill
-
-Use this skill for .NET repositories that use TUnit.
-
-## Rules
-
-- Use `TUnit.Core`.
-- Use `TUnit.Assertions`.
-- Test methods must have `[Test]`.
-- Assertion calls must be awaited.
-- Prefer `await Assert.That(actual).IsEqualTo(expected);`.
-- Do not use xUnit, NUnit, MSTest, or FluentAssertions unless explicitly requested.
-- Run the relevant `dotnet test` command before completion.
diff --git a/.agents/skills/git-conventional-commits/SKILL.md b/.agents/skills/git-conventional-commits/SKILL.md
deleted file mode 100644
index 49aeef1a..00000000
--- a/.agents/skills/git-conventional-commits/SKILL.md
+++ /dev/null
@@ -1,16 +0,0 @@
----
-name: git-conventional-commits
-description: Git workflow and conventional commit guidance.
----
-
-# Git Conventional Commits Skill
-
-Use this skill for Git workflow and commit hygiene.
-
-## Rules
-
-- Use Conventional Commits.
-- Prefer small, reviewable commits.
-- Commit types include `feat`, `fix`, `docs`, `test`, `refactor`, `chore`, `build`, and `ci`.
-- Do not mix unrelated changes.
-- Explain validation commands before completion.
diff --git a/.agents/skills/lefthook-integration/SKILL.md b/.agents/skills/lefthook-integration/SKILL.md
deleted file mode 100644
index 34fe3567..00000000
--- a/.agents/skills/lefthook-integration/SKILL.md
+++ /dev/null
@@ -1,16 +0,0 @@
----
-name: lefthook-integration
-description: Lefthook Git hook integration.
----
-
-# lefthook-integration Skill
-
-Use this skill for repo-local Git hook setup.
-
-## Rules
-
-- Prefer small, fast checks in pre-commit.
-- Put slower checks in pre-push.
-- Do not block commits with network-dependent checks.
-- Keep commands cross-platform where possible.
-- Document how to install and run hooks locally.
diff --git a/.agents/skills/project-placement-defaults/.gitignore b/.agents/skills/project-placement-defaults/.gitignore
deleted file mode 100644
index 27997545..00000000
--- a/.agents/skills/project-placement-defaults/.gitignore
+++ /dev/null
@@ -1,8 +0,0 @@
-# Ignore all files
-*
-
-# Don't ignore directories, so Git can traverse them
-!*/
-
-# Keep this file
-!.gitignore
\ No newline at end of file
diff --git a/.agents/skills/purview-architests-contracts/SKILL.md b/.agents/skills/purview-architests-contracts/SKILL.md
new file mode 100644
index 00000000..3484534f
--- /dev/null
+++ b/.agents/skills/purview-architests-contracts/SKILL.md
@@ -0,0 +1,163 @@
+---
+name: purview-architests-contracts
+description: Use when enabling or debugging Purview.Architecture.Testing's committed-API and port rules - apiSurface, apiDocumentation, portImplementation and portPurity. Covers capturing and reviewing .config/api-surface.json, reading an added or breaking API change, requiring XML documentation, and keeping an inner-layer port implemented and technology-neutral.
+license: MIT
+metadata:
+ product: Purview.Architecture.Testing
+ repository: purview-dev/architests
+---
+
+# API contracts and ports
+
+Dependency rules say which project may reference which. These rules say what the public surface
+actually **is**, and whether the interfaces that define a boundary are honest. They read the compiled
+assemblies by metadata only and are off by default, because they need a build.
+
+| Rule | Group | Catches |
+| -- | -- | -- |
+| `apiSurface` | `apiRules` | The public API differs from the committed baseline |
+| `apiDocumentation` | `apiRules` | A public type or member has no XML documentation |
+| `portImplementation` | `portRules` | A port in an inner layer has no public implementation |
+| `portPurity` | `portRules` | A port's signature names an infrastructure technology |
+
+```json
+"apiRules": {
+ "enabled": true
+},
+"portRules": {
+ "enabled": true
+}
+```
+
+Each enabled rule becomes its own TUnit test. A disabled group produces no test, so an absent
+`apiSurface` test means the group is off, not that the surface is unchecked.
+
+## The committed baseline
+
+`.config/api-surface.json` records every public type and member, grouped by project, with the
+responsibility recorded for review context. It is the contract: a change to it is a change to what a
+consumer may call.
+
+- **Captured, never hand-written.** `architests api capture` writes it.
+- **Canonical.** Projects, types, interfaces and members are sorted; there are no timestamps; line
+ endings are always `\n`. An unchanged API regenerates byte for byte, so a diff means a real change.
+- **Committed.** It is reviewed like code. A pull request that changes it explains why.
+
+```bash
+dotnet tool install --global Purview.Architecture.Testing.Cli
+
+architests api capture # write the baseline from the current build
+architests api check # compare; exit 1 on any difference
+```
+
+`api check` is the CI gate; `apiSurface` is the same comparison as a test. A missing baseline is
+itself an `apiSurface` failure, because the rule would otherwise pass without checking anything.
+
+`api capture` and `api check` accept `--repository ` and `--baseline `. Unlike the test
+run, a command scans the repository's own build output even when `assemblyRules.assemblyRoots` is
+empty, because a tool does not run from a test output directory.
+
+## Reading a baseline failure
+
+The message names the project, the type or member, and whether it was added, removed or changed.
+
+- **Added.** The API grew. Run `architests api capture`, inspect the added entries, and commit them
+ with the feature. Additions are not breaking, but they are still a reviewed contract change.
+- **Removed.** The message calls it breaking. Restore the member, or capture the baseline as a
+ deliberate breaking release and say so in the pull request.
+- **Changed.** The shape moved: kind, `sealed`, `abstract`, base type, interfaces, a member's type, or
+ whether it is static. Treat the same way as a removal until proven otherwise.
+
+The baseline includes public **nested** types and the SDK's generated `Assembly` marker.
+Both are real public metadata; leave them alone.
+
+## API documentation
+
+`apiDocumentation` reads the XML documentation file the compiler writes beside each assembly.
+
+- `requireTypeDocumentation` (default true) requires a `` entry for every public type.
+- `requireMemberDocumentation` (default false) extends that to every public member.
+
+Member documentation is off by default because a record's positional parameters document its
+properties through the type's entry; requiring a separate entry per generated property would punish
+a correct record.
+
+A project that ships no XML file is reported once with the fix: set
+`true`. The Purview SDK does this already.
+
+## The port rules
+
+A **port** is an interface in one of `portRules.categories`, which default to `domain` and
+`application`. Those are the layers that own contracts; an interface in `shared` or in an adapter is
+not a port by this definition.
+
+### `portImplementation`
+
+Every port must have at least one **public implementation** in a production project. An unimplemented
+port is either dead or a boundary nobody crossed; both deserve a review. The dependency matrix still
+governs where that implementation may live.
+
+A port implemented only by a consumer (an extension point such as `IArchitectureRule`) fits badly
+here: either move it out of the port categories, or record a waiver explaining that the repository
+is the contract's publisher, not its implementer.
+
+### `portPurity`
+
+A port's property types, return types and parameter types must not name a forbidden prefix. Defaults
+cover `Microsoft.EntityFrameworkCore`, `System.Data`, `Microsoft.AspNetCore` and `System.Net.Http`.
+Generic arguments count, so `IReadOnlyList` is caught.
+
+```json
+"portRules": {
+ "enabled": true,
+ "forbiddenTypePrefixes": ["Microsoft.EntityFrameworkCore", "System.Data"]
+}
+```
+
+A port that names a database or an HTTP client is not a boundary; it is a leak. Move the technology
+into the adapter and keep the interface in terms the domain understands.
+
+## Waivers and scope
+
+All four rules are waivable per project and per rule, like the rest of the set:
+
+```json
+"waivers": [
+ {
+ "project": "Legacy.Api",
+ "rules": ["apiSurface"],
+ "reason": "The published surface is frozen for a major version; the next major captures it.",
+ "reviewedOn": "2026-10-18"
+ }
+]
+```
+
+Prefer a narrower setting when the whole repository shares the exception:
+`apiRules.requireMemberDocumentation: false`, a different `portRules.categories`, or a longer
+`forbiddenTypePrefixes` list.
+
+## CI
+
+```yaml
+- run: architests api check
+```
+
+`api check` needs a build but no test run. In the test suite, `apiSurface` does the same comparison,
+so a repository that runs its architecture tests does not need the command — it is there for a fast
+job and for reviewers who want the diff without running TUnit.
+
+## See it working
+
+`src/samples/ArchitectureSample` demonstrates all four rules: `Domain.IOrderRepository` is a port
+implemented by `Persistence.InMemory` and `Persistence.Json`, `Application` depends only on the port,
+and `.config/api-surface.json` is committed for all six projects.
+
+## Checklist
+
+- `apiRules.enabled` and `portRules.enabled` are deliberate.
+- The baseline is committed, canonical, and regenerated after every intended API change.
+- A removed or changed member is called out as breaking in the pull request.
+- Every public type has a ``, and the project generates its XML documentation.
+- Ports live in an inner layer, are implemented, and name no infrastructure technology.
+- A waiver names one project and one rule, with a reason and a review date.
+
diff --git a/.agents/skills/purview-architests-extending/SKILL.md b/.agents/skills/purview-architests-extending/SKILL.md
new file mode 100644
index 00000000..96267b20
--- /dev/null
+++ b/.agents/skills/purview-architests-extending/SKILL.md
@@ -0,0 +1,123 @@
+---
+name: purview-architests-extending
+description: Use when adding a bespoke rule to Purview.Architecture.Testing, implementing IArchitectureRule, or working on the package's internals - the three-layer design, the project graph, the metadata-only assembly reader, or the evaluator. Covers the ArchitectureContext, what an additional rule gets for free, and testing a rule against an in-memory fixture.
+license: MIT
+metadata:
+ product: Purview.Architecture.Testing
+ repository: purview-dev/architests
+---
+
+# Extending Purview.Architecture.Testing
+
+A repository can add a bespoke check without a second architecture framework. This skill covers the
+extension point and the internals a rule is built on. To *consume* the package — adopting it,
+writing a policy, reading a failure — use the `purview-architests` skill instead.
+
+## Add a rule
+
+Implement `IArchitectureRule` and list it in `AdditionalRules`:
+
+```csharp
+using Purview.Architecture.Testing;
+
+[InheritsTests]
+public sealed class ArchitectureTests : PurviewArchitectureTests
+{
+ protected override IReadOnlyList AdditionalRules => [new NoConsoleLoggingRule()];
+
+ sealed class NoConsoleLoggingRule : IArchitectureRule
+ {
+ public string Rule => "noConsoleLogging";
+
+ public IReadOnlyList Evaluate(ArchitectureContext context) =>
+ context.Projects.Values
+ .Where(project => !project.IsTestProject)
+ // ...inspect the project or its assembly...
+ .Select(project => new ArchitectureViolation(Rule, project.Name, "Console logging is banned here."))
+ .ToArray();
+ }
+}
+```
+
+The `Rule` id is the key everywhere: it names the generated test, it is what `SkipRule` receives, and
+it is what a waiver's `rules` array matches.
+
+## What the context gives you
+
+`ArchitectureContext` carries the three inputs a rule can need:
+
+| Member | What it is |
+| -- | -- |
+| `Policy` | The parsed `ArchitecturePolicy`, so a rule reads the same definition the built-in rules do. |
+| `Projects` | The project graph, keyed by project name, with declared references, packages, framework references and analyzers. |
+| `Assemblies` | The compiled assemblies, keyed by project name, each with the external types it references. Empty when `assemblyRules.enabled` is false. |
+
+`ArchitecturePolicy.Classify(projectName)` is the classification every built-in rule uses — the first
+segment of the project name, honouring aliases and a waiver's `mapsTo`. Use it so a custom rule
+agrees with the standard set.
+
+## What an additional rule gets for free
+
+- **Its own `[Test]`.** Each rule id becomes a case of
+ `AdditionalRule_GivenTheRepository_RespectsThePolicy`, so a failure names the rule rather than
+ collapsing into one assertion.
+- **`SkipRule`.** Override `SkipRule` and return `true` for the rule id.
+- **Waivers.** A waiver whose `rules` names the rule id is honoured automatically, so a reviewed,
+ per-project departure needs no code.
+- **Reporting.** `ArchitecturePolicyEvaluator.Report` renders the violations, and the failure's
+ `.Because(...)` lists every one.
+
+A violation's `Project` must be the project name (or the offender a waiver can name), and its `Rule`
+must be the rule id, or the waiver filter cannot match it.
+
+## Test the rule against a fixture
+
+The evaluator takes an in-memory graph, so a rule is tested as a small fixture rather than a
+repository on disk — exactly how the package's own rules are tested:
+
+```csharp
+var evaluator = new ArchitecturePolicyEvaluator(
+ policy,
+ projects,
+ assemblies,
+ [new NoConsoleLoggingRule()]
+);
+
+await Assert.That(evaluator.EvaluateAdditionalRule("noConsoleLogging")).IsEmpty();
+```
+
+`ArchitecturePolicyEvaluator` also has a two-argument constructor for project-only rules, and a
+four-argument one when the rule needs the assembly graph.
+
+## The three layers (non-negotiable)
+
+Keep the separation, because it is what makes a rule testable:
+
+- **`ArchitecturePolicy` / `ProjectGraph` / `AssemblyGraph`** — read the policy, the `.csproj` graph
+ and the compiled assembly metadata. **No MSBuild and no test-framework types.**
+- **`ArchitecturePolicyEvaluator`** — the rules, returning typed `ArchitectureViolation` lists. It
+ takes an **in-memory graph**, so a rule is testable as a small fixture.
+- **`PurviewArchitectureTests`** — the TUnit wrapper, one `[Test]` per rule.
+
+Every new rule must be evaluable from an in-memory fixture and asserted by a small
+`ArchitectureTesting.UnitTests` test.
+
+## Reading assemblies
+
+- Read compiled assemblies by **metadata only** (`System.Reflection.Metadata`). Never `Assembly.Load`
+ or any API that executes code or needs a probing path.
+- The `TypeReference` table is the dependency set: base types, interfaces, generic arguments,
+ signatures, attributes and method-body uses all appear there.
+- Attribute an assembly to a project by the SDK's generated `Assembly` marker, falling
+ back to an exact project-name match. An assembly that maps to no project is a package and is
+ ignored — a package is never a project.
+- Resolve references against the set of assemblies actually scanned, never by name guessing.
+
+## Repository conventions
+
+- TUnit on Microsoft.Testing.Platform. No xUnit, NUnit, MSTest or FluentAssertions.
+- Tests use AAA and `Subject_Scenario_Expectation` naming, and must pass on Windows, Linux and macOS.
+- `architecture-policy.schema.json` at the repository root is both the published schema and the
+ resource embedded in the package. Never keep a second copy.
+- The repository applies its own package to itself (`src/tests/Repository.UnitTests`), with the
+ sample at `src/samples/ArchitectureSample` showing consumer adoption.
diff --git a/.agents/skills/purview-architests-migration/SKILL.md b/.agents/skills/purview-architests-migration/SKILL.md
new file mode 100644
index 00000000..d2b5063b
--- /dev/null
+++ b/.agents/skills/purview-architests-migration/SKILL.md
@@ -0,0 +1,143 @@
+---
+name: purview-architests-migration
+description: Use when adopting Purview.Architecture.Testing in an existing repository that already has tangled dependencies, or when ratcheting an adopted policy tighter. Covers a permissive first policy, committing the API baseline before enforcing it, recording narrow waivers instead of using SkipRule, starting an empty dependency budget, and tightening one rule at a time without a big-bang rewrite.
+license: MIT
+metadata:
+ product: Purview.Architecture.Testing
+ repository: purview-dev/architests
+---
+
+# Migrating an existing repository
+
+A policy that describes the architecture you wish you had fails on day one and gets switched off.
+Adopt the architecture you **do** have, then tighten it one reviewed step at a time. The rules are
+the same either way; only the policy and the waivers change.
+
+## 1. Inventory before writing the policy
+
+- List every production project and what it references. `architests graph` prints the graph once the
+ policy can find the projects.
+- Group projects into responsibilities that describe what they are for, not where they sit. A
+ qualified name (`Persistence.SqlServer`) belongs to `Persistence`; only the first segment counts.
+- Name the composition root with `category: "composition"` and hosts with `category: "host"`, so the
+ composition boundary works without special cases.
+
+## 2. A permissive first policy
+
+Start with the full dependency closure permitted. The first run should fail only on things you are
+ready to fix — usually naming.
+
+```json
+{
+ "version": 3,
+ "sourceRoots": ["src"],
+ "responsibilities": [
+ {
+ "name": "Domain",
+ "category": "domain",
+ "purpose": "The domain model and its invariants.",
+ "mayDependOn": ["Application", "Persistence", "Composition"],
+ "mustNotDependOn": []
+ }
+ ]
+}
+```
+
+Set `sourceRoots` correctly first: an empty graph makes every rule pass vacuously, which is why
+`graphDiscovery` fails instead.
+
+## 3. Add the test class once
+
+```csharp
+[InheritsTests]
+public sealed class ArchitectureTests : PurviewArchitectureTests;
+```
+
+`[InheritsTests]` is load-bearing. Without it the run is green and nothing is checked.
+
+## 4. Record the API before enforcing it
+
+If the public API is already shipped, capture it before enabling `apiRules`:
+
+```bash
+architests api capture
+```
+
+Then enable the group. The first `apiSurface` run compares against the API you actually have, so it
+passes, and every later change becomes a reviewed diff. Do the same for the sample or any package in
+the repository.
+
+## 5. Waivers, not skips
+
+When a rule finds a real departure you cannot fix today, record it:
+
+```json
+"waivers": [
+ {
+ "project": "Legacy.Utilities",
+ "mapsTo": "Shared",
+ "rules": ["naming"],
+ "reason": "The package id is published; renaming it is a separate breaking release.",
+ "reviewedOn": "2026-10-18"
+ }
+]
+```
+
+- `mapsTo` keeps every dependency rule in force; only the name is excused.
+- Excuse one rule, not the whole set.
+- Set `waiverPolicy.maxAgeDays` so a waiver has to be renewed. An unreviewed waiver is how a policy
+ quietly stops being true.
+
+`SkipRule` removes a rule for the whole repository with no record. Treat it as a last resort, never
+as the adoption strategy.
+
+## 6. Start the dependency budget empty
+
+```json
+"dependencyBudget": {
+ "enabled": true,
+ "failOnStale": true,
+ "entries": []
+}
+```
+
+The rule is enabled and checks nothing, which is exactly right: the mechanism is in place. Add an
+entry for one project at a time, listing only the references it has today. From then on a new
+reference needs a reviewed policy change, and a removed one must be removed from the budget.
+
+## 7. Tighten one step at a time
+
+Each step is a small pull request that keeps the suite green:
+
+1. **Naming.** Add aliases or waivers, then rename projects in a dedicated change.
+2. **Forbidden packages.** Add one prefix to one responsibility, fix the violations, repeat.
+3. **Dependency direction.** Move a single edge from `mayDependOn` to `mustNotDependOn`, or remove it
+ from `mayDependOn` entirely so silence becomes a violation.
+4. **Type rules.** Enable `typeRules` for one category with `sealConcreteClasses` and generated-code
+ exclusions, fix, then widen the scope.
+5. **Ports.** Move an interface into `domain` or `application` only when its implementation lives in
+ an adapter and its signature is technology-neutral.
+6. **Reachability.** Turn on `policyIntegrity.checkReachability` once the matrix is honest; it will
+ find prohibitions the permitted closure bypasses.
+
+A rule that cannot pass even with waivers is telling you the policy is wrong, not the code. Change
+the policy.
+
+## Reading a failure during migration
+
+- `naming` — add an alias for an established name, or a waiver with `mapsTo`.
+- `dependencyMatrix` / `assemblyDependencyMatrix` — the message names the reference, the direction
+ and the likely fix. Prefer moving a type over widening `mayDependOn`.
+- `apiSurface` — expected after any intentional API change: run `architests api capture` and review
+ the diff before committing.
+- `dependencyBudget` — a new reference is over budget; a stale allowance needs removing.
+- `policyIntegrity` — the policy contradicts itself; fix the policy before the code.
+
+## Checklist
+
+- `sourceRoots` finds the projects, and `graphDiscovery` passes.
+- The matrix describes today's graph, not the target graph.
+- The API baseline is committed before `apiRules` is switched on.
+- Every departure is a narrow, dated waiver rather than a skip.
+- The dependency budget starts empty and grows one reviewed entry at a time.
+- Each tightening step is its own pull request, with the suite green.
diff --git a/.agents/skills/purview-architests-policy-authoring/SKILL.md b/.agents/skills/purview-architests-policy-authoring/SKILL.md
new file mode 100644
index 00000000..9f1f2f52
--- /dev/null
+++ b/.agents/skills/purview-architests-policy-authoring/SKILL.md
@@ -0,0 +1,190 @@
+---
+name: purview-architests-policy-authoring
+description: Use when authoring or changing .config/architecture-policy.json for Purview.Architecture.Testing - defining responsibilities, categories, mayDependOn and mustNotDependOn, choosing sourceRoots, adding aliases, recording a waiver, setting waiver expiry, or fixing a policyIntegrity failure. Covers the version-3 document, the matrix semantics, and how to validate a policy without running the tests.
+license: MIT
+metadata:
+ product: Purview.Architecture.Testing
+ repository: purview-dev/architests
+---
+
+# Authoring an architecture policy
+
+The policy is the definition of the architecture. The tests only report what it says, so a vague or
+contradictory policy produces a vague or contradictory suite. This skill is about getting the
+document right; to *adopt* the package or read a failure, use `purview-architests` instead.
+
+## The shape
+
+`.config/architecture-policy.json` at the repository root:
+
+```json
+{
+ "$schema": "https://raw.githubusercontent.com/purview-dev/architests/main/architecture-policy.schema.json",
+ "version": 3,
+ "description": "What this repository's architecture is.",
+ "sourceRoots": ["src"],
+ "responsibilities": [
+ {
+ "name": "Core",
+ "aliases": ["Domain"],
+ "category": "domain",
+ "purpose": "The domain model, its invariants and its rules.",
+ "mayDependOn": [],
+ "mustNotDependOn": ["Application", "Persistence", "Composition"],
+ "forbiddenFrameworkReferences": ["Microsoft.AspNetCore.App"]
+ }
+ ]
+}
+```
+
+`version` and `responsibilities` are required. Everything else is optional. Version 3 adds
+`policyIntegrity` and `waiverPolicy`; both are optional, so a version-2 document remains valid.
+
+## Responsibilities
+
+A project name is `[.]`, and only the **first segment** is
+classified. `Persistence.SqlServer` and `Persistence` are both Persistence: qualification is a
+naming choice, never a different set of rules.
+
+| Field | Guidance |
+| -- | -- |
+| `name` | One PascalCase segment. Name the role, not the technology. |
+| `aliases` | Existing names you are not renaming. Prefer renaming and deleting the alias. |
+| `category` | `domain`, `application`, `infrastructure`, `composition`, `host` or `shared`. `composition` is the exemption `compositionBoundary` keys on; `host` may also reference it. |
+| `purpose` | At least 20 characters, and quoted in failures. Write why the responsibility exists; "misc" is not a purpose. |
+| `mayDependOn` | The complete set of permitted references. Silence is not permission. |
+| `mustNotDependOn` | Prohibitions that matter. Must not overlap `mayDependOn`. |
+| `forbiddenPackagePrefixes` | NuGet prefixes that must never appear, such as `Microsoft.EntityFrameworkCore`. |
+| `forbiddenPackageScope` | `own` (default) reports packages the project declares or its own packages pull in; `closure` also reports packages inherited from project references. |
+| `forbiddenFrameworkReferences` | Framework prefixes, such as `Microsoft.AspNetCore.App` in a portable layer. |
+| `siblingIndependence` | When true, qualified implementations of this responsibility must not reference each other. |
+
+Avoid names that describe a category. `Infrastructure`, `Services`, `Helpers`, `Common`,
+`Utilities` and `Managers` are discouraged because nothing can be kept out of them.
+
+## The matrix is three-way
+
+For every declared reference, and for every type reference in the compiled assemblies:
+
+1. **Same responsibility** is always allowed.
+2. **`mustNotDependOn`** is a violation.
+3. **`mayDependOn`** is permitted.
+
+Anything else is a violation. That is deliberate: an unclassified dependency is a gap in the
+policy, not an implicit yes. When a new edge is genuinely intended, add it to `mayDependOn` — that
+is a reviewed policy change, which is the point.
+
+## Policy integrity
+
+`policyIntegrity` always runs and cannot be waived. It catches what the schema cannot:
+
+- a matrix entry that names no responsibility (aliases and project names are not names here);
+- the same responsibility in both `mayDependOn` and `mustNotDependOn`;
+- two responsibilities with the same name;
+- an alias equal to a name, or two responsibilities claiming the same alias;
+- with `checkReachability`, a prohibition the permitted dependencies can reach anyway. The failure
+ prints the path, such as `Core -> Application -> Persistence`, so the edge to remove is obvious.
+
+```json
+"policyIntegrity": {
+ "checkReachability": true
+}
+```
+
+Reachability is opt-in because it is the stronger claim: the lists can be consistent while a longer
+permitted path still defeats the prohibition.
+
+## Waivers
+
+A waiver is a reviewed departure, not a skip:
+
+```json
+"waivers": [
+ {
+ "project": "Legacy.Utilities",
+ "mapsTo": "Shared",
+ "rules": ["naming"],
+ "reason": "Predates the catalogue; renaming breaks a published package identifier.",
+ "reviewedOn": "2026-10-18"
+ }
+]
+```
+
+- `mapsTo` is the useful part: the project keeps its real responsibility, so every dependency rule
+ still applies and only the **name** is excused.
+- Excuse the narrowest rule that applies. A waiver listing everything is a policy opt-out.
+- `policyIntegrity`, `graphDiscovery` and `waiverIntegrity` cannot be waived; naming one is a
+ `waiverIntegrity` failure.
+
+### Expiry
+
+```json
+"waiverPolicy": {
+ "maxAgeDays": 180
+}
+```
+
+A waiver older than the maximum is a `waiverIntegrity` failure. So are an undated waiver while a
+maximum is set, a date that is not `yyyy-MM-dd`, and a date in the future. Expiry is off by default;
+adopt it deliberately, and expect to renew or delete the waivers it surfaces.
+
+### Package scope
+
+`forbiddenPackagePrefixes` measures **ownership** by default: what the project declares, what a
+shared props file injected, and what its own package references pull in. A package inherited through
+a permitted project reference is not owned, so a host is not reported for its adapter’s EF Core.
+
+Use `"forbiddenPackageScope": "closure"` only when the policy means “this technology must not be
+anywhere on the compile graph”. That makes hosts responsible for every package their adapters bring
+in, and usually requires the adapter to mark implementation packages `PrivateAssets="compile"`.
+
+## Dependency budget
+
+`dependencyBudget` ratchets the project graph: it records the references each project may declare
+today, so growth is a reviewed policy change.
+
+```json
+"dependencyBudget": {
+ "enabled": true,
+ "failOnStale": true,
+ "entries": [
+ { "project": "Application", "references": ["Domain"] },
+ { "project": "Persistence.SqlServer", "references": ["Domain", "Application"] }
+ ]
+}
+```
+
+- An entry lists **project names**, exactly as they appear on disk, including the qualification:
+ `Persistence.SqlServer`, not `Persistence`.
+- A reference outside the entry is a failure. Remove it, or add it in the same reviewed commit that
+ adds the `ProjectReference`.
+- With `failOnStale` (default true), an allowance the project no longer uses is a failure. Tighten the
+ budget rather than leaving a permission nobody needs.
+- A project with no entry is not budgeted. Start with `entries: []`, then add one project at a time.
+- The rule is not waivable; changing the budget is the sanctioned way to change the graph.
+
+## Validate the policy
+
+```bash
+dotnet tool install --global Purview.Architecture.Testing.Cli
+architests validate
+architests waivers list --stale
+```
+
+`validate` runs the schema check and `policyIntegrity` without a build; `waivers list --stale` exits
+non-zero when a waiver is due. Exit codes: `0` clean, `1` findings, `2` a malformed command line.
+Both commands accept `--repository `.
+
+The test suite runs the same checks and one test per rule, so a policy that passes the tool can
+still fail a matrix rule — that failure is an architecture decision, not a document error.
+
+## Checklist
+
+- Every responsibility has a purpose that says what it is for, not what it uses.
+- Every dependency that exists is either permitted or forbidden; nothing is left unclassified.
+- `mustNotDependOn` entries are not also in `mayDependOn`.
+- Names are roles, not categories, and no alias duplicates a name.
+- Waivers are narrow, justified, dated, and none is due.
+- `policyIntegrity.checkReachability` is on before claiming a prohibition is enforced.
+- A version bump is deliberate: adding optional sections does not require one.
+
diff --git a/.agents/skills/purview-architests-type-rules/SKILL.md b/.agents/skills/purview-architests-type-rules/SKILL.md
new file mode 100644
index 00000000..1d933788
--- /dev/null
+++ b/.agents/skills/purview-architests-type-rules/SKILL.md
@@ -0,0 +1,188 @@
+---
+name: purview-architests-type-rules
+description: Use when enabling or debugging Purview.Architecture.Testing's type-level rules - typeNaming, typeShape, typeNamespace and attributePolicy. Covers the typeRules policy section, which public types are governed, why a type is reported as unsealed or outside its root namespace, how generated code and nested types are treated, and how to fix or waive each finding.
+license: MIT
+metadata:
+ product: Purview.Architecture.Testing
+ repository: purview-dev/architests
+---
+
+# Type-level naming, shape and namespace rules
+
+These rules police the **public surface** a project compiles, not its dependencies. They read the
+compiled assembly by metadata only: no assembly is loaded, no code runs, and no source file is
+needed. Enable them when the API a consumer receives matters as much as the direction its
+references run.
+
+For dependency direction, use the `purview-architests` skill. This skill covers `typeNaming`,
+`typeShape`, `typeNamespace` and `attributePolicy`.
+
+## Enable them
+
+They are off by default, because they need a build to have produced the assemblies:
+
+```json
+{
+ "assemblyRules": { "enabled": true },
+ "typeRules": {
+ "enabled": true,
+ "appliesTo": { "categories": ["domain", "application", "shared"] },
+ "excludeGeneratedCode": true
+ }
+}
+```
+
+- An empty `appliesTo.categories` governs **every production responsibility**.
+- Test projects are never governed.
+- `assemblyRules` and `typeRules` scan the same assemblies. `assemblyRoots` and `assemblyGlobs` live
+ under `assemblyRules` and apply to both; an empty `assemblyRoots` scans the test output directory.
+- Only **public** types are checked, including public nested types. Internal and private types are
+ outside the API and are left alone.
+
+## What the four rules catch
+
+| Rule | Catches |
+| -- | -- |
+| `typeNaming` | An interface without `I`, an attribute without `Attribute`, an exception without `Exception`, a discouraged suffix (`Manager`, `Helper`, `Util`, `Impl`) |
+| `typeShape` | An unsealed public class, a public instance field, a mutable collection return, a misnamed exception, a utility class that is not static |
+| `typeNamespace` | A public type outside the project's `RootNamespace` |
+| `attributePolicy` | A missing required attribute, a forbidden attribute, `[Obsolete]` without a message, `InternalsVisibleTo` naming production code |
+
+Each enabled rule becomes its own TUnit test. A disabled group produces **no** type-rule test rather
+than a test that checks nothing, so a green run cannot mean "the group was off".
+
+## Governing a subset
+
+`appliesTo.categories` is the usual scope. A composition root is often excluded because it is allowed
+to reference everything:
+
+```json
+"appliesTo": { "categories": ["domain", "application", "infrastructure", "shared"] }
+```
+
+Generated code is skipped by default. A source generator must not be forced to change its output:
+
+```json
+"excludeGeneratedCode": true,
+"excludeNamespacePrefixes": ["Contoso.Generated"]
+```
+
+A type marked `[GeneratedCode]` or `[CompilerGenerated]` is skipped, as is any type under an excluded
+namespace prefix.
+
+## Type naming
+
+- An interface name must start with `I` followed by an uppercase letter: `IOrderRepository`.
+- A class deriving from `System.Attribute` must end with `Attribute`.
+- A class deriving from an exception must end with `Exception`.
+- A type ending with a configured `discouragedTypeSuffixes` entry is reported. The default list
+ names mechanisms, not responsibilities. Configure it to match the repository's vocabulary.
+
+Generic arity is removed before the check, so `IRepository` is checked as `IRepository`.
+
+## Type shape
+
+- **Unsealed public class.** A public concrete class must be `sealed` unless it is `abstract`. An
+ unsealed class is a public extension point nobody declared; seal it, or make the base type explicit.
+- **Public instance field.** Constants and static readonly fields are fine; an instance field cannot
+ validate or evolve without a breaking change.
+- **Mutable collection return.** A public property or method returning `List` or
+ `Dictionary` hands the caller the owner's state. Return `IReadOnlyList` or
+ `IReadOnlyDictionary`.
+- **Misnamed exception.** A class named `...Exception` must derive from `System.Exception`.
+- **Utility class.** A class with only static members and no public constructor must be declared
+ `static`, so it cannot be instantiated by accident.
+
+Turn off either check in the policy when it does not fit:
+
+```json
+"sealConcreteClasses": false,
+"requireReadOnlyCollections": false
+```
+
+## Type namespace
+
+The rule compares the type's declared namespace with the project's `RootNamespace`, read from the
+`.csproj`: the namespace must equal it or start with it followed by a dot.
+
+Metadata records the namespace, not the file path, so the rule **cannot** check that the folder
+matches. It deliberately makes no such claim.
+
+Set `RootNamespace` explicitly when it differs from the project name:
+
+```xml
+Purview.Architecture.Testing
+```
+
+Without it, the project name is used, which is the SDK's own fallback.
+
+## Attribute policy
+
+| Setting | Default | Effect |
+| -- | -- | -- |
+| `requiredAttributes` | `[]` | Namespace-qualified attributes every governed public type must carry |
+| `forbiddenAttributes` | `[]` | Namespace-qualified attributes no governed public type may carry |
+| `allowObsoleteWithoutMessage` | `false` | Permit `[Obsolete]` with no message |
+| `forbidInternalsVisibleToProduction` | `true` | Reject `InternalsVisibleTo` naming a production assembly |
+
+`[Obsolete("Use IOrderStore instead.")]` is fine. A bare `[Obsolete]` is reported: a caller is told
+the type is going away but not what to do about it.
+
+`InternalsVisibleTo` is checked at assembly level. A friend that maps to a **test** project is
+ordinary; a friend that maps to a **production** project is a boundary leak, because the referenced
+project can now see internals it was never meant to depend on. Expose a public abstraction instead.
+
+## Fix or waive
+
+Fix the type when the rule is right; rename it, seal it, return a read-only interface, or move it
+under the root namespace.
+
+A waiver is per project and per rule, and the project field is the **project name** the assembly
+belongs to:
+
+```json
+"waivers": [
+ {
+ "project": "Persistence",
+ "rules": ["typeShape"],
+ "reason": "The EF entity must stay inheritable for the proxy; sealing it breaks materialisation.",
+ "reviewedOn": "2026-10-18"
+ }
+]
+```
+
+Prefer the narrow settings when the whole repository shares an exception: `excludeNamespacePrefixes`
+for generated code, `sealConcreteClasses` for a codebase that uses inheritance as a feature, or
+`appliesTo.categories` to leave the composition root out.
+
+## Troubleshooting
+
+- **No type-rule tests at all.** `typeRules.enabled` is false, or the policy failed to load. The
+ group produces no test rather than a vacuous pass, so this is visible in the test list.
+- **A rule reports nothing and you expected findings.** The projects were not built, or the
+ assembly was not in the scan root. Type rules use `assemblyRules.assemblyRoots`; an empty value
+ scans the test output directory, so the test project must reference the projects it governs.
+- **A type you expected is missing.** It is internal, nested inside an internal type, marked as
+ generated, under an excluded namespace, in a test project, or in a responsibility outside
+ `appliesTo.categories`.
+- **`typeNamespace` reports everything.** The project has no `RootNamespace` and its namespace is
+ not the project name. Set `RootNamespace` explicitly.
+- **A public API baseline is also enabled.** Type-rule findings are API-shape findings; fix them
+ before regenerating a baseline, or the baseline records the problem.
+
+## See it working
+
+`src/samples/ArchitectureSample` enables `typeRules` for the `domain`, `application`, `infrastructure`
+and `shared` categories. Its projects declare `RootNamespace` explicitly, its classes are sealed, its
+collections are exposed as `IReadOnlyList`, and `IOrderRepository` follows the interface
+convention.
+
+## Checklist
+
+- `typeRules.enabled` is true and the categories are deliberate.
+- Every governed public class is sealed or abstract, unless `sealConcreteClasses` is off.
+- No public instance fields or mutable collection returns are exposed.
+- `RootNamespace` is set on projects whose namespace differs from their name.
+- Generated code is excluded by attribute or namespace, not by loosening the rule.
+- Every waiver names one project and one rule, with a reason and a review date.
+
diff --git a/.agents/skills/purview-architests/SKILL.md b/.agents/skills/purview-architests/SKILL.md
new file mode 100644
index 00000000..dd9d5db6
--- /dev/null
+++ b/.agents/skills/purview-architests/SKILL.md
@@ -0,0 +1,354 @@
+---
+name: purview-architests
+description: Adopt or debug Purview.Architecture.Testing, the package that enforces a repository's project and type-level dependency policy as TUnit tests. Use when adding architecture tests to a repository, writing or changing .config/architecture-policy.json, validating a policy with the architests tool, enabling the assembly, type, API or port rules, recording or expiring a waiver, setting a dependency budget, interpreting a policy-integrity, dependency-matrix, type-level, cycle, sibling-independence, composition-boundary, forbidden-package, framework-reference or naming failure, or when the architecture tests pass but enforce nothing.
+license: MIT
+metadata:
+ product: Purview.Architecture.Testing
+ repository: purview-dev/architests
+---
+
+# Architecture tests with Purview.Architecture.Testing
+
+The package defines the rules once so a policy is not copied into every repository's test project.
+
+## Adoption is two things
+
+**1. A policy file** at `.config/architecture-policy.json`:
+
+```json
+{
+ "$schema": "https://raw.githubusercontent.com/purview-dev/architests/main/architecture-policy.schema.json",
+ "version": 3,
+ "sourceRoots": ["src"],
+ "responsibilities": [
+ {
+ "name": "Core",
+ "aliases": ["Domain"],
+ "category": "domain",
+ "purpose": "The domain model, its invariants and its rules.",
+ "mayDependOn": [],
+ "mustNotDependOn": ["Application", "Persistence"],
+ "forbiddenFrameworkReferences": ["Microsoft.AspNetCore.App"]
+ }
+ ]
+}
+```
+
+**2. One derived test class:**
+
+```csharp
+[InheritsTests]
+public sealed class ArchitectureTests : PurviewArchitectureTests;
+```
+
+## `[InheritsTests]` is load-bearing
+
+TUnit does **not** walk base types during discovery. Without the attribute the class compiles, the
+run is green, and nothing is enforced — the worst failure this package can have.
+
+TUnit's analyzer reports `TUnit0030` when it is missing. Treat it as an error, not a suggestion.
+
+If the architecture tests "pass" but you cannot name which rule ran, check this first.
+
+## The rules
+
+| Rule id | Test | What it catches |
+| -- | -- | -- |
+| `policyIntegrity` | `Policy_GivenItsOwnDefinitions_IsConsistent` | An unknown responsibility name, a dependency both permitted and forbidden, or a duplicate name or alias. Not waivable |
+| `graphDiscovery` | `Repository_GivenItsSourceRoots_YieldsProjectsToCheck` | An empty graph — which satisfies every other rule |
+| `naming` | `ProductionProjects_GivenTheirNames_MapToAResponsibility` | A project name matching no responsibility or alias |
+| `discouragedName` | `ProductionProjects_GivenTheirNames_AvoidCatchAllNames` | A project named after a category, so nothing can be kept out of it |
+| `dependencyMatrix` | `ProductionProjects_GivenTheirReferences_RespectTheDependencyMatrix` | A declared `ProjectReference` the matrix forbids or does not permit |
+| `assemblyDependencyMatrix` | `AssemblyTypes_GivenTheirReferences_RespectTheDependencyMatrix` | A **type** in one responsibility using a type in another, including a dependency that only arrives transitively or through a package |
+| `typeNaming` | `TypeRules_GivenTheRepository_RespectThePolicy` | A public interface without `I`, an attribute or exception without its suffix, or a discouraged suffix |
+| `typeShape` | `TypeRules_GivenTheRepository_RespectThePolicy` | An unsealed public class, a public field, a mutable collection return, or a non-static utility class |
+| `typeNamespace` | `TypeRules_GivenTheRepository_RespectThePolicy` | A public type outside the project's root namespace |
+| `attributePolicy` | `TypeRules_GivenTheRepository_RespectThePolicy` | A missing or forbidden attribute, `[Obsolete]` without a message, or `InternalsVisibleTo` naming production code |
+| `apiSurface` | `APIRules_GivenTheRepository_RespectThePolicy` | The public API differs from the committed baseline |
+| `apiDocumentation` | `APIRules_GivenTheRepository_RespectThePolicy` | A public type or member has no XML documentation |
+| `portImplementation` | `PortRules_GivenTheRepository_RespectThePolicy` | A port in an inner layer has no implementation |
+| `portPurity` | `PortRules_GivenTheRepository_RespectThePolicy` | A port exposes an infrastructure technology |
+| `dependencyBudget` | `AdoptionRules_GivenTheRepository_RespectThePolicy` | A project references beyond its budget, or the budget still allows a reference that has gone |
+| `siblingIndependence` | `SiblingImplementations_GivenTheirReferences_DoNotDependOnEachOther` | A qualified implementation referencing a qualified sibling |
+| `compositionBoundary` | `Implementations_GivenTheirReferences_DoNotDependOnComposition` | A non-host project referencing the composition root (`category == "composition"`) |
+| `forbiddenPackage` | `ProductionProjects_GivenTheirPackages_AvoidForbiddenFrameworkDependencies` | A package matching a forbidden prefix for that responsibility |
+| `forbiddenFramework` | `ProductionProjects_GivenTheirFrameworkReferences_AvoidForbiddenFrameworks` | A `` matching a forbidden prefix, e.g. `Microsoft.AspNetCore.App` in a portable layer |
+| `cycle` | `ProjectGraph_GivenItsReferences_HasNoCycles` | A dependency cycle, reported readably |
+| `testReference` | `ProductionProjects_GivenTheirReferences_DoNotReferenceATestProject` | Production code referencing a test project |
+| `waiverIntegrity` | `PolicyWaivers_GivenTheirDefinitions_AreJustifiedAndStillApply` | A waiver that is stale, unjustified, malformed, or excuses an unknown rule id |
+
+A separate test validates the policy against the schema first, because a policy that does not match
+its schema may be silently missing a rule.
+
+## Policy integrity
+
+`policyIntegrity` always runs and is **not waivable**, so a broken policy cannot be excused. It
+reports what a JSON Schema cannot express:
+
+- a `mayDependOn` or `mustNotDependOn` entry that names no responsibility — aliases and project
+ names do not count in the matrix;
+- the same responsibility in both lists, which is a contradiction rather than a choice;
+- two responsibilities with the same name, or an alias that equals a name or another alias;
+- with `checkReachability`, a `mustNotDependOn` the permitted `mayDependOn` closure can reach. The
+ message prints the path, such as `Core -> Application -> Persistence`.
+
+```json
+"policyIntegrity": {
+ "checkReachability": true
+}
+```
+
+Reachability is opt-in because it is a stronger claim: the direct lists can be consistent while a
+longer permitted path still defeats the prohibition.
+
+## Check it without a test run
+
+```bash
+dotnet tool install --global Purview.Architecture.Testing.Cli
+architests validate
+architests waivers list --stale
+```
+
+`validate` runs the schema check and `policyIntegrity`; it needs no build. Exit codes are `0` clean,
+`1` findings, `2` a malformed command line. Both commands accept `--repository `; without it
+the tool walks up from the current directory and stops at the repository boundary.
+
+`graphDiscovery` runs before the rules it protects. If `sourceRoots` is wrong, discovery finds
+nothing and every other rule passes vacuously — that is what this rule exists to stop.
+
+## The type-level rule
+
+A project file only shows a declared `ProjectReference`. `assemblyDependencyMatrix` reads the
+compiled assemblies by **metadata only** — no assembly is loaded or executed — and checks every
+external type each one references against the same `mayDependOn` / `mustNotDependOn` matrix. It
+catches what a project file cannot: a type that only arrives transitively, or through a package.
+
+```json
+"assemblyRules": {
+ "enabled": true,
+ "assemblyRoots": [],
+ "assemblyGlobs": ["*.dll"]
+}
+```
+
+- **Off by default.** It needs a build to have produced the assemblies, so it is opt-in.
+- An empty `assemblyRoots` scans the test output directory, which already holds every project the
+ test project references, directly or transitively. Set it to repo-relative folders only if the
+ assemblies are somewhere else.
+- Semantics mirror `dependencyMatrix`: same-responsibility references are always allowed; a
+ reference the matrix neither permits nor forbids is a violation.
+- Enabled with nothing found is a **failure**, not a silent pass — the same guard `graphDiscovery`
+ provides for projects.
+- Qualified implementations collapse into their responsibility, so `Persistence.SqlServer` is
+ `Persistence` at the type level too. Qualification is a naming choice, never a different rule.
+
+Assemblies are attributed to projects by the SDK's generated `Assembly` marker when a
+project's `AssemblyName` is unrelated to its name, and by name otherwise.
+
+## Type naming, shape and namespace
+
+The same reader exposes the public declarations a project compiles, which powers four opt-in rules:
+`typeNaming`, `typeShape`, `typeNamespace` and `attributePolicy`. They are configured under
+`typeRules`, off by default, and share the assembly roots and globs above.
+
+```json
+"typeRules": {
+ "enabled": true,
+ "appliesTo": { "categories": ["domain", "application", "shared"] }
+}
+```
+
+Use the `purview-architests-type-rules` skill for what each rule catches, why a type is reported, and
+how to fix or waive it. A disabled group produces no test, so a missing type-rule test is a policy
+setting rather than a silent pass.
+
+## Classifying test and production projects
+
+The package decides which projects the rules govern from the project graph:
+
+- A project is a **test project** when its name ends with `Tests`, **or** its path contains a
+ `tests` directory. Test projects are excluded from every rule — a test references everything by
+ design, so applying the matrix to it would make the rule set unusable.
+- Everything else is a **production project**, and every rule applies to it.
+
+## API baseline and ports
+
+Four more rules are opt-in. `apiRules` compares the public API with a committed baseline and checks
+its documentation; `portRules` checks that inner-layer interfaces are implemented and stay
+technology-neutral.
+
+```json
+"apiRules": { "enabled": true },
+"portRules": { "enabled": true }
+```
+
+Write the baseline with the tool, never by hand:
+
+```bash
+architests api capture # write .config/api-surface.json
+architests api check # exit 1 on any difference
+```
+
+A missing baseline is itself an `apiSurface` failure. A removal is reported as breaking; an addition
+still needs a reviewed baseline change, because the baseline is the contract. The
+`purview-architests-contracts` skill covers the baseline document, documentation requirements and
+the port rules in detail.
+
+## Dependency budget
+
+`dependencyBudget` is a ratchet on the project graph: it records the references each project may
+declare today, so a new dependency needs a reviewed policy change.
+
+```json
+"dependencyBudget": {
+ "enabled": true,
+ "failOnStale": true,
+ "entries": [
+ { "project": "Application", "references": ["Domain"] }
+ ]
+}
+```
+
+- A reference outside the entry is a `dependencyBudget` failure.
+- With `failOnStale` (the default), an allowance the project no longer uses fails too, so the budget
+ only tightens.
+- It is **not waivable**, and a project without an entry is not budgeted.
+- Start with `entries: []`, then add one project at a time.
+
+## See it working
+
+`src/samples/ArchitectureSample` is a six-project repository that exercises every rule group: a port
+with two adapters, a waived legacy project, the type rules, the committed baseline and a dependency
+budget. Use it as the reference when a policy question is easier to answer from a working example
+than from prose.
+
+## Prefer a waiver to a skip
+
+```csharp
+protected override bool SkipRule(string rule) => rule == ArchitectureRules.DiscouragedName;
+```
+
+`SkipRule` removes a rule for the whole repository, with no record. A waiver is better: it is per
+project, carries a reason and a review date, keeps every other rule in force for that project, and
+is itself checked by `waiverIntegrity`.
+
+```json
+"waivers": [
+ {
+ "project": "Legacy.Utilities",
+ "mapsTo": "Shared",
+ "rules": ["naming"],
+ "reason": "Predates the catalogue; renaming breaks a published package id.",
+ "reviewedOn": "2026-01-14"
+ }
+]
+```
+
+`mapsTo` is the useful part: it maps an established project onto the responsibility it actually has,
+so the dependency rules still apply in full and only the *name* is excused.
+
+Any waivable rule id may be waived, including `siblingIndependence` and `assemblyDependencyMatrix`.
+An unknown id is a `waiverIntegrity` failure, so a typo cannot silently excuse nothing. Naming a
+guard (`policyIntegrity`, `graphDiscovery` or `waiverIntegrity`) is also a failure: those rules exist
+to keep the policy falsifiable, so a waiver that appears to excuse them would be a lie.
+
+### Waiver expiry
+
+```json
+"waiverPolicy": {
+ "maxAgeDays": 180
+}
+```
+
+A waiver reviewed longer ago than the maximum is a `waiverIntegrity` failure. So are a waiver with
+no `reviewedOn` while a maximum is set, a date that is not `yyyy-MM-dd`, and a date in the future.
+Expiry is off by default; adopting it turns the review date from a note into an obligation.
+
+## Adding your own rule
+
+A repository can add a bespoke check without a second architecture framework. Implement
+`IArchitectureRule` and return the same `ArchitectureViolation` type as the built-in rules:
+
+```csharp
+[InheritsTests]
+public sealed class ArchitectureTests : PurviewArchitectureTests
+{
+ protected override IReadOnlyList AdditionalRules => [new NoConsoleLoggingRule()];
+
+ sealed class NoConsoleLoggingRule : IArchitectureRule
+ {
+ public string Rule => "noConsoleLogging";
+
+ public IReadOnlyList Evaluate(ArchitectureContext context) =>
+ // context.Policy, context.Projects and context.Assemblies
+ [];
+ }
+}
+```
+
+Each additional rule becomes its own `[Test]` (`AdditionalRule_GivenTheRepository_RespectsThePolicy`),
+so a failure names the rule. It participates in the same failure reporting, `SkipRule` (by its
+`Rule` id) and waiver model — a waiver whose `rules` names it is honoured automatically.
+
+The `purview-architests-extending` skill covers the full extension point and the package's internals.
+
+## Reading a failure
+
+Each rule is its own test, so a failure names the rule rather than collapsing the set into one
+assertion. The `.Because(...)` text lists every violation the rule found.
+
+- `naming` — a project name is `[.]`, and only the **first segment**
+ is classified. `Persistence.SqlServer` and `Persistence` are both Persistence. Add an alias, or a
+ waiver with `mapsTo`.
+- `dependencyMatrix` / `assemblyDependencyMatrix` — fix the reference, or move the type. Widening
+ `mayDependOn` is the last resort, and it is a policy change that needs review.
+- `forbiddenPackage` — by default the package is one the project **owns**: declared, injected by
+ `Directory.Build.props`, or pulled in by its own package references. A package inherited from a
+ permitted project reference is not reported, so a host is not blamed for its adapter’s EF Core.
+ Set `forbiddenPackageScope: "closure"` on the responsibility only when the strict compile-graph
+ guarantee is intended.
+- `forbiddenFramework` — a `` on a project that should not have it. Move it to
+ the responsibility that owns that technology.
+- `graphDiscovery` — almost always a wrong `sourceRoots`. An empty array scans the repository root,
+ which suits a flat layout.
+- `assemblyDependencyMatrix` reporting "no compiled assemblies" — the projects were not built, or
+ `assemblyRoots` points at the wrong folder.
+
+## The three layers
+
+Useful when extending the package rather than consuming it:
+
+- `ArchitecturePolicy` / `ProjectGraph` / `AssemblyGraph` — read the policy, the `.csproj` graph and
+ the compiled assembly metadata. No MSBuild and no test-framework types.
+- `ArchitecturePolicyEvaluator` — the rules, returning typed `ArchitectureViolation` lists. It takes
+ an **in-memory graph**, so a rule is tested as a three-project fixture rather than a repository on
+ disk.
+- `PurviewArchitectureTests` — the TUnit wrapper, one `[Test]` per rule.
+
+Project files are read because a declared `ProjectReference` is what a reviewer adds and what the
+policy governs; compiled assemblies are read separately because they catch what the project file
+does not show.
+
+## Overrides
+
+```csharp
+[InheritsTests]
+public sealed class ArchitectureTests : PurviewArchitectureTests
+{
+ protected override string? RepositoryRoot => "/path/to/repo";
+}
+```
+
+`RepositoryRoot` defaults to probing upward from the test binary for the policy file. The search
+**stops at the repository boundary** (`.git`) rather than continuing into parent folders — walking
+past it would happily find a sibling checkout's policy and validate this repository against someone
+else's rules.
+
+## Policy schema version
+
+The current policy document version is **3**. Version 3 adds `typeRules`, `policyIntegrity` and
+`waiverPolicy`, all optional, so a version-2 policy remains valid. Version 2 removed the `rules` object
+(`noCycles`, `noProductionToTestReferences`, `implementationsMustNotReferenceComposition`,
+`siblingImplementationsIndependent`), whose flags were deserialised but never consulted. Use
+`SkipRule` or a waiver to opt out of a rule. A version-1 policy that set `rules` must delete the
+block; a version-1 policy that did not still validates.
diff --git a/.agents/skills/purview-buildsdk-adoption/SKILL.md b/.agents/skills/purview-buildsdk-adoption/SKILL.md
new file mode 100644
index 00000000..b1f222c5
--- /dev/null
+++ b/.agents/skills/purview-buildsdk-adoption/SKILL.md
@@ -0,0 +1,114 @@
+---
+name: purview-buildsdk-adoption
+description: Adopt Purview.BuildSdk in a repository, or troubleshoot an adoption that is not behaving. Use when wiring the SDK into Directory.Build.props for the first time, when a property seems to have no effect, when the resolved version or namespace is wrong, or when a consuming repository builds but the SDK's automatic behaviour is not appearing. Covers the import chain, pre-import property ordering, and version detection from package.json.
+license: MIT
+metadata:
+ package: Purview.BuildSdk
+ repository: purview-dev/build-sdk
+---
+
+# Adopting Purview.BuildSdk
+
+The goal is a working adoption that does not break existing build behaviour. Prefer minimal,
+targeted property changes over rewriting a repository's `Directory.Build.props`.
+
+For the full property list use `purview-buildsdk-configuration`; for auditing an existing
+repository's shape, `purview-buildsdk-repository-review`.
+
+## 1. The import chain
+
+```xml
+
+
+
+
+ Acme.Sales
+
+
+
+
+```
+
+```xml
+
+
+
+
+```
+
+Both halves are required. A repository with only `Sdk.props` imported gets the evaluation-time
+defaults — naming, identity, framework selection — but none of the targets, so validation,
+packaging behaviour and the generated files never run. That combination usually presents as "the
+properties look right but nothing happens".
+
+The SDK version comes from `global.json`, which the SDK itself bootstraps.
+
+## 2. Pre-import ordering is the first thing to check
+
+**A property that must affect `Sdk.props` evaluation has to be set before the import.** Setting it
+in a `.csproj`, or below the import, is too late and silently does nothing — no error, no warning.
+This is the single most common adoption failure.
+
+Set before the import:
+
+- `NamespacePrefix`
+- `UsePackageJsonVersion`, `RootPackageJson`
+- `EnableAssemblyNameGeneration`
+- `AutoIncludeUsings`
+- `PurviewSharedTestingOutputType`, `PurviewTestContextNoWarn`
+- any repo-wide testing-framework selection you want every project to inherit
+
+Everything else is read in `Sdk.targets` and can be set in a project file.
+
+When a property appears to have no effect, confirm what MSBuild actually resolved before changing
+anything else:
+
+```bash
+dotnet msbuild -getProperty:NamespacePrefix -getProperty:RootNamespace
+```
+
+## 3. Version detection
+
+Versions come from `package.json`. Resolution order:
+
+1. An explicit `RootPackageJson`.
+2. CI workspace variables.
+3. The `.git` root.
+4. A nearby `package.json`.
+
+On success both `Version` and `PackageVersion` are set from the `version` field.
+
+If the version looks wrong, do not guess at the discovery — make it fail loudly instead:
+
+```xml
+Strict
+```
+
+`Strict` fails the build when discovery or resolution cannot succeed, rather than silently skipping
+it and leaving the default `1.0.0`. Set `VersionDetectionLogEnabled=true` to see what it found.
+
+## 4. Naming and placement
+
+Most of the SDK's value is inferred from project names and locations, so an adoption that keeps a
+bespoke structure gets correspondingly little. Confirm the repository follows the conventions rather
+than introducing new structure to work around them — see `purview-buildsdk-project-layout`, and
+`purview-buildsdk-repository-review` for auditing an existing layout.
+
+The highest-value single check: every test project is named `.Tests`. **The dot is
+required.** A project named plainly `UnitTests` is not detected as a test project at all, and
+silently gets no runner, no coverage, no `InternalsVisibleTo` and no category.
+
+## 5. Agent skills are a separate, explicit step
+
+The SDK does not install agent skills, and nothing it does during a build writes to an agent
+directory. It reads which skills each referenced package ships and recommends the command that
+installs them; the skills CLI does the installing. See `purview-buildsdk-skill-installation`.
+
+## Constraints
+
+- Prefer minimal, targeted property changes over broad `Directory.Build.props` rewrites.
+- Do not disable `PurviewAutoSdkPack` unless the consumer explicitly asks to opt out.
+- Do not restate an SDK default in a project file. Hand-configuration that merely repeats a default
+ is pure maintenance cost, and it hides the fact that the default later changed.
+- Re-run the build — or the repository's canonical build command — after each change, and confirm
+ the fix before moving to the next one.
diff --git a/.agents/skills/purview-buildsdk-configuration/SKILL.md b/.agents/skills/purview-buildsdk-configuration/SKILL.md
new file mode 100644
index 00000000..f0ee7156
--- /dev/null
+++ b/.agents/skills/purview-buildsdk-configuration/SKILL.md
@@ -0,0 +1,110 @@
+---
+name: purview-buildsdk-configuration
+description: Configure Purview.BuildSdk from Directory.Build.props or a .csproj. Use when setting NamespacePrefix, choosing a testing or mocking framework, turning telemetry or SourceLink off, controlling version detection from package.json, tuning the repository bootstrap, or working out whether a property must be set before the SDK import. Also use when the SDK "did something automatically" and you need the property that controls it.
+license: MIT
+metadata:
+ package: Purview.BuildSdk
+ repository: purview-dev/build-sdk
+---
+
+# Purview.BuildSdk configuration
+
+Use this skill when the question is "what property controls this, and where do I set it?"
+
+For *why* the SDK classified a project a particular way, use `purview-buildsdk-project-detection`
+instead. For where projects and tests should live, use `purview-buildsdk-project-layout`.
+
+## First rule: know where a property must be set
+
+A property that changes `Sdk.props` evaluation must be set **before** the SDK import — in
+`Directory.Build.props`, above the import. Setting it in a `.csproj` is too late and silently has no
+effect.
+
+Pre-import properties include:
+
+- `NamespacePrefix`
+- `UsePackageJsonVersion`, `RootPackageJson`
+- `EnableAssemblyNameGeneration`
+- `PurviewSharedTestingOutputType`, `PurviewTestContextNoWarn`
+- `AutoIncludeUsings`
+- repo-wide testing-framework selection you want every project to inherit
+
+Everything else is read in `Sdk.targets` and can be set in a project file. Prefer repo-wide defaults
+in `Directory.Build.props` unless the setting is deliberately project-specific.
+
+## The properties you will reach for most
+
+| Property | Default | What it does |
+| -- | -- | -- |
+| `NamespacePrefix` | *(required)* | The root identity. Required unless `DisableNamespacePrefixCheck=true` |
+| `TestingFramework` | `TUnit` | `TUnit`, `Xunit` or `None` |
+| `SubstituteFramework` | `TUnitMocks` | `TUnitMocks`, `NSubstitute` or `None` |
+| `TestDataFramework` | `Bogus` | `Bogus` or `None` |
+| `TargetFramework` | `net10.0` | `netstandard2.0` when `IsRoslynComponent=true` |
+| `IsPackable` | `false` | Opts a project into the packable defaults |
+| `UsePackageJsonVersion` | `true` | `true`, `false` or `Strict` — version from `package.json` |
+| `ExcludePurviewTelemetry` | `false` | Drops the telemetry source generator |
+| `DisableSourceLink` | `false` | Drops SourceLink from packable projects |
+| `EnableAssemblyNameGeneration` | `true` | `AssemblyName`/`PackageId` follow the resolved `RootNamespace` |
+
+The full set, grouped by area and with the behaviour each one changes, is in
+[references/properties.md](references/properties.md). Read it rather than guessing a property name —
+several of these have near-miss names that do nothing.
+
+## Derived properties to inspect, not re-derive
+
+When explaining what the SDK did, read the value it computed rather than reasoning from the folder
+name:
+
+`PurviewLogicalProjectName`, `PurviewNamespacePrefix`, `PurviewProjectShortName`, `PurviewTestType`,
+`RootNamespace`, `AssemblyName`, `PackageVersion`, `TestingType`, `TargetProjectName`, `RepoRoot`,
+`RootPackageJson`.
+
+Ask MSBuild for one directly:
+
+```bash
+dotnet msbuild -getProperty:RootNamespace
+dotnet msbuild -getProperty:TestingType -getProperty:TargetProjectName
+```
+
+## Compiler-visible properties
+
+The SDK exports its properties to analyzers and generators as `build_property.`. When
+authoring an analyzer, read the exported property instead of re-deriving SDK behaviour — the export
+is the SDK's answer, and it stays correct when the rules change. The exported set is listed in
+[references/properties.md](references/properties.md).
+
+## Version detection
+
+1. If `RootPackageJson` is set, that file is used.
+2. Otherwise the repo root is discovered from CI variables, `.git`, or a nearby `package.json`.
+3. On success, both `Version` and `PackageVersion` come from the `version` field.
+4. `UsePackageJsonVersion=Strict` turns a failed discovery into a build failure instead of a silent
+ fallback.
+
+## Repository bootstrap
+
+The SDK bootstraps two repository-wide files from the package: `.editorconfig` and `global.json`.
+
+- `PurviewRepoBootstrapMode` — `IfMissing` (default), `Always`, `WarnOnDrift`, `Never`
+- `DisableAutoCopySdkFiles` — the master off switch
+- `PurviewRepoBootstrapCopyRetries` / `...RetryDelayMilliseconds` / `...FailureAsError`
+
+Every project in a solution writes those same destinations, so the write is race-tolerant by
+design: an existing file is never overwritten unless asked, each write is staged into a temporary
+file and renamed into place, retries are quiet, and only a failure that survives every retry is
+reported.
+
+**The SDK writes nothing into an agent directory.** It used to mirror a package's `.agents/**` into
+the repository; that is gone, along with `EnableAgentFolderInPackage`, `AgentPackDestinationFolder`
+and the `PurviewAgentFolder*` properties. Skills have exactly one installer, the skills CLI — see
+`purview-buildsdk-skill-installation`.
+
+## Guidance when changing SDK configuration
+
+1. Preserve existing defaults unless the task explicitly changes product behaviour.
+2. Keep `README.md`, the property declaration, its validation and the shipped skills aligned — a
+ property documented in one place and absent from another is the failure mode this repository
+ keeps hitting.
+3. A new property that affects import-time behaviour must say so in its documentation.
+4. Add the property to the `CompilerVisibleProperty` list if an analyzer would benefit from it.
diff --git a/.agents/skills/purview-buildsdk-configuration/references/properties.md b/.agents/skills/purview-buildsdk-configuration/references/properties.md
new file mode 100644
index 00000000..93a0d9b3
--- /dev/null
+++ b/.agents/skills/purview-buildsdk-configuration/references/properties.md
@@ -0,0 +1,146 @@
+# Purview.BuildSdk property reference
+
+Every user-facing property, grouped by what it changes. Defaults are what the SDK applies when the
+consuming project supplies nothing.
+
+## Identity and naming
+
+| Property | Default | Behaviour |
+| -- | -- | -- |
+| `NamespacePrefix` | *(required)* | The root identity source. Required unless the check is disabled. Set before the SDK import |
+| `DisableNamespacePrefixCheck` | `false` | Stops the build failing when `NamespacePrefix` is unset |
+| `EnableAssemblyNameGeneration` | `true` | `AssemblyName` and the default `PackageId` follow the fully evaluated `RootNamespace`, or the full logical project name when suffix-stripping removed a segment (`Shared`, `ServiceDefaults`). Set `false` before the SDK import for standard project-name behaviour |
+| `AssemblyIdentifierClassName` | *(derived)* | Renames the generated marker class |
+| `DisableGenerateAssemblyIdentifierClass` | `false` (forced `true` for test and shared-testing projects) | Drops the empty marker class (`Assembly`, global namespace) that architecture tests use to pin an assembly by `typeof` rather than by name |
+| `DisableGenerateAssemblyInfoClass` | `false` | Drops the generated `AssemblyInfo` |
+| `DisableAutoInternalsVisibleTo` | `false` | Drops automatic friend-assembly generation |
+| `DisableProjectFileNamingConventionCheck` | `false` | Stops validating that the `.csproj` filename matches its directory |
+| `AutoIncludeUsings` | `true` | Controls the SDK-added global usings. Set before the SDK import |
+
+## Target framework and language
+
+| Property | Default | Behaviour |
+| -- | -- | -- |
+| `TargetFramework` | `net10.0` | Applied when neither `TargetFramework` nor `TargetFrameworks` is set. A project that explicitly declares `IsRoslynComponent=true` defaults to `netstandard2.0` |
+| `IsRoslynComponent` | *(unset)* | When explicitly `true`: a single `netstandard2.0` target, `LangVersion=latest`, `Nullable=enable`, `TreatWarningsAsErrors=true`, `Deterministic=true`, extended analyzer rules, SourceLink with `EmbedUntrackedSources=true`, no dependency file, telemetry exclusion, and `PrivateAssets=all` on `Microsoft.CodeAnalysis.*` references |
+| `IsRoslynComponentOnly` | `true` for Roslyn components | Analyzer-only package: `IncludeBuildOutput=false`, `IncludeSymbols=false`, portable PDB packed beside the analyzer under `analyzers/dotnet/cs/`. Set `false` for a dual-role component using normal library symbol packaging |
+| `DisableRoslynCompilerDefaultsValidation` | `false` | Opts out of `ValidateRoslynComponentCompilerSettings`, which fails the pack of a packable Roslyn component missing `LangVersion`, `Nullable`, `TreatWarningsAsErrors` or `EnforceExtendedAnalyzerRules` |
+| `PackProjectReferencedSourceGenerators` | `true` | Packable projects include analyzer `ProjectReference` outputs under `analyzers/dotnet/cs/`. Use `Pack="false"` on one reference to opt that one out |
+
+## Style policy
+
+| Property | Default | Behaviour |
+| -- | -- | -- |
+| `DisablePurviewStylePolicyValidation` | `false` | Stops the build failing (`PRSGD0006`–`PRSGD0009`) when the repository `.editorconfig` overrides the modifier policy — `dotnet_style_require_accessibility_modifiers` other than `omit_if_default`, hiding `IDE0040`/`IDE1006`, disabling the Style category in bulk, weakening the `_camelCase` private-instance-field rule, or adding the accessibility rules to `NoWarn`. Entries the SDK injects itself are ignored |
+| `PurviewTestContextNoWarn` | `CA1002;CA1012;CA1034;CA1047;CA1050;CA1051;CA1062;CA1064;CA1515;CA1707` | The production API-surface rules exempted in test and shared-testing projects. Test projects keep the strict style contract (`IDE0040`, field naming, formatting, `IDE1006`) but are context aware: public test classes, `Method_Scenario_Expectation` names, exposed fields and unvalidated helper parameters are allowed. Set before the SDK import |
+| `DisablePurviewTestContextRuleSet` | `false` | Makes test and shared-testing projects enforce the production API-surface rules too |
+| `PurviewPolicyExemptNoWarn` | *(derived)* | The SDK-injected `NoWarn` entries `ValidatePurviewStylePolicy` accepts |
+
+## Testing
+
+| Property | Default | Behaviour |
+| -- | -- | -- |
+| `TestingFramework` | `TUnit` | `TUnit`, `Xunit`, `None` |
+| `SubstituteFramework` | `TUnitMocks` | `TUnitMocks`, `NSubstitute`, `None` |
+| `TestDataFramework` | `Bogus` | `Bogus`, `None` |
+| `CollectCoverage` | `true` for detected test projects | |
+| `EnableStaticNativeInstrumentation` | `false` for test projects | |
+| `EnableDynamicNativeInstrumentation` | `false` for test projects | |
+| `TestingPlatformDotnetTestSupport`, `UseMicrosoftTestingPlatformRunner`, `EnableMicrosoftTestingPlatform` | enabled for TUnit test projects | Microsoft.Testing.Platform wiring |
+| `PurviewSharedTestingOutputType` | `Library` | Forced onto `IsSharedTestingProject` projects, with `IsTestProject`/`IsTestingPlatformApplication` cleared, because the test packages otherwise flip them into an executable test host. Set `Exe` before the SDK import to keep the package-driven shape |
+
+## Packaging
+
+| Property | Default | Behaviour |
+| -- | -- | -- |
+| `IsPackable` | `false` | |
+| `PurviewAutoSdkPack` | `true` | Packs `Sdk/**/*` into the package at the right root-level paths |
+| `PurviewSkillsSourceFolder` | `/skills` | Where authored skills live |
+
+Packable-project defaults, applied only when the project supplied nothing:
+`GenerateDocumentationFile=true`, `IncludeSymbols=true`, `SymbolPackageFormat=snupkg`,
+`PublishRepositoryUrl=true`, `EmbedUntrackedSources=true`, `DebugType=portable`. Portable PDBs ship
+in the `.snupkg`; the `.nupkg` gets none unless the project opts in. Roslyn-component-only packages
+instead default `IncludeSymbols=false` and ship their PDB inside `analyzers/dotnet/cs/`.
+
+When the repository root is discoverable, the root `README.md` is packed automatically and
+registered as `PackageReadmeFile`, unless one is configured already.
+
+Non-packable projects, including web apps, default `WarnOnPackingNonPackableProject=false` so a
+solution-wide pack skips them silently.
+
+`ContinuousIntegrationBuild` is set only by real CI environment variables. Packability alone never
+forces SourceLink's CI-mode dirty-repository checks.
+
+## Telemetry and SourceLink
+
+| Property | Default | Behaviour |
+| -- | -- | -- |
+| `ExcludePurviewTelemetry` | `false` | Removes `Purview.Telemetry.SourceGenerator` |
+| `ExcludeMSTelemetryExtension` | `false` | Removes `Microsoft.Extensions.Telemetry.Abstractions`. Only relevant when `ExcludePurviewTelemetry` is also `false` — the whole group is skipped otherwise |
+| `SourceLinkPackageName` | `Microsoft.SourceLink.GitHub` | |
+| `DisableSourceLink` | `false` | |
+
+## Version detection
+
+| Property | Default | Behaviour |
+| -- | -- | -- |
+| `UsePackageJsonVersion` | `true` | `true`, `false`, `Strict` |
+| `RootPackageJson` | *(discovered)* | Explicit path to the `package.json` to read |
+| `EnableVersionDetectionCache` | `true` | |
+| `VersionDetectionCacheFile` | *(derived)* | |
+| `VersionDetectionLogEnabled` | `false` | Logs the detected version |
+
+## Repository bootstrap
+
+| Property | Default | Behaviour |
+| -- | -- | -- |
+| `DisableAutoCopySdkFiles` | `false` | Master switch for SDK-managed repository file writes |
+| `PurviewRepoBootstrapMode` | `IfMissing` | Also `Always`, `WarnOnDrift`, `Never` |
+| `BootstrapEditorConfigToRepoRoot` | `true` | |
+| `RepositoryEditorConfigFilePath` | *(derived)* | Overrides the destination `.editorconfig` |
+| `BootstrapGlobalJsonToRepoRoot` | `true` | |
+| `RepositoryGlobalJsonFilePath` | *(derived)* | Overrides the destination `global.json` |
+| `PurviewBuildSdkVersionForGlobalJson` | detected SDK version, else `1.0.0` | |
+| `PurviewRepoBootstrapCopyRetries` | `3` | |
+| `PurviewRepoBootstrapCopyRetryDelayMilliseconds` | `500` | |
+| `PurviewRepoBootstrapCopyFailureAsError` | `true` | `false` downgrades a persistent write failure to a warning |
+| `PurviewSuppressCopyRetryWarnings` | `true` | Demotes the built-in copy task's `MSB3026` retry notice to a message |
+| `PurviewRepositoryRootMarkers` | `.git/;.github/;.gitattributes;LICENSE.md;AGENTS.md;.agents/;CLAUDE.md;.claude/;package.json` | Ordered markers identifying a repository root, most authoritative first |
+
+There is no agent-folder mirror. `EnableAgentFolderInPackage`, `AgentPackDestinationFolder`,
+`PurviewAgentFolderSourcePath`, `PurviewAgentFolderCopy*`, `PurviewAgentSyncManifestPath` and
+`DisableMirroredFileTrackingCheck` were removed: skills are installed by the skills CLI, and
+nothing else was left for the mirror to deliver.
+
+## Skills
+
+Covered in full by `purview-buildsdk-skill-installation`: `PurviewSkillsRunner`,
+`PurviewSkillsRunnerCandidates`, `PurviewSkillsCommand`, `PurviewSkillsPackage`,
+`PurviewSkillsAgents`, `PurviewSkillsSource`, `PurviewSkillsInstallRoot`, `PurviewSkillsRepoRoot`,
+`EnablePurviewSkillRecommendations`, `PurviewSkillRecommendationsInCI`.
+
+## Compiler-visible properties
+
+Exported to analyzers and generators as `build_property.`:
+
+- `UsePackageJsonVersion`, `RootPackageJson`, `RepoRoot`, `Version`, `PackageVersion`
+- `NamespacePrefix`, `DisableNamespacePrefixCheck`
+- `TestingFramework`, `SubstituteFramework`, `TestDataFramework`
+- `ExcludePurviewTelemetry`, `ExcludeMSTelemetryExtension`
+- `EnableAssemblyNameGeneration`, `DisableAutoInternalsVisibleTo`, `DisableGenerateAssemblyInfoClass`,
+ `DisableGenerateAssemblyIdentifierClass`, `AssemblyIdentifierClassName`
+- `IsCSharpProject`, `IsTestProject`, `IsSharedTestingProject`, `IsSharedProject`
+- `TestingType`, `TargetProjectName`
+- `IsContainerProject`, `IsSdkProject`, `SdkProjectName`, `IsWebProject`, `IsWebSdkProject`,
+ `IsWorkerSdkProject`, `IsAspireHostProject`, `IsCLIProject`
+- `EditorConfigFilePath`, `RepositoryEditorConfigFilePath`, `BootstrapEditorConfigToRepoRoot`
+- `RepositoryGlobalJsonFilePath`, `BootstrapGlobalJsonToRepoRoot`, `DisableAutoCopySdkFiles`
+- `PurviewRepoBootstrapMode`, `PurviewRepoBootstrapCopyRetries`,
+ `PurviewRepoBootstrapCopyRetryDelayMilliseconds`, `PurviewRepoBootstrapCopyFailureAsError`
+- `PurviewSuppressCopyRetryWarnings`
+- `PurviewSkillsSourceFolder`,
+ `PurviewSkillsAgents`, `PurviewSkillsInstallRoot`, `PurviewRepositoryRootMarkers`,
+ `PurviewSkillsRunner`
+- `PurviewBuildSdkVersionForGlobalJson`, `CurrentYear`, `AutoGeneratedAssemblyInfoFile`,
+ `AutoGeneratedAssemblyIdentifierFile`
diff --git a/.agents/skills/purview-buildsdk-project-detection/SKILL.md b/.agents/skills/purview-buildsdk-project-detection/SKILL.md
new file mode 100644
index 00000000..2d0d9862
--- /dev/null
+++ b/.agents/skills/purview-buildsdk-project-detection/SKILL.md
@@ -0,0 +1,134 @@
+---
+name: purview-buildsdk-project-detection
+description: Explain why Purview.BuildSdk classified a project as test, shared, shared-testing, CLI, web, worker, Aspire host, container or Roslyn component, and why it added a package, a project reference, a namespace or an analyzer automatically. Use when SDK behaviour looks surprising, when a test project gets no runner or no InternalsVisibleTo, or when reasoning about RootNamespace, AssemblyName and TargetProjectName.
+license: MIT
+metadata:
+ package: Purview.BuildSdk
+ repository: purview-dev/build-sdk
+---
+
+# Why Purview.BuildSdk did that
+
+Use this skill when the question is **why** the SDK applied something automatically.
+
+For where a project should live, use `purview-buildsdk-project-layout`. For the property that turns
+a behaviour off, use `purview-buildsdk-configuration`.
+
+## Diagnose from computed properties, never from the folder name
+
+Read what the SDK actually computed:
+
+```bash
+dotnet msbuild -getProperty:PurviewLogicalProjectName -getProperty:RootNamespace \
+ -getProperty:TestingType -getProperty:TargetProjectName -getProperty:IsTestProject
+```
+
+The values worth inspecting first: `MSBuildProjectName`, `NamespacePrefix`,
+`PurviewLogicalProjectName`, `RootNamespace`, `TestingType`, `TargetProjectName`, `SdkProjectName`,
+`IsTestProject`, `IsSharedProject`, `IsSharedTestingProject`, `IsContainerProject`, `IsCLIProject`,
+`IsWebSdkProject`, `IsAspireHostProject`.
+
+## Detection rules
+
+### Test projects
+
+Name matches `^.*\.([\w|_]\w*)Tests?$` — a target name, a dot, then any word before `Test`/`Tests`.
+The captured word becomes `TestingType`.
+
+This is a pattern, **not** a lookup. `MyProject.GoldenTests` is detected exactly as readily as
+`MyProject.UnitTests`, with `TestingType=Golden` and `Category=Golden`, even though `Golden` is not a
+name the SDK ships.
+
+**The dot is required.** A project named plainly `UnitTests` does not match, and silently gets no
+runner, no coverage, no `InternalsVisibleTo` and no category. This is the single most common
+surprise.
+
+Derived: `IsTestProject=true`, `TestingType=`, `PurviewTestType=Tests`,
+`TargetProjectName=`.
+
+The SDK's explicit `TestType` item group governs **`InternalsVisibleTo` generation**, not detection:
+a non-test project grants access to `{AssemblyName}.{TestType}Tests` for each name in the group. A
+suffix outside it still builds, runs and gets a category — it just cannot see `internal` members.
+The 53 names are in [references/test-types.md](references/test-types.md).
+
+### Shared and shared-testing projects
+
+Recognised by **exact name**, never by substring. The two lists are in
+[references/detection.md](references/detection.md). Derived: `IsSharedProject`,
+`IsSharedTestingProject`.
+
+### SDK and content based
+
+| Signal | Result |
+| -- | -- |
+| the project's `Sdk="..."` declaration | `IsSdkProject`, `SdkProjectName` |
+| `Microsoft.NET.Sdk.Web` | `IsWebSdkProject=true` |
+| `Microsoft.NET.Sdk.Worker` | `IsWorkerSdkProject=true` |
+| SDK starts with `Aspire.Sdk.Host` or `Aspire.AppHost.Sdk` | `IsAspireHostProject=true` |
+| `Dockerfile`, `dockerfile` or `Dockerfile.dev` in the project directory | `IsContainerProject=true` |
+| name ends with `CLI`, `Console`, `CommandLine`, `QuickStart`, `QuickStarts` | `IsCLIProject=true` |
+
+## Namespace and identity
+
+1. `PurviewLogicalProjectName` is `NamespacePrefix` plus the project name, de-duplicated when the
+ project name already starts with the prefix's tail.
+2. `RootNamespace` defaults to `PurviewLogicalProjectName`.
+3. Known suffixes are stripped from `RootNamespace` — shared and shared-testing names, and segments
+ such as `Core`, `EF`, `Shared`, `ClientShared`, `ServiceDefaults`.
+4. Test suffixes are stripped too, so `Acme.Api.UnitTests` maps back to `Acme.Api`.
+5. `AssemblyName` and `PackageId` default to the fully evaluated `RootNamespace` — except where
+ stripping removed a segment, where they use the full `PurviewLogicalProjectName` so the artifact
+ stays distinct from its parent. Test and shared-testing projects keep their detected suffix.
+ Explicit `AssemblyName`/`PackageId`/`RootNamespace` always win.
+6. The naming defaults are applied during `Sdk.props`, before the Microsoft SDK computes
+ `TargetName`, so the compiled output name always matches `AssemblyName`.
+
+## Automatic packages and references
+
+- **Non-test C# projects**: SourceLink (unless `DisableSourceLink`), the Purview telemetry packages
+ (unless `ExcludePurviewTelemetry`), `GenerateDocumentationFile=true`, and `InternalsVisibleTo`
+ generation (unless `DisableAutoInternalsVisibleTo`).
+- **Test and shared-testing projects**: test-friendly `NoWarn` defaults, not packable or
+ publishable, and the packages selected by `TestingFramework`, `SubstituteFramework` and
+ `TestDataFramework`. TUnit test projects get Microsoft.Testing.Platform wiring automatically.
+ Shared-testing projects skip the runnable test package.
+- **Packable projects**, **Roslyn components** and **special project types** (CLI, container, web,
+ Aspire host): see [references/detection.md](references/detection.md).
+
+Project-reference probing is layout-driven and covered by `purview-buildsdk-project-layout`.
+
+## The shipped analyzers
+
+The SDK adds `Purview.BuildSdk.Analyzers` as an `` item to every C# project, so its rules
+surface in command-line builds and in Visual Studio. The code-fix assembly ships beside it.
+
+| Rule | What it enforces |
+| -- | -- |
+| `PDS0002` | Extensions classes live under `Extensions//` |
+| `PDS0003` | Explicit types with target-typed `new()` |
+| `PDS0004` | Correct acronym capitalisation |
+
+`PDS0004` follows .NET naming guidance: well-known framework spellings (`Sql`, `Guid`, `Uuid`,
+`Url`, `Dns`, `Tcp`, `Http`, `Xml`, `Db`, …) are exempt — `Db` among them, so `DbContext`,
+`DbConnection` and `DbSet` are never flagged. A small set is still uppercased: `Api`, `Ai`, `Ui`,
+`Io`, `Os`, `Cpu`, `Gpu`, `Cli`, `Gui`, `Ram`, `Ssh`. Members mandated by a contract — interface
+implementations and base-class overrides — are never renamed.
+
+Customise through `dotnet_analyzer_configuration.pds0004.allowed_words` (exempt segments),
+`.acronym_map` (segment renames, e.g. `Sql:SQL`, or `Db:DB` to re-enable it) and
+`.allowed_identifiers` (brand names, exact or word-boundary prefix, first match wins — `CosmosDb`
+covers `CosmosDbServer`). All three merge with and override the shipped defaults.
+
+The shipped `.editorconfig` marks generated content (`Migrations/`, `*.g.cs`, `Generated/`,
+`*.Designer.cs`, `obj/`, `bin/`) as `generated_code = true`, and suppresses namespace-conflict
+diagnostics under `Extensions/`, so no `#pragma` suppressions are needed there.
+
+Two Visual Studio refactorings ship with them, both described in
+[references/detection.md](references/detection.md).
+
+## When changing a detection rule
+
+1. Keep the `.csproj` filename equal to its directory name.
+2. Update `README.md` and the shipped skills in the same change — a rule true in code and false in
+ prose is this repository's recurring failure.
+3. Add or update the integration test in `src/tests/BuildSdk.IntegrationTests/` that pins it.
diff --git a/.agents/skills/purview-buildsdk-project-detection/references/detection.md b/.agents/skills/purview-buildsdk-project-detection/references/detection.md
new file mode 100644
index 00000000..bf75823d
--- /dev/null
+++ b/.agents/skills/purview-buildsdk-project-detection/references/detection.md
@@ -0,0 +1,79 @@
+# Detection detail
+
+## Shared project names (exact)
+
+`Shared`, `SharedFramework`, `SharedInfrastructure`, `SharedInfra`, `SharedUtilities`,
+`SharedUtils`, `SharedLibrary`, `SharedLib`, `SharedHelpers`
+
+## Shared testing project names (exact)
+
+`SharedTestingFramework`, `SharedTestingInfrastructure`, `SharedTestingInfra`,
+`SharedTestingUtilities`, `SharedTestingUtils`, `SharedTestingLibrary`, `SharedTestingLib`,
+`SharedTestingHelpers`
+
+These are matched whole, not as substrings. `SharedModels` is not a shared project.
+
+A shared-testing project is forced to `PurviewSharedTestingOutputType` (default `Library`), with
+`IsTestProject` and `IsTestingPlatformApplication` cleared, because the test packages otherwise flip
+it into an executable test host. Set `PurviewSharedTestingOutputType=Exe` before the SDK import to
+keep that package-driven shape.
+
+## Packable projects
+
+Defaults applied only where the project supplied nothing: `GenerateDocumentationFile`,
+`IncludeSymbols`, `SymbolPackageFormat=snupkg`, `PublishRepositoryUrl`, `EmbedUntrackedSources`,
+`IncludeSource`, `DebugType=portable`.
+
+- Portable PDBs ship in the `.snupkg`. The `.nupkg` receives none unless the project opts in.
+- The repository-root `README.md` is packed and registered as `PackageReadmeFile` when it exists and
+ nothing else is already being packed as one.
+- Non-packable projects, web apps included, default `WarnOnPackingNonPackableProject=false`, so a
+ solution-wide `dotnet pack` skips them silently.
+- `ContinuousIntegrationBuild` is set only by real CI environment variables. Packability alone never
+ forces SourceLink's CI-mode dirty-repository checks.
+
+## Roslyn components
+
+A project that explicitly declares `IsRoslynComponent=true` gets:
+
+- a single `netstandard2.0` target, `LangVersion=latest`, `Nullable=enable`,
+ `TreatWarningsAsErrors=true`, `Deterministic=true`, extended analyzer rules
+- SourceLink with `EmbedUntrackedSources=true`, no dependency file, telemetry excluded
+- compiler-generated output under the framework-specific intermediate directory
+- `PrivateAssets=all` on `Microsoft.CodeAnalysis.*` and `Microsoft.CodeAnalysis.Analyzers`, so they
+ never leak into the packed nuspec
+
+`IsRoslynComponentOnly` defaults to `true`: `IncludeBuildOutput=false`, `IncludeSymbols=false`, no
+`.symbols.nupkg` or `.snupkg`, and the analyzer PDB shipped inside the main `.nupkg` under
+`analyzers/dotnet/cs/` beside the assembly (`PurviewPackAnalyzerPdb=true`). Set it to `false` for a
+dual-role component that wants normal library symbol packaging.
+
+`ValidateRoslynComponentCompilerSettings` fails the pack of a packable Roslyn component missing
+`LangVersion`, `Nullable`, `TreatWarningsAsErrors` or `EnforceExtendedAnalyzerRules`. Opt out with
+`DisableRoslynCompilerDefaultsValidation=true`.
+
+`PackProjectReferencedSourceGenerators` (default `true`) makes a packable project include analyzer
+`ProjectReference` outputs and their runtime dependencies under `analyzers/dotnet/cs/`. Set it
+`false` globally, or `Pack="false"` on one analyzer reference.
+
+## Special project types
+
+| Type | Applied |
+| -- | -- |
+| CLI | `OutputType=Exe`, `appsettings*.json` included as content |
+| Container | `InvariantGlobalization`, `PublishAot`, Linux Docker defaults, container tooling packages |
+| Web SDK | `Microsoft.AspNetCore.OpenApi.Generated` added to `InterceptorsNamespaces`, unless marked as a separate web-project mode |
+| Aspire host | `OutputType=Exe` |
+
+## The Visual Studio refactorings
+
+Two ship with the code-fix assembly, both serving the `PDS0002` convention:
+
+- **Split extensions class into one class per receiver type** — offered on a static extensions class
+ targeting several receiver types. It produces one `Extensions` class per receiver
+ (a generic `this TBuilder where TBuilder : IHostApplicationBuilder` receiver becomes
+ `HostApplicationBuilderExtensions`) and places each under `Extensions//`.
+- **Move extensions class to conventional location** — offered on a misplaced single-receiver
+ extensions class. It re-paths the file to `Extensions//`, fixes the namespace
+ to the receiver's, and updates `using` directives in other referencing documents so the move
+ compiles.
diff --git a/.agents/skills/purview-buildsdk-project-detection/references/test-types.md b/.agents/skills/purview-buildsdk-project-detection/references/test-types.md
new file mode 100644
index 00000000..dace44fc
--- /dev/null
+++ b/.agents/skills/purview-buildsdk-project-detection/references/test-types.md
@@ -0,0 +1,35 @@
+# The shipped `TestType` group
+
+These 53 names drive **`InternalsVisibleTo` generation**, not test detection. A non-test project
+grants friend access to `{AssemblyName}.{TestType}Tests` for each name here.
+
+Detection is the pattern `^.*\.([\w|_]\w*)Tests?$`, so a suffix outside this group is still detected,
+still runs and still gets its category — it simply cannot reach the target project's `internal`
+members. Prefer a name from this group unless the test type genuinely needs its own word.
+
+```text
+Unit Integration E2E EndToEnd Acceptance
+Functional Performance Load Smoke Stress
+Regression Security Chaos Scenario System
+Threat BlackBox WhiteBox GrayBox GreyBox
+Accessibility Usability Visual Interactive Localization
+Globalization Environment Configuration Deployment Architecture
+Contract Component Sanity Property Fuzz
+Mutation Snapshot Approval Benchmark Capacity
+Concurrency Endurance Soak Spike Failover
+Recovery Resilience Compatibility Interoperability Migration
+Upgrade Penetration Compliance
+```
+
+## The five to reach for first
+
+`Unit`, `Integration`, `E2E`, `Functional`, `Contract`. Everything else is available, but a reader
+has to ask what it means — use one only when the test type itself carries operational weight.
+
+## What a suffix buys you
+
+| | detected as a test project | gets a category | gets a runner and coverage | sees `internal` members |
+| -- | -- | -- | -- | -- |
+| `Api.UnitTests` | yes | `Unit` | yes | yes |
+| `Api.GoldenTests` | yes | `Golden` | yes | **no** |
+| `UnitTests` *(no dot)* | **no** | no | **no** | no |
diff --git a/.agents/skills/purview-buildsdk-project-layout/SKILL.md b/.agents/skills/purview-buildsdk-project-layout/SKILL.md
new file mode 100644
index 00000000..55a019cd
--- /dev/null
+++ b/.agents/skills/purview-buildsdk-project-layout/SKILL.md
@@ -0,0 +1,136 @@
+---
+name: purview-buildsdk-project-layout
+description: Decide where a project goes and what to call it in a repository that uses Purview.BuildSdk. Use when creating, moving, splitting or renaming a project or test project, choosing a test suffix, aligning namespaces and assembly identity with NamespacePrefix, or relying on the SDK's automatic project references. Also use when rationalising a repository's shape so the SDK's conventions work without overrides.
+license: MIT
+metadata:
+ package: Purview.BuildSdk
+ repository: purview-dev/build-sdk
+---
+
+# Project layout and naming for Purview.BuildSdk
+
+Use this skill when physically adding, moving, splitting or renaming a project.
+
+For *why* the SDK classified an existing project a particular way, use
+`purview-buildsdk-project-detection`. For the property that changes a behaviour, use
+`purview-buildsdk-configuration`.
+
+## First principle
+
+**Treat naming and placement as configuration, not decoration.**
+
+The SDK infers namespaces, assembly identity, test categories, package wiring and project references
+from a small set of conventions. The closer a repository sits to them, the fewer overrides it needs.
+
+The corollary matters just as much: **preserve the host repository's existing layout first.** Only
+introduce new structure when no established pattern exists.
+
+## Canonical layout
+
+```text
+/
+ package.json version source
+ .editorconfig bootstrapped by the SDK
+ skills/ authored agent skills, if any
+ src/
+ .slnx
+ src//.csproj
+ tests/.Tests/.Tests.csproj
+```
+
+- The `.csproj` filename must equal its containing directory name, unless
+ `DisableProjectFileNamingConventionCheck=true`.
+- Source projects under `src/`, test projects under `tests/`.
+- Place a new project beside similar ones — same language, layer and test type.
+- One test type per project by default.
+
+A repository that already uses a different shape keeps it; add to it rather than converting it.
+
+## Naming and identity
+
+`NamespacePrefix` is the root identity source. Keep project names short and let the SDK apply the
+prefix:
+
+| `NamespacePrefix` | Project | `RootNamespace` |
+| -- | -- | -- |
+| `Aspire` | `Hosting` | `Aspire.Hosting` |
+| `Acme.Sales.RegionalPipeline` | `Identity.API` | `Acme.Sales.RegionalPipeline.Identity.API` |
+| `Acme.Sales.RegionalPipeline` | `Identity.Core` | `Acme.Sales.RegionalPipeline.Identity` |
+
+`AssemblyName` and `PackageId` follow the resolved `RootNamespace` — except where suffix-stripping
+removed a segment (`Core`, `Shared`, `ServiceDefaults`), in which case they keep the fuller logical
+name so the artifacts stay distinct from their parent. Explicit values always win, and
+`EnableAssemblyNameGeneration=false` (before the SDK import) restores standard behaviour.
+
+Do not hand-author an alternate namespace scheme when one is already in use.
+
+## Test project naming
+
+Test detection is a **pattern**, not a list: `^.*\.([\w|_]\w*)Tests?$`. A target name, a dot, then
+any word before `Test` or `Tests`. The captured word becomes `TestingType` and the baseline category.
+
+**The dot is required.** A project named plainly `UnitTests`, with no target in front of it, is not
+detected as a test project at all — no runner, no coverage, no `InternalsVisibleTo`, no category.
+Always name a test project `.Tests`.
+
+Prefer these by default: `UnitTests`, `IntegrationTests`, `E2ETests`, `FunctionalTests`,
+`ContractTests`. Use another suffix only when the test type itself carries operational meaning.
+
+A suffix outside the SDK's shipped `TestType` group still builds, runs and gets its category — it
+just cannot reach the target project's `internal` members, because that group drives
+`InternalsVisibleTo` generation. The full list is in `purview-buildsdk-project-detection`.
+
+## Shared projects: exact names only
+
+The SDK recognises these names exactly — a near miss gets none of the behaviour.
+
+Shared: `Shared`, `SharedFramework`, `SharedInfrastructure`, `SharedInfra`, `SharedUtilities`,
+`SharedUtils`, `SharedLibrary`, `SharedLib`, `SharedHelpers`.
+
+Shared testing: `SharedTestingFramework`, `SharedTestingInfrastructure`, `SharedTestingInfra`,
+`SharedTestingUtilities`, `SharedTestingUtils`, `SharedTestingLibrary`, `SharedTestingLib`,
+`SharedTestingHelpers`.
+
+## Automatic project references to preserve
+
+Layout is what makes these work. Move a project off the convention and you own the reference.
+
+Test projects probe for their target, in order:
+
+- `../$(TargetProjectName)/$(TargetProjectName).csproj`
+- `../../$(TargetProjectName)/$(TargetProjectName).csproj`
+- `../src/$(TargetProjectName)/$(TargetProjectName).csproj`
+- `../../src/$(TargetProjectName)/$(TargetProjectName).csproj`
+
+Non-test projects pick up sibling shared projects via `../Shared*/Shared*.csproj`; test projects
+pick up `../SharedTesting*/SharedTesting*.csproj`.
+
+## Creating a new project
+
+1. Match the SDK and style of sibling projects.
+2. Use Central Package Management if the repository has it.
+3. Add only the dependencies the project's scope needs — the SDK supplies the testing stack,
+ SourceLink and telemetry by default.
+4. Add the project to the solution.
+5. Keep target frameworks, nullability, analyzers and warning settings consistent with neighbours.
+
+## Moving or splitting
+
+1. Create the destination using the established layout.
+2. Move the files.
+3. Update namespaces, usings and references for the destination.
+4. Verify the destination still produces the intended `TestingType`, `TargetProjectName` and
+ `RootNamespace` — ask MSBuild rather than assuming:
+ `dotnet msbuild -getProperty:RootNamespace -getProperty:TargetProjectName`.
+5. Remove dependencies the source no longer needs.
+6. Update solution membership and project references.
+7. Build, then run the affected tests.
+
+## Guardrails
+
+- Prefer minimal, targeted diffs; avoid cross-cutting renames unrelated to the move.
+- Keep test intent unchanged while relocating.
+- When the structure is ambiguous, infer from the nearest sibling projects and say which assumption
+ you made.
+- When in doubt, preserve compatibility with the SDK's automatic naming, namespace and
+ project-reference behaviour.
diff --git a/.agents/skills/purview-buildsdk-repository-review/SKILL.md b/.agents/skills/purview-buildsdk-repository-review/SKILL.md
new file mode 100644
index 00000000..ce1fd294
--- /dev/null
+++ b/.agents/skills/purview-buildsdk-repository-review/SKILL.md
@@ -0,0 +1,111 @@
+---
+name: purview-buildsdk-repository-review
+description: Review a repository that uses Purview.BuildSdk for naming, placement and test-structure alignment, and report what the SDK can and cannot do automatically as a result. Use when asked to audit, rationalise or health-check a repo against the SDK's conventions, when onboarding an existing codebase onto Purview.BuildSdk, or when deciding whether a layout quirk is worth changing.
+license: MIT
+metadata:
+ package: Purview.BuildSdk
+ repository: purview-dev/build-sdk
+---
+
+# Reviewing a repository against the SDK's conventions
+
+This is an audit, not a refactor. The deliverable is a prioritised list of findings and the cost of
+each, so somebody else can decide what to change.
+
+For the conventions themselves use `purview-buildsdk-project-layout`; for why one project was
+classified as it was, `purview-buildsdk-project-detection`.
+
+## The governing judgement
+
+**Deviation is only a finding when it costs the repository something.** The SDK infers behaviour
+from naming and placement, so a deviation is interesting precisely to the extent that it turns an
+automatic behaviour off. A layout that differs from the canonical one but still gets every automatic
+behaviour is not debt, and reporting it as such wastes the reader's attention.
+
+Sort every finding into one of three buckets, and say which:
+
+| Bucket | Meaning |
+| -- | -- |
+| **Acceptable variance** | Differs from the canonical layout, costs nothing. Preserve it. |
+| **Structural debt** | Blocks an automatic behaviour the repository would benefit from. |
+| **Incremental opportunity** | Low-risk tidying worth doing when the area is touched anyway. |
+
+## 1. Read before concluding
+
+Inspect, in this order, before forming any opinion:
+
+- `Directory.Build.props` and `Directory.Build.targets` — where the SDK is imported, and what is set
+ before the import
+- the solution entry point, for what is actually in the build
+- `Directory.Packages.props`, for Central Package Management
+- the project layout on disk
+
+## 2. Check the structural signals
+
+- Source projects under `src/`, test projects under `tests/`.
+- `.csproj` filename equals its containing directory name — unless
+ `DisableProjectFileNamingConventionCheck=true`, which is itself a finding worth surfacing.
+- Short project names, with `NamespacePrefix` carrying the repository identity.
+- Test project names match `^.*\.([\w|_]\w*)Tests?$`. **The dot is required**; a project named
+ plainly `UnitTests` is not detected at all and silently gets no runner, no coverage, no
+ `InternalsVisibleTo` and no category. This is the single highest-value thing to check.
+- Test suffixes come from the SDK's shipped `TestType` group where `internal` access is wanted — a
+ suffix outside it still runs, it just cannot see `internal` members.
+- Shared and shared-testing projects use the **exact** recognised names. A near miss gets none of
+ the behaviour.
+
+## 3. Verify with MSBuild, do not infer from folder names
+
+A review that reasons from directory names will be wrong about at least one project. Ask:
+
+```bash
+dotnet msbuild -getProperty:RootNamespace -getProperty:AssemblyName \
+ -getProperty:IsTestProject -getProperty:TestingType -getProperty:TargetProjectName
+```
+
+Quote the computed values in the findings. "`Api.Tests` resolves `TestingType=` empty, so it has no
+runner" is actionable; "`Api.Tests` looks like it might not be detected" is not.
+
+## 4. Review test readability
+
+- Subject-based suites: `{SubjectName}Tests`, with
+ `{SubjectOrMemberUnderTest}_{Scenario}_{Expectation}` methods.
+- Non-subject-based suites — build, generator, workflow, package, full-system — named clearly for
+ their broader role. A forced `{Subject}Tests` on one of these is worse, not better.
+- TUnit categories and display names used where a suite is large enough to need navigating.
+
+See `purview-buildsdk-testing`.
+
+## 5. Check the test dependencies are earned
+
+The SDK already supplies `TUnit`, `TUnit.Mocks`, `Bogus` and the Microsoft.Testing.Platform wiring
+to every detected test project. Anything beyond that was a deliberate choice, and deliberate choices
+go stale:
+
+- `TUnit.Aspire` and `Purview.Containers` are **not** universal defaults. Confirm each reference is
+ genuinely needed by that project rather than copied from a sibling.
+- Where a project references `Testcontainers` directly, check whether a `Purview.Containers` typed
+ module now covers it — the module set grows, and a direct reference that was once necessary often
+ is not any more.
+- A package the SDK already adds, restated in a project file, is maintenance cost with no effect.
+
+## 6. Explain consequences, not just mismatches
+
+For each finding, name the specific automatic behaviour that is lost: `RootNamespace`,
+`AssemblyName`, `PackageId`, `TargetProjectName`, the automatic target-project reference, the
+sibling `Shared*` reference, `InternalsVisibleTo` generation, the test runner and coverage wiring.
+
+"Project is not under `src/`" is not a finding. "Project is not under `src/`, so the test project's
+four probe paths all miss and the `ProjectReference` has to be maintained by hand" is.
+
+## Reporting the result
+
+1. One sentence on whether the repository broadly fits the SDK's conventions.
+2. The findings, ordered by impact, each with its bucket and the behaviour it costs.
+3. The low-risk rationalisation steps, as concrete renames or moves.
+4. An explicit split of what is **already automatic** versus what this repository has configured by
+ hand — that list is usually the most useful part of the review, because hand-configuration that
+ merely restates a default is pure maintenance cost.
+
+Do not propose a cross-cutting rename as a first step. Name the one change with the best
+cost-to-benefit ratio and say what it unlocks.
diff --git a/.agents/skills/purview-buildsdk-skill-installation/SKILL.md b/.agents/skills/purview-buildsdk-skill-installation/SKILL.md
new file mode 100644
index 00000000..66c20a33
--- /dev/null
+++ b/.agents/skills/purview-buildsdk-skill-installation/SKILL.md
@@ -0,0 +1,166 @@
+---
+name: purview-buildsdk-skill-installation
+description: Install, list and diagnose the agent skills a Purview.BuildSdk package ships. Use for the InstallPurviewSkills, ListPurviewSkills and RecommendPurviewSkills MSBuild targets, for any PRSKL0001-PRSKL0014 diagnostic, for choosing a package runner (npx, pnpm dlx, bunx, yarn dlx, deno), for skills-lock.json, or when a package ships skills but no agent can see them.
+license: MIT
+metadata:
+ package: Purview.BuildSdk
+ repository: purview-dev/build-sdk
+---
+
+# Installing the skills a package ships
+
+For *authoring* skills, use `purview-buildsdk-skill-tests`.
+
+## The one thing to understand first
+
+**The SDK writes nothing into an agent directory.** A package *ships* `.agents/skills//`, but
+as metadata — it is what tells the SDK which skills the package offers and at which commit. Nothing
+copies it out.
+
+Skills are installed by the skills CLI and by nothing else. That is a deliberate single-writer rule.
+Earlier versions of this SDK mirrored a package's whole `.agents/**` folder into the consuming
+repository, and the CLI's own universal install location is `.agents/skills/` — the same paths. The
+mirror would silently overwrite a pinned install on the next build, while `PRSKL0011` compared a
+lockfile ref against content the mirror had already replaced. The mirror was removed outright rather
+than fenced off, because the CLI covers the whole job.
+
+Installing is therefore a separate, deliberately **explicit** step. It is never a side effect of a
+restore, a build, a design-time build or a test run.
+
+```bash
+dotnet msbuild -t:ListPurviewSkills # diagnostics only, installs nothing
+dotnet msbuild -t:InstallPurviewSkills # delegates to the skills CLI
+```
+
+Neither target has `BeforeTargets` or `AfterTargets`. If skills are appearing or changing on their
+own, something has been wired up that should not be.
+
+## How a skill is resolved, and why the version is always right
+
+There is deliberately **no custom manifest**. A package that ships skills already carries both
+halves of the mapping, and `ResolvePurviewSkillSources` reads them:
+
+- `.agents/skills//` in the restored package says *which* skills it ships.
+- The nuspec's ``, written by SourceLink for every package this
+ SDK builds, says which git repository and which **exact commit** produced them.
+
+So the resolved ref is the commit the *restored package version* was built from. An older
+`PackageReference` gets that version's skills, not whatever is on the default branch. Compatibility
+is exact by construction rather than by convention.
+
+## Installing from an explicit source
+
+For a skill you want but have no `PackageReference` for:
+
+```bash
+dotnet msbuild -t:InstallPurviewSkills -p:PurviewSkillsSource=purview-dev/build-sdk
+```
+
+The caller owns the ref here — append `#[` to pin it. This path needs no restore, so
+`PRSKL0001` does not apply.
+
+## Diagnostics
+
+| Code | Meaning | Fix |
+| -- | -- | -- |
+| `PRSKL0001` | `project.assets.json` is missing | Restore. Resolution reads the restore graph and deliberately does not trigger a restore of its own |
+| `PRSKL0002` | The package's nuspec has no GitHub repository URL, or no commit | The package cannot be pinned. It is reported rather than installed from a guessed branch |
+| `PRSKL0003` | No repository root resolved | Pass `-p:PurviewSkillsInstallRoot=` |
+| `PRSKL0004` | No skills CLI and no package runner found | Install Node, or set `PurviewSkillsCommand` |
+| `PRSKL0005` | An authored skill is malformed | See `purview-buildsdk-skill-tests` |
+| `PRSKL0010` | A skill a referenced package ships is missing | Warning. `npx skills add ...` |
+| `PRSKL0011` | An installed skill is pinned to a different ref than the referenced package | Warning. Install the package's own commit |
+| `PRSKL0012` | A skill cannot be verified | Message |
+| `PRSKL0013` | An orphaned lockfile entry | Message |
+| `PRSKL0014` | Recorded in the lockfile but never restored | Message |
+
+## Recommendations run during an ordinary build
+
+This is the **one** skill feature that does. `RecommendPurviewSkillsOnBuild` runs after `Build` and
+delegates to `RecommendPurviewSkills`, which can also be invoked by name:
+
+```bash
+dotnet msbuild -t:RecommendPurviewSkills
+```
+
+`EvaluatePurviewSkillState` joins the skills each restored package ships against the CLI's own
+`skills-lock.json`. Both inputs are local files, so it stays offline and spawns no process.
+
+Four things keep it quiet, and all of them are load-bearing:
+
+- Design-time builds, CI builds, non-default TFM passes and
+ `EnablePurviewSkillRecommendations=false` are skipped outright.
+ `PurviewSkillRecommendationsInCI=true` re-enables CI.
+- A fingerprint stamp at `/.purview/skill-recommendations.cache` means a given state is
+ reported once per repository, not once per project and again on every rebuild. The explicit target
+ ignores the stamp.
+- Missing and drifted are **warnings** (fixable in one command); unverifiable and orphaned are
+ **messages**. No amount of skill advice can break a build using `TreatWarningsAsErrors`.
+- A correctly installed set produces no output at all.
+
+Orphan detection is **owner-scoped on purpose**: a lockfile cannot record who asked for an entry, so
+only an entry under an owner the project references — but from a repository it no longer references
+— is reported. A skill from any other owner is the developer's own, and is never mentioned.
+
+### Drift never recommends `npx skills update`
+
+`update` installs the *newest* published skill, which is only correct when the newest skill happens
+to describe the referenced package version. `PRSKL0011` names the referenced package's own commit in
+a pinned `npx skills add` instead.
+
+## Package runners
+
+The CLI is published to npm, and every runner spells "run this npm package" differently.
+`PurviewSkillsRunner` selects one, defaulting to `npx` because npx ships with Node itself.
+
+| Runner | Invocation |
+| -- | -- |
+| `npx` | `npx -y skills@1` |
+| `bunx` | `bunx skills@1` |
+| `bun` | `bun x skills@1` |
+| `pnpm` | `pnpm dlx skills@1` |
+| `yarn` | `yarn dlx skills@1` — Yarn 2+ only |
+| `deno` | `deno run -A npm:skills@1` |
+
+An unknown runner falls through to ` $(PurviewSkillsPackage)`, so it still works.
+
+`DetectPurviewSkillsCli` probes `PATH` for `skills` first, then `$(PurviewSkillsRunner)`, then
+`$(PurviewSkillsRunnerCandidates)`, honouring `PATHEXT` on Windows where these are `.cmd` shims.
+`PATH` is read directly rather than by spawning a version check: deterministic, no process, and it
+cannot hang on a cold download. **The runner actually found wins over the configured preference.**
+`PurviewSkillsCommand` overrides the launcher entirely and skips detection.
+
+`ListPurviewSkills` reports runner availability but **never** errors on its absence — resolving and
+reporting needs no Node tooling at all.
+
+## Always the repository root
+
+`skills-lock.json` and the agent directories belong to the repository, not to a project, so every
+skill target runs from one resolved root:
+
+1. `PurviewSkillsInstallRoot` — an explicit override
+2. `PurviewSkillsRepoRoot` — only when the **user** set it
+3. the `PurviewRepositoryRootMarkers` walk
+4. `PurviewSkillsRepoRoot` / `RepoRoot` as the SDK guessed them
+5. CI workspace variables
+6. SourceLink's git `SourceRoot`
+
+There is deliberately **no project-directory fallback**. That would scatter a lockfile and an agent
+directory through the tree, one per project. An unresolved root is `PRSKL0003` on install, and
+silence for recommendations — a build never fails over advice.
+
+The marker walk is described in [references/repository-root.md](references/repository-root.md); its
+two-pass behaviour and its home-directory bound are both load-bearing.
+
+## Why the CLI rather than a reimplementation
+
+The CLI owns the agent-specific destinations and their discovery conventions, which differ per agent
+and change independently of this SDK. It also owns `skills-lock.json`, so a repository can restore
+the same set later with `npx skills experimental_install`.
+
+`PurviewSkillsAgents` (default `*`) narrows the target agents.
+
+The lockfile is read **directly** rather than by parsing `npx skills list --json`, because that
+listing omits the `ref` — and the ref is the whole compatibility question. Reading a file also needs
+no Node tooling, which is what keeps recommendations working on a machine that can build .NET but
+has no Node. There is deliberately no competing lockfile.
diff --git a/.agents/skills/purview-buildsdk-skill-installation/references/repository-root.md b/.agents/skills/purview-buildsdk-skill-installation/references/repository-root.md
new file mode 100644
index 00000000..e90b695c
--- /dev/null
+++ b/.agents/skills/purview-buildsdk-skill-installation/references/repository-root.md
@@ -0,0 +1,55 @@
+# The repository-root marker walk
+
+`FindPurviewRepositoryRoot` is an inline MSBuild task driven by `PurviewRepositoryRootMarkers`:
+
+```text
+.git/;.github/;.gitattributes;LICENSE.md;AGENTS.md;.agents/;CLAUDE.md;.claude/;package.json
+```
+
+A trailing slash marks a directory. A directory marker still matches a **file** of that name,
+because `.git` is a directory in a clone but a file in a worktree or a submodule, and both identify
+a repository root.
+
+## Three things that are load-bearing
+
+### It cannot be an MSBuild intrinsic
+
+`GetDirectoryNameOfFileAbove` matches **files only** and returns nothing for `.git/`, `.github/`,
+`.agents/` or `.claude/` — four of the nine markers. Verified, not assumed.
+
+### Two passes
+
+- **Pass 1** — the first marker in the list is *definitive* and is searched all the way up. `.git/`
+ *is* the repository root, so a monorepo sub-package with its own `package.json` does not win.
+- **Pass 2** — every other marker resolves nearest-ancestor-first, with list order breaking ties
+ inside a single directory. Searching them all to the top would let a stray `.claude/` in a
+ developer's home directory outrank the real root.
+
+### The home directory is never a candidate
+
+The home directory and everything above it are excluded. Without that bound, a project outside any
+repository resolves to `~` and installs into it — and a `.claude/` or a `.github/` very commonly
+sits there. A repository *below* the home directory is unaffected, because it is below it.
+
+## Why the marker walk outranks the evaluation-time guess
+
+`PurviewSkillsRepoRoot` is computed during evaluation from `RepoRoot` and an `AGENTS.md` walk-up.
+An `AGENTS.md` can legitimately sit in a subdirectory, and resolving to it would put a lockfile and
+an agent directory somewhere that is not the repository.
+
+`_PurviewSkillsRepoRootWasSpecified` is captured in `Sdk.props` *before* defaulting, so a value the
+**user** set still outranks the walk while a value the SDK guessed does not.
+
+## A target's Condition is evaluated before its DependsOnTargets
+
+A property a dependency computes is still empty in the depending target's `Condition`. That is why
+the unresolved-root guard sits on the `EvaluatePurviewSkillState` task rather than on
+`RecommendPurviewSkills` — and equally why the build hook's CI and design-time gating works at all.
+
+## The managed port
+
+`Purview.Skills.Testing` ships `SkillRepositoryRoot`, a managed port of the same walk with the same
+default markers, so a test that validates a repository's skills resolves the same root the build
+installs them into. The two are kept in step by `SkillRepositoryRootTests`, including an assertion
+on the default marker list itself — both are defaults nobody sets, so nothing else would notice them
+drifting apart.
diff --git a/.agents/skills/purview-buildsdk-skill-tests/SKILL.md b/.agents/skills/purview-buildsdk-skill-tests/SKILL.md
new file mode 100644
index 00000000..4043ac4f
--- /dev/null
+++ b/.agents/skills/purview-buildsdk-skill-tests/SKILL.md
@@ -0,0 +1,131 @@
+---
+name: purview-buildsdk-skill-tests
+description: Author agent skills in a repository that uses Purview.BuildSdk, and validate them with Purview.Skills.Testing or the SDK's pack-time ValidatePurviewSkills target. Use when adding or renaming a skill, writing SKILL.md frontmatter, splitting content into references/ or scripts/, fixing a PRSKL0005 pack failure or a skill-name, skill-description or skill-bundled-resources test failure, or deciding where skills belong in a repository.
+license: MIT
+metadata:
+ package: Purview.Skills.Testing
+ repository: purview-dev/build-sdk
+---
+
+# Authoring and validating agent skills
+
+For installing skills a package ships, use `purview-buildsdk-skill-installation`.
+
+## Where skills live
+
+**At the repository root, in `skills//SKILL.md`.** Always.
+
+The skills CLI only discovers skills at a root `skills/` folder, and it reaches a repository by
+The skills CLI only discovers skills at a root `skills/` folder, and it reaches a repository by
+cloning it, so nothing else is visible to it. Nothing is packed into a NuGet package — a package
+carries .NET artifacts, and skills are delivered by the CLI from git.
+
+```text
+skills/
+ my-skill/
+ SKILL.md required
+ references/ loaded on demand
+ scripts/ executable, run on demand
+ assets/ templates and static resources
+```
+
+Link to a skill by its **authored** path, `./skills//SKILL.md`. A link into `.agents/skills/`
+points at a gitignored file that does not exist in a fresh clone.
+
+## `SKILL.md` format
+
+```markdown
+---
+name: my-skill
+description: What it does, and when to use it. Include the words a task would contain.
+license: MIT
+metadata:
+ package: My.Package
+---
+
+# My skill
+
+Instructions.
+```
+
+| Field | Required | Constraint |
+| -- | -- | -- |
+| `name` | yes | 1–64 chars, lowercase `a-z0-9` and single hyphens, no leading, trailing or consecutive hyphen, **must equal the folder name** |
+| `description` | yes | 1–1024 chars, non-empty |
+| `license` | no | A licence name, or the name of a bundled licence file |
+| `compatibility` | no | ≤500 chars, only when the skill has real environment requirements |
+| `metadata` | no | A map of string to string. Anything not defined above belongs here |
+| `allowed-tools` | no | Space-separated pre-approved tools. Experimental |
+
+**There are no other top-level fields.** `category`, `roles` and `tags` are common inventions and a
+strict client rejects them; put them under `metadata`.
+
+The full specification is at .
+[references/authoring.md](references/authoring.md) covers description writing, naming for a shared
+namespace, and progressive disclosure.
+
+## Progressive disclosure
+
+An agent loads a skill in three stages: the `name` and `description` at startup, the whole
+`SKILL.md` body once the skill activates, and `references/`, `scripts/` or `assets/` only when the
+task reaches them.
+
+So: keep `SKILL.md` **under 500 lines**, and move detail into `references/`. The body is a cost paid
+on every activation; a reference file is paid only when it is needed.
+
+Keep file references one level deep from `SKILL.md`, and relative to the skill root. A path that
+climbs out of the skill folder is broken everywhere except the authoring repository, because only
+the skill's own folder is installed.
+
+## Validating
+
+### In tests — `Purview.Skills.Testing`
+
+```csharp
+[InheritsTests]
+public sealed class SkillTests : PurviewSkillTests;
+```
+
+**`[InheritsTests]` is load-bearing.** TUnit does not walk base types during discovery, so without
+it the class compiles, the run is green and nothing is validated. TUnit reports `TUnit0030`; treat
+it as an error.
+
+| Rule id | What it checks |
+| -- | -- |
+| `skills-discovery` | The folder, when present, holds at least one skill |
+| `skill-structure` | Every folder has a `SKILL.md` whose frontmatter parses |
+| `skill-name` | Spec-legal, unique, and equal to the folder name |
+| `skill-description` | Present, non-empty, within 1024 characters |
+| `skill-optional-fields` | Only spec-defined fields, each within its limit |
+| `skill-bundled-resources` | Every linked file exists, inside the skill folder |
+| `skill-body-size` | `SKILL.md` stays under the recommended 500 lines |
+
+A repository with **no** `skills/` folder passes every rule — authoring skills is optional. An
+**empty** folder fails `skills-discovery`, because every other rule is vacuous against an empty
+catalogue.
+
+Overrides: `RepositoryRoot` (default: the SDK's repository-root marker walk),
+`SkillsFolderName` (default `skills`), and `SkipRule(string)`.
+
+The evaluator takes a `SkillCatalogue`, so a rule can be exercised against a fixture folder rather
+than a real repository — the same three-layer shape this repository uses throughout: a reader, an
+evaluator over an in-memory model, and a thin test base class.
+
+### At pack time — `ValidatePurviewSkills`
+
+It runs `BeforeTargets="Pack"`, so a malformed skill fails in the repository that owns it rather
+than reaching the CLI, which would silently skip it.
+
+```bash
+dotnet msbuild -t:ValidatePurviewSkills
+```
+
+Failures are reported as `PRSKL0005`, one per problem. Every authored skill is checked.
+
+The two checks overlap deliberately: the pack-time one runs without a test host, the test one
+covers more of the specification.
+
+## What is deliberately not checked
+
+Prose quality, and whether an agent actually obeys the skill. A build can only check that a skill is
+well formed. Treat a green run as "installable", not "good".
diff --git a/.agents/skills/purview-buildsdk-skill-tests/references/authoring.md b/.agents/skills/purview-buildsdk-skill-tests/references/authoring.md
new file mode 100644
index 00000000..69d4ee45
--- /dev/null
+++ b/.agents/skills/purview-buildsdk-skill-tests/references/authoring.md
@@ -0,0 +1,79 @@
+# Authoring a skill that fires, and keeps firing
+
+## The description is the whole activation decision
+
+`name` and `description` are the only things loaded at startup. Everything else — the body, the
+references, the scripts — is invisible until an agent has already decided to activate the skill on
+the strength of those two fields.
+
+So write the description for a *matcher*, not for a reader:
+
+- Say **what it does** and **when to use it**, in that order.
+- Include the words a real task would contain: the tool names, the file names, the error codes, the
+ property names, the phrases a person would type.
+- Name the thing the skill is *not*, when a neighbouring skill could be confused with it.
+
+| | |
+| -- | -- |
+| Poor | `Helps with the build SDK.` |
+| Better | `Configure Purview.BuildSdk from Directory.Build.props or a .csproj. Use when setting NamespacePrefix, choosing a testing framework, or working out whether a property must be set before the SDK import.` |
+
+The limit is 1024 characters. Most of that budget is better spent on trigger words than on prose.
+
+## Naming for a shared namespace
+
+Skills install into one flat directory per agent, shared with every other skill a developer has
+installed from anywhere. A generic name is a collision waiting to happen, and the loser is whichever
+one installed second.
+
+- Prefix with the vendor and the product: `purview-buildsdk-configuration`, not `sdk-configuration`.
+- `sdk-*`, `project-*`, `test-*`, `build-*` are all too common to use unprefixed.
+- The name must be 1–64 characters, lowercase `a-z0-9` with single hyphens, no leading, trailing or
+ consecutive hyphen — and it must equal the folder name, because the CLI installs by the
+ frontmatter name while a human reads the folder.
+
+Renaming a skill means renaming the folder and the frontmatter together, and re-running the install.
+
+## Progressive disclosure in practice
+
+| Stage | Loaded | Budget |
+| -- | -- | -- |
+| Metadata | `name`, `description` | ~100 tokens, always |
+| Instructions | the whole `SKILL.md` body | under 5000 tokens recommended; keep the file under 500 lines |
+| Resources | `references/`, `scripts/`, `assets/` | only when the task reaches them |
+
+What belongs where:
+
+- **`SKILL.md`** — the decisions, the rules, the things that are wrong by default, and a pointer to
+ everything else. If a reader needs it to make the *first* correct move, it goes here.
+- **`references/`** — long tables, full option lists, grammars, enumerations. Keep each file
+ focused; an agent loads the whole file.
+- **`scripts/`** — executable code. Self-contained, or documenting its dependencies clearly, with
+ helpful error messages.
+- **`assets/`** — templates, schemas, images, lookup data.
+
+Keep references one level deep. Avoid a chain where one reference sends an agent to another.
+
+## Links
+
+Use relative paths from the skill root:
+
+```markdown
+See [the reference](references/REFERENCE.md) for detail.
+Run `scripts/extract.py`.
+```
+
+Only the skill's own folder is installed, so a link that climbs out of it (`../other-skill/...`) is
+broken on every machine except the one that authored it. To point at another skill, name it in prose
+and let the agent find it by name.
+
+## Keeping a skill true
+
+A skill that describes a product goes stale the moment the product changes, and nothing about a
+stale skill looks broken — it just gives confidently wrong advice.
+
+- Change the skill in the **same commit** as the behaviour it documents.
+- Prefer stating the property name, the diagnostic code or the target name over paraphrasing the
+ behaviour; those are greppable when the code changes.
+- Where a number or a list is authoritative somewhere else — a default, an enumeration — say where
+ it comes from, so a reader can check it.
diff --git a/.agents/skills/purview-buildsdk-testing/SKILL.md b/.agents/skills/purview-buildsdk-testing/SKILL.md
new file mode 100644
index 00000000..5a5a7d53
--- /dev/null
+++ b/.agents/skills/purview-buildsdk-testing/SKILL.md
@@ -0,0 +1,121 @@
+---
+name: purview-buildsdk-testing
+description: Write and run tests in a repository that uses Purview.BuildSdk. Use when authoring or refactoring TUnit tests (AAA structure, Subject_Scenario_Expectation naming, awaited assertions, CancellationToken), when choosing a test project's framework packages, and when running or filtering tests - the SDK wires Microsoft.Testing.Platform, so `dotnet test --filter` reports "Zero tests ran" and `--treenode-filter` is the one that works.
+license: MIT
+metadata:
+ package: Purview.BuildSdk
+ repository: purview-dev/build-sdk
+---
+
+# Testing in a Purview.BuildSdk repository
+
+Two things to know before anything else:
+
+1. A test project is detected by **name**, and detection is what wires the runner. See
+ `purview-buildsdk-project-layout` if the project is new or being moved.
+2. The runner is **Microsoft.Testing.Platform (MTP)**, not VSTest. `--filter` does nothing useful.
+
+## What a test project gets automatically
+
+With the defaults (`TestingFramework=TUnit`, `SubstituteFramework=TUnitMocks`,
+`TestDataFramework=Bogus`), a detected test project receives:
+
+- `TUnit`, `TUnit.Mocks`, `Bogus`
+- Microsoft.Testing.Platform integration
+- `CollectCoverage=true`
+- test-friendly `NoWarn` defaults (`PurviewTestContextNoWarn`), while keeping the strict style
+ contract — `IDE0040`, field naming, formatting, `IDE1006`
+- `IsPackable=false`, `IsPublishable=false`
+
+Add nothing else unless the project's purpose demands it. Two that stay explicit:
+
+- `TUnit.Aspire` — Aspire lifecycle and AppHost-backed integration tests
+- `Purview.Containers` — container-backed integration tests. One API over Microsoft WSL Containers
+ (no Docker install needed on Windows) or Docker, with typed modules for SQL Server, PostgreSQL,
+ Redis, MySQL, RabbitMQ, Azurite and NATS. Experimental and prerelease, so pin the version.
+ Reference `Testcontainers` directly only where no typed module exists yet.
+
+## Authoring rules
+
+- Use TUnit (`TUnit.Core`, `TUnit.Assertions`). Do not introduce xUnit, NUnit, MSTest or
+ FluentAssertions unless explicitly asked.
+- Every test method carries `[Test]`.
+- **Every assertion is awaited**: `await Assert.That(actual).IsEqualTo(expected);`. An un-awaited
+ assertion silently passes.
+- Arrange / Act / Assert, with the `// Arrange`, `// Act`, `// Assert` comments present.
+- Test classes are `{SubjectName}Tests`, in the **same namespace** as the subject.
+- Test methods are `{SubjectOrMemberUnderTest}_{Scenario}_{Expectation}`. Use `ctor` as the subject
+ for constructor tests. Methods, constructors, properties, operators, conversions and validation
+ hooks are all valid subjects.
+- When any method called in the test body accepts a `CancellationToken`, take
+ `CancellationToken cancellationToken` as the **last parameter** and pass it through.
+
+```csharp
+[Test]
+public async Task ProcessAsync_GivenAnEmptyBatch_ReturnsZero(CancellationToken cancellationToken)
+{
+ // Arrange
+ var sut = new BatchProcessor();
+
+ // Act
+ var result = await sut.ProcessAsync([], cancellationToken);
+
+ // Assert
+ await Assert.That(result).IsEqualTo(0);
+}
+```
+
+For a suite that is not subject-based — a build, generator, workflow, package or full-system suite —
+a broader, more truthful class name is better than a forced `{Subject}Tests`. Use TUnit display
+names and categories to keep it navigable.
+
+When refactoring existing tests, bring them into compliance with all of the above while preserving
+test intent.
+
+## Categories
+
+The detected test type becomes the baseline category automatically — `Api.IntegrationTests` yields
+`Category=Integration`. Add further categories when they make a large suite easier to navigate;
+they are what `--treenode-filter` property predicates select on.
+
+## Running tests
+
+```bash
+dotnet test # the whole suite
+dotnet test --treenode-filter "/*/*/LoginTests/*" # one class
+dotnet test --treenode-filter "/*/*/*/*[Category=Unit]"
+```
+
+Prefer the repository's own task (`just test`, or equivalent) for a full run.
+
+The filter path is `////`, with `*` wildcards, `=`/`!=` property
+predicates, `&`/`|` inside a single bracket group, and `**` only at the end. The full grammar, the
+`--` separator rules across SDK versions, and the zero-tests checklist are in
+[references/treenode-filter.md](references/treenode-filter.md).
+
+### "Zero tests ran"
+
+In order:
+
+1. Are you using `--treenode-filter` and not `--filter`? This is the cause most of the time.
+2. Try `dotnet test --treenode-filter "..."`; on an older SDK use `dotnet test -- --treenode-filter "..."`.
+3. Broaden to `/*/*/*/*`, then narrow one segment at a time.
+4. Does the project actually contain `[Test]` methods?
+5. Is the project **detected** as a test project? A name without the dot — `UnitTests` rather than
+ `Api.UnitTests` — gets no runner at all. Check with
+ `dotnet msbuild -getProperty:IsTestProject`.
+6. Are all property predicates inside one bracket group, `[(A=1)&(B=2)]`?
+
+## Cross-platform requirement
+
+CI runs the full suite on Linux, so a test that only passes on Windows is a failing change.
+
+- Never hardcode a platform-specific path — no `C:\...`, no backslash-only separators, no
+ case-insensitive path assumptions.
+- Build paths with `Path.Combine`, `Path.GetTempPath()`, `Path.DirectorySeparatorChar`,
+ `Path.GetFullPath()`.
+- Feed production path-math code only native-format paths. Normalise a fixed Windows-style literal
+ to the current platform before passing it in.
+- Do not rely on a case-insensitive filesystem, a `C:` drive, or trailing-separator behaviour.
+- Keep `SyntaxTree` file paths and `build_property.*` values consistent and native when writing
+ analyzer tests.
diff --git a/.agents/skills/purview-buildsdk-testing/references/treenode-filter.md b/.agents/skills/purview-buildsdk-testing/references/treenode-filter.md
new file mode 100644
index 00000000..35d032bc
--- /dev/null
+++ b/.agents/skills/purview-buildsdk-testing/references/treenode-filter.md
@@ -0,0 +1,107 @@
+# `--treenode-filter` reference
+
+TUnit runs on Microsoft.Testing.Platform, not VSTest, so the VSTest `--filter` syntax does not
+apply. Narrowing is done with `--treenode-filter`.
+
+## The path
+
+```text
+////
+```
+
+Each segment maps to one level of the tree:
+
+| Position | Matches |
+| -- | -- |
+| 1 | Assembly |
+| 2 | Namespace |
+| 3 | Class |
+| 4 | Test name |
+
+```text
+/*/*/LoginTests/* every test in LoginTests
+/*/*/*/AcceptCookiesTest one test by name
+/*/MyProject.Tests.Integration/*/* every test in a namespace
+/*/*/*/* everything
+```
+
+## Operators
+
+### `*` — wildcard
+
+Matches a whole segment or part of one.
+
+```text
+/*/*/LoginTests*/*
+/*/*/MyProject.Tests.Api*/*
+```
+
+### `=` and `!=` — property predicates
+
+In the last segment, inside `[...]`.
+
+```text
+/*/*/*/*[Category=Unit]
+/*/*/*/*[Category!=Slow]
+/*/*/*/*[Owner=*Team-Backend*]
+```
+
+### `&` and `|` — combining
+
+Inside a **single** bracket group, or a single parenthesised segment.
+
+```text
+/*/*/*/*[(Category=Unit)&(Priority=High)]
+/**[(Category=Unit)|(Priority=High)]
+/*/*/(LoginTests)|(SignupTests)/*
+```
+
+### `**` — match all
+
+Any depth, but **only at the end** of the path.
+
+```text
+/**
+/MyAssembly/**
+```
+
+`/**/Path` is not valid.
+
+## Rules that catch people out
+
+- Only **one** property group `[...]` per path segment. `[Category=Smoke]|[Priority=High]` is not
+ valid; write `[(Category=Smoke)|(Priority=High)]`.
+- `**` must be last.
+- A segment left empty is not a wildcard — write `*`.
+
+## The `--` separator
+
+```bash
+dotnet test --treenode-filter "/*/*/*/*[Category=Unit]" # preferred
+dotnet test -- --treenode-filter "/*/*/*/*[Category=Unit]" # older SDKs
+```
+
+Newer .NET SDKs forward unrecognised arguments to the MTP runner directly. On an older SDK the `--`
+separator is required, and omitting it produces an argument error rather than a filter.
+
+## Common selections
+
+| Intent | Filter |
+| -- | -- |
+| Everything | `/*/*/*/*` |
+| All unit tests | `/*/*/*/*[Category=Unit]` |
+| High-priority unit tests | `/*/*/*/*[(Category=Unit)&(Priority=High)]` |
+| One class | `/*/*/MyFeatureTests/*` |
+| A name pattern | `/*/*/*/MyScenario*` |
+| Critical integration tests | `/*/MyProject.Tests.Integration/*/*[Priority=Critical]` |
+
+## Zero tests ran
+
+1. `--treenode-filter`, not `--filter`.
+2. Try without the `--` separator first, then with it.
+3. Broaden to `/*/*/*/*`, then narrow one segment at a time.
+4. Confirm the project has `[Test]` methods.
+5. Confirm the project is **detected** as a test project —
+ `dotnet msbuild -getProperty:IsTestProject`. A name without the dot, such as
+ `UnitTests` rather than `Api.UnitTests`, is not detected and gets no runner.
+6. Confirm every property predicate sits in one bracket group.
diff --git a/.agents/skills/purview-containers-consumer-requirements/SKILL.md b/.agents/skills/purview-containers-consumer-requirements/SKILL.md
new file mode 100644
index 00000000..28a7ee46
--- /dev/null
+++ b/.agents/skills/purview-containers-consumer-requirements/SKILL.md
@@ -0,0 +1,128 @@
+---
+name: purview-containers-consumer-requirements
+description: >-
+ Use when a project consuming Purview.Containers will not build - PCC0001 or PCC0002, CS1705 for
+ Microsoft.Windows.SDK.NET, CS0234/CS0246 for Microsoft.WSL types, NETSDK1100 on a Linux build agent
+ - or when choosing the target framework and platform for a consumer of the WSL Containers backend.
+metadata:
+ product: Purview.Containers
+ repository: purview-dev/containers
+---
+
+# Consumer requirements
+
+## Which package requires what
+
+| Package | Target frameworks | Notes |
+| --- | --- | --- |
+| `Purview.Containers` | `net10.0`, any platform | the umbrella: `Core` plus both backends |
+| `Purview.Containers.Core` | `net10.0`, any platform | backend-neutral abstractions |
+| `Purview.Containers.` | `net10.0`, any platform | service modules; restore anywhere, need a backend to run |
+| `Purview.Containers.Wsl` | `net10.0` **and** `net10.0-windows10.0.19041.0` | a portable facade plus the Windows implementation. **Everything below is its contract.** |
+| `Purview.Containers.Docker` | `net10.0`, any platform | needs a reachable Docker daemon, not a Windows target framework |
+
+A consumer of any backend other than WSL needs only a portable `net10.0` project.
+
+## Most projects need nothing
+
+```xml
+net10.0
+```
+
+That binds the portable facade and gets automatic backend selection — WSLC on a Windows host, Docker
+everywhere else. It is the recommended choice, and it is why a Windows developer and a Linux CI
+runner can share one test project.
+
+A Windows-targeting project binds the implementation directly, with no run-time load:
+
+```xml
+
+ net10.0-windows10.0.19041.0
+ x64
+ 10.0.26100.80
+
+```
+
+The last two lines are optional — the package ships MSBuild defaults — but stating them makes the
+requirement visible to the next person reading the project file, and the defaults only fill in a
+value you have not chosen.
+
+## The five requirements
+
+| # | Requirement | Why |
+| --- | --- | --- |
+| 1 | **.NET 10 or later** | the package ships `lib/net10.0/` (facade) and `lib/net10.0-windows10.0.19041/` (implementation) |
+| 2 | **A Windows target framework that names the OS version** — *only* if you want the implementation bound directly | the `Microsoft.WSL.Containers` projection ships Windows assets only |
+| 3 | **64-bit** — `PlatformTarget` `x64`/`arm64`, or a matching `RuntimeIdentifier` | the native `wslcsdk.dll` ships for `win-x64` and `win-arm64` only |
+| 4 | **`WindowsSdkPackageVersion` ≥ `10.0.26100.80`** | the projection is compiled against `Microsoft.Windows.SDK.NET` `10.0.26100.79`, and the pack the SDK resolves for a `10.0.19041.0` target framework is older |
+| 5 | **A Windows 10/11 host with WSL Containers**, to actually run anything | the library drives WSLC; it never installs or updates it for you |
+
+### Always spell out the Windows version
+
+```xml
+net10.0-windows10.0.19041.0
+net10.0-windows
+```
+
+`net10.0-windows` resolves its platform version to **7.0**, older than the `10.0.19041.0` the
+implementation was built against, so NuGet selects no compile assets at all. (The
+`Microsoft.WSL.Containers` package is itself `net8.0-windows10.0.19041.0`, which a
+`net10.0-windows10.0.19041.0` project consumes without issue.)
+
+## What the package does for you
+
+`Purview.Containers.Wsl` ships two `buildTransitive` files, imported by NuGet for **direct and
+transitive** references:
+
+| File | Effect |
+| --- | --- |
+| `…Wsl.props` | defaults `WindowsSdkPackageVersion` to `10.0.26100.80` when unset, and registers the `wsl` backend |
+| `…Wsl.targets` | **Windows consumer:** defaults `PlatformTarget` to `x64` when unset or `AnyCPU` and no `RuntimeIdentifier` is selected, and fails with `PCC0001`/`PCC0002` when the target framework or platform cannot be supported. **Platform-neutral consumer:** copies the Windows implementation payload — implementation, WSLC projection, its Windows SDK dependencies, the native SDK — into `wslc/` beside the output on a Windows build host, so the facade can load it at run time. |
+
+An explicit `PlatformTarget`, `RuntimeIdentifier` or `WindowsSdkPackageVersion` in the consumer
+always wins.
+
+A **service module** is backend-neutral and brings no backend. Reference the module *and* a backend
+package, and use `PURVIEW_CONTAINERS_BACKEND` to pin which one runs.
+
+> Because `buildTransitive` assets are framework-agnostic, NuGet no longer reports `NU1202` for an
+> incompatible target framework: restore succeeds and the **guard target** produces the failure
+> instead. That is deliberate. `PCC0001` names the required target framework, whereas an empty
+> compile-asset set only produces `CS0246` errors in your own code — which blame the wrong thing.
+
+## Error reference
+
+| Error | Raised by | Means | Fix |
+| --- | --- | --- | --- |
+| `PCC0001` | the shipped guard target | the target framework is neither .NET 10+ on Windows `10.0.19041.0`+ nor a platform-neutral .NET 10+ framework | retarget as above |
+| `PCC0002` | the shipped guard target | the consumer is not 64-bit | remove `PlatformTarget`, set it to `x64`/`arm64`, or choose a matching `RuntimeIdentifier` |
+| `CS1705` naming `Microsoft.Windows.SDK.NET` | the compiler | the resolved Windows SDK targeting pack is older than the projection's | pin `WindowsSdkPackageVersion` to `10.0.26100.80` |
+| `CS0234`/`CS0246` for `Microsoft.WSL`/`Purview` types | the compiler | the package contributed no compile assets — an unsupported target framework, or an unverified escape hatch | fix the target framework; `PCC0001` says the same thing more clearly |
+| `NETSDK1100` | the SDK | building a Windows-targeted project on a non-Windows agent | set `EnableWindowsTargeting=true` |
+
+### `EnableWindowsTargeting` on a non-Windows agent
+
+It lets a Linux build agent *compile* a Windows-targeted project. It does **not** make the
+implementation runnable there — the facade still reports `wsl` unavailable, and Docker is selected.
+Use it to keep one solution building in CI, not as a way to run WSLC off Windows.
+
+## Verifying all of this
+
+The repository proves every row above rather than asserting it:
+
+- `Wsl.UnitTests/ConsumerRequirementsTests.cs` guards the **shape** inside the normal unit run — the
+ Windows build targets `.NETCoreApp,Version=v10.0`, targets `Windows10.0.19041.0`, and declares only
+ that OS platform. If the target framework drifts, that test fails, and this page, the package
+ READMEs and the `buildTransitive` defaults all have to move with it.
+- `just verify-consumers` proves the **behaviour**: it packs, then builds throwaway consumer projects
+ for every documented outcome, including the guard errors (`PlatformTarget=x86` → `PCC0002`;
+ `net8.0-windows` → `PCC0001`; `net11.0-windows` without an OS version → `PCC0001`). It sits outside
+ the `[Category=Unit]` filter because it restores from nuget.org.
+
+That split is the point: **a library's own build is not a consumer**, so a claim about consumers is
+only true if something builds one.
+
+## Related skills
+
+`purview-containers-quickstart` for packages and backend selection, and
+`purview-containers-testing` for the test tiers and CI shape.
diff --git a/.agents/skills/purview-containers-lifecycle/SKILL.md b/.agents/skills/purview-containers-lifecycle/SKILL.md
new file mode 100644
index 00000000..01b84ed7
--- /dev/null
+++ b/.agents/skills/purview-containers-lifecycle/SKILL.md
@@ -0,0 +1,144 @@
+---
+name: purview-containers-lifecycle
+description: >-
+ Use when reasoning about a Purview.Containers container's lifecycle or readiness - StartAsync,
+ StopAsync and DisposeAsync semantics, cleanup guarantees and why there is no restart, the Wait
+ strategy family and started-versus-ready, and WSL Containers networking, port mapping and the
+ absence of inter-container DNS.
+metadata:
+ product: Purview.Containers
+ repository: purview-dev/containers
+---
+
+# Lifecycle, readiness and networking
+
+## The public surface
+
+```csharp
+public interface IContainer : IAsyncDisposable
+{
+ Task StartAsync(CancellationToken ct = default);
+ Task StopAsync(CancellationToken ct = default);
+ ValueTask DisposeAsync();
+ // restart is intentionally NOT offered
+}
+```
+
+**There is no `RestartAsync`.** WSLC has no restart operation, and stop-then-start is not equivalent,
+so offering one would be a method that quietly means something different per backend.
+
+WSLC's `ContainerState` runs `Invalid → Created → Running → Exited → Deleted`.
+
+| Operation | Behaviour |
+| --- | --- |
+| `StartAsync` | creates the session if needed, ensures the image per the pull policy, creates the container, starts it, then waits. A missing init binary throws `ArgumentException 0x80070057` with the OCI message, surfaced as `WslContainerStartupException`. |
+| `StopAsync` | `Stop(SIGTERM, grace)`, then `Stop(SIGKILL, …)` if still running. **Idempotent** — WSLC accepts stopping an already-stopped container. |
+| `DeleteAsync` | `Delete(Force)`. A double delete throws `0x80010108` (`RPC_E_DISCONNECTED`) and is swallowed. |
+| `DisposeAsync` | stop if running → delete → release the WinRT object. **Idempotent.** |
+
+## Cleanup guarantees
+
+These are the ones that matter when a test throws:
+
+- `DisposeAsync` runs in a `finally` by callers, **and** the container object is registered for
+ cleanup by the runtime, so disposal happens even if a test throws after `StartAsync`.
+- `EnableAutoRemove` defaults to **`false`**: the library owns deletion. WSLC auto-removal would
+ delete a one-shot container before its state or output could be inspected — precisely when you need
+ them. Opt in with `.WithAutoRemove()`.
+- A **partial startup failure** — image pull, create, start or wait — tears down through the same
+ `DisposeAsync` path. So does a **cancelled** `StartAsync` or wait.
+- A **container crash** fires `InitProcess.Exited`; the container is then `Exited` and `DisposeAsync`
+ deletes it.
+- A **session crash** marks the runtime session dead, and subsequent operations throw
+ `WslContainerSessionTerminatedException` rather than failing obscurely.
+- **Test-process termination** disposes the shared session through a process-exit hook, freeing the
+ name. A *crashed* process leaves an orphaned session that only reserves its name; sweep it with
+ `wslc --session system session terminate`.
+
+## Secrets and names
+
+Container names are generated uniquely as `{service}-{processId}-{random8}` and **never contain
+credentials**; session names are `wslc-{pid}-{random8}`. Diagnostics redact secrets through a
+`Secret` wrapper whose `ToString()` returns ``.
+
+## Wait strategies
+
+**A started container is not a ready service.** `Container.Start()` returns once the init process is
+running; readiness is a separate check, and it is the one your test actually depends on.
+
+```text
+IWaitStrategy
+ TimeSpan? Timeout // null -> the container's StartupTimeout
+ TimeSpan Interval // default 250 ms
+ int? Retries // optional max failed checks
+ Task UntilAsync(WaitContext context, CancellationToken ct)
+
+WaitContext { IContainer Container; string? NetworkIp; int? GetHostPort(ushort); int? FirstHostPort; }
+```
+
+| Factory | Checks |
+| --- | --- |
+| `Wait.ForContainerRunning()` | `State == Running`. **Started, not ready.** |
+| `Wait.ForTcpPort(8080)` | connects to `127.0.0.1:`. IPv4 only. |
+| `Wait.ForHttp("/health")` | `.ForPort`, `.ForScheme`, `.ForStatusCode`, `.ForStatusPredicate`, `.ForHeader`, `.AllowInsecureTls` |
+| `Wait.ForLogMessage(string \| Regex)` | case-insensitive substring, or regex, against **accumulated** init-process output |
+| `Wait.ForCommand("pg_isready", "-U", "postgres")` | runs it via `ExecAsync`; ready at the expected exit code (default 0, `.ForExitCode(…)`) |
+| `Wait.ForCustom((context, ct) => …)` | anything else |
+| `Wait.ForAll(…)` / `Wait.ForAny(…)` | every strategy ready on the same check / at least one |
+
+Fluent modifiers: `.WithTimeout(…)`, `.WithInterval(…)`, `.WithRetries(…)`.
+
+Details worth knowing:
+
+- Waits run **inside** `StartAsync()`, after the container starts. `StartAsync` only returns when
+ every strategy is ready, or throws `ContainerTimeoutException`.
+- The default timeout is the container's `StartupTimeout` — 5 minutes, overridable with
+ `.WithStartupTimeout(…)` or per-strategy.
+- A timeout diagnostic includes the container name, image, state, mapped ports, the strategy type,
+ the last check error, and a bounded, secret-redacted tail of stdout/stderr.
+- The container buffers output from process start, so a log message emitted **before** the waiter's
+ first check still matches.
+- HTTP TLS validation is **on** by default. `AllowInsecureTls()` disables it for that request handler
+ only, never globally.
+- Transient exec failures during startup count as not-ready, not as failure.
+
+Modules pick their own readiness check: PostgreSQL `pg_isready`, Redis `redis-cli ping`, RabbitMQ
+`rabbitmq-diagnostics ping`, SQL Server a host-side connection.
+
+## Networking
+
+| `ContainerNetworkingMode` | Effect | Port mappings |
+| --- | --- | --- |
+| `null` (raw default) | Docker `NetworkMode: "none"` — no network, no IP | `CreateContainer` throws `0x80070057` |
+| `None` | the same | no |
+| `Bridged` | `172.17.0.x` on the session bridge; host→container mapped ports work | yes |
+
+`ContainerBuilder` defaults to **`Bridged`**, because a container with no network is not useful.
+
+Verified WSLC behaviour, and the parts that surprise people:
+
+- The host bind address is **IPv4 loopback only** (`HostIp: 127.0.0.1`). IPv6 `::1` does not connect.
+- **Clients must use `127.0.0.1`, not `localhost`.** `localhost` resolves to `::1` first on .NET.
+ Npgsql and StackExchange.Redis fall back to IPv4; `Microsoft.Data.SqlClient` **hangs** without
+ falling back.
+- Containers in the same session **can** reach each other by IP under `Bridged`.
+- There is **no name or DNS resolution between containers**. `http://:8080/` and
+ `http://:8080/` fail with "bad address"; `/etc/hosts` holds only localhost and the
+ container's own `IP `.
+- There are **no managed network objects** — `Microsoft.WSL.Containers` has no `network
+ create/connect`, unlike the CLI.
+
+How the library models it: `GetMappedPublicPort(containerPort)` reads
+`Inspect().Ports["/tcp"][0].HostPort`; `GetNetworkIp()` reads
+`Inspect().NetworkSettings.Networks.bridge.IPAddress` (Bridged only); TCP and HTTP waits connect to
+`127.0.0.1:`.
+
+**What not to model.** Do not invent Docker-style `Network` objects — the semantics are just "bridged
+with IPs". Do not claim container-name resolution works; it does not. Multi-container environments
+are deliberately deferred, and would wire containers together by passing each other's IPs from
+`GetNetworkIp()` into configuration or environment — which is why the core API does not preclude it.
+
+## Related skills
+
+`purview-containers-quickstart` for packages, backends and connection strings;
+`purview-containers-testing` for how a suite is organised and why it runs serially.
diff --git a/.agents/skills/purview-containers-quickstart/SKILL.md b/.agents/skills/purview-containers-quickstart/SKILL.md
new file mode 100644
index 00000000..c90b6c10
--- /dev/null
+++ b/.agents/skills/purview-containers-quickstart/SKILL.md
@@ -0,0 +1,181 @@
+---
+name: purview-containers-quickstart
+description: >-
+ Use when adding throwaway containers to a .NET test suite with Purview.Containers - which package to
+ reference, how the WSL Containers and Docker backends are selected automatically, running a generic
+ container with ContainerBuilder, using a typed service module, and getting a connection string.
+metadata:
+ product: Purview.Containers
+ repository: purview-dev/containers
+---
+
+# Purview.Containers quickstart
+
+Throwaway Linux containers for .NET tests, behind one API, over either **WSL Containers** (no Docker
+installation on Windows) or **Docker** (anywhere). The same test code runs on both.
+
+> **Experimental and prerelease.** The API, defaults and packaging rules can change between releases.
+> Pin the version you adopt.
+
+## Which package
+
+| Package | Use it when |
+| --- | --- |
+| `Purview.Containers` | the umbrella: `Core` plus both backends. One reference, zero config — WSLC on Windows, Docker elsewhere. **The default.** |
+| `Purview.Containers.Wsl` | WSL Containers only — a Windows machine with no Docker. |
+| `Purview.Containers.Docker` | Docker only — any platform, CI, Linux/macOS. A Linux-only job can skip the WSL backend's ~19 MB payload with `Core` + `.Docker`. |
+
+A service module is backend-neutral, so it needs a backend (or the umbrella) alongside it:
+
+```bash
+dotnet add package Purview.Containers.PostgreSql
+dotnet add package Purview.Containers
+```
+
+## The zero-config shape
+
+```xml
+
+
+ net10.0
+
+
+
+
+
+
+
+```
+
+Three things make it work, and nothing else is required:
+
+- **A platform-neutral target framework** (`net10.0`). `Purview.Containers.Wsl` is multi-targeted; a
+ `net10.0` project binds its **portable facade**, which runs the WSLC implementation on Windows and
+ reports `wsl` unavailable everywhere else. A Windows target framework binds the implementation
+ directly — and then cannot run on a Linux CI runner.
+- **The umbrella package**, bringing `Core` and both backends.
+- **No registration line and no environment variable.** Each backend package ships `buildTransitive`
+ assets that generate a module initializer in your assembly, so the process discovers the registered
+ backends itself. Those assets flow transitively through the umbrella.
+
+## Backend selection
+
+| Host | Selected | Why |
+| --- | --- | --- |
+| Windows with WSL Containers | `wsl` | the facade loads the WSLC implementation, and WSLC is preferred |
+| Windows with Docker only | `docker` | the facade reports `wsl` unavailable, so selection falls through |
+| Linux / macOS | `docker` | the facade only ever activates on Windows |
+
+Selection probes the registered backends in priority order (`wsl` is `0`, `docker` is `100`) and
+returns the first that is both **available** and **compatible**. When none is usable, the exception
+lists each backend's availability, version and missing components.
+
+```csharp
+foreach (var backend in await ContainerBackends.ProbeAllAsync())
+ Console.WriteLine($"{backend.Name}: usable={backend.IsUsable} version={backend.Version}");
+```
+
+```bash
+PURVIEW_CONTAINERS_BACKEND=docker # or wsl - fail loudly instead of falling back
+```
+
+A **named** backend never silently falls back: if it cannot run, the test fails with that backend's own
+diagnostics. That is usually what you want in CI.
+
+The library never installs a runtime. `WslContainerRuntime.GetInfoAsync()` and
+`DockerContainerBackend.GetInfoAsync()` report what is missing. Verify a host with `wsl --version` and
+`wslc version`, or `docker info`.
+
+## A generic container
+
+```csharp
+using Purview.Containers;
+using Purview.Containers.Waiting;
+
+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);
+```
+
+`Build()` validates the accumulated configuration and resolves the backend when the container starts.
+`StartAsync()` creates the container, starts it, and **only returns once every configured wait
+strategy is satisfied**. `DisposeAsync()` stops and deletes the container — and never terminates a
+shared WSLC session.
+
+## A typed module
+
+```csharp
+using Npgsql;
+using Purview.Containers.PostgreSql;
+
+await using var postgres = new PostgreSqlBuilder()
+ .WithDatabase("tests")
+ .WithUsername("postgres")
+ .WithPassword("postgres")
+ .Build();
+
+await postgres.StartAsync(); // returns once pg_isready succeeds
+
+await using var connection = new NpgsqlConnection(postgres.GetConnectionString());
+await connection.OpenAsync();
+```
+
+No image names, no ports, no `docker`, no `wslc`. The default image, the random host port mapping and
+the readiness check all come from the module.
+
+Modules: PostgreSQL, Redis, SQL Server, MySQL, RabbitMQ, Azurite, NATS and the Azure Key Vault
+Emulator. Each ships a README inside its own package.
+
+## Connection strings
+
+Every container implements `IConnectionStringProvider`, so you can ask any container without knowing
+its module type:
+
+```csharp
+string connectionString = container.GetConnectionString(); // ConnectionMode.Host
+string same = container.GetConnectionString(ConnectionMode.Host);
+```
+
+| Mode | Meaning | Support |
+| --- | --- | --- |
+| `Host` | test host → container, via the mapped host port (`127.0.0.1:{port}`) | both backends |
+| `Container` | container → container, via the container network | **not supported** — throws `ConnectionStringModeNotSupportedException` |
+
+Container-to-container is deliberately deferred: WSLC has no managed networks or inter-container DNS,
+and the Docker backend does not attach containers to a shared network.
+
+**Use `127.0.0.1`, never `localhost`.** `localhost` resolves to `::1` first on .NET, and while most
+clients fall back to IPv4, `Microsoft.Data.SqlClient` **hangs** on `::1` without falling back — which
+is why the SQL Server module's connection strings are explicitly `127.0.0.1,{port}`.
+
+### A custom provider
+
+```csharp
+sealed class ReadOnlyPostgreSql : ContainerConnectionStringProvider
+{
+ protected override string GetHostConnectionString() =>
+ $"{Container.GetConnectionString()};ApplicationName=readonly";
+}
+
+var postgres = new PostgreSqlBuilder()
+ .WithConnectionStringProvider(new ReadOnlyPostgreSql())
+ .Build();
+```
+
+`Configure` runs once, **after** the container has started, so runtime-assigned ports are available. A
+provider producing an empty string throws `ConnectionStringNotAvailableException`; one used before
+`Configure` throws `ConnectionStringProviderNotConfiguredException`. The named overload
+(`GetConnectionString(name, mode)`) exists for modules with several endpoints and otherwise throws
+`ConnectionStringNameNotSupportedException`.
+
+## Related skills
+
+`purview-containers-lifecycle` for start/stop/dispose semantics, wait strategies and networking;
+`purview-containers-testing` for suite layout, serial execution and CI; and
+`purview-containers-consumer-requirements` for the target-framework contract and the `PCC` guards.
diff --git a/.agents/skills/purview-containers-testing/SKILL.md b/.agents/skills/purview-containers-testing/SKILL.md
new file mode 100644
index 00000000..5d8be988
--- /dev/null
+++ b/.agents/skills/purview-containers-testing/SKILL.md
@@ -0,0 +1,126 @@
+---
+name: purview-containers-testing
+description: >-
+ Use when organising or running a test suite that uses Purview.Containers - the Unit and Integration
+ tiers, why test modules must run serially under WSL Containers, pinning or skipping a backend,
+ running the Docker suites in CI and the WSL suites on a self-hosted runner, and verifying the
+ consumer contract.
+metadata:
+ product: Purview.Containers
+ repository: purview-dev/containers
+---
+
+# Testing with containers
+
+## Tiers
+
+The SDK stamps every test assembly with a TUnit category derived from the **project name**, so the
+tier is a property of the project rather than of a hand-written attribute:
+
+| Project | Category | Runtime needed |
+| --- | --- | --- |
+| `*.UnitTests` | `Unit` | none — logic, parsing, configuration, wait-strategy units, in-process fakes |
+| `Wsl.*` and module `*.IntegrationTests` | `Integration` | a **WSLC host** |
+| `Docker.IntegrationTests`, `Modules.DockerIntegrationTests` | `Integration` | any **Docker daemon**; these target `net10.0`, so they run on Linux too |
+
+The shared pipeline filters to `/*/*/*/*[Category=Unit]`, so **the standard pipeline never starts a
+container**. The Docker suites are the exception: the PR workflow adds an `integration-docker` job on
+`ubuntu-latest`. That job is the standing proof that the library and every service module work off
+Windows and WSL — the same modules a developer runs on WSLC locally.
+
+```powershell
+just test # every discovered project
+just test '/*/*/*/*[Category=Unit]' # unit only
+just test '/*/*/*/*[Category=Integration]' --max-parallel-test-modules 1
+just test src/tests/Docker.IntegrationTests/Docker.IntegrationTests.csproj
+```
+
+Filtering uses TUnit's `--treenode-filter`, not `--filter`: this runs on Microsoft.Testing.Platform,
+where `dotnet test --filter` reports "Zero tests ran".
+
+## Why test modules run serially
+
+A WSLC session takes an **exclusive lock on its `storage.vhdx`**, and takes it lazily on first store
+access rather than at session start. Running test assemblies in parallel therefore makes the losers
+fail:
+
+```text
+0x80070020: The process cannot access the file because it is being used by another process.
+```
+
+`just test` passes `--max-parallel-test-modules 1` for exactly that reason. The runtime verifies the
+store once and transparently falls back to an isolated per-process store, but serial modules keep the
+**warm shared image cache** — no per-process re-pull — and are the fastest option.
+
+In Visual Studio, untick **Run Tests in Parallel** (or set *Maximum Parallel Test Projects* to 1)
+before running the WSLC integration suites.
+
+## Choosing a backend in a suite
+
+Automatic detection prefers WSLC and falls back to Docker, so a WSLC host runs the WSLC suites and a
+Docker-only host runs the Docker ones. Pin one to **fail loudly instead of falling back** —
+usually what you want in CI:
+
+```bash
+PURVIEW_CONTAINERS_BACKEND=wsl # or docker
+```
+
+Both halves skip themselves when their runtime is unreachable: the Docker suites when no daemon
+responds, the WSLC suites when the host lacks the WSL Containers components. That is what lets a
+machine without WSLC still run the unit tier — and it is also why a mis-provisioned CI runner reports
+*successes with skips* rather than real coverage. Print `wsl --version` and `wslc version` as the
+job's first step so that failure is visible immediately.
+
+## CI shape
+
+- **Docker half** — runs on every pull request, on `ubuntu-latest`.
+- **WSL half** — cannot: it needs a Windows host with WSL Containers, which no GitHub-hosted runner
+ provides. It is a **manual** workflow on a self-hosted runner:
+
+ ```bash
+ gh workflow run "Integration (WSL Containers)" --ref main
+ gh run watch
+ ```
+
+ It runs `Wsl.IntegrationTests` then each service-module suite **one project at a time**, so the
+ shared WSLC image store is never contended. Inputs: `ref` and `filter` (a treenode filter).
+
+Self-hosted runner prerequisites: a **Windows x64** runner labelled `self-hosted` and `wslc`, with
+WSL Containers installed (`wsl --install --no-distribution`) and the pinned .NET SDK. Tell
+`actionlint` about the custom label in `.github/actionlint.yaml`.
+
+> The shared pipeline runs on `ubuntu-latest`, so it builds the portable `net10.0` projects **and**
+> the Windows-targeted test projects on Linux. That works only because `src/Directory.Build.props`
+> sets `EnableWindowsTargeting=true`; without it the SDK reports `NETSDK1100`.
+
+## Expectations
+
+`Wsl.IntegrationTests` runs many real containers in one session and can take several minutes, because
+WSLC serialises container operations. Slow-test warnings while it runs are expected, not a signal.
+
+## Verifying the consumer contract
+
+Two layers, and the split matters.
+
+**Shape, inside the unit run.** `Wsl.UnitTests/ConsumerRequirementsTests.cs` asserts that the Windows
+build targets `.NETCoreApp,Version=v10.0`, targets `Windows10.0.19041.0`, and declares only that OS
+platform. If the target framework drifts, that test fails — and the consumer-requirements page, the
+package READMEs and the shipped `buildTransitive` defaults all have to move with it.
+
+**Behaviour, outside it.** `just verify-consumers` packs the packages and builds throwaway consumer
+projects for every documented outcome — the happy paths *and* the documented guard errors. It is
+deliberately outside the `[Category=Unit]` filter because it packs and restores from nuget.org:
+
+```powershell
+just verify-consumers # 21 consumer projects, all assertions
+just verify-consumers -Keep # keep the generated projects for inspection
+```
+
+This is the general rule worth copying: **a library's own build is not a consumer**, so a claim about
+consumers is only true if something builds one.
+
+## Related skills
+
+`purview-containers-quickstart` for the packages and backend selection,
+`purview-containers-lifecycle` for readiness and cleanup, and
+`purview-containers-consumer-requirements` for the target-framework contract and `PCC` guards.
diff --git a/.agents/skills/purview-results-core/SKILL.md b/.agents/skills/purview-results-core/SKILL.md
new file mode 100644
index 00000000..93719fdd
--- /dev/null
+++ b/.agents/skills/purview-results-core/SKILL.md
@@ -0,0 +1,140 @@
+---
+name: purview-results-core
+description: "Use when writing or reviewing code that returns Purview.Results Result or value-less Result values — choosing between exceptions and results, creating, reading, or transforming a result, and reasoning about the uninitialized default state."
+---
+
+# Purview.Results core
+
+Use this skill whenever a method returns `Result` or the value-less `Result` from the
+`Purview.Results` package.
+
+## The three states
+
+`Result` is a `readonly record struct`, so `default` is a real, observable state.
+
+| State | `IsInitialized` | `IsSuccess` | `IsFailure` | `Value` | `Error` |
+| --- | --- | --- | --- | --- | --- |
+| Success | `true` | `true` | `false` | the value | throws |
+| Failure | `true` | `false` | `true` | throws | the error |
+| Uninitialized (`default`) | `false` | `false` | `false` | throws | throws |
+
+`Value` and `Error` throw `InvalidOperationException` when the result is in the wrong state, and `Match`, `Map`,
+`Bind` and `MapError` throw `"The result is uninitialized."` for `default`. **An uninitialized result is a bug,
+never a success and never a failure** — if a method can fail to produce a result, return a failure case instead
+of falling off the end of the method body.
+
+## Creating results
+
+```csharp
+// Named factories
+Result.Success(tenant);
+Result.Failure(new TenantNotFound(id));
+
+// Type-inferring factories
+Result.Success(tenant);
+Result.Failure(new TenantNotFound(id));
+
+// Implicit conversions (one hop only)
+Result ok = tenant;
+TenantError error = new TenantNotFound(id); // case -> union is one hop
+Result failed = error; // union -> result is the next hop
+
+// Union-receiver factory (generated for [GenerateResult] unions; shared-case safe)
+TenantError.Failure(new TenantNotFound(id));
+TenantError.Failure(new TenantNotFound(id));
+TenantError.Success();
+TenantError.Success(tenant);
+```
+
+The implicit conversions accept `TValue` or `TError` directly. They do **not** compose: a union *case* cannot
+convert to the result in one hop, which is why the source generator exists (see the
+`purview-results-union-errors` skill).
+
+## Reading and transforming
+
+| Member | Purpose |
+| --- | --- |
+| `Match(success, failure)` | Fold both states into one value |
+| `Map(map)` | Transform the successful value, preserving the error |
+| `Bind(bind)` | Chain an operation that can fail, preserving the error type |
+| `Bind(bind, mapError)` | Chain an operation that fails with a different error type, widening the existing error |
+| `MapError(map)` | Transform the error, preserving the value |
+| `TryGetValue(out value)` | Probe without throwing: `true` only for a success |
+| `TryGetError(out error)` | Probe without throwing: `true` only for a failure |
+| `GetValueOrDefault()` / `(fallback)` / `(factory)` | Value, or a default/fallback — throws for `default` |
+| `GetErrorOrDefault(fallback)` | Error, or a fallback — throws for `default` |
+| `OrElse(fallback)` | This result when successful, otherwise another result |
+| `Switch(success, failure)` | Side effects per state; returns `void` |
+| `Tap(success)` / `TapError(failure)` | Side effects that return the result, so calls can be chained |
+| `Ensure(predicate, errorFactory)` | Turn a value that fails a predicate into a failure |
+| `MapAsync(map)` / `BindAsync(bind)` | Asynchronous `Map`/`Bind` |
+| `BindAsync(bind, mapError)` | Asynchronous widening `Bind` |
+| `Throw()` | Return the value, or throw `ResultException` carrying the error (escape hatch) |
+
+Prefer `Match`/`Map`/`Bind` over `if (result.IsSuccess)` when a value has to come out of the result: they keep
+the failure path explicit and cannot silently leak a `default`.
+
+`TryGetValue`/`TryGetError` are the only members that never throw; the rest throw for `default` so a forgotten
+initialization surfaces immediately.
+
+## Value-less results
+
+When an operation has nothing to return on success — a command, a validation-only step — use `Result`
+instead of inventing a meaningless value (a `bool`, a `Unit`). It has the same three states and the same
+throw-on-misuse contract, but a success holds the `Success` marker and its success callbacks take no argument:
+
+```csharp
+Result DeleteTenant(TenantId tenantId) =>
+ _tenants.Remove(tenantId)
+ ? Result.Success()
+ : new TenantNotFound(tenantId).AsFailure();
+
+deleted.Match(() => "deleted", error => $"could not delete: {error}");
+deleted.Map(() => 1); // attach a value: Result
+deleted.Bind(() => GetTenant(tenantId)); // continue with another operation
+deleted.Ensure(() => _tenants.Count > 0, () => new TenantError());
+```
+
+- `Result.Success()` / `.Failure(error)`, `Result.Success()` / `Result.Failure(error)`,
+ and the implicit conversions from `Success` and `TError` create a unit result.
+- `Match`, `Switch`, `Tap` and `Ensure` take a **no-argument** success delegate; `Map` produces a value from a
+ success that had none; `Bind` continues with either another unit operation or a value-producing one.
+- `Error` throws in the wrong state; `Throw()` returns the `Success` marker or throws `ResultException`;
+ `ToString()` is `Success` / `Failure(error)` / `Uninitialized`.
+- `Result.DiscardValue()` drops a value result's value and keeps the error, so a value result can
+ join a unit-result chain.
+
+Use `Result` when the failure is the only interesting outcome; use `Result` when the
+caller needs the produced value.
+
+## Infrastructural view
+
+`IResultValue` is the non-generic, read-only view (`IsInitialized`, `IsSuccess`, `SuccessValue`, `ErrorValue`)
+for code that cannot be generic over the value and error types — an endpoint filter or a logging middleware, for
+example. Its accessors never throw: the one that does not describe the current state returns `null`, and a
+successful unit `Result` reports the `Success` marker as its `SuccessValue`. Use it in infrastructure, and
+the generic type in domain code.
+
+## When to use a result
+
+**Use it** for expected, domain-level outcomes the caller must handle: not found, invalid, conflict, disabled,
+already exists. These are values with meaning, and making them explicit keeps the happy path readable.
+
+**Throw instead** for programming errors and unrecoverable infrastructure faults (a lost connection, a violated
+invariant, a missing configuration key). Wrapping those in a result forces every caller to branch on something
+it cannot act on.
+
+Rules of thumb:
+
+1. If the caller is expected to *do* something different per outcome, the outcome is a result value.
+2. If the caller can only log and rethrow, it is an exception.
+3. Never use `Result` where the failure is the only interesting outcome — use the value-less
+ `Result` instead, or model the outcomes as cases.
+4. Convert at the boundaries: a controller or endpoint handler turns the result into a response, an application
+ service returns it, and repositories return it rather than throwing on "not found".
+
+## Related skills
+
+- `purview-results-union-errors` — modelling the error type as a union and generating the failure helpers.
+- `purview-results-http-mapping` — turning results into ASP.NET Core responses.
+- `purview-results-zodsharp-validation` — folding ZodSharp validation outcomes into results.
diff --git a/.agents/skills/purview-results-http-mapping/SKILL.md b/.agents/skills/purview-results-http-mapping/SKILL.md
new file mode 100644
index 00000000..ac4629ea
--- /dev/null
+++ b/.agents/skills/purview-results-http-mapping/SKILL.md
@@ -0,0 +1,135 @@
+---
+name: purview-results-http-mapping
+description: "Use when an ASP.NET Core endpoint returns Purview.Results values — registering AddResultsHttp, mapping error cases to status codes with Map, answering a failure by its shape with an IResultsFailureMapper, using fallbacks, correcting unmapped-failure 500s, or converting a result with ToHttpResult."
+---
+
+# Mapping results onto ASP.NET Core responses
+
+Use this skill when a minimal-API endpoint, or any handler, returns `Result` or the value-less
+`Result` and the host has to decide what each error case looks like on the wire.
+
+## Registration
+
+```csharp
+using Microsoft.Extensions.DependencyInjection;
+
+builder.Services.AddResultsHttp(options => options
+ .Map(error => TypedResults.NotFound())
+ .Map(error => TypedResults.Problem(
+ statusCode: StatusCodes.Status403Forbidden,
+ title: "The tenant is disabled."))
+ .Map(error => TypedResults.Problem(statusCode: StatusCodes.Status409Conflict)) // every other case
+);
+
+app.MapGet("/tenants/{id:int}", (int id) => GetTenant(id)).WithResultsHttp();
+```
+
+- `AddResultsHttp` registers problem-details services, the mapper (`TryAddSingleton`, so a host can register its
+ own first) and the endpoint filter. Its `configure` callback is optional.
+- `WithResultsHttp()` exists on both `RouteHandlerBuilder` and `RouteGroupBuilder` and adds the endpoint filter.
+ A handler that returns something other than an `IResultValue` is left untouched, so the filter is safe to
+ apply to a whole group.
+- Mapping by hand is also supported: `result.ToHttpResult(context)` resolves the mapper from the request
+ services, and `result.ToHttpResult(mapper, context)` takes one directly.
+
+## Response resolution order
+
+**Success**
+
+1. `SuccessMapper` when set — it replaces the default entirely.
+2. A successful value that is itself an `IResult` is passed through untouched.
+3. A successful unit `Result` carries no payload, so it answers `204 No Content`.
+4. Otherwise the value is serialized: `200 OK` for the default status code, `TypedResults.Json(value,
+ statusCode: …)` when `SuccessStatusCode` was changed.
+
+**Failure** — the error is resolved to its *case* value (the innermost active union case, so a nested union
+resolves to its leaf; or the error itself when it is not a union), then:
+
+1. the mapping registered for the most specific **case** type — `Map(…)`;
+2. the mapping registered for each enclosing **union** type, from the inside out — `Map(…)` handles
+ a whole nested union when its leaf has no mapping;
+3. the mapping registered for the **error** type — `Map(…)`, which covers every case without its
+ own mapping;
+4. the **fallback stage**, in registration order — `AddFallback(...)` delegates and
+ `AddFailureMapper()` mappers share this one list, so whichever was registered first is consulted
+ first; returning `null` defers to the next entry;
+5. the **unmapped-failure** response.
+
+Registering the same type twice replaces the earlier mapping. Fallbacks receive the *leaf* case value, so a
+fallback never has to unwrap the union itself.
+
+## Shape-based rules
+
+`Map` is keyed by type, which cannot see the *value* a failure carries. When the answer depends on the
+payload — a validation error code, a category, a field — register a failure mapper instead:
+
+```csharp
+public sealed class BlankIdentifierMapper : IResultsFailureMapper
+{
+ public IResult? Map(ResultsFailureContext context) =>
+ context.Case is ITenantFailure { TenantId.Value: var id } && string.IsNullOrWhiteSpace(id)
+ ? TypedResults.Problem(statusCode: StatusCodes.Status400BadRequest, title: "An identifier is required.")
+ : null; // defer to the case mappings and the other fallbacks
+}
+
+builder.Services.AddSingleton();
+builder.Services.AddResultsHttp(options => options.AddFailureMapper());
+```
+
+- `ResultsFailureContext` carries `Case` (the innermost active case, so a nested union resolves to its leaf; or
+ the error itself for a non-union error), `Error` (the union or error value as a whole) and `HttpContext`.
+- The mapper is resolved from the request's services, so it may take dependencies in its constructor; register
+ it before the first request or the failure throws an `InvalidOperationException` naming what is missing.
+- A mapper shares the fallback list with `AddFallback`, so **registering it earlier makes it win** — that is how
+ a host answers some validation codes before a package's validation mapping (see
+ `purview-results-zodsharp-problems`).
+- **A mapper is not a catch-all.** Answering every failure with a generic problem hides the mapping gaps the
+ unmapped-failure `500` exists to expose. Answer the shape you can name and return `null` for the rest.
+
+## Options
+
+| Option | Default | Notes |
+| --- | --- | --- |
+| `SuccessStatusCode` | `200` | Status for a serialized successful value |
+| `SuccessMapper` | `null` | Replaces the default success handling |
+| `UnmappedStatusCode` | `500` | Status for a failure with no mapping |
+| `UnmappedTitle` | *"The operation failed with an error that is not mapped to an HTTP response."* | Title of the unmapped problem |
+| `ThrowOnUnmappedFailure` | `false` | Throw instead of responding; use during development |
+| `IncludeTraceId` | `true` | Whether problems this package writes carry the request trace identifier |
+
+## Treat an unmapped failure as a bug in the host
+
+An unmapped failure is a **mapping gap**, not a domain outcome: the response is `UnmappedStatusCode` (`500`)
+with a `ProblemDetails` carrying an `errorType` extension naming the case, and an error is logged. When you see
+one in the logs, add the mapping; do not widen a catch-all mapping to silence it.
+
+The same path handles an **uninitialized** result (`default`), which is logged and answered with
+`errorType = "results_uninitialized"` — an endpoint returning `default` is always a bug in the handler.
+
+During development, `ThrowOnUnmappedFailure = true` turns both into an `InvalidOperationException` so the gap
+surfaces at the call site.
+
+## Choosing status codes
+
+Map the *case*, not the HTTP verb:
+
+| Domain meaning | Response |
+| --- | --- |
+| Input failed validation | `400` with a validation problem (see `purview-results-zodsharp-problems`) |
+| Not authenticated / not authorised | `401` / `403` |
+| The thing does not exist | `404` |
+| The thing already exists | `409` |
+| The thing is in the wrong state for this operation | `409` or `422` |
+| Rate-limited or temporarily unavailable | `429` / `503` |
+
+Keep the mapping table next to `AddResultsHttp` so every case is visible in one place; a case that is missing
+from it is exactly what the unmapped-failure log is telling you.
+
+## Pitfalls
+
+- **Do not** return `IResult` from domain or application code — results stay transport-agnostic and the host
+ keeps the mapping.
+- **Do not** map a case to a status code you would not document; `500` for a domain outcome hides real bugs.
+- A shared case type used by two unions can be mapped once — mapping is keyed by the case type.
+- The unmapped `ProblemDetails` is written through `IProblemDetailsService`, so ASP.NET Core adds the trace
+ identifier itself; `IncludeTraceId` only affects problems this package serializes itself.
diff --git a/.agents/skills/purview-results-union-errors/SKILL.md b/.agents/skills/purview-results-union-errors/SKILL.md
new file mode 100644
index 00000000..ce6ea9ab
--- /dev/null
+++ b/.agents/skills/purview-results-union-errors/SKILL.md
@@ -0,0 +1,179 @@
+---
+name: purview-results-union-errors
+description: "Use when modelling expected failures as a C# 15 union and converting its cases into Purview.Results values — declaring [GenerateResult] unions, using the generated per-case AsFailure()/AsFailure() helpers and the union-receiver Union.Failure(...)/Union.Success(...) factories, reacting to the RSG1000-RSG1008 diagnostics, or explaining why a union case cannot convert implicitly."
+---
+
+# Modelling error unions for Purview.Results
+
+Use this skill when a codebase models expected failures as a **union** and returns
+`Result` or the value-less `Result` from the `Purview.Results` package.
+
+Replacing thrown domain exceptions, `bool`/`out` pairs or error enums in existing code? The
+step-by-step playbook is in
+[references/migrating-error-returns.md](references/migrating-error-returns.md).
+
+## The shape
+
+```csharp
+using Purview.Results;
+
+// One small, focused type per case.
+public readonly record struct TenantNotFound(TenantId TenantId);
+public readonly record struct TenantDisabled(TenantId TenantId);
+public readonly record struct TenantAlreadyExists(TenantId TenantId);
+
+// One union per operation family.
+[GenerateResult]
+public readonly union TenantError(TenantNotFound, TenantDisabled, TenantAlreadyExists);
+
+public static Result Get(TenantId id) =>
+ _tenants.TryGet(id, out var tenant)
+ ? Result.Success(tenant)
+ : new TenantNotFound(id).AsFailure(); // generated
+```
+
+`AsFailure()` and the non-generic `AsFailure()` are generated **once per case type**, into
+`public static class {Union}ResultExtensions` in the union's own namespace. The generic helper calls
+`Result.Failure(case)`; the non-generic one calls `Result.Failure(case)` and produces a
+value-less unit result:
+
+```csharp
+Result Get(TenantId id) => new TenantNotFound(id).AsFailure();
+Result Delete(TenantId id) => new TenantNotFound(id).AsFailure();
+```
+
+The same class declares a C# 14 extension block on the union type, so the union can name the call instead of the
+case:
+
+```csharp
+Result Get(TenantId id) => TenantError.Failure(new TenantNotFound(id));
+Result Delete(TenantId id) => TenantError.Failure(new TenantNotFound(id));
+Result ok = TenantError.Success();
+Result created = TenantError.Success(tenant);
+```
+
+Prefer the union-receiver factory when a case type is shared with another union (`RSG1006`): the per-case
+`AsFailure` helper is generated once and can bind to the wrong union, while `Union.Failure(...)` always names the
+union you want. A case type that is itself a union is an *included union*: sharing it is composition, so it is not
+reported, and the factory also covers the included union's cases by building the nested value.
+
+## Why the helper is required
+
+The generator cannot declare an implicit conversion from a case to the result, and neither can you. Five
+independent C# rules block it:
+
+| Attempt | Diagnostic |
+| --- | --- |
+| Declare the operator beside the helpers | `CS0715` — operators are illegal in a **static class** |
+| Declare it in any other helper class | `CS0556` — a conversion must be declared by the **source or target type** |
+| Declare it as an extension member | `CS9282` — **conversions are not allowed in extension blocks** |
+| Make it generic over the result's value type | `CS0246` — operators **cannot declare type parameters** |
+| Rely on `case → union → result` composing | `CS0029` — **one user-defined conversion per sequence** |
+
+The only shape the language accepts is a *generic case type* carrying the value type parameter, which the
+generator rejects as `RSG1002` — so `AsFailure()` is the ergonomics the language allows.
+
+A helper-free form exists when a cast reads better, because the cast closes the first conversion:
+
+```csharp
+Result Get(TenantId id) => (TenantError)new TenantNotFound(id);
+```
+
+`Purview.Results` also ships an IDE code fix: when you write
+`return new TenantNotFound(id);` in a `Result`- or `Result`-returning member, the
+lightbulb offers the `Union.Failure(case)` or `Union.Failure(case)` rewrite. The fix names the union, so it
+is correct even when the case type is shared with another union. It is only offered when the rewrite will bind (the
+converted type is a result, the error type is a `[GenerateResult]` union, the value is one of its cases, and the
+union is in scope by simple name).
+
+## Chaining across services
+
+When one service calls another, the caller's operation-family union takes the callee's **error union** as a case,
+then the widening `Bind` (or a `TryGetError` guard) lifts the callee's failure into the caller's contract:
+
+```csharp
+[GenerateResult]
+public readonly union RegisterTenantError(TenantError, BillingError);
+
+Result Register(TenantId id, string name) =>
+ billing.ReserveQuota(id)
+ .Bind(quota => CreateTenant(quota, name), error => error); // BillingError -> RegisterTenantError
+```
+
+List the union as a case, not its leaf cases: the caller's union-receiver factory then covers the callee's cases and
+builds the nested value (`CallerUnion.Failure(leaf)`), so no leaf is shared and no `RSG1006` is raised. A leaf listed
+in two unions is a shared leaf: its per-case helper is generated for only one of them, so a case-receiver call site
+can bind to the wrong union; convert it with the union-receiver factory instead. A case reachable through two
+different included unions is reported as `RSG1008` and its inclusion factory is skipped. To keep the callee's types
+out of the caller's contract, map its cases into the caller's own case types with `MapError` instead — the compiler
+then forces the mapping to stay exhaustive as the callee's union grows. The ASP.NET Core mapper resolves a union
+error to its innermost case, so a leaf mapping wins and an enclosing-union mapping still applies when the leaf has
+none.
+
+## Rules of thumb
+
+- **One case type, one meaning.** Cases are the vocabulary of the failure surface; a case with a `string
+ Reason` invites callers to match on that string instead of on the type.
+- **One union per operation family**, not one per method: `TenantError` covers every way tenant work fails, so
+ the union stays a stable contract while methods come and go.
+- **Never re-derive the case from the union in the caller** — keep the case strongly typed and let the HTTP or
+ UI layer map it (see the `purview-results-http-mapping` skill).
+- **Small unions are better.** A union with a dozen cases is usually several operation families sharing one
+ name.
+- **Opt in deliberately.** `[GenerateResult]` on a union you do not return from a result produces dead code;
+ apply it where the union crosses a `Result` boundary.
+
+## Diagnostics
+
+The package ships an analyzer and a generator that share one diagnostics library.
+
+| ID | Severity | Meaning |
+| --- | --- | --- |
+| `RSG1000` | Error | `[GenerateResult]` was applied to a type that is not a union |
+| `RSG1001` | Error | The union declares no union cases |
+| `RSG1002` | Error | Generic union, or a case type that contains type parameters |
+| `RSG1003` | Error | A type generated code must reference is not accessible (for example a `file` type) |
+| `RSG1004` | Error | The same union is configured more than once; the helpers are generated once |
+| `RSG1005` | Error | Two unions produce the same generated class name in one namespace |
+| `RSG1006` | Warning | A **leaf** case type is shared with another union, so its per-case `AsFailure` helper is generated once; the union-receiver `Failure(...)` factory is generated for every union. A union-typed case shared across unions is composition and is not reported |
+| `RSG1007` | Error | The union uses an `IUnionMembers` member provider, which is not supported |
+| `RSG1008` | Warning | A case is reachable through two different included unions, so no inclusion factory can name its construction path; that case's inclusion factory is skipped |
+
+`RSG1004`, `RSG1006` and `RSG1008` are non-blocking: the union (or the shared/ambiguous case) is skipped and
+reported.
+
+Unsupported by design: `IUnionMembers` member providers (`RSG1007`) and generic unions (`RSG1002`).
+
+## CA1815 needs no pragma
+
+A union declaration gets no value equality from the compiler, so it raises `CA1815` unless it is silenced by hand.
+`[GenerateResult]` unions do not need that: the package ships a diagnostic suppressor that answers `CA1815` for
+every union opted in with the attribute, because a result union is read by matching its case type rather than
+compared by value.
+
+- Only the union is covered. A union without `[GenerateResult]`, the union's case types and every other value
+ type keep the warning, and a case declared as a plain `struct` should still be a `record struct`.
+- The suppression is logged as an `Info` diagnostic under the suppression id `RSG2000`, so a build audit can see
+ exactly what was suppressed.
+- `RSG2000` is a suppression id, not a rule: it never appears in the diagnostics table above, and
+ `$(NoWarn);RSG2000` brings `CA1815` back.
+
+## Requirements and switches
+
+- **.NET 11 SDK or later** with `LangVersion=preview` — union declarations are a preview language feature.
+- A reference to `Purview.Results`, which provides both result shapes (`Result` and
+ `Result`) and this generator.
+- `-p:DisableResultsSourceGenerator=true` (or a `Directory.Build.props` setting) disables the helpers while
+ the opt-in attribute is still emitted, which is useful when the generated code has to be inspected in
+ isolation.
+
+## Checklist
+
+1. Cases are small records with meaningful payloads.
+2. The union is a `union` declaration annotated with `[GenerateResult]`.
+3. Every method that fails for an expected reason returns `Result`, or `Result` when the
+ success carries no value.
+4. Failures are produced with `new Case(...).AsFailure()` (or `AsFailure()` for a unit result, the
+ union-receiver `Union.Failure(case)` / `Union.Failure(case)` factory, or the cast form).
+5. The build is clean of `RSG1000`–`RSG1008`.
+6. The union is mapped to responses once, in the host (see `purview-results-http-mapping`).
diff --git a/.agents/skills/purview-results-union-errors/references/migrating-error-returns.md b/.agents/skills/purview-results-union-errors/references/migrating-error-returns.md
new file mode 100644
index 00000000..b0405f44
--- /dev/null
+++ b/.agents/skills/purview-results-union-errors/references/migrating-error-returns.md
@@ -0,0 +1,67 @@
+# Migrating ad-hoc failure signalling to an error union
+
+A playbook for replacing thrown domain exceptions, `bool`/`out` pairs, sentinel return values and
+error-code enums with a C# 15 `union` of case types returned as `Result`.
+
+## Before you start, collect
+
+- The file(s) being migrated, and the operation family they belong to — a union is per family, not
+ per method, so methods can come and go without changing the error contract.
+- A name for the union (for example `TenantError`).
+- The failure modes to model as cases, or the decision to infer them from the current code.
+- Whether genuinely exceptional exits stay throwing. They normally should: a lost connection or a
+ violated invariant is not a domain outcome.
+
+## Requirements
+
+1. Declare one `readonly record struct` per failure mode, carrying the payload a caller needs to
+ react, and declare the union once:
+
+ ```csharp
+ [GenerateResult]
+ public readonly union TenantError(TenantNotFound, TenantDisabled, TenantAlreadyExists);
+ ```
+
+2. Change the affected signatures to `Result` — or the value-less
+ `Result` when the member has nothing to return on success — and produce failures with
+ `TenantError.Failure(case)` / `TenantError.Failure(case)`, or the per-case
+ `new Case(...).AsFailure()` / `AsFailure()` helpers.
+3. Leave genuinely exceptional exits throwing.
+4. Do **not** attempt implicit conversions from a case to a result, and do not add operators,
+ extension conversions or wrapper types: `CS0715`, `CS0556`, `CS9282`, `CS0246` and `CS0029` each
+ block that route. Use the generated factory or helper, or `(TenantError)new TenantNotFound(id)`
+ when a cast reads better. Prefer the union-receiver factory when a leaf case type is shared with
+ another union (`RSG1006`), because it names the union.
+5. Remove the replaced mechanism — thrown domain exceptions, error enums, `out` error parameters,
+ sentinel values — rather than leaving both paths in place.
+6. Keep the union free of transport concerns: no `IResult`, no status codes, no HTTP types.
+7. One case type per meaning. A case carrying a `string Reason` or an `int Code` invites string or
+ int matching and defeats the point.
+8. Compose unions rather than repeating leaf cases. A case type that is itself a union is an
+ *included union*: the including union's factory also covers its cases and builds the nested value,
+ and sharing a union-typed case across unions is not reported. This is how to avoid `RSG1006`,
+ which applies only to a shared **leaf** case.
+
+## Migration strategy
+
+- Inventory the failure modes and the call sites of each affected member.
+- Introduce the cases and the union before changing signatures, so each edit compiles in isolation.
+- Update call sites to `Match` / `Map` / `Bind` where a value has to come out of the result, rather
+ than `if (IsSuccess)`.
+- Update or add tests: one per case, asserting the case the caller receives.
+- Map the union once in the host — see the `purview-results-http-mapping` skill — instead of deciding
+ status codes in the domain.
+
+## Verification
+
+- Build the solution and confirm no `RSG1000`–`RSG1008` diagnostics.
+- Run the affected tests.
+- Confirm no remaining `throw` for an outcome the caller is expected to handle.
+- Confirm the union appears in exactly one mapper, not scattered through handlers.
+- Confirm no method can fall off the end of its body: `default` is a bug, not a failure.
+- Reflect public API changes in the package documentation.
+
+## Report
+
+When the migration is done, state: the files changed, the union and its cases, the failure modes that
+stayed exceptional and why, and the verification performed.
diff --git a/.agents/skills/purview-results-zodsharp-problems/SKILL.md b/.agents/skills/purview-results-zodsharp-problems/SKILL.md
new file mode 100644
index 00000000..ed0dd935
--- /dev/null
+++ b/.agents/skills/purview-results-zodsharp-problems/SKILL.md
@@ -0,0 +1,101 @@
+---
+name: purview-results-zodsharp-problems
+description: "Use when a Purview.Results failure that carries ZodSharp validation errors has to render as an ASP.NET Core HttpValidationProblemDetails — registering AddResultsZodSharpHttp, calling ToValidationProblem, or making a result-carried rejection and a thrown ZodException produce identical responses."
+---
+
+# Rendering validation-carrying failures as validation problems
+
+Use this skill when a result failure carries ZodSharp `ValidationError` values (it implements
+`IValidationErrorCarrier`) and the host has to respond with `application/problem+json`.
+
+## Registration
+
+```csharp
+builder.Services.AddZodSharpProblemDetails(); // the ZodSharp package's own problem options/exception handler
+builder.Services.AddResultsHttp(); // the result-to-response mapping
+builder.Services.AddResultsZodSharpHttp(); // the bridge: validation-carrying failures -> validation problem
+```
+
+- `AddResultsZodSharpHttp()` registers the ZodSharp problem options (a no-op when the host already did) and adds
+ a **failure mapper** (`ZodResultsFailureMapper`) to the fallback stage.
+- Because it is a failure mapper, **a mapping the host registered for a specific error case always wins**, a
+ mapping registered for the error type wins too, and a host failure mapper registered *before*
+ `AddResultsZodSharpHttp` wins as well. That is the escape hatch: when a case deserves its own response, register
+ it — and when a validation **code**, **category** or **origin** deserves one, use the rules below.
+- Pair it with `AddZodSharpProblemDetails()` so a thrown `ZodException` and a result-carried rejection are
+ rendered by the same mapper and therefore produce identical responses.
+
+## Rules per validation error code, category and origin
+
+Pass a callback to answer particular codes, categories or origins with a response of their own:
+
+```csharp
+builder.Services.AddResultsZodSharpHttp(options => options
+ .MapCode("tenant_not_found", StatusCodes.Status404NotFound) // validation problem, 404 default
+ .MapCode("tenant_id_matches_name", (errors, context) => TypedResults.Conflict())
+ .MapCategory("invalid_value", StatusCodes.Status422UnprocessableEntity)
+ .MapOrigin("value_object", StatusCodes.Status422UnprocessableEntity) // every type-level rule failure
+);
+```
+
+The three axes are the identity a `ValidationError` carries: **code** (the specific rule), **category** (a broad
+grouping many codes share) and **origin** (the structured origin a rule owns — `"value_object"` for a type-level
+rule, `"array"` for a collection rule). Reach for `MapOrigin` when the answer is keyed by the *kind* of rule
+rather than one code.
+
+Matching and precedence:
+
+1. every matching **code** rule in registration order,
+2. then every matching **category** rule in registration order,
+3. then every matching **origin** rule in registration order,
+4. then the default validation problem — so rules only ever narrow what the host already gets.
+
+- A rule matches when **any** of the failure's errors carries its code/category/origin, so a registered rule is
+ always reachable; a factory that wants stricter semantics returns `null` to decline and matching continues.
+- A factory receives the failure's **whole error set**, so a rule never hides the other problems the caller has
+ to fix; the `int statusCode` overloads still render every error.
+- A code, category or origin registered twice with different behaviour throws at configuration time.
+
+## Rendering by hand
+
+| Member | Purpose |
+| --- | --- |
+| `IValidationErrorCarrier.ToValidationProblem(context, statusCode = 400)` | Renders the errors the error value carries |
+| `ImmutableArray.ToValidationProblem(context, statusCode = 400)` | Renders a set of errors |
+| `ZodValidationProblems.ToProblem(errors, options, defaultStatusCode = 400, traceId = null)` | The underlying mapper, for hosts that resolve the options themselves |
+
+```csharp
+if (result.Error is IValidationErrorCarrier carrier)
+ return carrier.ToValidationProblem(context);
+```
+
+The response is written as `application/problem+json` through `TypedResults.Json`, so it does not depend on the
+MVC problem-details writer.
+
+## Status code and trace identifier
+
+- The status code resolved by `ZodProblemDetailsOptions.StatusCodeSelector` wins.
+- `statusCode` (or `defaultStatusCode`) is only used when the resolved error type does not define one — the
+ default is `400 Bad Request`.
+- The request trace identifier is included when `ResultsHttpOptions.IncludeTraceId` is `true` (the default).
+
+## Pitfalls
+
+- **Do not reimplement error-to-problem mapping.** Reuse `ZodValidationProblems.ToProblem` so a carried failure
+ and a thrown `ZodException` cannot drift apart in status code, title, `errors` shape or `issues` extension.
+- **Do not map the whole union to a validation problem** unless every case is a validation failure; map the
+ carrying case (or rely on the mapper, which already does exactly that).
+- If a case does deserve its own response, still build it from `ToValidationProblem(context)` when the payload
+ is validation data, so clients see one shape.
+- The mapper receives the *case* value, so the carrier is the union case that implements the interface — not
+ the union itself (`ResultsFailureContext.Error` carries the union when a rule needs it).
+
+## Verifying the pairing
+
+A test that exercises both paths is the cheapest guard against drift:
+
+1. return a failure carrying validation errors through an endpoint, and
+2. throw the same errors as a `ZodException` through the host's exception handler,
+
+then assert the two response bodies are equal. See the `purview-results-http-mapping` skill for the surrounding
+registration and status-code guidance.
diff --git a/.agents/skills/purview-results-zodsharp-validation/SKILL.md b/.agents/skills/purview-results-zodsharp-validation/SKILL.md
new file mode 100644
index 00000000..83bc66c6
--- /dev/null
+++ b/.agents/skills/purview-results-zodsharp-validation/SKILL.md
@@ -0,0 +1,121 @@
+---
+name: purview-results-zodsharp-validation
+description: "Use when ZodSharp validation has to feed Purview.Results — converting ValidationResult with ToResult or the value-discarding ToUnitResult, carrying ValidationError values on a union case, implementing IValidationErrorCarrier, or deciding what a rejected input becomes in the result pipeline."
+---
+
+# Folding ZodSharp validation into results
+
+Use this skill when a codebase validates with the `Purview.ZodSharp` package and returns
+`Purview.Results` values, and a rejected input has to become an ordinary failure rather than an exception.
+
+## The conversion
+
+```csharp
+using Purview.Results;
+using Purview.Results.ZodSharp;
+
+return RepositoryReconciliationResultSchema
+ .Validate(reconciliationResult)
+ .ToResult(errors =>
+ new ReconciliationResultInvalid(reconciliationResult, errors) // a union case
+ );
+```
+
+`ToResult(onFailure)`:
+
+- returns a **success carrying the validated value** when validation passed;
+- returns a **failure carrying the created error** when it failed;
+- invokes `onFailure` only for a failure, so a successful validation allocates no error;
+- takes the error type explicitly, and it must be named when it is a union, because a union case does not carry
+ the union type that contains it.
+
+ZodSharp validation never throws: `Validate` returns the value on success and every `ValidationError` on
+failure. Keep it that way — map the outcome, do not re-throw it.
+
+## When the validated value is not the method's success type
+
+`ToResult` can only produce a result whose success type is the validated type. When the surrounding method
+succeeds with something else (a repository result, an aggregate, a summary), produce the failure with the
+generated helper instead:
+
+```csharp
+var validated = ProviderConnectionIdSchema.Validate(providerConnectionId);
+
+if (!validated.IsSuccess)
+ return new ProviderConnectionInvalid(providerConnectionId, validated.Errors)
+ .AsFailure();
+
+return await ReconcileCoreAsync(validated.Value, repositories, cancellationToken);
+```
+
+This keeps the failure case carrying the errors while the success type stays whatever the method actually
+produces.
+
+## When the method has no success value
+
+When the method reports only why an input was rejected, `ToUnitResult` discards the validated value and returns a
+value-less `Result`. It still names the validated value type, because a union case does not carry its
+union:
+
+```csharp
+Result Validate(TenantInput input) =>
+ TenantInputSchema
+ .Validate(input)
+ .ToUnitResult(errors => new TenantInputInvalid(input, errors));
+```
+
+Use `ToResult` when the success carries the validated value, `ToUnitResult` when it carries nothing, and the
+generated `AsFailure()` when the success carries something else.
+
+## Async validation
+
+`ValidateAsync` returns a `ValueTask>`, and the async counterparts fold it in the same way:
+
+```csharp
+async Task> Validate(TenantInput input, CancellationToken cancellationToken) =>
+ await TenantInputSchemaValidator
+ .ValidateAsync(input, cancellationToken)
+ .ToUnitResultAsync(errors => new TenantInputInvalid(input, errors));
+```
+
+- `ToResultAsync` carries the validated value on success; `ToUnitResultAsync` discards it.
+- The error type is named explicitly for the same reason as the synchronous forms.
+- Do not block on `ValidateAsync` to reuse the synchronous methods — that reintroduces the sync-over-async the
+ bridge exists to avoid.
+
+## Carrying the errors
+
+```csharp
+public readonly record struct ProviderConnectionInvalid(
+ ProviderConnectionId ProviderConnectionId,
+ ImmutableArray ValidationErrors
+) : IValidationErrorCarrier;
+```
+
+Implement `IValidationErrorCarrier` on the case (or error) that carries ZodSharp `ValidationError` values.
+`ValidationErrors` preserves each error's code, origin, category, path and parameters, so an HTTP layer can render
+a validation problem **without knowing the error type** — which is exactly how
+`Purview.Results.ZodSharp.AspNetCore` maps it (see the `purview-results-zodsharp-problems` skill).
+
+Guidance:
+
+- **Keep the errors on the case**, never flatten them into a message string; the structured form is what clients
+ and problem responses need.
+- **One carrier per rejection**, holding the whole `ImmutableArray` for that input.
+- Implementing the interface (rather than a helper that extracts errors) lets the HTTP mapping stay generic.
+
+## Why there is no factory that returns a result
+
+`ToResult` takes `Func, TError>` on purpose. A lambda that returns
+`Result` would bind to that parameter — C# prefers `Func<…, TError>` — and silently nest the
+results. Naming the error type explicitly keeps the intent unambiguous.
+
+## Checklist
+
+1. Validation outcomes are mapped, never thrown.
+2. The error type is named explicitly (`ToResult(…)` or `ToUnitResult(…)`, and
+ the async counterparts for a `ValidateAsync` outcome).
+3. The case that carries the errors implements `IValidationErrorCarrier`.
+4. A method whose success type differs uses `AsFailure()`, or `AsFailure()` for a unit result, with the
+ validation errors.
+5. The host maps the carrier to a validation problem once (see `purview-results-zodsharp-problems`).
diff --git a/.agents/skills/purview-sourcegenerator-codewriter/SKILL.md b/.agents/skills/purview-sourcegenerator-codewriter/SKILL.md
new file mode 100644
index 00000000..ee363c97
--- /dev/null
+++ b/.agents/skills/purview-sourcegenerator-codewriter/SKILL.md
@@ -0,0 +1,334 @@
+---
+name: purview-sourcegenerator-codewriter
+description: >-
+ Use when implementing, reviewing or refactoring C# source generators and analysers built on
+ Purview.SourceGeneratorFramework. Covers CodeWriter and XmlCommentWriter emission, scope safety,
+ incremental pipeline design, value equality, deterministic output, and migrating a legacy
+ string/StringBuilder emitter to CodeWriter.
+metadata:
+ product: Purview.SourceGeneratorFramework
+ repository: purview-dev/sourcegenerator-framework
+---
+
+# Source generator CodeWriter modernization
+
+Use this skill for any work involving C# source generators, analysers, or generated output in `Purview.SourceGeneratorFramework`. It combines CodeWriter/XmlCommentWriter emission guidance with the incremental-source-generator and analyser best practices that ship with the framework.
+
+Refactoring an existing emitter off `string`/`StringBuilder`? The step-by-step playbook is in
+[references/legacy-emitter-migration.md](references/legacy-emitter-migration.md).
+
+## Required implementation pattern
+
+When creating source output, favor this shape:
+
+1. Build immutable, value-equatable pipeline values first.
+2. Register source output.
+3. Inside the callback: `var writer = generationContext.CreateCodeWriter();`
+4. Write header/usings/namespace.
+5. Write structured types and members using declaration options records.
+6. Add source once per output artifact.
+
+### CodeWriter lifetime: created in the output callback, never in pipeline state
+
+The line between "fine" and "forbidden" is the **incremental-cache boundary**, not the act of
+creating a writer or handing it to a helper.
+
+**Fine — output-scoped use inside a `RegisterSourceOutput` callback.** Create the writer inside the
+callback and pass it to any emitter/helper methods called from that same callback. It may be held in
+local variables, passed as a parameter, or wrapped in a short-lived output context:
+
+```csharp
+context.RegisterSourceOutput(
+ targets.CombineWithContext(contextProvider),
+ static (spc, pair) =>
+ {
+ var (model, generationContext) = pair;
+ var writer = generationContext.CreateCodeWriter();
+ EmitHeader(writer, model);
+ EmitType(writer, model);
+ spc.AddSource($"{model.Name}.g.cs", writer.ToString());
+ }
+);
+```
+
+**Forbidden — persisting the writer across the incremental-cache boundary.** Do not create it earlier
+in the pipeline and pass it down, and do not store it anywhere Roslyn caches or another callback can
+observe it:
+
+- Do not create a `CodeWriter` in a provider stage and carry it through the pipeline.
+- Do not store a `CodeWriter` as a property or field on `GenerationContext` or a custom context.
+- Do not return a `CodeWriter` (or an object holding one) from an incremental provider.
+- Do not cache or reuse a writer for a later callback or a different output.
+
+A cached writer can retain previously written source, mix output from concurrently running
+callbacks, and defeat scope tracking. A writer created in the callback and used only within that
+callback is safe and expected.
+
+## Source generator & analyser best practices
+
+Apply the following rules to every generator, analyser, and refactor.
+
+### 1. Core principles
+
+- **Analyser for validation; generator for generation.**
+- **Syntax for syntax, symbols for declarations, operations for executable semantics.**
+- **Use `ForAttributeWithMetadataName` for attribute-driven generators.**
+- **Remove Roslyn objects from the incremental pipeline as early as possible.**
+- **Every value crossing a pipeline boundary must have meaningful value equality.**
+- **Prefer many small incremental stages over one large transform.**
+- **Keep broad inputs such as `Compilation` away from downstream generation.**
+- **Generate deterministic output.**
+- **Compile against the oldest Roslyn API version containing the functionality you need.**
+- **Test caching, not just generated text.**
+
+The guiding principle for an incremental generator is:
+
+> Extract semantic information once, convert it into a small value model, and make everything downstream operate only on that value model.
+
+### 2. Analyser vs source generator
+
+Use a `DiagnosticAnalyser` when the question is:
+
+> Is the source code valid according to this library's rules?
+
+Use an `IIncrementalGenerator` when the question is:
+
+> Given valid source code, what source should be generated?
+
+| Requirement | Prefer |
+| --- | --- |
+| Require a class to be `partial` | Analyser |
+| Require an attribute on a declaration | Analyser |
+| Validate a method signature | Analyser |
+| Reject unsupported property types | Analyser |
+| Detect invalid attribute arguments | Analyser |
+| Detect unsupported API usage | Analyser |
+| Offer an automatic fix | Analyser + `CodeFixProvider` |
+| Generate members for a marked class | Incremental generator |
+| Generate serializers/validators/mappers | Incremental generator |
+| Generate a registry from discovered types | Incremental generator |
+| Read a schema file and generate C# | Incremental generator |
+| Internal generation failure | Generator diagnostic |
+
+### 3. Choosing an analyser action
+
+Use the narrowest API that represents the concept being analysed:
+
+- `RegisterSyntaxNodeAction` — exact source syntax (e.g., modifier presence).
+- `RegisterSymbolAction` — declaration semantics (e.g., attributes, interfaces, accessibility).
+- `RegisterOperationAction` — executable behaviour (e.g., invocation, assignment, object creation).
+- `RegisterOperationBlockStart/EndAction` — stateful method analysis.
+- `RegisterSymbolStart/EndAction` — type-wide analysis across members.
+- `RegisterCompilationStartAction` — resolve known framework symbols once.
+- `RegisterAdditionalFileAction` — analyse `AdditionalFiles`.
+- Avoid `RegisterSyntaxTreeAction`, `RegisterSemanticModelAction`, and compilation-end actions unless genuinely necessary.
+
+### 4. Syntax vs symbol vs operation
+
+Decision tree:
+
+1. Does exact source spelling/structure matter? → **Syntax**
+2. Otherwise, is it a declaration? → **Symbol**
+3. Otherwise, is it executable behaviour? → **Operation**
+
+Use `SymbolEqualityComparer.Default.Equals(...)` when comparing symbols.
+
+### 5. Analyser best practices
+
+- Enable concurrent execution with `context.EnableConcurrentExecution()`.
+- Explicitly configure generated-code analysis with `context.ConfigureGeneratedCodeAnalysis(...)`.
+- Resolve known framework/library symbols once in a `RegisterCompilationStartAction`.
+- Prefer narrow registrations over scanning entire syntax trees or compilations.
+- Treat diagnostic IDs as public contracts and maintain release tracking files when publishing public diagnostics.
+
+### 6. Incremental generator golden rules
+
+Implement `IIncrementalGenerator`. Simply implementing it is not enough; the pipeline must be incremental.
+
+> **Pipeline values must be immutable and value-equatable.**
+
+Never keep these in persistent pipeline models:
+
+| Type | Verdict |
+| --- | --- |
+| `ISymbol` / `INamedTypeSymbol` / `IMethodSymbol` / `IPropertySymbol` | Never retain |
+| `Compilation` | Do not propagate |
+| `SemanticModel` | Do not propagate |
+| `IOperation` | Do not propagate |
+| `SyntaxTree` | Do not propagate |
+| `SyntaxNode` | Remove ASAP |
+| `Location` | Remove ASAP |
+| `AdditionalText` | Project immediately |
+| `T[]` / `List` | Avoid |
+| `ImmutableArray` | Wrap with sequence equality |
+
+Use immutable records and `EquatableArray` (sequence equality) for collection members.
+
+### 7. Designing the pipeline
+
+Pipeline shape:
+
+```text
+Roslyn Input
+ ↓
+Cheap discovery
+ ↓
+Semantic extraction
+ ↓
+Small equatable model
+ ↓
+Validation/transformation
+ ↓
+Generation model
+ ↓
+Source output
+```
+
+Guidelines:
+
+- Project the semantic transform as the boundary where Roslyn objects disappear.
+- Prefer `static` callbacks to avoid capturing generator state.
+- Honour cancellation tokens.
+- Split transformations into many small stages.
+- Keep syntax predicates cheap.
+- Avoid indirect discovery (every interface implementation, every subclass, entire-compilation scans).
+
+### 8. Syntax discovery
+
+- Prefer `context.SyntaxProvider.ForAttributeWithMetadataName(...)` for attribute-driven generators.
+- Use `context.SyntaxProvider.CreateSyntaxProvider(...)` only when syntax itself is the trigger and there is no marker attribute.
+- The predicate must be cheap; do not walk the tree or do semantic work in it.
+
+### 9. `Collect`, `Combine`, and invalidation
+
+- `Collect()` turns per-item outputs into one aggregate. Changing any item invalidates the aggregate.
+- Use `Collect()` only for genuinely global output: registries, lookups, duplicate detection, aggregate switches.
+- Prefer per-item `RegisterSourceOutput`.
+- `Combine()` is correct when the output depends on two providers.
+- Avoid `models.Combine(context.CompilationProvider)` — project the compilation to a tiny capability fact first.
+- Use `.WithComparer(...)` only when logical equality differs from the default.
+
+### 10. Diagnostics
+
+- Prefer a separate `DiagnosticAnalyser` for normal user validation.
+- Use generator diagnostics only for malformed additional files, generator-only configuration, conflicting output, or failures that cannot be expressed by an analyser.
+- Report diagnostics on the most useful user-authored `Location`.
+- Do not keep `Location` in long-lived pipeline models.
+
+### 11. Output generation
+
+- Output must be deterministic: no timestamps, random GUIDs, process IDs, machine paths, culture-dependent output, or unordered dictionary output.
+- Hint names must be deterministic, unique, and stable.
+- Prefer text generation or `CodeWriter` over building Roslyn syntax trees just to stringify them.
+- Use `RegisterPostInitializationOutput` for constant source such as marker attributes.
+- Add generated source once per output artifact.
+
+### 12. Testing incrementally
+
+- Snapshot-testing generated source is not enough.
+- Test first execution, cached second execution, unrelated changes remaining cached, per-target invalidation, deletion, renaming, global options, additional files, and global registry invalidation.
+- Use `GeneratorDriverOptions` with `trackIncrementalGeneratorSteps: true` and inspect reasons: `New`, `Modified`, `Unchanged`, `Cached`, `Removed`.
+
+### 13. Roslyn version compatibility and packaging
+
+- The `Microsoft.CodeAnalysis.*` version used to compile the analyser/generator sets the minimum compiler-host requirement.
+- The consumer's `TargetFramework` does not determine analyser compatibility.
+- Choose the oldest Roslyn version that contains the APIs you need.
+- Common baselines: Roslyn 4.8 for VS 17.8 / .NET 8, 4.12 for VS 17.12 / .NET 9, 5.0 for VS 2026 18.0 / .NET 10.
+- Ship one `netstandard2.0` analyser/generator binary unless you have a deliberate multi-version strategy.
+- Do not mistake multi-targeting for automatic analyser asset selection.
+- Use `PrivateAssets="all"` for Roslyn development dependencies.
+- Enable `EnforceExtendedAnalyzerRules` and investigate `RSxxxx` diagnostics before suppressing them.
+
+### 14. Recommended project configuration
+
+A generator project should normally include:
+
+```xml
+
+ netstandard2.0
+ latest
+ enable
+ true
+ false
+ true
+ true
+
+
+
+
+
+
+
+
+
+
+```
+
+## Preferred API map for CodeWriter
+
+### File and namespace
+
+- `AutoGeneratedHeader(...)`
+- `Using(...)`
+- `FileScopedNamespace(...)` or `BlockNamespace(...)`
+- `OpenPragmasScope(...)` for warning suppression scopes
+
+### Types and members
+
+- Types: `Class`, `Struct`, `RecordClass`, `RecordStruct`, `Interface`, `Enum`, `Delegate`
+- Members: `Method`, `MethodScope`, `Property`, `Field`, `Constructor`
+- Attributes: `AttributeDeclarationOptions`, `AttributeArgumentOptions`
+- Type syntax: `TypeReference` (nullable/generic/array/pointer-safe composition)
+
+### XML documentation
+
+Use `XmlCommentWriter` extension methods on `CodeWriter`:
+
+- `XmlSummary(...)`, `XmlParam(...)`, `XmlTypeParam(...)`, `XmlReturn(...)`, `XmlRemarks(...)`, `XmlExample(...)`
+- `XmlCode(...)` / `XmlCodeBlock(...)`
+- `XmlList(...)`, `XmlSeeAlso(...)`, `XmlException(...)`
+
+Static helpers: `CodeWriter.XmlInlineCode(...)`, `CodeWriter.XmlSee(...)`, `CodeWriter.XmlParamRef(...)`, `CodeWriter.XmlText(...)`.
+
+## Refactoring guide: string/StringBuilder -> CodeWriter
+
+Apply this checklist in order:
+
+1. **Move emission boundaries** — replace giant string assembly with phases: header, namespace, type, members.
+2. **Replace manual braces/indentation** — use `using` scopes (`ClassScope`, `MethodScope`, `OpenBlockScope`, `IndentedScope`).
+3. **Replace handwritten signatures** — use declaration option records.
+4. **Replace raw XML lines** — use XML extension methods (`XmlSummary`, `XmlParam`, etc.).
+5. **Normalize type strings** — use `TypeReference`.
+6. **Preserve semantics and ordering** — generated members and diagnostics must remain equivalent.
+7. **Validate scope safety** — keep or enable `PurviewSourceGeneratorFrameworkValidateCodeWriterScopes` for tests/dev.
+
+## Anti-patterns to remove during refactors
+
+- `StringBuilder.AppendLine("public class ...")` for declarations that can be structured.
+- Manually writing `{` / `}` around methods and types where scope APIs exist.
+- Hard-coded nullable type suffixes and generic syntax in arbitrary strings when `TypeReference` is available.
+- Raw XML tag string composition when XML extension methods can enforce consistency.
+- Creating a `CodeWriter` before the output callback and passing it through the pipeline.
+- Storing a `CodeWriter` on `GenerationContext`, a custom context, or any incremental pipeline model.
+- Sharing one `CodeWriter` across multiple generated outputs or callbacks.
+- Keeping Roslyn objects, `CodeWriter`, or mutable state in incremental pipeline models.
+
+## Review checklist for pull requests
+
+- Generated declarations use structured APIs for types and members.
+- XML docs use XML extension methods rather than raw `///` fragments.
+- `CodeWriter` is created inside each output callback and never persists in pipeline state; passing it
+ to helper methods within that callback is expected.
+- Header and generated attributes are deterministic and consistent.
+- Existing diagnostics, generated member names, and public behavior are preserved.
+- Roslyn objects are removed from pipeline models; `EquatableArray` is used for collections.
+- Per-target output is preferred over collected global output unless global knowledge is required.
+- `CompilationProvider` is not casually combined into output.
+- Deterministic hint names and source text are used.
+- Incremental caching behavior is tested, not just generated text.
+
+## See also
+
+- `agents/source-generator-framework-writer.agent.md` — specialist agent for `Purview.SourceGeneratorFramework` emitter authoring.
+- `prompts/refactor-source-generator-to-codewriter.prompt.md` — prompt template for legacy-emitter refactor tasks.
diff --git a/.agents/skills/purview-sourcegenerator-codewriter/references/legacy-emitter-migration.md b/.agents/skills/purview-sourcegenerator-codewriter/references/legacy-emitter-migration.md
new file mode 100644
index 00000000..54efd09f
--- /dev/null
+++ b/.agents/skills/purview-sourcegenerator-codewriter/references/legacy-emitter-migration.md
@@ -0,0 +1,58 @@
+# Migrating a legacy emitter to CodeWriter
+
+A playbook for moving a source generator's emission from manual `string` / `StringBuilder`
+construction to `CodeWriter` plus the `XmlCommentWriter` documentation extensions, with behaviour
+parity.
+
+## Before you start, collect
+
+- The emitter file(s) being changed.
+- The generator type name, and the version string it stamps into generated attributes or headers.
+- Whether the output must stay **byte-identical**. If it must, every whitespace decision below is a
+ constraint rather than a preference, and the diff of the generated snapshots is the acceptance
+ test.
+
+## Requirements
+
+1. Use the structured declaration APIs rather than hand-written declaration text:
+ `Class` / `Struct` / `RecordClass` / `Interface` / `Enum`, and `Method`, `Property`, `Field`,
+ `Constructor`.
+2. Use the XML helper extensions instead of composing `///` lines: `XmlSummary`, `XmlParam`,
+ `XmlReturn`, `XmlRemarks`, `XmlCode` / `XmlCodeBlock`.
+3. Use `TypeReference` once the type text gets complex — nullability, generics, arrays.
+4. Keep the writer **output-scoped**: `generationContext.CreateCodeWriter()` *inside* the output
+ callback. Never create it earlier in the pipeline, and never store it in incremental provider
+ state or in a custom context.
+5. Preserve behaviour, diagnostics and generated names.
+6. Keep the change minimal. Do not reformat logic the migration does not touch.
+
+## Strategy
+
+Work phase by phase, because each phase has a different mechanical replacement:
+
+| Emitter phase | Replace with |
+| --- | --- |
+| header | the header helper, not a literal banner string |
+| namespace | the namespace scope API |
+| type declarations | declaration option records, not signature strings |
+| member declarations | `Method` / `Property` / `Field` / `Constructor` |
+| indentation and braces | scoped APIs — never manual `{`/`}` and `\t` |
+| `///` comment composition | `XmlSummary`, `XmlParam`, `XmlReturn`, `XmlRemarks`, `XmlCode` |
+
+Call out any intentional semantic delta explicitly; a migration that quietly changes emitted names or
+diagnostics is the failure mode this playbook exists to avoid.
+
+## Verification
+
+- Run the impacted tests.
+- Confirm the generated files still compile.
+- Confirm there are **no scope leaks**: `OpenScopeCount == 0` when the writer is materialized. Enable
+ CodeWriter scope validation in the test run.
+- Where byte-identical output was required, diff the generated snapshots.
+
+## Report
+
+1. Files changed.
+2. Why each change was necessary.
+3. Risks and behaviour differences, if any.
+4. The verification that actually ran.
diff --git a/.agents/skills/purview-sourcegenerator-diagnostics/SKILL.md b/.agents/skills/purview-sourcegenerator-diagnostics/SKILL.md
new file mode 100644
index 00000000..21d9522c
--- /dev/null
+++ b/.agents/skills/purview-sourcegenerator-diagnostics/SKILL.md
@@ -0,0 +1,142 @@
+---
+name: purview-sourcegenerator-diagnostics
+description: >-
+ Use when a Purview.SourceGeneratorFramework build reports a PSGFR, PSGF, PRSGD or TLB diagnostic,
+ when choosing which code fix applies, or when a source generator, diagnostic analyzer or code fix
+ provider is silently not running at all.
+metadata:
+ product: Purview.SourceGeneratorFramework
+ repository: purview-dev/sourcegenerator-framework
+---
+
+# Purview.SourceGeneratorFramework diagnostics
+
+`Purview.SourceGeneratorFramework` ships `Purview.SourceGeneratorFramework.Analyzers` and
+`Purview.SourceGeneratorFramework.CodeFixers` as analyzer assets inside the package, under
+`analyzers/dotnet/cs/`. They are enabled automatically in any project that references the framework —
+there is no separate package to add.
+
+Two compiler-analyzer families, plus a set of MSBuild-time diagnostics:
+
+- **Incremental generator best practice** — `PSGFR11`–`PSGFR33`: pipeline design, `CodeWriter` usage,
+ Roslyn component discovery, extension-class conventions.
+- **C# 14 extension-member conventions** — `PSGFR34`–`PSGFR38`, with
+ `ReorganizeExtensionClassCodeFixProvider` and `ConvertToExtensionBlockCodeFixProvider`.
+- **Merge and packaging** — `PSGFR39`–`PSGFR43`, where `PSGFR43` is the merge tool's blocked
+ public-surface code.
+
+## Start here when nothing runs
+
+A compiler host loads a generator, analyzer or code fix provider only when **three** conditions hold.
+Missing any one means the component is **silently ignored** — no error, no output, a green build:
+
+1. **The type is public** (`PSGFR27`).
+2. **The type is decorated** — `[Generator]` (`PSGFR26`), `[DiagnosticAnalyzer]` (`PSGFR25`), or
+ `[ExportCodeFixProvider]` (`PSGFR24`).
+3. **The assembly is loaded as an analyzer** — packed under `analyzers/dotnet/cs/` in a package, or
+ referenced with `OutputItemType="Analyzer"` on a `ProjectReference`.
+
+A code fix provider additionally appears only when a diagnostic ID in its `FixableDiagnosticIds` is
+actually produced by an analyzer loaded alongside it (`PSGFR28`). Visual Studio MEF-composes fix
+providers when the analyzer set loads, so after adding or updating a fixer assembly you must restart
+Visual Studio or reload the project before the fixes show up.
+
+## Build-time validation diagnostics
+
+These are MSBuild diagnostics, not compiler analyzers, so they are **not** tracked in
+`AnalyzerReleases.*.md`:
+
+| Code | Raised by | Summary |
+| --- | --- | --- |
+| `PSGF0001` | `Purview.BuildSdk` | A Roslyn component did not produce (or declare) a source-generator analyzer file. |
+| `PSGF0003` | `Purview.SourceGeneratorFramework` | A `PurviewGeneratorVisibleProperty` is not compiler-visible in the declaring project or its `Sdk/build`/`Sdk/buildTransitive` assets, so consumers cannot read `build_property.`. |
+| `PRSGD0005` | `Purview.BuildSdk` | A file in the returned analyzer closure references an assembly that is neither in the closure nor a compiler-host assembly. |
+| `PSGFR41` | merge tool | A component's public surface exposes framework types the merge internalizes. Reported by the analyzer at design time, and by the merge pass as `message` (default), `warning` or `error`. |
+| `PSGFR43` | merge tool | The merged analyzer still exposes a public framework type, so it is not self-contained. Always an error; the merge fails with exit code 5. |
+
+Opt out with `PurviewSourceGeneratorFrameworkAnalyzerValidation=false` (`PRSGD0005`) or
+`PurviewSourceGeneratorFrameworkGeneratorPropertyValidation=false` (`PSGF0003`).
+
+## Incremental pipeline rules
+
+| Rule | Summary |
+| --- | --- |
+| `PSGFR11` | Prefer `SyntaxProvider.ForAttributeWithMetadataName` over `CreateSyntaxProvider` for attribute-based detection. |
+| `PSGFR12` | Use `IIncrementalGenerator` / `RegisterSourceOutput` instead of `ISourceGenerator`. |
+| `PSGFR14` | Avoid `RegisterImplementationSourceOutput` unless implementation-only output is required. |
+| `PSGFR15` | Pipeline model collection members should use sequence equality (`EquatableArray`). |
+| `PSGFR30` | Prefer `static` lambdas in pipeline methods, so the compiler never allocates a closure on the per-item hot path. |
+| `PSGFR31` | Prefer `GeneratorAttributeSyntaxContext.TargetSymbol` over `SemanticModel.GetDeclaredSymbol(ctx.TargetNode)`. |
+| `PSGFR33` | Pipeline models must not retain Roslyn objects (`ISymbol`, `SyntaxNode`, `Location`, …); extract the information into value types. |
+
+## CodeWriter rules
+
+| Rule | Summary |
+| --- | --- |
+| `PSGFR16` | Prefer the nullable-context `Nullable()`/`MakeNullable()` overload, so annotations honour the target compilation. |
+| `PSGFR17` | Consume scope-returning methods (`…Scope`, `IndentedScope`) with `using`. |
+| `PSGFR18` | Prefer structured declaration APIs (`Class`, `Method`, `Property`, `Field`) over raw declaration text. |
+| `PSGFR19` | Prefer structured statement APIs (`Return`, `MethodCall`, `Throw`, `Assignment`, `Using`, `Comment`) over raw statement text. |
+| `PSGFR20` | Prefer the minimal `CodeWriter` overloads over hand-constructing `*DeclarationOptions` values. |
+| `PSGFR21` | Prefer `HashDefines`/`HashDefinesScope` for `#if`/`#endif`. |
+| `PSGFR22` | Prefer `PragmaDisable`/`OpenPragmasScope` for `#pragma warning`. |
+| `PSGFR23` | Prefer structured `IfBlock`/`ElseIf`/`Else` over raw `if` block text. |
+| `PSGFR29` | Do not embed a `CodeWriter` in a string; use `XmlCommentWriter.XmlInlineCode`. |
+| `PSGFR32` | Avoid `NormalizeWhitespace` when generating source; use an indented text writer such as `CodeWriter`. |
+
+## Component, extension and merge rules
+
+| Rule | Summary |
+| --- | --- |
+| `PSGFR24` | `CodeFixProvider` is not marked `[ExportCodeFixProvider]`; Visual Studio will never discover it. |
+| `PSGFR25` | `DiagnosticAnalyzer` is not marked `[DiagnosticAnalyzer]`; it will never run. |
+| `PSGFR26` | A generator type is not marked `[Generator]`; it will never run. |
+| `PSGFR27` | A Roslyn component type is not public; the compiler host cannot instantiate it. |
+| `PSGFR28` | `FixableDiagnosticIds` names a diagnostic no analyzer in the compilation produces; the fix will never be shown. |
+| `PSGFR34` | Prefer C# 14 `extension(Receiver)` blocks over classic static `this`-parameter extension methods. |
+| `PSGFR35` | Extension class name must match the extended type (`{Receiver}Extensions`). |
+| `PSGFR36` | Extension classes belong in the extended type's namespace, under an `Extensions` folder. |
+| `PSGFR37` | One extension class per receiver type; split a class that extends several. |
+| `PSGFR38` | Extension classes should carry `[EditorBrowsable(EditorBrowsableState.Never)]`. |
+| `PSGFR39` | A non-packable Roslyn component opted out of the default self-contained analyzer output (`PurviewMergeSourceGeneratorFrameworkForAnalyzerFiles=false`) while embedding the framework; otherwise the package embeds the loose framework DLL under `analyzers/`. |
+| `PSGFR40` | In a Roslyn component (`IsRoslynComponent=true`), reference SGF types as inline code (`Type`) rather than a `cref`: copied documentation must not depend on cref resolution. |
+| `PSGFR41` | A public member (or generic constraint) whose signature references an SGF type in a component whose framework implementation is merged. The merge internalizes every SGF type, so the signature ends up referring to an internal type. Make the member, or its declaring type, non-public. |
+| `PSGFR42` | A disposable Testing-harness result (`DriverRunResult`) is produced and never disposed, leaking the collectible `AssemblyLoadContext` and `MetadataLoadContext` of a compiled run. `warning` when the run syntactically compiles to an assembly (a `Compile` options member, or `CompileToAssembly = true`), otherwise `info`. Awaiting an assertion, or calling a helper handed the result — an extension on it, or a method taking it as a parameter — is not a production: both hand the same instance back, so only a task-like await or a genuine producer is reported. |
+
+## Type-library and attribute-model diagnostics
+
+The bundled generators carry their own families: `TypeLibraryValidationAnalyzer`
+(`TLB0001`–`TLB0019`, plus `TLB0021`) and the attribute-data-model validation analyzers. They are
+documented on their own wiki pages, `Type-Library.md` and `Attribute-Data-Models.md`.
+
+## Code fixes
+
+Most rules above have a fix in `Purview.SourceGeneratorFramework.CodeFixers`:
+
+| Fix provider | Rule |
+| --- | --- |
+| `AddGeneratorAttributeCodeFixProvider` | `PSGFR26` |
+| `AddDiagnosticAnalyzerAttributeCodeFixProvider` | `PSGFR25` |
+| `AddExportCodeFixProviderAttributeCodeFixProvider` | `PSGFR24` |
+| `MakeRoslynComponentPublicCodeFixProvider` | `PSGFR27` |
+| `RemoveOrphanedFixableDiagnosticIdCodeFixProvider` | `PSGFR28` |
+| `PreferTargetSymbolCodeFixProvider` | `PSGFR31` |
+| `PreferStaticLambdaCodeFixProvider` | `PSGFR30` |
+| `PreferNullableContextOverloadCodeFixProvider` (project-wide Fix All) | `PSGFR16` |
+| `PipelineModelReferenceEqualityCollectionCodeFixProvider` | `PSGFR15` |
+| `PreferStructuredCodeWriterIfBlockCodeFixProvider` | `PSGFR23` |
+| `CodeWriterToStringCodeFixProvider` | `PSGFR29` |
+| `PreferInlineCodeForFrameworkCrefCodeFixProvider` | `PSGFR40` |
+| `MakeComponentSurfaceNonPublicCodeFixProvider` | `PSGFR41` |
+| `DisposeTestResultCodeFixProvider` | `PSGFR42` |
+| `ReorganizeExtensionClassCodeFixProvider` (renames, splits, moves, updates referencing files) | `PSGFR35`, `PSGFR36`, `PSGFR37` |
+| `ConvertToExtensionBlockCodeFixProvider` | `PSGFR34` |
+| `AddExtensionClassMetadataCodeFixProvider` | `PSGFR38` |
+| `MakeTypeLibrarySpecNonPublicCodeFixProvider` | `TLB0021` |
+| `AttributeDataModelSymbolPropertyCodeFixProvider` | attribute-data-model symbol properties |
+| `TypeLibraryMemberAccessibilityCodeFixProvider`, `TypeLibraryMarkerDefaultInitializerCodeFixProvider`, `MakeTypeLibrarySpecPartialCodeFixProvider`, `RenameTypeLibrarySpecCodeFixProvider`, `TypeLibraryMemberTypeCodeFixProvider` | type-library rules |
+
+## Related skills
+
+`purview-sourcegenerator-codewriter` for the emission patterns the `CodeWriter` rules push you
+towards, and `purview-sourcegenerator-testing` for proving a pipeline actually caches.
diff --git a/.agents/skills/purview-sourcegenerator-packaging/SKILL.md b/.agents/skills/purview-sourcegenerator-packaging/SKILL.md
new file mode 100644
index 00000000..92350db8
--- /dev/null
+++ b/.agents/skills/purview-sourcegenerator-packaging/SKILL.md
@@ -0,0 +1,245 @@
+---
+name: purview-sourcegenerator-packaging
+description: >-
+ Use when packaging or referencing a source generator built on Purview.SourceGeneratorFramework -
+ the self-contained merged analyzer, GetSourceGeneratorAnalyzerFiles, embedding a generator in
+ another package, PurviewGeneratorVisibleProperty, analyzer-closure validation, Roslyn version
+ compatibility, and errors such as CS0433, CS8784 or MSB3073 from a loaded analyzer.
+metadata:
+ product: Purview.SourceGeneratorFramework
+ repository: purview-dev/sourcegenerator-framework
+---
+
+# Packaging a source generator
+
+The rule everything else follows from: **a shipped Roslyn component carries its own copy of the
+framework and references no loose `Purview.SourceGeneratorFramework.dll`.** Two generators built
+against different framework versions must be able to load into one compiler host. A shared DLL under
+`analyzers/` cannot give you that — whichever version loads first wins, and the other fails with
+`MissingMethodException` or `CS0433`.
+
+The framework delivers this by IL-merging and internalizing its implementation into each component's
+**intermediate** output, leaving the component's `bin` unmerged.
+
+## Referencing the framework from a component
+
+```xml
+
+ true
+
+
+
+
+
+```
+
+And from a consuming project, as an analyzer:
+
+```xml
+
+```
+
+`Purview.BuildSdk` invokes `GetSourceGeneratorAnalyzerFiles` automatically — naming
+`Targets="GetSourceGeneratorAnalyzerFiles"` explicitly still works but is not required.
+
+## The three consumption paths
+
+| Path | Trigger | What you get |
+| --- | --- | --- |
+| `GetSourceGeneratorAnalyzerFiles` (default) | a consuming project references the component as an analyzer | the **merged** component, from the content-addressed `purview-merged//`. `bin` stays unmerged, so an in-process test harness keeps shared framework type identity and `InternalsVisibleTo` access without `CS0433`. |
+| `GetSourceGeneratorAnalyzerFiles` with `PurviewMergeSourceGeneratorFrameworkForAnalyzerFiles=false` | opt-out | unmerged component **plus** the loose framework DLL from the package `lib/`. |
+| `GetPurviewMergedAnalyzerFile` | the framework's own bundled-component pack, or a third-party package embedding the generator | the merged component; `bin` is never overwritten. |
+| `GetPurviewMergedAnalyzerFileForPack` (pack-time, via `TargetsForTfmSpecificContentInPackage`) | packing a standalone packable generator | the merged DLL and PDB contributed straight to `analyzers/dotnet/cs`. `bin` is never mutated, so its shape does not depend on whether `build` or `pack` ran last. |
+
+Two properties exist and both should normally be left alone:
+
+- `PurviewEmbedSourceGeneratorFramework=false` — only for a project that *is* the framework
+ compile-time library. A published generator package must never disable embedding.
+- `PurviewMergeSourceGeneratorFrameworkForAnalyzerFiles=false` — only when the analyzer-files
+ consumer must keep the unmerged + loose-DLL shape (a generator shipped into one compiler process
+ alongside an incompatible framework version).
+
+`PSGFR39` errors when a **non-packable** component opts out while embedding the framework, because
+that shape, packed through the GASF path, forces the loose DLL back under `analyzers/`.
+
+## A component that references another component
+
+A code-fix or analyzer component can reference the generator component normally (`ProjectReference`,
+`ReferenceOutputAssembly` **not** `false`) when it needs the generator's internal diagnostic
+identity. Both are `IsRoslynComponent`; only the generator references the framework.
+
+- The referenced component is returned as **its own merged assembly** and is never IL-merged into the
+ dependent one — that would duplicate its types, including `InternalsVisibleTo`-visible internals,
+ inside a second analyzer in the same host.
+- The framework assembly is declared as copy-to-output content beside the generator's `bin`, and
+ content with `CopyToOutputDirectory` flows transitively through `ProjectReference`. That is what
+ lets Visual Studio load the dependent code-fix provider from its own `bin` without a
+ `FileNotFoundException` for the framework assembly.
+- Visual Studio's project system resolves an `OutputItemType=Analyzer` project reference to the
+ referenced project's **unmerged** `bin` assembly and adds it to the compiler's analyzers — the
+ command-line build does not. `Purview.BuildSdk` removes that item before adding the resolved
+ closure, so Roslyn only ever receives the merged artifact. Without that removal the unmerged copy
+ drags `Purview.SourceGeneratorFramework` into the compiler host
+ (`CS8784 FileNotFoundException: Could not load file or assembly 'Purview.SourceGeneratorFramework'`)
+ and every generator registers twice.
+
+## Analyzer-closure validation
+
+`Purview.BuildSdk` validates the whole closure `GetSourceGeneratorAnalyzerFiles` returns: every
+file's PE `AssemblyRef` must resolve to another file in the returned set, or to a compiler-host
+assembly (`Microsoft.CodeAnalysis*`, `System.Composition.*`, `System.*`, `netstandard`, …). A missing
+component artifact fails the build with `PRSGD0005`.
+
+Extend the permitted set with `` or the
+`PurviewAnalyzerClosurePermittedReferences` property. Opt out with
+`PurviewSourceGeneratorFrameworkAnalyzerValidation=false`.
+
+## Generator-read MSBuild properties
+
+A generator reading `build_property.` is only correct if `` is a
+`CompilerVisibleProperty` **wherever the generator runs** — including in a consumer's project.
+Declare what the component reads:
+
+```xml
+
+
+
+```
+
+`PSGF0003` fails the build when a declared property is neither a `CompilerVisibleProperty` in the
+project nor declared by the project's own `Sdk/build` or `Sdk/buildTransitive` assets — which is what
+consumers actually receive. Opt out with
+`PurviewSourceGeneratorFrameworkGeneratorPropertyValidation=false`.
+
+NuGet imports `buildTransitive` assets for **PackageReference** consumers only. Inside the package
+repository every project uses `ProjectReference`, so `Purview.BuildSdk`'s
+`ImportProjectReferencedBuildTransitiveAssets` registers the referenced project's
+`Sdk/buildTransitive/*.props|*.targets` `CompilerVisibleProperty` items for in-repo consumers. Opt
+out with `PurviewImportProjectReferenceBuildTransitive=false`.
+
+## Embedding a generator in another package
+
+Pack the **merged** assembly, so the outer package ships no loose framework DLL:
+
+```xml
+
+ false
+ $(TargetsForTfmSpecificContentInPackage);PackMyGenerator
+
+
+
+
+
+
+
+
+ analyzers/dotnet/cs/
+
+
+
+```
+
+If the generator is also embedded at compile time for the outer package's consumers, the outer
+package must make the framework's compiler-visible properties visible to them — build assets from
+`Purview.SourceGeneratorFramework` are **not** copied into the outer package. Ship a `.props` that
+declares the property and its `CompilerVisibleProperty` entry, packed under the outer package's own
+ID so NuGet imports it:
+
+```xml
+
+```
+
+## `IsExternalInit`
+
+The framework assembly defines `System.Runtime.CompilerServices.IsExternalInit` **publicly**, so the
+bundled generators can emit `init`-based attribute types into any consumer compilation and the merge
+has a single marker definition to internalize.
+
+**Do not declare your own.** A generator-local marker gives calls to the framework's `init` setters a
+different required-custom-modifier identity from the setter definitions. The merge tool normalizes
+those modifiers in a temporary copy for compatibility with legacy tooling, but removing the redundant
+marker is the preferred configuration.
+
+## Roslyn version compatibility
+
+> The version of `Microsoft.CodeAnalysis.*` you compile the component against sets a **minimum
+> compiler-host API requirement**. The consumer's `` has nothing to do with it —
+> analyzer code runs inside the compiler/IDE host.
+
+| Roslyn package | Minimum Visual Studio | Language / .NET generation |
+| ---: | --- | --- |
+| 4.8 | VS 2022 17.8 | C# 12 / .NET 8 |
+| 4.12 | VS 2022 17.12 | C# 13 / .NET 9 |
+| 5.0 | VS 2026 18.0 | C# 14 / .NET 10 |
+
+**This framework is built against Roslyn 5.0**, so a host loading it must be Roslyn 5.0 or later
+(.NET 10 SDK / Visual Studio 2026 18.0). The testing packages multi-target `net8.0`–`net10.0`, and
+Roslyn 5.x ships `net8.0`/`net9.0` assets, so those test targets still load the runner.
+
+## A generator project to start from
+
+```xml
+
+
+ netstandard2.0
+ latest
+ enable
+ true
+ false
+ true
+ true
+
+
+
+
+
+
+
+
+
+
+
+
+```
+
+`Purview.BuildSdk` already defaults most of this for a project it classifies as a Roslyn component,
+so in an SDK repository the project file is usually far shorter. The exact Roslyn baseline is a
+product-support decision.
+
+## Release gates
+
+Acceptance criteria for self-contained packaging — check metadata, never "the sample compiled":
+
+1. **No framework reference, no public framework types.** Every `analyzers/dotnet/cs/*.dll` has no
+ assembly reference to `Purview.SourceGeneratorFramework` and exposes no public type in a
+ framework-owned namespace (including the generated `Generators` attribute set and the
+ framework-emitted `Microsoft.CodeAnalysis.EmbeddedAttribute`). The one exception is the
+ component's own Roslyn entry points, which must stay public — Roslyn only instantiates public
+ components (`PSGFR27`).
+2. **No loose framework DLL in any package**, and no `*.pdb` in the `.nupkg` — symbols ship only
+ through the `.snupkg`.
+3. **Merged entry points survive**: each merged DLL still exposes its `IIncrementalGenerator`,
+ `DiagnosticAnalyzer` or `CodeFixProvider`.
+4. **Installed-package consumer test**: a generator project referencing the framework by
+ `PackageReference` packs one self-contained DLL under `analyzers/dotnet/cs`, and a consumer that
+ installs it builds with the generator producing output.
+5. **Two-version coexistence test**: build Generator A against the current framework and Generator B
+ against an intentionally binary-incompatible version, install both into one consumer, and build
+ with both package-reference orders. Both must run against their own embedded copy.
+
+## Going deeper
+
+The merge pass, the content-addressed artifact, framework type internalization and the properties
+that tune it are in [references/merge-internals.md](references/merge-internals.md) — read it when a
+merge fails, when a type leaks, or when you hit `MSB3073` / `CS0433` / `CS8784` from a loaded
+analyzer.
diff --git a/.agents/skills/purview-sourcegenerator-packaging/references/merge-internals.md b/.agents/skills/purview-sourcegenerator-packaging/references/merge-internals.md
new file mode 100644
index 00000000..5d8b6c9e
--- /dev/null
+++ b/.agents/skills/purview-sourcegenerator-packaging/references/merge-internals.md
@@ -0,0 +1,139 @@
+# The merge pass and the self-contained analyzer
+
+## Where the merged artifact lives
+
+`_PurviewMergeSourceGeneratorFramework` only ever writes to the component's **intermediate** output.
+`GetSourceGeneratorAnalyzerFiles` returns that result by substituting the merged path into
+`TargetPathWithTargetPlatformMoniker` immediately before its body runs, leaving `GetTargetPath` —
+which resolves assembly references — pointing at the unmerged `bin`. That split is what keeps the
+in-repo test harness working while shipped assemblies stay self-contained.
+
+The artifact is **content-addressed**:
+
+```text
+$(IntermediateOutputPath)purview-merged//$(TargetFileName)
+```
+
+`` is a SHA-256 over the component, the framework assembly and the merge tool (the tool
+computes it in its `--tag` mode). The tag is in the **directory**, never the file name, because
+ILRepack derives the merged assembly's simple name from the output file name and an analyzer must
+keep `.dll`.
+
+Two properties follow, and both matter:
+
+- A rebuild with identical inputs reuses the existing file and **skips the merge**, so
+ `_PurviewMergeSourceGeneratorFramework` is idempotent across the per-consumer — and potentially
+ parallel — invocations of `GetSourceGeneratorAnalyzerFiles`.
+- Changed inputs select a **new directory**, so the merge never overwrites an assembly a compiler
+ host (csc, `VBCSCompiler`, Visual Studio) already has loaded. Overwriting such a file fails on
+ Windows with a sharing violation, which surfaced as `MSB3073` (merge tool exit code
+ `-532462766`) and left consumers loading a stale or partially written analyzer — the root cause of
+ `CS8784 FileNotFoundException: Could not load file or assembly 'Purview.SourceGeneratorFramework'`.
+
+The tool merges into a per-process `.staging-` directory and publishes it with a
+non-overwriting directory rename. A concurrent invocation that loses the race simply observes the
+published artifact rather than failing.
+
+Packaging needs the stable `.dll` name, so the pack paths
+(`GetPurviewMergedAnalyzerFile`, `GetPurviewMergedAnalyzerFileForPack`) copy the content-addressed
+artifact into `$(IntermediateOutputPath)purview-pack/` and pack that plainly named staging copy.
+
+## Framework type internalization
+
+ILRepack's `Internalize` is best-effort, and two gaps matter:
+
+- a framework type that reaches the merged component's public API surface stays public; and
+- the types the framework's own generators emit **into** the component — the
+ `Purview.SourceGeneratorFramework.Generators` attribute set, generated type libraries, marker
+ attributes — are not part of the merged framework assembly at all, so ILRepack never sees them.
+
+Either gap leaks framework types out of what must be a self-contained analyzer, and any project
+loading that analyzer alongside the real framework assembly fails with `CS0433` ambiguity for every
+leaked type.
+
+So the merge tool runs a deterministic internalization pass (`FrameworkTypeInternalizer`) after
+ILRepack finishes:
+
+- Every type in a framework-owned namespace (`Purview.SourceGeneratorFramework` and its children,
+ including the generated `Generators` attribute set) becomes non-public. Ownership is evaluated
+ through the **declaring chain**, because Mono.Cecil reports an empty namespace for a nested type:
+ the framework's nested containers — generated type-library namespace classes, nested operator/enum
+ groups, `CodeWriter` scopes — are only reachable through their declaring type.
+- Types the framework's generators emitted into the component, recognized by the tool name on their
+ `System.CodeDom.Compiler.GeneratedCodeAttribute` (`TypeLibraryGenerator`,
+ `AttributeDataModelGenerator`), become non-public too, so a generated type library can never leak a
+ `TypeIdentity`/`TypeReference` member as public API.
+- `Microsoft.CodeAnalysis.EmbeddedAttribute`, the framework-emitted marker, becomes non-public.
+- **Roslyn component entry points are never internalized.** A generator, analyzer, code fix provider
+ or refactoring provider reachable from the framework namespace stays public, because Roslyn only
+ instantiates public components (`PSGFR27`). This is what keeps the framework's own bundled
+ analyzers working after the pass.
+- The pass reports the result. Leftover public framework types fail the merge with **exit code 5**
+ (`PSGFR43`). Public component members whose signature exposes a framework type are logged
+ (`PSGFR41`) so the author can make them, or their declaring type, non-public. Visibility is
+ followed through the declaring chain here too: a public nested type inside an internal type — for
+ example the compiler-synthesised `$`/`$` extension containers emitted for an extension class
+ — is not reachable from outside the component, so it is not part of the public surface and is not
+ reported.
+
+Ownership is seeded with the framework assembly's own type identities, so a framework type living
+*outside* the framework namespace (`Microsoft.CodeAnalysis.*Extensions`, `System.StringExtensions`)
+is internalized as well. The artifact's assembly-level `InternalsVisibleTo` /
+`IgnoresAccessChecksTo` grants are removed, because a shipped analyzer is not the component's own
+assembly.
+
+## Tuning the pass
+
+| Property | Default | Effect |
+| --- | --- | --- |
+| `PurviewMergeOwnedNamespaces` | empty | Extra namespace prefixes (semicolon-separated) treated as framework-owned. |
+| `PurviewMergeOwnedTypeFullNames` | empty | Extra type full names (semicolon-separated) treated as framework-owned. |
+| `PurviewMergePublicSurfaceSeverity` | `message` | How a finding is reported: `message` (plain log text), `warning`/`error` (MSBuild diagnostics with code `PSGFR41`), or `none`. |
+| `PurviewMergePublicSurfaceValidation` | `true` | `false` sets the severity to `none`. |
+| `PurviewMergePublicSurfaceOrigin` | the merged component assembly | The origin reported with an MSBuild finding; point it at a source or project path for IDE navigation. |
+
+All five participate in the content tag, so changing one re-runs the merge — and re-emits its
+findings — rather than reusing a cached artifact. The compiler analyzer with the same id (`PSGFR41`)
+reports the same condition while you edit, so the surface is usually fixed before the merge runs.
+
+## Generated accessibility: bin versus merged artifact
+
+The component's own generated types — the type library, the attribute data models — keep their
+generated accessibility in the component's **bin output**. `TLB0015` requires a hand-written partial
+to be `public static partial` so it can merge with the generated library, and in-repo consumers such
+as code fixers and sibling assemblies compile against it.
+
+Only the **merged analyzer artifact** internalizes them. Self-containment is therefore enforced at
+the merge boundary without rewriting the accessibility an in-repo consumer compiles against, and that
+split is safe precisely because a merged artifact is never referenced as a compile-time dependency.
+
+> A merged component is an analyzer artifact. Never reference it as a compile-time dependency. Tests
+> that need to run a *packaged* generator load it out of band.
+
+## How the framework package itself is assembled
+
+`Purview.SourceGeneratorFramework` is dual-role: the framework assembly ships in `lib/` so generator
+projects compile against it, and `analyzers/` carries self-contained generator, analyzer and
+code-fixer assemblies. The bundled projects are:
+
+- `SourceGeneratorFramework.Generators` — `AttributeDataModelGenerator`, `TypeLibraryGenerator`;
+- `SourceGeneratorFramework.Analyzers` — the `PSGFR*` and `TLB*` analyzers;
+- `SourceGeneratorFramework.CodeFixers` — the code fix providers.
+
+Each has the framework implementation merged and internalized into it. The package deliberately does
+**not** put `Purview.SourceGeneratorFramework.dll` under `analyzers/dotnet/cs`, so generators built
+against different framework versions never ask Roslyn to load competing versions of a same-named
+dependency.
+
+The shared models and helpers that once shipped as a separate
+`Purview.SourceGeneratorFramework.Shared.dll` are compiled directly into the framework assembly
+(`SourceGeneratorShared.Link.targets` links the sources). Consumers get one
+`Purview.SourceGeneratorFramework.dll`, which removes the version-skew hazard a separately bundled
+Shared assembly caused — generator packages loading a different Shared version in-process failed with
+binary-incompatibility errors, such as removed `PurviewTypeLibrary` fields.
+
+Those projects are `IsRoslynComponent = true` and are **not** packable on their own. The
+`SourceGeneratorFramework` project builds them via `GetPurviewMergedAnalyzerFile` and packs them
+under `analyzers/dotnet/cs/` in `BuildAndPackBundledAnalyzerAssemblies`. They were previously
+consumed as analyzer project references, but they now reference the framework assembly for the shared
+types, which would form a project-reference cycle.
diff --git a/.agents/skills/purview-sourcegenerator-pipeline/SKILL.md b/.agents/skills/purview-sourcegenerator-pipeline/SKILL.md
new file mode 100644
index 00000000..373942fd
--- /dev/null
+++ b/.agents/skills/purview-sourcegenerator-pipeline/SKILL.md
@@ -0,0 +1,231 @@
+---
+name: purview-sourcegenerator-pipeline
+description: >-
+ Use when composing an incremental pipeline with Purview.SourceGeneratorFramework -
+ IncrementalPipeline helpers, GenerationContext and custom contexts, CreateCodeWriter lifetime,
+ GeneratorResult and blocking versus non-blocking diagnostics, disabling a generator from MSBuild,
+ scope validation, test logging, and stage tracking names.
+metadata:
+ product: Purview.SourceGeneratorFramework
+ repository: purview-dev/sourcegenerator-framework
+---
+
+# Incremental pipeline composition
+
+`IncrementalPipeline` composes `IncrementalValueProvider` and `IncrementalValuesProvider`:
+attribute-based discovery, generation-context creation, disable-property checks, and thin
+source-output registration.
+
+Everything here follows from one rule: **pipeline values must be immutable and value-equatable.**
+Roslyn caches the complete value a provider publishes, and offers no way to exclude one property of
+it from caching.
+
+## `GenerationContext`
+
+A base execution-services context carrying the Roslyn `Compilation`, immutable `GenerationSettings`,
+an optional `ISourceGenLogger`, and a factory for independently owned `CodeWriter` instances.
+
+```csharp
+var contextProvider = IncrementalPipeline.DefaultGenerationContextValueProvider(context);
+```
+
+### Custom contexts
+
+A custom context does not need to accept or read build properties itself:
+
+```csharp
+public sealed class MyGenerationContext : GenerationContext
+{
+ public MyGenerationContext(Compilation compilation, GenerationSettings settings, ISourceGenLogger? logger)
+ : base(compilation, settings, logger)
+ {
+ }
+}
+
+var contextProvider = IncrementalPipeline.GenerationContextValueProvider(
+ context,
+ nameof(MyGenerator),
+ "1.0.0",
+ factory: static (compilation, settings, logger, cancellationToken) =>
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ return new MyGenerationContext(compilation, settings, logger);
+ },
+ disablePropertyName: "MyGenerator_Disable"
+);
+```
+
+The provider resolves scope validation, generator disabling and test logging from analyzer-config
+properties *before* invoking the factory. The logger is created internally only when logging is
+enabled and a sink is registered for that run.
+
+## `CodeWriter` lifetime — the rule that bites
+
+Treat `GenerationContext` as **cached incremental state** and each `CodeWriter` as **mutable,
+output-scoped execution state**. Create the writer inside the registered source-output callback,
+after the incremental cache boundary:
+
+```csharp
+IncrementalPipeline.RegisterSourceOutput(
+ context,
+ targets,
+ contextProvider,
+ static (spc, target, generationContext) =>
+ {
+ var writer = generationContext.CreateCodeWriter();
+ EmitTarget(generationContext, writer, target);
+ spc.AddSource($"{target.Name}.g.cs", writer.ToString());
+ }
+);
+```
+
+Creating it in the callback and passing it to emitter helpers called from that same callback is the
+intended pattern. The only forbidden thing is **persisting the writer in pipeline state**.
+
+Why, concretely:
+
+- Roslyn caches the whole published value; you cannot exempt a field.
+- `CodeWriter` is mutable, so a cached one retains previously written source when the context is
+ reused for another output or run.
+- Source-output callbacks may process independent targets **concurrently**; a shared writer mixes
+ their output and races.
+- A fresh writer gives each generated source independent scope tracking and deterministic ownership.
+
+`CreateCodeWriter()` returns a new, independently owned instance every call.
+
+**Never add a `CodeWriter` property or field to a class derived from `GenerationContext`.** A custom
+context is still produced by an incremental provider and cached as one complete value. Store only
+compilation-derived services and immutable configuration there.
+
+When an emitter needs both services and writing, pass the context and the writer separately, or
+compose a short-lived wrapper created inside the callback — which must never be returned from a
+provider:
+
+```csharp
+public sealed class GenerationOutputContext : ISourceGenLogger
+ where TContext : GenerationContext
+{
+ public GenerationOutputContext(TContext generation)
+ {
+ Generation = generation;
+ Writer = generation.CreateCodeWriter();
+ }
+
+ public TContext Generation { get; }
+
+ public CodeWriter Writer { get; }
+
+ public void Log(SourceGenLogLevel level, int indentation, string message, params object[] args) =>
+ Generation.Log(level, indentation, message, args);
+}
+```
+
+## `GeneratorResult` and diagnostics that do not stop generation
+
+`RegisterSourceOutput` combines targets with the generation context, reports diagnostics, and runs
+the callback only for successful results:
+
+```csharp
+var targets = IncrementalPipeline.ForAttributeWithMetadataName(
+ context,
+ AttributeType,
+ static (ctx, ct) =>
+ {
+ var symbol = ctx.TargetSymbol;
+
+ return symbol is null
+ ? GeneratorResult.Empty
+ : GeneratorResult.Create(symbol.Name);
+ }
+);
+```
+
+The callback runs only when `GeneratorResult.ShouldProcess` is `true` — the result carries a value
+**and** none of its diagnostics are blocking.
+
+`ReportableDiagnostic.IsBlocking` is an explicit per-diagnostic decision, **independent of
+severity**. An `Error`-severity diagnostic can still allow generation to continue, which is what you
+want when the generated code is what helps the developer fix the problem — a generator emitting an
+abstract base class can report an error per missing override while still emitting the base class, so
+the user can see exactly what to implement:
+
+```csharp
+static readonly DiagnosticDescriptor MissingOverride = new(
+ "MYGEN001",
+ "Missing override",
+ "Type '{0}' must override '{1}'",
+ "Usage",
+ DiagnosticSeverity.Error,
+ isEnabledByDefault: true
+);
+
+// IsBlocking is false, so ShouldProcess stays true and the base class is still emitted.
+var diagnostic = ReportableDiagnostic.Create(MissingOverride, isBlocking: false, symbol, symbol.Name, "Execute");
+
+return GeneratorResult.Create(model, diagnostic);
+```
+
+`isBlocking: true` stops generation for that target while still reporting.
+`HasBlockingDiagnostics` reports whether any carried diagnostic blocked;
+`HasErrorDiagnostics` reports the severity-based view.
+
+## Disabling a generator at build time
+
+Pass the compiler-visible disable property to the context provider; its resolved value lands in
+`GenerationSettings` automatically:
+
+```xml
+
+ true
+
+```
+
+```csharp
+var contextProvider = IncrementalPipeline.DefaultGenerationContextValueProvider(
+ context,
+ nameof(MyGenerator),
+ "1.0.0",
+ disablePropertyName: "MyGenerator_Disable"
+);
+
+// In the output stage:
+if (generationContext.Settings.IsSourceGeneratorDisabled)
+ return;
+```
+
+`IsDisabledValueProvider` is still there for when expensive upstream transforms must be filtered
+before being combined with the generation context.
+
+Declare the property with `PurviewGeneratorVisibleProperty` so it is compiler-visible wherever the
+generator runs — `PSGF0003` otherwise fails the build. See the `purview-sourcegenerator-packaging`
+skill.
+
+## Scope validation
+
+The default context provider reads
+`PurviewSourceGeneratorFrameworkValidateCodeWriterScopes` and threads it into
+`GenerationSettings.ValidateCodeWriterScopes`. When enabled, `ToString()` throws
+`CodeWriterScopeValidationException` if `OpenScopeCount` is not zero.
+
+## Test logging
+
+Framework logging is off in ordinary compiler runs. The testing integration enables it by registering
+an isolated sink and supplying a per-run session ID through analyzer config. Context providers create
+the internal logger automatically — generators implement no logging interface and no logging-support
+source is generated.
+
+The sink registry stores **callbacks only**; it never buffers entries. With logging disabled, a
+missing session ID, or no matching sink, the provider supplies no logger and log calls are discarded.
+Test sinks own whatever they capture and are removed when the run completes.
+
+## Tracking names
+
+The pipeline helpers assign a tracking name to every stage, so a cache test can assert which stages
+were recomputed. The `purview-sourcegenerator-testing` skill covers the stage matrix and the four
+scenarios a cache test should assert.
+
+## Related skills
+
+`purview-sourcegenerator-codewriter` for emission, `purview-sourcegenerator-diagnostics` for the
+`PSGFR` rules that enforce most of the above, and `purview-sourcegenerator-testing` for proving the
+pipeline caches.
diff --git a/.agents/skills/purview-sourcegenerator-testing/SKILL.md b/.agents/skills/purview-sourcegenerator-testing/SKILL.md
new file mode 100644
index 00000000..aaeff09e
--- /dev/null
+++ b/.agents/skills/purview-sourcegenerator-testing/SKILL.md
@@ -0,0 +1,404 @@
+---
+name: purview-sourcegenerator-testing
+description: >-
+ Use when writing or fixing tests for source generators, diagnostic analyzers, code fixes or
+ refactorings built on Purview.SourceGeneratorFramework - picking the right runner and base class,
+ configuring SourceGeneratorTestOptions, querying produced code with CodeQuery, and asserting
+ incremental pipeline caching stage by stage.
+metadata:
+ product: Purview.SourceGeneratorFramework
+ repository: purview-dev/sourcegenerator-framework
+---
+
+# Testing source generators, analyzers, code fixes and refactorings
+
+Use this skill whenever a task involves authoring, fixing, or modernising tests for Roslyn components
+(generators, diagnostic analyzers, code fix providers, refactoring providers) built with
+`Purview.SourceGeneratorFramework`. It covers the framework-agnostic test runner layer and the
+`CodeQuery` syntax-lookup API. For the TUnit base classes and assertion extensions, also load the
+`purview-sourcegenerator-tunit-tests` skill.
+
+Modernising an existing suite onto `CodeQuery` and adding a stage-by-stage cache test? The playbook
+is in [references/test-modernisation.md](references/test-modernisation.md).
+
+## Picking the right runner
+
+| Roslyn type | Runner |
+|---|---|
+| `IIncrementalGenerator` / `ISourceGenerator` | `SourceGeneratorTestRunner` |
+| `DiagnosticAnalyzer` | `DiagnosticAnalyzerTestRunner` |
+| `CodeFixProvider` | `CodeFixTestRunner` (single) |
+| — | `CodeFixTestRunner.RunFixAllAsync` (project-wide) |
+| `CodeRefactoringProvider` | `RefactoringTestRunner` |
+
+TUnit projects should prefer the matching base class instead (see `purview-sourcegenerator-tunit-tests`):
+`TUnitSourceGeneratorTestBase`, `TUnitDiagnosticAnalyzerTestBase`, `TUnitCodeFixTestBase`,
+`TUnitRefactoringTestBase`.
+
+## Result types
+
+- `DriverRunResult` (generator) — `DriverResult`, `AllSyntaxTrees`/`PrimarySyntaxTrees`,
+ `CompilationResult.Compilation`, `GetGeneratedTree`, `GetSource`, `GetTypeByMetadataName`, `LogEntries`.
+- `AnalyzerTestResult` — `Diagnostics`, `Compilation`.
+- `CodeFixTestResult` — `Diagnostics`, `CodeActions`, `FixedSource`, `Compilation`, `ChangedSolution`.
+- `CodeFixFixAllResult` — `Diagnostics`, `CodeActions`, `FixedSources`, `ChangedSolution`.
+- `RefactorTestResult` — `CodeActions`, `FixedSources`, `ChangedSolution`, `Compilation`.
+
+Use `DriverRunResultExtensions` (`AssertNoCompilationErrors`, `AssertNoGenerationExceptions`,
+`AssertSingleGeneratedSource`, `AssertGeneratedSourceContains`, …) for quick checks, but prefer
+`CodeQuery` for structural assertions.
+
+## Querying produced code with `CodeQuery`
+
+Every result exposes a `CodeQuery` via extensions in `CodeQueryResultExtensions`:
+
+```csharp
+result.Generated() // DriverRunResult: generated trees (default, generated-first)
+result.Output() // DriverRunResult: entire output compilation (user + generated)
+analyzerResult.Code() // AnalyzerTestResult: input compilation
+codeFixResult.Code() // CodeFixTestResult: input compilation
+codeFixResult.FixedCode() // CodeFixTestResult: parsed fixed source (or post-fix solution)
+fixAllResult.FixedCode() // CodeFixFixAllResult: post-fix documents
+refactorResult.FixedCode() // RefactorTestResult: post-refactor documents
+```
+
+Every `Get` has an accompanying `Has` (bool) and `TryGet` (out): `GetMethod`/`HasMethod`/`TryGetMethod`,
+`GetClass`, `GetStruct`, `GetInterface`, `GetEnum`, `GetDelegate`, `GetRecord`, `GetProperty`,
+`GetField`, `GetConstructor`, `GetNamespace`, `GetTypeDeclaration`, plus generic `Get`/`Has`
+and `GetSyntaxTree`/`HasSyntaxTree`. `Get` throws `SyntaxNotFoundException` when nothing matches.
+
+Type lookups accept an optional generic arity — `GetClass(name, arity)` / `HasClass(name, arity)` — and the
+`TypeReference`/`TypeIdentity` overloads match arity automatically from the identity, so
+`new TypeIdentity("ResourceDefinition", ns, arity: 1)` finds `ResourceDefinition` without matching the
+non-generic `ResourceDefinition`.
+
+Every `Get` returns a `CodeQueryResult` — the matched syntax node (`Node`) plus a query scoped to it
+(`Query`), with implicit conversions to both the node and the scoped query. Use `.Node` for direct syntax
+access, or chain member queries (the originating query is carried by the result, so it is not passed again).
+
+Types can be matched against `TypeReference`/`TypeIdentity`, resolved through the compilation's semantic
+model (nullable value types are significant, so `int?` never matches `int`):
+
+```csharp
+result.Generated().HasMethod("DoWork", TypeReference.Create(), TypeReference.Create().Nullable(), complexType);
+result.Generated().HasReturnType("Compute", TypeReference.Create());
+result.Generated().GetMethod("Format").HasParameters(TypeReference.Create(), objectReference);
+```
+
+When a test expects a nullable annotation, prefer the test-only `query.MakeNullable(type)` extension (on a
+`CodeQuery`, accepting a `TypeReference` or `TypeIdentity`). It resolves the annotation against the query's
+compilation and, unlike `TypeReference.Nullable()`/`TypeIdentity.MakeNullable()`, does not trigger the
+`PSGFR16` context-overload suggestion (tests have no generation context to pass).
+
+Member chaining from a type declaration (`MemberQueryExtensions`):
+
+```csharp
+var service = result.Generated().GetClass("ServiceCollectionExtensions"); // or GetClass(name, "Namespace")
+service.HasProperty("Count", intType);
+service.HasIndexer(stringType, intType);
+service.HasMethod("Add", intType, complexType);
+service.HasMethodReturnType("Add", stringType);
+service.HasConstructor(stringType);
+service.HasAttribute("SomeAttribute");
+```
+
+Node-inspection checks on scoped results:
+
+```csharp
+result.Generated().GetClass("Service").HasAccessibility(Accessibility.Public); // resolves C# defaults
+result.Generated().GetClass("Service").GetProperty("Name").HasSetterAccessibility(Accessibility.Private);
+result.Generated().GetClass("ResourceDefinition", 1).HasGenericTypeParameters("TResourceType");
+result.Generated().GetClass("ResourceDefinition", 1).HasBaseType(new TypeIdentity("ResourceDefinition", ns));
+result.Generated().GetClass("Service").HasNestedType("Builder"); // GetNestedType(...) to fetch
+result.Generated().GetClass("Service").IsInNamespace("Example.Models"); // IsInGlobalNamespace() for no namespace
+result.Generated().IsInNamespace(cls.Node, "Example.Models"); // or on the query directly
+```
+
+## Configuring options and a reusable starting point
+
+`SourceGeneratorTestOptions` is the base record. Common knobs:
+
+- `AdditionalNamespaces` / `IncludeDefaultNamespaces` — namespaces prepended to test source.
+- `AdditionalAssemblyTypes` / `AdditionalReferences` — assemblies referenced by the test compilation
+ (use `AdditionalAssemblyTypes = [typeof(SomeType)]` to pull in a whole assembly).
+- `AdditionalSources` — extra source files added to every run.
+- `AnalyzerConfigOptions` — `build_property.*` values; keys without the prefix are also exposed as MSBuild
+ properties.
+- `DisableSourceGeneratorPropertyName` / `DisableSourceGeneratorValue` — generator disable toggle.
+- `NullableContextOptions`, `OutputKind`, `LanguageVersion`, `CompileToAssembly`.
+- `ValidateCodeWriterScopes`, `EnableLogging`.
+- `ExcludeGeneratedSourceHintNames` — hides generated marker trees from `PrimarySyntaxTrees`.
+
+**Easy starting point recipe.** Derive an options record that seeds the namespaces and assemblies your
+generator needs, so every test gets a working compilation with no boilerplate:
+
+```csharp
+public sealed record MyGeneratorTestOptions : SourceGeneratorTestOptions
+{
+ public MyGeneratorTestOptions()
+ {
+ AdditionalNamespaces = AdditionalNamespaces.Add("My.Namespace");
+ AdditionalAssemblyTypes = AdditionalAssemblyTypes.AddRange(
+ typeof(SomeDependencyType),
+ typeof(TypeIdentity) // the framework's Shared assembly, when needed
+ );
+ DisableSourceGeneratorPropertyName = PropertyLibrary.DisableMyGenerator;
+ }
+}
+```
+
+`Compile()` returns a copy with `CompileToAssembly = true`, preserving the derived options type. Use the
+base class hooks `OnBeforeRun`/`OnBeforeRunAsync`/`OnAfterRun` to mutate sources/options per run (for
+example to append a marker attribute source via `WithAdditionalSources`).
+
+When `CompileToAssembly` is enabled, emission is fully in-memory. On .NET 8+ the assembly loads into a
+collectible `AssemblyLoadContext`, so the result is `IDisposable` — `using var result = ...` unloads it and
+keeps repeated runs from polluting the default context. `result.CompilationResult.Assembly` is the runnable
+assembly (generated code can execute); `result.CompilationResult.Metadata` / `.MetadataAssembly` give a
+metadata-only reflection view (types, members, attributes) over the emitted assembly without executing code.
+
+**Always write `using var result = ...`.** `PSGFR42` ("Dispose test harness results with a using
+declaration") flags a `DriverRunResult` that is produced and never disposed — including the indirect case
+where a helper creates a result, projects a value out of it and returns only the projection. It is a
+`warning` when the run syntactically compiles to an assembly (`.Compile()`, a `Compile` options member, or
+`CompileToAssembly = true`) and `info` otherwise; the `DisposeTestResultCodeFixProvider` fix inserts the
+`using`. A result that is returned to the caller, or disposed explicitly, is not flagged. Neither is awaiting
+an assertion, nor calling a helper that is handed the result — an extension on it, or a method taking it as a
+parameter: both hand the same instance back, so `await Assert.That(result).SomeAssertion()` and
+`result.AssertNoGenerationExceptions()` are not flagged.
+
+## Best practices
+
+- **Deterministic output**: `WriteAutoGeneratedHeader` is timestamp-free; assert with
+ `ContainsGeneratedCode`/`GeneratesCode` (whitespace-flattened) or `CodeQuery`, never with timestamps.
+- **Generator references**: to use a generated type in the test project AND pass the generator type to a
+ runner, reference the generator project twice — once `OutputItemType="Analyzer"` and once as a normal
+ reference.
+- **Multi-target**: build generators against the Roslyn version that supports the test matrix; the
+ framework is built against Roslyn 5.0 (net8.0/net9.0 assets keep a .NET 8–10 matrix loading); keep
+ `System.Collections.Immutable` version pinned to the shared one.
+- **Scope validation**: keep `PurviewSourceGeneratorFrameworkValidateCodeWriterScopes` enabled; it makes
+ undisposed `CodeWriter` scopes fail tests.
+- **Prefer `CodeQuery` over string matching** for structural assertions (members, signatures, namespaces).
+- **Dispose results**: `using var result = ...`, enforced by `PSGFR42`.
+- **Cap parallelism**: the harness shares one `MetadataReference` set per process, so memory is largely flat
+ in the degree of parallelism, but the platform's auto-detected default is both slower and heavier than an
+ explicit ceiling. Wall clock saturates around four concurrent tests; prefer
+ `--maximum-parallel-tests 8` (or a `TestingPlatformCommandLineArguments` equivalent) for a project that
+ multi-targets and runs several TFM executables at once.
+
+## Incremental cache testing (`RunIncrementalAsync`)
+
+To prove the pipeline caches correctly stage-by-stage, use `SourceGeneratorTestRunner.RunIncrementalAsync`
+(or `GenerateIncrementalAsync` on the TUnit base). It runs a sequence of source sets over a **single shared
+`GeneratorDriver`** and captures each run's `TrackedSteps`, keyed by tracking name. The canonical reference
+implementation is `IncrementalPipelineCacheTests` in `SourceGeneratorShared.UnitTests`; the end-to-end
+generator variant is `ServiceRegistrationCacheTests` in
+`SourceGeneratorFramework.ExampleGenerator.UnitTests`. Copy the pattern into your own test project — do
+not expect the source repo's files locally.
+
+### What is being asserted and why
+
+Roslyn reports one `IncrementalStepRunReason` per step output on each run:
+
+- `New` — the step ran for the first time.
+- `Modified` — the step ran and produced a different value than the previous run.
+- `Unchanged` — the step ran but produced the same value.
+- `Cached` — the step was skipped and its previous result reused from the incremental cache.
+
+A pipeline is "caching correctly" when an unchanged input keeps every stage `Cached`/`Unchanged`, and a
+targeted change marks **only** the stages whose inputs actually changed `Modified` while unrelated stages
+stay `Cached`. If a generator accidentally leaks `Compilation`, `SemanticModel`, `ISymbol`,
+`SyntaxNode`, or `Location` into a pipeline model, unrelated stages will report `Modified`/`New` on rerun —
+these tests fail the build and catch the regression.
+
+### The four scenarios every cache test should cover
+
+1. **First run → all `New`.** Nothing can be cached on the first run; this confirms every stage is tracked
+ under the expected name.
+2. **Identical rerun → all `Cached`/`Unchanged`.** `RunIncrementalAsync(sources, ...)` runs the same source
+ set twice for exactly this case. This is the strongest "it caches" proof.
+3. **Source-only change → only the source/attribute stage `Modified`.** Changing an attributed class must
+ mark `ForAttribute_*` (and downstream output) `Modified` while property/config stages stay `Cached`.
+4. **Property-only change → only the property/configuration stage `Modified`.** Toggling an MSBuild
+ property (via `IncrementalRunInput.AnalyzerConfig`) must mark `GetMSBuildPropertyValue_*` /
+ `GetGenerationConfiguration` / `GetGenerationContext_*` `Modified` while `ForAttribute_*` stays `Cached`.
+
+### How the runner makes this possible
+
+`RunIncrementalAsync` creates **one** driver, enables incremental step tracking, and **reuses the same
+`Compilation` instance for identical source sets** (keyed by prepared source text). Without that reuse,
+Roslyn would see a fresh compilation on the second run and report stages `Modified`/`New` even though the
+sources are byte-identical — the "cached" assertion would fail.
+
+### Log entries per run
+
+`IncrementalCacheRun.LogEntries` carries the framework log entries that run wrote, in order. The sink is
+registered for the whole sequence and drained between runs, so entries never accumulate. A rerun whose
+output step is cached logs nothing, which makes it a second signal alongside the step reasons:
+
+```csharp
+await Assert.That(result.Runs[0].LogEntries).IsNotEmpty();
+await Assert.That(result.Runs[1].LogEntries).IsEmpty();
+```
+
+`DriverRunResult.LogEntries` (the `RunAsync` path) is likewise in write order. Both are empty when
+`EnableLogging` is disabled.
+
+### The `StepReasons` helper
+
+`IncrementalCacheRun.Steps` is `ImmutableDictionary>`
+keyed by tracking name. Flatten each step's `Outputs` into the reasons list so assertions read cleanly:
+
+```csharp
+static ImmutableDictionary> StepReasons(IncrementalCacheRun run)
+{
+ var builder = ImmutableDictionary.CreateBuilder>();
+ foreach (var pair in run.Steps)
+ builder[pair.Key] = [.. pair.Value.SelectMany(step => step.Outputs.Select(static output => output.Reason))];
+ return builder.ToImmutable();
+}
+```
+
+### Framework pipeline stage names
+
+- `GetMSBuildPropertyValue_{Property}` — `IncrementalPipeline.PropertyValueProvider`.
+- `GetGenerationConfiguration` — `IncrementalPipeline.GenerationContextValueProvider`.
+- `GetGenerationContext_{Capabilities}` — e.g. `GetGenerationContext_EmptyCapabilities`.
+- `ForAttribute_{AttributeType}` — `IncrementalPipeline.ForAttributeWithMetadataName`.
+
+The framework reference (`IncrementalPipelineCacheTests`, framework-agnostic runner) shows all four
+scenarios against `TestGenerator`/`DiagnosticTestGenerator`:
+
+```csharp
+using System.Collections.Immutable;
+using Purview.SourceGeneratorFramework.TestGenerators;
+using StepReason = Microsoft.CodeAnalysis.IncrementalStepRunReason;
+
+public class IncrementalPipelineCacheTests
+{
+ const string AttributedSource = """
+ [TestAttribute]
+ public partial class MyClass { }
+ """;
+ const string ChangedAttributedSource = """
+ [TestAttribute]
+ public partial class AnotherClass { }
+ """;
+ const string TestAttributeSource = """
+ [System.AttributeUsage(System.AttributeTargets.Class)]
+ public sealed class TestAttribute : System.Attribute { }
+ """;
+
+ static SourceGeneratorTestOptions CreateOptions() =>
+ new SourceGeneratorTestOptions()
+ .WithAdditionalSources(TestAttributeSource)
+ .WithExcludeGeneratedSourceHintNames("TestAttribute");
+
+ static ImmutableDictionary> StepReasons(IncrementalCacheRun run) { /* as above */ }
+
+ [Test]
+ public async Task FirstRun_AllStagesAreNew(CancellationToken cancellationToken)
+ {
+ var result = await new SourceGeneratorTestRunner().RunIncrementalAsync(
+ [new IncrementalRunInput([AttributedSource])],
+ CreateOptions(),
+ cancellationToken);
+
+ var reasons = StepReasons(result.Runs[0]);
+ await Assert.That(reasons).IsNotEmpty();
+ await Assert.That(reasons.Values.SelectMany(r => r).All(r => r == StepReason.New)).IsTrue();
+ }
+
+ [Test]
+ public async Task IdenticalRerun_AllStagesCached(CancellationToken cancellationToken)
+ {
+ var result = await new SourceGeneratorTestRunner()
+ .RunIncrementalAsync([AttributedSource], CreateOptions(), cancellationToken);
+
+ var second = StepReasons(result.Runs[1]);
+ await Assert.That(second.Values.SelectMany(r => r).All(r => r is StepReason.Cached or StepReason.Unchanged)).IsTrue();
+ }
+
+ [Test]
+ public async Task SourceChange_MarksAttributeStageModified_PropertyStagesStayCached(CancellationToken cancellationToken)
+ {
+ var result = await new SourceGeneratorTestRunner().RunIncrementalAsync(
+ [new IncrementalRunInput([AttributedSource]), new IncrementalRunInput([ChangedAttributedSource])],
+ CreateOptions(),
+ cancellationToken);
+
+ var second = StepReasons(result.Runs[1]);
+ await Assert.That(second["ForAttribute_TestAttribute"]).Contains(StepReason.Modified);
+ await Assert.That(second["GetMSBuildPropertyValue_DisableTestGenerator"].All(r => r == StepReason.Cached)).IsTrue();
+ }
+
+ [Test]
+ public async Task PropertyChange_MarksPropertyStageModified_AttributeStageStaysCached(CancellationToken cancellationToken)
+ {
+ var result = await new SourceGeneratorTestRunner().RunIncrementalAsync(
+ [
+ new IncrementalRunInput([AttributedSource]),
+ new IncrementalRunInput([AttributedSource], [("build_property.DisableTestGenerator", "true")]),
+ ],
+ CreateOptions(),
+ cancellationToken);
+
+ var second = StepReasons(result.Runs[1]);
+ await Assert.That(second["GetMSBuildPropertyValue_DisableTestGenerator"]).Contains(StepReason.Modified);
+ await Assert.That(second["ForAttribute_TestAttribute"].All(r => r == StepReason.Cached)).IsTrue();
+ }
+}
+```
+
+### End-to-end generator variant (`GenerateIncrementalAsync`)
+
+TUnit tests derive from the base class and call `GenerateIncrementalAsync` (which wires the
+`OnBeforeRun`/`OnBeforeRunAsync` hooks and the derived options). `ServiceRegistrationCacheTests` in
+`SourceGeneratorFramework.ExampleGenerator.UnitTests` is the reference:
+
+```csharp
+public class ServiceRegistrationCacheTests
+ : TUnitSourceGeneratorTestBase
+{
+ const string Source = """
+ namespace Test;
+
+ [GenerateService]
+ public class MyService { }
+ """;
+
+ [Test]
+ public async Task IdenticalRerun_AllStagesCached(CancellationToken cancellationToken)
+ {
+ var result = await GenerateIncrementalAsync([Source], cancellationToken: cancellationToken);
+
+ var second = StepReasons(result.Runs[1]);
+ string[] frameworkStages =
+ [
+ "GetMSBuildPropertyValue_EmitServiceRegistrationInfo",
+ "GetGenerationConfiguration",
+ "GetGenerationContext_EmptyCapabilities",
+ "ForAttribute_GenerateServiceAttribute",
+ ];
+ await Assert.That(
+ frameworkStages.All(stage =>
+ second.TryGetValue(stage, out var reasons)
+ && reasons.All(r => r is StepReason.Cached or StepReason.Unchanged))).IsTrue();
+ }
+}
+```
+
+**Why the example filters to `frameworkStages`:** `ServiceRegistrationGenerator` emits its own
+`GenerateServiceAttribute` via post-initialization output, which is regenerated as a new `SyntaxTree` each
+run. That makes Roslyn's *internal* `ForAttributeWithMetadataName` `Compilation` step legitimately report
+`Modified` on an identical rerun. Asserting on the framework-named stages (which stay `Cached`/`Unchanged`)
+is the meaningful check. If your generator does not depend on its own post-init output, the stricter
+"every tracked step is `Cached`/`Unchanged`" assertion (as in the framework `IncrementalPipelineCacheTests`)
+is correct.
+
+Per-run MSBuild-property changes are supplied with `new IncrementalRunInput(sources, [("build_property.X", "value")])`.
+
+## License
+
+This project is licensed under the MIT license.
\ No newline at end of file
diff --git a/.agents/skills/purview-sourcegenerator-testing/references/test-modernisation.md b/.agents/skills/purview-sourcegenerator-testing/references/test-modernisation.md
new file mode 100644
index 00000000..6db47803
--- /dev/null
+++ b/.agents/skills/purview-sourcegenerator-testing/references/test-modernisation.md
@@ -0,0 +1,63 @@
+# Modernising a Roslyn test suite
+
+A playbook for moving an existing test suite onto `CodeQuery` plus the TUnit assertion extensions,
+and adding a stage-by-stage incremental cache test.
+
+## Before you start, collect
+
+- The test file(s) being changed.
+- The Roslyn component under test — generator, analyzer, code fix or refactor (infer it from the
+ base class if the task does not say).
+- The component's type name.
+
+## Requirements
+
+### 1. The right base class and method
+
+| Component | Base class | Method |
+| --- | --- | --- |
+| Generator | `TUnitSourceGeneratorTestBase` | `GenerateAsync` |
+| Analyzer | `TUnitDiagnosticAnalyzerTestBase` | `AnalyzeAsync` |
+| Code fix | `TUnitCodeFixTestBase` | `ApplyCodeFixAsync` / `ApplyFixAllAsync` |
+| Refactor | `TUnitRefactoringTestBase` | `RefactorAsync` |
+
+### 2. `CodeQuery` instead of string matching
+
+Replace `GetGeneratedTree(...)` + `string.Contains(...)` with `CodeQuery`
+(`result.Generated().Get/Has/TryGet…`) and the terminal assertion extensions —
+`await Assert.That(result).HasGeneratedMethod/Class/Property/Field/SyntaxTree(…)` — which return the
+node so a follow-up assertion has something to work with.
+
+### 3. `TypeReference` instead of signature strings
+
+Match parameter and return types structurally. A signature string breaks on a whitespace or
+nullability change that means nothing.
+
+### 4. Options in one place
+
+Derive a `SourceGeneratorTestOptions` record that seeds the required namespaces and additional
+assemblies, and remove the per-test duplication it replaces.
+
+### 5. A stage-by-stage cache test
+
+Use `RunIncrementalAsync`, or `GenerateIncrementalAsync` on the TUnit base, and assert the four
+scenarios. `ServiceRegistrationCacheTests` and `IncrementalPipelineCacheTests` are the reference
+pattern.
+
+| Scenario | Expected |
+| --- | --- |
+| First run | every framework stage `New` |
+| Identical rerun (`RunIncrementalAsync(sources, …)` runs the same source twice) | framework stages `Cached`/`Unchanged` |
+| Source-only change | `ForAttribute_*` `Modified`; property/config stages stay `Cached` |
+| Property-only change (`new IncrementalRunInput(sources, [("build_property.X", "value")])`) | `GetMSBuildPropertyValue_*`, `GetGenerationConfiguration`, `GetGenerationContext_*` `Modified`; `ForAttribute_*` stays `Cached` |
+
+Use the `StepReasons(IncrementalCacheRun)` flattening helper. If the generator depends on its own
+post-init output, assert on the framework-named stages rather than on every tracked step.
+
+### 6. Minimal change
+
+Keep behaviour equivalent, and do not reformat unrelated tests.
+
+## Verification
+
+Build the test project and run its suite before finishing.
diff --git a/.agents/skills/tunit-test-authoring/SKILL.md b/.agents/skills/purview-sourcegenerator-tunit-tests/SKILL.md
similarity index 87%
rename from .agents/skills/tunit-test-authoring/SKILL.md
rename to .agents/skills/purview-sourcegenerator-tunit-tests/SKILL.md
index fa58cd8f..bc711c59 100644
--- a/.agents/skills/tunit-test-authoring/SKILL.md
+++ b/.agents/skills/purview-sourcegenerator-tunit-tests/SKILL.md
@@ -1,6 +1,13 @@
---
-name: tunit-test-authoring
-description: "Use when writing TUnit tests for source generators, diagnostic analyzers, code fixes, or refactorings in a Purview.SourceGeneratorFramework repository — choosing the correct base class and method, customising options, using the assertion extensions, and modernising existing tests."
+name: purview-sourcegenerator-tunit-tests
+description: >-
+ Use when writing TUnit tests for source generators, diagnostic analyzers, code fixes or
+ refactorings built on Purview.SourceGeneratorFramework - choosing the correct TUnit base class and
+ method, customising SourceGeneratorTestOptions, using the TUnit assertion extensions, and
+ modernising existing tests.
+metadata:
+ product: Purview.SourceGeneratorFramework.Testing.TUnit
+ repository: purview-dev/sourcegenerator-framework
---
# TUnit test authoring for Roslyn components
@@ -9,7 +16,7 @@ Use this skill whenever a task involves authoring, fixing, or modernising **TUni
components built with `Purview.SourceGeneratorFramework`. It tells you which base class to derive from,
which method to call, how to customise options with an easy starting point, and how to use the TUnit
assertion extensions. For the framework-agnostic runner layer and the `CodeQuery` API, also load the
-`sdk` package's `source-generator-testing` skill.
+`purview-sourcegenerator-testing` skill.
## Base class → method matrix
@@ -57,6 +64,13 @@ Use the base hooks to customise per-run: `OnBeforeRun`/`OnBeforeRunAsync` (mutat
`options.WithAdditionalSources(markerAttributeSource)`) and `OnAfterRun`/`OnAfterRunAsync`. Use
`options.Compile()` to opt into `CompileToAssembly` while preserving the derived options type.
+Write `using var result = await GenerateAsync(...)`: `DriverRunResult` is `IDisposable`, and `PSGFR42`
+flags a result that is produced and never disposed (a `warning` once the run compiles to an assembly,
+`info` otherwise). It also catches the indirect case — a helper that creates a result, projects a value out
+of it and returns only the projection. Awaiting an assertion, or calling a helper that is handed the result —
+an extension on it, or a method taking it as a parameter — is not a production: both hand the same instance
+back, so neither is flagged.
+
For code fixes/refactorings, select a specific registered action via `CodeFixTestOptions.EquivalenceKey`
or `CodeActionIndex`, and `RefactorTestOptions.Span`/`NodeSelector` (e.g.
`NodeSelector = query => query.GetMethod("M")`).
@@ -116,7 +130,7 @@ when awaited.
(whitespace-flattened string comparison).
For structural assertions (members, signatures, namespaces) prefer `result.Generated()` +
-`Get/Has/TryGet` from `CodeQuery` (see `source-generator-testing`).
+`Get/Has/TryGet` from `CodeQuery` (see `purview-sourcegenerator-testing`).
## Incremental cache tests (`GenerateIncrementalAsync`)
@@ -124,7 +138,7 @@ For structural assertions (members, signatures, namespaces) prefer `result.Gener
also wires the base class hooks (`OnBeforeRun`/`OnBeforeRunAsync`) and your derived options record. Use it to
prove the pipeline caches stage-by-stage. The reference is `ServiceRegistrationCacheTests` in
`SourceGeneratorFramework.ExampleGenerator.UnitTests`; the framework-agnostic twin with a full walkthrough is
-in the `source-generator-testing` skill.
+in the `purview-sourcegenerator-testing` skill.
Why the tests look the way they do:
@@ -137,9 +151,11 @@ Why the tests look the way they do:
- `new IncrementalRunInput([Source], [("build_property.X", "value")])` toggles an MSBuild property for one
run only, so a property-only change must mark `GetMSBuildPropertyValue_*`/`GetGenerationConfiguration`/
`GetGenerationContext_*` `Modified` while `ForAttribute_*` stays `Cached`.
+- `result.Runs[n].LogEntries` carries the framework log entries *that run* wrote, in order, so a rerun whose
+ output step is cached can be asserted to have logged nothing. Empty when `EnableLogging` is disabled.
- The `StepReasons(IncrementalCacheRun)` helper flattens each tracked step's `Outputs` into a
`ImmutableDictionary>` so assertions can address a stage
- by name (see `source-generator-testing` for the helper body).
+ by name (see `purview-sourcegenerator-testing` for the helper body).
- If the generator's pipeline depends on its own post-initialization output (a self-referencing generated
attribute), Roslyn's internal `ForAttributeWithMetadataName` `Compilation` step is legitimately `Modified`
on rerun; assert on the framework-named stages (e.g. `ForAttribute_GenerateServiceAttribute`,
@@ -206,7 +222,7 @@ When converting legacy tests that do `result.GetGeneratedTree(...)` + `string.Co
per test.
5. Add a stage-by-stage cache test if the component has an incremental pipeline — first run `New`,
identical rerun `Cached`/`Unchanged`, and targeted changes mark only the affected stage `Modified`.
- Use the inlined examples in this skill and in `source-generator-testing`'s "Incremental cache testing"
+ Use the inlined examples in this skill and in `purview-sourcegenerator-testing`'s "Incremental cache testing"
section, swapping in your own generator and stage names.
## License
diff --git a/.agents/skills/purview-telemetry-design/SKILL.md b/.agents/skills/purview-telemetry-design/SKILL.md
new file mode 100644
index 00000000..c8df5f81
--- /dev/null
+++ b/.agents/skills/purview-telemetry-design/SKILL.md
@@ -0,0 +1,96 @@
+---
+name: purview-telemetry-design
+description: Design best practices for Purview.Telemetry.SourceGenerator interfaces. Use when deciding between a single telemetry interface and per-area interfaces, choosing telemetry names, designing multi-target methods, or reviewing telemetry structure in a C# project.
+license: MIT
+compatibility: C# projects using Purview.Telemetry.SourceGenerator.
+metadata:
+ author: Purview-Dev
+ version: "1.0"
+---
+
+# Design best practices for Purview Telemetry
+
+This skill guides the design of generated telemetry interfaces.
+
+## Single combined interface vs. per-area interfaces
+
+The generator lets you put all telemetry types on one interface, or split them by concern.
+
+### Combined interface
+
+Use one interface when:
+
+- A single service owns all telemetry and the operations naturally overlap.
+- You want a single injection point and fewer constructor parameters.
+- Multi-target methods emit Activity + Log + Metric from one call.
+
+Naming convention:
+
+```csharp
+[ActivitySource]
+[Logger]
+[Meter]
+public interface IOrderServiceTelemetry
+```
+
+### Per-area interfaces
+
+Split into separate interfaces when:
+
+- Different consumers need only one telemetry type (e.g., tests mock only logs).
+- The team prefers clear separation between tracing, logging, and metrics.
+- The service is large and each telemetry type has many operations.
+
+Naming convention:
+
+```csharp
+[ActivitySource] public interface IOrderServiceTracing { ... }
+[Logger] public interface IOrderServiceLogs { ... }
+[Meter] public interface IOrderServiceMetrics { ... }
+```
+
+Default recommendation: start with one combined interface per service. Split only when a clear boundary emerges.
+
+## Naming conventions
+
+Default to the OpenTelemetry naming convention (`NamingConvention.OpenTelemetry`).
+
+- ActivitySource names: preserve assembly casing (e.g., `MyApp`).
+- Activity names: descriptive, sentence-case-ish, no spaces: `placing-order`.
+- Log message templates: human-readable, with `{PascalCase}` placeholders.
+- Metric instrument names: hierarchical, dot-separated, lowercase: `myapp.orders.placed`.
+- Tag/baggage keys: `snake_case`.
+
+Only use `NamingConvention.Legacy` for exact v3 backward compatibility.
+
+## Multi-target method design
+
+Combine attributes on one method when a single operation emits multiple telemetry types:
+
+```csharp
+[Activity]
+[Info]
+[AutoCounter]
+Activity? PlacingOrder(int orderId);
+```
+
+Rules:
+
+- Methods that return `Activity?` create an Activity.
+- Methods that return `void` typically add events, log, or record metrics.
+- Pass the `Activity?` from the starting method to event/context methods.
+
+## Parameter attributes
+
+| Attribute | Use |
+|---|---|
+| `[Baggage]` | Adds the parameter to Activity baggage; also included in logs. |
+| `[Tag]` | Adds the parameter as an Activity tag. |
+| `[ExcludeTargets(Targets.Activities)]` | Excludes the parameter from Activity generation only. |
+| `[ExpandEnumerable(maximumValueCount: N)]` | Expands an array/IEnumerable into indexed log properties. |
+
+## Testing
+
+Inject the interface in your service and mock it in tests. The generated interface has no implementation code in the interface itself, so standard mocking frameworks (NSubstitute, Moq, TUnitMocks) work directly.
+
+See [references/REFERENCE.md](references/REFERENCE.md) for a decision matrix and naming examples.
diff --git a/.agents/skills/purview-telemetry-design/references/REFERENCE.md b/.agents/skills/purview-telemetry-design/references/REFERENCE.md
new file mode 100644
index 00000000..b15cfcf0
--- /dev/null
+++ b/.agents/skills/purview-telemetry-design/references/REFERENCE.md
@@ -0,0 +1,101 @@
+# Design reference
+
+## Interface shape decision matrix
+
+| Situation | Recommendation |
+|---|---|
+| Small service with < 10 telemetry operations | One combined `ITelemetry` |
+| Service only logs | `ILogs` |
+| Service only traces | `ITracing` |
+| Service only emits metrics | `IMetrics` |
+| Large service with distinct teams owning logs vs. metrics | Split into per-area interfaces |
+| Need to mock only one telemetry type in many tests | Split into per-area interfaces |
+
+## Naming examples
+
+### OpenTelemetry mode (default)
+
+```csharp
+[ActivitySource] // name = "MyApp"
+[Logger]
+[Meter]
+public interface IOrderServiceTelemetry
+{
+ [Activity]
+ Activity? PlacingOrder(int orderId); // activity name = "placing-order"
+
+ [Info("Placing order {OrderId}")]
+ void PlacingOrderInfo(int orderId); // log
+
+ [AutoCounter]
+ void OrderPlaced(); // instrument = "myapp.orders.order-placed"
+}
+```
+
+### Legacy mode
+
+```csharp
+[assembly: TelemetryGeneration(NamingConvention = NamingConvention.Legacy)]
+```
+
+Use only when exact v3 names must be preserved.
+
+## Multi-target example
+
+```csharp
+[ActivitySource]
+[Logger]
+[Meter]
+public interface IOrderServiceTelemetry
+{
+ // Starts Activity, logs Info, increments Counter
+ [Activity(ActivityKind.Internal)]
+ [Info("Placing order {OrderId} for {CustomerName}")]
+ [AutoCounter]
+ Activity? PlacingOrder(int orderId, string customerName, [Baggage] string region);
+
+ // Adds event to the Activity and logs Trace
+ [Event]
+ [Trace]
+ void OrderValidated(Activity? activity, int orderId);
+
+ // Records histogram
+ [Histogram]
+ void OrderProcessingTime(double latencyMs);
+}
+```
+
+## Parameter attribute examples
+
+```csharp
+[Activity]
+[Info]
+Activity? FetchingOrder(
+ int orderId,
+ [Baggage] string region, // carried in Activity baggage
+ [Tag] string tenantId); // Activity tag only
+
+[Event]
+void OrderLoaded(
+ Activity? activity,
+ int orderId,
+ [ExcludeTargets(Targets.Activities)] string[] rawLines); // not in Activity
+```
+
+## Testing example
+
+```csharp
+public class OrderServiceTests
+{
+ [Test]
+ public void PlaceOrder_EmitsTelemetry()
+ {
+ var telemetry = Substitute.For();
+ var service = new OrderService(telemetry);
+
+ service.PlaceOrder(42, "Alice", "EMEA");
+
+ telemetry.Received().PlacingOrder(42, "Alice", "EMEA");
+ }
+}
+```
diff --git a/.agents/skills/purview-telemetry-diagnostics/SKILL.md b/.agents/skills/purview-telemetry-diagnostics/SKILL.md
new file mode 100644
index 00000000..fec24d27
--- /dev/null
+++ b/.agents/skills/purview-telemetry-diagnostics/SKILL.md
@@ -0,0 +1,168 @@
+---
+name: purview-telemetry-diagnostics
+description: >-
+ Use when a Purview.Telemetry.SourceGenerator build reports a TSG diagnostic - TSG1xxx general,
+ TSG2xxx logging, TSG3xxx activities, TSG4xxx metrics - to find what triggered it and how to fix it,
+ or when deciding whether a rule can be suppressed.
+license: MIT
+compatibility: C# projects using Purview.Telemetry.SourceGenerator.
+metadata:
+ author: Purview-Dev
+ product: Purview.Telemetry.SourceGenerator
+ repository: purview-dev/telemetry-sourcegenerator
+---
+
+# Purview.Telemetry.SourceGenerator diagnostics
+
+One Roslyn analyzer, `TelemetryDiagnosticAnalyzer`, validates telemetry interfaces and raises `TSG`
+diagnostics in four families:
+
+| Family | Covers |
+| --- | --- |
+| `TSG1xxx` | general — interface and method shape, targets, framework support |
+| `TSG2xxx` | logging |
+| `TSG3xxx` | activities |
+| `TSG4xxx` | metrics |
+
+Every rule is tracked in `AnalyzerReleases.Shipped.md` / `AnalyzerReleases.Unshipped.md` with its ID,
+category and severity, validated by the Roslyn release-tracking analyzers on every build. A new or
+changed diagnostic must be recorded there in the same change.
+
+## General — `TSG1xxx`
+
+| ID | Severity | Reported when |
+| --- | --- | --- |
+| `TSG1000` | Error | An unexpected exception escaped the generation pipeline. |
+| `TSG1001` | Error | A method on a multi-target interface has no explicit generation attribute — inference is not supported there. |
+| `TSG1002` | Error | Two attributes from the same target family on one method. Only one Activity, Logging or Metrics attribute per method. |
+| `TSG1003` | Error | Two methods on the interface share a name. |
+| `TSG1004` | Error | Generic interfaces are not supported. |
+| `TSG1005` | Error | Generic methods are not supported. |
+| `TSG1006` | Warning | `ExcludeTargets` names a target not present on the method. |
+| `TSG1007` | Warning | `ExcludeTargets` leaves a target with an empty or invalid parameter set. |
+| `TSG1008` | Warning | An `Activity`-typed parameter on a method with no `[Activity]`/`[Event]`/`[Context]`. |
+| `TSG1010` | Error | A method carries an attribute for a target family the interface does not register. |
+| `TSG1011` | Error | The compilation targets neither .NET 8+ nor .NET Framework 4.8+. Define `PURVIEW_TELEMETRY_NON_NULLABLE` to opt out. |
+
+## Logging — `TSG2xxx`
+
+| ID | Severity | Reported when |
+| --- | --- | --- |
+| `TSG2000` | Error | A non-scoped log method has more than one `Exception` parameter. |
+| `TSG2001` | Error | A v1-mode log method has more than 6 non-exception parameters. |
+| `TSG2002` | Info | v1 generation inferred `Error` from a lone `Exception` parameter with no explicit level. |
+| `TSG2003` | Warning | No reference to `Microsoft.Extensions.Logging.ILogger`; log generation is skipped. |
+| `TSG2004` | Error | Ordinal and named placeholders mixed in one message template. |
+| `TSG2005` | Error | The maximum ordinal placeholder exceeds the parameter count. |
+| `TSG2006` | Error | `[LogProperties]` and `[ExpandEnumerable]` on the same parameter. |
+| `TSG2007` | Warning | A scoped log declares a `LogLevel`; it is ignored. |
+| `TSG2008` | Warning | `[ExpandEnumerable]` has a `MaximumValueCount` above the recommended default of 5. |
+| `TSG2021` | Error | A log method returns something other than `void` or `IDisposable`. (`Activity` is allowed when the method is also an Activity method.) |
+
+## Activities — `TSG3xxx`
+
+| ID | Severity | Reported when |
+| --- | --- | --- |
+| `TSG3000` | Warning | A baggage parameter is not a string; `ToString()` will be called. |
+| `TSG3001` | Warning | No activity source name available anywhere; generation defaults to `purview`. |
+| `TSG3002` | Error | An Activity/Event method returns something other than `void` or `Activity`. |
+| `TSG3003` | Error | More than one parameter maps to the same reserved destination. |
+| `TSG3004` | Error | An `Activity`-destination parameter on an Activity method — only valid on `[Event]`. |
+| `TSG3005` | Error | A `timestamp` parameter on a method that is not `[Event]`. |
+| `TSG3006` | Error | A start-time parameter on a Create-activity or Event method. |
+| `TSG3007` | Error | A parent-context or parent-id parameter on an event. |
+| `TSG3008` | Error | Activity-links parameters on an event or context method. |
+| `TSG3009` | Error | An activity-tags parameter on a context method. |
+| `TSG3010` | Error | An escaped parameter is not a boolean. |
+| `TSG3011` | Error | Escaped parameters on an Activity or Context method — Events only. |
+| `TSG3012` | Info | No Activity methods defined; `Activity.Current` is assumed. |
+| `TSG3013` | Warning | An Activity method does not return the created `Activity`. |
+| `TSG3014` | Warning | An Event/Context method has no `Activity` parameter. Controlled by `ActivitySourceGeneration.GenerateDiagnosticsForMissingActivity` (default `true`). |
+| `TSG3015` | Info | `Activity` should be the first parameter. Same opt-in as `TSG3014`. |
+| `TSG3016` | Error | A status-description parameter is not a string. |
+| `TSG3017` | Error | Status-description parameters on an Activity or Context method — Events only. |
+| `TSG3021` | Info | An `[Event]` records an exception under the OpenTelemetry rules but is not named `"exception"`. |
+| `TSG3022` | Warning | An Activity method returns non-nullable `Activity`. |
+
+## Metrics — `TSG4xxx`
+
+| ID | Severity | Reported when |
+| --- | --- | --- |
+| `TSG4000` | Error | A method on a Metrics interface has no instrument attribute and is not excluded. |
+| `TSG4001` | Error | A metrics-owned method returns something other than `void` or `bool`. |
+| `TSG4002` | Error | An auto-increment instrument also declares a measurement parameter. |
+| `TSG4003` | Error | More than one measurement value. |
+| `TSG4004` | Error | A non-auto-increment instrument method has no measurement parameter. |
+| `TSG4005` | Error | An observable instrument is not declared as `Func`. |
+| `TSG4006` | Error | The measurement type is not `byte`, `short`, `int`, `long`, `double`, `float`, `decimal`, `Measurement]