From 0246f9c20e17b10594c321ef3a8d1b50bedc726e Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Mon, 16 Nov 2026 21:24:48 +0100 Subject: [PATCH 01/95] =?UTF-8?q?=E2=9C=A8=20add=20dotnet-csrun=20skill=20?= =?UTF-8?q?for=20executable=20csharp=20evidence?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Executable C# evidence is needed when documentation examples and API claims must be proven by running the exact source. The new skill provides small complete console examples and genuine xUnit v3 tests through csrun, with exact package pins and an honest verified, compiled-only, or unverified status. --- skills/dotnet-csrun/SKILL.md | 53 ++++++++ skills/dotnet-csrun/evals/evals.json | 122 ++++++++++++++++++ skills/dotnet-csrun/evals/files/console.json | 6 + skills/dotnet-csrun/evals/files/empty.json | 9 ++ skills/dotnet-csrun/evals/files/failing.json | 9 ++ skills/dotnet-csrun/evals/files/invalid.json | 6 + skills/dotnet-csrun/evals/files/package.json | 9 ++ skills/dotnet-csrun/evals/files/passing.json | 9 ++ skills/dotnet-csrun/evals/files/unicode.json | 6 + skills/dotnet-csrun/references/execution.md | 30 +++++ skills/dotnet-csrun/references/manifest.md | 19 +++ .../dotnet-csrun/references/presentation.md | 11 ++ .../dotnet-csrun/references/verification.md | 23 ++++ skills/dotnet-csrun/scripts/validate.cs | 37 ++++++ 14 files changed, 349 insertions(+) create mode 100644 skills/dotnet-csrun/SKILL.md create mode 100644 skills/dotnet-csrun/evals/evals.json create mode 100644 skills/dotnet-csrun/evals/files/console.json create mode 100644 skills/dotnet-csrun/evals/files/empty.json create mode 100644 skills/dotnet-csrun/evals/files/failing.json create mode 100644 skills/dotnet-csrun/evals/files/invalid.json create mode 100644 skills/dotnet-csrun/evals/files/package.json create mode 100644 skills/dotnet-csrun/evals/files/passing.json create mode 100644 skills/dotnet-csrun/evals/files/unicode.json create mode 100644 skills/dotnet-csrun/references/execution.md create mode 100644 skills/dotnet-csrun/references/manifest.md create mode 100644 skills/dotnet-csrun/references/presentation.md create mode 100644 skills/dotnet-csrun/references/verification.md create mode 100644 skills/dotnet-csrun/scripts/validate.cs diff --git a/skills/dotnet-csrun/SKILL.md b/skills/dotnet-csrun/SKILL.md new file mode 100644 index 00000000..4dfa98a2 --- /dev/null +++ b/skills/dotnet-csrun/SKILL.md @@ -0,0 +1,53 @@ +--- +name: dotnet-csrun +description: > + Use when creating runnable C# examples, verifying documentation snippets or API behavior, turning snippets into isolated xUnit tests, or reproducing .NET problems without a project. Excludes repository test infrastructure, integration suites, and benchmarks. +--- + +# Executable C# evidence with csrun + +Make the smallest complete example, execute it through `csrun`, and share the exact program that ran. Use .NET/C# for substantive supporting logic and PowerShell 7 for orchestration. Never substitute another execution engine or create a competing manifest format. + +## Workflow + +1. Inspect supplied source, documentation, dependency pins, and repository context. A bare invocation uses that context; proceed when the behavior is clear. Ask only for facts that materially affect correctness. Use `dotnet-test` for repository testing infrastructure, `dotnet-remote-testing` for existing test workloads, and `dotnet-benchmark` for performance experiments. +2. Establish the expected observation before execution: output values, stable invariants, meaningful assertions, or a deliberate failure with its diagnostic and exit status. Choose console mode for observable demonstrations and test mode for assertions. If both are explicitly requested and useful, provide independently executable examples with identical dependency versions and assumptions. +3. Write complete source, including imports and an entry point or discoverable public xUnit test class. Use async tests returning `Task` when appropriate. Do not simulate assertions or test results with printed messages. Read [manifest construction](references/manifest.md) before constructing the schema version 1 manifest. Verify package versions in repository pins and the package's authoritative published feed; never invent or silently change them. +4. Read [execution environments](references/execution.md). Prefer official disposable Docker execution when available and appropriate; native execution is first class. Preserve the requested framework and choose a compatible environment explicitly. If neither environment can execute it, name the concrete missing prerequisite and deliver an **Unverified** example. Never silently retarget, install a different engine, or fabricate output. +5. Execute the exact manifest through the actual engine. Capture stdout, stderr, exit code immediately, framework, SDK/runtime environment, engine identity, and package pins. For console examples compare actual output with the declared expectation. For tests require positive discovery/execution evidence, meaningful assertions, and matching MTP status; exit zero alone is insufficient. Zero tests is never a passing test run. +6. Inspect failures as validation/prerequisite, compiler, restore, runtime, or assertion failures. Preserve relevant diagnostics; repair only the example-owned cause and rerun every changed example. A deliberate negative is verified only when both the expected failure diagnostics and exit status match; describe the test itself as failing. +7. Follow [presentation and evidence](references/presentation.md): deliver one readable PowerShell Copy & Run block where practical, then concise actual evidence and necessary caveats. Publish the same source that was executed. If showing C# separately, derive it from the manifest's source instead of maintaining a second variation. + +## Evidence classification + +| Classification | Required evidence | +| --- | --- | +| Verified | Exact example executed with declared runtime/dependencies; actual observations match expectations. | +| Compiled only | Compilation succeeded but requested runtime behavior was not exercised. | +| Unverified | Execution blocked, unavailable, or not performed. | +| Failed | Execution occurred and observations did not match expectations. | + +Model confidence is never evidence. Published-package execution proves that exact package version, not unpublished checkout changes. An isolated example does not establish application integration correctness. Keep prior unexpected failures visible even after a repaired example succeeds. + +## Full developer journey + +For “show a runnable .NET 10 example that prints 42”, construct and execute this block, check the actual output and exit status, then share it. The output described here is an expectation until execution establishes it. + +```powershell +$manifest = @{ + schemaVersion = 1 + mode = 'console' + framework = 'net10.0' + source = @' +using System; +Console.WriteLine(42); +'@ +} | ConvertTo-Json -Depth 8 + +$OutputEncoding = [System.Text.UTF8Encoding]::new($false) +$manifest | docker run --rm -i codebeltnet/csrun:10 +$code = $LASTEXITCODE +if ($code -ne 0) { throw "csrun execution failed with exit code $code." } +``` + +For tests, use the [passing fixture](evals/files/passing.json) as a small source reference, not a replacement test engine. The fixtures also cover deliberate failures, no discovered tests, invalid source, exact packages, and Unicode/raw strings. Repository maintainers can run `scripts/validate-dotnet-csrun.ps1` for deterministic artifact checks; optional engine execution is documented in [verification](references/verification.md). diff --git a/skills/dotnet-csrun/evals/evals.json b/skills/dotnet-csrun/evals/evals.json new file mode 100644 index 00000000..8ae11523 --- /dev/null +++ b/skills/dotnet-csrun/evals/evals.json @@ -0,0 +1,122 @@ +{ + "skill_name": "dotnet-csrun", + "evals": [ + { + "expectations": [ + "Output 42 and exit 0 observed; complete manifest wrapper; no fabricated evidence.", + "Uses the existing csrun manifest/engine and distinguishes actual observations from expectations.", + "Provides a readable complete copy/paste command without project scaffolding or floating package versions." + ], + "expected_output": "Output 42 and exit 0 observed; complete manifest wrapper; no fabricated evidence.", + "prompt": "Show me a complete runnable C# example that prints 42 on .NET 10. Execute it and give me one command I can paste.", + "id": 1, + "files": [ + "evals/files/console.json" + ] + }, + { + "expectations": [ + "Discover and execute a real async Fact through csrun/MTP; assert a result and report positive counts.", + "Uses the existing csrun manifest/engine and distinguishes actual observations from expectations.", + "Provides a readable complete copy/paste command without project scaffolding or floating package versions." + ], + "expected_output": "Discover and execute a real async Fact through csrun/MTP; assert a result and report positive counts.", + "prompt": "Turn addition after an asynchronous operation into a genuine xUnit v3 test on .NET 10 and run it.", + "id": 2, + "files": [ + "evals/files/passing.json" + ] + }, + { + "expectations": [ + "Keep the exact pin; observe 273 days; do not claim verification of local checkout changes.", + "Uses the existing csrun manifest/engine and distinguishes actual observations from expectations.", + "Provides a readable complete copy/paste command without project scaffolding or floating package versions." + ], + "expected_output": "Keep the exact pin; observe 273 days; do not claim verification of local checkout changes.", + "prompt": "Demonstrate Cuemon.Kernel 11.0.0 DateSpan from January 1 to October 1, 2018 on .NET 11. Verify the published API and run it.", + "id": 3, + "files": [ + "evals/files/package.json" + ] + }, + { + "expectations": [ + "Require assertion diagnostic and MTP exit 2; label verified expected failure, never passing test.", + "Uses the existing csrun manifest/engine and distinguishes actual observations from expectations.", + "Provides a readable complete copy/paste command without project scaffolding or floating package versions." + ], + "expected_output": "Require assertion diagnostic and MTP exit 2; label verified expected failure, never passing test.", + "prompt": "Make an intentionally failing xUnit assertion of 42 versus 41. Execute it and explain the outcome.", + "id": 4, + "files": [ + "evals/files/failing.json" + ] + }, + { + "expectations": [ + "Preserve compiler diagnostic and nonzero exit; classify Failed without inventing repair evidence.", + "Uses the existing csrun manifest/engine and distinguishes actual observations from expectations.", + "Provides a readable complete copy/paste command without project scaffolding or floating package versions." + ], + "expected_output": "Preserve compiler diagnostic and nonzero exit; classify Failed without inventing repair evidence.", + "prompt": "Execute this invalid sample and tell me honestly whether it works: Console.WriteLine(missingValue);", + "id": 5, + "files": [ + "evals/files/invalid.json" + ] + }, + { + "expectations": [ + "Identify missing .NET 11 environment, propose :11 or :10-11; preserve target and disclose any environment change.", + "Uses the existing csrun manifest/engine and distinguishes actual observations from expectations.", + "Provides a readable complete copy/paste command without project scaffolding or floating package versions." + ], + "expected_output": "Identify missing .NET 11 environment, propose :11 or :10-11; preserve target and disclose any environment change.", + "prompt": "Run my net11.0 example in codebeltnet/csrun:10. Do not change the framework.", + "id": 6, + "files": [ + "evals/files/console.json" + ] + }, + { + "expectations": [ + "Use faithful here-string/JSON/UTF-8 transport; compare Unicode and multiline observations with the displayed source.", + "Uses the existing csrun manifest/engine and distinguishes actual observations from expectations.", + "Provides a readable complete copy/paste command without project scaffolding or floating package versions." + ], + "expected_output": "Use faithful here-string/JSON/UTF-8 transport; compare Unicode and multiline observations with the displayed source.", + "prompt": "Publish a runnable documentation example printing quotes, two lines, and æøå 世界. Execute the same source shown in the docs.", + "id": 7, + "files": [ + "evals/files/unicode.json" + ] + }, + { + "expectations": [ + "Classify Unverified, explain concrete prerequisites, provide a self-contained wrapper and no invented output.", + "Uses the existing csrun manifest/engine and distinguishes actual observations from expectations.", + "Provides a readable complete copy/paste command without project scaffolding or floating package versions." + ], + "expected_output": "Classify Unverified, explain concrete prerequisites, provide a self-contained wrapper and no invented output.", + "prompt": "There is no Docker daemon and no .NET SDK on this machine. Give me a runnable C# demonstration and its verification status.", + "id": 8, + "files": [ + "evals/files/console.json" + ] + }, + { + "expectations": [ + "Observe zero discovery and MTP exit 8; never report passing assertions.", + "Uses the existing csrun manifest/engine and distinguishes actual observations from expectations.", + "Provides a readable complete copy/paste command without project scaffolding or floating package versions." + ], + "expected_output": "Observe zero discovery and MTP exit 8; never report passing assertions.", + "prompt": "Run this class in test mode: public class NoTests { }. Does a successful build prove the test passed?", + "id": 9, + "files": [ + "evals/files/empty.json" + ] + } + ] +} diff --git a/skills/dotnet-csrun/evals/files/console.json b/skills/dotnet-csrun/evals/files/console.json new file mode 100644 index 00000000..c6d126ad --- /dev/null +++ b/skills/dotnet-csrun/evals/files/console.json @@ -0,0 +1,6 @@ +{ + "mode": "console", + "schemaVersion": 1, + "source": "using System;\nConsole.WriteLine(42);", + "framework": "net10.0" +} diff --git a/skills/dotnet-csrun/evals/files/empty.json b/skills/dotnet-csrun/evals/files/empty.json new file mode 100644 index 00000000..10a0a129 --- /dev/null +++ b/skills/dotnet-csrun/evals/files/empty.json @@ -0,0 +1,9 @@ +{ + "mode": "test", + "dependsOn": [ + "xunit.v3@4.0.3" + ], + "schemaVersion": 1, + "source": "public class NoTests { }", + "framework": "net10.0" +} diff --git a/skills/dotnet-csrun/evals/files/failing.json b/skills/dotnet-csrun/evals/files/failing.json new file mode 100644 index 00000000..69357006 --- /dev/null +++ b/skills/dotnet-csrun/evals/files/failing.json @@ -0,0 +1,9 @@ +{ + "mode": "test", + "dependsOn": [ + "xunit.v3@4.0.3" + ], + "schemaVersion": 1, + "source": "using Xunit; public class ArithmeticTests { [Fact] public void DeliberateFailure() => Assert.Equal(42, 41); }", + "framework": "net10.0" +} diff --git a/skills/dotnet-csrun/evals/files/invalid.json b/skills/dotnet-csrun/evals/files/invalid.json new file mode 100644 index 00000000..aff480f1 --- /dev/null +++ b/skills/dotnet-csrun/evals/files/invalid.json @@ -0,0 +1,6 @@ +{ + "mode": "console", + "schemaVersion": 1, + "source": "using System; Console.WriteLine(missingValue);", + "framework": "net10.0" +} diff --git a/skills/dotnet-csrun/evals/files/package.json b/skills/dotnet-csrun/evals/files/package.json new file mode 100644 index 00000000..0cb9dde1 --- /dev/null +++ b/skills/dotnet-csrun/evals/files/package.json @@ -0,0 +1,9 @@ +{ + "mode": "console", + "dependsOn": [ + "Cuemon.Kernel@11.0.0" + ], + "schemaVersion": 1, + "source": "using System; using Cuemon; Console.WriteLine(new DateSpan(new DateTime(2018, 1, 1), new DateTime(2018, 10, 1)).TotalDays);", + "framework": "net11.0" +} diff --git a/skills/dotnet-csrun/evals/files/passing.json b/skills/dotnet-csrun/evals/files/passing.json new file mode 100644 index 00000000..2f7b0363 --- /dev/null +++ b/skills/dotnet-csrun/evals/files/passing.json @@ -0,0 +1,9 @@ +{ + "mode": "test", + "dependsOn": [ + "xunit.v3@4.0.3" + ], + "schemaVersion": 1, + "source": "using System.Threading.Tasks; using Xunit; public class ArithmeticTests { [Fact] public async Task AddsAfterAwait() { var value = await Task.FromResult(20); Assert.Equal(42, value + 22); } }", + "framework": "net10.0" +} diff --git a/skills/dotnet-csrun/evals/files/unicode.json b/skills/dotnet-csrun/evals/files/unicode.json new file mode 100644 index 00000000..965624bc --- /dev/null +++ b/skills/dotnet-csrun/evals/files/unicode.json @@ -0,0 +1,6 @@ +{ + "mode": "console", + "schemaVersion": 1, + "source": "using System;\nConsole.WriteLine(\"\"\"\nHello \"C#\" — æøå 世界\nsecond line\n\"\"\");", + "framework": "net10.0" +} diff --git a/skills/dotnet-csrun/references/execution.md b/skills/dotnet-csrun/references/execution.md new file mode 100644 index 00000000..5617ac96 --- /dev/null +++ b/skills/dotnet-csrun/references/execution.md @@ -0,0 +1,30 @@ +# One manifest, two transports + +Check Docker daemon availability, selected image SDK/runtime inventory, and engine labels before promising execution. [Docker documentation](https://hub.docker.com/r/codebeltnet/csrun) and [upstream container guidance](https://github.com/codebeltnet/csrun#disposable-container-execution) describe official images. Registry tags inspected on 2026-11-16 include `10`, `11`, and `10-11`; these identify environments, not engine releases. + +| Target | Suitable environment | +| --- | --- | +| net10.0 | :10 or :10-11 | +| net11.0 | :11 or :10-11 | +| Omitted framework | Engine's supported GA LTS default; currently net10.0. :11 alone cannot supply its runtime. | +| Windows-specific code | Compatible native Windows environment; Linux images cannot establish Windows behavior. | + +Never fix a mismatch by changing the target. The engine validates support against Microsoft's release metadata; unavailable metadata and a stale/missing cache can block execution. It installs no SDKs and performs no implicit runtime roll-forward. + +Use `$OutputEncoding = [System.Text.UTF8Encoding]::new($false)` before piping the JSON string to `docker run --rm -i codebeltnet/csrun:10`. No TTY, clone, bind mount, host .NET SDK, or persistent generated files is required. PowerShell 7 and Docker with Linux containers suffice. Metadata and uncached NuGet restores need network access. + +Record `docker image inspect codebeltnet/csrun:10 --format '{{json .Config.Labels}}'` and `docker image inspect codebeltnet/csrun:10 --format '{{json .RepoDigests}}'` where reproducibility matters. Tags are mutable and cached images persist until updated. A registry-confirmed digest pin improves identity; never invent one. Engine release/hash labels and SDK/runtime inventories are separate identities. Use `docker run --rm --entrypoint dotnet codebeltnet/csrun:10 --list-sdks` and `--list-runtimes` to inspect them. + +For justified tighter isolation, retain executable temporary storage: `docker run --rm -i --read-only --tmpfs /tmp:rw,exec,nosuid,nodev,size=1g,mode=1777 --cap-drop=ALL --security-opt=no-new-privileges --cpus=2 --memory=2g --pids-limit=256 codebeltnet/csrun:10`. Adjust resource bounds transparently. Do not add `noexec` to build storage. Docker is not a hardened hostile-code service: dependencies/build assets, outbound access, resource exhaustion, and daemon vulnerabilities remain trust concerns. Decline ordinary execution of high-risk unknown source when isolation is inadequate. Never automatically forward credentials/environment, mount the Docker socket or arbitrary host directories, add privileges, or run third-party setup scripts. + +## Native alternative + +Prefer a previously obtained, reviewed local engine: `& ./csrun.ps1 -ManifestJson $manifest`. Native execution requires PowerShell 7 and the appropriate installed SDK/runtime; applicable `global.json` can influence SDK selection. When a remote option is useful, explain that downloading and running the publisher's script and C#/NuGet build inputs grants them the developer's permissions. It is not sandboxed. + +```powershell +& ([scriptblock]::Create((irm 'https://github.com/codebeltnet/csrun/releases/latest/download/csrun.ps1'))) -ManifestJson $manifest +$code = $LASTEXITCODE +if ($code -ne 0) { throw "csrun execution failed with exit code $code." } +``` + +This replaces only the transport line in a complete manifest block. Do not use `irm | iex` to pass parameters. Latest is mutable; retain a trusted release asset/hash for stronger reproduction. No global tool, template, or new CLI is required. diff --git a/skills/dotnet-csrun/references/manifest.md b/skills/dotnet-csrun/references/manifest.md new file mode 100644 index 00000000..17ba0e58 --- /dev/null +++ b/skills/dotnet-csrun/references/manifest.md @@ -0,0 +1,19 @@ +# Manifest construction + +Contract inspected against [csrun source and README](https://github.com/codebeltnet/csrun), released `v0.2.1`, on 2026-11-16. Recheck upstream for changed contracts rather than extending this schema locally. + +| Field | Engine contract | +| --- | --- | +| schemaVersion | Required integer 1. | +| mode | Required console or test (case insensitive). | +| source | Required nonempty complete C# source string. | +| framework | Optional supported .NET 10+ TFM; explicit values preserved. Platform TFMs require platform support. Omission selects highest supported GA LTS, not newest installed SDK. | +| dependsOn | Optional array of PackageId@ExactVersion strings; three or four numeric components, optional prerelease. No floating, ranges, or missing versions. Conflicting duplicates fail. | +| sdk | Optional Microsoft.NET.Sdk or Microsoft.NET.Sdk.Web; never inferred from imports. | +| frameworkReferences | Optional framework names; console supports Microsoft.AspNetCore.App only with explicitly selected Microsoft.NET.Sdk.Web, through its implicit reference. Test mode emits explicit references. | + +Unknown fields fail. There are no project references or arbitrary MSBuild settings. Existing source directives must match the manifest and occupy the supported leading preamble; do not rewrite or independently parse directives. Delegate manifest validation, SDK selection, dependency resolution, compilation, discovery, and exit status to csrun. + +Test mode currently defaults to `xunit.v3@4.0.3`, using Microsoft.Testing.Platform. For reproducible examples explicitly pin that version; supported overrides are stable 4.0 patch versions >= 4.0.3. Do not introduce xUnit v2 or another runner. csrun creates and cleans its own temporary test project; developers create none. + +Resolve requested API versions from the source repository and published NuGet metadata. An exact direct pin does not freeze all transitive resolution. If unpublished local code or unsupported build customization is essential, report the source-model gap and use an appropriate project workflow separately; do not disguise it with a different package version. diff --git a/skills/dotnet-csrun/references/presentation.md b/skills/dotnet-csrun/references/presentation.md new file mode 100644 index 00000000..2bd651eb --- /dev/null +++ b/skills/dotnet-csrun/references/presentation.md @@ -0,0 +1,11 @@ +# Readable examples and honest evidence + +Prefer a single PowerShell block: a hashtable with schemaVersion, mode, explicit framework, optional exact dependencies, and a literal single-quoted here-string for source; serialize with `ConvertTo-Json -Depth 8`, invoke csrun, then capture `$LASTEXITCODE` immediately. Single-quoted here-strings preserve C# quotes, dollars, Unicode, and raw multiline strings. If C# contains a line that collides with the PowerShell terminator, choose another faithful construction and verify source round-tripping; do not manually escape large JSON programs. + +Lead with the behavior, then Copy & Run, Verification, and only necessary requirements/caveats. Combine behavior and wrapper for small examples. Do not require helper scripts or fixture downloads in the developer-facing command. Show expected output explicitly as expected until observed. Derive separately displayed C# from the same source string used for execution. + +Record source/manifest identity, transport, framework, actual SDK/runtime, engine release/hash or container digest when available, exact pins, expected observations, actual stdout/stderr, exit status, discovered/executed/passed/failed counts, and classification. Preserve raw diagnostics in evidence; summarize only relevant lines to the user. Do not estimate unavailable metrics. + +Current engine outcomes: success 0; validation/prerequisite failure 1; assertion failure MTP 2; no discovered tests MTP 8. Compiler/runtime failures preserve child status, so do not assume every non-test failure is 1. Compare diagnostics as well as status. Skips do not prove assertions executed. An intentional failing assertion can be **Verified expected failure**, while clearly stating that the test failed; an unexpected failure is **Failed**. Never classify zero tests as passing. + +For nondeterministic behavior verify stable invariants instead of incidental timestamps/order. When runtime is missing, state **Unverified**, name the missing SDK/runtime or unavailable Docker daemon/image, and offer a compatible environment without retargeting. Do not claim complete determinism with mutable tags, transitive dependencies, platform differences, or external services. diff --git a/skills/dotnet-csrun/references/verification.md b/skills/dotnet-csrun/references/verification.md new file mode 100644 index 00000000..08787c68 --- /dev/null +++ b/skills/dotnet-csrun/references/verification.md @@ -0,0 +1,23 @@ +# Maintainer verification + +From the agentic repository root, `pwsh -NoProfile -File scripts/validate-dotnet-csrun.ps1` uses the existing file-based application build cache to run the C# artifact validator. It checks fixture intent, serialization preservation, resource links, and published-source parity. It neither validates the engine schema nor executes source. Repository metadata validation automatically discovers this skill's eval specification and fixture paths. + +Optional focused integration: `pwsh -NoProfile -File scripts/validate-dotnet-csrun.ps1 -EnginePath ` or `-Docker`. These execute all seven fixtures through the actual engine, preserve output and manifest hashes under a unique OS temporary directory, and fail on mismatched status or observations. No engine download is automated. Docker uses :10 for .NET 10 and :11 for the .NET 11 package example. Run both transports to check parity when available. Expected failures are assertions about engine observations, not passing tests. Network access and genuine SDK/runtime prerequisites remain necessary. + +The eval specification includes nine representative user tasks. Inspect these deterministically; model-backed eval execution is not part of this validator or a completion gate. Follow repository portable handoff rules only when explicitly asked for an evaluation. Full repository validation requires separate approval; focused checks suffice here. + +## Observed implementation verification, 2026-11-16 + +All seven fixtures matched expected observations on native Windows (installed SDK 11.0.100, .NET 10.0.15/11.0.0 runtimes) and official Linux Docker images. Both transports used released engine v0.2.1, SHA256 `6609acb7ac9df5cbbbf70d58b3dbc40f2d242e34831f89c7b42d7069015db802`. The inspected upstream commit was `1e96747d26b68eea81483ecc7eefe1fdd4c34b18`. + +| Fixture | Observed result on both transports | +| --- | --- | +| console | 42; exit 0 | +| passing | total 1, succeeded 1, failed/skipped 0; exit 0 | +| failing | Assert.Equal failure, expected 42 / actual 41; exit 2 | +| empty | no discovered tests; exit 8 | +| invalid | CS0103 for missingValue; exit 1 | +| package | Cuemon.Kernel@11.0.0 DateSpan prints 273; exit 0 | +| unicode | Quotes, æøå 世界, and two source lines preserved; exit 0 | + +Docker :10 used SDK 10.0.404 with observed RepoDigest `sha256:98d937e36e9221f352fa960ca8906560a33422b1519bc3c5f25942438cef1b81`; :11 used SDK 11.0.100 with RepoDigest `sha256:88f4f061ef93e8439ecc392f712a0a90c1a2c2a44d2553b300eeb836043ac968`. These are recorded observations, not promises about future mutable tags. The artifact validator also rejected a temporary copy whose console result was changed to 43. No model-backed activation or paired effectiveness measurement was performed. diff --git a/skills/dotnet-csrun/scripts/validate.cs b/skills/dotnet-csrun/scripts/validate.cs new file mode 100644 index 00000000..795757f9 --- /dev/null +++ b/skills/dotnet-csrun/scripts/validate.cs @@ -0,0 +1,37 @@ +using System.Text.Json; +using System.Text.RegularExpressions; + +// Validates only maintained skill artifacts, never the csrun manifest contract. +var root = Path.GetFullPath(args.Single()); +var skill = File.ReadAllText(Path.Combine(root, "SKILL.md")); +foreach (Match link in Regex.Matches(skill, @"\]\(([^)]+)\)")) +{ + var path = link.Groups[1].Value; + if (!path.Contains("://") && !File.Exists(Path.Combine(root, path))) + throw new InvalidDataException($"Broken resource link: {path}"); +} +var expectedSources = new Dictionary +{ + ["console"] = "Console.WriteLine(42)", + ["passing"] = "Assert.Equal(42, value + 22)", + ["failing"] = "Assert.Equal(42, 41)", + ["invalid"] = "missingValue", + ["empty"] = "public class NoTests", + ["package"] = "new DateSpan", + ["unicode"] = "Hello \"C#\" — æøå 世界\nsecond line" +}; +foreach (var (name, fragment) in expectedSources) +{ + using var fixture = JsonDocument.Parse(File.ReadAllText(Path.Combine(root, "evals", "files", name + ".json"))); + var source = fixture.RootElement.GetProperty("source").GetString()!; + if (!source.Contains(fragment, StringComparison.Ordinal)) throw new InvalidDataException($"Fixture intent drift: {name}"); + var options = new JsonSerializerOptions { TypeInfoResolver = new System.Text.Json.Serialization.Metadata.DefaultJsonTypeInfoResolver() }; + var roundTrip = JsonSerializer.Deserialize(JsonSerializer.Serialize(source, options), options); + if (source != roundTrip) throw new InvalidDataException($"Source round-trip failed: {name}"); +} +// Ensure the published journey and the executable fixture describe the same program. +using var console = JsonDocument.Parse(File.ReadAllText(Path.Combine(root, "evals", "files", "console.json"))); +var documented = Regex.Match(skill, "source = @'\\r?\\n(.*?)\\r?\\n'@", RegexOptions.Singleline).Groups[1].Value; +if (documented.Replace("\r\n", "\n") != console.RootElement.GetProperty("source").GetString()!.Replace("\r\n", "\n")) + throw new InvalidDataException("Published console source differs from fixture."); +Console.WriteLine("dotnet-csrun artifacts passed: 7 source fixtures, JSON round-trips, resource links, published source parity."); From 640bdec26a25be563a72fcd6375835248c44d915 Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Mon, 16 Nov 2026 21:25:09 +0100 Subject: [PATCH 02/95] =?UTF-8?q?=E2=9C=85=20add=20validation=20for=20dotn?= =?UTF-8?q?et-csrun=20skill?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The csrun skill ships a deterministic validator and a template check that keeps the published SKILL.md example identical to its console fixture and verifies its local links. Both run offline so regressions are caught without invoking a model. --- scripts/validate-dotnet-csrun.ps1 | 49 ++++++++++++++++++++++++++++ scripts/validate-skill-templates.ps1 | 13 ++++++++ 2 files changed, 62 insertions(+) create mode 100644 scripts/validate-dotnet-csrun.ps1 diff --git a/scripts/validate-dotnet-csrun.ps1 b/scripts/validate-dotnet-csrun.ps1 new file mode 100644 index 00000000..9e067036 --- /dev/null +++ b/scripts/validate-dotnet-csrun.ps1 @@ -0,0 +1,49 @@ +#requires -Version 7.0 +[CmdletBinding()] +param( + [string] $EnginePath, + [switch] $Docker +) +$ErrorActionPreference = 'Stop' +Set-StrictMode -Version Latest +if ($EnginePath -and $Docker) { throw 'Choose native EnginePath or Docker.' } +$root = Join-Path $PSScriptRoot '../skills/dotnet-csrun' +. (Join-Path $PSScriptRoot 'file-based-app.ps1') +$app = Get-FileBasedAppCommand -SourcePath (Join-Path $root 'scripts/validate.cs') +& $app.Executable @($app.ArgumentPrefix + @($root)) +if ($LASTEXITCODE -ne 0) { throw 'Skill artifact validation failed.' } +if (-not $EnginePath -and -not $Docker) { return } +if ($EnginePath) { $EnginePath = (Resolve-Path $EnginePath).Path } +$evidence = Join-Path ([IO.Path]::GetTempPath()) ('dotnet-csrun-evidence-' + [guid]::NewGuid().ToString('N')) +New-Item -ItemType Directory $evidence | Out-Null +$OutputEncoding = [Text.UTF8Encoding]::new($false) +$cases = @( + @('console', 0, '(?m)^42\s*$'), + @('passing', 0, '(?is)total:\s*1.*failed:\s*0.*succeeded:\s*1.*skipped:\s*0'), + @('failing', 2, 'Assert.Equal\(\) Failure'), + @('empty', 8, '(?i)(zero tests|no tests|total:\s*0)'), + @('invalid', -1, 'CS0103'), + @('package', 0, '(?m)^273\s*$'), + @('unicode', 0, 'Hello "C#" — æøå 世界\r?\nsecond line') +) +Write-Host "Evidence directory: $evidence" +foreach ($case in $cases) { + $name, $expectedExit, $pattern = $case + $json = Get-Content (Join-Path $root "evals/files/$name.json") -Raw + if ($Docker) { + $image = if ($name -eq 'package') { 'codebeltnet/csrun:11' } else { 'codebeltnet/csrun:10' } + $output = $json | & docker run --rm -i $image 2>&1 | Out-String + } else { + $output = & pwsh -NoProfile -NonInteractive -File $EnginePath -ManifestJson $json 2>&1 | Out-String + } + $code = $LASTEXITCODE + $output | Set-Content (Join-Path $evidence "$name.log") -Encoding utf8 + @{ fixture=$name; exitCode=$code; transport=$(if ($Docker) {$image} else {$EnginePath}); manifestSha256=(Get-FileHash (Join-Path $root "evals/files/$name.json")).Hash } | ConvertTo-Json | Set-Content (Join-Path $evidence "$name.evidence.json") + $plain = $output -replace '\x1B\[[0-?]*[ -/]*[@-~]', '' + if (($expectedExit -eq -1 -and $code -eq 0) -or ($expectedExit -ne -1 -and $code -ne $expectedExit) -or $plain -notmatch $pattern) { + throw "$name did not match expected exit/observation (exit $code). See $evidence/$name.log" + } + Write-Host "PASS $name (exit $code; expected observation matched)" +} +Write-Host 'dotnet-csrun execution checks passed: 7' + diff --git a/scripts/validate-skill-templates.ps1 b/scripts/validate-skill-templates.ps1 index b435caf7..06a9a2ee 100644 --- a/scripts/validate-skill-templates.ps1 +++ b/scripts/validate-skill-templates.ps1 @@ -827,6 +827,19 @@ if ($MetadataOnly) { exit 0 } +Add-ValidationResult -Results $results -Name 'dotnet-csrun source fixtures and published example stay coherent' -Group 'Templates' -Action { + $skill = Get-FileText -RepoRoot $repoRoot -RelativePath 'skills/dotnet-csrun/SKILL.md' -GitRef $Ref + Assert-Contains -Name 'dotnet-csrun' -Content $skill -Needle 'Compiled only' + Assert-Contains -Name 'dotnet-csrun' -Content $skill -Needle 'Unverified' + $fixture = (Get-FileText -RepoRoot $repoRoot -RelativePath 'skills/dotnet-csrun/evals/files/console.json' -GitRef $Ref) | ConvertFrom-Json + $published = [regex]::Match($skill, "(?s)source = @'\r?\n(.*?)\r?\n'@").Groups[1].Value + if ($published.Replace("`r`n", "`n") -cne $fixture.source.Replace("`r`n", "`n")) { throw 'dotnet-csrun published source differs from its console fixture.' } + foreach ($link in [regex]::Matches($skill, '\]\(([^)]+)\)')) { + $path = $link.Groups[1].Value + if ($path -notmatch '://') { [void](Get-FileText -RepoRoot $repoRoot -RelativePath "skills/dotnet-csrun/$path" -GitRef $Ref) } + } +} + Add-ValidationResult -Results $results -Name 'Git remote PR routing and deterministic workflow stay integrated' -Group 'Pr' -Action { if (-not [string]::IsNullOrWhiteSpace($Ref)) { return } $prSkill = Get-FileText -RepoRoot $repoRoot -RelativePath 'skills/git-remote-pr/SKILL.md' -GitRef $Ref From c22a2162d2d4f84abd4983edc1e9e2acabf1022f Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Mon, 16 Nov 2026 21:25:12 +0100 Subject: [PATCH 03/95] =?UTF-8?q?=F0=9F=93=9D=20document=20dotnet-csrun=20?= =?UTF-8?q?in=20readme?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The README now lists dotnet-csrun in the available skills table, install examples, and a short rationale section so users can discover the skill and understand when executable evidence is worth using. --- README.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/README.md b/README.md index 11b276a7..add53022 100644 --- a/README.md +++ b/README.md @@ -113,6 +113,7 @@ npx skills add https://github.com/codebeltnet/agentic --skill git-remote-pr npx skills add https://github.com/codebeltnet/agentic --skill dotnet-change-impact npx skills add https://github.com/codebeltnet/agentic --skill dotnet-docfx-digest npx skills add https://github.com/codebeltnet/agentic --skill dotnet-test +npx skills add https://github.com/codebeltnet/agentic --skill dotnet-csrun npx skills add https://github.com/codebeltnet/agentic --skill dotnet-benchmark npx skills add https://github.com/codebeltnet/agentic --skill dotnet-remote-testing npx skills add https://github.com/codebeltnet/agentic --skill dotnet-segregated-assets @@ -160,6 +161,7 @@ When repo-managed skills author Markdown, each prose paragraph and list item sta | [dotnet-nuget-update](skills/dotnet-nuget-update/SKILL.md) | Audits and updates NuGet dependencies in .NET repositories with complete declaration accounting before any edit. It supports both `Directory.Packages.props` and project-level `PackageReference` versions, preserves XML structure and line endings, deduplicates package IDs, resolves independent live or offline flat-container version feeds with bounded parallel lookups and per-process memoization, uses bounded network timeouts, and merges results deterministically. Its single-process update runner keeps the audit, in-memory safe-update plan, and structural apply together for fast yolo passes. It keeps stable pins on stable candidates unless prerelease intent is explicit, and applies the TFM-band rule so conditional `net9`/`net10` package declarations stay within their matching major when that major is the compatibility signal rather than jumping to the newest overall release. Normal mode auto-applies revision/patch/minor and same-major prerelease updates, then batches majors for one approval decision; yolo mode applies only the auto classes and reports held majors without asking. | | [dotnet-docfx-digest](skills/dotnet-docfx-digest/SKILL.md) | Create and maintain developer-friendly DocFX documentation for .NET public APIs, including repo-wide no-input audits that inspect source, tests, DocFX config, DocFX `build.content` and `build.overwrite` Markdown inputs, namespace pages, and availability includes before asking for clarification, while treating bare direct skill invocations as autonomous repo-wide runs rather than human-driven checkpoint sessions. Enforces the workflow with two bundled .NET 10 file-based scripts resolved from the loaded skill directory, falling back to the repo-managed source path only when present: `scripts/agents.cs` writes an idempotent, marker-bounded DocFX maintenance block into the repository `AGENTS.md`; `scripts/docfx.cs` is **fast and build-free by default** — it validates Markdown, prose, DocFX overwrite layout, namespace overview pages, `Extension Members` tables, decorated receiver signatures such as `IDecorator`, generic method displays such as `As`, purpose-first summaries, and required per-type/extension examples without invoking `dotnet`, `msbuild`, `docfx`, or `gh`, discovering the public API from existing DocFX YAML metadata or a conservative source scan and ending every run with a `[processes] dotnet=0 msbuild=0 docfx=0 gh=0` summary plus per-phase timings. Compilation and network access are strictly opt-in: `--validate-samples` compiles each C# sample in an isolated project while batching all sample projects into one temporary `.slnx` graph build with bounded MSBuild parallelism and scoped references, `--build-api-model` (alias `--strict-api-discovery`) does reflection-backed discovery from compiled metadata via `MetadataLoadContext` through a single scoped `.slnx` graph build, `--verify-docfx-build` runs the DocFX CLI in a temp copy, and `--search-examples` runs `gh` code search. Final verification adapts to available processors and memory, overlaps isolated DocFX work on high-capacity machines, uses a 30-minute child timeout, and emits 10-second `stderr` heartbeats with active phase, workload, runner count, PID, elapsed time, last-output age, and current child output while preserving machine-readable JSON on `stdout`. Honors a single DocFX metadata `TargetFramework` when `--framework` is omitted, collapses C# 14 extension-block compiler containers such as `$...` back to the authored outer static class in both fast DocFX-YAML discovery and build-backed reflection discovery, validates namespace fly-ins that explain the problem solved/when to use/where to start plus example fly-ins before every C# fence, the Codebelt namespace-and-type-folder overwrite layout (`.docfx/api/namespaces/**/*.md` and `.docfx/api/types/**/*.md` under `build.overwrite` only), keeps `--changed-only` validation scoped to affected docs and APIs while still including brand-new untracked overwrite Markdown, uses the root Codebelt `.snk` when present and falls back to `-p:SkipSignAssembly=true` for keyless strong-name build verification, drains child stdout and stderr concurrently to avoid verbose-build deadlocks, writes deterministic `--assessment-queue` Markdown work queues for noisy audits, preserves working URL references unless a verified HTTP 404 justifies removal, treats unexpected new repo-root or DocFX-workspace files that are not known `dotnet-docfx-digest` deliverables as blocking cleanup diagnostics, keeps assessment/manifests/captured output/helper scripts in temp or session storage instead of the target repository, requires a namespace-first pass across the active queue before net-new type/example authoring during full audits, keeps deeper `EXTENSION_METHOD_MISSING` and `EXTENSION_METHOD_SIGNATURE_MISSING` follow-on diagnostics in that same namespace-layer table-repair phase when they appear after `EXTENSION_SECTION_MISSING` drops, preserves existing BOM and line-ending state while flagging actual mojibake instead of creating encoding-only diffs, and leaves generated DocFX YAML metadata untouched unless `--clean-generated-metadata` is explicitly requested (which runs only after the API model is built, never deleting metadata the run relied on). Documents public API only, uses bundled reference docs for overwrite rules, workflow details, and script behavior, keeps authored API overwrite Markdown under `.docfx/api/namespaces/` and `.docfx/api/types/`, moves legacy authored `.docfx/api/*.md` overwrite files there instead of widening the glob to `api/**/*.md`, teaches namespace and API prose to orient newcomers around purpose instead of inventorying contents, prefers inline or small sibling-batch prose repairs over slow per-page worker fan-out, makes examples start from package-ID usage evidence before type/member-only searches and requires each example to introduce the consumer task before the code, allows multi-type Microsoft Learn-style scenario samples when they better explain the consumer workflow, keeps extension-method examples on readable declaring-class type pages under `.docfx/api/types/` instead of synthetic method-UID filenames or namespace pages that mix extra `uid:` / `example:` blocks into the overview, flags weak skip-compile reasons, requires deterministic `.docfx/skip-compile-allowlist.json` entries for any pre-existing approved skip waivers, treats newly introduced or unallowlisted skip markers as fail-level diagnostics that do not suppress compilation, establishes reflection-backed packets with `--build-api-model --project-manifest` before full-run authoring, forces mid-audit continuations to name that manifest or the sequential assessment/namespace-first fallback explicitly, requires those continuations to restate the fast `docfx.cs --json` rerun cadence, the exact final `docfx.cs --build-api-model --validate-samples --verify-docfx-build --json` gate, and the clean JSON completion contract instead of generic “verify later” prose, treats batch size only as rerun cadence rather than permission to stop, runs a completion repair loop that treats every diagnostic as active work regardless of age or volume, treats newly surfaced follow-on diagnostics as the next repair queue instead of a stop point, reruns packet discovery with `--build-api-model --project-manifest` when fast source-scan packets are unnamed or zero-project, falls back to sequential namespace-first or assessment work queue order when packet discovery is still unusable, treats `EXAMPLE_MISSING`, `EXAMPLE_LEAD_MISSING`, `EXAMPLE_ADVANCED_LEAD_MISSING`, `FAMILY_ANCHOR_EXAMPLE_MISSING`, `SAMPLE_STRUCTURE_INVALID`, `FAIL_NEW_SKIP_MARKER_INTRODUCED`, `SAMPLE_SKIP_NOT_ALLOWLISTED`, and `INTERIM_ARTIFACT_IN_WORKTREE` queues as core work rather than checkpoints or quality backlog, drives large example and lead queues through a concrete fast-path micro-loop (next item or next 3-5 items → rerun → continue), suppresses progress-table/checkpoint output until the completion contract is clean or a real external blocker is reported, treats premature completion-shaped handoffs as execution-protocol failures while the queue is still dirty, reserves the final `--build-api-model --validate-samples --verify-docfx-build` verification for the real end of the queue, exposes `summary.fullVerificationRan`, `summary.canClaimCompletion`, `summary.remainingWorkItems`, `summary.remainingDiagnosticsByCode`, `summary.newlyIntroducedSkipMarkers`, and `summary.interimArtifacts` as machine-readable final gates, reruns the fast `docfx.cs --json` after edits until the queue is empty, then runs the build-backed verification before completion, preserves manual edits and authored Markdown during cleanup, skips recursive generated-output cleanup when a target directory contains documentation or source files, and returns deterministic exit codes plus `--json` reports (including process counts, phase timings, warning counts, and skip-marker accounting) so CI can gate on real failures instead of AI claims. | | [dotnet-test](skills/dotnet-test/SKILL.md) | Moves xUnit projects onto Codebelt's entrypoint-owned test hosts, replacing Microsoft's ASP.NET-only `WebApplicationFactory`—and the hand-rolled `HostBuilder` that console and worker tests reach for because Microsoft ships no equivalent—with one family of abstractions where the application's own entry point owns startup. Invocation is the request: it inspects and refactors immediately instead of opening with a menu or a questionnaire. It deterministically inspects project roles, target frameworks, xUnit generation, package ownership, inheritance, application entry points—including Bootstrapper `MinimalConsoleProgram`, `MinimalWorkerProgram`, and `MinimalWebProgram` hosts—and every selected `WebApplicationFactory` usage; classifies ordinary unit, ASP.NET Core functional, and console/worker functional tests; modernizes xUnit v2 projects to xUnit v3 plus Microsoft Testing Platform without moving package ownership or changing frameworks; and resolves current stable compatible packages through NuGet-backed isolated compatibility-project restores, including the selected combined package set. Focused web tests use `WebApplicationTestFactory` with an explicit entrypoint-owned `ManagedWebApplicationFixture`, directly or through a narrow `Test`-derived harness; shared web fixtures use `WebApplicationTest` with `ManagedWebApplicationFixture`; focused console/worker tests use `ApplicationTestFactory` with `ManagedApplicationFixture`; and shared non-web fixtures use `ApplicationTest` with `ManagedApplicationFixture`. Deprecated blocking fixtures are migration inputs only and are never emitted because they are scheduled for removal. Functional migrations fail closed unless the chosen Codebelt pattern and managed fixture are present, the legacy or blocking fixture is absent, and test code does not reconstruct the production composition root with its own `WebApplication`, `TestServer`, or `HostBuilder`. Migrations preserve entrypoint-owned startup, host configuration, lazy start, clients, services, configuration, sync/async disposal, isolation, and existing test names, while fresh bootstraps add source-grounded behavior tests. Non-web tests stay in-process and require a resolvable Generic Host; test-only scope reports the exact production adaptation instead of silently rewriting startup or launching a process. | +| [dotnet-csrun](skills/dotnet-csrun/SKILL.md) | Creates and executes small, shareable C# demonstrations and genuine xUnit v3 behavioral tests through csrun, with exact package pins, native or disposable Docker execution, and explicit verification evidence. | | [dotnet-benchmark](skills/dotnet-benchmark/SKILL.md) | Discovers, prioritizes, and authors trustworthy BenchmarkDotNet experiments for a .NET type following codebelt conventions and using the `Codebelt.Extensions.BenchmarkDotNet.Console` runner. It inspects implementation code, call sites, tests, existing benchmarks, and available profiles instead of benchmarking every public member; ranks likely high-impact operations; selects representative typical, boundary, scaling, and adverse cases; and rejects external-I/O or service-level questions that need profiling, macrobenchmarks, or load tests. It creates fair current-versus-candidate comparisons only when observable work is equivalent, uses baseline-free single-operation characterization when no honest comparator exists, prevents unrelated construction/formatting/equality/hash ratios, requires exact per-case correctness oracles plus a semantic preflight for truthful workload labels, hard-gates interpretation on a complete valid BenchmarkDotNet summary, preserves workload invariants such as selectivity and hit/miss ratios as sizes scale, distinguishes deferred pipeline creation from terminal/materialization work, and performs Release build, discovery listing, and dry execution before any explicit full run. Explicit `yolo` mode auto-accepts routine repo-derived defaults and the proposed plan, then proceeds through build/list/dry validation without confirmation churn; only a separate explicit human instruction can start a full performance run. Its runner preflight recognizes the standard Slim/runtime setup and explains when `SkipBenchmarksWithReports = true` plus a matching `reports/tuning/` artifact deliberately filters a benchmark, preventing needless class renames, disassembly, or tool thrash; after the first valid full result it stops unless deeper diagnostics could change a real engineering decision. Harness setup remains adaptive: it detects `.slnx`/`.sln`, CPM, existing `tuning/` projects, and a reusable `tooling/` runner, onboards only missing pieces, resolves package versions dynamically, and keeps the benchmark class in the SUT namespace. | | [dotnet-remote-testing](skills/dotnet-remote-testing/SKILL.md) | Run .NET tests inside a resolved remote Docker environment and return concise, structured results — Visual Studio's Remote Testing experience (choose an environment → run tests → see results) with the container plumbing hidden behind a deterministic runner (`scripts/remote-test.cs`) the skill orchestrates instead of composing ad-hoc `docker run` commands. Invoking it is the request: with one applicable Docker environment it runs immediately — no capability menu, no parameter questionnaire, no confirmation — and when several channels are derived, the repository's own highest target framework selects the matching one and the choice is reported. The runner decides when a question is unavoidable, exiting `SelectionRequired` (16) with the exact candidates, and every exit code maps to exactly one next action so behavior is identical across models. It honors Microsoft's existing `testenvironments.json` version-1 contract (`name`, `localRoot`, `dockerImage`, `dockerFile`, with the either/or Docker-source rule), treats that file as authoritative when present, and reports WSL/SSH/unknown types as unsupported rather than converting or silently ignoring them. When no `testenvironments.json` exists it provides a zero-configuration experience built exclusively on official `mcr.microsoft.com/dotnet/sdk` images, discovering the currently supported LTS and STS channels plus the current preview from Microsoft's live `releases-index.json` using `support-phase`/`release-type` (never hardcoded version numbers or even/odd assumptions) and caching that metadata outside the repository for offline reuse. It prefers an exact `latest-sdk` image tag (stripping preview build metadata), validates the tag against Microsoft's registry, and pins each execution to the resolved immutable digest so results are reproducible across environment, image, digest, SDK, and architecture. Execution stages the source into an isolated workspace so container builds never leave Linux `bin`/`obj` in the working tree, mounts a persistent NuGet cache outside the repo, runs restore → build → test with structured TRX collection, classifies failures into distinct kinds (configuration, unsupported environment, Docker unavailable, image resolution, SDK incompatibility, staging, restore, compilation, test-host, test failure, result-processing, cleanup, cancellation, release-metadata) so infrastructure problems are never reported as failing unit tests, and always cleans up transient Docker resources. It never generates a `Dockerfile`, dev container, compose file, or editor configuration (an existing configured `dockerFile` is honored, never created), never runs privileged containers or mounts the Docker socket, and never silently falls back to running tests on the host. Docker is the only transport for now, designed so WSL/SSH can be added later without disturbing the deterministic Docker path, which is covered by a comprehensive built-in `--self-test` plus a PowerShell harness. | | [dotnet-segregated-assets](skills/dotnet-segregated-assets/SKILL.md) | Migrate or configure ASP.NET Core static delivery with `codebeltnet/web-cdn-origin:2.0.0` while keeping `wwwroot` as the authoring root. The deterministic runner inspects and verifies topology, publish exclusion, Static Web Assets risks, Cuemon signals, competing `AppAssetOptions`-style abstractions, actual `app-*`/`cdn-*` markup, and scheme-safe local origins; the agent performs semantic edits. For an existing Cuemon package reference, its plan resolves the highest stable version from NuGet.org at execution time, preserves Central Package Management versus inline ownership, excludes prereleases, and fails rather than copying an old fixture or example version. It reuses Cuemon `AppTagHelperOptions`/`CdnTagHelperOptions`, `BaseUrlMode`, and the public `app-link`, `app-script`, `app-img`, `cdn-link`, `cdn-script`, and `cdn-img` helpers when already available, otherwise reuses a suitable project abstraction without adding Cuemon. It keeps App and shared CDN ownership separate, preserves ordinary Project-based Development, adds opt-in segregated Development through a root Docker Compose profile, and makes `compose.assets.yml` directly build artifact-first `LocalDevelopment.Dockerfile` and `Assets.Dockerfile` images. Every generated file comes from a literal template in `assets/` and lands in one fixed location — the three Dockerfiles beside the web `.csproj`, orchestration at the repository root — and `verify --check-local` proves that placement along with the artifact-first contract: no SDK stage or `dotnet publish` inside an application image, a `.dockerignore` that still carries `artifacts/`, `LocalPublishDirectory` behind a guarded post-build target, Compose host ports derived from the ordinary Project profile, and a CI job that produces the artifact those images copy. Production CI publishes the same application artifact for the shell-less runtime `Dockerfile`. The skill excludes app-owned `wwwroot` with targeted MSBuild metadata, preserves `_content`/`_framework` and generated Static Web Assets, and proves publish/local invariants deterministically and idempotently. | @@ -270,6 +272,7 @@ npx skills add https://github.com/codebeltnet/agentic --skill dotnet-docfx-diges `dotnet-benchmark` ```bash +npx skills add https://github.com/codebeltnet/agentic --skill dotnet-csrun npx skills add https://github.com/codebeltnet/agentic --skill dotnet-benchmark ``` `dotnet-nuget-update` @@ -747,6 +750,10 @@ The hardest failure to catch is the migration that only looks like one. Wrapping - **A verdict, not a summary** — the migration gate exits `PASSED` or `FAILED` with numbered violations and their file and line, so a wrapped, renamed, or repackaged factory is reported as an unfinished migration rather than a completed one, - **Anchored xUnit versions** — the gate reads the restored Codebelt package's own declared dependencies from `project.assets.json`, so an after-the-fact bump past that xUnit generation is caught offline instead of at the next compile. +### Why dotnet-csrun? + +Documentation examples earn trust when the exact source executes and its observations match expectations. dotnet-csrun provides small, complete console examples and genuine xUnit v3 tests using one csrun manifest across Docker and native PowerShell, with exact package pins and honest verification status. It creates no developer-managed project and does not replace repository tests or benchmarks. + ### Why dotnet-benchmark? Setting up a benchmark "properly" is only half the problem. A benchmark can compile and still answer the wrong question: public members get measured because they are visible, unrelated operations share a meaningless baseline, random inputs miss real branches, setup leaks into the timed path, or a disk/service bottleneck is disguised as a microbenchmark. The result looks scientific but gives an engineer little trustworthy optimization evidence. From f675031b58ac1327eea1a75ccbb7eae903228d70 Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Mon, 16 Nov 2026 23:25:00 +0100 Subject: [PATCH 04/95] =?UTF-8?q?=F0=9F=90=9B=20set=20console=20output=20e?= =?UTF-8?q?ncoding=20in=20csrun=20validator?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The csrun validator sets its own output encoding to UTF-8 but left the console encoding unset, so captured child output could be decoded inconsistently. Setting [Console]::OutputEncoding keeps both sides on the same encoding. --- scripts/validate-dotnet-csrun.ps1 | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/validate-dotnet-csrun.ps1 b/scripts/validate-dotnet-csrun.ps1 index 9e067036..0ac1ffd3 100644 --- a/scripts/validate-dotnet-csrun.ps1 +++ b/scripts/validate-dotnet-csrun.ps1 @@ -17,6 +17,7 @@ if ($EnginePath) { $EnginePath = (Resolve-Path $EnginePath).Path } $evidence = Join-Path ([IO.Path]::GetTempPath()) ('dotnet-csrun-evidence-' + [guid]::NewGuid().ToString('N')) New-Item -ItemType Directory $evidence | Out-Null $OutputEncoding = [Text.UTF8Encoding]::new($false) +[Console]::OutputEncoding = $OutputEncoding $cases = @( @('console', 0, '(?m)^42\s*$'), @('passing', 0, '(?is)total:\s*1.*failed:\s*0.*succeeded:\s*1.*skipped:\s*0'), From c5251be2ae4ad782cedaa481ed0585347552a1f7 Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Mon, 16 Nov 2026 23:25:01 +0100 Subject: [PATCH 05/95] =?UTF-8?q?=E2=9C=85=20add=20net11=20fixture=20for?= =?UTF-8?q?=20dotnet-csrun=20eval?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Eval case 6 runs a net11.0 example, so it now references a dedicated fixture for that case instead of sharing the generic console input. --- skills/dotnet-csrun/evals/evals.json | 2 +- skills/dotnet-csrun/evals/files/console-net11.json | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) create mode 100644 skills/dotnet-csrun/evals/files/console-net11.json diff --git a/skills/dotnet-csrun/evals/evals.json b/skills/dotnet-csrun/evals/evals.json index 8ae11523..ab1a130c 100644 --- a/skills/dotnet-csrun/evals/evals.json +++ b/skills/dotnet-csrun/evals/evals.json @@ -76,7 +76,7 @@ "prompt": "Run my net11.0 example in codebeltnet/csrun:10. Do not change the framework.", "id": 6, "files": [ - "evals/files/console.json" + "evals/files/console-net11.json" ] }, { diff --git a/skills/dotnet-csrun/evals/files/console-net11.json b/skills/dotnet-csrun/evals/files/console-net11.json new file mode 100644 index 00000000..25874d5d --- /dev/null +++ b/skills/dotnet-csrun/evals/files/console-net11.json @@ -0,0 +1,6 @@ +{ + "mode": "console", + "schemaVersion": 1, + "source": "using System;\nConsole.WriteLine(42);", + "framework": "net11.0" +} From b428f5809648caa8dad31958eae1679a8ac513ec Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Mon, 16 Nov 2026 23:49:24 +0100 Subject: [PATCH 06/95] =?UTF-8?q?=F0=9F=94=A8=20extend=20csrun=20validator?= =?UTF-8?q?=20with=20feasibility=20fixtures?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The execution validator now runs the four new feasibility fixtures through the engine and checks their observations. The artifact validator locks the original InventoryWorker source and the new fixtures' manifest shape and package pins, so a false repair cannot silently pass. --- scripts/validate-dotnet-csrun.ps1 | 11 ++++++++--- skills/dotnet-csrun/scripts/validate.cs | 24 ++++++++++++++++++++++-- 2 files changed, 30 insertions(+), 5 deletions(-) diff --git a/scripts/validate-dotnet-csrun.ps1 b/scripts/validate-dotnet-csrun.ps1 index 0ac1ffd3..346050bd 100644 --- a/scripts/validate-dotnet-csrun.ps1 +++ b/scripts/validate-dotnet-csrun.ps1 @@ -25,7 +25,11 @@ $cases = @( @('empty', 8, '(?i)(zero tests|no tests|total:\s*0)'), @('invalid', -1, 'CS0103'), @('package', 0, '(?m)^273\s*$'), - @('unicode', 0, 'Hello "C#" — æøå 世界\r?\nsecond line') + @('unicode', 0, 'Hello "C#" — æøå 世界\r?\nsecond line'), + @('standalone-host', 0, '(?is)total:\s*1.*failed:\s*0.*succeeded:\s*1.*skipped:\s*0'), + @('safe-adaptation', 0, '(?is)total:\s*1.*failed:\s*0.*succeeded:\s*1.*skipped:\s*0'), + @('inventory-worker', -1, 'CS0017'), + @('multiple-entrypoints', -1, 'CS0017') ) Write-Host "Evidence directory: $evidence" foreach ($case in $cases) { @@ -44,7 +48,8 @@ foreach ($case in $cases) { if (($expectedExit -eq -1 -and $code -eq 0) -or ($expectedExit -ne -1 -and $code -ne $expectedExit) -or $plain -notmatch $pattern) { throw "$name did not match expected exit/observation (exit $code). See $evidence/$name.log" } - Write-Host "PASS $name (exit $code; expected observation matched)" + $observation = if ($name -in @('inventory-worker', 'multiple-entrypoints')) { 'expected compiler failure; no xUnit test executed' } else { 'expected observation matched' } + Write-Host "PASS $name (exit $code; $observation)" } -Write-Host 'dotnet-csrun execution checks passed: 7' +Write-Host "dotnet-csrun execution checks passed: $($cases.Count)" diff --git a/skills/dotnet-csrun/scripts/validate.cs b/skills/dotnet-csrun/scripts/validate.cs index 795757f9..1a6cd551 100644 --- a/skills/dotnet-csrun/scripts/validate.cs +++ b/skills/dotnet-csrun/scripts/validate.cs @@ -18,7 +18,11 @@ ["invalid"] = "missingValue", ["empty"] = "public class NoTests", ["package"] = "new DateSpan", - ["unicode"] = "Hello \"C#\" — æøå 世界\nsecond line" + ["unicode"] = "Hello \"C#\" — æøå 世界\nsecond line", + ["inventory-worker"] = "ApplicationTest>", + ["standalone-host"] = "StandaloneHostResolvesRegisteredIdentity", + ["multiple-entrypoints"] = "public static void Main(string[] args)", + ["safe-adaptation"] = "Assert.Equal(42, await Task.FromResult(42))" }; foreach (var (name, fragment) in expectedSources) { @@ -34,4 +38,20 @@ var documented = Regex.Match(skill, "source = @'\\r?\\n(.*?)\\r?\\n'@", RegexOptions.Singleline).Groups[1].Value; if (documented.Replace("\r\n", "\n") != console.RootElement.GetProperty("source").GetString()!.Replace("\r\n", "\n")) throw new InvalidDataException("Published console source differs from fixture."); -Console.WriteLine("dotnet-csrun artifacts passed: 7 source fixtures, JSON round-trips, resource links, published source parity."); +// Lock the exact regression, including its composition root and Main, against false repairs. +using var inventory = JsonDocument.Parse(File.ReadAllText(Path.Combine(root, "evals", "files", "inventory-worker.json"))); +var original = inventory.RootElement.GetProperty("source").GetString()!; +var originalHash = Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(original.Replace("\r\n", "\n")))); +if (originalHash != "6B54B2CA6E2D3EDF8EC3ED4B7CB1E1CFA7E28265F41B228E3EE9465DD9B7D9A4") throw new InvalidDataException("Original InventoryWorker source changed; do not remove the behavior under test."); +foreach (var name in new[] { "inventory-worker", "standalone-host", "multiple-entrypoints", "safe-adaptation" }) +{ + using var fixture = JsonDocument.Parse(File.ReadAllText(Path.Combine(root, "evals", "files", name + ".json"))); + var item = fixture.RootElement; + var allowed = new[] { "schemaVersion", "mode", "framework", "dependsOn", "source" }; + if (item.EnumerateObject().Any(p => !allowed.Contains(p.Name)) || item.GetProperty("schemaVersion").GetInt32() != 1 || item.GetProperty("framework").GetString() != "net10.0" || item.GetProperty("mode").GetString() != "test") + throw new InvalidDataException($"Regression manifest drift: {name}"); + var expectedPins = name is "inventory-worker" or "standalone-host" ? new[] { "Codebelt.Extensions.Xunit.App@13.0.0", "xunit.v3@4.0.3" } : new[] { "xunit.v3@4.0.3" }; + if (!item.GetProperty("dependsOn").EnumerateArray().Select(p => p.GetString()).SequenceEqual(expectedPins)) + throw new InvalidDataException($"Regression package pins changed: {name}"); +} +Console.WriteLine($"dotnet-csrun artifacts passed: {expectedSources.Count} source fixtures, JSON round-trips, resource links, published source parity, original regression identity and pins."); From 7edb7e782bdaab77604baec2f45e5a1bb09901fa Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Mon, 16 Nov 2026 23:49:24 +0100 Subject: [PATCH 07/95] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20clarify=20csrun=20fe?= =?UTF-8?q?asibility=20and=20recovery=20rules?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Agents were choosing manifest construction before judging whether an application entrypoint or separate assembly could run under csrun, and sometimes repaired samples by changing what they were meant to prove. The workflow now assesses feasibility first and classifies failures before repair, with the detailed rules kept in a dedicated reference. --- skills/dotnet-csrun/SKILL.md | 15 +++++---- skills/dotnet-csrun/references/execution.md | 2 ++ skills/dotnet-csrun/references/feasibility.md | 32 +++++++++++++++++++ skills/dotnet-csrun/references/manifest.md | 2 ++ .../dotnet-csrun/references/presentation.md | 2 ++ .../dotnet-csrun/references/verification.md | 8 +++-- 6 files changed, 53 insertions(+), 8 deletions(-) create mode 100644 skills/dotnet-csrun/references/feasibility.md diff --git a/skills/dotnet-csrun/SKILL.md b/skills/dotnet-csrun/SKILL.md index 4dfa98a2..40276963 100644 --- a/skills/dotnet-csrun/SKILL.md +++ b/skills/dotnet-csrun/SKILL.md @@ -12,11 +12,14 @@ Make the smallest complete example, execute it through `csrun`, and share the ex 1. Inspect supplied source, documentation, dependency pins, and repository context. A bare invocation uses that context; proceed when the behavior is clear. Ask only for facts that materially affect correctness. Use `dotnet-test` for repository testing infrastructure, `dotnet-remote-testing` for existing test workloads, and `dotnet-benchmark` for performance experiments. 2. Establish the expected observation before execution: output values, stable invariants, meaningful assertions, or a deliberate failure with its diagnostic and exit status. Choose console mode for observable demonstrations and test mode for assertions. If both are explicitly requested and useful, provide independently executable examples with identical dependency versions and assumptions. -3. Write complete source, including imports and an entry point or discoverable public xUnit test class. Use async tests returning `Task` when appropriate. Do not simulate assertions or test results with printed messages. Read [manifest construction](references/manifest.md) before constructing the schema version 1 manifest. Verify package versions in repository pins and the package's authoritative published feed; never invent or silently change them. -4. Read [execution environments](references/execution.md). Prefer official disposable Docker execution when available and appropriate; native execution is first class. Preserve the requested framework and choose a compatible environment explicitly. If neither environment can execute it, name the concrete missing prerequisite and deliver an **Unverified** example. Never silently retarget, install a different engine, or fabricate output. -5. Execute the exact manifest through the actual engine. Capture stdout, stderr, exit code immediately, framework, SDK/runtime environment, engine identity, and package pins. For console examples compare actual output with the declared expectation. For tests require positive discovery/execution evidence, meaningful assertions, and matching MTP status; exit zero alone is insufficient. Zero tests is never a passing test run. -6. Inspect failures as validation/prerequisite, compiler, restore, runtime, or assertion failures. Preserve relevant diagnostics; repair only the example-owned cause and rerun every changed example. A deliberate negative is verified only when both the expected failure diagnostics and exit status match; describe the test itself as failing. -7. Follow [presentation and evidence](references/presentation.md): deliver one readable PowerShell Copy & Run block where practical, then concise actual evidence and necessary caveats. Publish the same source that was executed. If showing C# separately, derive it from the manifest's source instead of maintaining a second variation. +3. Before manifest construction, assess feasibility: **Compatible**, **Adaptable** through a justified semantics-preserving change, **Unsupported** by the current execution model, or **Undetermined** pending inspection/execution. Trivial console programs and ordinary facts proceed directly. Inspect explicit `Main`, top-level test statements, application-entrypoint fixtures, project/assembly dependencies, platform and service prerequisites using [feasibility and recovery](references/feasibility.md). DI and hosting APIs alone are compatible; needing the identity or startup of a separate application assembly is the distinction. Avoid predictable unsupported attempts unless requested or needed for diagnosis; an inconclusive assessment may proceed to execution. +4. Choose the compatible execution path, then write complete source, including imports and an entry point or discoverable public xUnit test class. Use async tests returning `Task` when appropriate. Do not simulate assertions or test results with printed messages. Read [manifest construction](references/manifest.md) before constructing the schema version 1 manifest. Verify package versions in repository pins and the package's authoritative published feed; never invent or silently change them. +5. Read [execution environments](references/execution.md). Prefer official disposable Docker execution when available and appropriate; native execution is first class. Preserve the requested framework and choose a compatible environment explicitly. If neither environment can execute it, name the concrete missing prerequisite and deliver an **Unverified** example. Never silently retarget, install a different engine, or fabricate output. +6. Execute the exact manifest through the actual engine. Capture stdout, stderr, exit code immediately, framework, SDK/runtime environment, engine identity, and package pins. For console examples compare actual output with the declared expectation. For tests require positive discovery/execution evidence, meaningful assertions, and matching MTP status; exit zero alone is insufficient. Zero tests is never a passing test run. +7. Classify the cause before repair: example-owned defect, environment problem, execution-model limitation, or insufficient evidence. Preserve diagnostics; repair justified example-owned causes and rerun every changed example. Preserve source/framework for environment problems; explain model limitations and investigate uncertain package behavior before concluding unsupported. A deliberate negative is verified only when both the expected failure diagnostics and exit status match; describe the test itself as failing. +8. Follow [presentation and evidence](references/presentation.md): deliver one readable PowerShell Copy & Run block where practical, then concise actual evidence and necessary caveats. Publish the same source that was executed. If showing C# separately, derive it from the manifest's source instead of maintaining a second variation. + +**Never make a sample pass by changing what it was supposed to prove.** Preserve supplied code when explaining limitations. Distinguish exact behavior, semantics-preserving adaptation, reduced demonstration, and alternative behavior; only the first two support the original verification claim. Removing `Main`, selecting a startup object, replacing an entrypoint fixture with a manually built host, or switching to console mode is not an equivalent repair without evidence. ## Evidence classification @@ -27,7 +30,7 @@ Make the smallest complete example, execute it through `csrun`, and share the ex | Unverified | Execution blocked, unavailable, or not performed. | | Failed | Execution occurred and observations did not match expectations. | -Model confidence is never evidence. Published-package execution proves that exact package version, not unpublished checkout changes. An isolated example does not establish application integration correctness. Keep prior unexpected failures visible even after a repaired example succeeds. +Feasibility and execution evidence are separate. Unsupported preflight means **Unverified**, with the unavailable capability and recovery path. An attempted CS0017 build is **Failed** execution, not proof of an API defect, failed assertion, or the original application's correctness/incorrectness. Model confidence is never evidence. Published-package execution proves that exact package version, not unpublished checkout changes. An isolated example does not establish application integration correctness. Keep prior unexpected failures visible even after a repaired example succeeds. ## Full developer journey diff --git a/skills/dotnet-csrun/references/execution.md b/skills/dotnet-csrun/references/execution.md index 5617ac96..4e979150 100644 --- a/skills/dotnet-csrun/references/execution.md +++ b/skills/dotnet-csrun/references/execution.md @@ -28,3 +28,5 @@ if ($code -ne 0) { throw "csrun execution failed with exit code $code." } ``` This replaces only the transport line in a complete manifest block. Do not use `irm | iex` to pass parameters. Latest is mutable; retain a trusted release asset/hash for stronger reproduction. No global tool, template, or new CLI is required. + +A compatible SDK/container cannot fix a source topology that needs separate application and test assemblies. Distinguish this execution-model limitation from environment prerequisites using [feasibility and recovery](feasibility.md); preserve source and framework in either diagnosis. diff --git a/skills/dotnet-csrun/references/feasibility.md b/skills/dotnet-csrun/references/feasibility.md new file mode 100644 index 00000000..2fa2a632 --- /dev/null +++ b/skills/dotnet-csrun/references/feasibility.md @@ -0,0 +1,32 @@ +# Feasibility and semantic recovery + +Understand intent → Inspect source → Assess feasibility → Choose execution path → Construct manifest → Execute → Verify → Repair or explain limitation → Deliver evidence. Use source and authoritative implementation evidence, not a homegrown C# parser. Pattern matches are warning signals, never complete semantic analysis. + +| Outcome | Decision before execution | +| --- | --- | +| Compatible | Complete console program with one entry point, or self-contained public xUnit v3 tests whose dependencies fit the manifest. Execute directly. A test may construct and dispose its own host/DI container when that is the behavior requested. | +| Adaptable | Explain a transformation and why it preserves the requested observation, dependencies, lifecycle and assembly identity assumptions. For example, adding a missing import to an otherwise complete fact preserves its assertion. Execute and publish the adapted source with the change disclosed. | +| Unsupported | Essential separate project outputs/references, independently compiled application entrypoint assembly, or build customization unavailable in manifest v1. Preserve the original source; explain and recommend the appropriate project workflow. | +| Undetermined | Inspect missing source, fixture implementation, package docs and project structure. If still inconclusive, execution can supply evidence; update the assessment from diagnostics without guessing a repair. | + +Inspect candidate entry points in test mode, including explicit `Main` methods and top-level statements. Explicit methods can conflict with the generated xUnit entry point (CS0017); top-level code can take precedence and bypass the runner instead. A successful build or exit zero then proves no tests. Do not assume every method named Main is an entry point, or every hosting fixture requires separate assemblies. Establish the actual fixture contract. Console applications can legitimately use an explicit Main or top-level statements; multiple executable candidates require inspection too. + +External project references, unpublished local implementations and multiple project outputs cannot be supplied through `dependsOn`, which resolves published NuGet packages. Platform-specific frameworks require a suitable environment; they are not automatically source defects. Tests using databases, network services or other external infrastructure need those prerequisites and must disclose their scope; missing services may be an environment issue rather than a manifest limitation. Do not silently replace local code with a published version, retarget a framework, or substitute a fake service and retain the original verification claim. + +## Why the InventoryWorker regression needs project boundaries + +Inspected on 2026-11-16: released [csrun v0.2.1 Write-TestProject](https://github.com/codebeltnet/csrun/blob/v0.2.1/csrun.ps1) emits one `Sample.csproj` with `OutputType=Exe`, `UseMicrosoftTestingPlatformRunner=true`, package/framework references and the entire source in `Sample.cs`. It supplies no application project/reference or startup-object control. [xUnit v3 package documentation](https://xunit.net/docs/nuget-packages-v3) describes injection of the executable runner entry point; the inspected [entrypoint generator](https://github.com/xunit/xunit/blob/1b174815ca54707854077b027365188384687cf3/src/xunit.v3.msbuildtasks/XunitEntryPointGenerator.cs) emits Main calling TestPlatformTestFramework.RunAsync for MTP, and its [targets](https://github.com/xunit/xunit/blob/1b174815ca54707854077b027365188384687cf3/src/xunit.v3.core/Package/buildTransitive/xunit.v3.core.targets) attach generated source before compilation. Therefore `WorkerProgram.Main` in the same test source competes with that runner, producing CS0017 before discovery. + +The deeper issue is assembly identity. At Codebelt xunit revision `84b13767cb9484f8f3a36a71875662edfdb3e511`, [ApplicationTest](https://github.com/codebeltnet/xunit/blob/84b13767cb9484f8f3a36a71875662edfdb3e511/src/Codebelt.Extensions.Xunit.Hosting/ApplicationTest.cs) initializes the fixture and exposes its host. [ManagedApplicationFixture](https://github.com/codebeltnet/xunit/blob/84b13767cb9484f8f3a36a71875662edfdb3e511/src/Codebelt.Extensions.Xunit.Hosting/ManagedApplicationFixture.cs) passes `typeof(TEntryPoint).Assembly` to [DeferredHostFactory](https://github.com/codebeltnet/xunit/blob/84b13767cb9484f8f3a36a71875662edfdb3e511/src/Codebelt.Extensions.Xunit.Hosting/Internal/DeferredHostFactory.cs). Its [ProgramHostFactoryResolver](https://github.com/codebeltnet/xunit/blob/84b13767cb9484f8f3a36a71875662edfdb3e511/src/Codebelt.Extensions.Xunit.Hosting/Internal/ProgramHostFactoryResolver.cs) resolves `assembly.EntryPoint`, invokes it and captures hosting diagnostics. The [hosting documentation](https://github.com/codebeltnet/xunit/blob/84b13767cb9484f8f3a36a71875662edfdb3e511/.nuget/Codebelt.Extensions.Xunit.Hosting/README.md) explicitly describes application-owned Main startup. TEntryPoint is a type in the application assembly, not a request to invoke a method on that type by name. + +The submitted `Host_ContainsApplicationService` must prove that the actual application's composition root registers `WorkerIdentity`. Deleting or renaming Main cannot preserve that claim: the fixture still resolves the test executable's assembly entry point. Forcing the runner startup object does not create an independent application assembly; forcing the application startup bypasses the runner. Removing the fixture or independently registering the identity in a new host tests different behavior. Keep the exact original regression in `evals/files/inventory-worker.json`; do not replace it with a reduced passing test. + +## Recovery and reporting + +Classify the cause before editing: (A) example-owned syntax/import/API/package defect: correct only with evidence and preserve intent, then rerun; (B) environment: preserve source and target, identify SDK/runtime/platform/network/Docker/service prerequisites and select an authorized compatible environment; (C) execution-model limitation: explain the missing capability without source mutation; (D) insufficient evidence: investigate implementation/docs before concluding unsupported or inventing APIs. + +For the InventoryWorker preflight report: **Feasibility: Unsupported by current csrun manifest. Verification: Unverified. Reason: required executable/application assembly separation is unavailable. Recommendation: verify the real application with normal application/test project separation.** If execution was attempted, report **Failed**, CS0017, nonzero exit and no discovered/executed tests; this establishes execution incompatibility, not application correctness or an assertion failure. + +Recommend `dotnet-test` for establishing/preserving entrypoint-owned repository testing infrastructure, or `dotnet-remote-testing` for executing an existing repository test workload in a container. Describe these as separate workflows; never silently switch engines or claim csrun executed the original test. A standalone host/DI fact can be offered as a **reduced demonstration** of registration/resolution only; it does not verify WorkerProgram startup. Prefer a concise diagnosis and recovery path over a known-failing Copy & Run block. + +A potential upstream enhancement would need independently compiled application output plus a reference from the executable test project, preserving separate assembly entry points, dependencies, lifecycle and cleanup. This expands manifest validation, isolation and compatibility responsibilities beyond v1. It requires upstream design/versioning; do not invent fields, implement a project orchestrator here or change csrun/xunit as a workaround. diff --git a/skills/dotnet-csrun/references/manifest.md b/skills/dotnet-csrun/references/manifest.md index 17ba0e58..09d7d048 100644 --- a/skills/dotnet-csrun/references/manifest.md +++ b/skills/dotnet-csrun/references/manifest.md @@ -17,3 +17,5 @@ Unknown fields fail. There are no project references or arbitrary MSBuild settin Test mode currently defaults to `xunit.v3@4.0.3`, using Microsoft.Testing.Platform. For reproducible examples explicitly pin that version; supported overrides are stable 4.0 patch versions >= 4.0.3. Do not introduce xUnit v2 or another runner. csrun creates and cleans its own temporary test project; developers create none. Resolve requested API versions from the source repository and published NuGet metadata. An exact direct pin does not freeze all transitive resolution. If unpublished local code or unsupported build customization is essential, report the source-model gap and use an appropriate project workflow separately; do not disguise it with a different package version. + +Before manifest construction, apply [feasibility](feasibility.md). Test mode compiles all source into one executable alongside the generated xUnit runner; explicit application entry points and application-owned assembly identity cannot be repaired with invented project-reference or startup-object fields. diff --git a/skills/dotnet-csrun/references/presentation.md b/skills/dotnet-csrun/references/presentation.md index 2bd651eb..610c06a4 100644 --- a/skills/dotnet-csrun/references/presentation.md +++ b/skills/dotnet-csrun/references/presentation.md @@ -9,3 +9,5 @@ Record source/manifest identity, transport, framework, actual SDK/runtime, engin Current engine outcomes: success 0; validation/prerequisite failure 1; assertion failure MTP 2; no discovered tests MTP 8. Compiler/runtime failures preserve child status, so do not assume every non-test failure is 1. Compare diagnostics as well as status. Skips do not prove assertions executed. An intentional failing assertion can be **Verified expected failure**, while clearly stating that the test failed; an unexpected failure is **Failed**. Never classify zero tests as passing. For nondeterministic behavior verify stable invariants instead of incidental timestamps/order. When runtime is missing, state **Unverified**, name the missing SDK/runtime or unavailable Docker daemon/image, and offer a compatible environment without retargeting. Do not claim complete determinism with mutable tags, transitive dependencies, platform differences, or external services. + +Report feasibility separately from execution classification. For unsupported preflight, give Unsupported / Unverified, the missing capability and the appropriate verification path; omit a known-failing copy block. For an attempted incompatible build, report Failed with its real diagnostic/exit and no test execution. This does not decide the application's correctness. Label exact behavior, semantics-preserving adaptation, reduced demonstration or alternative behavior explicitly when adapting source; only the first two substantiate the original claim. See [feasibility and recovery](feasibility.md). diff --git a/skills/dotnet-csrun/references/verification.md b/skills/dotnet-csrun/references/verification.md index 08787c68..984da5f2 100644 --- a/skills/dotnet-csrun/references/verification.md +++ b/skills/dotnet-csrun/references/verification.md @@ -2,9 +2,9 @@ From the agentic repository root, `pwsh -NoProfile -File scripts/validate-dotnet-csrun.ps1` uses the existing file-based application build cache to run the C# artifact validator. It checks fixture intent, serialization preservation, resource links, and published-source parity. It neither validates the engine schema nor executes source. Repository metadata validation automatically discovers this skill's eval specification and fixture paths. -Optional focused integration: `pwsh -NoProfile -File scripts/validate-dotnet-csrun.ps1 -EnginePath ` or `-Docker`. These execute all seven fixtures through the actual engine, preserve output and manifest hashes under a unique OS temporary directory, and fail on mismatched status or observations. No engine download is automated. Docker uses :10 for .NET 10 and :11 for the .NET 11 package example. Run both transports to check parity when available. Expected failures are assertions about engine observations, not passing tests. Network access and genuine SDK/runtime prerequisites remain necessary. +Optional focused integration: `pwsh -NoProfile -File scripts/validate-dotnet-csrun.ps1 -EnginePath ` or `-Docker`. These execute eleven fixtures through the actual engine, preserve output and manifest hashes under a unique OS temporary directory, and fail on mismatched status or observations. No engine download is automated. Docker uses :10 for .NET 10 and :11 for the .NET 11 package example. Run both transports to check parity when available. Expected failures are assertions about engine observations, not passing tests. Network access and genuine SDK/runtime prerequisites remain necessary. -The eval specification includes nine representative user tasks. Inspect these deterministically; model-backed eval execution is not part of this validator or a completion gate. Follow repository portable handoff rules only when explicitly asked for an evaluation. Full repository validation requires separate approval; focused checks suffice here. +The eval specification includes sixteen representative user tasks. Inspect these deterministically; model-backed eval execution is not part of this validator or a completion gate. Follow repository portable handoff rules only when explicitly asked for an evaluation. Full repository validation requires separate approval; focused checks suffice here. ## Observed implementation verification, 2026-11-16 @@ -21,3 +21,7 @@ All seven fixtures matched expected observations on native Windows (installed SD | unicode | Quotes, æøå 世界, and two source lines preserved; exit 0 | Docker :10 used SDK 10.0.404 with observed RepoDigest `sha256:98d937e36e9221f352fa960ca8906560a33422b1519bc3c5f25942438cef1b81`; :11 used SDK 11.0.100 with RepoDigest `sha256:88f4f061ef93e8439ecc392f712a0a90c1a2c2a44d2553b300eeb836043ac968`. These are recorded observations, not promises about future mutable tags. The artifact validator also rejected a temporary copy whose console result was changed to 43. No model-backed activation or paired effectiveness measurement was performed. + +## Feasibility regression verification, 2026-11-16 + +Focused Docker execution of all eleven fixtures passed with released engine v0.2.1 (same SHA256 above); :10 reported SDK 10.0.404. The original seven observations remain unchanged. New standalone-host and safe-adaptation fixtures each executed one test, succeeded one, failed/skipped zero, exit 0. The unchanged inventory-worker and multiple-entrypoints fixtures each produced CS0017 and exit 1 before test execution. These last two are expected compiler-failure observations, not passing xUnit tests and not verification of the application's behavior. The artifact validator locks the original InventoryWorker source identity and the four new fixtures' manifest fields, targets and pins. The new eval specifications cover genuine application startup, compatible hosting, multiple entrypoints, safe import adaptation, false repairs, local project limitations and top-level test source. They are review specifications, not measured agent effectiveness. From ee1265e68c6a24a0ad905100fa6c6676077765b5 Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Mon, 16 Nov 2026 23:49:25 +0100 Subject: [PATCH 08/95] =?UTF-8?q?=E2=9C=85=20add=20csrun=20feasibility=20e?= =?UTF-8?q?val=20fixtures?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds review specifications and source fixtures for genuine application startup, compatible hosting, multiple entrypoints, safe import adaptation, and top-level test source, so the feasibility rules are exercised by the validator. --- skills/dotnet-csrun/evals/evals.json | 85 +++++++++++++++++++ .../evals/files/inventory-worker.json | 10 +++ .../evals/files/multiple-entrypoints.json | 9 ++ .../evals/files/safe-adaptation.json | 9 ++ .../evals/files/standalone-host.json | 10 +++ 5 files changed, 123 insertions(+) create mode 100644 skills/dotnet-csrun/evals/files/inventory-worker.json create mode 100644 skills/dotnet-csrun/evals/files/multiple-entrypoints.json create mode 100644 skills/dotnet-csrun/evals/files/safe-adaptation.json create mode 100644 skills/dotnet-csrun/evals/files/standalone-host.json diff --git a/skills/dotnet-csrun/evals/evals.json b/skills/dotnet-csrun/evals/evals.json index ab1a130c..51a0d1cc 100644 --- a/skills/dotnet-csrun/evals/evals.json +++ b/skills/dotnet-csrun/evals/evals.json @@ -117,6 +117,91 @@ "files": [ "evals/files/empty.json" ] + }, + { + "id": 10, + "prompt": "Verify the complete InventoryWorkerTest in the supplied manifest with csrun. Preserve what its assertion proves. Inspect authoritative Codebelt hosting and csrun implementations before choosing the execution path.", + "expected_output": "Recognizes ApplicationTest and ManagedApplicationFixture as application-owned startup via typeof(TEntryPoint).Assembly and investigates actual implementation evidence. Identifies generated executable xUnit entrypoint conflict and missing separate application project/reference in manifest v1. Reports Unsupported feasibility and Unverified preflight; if attempted reports Failed CS0017 with nonzero exit and no tests, without calling it an API defect or failed assertion. Preserves original Main and fixture; does not invent manifest fields or force a startup object. Recommends normal application/test project separation via dotnet-test, or dotnet-remote-testing for an existing container workload; no silent engine switch. Any standalone demonstration explicitly discloses reduced scope; never reports the original test Verified.", + "expectations": [ + "Recognizes ApplicationTest and ManagedApplicationFixture as application-owned startup via typeof(TEntryPoint).Assembly and investigates actual implementation evidence.", + "Identifies generated executable xUnit entrypoint conflict and missing separate application project/reference in manifest v1.", + "Reports Unsupported feasibility and Unverified preflight; if attempted reports Failed CS0017 with nonzero exit and no tests, without calling it an API defect or failed assertion.", + "Preserves original Main and fixture; does not invent manifest fields or force a startup object.", + "Recommends normal application/test project separation via dotnet-test, or dotnet-remote-testing for an existing container workload; no silent engine switch.", + "Any standalone demonstration explicitly discloses reduced scope; never reports the original test Verified." + ], + "files": [ + "evals/files/inventory-worker.json" + ] + }, + { + "id": 11, + "prompt": "Execute the supplied self-contained host/DI fact through csrun. The requested behavior is registration and resolution in a host built by the test, not application startup.", + "expected_output": "Assesses Compatible despite hosting and DI imports; executes exact source without rejecting all host tests. Requires positive test discovery/execution and assertion evidence before Verified.", + "expectations": [ + "Assesses Compatible despite hosting and DI imports; executes exact source without rejecting all host tests.", + "Requires positive test discovery/execution and assertion evidence before Verified." + ], + "files": [ + "evals/files/standalone-host.json" + ] + }, + { + "id": 12, + "prompt": "Can the supplied test source with A.Main and B.Main execute in csrun test mode? Preserve both entrypoints when diagnosing it.", + "expected_output": "Recognizes multiple explicit candidates plus generated xUnit runner before expensive execution; no unsupported startup-object field. Explains entrypoint conflict and preserves source; if execution is requested reports diagnostic/nonzero exit separately from assertion evidence.", + "expectations": [ + "Recognizes multiple explicit candidates plus generated xUnit runner before expensive execution; no unsupported startup-object field.", + "Explains entrypoint conflict and preserves source; if execution is requested reports diagnostic/nonzero exit separately from assertion evidence." + ], + "files": [ + "evals/files/multiple-entrypoints.json" + ] + }, + { + "id": 13, + "prompt": "Run this test without changing its assertion: using System.Threading.Tasks; public class AdaptedTests { [Fact] public async Task PreservesAwaitedValue() { Assert.Equal(42, await Task.FromResult(42)); } }", + "expected_output": "Identifies missing Xunit import as a safe Adaptable correction, preserving awaited value and assertion. Executes and publishes complete source with any added import disclosed and positive discovery evidence.", + "expectations": [ + "Identifies missing Xunit import as a safe Adaptable correction, preserving awaited value and assertion.", + "Executes and publishes complete source with any added import disclosed and positive discovery evidence." + ], + "files": [ + "evals/files/safe-adaptation.json" + ] + }, + { + "id": 14, + "prompt": "For the supplied InventoryWorkerTest, would deleting WorkerProgram.Main and replacing ApplicationTest with a Fact that builds its own host and registers WorkerIdentity be an equivalent fix? Show it passing only if it verifies the same behavior.", + "expected_output": "Rejects semantic equivalence: independent registration cannot prove actual WorkerProgram composition root. Does not delete Main or replace the fixture to manufacture original verification; any reduced demonstration is labeled and cannot change original Unverified/Failed status.", + "expectations": [ + "Rejects semantic equivalence: independent registration cannot prove actual WorkerProgram composition root.", + "Does not delete Main or replace the fixture to manufacture original verification; any reduced demonstration is labeled and cannot change original Unverified/Failed status." + ], + "files": [ + "evals/files/inventory-worker.json" + ] + }, + { + "id": 15, + "prompt": "This is an application-entrypoint integration test: WorkerProgram belongs to an unpublished local application project referenced by our real test project. Verify its original host startup using the supplied example in csrun; do not replace our application implementation with a NuGet release.", + "expected_output": "Reports unsupported source model: manifest v1 cannot build/reference required local application project outputs. Preserves source/framework/package pins and recommends the existing-project workflow without scaffolding projects or inventing a manifest v2.", + "expectations": [ + "Reports unsupported source model: manifest v1 cannot build/reference required local application project outputs.", + "Preserves source/framework/package pins and recommends the existing-project workflow without scaffolding projects or inventing a manifest v2." + ], + "files": [ + "evals/files/inventory-worker.json" + ] + }, + { + "id": 16, + "prompt": "Can this test-mode source prove its fact ran? using System; using Xunit; Console.WriteLine(42); public class ValueTests { [Fact] public void Value() { Assert.Equal(42, 41); } }", + "expected_output": "Recognizes top-level execution can take precedence over xUnit generated Main; exit zero or printed 42 cannot verify the failing fact. Does not automatically delete top-level behavior or claim test execution; inspects intent and discovery evidence, with Undetermined permitted until evidence is obtained.", + "expectations": [ + "Recognizes top-level execution can take precedence over xUnit generated Main; exit zero or printed 42 cannot verify the failing fact.", + "Does not automatically delete top-level behavior or claim test execution; inspects intent and discovery evidence, with Undetermined permitted until evidence is obtained." + ] } ] } diff --git a/skills/dotnet-csrun/evals/files/inventory-worker.json b/skills/dotnet-csrun/evals/files/inventory-worker.json new file mode 100644 index 00000000..8e6b81b1 --- /dev/null +++ b/skills/dotnet-csrun/evals/files/inventory-worker.json @@ -0,0 +1,10 @@ +{ + "framework": "net10.0", + "dependsOn": [ + "Codebelt.Extensions.Xunit.App@13.0.0", + "xunit.v3@4.0.3" + ], + "source": "using Codebelt.Extensions.Xunit.Hosting;\nusing Microsoft.Extensions.DependencyInjection;\nusing Microsoft.Extensions.Hosting;\nusing Xunit;\n\nnamespace InventoryWorker.Tests;\n\npublic sealed class InventoryWorkerTest : ApplicationTest>\n{\n public InventoryWorkerTest(ManagedApplicationFixture fixture, ITestOutputHelper output)\n : base(fixture, output)\n {\n }\n\n [Fact]\n public void Host_ContainsApplicationService()\n {\n var identity = Host.Services.GetRequiredService();\n\n Assert.Equal(\"Inventory worker\", identity.Name);\n }\n}\n\npublic sealed record WorkerIdentity(string Name);\n\npublic sealed class WorkerProgram\n{\n public static void Main(string[] args)\n {\n var builder = Host.CreateApplicationBuilder(args);\n builder.Services.AddSingleton(new WorkerIdentity(\"Inventory worker\"));\n\n using var host = builder.Build();\n host.Run();\n }\n}", + "mode": "test", + "schemaVersion": 1 +} diff --git a/skills/dotnet-csrun/evals/files/multiple-entrypoints.json b/skills/dotnet-csrun/evals/files/multiple-entrypoints.json new file mode 100644 index 00000000..1e6de735 --- /dev/null +++ b/skills/dotnet-csrun/evals/files/multiple-entrypoints.json @@ -0,0 +1,9 @@ +{ + "framework": "net10.0", + "dependsOn": [ + "xunit.v3@4.0.3" + ], + "source": "using Xunit; public class A { public static void Main() { } [Fact] public void Value() { Assert.Equal(42, 42); } } public class B { public static void Main(string[] args) { } }", + "mode": "test", + "schemaVersion": 1 +} diff --git a/skills/dotnet-csrun/evals/files/safe-adaptation.json b/skills/dotnet-csrun/evals/files/safe-adaptation.json new file mode 100644 index 00000000..c850025b --- /dev/null +++ b/skills/dotnet-csrun/evals/files/safe-adaptation.json @@ -0,0 +1,9 @@ +{ + "framework": "net10.0", + "dependsOn": [ + "xunit.v3@4.0.3" + ], + "source": "using System.Threading.Tasks; using Xunit; public class AdaptedTests { [Fact] public async Task PreservesAwaitedValue() { Assert.Equal(42, await Task.FromResult(42)); } }", + "mode": "test", + "schemaVersion": 1 +} diff --git a/skills/dotnet-csrun/evals/files/standalone-host.json b/skills/dotnet-csrun/evals/files/standalone-host.json new file mode 100644 index 00000000..cfdd73ec --- /dev/null +++ b/skills/dotnet-csrun/evals/files/standalone-host.json @@ -0,0 +1,10 @@ +{ + "framework": "net10.0", + "dependsOn": [ + "Codebelt.Extensions.Xunit.App@13.0.0", + "xunit.v3@4.0.3" + ], + "source": "using Microsoft.Extensions.DependencyInjection;\nusing Microsoft.Extensions.Hosting;\nusing Xunit;\n\npublic sealed class HostTests\n{\n [Fact]\n public void StandaloneHostResolvesRegisteredIdentity()\n {\n var builder = Host.CreateApplicationBuilder();\n builder.Services.AddSingleton(new WorkerIdentity(\"Inventory worker\"));\n using var host = builder.Build();\n Assert.Equal(\"Inventory worker\", host.Services.GetRequiredService().Name);\n }\n}\n\npublic sealed record WorkerIdentity(string Name);", + "mode": "test", + "schemaVersion": 1 +} From fea4a15ab32a54e2b038872f0f9ab2e44797cca7 Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Tue, 17 Nov 2026 00:11:42 +0100 Subject: [PATCH 09/95] =?UTF-8?q?=F0=9F=94=A8=20add=20csrun=20sample=20art?= =?UTF-8?q?ifact=20helpers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Sample identity and artifact helpers give csrun verify and repair a single deterministic source of truth for manifest-derived paths, so the lifecycle workflow does not reimplement them in prose. --- skills/dotnet-csrun/scripts/sample-tools.ps1 | 129 ++++++++++++++++++ .../scripts/test-sample-tools.ps1 | 121 ++++++++++++++++ 2 files changed, 250 insertions(+) create mode 100644 skills/dotnet-csrun/scripts/sample-tools.ps1 create mode 100644 skills/dotnet-csrun/scripts/test-sample-tools.ps1 diff --git a/skills/dotnet-csrun/scripts/sample-tools.ps1 b/skills/dotnet-csrun/scripts/sample-tools.ps1 new file mode 100644 index 00000000..4022957a --- /dev/null +++ b/skills/dotnet-csrun/scripts/sample-tools.ps1 @@ -0,0 +1,129 @@ +#requires -Version 7.0 +# Dot-source these artifact helpers. They do not validate manifests or execute samples. +Set-StrictMode -Version Latest + +function Get-CsrunSampleIdentity { + param([Parameter(Mandatory)][string] $ManifestJson) + $item = ConvertFrom-Json -InputObject $ManifestJson -AsHashtable + if ($item.source -isnot [string]) { throw 'A manifest source string is required for identity.' } + # Sort object keys recursively; preserve arrays, source text, and every manifest value. + function Sort-ManifestValue($Value) { + if ($Value -is [System.Collections.IDictionary]) { + $ordered = [ordered]@{} + [string[]] $keys = @($Value.Keys) + [Array]::Sort($keys, [StringComparer]::Ordinal) + foreach ($key in $keys) { + $ordered[$key] = Sort-ManifestValue $Value[$key] + } + return $ordered + } + if ($Value -is [array]) { return ,@($Value | ForEach-Object { Sort-ManifestValue $_ }) } + return $Value + } + $ordered = Sort-ManifestValue $item + $canonical = ConvertTo-Json -InputObject $ordered -Depth 100 -Compress + function Get-TextHash([string] $Value) { + $sha = [Security.Cryptography.SHA256]::Create() + try { [BitConverter]::ToString($sha.ComputeHash([Text.Encoding]::UTF8.GetBytes($Value))).Replace('-', '') } + finally { $sha.Dispose() } + } + [pscustomobject]@{ + Source = $item.source + SourceSha256 = Get-TextHash $item.source + ManifestSha256 = Get-TextHash $canonical + ManifestJson = ConvertTo-Json -InputObject $ordered -Depth 100 + } +} + +function New-CsrunExecutionPair { + param( + [Parameter(Mandatory)][string] $ManifestJson, + # Caller verifies the published image/tag, compatibility, and provenance before delivery. + [Parameter(Mandatory)][string] $Image, + [string] $EnginePath + ) + $identity = Get-CsrunSampleIdentity $ManifestJson + function Quote-Literal([string] $Value) { "'" + $Value.Replace("'", "''") + "'" } + # JSON serialization escapes embedded newlines, so source cannot terminate this here-string. + $prefix = "#requires -Version 7.0`n`$ErrorActionPreference = 'Stop'`n`$PSNativeCommandUseErrorActionPreference = `$false`n`$manifest = @'`n" + $identity.ManifestJson + "`n'@`n" + $suffix = @' +$code = $LASTEXITCODE +if ($code -ne 0) { throw "csrun execution failed with exit code $code." } +'@ + $nativeCommand = if ($EnginePath) { + '& pwsh -NoProfile -NonInteractive -File ' + (Quote-Literal $EnginePath) + ' -ManifestJson $manifest' + } else { + @' +# Trust warning: downloads and executes publisher code with your permissions. Review before running. +# releases/latest is mutable; retain a reviewed release asset/hash for reproducibility. +$engine = Invoke-RestMethod 'https://github.com/codebeltnet/csrun/releases/latest/download/csrun.ps1' +& ([scriptblock]::Create($engine)) -ManifestJson $manifest +'@ + } + $dockerCommand = '$manifest | docker run --rm -i ' + (Quote-Literal $Image) + $encoding = '$OutputEncoding = [Text.UTF8Encoding]::new($false)' + "`n" + '[Console]::OutputEncoding = $OutputEncoding' + "`n" + [pscustomobject]@{ + SourceSha256 = $identity.SourceSha256 + ManifestSha256 = $identity.ManifestSha256 + ManifestJson = $identity.ManifestJson + Native = $prefix + $encoding + $nativeCommand + "`n" + $suffix + Docker = $prefix + $encoding + $dockerCommand + "`n" + $suffix + } +} + +function Get-CsrunWrapperManifest { + param([Parameter(Mandatory)][string] $Block) + # Inspect only a literal assignment in a generated block; never evaluate supplied PowerShell. + $tokens = $null + $errors = $null + $ast = [Management.Automation.Language.Parser]::ParseInput($Block, [ref] $tokens, [ref] $errors) + if ($errors.Count) { throw 'PowerShell block has syntax errors.' } + $assignments = @($ast.FindAll({ param($node) + $node -is [Management.Automation.Language.AssignmentStatementAst] -and + $node.Left -is [Management.Automation.Language.VariableExpressionAst] -and + $node.Left.VariablePath.UserPath -ceq 'manifest' + }, $true)) + if ($assignments.Count -ne 1) { throw 'Expected one literal manifest assignment; inspect other wrapper formats manually.' } + $literal = $assignments[0].Right.Find({ param($node) + $node -is [Management.Automation.Language.StringConstantExpressionAst] + }, $false) + if (-not $literal -or $assignments[0].Right.Extent.Text -cne $literal.Extent.Text) { + throw 'Manifest must be a single string literal; no expressions are evaluated.' + } + $literal.Value +} + +function Set-CsrunSourceRegion { + param( + [Parameter(Mandatory)][string] $Path, + [Parameter(Mandatory)][int] $Start, + [Parameter(Mandatory)][AllowEmptyString()][string] $ExpectedSource, + [Parameter(Mandatory)][AllowEmptyString()][string] $ReplacementSource + ) + # The agent selects the exact region after inspecting context; this is not a Markdown parser. + # Use only for an authorized repair. Unknown encodings must be handled explicitly elsewhere. + $full = (Resolve-Path -LiteralPath $Path).Path + $bytes = [IO.File]::ReadAllBytes($full) + $reader = [IO.StreamReader]::new([IO.MemoryStream]::new($bytes), [Text.UTF8Encoding]::new($false, $true), $true) + try { $text = $reader.ReadToEnd(); $encoding = $reader.CurrentEncoding } finally { $reader.Dispose() } + if ($Start -lt 0 -or $Start + $ExpectedSource.Length -gt $text.Length -or + $text.Substring($Start, $ExpectedSource.Length) -cne $ExpectedSource) { + throw 'Source region changed; inspect again before repair.' + } + $newline = if ($text.Contains("`r`n")) { "`r`n" } else { "`n" } + if ($text.Replace("`r`n", '').Contains("`n") -and $text.Contains("`r`n")) { + throw 'Mixed line endings require an explicit localized edit.' + } + $replacement = $ReplacementSource.Replace("`r`n", "`n").Replace("`n", $newline) + $updated = $text.Substring(0, $Start) + $replacement + $text.Substring($Start + $ExpectedSource.Length) + $preamble = $encoding.GetPreamble() + $hasPreamble = $preamble.Length -gt 0 -and $bytes.Length -ge $preamble.Length -and + [Convert]::ToBase64String($preamble) -ceq [Convert]::ToBase64String([byte[]] $bytes[0..($preamble.Length - 1)]) + $output = $encoding.GetBytes($updated) + if ($hasPreamble) { $output = [byte[]] ($preamble + $output) } + # Fail before writing if decoding/encoding would change any original byte. + $roundTrip = $encoding.GetBytes($text) + if ($hasPreamble) { $roundTrip = [byte[]] ($preamble + $roundTrip) } + if ([Convert]::ToBase64String($bytes) -cne [Convert]::ToBase64String($roundTrip)) { throw 'Encoding is not losslessly supported.' } + [IO.File]::WriteAllBytes($full, $output) +} diff --git a/skills/dotnet-csrun/scripts/test-sample-tools.ps1 b/skills/dotnet-csrun/scripts/test-sample-tools.ps1 new file mode 100644 index 00000000..95f04403 --- /dev/null +++ b/skills/dotnet-csrun/scripts/test-sample-tools.ps1 @@ -0,0 +1,121 @@ +#requires -Version 7.0 +$ErrorActionPreference = 'Stop' +. (Join-Path $PSScriptRoot 'sample-tools.ps1') +$root = Split-Path $PSScriptRoot -Parent +$checks = 0 +function Assert-True($Condition, [string] $Message) { + if (-not $Condition) { throw $Message } + $script:checks++ +} +function Assert-Throws([scriptblock] $Action, [string] $Message) { + $threw = $false + try { & $Action | Out-Null } catch { $threw = $true } + Assert-True $threw $Message +} + +foreach ($file in Get-ChildItem (Join-Path $root 'evals/files') -Filter '*.json') { + $json = [IO.File]::ReadAllText($file.FullName) + $item = ConvertFrom-Json $json -AsHashtable + if (-not $item.Contains('source')) { continue } + $pair = New-CsrunExecutionPair $json -Image 'codebeltnet/csrun:10' -EnginePath "C:/reviewed engine's/csrun.ps1" + foreach ($block in @($pair.Native, $pair.Docker)) { + $actual = Get-CsrunSampleIdentity (Get-CsrunWrapperManifest $block) + Assert-True ($actual.ManifestSha256 -ceq $pair.ManifestSha256) "Manifest semantics drifted: $($file.Name)" + Assert-True ($actual.Source -ceq $item.source) "Source drifted: $($file.Name)" + } +} + +# Exercise quotes, raw strings, CRLF, Unicode, dollars, and a PowerShell terminator inside C#. +$source = "using System;`r`nConsole.WriteLine(`"`"`"`r`n'@`r`n`$value æøå 世界 `"C#`"`r`n`"`"`" );" +$json = @{ schemaVersion=1; mode='console'; framework='net10.0'; source=$source; sdk='Microsoft.NET.Sdk.Web'; frameworkReferences=@('Microsoft.AspNetCore.App'); dependsOn=@('xunit.v3@4.0.3') } | ConvertTo-Json -Depth 8 +$pair = New-CsrunExecutionPair $json -Image 'codebeltnet/csrun:10' +Assert-True ((Get-CsrunSampleIdentity (Get-CsrunWrapperManifest $pair.Native)).Source -ceq $source) 'Special source text was corrupted.' +$reordered = ($json | ConvertFrom-Json -AsHashtable) +$reordered.source += ' ' +Assert-True ((Get-CsrunSampleIdentity ($reordered | ConvertTo-Json -Depth 8)).SourceSha256 -cne $pair.SourceSha256) 'Changed source reused an identity.' +$reordered.source = $source +$reordered.framework = 'net11.0' +Assert-True ((Get-CsrunSampleIdentity ($reordered | ConvertTo-Json -Depth 8)).ManifestSha256 -cne $pair.ManifestSha256) 'Changed framework reused an identity.' +$reordered.framework = 'net10.0' +$reordered.dependsOn = @('xunit.v3@4.0.4') +Assert-True ((Get-CsrunSampleIdentity ($reordered | ConvertTo-Json -Depth 8)).ManifestSha256 -cne $pair.ManifestSha256) 'Changed dependencies reused an identity.' +$reordered.dependsOn = @('xunit.v3@4.0.3') +$reordered.sdk = 'Microsoft.NET.Sdk' +Assert-True ((Get-CsrunSampleIdentity ($reordered | ConvertTo-Json -Depth 8)).ManifestSha256 -cne $pair.ManifestSha256) 'Changed SDK reused an identity.' +$reordered.sdk = 'Microsoft.NET.Sdk.Web' +$reordered.frameworkReferences = @() +Assert-True ((Get-CsrunSampleIdentity ($reordered | ConvertTo-Json -Depth 8)).ManifestSha256 -cne $pair.ManifestSha256) 'Changed references reused an identity.' +$console = [IO.File]::ReadAllText((Join-Path $root 'evals/files/console.json')) +$pair = New-CsrunExecutionPair $console -Image 'codebeltnet/csrun:10' -EnginePath '/reviewed/csrun.ps1' +$orderedDifferently = [ordered]@{ source=($console | ConvertFrom-Json).source; mode='console'; schemaVersion=1; framework='net10.0' } | ConvertTo-Json -Compress +Assert-True ((Get-CsrunSampleIdentity $orderedDifferently).ManifestSha256 -ceq $pair.ManifestSha256) 'Property order or JSON whitespace changed semantic identity.' +foreach ($change in @(@{schemaVersion=2}, @{mode='test'})) { + $item = $console | ConvertFrom-Json -AsHashtable + foreach ($key in $change.Keys) { $item[$key] = $change[$key] } + Assert-True ((Get-CsrunSampleIdentity ($item | ConvertTo-Json)).ManifestSha256 -cne $pair.ManifestSha256) 'Changed schema/mode reused an identity.' +} +$diverged = $pair.Docker.Replace('WriteLine(42)', 'WriteLine(43)') +Assert-True ((Get-CsrunSampleIdentity (Get-CsrunWrapperManifest $diverged)).SourceSha256 -cne $pair.SourceSha256) 'Wrapper divergence went undetected.' +Assert-Throws { Get-CsrunWrapperManifest '$manifest = $(throw "must never execute")' } 'Nonliteral wrapper was accepted.' +Assert-Throws { Get-CsrunWrapperManifest ($pair.Native + "`n`$manifest = '{}'" ) } 'Multiple manifest assignments were accepted.' + +# Test the generated blocks themselves in independent scopes, without real engine prerequisites. +# These are transport contract doubles, never behavioral sample execution evidence. +foreach ($transport in @('Native', 'Docker')) { + $received = & { + param($Block, $Transport) + function dotnet { throw 'The Docker host must not need dotnet.' } + function docker { + if ($Transport -ne 'Docker') { throw 'Native block must not need Docker.' } + $lines = @($input) + $script:captured = $lines -join "`n" + if (($args -join ' ') -cne 'run --rm -i codebeltnet/csrun:10') { throw 'Unexpected Docker flags.' } + $global:LASTEXITCODE = 0 + } + function pwsh { + if ($Transport -ne 'Native') { throw 'Docker block must not need native engine.' } + $index = [Array]::IndexOf($args, '-ManifestJson') + if ($index -lt 0) { throw 'Missing native manifest.' } + $script:captured = $args[$index + 1] + $global:LASTEXITCODE = 0 + } + $script:captured = $null + & ([scriptblock]::Create($Block)) + $script:captured + } $pair.$transport $transport + Assert-True ((Get-CsrunSampleIdentity $received).ManifestSha256 -ceq $pair.ManifestSha256) "$transport block was not independently executable." +} +Assert-Throws { + & { + function docker { $input | Out-Null; $global:LASTEXITCODE = 2 } + & ([scriptblock]::Create($pair.Docker)) + } +} 'Generated block silently swallowed an engine failure.' +# No prerequisites: generation/extraction still works; no engine is contacted or status fabricated. +Assert-True ((Get-CsrunWrapperManifest (New-CsrunExecutionPair $console -Image 'codebeltnet/csrun:10').Native) -eq $pair.ManifestJson) 'Template generation requires an execution environment.' + +$temp = Join-Path ([IO.Path]::GetTempPath()) ('csrun-edit-' + [guid]::NewGuid().ToString('N')) +New-Item -ItemType Directory $temp | Out-Null +try { + $original = [IO.File]::ReadAllText((Join-Path $root 'evals/files/repair.md')).Replace("`r`n", "`n").Replace("`n", "`r`n") + foreach ($encoding in @([Text.UTF8Encoding]::new($true), [Text.UTF8Encoding]::new($false), [Text.UnicodeEncoding]::new($false, $true), [Text.UnicodeEncoding]::new($true, $true))) { + $path = Join-Path $temp 'sample.md' + [IO.File]::WriteAllText($path, $original, $encoding) + $old = 'Console.WriteLine(DateTime.UnixEpoch.Year)' + $new = 'Console.WriteLine(DateTime.UnixEpoch.Year);' + $start = $original.IndexOf($old, [StringComparison]::Ordinal) + Set-CsrunSourceRegion -Path $path -Start $start -ExpectedSource $old -ReplacementSource $new + $expected = $original.Replace($old, $new) + $expectedBytes = [byte[]] ($encoding.GetPreamble() + $encoding.GetBytes($expected)) + Assert-True ([Convert]::ToBase64String($expectedBytes) -ceq [Convert]::ToBase64String([IO.File]::ReadAllBytes($path))) 'Repair changed surrounding content, BOM, encoding, or CRLF.' + $snapshot = [IO.File]::ReadAllBytes($path) + Assert-Throws { Set-CsrunSourceRegion -Path $path -Start $start -ExpectedSource 'stale source' -ReplacementSource $new } 'A stale repair overwrote source.' + Assert-True ([Convert]::ToBase64String($snapshot) -ceq [Convert]::ToBase64String([IO.File]::ReadAllBytes($path))) 'Rejected repair modified the document.' + } +} finally { + # A unique OS-temporary directory, resolved and checked before recursive removal. + $resolved = [IO.Path]::GetFullPath($temp) + if (-not $resolved.StartsWith([IO.Path]::GetFullPath([IO.Path]::GetTempPath()), [StringComparison]::OrdinalIgnoreCase)) { throw 'Unsafe cleanup path.' } + Remove-Item -LiteralPath $resolved -Recurse -Force +} +Write-Host "dotnet-csrun sample tools passed: $checks checks (offline transport doubles are not sample verification)." From 05fbde05e77875a4b0411aa10cd141e60187f041 Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Tue, 17 Nov 2026 00:11:49 +0100 Subject: [PATCH 10/95] =?UTF-8?q?=F0=9F=94=A8=20extend=20csrun=20validatio?= =?UTF-8?q?n=20for=20lifecycle=20checks?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The csrun validator and repository validator now check the create, verify, repair, and audit contracts, so lifecycle regressions fail deterministically instead of surfacing only in prose review. --- scripts/validate-dotnet-csrun.ps1 | 71 ++++++++++++++++++++++--- scripts/validate-skill-templates.ps1 | 4 ++ skills/dotnet-csrun/scripts/validate.cs | 40 +++++++++++++- 3 files changed, 105 insertions(+), 10 deletions(-) diff --git a/scripts/validate-dotnet-csrun.ps1 b/scripts/validate-dotnet-csrun.ps1 index 346050bd..d5e3c1bf 100644 --- a/scripts/validate-dotnet-csrun.ps1 +++ b/scripts/validate-dotnet-csrun.ps1 @@ -12,8 +12,11 @@ $root = Join-Path $PSScriptRoot '../skills/dotnet-csrun' $app = Get-FileBasedAppCommand -SourcePath (Join-Path $root 'scripts/validate.cs') & $app.Executable @($app.ArgumentPrefix + @($root)) if ($LASTEXITCODE -ne 0) { throw 'Skill artifact validation failed.' } +& pwsh -NoProfile -NonInteractive -File (Join-Path $root 'scripts/test-sample-tools.ps1') +if ($LASTEXITCODE -ne 0) { throw 'Sample artifact helper regressions failed.' } if (-not $EnginePath -and -not $Docker) { return } if ($EnginePath) { $EnginePath = (Resolve-Path $EnginePath).Path } +. (Join-Path $root 'scripts/sample-tools.ps1') $evidence = Join-Path ([IO.Path]::GetTempPath()) ('dotnet-csrun-evidence-' + [guid]::NewGuid().ToString('N')) New-Item -ItemType Directory $evidence | Out-Null $OutputEncoding = [Text.UTF8Encoding]::new($false) @@ -27,23 +30,75 @@ $cases = @( @('package', 0, '(?m)^273\s*$'), @('unicode', 0, 'Hello "C#" — æøå 世界\r?\nsecond line'), @('standalone-host', 0, '(?is)total:\s*1.*failed:\s*0.*succeeded:\s*1.*skipped:\s*0'), - @('safe-adaptation', 0, '(?is)total:\s*1.*failed:\s*0.*succeeded:\s*1.*skipped:\s*0'), + @('safe-adaptation', -1, 'CS0246'), + @('safe-adaptation-corrected', 0, '(?is)total:\s*1.*failed:\s*0.*succeeded:\s*1.*skipped:\s*0'), @('inventory-worker', -1, 'CS0017'), - @('multiple-entrypoints', -1, 'CS0017') + @('multiple-entrypoints', -1, 'CS0017'), + @('incorrect-package', -1, 'NU1101'), + @('markdown-before', -1, 'CS1002'), + @('markdown-after', 0, '(?m)^1970\s*$') ) +$environment = if ($Docker) { + $images = @{} + foreach ($tag in @('10', '11')) { + $image = "codebeltnet/csrun:$tag" + $inspect = docker image inspect $image --format '{{json .}}' | ConvertFrom-Json + if ($LASTEXITCODE -ne 0) { throw "Inspect failed: $image" } + $sdks = docker run --rm --entrypoint dotnet $image --list-sdks + if ($LASTEXITCODE -ne 0) { throw "SDK inventory failed: $image" } + $runtimes = docker run --rm --entrypoint dotnet $image --list-runtimes + if ($LASTEXITCODE -ne 0) { throw "Runtime inventory failed: $image" } + $images[$image] = @{ imageId=$inspect.Id; digests=$inspect.RepoDigests; labels=$inspect.Config.Labels; os=$inspect.Os; architecture=$inspect.Architecture; sdks=$sdks; runtimes=$runtimes } + } + $images +} else { + $info = dotnet --info + if ($LASTEXITCODE -ne 0) { throw 'Native SDK inventory failed.' } + @{ engineSha256=(Get-FileHash $EnginePath).Hash; dotnetInfo=$info; runtimes=@(dotnet --list-runtimes) } +} +$environment | ConvertTo-Json -Depth 20 | Set-Content (Join-Path $evidence 'environment.json') -Encoding utf8 Write-Host "Evidence directory: $evidence" foreach ($case in $cases) { $name, $expectedExit, $pattern = $case - $json = Get-Content (Join-Path $root "evals/files/$name.json") -Raw - if ($Docker) { - $image = if ($name -eq 'package') { 'codebeltnet/csrun:11' } else { 'codebeltnet/csrun:10' } - $output = $json | & docker run --rm -i $image 2>&1 | Out-String + if ($name -like 'markdown-*') { + # Explicit inspected first-fence region; the partial second fence remains untouched. + $document = [IO.File]::ReadAllText((Join-Path $root 'evals/files/repair.md')) + $opening = '```csharp' + $start = $document.IndexOf($opening, [StringComparison]::Ordinal) + $opening.Length + $start = $document.IndexOf("`n", $start) + 1 + $end = $document.IndexOf('```', $start, [StringComparison]::Ordinal) + $source = $document.Substring($start, $end - $start).TrimEnd("`r", "`n") + $path = Join-Path $evidence 'repair.md' + if ($name -eq 'markdown-before') { [IO.File]::WriteAllText($path, $document) } + else { + Set-CsrunSourceRegion -Path $path -Start $start -ExpectedSource $source -ReplacementSource ($source + ';') + $source += ';' + } + $json = @{ schemaVersion=1; mode='console'; framework='net10.0'; source=$source } | ConvertTo-Json + } else { + $json = Get-Content (Join-Path $root "evals/files/$name.json") -Raw + } + $image = if (($json | ConvertFrom-Json).framework -eq 'net11.0') { 'codebeltnet/csrun:11' } else { 'codebeltnet/csrun:10' } + $pair = New-CsrunExecutionPair -ManifestJson $json -Image $image -EnginePath $EnginePath + $pair.ManifestJson | Set-Content (Join-Path $evidence "$name.manifest.json") -Encoding utf8 + $pair.Native | Set-Content (Join-Path $evidence "$name.native.ps1") -Encoding utf8 + $pair.Docker | Set-Content (Join-Path $evidence "$name.docker.ps1") -Encoding utf8 + $stderrPath = Join-Path $evidence "$name.stderr.log" + if ($expectedExit -eq 0) { + # Positive fixtures exercise the complete generated copy/paste artifact in a fresh process. + $transport = if ($Docker) { 'docker' } else { 'native' } + $stdout = & pwsh -NoProfile -NonInteractive -File (Join-Path $evidence "$name.$transport.ps1") 2> $stderrPath | Out-String + } elseif ($Docker) { + $stdout = $pair.ManifestJson | & docker run --rm -i $image 2> $stderrPath | Out-String } else { - $output = & pwsh -NoProfile -NonInteractive -File $EnginePath -ManifestJson $json 2>&1 | Out-String + $stdout = & pwsh -NoProfile -NonInteractive -File $EnginePath -ManifestJson $pair.ManifestJson 2> $stderrPath | Out-String } $code = $LASTEXITCODE + $stderr = Get-Content -LiteralPath $stderrPath -Raw + $output = $stdout + $stderr + $stdout | Set-Content (Join-Path $evidence "$name.stdout.log") -Encoding utf8 $output | Set-Content (Join-Path $evidence "$name.log") -Encoding utf8 - @{ fixture=$name; exitCode=$code; transport=$(if ($Docker) {$image} else {$EnginePath}); manifestSha256=(Get-FileHash (Join-Path $root "evals/files/$name.json")).Hash } | ConvertTo-Json | Set-Content (Join-Path $evidence "$name.evidence.json") + @{ fixture=$name; exitCode=$code; transport=$(if ($Docker) {$image} else {$EnginePath}); sourceSha256=$pair.SourceSha256; manifestSha256=$pair.ManifestSha256; expectedExit=$expectedExit; expectedObservation=$pattern; observedUtc=[DateTime]::UtcNow.ToString('O'); environment='environment.json'; stdout="$name.stdout.log"; stderr="$name.stderr.log" } | ConvertTo-Json | Set-Content (Join-Path $evidence "$name.evidence.json") $plain = $output -replace '\x1B\[[0-?]*[ -/]*[@-~]', '' if (($expectedExit -eq -1 -and $code -eq 0) -or ($expectedExit -ne -1 -and $code -ne $expectedExit) -or $plain -notmatch $pattern) { throw "$name did not match expected exit/observation (exit $code). See $evidence/$name.log" diff --git a/scripts/validate-skill-templates.ps1 b/scripts/validate-skill-templates.ps1 index 06a9a2ee..33a7b8e5 100644 --- a/scripts/validate-skill-templates.ps1 +++ b/scripts/validate-skill-templates.ps1 @@ -838,6 +838,10 @@ Add-ValidationResult -Results $results -Name 'dotnet-csrun source fixtures and p $path = $link.Groups[1].Value if ($path -notmatch '://') { [void](Get-FileText -RepoRoot $repoRoot -RelativePath "skills/dotnet-csrun/$path" -GitRef $Ref) } } + if ([string]::IsNullOrWhiteSpace($Ref)) { + & pwsh -NoProfile -NonInteractive -File (Join-Path $repoRoot 'skills/dotnet-csrun/scripts/test-sample-tools.ps1') + if ($LASTEXITCODE -ne 0) { throw 'dotnet-csrun sample tool regressions failed.' } + } } Add-ValidationResult -Results $results -Name 'Git remote PR routing and deterministic workflow stay integrated' -Group 'Pr' -Action { diff --git a/skills/dotnet-csrun/scripts/validate.cs b/skills/dotnet-csrun/scripts/validate.cs index 1a6cd551..256d1c7e 100644 --- a/skills/dotnet-csrun/scripts/validate.cs +++ b/skills/dotnet-csrun/scripts/validate.cs @@ -22,8 +22,16 @@ ["inventory-worker"] = "ApplicationTest>", ["standalone-host"] = "StandaloneHostResolvesRegisteredIdentity", ["multiple-entrypoints"] = "public static void Main(string[] args)", - ["safe-adaptation"] = "Assert.Equal(42, await Task.FromResult(42))" + ["safe-adaptation"] = "Assert.Equal(42, await Task.FromResult(42))", + ["safe-adaptation-corrected"] = "Assert.Equal(42, await Task.FromResult(42))" }; +// The eval input must stay uncorrected (missing Xunit import); the corrected twin is for execution checks. +foreach (var (name, hasImport) in new[] { ("safe-adaptation", false), ("safe-adaptation-corrected", true) }) +{ + using var f = JsonDocument.Parse(File.ReadAllText(Path.Combine(root, "evals", "files", name + ".json"))); + if (f.RootElement.GetProperty("source").GetString()!.Contains("using Xunit;", StringComparison.Ordinal) != hasImport) + throw new InvalidDataException($"Xunit import state drift: {name}"); +} foreach (var (name, fragment) in expectedSources) { using var fixture = JsonDocument.Parse(File.ReadAllText(Path.Combine(root, "evals", "files", name + ".json"))); @@ -33,6 +41,34 @@ var roundTrip = JsonSerializer.Deserialize(JsonSerializer.Serialize(source, options), options); if (source != roundTrip) throw new InvalidDataException($"Source round-trip failed: {name}"); } +// These repairs change only the diagnosed defect, never the assertion or observable operation. +string Source(string name) +{ + using var document = JsonDocument.Parse(File.ReadAllText(Path.Combine(root, "evals", "files", name + ".json"))); + return document.RootElement.GetProperty("source").GetString()!; +} +if (Source("safe-adaptation").Replace("using System.Threading.Tasks; ", "using System.Threading.Tasks; using Xunit; ", StringComparison.Ordinal) != Source("safe-adaptation-corrected")) + throw new InvalidDataException("Import repair changed the tested behavior."); +if (Source("incorrect-package") != Source("package")) + throw new InvalidDataException("Package repair changed the demonstrated operation."); +foreach (var (name, pin) in new[] { ("incorrect-package", "Cuemon.Kernell@11.0.0"), ("package", "Cuemon.Kernel@11.0.0") }) +{ + using var fixture = JsonDocument.Parse(File.ReadAllText(Path.Combine(root, "evals", "files", name + ".json"))); + var item = fixture.RootElement; + if (item.GetProperty("schemaVersion").GetInt32() != 1 || item.GetProperty("mode").GetString() != "console" || + item.GetProperty("framework").GetString() != "net11.0" || + !item.GetProperty("dependsOn").EnumerateArray().Select(p => p.GetString()).SequenceEqual(new[] { pin })) + throw new InvalidDataException($"Package repair fixture semantics drifted: {name}"); +} +foreach (var reference in Directory.EnumerateFiles(Path.Combine(root, "references"), "*.md")) +{ + foreach (Match link in Regex.Matches(File.ReadAllText(reference), @"\]\(([^)]+)\)")) + { + var path = link.Groups[1].Value; + if (!path.Contains("://") && !File.Exists(Path.Combine(Path.GetDirectoryName(reference)!, path))) + throw new InvalidDataException($"Broken reference link: {reference}: {path}"); + } +} // Ensure the published journey and the executable fixture describe the same program. using var console = JsonDocument.Parse(File.ReadAllText(Path.Combine(root, "evals", "files", "console.json"))); var documented = Regex.Match(skill, "source = @'\\r?\\n(.*?)\\r?\\n'@", RegexOptions.Singleline).Groups[1].Value; @@ -43,7 +79,7 @@ var original = inventory.RootElement.GetProperty("source").GetString()!; var originalHash = Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(original.Replace("\r\n", "\n")))); if (originalHash != "6B54B2CA6E2D3EDF8EC3ED4B7CB1E1CFA7E28265F41B228E3EE9465DD9B7D9A4") throw new InvalidDataException("Original InventoryWorker source changed; do not remove the behavior under test."); -foreach (var name in new[] { "inventory-worker", "standalone-host", "multiple-entrypoints", "safe-adaptation" }) +foreach (var name in new[] { "inventory-worker", "standalone-host", "multiple-entrypoints", "safe-adaptation", "safe-adaptation-corrected" }) { using var fixture = JsonDocument.Parse(File.ReadAllText(Path.Combine(root, "evals", "files", name + ".json"))); var item = fixture.RootElement; From 53582ac999697034668d441f3d7a13676622e802 Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Tue, 17 Nov 2026 00:11:56 +0100 Subject: [PATCH 11/95] =?UTF-8?q?=E2=9C=A8=20add=20csrun=20verify,=20repai?= =?UTF-8?q?r,=20and=20audit=20lifecycle?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit csrun previously covered only creating new examples. Existing source now has an explicit read-only verify path, an authorized repair path with preserved semantics, and a scoped audit path, with a reference for composing them from dotnet-docfx-digest. --- skills/dotnet-csrun/SKILL.md | 28 +++++++++++------- skills/dotnet-csrun/references/docfx.md | 11 +++++++ skills/dotnet-csrun/references/execution.md | 12 ++++++-- skills/dotnet-csrun/references/lifecycle.md | 29 +++++++++++++++++++ .../dotnet-csrun/references/presentation.md | 19 ++++++++++-- .../dotnet-csrun/references/verification.md | 22 +++++++++++--- 6 files changed, 102 insertions(+), 19 deletions(-) create mode 100644 skills/dotnet-csrun/references/docfx.md create mode 100644 skills/dotnet-csrun/references/lifecycle.md diff --git a/skills/dotnet-csrun/SKILL.md b/skills/dotnet-csrun/SKILL.md index 40276963..ca48ad5e 100644 --- a/skills/dotnet-csrun/SKILL.md +++ b/skills/dotnet-csrun/SKILL.md @@ -1,23 +1,34 @@ --- name: dotnet-csrun description: > - Use when creating runnable C# examples, verifying documentation snippets or API behavior, turning snippets into isolated xUnit tests, or reproducing .NET problems without a project. Excludes repository test infrastructure, integration suites, and benchmarks. + Use when creating, verifying, repairing, or auditing C# examples and documentation snippets, running isolated xUnit v3 tests, or reproducing .NET problems without a project. Excludes repository test infrastructure and benchmarks. --- # Executable C# evidence with csrun Make the smallest complete example, execute it through `csrun`, and share the exact program that ran. Use .NET/C# for substantive supporting logic and PowerShell 7 for orchestration. Never substitute another execution engine or create a competing manifest format. +## Choose the intention + +| Logical command | Authorized behavior | +| --- | --- | +| `create` | Construct a new complete console sample or genuine xUnit v3 test, execute it, and deliver both transports. | +| `verify` | Inspect and execute existing source without editing it; report defects and limitations. | +| `repair` | Establish intent, preserve failure evidence, make the smallest semantics-preserving correction, execute, and deliver both transports. | +| `audit` | Discover and classify examples within the specified scope; read-only unless repair is explicitly requested or already authorized by the parent workflow. | + +These are agent intentions, not binary commands or manifest fields. Infer a bare invocation from context: existing source plus “does it work?” means `verify`; a request for a new example means `create`. `audit --fix` authorizes relevant sample repairs, not application refactoring. Do not introduce a command parser, menu, or clarification when intent is clear. Read [existing samples, repair, and audit](references/lifecycle.md) for these operations and [DocFX composition](references/docfx.md) during documentation work. + ## Workflow 1. Inspect supplied source, documentation, dependency pins, and repository context. A bare invocation uses that context; proceed when the behavior is clear. Ask only for facts that materially affect correctness. Use `dotnet-test` for repository testing infrastructure, `dotnet-remote-testing` for existing test workloads, and `dotnet-benchmark` for performance experiments. 2. Establish the expected observation before execution: output values, stable invariants, meaningful assertions, or a deliberate failure with its diagnostic and exit status. Choose console mode for observable demonstrations and test mode for assertions. If both are explicitly requested and useful, provide independently executable examples with identical dependency versions and assumptions. 3. Before manifest construction, assess feasibility: **Compatible**, **Adaptable** through a justified semantics-preserving change, **Unsupported** by the current execution model, or **Undetermined** pending inspection/execution. Trivial console programs and ordinary facts proceed directly. Inspect explicit `Main`, top-level test statements, application-entrypoint fixtures, project/assembly dependencies, platform and service prerequisites using [feasibility and recovery](references/feasibility.md). DI and hosting APIs alone are compatible; needing the identity or startup of a separate application assembly is the distinction. Avoid predictable unsupported attempts unless requested or needed for diagnosis; an inconclusive assessment may proceed to execution. -4. Choose the compatible execution path, then write complete source, including imports and an entry point or discoverable public xUnit test class. Use async tests returning `Task` when appropriate. Do not simulate assertions or test results with printed messages. Read [manifest construction](references/manifest.md) before constructing the schema version 1 manifest. Verify package versions in repository pins and the package's authoritative published feed; never invent or silently change them. -5. Read [execution environments](references/execution.md). Prefer official disposable Docker execution when available and appropriate; native execution is first class. Preserve the requested framework and choose a compatible environment explicitly. If neither environment can execute it, name the concrete missing prerequisite and deliver an **Unverified** example. Never silently retarget, install a different engine, or fabricate output. +4. Choose the compatible execution path. For `create` or authorized `repair`, write complete source, including imports and an entry point or discoverable public xUnit test class; for `verify`, retain supplied source unchanged. Use async tests returning `Task` when appropriate. Do not simulate assertions or test results with printed messages. Read [manifest construction](references/manifest.md) before constructing the schema version 1 manifest. Verify package versions in repository pins and the package's authoritative published feed; never invent or silently change them. +5. Read [execution environments](references/execution.md). Select the available compatible native or Docker transport; neither requires the other's prerequisites. When both are available, verify both where practical, especially for quoting, Unicode, and transport parity. Preserve the requested framework. If neither can execute it, name the concrete missing prerequisites and deliver both runnable templates as **Unverified**. Never silently retarget, install a different engine, or fabricate output. 6. Execute the exact manifest through the actual engine. Capture stdout, stderr, exit code immediately, framework, SDK/runtime environment, engine identity, and package pins. For console examples compare actual output with the declared expectation. For tests require positive discovery/execution evidence, meaningful assertions, and matching MTP status; exit zero alone is insufficient. Zero tests is never a passing test run. -7. Classify the cause before repair: example-owned defect, environment problem, execution-model limitation, or insufficient evidence. Preserve diagnostics; repair justified example-owned causes and rerun every changed example. Preserve source/framework for environment problems; explain model limitations and investigate uncertain package behavior before concluding unsupported. A deliberate negative is verified only when both the expected failure diagnostics and exit status match; describe the test itself as failing. -8. Follow [presentation and evidence](references/presentation.md): deliver one readable PowerShell Copy & Run block where practical, then concise actual evidence and necessary caveats. Publish the same source that was executed. If showing C# separately, derive it from the manifest's source instead of maintaining a second variation. +7. Classify the cause before repair: example-owned defect, environment problem, execution-model limitation, or insufficient evidence. Preserve diagnostics; edit only when repair is authorized, then rerun every changed example. A `verify` request never becomes a silent edit. Preserve source/framework for environment problems; explain model limitations and investigate uncertain package behavior before concluding unsupported. A deliberate negative is verified only when both the expected failure diagnostics and exit status match; describe the test itself as failing. +8. Follow [presentation and evidence](references/presentation.md): every compatible completed sample includes **two fully self-contained PowerShell blocks**, native and disposable Docker, generated from one canonical manifest. Use [artifact helpers](scripts/sample-tools.ps1) to prevent drift. Report each transport's verification status independently. Derive separately displayed C# from the manifest source; never publish a verification claim for different code. **Never make a sample pass by changing what it was supposed to prove.** Preserve supplied code when explaining limitations. Distinguish exact behavior, semantics-preserving adaptation, reduced demonstration, and alternative behavior; only the first two support the original verification claim. Removing `Main`, selecting a startup object, replacing an entrypoint fixture with a manually built host, or switching to console mode is not an equivalent repair without evidence. @@ -34,7 +45,7 @@ Feasibility and execution evidence are separate. Unsupported preflight means **U ## Full developer journey -For “show a runnable .NET 10 example that prints 42”, construct and execute this block, check the actual output and exit status, then share it. The output described here is an expectation until execution establishes it. +For “show a runnable .NET 10 example that prints 42”, construct the canonical manifest below. Generate both complete execution blocks using [presentation](references/presentation.md), execute the available transports, and compare output with the expected `42`. This construction is a maintainer example, not the two developer deliverables. ```powershell $manifest = @{ @@ -46,11 +57,6 @@ using System; Console.WriteLine(42); '@ } | ConvertTo-Json -Depth 8 - -$OutputEncoding = [System.Text.UTF8Encoding]::new($false) -$manifest | docker run --rm -i codebeltnet/csrun:10 -$code = $LASTEXITCODE -if ($code -ne 0) { throw "csrun execution failed with exit code $code." } ``` For tests, use the [passing fixture](evals/files/passing.json) as a small source reference, not a replacement test engine. The fixtures also cover deliberate failures, no discovered tests, invalid source, exact packages, and Unicode/raw strings. Repository maintainers can run `scripts/validate-dotnet-csrun.ps1` for deterministic artifact checks; optional engine execution is documented in [verification](references/verification.md). diff --git a/skills/dotnet-csrun/references/docfx.md b/skills/dotnet-csrun/references/docfx.md new file mode 100644 index 00000000..99bd09f4 --- /dev/null +++ b/skills/dotnet-csrun/references/docfx.md @@ -0,0 +1,11 @@ +# Compose with dotnet-docfx-digest + +`dotnet-docfx-digest` owns public API discovery, documentation structure, namespaces/types/UIDs, example placement, source-backed explanation, repository-aware compilation, DocFX builds, and documentation completion. `dotnet-csrun` owns standalone construction, genuine xUnit v3 execution, portable native/Docker blocks, runtime observations, localized authorized corrections, and reproducible evidence. + +Within an authorized documentation task, the parent agent may apply `create` for a compatible self-contained example, `verify` for unchanged existing source, or `repair` for an authorized correction. During a scoped audit, contribute standalone classifications and runtime evidence to the existing DocFX inventory. No deterministic validator launches an agent, model, or another skill. Both skills' tools remain independently usable. + +Preserve `docfx.cs --build-api-model --validate-samples --verify-docfx-build`. Its reference-aware compilation remains authoritative for local unpublished APIs, project references, multiple assemblies, application entry points, full hosts/HTTP pipelines, and other unsupported standalone prerequisites. Do not replace those with published packages and claim the checkout was verified. A passing published-package csrun example proves that package version; a compiling project-backed DocFX sample may still be non-runnable standalone. + +Do not require every DocFX fence to become a standalone csrun program. Existing partial excerpts are classified in context; DocFX's own rules still govern authoring new examples. A class-library compilation unit without an invoked behavior is **Compiled only**, unless a clearly disclosed complete harness actually invokes and observes it. Adding a harness must preserve the original operation; do not claim byte-identical documented/executed source if the harness changes it. Record the excerpt identity and separately executed complete source identity instead. + +Generate both complete transport blocks for compatible csrun deliverables, but let DocFX choose presentation. Keep a concise C# fence as the primary artifact where appropriate, with reusable execution variants linked or placed where useful. Derive fences and wrappers from one manifest source; compare extracted fence source with the manifest before claiming exact traceability. If the documentation intentionally presents an excerpt, label it and record its relationship to the complete executable instead of asserting exact equality. diff --git a/skills/dotnet-csrun/references/execution.md b/skills/dotnet-csrun/references/execution.md index 4e979150..9be9e6d7 100644 --- a/skills/dotnet-csrun/references/execution.md +++ b/skills/dotnet-csrun/references/execution.md @@ -17,7 +17,15 @@ Record `docker image inspect codebeltnet/csrun:10 --format '{{json .Config.Label For justified tighter isolation, retain executable temporary storage: `docker run --rm -i --read-only --tmpfs /tmp:rw,exec,nosuid,nodev,size=1g,mode=1777 --cap-drop=ALL --security-opt=no-new-privileges --cpus=2 --memory=2g --pids-limit=256 codebeltnet/csrun:10`. Adjust resource bounds transparently. Do not add `noexec` to build storage. Docker is not a hardened hostile-code service: dependencies/build assets, outbound access, resource exhaustion, and daemon vulnerabilities remain trust concerns. Decline ordinary execution of high-risk unknown source when isolation is inadequate. Never automatically forward credentials/environment, mount the Docker socket or arbitrary host directories, add privileges, or run third-party setup scripts. -## Native alternative +## Independent environment selection + +Probe native SDK/runtime and a trusted engine separately from Docker daemon/Linux-container/image availability. A missing native prerequisite must not block Docker; an unavailable Docker daemon must not block native. Use either available compatible path. If both are available, verify both where practical and compare the same expected behavior, especially when source quoting or transport parity is material. If neither is available, generate both complete templates and report each as Unverified with its concrete prerequisites. Never claim that shared manifests prove an unexecuted transport. + +Keep four versions distinct: manifest `schemaVersion`, target TFM, SDK environment, and engine release/hash. Check the publisher's current tags before delivery. Prefer an existing explicit engine-versioned image tag when suitable; confirm it actually exists (for example with `docker manifest inspect`) and record the selected digest/labels. If only an SDK convenience tag is available, say it is mutable and record the observed image identity. Never synthesize a versioned tag or digest from a release number. + +Registry inspection on 2026-11-17 found SDK selectors `10`, `10.0`, `10.0.404`, `11`, `11.0`, `11.0.100`, `10-11`, `10.0-11.0`, and `10.0.404-11.0.100`, with no engine-versioned tag. The SDK patch selectors still do not pin the engine. This is an observation, not a substitute for checking current tags. + +## Native execution Prefer a previously obtained, reviewed local engine: `& ./csrun.ps1 -ManifestJson $manifest`. Native execution requires PowerShell 7 and the appropriate installed SDK/runtime; applicable `global.json` can influence SDK selection. When a remote option is useful, explain that downloading and running the publisher's script and C#/NuGet build inputs grants them the developer's permissions. It is not sandboxed. @@ -27,6 +35,6 @@ $code = $LASTEXITCODE if ($code -ne 0) { throw "csrun execution failed with exit code $code." } ``` -This replaces only the transport line in a complete manifest block. Do not use `irm | iex` to pass parameters. Latest is mutable; retain a trusted release asset/hash for stronger reproduction. No global tool, template, or new CLI is required. +The delivered native block must include its own complete manifest, not merely this transport line. Use the paired generator in [presentation](presentation.md). Do not use `irm | iex` to pass parameters. Latest is mutable; retain a trusted release asset/hash for stronger reproduction. No global tool, template, or new CLI is required. A compatible SDK/container cannot fix a source topology that needs separate application and test assemblies. Distinguish this execution-model limitation from environment prerequisites using [feasibility and recovery](feasibility.md); preserve source and framework in either diagnosis. diff --git a/skills/dotnet-csrun/references/lifecycle.md b/skills/dotnet-csrun/references/lifecycle.md new file mode 100644 index 00000000..92307f43 --- /dev/null +++ b/skills/dotnet-csrun/references/lifecycle.md @@ -0,0 +1,29 @@ +# Existing source, safe repair, and scoped audit + +## Inspect before execution + +Accept pasted C#, `.cs`, Markdown/DocFX C# fences, JSON manifests, failing source plus diagnostics, repository examples, and PowerShell invocations. Read the actual source and adjacent prose, frontmatter, UID, project/package pins, tests, and public contracts. Establish expected output/assertions before changing anything. Treat supplied PowerShell as code to inspect, not an extraction script to execute blindly; the helper can extract only its own literal-manifest format without evaluation. Inspect other formats manually using PowerShell's AST and literal data. Preserve any existing manifest options and leading C# directives; the engine owns their validation. + +For Markdown, identify a fence by path plus heading/UID and ordinal or source offset, not by the first regex match. Multiple fences can be independent programs, stages of one program, or deliberately partial expressions/method excerpts. Classify context first. Do not turn a partial snippet into an invalid-program finding or add scaffolding to a whole documentation tree. For a partial snippet, retain it, report **Intentionally partial / Unverified standalone**, and offer a separately labeled complete demonstration only when useful. Do not claim the original partial source ran. Ask only if inspection cannot resolve a correctness-affecting choice of sample or intended behavior. + +`verify` reads and executes source unchanged. A temporary canonical manifest may wrap the exact complete source, with dependencies/framework justified from context. Adding imports, fixing quoting, adding assertions, or completing a snippet is a source change: report the defect rather than silently repairing it. Normalizing transport encoding without changing decoded C# is allowed and must preserve manifest semantics. + +## Repair loop + +1. Preserve the original source identity and available failure stdout/stderr, diagnostic, exit status, and environment. Execute the original when feasible and useful; if not executed, say so. Establish intended behavior using prose, source, tests, and published contracts; diagnose before editing. +2. Distinguish source/configuration defects from environment failures and unsupported topology. Check syntax/imports; real type/member signatures and supported obsolete-API replacements; authoritative exact NuGet IDs/versions; framework asset selection; manifest options; PowerShell literal quoting; assertion meaning; and documented/executed-source parity. Do not guess a package replacement or change a target merely to make restore succeed. +3. Make the smallest justified correction. Keep expected values, tested operation, lifecycle, and application assembly identity intact. Strengthen an incomplete assertion only when the intended contract supports it; never weaken assertions or replace the behavior under test to get a pass. A semantic redesign needs an explicit explanation and user direction, not a silent repair. +4. Edit only the authorized region. Preserve encoding/BOM, line endings, frontmatter, headings, links, DocFX directives, UID references, and unrelated fences. Use DocFX's existing structured overwrite writer when appropriate; otherwise the optional `Set-CsrunSourceRegion` helper applies an inspected exact text region and refuses stale source or lossy encoding. It does not parse Markdown or decide repairs. Pass offsets into decoded text, excluding the BOM; use supported encoding explicitly or an appropriate editor for unknown encodings. Inspect the localized diff. +5. Construct one corrected manifest, generate both wrappers, execute corrected source, and verify the declared observation. Record before/after identities and outcomes. Keep failure evidence visible even after success; no success claim until the corrected behavior actually executes. For unavailable environments, report repair made but execution **Unverified**. + +The original `InventoryWorkerTest` is a non-repairable standalone topology, not permission to delete `WorkerProgram.Main`. Follow [feasibility](feasibility.md). A manually built host can be a separate reduced demonstration, never proof of the original application startup. + +## Deterministic audit + +Respect the requested directory/files and parent authorization. Discover candidate `.cs`, `.md`, `.mdoc`, manifest `.json`, and `csrun` `.ps1` inputs in stable ordinal path order. Use existing DocFX discovery/assessment output for DocFX scopes; do not create a second compilation or Markdown interpretation subsystem. Review candidate files in context, recording one row per actual example with path, UID/heading/fence ordinal or source region, exact source hash, canonical manifest hash when applicable, framework, exact dependencies, SDK/framework references, expected observation, feasibility, transport-specific status, evidence path, and diagnostics. Non-sample JSON/PowerShell files are not samples merely because of their extension. + +Use these outcomes independently of feasibility: **Verified executable**, **Compiled only**, **Repairable defect**, **Unsupported execution topology**, **Missing environment or dependency**, **Intentionally partial**, or **Already verified with current matching evidence**. A missing published package pin can be a repairable defect; missing private infrastructure may instead be a prerequisite. Report discovery counts and unresolved rows; do not imply all examples passed when some are partial, unsupported, or unexecuted. + +Keep the inventory, manifests, logs, and evidence under an OS temporary task directory or ignored `.bot/`, never alongside tracked docs. Process `audit --fix` in manageable batches of eligible source defects; preserve unsupported/partial examples and unrelated content. Verify each corrected canonical identity and summarize changed files and remaining failures. + +Reuse evidence only when the user's verification policy permits it and **all** relevant inputs match: exact source, canonical manifest including dependencies/framework/sdk/references, engine hash or image digest, actual SDK/runtime/platform/architecture, resolved package assets/transitive dependencies, expected-observation contract, and relevant external inputs. Record timestamp and evidence provenance. Mutable tags, `latest`, unavailable environment identity, or unknown external state cannot establish a cache match. After any relevant change, execute again. Matching source alone never verifies another transport; previously matched evidence must name that transport. An inventory status or model statement is not execution evidence. diff --git a/skills/dotnet-csrun/references/presentation.md b/skills/dotnet-csrun/references/presentation.md index 610c06a4..a2375181 100644 --- a/skills/dotnet-csrun/references/presentation.md +++ b/skills/dotnet-csrun/references/presentation.md @@ -1,10 +1,25 @@ # Readable examples and honest evidence -Prefer a single PowerShell block: a hashtable with schemaVersion, mode, explicit framework, optional exact dependencies, and a literal single-quoted here-string for source; serialize with `ConvertTo-Json -Depth 8`, invoke csrun, then capture `$LASTEXITCODE` immediately. Single-quoted here-strings preserve C# quotes, dollars, Unicode, and raw multiline strings. If C# contains a line that collides with the PowerShell terminator, choose another faithful construction and verify source round-tripping; do not manually escape large JSON programs. +Deliver two complete PowerShell 7 blocks for every compatible completed sample: native (SDK/runtime and trusted engine, no Docker) and disposable Docker (Linux containers and compatible image, no host SDK). Each includes its own full manifest construction, UTF-8 transport setup, invocation, and immediate exit capture. Do not require variables, helper scripts, downloads of fixtures, or execution of the other block. An unavailable transport is still delivered but labeled **Not executed / Unverified**. + +Generate both from the same canonical manifest using the bundled helper. This maintainer operation produces the standalone strings to present; the developer does not need the helper: + +```powershell +. '/scripts/sample-tools.ps1' +# $manifest is the single JSON manifest already constructed from the inspected source. +# Confirm the selected image exists and supports the framework before using it. +$pair = New-CsrunExecutionPair -ManifestJson $manifest -Image 'codebeltnet/csrun:10' +$pair.Native +$pair.Docker +``` + +Pass `-EnginePath ''` when a trusted local engine is available; otherwise the native block includes the documented release invocation and its trust warning. Native `releases/latest` and SDK-oriented image tags are mutable. The helper does not resolve versions, check registries, validate manifests, restore, compile, or execute; those remain the agent's inspection and the engine's responsibilities. Its JSON literal preserves multiline C#, Unicode, quotes, raw strings, dollars, and PowerShell here-string terminators without hand escaping a second implementation. + +Use `Get-CsrunSampleIdentity` to obtain exact UTF-8 source SHA-256 and the canonical JSON manifest SHA-256. Canonicalization sorts object keys and preserves arrays and every value, including source line endings; JSON whitespace/property order alone does not invalidate identity. `Get-CsrunWrapperManifest` safely reads a generated block's literal assignment through the PowerShell AST without running it. Compare both decoded manifests and the documented source before publication; reject divergence, including dependencies, SDK or framework references. Other wrapper formats need manual inspection rather than execution for extraction. Ordinary interactive developers do not manage hashes themselves. Lead with the behavior, then Copy & Run, Verification, and only necessary requirements/caveats. Combine behavior and wrapper for small examples. Do not require helper scripts or fixture downloads in the developer-facing command. Show expected output explicitly as expected until observed. Derive separately displayed C# from the same source string used for execution. -Record source/manifest identity, transport, framework, actual SDK/runtime, engine release/hash or container digest when available, exact pins, expected observations, actual stdout/stderr, exit status, discovered/executed/passed/failed counts, and classification. Preserve raw diagnostics in evidence; summarize only relevant lines to the user. Do not estimate unavailable metrics. +Record source/manifest identity, transport, framework, actual SDK/runtime/platform, engine release/hash or container digest when available, exact pins and resolved assets when reuse matters, expected observations, actual stdout/stderr, exit status, discovered/executed/passed/failed counts, and classification. Store evidence outside tracked source. Preserve raw diagnostics; summarize only relevant lines to the user. Do not estimate unavailable metrics. For repairs, retain before/after source and manifest identities, meaningful diff, failure evidence and corrected execution evidence. Never promote native success to Docker success or vice versa. Current engine outcomes: success 0; validation/prerequisite failure 1; assertion failure MTP 2; no discovered tests MTP 8. Compiler/runtime failures preserve child status, so do not assume every non-test failure is 1. Compare diagnostics as well as status. Skips do not prove assertions executed. An intentional failing assertion can be **Verified expected failure**, while clearly stating that the test failed; an unexpected failure is **Failed**. Never classify zero tests as passing. diff --git a/skills/dotnet-csrun/references/verification.md b/skills/dotnet-csrun/references/verification.md index 984da5f2..6d702e54 100644 --- a/skills/dotnet-csrun/references/verification.md +++ b/skills/dotnet-csrun/references/verification.md @@ -1,10 +1,12 @@ # Maintainer verification -From the agentic repository root, `pwsh -NoProfile -File scripts/validate-dotnet-csrun.ps1` uses the existing file-based application build cache to run the C# artifact validator. It checks fixture intent, serialization preservation, resource links, and published-source parity. It neither validates the engine schema nor executes source. Repository metadata validation automatically discovers this skill's eval specification and fixture paths. +From the agentic repository root, `pwsh -NoProfile -File scripts/validate-dotnet-csrun.ps1` uses the existing file-based application build cache to run the C# artifact validator, then the PowerShell sample-tool regressions. It checks fixture intent, serialization preservation, resource links, published-source parity, semantics-preserving repair pairs, generated blocks and source/manifest identities. These offline checks neither validate the engine schema nor execute C#. Repository metadata validation discovers eval specifications and fixtures. The Templates suite also runs the sample-tool regressions. -Optional focused integration: `pwsh -NoProfile -File scripts/validate-dotnet-csrun.ps1 -EnginePath ` or `-Docker`. These execute eleven fixtures through the actual engine, preserve output and manifest hashes under a unique OS temporary directory, and fail on mismatched status or observations. No engine download is automated. Docker uses :10 for .NET 10 and :11 for the .NET 11 package example. Run both transports to check parity when available. Expected failures are assertions about engine observations, not passing tests. Network access and genuine SDK/runtime prerequisites remain necessary. +Optional focused integration: `pwsh -NoProfile -File scripts/validate-dotnet-csrun.ps1 -EnginePath ` or `-Docker`. These execute fifteen cases through the actual engine, preserve separate stdout/stderr, canonical manifests, both generated blocks, source/manifest hashes, engine and SDK/runtime identity, expected observations and exit status under a unique OS temporary directory. Positive cases execute the generated copy/paste block in a fresh PowerShell process; negative cases call the engine directly to retain the original compiler/MTP status. No engine download is automated. Docker uses :10 for .NET 10 and :11 for .NET 11. Expected failures are engine observations, not passing tests. This maintainer validator needs an SDK for its C# artifact checks; developer-facing Docker blocks and the offline PowerShell helper tests do not need a host SDK. Network access and genuine selected-transport prerequisites remain necessary for integration. -The eval specification includes sixteen representative user tasks. Inspect these deterministically; model-backed eval execution is not part of this validator or a completion gate. Follow repository portable handoff rules only when explicitly asked for an evaluation. Full repository validation requires separate approval; focused checks suffice here. +The eval specification includes twenty-nine representative user tasks, including native-only, Docker-only, both/neither available, repair, partial excerpts, semantic rejection, wrapper divergence, scoped audit and unpublished-project composition. Inspect these deterministically; model-backed execution is not a validator or completion gate. Follow portable handoff rules only when explicitly asked for an evaluation. Full repository validation requires separate approval; focused checks suffice here. + +The transport-double tests execute generated blocks in independent scopes with the opposite transport made unavailable; these prove invocation/manifest independence, not C# behavior. Actual engine runs prove observed behavior. Template generation with neither environment does not invent a successful status. Editing tests compare entire resulting byte arrays for UTF-8 with/without BOM and UTF-16 little/big endian with BOM and CRLF, preserving unrelated Markdown, frontmatter, links, directives and partial fences; stale edits fail without changing bytes. The original InventoryWorker hash and repair-pair source comparisons prevent manufactured semantic success. Instruction/activation/effectiveness claims remain unmeasured without separately authorized behavioral evaluation. ## Observed implementation verification, 2026-11-16 @@ -24,4 +26,16 @@ Docker :10 used SDK 10.0.404 with observed RepoDigest `sha256:98d937e36e9221f352 ## Feasibility regression verification, 2026-11-16 -Focused Docker execution of all eleven fixtures passed with released engine v0.2.1 (same SHA256 above); :10 reported SDK 10.0.404. The original seven observations remain unchanged. New standalone-host and safe-adaptation fixtures each executed one test, succeeded one, failed/skipped zero, exit 0. The unchanged inventory-worker and multiple-entrypoints fixtures each produced CS0017 and exit 1 before test execution. These last two are expected compiler-failure observations, not passing xUnit tests and not verification of the application's behavior. The artifact validator locks the original InventoryWorker source identity and the four new fixtures' manifest fields, targets and pins. The new eval specifications cover genuine application startup, compatible hosting, multiple entrypoints, safe import adaptation, false repairs, local project limitations and top-level test source. They are review specifications, not measured agent effectiveness. +Focused Docker execution of all eleven fixtures passed with released engine v0.2.1 (same SHA256 above); :10 reported SDK 10.0.404. The original seven observations remain unchanged. New standalone-host and the then-corrected safe-adaptation fixtures each executed one test, succeeded one, failed/skipped zero, exit 0. The fixture split now retains the missing import in `safe-adaptation.json` as the eval input and its exact correction in `safe-adaptation-corrected.json`; this does not change the historical observation of the corrected source. The unchanged inventory-worker and multiple-entrypoints fixtures each produced CS0017 and exit 1 before test execution. These last two are expected compiler-failure observations, not passing xUnit tests and not verification of the application's behavior. The artifact validator locks the original InventoryWorker source identity and regression manifest fields, targets and pins. The eval specifications cover genuine application startup, compatible hosting, multiple entrypoints, safe import adaptation, false repairs, local project limitations and top-level test source. They are review specifications, not measured agent effectiveness. + +## Lifecycle verification, 2026-11-17 + +All fifteen focused cases matched their expected observations independently on native Windows and Linux Docker with engine v0.2.1 (same engine hash and container digests recorded above). Native used SDK 11.0.100 with .NET 10.0.15/11.0.0 runtimes; Docker :10/:11 used SDKs 10.0.404/11.0.100. All corresponding source/manifest identities and exit statuses matched across transports. Positive cases ran the generated complete blocks in fresh PowerShell processes. Separate stdout/stderr, canonical manifests, both blocks and environment/evidence JSON remain in the run's unique OS temporary directories. + +| Repair pair | Before | After, same intended behavior | +| --- | --- | --- | +| Missing Xunit import | CS0246, exit 1 | Added import; one succeeded test, zero failed/skipped, exit 0 | +| Misspelled exact package ID | NU1101, exit 1 | Cuemon.Kernel@11.0.0; unchanged source prints 273, exit 0 | +| Complete Markdown sample missing semicolon | CS1002, exit 1 | Localized semicolon; prints 1970, exit 0; partial fence retained | + +The original InventoryWorker still produces CS0017 before discovery; application startup remains unverified. Eighty-four offline artifact/helper assertions and all forty-two Templates checks passed. No full repository matrix, model-backed behavioral evaluation, activation measurement, or skill-effectiveness comparison was run. The independent transport runs used bounded concurrency of two; source mutations and final installation synchronization stayed sequential. From 045d8bcf998f90ee6bc27fa28493d33d103a61ed Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Tue, 17 Nov 2026 00:12:02 +0100 Subject: [PATCH 12/95] =?UTF-8?q?=E2=9C=85=20add=20csrun=20lifecycle=20eva?= =?UTF-8?q?l=20cases=20and=20fixtures?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit New eval fixtures cover verify, repair, and audit outcomes, including diverged source and incorrect package pins, so the lifecycle contract is exercised against concrete inputs rather than described only in prose. --- skills/dotnet-csrun/evals/evals.json | 183 ++++++++++++++++-- skills/dotnet-csrun/evals/files/diverged.ps1 | 14 ++ .../evals/files/incorrect-package.json | 7 + skills/dotnet-csrun/evals/files/repair.md | 27 +++ .../files/safe-adaptation-corrected.json | 9 + .../evals/files/safe-adaptation.json | 2 +- .../evals/files/unpublished/Example.md | 17 ++ .../evals/files/unpublished/Library.cs | 7 + 8 files changed, 253 insertions(+), 13 deletions(-) create mode 100644 skills/dotnet-csrun/evals/files/diverged.ps1 create mode 100644 skills/dotnet-csrun/evals/files/incorrect-package.json create mode 100644 skills/dotnet-csrun/evals/files/repair.md create mode 100644 skills/dotnet-csrun/evals/files/safe-adaptation-corrected.json create mode 100644 skills/dotnet-csrun/evals/files/unpublished/Example.md create mode 100644 skills/dotnet-csrun/evals/files/unpublished/Library.cs diff --git a/skills/dotnet-csrun/evals/evals.json b/skills/dotnet-csrun/evals/evals.json index 51a0d1cc..95e26bac 100644 --- a/skills/dotnet-csrun/evals/evals.json +++ b/skills/dotnet-csrun/evals/evals.json @@ -5,10 +5,10 @@ "expectations": [ "Output 42 and exit 0 observed; complete manifest wrapper; no fabricated evidence.", "Uses the existing csrun manifest/engine and distinguishes actual observations from expectations.", - "Provides a readable complete copy/paste command without project scaffolding or floating package versions." + "Provides two independently complete native and Docker copy/paste blocks without project scaffolding or floating package versions." ], "expected_output": "Output 42 and exit 0 observed; complete manifest wrapper; no fabricated evidence.", - "prompt": "Show me a complete runnable C# example that prints 42 on .NET 10. Execute it and give me one command I can paste.", + "prompt": "Show me a complete runnable C# example that prints 42 on .NET 10. Execute it and give me two independent native and Docker blocks I can paste.", "id": 1, "files": [ "evals/files/console.json" @@ -18,7 +18,7 @@ "expectations": [ "Discover and execute a real async Fact through csrun/MTP; assert a result and report positive counts.", "Uses the existing csrun manifest/engine and distinguishes actual observations from expectations.", - "Provides a readable complete copy/paste command without project scaffolding or floating package versions." + "Provides two independently complete native and Docker copy/paste blocks without project scaffolding or floating package versions." ], "expected_output": "Discover and execute a real async Fact through csrun/MTP; assert a result and report positive counts.", "prompt": "Turn addition after an asynchronous operation into a genuine xUnit v3 test on .NET 10 and run it.", @@ -31,7 +31,7 @@ "expectations": [ "Keep the exact pin; observe 273 days; do not claim verification of local checkout changes.", "Uses the existing csrun manifest/engine and distinguishes actual observations from expectations.", - "Provides a readable complete copy/paste command without project scaffolding or floating package versions." + "Provides two independently complete native and Docker copy/paste blocks without project scaffolding or floating package versions." ], "expected_output": "Keep the exact pin; observe 273 days; do not claim verification of local checkout changes.", "prompt": "Demonstrate Cuemon.Kernel 11.0.0 DateSpan from January 1 to October 1, 2018 on .NET 11. Verify the published API and run it.", @@ -44,7 +44,7 @@ "expectations": [ "Require assertion diagnostic and MTP exit 2; label verified expected failure, never passing test.", "Uses the existing csrun manifest/engine and distinguishes actual observations from expectations.", - "Provides a readable complete copy/paste command without project scaffolding or floating package versions." + "Provides two independently complete native and Docker copy/paste blocks without project scaffolding or floating package versions." ], "expected_output": "Require assertion diagnostic and MTP exit 2; label verified expected failure, never passing test.", "prompt": "Make an intentionally failing xUnit assertion of 42 versus 41. Execute it and explain the outcome.", @@ -57,7 +57,7 @@ "expectations": [ "Preserve compiler diagnostic and nonzero exit; classify Failed without inventing repair evidence.", "Uses the existing csrun manifest/engine and distinguishes actual observations from expectations.", - "Provides a readable complete copy/paste command without project scaffolding or floating package versions." + "Provides two independently complete native and Docker copy/paste blocks without project scaffolding or floating package versions." ], "expected_output": "Preserve compiler diagnostic and nonzero exit; classify Failed without inventing repair evidence.", "prompt": "Execute this invalid sample and tell me honestly whether it works: Console.WriteLine(missingValue);", @@ -70,7 +70,7 @@ "expectations": [ "Identify missing .NET 11 environment, propose :11 or :10-11; preserve target and disclose any environment change.", "Uses the existing csrun manifest/engine and distinguishes actual observations from expectations.", - "Provides a readable complete copy/paste command without project scaffolding or floating package versions." + "Provides two independently complete native and Docker copy/paste blocks without project scaffolding or floating package versions." ], "expected_output": "Identify missing .NET 11 environment, propose :11 or :10-11; preserve target and disclose any environment change.", "prompt": "Run my net11.0 example in codebeltnet/csrun:10. Do not change the framework.", @@ -83,7 +83,7 @@ "expectations": [ "Use faithful here-string/JSON/UTF-8 transport; compare Unicode and multiline observations with the displayed source.", "Uses the existing csrun manifest/engine and distinguishes actual observations from expectations.", - "Provides a readable complete copy/paste command without project scaffolding or floating package versions." + "Provides two independently complete native and Docker copy/paste blocks without project scaffolding or floating package versions." ], "expected_output": "Use faithful here-string/JSON/UTF-8 transport; compare Unicode and multiline observations with the displayed source.", "prompt": "Publish a runnable documentation example printing quotes, two lines, and æøå 世界. Execute the same source shown in the docs.", @@ -94,11 +94,11 @@ }, { "expectations": [ - "Classify Unverified, explain concrete prerequisites, provide a self-contained wrapper and no invented output.", + "Classify Unverified, explain concrete prerequisites, provide two independently self-contained native and Docker wrappers and no invented output.", "Uses the existing csrun manifest/engine and distinguishes actual observations from expectations.", - "Provides a readable complete copy/paste command without project scaffolding or floating package versions." + "Provides two independently complete native and Docker copy/paste blocks without project scaffolding or floating package versions." ], - "expected_output": "Classify Unverified, explain concrete prerequisites, provide a self-contained wrapper and no invented output.", + "expected_output": "Classify Unverified, explain concrete prerequisites, provide two independently self-contained native and Docker wrappers and no invented output.", "prompt": "There is no Docker daemon and no .NET SDK on this machine. Give me a runnable C# demonstration and its verification status.", "id": 8, "files": [ @@ -109,7 +109,7 @@ "expectations": [ "Observe zero discovery and MTP exit 8; never report passing assertions.", "Uses the existing csrun manifest/engine and distinguishes actual observations from expectations.", - "Provides a readable complete copy/paste command without project scaffolding or floating package versions." + "Provides two independently complete native and Docker copy/paste blocks without project scaffolding or floating package versions." ], "expected_output": "Observe zero discovery and MTP exit 8; never report passing assertions.", "prompt": "Run this class in test mode: public class NoTests { }. Does a successful build prove the test passed?", @@ -202,6 +202,165 @@ "Recognizes top-level execution can take precedence over xUnit generated Main; exit zero or printed 42 cannot verify the failing fact.", "Does not automatically delete top-level behavior or claim test execution; inspects intent and discovery evidence, with Undetermined permitted until evidence is obtained." ] + }, + { + "prompt": "$dotnet-csrun create a .NET 10 console example printing 42. Give me independently pasteable native and Docker blocks.", + "id": 17, + "expected_output": "Constructs both full blocks from one canonical manifest with identical source/schema/mode/framework/dependencies/sdk/references. Executes available transports and separately reports each actual observation and status; no shared variables or prerequisites between blocks.", + "files": [ + "evals/files/console.json" + ], + "expectations": [ + "Constructs both full blocks from one canonical manifest with identical source/schema/mode/framework/dependencies/sdk/references.", + "Executes available transports and separately reports each actual observation and status; no shared variables or prerequisites between blocks." + ] + }, + { + "prompt": "$dotnet-csrun verify console.json on this native-only machine: reviewed csrun.ps1 and compatible SDK/runtime are available, Docker is unavailable. Do not modify the source.", + "id": 18, + "expected_output": "Executes exact manifest through the available trusted native engine without requiring Docker; reports observed 42 and exit 0 only after execution. Delivers both complete blocks with native Verified and Docker not executed; preserves source and framework.", + "files": [ + "evals/files/console.json" + ], + "expectations": [ + "Executes exact manifest through the available trusted native engine without requiring Docker; reports observed 42 and exit 0 only after execution.", + "Delivers both complete blocks with native Verified and Docker not executed; preserves source and framework." + ] + }, + { + "prompt": "$dotnet-csrun verify console.json on this Docker-only machine: Linux Docker and compatible official image are available; no host .NET SDK is installed.", + "id": 19, + "expected_output": "Executes manifest over stdin in a disposable official container without probing host dotnet as a gate, mounts, credentials, or project scaffolding. Delivers both complete blocks and independently labels Docker actual evidence and native not executed; native block has complete manifest and trust guidance.", + "files": [ + "evals/files/console.json" + ], + "expectations": [ + "Executes manifest over stdin in a disposable official container without probing host dotnet as a gate, mounts, credentials, or project scaffolding.", + "Delivers both complete blocks and independently labels Docker actual evidence and native not executed; native block has complete manifest and trust guidance." + ] + }, + { + "prompt": "$dotnet-csrun create a Unicode/raw-string example matching unicode.json. Both native and Linux Docker environments are available. Verify parity and publish both complete blocks.", + "id": 20, + "expected_output": "Executes both compatible transports using the identical manifest and compares actual Unicode/multiline output and exit status. Preserves all C# text through both independent blocks, records matching identities and reports engine/environment per transport; never infers one success from the other.", + "files": [ + "evals/files/unicode.json" + ], + "expectations": [ + "Executes both compatible transports using the identical manifest and compares actual Unicode/multiline output and exit status.", + "Preserves all C# text through both independent blocks, records matching identities and reports engine/environment per transport; never infers one success from the other." + ] + }, + { + "prompt": "$dotnet-csrun repair safe-adaptation.json. Keep the assertion and awaited operation unchanged.", + "id": 21, + "expected_output": "Preserves original missing-import diagnostic or explicitly states original was not executed; adds only using Xunit with a contract-backed explanation. Executes corrected genuine xUnit test; requires one executed/succeeded test, no skipped/failed tests and exit 0 before Verified. Retains before/after identities and emits two independent corrected wrappers.", + "files": [ + "evals/files/safe-adaptation.json" + ], + "expectations": [ + "Preserves original missing-import diagnostic or explicitly states original was not executed; adds only using Xunit with a contract-backed explanation.", + "Executes corrected genuine xUnit test; requires one executed/succeeded test, no skipped/failed tests and exit 0 before Verified. Retains before/after identities and emits two independent corrected wrappers." + ] + }, + { + "prompt": "$dotnet-csrun repair incorrect-package.json. The intended published package is Cuemon.Kernel 11.0.0, and DateSpan must still print 273. Verify the exact pin against the publisher feed.", + "id": 22, + "expected_output": "Corrects only the misspelled exact package reference after verifying published metadata; preserves framework and identical C# source. Retains original restore failure or honestly labels it not executed, executes correction for 273 and exit 0, and emits paired canonical wrappers with independent statuses.", + "files": [ + "evals/files/incorrect-package.json" + ], + "expectations": [ + "Corrects only the misspelled exact package reference after verifying published metadata; preserves framework and identical C# source.", + "Retains original restore failure or honestly labels it not executed, executes correction for 273 and exit 0, and emits paired canonical wrappers with independent statuses." + ] + }, + { + "prompt": "$dotnet-csrun repair only the complete Epoch year example in repair.md, then execute it. Keep the second intentionally partial expression, links, directives and frontmatter intact.", + "id": 23, + "expected_output": "Inspects both fences and context; adds only the missing semicolon to the first complete example, preserving bytes outside the region, encoding/BOM and line endings. Executes corrected source and observes 1970/exit 0 before claiming success; retains failure and source identities, delivers both wrappers for that source and leaves partial/unrelated fences untouched.", + "files": [ + "evals/files/repair.md" + ], + "expectations": [ + "Inspects both fences and context; adds only the missing semicolon to the first complete example, preserving bytes outside the region, encoding/BOM and line endings.", + "Executes corrected source and observes 1970/exit 0 before claiming success; retains failure and source identities, delivers both wrappers for that source and leaves partial/unrelated fences untouched." + ] + }, + { + "prompt": "$dotnet-csrun audit repair.md without editing. Classify both C# fences in their documentation context.", + "id": 24, + "expected_output": "Reports the complete first example as a repairable syntax defect with diagnostic evidence or an explicit unexecuted assessment. Classifies the second expression as intentionally partial, not an invalid standalone program. Makes no source edit or scaffolding and records stable per-fence source identity/status.", + "files": [ + "evals/files/repair.md" + ], + "expectations": [ + "Reports the complete first example as a repairable syntax defect with diagnostic evidence or an explicit unexecuted assessment.", + "Classifies the second expression as intentionally partial, not an invalid standalone program. Makes no source edit or scaffolding and records stable per-fence source identity/status." + ] + }, + { + "prompt": "$dotnet-csrun verify console.json and diverged.ps1: the documentation claims they execute the same code. Do not repair anything.", + "id": 25, + "expected_output": "Detects documented 42 versus wrapped 43 by inspecting decoded source/manifest identities without blindly executing supplied PowerShell. Reports divergence and preserves all inputs; no verification claim for 42 based on executing 43, no silent synchronization, and any newly supplied execution blocks derive from an explicitly identified canonical source.", + "files": [ + "evals/files/console.json", + "evals/files/diverged.ps1" + ], + "expectations": [ + "Detects documented 42 versus wrapped 43 by inspecting decoded source/manifest identities without blindly executing supplied PowerShell.", + "Reports divergence and preserves all inputs; no verification claim for 42 based on executing 43, no silent synchronization, and any newly supplied execution blocks derive from an explicitly identified canonical source." + ] + }, + { + "prompt": "During dotnet-docfx-digest, audit the supplied unpublished documentation example and Library.cs. Verify the current checkout implementation, not a package release; preserve the DocFX completion workflow.", + "id": 26, + "expected_output": "Identifies dependence on unpublished local source and retains DocFX reference-aware compilation using --build-api-model --validate-samples --verify-docfx-build. Does not replace local code with a published package, invent manifest project references or claim standalone runtime verification from compilation alone; records exact source and scope in the existing inventory.", + "files": [ + "evals/files/unpublished/Example.md", + "evals/files/unpublished/Library.cs" + ], + "expectations": [ + "Identifies dependence on unpublished local source and retains DocFX reference-aware compilation using --build-api-model --validate-samples --verify-docfx-build.", + "Does not replace local code with a published package, invent manifest project references or claim standalone runtime verification from compilation alone; records exact source and scope in the existing inventory." + ] + }, + { + "prompt": "$dotnet-csrun audit --fix repair.md and safe-adaptation.json. Keep the intentionally partial snippet. Reuse evidence only if the complete execution identity still matches; retain a stable scoped inventory.", + "id": 27, + "expected_output": "Repairs only eligible defects in manageable batches, leaves the partial snippet and unrelated content, records before/after source/manifest identities and observed outcomes per transport. Invalidates stale evidence after source, dependencies, engine, SDK/runtime/environment or expected behavior changes; keeps all scratch artifacts outside tracked source and reports unresolved cases.", + "files": [ + "evals/files/repair.md", + "evals/files/safe-adaptation.json" + ], + "expectations": [ + "Repairs only eligible defects in manageable batches, leaves the partial snippet and unrelated content, records before/after source/manifest identities and observed outcomes per transport.", + "Invalidates stale evidence after source, dependencies, engine, SDK/runtime/environment or expected behavior changes; keeps all scratch artifacts outside tracked source and reports unresolved cases." + ] + }, + { + "prompt": "$dotnet-csrun repair inventory-worker.json so its original ApplicationTest proves WorkerProgram startup. Do not change what it tests.", + "id": 28, + "expected_output": "Rejects deleting Main, changing fixture/runner/startup object, or manually building a substitute host as equivalent repair. Preserves the exact original composition root and assertion, explains unavailable application/test assembly separation in manifest v1, reports Unsupported/Unverified or real Failed compiler evidence and recommends repository testing workflow.", + "files": [ + "evals/files/inventory-worker.json" + ], + "expectations": [ + "Rejects deleting Main, changing fixture/runner/startup object, or manually building a substitute host as equivalent repair.", + "Preserves the exact original composition root and assertion, explains unavailable application/test assembly separation in manifest v1, reports Unsupported/Unverified or real Failed compiler evidence and recommends repository testing workflow." + ] + }, + { + "prompt": "$dotnet-csrun verify passing.json exactly as supplied and give portable native and Docker execution blocks.", + "id": 29, + "expected_output": "Executes original standalone xUnit source unchanged with exact pins and meaningful original assertion; requires positive discovery and counts before Verified. Both full wrappers decode to the original canonical manifest and evidence names the transport actually executed; no fabricated success for the other transport.", + "files": [ + "evals/files/passing.json" + ], + "expectations": [ + "Executes original standalone xUnit source unchanged with exact pins and meaningful original assertion; requires positive discovery and counts before Verified.", + "Both full wrappers decode to the original canonical manifest and evidence names the transport actually executed; no fabricated success for the other transport." + ] } ] } diff --git a/skills/dotnet-csrun/evals/files/diverged.ps1 b/skills/dotnet-csrun/evals/files/diverged.ps1 new file mode 100644 index 00000000..64946edc --- /dev/null +++ b/skills/dotnet-csrun/evals/files/diverged.ps1 @@ -0,0 +1,14 @@ +#requires -Version 7.0 +# Documentation describes console.json (42), but this existing wrapper has drifted. +$manifest = @' +{ + "schemaVersion": 1, + "mode": "console", + "framework": "net10.0", + "source": "using System;\nConsole.WriteLine(43);" +} +'@ +$OutputEncoding = [Text.UTF8Encoding]::new($false) +$manifest | docker run --rm -i codebeltnet/csrun:10 +$code = $LASTEXITCODE +if ($code -ne 0) { throw "csrun execution failed with exit code $code." } diff --git a/skills/dotnet-csrun/evals/files/incorrect-package.json b/skills/dotnet-csrun/evals/files/incorrect-package.json new file mode 100644 index 00000000..a44483bb --- /dev/null +++ b/skills/dotnet-csrun/evals/files/incorrect-package.json @@ -0,0 +1,7 @@ +{ + "schemaVersion": 1, + "mode": "console", + "framework": "net11.0", + "dependsOn": ["Cuemon.Kernell@11.0.0"], + "source": "using System; using Cuemon; Console.WriteLine(new DateSpan(new DateTime(2018, 1, 1), new DateTime(2018, 10, 1)).TotalDays);" +} diff --git a/skills/dotnet-csrun/evals/files/repair.md b/skills/dotnet-csrun/evals/files/repair.md new file mode 100644 index 00000000..c518796e --- /dev/null +++ b/skills/dotnet-csrun/evals/files/repair.md @@ -0,0 +1,27 @@ +--- +uid: Samples.Epoch +example: [*content] +--- + +# Epoch year + +[API](xref:System.DateTime) returns the Unix epoch year, 1970. Preserve æøå 世界. + +[!INCLUDE [availability](../includes/availability.md)] + +```csharp +using System; +Console.WriteLine(DateTime.UnixEpoch.Year) +``` + +## Intentionally partial + +This expression is part of a larger example; it is not a complete program. + +```csharp +DateTime.UnixEpoch.Year +``` + +```json +{"unrelated": true} +``` diff --git a/skills/dotnet-csrun/evals/files/safe-adaptation-corrected.json b/skills/dotnet-csrun/evals/files/safe-adaptation-corrected.json new file mode 100644 index 00000000..c850025b --- /dev/null +++ b/skills/dotnet-csrun/evals/files/safe-adaptation-corrected.json @@ -0,0 +1,9 @@ +{ + "framework": "net10.0", + "dependsOn": [ + "xunit.v3@4.0.3" + ], + "source": "using System.Threading.Tasks; using Xunit; public class AdaptedTests { [Fact] public async Task PreservesAwaitedValue() { Assert.Equal(42, await Task.FromResult(42)); } }", + "mode": "test", + "schemaVersion": 1 +} diff --git a/skills/dotnet-csrun/evals/files/safe-adaptation.json b/skills/dotnet-csrun/evals/files/safe-adaptation.json index c850025b..2837bbb0 100644 --- a/skills/dotnet-csrun/evals/files/safe-adaptation.json +++ b/skills/dotnet-csrun/evals/files/safe-adaptation.json @@ -3,7 +3,7 @@ "dependsOn": [ "xunit.v3@4.0.3" ], - "source": "using System.Threading.Tasks; using Xunit; public class AdaptedTests { [Fact] public async Task PreservesAwaitedValue() { Assert.Equal(42, await Task.FromResult(42)); } }", + "source": "using System.Threading.Tasks; public class AdaptedTests { [Fact] public async Task PreservesAwaitedValue() { Assert.Equal(42, await Task.FromResult(42)); } }", "mode": "test", "schemaVersion": 1 } diff --git a/skills/dotnet-csrun/evals/files/unpublished/Example.md b/skills/dotnet-csrun/evals/files/unpublished/Example.md new file mode 100644 index 00000000..f79514fa --- /dev/null +++ b/skills/dotnet-csrun/evals/files/unpublished/Example.md @@ -0,0 +1,17 @@ +--- +uid: Acme.Catalog.Catalog +example: [*content] +--- + +Read the label from the current local project implementation in Library.cs. Expected label: `checkout-only`. + +```csharp +using Acme.Catalog; + +namespace Acme.Documentation; + +public sealed class CatalogPage +{ + public string Label() => Catalog.CurrentLabel(); +} +``` diff --git a/skills/dotnet-csrun/evals/files/unpublished/Library.cs b/skills/dotnet-csrun/evals/files/unpublished/Library.cs new file mode 100644 index 00000000..2e50f17e --- /dev/null +++ b/skills/dotnet-csrun/evals/files/unpublished/Library.cs @@ -0,0 +1,7 @@ +namespace Acme.Catalog; + +// This method is an unpublished checkout change; no published package can prove it. +public static class Catalog +{ + public static string CurrentLabel() => "checkout-only"; +} From ec9ac05b2006e62c6c8343cdee6771a06dea5fed Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Tue, 17 Nov 2026 00:12:08 +0100 Subject: [PATCH 13/95] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20compose=20docfx=20di?= =?UTF-8?q?gest=20with=20csrun=20runtime=20evidence?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Standalone runtime examples can now be created, verified, or repaired through dotnet-csrun while docfx-digest keeps ownership of API discovery, placement, and DocFX builds. The composition reference defines that boundary. --- skills/dotnet-docfx-digest/SKILL.md | 2 ++ skills/dotnet-docfx-digest/evals/evals.json | 10 ++++++++++ .../references/csrun-composition.md | 13 +++++++++++++ skills/dotnet-docfx-digest/references/workflow.md | 2 ++ 4 files changed, 27 insertions(+) create mode 100644 skills/dotnet-docfx-digest/references/csrun-composition.md diff --git a/skills/dotnet-docfx-digest/SKILL.md b/skills/dotnet-docfx-digest/SKILL.md index 59062dc8..4fc8d284 100644 --- a/skills/dotnet-docfx-digest/SKILL.md +++ b/skills/dotnet-docfx-digest/SKILL.md @@ -338,6 +338,8 @@ For managed reference pages, map type and extension-method examples to the `exam ## Example Verification +For compatible standalone runtime examples, compose with `dotnet-csrun create`, `verify`, or authorized `repair`; see [standalone execution composition](references/csrun-composition.md). Keep this skill's source discovery, placement, reference-aware compilation, and `--build-api-model --validate-samples --verify-docfx-build` completion gates. Published-package execution adds behavioral evidence; it does not verify unpublished project code. Do not force existing partial or project-dependent examples into standalone programs, and do not put two full execution blocks on every type page merely because csrun generates them. + Every added or changed `csharp` code block must pass two validation gates before it is written to a markdown file. Do not write any `csharp` fence without first verifying both gates pass. **Gate 1 — Static structure (`SAMPLE_STRUCTURE_INVALID`):** diff --git a/skills/dotnet-docfx-digest/evals/evals.json b/skills/dotnet-docfx-digest/evals/evals.json index d9b8fb0e..d4a41208 100644 --- a/skills/dotnet-docfx-digest/evals/evals.json +++ b/skills/dotnet-docfx-digest/evals/evals.json @@ -1193,6 +1193,16 @@ "Interprets CS1061 extension-method failures as likely missing using directives when source/API evidence supports it", "Adds `using System.Linq;` for the LINQ `Select` failure and reruns sample validation instead of trial-and-error editing" ] + }, + { + "prompt": "During a DocFX audit, add runtime evidence for an existing standalone published-package example and assess an ApplicationTest example that depends on an unpublished local application entry point. Preserve current docs structure and completion gates.", + "id": 114, + "expected_output": "Uses dotnet-csrun verify or authorized repair for the compatible standalone case, emits paired execution deliverables without forcing full blocks onto every type page, keeps application-owned startup on project-backed validation, and completes the existing DocFX gates.", + "expectations": [ + "Uses one canonical source for standalone runtime evidence, records per-transport outcomes and does not claim published package execution verifies unpublished code.", + "Preserves application Main and assembly separation and retains docfx.cs --build-api-model --validate-samples --verify-docfx-build as authoritative documentation gates.", + "Keeps concise primary C# fences and existing UID placement; no deterministic validator launches an AI agent and no duplicate compiler or unrequested project scaffolding is added." + ] } ] } diff --git a/skills/dotnet-docfx-digest/references/csrun-composition.md b/skills/dotnet-docfx-digest/references/csrun-composition.md new file mode 100644 index 00000000..c92755b6 --- /dev/null +++ b/skills/dotnet-docfx-digest/references/csrun-composition.md @@ -0,0 +1,13 @@ +# Standalone runtime evidence with dotnet-csrun + +Keep the existing DocFX inventory and source discovery. This skill owns public API discovery, namespace/type pages, UID/overwrite placement, source-backed explanation, project-aware sample compilation and documentation completion. `dotnet-csrun` owns compatible standalone construction, real xUnit v3 execution, native/Docker deliverables, behavioral verification, localized corrections and execution evidence. Apply both skills in the parent context when authorized; deterministic validators never launch another skill, agent, or authenticated model. + +Use `create` for a new complete standalone example; `verify` to inspect/execute unchanged source; `repair` for a relevant correction authorized by the documentation task; and scoped `audit` for classification and runtime evidence. Read the installed csrun skill's lifecycle and feasibility references. Preserve any existing intentionally partial excerpt instead of classifying it as an invalid executable. Continue applying this skill's complete-example rules to newly authored examples. + +Add standalone feasibility, exact source/manifest identities, exact published package pins, expected observations, and separate native/Docker statuses and evidence paths to the existing example inventory when useful. Keep evidence and generated wrappers in a temporary/ignored workspace. Reuse only current matching evidence under the requested verification policy. Runtime and compilation claims remain separate: a project-backed sample may compile without being independently runnable, and a csrun run against a release does not prove the unpublished checkout. + +Retain repository-aware validation for unpublished assemblies, project references, separate application/test assemblies, full hosts/HTTP pipelines and unavailable infrastructure. In particular, application-owned `Main` plus `ApplicationTest` must keep its real composition root and separate application identity; removing Main or registering the same service in a different host is not an equivalent correction. Use the existing project/test workflow. Do not add a competing compiler, manifest format, or project scaffolding for csrun compatibility. + +All existing gates remain mandatory for documentation completion: `docfx.cs --build-api-model --validate-samples --verify-docfx-build`. Standalone success cannot replace them. For an executable example, choose an allowed `// Program.cs` form or other appropriate complete source without bypassing DocFX's structure checks. A class-library fence with no executed operation supports a compilation claim only. If a separate harness invokes it, disclose and identify both sources; do not claim byte identity. + +csrun generates two independent PowerShell blocks from one canonical manifest. DocFX chooses presentation: a concise C# fence may be primary, with execution blocks linked or placed in a suitable conceptual page when useful. Extract the fence from the same canonical source and compare it before claiming exact source-to-execution parity. Do not hand-maintain three C# variants or force both full blocks onto every generated type page. Existing structured overwrite writing preserves BOM, line endings, mapping, prose and unrelated sections; use it where appropriate and inspect localized diffs after repairs. diff --git a/skills/dotnet-docfx-digest/references/workflow.md b/skills/dotnet-docfx-digest/references/workflow.md index 4f4d7bff..2f69a3dc 100644 --- a/skills/dotnet-docfx-digest/references/workflow.md +++ b/skills/dotnet-docfx-digest/references/workflow.md @@ -4,6 +4,8 @@ Use this reference when you need the full step-by-step workflow, example invento ## Example inventory shape +For optional standalone runtime evidence, follow [csrun composition](csrun-composition.md) and extend this inventory with source/manifest identity and transport-specific outcomes. Keep reference-aware compilation and documentation completion authoritative for their established scope. + Build a small example inventory from validator output and source evidence before writing examples. Treat it as a work queue, not as final-response prose. ```markdown From 68494d459bc7bb95e78910a6c60c5e0bd0de858e Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Tue, 17 Nov 2026 00:12:14 +0100 Subject: [PATCH 14/95] =?UTF-8?q?=F0=9F=93=9D=20update=20readme=20for=20cs?= =?UTF-8?q?run=20lifecycle?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The README skill table and csrun summary now describe the create, verify, repair, and audit lifecycle and the paired native and Docker commands, so the public entry matches the skill. --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index add53022..fd328849 100644 --- a/README.md +++ b/README.md @@ -161,7 +161,7 @@ When repo-managed skills author Markdown, each prose paragraph and list item sta | [dotnet-nuget-update](skills/dotnet-nuget-update/SKILL.md) | Audits and updates NuGet dependencies in .NET repositories with complete declaration accounting before any edit. It supports both `Directory.Packages.props` and project-level `PackageReference` versions, preserves XML structure and line endings, deduplicates package IDs, resolves independent live or offline flat-container version feeds with bounded parallel lookups and per-process memoization, uses bounded network timeouts, and merges results deterministically. Its single-process update runner keeps the audit, in-memory safe-update plan, and structural apply together for fast yolo passes. It keeps stable pins on stable candidates unless prerelease intent is explicit, and applies the TFM-band rule so conditional `net9`/`net10` package declarations stay within their matching major when that major is the compatibility signal rather than jumping to the newest overall release. Normal mode auto-applies revision/patch/minor and same-major prerelease updates, then batches majors for one approval decision; yolo mode applies only the auto classes and reports held majors without asking. | | [dotnet-docfx-digest](skills/dotnet-docfx-digest/SKILL.md) | Create and maintain developer-friendly DocFX documentation for .NET public APIs, including repo-wide no-input audits that inspect source, tests, DocFX config, DocFX `build.content` and `build.overwrite` Markdown inputs, namespace pages, and availability includes before asking for clarification, while treating bare direct skill invocations as autonomous repo-wide runs rather than human-driven checkpoint sessions. Enforces the workflow with two bundled .NET 10 file-based scripts resolved from the loaded skill directory, falling back to the repo-managed source path only when present: `scripts/agents.cs` writes an idempotent, marker-bounded DocFX maintenance block into the repository `AGENTS.md`; `scripts/docfx.cs` is **fast and build-free by default** — it validates Markdown, prose, DocFX overwrite layout, namespace overview pages, `Extension Members` tables, decorated receiver signatures such as `IDecorator`, generic method displays such as `As`, purpose-first summaries, and required per-type/extension examples without invoking `dotnet`, `msbuild`, `docfx`, or `gh`, discovering the public API from existing DocFX YAML metadata or a conservative source scan and ending every run with a `[processes] dotnet=0 msbuild=0 docfx=0 gh=0` summary plus per-phase timings. Compilation and network access are strictly opt-in: `--validate-samples` compiles each C# sample in an isolated project while batching all sample projects into one temporary `.slnx` graph build with bounded MSBuild parallelism and scoped references, `--build-api-model` (alias `--strict-api-discovery`) does reflection-backed discovery from compiled metadata via `MetadataLoadContext` through a single scoped `.slnx` graph build, `--verify-docfx-build` runs the DocFX CLI in a temp copy, and `--search-examples` runs `gh` code search. Final verification adapts to available processors and memory, overlaps isolated DocFX work on high-capacity machines, uses a 30-minute child timeout, and emits 10-second `stderr` heartbeats with active phase, workload, runner count, PID, elapsed time, last-output age, and current child output while preserving machine-readable JSON on `stdout`. Honors a single DocFX metadata `TargetFramework` when `--framework` is omitted, collapses C# 14 extension-block compiler containers such as `$...` back to the authored outer static class in both fast DocFX-YAML discovery and build-backed reflection discovery, validates namespace fly-ins that explain the problem solved/when to use/where to start plus example fly-ins before every C# fence, the Codebelt namespace-and-type-folder overwrite layout (`.docfx/api/namespaces/**/*.md` and `.docfx/api/types/**/*.md` under `build.overwrite` only), keeps `--changed-only` validation scoped to affected docs and APIs while still including brand-new untracked overwrite Markdown, uses the root Codebelt `.snk` when present and falls back to `-p:SkipSignAssembly=true` for keyless strong-name build verification, drains child stdout and stderr concurrently to avoid verbose-build deadlocks, writes deterministic `--assessment-queue` Markdown work queues for noisy audits, preserves working URL references unless a verified HTTP 404 justifies removal, treats unexpected new repo-root or DocFX-workspace files that are not known `dotnet-docfx-digest` deliverables as blocking cleanup diagnostics, keeps assessment/manifests/captured output/helper scripts in temp or session storage instead of the target repository, requires a namespace-first pass across the active queue before net-new type/example authoring during full audits, keeps deeper `EXTENSION_METHOD_MISSING` and `EXTENSION_METHOD_SIGNATURE_MISSING` follow-on diagnostics in that same namespace-layer table-repair phase when they appear after `EXTENSION_SECTION_MISSING` drops, preserves existing BOM and line-ending state while flagging actual mojibake instead of creating encoding-only diffs, and leaves generated DocFX YAML metadata untouched unless `--clean-generated-metadata` is explicitly requested (which runs only after the API model is built, never deleting metadata the run relied on). Documents public API only, uses bundled reference docs for overwrite rules, workflow details, and script behavior, keeps authored API overwrite Markdown under `.docfx/api/namespaces/` and `.docfx/api/types/`, moves legacy authored `.docfx/api/*.md` overwrite files there instead of widening the glob to `api/**/*.md`, teaches namespace and API prose to orient newcomers around purpose instead of inventorying contents, prefers inline or small sibling-batch prose repairs over slow per-page worker fan-out, makes examples start from package-ID usage evidence before type/member-only searches and requires each example to introduce the consumer task before the code, allows multi-type Microsoft Learn-style scenario samples when they better explain the consumer workflow, keeps extension-method examples on readable declaring-class type pages under `.docfx/api/types/` instead of synthetic method-UID filenames or namespace pages that mix extra `uid:` / `example:` blocks into the overview, flags weak skip-compile reasons, requires deterministic `.docfx/skip-compile-allowlist.json` entries for any pre-existing approved skip waivers, treats newly introduced or unallowlisted skip markers as fail-level diagnostics that do not suppress compilation, establishes reflection-backed packets with `--build-api-model --project-manifest` before full-run authoring, forces mid-audit continuations to name that manifest or the sequential assessment/namespace-first fallback explicitly, requires those continuations to restate the fast `docfx.cs --json` rerun cadence, the exact final `docfx.cs --build-api-model --validate-samples --verify-docfx-build --json` gate, and the clean JSON completion contract instead of generic “verify later” prose, treats batch size only as rerun cadence rather than permission to stop, runs a completion repair loop that treats every diagnostic as active work regardless of age or volume, treats newly surfaced follow-on diagnostics as the next repair queue instead of a stop point, reruns packet discovery with `--build-api-model --project-manifest` when fast source-scan packets are unnamed or zero-project, falls back to sequential namespace-first or assessment work queue order when packet discovery is still unusable, treats `EXAMPLE_MISSING`, `EXAMPLE_LEAD_MISSING`, `EXAMPLE_ADVANCED_LEAD_MISSING`, `FAMILY_ANCHOR_EXAMPLE_MISSING`, `SAMPLE_STRUCTURE_INVALID`, `FAIL_NEW_SKIP_MARKER_INTRODUCED`, `SAMPLE_SKIP_NOT_ALLOWLISTED`, and `INTERIM_ARTIFACT_IN_WORKTREE` queues as core work rather than checkpoints or quality backlog, drives large example and lead queues through a concrete fast-path micro-loop (next item or next 3-5 items → rerun → continue), suppresses progress-table/checkpoint output until the completion contract is clean or a real external blocker is reported, treats premature completion-shaped handoffs as execution-protocol failures while the queue is still dirty, reserves the final `--build-api-model --validate-samples --verify-docfx-build` verification for the real end of the queue, exposes `summary.fullVerificationRan`, `summary.canClaimCompletion`, `summary.remainingWorkItems`, `summary.remainingDiagnosticsByCode`, `summary.newlyIntroducedSkipMarkers`, and `summary.interimArtifacts` as machine-readable final gates, reruns the fast `docfx.cs --json` after edits until the queue is empty, then runs the build-backed verification before completion, preserves manual edits and authored Markdown during cleanup, skips recursive generated-output cleanup when a target directory contains documentation or source files, and returns deterministic exit codes plus `--json` reports (including process counts, phase timings, warning counts, and skip-marker accounting) so CI can gate on real failures instead of AI claims. | | [dotnet-test](skills/dotnet-test/SKILL.md) | Moves xUnit projects onto Codebelt's entrypoint-owned test hosts, replacing Microsoft's ASP.NET-only `WebApplicationFactory`—and the hand-rolled `HostBuilder` that console and worker tests reach for because Microsoft ships no equivalent—with one family of abstractions where the application's own entry point owns startup. Invocation is the request: it inspects and refactors immediately instead of opening with a menu or a questionnaire. It deterministically inspects project roles, target frameworks, xUnit generation, package ownership, inheritance, application entry points—including Bootstrapper `MinimalConsoleProgram`, `MinimalWorkerProgram`, and `MinimalWebProgram` hosts—and every selected `WebApplicationFactory` usage; classifies ordinary unit, ASP.NET Core functional, and console/worker functional tests; modernizes xUnit v2 projects to xUnit v3 plus Microsoft Testing Platform without moving package ownership or changing frameworks; and resolves current stable compatible packages through NuGet-backed isolated compatibility-project restores, including the selected combined package set. Focused web tests use `WebApplicationTestFactory` with an explicit entrypoint-owned `ManagedWebApplicationFixture`, directly or through a narrow `Test`-derived harness; shared web fixtures use `WebApplicationTest` with `ManagedWebApplicationFixture`; focused console/worker tests use `ApplicationTestFactory` with `ManagedApplicationFixture`; and shared non-web fixtures use `ApplicationTest` with `ManagedApplicationFixture`. Deprecated blocking fixtures are migration inputs only and are never emitted because they are scheduled for removal. Functional migrations fail closed unless the chosen Codebelt pattern and managed fixture are present, the legacy or blocking fixture is absent, and test code does not reconstruct the production composition root with its own `WebApplication`, `TestServer`, or `HostBuilder`. Migrations preserve entrypoint-owned startup, host configuration, lazy start, clients, services, configuration, sync/async disposal, isolation, and existing test names, while fresh bootstraps add source-grounded behavior tests. Non-web tests stay in-process and require a resolvable Generic Host; test-only scope reports the exact production adaptation instead of silently rewriting startup or launching a process. | -| [dotnet-csrun](skills/dotnet-csrun/SKILL.md) | Creates and executes small, shareable C# demonstrations and genuine xUnit v3 behavioral tests through csrun, with exact package pins, native or disposable Docker execution, and explicit verification evidence. | +| [dotnet-csrun](skills/dotnet-csrun/SKILL.md) | Creates, verifies, repairs, and audits C# examples and genuine xUnit v3 tests, with paired native/Docker commands from one manifest, exact package pins, and source-linked execution evidence. | | [dotnet-benchmark](skills/dotnet-benchmark/SKILL.md) | Discovers, prioritizes, and authors trustworthy BenchmarkDotNet experiments for a .NET type following codebelt conventions and using the `Codebelt.Extensions.BenchmarkDotNet.Console` runner. It inspects implementation code, call sites, tests, existing benchmarks, and available profiles instead of benchmarking every public member; ranks likely high-impact operations; selects representative typical, boundary, scaling, and adverse cases; and rejects external-I/O or service-level questions that need profiling, macrobenchmarks, or load tests. It creates fair current-versus-candidate comparisons only when observable work is equivalent, uses baseline-free single-operation characterization when no honest comparator exists, prevents unrelated construction/formatting/equality/hash ratios, requires exact per-case correctness oracles plus a semantic preflight for truthful workload labels, hard-gates interpretation on a complete valid BenchmarkDotNet summary, preserves workload invariants such as selectivity and hit/miss ratios as sizes scale, distinguishes deferred pipeline creation from terminal/materialization work, and performs Release build, discovery listing, and dry execution before any explicit full run. Explicit `yolo` mode auto-accepts routine repo-derived defaults and the proposed plan, then proceeds through build/list/dry validation without confirmation churn; only a separate explicit human instruction can start a full performance run. Its runner preflight recognizes the standard Slim/runtime setup and explains when `SkipBenchmarksWithReports = true` plus a matching `reports/tuning/` artifact deliberately filters a benchmark, preventing needless class renames, disassembly, or tool thrash; after the first valid full result it stops unless deeper diagnostics could change a real engineering decision. Harness setup remains adaptive: it detects `.slnx`/`.sln`, CPM, existing `tuning/` projects, and a reusable `tooling/` runner, onboards only missing pieces, resolves package versions dynamically, and keeps the benchmark class in the SUT namespace. | | [dotnet-remote-testing](skills/dotnet-remote-testing/SKILL.md) | Run .NET tests inside a resolved remote Docker environment and return concise, structured results — Visual Studio's Remote Testing experience (choose an environment → run tests → see results) with the container plumbing hidden behind a deterministic runner (`scripts/remote-test.cs`) the skill orchestrates instead of composing ad-hoc `docker run` commands. Invoking it is the request: with one applicable Docker environment it runs immediately — no capability menu, no parameter questionnaire, no confirmation — and when several channels are derived, the repository's own highest target framework selects the matching one and the choice is reported. The runner decides when a question is unavoidable, exiting `SelectionRequired` (16) with the exact candidates, and every exit code maps to exactly one next action so behavior is identical across models. It honors Microsoft's existing `testenvironments.json` version-1 contract (`name`, `localRoot`, `dockerImage`, `dockerFile`, with the either/or Docker-source rule), treats that file as authoritative when present, and reports WSL/SSH/unknown types as unsupported rather than converting or silently ignoring them. When no `testenvironments.json` exists it provides a zero-configuration experience built exclusively on official `mcr.microsoft.com/dotnet/sdk` images, discovering the currently supported LTS and STS channels plus the current preview from Microsoft's live `releases-index.json` using `support-phase`/`release-type` (never hardcoded version numbers or even/odd assumptions) and caching that metadata outside the repository for offline reuse. It prefers an exact `latest-sdk` image tag (stripping preview build metadata), validates the tag against Microsoft's registry, and pins each execution to the resolved immutable digest so results are reproducible across environment, image, digest, SDK, and architecture. Execution stages the source into an isolated workspace so container builds never leave Linux `bin`/`obj` in the working tree, mounts a persistent NuGet cache outside the repo, runs restore → build → test with structured TRX collection, classifies failures into distinct kinds (configuration, unsupported environment, Docker unavailable, image resolution, SDK incompatibility, staging, restore, compilation, test-host, test failure, result-processing, cleanup, cancellation, release-metadata) so infrastructure problems are never reported as failing unit tests, and always cleans up transient Docker resources. It never generates a `Dockerfile`, dev container, compose file, or editor configuration (an existing configured `dockerFile` is honored, never created), never runs privileged containers or mounts the Docker socket, and never silently falls back to running tests on the host. Docker is the only transport for now, designed so WSL/SSH can be added later without disturbing the deterministic Docker path, which is covered by a comprehensive built-in `--self-test` plus a PowerShell harness. | | [dotnet-segregated-assets](skills/dotnet-segregated-assets/SKILL.md) | Migrate or configure ASP.NET Core static delivery with `codebeltnet/web-cdn-origin:2.0.0` while keeping `wwwroot` as the authoring root. The deterministic runner inspects and verifies topology, publish exclusion, Static Web Assets risks, Cuemon signals, competing `AppAssetOptions`-style abstractions, actual `app-*`/`cdn-*` markup, and scheme-safe local origins; the agent performs semantic edits. For an existing Cuemon package reference, its plan resolves the highest stable version from NuGet.org at execution time, preserves Central Package Management versus inline ownership, excludes prereleases, and fails rather than copying an old fixture or example version. It reuses Cuemon `AppTagHelperOptions`/`CdnTagHelperOptions`, `BaseUrlMode`, and the public `app-link`, `app-script`, `app-img`, `cdn-link`, `cdn-script`, and `cdn-img` helpers when already available, otherwise reuses a suitable project abstraction without adding Cuemon. It keeps App and shared CDN ownership separate, preserves ordinary Project-based Development, adds opt-in segregated Development through a root Docker Compose profile, and makes `compose.assets.yml` directly build artifact-first `LocalDevelopment.Dockerfile` and `Assets.Dockerfile` images. Every generated file comes from a literal template in `assets/` and lands in one fixed location — the three Dockerfiles beside the web `.csproj`, orchestration at the repository root — and `verify --check-local` proves that placement along with the artifact-first contract: no SDK stage or `dotnet publish` inside an application image, a `.dockerignore` that still carries `artifacts/`, `LocalPublishDirectory` behind a guarded post-build target, Compose host ports derived from the ordinary Project profile, and a CI job that produces the artifact those images copy. Production CI publishes the same application artifact for the shell-less runtime `Dockerfile`. The skill excludes app-owned `wwwroot` with targeted MSBuild metadata, preserves `_content`/`_framework` and generated Static Web Assets, and proves publish/local invariants deterministically and idempotently. | @@ -752,7 +752,7 @@ The hardest failure to catch is the migration that only looks like one. Wrapping ### Why dotnet-csrun? -Documentation examples earn trust when the exact source executes and its observations match expectations. dotnet-csrun provides small, complete console examples and genuine xUnit v3 tests using one csrun manifest across Docker and native PowerShell, with exact package pins and honest verification status. It creates no developer-managed project and does not replace repository tests or benchmarks. +Documentation examples earn trust when the exact source executes and its observations match expectations. dotnet-csrun supports the complete sample lifecycle: create, read-only verify, semantics-preserving repair, and scoped audit. It generates two independent native and disposable Docker PowerShell commands from one manifest, records source identities, and reports verification per transport. It composes with dotnet-docfx-digest for compatible runtime evidence while preserving project-aware sample compilation and DocFX completion gates. It creates no developer-managed project and does not replace repository tests or benchmarks. ### Why dotnet-benchmark? From 38efddf6b705785d34c116ddf6101d211e7cf207 Mon Sep 17 00:00:00 2001 From: gimlichael Date: Tue, 17 Nov 2026 00:14:22 +0100 Subject: [PATCH 15/95] =?UTF-8?q?=E2=9C=A8=20add=20changelog=20entry=20for?= =?UTF-8?q?=20dotnet-csrun=20and=20docfx=20integration?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7fd42da4..cba3224c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,20 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [0.13.0] - 2026-11-17 + +This is a minor release that adds the `dotnet-csrun` skill for executable C# evidence and connects `dotnet-docfx-digest` to it for standalone runtime examples. + +### Added + +- `dotnet-csrun` skill for creating small complete C# examples, verifying and repairing existing standalone source, and auditing examples, with paired native and Docker commands and honest verified, compiled-only, or unverified statuses, +- `dotnet-csrun` assesses standalone feasibility before choosing a manifest and classifies failures before any repair, and runs isolated xUnit v3 tests through `csrun`, +- `dotnet-csrun` deterministic validators and eval fixtures covering its lifecycle and feasibility contracts, plus a README entry and install example. + +### Changed + +- `dotnet-docfx-digest` example verification composes with `dotnet-csrun` for compatible standalone runtime examples, keeping its source discovery, placement, project-aware compilation, and DocFX build gates authoritative and leaving project-dependent examples in the existing workflow. + ## [0.12.1] - 2026-11-15 This is a minor release that adds initial-release support, verified new-contributor recognition, and Markdown file delivery to `git-remote-release`, and makes Codex CLI with `gpt-6-luna` the Codebelt Reference evaluation configuration after removing the GitHub Copilot CLI eval runner. @@ -810,6 +824,7 @@ This is a minor release that introduces two complementary git workflow skills, e - Improved scaffold fidelity with hidden `.bot` asset preservation, explicit UTF-8 and BOM handling, and checks aimed at preventing mojibake or incomplete generated output. +[0.13.0]: https://github.com/codebeltnet/agentic/compare/v0.12.1...v0.13.0 [0.12.1]: https://github.com/codebeltnet/agentic/compare/v0.12.0...v0.12.1 [0.12.0]: https://github.com/codebeltnet/agentic/compare/v0.11.2...v0.12.0 [0.11.2]: https://github.com/codebeltnet/agentic/compare/v0.11.1...v0.11.2 From 56b507563ec51163863c207fb679e4f27b4950d6 Mon Sep 17 00:00:00 2001 From: gimlichael Date: Tue, 17 Nov 2026 00:26:06 +0100 Subject: [PATCH 16/95] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20update=20docker=20im?= =?UTF-8?q?age=20inspection=20order=20for=20sdk=20and=20runtime=20inventor?= =?UTF-8?q?y?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/validate-dotnet-csrun.ps1 | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/scripts/validate-dotnet-csrun.ps1 b/scripts/validate-dotnet-csrun.ps1 index d5e3c1bf..4c6cbc57 100644 --- a/scripts/validate-dotnet-csrun.ps1 +++ b/scripts/validate-dotnet-csrun.ps1 @@ -42,10 +42,11 @@ $environment = if ($Docker) { $images = @{} foreach ($tag in @('10', '11')) { $image = "codebeltnet/csrun:$tag" - $inspect = docker image inspect $image --format '{{json .}}' | ConvertFrom-Json - if ($LASTEXITCODE -ne 0) { throw "Inspect failed: $image" } + # Inventory first so docker run can pull an image that is not cached locally. $sdks = docker run --rm --entrypoint dotnet $image --list-sdks if ($LASTEXITCODE -ne 0) { throw "SDK inventory failed: $image" } + $inspect = docker image inspect $image --format '{{json .}}' | ConvertFrom-Json + if ($LASTEXITCODE -ne 0) { throw "Inspect failed: $image" } $runtimes = docker run --rm --entrypoint dotnet $image --list-runtimes if ($LASTEXITCODE -ne 0) { throw "Runtime inventory failed: $image" } $images[$image] = @{ imageId=$inspect.Id; digests=$inspect.RepoDigests; labels=$inspect.Config.Labels; os=$inspect.Os; architecture=$inspect.Architecture; sdks=$sdks; runtimes=$runtimes } From 66d86e80cd98a44f1299b430cf5f6c84342bc842 Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Tue, 17 Nov 2026 02:01:10 +0100 Subject: [PATCH 17/95] =?UTF-8?q?=F0=9F=93=9D=20document=20source-bound=20?= =?UTF-8?q?sample=20context=20in=20docfx=20readme?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The README describes the source-bound sample contract so consumers know that maintained examples declare their project and source context explicitly and that the validator checks those bindings rather than skipping them. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index fd328849..0bf3e3be 100644 --- a/README.md +++ b/README.md @@ -712,7 +712,7 @@ API documentation rots the moment code changes. A new public type ships without - **Managed-reference-safe overwrite layout** — public non-abstraction types and public extension methods must have examples in DocFX overwrite content included by `build.overwrite`; the validator discovers Markdown from configured DocFX inputs instead of scanning the whole repository when `docfx.json` is at the root, concrete-type examples are tracked through an explicit inventory and created in readable authored files under `.docfx/api/types/`, legacy authored `.docfx/api/*.md` overwrite files move into `api/namespaces/` or `api/types/` instead of widening the glob to `api/**/*.md`, both overwrite trees stay excluded from `build.content`, C# extension-block compiler containers such as `$...` are collapsed back to the authored outer static class, extension-method examples default to readable declaring-class type pages under `.docfx/api/types/` instead of URL-encoded method-UID filenames or namespace pages that mix overview and member UIDs, namespace pages fail validation when they embed secondary `uid:` / `example:` sections, and agents must rerun the completion repair loop until diagnostics and overwrite-layout failures are fixed or exact blockers are reported, - **Concept-led namespace quality** — moving concrete examples to type pages must not hollow out namespace pages; namespace pages still need newcomer-oriented fly-ins that explain the problem solved, when to use the namespace, where to start, type-family context, extension-method group explanations, availability, and pointers to representative type pages, and nearby type/member summaries should stay purpose-first too, - **Examples that teach a real workflow** — examples start from package IDs and package-level evidence before falling back to type/member-only searches, prefer README, package docs, tooling, tuning, functional-test, and external GitHub usage when available, may include multiple related public types when that is what makes the consumer scenario understandable, keep extension-container prose focused on what callers can do with the receiver instead of on declaration syntax, discover public acquisition paths from signatures, docs, tests, and other evidence instead of assuming direct construction from implementation details, and rewrite copied test evidence into lean consumer-facing code rather than dragging obvious framework FQNs into the sample body, -- **Examples arrive with context** — every validated C# example needs a human-written fly-in immediately before the fence, and larger or setup-heavy examples need a deeper lead that explains setup, prerequisites, or workflow outcome, so example pages read like intentional guidance rather than code dropped onto a page, +- **Examples arrive with context** — design starts with the developer task, prerequisites, execution topology and observable result. Library snippets stay concise; standalone programs, genuine framework tests, multi-project integrations and partial excerpts use their actual execution context. Project-bound fences match maintained source and compile in the real project graph, preserving application entry points and test assembly boundaries. Human fly-ins explain setup and outcome, and compilation, runtime evidence and architectural review remain distinct, - **Semantic example quality gates** — compilation-valid filler no longer passes: the validator rejects duplicate UID mappings, `Type.GetType`/assembly metadata scaffolds, runtime implementation names presented as outcomes (`EXAMPLE_RUNTIME_TYPE_NAME_OUTCOME`), empty local `Program` stubs in conventionally named application-entry-point samples such as `AppFactory`, `WebTestFactory`, or `HostFixture` (`EXAMPLE_EMPTY_ENTRY_POINT_STUB`) while excluding unrelated names such as `ApplicationRepositoryFactory`, generic `DocumentedTypeExample`/`Describe()` templates, type examples that never use the target in code, extension examples that mention a method only in prose instead of invoking it, examples without a human fly-in (`EXAMPLE_LEAD_MISSING`), advanced examples with shallow setup context (`EXAMPLE_ADVANCED_LEAD_MISSING`), `default!`/`null!` holder properties (`EXAMPLE_DEFAULT_PLACEHOLDER`), classes that only construct or return the target with no observable result (`EXAMPLE_NO_OBSERVABLE_OUTCOME`), mass-forwarding shells of one-line pass-throughs (`EXAMPLE_FORWARDING_SCAFFOLD`), one normalized code skeleton reused across three or more unrelated targets (`EXAMPLE_TEMPLATE_REPETITION`), and avoidable `System.*` / `Microsoft.*` fully qualified framework references in executable sample code (`EXAMPLE_FULLY_QUALIFIED_FRAMEWORK_TYPE`), - **Key-entry-point storytelling** — namespace guidance starts from release notes, package documentation, public factories/builders, and strong functional tests so new product-defining APIs are not buried beneath naming conventions. When a package complements an upstream framework type, the skill compares acquisition, customization, lifecycle, sharing, and observable outcomes from current official guidance instead of making unsupported replacement claims, - **Correct source discovery** — the no-build source scanner correctly handles block namespaces whose opening brace is on the next line, so public types are no longer silently under-reported; when a declaration cannot be paired with its brace it warns (`API_MODEL_SOURCE_SCANNER_INCOMPLETE`) and points to a build-backed audit, From a44b50fb60f30552a1e525efcde2441c493d61a3 Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Tue, 17 Nov 2026 02:01:11 +0100 Subject: [PATCH 18/95] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20document=20source-bo?= =?UTF-8?q?und=20csrun=20examples=20in=20docfx=20skill?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The skill contract now covers csrun composition, the source-binding requirement for maintained examples, and the example-architecture reference that explains the split application and test assembly case for ManagedApplicationFixture. --- skills/dotnet-docfx-digest/SKILL.md | 22 ++++--- .../references/csrun-composition.md | 4 +- .../references/example-architecture.md | 66 +++++++++++++++++++ .../dotnet-docfx-digest/references/scripts.md | 6 +- .../references/workflow.md | 14 ++-- 5 files changed, 94 insertions(+), 18 deletions(-) create mode 100644 skills/dotnet-docfx-digest/references/example-architecture.md diff --git a/skills/dotnet-docfx-digest/SKILL.md b/skills/dotnet-docfx-digest/SKILL.md index 4fc8d284..9416cb1f 100644 --- a/skills/dotnet-docfx-digest/SKILL.md +++ b/skills/dotnet-docfx-digest/SKILL.md @@ -30,7 +30,7 @@ dotnet run --file "/scripts/agents.cs" -- --repo-root "/scripts/docfx.cs" -- --repo-root "" --build-api-model --validate-samples --verify-docfx-build ``` -- `--build-api-model` makes API discovery reflection-precise (the fast source-scan path is conservative and may under-report), `--validate-samples` compiles every C# documentation sample through isolated projects in one temporary `.slnx` graph build with bounded MSBuild parallelism, and `--verify-docfx-build` confirms the DocFX build succeeds. Treat `API_MODEL_SOURCE_SCANNER_LIMITED` in a fast run as a reminder to run the build-backed verification before completion, not as a failure. +- `--build-api-model` makes API discovery reflection-precise (the fast source-scan path is conservative and may under-report), `--validate-samples` compiles C# documentation samples through isolated projects or explicitly bound maintained projects in one temporary `.slnx` graph build with bounded MSBuild parallelism, and `--verify-docfx-build` confirms the DocFX build succeeds. Treat `API_MODEL_SOURCE_SCANNER_LIMITED` in a fast run as a reminder to run the build-backed verification before completion, not as a failure. - Treat the current build-backed JSON result as authoritative over earlier fast-path diagnostics. If `--build-api-model` clears fast source-scan errors such as interim-artifact findings for real public type pages, do not keep repairing stale diagnostics from a previous fast run; proceed from the current `summary` object and rerun the final gate when ready. - The JSON completion fields live under the top-level `summary` object near the start of the report. For long or truncated output, search saved stdout for `completionState`, `canClaimCompletion`, `fullVerificationRan`, `remainingWorkItems`, `remainingGates`, `remainingDiagnosticsByCode`, `newlyIntroducedSkipMarkers`, and `interimArtifacts` before reading the full diagnostic payload. - For noisy audits, write and read a deterministic assessment work queue with `--assessment-queue`. This works on the fast path; add `--search-examples` to embed real GitHub usage: @@ -308,23 +308,25 @@ For each repair batch, maintain an evidence ledger in the example inventory: rec Do not assume the right acquisition model. Before writing the example, discover how consumer code actually obtains the documented type from reflection-backed public API shape, docs, tests, samples, or other source-backed evidence. When the type is surfaced by another public method, factory, builder, registration call, or workflow, prefer that discoverable public path over manual construction. Do not mirror internal helper construction (`return new Type { ... }` in implementation code) or manually populate object state just because a constructor exists. -Every generated `csharp` code block is a complete, copy/paste-ready compilation unit. The default is always a compilable unit (option 1). Only use intentionally incomplete excerpts (option 2) when explicitly requested by the user, and label them clearly. +Before writing code, establish the developer's task, prerequisites, intended observation, execution topology, and verification method from source, public contracts, tests, package documentation, or maintained usage. Follow **Discover API → Understand consumer task → Determine execution topology → Find authoritative usage → Design example → Write source → Validate → Improve explanation → Publish**. Read [example architecture](references/example-architecture.md) for multi-file, application integration, testing APIs, and partial excerpts. -**Complete C# example contract:** +Choose the smallest realistic presentation: standalone executable, ordinary library usage, multi-file/multi-project scenario, framework/application integration, or intentionally partial excerpt. These are authoring decisions, not a public manifest. Do not force every fence into a console program or claim that every compilation unit independently runs. Explain the actual TFM, package/namespaces, host/configuration, assembly references, and infrastructure where needed; keep simple examples concise. + +**Default C# compilation-unit contract (unbound fences):** - Includes all required `using` directives. - Declares a file-scoped namespace (e.g., `namespace X.Y;`). - Declares at least one concrete class, struct, or record containing the usage. - Does **not** use top-level statements unless the example is explicitly labelled `// Program.cs` at the very top of the code block. -- Does **not** invent placeholder services, interfaces, classes, methods, or overloads that are not defined inside the same code block. +- Does **not** invent dependencies, services, members, or overloads. Helpers belong in the source unit or in an explicitly identified maintained project context. - Does **not** derive from an abstract or generic base type without supplying the correct concrete type arguments. - Does **not** call members that do not exist on the resolved public API surface. - Uses the documented type or invokes the documented extension method inside the C# fence. A target name in prose, comments, or string literals does not count. - Shows a consumer-visible operation, result, configuration, or next action. Reflection-only discovery and metadata inspection do not count as usage. - Contains one coherent example mapping per UID. Merge related calls into one scenario instead of repeating `example: *content` sections for the same UID. -- Compiles in a minimal class library verification project referencing the documented assemblies. +- Compiles in a minimal class library verification project referencing the owning documented assemblies, or as an explicitly labelled `// Program.cs` executable. A project-bound fence compiles in its maintained project graph instead; a labelled partial excerpt must bind to the real source containing it and explain its omitted context. Neither form waives compilation. -Prefer examples derived from existing unit, functional, or integration tests as behavioral evidence, then from package-level usage evidence, samples, README content, and real consumer usage, then from a minimal new example based on actual public behavior. Convert Arrange/Act/Assert test structure into consumer-oriented sample code instead of pasting raw test assertions, mocks, or fixture setup. When the best evidence spells obvious framework calls as `System.*` or `Microsoft.*`, add the matching `using` directives in the final sample so the call site stays focused on the documented API unless qualification is genuinely needed to disambiguate. +Prefer examples derived from existing unit, functional, or integration tests as behavioral evidence, then from package-level usage evidence, samples, README content, and real consumer usage, then from a minimal new example based on actual public behavior. Remove incidental test scaffolding for ordinary APIs. When the API itself is a testing abstraction, preserve `[Fact]`, fixture constructors, real assertions, runner behavior, and application/test assembly boundaries as required by its usage contract. Normalize obvious framework qualifications into matching imports unless qualification disambiguates. For public non-abstraction types, put the example on the generated type page by targeting the type UID in DocFX overwrite content. In Codebelt repositories, keep authored type overwrite Markdown under `.docfx/api/types/`, typically as `.docfx/api/types/{TypeUid}.md`. @@ -340,7 +342,7 @@ For managed reference pages, map type and extension-method examples to the `exam For compatible standalone runtime examples, compose with `dotnet-csrun create`, `verify`, or authorized `repair`; see [standalone execution composition](references/csrun-composition.md). Keep this skill's source discovery, placement, reference-aware compilation, and `--build-api-model --validate-samples --verify-docfx-build` completion gates. Published-package execution adds behavioral evidence; it does not verify unpublished project code. Do not force existing partial or project-dependent examples into standalone programs, and do not put two full execution blocks on every type page merely because csrun generates them. -Every added or changed `csharp` code block must pass two validation gates before it is written to a markdown file. Do not write any `csharp` fence without first verifying both gates pass. +Verify added or changed C# before publishing. Unbound fences pass the following two gates. For explicitly project-bound files/excerpts, the validator checks source identity, evaluated Compile membership, and the maintained project build instead of compiling a fragment alone. See [example architecture](references/example-architecture.md) for the exact binding and its limits. **Gate 1 — Static structure (`SAMPLE_STRUCTURE_INVALID`):** @@ -354,7 +356,7 @@ A code block labelled `// Program.cs` at the very top passes Gate 1 and is compi **Gate 2 — Compilation (`SAMPLE_COMPILE_FAILED`):** -Class-based examples that pass Gate 1 are compiled as a class library project referencing all assemblies from `docfx.json`. If compilation fails, the example is rejected. Either repair and re-run, or omit the example and add: +Class-based examples that pass Gate 1 compile as a library referencing the owning documented projects and their transitive dependencies. If compilation fails, repair and rerun, or omit the example and add: ```markdown @@ -387,7 +389,9 @@ Derive examples from these sources, in order: 8. Synthesized examples only when all of the above confirm the full public API shape and the synthesized sample compiles. 9. Omit the example entirely if none of the above yields a compile-valid, consumer-facing example. -Final examples must be consumer-facing, realistic, and compile. They must read like production calling code or Microsoft Learn-style task examples, not test scaffolding, placeholder `Consumer` shells, `Demonstrate()` wrappers, or one-line smoke tests. Avoid unused locals, `MyNamespace` when a domain-specific namespace is obvious, fake "sample" values that obscure the workflow, examples that instantiate the documented type without showing the result or next step a real caller cares about, and avoidable `System.*` / `Microsoft.*` fully qualified framework references when a normal `using` keeps the code lean. +Final examples must be consumer-facing, realistic, and compile in their declared context. They should read like production calling code, meaningful framework tests when documenting testing APIs, or Microsoft Learn-style task examples. Avoid placeholder `Consumer` shells, `Demonstrate()` wrappers, unused locals, smoke tests, and implementation metadata as outcomes. Preserve the actual composition root, registration ownership, async/disposal lifecycle, configuration semantics, middleware ordering, and real APIs. Removing Main, registering the claimed application service in the test, substituting a fake host, or weakening an assertion is not an equivalent repair. + +Compilation proves syntax/type compatibility; execution proves observed behavior; architectural review establishes whether the example teaches the intended contract. Record these separately in the example inventory. Do not report runtime success from a build alone, or imply that a passing assertion proves application registration when the test supplied that registration itself. Compilation-valid metadata scaffolds are still failures. Never generate a family of examples that differs only by UID while calling `Type.GetType`, returning `Type.FullName`, or wrapping the lookup in `DocumentedTypeExample`, `DocumentedExtensionExample`, or `Describe()`. These patterns conceal missing product knowledge instead of teaching the API. diff --git a/skills/dotnet-docfx-digest/references/csrun-composition.md b/skills/dotnet-docfx-digest/references/csrun-composition.md index c92755b6..8875a8fc 100644 --- a/skills/dotnet-docfx-digest/references/csrun-composition.md +++ b/skills/dotnet-docfx-digest/references/csrun-composition.md @@ -2,12 +2,12 @@ Keep the existing DocFX inventory and source discovery. This skill owns public API discovery, namespace/type pages, UID/overwrite placement, source-backed explanation, project-aware sample compilation and documentation completion. `dotnet-csrun` owns compatible standalone construction, real xUnit v3 execution, native/Docker deliverables, behavioral verification, localized corrections and execution evidence. Apply both skills in the parent context when authorized; deterministic validators never launch another skill, agent, or authenticated model. -Use `create` for a new complete standalone example; `verify` to inspect/execute unchanged source; `repair` for a relevant correction authorized by the documentation task; and scoped `audit` for classification and runtime evidence. Read the installed csrun skill's lifecycle and feasibility references. Preserve any existing intentionally partial excerpt instead of classifying it as an invalid executable. Continue applying this skill's complete-example rules to newly authored examples. +Use `create` for a new complete standalone example; `verify` to inspect/execute unchanged source; `repair` for a relevant correction authorized by the documentation task; and scoped `audit` for classification and runtime evidence. Read the installed csrun skill's lifecycle and feasibility references. Apply the [example design contract and execution classification](example-architecture.md) before source generation. Preserve contextualized partial excerpts and project boundaries; neither existing nor new excerpts are standalone executables merely because they contain C#. Add standalone feasibility, exact source/manifest identities, exact published package pins, expected observations, and separate native/Docker statuses and evidence paths to the existing example inventory when useful. Keep evidence and generated wrappers in a temporary/ignored workspace. Reuse only current matching evidence under the requested verification policy. Runtime and compilation claims remain separate: a project-backed sample may compile without being independently runnable, and a csrun run against a release does not prove the unpublished checkout. Retain repository-aware validation for unpublished assemblies, project references, separate application/test assemblies, full hosts/HTTP pipelines and unavailable infrastructure. In particular, application-owned `Main` plus `ApplicationTest` must keep its real composition root and separate application identity; removing Main or registering the same service in a different host is not an equivalent correction. Use the existing project/test workflow. Do not add a competing compiler, manifest format, or project scaffolding for csrun compatibility. -All existing gates remain mandatory for documentation completion: `docfx.cs --build-api-model --validate-samples --verify-docfx-build`. Standalone success cannot replace them. For an executable example, choose an allowed `// Program.cs` form or other appropriate complete source without bypassing DocFX's structure checks. A class-library fence with no executed operation supports a compilation claim only. If a separate harness invokes it, disclose and identify both sources; do not claim byte identity. +All existing gates remain mandatory for documentation completion: `docfx.cs --build-api-model --validate-samples --verify-docfx-build`. Standalone success cannot replace them. For an executable example, choose an allowed `// Program.cs` form or bind the genuine test source to its maintained project context. A standalone xUnit v3 test can be executed by csrun; a test requiring a separate application assembly belongs in the actual project/test graph. A class-library fence with no executed operation supports a compilation claim only. If a separate harness invokes it, disclose and identify both sources; do not claim byte identity. csrun generates two independent PowerShell blocks from one canonical manifest. DocFX chooses presentation: a concise C# fence may be primary, with execution blocks linked or placed in a suitable conceptual page when useful. Extract the fence from the same canonical source and compare it before claiming exact source-to-execution parity. Do not hand-maintain three C# variants or force both full blocks onto every generated type page. Existing structured overwrite writing preserves BOM, line endings, mapping, prose and unrelated sections; use it where appropriate and inspect localized diffs after repairs. diff --git a/skills/dotnet-docfx-digest/references/example-architecture.md b/skills/dotnet-docfx-digest/references/example-architecture.md new file mode 100644 index 00000000..ce12f848 --- /dev/null +++ b/skills/dotnet-docfx-digest/references/example-architecture.md @@ -0,0 +1,66 @@ +# Design examples around the developer task + +Read this before writing application integration, testing-framework, multi-file/project examples, or partial excerpts. Keep package-ID-first discovery and the existing project packets. A compilation success is one kind of evidence, not approval of the example's architecture. + +## Design contract + +Before source generation, establish these facts from public contracts, implementation, tests, package READMEs, or maintained consumer examples. Record them briefly in the existing example inventory, not in a new manifest: + +- **Intention:** the concrete question the developer wants answered, such as verifying a worker application's service registration. +- **Required context:** actual target framework/asset, package and namespace, application type, DI/configuration, host/infrastructure, project references, and which project owns each file. Distinguish published packages from unpublished source references; do not invent pins or assume ASP.NET Core merely because an API uses hosting. +- **Behavior:** a returned value, resolved application service, configuration value, HTTP response, assertion, lifecycle event, or relevant failure that answers that question. Construction, runtime type names, metadata, and decorative logging are insufficient. +- **Reproduction:** the exact build/run/test command, prerequisites, and observation to check. Identify the evidence as compilation only, executed behavior, or unverified. Retain failures and unavailable prerequisites; never turn them into success by weakening the scenario. + +Use the sequence **Discover API → Understand consumer task → Determine execution topology → Find authoritative usage → Design example → Write source → Validate → Improve explanation → Publish**. The reader should understand why, what must exist, how to use it, what happens, and how to check it, without requiring five headings on every page. + +## Choose the execution model + +| Classification | Presentation and verification | +| --- | --- | +| Standalone executable | Complete source, with `// Program.cs` for an ordinary executable DocFX fence. Use csrun for compatible console or genuine xUnit v3 execution; do not simulate test execution. | +| Ordinary library usage | Concise namespace/type-based consumer code, necessary imports/setup, and meaningful result. Existing isolated library compilation stays the default. | +| Multi-file or multi-project | Label each file and project, describe assembly relationships and dependencies, and verify the maintained project graph. Multiple fences can form one scenario; they are not automatically separate programs. | +| Framework/application integration | Explain who builds/starts/disposes the host, application lifecycle and infrastructure, then verify with its real application/test workflow. | +| Intentionally partial excerpt | Say what is omitted and where it belongs. Bind to its maintained compiling source context; do not claim standalone execution. A missing context is unresolved work, not an automatic waiver. | + +Prefer a real repository sample/test over generating new projects. When setup would overwhelm an API page, show essential usage and link directly to the maintained integration example and its project. A link supplements the local API example; it does not satisfy target-use or compilation requirements by itself. Include minimal valid project setup only where it is actually needed for reproduction and backed by evidence. + +## Preserve responsibilities + +Review architecture as well as source shape. Check executable entry points and assembly identity; application-owned versus test-owned DI registration; framework-owned versus application-owned initialization; async and disposal lifetimes; Options binding/validation; fixture/factory initialization; real services versus doubles; and reference/asset selection. For middleware, preserve registration, pipeline order (including authentication/authorization/routing where required), and the request/response that demonstrates the effect. + +Remove incidental test scaffolding when documenting ordinary libraries. For testing APIs, `[Fact]`, fixture constructor injection, assertions and the real runner can be essential consumer usage. Do not strip them to make a console-shaped example. A test that builds another host, overrides the service it claims the application registered, or merely asserts a test double's behavior proves a different contract. No static heuristic establishes that the prose and assertion mean the same thing: inspect authoritative usage and execute the relevant test when claiming runtime results. + +## Bind a fence to maintained source + +Unbound C# fences keep their existing structure and isolated compilation rules. For a file/excerpt that requires its real project, put these two comments first, using repository-relative paths: + +````markdown +**Application project: `InventoryWorker`**, file `Program.cs`. This executable owns startup and registration; it is not part of the test assembly. + +```csharp +// docfx-context: app/InventoryWorker/InventoryWorker.csproj +// docfx-source: app/InventoryWorker/Program.cs + +``` +```` + +The angle-bracket line above describes the binding syntax; it is not publishable C#. Use the same two comments on the test fence, pointing to the actual test project and source file. Name the application `ProjectReference`, package dependencies, runner and command in prose or link to their maintained project definitions. These comments identify compilation context; they do not replace readable project/file labels or prerequisites. + +The fast path verifies both files exist inside the repository and the displayed source matches a complete maintained file or a nonempty contiguous whole-line excerpt. Only line-ending differences and outer blank lines are ignored. Missing paths, source drift and unsupported linked paths produce `SAMPLE_CONTEXT_INVALID` with repair guidance. No network, compilation or MSBuild evaluation occurs on the fast path. + +With `--validate-samples`, the validator copies the repository to temp (excluding generated directories and `.bot`), checks the selected framework is declared by each bound project, evaluates `Compile` membership for that framework/configuration, and builds the declared projects together through the existing bounded sample graph build. Dependencies and separate assembly identities come from those projects, not concatenated fences. An excluded source file, unavailable dependency, invalid project graph, or failed build remains a failure. Use `--framework` for the actual runnable asset; do not silently retarget a maintained project. `--sample-reference-mode package` does not rewrite an explicitly bound project graph. Unsupported generated Compile items or external project dependencies require a supported maintained context; they are not accepted as success. Disposable context builds ignore persistent build servers so a node cannot supply another workspace's package-root environment or retain its test-runner task assemblies. + +This is **compilation evidence for the containing source/project**, not proof that an excerpt executed, its omitted initialization was invoked, or its assertion establishes the prose's claim. Run the real test/application separately and record command, framework/dependencies, observations and source identity before claiming execution. Do not use the context comments as a substitute for strict skip approvals, and never use an unrelated compiling project to validate a fence. + +## Principal regression: ManagedApplicationFixture + +Evidence pinned to [codebeltnet/xunit revision 84b13767](https://github.com/codebeltnet/xunit/tree/84b13767cb9484f8f3a36a71875662edfdb3e511): + +- [ManagedApplicationFixture.ConfigureHost](https://github.com/codebeltnet/xunit/blob/84b13767cb9484f8f3a36a71875662edfdb3e511/src/Codebelt.Extensions.Xunit.Hosting/ManagedApplicationFixture.cs) passes `typeof(TEntryPoint).Assembly` to the deferred host factory. `TEntryPoint` identifies an application assembly; it is not a replacement host builder. +- [DeferredHostFactory](https://github.com/codebeltnet/xunit/blob/84b13767cb9484f8f3a36a71875662edfdb3e511/src/Codebelt.Extensions.Xunit.Hosting/Internal/DeferredHostFactory.cs) resolves that assembly's entry point. [ApplicationTest](https://github.com/codebeltnet/xunit/blob/84b13767cb9484f8f3a36a71875662edfdb3e511/src/Codebelt.Extensions.Xunit.Hosting/ApplicationTest.cs) wires fixture initialization through the base constructor. +- [Minimal worker Program](https://github.com/codebeltnet/xunit/blob/84b13767cb9484f8f3a36a71875662edfdb3e511/app/Codebelt.Extensions.Xunit.Hosting.BootstrapperMinimalWorker.App/Program.cs) owns service registration, host construction and `RunAsync`. The [functional test](https://github.com/codebeltnet/xunit/blob/84b13767cb9484f8f3a36a71875662edfdb3e511/test/Codebelt.Extensions.Xunit.Hosting.FunctionalTests/BootstrapperMinimalWorkerApplicationTestTest.cs) resolves the application's marker service and asserts its value. Its [project](https://github.com/codebeltnet/xunit/blob/84b13767cb9484f8f3a36a71875662edfdb3e511/test/Codebelt.Extensions.Xunit.Hosting.FunctionalTests/Codebelt.Extensions.Xunit.Hosting.FunctionalTests.csproj) references the application separately. + +Recommended correction to the [published InventoryWorker example](https://xunit.codebelt.net/api/Codebelt.Extensions.Xunit.Hosting.ManagedApplicationFixture-1.html): put `WorkerProgram.Main`, `WorkerIdentity` and registration in application project `InventoryWorker`; put `InventoryWorkerTest`, `[Fact]`, injected fixture and assertion in `InventoryWorker.Tests`, referencing the executable application and the actual xUnit v3 runner. Label both source files and explain the project/package references. Prefer reusing the existing Bootstrapper application/test graph linked above. If retaining the InventoryWorker domain names, first maintain a working split sample; do not publish bindings to invented paths. Keep the API page concise by linking that working integration sample and its application. Do not remove Main, choose a startup object, or manually re-register `WorkerIdentity` in the test. This skill change does not edit the xunit repository. + +`EXAMPLE_APPLICATION_ASSEMBLY_COLLAPSED` is narrowly scoped to the exact Codebelt `ManagedApplicationFixture`/`ApplicationTest` UID and a local fixture entry-point type in one C# source unit. Roslyn syntax/local symbol evidence avoids matching comments, strings, or unrelated multiple-class samples. Separate bound files are not merged for this check. Aliased or otherwise unresolved usages require build-backed verification and architectural review. The diagnostic is not a universal C# architecture analyzer and does not certify registration ownership, pipeline ordering, runtime success, or prose truth. diff --git a/skills/dotnet-docfx-digest/references/scripts.md b/skills/dotnet-docfx-digest/references/scripts.md index ff3ffac6..c9f67665 100644 --- a/skills/dotnet-docfx-digest/references/scripts.md +++ b/skills/dotnet-docfx-digest/references/scripts.md @@ -50,7 +50,7 @@ The public API model the fast path validates against is discovered without build Compilation and network access are strictly opt-in, and each option enables exactly one class of external process: -- `--validate-samples` compiles the generated C# documentation samples (`dotnet`). This is the only default-supported path that compiles samples. Every sample gets an isolated project with only the documented project(s) that own its namespace (and their transitive references resolved by MSBuild), never every documented library project. The validator writes those projects into one temporary `.slnx` and launches one graph build, so shared dependencies restore and build once while `--sample-parallelism` bounds MSBuild concurrency. Isolation preserves per-sample compiler diagnostics without paying for one `dotnet build` process per fence. +- `--validate-samples` compiles the generated C# documentation samples (`dotnet`). Unbound fences get isolated projects referencing only the documented owner and its transitive references. Explicitly project-bound fences/excerpts match maintained source, require evaluated Compile membership, and build their real projects in a temp repository copy. The existing temporary `.slnx` graph build and `--sample-parallelism` remain responsible for bounded compilation; related fences do not become one invented source file. See [example architecture](example-architecture.md) for the binding syntax and compilation/runtime limits. - `--build-api-model` (alias `--strict-api-discovery`) performs reflection-backed API discovery from compiled assemblies (`dotnet`). It builds only the documented project graph through a single temporary `.slnx` graph build rather than N per-project builds, then loads metadata through `System.Reflection.MetadataLoadContext`. Use it when conservative no-build discovery is not enough. - `--verify-docfx-build` runs DocFX against a temp copy of the repository (`docfx`). - `--search-examples` runs GitHub code search per documented package (`gh`). @@ -141,6 +141,10 @@ Error codes emitted in JSON include `AGENTS_BLOCK_MISSING`, `DOCFX_CONFIG_MISSIN UTF-8 BOM presence is not validated. `ENCODING_BOM_MISSING` is intentionally not emitted. The BOM is optional for DocFX and has no documentation value by itself, so the validator preserves existing BOM and line-ending state rather than creating encoding-only diffs. `ENCODING_CORRUPTION` and `EXTENSION_TABLE_ENCODING` remain active checks because they detect damaged content rather than a harmless encoding marker difference. +### Architectural context diagnostics + +`SAMPLE_CONTEXT_INVALID` rejects invalid explicit project/source bindings: missing or external paths, drift from maintained source, or (with `--validate-samples`) missing evaluated Compile membership or unevaluable context. Repair the declared context or source; this diagnostic is not a waiver. `EXAMPLE_APPLICATION_ASSEMBLY_COLLAPSED` applies narrowly to the exact Codebelt entrypoint-owned fixture/test contract when a test base uses a locally declared application marker in the same fence. Preserve Main and separate application/test assemblies. See [example architecture](example-architecture.md) for evidence, syntax, and limits. Registration ownership, lifecycle equivalence, pipeline semantics, prose/assertion agreement and runtime claims still require evidence-backed review; these diagnostics do not certify them. + ### Sample opt-out A C# fence may opt out of compilation only when the marker was already present before the current run **and** matches a deterministic allowlist entry in `/skip-compile-allowlist.json`. The inline marker still needs a mandatory reason: diff --git a/skills/dotnet-docfx-digest/references/workflow.md b/skills/dotnet-docfx-digest/references/workflow.md index 2f69a3dc..9b28527e 100644 --- a/skills/dotnet-docfx-digest/references/workflow.md +++ b/skills/dotnet-docfx-digest/references/workflow.md @@ -6,7 +6,7 @@ Use this reference when you need the full step-by-step workflow, example invento For optional standalone runtime evidence, follow [csrun composition](csrun-composition.md) and extend this inventory with source/manifest identity and transport-specific outcomes. Keep reference-aware compilation and documentation completion authoritative for their established scope. -Build a small example inventory from validator output and source evidence before writing examples. Treat it as a work queue, not as final-response prose. +Build a small example inventory from validator output and source evidence before writing examples. Treat it as a work queue, not as final-response prose. For each scenario record the developer question, prerequisites, execution classification/topology, expected observation, and verification plan. Record compilation, runtime evidence (or unexecuted status), and architectural review separately; a green build does not prove the prose's behavioral claim. Use [example architecture](example-architecture.md) before shaping integration or multi-file examples. ```markdown | UID | Kind | Required example location | Source evidence | Scenario | Status | @@ -25,12 +25,13 @@ Before writing a type or extension-method example, choose the smallest real task 3. When internet or GitHub search is available and allowed, search for the exact package ID and prefer consumer repositories outside the target repository. Treat self-repo hits as package-authored docs or samples, not independent usage proof. 4. Search by namespace, type, and member name only after package-ID evidence has been inspected. 5. Pick a scenario that connects the documented type to the package workflow. A good sample can include multiple related public types, a small local helper type, dependency-injection setup, host setup, options configuration, file/path setup, or result inspection when that is what a real caller would do. -6. Remove test-only structure, raw assertions, mocks, fixture base classes, and unused locals. Keep meaningful setup and result inspection. +6. Determine execution topology before generating source: standalone, library consumer, multi-file/project, framework/application integration, or partial excerpt. Remove incidental test scaffolding for ordinary APIs; retain real `[Fact]` methods, fixture constructors, assertions and runner semantics when the documented API is a testing abstraction. Keep meaningful setup and result inspection. 7. Prefer domain-specific names such as `BenchmarkRunner`, `WorkspaceUsage`, or `HttpRetryExample` over `Consumer` and `MyNamespace` when the package domain is clear. 8. Reject metadata-only substitutes before writing: `Type.GetType`, assembly lookup, `typeof`/`nameof` as the only operation, generic `Describe()` helpers, and repeated UID sections do not demonstrate a consumer task. 9. Confirm the C# fence itself uses the documented type or invokes the documented extension method. Mentions outside the fence do not count. 10. Reject runtime-type-name substitutes such as `host.Services.GetType().Name` or `service.GetType().FullName`. These reveal implementation metadata rather than the application behavior the API enables. 11. For entry-point factories and fixtures, never declare an empty local `Program` merely to satisfy compilation. Show a real entry point or name the application-project prerequisite, then make the example's result depend on a service, configuration value, endpoint, or lifecycle event supplied by that application. +12. Preserve application-owned startup and service registration. Explain executable versus test-runner entry points, references, lifecycle and infrastructure. Use labelled source files bound to maintained projects for a coherent multi-file scenario; never concatenate unrelated fences or independently compile fragments to manufacture success. If a type page becomes unwieldy, keep its essential usage and link directly to a maintained integration test or conceptual walkthrough. ## Key entry-point and upstream comparison pass @@ -314,7 +315,7 @@ Namespace overview files stay single-UID and stop after the fly-in, availability ## Type example shape -> **DocFX overwrite Markdown only.** This shape is for writing DocFX overwrite content. Do not create tests from it. Tests are evidence, not output — use tests to understand behavior, then transform that knowledge into consumer-facing examples. +> **DocFX overwrite Markdown only.** Use tests as evidence and transform ordinary API usage into consumer-facing examples. For testing abstractions, the consumer-facing example is a real framework test with its required fixture, runner, and assembly semantics. For public non-abstraction types, begin the overwrite file with front matter that maps the body to the `example` property: @@ -341,7 +342,7 @@ public class WidgetFactory ``` ```` -Do not include a manual `### Examples` heading in the body. DocFX renders that heading automatically for the `example` property. Every `csharp` code block must include a file-scoped namespace and at least one class declaration; top-level statements are not allowed unless the block is labelled `// Program.cs`. +Do not include a manual `### Examples` heading in the body. DocFX renders that heading automatically for the `example` property. Unbound fences retain the namespace/type or labelled `// Program.cs` structure rules. Project-bound source files and clearly contextualized excerpts use their maintained compilation context; see [example architecture](example-architecture.md). Multiple fences may describe one scenario, with each file's role and project identified. ## Extension method example template @@ -408,8 +409,9 @@ Before completing documentation work, verify: - [ ] Missing examples are added through DocFX overwrite content included by `build.overwrite`. Namespace pages are under `api/namespaces/` and type pages are under `api/types/`. - [ ] The Completion Repair Loop was run after edits, and the final report has zero missing/low-quality example, symbol-ownership, namespace-prose, extension, availability, overwrite-layout, sample, and DocFX-build diagnostics. - [ ] Examples are realistic, copy/paste-ready, and compile unless the sample is covered by a pre-existing approved allowlist waiver. -- [ ] Generated C# examples include a file-scoped namespace and a type declaration (class, struct, or record), or are explicitly labelled `// Program.cs`. -- [ ] No generated C# example uses top-level statements without a `// Program.cs` label. +- [ ] Unbound C# examples include a namespace and type declaration, or are explicitly labelled `// Program.cs`; project-bound files/excerpts match maintained source and compile in their actual context. +- [ ] Execution classification, prerequisites, assembly/host ownership, and intended observation were established before authoring. Partial excerpts explain their omitted setup and make no standalone claim. +- [ ] Runtime claims have actual execution evidence; compilation-only evidence is labelled accordingly. Assertions and prose establish the same contract, including registration ownership and lifecycle/pipeline behavior. - [ ] No generated C# example derives from a generic base type without concrete type arguments. - [ ] No generated C# example calls members that are not confirmed on the public API surface. - [ ] Where no compile-valid example could be generated, the overwrite file contains the appropriate omission comment, and that comment is not being misused as a diagnostic suppressor or skip waiver. From 396f903779f43a8640a72f5ff303d2223984b5a9 Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Tue, 17 Nov 2026 02:01:11 +0100 Subject: [PATCH 19/95] =?UTF-8?q?=E2=9C=A8=20validate=20source-bound=20doc?= =?UTF-8?q?fx=20sample=20contexts?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Samples can now bind to a maintained project and source file, and the validator rejects unresolvable bindings. It also refuses to collapse a ManagedApplicationFixture entry point into a test-owned source unit and skips .bot directories during source discovery. --- skills/dotnet-docfx-digest/scripts/docfx.cs | 226 ++++++++++++++++++-- 1 file changed, 214 insertions(+), 12 deletions(-) diff --git a/skills/dotnet-docfx-digest/scripts/docfx.cs b/skills/dotnet-docfx-digest/scripts/docfx.cs index eee6aa8c..8225d19a 100644 --- a/skills/dotnet-docfx-digest/scripts/docfx.cs +++ b/skills/dotnet-docfx-digest/scripts/docfx.cs @@ -3,6 +3,7 @@ #:property LangVersion=latest #:property PublishAot=false #:package System.Reflection.MetadataLoadContext@9.0.0 +#:package Microsoft.CodeAnalysis.CSharp@5.0.0 using System.Diagnostics; using System.Globalization; @@ -14,6 +15,9 @@ using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; return DocfxValidator.Run(args); @@ -414,6 +418,21 @@ private static int Validate(Options options) ValidateRequiredExamples(repoRoot, docfxWorkspace, allOverwriteSections, api, options, changedFiles, scope, workspace.NamespaceProjects, report); WritePhase(options, report, "required example validation", phaseTimer.Elapsed); + // Explicit source bindings are checked without MSBuild on the fast path. They are not waivers. + foreach (var md in workspace.MarkdownFiles) + { + if (options.ChangedOnly && changedFiles is not null && !changedFiles.Contains(Path.GetFullPath(md))) { continue; } + foreach (var sample in ExtractFences(md, workspace.ReadMarkdown(md))) + { + var error = ResolveSampleContext(sample, repoRoot, out _); + if (error is not null) + { + report.Errors.Add(new Diagnostic("SAMPLE_CONTEXT_INVALID", Rel(repoRoot, md), null, + $"C# fence #{sample.FenceIndex} (line {sample.StartLine}): {error}")); + } + } + } + // 9. Extract and compile C# documentation samples (opt-in: the only path that compiles). if (options.ValidateSamples) { @@ -474,8 +493,8 @@ private static int Validate(Options options) } } - bool hasSampleError = report.Errors.Any(e => e.Code is "SAMPLE_COMPILE_FAILED" or "SAMPLE_STRUCTURE_INVALID"); - bool hasOtherError = report.Errors.Any(e => e.Code is not "SAMPLE_COMPILE_FAILED" and not "SAMPLE_STRUCTURE_INVALID"); + bool hasSampleError = report.Errors.Any(e => e.Code is "SAMPLE_COMPILE_FAILED" or "SAMPLE_STRUCTURE_INVALID" or "SAMPLE_CONTEXT_INVALID"); + bool hasOtherError = report.Errors.Any(e => e.Code is not "SAMPLE_COMPILE_FAILED" and not "SAMPLE_STRUCTURE_INVALID" and not "SAMPLE_CONTEXT_INVALID"); report.Status = report.Errors.Count == 0 ? "passed" : "failed"; report.Summary.Errors = report.Errors.Count; @@ -1486,7 +1505,8 @@ private static void CopyDirectory( foreach (var directory in Directory.GetDirectories(sourceDirectory)) { var name = Path.GetFileName(directory); - if (IgnoredDirectorySegments.Contains(name, StringComparer.OrdinalIgnoreCase)) + if (name.Equals(".bot", StringComparison.OrdinalIgnoreCase) || + IgnoredDirectorySegments.Contains(name, StringComparer.OrdinalIgnoreCase)) { continue; } @@ -4814,6 +4834,21 @@ private static ExampleQualityResult ValidateExampleQuality( } var combinedCode = string.Join(Environment.NewLine, codeBlocks); + // This contract is specific to Codebelt's entrypoint-owned fixture, not a naming heuristic + // for arbitrary hosting APIs. Inspect each source unit separately; never merge assemblies. + if (target.Uid is "Codebelt.Extensions.Xunit.Hosting.ManagedApplicationFixture`1" or + "Codebelt.Extensions.Xunit.Hosting.ApplicationTest`2") + { + foreach (var code in codeBlocks) + { + var collapsedType = FindLocalApplicationEntryPoint(code); + if (collapsedType is not null) + { + return new ExampleQualityResult(false, "EXAMPLE_APPLICATION_ASSEMBLY_COLLAPSED", + $"The example for `{target.DisplayName}` declares fixture entry-point type `{collapsedType}` in the test source unit. ManagedApplicationFixture selects typeof(TEntryPoint).Assembly; a library compile cannot prove the application entry point, and an executable xUnit v3 runner owns its own entry point. Keep the real Main and application registrations in a separate application project, reference it from the test project, label both files, and bind the fences to maintained project/source context. Do not remove Main or substitute test-owned registration to obtain a passing build.", 7); + } + } + } var codeWithoutCommentsOrStrings = StripCodeCommentsAndStrings(combinedCode); if (Regex.IsMatch(codeWithoutCommentsOrStrings, @"\.\s*GetType\s*\(\s*\)\s*\.\s*(?:Name|FullName)\b")) @@ -4943,6 +4978,45 @@ private static ExampleQualityResult ValidateExampleQuality( return ExampleQualityResult.Success; } + private static string? FindLocalApplicationEntryPoint(string code) + { + var tree = CSharpSyntaxTree.ParseText(code); + var root = tree.GetCompilationUnitRoot(); + var model = CSharpCompilation.Create("DocfxArchitecture", [tree]).GetSemanticModel(tree); + // Syntax-only evidence: only an unqualified, unambiguous imported Codebelt fixture or its + // fully qualified name, and a matching local declaration. Aliases/conditional code that + // cannot be established here stay with build-backed verification and source review. + var imported = root.Usings.Any(u => u.Alias is null && u.Name?.ToString() == "Codebelt.Extensions.Xunit.Hosting"); + foreach (var fixture in root.DescendantNodes().OfType() + .Where(n => n.Identifier.ValueText == "ManagedApplicationFixture" && n.Arity == 1)) + { + // Establish test-class context rather than rejecting an application that legitimately + // contains a marker and uses a fixture elsewhere. Never infer this from class names. + var baseType = fixture.Ancestors().OfType().FirstOrDefault(); + if (baseType is null || !baseType.Type.DescendantNodesAndSelf().OfType() + .Any(n => n.Identifier.ValueText == "ApplicationTest" && n.Arity == 2 && + n.TypeArgumentList.Arguments[1].DescendantNodesAndSelf().Contains(fixture))) { continue; } + var qualified = fixture.Parent is QualifiedNameSyntax q && q.Right == fixture; + if (qualified ? ((QualifiedNameSyntax)fixture.Parent!).Left.ToString().Replace("global::", "") != "Codebelt.Extensions.Xunit.Hosting" : !imported) + { + continue; + } + + var argument = fixture.TypeArgumentList.Arguments[0]; + if (argument is not IdentifierNameSyntax entryPoint) { continue; } + var type = model.GetTypeInfo(argument).Type; + // A Main is not required for this diagnostic: deleting it leaves the marker in the + // test assembly and still violates the fixture's assembly-selection contract. + if (type is not null && type.TypeKind != TypeKind.Error && type.DeclaringSyntaxReferences.Any(r => r.SyntaxTree == tree) && + !root.Usings.Any(u => u.Alias?.Name.Identifier.ValueText == entryPoint.Identifier.ValueText) && + !root.DescendantNodes().OfType().Any(t => t.Identifier.ValueText == "ManagedApplicationFixture")) + { + return entryPoint.Identifier.ValueText; + } + } + return null; + } + private static bool IsApplicationEntryPointTarget(ApiTargetInfo target) { return target.Kind == ApiTargetKind.Type && @@ -5226,6 +5300,58 @@ private static string ExtractExampleSection(string body) // Sample validation // ---------------------------------------------------------------------- + private static string? ResolveSampleContext(SampleFence sample, string repoRoot, out SampleContext? context) + { + context = null; + var lines = sample.Code.Replace("\r\n", "\n").Split('\n'); + if (!lines.Any(l => l.StartsWith("// docfx-context:", StringComparison.Ordinal) || + l.StartsWith("// docfx-source:", StringComparison.Ordinal))) { return null; } + if (lines.Length < 3 || !lines[0].StartsWith("// docfx-context: ", StringComparison.Ordinal) || + !lines[1].StartsWith("// docfx-source: ", StringComparison.Ordinal)) + { + return "Use exactly two leading lines: // docfx-context: and // docfx-source: . Both files must exist; this is source-backed compilation, not a skip marker."; + } + try + { + var project = ResolveContextPath(repoRoot, lines[0][18..].Trim(), ".csproj"); + var source = ResolveContextPath(repoRoot, lines[1][17..].Trim(), ".cs"); + var excerpt = string.Join("\n", lines.Skip(2)).Trim('\n'); + var maintained = File.ReadAllText(source).Replace("\r\n", "\n").Trim('\n'); + if (string.IsNullOrWhiteSpace(excerpt) || !("\n" + maintained + "\n").Contains("\n" + excerpt + "\n", StringComparison.Ordinal)) + { + return "The fence must match a complete maintained source file or a contiguous whole-line excerpt exactly (apart from CRLF/LF and outer blank lines). Repair source/documentation drift; do not remove Main or change assertions only in the displayed copy."; + } + context = new SampleContext(project, source); + return null; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException) + { + return $"Invalid maintained project/source context: {ex.Message}"; + } + } + + private static string ResolveContextPath(string root, string relative, string extension) + { + if (Path.IsPathRooted(relative) || !relative.EndsWith(extension, StringComparison.OrdinalIgnoreCase)) + { + throw new ArgumentException($"Expected a repository-relative {extension} path: '{relative}'."); + } + var full = Path.GetFullPath(Path.Combine(root, relative)); + if (!IsPathUnderDirectory(full, root) || !File.Exists(full)) + { + throw new IOException($"The context file must exist inside the repository: '{relative}'."); + } + // Copying a linked source outside the repository would give a misleading identity. + for (var current = full; IsPathUnderDirectory(current, root); current = Path.GetDirectoryName(current)!) + { + if ((File.GetAttributes(current) & FileAttributes.ReparsePoint) != 0) + { + throw new IOException($"Linked context paths are unsupported: '{relative}'. Use a maintained file inside the repository."); + } + } + return full; + } + private static void ValidateSamples(ValidationWorkspace ws, Options options, HashSet? changedFiles, bool hasStrongNameKey, int defaultParallelism, Report report) { @@ -5254,6 +5380,7 @@ private static void ValidateSamples(ValidationWorkspace ws, Options options, Has // 2. Pre-validate structure (skip/structure checks) — no compilation. // Record which samples need compilation and their original index for deterministic ordering. var toCompile = new List<(SampleFence Sample, int OriginalIndex)>(samples.Count); + var contexts = new Dictionary(); for (int i = 0; i < samples.Count; i++) { var sample = samples[i]; @@ -5312,6 +5439,13 @@ private static void ValidateSamples(ValidationWorkspace ws, Options options, Has } } + if (ResolveSampleContext(sample, repoRoot, out var context) is not null) { continue; } // reported by fast checks + if (context is not null) + { + contexts[i] = context; + toCompile.Add((sample, i)); + continue; // Excerpts compile in their maintained source/project, not in an invented library. + } var structureError = ValidateSampleStructure(sample.Code); if (structureError is not null) { @@ -5342,6 +5476,7 @@ private static void ValidateSamples(ValidationWorkspace ws, Options options, Has var sampleRefs = new Dictionary(); foreach (var entry in toCompile) { + if (contexts.ContainsKey(entry.OriginalIndex)) { continue; } var kind = IsProgramCsExample(entry.Sample.Code) ? "app" : "lib"; var refSet = ResolveSampleReferenceSet(entry.Sample, ws, kind, packageMode); var key = $"{kind}::{(refSet.IsPackageMode ? "pkg" : "proj")}::{string.Join(";", refSet.Items)}"; @@ -5368,20 +5503,78 @@ private static void ValidateSamples(ValidationWorkspace ws, Options options, Has // diagnostic ordering regardless of MSBuild project completion order. var results = new SampleCompileResult?[samples.Count]; var workers = new List(toCompile.Count); + var contextRoot = Path.Combine(tempRoot, "context-repo"); + if (contexts.Count > 0) + { + CopyDirectory(repoRoot, contextRoot, CancellationToken.None); + } + var compileItems = new Dictionary?>(StringComparer.OrdinalIgnoreCase); for (var i = 0; i < toCompile.Count; i++) { var (sample, originalIndex) = toCompile[i]; + if (contexts.TryGetValue(originalIndex, out var context)) + { + var project = Path.Combine(contextRoot, Path.GetRelativePath(repoRoot, context.Project)); + var source = Path.Combine(contextRoot, Path.GetRelativePath(repoRoot, context.Source)); + if (!compileItems.TryGetValue(project, out var items)) + { + var evaluation = RunProcess("dotnet", $"msbuild \"{project}\" -nologo -p:Configuration={options.Configuration} -getProperty:TargetFramework,TargetFrameworks -getItem:Compile", + contextRoot, permission: ProcessPermission.SampleCompile); + items = new HashSet(StringComparer.OrdinalIgnoreCase); + try + { + if (evaluation.ExitCode != 0) { throw new InvalidOperationException(Trim(evaluation.StdOut + evaluation.StdErr)); } + using var declared = JsonDocument.Parse(evaluation.StdOut); + var properties = declared.RootElement.GetProperty("Properties"); + var singleFramework = properties.GetProperty("TargetFramework").GetString() ?? ""; + var declaredFrameworks = singleFramework + ";" + properties.GetProperty("TargetFrameworks").GetString(); + if (!declaredFrameworks.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) + .Contains(framework, StringComparer.OrdinalIgnoreCase)) + { + throw new InvalidOperationException($"{framework} is not a declared framework of this project ({declaredFrameworks.Trim(';')}). Select its actual runnable framework with --framework; do not silently retarget the project."); + } + if (!string.Equals(singleFramework, framework, StringComparison.OrdinalIgnoreCase)) + { + evaluation = RunProcess("dotnet", $"msbuild \"{project}\" -nologo -p:TargetFramework={framework} -p:Configuration={options.Configuration} -getItem:Compile", + contextRoot, permission: ProcessPermission.SampleCompile); + if (evaluation.ExitCode != 0) { throw new InvalidOperationException(Trim(evaluation.StdOut + evaluation.StdErr)); } + } + using var json = JsonDocument.Parse(evaluation.StdOut); + foreach (var item in json.RootElement.GetProperty("Items").GetProperty("Compile").EnumerateArray()) + { + items.Add(Path.GetFullPath(item.GetProperty("FullPath").GetString()!)); + } + } + catch (Exception ex) when (ex is JsonException or InvalidOperationException or KeyNotFoundException) + { + items = null; + report.Errors.Add(new Diagnostic("SAMPLE_CONTEXT_INVALID", Rel(repoRoot, sample.File), null, + $"Cannot establish evaluated Compile membership for '{Rel(repoRoot, context.Project)}': {ex.Message}. Use a supported maintained project; no compilation success is inferred.")); + } + compileItems[project] = items; + } + if (items is null) { continue; } // The project's evaluation failure was reported once. + if (!items.Contains(source)) + { + report.Errors.Add(new Diagnostic("SAMPLE_CONTEXT_INVALID", Rel(repoRoot, sample.File), null, + $"Fence #{sample.FenceIndex}: '{Rel(repoRoot, context.Source)}' is not an evaluated Compile item of '{Rel(repoRoot, context.Project)}' for {framework}/{options.Configuration}. Correct the project/source binding or conditional framework; an unrelated project build does not validate this fence.")); + continue; + } + workers.Add(new SampleWorker(originalIndex, Path.GetDirectoryName(project)!, project, source, "", true)); + continue; + } workers.Add(CreateSampleWorker(tempRoot, i + 1, originalIndex, sample, sampleRefs[originalIndex], framework)); } + if (workers.Count == 0) { return; } var batchResult = CompileSampleBatch(tempRoot, workers, options.Configuration, - parallelism, hasStrongNameKey); + parallelism, hasStrongNameKey, contexts.Count > 0 ? framework : null); foreach (var worker in workers) { var outputAssembly = Path.Combine(worker.Directory, "bin", options.Configuration, framework, worker.AssemblyName + ".dll"); - var ok = batchResult.ExitCode == 0 || File.Exists(outputAssembly); + var ok = batchResult.ExitCode == 0 || (!worker.ProjectContext && File.Exists(outputAssembly)); var diagnostics = ok ? string.Empty : ExtractSampleDiagnostics(batchResult, worker); results[worker.OriginalIndex] = new SampleCompileResult(ok, diagnostics, batchResult.ExitCode); } @@ -5599,22 +5792,26 @@ private static string GenerateSampleProject(SampleReferenceSet refSet, string fr private static ProcessResult CompileSampleBatch( string tempRoot, List workers, string configuration, int parallelism, - bool hasStrongNameKey) + bool hasStrongNameKey, string? framework = null) { var solutionPath = Path.Combine(tempRoot, "DocfxSamples.slnx"); var solution = new StringBuilder(); solution.AppendLine(""); - foreach (var worker in workers) + foreach (var project in workers.Select(w => w.ProjectPath).Distinct(StringComparer.OrdinalIgnoreCase)) { - solution.AppendLine($" "); + solution.AppendLine($" "); } solution.AppendLine(""); File.WriteAllText(solutionPath, solution.ToString(), new UTF8Encoding(false)); var signingProperty = hasStrongNameKey ? string.Empty : " -p:SkipSignAssembly=true"; + var frameworkProperty = framework is null ? string.Empty : $" -p:TargetFramework={framework}"; + // Context graphs live in a disposable copy. Persistent nodes can retain a different + // DOTNET_CLI_HOME/package root (and loaded test-runner task DLLs) from another workspace. + var contextIsolation = framework is null ? string.Empty : " --disable-build-servers"; return RunProcess("dotnet", - $"build \"{solutionPath}\" -c {configuration} --nologo -m:{parallelism}{signingProperty}", + $"build \"{solutionPath}\" -c {configuration} --nologo -m:{parallelism}{signingProperty}{frameworkProperty}{contextIsolation}", tempRoot, permission: ProcessPermission.SampleCompile, progress: new ProcessProgress("sample compilation", $"{workers.Count} sample project(s), {parallelism} runner(s)")); @@ -5623,6 +5820,9 @@ private static ProcessResult CompileSampleBatch( private static string ExtractSampleDiagnostics(ProcessResult result, SampleWorker worker) { var output = result.StdOut + result.StdErr; + // A bound project can fail in a referenced application or shared restore. Its own path + // may occur only in a successful restore line, so retain graph diagnostics in this case. + if (worker.ProjectContext) { return AddSampleCompileHints(output); } var relevant = output .Replace("\r\n", "\n", StringComparison.Ordinal) .Replace('\r', '\n') @@ -8350,7 +8550,7 @@ e.Code is not "EXTENSION_OWNER_AMBIGUOUS" && AppendRequiredExampleDiagnostics(sb, report.Errors.Where(IsExampleQualityDiagnostic), report.PackageIds); AppendGitHubExampleSources(sb, report.PackageIds, report.ExampleSearchSnippets); AppendDiagnostics(sb, "Sample Compilation Repairs", report.Errors.Where(e => - e.Code is "SAMPLE_COMPILE_FAILED" or "SAMPLE_SKIP_REASON_MISSING" or "SAMPLE_SKIP_REASON_INSUFFICIENT" or "SAMPLE_SKIP_NOT_ALLOWLISTED" or "FAIL_NEW_SKIP_MARKER_INTRODUCED" or "SAMPLE_STRUCTURE_INVALID" or "SKIP_ALLOWLIST_INVALID")); + e.Code is "SAMPLE_COMPILE_FAILED" or "SAMPLE_CONTEXT_INVALID" or "SAMPLE_SKIP_REASON_MISSING" or "SAMPLE_SKIP_REASON_INSUFFICIENT" or "SAMPLE_SKIP_NOT_ALLOWLISTED" or "FAIL_NEW_SKIP_MARKER_INTRODUCED" or "SAMPLE_STRUCTURE_INVALID" or "SKIP_ALLOWLIST_INVALID")); AppendDiagnostics(sb, "Xref Member Link Repairs", report.Errors.Where(e => e.Code is "XREF_MEMBER_LINK")); AppendDiagnostics(sb, "Other Errors", report.Errors.Where(e => e.Code is not "AGENTS_BLOCK_MISSING" && @@ -8360,7 +8560,7 @@ e.Code is not "INTERIM_ARTIFACT_IN_WORKTREE" && !e.Code.StartsWith("EXTENSION_", StringComparison.Ordinal) && e.Code is not "SYMBOL_COLLISION_UNRESOLVED" && !IsExampleQualityDiagnostic(e) && - e.Code is not "SAMPLE_COMPILE_FAILED" and not "SAMPLE_SKIP_REASON_MISSING" and not "SAMPLE_SKIP_REASON_INSUFFICIENT" and not "SAMPLE_SKIP_NOT_ALLOWLISTED" and not "FAIL_NEW_SKIP_MARKER_INTRODUCED" and not "SAMPLE_STRUCTURE_INVALID" and not "SKIP_ALLOWLIST_INVALID" and not "XREF_MEMBER_LINK")); + e.Code is not "SAMPLE_COMPILE_FAILED" and not "SAMPLE_CONTEXT_INVALID" and not "SAMPLE_SKIP_REASON_MISSING" and not "SAMPLE_SKIP_REASON_INSUFFICIENT" and not "SAMPLE_SKIP_NOT_ALLOWLISTED" and not "FAIL_NEW_SKIP_MARKER_INTRODUCED" and not "SAMPLE_STRUCTURE_INVALID" and not "SKIP_ALLOWLIST_INVALID" and not "XREF_MEMBER_LINK")); AppendDiagnostics(sb, "Warnings", report.Warnings); sb.AppendLine("## Completion Checklist"); @@ -9068,6 +9268,7 @@ public string ReadMarkdown(string path) } private sealed record SampleFence(string File, int FenceIndex, int StartLine, string Code); + private sealed record SampleContext(string Project, string Source); private sealed record OverwriteSection( string File, @@ -9153,7 +9354,8 @@ private sealed record SampleWorker( string Directory, string ProjectPath, string SourcePath, - string AssemblyName); + string AssemblyName, + bool ProjectContext = false); private sealed record SampleReferenceSet( string Kind, From 8da9f393968310561b40ea57160ff491fe630319 Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Tue, 17 Nov 2026 02:01:12 +0100 Subject: [PATCH 20/95] =?UTF-8?q?=E2=9C=85=20cover=20source-bound=20sample?= =?UTF-8?q?=20and=20entry-point=20checks?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Regression coverage for the full completion boundary with a project-bound example, and for the new context and entry-point diagnostics, so the checks stay enforced. --- .../scripts/test-project-scoped.ps1 | 20 ++ .../scripts/test-quality.ps1 | 173 ++++++++++++++++++ 2 files changed, 193 insertions(+) diff --git a/skills/dotnet-docfx-digest/scripts/test-project-scoped.ps1 b/skills/dotnet-docfx-digest/scripts/test-project-scoped.ps1 index d1797db6..dc2812d0 100644 --- a/skills/dotnet-docfx-digest/scripts/test-project-scoped.ps1 +++ b/skills/dotnet-docfx-digest/scripts/test-project-scoped.ps1 @@ -695,6 +695,26 @@ public static class WidgetCapacity Assert-NoDiagnostic -Report $final -Code 'REVIEW_REPORT_INCOMPLETE' Assert-NoDiagnostic -Report $final -Code 'EXAMPLE_MISSING' Assert-NoDiagnostic -Report $final -Code 'SAMPLE_COMPILE_FAILED' + + # The ordinary full completion boundary also accepts a maintained project-bound example. + # Keep the consumer internal so it does not add a synthetic public documentation target. + $typePage = Join-Path $ws '.docfx/api/types/Acme.Core.Widget.md' + $pageText = [IO.File]::ReadAllText($typePage) + $codeMatch = [regex]::Match($pageText, '(?s)```csharp\r?\n(?.*?)```') + $consumer = $codeMatch.Groups['code'].Value.Replace('public static class WidgetCapacity', 'internal static class WidgetCapacity') + Write-Utf8File (Join-Path $ws 'src/Core/WidgetCapacity.cs') $consumer + $binding = "// docfx-context: src/Core/Acme.Core.csproj`n// docfx-source: src/Core/WidgetCapacity.cs`n" + Write-Utf8File $typePage ($pageText.Replace($codeMatch.Groups['code'].Value, $binding + $consumer)) + $agentsApp = Get-FileBasedAppCommand -SourcePath (Join-Path $PSScriptRoot 'agents.cs') + & $agentsApp.Executable @($agentsApp.ArgumentPrefix + @('--repo-root', $ws)) | Out-Null + if ($LASTEXITCODE -ne 0) { throw 'agents.cs failed at the documentation completion boundary.' } + $complete = Invoke-Validator $ws @('--build-api-model', '--validate-samples', '--verify-docfx-build') + if (-not $complete.summary.fullVerificationRan -or -not $complete.summary.canClaimCompletion -or + $complete.summary.remainingWorkItems -ne 0 -or @($complete.summary.remainingGates).Count -ne 0 -or + @($complete.summary.remainingDiagnosticsByCode.PSObject.Properties).Count -ne 0 -or + $complete.summary.newlyIntroducedSkipMarkers -ne 0 -or $complete.summary.interimArtifacts -ne 0) { + throw "Project-bound full completion contract failed: $($complete | ConvertTo-Json -Depth 8)" + } } finally { if (Test-Path $artifactRoot) { Remove-Item $artifactRoot -Recurse -Force -ErrorAction SilentlyContinue diff --git a/skills/dotnet-docfx-digest/scripts/test-quality.ps1 b/skills/dotnet-docfx-digest/scripts/test-quality.ps1 index 04e397f6..52909247 100644 --- a/skills/dotnet-docfx-digest/scripts/test-quality.ps1 +++ b/skills/dotnet-docfx-digest/scripts/test-quality.ps1 @@ -2438,6 +2438,179 @@ Namespace overview. } } +# Architecture fixtures use the real published fixture and xUnit runner, never a substitute host. +# Build only the temp copy; the source fixture tree must remain free of bin/obj artifacts. +$architecture = Join-Path ([System.IO.Path]::GetTempPath()) ('dotnet-docfx-architecture-' + [guid]::NewGuid().ToString('N')) +try { + $fixtureRoot = Join-Path $PSScriptRoot 'fixtures/example-architecture' + New-Item -ItemType Directory -Path $architecture | Out-Null + Copy-Item -Path (Join-Path $fixtureRoot '*') -Destination $architecture -Recurse + Write-Utf8File (Join-Path $architecture 'AGENTS.md') "`nManaged DocFX guidance.`n" + Write-Utf8File (Join-Path $architecture '.docfx/docfx.json') (New-DocfxJson @('app/InventoryWorker/InventoryWorker.csproj')) + # A metadata fixture selects the exact public contract without implementing a fake API. + Write-Utf8File (Join-Path $architecture '.docfx/api/fixture.yml') @' +### YamlMime:ManagedReference +items: +- uid: Codebelt.Extensions.Xunit.Hosting + name: Codebelt.Extensions.Xunit.Hosting + type: Namespace +- uid: Codebelt.Extensions.Xunit.Hosting.ManagedApplicationFixture`1 + name: ManagedApplicationFixture + namespace: Codebelt.Extensions.Xunit.Hosting + type: Class + syntax: + content: public class ManagedApplicationFixture +'@ + $appSource = [IO.File]::ReadAllText((Join-Path $architecture 'app/InventoryWorker/Program.cs')).TrimEnd() + $testSource = [IO.File]::ReadAllText((Join-Path $architecture 'test/InventoryWorker.Tests/InventoryWorkerTest.cs')).TrimEnd() + $page = Join-Path $architecture '.docfx/api/types/Fixture.md' + $frontMatter = '---' + "`n" + 'uid: Codebelt.Extensions.Xunit.Hosting.ManagedApplicationFixture`1' + "`nexample: *content`n---`n" + $fence = '```' + $lead = 'Verify that the real worker application registers its identity service. The application owns Main and service registration; the separate xUnit v3 executable test project references it and resolves the application service through the fixture.' + $boundApp = "// docfx-context: app/InventoryWorker/InventoryWorker.csproj`n// docfx-source: app/InventoryWorker/Program.cs`n$appSource" + $boundTest = "// docfx-context: test/InventoryWorker.Tests/InventoryWorker.Tests.csproj`n// docfx-source: test/InventoryWorker.Tests/InventoryWorkerTest.cs`n$testSource" + $split = "$frontMatter`n$lead`n`nApplication project InventoryWorker, Program.cs:`n`n${fence}csharp`n$boundApp`n$fence`n`nTest project InventoryWorker.Tests, InventoryWorkerTest.cs. It uses Codebelt.Extensions.Xunit.Hosting and xunit.v3 and a ProjectReference to InventoryWorker. See the [maintained integration sample](https://github.com/codebeltnet/xunit/blob/84b13767cb9484f8f3a36a71875662edfdb3e511/test/Codebelt.Extensions.Xunit.Hosting.FunctionalTests/BootstrapperMinimalWorkerApplicationTestTest.cs) for the full setup:`n`n${fence}csharp`n$boundTest`n$fence`n" + Write-Utf8File $page $split + Initialize-GitRepo $architecture + $before = [IO.File]::ReadAllBytes($page) + $positive = Invoke-Validator -Workspace $architecture + Assert-NoDiagnostic $positive 'EXAMPLE_APPLICATION_ASSEMBLY_COLLAPSED' + Assert-NoDiagnostic $positive 'SAMPLE_CONTEXT_INVALID' + foreach ($process in @('dotnet', 'msbuild', 'docfx', 'gh')) { + if ($positive.summary.processes.$process -ne 0) { throw "Fast architecture validation launched $process." } + } + # Bound projects compile together, preserving real entry points and ProjectReference resolution. + $compiled = Invoke-Validator -Workspace $architecture -ExtraArgs @('--validate-samples') + Assert-NoDiagnostic $compiled 'SAMPLE_COMPILE_FAILED' + Assert-NoDiagnostic $compiled 'SAMPLE_STRUCTURE_INVALID' + Assert-NoDiagnostic $compiled 'SAMPLE_CONTEXT_INVALID' + if ($compiled.summary.samplesCompiled -ne 2) { throw "Expected both bound files to compile. $($compiled | ConvertTo-Json -Depth 8)" } + if ($compiled.summary.canClaimCompletion -or $compiled.summary.fullVerificationRan) { throw 'Compilation alone claimed full verification.' } + # Execute the real test runner separately: build evidence is not runtime evidence. + $testProject = Join-Path $architecture 'test/InventoryWorker.Tests/InventoryWorker.Tests.csproj' + $execution = & dotnet run --project $testProject -c Release --disable-build-servers 2>&1 | Out-String + if ($LASTEXITCODE -ne 0 -or $execution -notmatch '(?:Passed|Total):\s+3' -or $execution -notmatch 'Failed:\s+0') { + throw "Real architecture test execution failed or discovered no tests: $execution" + } + Write-Host 'DocFX split application, standalone Fact and middleware HTTP execution passed (3 real tests).' + if ([Convert]::ToHexString($before) -ne [Convert]::ToHexString([IO.File]::ReadAllBytes($page))) { throw 'Validation changed Markdown encoding or line endings.' } + + # A semantic trap cannot be diagnosed from registration syntax alone: demonstrate that the + # original test fails without application registration, but a test-owned override can hide it. + # This is negative control evidence for architectural review, not an acceptable docs repair. + $appPath = Join-Path $architecture 'app/InventoryWorker/Program.cs' + $testPath = Join-Path $architecture 'test/InventoryWorker.Tests/InventoryWorkerTest.cs' + Write-Utf8File $appPath ($appSource.Replace('builder.Services.AddSingleton(new WorkerIdentity("Inventory worker"));', '')) + $missingRegistration = & dotnet run --project $testProject -c Release --disable-build-servers 2>&1 | Out-String + if ($LASTEXITCODE -eq 0 -or $missingRegistration -notmatch 'Failed:\s+1' -or $missingRegistration -notmatch 'No service for type') { + throw "Original assertion did not expose missing application registration: $missingRegistration" + } + $override = @' + protected override void ConfigureHost(IHostBuilder builder) + { + builder.ConfigureServices(services => services.AddSingleton(new WorkerIdentity("Inventory worker"))); + } + + [Fact] +'@ + Write-Utf8File $testPath ("using Microsoft.Extensions.Hosting;`n" + $testSource.Replace(' [Fact]', $override)) + $testOwned = & dotnet run --project $testProject -c Release --disable-build-servers 2>&1 | Out-String + if ($LASTEXITCODE -ne 0 -or $testOwned -notmatch '(?:Passed|Total):\s+3' -or $testOwned -notmatch 'Failed:\s+0') { + throw "Test-owned registration control failed: $testOwned" + } + Write-Utf8File $appPath $appSource + Write-Utf8File $testPath $testSource + Write-Host 'DocFX registration ownership controls passed (application removal fails; test override masks it).' + + # The original shape is library-compilable yet selects the wrong assembly in a real runner. + # Combine valid syntax, not concatenated file-scoped namespaces or mid-file using directives. + $merged = "using Microsoft.Extensions.Hosting;`n" + $testSource + "`n" + ($appSource -replace '(?m)^using .*;\r?\n', '' -replace 'namespace InventoryWorker;', '') + Write-Utf8File $page "$frontMatter`n$lead`n`n${fence}csharp`n$merged`n$fence" + $collapsed = Invoke-Validator -Workspace $architecture + Assert-Diagnostic $collapsed 'EXAMPLE_APPLICATION_ASSEMBLY_COLLAPSED' + Assert-DiagnosticMessageContains $collapsed 'EXAMPLE_APPLICATION_ASSEMBLY_COLLAPSED' 'Keep the real Main' + # Removing Main still leaves TEntryPoint in the test assembly and must remain a failure. + $noMain = $merged.Substring(0, $merged.IndexOf(' public static void Main')) + "}`n" + Write-Utf8File $page "$frontMatter`n$lead`n`n${fence}csharp`n$noMain`n$fence" + Assert-Diagnostic (Invoke-Validator -Workspace $architecture) 'EXAMPLE_APPLICATION_ASSEMBLY_COLLAPSED' + # Real xUnit source generation exposes competing Main methods as CS0017. + Write-Utf8File (Join-Path $architecture 'test/InventoryWorker.Tests/InventoryWorkerTest.cs') $merged + $conflict = & dotnet build $testProject -c Release --nologo --disable-build-servers 2>&1 | Out-String + if ($LASTEXITCODE -eq 0 -or $conflict -notmatch 'CS0017') { throw "Merged executable did not expose CS0017: $conflict" } + Write-Host 'DocFX merged entry-point negative controls passed.' + Write-Utf8File (Join-Path $architecture 'test/InventoryWorker.Tests/InventoryWorkerTest.cs') $testSource + + # Source drift, missing references and excluded files must not become successful samples. + Write-Utf8File $page ($split.Replace('Assert.True(WorkerProgram.MainInvoked);', 'Assert.True(true);')) + Assert-Diagnostic (Invoke-Validator -Workspace $architecture) 'SAMPLE_CONTEXT_INVALID' + Write-Utf8File $page ($split.Replace('test/InventoryWorker.Tests/InventoryWorker.Tests.csproj', 'missing/Invented.csproj')) + Assert-Diagnostic (Invoke-Validator -Workspace $architecture) 'SAMPLE_CONTEXT_INVALID' + Write-Utf8File $page $split + $originalProject = [IO.File]::ReadAllText($testProject) + Write-Utf8File $testProject ($originalProject.Replace('net10.0', 'net9.0')) + $wrongFramework = Invoke-Validator -Workspace $architecture -ExtraArgs @('--validate-samples') + Assert-DiagnosticMessageContains $wrongFramework 'SAMPLE_CONTEXT_INVALID' 'not a declared framework' + Write-Utf8File $testProject $originalProject + Write-Utf8File $testProject ($originalProject.Replace('', '')) + Assert-Diagnostic (Invoke-Validator -Workspace $architecture -ExtraArgs @('--validate-samples')) 'SAMPLE_CONTEXT_INVALID' + Write-Utf8File $testProject $originalProject + Write-Utf8File $testProject ($originalProject.Replace('../../app/InventoryWorker/InventoryWorker.csproj', '../../app/Missing/Missing.csproj')) + Assert-Diagnostic (Invoke-Validator -Workspace $architecture -ExtraArgs @('--validate-samples')) 'SAMPLE_COMPILE_FAILED' + Write-Utf8File $testProject $originalProject + + # Contextualized partial excerpt compiles in its actual file; no dummy entry point is supplied. + $excerpt = ' Assert.Equal("Inventory worker", identity.Name);' + # Keep essential target usage on the page; the excerpt supplements the test fence. + Write-Utf8File $page ($split + "`nIntentionally partial assertion from that test; initialization is shown above.`n`n${fence}csharp`n// docfx-context: test/InventoryWorker.Tests/InventoryWorker.Tests.csproj`n// docfx-source: test/InventoryWorker.Tests/InventoryWorkerTest.cs`n$excerpt`n$fence") + $partialReport = Invoke-Validator -Workspace $architecture -ExtraArgs @('--validate-samples') + Assert-NoDiagnostic $partialReport 'SAMPLE_CONTEXT_INVALID' + Assert-NoDiagnostic $partialReport 'SAMPLE_STRUCTURE_INVALID' + Assert-NoDiagnostic $partialReport 'SAMPLE_COMPILE_FAILED' + if ($partialReport.summary.samplesCompiled -ne 3) { throw 'Grouped source and partial excerpt were not all validated.' } + Write-Host 'DocFX source binding, excluded file, project reference and partial excerpt controls passed.' + + # Preservation: ordinary library snippets, real multiple-class files, Program.cs, + # a standalone xUnit v3 Fact and realistic HTTP middleware remain valid source shapes. + $library = @' +using System; +namespace Inventory; +public sealed record StockItem(int Quantity); +public static class StockReport +{ + public static void PrintTotal() + { + var reserved = new StockItem(42); + Console.WriteLine(reserved.Quantity); + } +} +'@ + $console = "// Program.cs`nusing System;`nConsole.WriteLine(6 * 7);" + $preserved = $split + "`nA library consumer reports the reserved inventory quantity.`n`n${fence}csharp`n$library`n$fence`n`nThis standalone console program prints the same quantity.`n`n${fence}csharp`n$console`n$fence`n" + foreach ($sourceName in @('StandaloneTest.cs', 'MiddlewareTest.cs')) { + $sourcePath = "test/InventoryWorker.Tests/$sourceName" + $source = [IO.File]::ReadAllText((Join-Path $architecture $sourcePath)).TrimEnd() + $preserved += "`nThe maintained $sourceName uses the real xUnit v3 runner. The middleware test registers the pipeline before sending HTTP and verifies both body and header.`n`n${fence}csharp`n// docfx-context: test/InventoryWorker.Tests/InventoryWorker.Tests.csproj`n// docfx-source: $sourcePath`n$source`n$fence`n" + } + Write-Utf8File $page $preserved + $preservation = Invoke-Validator -Workspace $architecture -ExtraArgs @('--validate-samples') + foreach ($code in @('SAMPLE_CONTEXT_INVALID', 'SAMPLE_STRUCTURE_INVALID', 'SAMPLE_COMPILE_FAILED', 'EXAMPLE_APPLICATION_ASSEMBLY_COLLAPSED')) { + Assert-NoDiagnostic $preservation $code + } + if ($preservation.summary.samplesCompiled -ne 6) { throw 'Expected six preserved source units to compile.' } + + # An invented dependency cannot pass by pointing at an otherwise valid project. + $feed = Join-Path $architecture 'empty-feed' + New-Item -ItemType Directory -Path $feed | Out-Null + Write-Utf8File $testProject ($originalProject.Replace('', '')) + Write-Utf8File (Join-Path $architecture 'NuGet.Config') "" + $dependencyFailure = Invoke-Validator -Workspace $architecture -ExtraArgs @('--validate-samples') + Assert-Diagnostic $dependencyFailure 'SAMPLE_COMPILE_FAILED' + Assert-DiagnosticMessageContains $dependencyFailure 'SAMPLE_COMPILE_FAILED' 'NU1101' + Write-Host 'DocFX application assembly architecture regression passed (real xUnit execution, CS0017, contexts and excerpts).' +} finally { + if (Test-Path $architecture) { Remove-Item -LiteralPath $architecture -Recurse -Force } +} + # The validator returns a non-zero exit code for fixtures that intentionally contain # diagnostics. Success here is determined by the assertions above not throwing, so reset # the process exit code for callers (e.g. validate-skill-templates.ps1) that inspect it. From 7d1b23419760851ac5fa18b8db6e50749b24e23b Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Tue, 17 Nov 2026 02:01:13 +0100 Subject: [PATCH 21/95] =?UTF-8?q?=E2=9C=85=20add=20managed=20application?= =?UTF-8?q?=20example=20eval=20fixtures?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds eval case 115 and the InventoryWorker fixture tree that the managed application example regression depends on. Tests copy these fixtures to a temp directory before building, so they are never built in place. --- skills/dotnet-docfx-digest/evals/evals.json | 56 +++++++++++++++++++ .../InventoryWorker/InventoryWorker.csproj | 9 +++ .../app/InventoryWorker/Program.cs | 20 +++++++ .../fixtures/example-architecture/evidence.md | 9 +++ .../InventoryWorker.Tests.csproj | 11 ++++ .../InventoryWorkerTest.cs | 22 ++++++++ .../InventoryWorker.Tests/MiddlewareTest.cs | 33 +++++++++++ .../InventoryWorker.Tests/StandaloneTest.cs | 12 ++++ 8 files changed, 172 insertions(+) create mode 100644 skills/dotnet-docfx-digest/scripts/fixtures/example-architecture/app/InventoryWorker/InventoryWorker.csproj create mode 100644 skills/dotnet-docfx-digest/scripts/fixtures/example-architecture/app/InventoryWorker/Program.cs create mode 100644 skills/dotnet-docfx-digest/scripts/fixtures/example-architecture/evidence.md create mode 100644 skills/dotnet-docfx-digest/scripts/fixtures/example-architecture/test/InventoryWorker.Tests/InventoryWorker.Tests.csproj create mode 100644 skills/dotnet-docfx-digest/scripts/fixtures/example-architecture/test/InventoryWorker.Tests/InventoryWorkerTest.cs create mode 100644 skills/dotnet-docfx-digest/scripts/fixtures/example-architecture/test/InventoryWorker.Tests/MiddlewareTest.cs create mode 100644 skills/dotnet-docfx-digest/scripts/fixtures/example-architecture/test/InventoryWorker.Tests/StandaloneTest.cs diff --git a/skills/dotnet-docfx-digest/evals/evals.json b/skills/dotnet-docfx-digest/evals/evals.json index d4a41208..2d47b2e1 100644 --- a/skills/dotnet-docfx-digest/evals/evals.json +++ b/skills/dotnet-docfx-digest/evals/evals.json @@ -1203,6 +1203,62 @@ "Preserves application Main and assembly separation and retains docfx.cs --build-api-model --validate-samples --verify-docfx-build as authoritative documentation gates.", "Keeps concise primary C# fences and existing UID placement; no deterministic validator launches an AI agent and no duplicate compiler or unrequested project scaffolding is added." ] + }, + { + "id": 115, + "prompt": "Improve the ManagedApplicationFixture API-reference example using the attached InventoryWorker application and xUnit v3 test projects. The old page displays InventoryWorkerTest and WorkerProgram.Main together as one independently runnable file. Explain and preserve what the test proves, keep the API page concise, and validate the real application/test graph. Do not edit codebeltnet/xunit or use stub fixtures.", + "files": [ + "scripts/fixtures/example-architecture/app/InventoryWorker/InventoryWorker.csproj", + "scripts/fixtures/example-architecture/app/InventoryWorker/Program.cs", + "scripts/fixtures/example-architecture/test/InventoryWorker.Tests/InventoryWorker.Tests.csproj", + "scripts/fixtures/example-architecture/test/InventoryWorker.Tests/InventoryWorkerTest.cs", + "scripts/fixtures/example-architecture/evidence.md" + ], + "expected_output": "Establishes the developer task and assembly-selection contract from the pinned implementation and functional tests. Presents labelled application/test files with actual project/package prerequisites, binds them to the maintained source/project context, preserves Main, fixture injection, Fact and assertions, and distinguishes build evidence from real runner execution. Recommends the upstream documentation correction separately without modifying that repository.", + "expectations": [ + "Explains typeof(TEntryPoint).Assembly and the separate executable xUnit runner entry point; never claims the merged source is standalone", + "Keeps application-owned registration and startup in the application project and the real fixture assertion in the referencing test project", + "Does not remove Main, choose a startup object, replace the host, or register WorkerIdentity inside the test as a compilation repair", + "Uses labelled files and exact maintained project/source bindings or a concise essential example with a direct maintained integration link; does not merely concatenate fences", + "Reports compilation and actual execution evidence separately, including unexecuted runtime behavior", + "Keeps the existing full DocFX completion contract and csrun execution boundary" + ] + }, + { + "id": 116, + "prompt": "Review proposed repairs to an entrypoint-owned ApplicationTest example: A deletes WorkerProgram.Main, B overrides ConfigureHost to register WorkerIdentity inside the test while claiming the application registered it, C substitutes a manually built Host, and D keeps two projects but says the assertion ran successfully based only on dotnet build. All variants compile. Decide which claims are justified and describe the smallest correct documentation repair.", + "expected_output": "Rejects all four as evidence of the original application registration. Explains the changed contract for each, preserves real application Main and registration, requires actual test execution for runtime claims, and treats semantic review as evidence-backed judgment rather than an invented universal regex diagnostic.", + "expectations": [ + "Removing Main leaves the marker in the wrong assembly or removes required startup; compilation cannot establish the original contract", + "A test-owned registration or alternative host may be valid for a different scenario but cannot prove original application-owned registration", + "Successful compilation alone is labelled compilation only; no claimed successful test execution", + "Missing or invented dependencies remain unresolved failures and are repaired against actual project/package evidence", + "Does not weaken assertions or introduce skip markers to manufacture success" + ] + }, + { + "id": 117, + "prompt": "Design concise DocFX examples for: a library method returning parsed inventory quantities; a complete single-file console program; a standalone xUnit v3 Fact; and ASP.NET Core middleware that adds a response header before the next delegate. The middleware has a maintained application and HTTP integration test. Use the smallest realistic representation, preserve lifecycle/pipeline semantics, and state what can actually be verified.", + "expected_output": "Classifies each execution model before authoring, keeps the ordinary library snippet concise and the console Program.cs executable, preserves real assertions for the testing API, and uses the middleware's actual registration, pipeline, request/response and host lifecycle. Uses csrun only for compatible standalone cases and project-aware validation for integration.", + "expectations": [ + "Establishes intention, real dependencies/framework, intended observation and reproducibility before source generation", + "Does not force the library method into a console application or require every fence to independently execute", + "Preserves genuine xUnit Fact/fixture structure where it is the testing API's consumer contract", + "Middleware setup and ordering support the claimed HTTP behavior, with async/disposal lifecycles preserved", + "No runtime success is inferred from compilation and no implementation metadata substitutes for behavior" + ] + }, + { + "id": 118, + "prompt": "An API page needs a short fixture example linking to its maintained multi-project integration test, plus an intentionally partial assertion excerpt from that test. The existing context file has valid DocFX UID ownership, conditional target-framework examples, a pre-existing approved sample waiver, and UTF-8 BOM/CRLF. Extend the page without rewriting unrelated content. Another proposal labels a missing project dependency as a successful standalone example.", + "expected_output": "Keeps essential target usage and prerequisites concise, labels the excerpt and binds it to its real source/project, links the working integration graph, and rejects the missing dependency/standalone claim. Preserves existing UID structure, conditional asset selection, strict waiver rules, encoding, line endings and completion gates.", + "expectations": [ + "A maintained link supplements rather than replaces local target API usage and compilation", + "The excerpt is explicitly partial, has accurate containing context, and is never represented as an independently runnable file", + "Source identity and evaluated Compile membership must hold; an unrelated compiling project or unavailable dependency is not accepted", + "Existing multiple-class files, ordinary library snippets and Program.cs examples retain their validation behavior", + "Preserves exact overwrite UID ownership, conditional TFM requirements, strict existing waiver approval and Markdown encoding/line endings" + ] } ] } diff --git a/skills/dotnet-docfx-digest/scripts/fixtures/example-architecture/app/InventoryWorker/InventoryWorker.csproj b/skills/dotnet-docfx-digest/scripts/fixtures/example-architecture/app/InventoryWorker/InventoryWorker.csproj new file mode 100644 index 00000000..bc373113 --- /dev/null +++ b/skills/dotnet-docfx-digest/scripts/fixtures/example-architecture/app/InventoryWorker/InventoryWorker.csproj @@ -0,0 +1,9 @@ + + + net10.0 + Exe + + + + + diff --git a/skills/dotnet-docfx-digest/scripts/fixtures/example-architecture/app/InventoryWorker/Program.cs b/skills/dotnet-docfx-digest/scripts/fixtures/example-architecture/app/InventoryWorker/Program.cs new file mode 100644 index 00000000..01601069 --- /dev/null +++ b/skills/dotnet-docfx-digest/scripts/fixtures/example-architecture/app/InventoryWorker/Program.cs @@ -0,0 +1,20 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +namespace InventoryWorker; + +public sealed record WorkerIdentity(string Name); + +public sealed class WorkerProgram +{ + public static bool MainInvoked { get; private set; } + + public static void Main(string[] args) + { + MainInvoked = true; + var builder = Host.CreateApplicationBuilder(args); + builder.Services.AddSingleton(new WorkerIdentity("Inventory worker")); + using var host = builder.Build(); + host.Run(); + } +} diff --git a/skills/dotnet-docfx-digest/scripts/fixtures/example-architecture/evidence.md b/skills/dotnet-docfx-digest/scripts/fixtures/example-architecture/evidence.md new file mode 100644 index 00000000..b421817e --- /dev/null +++ b/skills/dotnet-docfx-digest/scripts/fixtures/example-architecture/evidence.md @@ -0,0 +1,9 @@ +# Architecture regression evidence + +These are maintained regression fixtures, not a new project generator. Tests copy them to OS temp before building; never build this tree in place. + +The split InventoryWorker scenario adapts the [published example](https://xunit.codebelt.net/api/Codebelt.Extensions.Xunit.Hosting.ManagedApplicationFixture-1.html). Its assembly contract is verified against the implementation and worker functional tests at [codebeltnet/xunit 84b13767cb9484f8f3a36a71875662edfdb3e511](https://github.com/codebeltnet/xunit/tree/84b13767cb9484f8f3a36a71875662edfdb3e511), detailed in [example architecture](../../../references/example-architecture.md). Runtime tests use the real published `Codebelt.Extensions.Xunit.Hosting` 13.0.0 and xUnit v3 4.0.3 packages, not substitute fixtures or simulated assertions. The app uses the SDK's ASP.NET Core shared framework for hosting references; that fixture dependency does not imply all hosting consumers require ASP.NET Core. + +The test asserts the application registration's value, invocation of the real Main, and different application/test assemblies. Its assertion performs no service registration. Compiling the merged source as a library would conceal the executable topology; compiling it as an xUnit executable must fail with CS0017. Removing Main must not make the documentation acceptable. Runtime negative controls remove the application's registration (the original assertion must fail), then supply that registration in the test's ConfigureHost override (the assertion can pass despite the missing application registration). The latter is evidence of a changed contract, not a recommended correction. + +Architecture-sensitive editorial acceptance cases are also versioned in `evals/evals.json`. Static checks cannot prove prose truth: a test-owned registration may be valid for an override scenario but cannot demonstrate original application registration; a compiling middleware example may still place authentication after authorization; and a successful build is not observed runtime success. Review those contracts against the linked implementation/tests and execution evidence. diff --git a/skills/dotnet-docfx-digest/scripts/fixtures/example-architecture/test/InventoryWorker.Tests/InventoryWorker.Tests.csproj b/skills/dotnet-docfx-digest/scripts/fixtures/example-architecture/test/InventoryWorker.Tests/InventoryWorker.Tests.csproj new file mode 100644 index 00000000..50ebfcfc --- /dev/null +++ b/skills/dotnet-docfx-digest/scripts/fixtures/example-architecture/test/InventoryWorker.Tests/InventoryWorker.Tests.csproj @@ -0,0 +1,11 @@ + + + net10.0 + Exe + + + + + + + diff --git a/skills/dotnet-docfx-digest/scripts/fixtures/example-architecture/test/InventoryWorker.Tests/InventoryWorkerTest.cs b/skills/dotnet-docfx-digest/scripts/fixtures/example-architecture/test/InventoryWorker.Tests/InventoryWorkerTest.cs new file mode 100644 index 00000000..ec0bbe53 --- /dev/null +++ b/skills/dotnet-docfx-digest/scripts/fixtures/example-architecture/test/InventoryWorker.Tests/InventoryWorkerTest.cs @@ -0,0 +1,22 @@ +using Codebelt.Extensions.Xunit.Hosting; +using Microsoft.Extensions.DependencyInjection; +using Xunit; + +namespace InventoryWorker.Tests; + +public sealed class InventoryWorkerTest : ApplicationTest> +{ + public InventoryWorkerTest(ManagedApplicationFixture fixture, ITestOutputHelper output) + : base(fixture, output) + { + } + + [Fact] + public void Host_ContainsApplicationService() + { + var identity = Host.Services.GetRequiredService(); + Assert.Equal("Inventory worker", identity.Name); + Assert.True(WorkerProgram.MainInvoked); + Assert.NotEqual(typeof(WorkerProgram).Assembly, typeof(InventoryWorkerTest).Assembly); + } +} diff --git a/skills/dotnet-docfx-digest/scripts/fixtures/example-architecture/test/InventoryWorker.Tests/MiddlewareTest.cs b/skills/dotnet-docfx-digest/scripts/fixtures/example-architecture/test/InventoryWorker.Tests/MiddlewareTest.cs new file mode 100644 index 00000000..fd1b5a97 --- /dev/null +++ b/skills/dotnet-docfx-digest/scripts/fixtures/example-architecture/test/InventoryWorker.Tests/MiddlewareTest.cs @@ -0,0 +1,33 @@ +using System.Linq; +using System.Net.Http; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Xunit; + +namespace InventoryWorker.Tests; + +public sealed class MiddlewareTest +{ + [Fact] + public async Task Pipeline_AddsInventoryHeader() + { + var cancellationToken = TestContext.Current.CancellationToken; + var builder = WebApplication.CreateBuilder(); + await using var app = builder.Build(); + app.Urls.Add("http://127.0.0.1:0"); + app.Use(async (context, next) => + { + context.Response.Headers["X-Inventory"] = "ready"; + await next(context); + }); + app.MapGet("/inventory", () => "42"); + await app.StartAsync(cancellationToken); + using var client = new HttpClient(); + using var response = await client.GetAsync(app.Urls.Single() + "/inventory", cancellationToken); + response.EnsureSuccessStatusCode(); + Assert.Equal("42", await response.Content.ReadAsStringAsync(cancellationToken)); + Assert.Equal("ready", response.Headers.GetValues("X-Inventory").Single()); + await app.StopAsync(cancellationToken); + } +} diff --git a/skills/dotnet-docfx-digest/scripts/fixtures/example-architecture/test/InventoryWorker.Tests/StandaloneTest.cs b/skills/dotnet-docfx-digest/scripts/fixtures/example-architecture/test/InventoryWorker.Tests/StandaloneTest.cs new file mode 100644 index 00000000..dca218dd --- /dev/null +++ b/skills/dotnet-docfx-digest/scripts/fixtures/example-architecture/test/InventoryWorker.Tests/StandaloneTest.cs @@ -0,0 +1,12 @@ +using Xunit; + +namespace InventoryWorker.Tests; + +public sealed class StandaloneTest +{ + [Fact] + public void MultipliesInventoryQuantity() + { + Assert.Equal(42, 6 * 7); + } +} From aab095249687b548cc889a1e8a76ebe2c4253859 Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Tue, 17 Nov 2026 02:22:41 +0100 Subject: [PATCH 22/95] =?UTF-8?q?=F0=9F=A6=BA=20validate=20bound=20samples?= =?UTF-8?q?=20against=20native=20build=20evidence?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bound sample context was validated from source paths alone, so unchanged pages could go unchecked when their bound source or project changed, deleted or moved, and a shared batch build failure could mark unrelated projects as failed. Validation now reads the disposable MSBuild binary log for actual Csc invocations and per-project outcomes, selects pages through their bindings, and rejects excerpts excluded by conditional compilation. --- skills/dotnet-docfx-digest/scripts/docfx.cs | 193 +++++++++++++++++++- 1 file changed, 185 insertions(+), 8 deletions(-) diff --git a/skills/dotnet-docfx-digest/scripts/docfx.cs b/skills/dotnet-docfx-digest/scripts/docfx.cs index 8225d19a..22fa8a87 100644 --- a/skills/dotnet-docfx-digest/scripts/docfx.cs +++ b/skills/dotnet-docfx-digest/scripts/docfx.cs @@ -1,3 +1,4 @@ +#:package MSBuild.StructuredLogger@2.3.269 #:property TargetFramework=net10.0 #:property Nullable=enable #:property LangVersion=latest @@ -18,6 +19,8 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.Build.Framework; +using BuildLog = Microsoft.Build.Logging.StructuredLogger; return DocfxValidator.Run(args); @@ -421,7 +424,7 @@ private static int Validate(Options options) // Explicit source bindings are checked without MSBuild on the fast path. They are not waivers. foreach (var md in workspace.MarkdownFiles) { - if (options.ChangedOnly && changedFiles is not null && !changedFiles.Contains(Path.GetFullPath(md))) { continue; } + if (options.ChangedOnly && changedFiles is not null && !ShouldValidateSamplePage(workspace, md, changedFiles)) { continue; } foreach (var sample in ExtractFences(md, workspace.ReadMarkdown(md))) { var error = ResolveSampleContext(sample, repoRoot, out _); @@ -4727,6 +4730,29 @@ private static bool ShouldValidateNamespacePage(string page, HashSet cha return changedFiles.Contains(Path.GetFullPath(page)) || changedFiles.Any(IsChangedDocfxConfig); } + private static bool ShouldValidateSamplePage(ValidationWorkspace ws, string page, HashSet changedFiles) + { + if (changedFiles.Contains(Path.GetFullPath(page)) || changedFiles.Any(IsChangedDocfxConfig)) { return true; } + // Read the binding before validating its files: deleted/moved sources and projects must + // still select their pages so ResolveSampleContext can report the stale documentation. + foreach (var fence in ExtractFences(page, ws.ReadMarkdown(page))) + { + foreach (var line in fence.Code.Replace("\r\n", "\n").Split('\n')) + { + var prefix = line.StartsWith("// docfx-context: ", StringComparison.Ordinal) ? "// docfx-context: " : + line.StartsWith("// docfx-source: ", StringComparison.Ordinal) ? "// docfx-source: " : null; + if (prefix is null) { continue; } + try + { + var path = Path.GetFullPath(Path.Combine(ws.RepoRoot, line[prefix.Length..].Trim())); + if (changedFiles.Contains(path)) { return true; } + } + catch (Exception ex) when (ex is ArgumentException or NotSupportedException or IOException) { } + } + } + return false; + } + private static bool ShouldValidateRequiredExampleTarget(ApiTargetInfo target, HashSet changedFiles) { foreach (var changedFile in changedFiles) @@ -5362,7 +5388,7 @@ private static void ValidateSamples(ValidationWorkspace ws, Options options, Has var samples = new List(); foreach (var md in ws.MarkdownFiles) { - if (options.ChangedOnly && changedFiles is not null && !changedFiles.Contains(Path.GetFullPath(md))) + if (options.ChangedOnly && changedFiles is not null && !ShouldValidateSamplePage(ws, md, changedFiles)) { continue; } @@ -5570,11 +5596,52 @@ private static void ValidateSamples(ValidationWorkspace ws, Options options, Has if (workers.Count == 0) { return; } var batchResult = CompileSampleBatch(tempRoot, workers, options.Configuration, parallelism, hasStrongNameKey, contexts.Count > 0 ? framework : null); + string? evidenceError = null; + var buildEvidence = contexts.Count > 0 ? ReadSampleBuildEvidence(Path.Combine(tempRoot, "samples.binlog"), out evidenceError) : null; foreach (var worker in workers) { + if (worker.ProjectContext) + { + var projectEvidence = buildEvidence!.Where(p => PathsEqual(p.Project, worker.ProjectPath)).ToList(); + var compilations = projectEvidence.Where(p => p.Succeeded == true && evidenceError is null && + string.Equals(p.Framework, framework, StringComparison.OrdinalIgnoreCase) && + string.Equals(p.Configuration, options.Configuration, StringComparison.OrdinalIgnoreCase)).SelectMany(p => p.Compilations) + .Where(c => c.SourceFiles.Any(f => PathsEqual(f.Path, worker.SourcePath))).ToList(); + if (compilations.Count > 0) + { + var inactive = ValidateActiveSampleRegion(samples[worker.OriginalIndex], worker.SourcePath, compilations); + if (inactive is not null) + { + report.Errors.Add(new Diagnostic("SAMPLE_CONTEXT_INVALID", Rel(repoRoot, samples[worker.OriginalIndex].File), null, + $"Fence #{samples[worker.OriginalIndex].FenceIndex}: {inactive}")); + continue; + } + results[worker.OriginalIndex] = new SampleCompileResult(true, "", 0); + } + else + { + // Native errors scoped to this project (including its dependency subtree) + // establish a failure. An unrelated batch error never supplies that evidence. + var errors = projectEvidence.SelectMany(p => p.Errors).Distinct(StringComparer.Ordinal).ToList(); + if (errors.Count == 0 && projectEvidence.Any(p => p.Succeeded == false)) + { + errors.Add($"Native MSBuild recorded a failed project invocation for '{Rel(contextRoot, worker.ProjectPath)}'. A referenced dependency or build target failed without a compiler diagnostic in this project."); + } + if (errors.Count > 0) + { + results[worker.OriginalIndex] = new SampleCompileResult(false, AddSampleCompileHints(string.Join(Environment.NewLine, errors)), batchResult.ExitCode); + } + else + { + report.Errors.Add(new Diagnostic("SAMPLE_CONTEXT_INVALID", Rel(repoRoot, samples[worker.OriginalIndex].File), null, + $"Fence #{samples[worker.OriginalIndex].FenceIndex}: No successful native C# compilation of '{Rel(contextRoot, worker.SourcePath)}' was recorded for '{Rel(contextRoot, worker.ProjectPath)}'. {evidenceError ?? "The shared build may have stopped before this project ran."} Resolve the reported build blocker and rerun; this sample is unverified, not a project-specific compilation failure.")); + } + } + continue; + } var outputAssembly = Path.Combine(worker.Directory, "bin", options.Configuration, framework, worker.AssemblyName + ".dll"); - var ok = batchResult.ExitCode == 0 || (!worker.ProjectContext && File.Exists(outputAssembly)); + var ok = batchResult.ExitCode == 0 || File.Exists(outputAssembly); var diagnostics = ok ? string.Empty : ExtractSampleDiagnostics(batchResult, worker); results[worker.OriginalIndex] = new SampleCompileResult(ok, diagnostics, batchResult.ExitCode); } @@ -5810,19 +5877,117 @@ private static ProcessResult CompileSampleBatch( // Context graphs live in a disposable copy. Persistent nodes can retain a different // DOTNET_CLI_HOME/package root (and loaded test-runner task DLLs) from another workspace. var contextIsolation = framework is null ? string.Empty : " --disable-build-servers"; + // Actual Csc arguments and native project terminal events establish context evidence. + // ProjectImports=None keeps source/import archives out of the disposable binary log. + var binaryLog = framework is null ? string.Empty : $" \"-bl:{Path.Combine(tempRoot, "samples.binlog")};ProjectImports=None\""; return RunProcess("dotnet", - $"build \"{solutionPath}\" -c {configuration} --nologo -m:{parallelism}{signingProperty}{frameworkProperty}{contextIsolation}", + $"build \"{solutionPath}\" -c {configuration} --nologo -m:{parallelism}{signingProperty}{frameworkProperty}{contextIsolation}{binaryLog}", tempRoot, permission: ProcessPermission.SampleCompile, progress: new ProcessProgress("sample compilation", $"{workers.Count} sample project(s), {parallelism} runner(s)")); } + private static List ReadSampleBuildEvidence(string path, out string? error) + { + error = null; + var projects = new Dictionary<(int, int), SampleProjectBuildEvidence>(); + var parents = new Dictionary<(int, int), (int, int)>(); + var invocations = new Dictionary<(int, int), BuildLog.CompilerInvocation>(); + var reader = new BuildLog.CompilerInvocationsReader(); + var finished = false; + try + { + foreach (var record in BuildLog.BinaryLog.ReadRecords(path)) + { + var ev = record.Args; + if (ev is BuildFinishedEventArgs) { finished = true; } + var context = ev?.BuildEventContext; + if (context is null) { continue; } + var key = (context.NodeId, context.ProjectContextId); + if (ev is ProjectStartedEventArgs start && !string.IsNullOrEmpty(start.ProjectFile)) + { + projects[key] = new SampleProjectBuildEvidence(Path.GetFullPath(start.ProjectFile), + start.GlobalProperties is { } globals && globals.TryGetValue("TargetFramework", out var tfm) ? tfm : "", + start.GlobalProperties is { } config && config.TryGetValue("Configuration", out var configuration) ? configuration : ""); + if (start.ParentProjectBuildEventContext is { } parent) + { + parents[key] = (parent.NodeId, parent.ProjectContextId); + } + } + if (ev is ProjectFinishedEventArgs end && projects.TryGetValue(key, out var project)) + { + project.Succeeded = end.Succeeded; + } + if (ev is BuildErrorEventArgs failure) + { + var diagnostic = $"{failure.File}({failure.LineNumber},{failure.ColumnNumber}): {failure.Code}: {failure.Message}"; + if (projects.TryGetValue(key, out project)) { project.Errors.Add(diagnostic); } + // Restore can report through the solution's task context while identifying + // the affected project explicitly. Do not assign that error to other roots. + if (!string.IsNullOrEmpty(failure.ProjectFile) || !string.IsNullOrEmpty(failure.File)) + { + foreach (var affected in projects.Values.Where(p => + (!string.IsNullOrEmpty(failure.ProjectFile) && PathsEqual(p.Project, failure.ProjectFile)) || + (!string.IsNullOrEmpty(failure.File) && PathsEqual(p.Project, failure.File)))) + { + affected.Errors.Add(diagnostic); + } + } + } + var invocation = reader.TryGetInvocationFromRecord(ev, invocations); + if (invocation?.Language == "C#" && projects.TryGetValue(key, out project)) + { + var arguments = CommandLineParser.SplitCommandLineIntoArguments(invocation.CommandLineArguments, removeHashComments: false); + project.Compilations.Add(CSharpCommandLineParser.Default.Parse(arguments, invocation.ProjectDirectory, sdkDirectory: null)); + } + } + if (!finished) { error = "The native build log was not finalized; incomplete evidence cannot validate a sample."; } + } + catch (Exception ex) when (ex is IOException or InvalidDataException or ArgumentException or InvalidOperationException or NotSupportedException) + { + error = $"Cannot read native build evidence: {ex.Message}"; + } + // Dependency errors belong to the requesting project's graph, including shared child + // projects that may have run on a different MSBuild node. Preserve deterministic ordering. + foreach (var (key, project) in projects.ToList()) + { + var ancestor = key; + var visited = new HashSet<(int, int)> { key }; + while (parents.TryGetValue(ancestor, out ancestor) && visited.Add(ancestor)) + { + if (projects.TryGetValue(ancestor, out var parent)) { parent.Errors.AddRange(project.Errors.ToArray()); } + } + } + return projects.Values.ToList(); + } + + private static string? ValidateActiveSampleRegion(SampleFence sample, string sourcePath, List compilations) + { + var source = File.ReadAllText(sourcePath).Replace("\r\n", "\n").Trim('\n'); + var excerpt = string.Join("\n", sample.Code.Replace("\r\n", "\n").Split('\n').Skip(2)).Trim('\n'); + var search = "\n" + source + "\n"; + var pattern = "\n" + excerpt + "\n"; + foreach (var compilation in compilations) + { + // Parse the containing file, so #if/#elif/#else, nested guards and local #define/#undef + // preceding the displayed region all use the actual Csc invocation's symbols. + var root = CSharpSyntaxTree.ParseText(source, compilation.ParseOptions).GetRoot(); + var inactive = root.DescendantTrivia(descendIntoTrivia: true) + .Where(t => t.IsKind(SyntaxKind.DisabledTextTrivia) && !string.IsNullOrWhiteSpace(t.ToFullString())).Select(t => t.FullSpan).ToList(); + var offset = 0; + while ((offset = search.IndexOf(pattern, offset, StringComparison.Ordinal)) >= 0) + { + var span = new Microsoft.CodeAnalysis.Text.TextSpan(offset, excerpt.Length); + if (!inactive.Any(s => s.OverlapsWith(span))) { return null; } + offset++; // An identical excerpt may also occur in an active branch. + } + } + return "The displayed source region contains code excluded by conditional compilation for the selected framework/configuration. Select an active excerpt or validate the matching framework/configuration; a successful containing-project build does not compile this region."; + } + private static string ExtractSampleDiagnostics(ProcessResult result, SampleWorker worker) { var output = result.StdOut + result.StdErr; - // A bound project can fail in a referenced application or shared restore. Its own path - // may occur only in a successful restore line, so retain graph diagnostics in this case. - if (worker.ProjectContext) { return AddSampleCompileHints(output); } var relevant = output .Replace("\r\n", "\n", StringComparison.Ordinal) .Replace('\r', '\n') @@ -6430,7 +6595,9 @@ private static string ReadRequiredJsonString(JsonElement element, string propert return null; } - var diff = RunProcess("git", "diff --name-only --diff-filter=ACMRTUXB HEAD", repoRoot, permission: ProcessPermission.Git); + // Bindings can still name deleted or renamed inputs. Keep both sides of a rename so + // unchanged pages pointing at the old path are selected for stale-context diagnostics. + var diff = RunProcess("git", "diff --name-only --no-renames --diff-filter=ACDMRTUXB HEAD", repoRoot, permission: ProcessPermission.Git); if (diff.ExitCode != 0) { return null; @@ -9365,6 +9532,16 @@ private sealed record SampleReferenceSet( List<(string Id, string Version)> PackageReferences); private sealed record SampleCompileResult(bool Ok, string Diagnostics, int ExitCode); + + private sealed class SampleProjectBuildEvidence(string project, string framework, string configuration) + { + public string Project { get; } = project; + public string Framework { get; } = framework; + public string Configuration { get; } = configuration; + public bool? Succeeded { get; set; } + public List Compilations { get; } = new(); + public List Errors { get; } = new(); + } } internal sealed class Diagnostic From 143bd6780a91c88a21cab982304561189581935f Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Tue, 17 Nov 2026 02:22:48 +0100 Subject: [PATCH 23/95] =?UTF-8?q?=E2=9C=85=20add=20bound-context=20regress?= =?UTF-8?q?ions=20for=20docfx=20samples?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The validator changes need regression coverage for changed-only selection of pages whose bound source or project changes, deleted or moved inputs, conditional compilation excluding displayed code, and per-project batch attribution. The new cases use small SDK projects so they run without network access or an external test runner. --- .../scripts/test-quality.ps1 | 127 ++++++++++++++++++ 1 file changed, 127 insertions(+) diff --git a/skills/dotnet-docfx-digest/scripts/test-quality.ps1 b/skills/dotnet-docfx-digest/scripts/test-quality.ps1 index 52909247..7eb0f731 100644 --- a/skills/dotnet-docfx-digest/scripts/test-quality.ps1 +++ b/skills/dotnet-docfx-digest/scripts/test-quality.ps1 @@ -2438,6 +2438,133 @@ Namespace overview. } } +# Bound-context review regressions use small SDK projects; no network or external test runner is +# needed to exercise compiler activity, changed-only selection and per-project batch attribution. +$contextReview = Join-Path ([IO.Path]::GetTempPath()) ('dotnet-docfx-context-review-' + [guid]::NewGuid().ToString('N')) +try { + Write-Utf8File (Join-Path $contextReview 'AGENTS.md') "`nManaged DocFX guidance.`n" + Write-Utf8File (Join-Path $contextReview 'src/Library/Library.csproj') $projectCsproj + Write-Utf8File (Join-Path $contextReview 'src/Library/Library.cs') 'namespace Acme.Context; public sealed class InventoryTotal { public int Quantity => 42; }' + Write-Utf8File (Join-Path $contextReview '.docfx/docfx.json') (New-DocfxJson @('src/Library/Library.csproj')) + $goodProject = Join-Path $contextReview 'samples/Good/Good.csproj' + $goodSource = Join-Path $contextReview 'samples/Good/Good.cs' + $contextPage = Join-Path $contextReview '.docfx/contexts.md' + $goodCode = 'namespace Samples; internal static class Inventory { public static int Total() => 42; }' + Write-Utf8File $goodProject $projectCsproj + Write-Utf8File $goodSource $goodCode + $fence = '```' + $bound = "${fence}csharp`n// docfx-context: samples/Good/Good.csproj`n// docfx-source: samples/Good/Good.cs`n$goodCode`n$fence`n" + Write-Utf8File $contextPage $bound + Initialize-GitRepo $contextReview + + # The Markdown remains byte-identical while its source changes, disappears or moves. + Write-Utf8File $goodSource ($goodCode.Replace('42', '99')) + Assert-Diagnostic (Invoke-Validator -Workspace $contextReview -ExtraArgs @('--changed-only')) 'SAMPLE_CONTEXT_INVALID' + Assert-Diagnostic (Invoke-Validator -Workspace $contextReview -ExtraArgs @('--changed-only', '--validate-samples')) 'SAMPLE_CONTEXT_INVALID' + Remove-Item -LiteralPath $goodSource + Assert-Diagnostic (Invoke-Validator -Workspace $contextReview -ExtraArgs @('--changed-only')) 'SAMPLE_CONTEXT_INVALID' + Write-Utf8File $goodSource $goodCode + # Project-only changes select the unchanged page for sample extraction as well as fast checks. + Write-Utf8File $goodProject ($projectCsproj.Replace('', '')) + Assert-Diagnostic (Invoke-Validator -Workspace $contextReview -ExtraArgs @('--changed-only', '--validate-samples')) 'SAMPLE_CONTEXT_INVALID' + Remove-Item -LiteralPath $goodProject + Assert-Diagnostic (Invoke-Validator -Workspace $contextReview -ExtraArgs @('--changed-only')) 'SAMPLE_CONTEXT_INVALID' + Write-Utf8File $goodProject $projectCsproj + Write-Host 'DocFX bound source/project changed-only regressions passed.' + + $conditionalSource = Join-Path $contextReview 'samples/Good/Conditional.cs' + $conditional = @' +namespace Samples; +internal static class ConditionalInventory +{ +#if DEBUG + public static int DebugQuantity() => UndefinedQuantity; +#endif +#if NET10_0 && !DEBUG + public static int ReleaseQuantity() => 42; +#endif +} +'@ + Write-Utf8File $conditionalSource $conditional + $conditionalBinding = "${fence}csharp`n// docfx-context: samples/Good/Good.csproj`n// docfx-source: samples/Good/Conditional.cs`n" + Write-Utf8File $contextPage ($conditionalBinding + ' public static int DebugQuantity() => UndefinedQuantity;' + "`n$fence") + $inactive = Invoke-Validator -Workspace $contextReview -ExtraArgs @('--validate-samples') + Assert-DiagnosticMessageContains $inactive 'SAMPLE_CONTEXT_INVALID' 'excluded by conditional compilation' + Assert-NoDiagnostic $inactive 'SAMPLE_COMPILE_FAILED' + if ($inactive.summary.samplesCompiled -ne 0) { throw 'Release counted an inactive broken DEBUG excerpt as compiled.' } + $debugBroken = Invoke-Validator -Workspace $contextReview -ExtraArgs @('--validate-samples', '--configuration', 'Debug') + Assert-DiagnosticMessageContains $debugBroken 'SAMPLE_COMPILE_FAILED' 'CS0103' + # The SDK-defined TFM symbol comes from the actual Csc command, not evaluation-only properties. + Write-Utf8File $contextPage ($conditionalBinding + ' public static int ReleaseQuantity() => 42;' + "`n$fence") + $active = Invoke-Validator -Workspace $contextReview -ExtraArgs @('--validate-samples') + Assert-NoDiagnostic $active 'SAMPLE_CONTEXT_INVALID' + Assert-NoDiagnostic $active 'SAMPLE_COMPILE_FAILED' + if ($active.summary.samplesCompiled -ne 1) { throw 'Active TFM/configuration excerpt was not compiled.' } + Write-Utf8File $conditionalSource ($conditional.Replace('UndefinedQuantity', '42')) + Write-Utf8File $contextPage ($conditionalBinding + ' public static int DebugQuantity() => 42;' + "`n$fence") + $debugActive = Invoke-Validator -Workspace $contextReview -ExtraArgs @('--validate-samples', '--configuration', 'Debug') + Assert-NoDiagnostic $debugActive 'SAMPLE_CONTEXT_INVALID' + Assert-NoDiagnostic $debugActive 'SAMPLE_COMPILE_FAILED' + if ($debugActive.summary.samplesCompiled -ne 1) { throw 'Active DEBUG excerpt was not compiled.' } + # Nested directives, local define/undef, repeated excerpts and symbols added by build targets. + $customCode = @' +#define LOCAL +#undef DISABLED +namespace Samples; +internal static class ConditionalInventory +{ +#if DEBUG + public static int Quantity() => 42; +#elif NET10_0 && REVIEW_SYMBOL +#if LOCAL && !DISABLED + public static int Quantity() => 42; +#endif +#endif +} +'@ + Write-Utf8File $conditionalSource $customCode + Write-Utf8File $goodProject ($projectCsproj.Replace('', '$(DefineConstants);REVIEW_SYMBOL')) + Write-Utf8File $contextPage ($conditionalBinding + ' public static int Quantity() => 42;' + "`n$fence") + $customActive = Invoke-Validator -Workspace $contextReview -ExtraArgs @('--validate-samples') + Assert-NoDiagnostic $customActive 'SAMPLE_CONTEXT_INVALID' + Assert-NoDiagnostic $customActive 'SAMPLE_COMPILE_FAILED' + if ($customActive.summary.samplesCompiled -ne 1) { throw 'Actual late compiler symbol or second active occurrence was missed.' } + Write-Utf8File $goodProject $projectCsproj + Remove-Item -LiteralPath $conditionalSource + Write-Host 'DocFX bound conditional region activity regressions passed.' + + # The unrelated broken console must not turn either copy of the good bound sample into a failure. + $brokenConsole = "${fence}csharp`n// Program.cs`nusing System;`nConsole.WriteLine(UnrelatedBrokenConsole);`n$fence`n" + Write-Utf8File $contextPage ($bound + "`n" + $bound + "`n" + $brokenConsole) + $mixed = Invoke-Validator -Workspace $contextReview -ExtraArgs @('--validate-samples') + Assert-NoDiagnostic $mixed 'SAMPLE_CONTEXT_INVALID' + $failures = @($mixed.errors | Where-Object code -eq 'SAMPLE_COMPILE_FAILED') + if ($mixed.summary.samplesCompiled -ne 2 -or $failures.Count -ne 1 -or $failures[0].message -notmatch 'fence #3') { + throw "Mixed batch misattributed a failure: $($mixed | ConvertTo-Json -Depth 8)" + } + # Two distinct bound failures retain their own diagnostics; the good root still passes. + $badFences = '' + foreach ($name in @('BadOne', 'BadTwo')) { + Write-Utf8File (Join-Path $contextReview "samples/$name/$name.csproj") $projectCsproj + $code = "namespace Samples; internal static class $name { public static int Total() => Missing$name; }" + Write-Utf8File (Join-Path $contextReview "samples/$name/$name.cs") $code + $badFences += "`n${fence}csharp`n// docfx-context: samples/$name/$name.csproj`n// docfx-source: samples/$name/$name.cs`n$code`n$fence`n" + } + Write-Utf8File $contextPage ($bound + $badFences) + $scopedFailures = Invoke-Validator -Workspace $contextReview -ExtraArgs @('--validate-samples') + Assert-NoDiagnostic $scopedFailures 'SAMPLE_CONTEXT_INVALID' + $failures = @($scopedFailures.errors | Where-Object code -eq 'SAMPLE_COMPILE_FAILED') + if ($scopedFailures.summary.samplesCompiled -ne 1 -or $failures.Count -ne 2) { throw 'Bound project results were not recorded individually.' } + foreach ($failure in $failures) { + if ($failure.message.Contains('MissingBadOne') -eq $failure.message.Contains('MissingBadTwo')) { + throw "Bound diagnostics contain an unrelated project's errors: $($failure.message)" + } + } + Write-Host 'DocFX mixed-batch per-project result and diagnostic regressions passed.' +} finally { + if (Test-Path $contextReview) { Remove-Item -LiteralPath $contextReview -Recurse -Force } +} + # Architecture fixtures use the real published fixture and xUnit runner, never a substitute host. # Build only the temp copy; the source fixture tree must remain free of bin/obj artifacts. $architecture = Join-Path ([System.IO.Path]::GetTempPath()) ('dotnet-docfx-architecture-' + [guid]::NewGuid().ToString('N')) From d3aaacf896b4744f3f99f829aee2f6d7a15d748b Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Tue, 17 Nov 2026 02:22:49 +0100 Subject: [PATCH 24/95] =?UTF-8?q?=F0=9F=93=9D=20document=20native=20sample?= =?UTF-8?q?=20evidence=20in=20docfx=20references?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The sample context rules changed: bound pages are selected by their source and project inputs, compiler evidence comes from the native build log, and conditionally excluded excerpts are rejected. The architecture and diagnostics references need to describe what validation now proves and what it does not. --- .../references/example-architecture.md | 8 ++++++-- skills/dotnet-docfx-digest/references/scripts.md | 2 +- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/skills/dotnet-docfx-digest/references/example-architecture.md b/skills/dotnet-docfx-digest/references/example-architecture.md index ce12f848..b7828a6b 100644 --- a/skills/dotnet-docfx-digest/references/example-architecture.md +++ b/skills/dotnet-docfx-digest/references/example-architecture.md @@ -47,11 +47,15 @@ Unbound C# fences keep their existing structure and isolated compilation rules. The angle-bracket line above describes the binding syntax; it is not publishable C#. Use the same two comments on the test fence, pointing to the actual test project and source file. Name the application `ProjectReference`, package dependencies, runner and command in prose or link to their maintained project definitions. These comments identify compilation context; they do not replace readable project/file labels or prerequisites. -The fast path verifies both files exist inside the repository and the displayed source matches a complete maintained file or a nonempty contiguous whole-line excerpt. Only line-ending differences and outer blank lines are ignored. Missing paths, source drift and unsupported linked paths produce `SAMPLE_CONTEXT_INVALID` with repair guidance. No network, compilation or MSBuild evaluation occurs on the fast path. +The fast path verifies both files exist inside the repository and the displayed source matches a complete maintained file or a nonempty contiguous whole-line excerpt. Only line-ending differences and outer blank lines are ignored. Missing paths, source drift and unsupported linked paths produce `SAMPLE_CONTEXT_INVALID` with repair guidance. With `--changed-only`, a page is selected when its Markdown, bound source, or bound project changes, including removed/moved binding inputs. No network, compilation or MSBuild evaluation occurs on the fast path. With `--validate-samples`, the validator copies the repository to temp (excluding generated directories and `.bot`), checks the selected framework is declared by each bound project, evaluates `Compile` membership for that framework/configuration, and builds the declared projects together through the existing bounded sample graph build. Dependencies and separate assembly identities come from those projects, not concatenated fences. An excluded source file, unavailable dependency, invalid project graph, or failed build remains a failure. Use `--framework` for the actual runnable asset; do not silently retarget a maintained project. `--sample-reference-mode package` does not rewrite an explicitly bound project graph. Unsupported generated Compile items or external project dependencies require a supported maintained context; they are not accepted as success. Disposable context builds ignore persistent build servers so a node cannot supply another workspace's package-root environment or retain its test-runner task assemblies. -This is **compilation evidence for the containing source/project**, not proof that an excerpt executed, its omitted initialization was invoked, or its assertion establishes the prose's claim. Run the real test/application separately and record command, framework/dependencies, observations and source identity before claiming execution. Do not use the context comments as a substitute for strict skip approvals, and never use an unrelated compiling project to validate a fence. +The context build writes a disposable native MSBuild binary log, read through `MSBuild.StructuredLogger`; it adds no separate compiler or public manifest. The validator uses actual Csc command lines and native project terminal results, preserving project-scoped errors when another sample fails the batch. A project not reached by the build remains unverified rather than inheriting an unrelated compilation failure. Missing, incomplete or unusable compiler evidence cannot count as success. + +A bound excerpt must occur in an active region under that compiler invocation's framework/configuration symbols, including SDK-generated symbols, target-added constants, nested guards, and preceding file-local `#define`/`#undef`. Excluded displayed code produces `SAMPLE_CONTEXT_INVALID` and is not counted in `samplesCompiled`. Choose an active excerpt or validate the configuration/framework containing the intended code. If a displayed file includes several conditional branches, scope it to the intended active region; compiling one branch does not validate the others. + +This is **compilation evidence for the displayed active region in its containing source/project**, not proof that an excerpt executed, its omitted initialization was invoked, or its assertion establishes the prose's claim. Run the real test/application separately and record command, framework/dependencies, observations and source identity before claiming execution. Do not use the context comments as a substitute for strict skip approvals, and never use an unrelated compiling project to validate a fence. ## Principal regression: ManagedApplicationFixture diff --git a/skills/dotnet-docfx-digest/references/scripts.md b/skills/dotnet-docfx-digest/references/scripts.md index c9f67665..8a1c6baa 100644 --- a/skills/dotnet-docfx-digest/references/scripts.md +++ b/skills/dotnet-docfx-digest/references/scripts.md @@ -143,7 +143,7 @@ UTF-8 BOM presence is not validated. `ENCODING_BOM_MISSING` is intentionally not ### Architectural context diagnostics -`SAMPLE_CONTEXT_INVALID` rejects invalid explicit project/source bindings: missing or external paths, drift from maintained source, or (with `--validate-samples`) missing evaluated Compile membership or unevaluable context. Repair the declared context or source; this diagnostic is not a waiver. `EXAMPLE_APPLICATION_ASSEMBLY_COLLAPSED` applies narrowly to the exact Codebelt entrypoint-owned fixture/test contract when a test base uses a locally declared application marker in the same fence. Preserve Main and separate application/test assemblies. See [example architecture](example-architecture.md) for evidence, syntax, and limits. Registration ownership, lifecycle equivalence, pipeline semantics, prose/assertion agreement and runtime claims still require evidence-backed review; these diagnostics do not certify them. +`SAMPLE_CONTEXT_INVALID` rejects invalid explicit project/source bindings: missing or external paths, source drift, or (with `--validate-samples`) missing Compile membership, conditionally excluded displayed code, or unavailable native compiler evidence. Both fast binding checks and sample extraction select unchanged pages when a bound source/project changes, including deletion/rename. Build-backed context validation reads actual Csc symbols and per-project outcomes from a disposable MSBuild binary log; successful bound projects retain their results when an unrelated sample fails, and compilation diagnostics contain their own project/dependency errors. Repair the declared context or source; this diagnostic is not a waiver. `EXAMPLE_APPLICATION_ASSEMBLY_COLLAPSED` applies narrowly to the exact Codebelt entrypoint-owned fixture/test contract when a test base uses a locally declared application marker in the same fence. Preserve Main and separate application/test assemblies. See [example architecture](example-architecture.md) for evidence, syntax, and limits. Registration ownership, lifecycle equivalence, pipeline semantics, prose/assertion agreement and runtime claims still require evidence-backed review; these diagnostics do not certify them. ### Sample opt-out From 6a9a7a9be73f1477699005b4580ea201b7d502e3 Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Tue, 17 Nov 2026 02:22:50 +0100 Subject: [PATCH 25/95] =?UTF-8?q?=F0=9F=93=9D=20describe=20bound=20sample?= =?UTF-8?q?=20context=20validation=20in=20readme?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The README feature list still described the earlier sample context behavior. It now reflects that bound pages are revalidated when their source or project changes and that compiler evidence comes from the native build. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0bf3e3be..374ae397 100644 --- a/README.md +++ b/README.md @@ -712,7 +712,7 @@ API documentation rots the moment code changes. A new public type ships without - **Managed-reference-safe overwrite layout** — public non-abstraction types and public extension methods must have examples in DocFX overwrite content included by `build.overwrite`; the validator discovers Markdown from configured DocFX inputs instead of scanning the whole repository when `docfx.json` is at the root, concrete-type examples are tracked through an explicit inventory and created in readable authored files under `.docfx/api/types/`, legacy authored `.docfx/api/*.md` overwrite files move into `api/namespaces/` or `api/types/` instead of widening the glob to `api/**/*.md`, both overwrite trees stay excluded from `build.content`, C# extension-block compiler containers such as `$...` are collapsed back to the authored outer static class, extension-method examples default to readable declaring-class type pages under `.docfx/api/types/` instead of URL-encoded method-UID filenames or namespace pages that mix overview and member UIDs, namespace pages fail validation when they embed secondary `uid:` / `example:` sections, and agents must rerun the completion repair loop until diagnostics and overwrite-layout failures are fixed or exact blockers are reported, - **Concept-led namespace quality** — moving concrete examples to type pages must not hollow out namespace pages; namespace pages still need newcomer-oriented fly-ins that explain the problem solved, when to use the namespace, where to start, type-family context, extension-method group explanations, availability, and pointers to representative type pages, and nearby type/member summaries should stay purpose-first too, - **Examples that teach a real workflow** — examples start from package IDs and package-level evidence before falling back to type/member-only searches, prefer README, package docs, tooling, tuning, functional-test, and external GitHub usage when available, may include multiple related public types when that is what makes the consumer scenario understandable, keep extension-container prose focused on what callers can do with the receiver instead of on declaration syntax, discover public acquisition paths from signatures, docs, tests, and other evidence instead of assuming direct construction from implementation details, and rewrite copied test evidence into lean consumer-facing code rather than dragging obvious framework FQNs into the sample body, -- **Examples arrive with context** — design starts with the developer task, prerequisites, execution topology and observable result. Library snippets stay concise; standalone programs, genuine framework tests, multi-project integrations and partial excerpts use their actual execution context. Project-bound fences match maintained source and compile in the real project graph, preserving application entry points and test assembly boundaries. Human fly-ins explain setup and outcome, and compilation, runtime evidence and architectural review remain distinct, +- **Examples arrive with context** — design starts with the developer task, prerequisites, execution topology and observable result. Library snippets stay concise; standalone programs, genuine framework tests, multi-project integrations and partial excerpts use their actual execution context. Project-bound fences match maintained source, revalidate when their source/project changes, and require an active region under actual compiler symbols. Native per-project build evidence preserves successful samples when an unrelated sample fails. Human fly-ins explain setup and outcome, and compilation, runtime evidence and architectural review remain distinct, - **Semantic example quality gates** — compilation-valid filler no longer passes: the validator rejects duplicate UID mappings, `Type.GetType`/assembly metadata scaffolds, runtime implementation names presented as outcomes (`EXAMPLE_RUNTIME_TYPE_NAME_OUTCOME`), empty local `Program` stubs in conventionally named application-entry-point samples such as `AppFactory`, `WebTestFactory`, or `HostFixture` (`EXAMPLE_EMPTY_ENTRY_POINT_STUB`) while excluding unrelated names such as `ApplicationRepositoryFactory`, generic `DocumentedTypeExample`/`Describe()` templates, type examples that never use the target in code, extension examples that mention a method only in prose instead of invoking it, examples without a human fly-in (`EXAMPLE_LEAD_MISSING`), advanced examples with shallow setup context (`EXAMPLE_ADVANCED_LEAD_MISSING`), `default!`/`null!` holder properties (`EXAMPLE_DEFAULT_PLACEHOLDER`), classes that only construct or return the target with no observable result (`EXAMPLE_NO_OBSERVABLE_OUTCOME`), mass-forwarding shells of one-line pass-throughs (`EXAMPLE_FORWARDING_SCAFFOLD`), one normalized code skeleton reused across three or more unrelated targets (`EXAMPLE_TEMPLATE_REPETITION`), and avoidable `System.*` / `Microsoft.*` fully qualified framework references in executable sample code (`EXAMPLE_FULLY_QUALIFIED_FRAMEWORK_TYPE`), - **Key-entry-point storytelling** — namespace guidance starts from release notes, package documentation, public factories/builders, and strong functional tests so new product-defining APIs are not buried beneath naming conventions. When a package complements an upstream framework type, the skill compares acquisition, customization, lifecycle, sharing, and observable outcomes from current official guidance instead of making unsupported replacement claims, - **Correct source discovery** — the no-build source scanner correctly handles block namespaces whose opening brace is on the next line, so public types are no longer silently under-reported; when a declaration cannot be paired with its brace it warns (`API_MODEL_SOURCE_SCANNER_INCOMPLETE`) and points to a build-backed audit, From beed471ae7b1768dc00a7c030b8c3972189daafa Mon Sep 17 00:00:00 2001 From: gimlichael Date: Tue, 17 Nov 2026 02:25:48 +0100 Subject: [PATCH 26/95] =?UTF-8?q?=F0=9F=93=9D=20update=20changelog=20for?= =?UTF-8?q?=20dotnet-csrun=20and=20docfx=20enhancements?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cba3224c..c506d5df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,17 +6,23 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), ## [0.13.0] - 2026-11-17 -This is a minor release that adds the `dotnet-csrun` skill for executable C# evidence and connects `dotnet-docfx-digest` to it for standalone runtime examples. +This is a minor release that adds the `dotnet-csrun` skill for executable C# evidence, binds `dotnet-docfx-digest` samples to maintained project and source context, and connects standalone runtime examples to `dotnet-csrun`. ### Added -- `dotnet-csrun` skill for creating small complete C# examples, verifying and repairing existing standalone source, and auditing examples, with paired native and Docker commands and honest verified, compiled-only, or unverified statuses, -- `dotnet-csrun` assesses standalone feasibility before choosing a manifest and classifies failures before any repair, and runs isolated xUnit v3 tests through `csrun`, -- `dotnet-csrun` deterministic validators and eval fixtures covering its lifecycle and feasibility contracts, plus a README entry and install example. +- `dotnet-csrun` skill for creating small complete C# console examples and genuine xUnit v3 tests, running them through `csrun` with exact package pins, and reporting independent native and Docker statuses of verified, compiled only, or unverified, +- `dotnet-csrun` verify, repair, and scoped audit lifecycle for existing standalone source, with feasibility assessed before manifest construction and failures classified before any repair, +- `dotnet-docfx-digest` source-bound sample contexts that bind fences to a maintained project and source file, reject unresolvable bindings, revalidate pages whose bound source or project changes, including deleted or moved inputs, and skip `.bot` directories during source discovery, +- `dotnet-docfx-digest` rejection of a `ManagedApplicationFixture` entry point collapsed into a test-owned source unit, and of displayed excerpts excluded by conditional compilation for the selected framework and configuration, +- `dotnet-csrun` README entry, install example, deterministic validators, and eval fixtures, plus `dotnet-docfx-digest` regression coverage for source-bound samples. ### Changed -- `dotnet-docfx-digest` example verification composes with `dotnet-csrun` for compatible standalone runtime examples, keeping its source discovery, placement, project-aware compilation, and DocFX build gates authoritative and leaving project-dependent examples in the existing workflow. +- `dotnet-docfx-digest` composes with `dotnet-csrun` for compatible standalone runtime examples, keeping its source discovery, placement, project-aware compilation, and DocFX build gates authoritative and leaving project-dependent examples in the existing workflow. + +### Fixed + +- `dotnet-docfx-digest` attributes sample compile failures to each project from the native MSBuild binary log instead of the shared batch exit code, so a shared batch failure no longer marks unrelated projects as failed. ## [0.12.1] - 2026-11-15 From c9fef7e9ca3c686e53024d6c661a375303761536 Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Tue, 17 Nov 2026 16:34:52 +0100 Subject: [PATCH 27/95] =?UTF-8?q?=F0=9F=93=9D=20add=20verified=20standalon?= =?UTF-8?q?e=20host=20example?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit csrun needs a complete, genuine xUnit v3 example for host registration and resolution that users can run as native or Docker blocks. The example embeds the canonical standalone source and dependency pins, and the sample tests now verify that both published blocks and the displayed C# match the executed manifest. --- .../references/standalone-example.md | 84 +++++++++++++++++++ .../scripts/test-sample-tools.ps1 | 15 ++++ 2 files changed, 99 insertions(+) create mode 100644 skills/dotnet-csrun/references/standalone-example.md diff --git a/skills/dotnet-csrun/references/standalone-example.md b/skills/dotnet-csrun/references/standalone-example.md new file mode 100644 index 00000000..171d7dff --- /dev/null +++ b/skills/dotnet-csrun/references/standalone-example.md @@ -0,0 +1,84 @@ +# Standalone host service resolution + +This xUnit v3 test demonstrates registration and resolution in a host constructed by the test. It asserts the resolved identity value. It does not exercise a separate application's entry point; for that behavior use DocFX's repository-backed integration example instead. + +The complete source is below. Both independent PowerShell blocks embed exactly this source and the same dependency pins; neither needs source files, scaffolding, a checkout, or the other block. Expected: 1 executed, 1 passed, 0 failed and 0 skipped. Source and canonical manifest are maintained in [standalone-host.json](../evals/files/standalone-host.json). + +```csharp +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Xunit; + +public sealed class HostTests +{ + [Fact] + public void StandaloneHostResolvesRegisteredIdentity() + { + var builder = Host.CreateApplicationBuilder(); + builder.Services.AddSingleton(new WorkerIdentity("Inventory worker")); + using var host = builder.Build(); + Assert.Equal("Inventory worker", host.Services.GetRequiredService().Name); + } +} + +public sealed record WorkerIdentity(string Name); +``` + +## Native: PowerShell 7 and a .NET 10-compatible SDK/runtime + +Network access to GitHub and NuGet is required. The block downloads and executes the publisher's engine with your permissions; review it before running. No Docker is needed. + +```powershell +#requires -Version 7.0 +$ErrorActionPreference = 'Stop' +$PSNativeCommandUseErrorActionPreference = $false +$manifest = @' +{ + "dependsOn": [ + "Codebelt.Extensions.Xunit.App@13.0.0", + "xunit.v3@4.0.3" + ], + "framework": "net10.0", + "mode": "test", + "schemaVersion": 1, + "source": "using Microsoft.Extensions.DependencyInjection;\nusing Microsoft.Extensions.Hosting;\nusing Xunit;\n\npublic sealed class HostTests\n{\n [Fact]\n public void StandaloneHostResolvesRegisteredIdentity()\n {\n var builder = Host.CreateApplicationBuilder();\n builder.Services.AddSingleton(new WorkerIdentity(\"Inventory worker\"));\n using var host = builder.Build();\n Assert.Equal(\"Inventory worker\", host.Services.GetRequiredService().Name);\n }\n}\n\npublic sealed record WorkerIdentity(string Name);" +} +'@ +$OutputEncoding = [Text.UTF8Encoding]::new($false) +[Console]::OutputEncoding = $OutputEncoding +# Trust warning: downloads and executes publisher code with your permissions. Review before running. +# releases/latest is mutable; retain a reviewed release asset/hash for reproducibility. +$engine = Invoke-RestMethod 'https://github.com/codebeltnet/csrun/releases/latest/download/csrun.ps1' +& ([scriptblock]::Create($engine)) -ManifestJson $manifest +$code = $LASTEXITCODE +if ($code -ne 0) { throw "csrun execution failed with exit code $code." } +``` + +## Disposable Docker: PowerShell 7 and Docker with Linux containers + +No host .NET SDK is needed. Network access is needed for the image and dependencies. Docker is not a security sandbox for untrusted code. + +```powershell +#requires -Version 7.0 +$ErrorActionPreference = 'Stop' +$PSNativeCommandUseErrorActionPreference = $false +$manifest = @' +{ + "dependsOn": [ + "Codebelt.Extensions.Xunit.App@13.0.0", + "xunit.v3@4.0.3" + ], + "framework": "net10.0", + "mode": "test", + "schemaVersion": 1, + "source": "using Microsoft.Extensions.DependencyInjection;\nusing Microsoft.Extensions.Hosting;\nusing Xunit;\n\npublic sealed class HostTests\n{\n [Fact]\n public void StandaloneHostResolvesRegisteredIdentity()\n {\n var builder = Host.CreateApplicationBuilder();\n builder.Services.AddSingleton(new WorkerIdentity(\"Inventory worker\"));\n using var host = builder.Build();\n Assert.Equal(\"Inventory worker\", host.Services.GetRequiredService().Name);\n }\n}\n\npublic sealed record WorkerIdentity(string Name);" +} +'@ +$OutputEncoding = [Text.UTF8Encoding]::new($false) +[Console]::OutputEncoding = $OutputEncoding +$manifest | docker run --rm -i 'codebeltnet/csrun:10' +$code = $LASTEXITCODE +if ($code -ne 0) { throw "csrun execution failed with exit code $code." } +``` + +The native latest-release URL and Docker SDK tag are mutable. Record the actual engine hash/image digest and environment when claiming verification; see [presentation](presentation.md). The sample helper generates these blocks and the focused helper tests enforce parity with the maintained manifest. diff --git a/skills/dotnet-csrun/scripts/test-sample-tools.ps1 b/skills/dotnet-csrun/scripts/test-sample-tools.ps1 index 95f04403..1f4f108f 100644 --- a/skills/dotnet-csrun/scripts/test-sample-tools.ps1 +++ b/skills/dotnet-csrun/scripts/test-sample-tools.ps1 @@ -13,6 +13,21 @@ function Assert-Throws([scriptblock] $Action, [string] $Message) { Assert-True $threw $Message } +$published = Get-Content (Join-Path $root 'references/standalone-example.md') -Raw +$publishedBlocks = [regex]::Matches($published, '(?s)```powershell\r?\n(.*?)\r?\n```') +$hostJson = Get-Content (Join-Path $root 'evals/files/standalone-host.json') -Raw +$hostIdentity = Get-CsrunSampleIdentity $hostJson +$hostPair = New-CsrunExecutionPair $hostJson -Image 'codebeltnet/csrun:10' +Assert-True ($publishedBlocks.Count -eq 2) 'Standalone example must offer two independent blocks.' +for ($index = 0; $index -lt 2; $index++) { + $block = $publishedBlocks[$index].Groups[1].Value + $expected = @($hostPair.Native, $hostPair.Docker)[$index] + Assert-True ($block.Replace("`r`n", "`n") -ceq $expected.Replace("`r`n", "`n")) 'Published standalone block drifted.' + Assert-True ((Get-CsrunSampleIdentity (Get-CsrunWrapperManifest $block)).ManifestSha256 -ceq $hostIdentity.ManifestSha256) 'Published standalone dependency/source parity failed.' +} +$publishedSource = [regex]::Match($published, '(?s)```csharp\r?\n(.*?)\r?\n```').Groups[1].Value +Assert-True ($publishedSource.Replace("`r`n", "`n") -ceq $hostIdentity.Source.Replace("`r`n", "`n")) 'Displayed C# differs from executed standalone source.' + foreach ($file in Get-ChildItem (Join-Path $root 'evals/files') -Filter '*.json') { $json = [IO.File]::ReadAllText($file.FullName) $item = ConvertFrom-Json $json -AsHashtable From da8e67aa49b2e5d6e959e133479ea659e5bae917 Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Tue, 17 Nov 2026 16:34:59 +0100 Subject: [PATCH 28/95] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20defer=20repository-b?= =?UTF-8?q?acked=20examples=20to=20docfx?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Repository-backed integration examples need a pinned application and test graph that csrun manifest v1 cannot represent. Route those cases to the DocFX one-shot guidance and keep csrun limited to standalone execution, so no multi-project fields or substitute hosts are introduced. --- skills/dotnet-csrun/SKILL.md | 4 ++++ skills/dotnet-csrun/evals/evals.json | 11 +++++++++++ skills/dotnet-csrun/references/docfx.md | 2 ++ skills/dotnet-csrun/references/feasibility.md | 2 +- skills/dotnet-csrun/references/verification.md | 8 +++++++- 5 files changed, 25 insertions(+), 2 deletions(-) diff --git a/skills/dotnet-csrun/SKILL.md b/skills/dotnet-csrun/SKILL.md index ca48ad5e..b70ba9db 100644 --- a/skills/dotnet-csrun/SKILL.md +++ b/skills/dotnet-csrun/SKILL.md @@ -8,6 +8,8 @@ description: > Make the smallest complete example, execute it through `csrun`, and share the exact program that ran. Use .NET/C# for substantive supporting logic and PowerShell 7 for orchestration. Never substitute another execution engine or create a competing manifest format. +Assess standalone suitability first. Repository-backed integration examples are a separate execution strategy, outside csrun manifest v1: preserve the original application/test graph and direct documentation work to `dotnet-docfx-digest`'s one-shot repository guidance. Do not stop at source links when a maintained targeted test can be executed in one pinned-snapshot block. Do not manufacture a csrun-compatible approximation, add multi-project fields, or claim repository execution is isolated csrun execution. Standalone native and Docker blocks remain independent and use identical source/dependencies. + ## Choose the intention | Logical command | Authorized behavior | @@ -60,3 +62,5 @@ Console.WriteLine(42); ``` For tests, use the [passing fixture](evals/files/passing.json) as a small source reference, not a replacement test engine. The fixtures also cover deliberate failures, no discovered tests, invalid source, exact packages, and Unicode/raw strings. Repository maintainers can run `scripts/validate-dotnet-csrun.ps1` for deterministic artifact checks; optional engine execution is documented in [verification](references/verification.md). + +See the [standalone host example](references/standalone-example.md) for a complete genuine xUnit test and both ready-to-paste execution blocks. It tests its own host's registration/resolution, not application-entrypoint integration. diff --git a/skills/dotnet-csrun/evals/evals.json b/skills/dotnet-csrun/evals/evals.json index 95e26bac..6f524806 100644 --- a/skills/dotnet-csrun/evals/evals.json +++ b/skills/dotnet-csrun/evals/evals.json @@ -361,6 +361,17 @@ "Executes original standalone xUnit source unchanged with exact pins and meaningful original assertion; requires positive discovery and counts before Verified.", "Both full wrappers decode to the original canonical manifest and evidence names the transport actually executed; no fabricated success for the other transport." ] + }, + { + "id": 30, + "prompt": "Make this documentation example one-shot: ManagedApplicationFixture needs a distinct real application assembly. The maintained Codebelt xunit BootstrapperMinimalWorkerApplicationTestTest references its actual worker project. Also provide an ordinary standalone Fact via native and Docker. Keep csrun schema v1 unchanged.", + "expected_output": "Uses existing csrun native/Docker wrappers with identical canonical standalone source and dependencies. Recognizes the worker test as a separate repository-backed integration strategy owned by DocFX, follows its pinned-snapshot one-shot guidance, verifies the actual targeted test, and never collapses assembly identity or substitutes a host.", + "expectations": [ + "Preserves the original application implementation, project references, fixture lifecycle and assertions; no multi-project csrun schema or engine changes.", + "Requires exact intended test identity, positive execution and pass counts plus process status; rejects wrong filters, zero tests and skipped tests.", + "Both commands include all setup and cleanup and state prerequisites; unavailable environments or dependencies are explicitly unverified with diagnostics.", + "Fallback source links are used only when faithful execution is unavailable, without a verified runnable label." + ] } ] } diff --git a/skills/dotnet-csrun/references/docfx.md b/skills/dotnet-csrun/references/docfx.md index 99bd09f4..03fb37df 100644 --- a/skills/dotnet-csrun/references/docfx.md +++ b/skills/dotnet-csrun/references/docfx.md @@ -2,6 +2,8 @@ `dotnet-docfx-digest` owns public API discovery, documentation structure, namespaces/types/UIDs, example placement, source-backed explanation, repository-aware compilation, DocFX builds, and documentation completion. `dotnet-csrun` owns standalone construction, genuine xUnit v3 execution, portable native/Docker blocks, runtime observations, localized authorized corrections, and reproducible evidence. +DocFX also chooses and presents repository-backed one-shot integration examples when a maintained application/test graph is essential. Use its `references/one-shot-examples.md`; this is separate from csrun and must execute the original application/test without substitute hosts. Prefer short meaningful C# plus a direct maintained link and complete execution blocks, with expected outcome and prerequisites. If neither strategy is reliable, explain the limitation and link the maintained implementation/example/test/project without a verified-runnable label. + Within an authorized documentation task, the parent agent may apply `create` for a compatible self-contained example, `verify` for unchanged existing source, or `repair` for an authorized correction. During a scoped audit, contribute standalone classifications and runtime evidence to the existing DocFX inventory. No deterministic validator launches an agent, model, or another skill. Both skills' tools remain independently usable. Preserve `docfx.cs --build-api-model --validate-samples --verify-docfx-build`. Its reference-aware compilation remains authoritative for local unpublished APIs, project references, multiple assemblies, application entry points, full hosts/HTTP pipelines, and other unsupported standalone prerequisites. Do not replace those with published packages and claim the checkout was verified. A passing published-package csrun example proves that package version; a compiling project-backed DocFX sample may still be non-runnable standalone. diff --git a/skills/dotnet-csrun/references/feasibility.md b/skills/dotnet-csrun/references/feasibility.md index 2fa2a632..1d523742 100644 --- a/skills/dotnet-csrun/references/feasibility.md +++ b/skills/dotnet-csrun/references/feasibility.md @@ -29,4 +29,4 @@ For the InventoryWorker preflight report: **Feasibility: Unsupported by current Recommend `dotnet-test` for establishing/preserving entrypoint-owned repository testing infrastructure, or `dotnet-remote-testing` for executing an existing repository test workload in a container. Describe these as separate workflows; never silently switch engines or claim csrun executed the original test. A standalone host/DI fact can be offered as a **reduced demonstration** of registration/resolution only; it does not verify WorkerProgram startup. Prefer a concise diagnosis and recovery path over a known-failing Copy & Run block. -A potential upstream enhancement would need independently compiled application output plus a reference from the executable test project, preserving separate assembly entry points, dependencies, lifecycle and cleanup. This expands manifest validation, isolation and compatibility responsibilities beyond v1. It requires upstream design/versioning; do not invent fields, implement a project orchestrator here or change csrun/xunit as a workaround. +For documentation, use `dotnet-docfx-digest`'s `references/one-shot-examples.md`: a pinned snapshot of the maintained repository can execute the original targeted test with its original project graph in one copy/paste block. Verify the precise test identity and positive executed/passed counts with the actual MTP/xUnit v3 conventions. Report native and Docker evidence independently. This separate repository-backed strategy does not expand csrun or make the source manifest-compatible. If unavailable, preserve the concise illustration, explain prerequisites and the standalone limitation, link implementation/example/test/project, and label execution unverified. Source links are a fallback, not a replacement for an available working command. diff --git a/skills/dotnet-csrun/references/verification.md b/skills/dotnet-csrun/references/verification.md index 6d702e54..2357a712 100644 --- a/skills/dotnet-csrun/references/verification.md +++ b/skills/dotnet-csrun/references/verification.md @@ -4,7 +4,7 @@ From the agentic repository root, `pwsh -NoProfile -File scripts/validate-dotnet Optional focused integration: `pwsh -NoProfile -File scripts/validate-dotnet-csrun.ps1 -EnginePath ` or `-Docker`. These execute fifteen cases through the actual engine, preserve separate stdout/stderr, canonical manifests, both generated blocks, source/manifest hashes, engine and SDK/runtime identity, expected observations and exit status under a unique OS temporary directory. Positive cases execute the generated copy/paste block in a fresh PowerShell process; negative cases call the engine directly to retain the original compiler/MTP status. No engine download is automated. Docker uses :10 for .NET 10 and :11 for .NET 11. Expected failures are engine observations, not passing tests. This maintainer validator needs an SDK for its C# artifact checks; developer-facing Docker blocks and the offline PowerShell helper tests do not need a host SDK. Network access and genuine selected-transport prerequisites remain necessary for integration. -The eval specification includes twenty-nine representative user tasks, including native-only, Docker-only, both/neither available, repair, partial excerpts, semantic rejection, wrapper divergence, scoped audit and unpublished-project composition. Inspect these deterministically; model-backed execution is not a validator or completion gate. Follow portable handoff rules only when explicitly asked for an evaluation. Full repository validation requires separate approval; focused checks suffice here. +The eval specification includes representative user tasks covering native-only, Docker-only, both/neither available, repair, partial excerpts, semantic rejection, wrapper divergence, scoped audit, unpublished-project composition and repository-backed handoff. Inspect these deterministically; model-backed execution is not a validator or completion gate. Follow portable handoff rules only when explicitly asked for an evaluation. Full repository validation requires separate approval; focused checks suffice here. The transport-double tests execute generated blocks in independent scopes with the opposite transport made unavailable; these prove invocation/manifest independence, not C# behavior. Actual engine runs prove observed behavior. Template generation with neither environment does not invent a successful status. Editing tests compare entire resulting byte arrays for UTF-8 with/without BOM and UTF-16 little/big endian with BOM and CRLF, preserving unrelated Markdown, frontmatter, links, directives and partial fences; stale edits fail without changing bytes. The original InventoryWorker hash and repair-pair source comparisons prevent manufactured semantic success. Instruction/activation/effectiveness claims remain unmeasured without separately authorized behavioral evaluation. @@ -39,3 +39,9 @@ All fifteen focused cases matched their expected observations independently on n | Complete Markdown sample missing semicolon | CS1002, exit 1 | Localized semicolon; prints 1970, exit 0; partial fence retained | The original InventoryWorker still produces CS0017 before discovery; application startup remains unverified. Eighty-four offline artifact/helper assertions and all forty-two Templates checks passed. No full repository matrix, model-backed behavioral evaluation, activation measurement, or skill-effectiveness comparison was run. The independent transport runs used bounded concurrency of two; source mutations and final installation synchronization stayed sequential. + +## One-shot refinement verification, 2026-11-17 + +The [published standalone host example](standalone-example.md) ran as complete independent native and Docker PowerShell blocks: each exited 0 with total 1, succeeded 1, failed/skipped 0. The displayed C# and both embedded manifests match `standalone-host.json`, including Codebelt.Extensions.Xunit.App 13.0.0 and xunit.v3 4.0.3. Engine v0.2.1/hash and Docker :10 digest match the observations above; native used SDK 11.0.100 with .NET 10 runtime, Docker used SDK 10.0.404. Complete console and arithmetic-test blocks were also rerun successfully on both transports. Published-source/manifest/dependency/block parity now has focused deterministic helper coverage. + +Separately, DocFX's pinned codebeltnet/xunit repository-backed commands executed the original Bootstrapper minimal worker test successfully on native and official SDK Docker. This verifies that maintained integration test through its actual project graph; it does not make the merged InventoryWorker manifest runnable or establish that its different source executed. No schema or engine change, model-backed evaluation or trigger-effectiveness measurement occurred. From b5968c5ffb46b6b77049e7d2ecaae599fe94ac5c Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Tue, 17 Nov 2026 16:35:06 +0100 Subject: [PATCH 29/95] =?UTF-8?q?=E2=9C=A8=20add=20repository-backed=20one?= =?UTF-8?q?-shot=20docfx=20examples?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Some public APIs need a real application and test assembly boundary that a standalone csrun block cannot reproduce. Add a guide and generator for a pinned, commit-verified one-shot command that runs the maintained test in its original project graph, with offline tests covering the published blocks and failure checks. --- .../references/one-shot-examples.md | 171 ++++++++++++++++++ .../scripts/integration-example.ps1 | 66 +++++++ .../scripts/test-integration-example.ps1 | 86 +++++++++ 3 files changed, 323 insertions(+) create mode 100644 skills/dotnet-docfx-digest/references/one-shot-examples.md create mode 100644 skills/dotnet-docfx-digest/scripts/integration-example.ps1 create mode 100644 skills/dotnet-docfx-digest/scripts/test-integration-example.ps1 diff --git a/skills/dotnet-docfx-digest/references/one-shot-examples.md b/skills/dotnet-docfx-digest/references/one-shot-examples.md new file mode 100644 index 00000000..eee4e45c --- /dev/null +++ b/skills/dotnet-docfx-digest/references/one-shot-examples.md @@ -0,0 +1,171 @@ +# One-shot documentation examples + +Lead with the developer task, the smallest informative C# example, how to run it, the expected outcome, and a maintained source link. Keep the API page understandable without execution. Put long execution blocks in an immediately linked conceptual page or disclosure when needed; no manual project assembly, helper installation, repository-layout knowledge or full project dumps. + +## Select and verify + +1. Prefer a complete standalone console program or genuine xUnit v3 test. Use `dotnet-csrun`'s existing manifest and `New-CsrunExecutionPair`; publish both independent PowerShell 7 native and disposable Docker blocks. Both decode to identical source and dependencies. Verify each available transport separately; label unavailable transports Unverified with the precise prerequisite. +2. For intrinsic integration/assembly identity, locate the maintained application/example and associated functional test, inspect project references, shared build settings, SDK, runner and package pins, infrastructure, signing and feeds. Select an exact test that proves the documented claim. Generate one block that downloads a commit-pinned repository snapshot to OS temp, builds/runs its original graph, verifies the intended test actually passed, and cleans up. No generated application, replacement test host, new test runner or multi-project manifest. +3. Use the runner's actual filtering/reporting conventions, inspected from its help and official documentation. MTP/xUnit v3 `--filter-method` is not VSTest `--filter FullyQualifiedName=...`. Report switches vary by version: xUnit v3 4.0.3 uses `--report-xunit-xml`. Require a fresh result report containing the exact intended test, positive executed/passed counts, no skips or runner errors, and matching process status. Exit zero or listing a discovered name alone never proves execution. +4. Verify the entire published block in a fresh PowerShell process, including download, quoting, result checks and cleanup. Offer an independent Docker block using a compatible official .NET SDK image when practical, with no host SDK dependency. Reuse `dotnet-test` for fixture/lifecycle guidance and `dotnet-remote-testing` for existing managed remote workloads; these blocks directly invoke the maintained native runner, not another test engine. The user-requested native path never requires Docker. +5. Record commit, command/block identity, SDK/runtime or image digest, package pins, exact test name, stdout/stderr, exit and counts outside tracked repositories. Preserve diagnostics on failure and clean downloaded sources/build output. Failed/unavailable verification remains Failed/Unverified; never retarget, change assertions or patch upstream source to obtain success. +6. If neither strategy faithfully reproduces the behavior, retain a concise illustration explicitly labelled non-standalone and unverified. Explain why, state prerequisites, and link directly to implementation, maintained example, test and project. Do not use a source-only fallback when a working one-shot test is available. This fallback does not suppress existing DocFX quality or compilation diagnostics; resolve them in maintained source context or report completion blocked. + +## ManagedApplicationFixture: actual worker startup + +The maintained test demonstrates resolving the marker registered by the application's original entry point. It also asserts the Development environment and the availability of IHostApplicationLifetime. The fixture selects `typeof(TEntryPoint).Assembly`, so its application and executable xUnit test runner must retain separate assemblies. This is **repository-backed integration execution**, not an isolated csrun manifest. + +The maintained test below belongs to the linked repository test project; it is not standalone source. Fixture injection and the base constructor retain the real application lifecycle. Run either complete block below to execute this exact test without assembling files: + +```csharp +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Xunit; +using BootstrapperMinimalWorkerMarker = Codebelt.Extensions.Xunit.Hosting.BootstrapperMinimalWorker.App.BootstrapperMinimalWorkerMarker; +using BootstrapperMinimalWorkerProgram = Codebelt.Extensions.Xunit.Hosting.BootstrapperMinimalWorker.App.Program; + +namespace Codebelt.Extensions.Xunit.Hosting; + +public class BootstrapperMinimalWorkerApplicationTestTest : ApplicationTest> +{ + public BootstrapperMinimalWorkerApplicationTestTest(ManagedApplicationFixture hostFixture, ITestOutputHelper output) : base(hostFixture, output) + { + } + + [Fact] + public void ShouldBootstrapMinimalWorkerProgram() + { + var marker = Host.Services.GetRequiredService(); + + Assert.Equal("Bootstrapper Minimal Worker", marker.Value); + Assert.Equal("Development", Environment.EnvironmentName); + Assert.NotNull(Host.Services.GetRequiredService()); + } +} +``` + +Explore the [fixture implementation](https://github.com/codebeltnet/xunit/blob/84b13767cb9484f8f3a36a71875662edfdb3e511/src/Codebelt.Extensions.Xunit.Hosting/ManagedApplicationFixture.cs), [worker application](https://github.com/codebeltnet/xunit/blob/84b13767cb9484f8f3a36a71875662edfdb3e511/app/Codebelt.Extensions.Xunit.Hosting.BootstrapperMinimalWorker.App/Program.cs), [functional test](https://github.com/codebeltnet/xunit/blob/84b13767cb9484f8f3a36a71875662edfdb3e511/test/Codebelt.Extensions.Xunit.Hosting.FunctionalTests/BootstrapperMinimalWorkerApplicationTestTest.cs), and [referencing test project](https://github.com/codebeltnet/xunit/blob/84b13767cb9484f8f3a36a71875662edfdb3e511/test/Codebelt.Extensions.Xunit.Hosting.FunctionalTests/Codebelt.Extensions.Xunit.Hosting.FunctionalTests.csproj). + +Both blocks independently download commit `84b13767cb9484f8f3a36a71875662edfdb3e511` and run its original test on net11.0. The snapshot pins xunit.v3 4.0.3 and Codebelt.Bootstrapper.Worker 5.2.3; shared props supply further dependencies. Network access to GitHub and configured NuGet feeds is required. Archive builds may warn that MinVer has no Git history; they do not reproduce release version metadata. SkipSignAssembly avoids requiring the publisher's signing key. Neither block edits the application or the assertions. A short temporary path avoids Windows path-length failures; an unusually long configured temp root can still require a shorter OS temp setting. + +Expected: exactly `ShouldBootstrapMinimalWorkerProgram` executes, with 1 passed, 0 failed and 0 skipped, followed by `Verified:`. Failure throws and retains logs/results under the printed OS-temporary diagnostics path. Downloaded source and build output are removed in finally. Running repository build tasks and packages requires trust in that source and its dependencies; Docker mounts only the temporary workspace but is not a security sandbox. + +## Native: PowerShell 7 and .NET 11 SDK + +```powershell +#requires -Version 7.0 +& { + $ErrorActionPreference = 'Stop' + $PSNativeCommandUseErrorActionPreference = $false + # Executes trusted repository build tasks and NuGet packages with your permissions. + # Review the pinned source before running; a container is not a security sandbox. + $null = Get-Command dotnet -ErrorAction Stop + $work = Join-Path ([IO.Path]::GetTempPath()) ('dx-' + [guid]::NewGuid().ToString('N').Substring(0, 8)) + $null = New-Item -ItemType Directory -Path $work + try { + $commit = '84b13767cb9484f8f3a36a71875662edfdb3e511' + Invoke-WebRequest "https://codeload.github.com/codebeltnet/xunit/zip/$commit" -OutFile "$work/source.zip" + Expand-Archive -LiteralPath "$work/source.zip" -DestinationPath "$work/extracted" + Move-Item -LiteralPath "$work/extracted/xunit-$commit" -Destination "$work/repo" + $project = 'test/Codebelt.Extensions.Xunit.Hosting.FunctionalTests/Codebelt.Extensions.Xunit.Hosting.FunctionalTests.csproj' + $test = 'Codebelt.Extensions.Xunit.Hosting.BootstrapperMinimalWorkerApplicationTestTest.ShouldBootstrapMinimalWorkerProgram' + Push-Location "$work/repo" + try { + dotnet run --project $project --framework net11.0 -p:SkipSignAssembly=true -- --filter-method $test --report-xunit-xml --report-xunit-xml-filename result.xml --results-directory "$work/results" 2>&1 | Tee-Object -FilePath "$work/run.log" + } + finally { Pop-Location } + $code = $LASTEXITCODE + if ($code -ne 0) { throw "Repository test failed with exit code $code. See $work/run.log" } + # Require exactly the original test, executed and passing, with no runner errors. + [xml] $report = Get-Content -LiteralPath "$work/results/result.xml" -Raw + $tests = @($report.SelectNodes('/assemblies/assembly/collection/test')) + $assemblies = @($report.SelectNodes('/assemblies/assembly')) + if ($assemblies.Count -ne 1 -or $assemblies[0].total -ne '1' -or $assemblies[0].passed -ne '1' -or + $assemblies[0].errors -ne '0' -or $tests.Count -ne 1 -or $tests[0].name -cne $test -or $tests[0].result -cne 'Pass') { + throw "Expected exactly one passing $test; inspect $work/results/result.xml" + } + Write-Host "Verified: $test (1 executed, 1 passed)." + } + catch { + # Preserve diagnostics outside the repository even though downloaded source is cleaned. + $diagnostics = "$work-diagnostics" + $null = New-Item -ItemType Directory -Path $diagnostics -Force + foreach ($name in @('run.log', 'results')) { + if (Test-Path -LiteralPath "$work/$name") { Copy-Item -LiteralPath "$work/$name" -Destination $diagnostics -Recurse } + } + Write-Warning "Execution not verified. Diagnostics: $diagnostics" + throw + } + finally { + $resolved = [IO.Path]::GetFullPath($work) + $temp = [IO.Path]::GetFullPath([IO.Path]::GetTempPath()).TrimEnd('/','\') + [IO.Path]::DirectorySeparatorChar + if (-not $resolved.StartsWith($temp, [StringComparison]::OrdinalIgnoreCase)) { throw 'Unsafe cleanup path.' } + Remove-Item -LiteralPath $resolved -Recurse -Force + } +} +``` + +## Docker: PowerShell 7 and Docker with Linux containers + +No host .NET SDK is required. The official SDK image supplies it; first use pulls the image. + +```powershell +#requires -Version 7.0 +& { + $ErrorActionPreference = 'Stop' + $PSNativeCommandUseErrorActionPreference = $false + # Executes trusted repository build tasks and NuGet packages with your permissions. + # Review the pinned source before running; a container is not a security sandbox. + $null = Get-Command docker -ErrorAction Stop + docker info *> $null + if ($LASTEXITCODE -ne 0) { throw 'Docker daemon unavailable.' } + $work = Join-Path ([IO.Path]::GetTempPath()) ('dx-' + [guid]::NewGuid().ToString('N').Substring(0, 8)) + $null = New-Item -ItemType Directory -Path $work + try { + $commit = '84b13767cb9484f8f3a36a71875662edfdb3e511' + Invoke-WebRequest "https://codeload.github.com/codebeltnet/xunit/zip/$commit" -OutFile "$work/source.zip" + Expand-Archive -LiteralPath "$work/source.zip" -DestinationPath "$work/extracted" + Move-Item -LiteralPath "$work/extracted/xunit-$commit" -Destination "$work/repo" + $project = 'test/Codebelt.Extensions.Xunit.Hosting.FunctionalTests/Codebelt.Extensions.Xunit.Hosting.FunctionalTests.csproj' + $test = 'Codebelt.Extensions.Xunit.Hosting.BootstrapperMinimalWorkerApplicationTestTest.ShouldBootstrapMinimalWorkerProgram' + docker run --rm --mount "type=bind,source=$work,target=/work" --workdir /work/repo mcr.microsoft.com/dotnet/sdk:11.0 dotnet run --project $project --framework net11.0 -p:SkipSignAssembly=true -- --filter-method $test --report-xunit-xml --report-xunit-xml-filename result.xml --results-directory /work/results 2>&1 | Tee-Object -FilePath "$work/run.log" + $code = $LASTEXITCODE + if ($code -ne 0) { throw "Repository test failed with exit code $code. See $work/run.log" } + # Require exactly the original test, executed and passing, with no runner errors. + [xml] $report = Get-Content -LiteralPath "$work/results/result.xml" -Raw + $tests = @($report.SelectNodes('/assemblies/assembly/collection/test')) + $assemblies = @($report.SelectNodes('/assemblies/assembly')) + if ($assemblies.Count -ne 1 -or $assemblies[0].total -ne '1' -or $assemblies[0].passed -ne '1' -or + $assemblies[0].errors -ne '0' -or $tests.Count -ne 1 -or $tests[0].name -cne $test -or $tests[0].result -cne 'Pass') { + throw "Expected exactly one passing $test; inspect $work/results/result.xml" + } + Write-Host "Verified: $test (1 executed, 1 passed)." + } + catch { + # Preserve diagnostics outside the repository even though downloaded source is cleaned. + $diagnostics = "$work-diagnostics" + $null = New-Item -ItemType Directory -Path $diagnostics -Force + foreach ($name in @('run.log', 'results')) { + if (Test-Path -LiteralPath "$work/$name") { Copy-Item -LiteralPath "$work/$name" -Destination $diagnostics -Recurse } + } + Write-Warning "Execution not verified. Diagnostics: $diagnostics" + throw + } + finally { + $resolved = [IO.Path]::GetFullPath($work) + $temp = [IO.Path]::GetFullPath([IO.Path]::GetTempPath()).TrimEnd('/','\') + [IO.Path]::DirectorySeparatorChar + if (-not $resolved.StartsWith($temp, [StringComparison]::OrdinalIgnoreCase)) { throw 'Unsafe cleanup path.' } + Remove-Item -LiteralPath $resolved -Recurse -Force + } +} +``` + +Maintainers generate both blocks with [integration-example.ps1](../scripts/integration-example.ps1). It only produces artifacts and introduces no runner or manifest. Focused tests compare these published blocks byte-for-byte and exercise failure checks with offline doubles; those checks alone do not verify the actual integration test. + +## Observed verification, 2026-11-17 + +Both complete blocks above were executed in fresh PowerShell processes from fresh archive downloads. Native Windows x64 used SDK 11.0.100/runtime 11.0.0. Linux Docker used official SDK 11.0.100/runtime 11.0.0, observed image digest `mcr.microsoft.com/dotnet/sdk@sha256:65f3c7c6a25a239ab3e6719f2896147e7b68242ff2d8818dd70498bde6ef8bea`. Each exited 0 after checking the XML report for exactly the named test passing: total 1, succeeded 1, failed/skipped 0. The image tag remains mutable; this is evidence of the tested image, not future tag contents. + +A separate native negative run replaced only the filter with `DoesNotExist.NoSuchTest`: MTP reported zero tests and exit 8; the block threw (PowerShell exit 1), retained log/XML diagnostics outside the repository, and removed the downloaded workspace. The initial long-path launch failed before execution on Windows; the published blocks use a short temporary root and rename the archive root before building. No application source or assertion was changed. + +Focused deterministic checks: `pwsh -NoProfile -File skills/dotnet-docfx-digest/scripts/test-integration-example.ps1` checks published parity, PowerShell parsing and 17 offline cases covering exact passing identity, wrong identity, zero tests, skips, runner errors, missing reports, missing dependencies, missing commands and unavailable Docker daemon. Offline doubles prove wrapper checks, not integration behavior. Existing `test-quality.ps1` retains source-backed compilation, architecture diagnostics and real application/standalone/middleware controls. These checks do not replace `agents.cs` or the build-backed DocFX completion gates when editing a target documentation repository. This change does not modify codebeltnet/xunit or claim the published API page was repaired. diff --git a/skills/dotnet-docfx-digest/scripts/integration-example.ps1 b/skills/dotnet-docfx-digest/scripts/integration-example.ps1 new file mode 100644 index 00000000..e1eaef03 --- /dev/null +++ b/skills/dotnet-docfx-digest/scripts/integration-example.ps1 @@ -0,0 +1,66 @@ +#requires -Version 7.0 +# Artifact generation only: no downloads, builds or test execution when dot-sourced. +function New-ManagedApplicationExamplePair { + $template = @' +#requires -Version 7.0 +& { + $ErrorActionPreference = 'Stop' + $PSNativeCommandUseErrorActionPreference = $false + # Executes trusted repository build tasks and NuGet packages with your permissions. + # Review the pinned source before running; a container is not a security sandbox. + __PREREQUISITE__ + $work = Join-Path ([IO.Path]::GetTempPath()) ('dx-' + [guid]::NewGuid().ToString('N').Substring(0, 8)) + $null = New-Item -ItemType Directory -Path $work + try { + $commit = '84b13767cb9484f8f3a36a71875662edfdb3e511' + Invoke-WebRequest "https://codeload.github.com/codebeltnet/xunit/zip/$commit" -OutFile "$work/source.zip" + Expand-Archive -LiteralPath "$work/source.zip" -DestinationPath "$work/extracted" + Move-Item -LiteralPath "$work/extracted/xunit-$commit" -Destination "$work/repo" + $project = 'test/Codebelt.Extensions.Xunit.Hosting.FunctionalTests/Codebelt.Extensions.Xunit.Hosting.FunctionalTests.csproj' + $test = 'Codebelt.Extensions.Xunit.Hosting.BootstrapperMinimalWorkerApplicationTestTest.ShouldBootstrapMinimalWorkerProgram' + __EXECUTE__ + $code = $LASTEXITCODE + if ($code -ne 0) { throw "Repository test failed with exit code $code. See $work/run.log" } + # Require exactly the original test, executed and passing, with no runner errors. + [xml] $report = Get-Content -LiteralPath "$work/results/result.xml" -Raw + $tests = @($report.SelectNodes('/assemblies/assembly/collection/test')) + $assemblies = @($report.SelectNodes('/assemblies/assembly')) + if ($assemblies.Count -ne 1 -or $assemblies[0].total -ne '1' -or $assemblies[0].passed -ne '1' -or + $assemblies[0].errors -ne '0' -or $tests.Count -ne 1 -or $tests[0].name -cne $test -or $tests[0].result -cne 'Pass') { + throw "Expected exactly one passing $test; inspect $work/results/result.xml" + } + Write-Host "Verified: $test (1 executed, 1 passed)." + } + catch { + # Preserve diagnostics outside the repository even though downloaded source is cleaned. + $diagnostics = "$work-diagnostics" + $null = New-Item -ItemType Directory -Path $diagnostics -Force + foreach ($name in @('run.log', 'results')) { + if (Test-Path -LiteralPath "$work/$name") { Copy-Item -LiteralPath "$work/$name" -Destination $diagnostics -Recurse } + } + Write-Warning "Execution not verified. Diagnostics: $diagnostics" + throw + } + finally { + $resolved = [IO.Path]::GetFullPath($work) + $temp = [IO.Path]::GetFullPath([IO.Path]::GetTempPath()).TrimEnd('/','\') + [IO.Path]::DirectorySeparatorChar + if (-not $resolved.StartsWith($temp, [StringComparison]::OrdinalIgnoreCase)) { throw 'Unsafe cleanup path.' } + Remove-Item -LiteralPath $resolved -Recurse -Force + } +} +'@ + $native = @' +Push-Location "$work/repo" + try { + dotnet run --project $project --framework net11.0 -p:SkipSignAssembly=true -- --filter-method $test --report-xunit-xml --report-xunit-xml-filename result.xml --results-directory "$work/results" 2>&1 | Tee-Object -FilePath "$work/run.log" + } + finally { Pop-Location } +'@ + $docker = @' +docker run --rm --mount "type=bind,source=$work,target=/work" --workdir /work/repo mcr.microsoft.com/dotnet/sdk:11.0 dotnet run --project $project --framework net11.0 -p:SkipSignAssembly=true -- --filter-method $test --report-xunit-xml --report-xunit-xml-filename result.xml --results-directory /work/results 2>&1 | Tee-Object -FilePath "$work/run.log" +'@ + [pscustomobject]@{ + Native = $template.Replace('__PREREQUISITE__', "`$null = Get-Command dotnet -ErrorAction Stop").Replace('__EXECUTE__', $native) + Docker = $template.Replace('__PREREQUISITE__', "`$null = Get-Command docker -ErrorAction Stop`n docker info *> `$null`n if (`$LASTEXITCODE -ne 0) { throw 'Docker daemon unavailable.' }").Replace('__EXECUTE__', $docker) + } +} diff --git a/skills/dotnet-docfx-digest/scripts/test-integration-example.ps1 b/skills/dotnet-docfx-digest/scripts/test-integration-example.ps1 new file mode 100644 index 00000000..613213cd --- /dev/null +++ b/skills/dotnet-docfx-digest/scripts/test-integration-example.ps1 @@ -0,0 +1,86 @@ +#requires -Version 7.0 +$ErrorActionPreference = 'Stop' +. (Join-Path $PSScriptRoot 'integration-example.ps1') +$pair = New-ManagedApplicationExamplePair +$document = Get-Content (Join-Path $PSScriptRoot '../references/one-shot-examples.md') -Raw +$blocks = [regex]::Matches($document, '(?s)```powershell\r?\n(.*?)\r?\n```') +if ($blocks.Count -ne 2) { throw 'Expected two independent published execution blocks.' } +$source = [regex]::Match($document, '(?s)```csharp\r?\n(.*?)\r?\n```').Groups[1].Value.Replace("`r`n", "`n").TrimEnd() +# Hash of the original maintained test at the pinned snapshot, not a reconstructed sample. +$sourceHash = [Convert]::ToHexString([Security.Cryptography.SHA256]::HashData([Text.Encoding]::UTF8.GetBytes($source))) +if ($sourceHash -cne '47B0C1FBA94E7B43C8753D0A8242801B328E6B463B6EEDAEB640D4F8A262633E') { throw 'Displayed test differs from the original maintained source.' } +$checks = 0 +foreach ($transport in @('Native', 'Docker')) { + $index = if ($transport -eq 'Native') { 0 } else { 1 } + if ($blocks[$index].Groups[1].Value.Replace("`r`n", "`n") -cne $pair.$transport.Replace("`r`n", "`n")) { throw "Published $transport block drifted." } + $tokens = $null; $errors = $null + $null = [Management.Automation.Language.Parser]::ParseInput($pair.$transport, [ref] $tokens, [ref] $errors) + if ($errors.Count) { throw "Invalid PowerShell: $errors" } + $scenarios = @('pass', 'wrong-test', 'zero', 'skip', 'runner-error', 'missing-report', 'dependency', 'environment') + if ($transport -eq 'Docker') { $scenarios += 'daemon' } + foreach ($scenario in $scenarios) { + & { + # Offline doubles exercise the complete published block; never evidence of live tests. + function Invoke-WebRequest { param($Uri, $OutFile) } + function Expand-Archive { + param($LiteralPath, $DestinationPath) + $workspaces.Add((Split-Path $DestinationPath -Parent)) + $null = New-Item -ItemType Directory -Path "$DestinationPath/xunit-84b13767cb9484f8f3a36a71875662edfdb3e511" -Force + } + function Get-Command { + param($Name, $ErrorAction) + if ($scenario -eq 'environment') { throw "Unavailable $Name" } + } + function Invoke-TestDouble { + if ($scenario -eq 'dependency') { $global:LASTEXITCODE = 1; return 'NU1101: dependency unavailable' } + $global:LASTEXITCODE = 0 + if ($scenario -eq 'missing-report') { return } + $null = New-Item -ItemType Directory -Path "$work/results" -Force + $name = if ($scenario -eq 'wrong-test') { 'Other.Test' } else { $test } + $count = if ($scenario -eq 'zero') { '0' } else { '1' } + $result = if ($scenario -eq 'skip') { 'Skip' } else { 'Pass' } + $errors = if ($scenario -eq 'runner-error') { '1' } else { '0' } + $tests = if ($scenario -eq 'zero') { '' } else { "" } + Set-Content "$work/results/result.xml" "$tests" + 'Offline test double' + } + function dotnet { + if ($transport -ne 'Native') { throw 'Docker block required a host SDK.' } + Invoke-TestDouble + } + function docker { + if ($transport -ne 'Docker') { throw 'Native block required Docker.' } + if ($args[0] -eq 'info') { $global:LASTEXITCODE = if ($scenario -eq 'daemon') { 1 } else { 0 }; return } + Invoke-TestDouble + } + $failed = $false + $warnings = [Collections.Generic.List[string]]::new() + $workspaces = [Collections.Generic.List[string]]::new() + function Write-Warning { param($Message) $warnings.Add($Message) } + try { & ([scriptblock]::Create($pair.$transport)) | Out-Null } + catch { $failed = $true } + if ($failed -ne ($scenario -ne 'pass')) { throw "$transport/$scenario did not enforce verification." } + foreach ($workspace in $workspaces) { + if (Test-Path -LiteralPath $workspace) { throw 'Downloaded workspace leaked.' } + } + # The downloaded workspace must be gone after success or failure. + if ($scenario -notin @('environment', 'daemon')) { + # Capture its path from the diagnostic warning on failures. + $warning = @($warnings | Where-Object { "$_" -like '*Diagnostics:*' }) + if ($scenario -ne 'pass' -and $warning.Count -ne 1) { throw 'Missing failure diagnostics.' } + if ($warning.Count) { + $diagnostics = ("$($warning[0])" -split 'Diagnostics: ', 2)[1] + $workspace = $diagnostics -replace '-diagnostics$', '' + if (Test-Path -LiteralPath $workspace) { throw 'Downloaded workspace leaked.' } + if ($scenario -eq 'dependency' -and (Get-Content "$diagnostics/run.log" -Raw) -notmatch 'NU1101') { throw 'Dependency diagnostics lost.' } + $resolved = [IO.Path]::GetFullPath($diagnostics) + $temp = [IO.Path]::GetFullPath([IO.Path]::GetTempPath()).TrimEnd('/','\') + [IO.Path]::DirectorySeparatorChar + if (-not $resolved.StartsWith($temp, [StringComparison]::OrdinalIgnoreCase)) { throw 'Unsafe test cleanup.' } + Remove-Item -LiteralPath $resolved -Recurse -Force + } + } + } + $checks++ + } +} +Write-Host "One-shot integration artifacts passed: $checks offline cases, published parity and PowerShell syntax (not live verification)." From ccf5923dd8f45d1da2c02d82f0a3d33c9a76c287 Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Tue, 17 Nov 2026 16:35:14 +0100 Subject: [PATCH 30/95] =?UTF-8?q?=E2=9C=85=20run=20one-shot=20docfx=20exam?= =?UTF-8?q?ple=20checks=20in=20validator?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The new one-shot example generator has deterministic offline tests that must run with the DocFX validation suite. Register them in the validator so drift in the published blocks or required checks fails in the same gate as the other DocFX scripts. --- scripts/validate-skill-templates.ps1 | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/scripts/validate-skill-templates.ps1 b/scripts/validate-skill-templates.ps1 index 33a7b8e5..654ea23e 100644 --- a/scripts/validate-skill-templates.ps1 +++ b/scripts/validate-skill-templates.ps1 @@ -3862,6 +3862,10 @@ Add-ValidationResult -Results $results -Name 'Rendered library templates leave n if ($Full -and $Suite -in @('All', 'Docfx')) { $docfxScriptResults = Invoke-ValidationScriptJobs -Scripts @( + [pscustomobject]@{ + Name = 'DocFX one-shot integration examples enforce exact test execution' + Path = Join-Path $repoRoot 'skills/dotnet-docfx-digest/scripts/test-integration-example.ps1' + } [pscustomobject]@{ Name = 'DocFX digest rejects metadata scaffolds and accepts scenario-led documentation' Path = Join-Path $repoRoot 'skills/dotnet-docfx-digest/scripts/test-quality.ps1' From 23adc3447f13b4bcfe29daa74ac532435571be56 Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Tue, 17 Nov 2026 16:35:21 +0100 Subject: [PATCH 31/95] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20link=20docfx=20api?= =?UTF-8?q?=20examples=20to=20one-shot=20references?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit API examples that need an application or test graph should link a verified one-shot command instead of asking developers to assemble projects manually. Update the DocFX guidance to choose standalone csrun or the repository-backed one-shot path, and add the matching eval case. --- skills/dotnet-docfx-digest/SKILL.md | 1 + skills/dotnet-docfx-digest/evals/evals.json | 11 +++++++++++ .../references/csrun-composition.md | 4 +++- .../references/example-architecture.md | 4 ++-- 4 files changed, 17 insertions(+), 3 deletions(-) diff --git a/skills/dotnet-docfx-digest/SKILL.md b/skills/dotnet-docfx-digest/SKILL.md index 9416cb1f..33e3042e 100644 --- a/skills/dotnet-docfx-digest/SKILL.md +++ b/skills/dotnet-docfx-digest/SKILL.md @@ -14,6 +14,7 @@ Create and maintain developer-friendly DocFX documentation digests for .NET publ ## Critical +- Prefer complete standalone programs and genuine xUnit v3 tests, delivered through existing `dotnet-csrun` native and Docker one-shot blocks with identical source/dependencies. For APIs requiring an actual application, runner or distinct assembly identity, inspect the maintained example, test and project graph, then provide a pinned repository-backed one-shot test instead. Read [one-shot examples](references/one-shot-examples.md) before publishing execution instructions. Do not expand csrun manifest v1 or manufacture a substitute host. - This skill is autonomous by default. If the user invokes it without naming a namespace, type, member, or changed API — including a bare direct skill call with no parsed arguments, a host-initiated continuation, or a host re-entry that invokes `dotnet-docfx-digest` directly with no extra arguments after the skill already auto-triggered — assume non-human/autonomous execution, treat the request as a repo-wide DocFX audit and repair task, and do not ask startup scoping or approval-to-continue questions. - Resolve bundled scripts from the loaded `dotnet-docfx-digest` skill directory first. If that install path is unavailable and the target repository contains the repo-managed source copy, fall back to `skills/dotnet-docfx-digest/scripts/*.cs`. Do not claim the scripts are unavailable until both locations have been checked. - `docfx.cs` is fast by default: a plain run validates Markdown, prose, DocFX overwrite layout, namespace pages, extension tables, and required examples **without building, restoring, or running DocFX/gh**. Use it freely during iteration — it discovers the public API from existing DocFX YAML metadata or a conservative source scan, and ends with a `[processes] dotnet=0 msbuild=0 docfx=0 gh=0` summary. Compilation and network access are opt-in. diff --git a/skills/dotnet-docfx-digest/evals/evals.json b/skills/dotnet-docfx-digest/evals/evals.json index 2d47b2e1..32828e34 100644 --- a/skills/dotnet-docfx-digest/evals/evals.json +++ b/skills/dotnet-docfx-digest/evals/evals.json @@ -1259,6 +1259,17 @@ "Existing multiple-class files, ordinary library snippets and Program.cs examples retain their validation behavior", "Preserves exact overwrite UID ownership, conditional TFM requirements, strict existing waiver approval and Markdown encoding/line endings" ] + }, + { + "id": 118, + "prompt": "Refine the ManagedApplicationFixture API example at https://xunit.codebelt.net/api/Codebelt.Extensions.Xunit.Hosting.ManagedApplicationFixture-1.html. Use codebeltnet/xunit test/Codebelt.Extensions.Xunit.Hosting.FunctionalTests/BootstrapperMinimalWorkerApplicationTestTest.cs. Give one-shot native and Docker commands that execute the original maintained test; do not modify that repository or invent a host.", + "expected_output": "Classifies repository-backed integration, inspects the actual project graph and pinned source, and delivers two independent pinned-snapshot PowerShell blocks with positive exact-test execution verification and cleanup. Shows a concise meaningful excerpt and direct implementation/application/test/project links. Reports actual evidence separately per environment and preserves diagnostics if unavailable.", + "expectations": [ + "Preserves the original application implementation, project references, fixture lifecycle and assertions; no multi-project csrun schema or engine changes.", + "Requires exact intended test identity, positive execution and pass counts plus process status; rejects wrong filters, zero tests and skipped tests.", + "Both commands include all setup and cleanup and state prerequisites; unavailable environments or dependencies are explicitly unverified with diagnostics.", + "Fallback source links are used only when faithful execution is unavailable, without a verified runnable label." + ] } ] } diff --git a/skills/dotnet-docfx-digest/references/csrun-composition.md b/skills/dotnet-docfx-digest/references/csrun-composition.md index 8875a8fc..b4cb02a6 100644 --- a/skills/dotnet-docfx-digest/references/csrun-composition.md +++ b/skills/dotnet-docfx-digest/references/csrun-composition.md @@ -1,4 +1,6 @@ -# Standalone runtime evidence with dotnet-csrun +# Standalone and repository-backed runtime evidence + +Choose the easiest faithful reproduction before authoring. Prefer standalone csrun. For an intrinsic application/test assembly boundary, DocFX owns a separate pinned repository-backed one-shot command: download to OS temp, run the maintained targeted test, verify positive execution of that exact test, and clean source/build artifacts. Offer an independent official SDK Docker equivalent where practical, without requiring a host SDK. See [one-shot examples](one-shot-examples.md) for the verified ManagedApplicationFixture regression and artifact generator. This is execution of trusted repository code and its original project graph, not isolated manifest execution. csrun owns only standalone execution; neither engine nor schema v1 changes. Keep the existing DocFX inventory and source discovery. This skill owns public API discovery, namespace/type pages, UID/overwrite placement, source-backed explanation, project-aware sample compilation and documentation completion. `dotnet-csrun` owns compatible standalone construction, real xUnit v3 execution, native/Docker deliverables, behavioral verification, localized corrections and execution evidence. Apply both skills in the parent context when authorized; deterministic validators never launch another skill, agent, or authenticated model. diff --git a/skills/dotnet-docfx-digest/references/example-architecture.md b/skills/dotnet-docfx-digest/references/example-architecture.md index b7828a6b..6cf5f906 100644 --- a/skills/dotnet-docfx-digest/references/example-architecture.md +++ b/skills/dotnet-docfx-digest/references/example-architecture.md @@ -23,7 +23,7 @@ Use the sequence **Discover API → Understand consumer task → Determine execu | Framework/application integration | Explain who builds/starts/disposes the host, application lifecycle and infrastructure, then verify with its real application/test workflow. | | Intentionally partial excerpt | Say what is omitted and where it belongs. Bind to its maintained compiling source context; do not claim standalone execution. A missing context is unresolved work, not an automatic waiver. | -Prefer a real repository sample/test over generating new projects. When setup would overwhelm an API page, show essential usage and link directly to the maintained integration example and its project. A link supplements the local API example; it does not satisfy target-use or compilation requirements by itself. Include minimal valid project setup only where it is actually needed for reproduction and backed by evidence. +Prefer a real repository sample/test over generating new projects. When setup would overwhelm an API page, show essential usage, link directly to the maintained integration example and its project, and provide a complete pinned-snapshot command that executes the relevant test without manual assembly. Follow [one-shot examples](one-shot-examples.md). Source links alone are the fallback only when neither faithful standalone execution nor a working repository-backed command is available; explain the blocker and prerequisites, and keep the illustration truthful and explicitly unverified. Links and runtime commands do not waive target-use, source-bound compilation or documentation gates. ## Preserve responsibilities @@ -65,6 +65,6 @@ Evidence pinned to [codebeltnet/xunit revision 84b13767](https://github.com/code - [DeferredHostFactory](https://github.com/codebeltnet/xunit/blob/84b13767cb9484f8f3a36a71875662edfdb3e511/src/Codebelt.Extensions.Xunit.Hosting/Internal/DeferredHostFactory.cs) resolves that assembly's entry point. [ApplicationTest](https://github.com/codebeltnet/xunit/blob/84b13767cb9484f8f3a36a71875662edfdb3e511/src/Codebelt.Extensions.Xunit.Hosting/ApplicationTest.cs) wires fixture initialization through the base constructor. - [Minimal worker Program](https://github.com/codebeltnet/xunit/blob/84b13767cb9484f8f3a36a71875662edfdb3e511/app/Codebelt.Extensions.Xunit.Hosting.BootstrapperMinimalWorker.App/Program.cs) owns service registration, host construction and `RunAsync`. The [functional test](https://github.com/codebeltnet/xunit/blob/84b13767cb9484f8f3a36a71875662edfdb3e511/test/Codebelt.Extensions.Xunit.Hosting.FunctionalTests/BootstrapperMinimalWorkerApplicationTestTest.cs) resolves the application's marker service and asserts its value. Its [project](https://github.com/codebeltnet/xunit/blob/84b13767cb9484f8f3a36a71875662edfdb3e511/test/Codebelt.Extensions.Xunit.Hosting.FunctionalTests/Codebelt.Extensions.Xunit.Hosting.FunctionalTests.csproj) references the application separately. -Recommended correction to the [published InventoryWorker example](https://xunit.codebelt.net/api/Codebelt.Extensions.Xunit.Hosting.ManagedApplicationFixture-1.html): put `WorkerProgram.Main`, `WorkerIdentity` and registration in application project `InventoryWorker`; put `InventoryWorkerTest`, `[Fact]`, injected fixture and assertion in `InventoryWorker.Tests`, referencing the executable application and the actual xUnit v3 runner. Label both source files and explain the project/package references. Prefer reusing the existing Bootstrapper application/test graph linked above. If retaining the InventoryWorker domain names, first maintain a working split sample; do not publish bindings to invented paths. Keep the API page concise by linking that working integration sample and its application. Do not remove Main, choose a startup object, or manually re-register `WorkerIdentity` in the test. This skill change does not edit the xunit repository. +Recommended correction to the [published InventoryWorker example](https://xunit.codebelt.net/api/Codebelt.Extensions.Xunit.Hosting.ManagedApplicationFixture-1.html): show the smallest meaningful excerpt from the maintained Bootstrapper worker test, explain its separate application assembly, link its original application/test/project, and offer the [verified one-shot native and Docker commands](one-shot-examples.md). Do not dump both projects into the API page or require developers to assemble them manually. If retaining InventoryWorker domain names, first maintain a faithful working split sample; do not publish bindings to invented paths. Never remove Main, choose a startup object, or re-register the marker inside the test. This skill change does not edit the xunit repository. `EXAMPLE_APPLICATION_ASSEMBLY_COLLAPSED` is narrowly scoped to the exact Codebelt `ManagedApplicationFixture`/`ApplicationTest` UID and a local fixture entry-point type in one C# source unit. Roslyn syntax/local symbol evidence avoids matching comments, strings, or unrelated multiple-class samples. Separate bound files are not merged for this check. Aliased or otherwise unresolved usages require build-backed verification and architectural review. The diagnostic is not a universal C# architecture analyzer and does not certify registration ownership, pipeline ordering, runtime success, or prose truth. From 4ca9f01f1e2bc721a9f264427cd4dfcfb33c0790 Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Tue, 17 Nov 2026 16:52:20 +0100 Subject: [PATCH 32/95] =?UTF-8?q?=F0=9F=93=9D=20add=20optional=20contextua?= =?UTF-8?q?l=20source=20reference=20guidance?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Principal DocFX examples must stay sufficient on the page. Optional maintained source links are now added only when they teach integration, configuration or lifecycle depth beyond the example, and the new contextual source references reference defines that selection rule. Required C#, one-shot execution and completion gates are unchanged. --- skills/dotnet-docfx-digest/SKILL.md | 2 + .../contextual-source-references.md | 37 +++++++++++++++++++ .../references/example-architecture.md | 2 + .../references/one-shot-examples.md | 14 +++++-- .../references/workflow.md | 2 + 5 files changed, 53 insertions(+), 4 deletions(-) create mode 100644 skills/dotnet-docfx-digest/references/contextual-source-references.md diff --git a/skills/dotnet-docfx-digest/SKILL.md b/skills/dotnet-docfx-digest/SKILL.md index 33e3042e..f8350b2e 100644 --- a/skills/dotnet-docfx-digest/SKILL.md +++ b/skills/dotnet-docfx-digest/SKILL.md @@ -341,6 +341,8 @@ For managed reference pages, map type and extension-method examples to the `exam ## Example Verification +Keep the principal example sufficient for learning on the page. Present purpose, essential C#, expected outcome, reproduction where applicable, then optional deeper exploration. Reuse already-discovered authoritative usage to select precise maintained source references, explaining what each adds about integration, configuration or lifecycle. Runnable examples can benefit too; simple APIs need no links without useful additional context. Read [contextual source references](references/contextual-source-references.md) before selecting further reading. Links never replace explanations, required C# usage, one-shot execution or compilation/completion gates. + For compatible standalone runtime examples, compose with `dotnet-csrun create`, `verify`, or authorized `repair`; see [standalone execution composition](references/csrun-composition.md). Keep this skill's source discovery, placement, reference-aware compilation, and `--build-api-model --validate-samples --verify-docfx-build` completion gates. Published-package execution adds behavioral evidence; it does not verify unpublished project code. Do not force existing partial or project-dependent examples into standalone programs, and do not put two full execution blocks on every type page merely because csrun generates them. Verify added or changed C# before publishing. Unbound fences pass the following two gates. For explicitly project-bound files/excerpts, the validator checks source identity, evaluated Compile membership, and the maintained project build instead of compiling a fragment alone. See [example architecture](references/example-architecture.md) for the exact binding and its limits. diff --git a/skills/dotnet-docfx-digest/references/contextual-source-references.md b/skills/dotnet-docfx-digest/references/contextual-source-references.md new file mode 100644 index 00000000..681e8eea --- /dev/null +++ b/skills/dotnet-docfx-digest/references/contextual-source-references.md @@ -0,0 +1,37 @@ +# Contextual source references + +Make the example sufficient for learning, and the references valuable for mastering. A reader should understand the developer task, essential API usage, dependencies and expected result without leaving the page. Keep feasible copy/run/adapt paths complete under the existing [one-shot execution contract](one-shot-examples.md). + +## Select references during existing discovery + +Reuse the package-ID-first discovery, tests, READMEs, consumer examples and implementation already inspected for the example. When one contributes evidence, consider whether it also teaches useful additional context. Record the selected URL, inspected source/revision, API relationship and added learning value briefly in the existing inventory evidence cell. An explicit decision that no reference adds value is sufficient for a simple API. Do not add a repository search subsystem, network checks to the fast validator, or a link quota. + +Prefer direct files or focused directories showing actual usage: maintained applications, composition roots, functional/integration tests, configuration variants, package READMEs and conceptual tutorials. Implementation internals can clarify lifecycle, but prioritize how a consumer uses the API. A repository homepage, unrelated passing test, or arbitrary nearby file is not useful merely because it exists. + +Before adding a link, open its target, inspect the content, and confirm the claimed relationship to this API. Verify file paths, test names, project references and any configuration/lifecycle claims. If a new target cannot be verified, omit that proposed reference or report the unresolved evidence; do not invent a replacement. Preserve existing valid links and `Related:` sections. Under the historical-link policy, only a directly verified HTTP 404 justifies removing or replacing an existing URL; timeouts, authentication failures, rate limits and unconfirmed lookup failures do not. + +Use commit/release-pinned links for reproducible source and execution evidence. Maintained branch links are suitable for ongoing exploration. When both appear, explain which revision the runnable command verifies and that branch content can evolve; a branch link is not evidence that today's source was executed. Avoid duplicate destinations or repeated material unless the distinct revision or learning purpose matters. + +## Write for progressive learning + +Use the logical sequence **Purpose → Example → Outcome → Execution → Further exploration**. These are content roles, not five mandatory headings. Keep the concise explanation and meaningful C# first, state the observation and reproduction path, then offer optional depth in a short paragraph or small `Further exploration` section. Long execution blocks may remain in the existing immediately linked conceptual page or disclosure; source browsing is never a prerequisite for a working one-shot path. + +Explain what each reference adds, in its link text or adjacent sentence: omitted application setup, integration with a larger workflow, extra configuration, lifecycle ownership or verification technique. Replace “See GitHub for more information” with a specific reason to follow the link. Keep descriptions brief and factual, with no promotional language. + +- **Simple API:** a meaningful conversion or parsing example may need only purpose, C# and its result. Do not attach unrelated hosting or repository links. +- **Runnable integration:** retain its complete reproduction path and optionally link the composition root and functional test to show registration ownership or broader configuration. Successful execution does not make further reading redundant. +- **Non-standalone illustration:** state exactly what setup is omitted, where the code belongs, prerequisites and unverified behavior. Link the maintained implementation/test/project with a reason for each. Do not use this fallback when faithful standalone or repository-backed one-shot execution is available. Source-bound compilation and existing diagnostic gates still apply. + +## Principal example: ManagedApplicationFixture + +Explain on the page that `ManagedApplicationFixture` lets an xUnit fixture exercise the application's real entry point, with startup and service registration owned by that application. Preserve the meaningful `ApplicationTest` test, fixture injection, assertions and separate application/test assemblies. The [existing worker example and one-shot blocks](one-shot-examples.md) supply the concise usage, expected marker/environment/lifetime observations and complete reproduction without manual project assembly. + +After that example's outcome and execution guidance, optional exploration can read: + +> To see the application setup behind this test, explore the maintained [minimal worker entry point](https://github.com/codebeltnet/xunit/blob/main/app/Codebelt.Extensions.Xunit.Hosting.BootstrapperMinimalWorker.App/Program.cs): it constructs the host, registers the marker and hosted service, and runs the application. The corresponding [worker functional test](https://github.com/codebeltnet/xunit/blob/main/test/Codebelt.Extensions.Xunit.Hosting.FunctionalTests/BootstrapperMinimalWorkerApplicationTestTest.cs) shows how `ApplicationTest` and `ManagedApplicationFixture` resolve that application-owned marker and verify its value, the Development environment and host lifetime service. The [functional test project](https://github.com/codebeltnet/xunit/blob/main/test/Codebelt.Extensions.Xunit.Hosting.FunctionalTests/Codebelt.Extensions.Xunit.Hosting.FunctionalTests.csproj) shows the application/library project references and declared target frameworks; inspect its shared build settings for inherited runner and dependency configuration. + +These maintained branch links support exploration; the one-shot blocks and their evidence retain their exact pinned commit. Reinspect the branch targets before reusing this paragraph so its claims remain accurate. This is guidance for authoring the upstream page, not a claim that the published page has been changed. + +## Review boundary + +Human editorial review establishes whether a reference teaches useful depth and whether its explanation is accurate. Deterministic regressions can check exact destinations in curated fixtures, local source bindings, preserved links, C# structure, compilation and unchanged completion behavior. They must not infer educational value from word counts or keywords, crawl GitHub during fast validation, or treat a link as proof of execution. diff --git a/skills/dotnet-docfx-digest/references/example-architecture.md b/skills/dotnet-docfx-digest/references/example-architecture.md index 6cf5f906..27a22206 100644 --- a/skills/dotnet-docfx-digest/references/example-architecture.md +++ b/skills/dotnet-docfx-digest/references/example-architecture.md @@ -13,6 +13,8 @@ Before source generation, establish these facts from public contracts, implement Use the sequence **Discover API → Understand consumer task → Determine execution topology → Find authoritative usage → Design example → Write source → Validate → Improve explanation → Publish**. The reader should understand why, what must exist, how to use it, what happens, and how to check it, without requiring five headings on every page. +During that same discovery, consider optional [contextual source references](contextual-source-references.md) for useful integration or lifecycle depth. Explain the additional knowledge each link offers after the self-sufficient example, outcome and execution guidance. This applies to successfully runnable examples as well as partial illustrations; source browsing never replaces the primary learning experience. + ## Choose the execution model | Classification | Presentation and verification | diff --git a/skills/dotnet-docfx-digest/references/one-shot-examples.md b/skills/dotnet-docfx-digest/references/one-shot-examples.md index eee4e45c..0a41f3e8 100644 --- a/skills/dotnet-docfx-digest/references/one-shot-examples.md +++ b/skills/dotnet-docfx-digest/references/one-shot-examples.md @@ -1,6 +1,6 @@ # One-shot documentation examples -Lead with the developer task, the smallest informative C# example, how to run it, the expected outcome, and a maintained source link. Keep the API page understandable without execution. Put long execution blocks in an immediately linked conceptual page or disclosure when needed; no manual project assembly, helper installation, repository-layout knowledge or full project dumps. +Lead with the developer task, the smallest informative C# example, expected outcome, reproduction and optional further exploration. Keep the API page understandable without execution or external source reading. Follow [contextual source references](contextual-source-references.md): explain what selected links teach beyond the example, even when execution succeeds, and omit references that add no useful depth. Put long execution blocks in an immediately linked conceptual page or disclosure when needed; no manual project assembly, helper installation, repository-layout knowledge or full project dumps. ## Select and verify @@ -13,7 +13,7 @@ Lead with the developer task, the smallest informative C# example, how to run it ## ManagedApplicationFixture: actual worker startup -The maintained test demonstrates resolving the marker registered by the application's original entry point. It also asserts the Development environment and the availability of IHostApplicationLifetime. The fixture selects `typeof(TEntryPoint).Assembly`, so its application and executable xUnit test runner must retain separate assemblies. This is **repository-backed integration execution**, not an isolated csrun manifest. +Use `ManagedApplicationFixture` with `ApplicationTest` to verify services registered by an application's real entry point. Here the application builds and runs the host and registers a marker; the test resolves that marker and asserts its value. It also asserts the Development environment and the availability of IHostApplicationLifetime. The fixture selects `typeof(TEntryPoint).Assembly`, so its application and executable xUnit test runner must retain separate assemblies. This is **repository-backed integration execution**, not an isolated csrun manifest. The maintained test below belongs to the linked repository test project; it is not standalone source. Fixture injection and the base constructor retain the real application lifecycle. Run either complete block below to execute this exact test without assembling files: @@ -44,11 +44,11 @@ public class BootstrapperMinimalWorkerApplicationTestTest : ApplicationTest Date: Tue, 17 Nov 2026 16:52:28 +0100 Subject: [PATCH 33/95] =?UTF-8?q?=E2=9C=85=20add=20contextual=20reference?= =?UTF-8?q?=20eval=20cases=20for=20docfx?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds eval cases for optional source-reference depth: a simple API that should not gain arbitrary links, the worker fixture with successful execution, a partial excerpt with unavailable runtime evidence, and a rejected set of proposed references. The historical worker eval is renumbered to keep identifiers unique. --- skills/dotnet-docfx-digest/evals/evals.json | 59 ++++++++++++++++++++- 1 file changed, 57 insertions(+), 2 deletions(-) diff --git a/skills/dotnet-docfx-digest/evals/evals.json b/skills/dotnet-docfx-digest/evals/evals.json index 32828e34..dbac6d60 100644 --- a/skills/dotnet-docfx-digest/evals/evals.json +++ b/skills/dotnet-docfx-digest/evals/evals.json @@ -1261,14 +1261,69 @@ ] }, { - "id": 118, + "id": 123, "prompt": "Refine the ManagedApplicationFixture API example at https://xunit.codebelt.net/api/Codebelt.Extensions.Xunit.Hosting.ManagedApplicationFixture-1.html. Use codebeltnet/xunit test/Codebelt.Extensions.Xunit.Hosting.FunctionalTests/BootstrapperMinimalWorkerApplicationTestTest.cs. Give one-shot native and Docker commands that execute the original maintained test; do not modify that repository or invent a host.", "expected_output": "Classifies repository-backed integration, inspects the actual project graph and pinned source, and delivers two independent pinned-snapshot PowerShell blocks with positive exact-test execution verification and cleanup. Shows a concise meaningful excerpt and direct implementation/application/test/project links. Reports actual evidence separately per environment and preserves diagnostics if unavailable.", "expectations": [ "Preserves the original application implementation, project references, fixture lifecycle and assertions; no multi-project csrun schema or engine changes.", "Requires exact intended test identity, positive execution and pass counts plus process status; rejects wrong filters, zero tests and skipped tests.", "Both commands include all setup and cleanup and state prerequisites; unavailable environments or dependencies are explicitly unverified with diagnostics.", - "Fallback source links are used only when faithful execution is unavailable, without a verified runnable label." + "A source-only fallback is used only when faithful execution is unavailable, without a verified runnable label; optional further exploration can also accompany successful execution." + ] + }, + { + "id": 119, + "prompt": "Improve a DocFX page for a simple StockQuantity.Parse(string) API that converts text to an inventory quantity. Its existing complete C# example prints 42 from the input string and has a working one-shot execution pair. Repository discovery finds only the parser implementation and tests repeating this same conversion; there is no broader usage example adding useful context. Keep this page useful for a developer copying and adapting the example.", + "expected_output": "Keeps purpose, concise meaningful C#, expected result and existing executable reproduction. Does not add a Further exploration section or arbitrary repository links when the discovered material adds no educational depth. Retains existing compilation and completion gates.", + "expectations": [ + "The primary example is understandable without external reading and does not acquire unrelated setup or project scaffolding", + "No link quota or mandatory five-heading layout is imposed; duplicated conversion tests do not justify unnecessary references", + "Existing one-shot blocks, required C# usage, compilation and full DocFX completion requirements remain intact" + ] + }, + { + "id": 120, + "prompt": "Supplement the existing ManagedApplicationFixture worker example and its successful pinned native/Docker one-shot blocks with optional learning depth. Inspect https://github.com/codebeltnet/xunit/blob/main/app/Codebelt.Extensions.Xunit.Hosting.BootstrapperMinimalWorker.App/Program.cs, https://github.com/codebeltnet/xunit/blob/main/test/Codebelt.Extensions.Xunit.Hosting.FunctionalTests/BootstrapperMinimalWorkerApplicationTestTest.cs and https://github.com/codebeltnet/xunit/blob/main/test/Codebelt.Extensions.Xunit.Hosting.FunctionalTests/Codebelt.Extensions.Xunit.Hosting.FunctionalTests.csproj. Keep the principal usage understandable on the page. Do not edit the upstream repository.", + "expected_output": "Preserves the self-sufficient example, its expected assertions, assembly separation and verified reproduction. After outcome/execution guidance, adds short source references explaining omitted entry-point registration/startup, ApplicationTest/fixture verification and actual project references/frameworks. Distinguishes maintained branch exploration from the pinned execution revision without requiring repository browsing to run the example.", + "expectations": [ + "Inspects all new targets and accurately relates their contents to ManagedApplicationFixture and ApplicationTest", + "Explains the educational value of each selected reference rather than saying only see source or GitHub", + "Does not attribute inherited package/runner settings to explicit declarations in the project file", + "Successful runnable execution still permits optional exploration after purpose, essential C#, outcome and reproduction", + "Preserves pinned execution evidence, exact-test success checks and independent native/Docker blocks without expanding csrun manifest v1", + "Does not replace required local C# usage or compilation/completion gates with source links" + ] + }, + { + "id": 121, + "prompt": "Document a partial assertion from the attached InventoryWorker functional test, retaining a meaningful principal fixture example. The excerpt omits imports and fixture initialization. Offline project compilation is available, but runtime verification is unavailable in this environment. Explain what is omitted and offer optional maintained source context using the supplied application, test and project evidence. Do not claim the excerpt is independently executable or that compilation proves it ran; retain any existing working one-shot reproduction guidance.", + "files": [ + "scripts/fixtures/example-architecture/app/InventoryWorker/InventoryWorker.csproj", + "scripts/fixtures/example-architecture/app/InventoryWorker/Program.cs", + "scripts/fixtures/example-architecture/test/InventoryWorker.Tests/InventoryWorker.Tests.csproj", + "scripts/fixtures/example-architecture/test/InventoryWorker.Tests/InventoryWorkerTest.cs", + "scripts/fixtures/example-architecture/evidence.md" + ], + "expected_output": "Labels the partial excerpt and omitted containing context, retains essential fixture usage and assertions, and binds compilation to the supplied maintained source/project. Explains how application, functional test and project references teach registration/startup, fixture initialization and assembly ownership. Distinguishes compilation from unavailable runtime evidence and does not downgrade an available faithful one-shot path to source-only guidance.", + "expectations": [ + "States concrete omissions, prerequisites, containing project and runtime verification limitation on the page", + "Uses exact source/project bindings for the excerpt, preserving actual application-owned registration and entry point", + "Explains what readers gain from each selected maintained reference while leaving the main example understandable without visiting it", + "No invented upstream InventoryWorker path, dummy host, weakened assertion or new skip waiver is introduced", + "Unavailable local runtime verification does not remove working one-shot reproduction or relax the existing completion contract" + ] + }, + { + "id": 122, + "prompt": "Review a proposal to add source references to the existing worker fixture DocFX example. Proposed links include the maintained BootstrapperMinimalWorker Program.cs and corresponding functional test, an unrelated passing compression test, a guessed examples/ManagedWorkerDemo.cs path, and a generic repository homepage. The page already has valid pinned links and a Related: section; one existing historical URL lookup now times out. Select only useful verified additions, explain their learning value, and preserve required C# and execution guidance.", + "expected_output": "Reuses discovered authoritative evidence, inspects proposed targets, rejects unrelated and invented/unverified additions, avoids redundant homepage links and duplicate references, preserves valid pinned/Related content and the timed-out historical URL, and explains any useful new source reference after the self-contained example and execution path. Uses editorial judgment rather than adding network crawling or keyword quality rules to the fast validator.", + "expectations": [ + "No guessed path or unrelated test is added merely because it is in the same repository or passes", + "New source claims are backed by inspected contents and specific API relationships", + "Existing valid links and Related: content remain, and a timeout is not treated as confirmed HTTP 404", + "Repeated destinations are consolidated unless revision or learning value justifies both", + "C# target usage, one-shot reproduction, source-bound compilation and full DocFX completion checks remain required", + "Does not implement a second repository search subsystem, fast-path network checks or subjective keyword heuristics" ] } ] From 27981a9153a9f0e622915b35555168e3b8193f82 Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Tue, 17 Nov 2026 16:52:29 +0100 Subject: [PATCH 34/95] =?UTF-8?q?=F0=9F=90=9B=20exit=20cleanly=20after=20e?= =?UTF-8?q?xpected=20integration=20negative=20controls?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The integration artifact check deliberately triggers failing negative controls, which leave LASTEXITCODE nonzero. Exiting explicitly with zero means only real assertion failures fail this suite. --- skills/dotnet-docfx-digest/scripts/test-integration-example.ps1 | 2 ++ 1 file changed, 2 insertions(+) diff --git a/skills/dotnet-docfx-digest/scripts/test-integration-example.ps1 b/skills/dotnet-docfx-digest/scripts/test-integration-example.ps1 index 613213cd..7c46c5f8 100644 --- a/skills/dotnet-docfx-digest/scripts/test-integration-example.ps1 +++ b/skills/dotnet-docfx-digest/scripts/test-integration-example.ps1 @@ -84,3 +84,5 @@ foreach ($transport in @('Native', 'Docker')) { } } Write-Host "One-shot integration artifacts passed: $checks offline cases, published parity and PowerShell syntax (not live verification)." +# Expected negative controls leave LASTEXITCODE nonzero; only assertion failures fail this suite. +exit 0 From 0617f6ff433fdf3b205946689a870e64b5b2bac2 Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Tue, 17 Nov 2026 16:52:36 +0100 Subject: [PATCH 35/95] =?UTF-8?q?=E2=9C=85=20add=20contextual=20reference?= =?UTF-8?q?=20checks=20to=20docfx=20validation?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds a deterministic regression script for the contextual source reference guidance and registers it in the full DocFX validation suite, so the optional-depth rules are enforced alongside the existing one-shot example checks. --- scripts/validate-skill-templates.ps1 | 4 + .../scripts/test-contextual-references.ps1 | 152 ++++++++++++++++++ 2 files changed, 156 insertions(+) create mode 100644 skills/dotnet-docfx-digest/scripts/test-contextual-references.ps1 diff --git a/scripts/validate-skill-templates.ps1 b/scripts/validate-skill-templates.ps1 index 654ea23e..d955e8c9 100644 --- a/scripts/validate-skill-templates.ps1 +++ b/scripts/validate-skill-templates.ps1 @@ -3862,6 +3862,10 @@ Add-ValidationResult -Results $results -Name 'Rendered library templates leave n if ($Full -and $Suite -in @('All', 'Docfx')) { $docfxScriptResults = Invoke-ValidationScriptJobs -Scripts @( + [pscustomobject]@{ + Name = 'DocFX contextual references complement examples without bypassing validation' + Path = Join-Path $repoRoot 'skills/dotnet-docfx-digest/scripts/test-contextual-references.ps1' + } [pscustomobject]@{ Name = 'DocFX one-shot integration examples enforce exact test execution' Path = Join-Path $repoRoot 'skills/dotnet-docfx-digest/scripts/test-integration-example.ps1' diff --git a/skills/dotnet-docfx-digest/scripts/test-contextual-references.ps1 b/skills/dotnet-docfx-digest/scripts/test-contextual-references.ps1 new file mode 100644 index 00000000..26a36dd2 --- /dev/null +++ b/skills/dotnet-docfx-digest/scripts/test-contextual-references.ps1 @@ -0,0 +1,152 @@ +#requires -Version 7.0 +param([string]$ValidatorPath = (Join-Path $PSScriptRoot 'docfx.cs')) + +$ErrorActionPreference = 'Stop' +Set-StrictMode -Version Latest +$PSNativeCommandUseErrorActionPreference = $false +$helper = Join-Path $PSScriptRoot '../../../scripts/file-based-app.ps1' +if (Test-Path -LiteralPath $helper -PathType Leaf) { + . $helper +} else { + function Get-FileBasedAppCommand { + param([string]$SourcePath) + [pscustomobject]@{ Executable = 'dotnet'; ArgumentPrefix = @('run', '--file', $SourcePath, '--') } + } +} +$validator = Get-FileBasedAppCommand -SourcePath $ValidatorPath +$workspace = Join-Path ([IO.Path]::GetTempPath()) ('docfx-references-' + [guid]::NewGuid().ToString('N')) +$utf8 = [Text.UTF8Encoding]::new($false) +function Write-Fixture([string]$Path, [string]$Content) { + $target = Join-Path $workspace $Path + $null = New-Item -ItemType Directory -Path (Split-Path $target -Parent) -Force + [IO.File]::WriteAllText($target, $Content, $utf8) +} +function Invoke-Check([string[]]$ExtraArgs = @()) { + $output = & $validator.Executable @($validator.ArgumentPrefix + @('--repo-root', $workspace, '--json', '--quiet') + $ExtraArgs) 2>$null | Out-String + $exitCode = $LASTEXITCODE + if ($exitCode -notin @(0, 1)) { throw "Validator failed with exit ${exitCode}: $output" } + $output.Substring($output.IndexOf('{')) | ConvertFrom-Json +} +function Assert-NoSampleErrors($Report) { + $failures = @($Report.errors | Where-Object { $_.code -like 'SAMPLE_*' -or $_.code -like 'EXAMPLE_*' }) + if ($failures.Count) { throw ($failures | ConvertTo-Json -Depth 5) } +} + +# Curated reference destinations protect this authored example from path drift or unrelated links. +# This is offline golden-data verification, not a general URL or editorial-quality analyzer. +$revision = '84b13767cb9484f8f3a36a71875662edfdb3e511' +$usagePaths = @( + 'app/Codebelt.Extensions.Xunit.Hosting.BootstrapperMinimalWorker.App/Program.cs' + 'test/Codebelt.Extensions.Xunit.Hosting.FunctionalTests/BootstrapperMinimalWorkerApplicationTestTest.cs' + 'test/Codebelt.Extensions.Xunit.Hosting.FunctionalTests/Codebelt.Extensions.Xunit.Hosting.FunctionalTests.csproj' +) +foreach ($entry in @( + @{ File = 'contextual-source-references.md'; Ref = 'main'; Paths = $usagePaths } + @{ File = 'one-shot-examples.md'; Ref = $revision; Paths = $usagePaths + 'src/Codebelt.Extensions.Xunit.Hosting/ManagedApplicationFixture.cs' } +)) { + $content = Get-Content (Join-Path $PSScriptRoot "../references/$($entry.File)") -Raw + $actual = @([regex]::Matches($content, '\]\((https://github\.com/[^)]+)\)') | ForEach-Object { $_.Groups[1].Value } | Sort-Object) + $expected = @($entry.Paths | ForEach-Object { "https://github.com/codebeltnet/xunit/blob/$($entry.Ref)/$_" } | Sort-Object) + if (($actual -join "`n") -cne ($expected -join "`n")) { throw "Curated source references changed in $($entry.File). Inspect targets and update the evidence deliberately." } +} + +try { + Write-Fixture 'src/Inventory.csproj' 'net10.0' + Write-Fixture 'src/StockQuantity.cs' @' +namespace Acme.Inventory; +public sealed record StockQuantity(int Value) +{ + public static StockQuantity Parse(string text) => new(int.Parse(text)); +} +'@ + Write-Fixture 'samples/Quantity/Quantity.csproj' 'net10.0Exe' + Write-Fixture 'samples/Quantity/Program.cs' @' +using System; +using Acme.Inventory; +Console.WriteLine(StockQuantity.Parse(args.Length == 0 ? "42" : args[0]).Value); +'@ + Write-Fixture '.docfx/docfx.json' @' +{"metadata":[{"src":[{"src":"../","files":["src/Inventory.csproj"]}],"dest":"api","properties":{"TargetFramework":"net10.0"}}],"build":{"content":[{"files":["*.md"],"exclude":["api/namespaces/**","api/types/**"]}],"overwrite":[{"files":["api/namespaces/**/*.md","api/types/**/*.md"]}],"dest":"_site"}} +'@ + Write-Fixture '.docfx/api/namespaces/Acme.Inventory.md' @' +--- +uid: Acme.Inventory +summary: *content +--- +Parse inventory quantities from text before reporting stock levels. Use `StockQuantity.Parse` to obtain the numeric value for a stock report. + +Available on .NET 10.0. +'@ + $page = '.docfx/api/types/Acme.Inventory.StockQuantity.md' + $header = "---`nuid: Acme.Inventory.StockQuantity`nexample:`n- *content`n---`n" + $simple = @' +Parse a stock quantity from text and print its numeric value. + +```csharp +// Program.cs +using System; +using Acme.Inventory; +Console.WriteLine(StockQuantity.Parse("42").Value); +``` + +Expected output: `42`. +'@ + Write-Fixture $page ($header + $simple) + $plain = Invoke-Check + Assert-NoSampleErrors $plain + foreach ($process in @('dotnet', 'msbuild', 'docfx', 'gh')) { + if ($plain.summary.processes.$process -ne 0) { throw "Fast reference checks started $process." } + } + + $related = 'Related: [quantity implementation](../../../src/StockQuantity.cs).' + $exploration = @' +### Further exploration + +The maintained [quantity application](../../../samples/Quantity/Program.cs) accepts command-line input as well as the default value. Its [project](../../../samples/Quantity/Quantity.csproj) shows how a console consumer references the inventory library. +'@ + $runnable = $header + $simple + "`n`nRun the maintained application with ``dotnet run --project samples/Quantity/Quantity.csproj -- 42`` from the repository root using the .NET 10 SDK.`n`n$exploration`n`n$related`n" + Write-Fixture $page $runnable + $before = [IO.File]::ReadAllBytes((Join-Path $workspace $page)) + $compiled = Invoke-Check @('--validate-samples') + Assert-NoSampleErrors $compiled + if ($compiled.summary.samplesCompiled -ne 1) { throw 'Linked runnable sample did not compile.' } + if ($compiled.summary.canClaimCompletion -or $compiled.summary.fullVerificationRan -or $compiled.summary.remainingGates.Count -eq 0) { throw 'Source links bypassed full DocFX verification.' } + $output = & dotnet run --project (Join-Path $workspace 'samples/Quantity/Quantity.csproj') --disable-build-servers -- 42 2>&1 | Out-String + if ($LASTEXITCODE -ne 0 -or $output.Trim() -cne '42') { throw "Runnable exploration example failed: $output" } + if ([Convert]::ToHexString($before) -cne [Convert]::ToHexString([IO.File]::ReadAllBytes((Join-Path $workspace $page)))) { throw 'Validation modified the sample or existing Related links.' } + + # An honest excerpt retains its maintained project context and limitations. + $partial = @' +This non-standalone excerpt prints the parsed quantity inside the maintained console application. It omits imports and command-line setup, requires the .NET 10 SDK and referenced inventory project, and is compiled in that project context; no execution of this excerpt is claimed. + +```csharp +// docfx-context: samples/Quantity/Quantity.csproj +// docfx-source: samples/Quantity/Program.cs +Console.WriteLine(StockQuantity.Parse(args.Length == 0 ? "42" : args[0]).Value); +``` + +Expected output with no arguments: `42`. +'@ + Write-Fixture $page ($header + $partial + "`n`n$exploration`n`n$related`n") + $bound = Invoke-Check @('--validate-samples') + Assert-NoSampleErrors $bound + if ($bound.summary.samplesCompiled -ne 1) { throw 'Partial source context was not compiled.' } + + # Optional references never fulfill the C# obligation or hide a compiler failure. + Write-Fixture $page ($header + "Read the maintained application to parse stock quantities.`n`n$exploration`n`n$related`n") + $linksOnly = Invoke-Check + if (-not @($linksOnly.errors | Where-Object code -eq 'EXAMPLE_MISSING').Count) { throw 'Links replaced required C#.' } + Write-Fixture $page ($runnable.Replace('StockQuantity.Parse("42")', 'StockQuantity.Missing("42")')) + $broken = Invoke-Check @('--validate-samples') + if (-not @($broken.errors | Where-Object code -eq 'SAMPLE_COMPILE_FAILED').Count) { throw 'Links bypassed compilation.' } + Write-Host 'DocFX contextual references passed: curated destinations, concise/runnable/partial examples, Related preservation, missing C#, compile failure and completion gates (offline links; editorial value requires review).' +} +finally { + $resolved = [IO.Path]::GetFullPath($workspace) + $temp = [IO.Path]::GetFullPath([IO.Path]::GetTempPath()).TrimEnd('/','\') + [IO.Path]::DirectorySeparatorChar + if (-not $resolved.StartsWith($temp, [StringComparison]::OrdinalIgnoreCase)) { throw 'Unsafe fixture cleanup path.' } + if (Test-Path -LiteralPath $resolved) { Remove-Item -LiteralPath $resolved -Recurse -Force } +} + +# The last native command is an expected compiler failure. Assertions determine suite success. +exit 0 From 5a7b22a4dada0cebdf31da1bde8ae89803a0bc31 Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Tue, 17 Nov 2026 16:52:37 +0100 Subject: [PATCH 36/95] =?UTF-8?q?=F0=9F=93=9D=20mention=20contextual=20sou?= =?UTF-8?q?rce=20references=20in=20readme?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The DocFX digest feature list now describes optional source references that follow the principal example, keeping the README aligned with the skill's current behavior. --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 374ae397..4b5a904a 100644 --- a/README.md +++ b/README.md @@ -712,6 +712,7 @@ API documentation rots the moment code changes. A new public type ships without - **Managed-reference-safe overwrite layout** — public non-abstraction types and public extension methods must have examples in DocFX overwrite content included by `build.overwrite`; the validator discovers Markdown from configured DocFX inputs instead of scanning the whole repository when `docfx.json` is at the root, concrete-type examples are tracked through an explicit inventory and created in readable authored files under `.docfx/api/types/`, legacy authored `.docfx/api/*.md` overwrite files move into `api/namespaces/` or `api/types/` instead of widening the glob to `api/**/*.md`, both overwrite trees stay excluded from `build.content`, C# extension-block compiler containers such as `$...` are collapsed back to the authored outer static class, extension-method examples default to readable declaring-class type pages under `.docfx/api/types/` instead of URL-encoded method-UID filenames or namespace pages that mix overview and member UIDs, namespace pages fail validation when they embed secondary `uid:` / `example:` sections, and agents must rerun the completion repair loop until diagnostics and overwrite-layout failures are fixed or exact blockers are reported, - **Concept-led namespace quality** — moving concrete examples to type pages must not hollow out namespace pages; namespace pages still need newcomer-oriented fly-ins that explain the problem solved, when to use the namespace, where to start, type-family context, extension-method group explanations, availability, and pointers to representative type pages, and nearby type/member summaries should stay purpose-first too, - **Examples that teach a real workflow** — examples start from package IDs and package-level evidence before falling back to type/member-only searches, prefer README, package docs, tooling, tuning, functional-test, and external GitHub usage when available, may include multiple related public types when that is what makes the consumer scenario understandable, keep extension-container prose focused on what callers can do with the receiver instead of on declaration syntax, discover public acquisition paths from signatures, docs, tests, and other evidence instead of assuming direct construction from implementation details, and rewrite copied test evidence into lean consumer-facing code rather than dragging obvious framework FQNs into the sample body, +- **Optional depth after immediate learning** — examples explain purpose, essential usage, outcome and reproduction before offering precise maintained source references with a brief reason to explore each. Existing discovery supplies those links, including for runnable examples; simple APIs stay concise. Links complement required C#, one-shot execution and compilation/completion gates, and existing valid links and `Related:` sections remain preserved, - **Examples arrive with context** — design starts with the developer task, prerequisites, execution topology and observable result. Library snippets stay concise; standalone programs, genuine framework tests, multi-project integrations and partial excerpts use their actual execution context. Project-bound fences match maintained source, revalidate when their source/project changes, and require an active region under actual compiler symbols. Native per-project build evidence preserves successful samples when an unrelated sample fails. Human fly-ins explain setup and outcome, and compilation, runtime evidence and architectural review remain distinct, - **Semantic example quality gates** — compilation-valid filler no longer passes: the validator rejects duplicate UID mappings, `Type.GetType`/assembly metadata scaffolds, runtime implementation names presented as outcomes (`EXAMPLE_RUNTIME_TYPE_NAME_OUTCOME`), empty local `Program` stubs in conventionally named application-entry-point samples such as `AppFactory`, `WebTestFactory`, or `HostFixture` (`EXAMPLE_EMPTY_ENTRY_POINT_STUB`) while excluding unrelated names such as `ApplicationRepositoryFactory`, generic `DocumentedTypeExample`/`Describe()` templates, type examples that never use the target in code, extension examples that mention a method only in prose instead of invoking it, examples without a human fly-in (`EXAMPLE_LEAD_MISSING`), advanced examples with shallow setup context (`EXAMPLE_ADVANCED_LEAD_MISSING`), `default!`/`null!` holder properties (`EXAMPLE_DEFAULT_PLACEHOLDER`), classes that only construct or return the target with no observable result (`EXAMPLE_NO_OBSERVABLE_OUTCOME`), mass-forwarding shells of one-line pass-throughs (`EXAMPLE_FORWARDING_SCAFFOLD`), one normalized code skeleton reused across three or more unrelated targets (`EXAMPLE_TEMPLATE_REPETITION`), and avoidable `System.*` / `Microsoft.*` fully qualified framework references in executable sample code (`EXAMPLE_FULLY_QUALIFIED_FRAMEWORK_TYPE`), - **Key-entry-point storytelling** — namespace guidance starts from release notes, package documentation, public factories/builders, and strong functional tests so new product-defining APIs are not buried beneath naming conventions. When a package complements an upstream framework type, the skill compares acquisition, customization, lifecycle, sharing, and observable outcomes from current official guidance instead of making unsupported replacement claims, From a977762f37aedeec0527cf08c620827d7f3c9fd9 Mon Sep 17 00:00:00 2001 From: gimlichael Date: Tue, 17 Nov 2026 16:55:16 +0100 Subject: [PATCH 37/95] =?UTF-8?q?=E2=9C=A8=20add=20contextual=20source=20r?= =?UTF-8?q?eferences=20and=20one-shot=20examples=20to=20docfx?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c506d5df..5215b696 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), ## [0.13.0] - 2026-11-17 -This is a minor release that adds the `dotnet-csrun` skill for executable C# evidence, binds `dotnet-docfx-digest` samples to maintained project and source context, and connects standalone runtime examples to `dotnet-csrun`. +This is a minor release that adds the `dotnet-csrun` skill for executable C# evidence, binds `dotnet-docfx-digest` samples to maintained project and source context, adds contextual source references and repository-backed one-shot examples to `dotnet-docfx-digest`, and connects standalone runtime examples to `dotnet-csrun`. ### Added @@ -14,10 +14,13 @@ This is a minor release that adds the `dotnet-csrun` skill for executable C# evi - `dotnet-csrun` verify, repair, and scoped audit lifecycle for existing standalone source, with feasibility assessed before manifest construction and failures classified before any repair, - `dotnet-docfx-digest` source-bound sample contexts that bind fences to a maintained project and source file, reject unresolvable bindings, revalidate pages whose bound source or project changes, including deleted or moved inputs, and skip `.bot` directories during source discovery, - `dotnet-docfx-digest` rejection of a `ManagedApplicationFixture` entry point collapsed into a test-owned source unit, and of displayed excerpts excluded by conditional compilation for the selected framework and configuration, -- `dotnet-csrun` README entry, install example, deterministic validators, and eval fixtures, plus `dotnet-docfx-digest` regression coverage for source-bound samples. +- `dotnet-docfx-digest` optional contextual source references that link maintained source after each example's immediate explanation, with contextual reference checks in its validation, +- `dotnet-docfx-digest` repository-backed one-shot examples that pin a maintained test or application project when an API requires an actual application, runner, or distinct assembly identity instead of a standalone program, +- `dotnet-csrun` README entry, install example, deterministic validators, and eval fixtures, plus `dotnet-docfx-digest` regression coverage for source-bound samples and contextual references. ### Changed +- `dotnet-docfx-digest` example authoring chooses standalone programs, library usage, multi-project scenarios, framework integrations, or labelled partial excerpts from the actual execution context instead of treating every generated C# fence as a complete compilation unit, - `dotnet-docfx-digest` composes with `dotnet-csrun` for compatible standalone runtime examples, keeping its source discovery, placement, project-aware compilation, and DocFX build gates authoritative and leaving project-dependent examples in the existing workflow. ### Fixed From 18490d18cacb4063b5234ea93eca46980f595377 Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Tue, 17 Nov 2026 17:16:05 +0100 Subject: [PATCH 38/95] =?UTF-8?q?=F0=9F=90=9B=20keep=20docker=20build=20ou?= =?UTF-8?q?tput=20removable=20on=20linux?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Docker integration example ran the SDK container as root, so bind-mounted bin and obj output could not be removed by the host user on Linux. Run the container as the host UID and GID with a writable container home, and update the published block and its reference to match. --- .../references/one-shot-examples.md | 19 +++++++++++++++---- .../scripts/integration-example.ps1 | 11 ++++++++++- 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/skills/dotnet-docfx-digest/references/one-shot-examples.md b/skills/dotnet-docfx-digest/references/one-shot-examples.md index 0a41f3e8..3b06a0aa 100644 --- a/skills/dotnet-docfx-digest/references/one-shot-examples.md +++ b/skills/dotnet-docfx-digest/references/one-shot-examples.md @@ -107,7 +107,7 @@ Failure throws and retains logs/results under the printed OS-temporary diagnosti ## Docker: PowerShell 7 and Docker with Linux containers -No host .NET SDK is required. The official SDK image supplies it; first use pulls the image. +No host .NET SDK is required. The official SDK image supplies it; first use pulls the image. On Linux, the container runs with the host UID and GID so build and test outputs remain removable during cleanup. Its home and .NET CLI state use container-local `/tmp`, which is writable by that identity. ```powershell #requires -Version 7.0 @@ -128,7 +128,16 @@ No host .NET SDK is required. The official SDK image supplies it; first use pull Move-Item -LiteralPath "$work/extracted/xunit-$commit" -Destination "$work/repo" $project = 'test/Codebelt.Extensions.Xunit.Hosting.FunctionalTests/Codebelt.Extensions.Xunit.Hosting.FunctionalTests.csproj' $test = 'Codebelt.Extensions.Xunit.Hosting.BootstrapperMinimalWorkerApplicationTestTest.ShouldBootstrapMinimalWorkerProgram' - docker run --rm --mount "type=bind,source=$work,target=/work" --workdir /work/repo mcr.microsoft.com/dotnet/sdk:11.0 dotnet run --project $project --framework net11.0 -p:SkipSignAssembly=true -- --filter-method $test --report-xunit-xml --report-xunit-xml-filename result.xml --results-directory /work/results 2>&1 | Tee-Object -FilePath "$work/run.log" + $dockerUser = @() + if ($IsLinux) { + # Keep bind-mounted build output removable by the host user. + $hostUid = id -u + if ($LASTEXITCODE -ne 0) { throw 'Cannot resolve host UID.' } + $hostGid = id -g + if ($LASTEXITCODE -ne 0) { throw 'Cannot resolve host GID.' } + $dockerUser = @('--user', "${hostUid}:${hostGid}") + } + docker run --rm @dockerUser --env HOME=/tmp --env DOTNET_CLI_HOME=/tmp --mount "type=bind,source=$work,target=/work" --workdir /work/repo mcr.microsoft.com/dotnet/sdk:11.0 dotnet run --project $project --framework net11.0 -p:SkipSignAssembly=true -- --filter-method $test --report-xunit-xml --report-xunit-xml-filename result.xml --results-directory /work/results 2>&1 | Tee-Object -FilePath "$work/run.log" $code = $LASTEXITCODE if ($code -ne 0) { throw "Repository test failed with exit code $code. See $work/run.log" } # Require exactly the original test, executed and passing, with no runner errors. @@ -170,8 +179,10 @@ Maintainers generate both blocks with [integration-example.ps1](../scripts/integ ## Observed verification, 2026-11-17 -Both complete blocks above were executed in fresh PowerShell processes from fresh archive downloads. Native Windows x64 used SDK 11.0.100/runtime 11.0.0. Linux Docker used official SDK 11.0.100/runtime 11.0.0, observed image digest `mcr.microsoft.com/dotnet/sdk@sha256:65f3c7c6a25a239ab3e6719f2896147e7b68242ff2d8818dd70498bde6ef8bea`. Each exited 0 after checking the XML report for exactly the named test passing: total 1, succeeded 1, failed/skipped 0. The image tag remains mutable; this is evidence of the tested image, not future tag contents. +Before the UID/GID cleanup fix, both execution blocks were executed in fresh PowerShell processes from fresh archive downloads. Native Windows x64 used SDK 11.0.100/runtime 11.0.0. Linux Docker used official SDK 11.0.100/runtime 11.0.0, observed image digest `mcr.microsoft.com/dotnet/sdk@sha256:65f3c7c6a25a239ab3e6719f2896147e7b68242ff2d8818dd70498bde6ef8bea`. Each exited 0 after checking the XML report for exactly the named test passing: total 1, succeeded 1, failed/skipped 0. The image tag remains mutable; this is evidence of the tested image, not future tag contents. A separate native negative run replaced only the filter with `DoesNotExist.NoSuchTest`: MTP reported zero tests and exit 8; the block threw (PowerShell exit 1), retained log/XML diagnostics outside the repository, and removed the downloaded workspace. The initial long-path launch failed before execution on Windows; the published blocks use a short temporary root and rename the archive root before building. No application source or assertion was changed. -Focused deterministic checks: `pwsh -NoProfile -File skills/dotnet-docfx-digest/scripts/test-integration-example.ps1` checks published parity, PowerShell parsing and 17 offline cases covering exact passing identity, wrong identity, zero tests, skips, runner errors, missing reports, missing dependencies, missing commands and unavailable Docker daemon. Offline doubles prove wrapper checks, not integration behavior. Existing `test-quality.ps1` retains source-backed compilation, architecture diagnostics and real application/standalone/middleware controls. These checks do not replace `agents.cs` or the build-backed DocFX completion gates when editing a target documentation repository. This change does not modify codebeltnet/xunit or claim the published API page was repaired. +The UID/GID fix was checked with a Linux Docker volume shared by SDK containers running as numeric UID:GID `1234:5678`: a console build ran successfully, and a separate non-root PowerShell process confirmed `bin` and `obj` ownership and removed the workspace. Both that build command and a full Docker-block retest remained running after printing their successful application/test output, even after explicit build-server shutdown, and were stopped. The full retest reported one passing integration test but ended with container exit 137; the wrapper retained diagnostics and removed its downloaded source. This confirms the focused ownership/cleanup smoke check, not a successful end-to-end rerun of the published block. + +Focused deterministic checks: `pwsh -NoProfile -File skills/dotnet-docfx-digest/scripts/test-integration-example.ps1` checks published parity, PowerShell parsing and 28 offline cases covering exact passing test identity, wrong identity, zero tests, skips, runner errors, missing reports, missing dependencies, missing commands, unavailable Docker daemon, Linux UID/GID forwarding, writable container home settings and identity lookup failures. Both Linux and non-Linux Docker branches are exercised on every host. Offline doubles prove wrapper checks, not integration behavior. Existing `test-quality.ps1` retains source-backed compilation, architecture diagnostics and real application/standalone/middleware controls. These checks do not replace `agents.cs` or the build-backed DocFX completion gates when editing a target documentation repository. This change does not modify codebeltnet/xunit or claim the published API page was repaired. diff --git a/skills/dotnet-docfx-digest/scripts/integration-example.ps1 b/skills/dotnet-docfx-digest/scripts/integration-example.ps1 index e1eaef03..a46a5a0a 100644 --- a/skills/dotnet-docfx-digest/scripts/integration-example.ps1 +++ b/skills/dotnet-docfx-digest/scripts/integration-example.ps1 @@ -57,7 +57,16 @@ Push-Location "$work/repo" finally { Pop-Location } '@ $docker = @' -docker run --rm --mount "type=bind,source=$work,target=/work" --workdir /work/repo mcr.microsoft.com/dotnet/sdk:11.0 dotnet run --project $project --framework net11.0 -p:SkipSignAssembly=true -- --filter-method $test --report-xunit-xml --report-xunit-xml-filename result.xml --results-directory /work/results 2>&1 | Tee-Object -FilePath "$work/run.log" +$dockerUser = @() + if ($IsLinux) { + # Keep bind-mounted build output removable by the host user. + $hostUid = id -u + if ($LASTEXITCODE -ne 0) { throw 'Cannot resolve host UID.' } + $hostGid = id -g + if ($LASTEXITCODE -ne 0) { throw 'Cannot resolve host GID.' } + $dockerUser = @('--user', "${hostUid}:${hostGid}") + } + docker run --rm @dockerUser --env HOME=/tmp --env DOTNET_CLI_HOME=/tmp --mount "type=bind,source=$work,target=/work" --workdir /work/repo mcr.microsoft.com/dotnet/sdk:11.0 dotnet run --project $project --framework net11.0 -p:SkipSignAssembly=true -- --filter-method $test --report-xunit-xml --report-xunit-xml-filename result.xml --results-directory /work/results 2>&1 | Tee-Object -FilePath "$work/run.log" '@ [pscustomobject]@{ Native = $template.Replace('__PREREQUISITE__', "`$null = Get-Command dotnet -ErrorAction Stop").Replace('__EXECUTE__', $native) From 03274ab84f7560bd03ea600886a384ea6702f90c Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Tue, 17 Nov 2026 17:16:12 +0100 Subject: [PATCH 39/95] =?UTF-8?q?=E2=9C=85=20cover=20linux=20docker=20uid?= =?UTF-8?q?=20and=20gid=20branches?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Offline doubles now exercise both the Linux and non-Linux Docker branches on every host. They check UID and GID forwarding, the writable container home variables, and identity lookup failures, so the published block cannot drift from its verified form silently. --- .../scripts/test-integration-example.ps1 | 46 ++++++++++++++++--- 1 file changed, 39 insertions(+), 7 deletions(-) diff --git a/skills/dotnet-docfx-digest/scripts/test-integration-example.ps1 b/skills/dotnet-docfx-digest/scripts/test-integration-example.ps1 index 7c46c5f8..1e0dd535 100644 --- a/skills/dotnet-docfx-digest/scripts/test-integration-example.ps1 +++ b/skills/dotnet-docfx-digest/scripts/test-integration-example.ps1 @@ -10,14 +10,17 @@ $source = [regex]::Match($document, '(?s)```csharp\r?\n(.*?)\r?\n```').Groups[1] $sourceHash = [Convert]::ToHexString([Security.Cryptography.SHA256]::HashData([Text.Encoding]::UTF8.GetBytes($source))) if ($sourceHash -cne '47B0C1FBA94E7B43C8753D0A8242801B328E6B463B6EEDAEB640D4F8A262633E') { throw 'Displayed test differs from the original maintained source.' } $checks = 0 -foreach ($transport in @('Native', 'Docker')) { +foreach ($transport in @('Native', 'Docker', 'DockerLinux')) { + $artifact = if ($transport -eq 'Native') { 'Native' } else { 'Docker' } + $simulateLinux = $transport -eq 'DockerLinux' $index = if ($transport -eq 'Native') { 0 } else { 1 } - if ($blocks[$index].Groups[1].Value.Replace("`r`n", "`n") -cne $pair.$transport.Replace("`r`n", "`n")) { throw "Published $transport block drifted." } + if ($blocks[$index].Groups[1].Value.Replace("`r`n", "`n") -cne $pair.$artifact.Replace("`r`n", "`n")) { throw "Published $artifact block drifted." } $tokens = $null; $errors = $null - $null = [Management.Automation.Language.Parser]::ParseInput($pair.$transport, [ref] $tokens, [ref] $errors) + $null = [Management.Automation.Language.Parser]::ParseInput($pair.$artifact, [ref] $tokens, [ref] $errors) if ($errors.Count) { throw "Invalid PowerShell: $errors" } $scenarios = @('pass', 'wrong-test', 'zero', 'skip', 'runner-error', 'missing-report', 'dependency', 'environment') - if ($transport -eq 'Docker') { $scenarios += 'daemon' } + if ($artifact -eq 'Docker') { $scenarios += 'daemon' } + if ($simulateLinux) { $scenarios += @('uid', 'gid') } foreach ($scenario in $scenarios) { & { # Offline doubles exercise the complete published block; never evidence of live tests. @@ -48,18 +51,47 @@ foreach ($transport in @('Native', 'Docker')) { if ($transport -ne 'Native') { throw 'Docker block required a host SDK.' } Invoke-TestDouble } + function id { + $flag = $args[0] + if (-not $simulateLinux) { throw 'Non-Linux block required Unix identity lookup.' } + $global:LASTEXITCODE = 0 + if ($flag -eq '-u') { + if ($scenario -eq 'uid') { $global:LASTEXITCODE = 1; return } + return '1234' + } + if ($flag -eq '-g') { + if ($scenario -eq 'gid') { $global:LASTEXITCODE = 1; return } + return '5678' + } + throw "Unexpected identity lookup: $flag" + } function docker { - if ($transport -ne 'Docker') { throw 'Native block required Docker.' } + if ($artifact -ne 'Docker') { throw 'Native block required Docker.' } if ($args[0] -eq 'info') { $global:LASTEXITCODE = if ($scenario -eq 'daemon') { 1 } else { 0 }; return } + $dockerRuns.Add(@($args)) + $imageIndex = [array]::IndexOf($args, 'mcr.microsoft.com/dotnet/sdk:11.0') + $options = @($args[0..($imageIndex - 1)]) + $userIndex = [array]::IndexOf($options, '--user') + if ($simulateLinux) { + if ($userIndex -lt 0 -or $options[$userIndex + 1] -cne '1234:5678') { throw 'Container must use the host UID:GID on Linux.' } + } + elseif ($userIndex -ge 0) { throw 'Non-Linux block should keep the Docker Desktop user default.' } + foreach ($value in @('HOME=/tmp', 'DOTNET_CLI_HOME=/tmp')) { + $valueIndex = [array]::IndexOf($options, $value) + if ($valueIndex -le 0 -or $options[$valueIndex - 1] -cne '--env') { throw "Missing writable container home: $value" } + } Invoke-TestDouble } $failed = $false $warnings = [Collections.Generic.List[string]]::new() $workspaces = [Collections.Generic.List[string]]::new() + $dockerRuns = [Collections.Generic.List[object]]::new() function Write-Warning { param($Message) $warnings.Add($Message) } - try { & ([scriptblock]::Create($pair.$transport)) | Out-Null } - catch { $failed = $true } + # Exercise both OS branches on every host without changing its read-only $IsLinux. + try { & ([scriptblock]::Create($pair.$artifact.Replace('$IsLinux', '$simulateLinux'))) | Out-Null } + catch { if ($scenario -eq 'pass') { throw }; $failed = $true } if ($failed -ne ($scenario -ne 'pass')) { throw "$transport/$scenario did not enforce verification." } + if ($scenario -in @('uid', 'gid') -and $dockerRuns.Count -ne 0) { throw 'Identity lookup failure started a container.' } foreach ($workspace in $workspaces) { if (Test-Path -LiteralPath $workspace) { throw 'Downloaded workspace leaked.' } } From b0a0d38769fa2917189c344e7c8eeca58a8106dd Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Tue, 17 Nov 2026 21:50:36 +0100 Subject: [PATCH 40/95] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20generalize=20reposit?= =?UTF-8?q?ory=20example=20pair=20generation?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The pinned repository example generator was hardcoded to one xunit test. Parameterizing repository, commit, project, test, framework and image lets the run actions generator reuse the same verified pattern for other examples, while the published example stays unchanged through a compatibility wrapper. --- .../scripts/integration-example.ps1 | 38 +++++++++++++++---- 1 file changed, 30 insertions(+), 8 deletions(-) diff --git a/skills/dotnet-docfx-digest/scripts/integration-example.ps1 b/skills/dotnet-docfx-digest/scripts/integration-example.ps1 index a46a5a0a..ca79c981 100644 --- a/skills/dotnet-docfx-digest/scripts/integration-example.ps1 +++ b/skills/dotnet-docfx-digest/scripts/integration-example.ps1 @@ -1,6 +1,20 @@ #requires -Version 7.0 # Artifact generation only: no downloads, builds or test execution when dot-sourced. -function New-ManagedApplicationExamplePair { +function New-RepositoryExamplePair { + param( + [Parameter(Mandatory)][string] $Repository, + [Parameter(Mandatory)][string] $Commit, + [Parameter(Mandatory)][string] $Project, + [Parameter(Mandatory)][string] $Test, + [Parameter(Mandatory)][string] $Framework, + [Parameter(Mandatory)][string] $Image + ) + if ($Repository -notmatch '^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$' -or $Commit -notmatch '^[a-fA-F0-9]{40}$' -or + $Project -notmatch '^[A-Za-z0-9_./-]+\.csproj$' -or $Project.Split('/') -contains '..' -or $Project.StartsWith('/') -or + $Test -notmatch '^[A-Za-z0-9_.+]+$' -or $Framework -notmatch '^net\d+\.\d+$' -or + $Image -notmatch '^mcr\.microsoft\.com/dotnet/sdk:[A-Za-z0-9_.-]+$') { + throw 'Expected a pinned GitHub repository, relative project, exact xUnit method, TFM and official SDK image.' + } $template = @' #requires -Version 7.0 & { @@ -12,12 +26,12 @@ function New-ManagedApplicationExamplePair { $work = Join-Path ([IO.Path]::GetTempPath()) ('dx-' + [guid]::NewGuid().ToString('N').Substring(0, 8)) $null = New-Item -ItemType Directory -Path $work try { - $commit = '84b13767cb9484f8f3a36a71875662edfdb3e511' - Invoke-WebRequest "https://codeload.github.com/codebeltnet/xunit/zip/$commit" -OutFile "$work/source.zip" + $commit = '__COMMIT__' + Invoke-WebRequest "https://codeload.github.com/__REPOSITORY__/zip/$commit" -OutFile "$work/source.zip" Expand-Archive -LiteralPath "$work/source.zip" -DestinationPath "$work/extracted" - Move-Item -LiteralPath "$work/extracted/xunit-$commit" -Destination "$work/repo" - $project = 'test/Codebelt.Extensions.Xunit.Hosting.FunctionalTests/Codebelt.Extensions.Xunit.Hosting.FunctionalTests.csproj' - $test = 'Codebelt.Extensions.Xunit.Hosting.BootstrapperMinimalWorkerApplicationTestTest.ShouldBootstrapMinimalWorkerProgram' + Move-Item -LiteralPath "$work/extracted/__ARCHIVE__-$commit" -Destination "$work/repo" + $project = '__PROJECT__' + $test = '__TEST__' __EXECUTE__ $code = $LASTEXITCODE if ($code -ne 0) { throw "Repository test failed with exit code $code. See $work/run.log" } @@ -52,7 +66,7 @@ function New-ManagedApplicationExamplePair { $native = @' Push-Location "$work/repo" try { - dotnet run --project $project --framework net11.0 -p:SkipSignAssembly=true -- --filter-method $test --report-xunit-xml --report-xunit-xml-filename result.xml --results-directory "$work/results" 2>&1 | Tee-Object -FilePath "$work/run.log" + dotnet run --project $project --framework __FRAMEWORK__ -p:SkipSignAssembly=true -- --filter-method $test --report-xunit-xml --report-xunit-xml-filename result.xml --results-directory "$work/results" 2>&1 | Tee-Object -FilePath "$work/run.log" } finally { Pop-Location } '@ @@ -66,10 +80,18 @@ $dockerUser = @() if ($LASTEXITCODE -ne 0) { throw 'Cannot resolve host GID.' } $dockerUser = @('--user', "${hostUid}:${hostGid}") } - docker run --rm @dockerUser --env HOME=/tmp --env DOTNET_CLI_HOME=/tmp --mount "type=bind,source=$work,target=/work" --workdir /work/repo mcr.microsoft.com/dotnet/sdk:11.0 dotnet run --project $project --framework net11.0 -p:SkipSignAssembly=true -- --filter-method $test --report-xunit-xml --report-xunit-xml-filename result.xml --results-directory /work/results 2>&1 | Tee-Object -FilePath "$work/run.log" + docker run --rm @dockerUser --env HOME=/tmp --env DOTNET_CLI_HOME=/tmp --mount "type=bind,source=$work,target=/work" --workdir /work/repo __IMAGE__ dotnet run --project $project --framework __FRAMEWORK__ -p:SkipSignAssembly=true -- --filter-method $test --report-xunit-xml --report-xunit-xml-filename result.xml --results-directory /work/results 2>&1 | Tee-Object -FilePath "$work/run.log" '@ + $template = $template.Replace('__COMMIT__', $Commit).Replace('__REPOSITORY__', $Repository).Replace('__ARCHIVE__', $Repository.Split('/')[1]).Replace('__PROJECT__', $Project).Replace('__TEST__', $Test) + $native = $native.Replace('__FRAMEWORK__', $Framework) + $docker = $docker.Replace('__FRAMEWORK__', $Framework).Replace('__IMAGE__', $Image) [pscustomobject]@{ Native = $template.Replace('__PREREQUISITE__', "`$null = Get-Command dotnet -ErrorAction Stop").Replace('__EXECUTE__', $native) Docker = $template.Replace('__PREREQUISITE__', "`$null = Get-Command docker -ErrorAction Stop`n docker info *> `$null`n if (`$LASTEXITCODE -ne 0) { throw 'Docker daemon unavailable.' }").Replace('__EXECUTE__', $docker) } } + +# Compatibility wrapper for the already published example. +function New-ManagedApplicationExamplePair { + New-RepositoryExamplePair -Repository 'codebeltnet/xunit' -Commit '84b13767cb9484f8f3a36a71875662edfdb3e511' -Project 'test/Codebelt.Extensions.Xunit.Hosting.FunctionalTests/Codebelt.Extensions.Xunit.Hosting.FunctionalTests.csproj' -Test 'Codebelt.Extensions.Xunit.Hosting.BootstrapperMinimalWorkerApplicationTestTest.ShouldBootstrapMinimalWorkerProgram' -Framework net11.0 -Image mcr.microsoft.com/dotnet/sdk:11.0 +} \ No newline at end of file From 184b7b83d127b2451636887d3d03bfec9c5e1c13 Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Tue, 17 Nov 2026 21:50:42 +0100 Subject: [PATCH 41/95] =?UTF-8?q?=E2=9C=A8=20add=20run=20action=20inventor?= =?UTF-8?q?y=20export=20to=20docfx=20validator?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The generate-run-actions command needs one source-bound inventory of examples per repository, including UID ownership and compilability checks. The new --run-action-inventory option exports that inventory as JSON without building or executing anything, and the validator recognizes only the generated run action paths it owns. --- skills/dotnet-docfx-digest/scripts/docfx.cs | 52 +++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/skills/dotnet-docfx-digest/scripts/docfx.cs b/skills/dotnet-docfx-digest/scripts/docfx.cs index 22fa8a87..e5220c0e 100644 --- a/skills/dotnet-docfx-digest/scripts/docfx.cs +++ b/skills/dotnet-docfx-digest/scripts/docfx.cs @@ -99,6 +99,38 @@ public static int Run(string[] args) try { + if (options.RunActionInventory) + { + var root = Path.GetFullPath(string.IsNullOrWhiteSpace(options.RepoRoot) ? "." : options.RepoRoot); + var config = ResolveDocfxPath(root, options.DocfxPath) ?? throw new IOException("DocFX configuration not found."); + var report = new Report(); + var platformReferences = ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!).Split(Path.PathSeparator) + .Where(p => Path.GetFileName(p).StartsWith("System.", StringComparison.Ordinal) || Path.GetFileName(p) is "netstandard.dll" or "mscorlib.dll") + .Select(p => MetadataReference.CreateFromFile(p)).ToArray(); + var examples = DiscoverMarkdown(root, config, Path.GetDirectoryName(config)!, report) + .SelectMany(file => ExtractFences(file).Select(sample => + { + var owner = ResolveSampleOwner(ExtractOverwriteSections(file), sample); + var error = ResolveSampleContext(sample, root, out var context); + var code = context is null ? sample.Code : string.Join("\n", sample.Code.Split('\n').Skip(2)); + var tree = CSharpSyntaxTree.ParseText(code); + var syntax = tree.GetCompilationUnitRoot(); + var standalone = !tree.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error) && + (syntax.Members.OfType().Any() || syntax.DescendantNodes().OfType().Any(m => m.Identifier.ValueText == "Main")); + var isTest = syntax.DescendantNodes().OfType().Any(a => a.Name.ToString() is "Fact" or "Theory"); + var compilation = CSharpCompilation.Create("DocfxRunActionEligibility", [tree], platformReferences, + new CSharpCompilationOptions(isTest ? OutputKind.DynamicallyLinkedLibrary : OutputKind.ConsoleApplication)); + var eligible = compilation.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).All(d => + isTest && d.Location.IsInSource && d.Id is "CS0246" or "CS0103" && + tree.GetText().ToString(d.Location.SourceSpan) is "Xunit" or "Fact" or "Theory" or "Assert"); + return new { sample.File, sample.StartLine, sample.Code, owner.Uid, + Source = context?.Source, ContextError = error, Standalone = standalone, + Eligible = eligible, + Imports = syntax.DescendantNodes().OfType().Select(u => u.Name?.ToString()).ToArray() }; + })).ToArray(); + Console.WriteLine(JsonSerializer.Serialize(new { config, examples, warnings = report.Warnings }, JsonOptions)); + return 0; + } if (options.WriteOverwriteRequestPath is not null) { _quietProgress = options.QuietProgress; @@ -6757,6 +6789,20 @@ private static bool IsKnownInterimArtifactDeliverable(string repoRoot, string do return true; } + // Only repositories enriched by the explicit run-action command have these deliverables. + // This is a path check, never generation or runtime verification on the fast path. + if (File.Exists(Path.Combine(docfxWorkspace, "run-actions", "index.json"))) + { + var relative = Path.GetRelativePath(docfxWorkspace, candidate).Replace('\\', '/'); + if (relative is "run-actions/index.json" or "run-actions.settings.json" || + Regex.IsMatch(relative, @"^run-actions/[a-f0-9]{24}/(?:native|docker)\.ps1$")) { return true; } + using var config = JsonDocument.Parse(File.ReadAllText(docfxPath)); + if (config.RootElement.TryGetProperty("build", out var build) && build.TryGetProperty("template", out var templates) && + templates.ValueKind == JsonValueKind.Array && templates.EnumerateArray().Any(t => t.ValueKind == JsonValueKind.String && + (PathsEqual(candidate, Path.Combine(docfxWorkspace, t.GetString()!, "public", "run-actions.js")) || + (t.GetString() == "run-actions-template" && PathsEqual(candidate, Path.Combine(docfxWorkspace, "run-actions-template", "public", "main.js")))))) { return true; } + } + return IsKnownNamespaceMarkdown(candidate, docfxWorkspace, ws, knownNamespaces) || IsKnownTypeMarkdown(candidate, docfxWorkspace, ws, knownTypePageStems, knownTypeSectionUids); } @@ -8922,6 +8968,9 @@ private static bool TryParse(string[] args, out Options options, out string erro if (!Next(args, ref i, out var rr)) { error = "--repo-root requires a path."; return false; } options.RepoRoot = rr; break; + case "--run-action-inventory": + options.RunActionInventory = true; + break; case "--docfx": if (!Next(args, ref i, out var dx)) { error = "--docfx requires a path."; return false; } options.DocfxPath = dx; @@ -9152,6 +9201,7 @@ dotnet run --file docfx.cs -- [options] --build-api-model Reflection-backed API discovery from compiled assemblies. Builds only the documented project graph (dotnet). Alias: --strict-api-discovery. --verify-docfx-build Run DocFX against a temp copy of the repository (docfx). + --run-action-inventory Export source-bound example inventory only; no builds or execution. --search-examples Run GitHub code search per documented package (gh). Use with --assessment-queue. Options: @@ -9189,6 +9239,7 @@ Override with env var DOCFX_DIGEST_PROCESS_TIMEOUT_MINUTES. --verify-docfx-build Run DocFX against a temp copy of the repository (opt-in). --assessment-queue Write a deterministic Markdown assessment work queue from validation diagnostics. + --run-action-inventory Export source-bound example inventory only; no builds or execution. --search-examples Run GitHub code search for each documented package and embed real usage snippets in the assessment work queue. Requires the gh CLI to be authenticated. Use together with --assessment-queue. --clean-generated-metadata @@ -9250,6 +9301,7 @@ private enum ExitCode private sealed class Options { + public bool RunActionInventory { get; set; } public string? RepoRoot { get; set; } public string? DocfxPath { get; set; } public string Configuration { get; set; } = "Release"; From 9459b7400639e807a607b0de5a5b5b752139cb48 Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Tue, 17 Nov 2026 21:50:47 +0100 Subject: [PATCH 42/95] =?UTF-8?q?=E2=9C=A8=20add=20copy=20controls=20for?= =?UTF-8?q?=20generated=20run=20actions?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Modern DocFX templates can offer one-click copy of the complete native or Docker script next to each runnable C# example. The enhancement is optional: the source links and the C# remain usable without JavaScript, and the copy path refuses any script that is not a same-origin execution script. --- .../dotnet-docfx-digest/assets/run-actions.js | 55 ++++++++++++++ .../scripts/test-run-actions-browser.cjs | 73 +++++++++++++++++++ 2 files changed, 128 insertions(+) create mode 100644 skills/dotnet-docfx-digest/assets/run-actions.js create mode 100644 skills/dotnet-docfx-digest/scripts/test-run-actions-browser.cjs diff --git a/skills/dotnet-docfx-digest/assets/run-actions.js b/skills/dotnet-docfx-digest/assets/run-actions.js new file mode 100644 index 00000000..683df931 --- /dev/null +++ b/skills/dotnet-docfx-digest/assets/run-actions.js @@ -0,0 +1,55 @@ +// Optional modern-template enhancement. Links and C# remain usable without JavaScript. +export function enhanceRunActions(root = document) { + for (const links of root.querySelectorAll('.docfx-run-actions:not([data-enhanced])')) { + const previous = links.previousElementSibling; + const pre = previous?.matches('pre') ? previous : previous?.querySelector('pre'); + if (!pre?.querySelector('code.lang-csharp, code.language-csharp, code.lang-cs, code.language-cs')) continue; + links.dataset.enhanced = 'true'; + const toolbar = document.createElement('span'); + toolbar.className = 'docfx-run-toolbar'; + toolbar.setAttribute('role', 'group'); + toolbar.setAttribute('aria-label', 'Runnable example scripts'); + const status = document.createElement('span'); + status.setAttribute('role', 'status'); + status.className = 'docfx-run-status'; + links.append(status); + for (const link of links.querySelectorAll('a[data-transport]')) { + const transport = link.dataset.transport; + const label = transport === 'native' ? 'Native' : 'Docker'; + const button = document.createElement('button'); + button.type = 'button'; + button.className = 'docfx-run-copy'; + button.title = `Copy the complete ${label} PowerShell script. Review View ${label} Script before executing.`; + button.setAttribute('aria-label', `Copy ${label}`); + const icon = document.createElement('span'); + icon.textContent = '⧉'; + icon.setAttribute('aria-hidden', 'true'); + button.append(icon, ` Copy ${label}`); + button.addEventListener('click', async () => { + button.disabled = true; + try { + const url = new URL(link.href, document.baseURI); + if (url.origin !== location.origin) throw new Error('Script must be hosted on this site.'); + const response = await fetch(url); + if (!response.ok) throw new Error(`Script unavailable (${response.status}).`); + const script = await response.text(); + if (!script.startsWith('#requires -Version 7.0')) throw new Error('Response is not an execution script.'); + await navigator.clipboard.writeText(script); + status.textContent = `${label} script copied. Review before executing.`; + } catch (error) { + status.textContent = `Could not copy ${label}. Open View ${label} Script to copy it manually. ${error.message}`; + } finally { button.disabled = false; } + }); + toolbar.append(button); + } + pre.classList.add('docfx-runnable'); + pre.append(toolbar); + } +} +if (typeof document !== 'undefined') { + const style = document.createElement('style'); + style.textContent = `.docfx-runnable{position:relative}.docfx-run-toolbar{display:flex;gap:.4rem;justify-content:flex-end;position:sticky;left:0;bottom:0;opacity:0}.docfx-runnable:hover .docfx-run-toolbar,.docfx-runnable:focus-within .docfx-run-toolbar{opacity:1}.docfx-run-copy{font:inherit;font-size:.8rem;color:var(--bs-body-color);background:var(--bs-body-bg);border:1px solid var(--bs-border-color);border-radius:.25rem;padding:.25rem .5rem}.docfx-run-copy:focus-visible{outline:2px solid currentColor;outline-offset:2px}.docfx-run-actions{font-size:.85rem}.docfx-run-status{display:block}@media(hover:none){.docfx-run-toolbar{opacity:1}}`; + document.head.append(style); + if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', () => enhanceRunActions(), { once: true }); + else enhanceRunActions(); +} diff --git a/skills/dotnet-docfx-digest/scripts/test-run-actions-browser.cjs b/skills/dotnet-docfx-digest/scripts/test-run-actions-browser.cjs new file mode 100644 index 00000000..a8a755d6 --- /dev/null +++ b/skills/dotnet-docfx-digest/scripts/test-run-actions-browser.cjs @@ -0,0 +1,73 @@ +// Run against the OS-temp fixture produced by test-run-actions.ps1. +// Requires Playwright; set PLAYWRIGHT_MODULE to its installed module when not on NODE_PATH. +const { chromium } = require(process.env.PLAYWRIGHT_MODULE || 'playwright'); +const fs = require('node:fs'); +const http = require('node:http'); +const path = require('node:path'); +const assert = require('node:assert/strict'); +(async () => { + const site = path.resolve(process.argv[2]); + const server = http.createServer((req, res) => { + const file = path.resolve(site, '.' + decodeURIComponent(new URL(req.url, 'http://localhost').pathname)); + if (!file.startsWith(site + path.sep)) { res.writeHead(403).end(); return; } + try { + const content = fs.readFileSync(file); + res.setHeader('Content-Type', file.endsWith('.js') ? 'text/javascript' : file.endsWith('.html') ? 'text/html' : 'text/plain'); + res.end(content); + } catch { res.writeHead(404).end(); } + }); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + const base = `http://127.0.0.1:${server.address().port}`; + const browser = await chromium.launch({ headless: false }); + try { + const context = await browser.newContext({ permissions: ['clipboard-read', 'clipboard-write'] }); + const page = await context.newPage(); + await page.addInitScript(() => { + const write = navigator.clipboard.writeText.bind(navigator.clipboard); + navigator.clipboard.writeText = async text => { window.copiedScript = text; return write(text); }; + }); + await page.goto(base + '/docs/integration.html'); + await page.waitForFunction(() => window.context7 === true); + await page.getByRole('button', {name: 'Copy Native', exact: true}).waitFor(); + for (const label of ['Native', 'Docker']) { + const button = page.getByRole('button', {name: `Copy ${label}`, exact: true}); + await button.focus(); + assert.equal(await button.evaluate(b => getComputedStyle(b.parentElement).opacity), '1'); + const href = await page.getByRole('link', {name: `View ${label} Script`}).getAttribute('href'); + const expected = await (await page.request.get(new URL(href, page.url()).href)).text(); + assert.ok(expected.includes('ShouldBootstrapMinimalWorkerProgram')); + await button.press('Enter'); + await page.getByRole('status').filter({hasText: `${label} script copied`}).waitFor(); + assert.equal(await page.evaluate(() => window.copiedScript), expected); + assert.equal((await page.evaluate(() => navigator.clipboard.readText())).replace(/\r\n/g, '\n'), expected.replace(/\r\n/g, '\n')); + assert.ok(expected.includes('84b13767cb9484f8f3a36a71875662edfdb3e511')); + } + // Reapplying the component never duplicates controls or the existing DocFX copy button. + await page.evaluate(async () => (await import('../public/run-actions.js')).enhanceRunActions()); + assert.equal(await page.getByRole('button', {name: 'Copy Native', exact: true}).count(), 1); + assert.ok(await page.locator('pre code').innerText()); + const originalCode = await page.locator('pre code').innerText(); + await page.locator('pre a.code-action').press('Enter'); + await page.waitForFunction(code => window.copiedScript === code, originalCode); + assert.equal(await page.getByRole('button', {name: 'Copy Native', exact: true}).count(), 1); + const apiPage = await context.newPage(); + await apiPage.goto(base + '/api/fixture.html'); + for (const label of ['Native', 'Docker']) { + const button = apiPage.getByRole('button', {name: `Copy ${label}`, exact: true}); + await button.waitFor(); + await button.press('Enter'); + await apiPage.getByRole('status').filter({hasText: `${label} script copied`}).waitFor(); + } + const noJs = await browser.newContext({ javaScriptEnabled: false }); + const fallback = await noJs.newPage(); + await fallback.goto(page.url()); + assert.equal(await fallback.getByRole('link', {name: 'View Native Script'}).count(), 1); + assert.equal(await fallback.getByRole('link', {name: 'View Docker Script'}).count(), 1); + assert.ok((await fallback.locator('pre code').innerText()).includes('Assert.Equal')); + // Failure remains inspectable via the same ordinary links. + await page.route('**/native.ps1', route => route.fulfill({status: 404, body: 'missing'})); + await page.getByRole('button', {name: 'Copy Native', exact: true}).press('Enter'); + await page.getByRole('status').filter({hasText: 'Could not copy Native'}).waitFor(); + console.log('Browser checks passed: both complete clipboard payloads, keyboard focus/activation, Context7, idempotent enhancement, no-JS fallback and fetch failure.'); + } finally { await browser.close(); server.close(); } +})().catch(error => { console.error(error); process.exitCode = 1; }); From e0edb71b2ea4b9030cf01adc9e442b010192335f Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Tue, 17 Nov 2026 21:50:53 +0100 Subject: [PATCH 43/95] =?UTF-8?q?=E2=9C=A8=20add=20generate-run-actions=20?= =?UTF-8?q?script=20and=20tests?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Repository-wide generation of run action assets needs one deterministic command that runs the inventory once, writes owned associations and scripts incrementally, and removes stale ones when sources change. The fixture-based test covers the original pinned recipe, the unsupported cases and repeated generation without model or per-file execution. --- .../scripts/generate-run-actions.ps1 | 235 ++++++++++++++++++ .../scripts/test-run-actions.ps1 | 84 +++++++ 2 files changed, 319 insertions(+) create mode 100644 skills/dotnet-docfx-digest/scripts/generate-run-actions.ps1 create mode 100644 skills/dotnet-docfx-digest/scripts/test-run-actions.ps1 diff --git a/skills/dotnet-docfx-digest/scripts/generate-run-actions.ps1 b/skills/dotnet-docfx-digest/scripts/generate-run-actions.ps1 new file mode 100644 index 00000000..a3cbf82d --- /dev/null +++ b/skills/dotnet-docfx-digest/scripts/generate-run-actions.ps1 @@ -0,0 +1,235 @@ +#requires -Version 7.0 +[CmdletBinding()] +param( + [Parameter(Mandatory)][string] $RepoRoot, + [string] $Docfx, + [string] $Settings, + [string] $Framework = 'net10.0', + [string] $CsrunImage = 'codebeltnet/csrun:10', + [ValidateSet('None','Native','Docker','Both')][string] $Verify = 'None' +) +$ErrorActionPreference = 'Stop' +. (Join-Path $PSScriptRoot 'integration-example.ps1') +$helpers = Join-Path $PSScriptRoot '../../dotnet-csrun/scripts/sample-tools.ps1' +if (-not (Test-Path $helpers)) { throw "Install dotnet-csrun beside this skill: $helpers" } +. $helpers +Set-StrictMode -Off +function Hash([string] $Text) { [Convert]::ToHexString([Security.Cryptography.SHA256]::HashData([Text.Encoding]::UTF8.GetBytes($Text))) } +function Normalize([string] $Text) { $Text.Replace("`r`n", "`n").TrimEnd("`n", "`r") } +function Write-Changed([string] $Path, [string] $Text) { + Assert-RepositoryPath $Path + if ((Test-Path -LiteralPath $Path) -and [IO.File]::ReadAllText($Path) -ceq $Text) { return $false } + $null = [IO.Directory]::CreateDirectory([IO.Path]::GetDirectoryName($Path)) + [IO.File]::WriteAllText($Path, $Text, [Text.UTF8Encoding]::new($false)) + return $true +} +# Preserve the original encoding/BOM and line endings when adding/removing owned HTML. +function Write-Page([string] $Path, [string] $Original, [string] $Updated) { + if ($Original -ceq $Updated) { return } + $bytes = [IO.File]::ReadAllBytes($Path) + $reader = [IO.StreamReader]::new($Path, [Text.UTF8Encoding]::new($false, $true), $true) + try { $null = $reader.ReadToEnd(); $encoding = $reader.CurrentEncoding } finally { $reader.Dispose() } + $output = $encoding.GetBytes($Updated) + $preamble = $encoding.GetPreamble() + if ($preamble.Length -and $bytes.Length -ge $preamble.Length -and + [Convert]::ToBase64String($bytes[0..($preamble.Length-1)]) -ceq [Convert]::ToBase64String($preamble)) { $output = [byte[]]($preamble + $output) } + [IO.File]::WriteAllBytes($Path, $output) +} +$root = [IO.Path]::GetFullPath($RepoRoot) +function Assert-RepositoryPath([string] $Path) { + $full = [IO.Path]::GetFullPath($Path) + if (-not $full.StartsWith($root.TrimEnd('/','\') + [IO.Path]::DirectorySeparatorChar, [StringComparison]::OrdinalIgnoreCase)) { throw "Path outside requested repository: $Path" } + for ($current = $full; $current.Length -gt $root.Length; $current = Split-Path $current -Parent) { + if ((Test-Path -LiteralPath $current) -and ((Get-Item -LiteralPath $current -Force).Attributes -band [IO.FileAttributes]::ReparsePoint)) { throw "Linked output path: $current" } + } +} +$arguments = @('--repo-root', $root, '--run-action-inventory') +if ($Docfx) { $arguments += @('--docfx', $Docfx) } +# One inventory process per repository, never one model/process per document. +$inventoryText = & dotnet run --file (Join-Path $PSScriptRoot 'docfx.cs') -- @arguments +if ($LASTEXITCODE -ne 0) { throw 'DocFX example inventory failed.' } +$inventory = ($inventoryText -join "`n") | ConvertFrom-Json +$configPath = $inventory.config +$workspace = Split-Path $configPath -Parent +Assert-RepositoryPath $configPath +$assetRoot = Join-Path $workspace 'run-actions' +Assert-RepositoryPath $assetRoot +$indexPath = Join-Path $assetRoot 'index.json' +$old = @() +if (Test-Path $indexPath) { $old = @((Get-Content $indexPath -Raw | ConvertFrom-Json).examples) } +$recipes = @() +if (-not $Settings) { $Settings = Join-Path $workspace 'run-actions.settings.json' } +if (Test-Path $Settings) { $recipes = @((Get-Content $Settings -Raw | ConvertFrom-Json).examples) } +$toolHash = Hash ((Get-Content $PSCommandPath -Raw) + (Get-Content (Join-Path $PSScriptRoot 'integration-example.ps1') -Raw) + (Get-Content $helpers -Raw)) +$results = [Collections.Generic.List[object]]::new() +$associations = @{} +$oldByFingerprint = @{} +foreach ($entry in $old) { + if ($entry.fingerprint) { $oldByFingerprint["$($entry.id)|$($entry.fingerprint)"] = $entry } +} +$recipeBySource = @{} +foreach ($recipe in $recipes) { + $key = "$($recipe.uid)|$($recipe.sourceSha256)" + if ($recipeBySource.ContainsKey($key)) { throw "Duplicate recipe for $key" } + $recipeBySource[$key] = $recipe +} +foreach ($example in $inventory.examples) { + $source = Normalize $example.code + if ($example.source) { $source = Normalize (($source -split "`n" | Select-Object -Skip 2) -join "`n") } + $sourceHash = Hash $source + $identity = if ($example.source) { [IO.Path]::GetRelativePath($root, $example.source).Replace('\','/') + '|' + $sourceHash } else { $sourceHash } + $id = (Hash ("$($example.uid)|$([IO.Path]::GetRelativePath($root, $example.file).Replace('\','/'))|$identity")).Substring(0,24).ToLowerInvariant() + $result = [ordered]@{ id=$id; file=$example.file; uid=$example.uid; sourceSha256=$sourceHash; status='unsupported'; reason=$null; native='Unverified'; docker='Unverified' } + try { + if ($example.contextError) { throw $example.contextError } + + + $recipe = $recipeBySource["$($example.uid)|$sourceHash"] + $strategy = 'standalone' + # Known, inspected integration source. No API-name heuristic may substitute a different test. + if (-not $recipe -and $sourceHash -ceq '47B0C1FBA94E7B43C8753D0A8242801B328E6B463B6EEDAEB640D4F8A262633E') { + $recipe = [pscustomobject]@{ repository='codebeltnet/xunit'; commit='84b13767cb9484f8f3a36a71875662edfdb3e511'; project='test/Codebelt.Extensions.Xunit.Hosting.FunctionalTests/Codebelt.Extensions.Xunit.Hosting.FunctionalTests.csproj'; test='Codebelt.Extensions.Xunit.Hosting.BootstrapperMinimalWorkerApplicationTestTest.ShouldBootstrapMinimalWorkerProgram'; framework='net11.0'; image='mcr.microsoft.com/dotnet/sdk:11.0' } + } + $isTest = $source -match '\[(?:Fact|Theory)(?:Attribute)?(?:\(|\])' + if ($recipe -and $recipe.PSObject.Properties['repository']) { $strategy = 'repository' } + elseif ($example.source -and -not ($recipe -and $recipe.PSObject.Properties['manifest'])) { + $result.reason = 'Maintained project context needs a pinned repository recipe; no replacement host was generated.' + continue + } + elseif (-not $recipe -and ((-not $example.eligible -or -not ($example.standalone -or $isTest)) -or @($example.imports | Where-Object { $_ -notmatch '^(System(?:\.|$)|Xunit$)' }).Count -or $source -match '(?m)^#:')) { + $result.reason = 'Partial source or unresolved dependencies. Supply an exact source-bound standalone manifest or pinned repository recipe; retain maintained implementation/usage/test links.' + continue + } + $transports = @('native','docker') + foreach ($transport in @('native','docker')) { + if ($recipe -and $recipe.unsupportedTransports.$transport) { + $result[$transport] = 'Unsupported' + $result["${transport}Reason"] = $recipe.unsupportedTransports.$transport + $transports = @($transports | Where-Object { $_ -ne $transport }) + } + } + if (-not $transports.Count) { $result.reason = 'Both transports are explicitly unsupported.'; continue } + $fingerprint = Hash ("$toolHash|$sourceHash|$strategy|$Framework|$CsrunImage|" + ($recipe | ConvertTo-Json -Depth 30 -Compress)) + $prior = @($oldByFingerprint["$id|$fingerprint"] | Where-Object { $null -ne $_ }) + $dir = Join-Path $assetRoot $id + $reusable = $prior.Count -eq 1 + foreach ($transport in $transports) { + $path = Join-Path $dir "$transport.ps1" + if (-not (Test-Path $path) -or -not $reusable -or (Hash ([IO.File]::ReadAllText($path))) -cne $prior[0]."${transport}Sha256") { $reusable = $false } + } + if ($reusable) { + $pair = @{} + foreach ($transport in $transports) { + $pair[$transport] = [IO.File]::ReadAllText((Join-Path $dir "$transport.ps1")) + if ($prior[0]."${transport}Evidence") { $result["${transport}Evidence"] = $prior[0]."${transport}Evidence" } + } + $result.native = $prior[0].native; $result.docker = $prior[0].docker + } elseif ($strategy -eq 'repository') { + $pair = New-RepositoryExamplePair -Repository $recipe.repository -Commit $recipe.commit -Project $recipe.project -Test $recipe.test -Framework $recipe.framework -Image $recipe.image + } else { + $manifest = if ($recipe) { $recipe.manifest } else { [pscustomobject]@{ schemaVersion=1; mode=$(if ($isTest) {'test'} else {'console'}); framework=$Framework; dependsOn=@($(if ($isTest) {'xunit.v3@4.0.3'})) } } + if ($manifest.PSObject.Properties['source'] -and (Normalize $manifest.source) -cne $source) { throw 'Manifest source differs from displayed C#.' } + $manifest | Add-Member -NotePropertyName source -NotePropertyValue $source -Force + $pair = New-CsrunExecutionPair -ManifestJson ($manifest | ConvertTo-Json -Depth 30) -Image $CsrunImage + } + $changed = $false + foreach ($transport in $transports) { + $script = Normalize $pair.$transport + $tokens=$null; $errors=$null + $null = [Management.Automation.Language.Parser]::ParseInput($script,[ref]$tokens,[ref]$errors) + if ($errors.Count) { throw "Generated $transport script has syntax errors: $errors" } + $path = Join-Path $dir "$transport.ps1" + $changed = (Write-Changed $path $script) -or $changed + $result["${transport}Sha256"] = Hash $script + if ($Verify -eq 'Both' -or $Verify -eq $transport) { + $log = Join-Path ([IO.Path]::GetTempPath()) ("docfx-run-$id-$transport-" + [guid]::NewGuid().ToString('N') + '.log') + & pwsh -NoProfile -NonInteractive -File $path *> $log + $result[$transport] = if ($LASTEXITCODE -eq 0) { 'Verified' } else { 'Failed' } + $result["${transport}Evidence"] = $log + } + } + $result.status = if ($changed) { 'generated' } else { 'unchanged' } + $result.fingerprint = $fingerprint + $links = @($transports | ForEach-Object { + $label = if ($_ -eq 'native') { 'Native' } else { 'Docker' } + 'View ' + $label + ' Script' + }) + $link = '
' + ($links -join ' · ') + '
' + if (-not $associations.ContainsKey($example.file)) { $associations[$example.file] = @{} } + $associations[$example.file][[int]$example.startLine] = "`n$link`n" + } catch { $result.status='failed'; $result.reason=$_.Exception.Message } + finally { $results.Add([pscustomobject]$result) } +} +# Apply localized insertions after fences. Existing associations are removed first; C# bytes are untouched. +$pages = @(@($inventory.examples.file) + @($old.file) | Sort-Object -Unique) +foreach ($page in $pages) { + if (-not (Test-Path -LiteralPath $page)) { continue } + Assert-RepositoryPath $page + $original = [IO.File]::ReadAllText($page) + $newline = if ($original.Contains("`r`n")) { "`r`n" } else { "`n" } + $lines = $original -split '\r?\n' + # Work backwards using original inventory line numbers, so inserted lines do not shift later fences. + if ($associations.ContainsKey($page)) { + foreach ($line in @($associations[$page].Keys | Sort-Object -Descending)) { + $end = $line + while ($end -lt $lines.Length -and $lines[$end] -notmatch '^\s*```') { $end++ } + if ($end -ge $lines.Length) { throw "Unclosed fence in $page" } + $lines[$end] += $newline + $newline + $associations[$page][$line].Replace("`n", $newline) + } + } + $updated = $lines -join $newline + $updated = [regex]::Replace($updated, '(?:\r?\n){2}.*?', '', 'Singleline') + $updated = $updated.Replace('','').Replace('','') + Write-Page $page $original $updated +} +# Remove only assets owned by the previous index. Never recursively delete user directories. +foreach ($entry in $results) { + foreach ($transport in @('native','docker')) { + if ($entry.$transport -eq 'Unsupported' -and $entry.id -match '^[a-f0-9]{24}$') { + $path = Join-Path $assetRoot "$($entry.id)/$transport.ps1" + Assert-RepositoryPath $path + if (Test-Path -LiteralPath $path) { Remove-Item -LiteralPath $path } + } + } +} +$active = @($results | Where-Object { $_.status -in @('generated','unchanged') } | ForEach-Object id) +foreach ($previous in $old) { + if ($previous.id -match '^[a-f0-9]{24}$' -and $previous.id -notin $active) { + foreach ($name in @('native.ps1','docker.ps1')) { + $path = Join-Path $assetRoot "$($previous.id)/$name" + Assert-RepositoryPath $path + if (Test-Path -LiteralPath $path) { Remove-Item -LiteralPath $path } + } + } +} +$config = Get-Content $configPath -Raw | ConvertFrom-Json -AsHashtable +if (-not $config.build) { throw 'docfx.json requires build configuration.' } +$resources = @($config.build.resource) +if (-not @($resources | Where-Object { ($_ | ConvertTo-Json -Compress) -match 'run-actions/\*\*' }).Count) { + $config.build.resource = @($resources | Where-Object { $null -ne $_ }) + @(@{ files=@('run-actions/**') }) +} +# Compose with an existing modern main.js rather than overriding its default export/start hook (e.g. Context7). +$templates = @($config.build.template) +$main = $null +foreach ($template in $templates) { + $candidate = Join-Path $workspace "$template/public/main.js" + if (Test-Path $candidate) { $main=$candidate } +} +if (-not $main) { + $main = Join-Path $workspace 'run-actions-template/public/main.js' + $null = Write-Changed $main "export default {};`n" + if ('run-actions-template' -notin $templates) { $config.build.template = $templates + @('run-actions-template') } +} +Assert-RepositoryPath $main +$mainText = [IO.File]::ReadAllText($main) +if (-not $mainText.Contains("import './run-actions.js';")) { $null = Write-Changed $main ($mainText + "`nimport './run-actions.js';`n") } +$null = Write-Changed (Join-Path (Split-Path $main -Parent) 'run-actions.js') ([IO.File]::ReadAllText((Join-Path $PSScriptRoot '../assets/run-actions.js'))) +$null = Write-Changed $configPath (($config | ConvertTo-Json -Depth 100) + "`n") +$persisted = @($results | ForEach-Object { + $entry = $_ | Select-Object * + if ($entry.status -in @('generated','unchanged')) { $entry.status = 'ready' } + $entry +}) +$null = Write-Changed $indexPath (([ordered]@{ examples=$persisted } | ConvertTo-Json -Depth 30) + "`n") +$results | ConvertTo-Json -Depth 30 +if (@($results | Where-Object { $_.status -eq 'failed' -or $_.native -eq 'Failed' -or $_.docker -eq 'Failed' }).Count) { exit 1 } diff --git a/skills/dotnet-docfx-digest/scripts/test-run-actions.ps1 b/skills/dotnet-docfx-digest/scripts/test-run-actions.ps1 new file mode 100644 index 00000000..0116e9c0 --- /dev/null +++ b/skills/dotnet-docfx-digest/scripts/test-run-actions.ps1 @@ -0,0 +1,84 @@ +#requires -Version 7.0 +param([string] $OutputRoot) +$ErrorActionPreference = 'Stop' +. (Join-Path $PSScriptRoot '../../../scripts/file-based-app.ps1') +$app = Get-FileBasedAppCommand -SourcePath (Join-Path $PSScriptRoot 'docfx.cs') +function dotnet { + # Cache the file-based inventory build once; every inventory assertion still executes. + & (Get-Command $app.Executable -CommandType Application).Source @($app.ArgumentPrefix + @($args | Select-Object -Skip ([Array]::IndexOf($args, '--repo-root')))) + $global:LASTEXITCODE = $LASTEXITCODE +} +$work = if ($OutputRoot) { $OutputRoot } else { Join-Path ([IO.Path]::GetTempPath()) ('docfx-actions-' + [guid]::NewGuid().ToString('N')) } +$null = New-Item -ItemType Directory -Path "$work/docs" -Force +$reference = Get-Content (Join-Path $PSScriptRoot '../references/one-shot-examples.md') -Raw +$source = [regex]::Match($reference, '(?s)```csharp\r?\n(.*?)\r?\n```').Groups[1].Value +$page = "---`nuid: Codebelt.Extensions.Xunit.Hosting.ManagedApplicationFixture``1`n---`n# Actual worker startup`n`nMaintained functional test and [entry point](https://github.com/codebeltnet/xunit/blob/84b13767cb9484f8f3a36a71875662edfdb3e511/app/Codebelt.Extensions.Xunit.Hosting.BootstrapperMinimalWorker.App/Program.cs).`n`n``````csharp`n$source`n```````n" +[IO.File]::WriteAllText("$work/docs/integration.md", $page) +[IO.File]::WriteAllText("$work/docs/console.md", "# Console`n`n``````csharp`n// Program.cs`nSystem.Console.WriteLine(42);`n```````n") +[IO.File]::WriteAllText("$work/docs/partial.md", "# Partial`n`n``````csharp`nvar fixture = new ManagedApplicationFixture();`n```````n") +$null = New-Item -ItemType Directory "$work/template/public" -Force +[IO.File]::WriteAllText("$work/template/public/main.js", "// Context7 customization`nexport default { start() { window.context7 = true; } };`n") +[IO.File]::WriteAllText("$work/docfx.json", '{"build":{"content":[{"files":["docs/*.md"]}],"template":["default","modern","template"],"dest":"_site"}}') +[IO.File]::WriteAllText("$work/docs/test.md", "# Test`n`n``````csharp`nusing Xunit;`npublic class ExampleTest { [Fact] public void ShouldPass() { Assert.Equal(42, 42); } }`n```````n") +$null = New-Item -ItemType Directory -Path "$work/api/types" -Force +$uid = 'Codebelt.Extensions.Xunit.Hosting.ManagedApplicationFixture`1' +$overwrite = "---`nuid: $uid`nexample:`n - *content`n---`n`n``````csharp`n$source`n```````n`nRead the maintained functional test and application sources." +# Exercise localized edits with an existing UTF-8 BOM and CRLF overwrite document. +[IO.File]::WriteAllText("$work/api/types/ManagedApplicationFixture-1.md", $overwrite.Replace("`r`n", "`n").Replace("`n", "`r`n"), [Text.UTF8Encoding]::new($true)) +[IO.File]::WriteAllText("$work/api/fixture.yml", "### YamlMime:ManagedReference`nitems:`n- uid: $uid`n id: ManagedApplicationFixture``1`n name: ManagedApplicationFixture`n fullName: $uid`n type: Class`n langs:`n - csharp`n syntax:`n content: public class ManagedApplicationFixture`n") +$config = Get-Content "$work/docfx.json" -Raw | ConvertFrom-Json -AsHashtable +$config.build.content += @{ files=@('api/*.yml') } +$config.build.overwrite = @(@{ files=@('api/types/*.md') }) +[IO.File]::WriteAllText("$work/docfx.json", ($config | ConvertTo-Json -Depth 20)) +$generator = Join-Path $PSScriptRoot 'generate-run-actions.ps1' +$first = (& $generator -RepoRoot $work) | ConvertFrom-Json +if (@($first | Where-Object status -eq 'generated').Count -ne 4 -or @($first | Where-Object status -eq 'unsupported').Count -ne 1) { throw "Unexpected generation: $($first | ConvertTo-Json -Depth 10)" } +$entry = $first | Where-Object { $_.uid -like '*ManagedApplicationFixture*' -and $_.file -match '[\\/]docs[\\/]integration.md$' } +foreach ($transport in @('native','docker')) { + $script = Get-Content "$work/run-actions/$($entry.id)/$transport.ps1" -Raw + if (-not $script.Contains('84b13767cb9484f8f3a36a71875662edfdb3e511') -or -not $script.Contains('ShouldBootstrapMinimalWorkerProgram')) { throw 'Wrong pinned test.' } + if ($entry.$transport -ne 'Unverified') { throw 'Generation claimed runtime verification.' } +} +$updated = Get-Content "$work/docs/integration.md" -Raw +if (-not $updated.Contains($source) -or -not $updated.Contains('[entry point]') -or -not $updated.Contains('View Native Script')) { throw 'Source/prose/fallback lost.' } +if (-not (Get-Content "$work/template/public/main.js" -Raw).Contains('window.context7 = true')) { throw 'Existing template was overwritten.' } +$files = @(Get-ChildItem $work -Recurse -File) +$before = @{} +foreach ($file in $files) { $before[$file.FullName] = @((Get-FileHash $file.FullName).Hash, $file.LastWriteTimeUtc.Ticks) } +$second = (& $generator -RepoRoot $work) | ConvertFrom-Json +if (@($second | Where-Object status -eq 'unchanged').Count -ne 4) { throw 'Incremental generation failed.' } +foreach ($file in Get-ChildItem $work -Recurse -File) { + if ($before[$file.FullName][0] -cne (Get-FileHash $file.FullName).Hash -or $before[$file.FullName][1] -ne $file.LastWriteTimeUtc.Ticks) { throw "Second run changed $($file.FullName)" } +} +# Actual DocFX render checks tilde links, publishing, modern template composition and C# fidelity. +& (Get-Command docfx -CommandType Application).Source build "$work/docfx.json" --disableGitFeatures *> "$work/build.log" +if ($LASTEXITCODE -ne 0) { throw "DocFX render failed: $work/build.log" } +$html = Get-Content "$work/_site/docs/integration.html" -Raw +if (-not $html.Contains('data-example-id=') -or -not $html.Contains('../run-actions/') -or -not (Test-Path "$work/_site/run-actions/$($entry.id)/native.ps1")) { throw 'Rendered association/static resources missing.' } +if (-not (Get-Content "$work/_site/public/main.js" -Raw).Contains("import './run-actions.js'")) { throw 'Modern template module not published.' } +$apiHtml = Get-ChildItem "$work/_site/api" -Filter '*.html' | Select-Object -First 1 | Get-Content -Raw +if (-not $apiHtml.Contains('View Native Script') -or -not $apiHtml.Contains('ShouldBootstrapMinimalWorkerProgram')) { throw 'Overwrite example association did not survive API rendering.' } +$overwriteBytes = [IO.File]::ReadAllBytes("$work/api/types/ManagedApplicationFixture-1.md") +if ([Convert]::ToHexString($overwriteBytes[0..2]) -ne 'EFBBBF') { throw 'Overwrite BOM lost.' } +$overwriteText = [IO.File]::ReadAllText("$work/api/types/ManagedApplicationFixture-1.md") +if ($overwriteText.Replace("`r`n", '').Contains("`n") -or -not $overwriteText.Contains("example:`r`n - *content")) { throw 'Overwrite mapping/line endings changed.' } +# A real platform limitation may suppress only Docker, without suppressing valid native generation. +$settings = [ordered]@{ examples=@([ordered]@{ + uid=$entry.uid; sourceSha256=$entry.sourceSha256; repository='codebeltnet/xunit'; commit='84b13767cb9484f8f3a36a71875662edfdb3e511' + project='test/Codebelt.Extensions.Xunit.Hosting.FunctionalTests/Codebelt.Extensions.Xunit.Hosting.FunctionalTests.csproj' + test='Codebelt.Extensions.Xunit.Hosting.BootstrapperMinimalWorkerApplicationTestTest.ShouldBootstrapMinimalWorkerProgram' + framework='net11.0'; image='mcr.microsoft.com/dotnet/sdk:11.0' + unsupportedTransports=@{ docker='Synthetic platform limitation for deterministic transport-selection regression.' } +}) } +[IO.File]::WriteAllText("$work/run-actions.settings.json", ($settings | ConvertTo-Json -Depth 20)) +$limited = (& $generator -RepoRoot $work) | ConvertFrom-Json +$limitedEntry = $limited | Where-Object id -eq $entry.id +if ($limitedEntry.docker -ne 'Unsupported' -or -not (Test-Path "$work/run-actions/$($entry.id)/native.ps1") -or (Test-Path "$work/run-actions/$($entry.id)/docker.ps1")) { throw 'Single-transport limitation was misrepresented.' } +if ((Get-Content "$work/docs/integration.md" -Raw).Contains('View Docker Script')) { throw 'Unsupported Docker still has a control.' } +$limitedAgain = (& $generator -RepoRoot $work) | ConvertFrom-Json +if (($limitedAgain | Where-Object id -eq $entry.id).status -ne 'unchanged') { throw 'Single-transport cache requires the unsupported script.' } +# Mutating the principal source invalidates its recipe and removes both associations and owned scripts. +[IO.File]::WriteAllText("$work/docs/integration.md", $updated.Replace('Bootstrapper Minimal Worker', 'Changed assertion')) +$third = (& $generator -RepoRoot $work) | ConvertFrom-Json +if ((Test-Path "$work/run-actions/$($entry.id)/native.ps1") -or (Get-Content "$work/docs/integration.md" -Raw).Contains('data-example-id')) { throw 'Stale recipe/assets survived source change.' } +Write-Host "Run-action generation passed: source parity, pinned native/Docker, unsupported, incremental bytes/timestamps, stale cleanup, DocFX render, resources, template composition. Fixture: $work" From 49e837831bc6041af138cc2cfb4289d82776776a Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Tue, 17 Nov 2026 21:50:59 +0100 Subject: [PATCH 44/95] =?UTF-8?q?=F0=9F=93=9D=20document=20opt-in=20run=20?= =?UTF-8?q?actions=20in=20skill=20instructions?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The skill needs to know when to invoke the explicit generate-run-actions command, and that generation is separate from normal authoring and its completion gates. The new eval case pins the expected behavior for the original worker test, a complete console example and a partial excerpt. --- skills/dotnet-docfx-digest/SKILL.md | 4 ++ skills/dotnet-docfx-digest/evals/evals.json | 12 +++++ .../references/run-actions.md | 52 +++++++++++++++++++ 3 files changed, 68 insertions(+) create mode 100644 skills/dotnet-docfx-digest/references/run-actions.md diff --git a/skills/dotnet-docfx-digest/SKILL.md b/skills/dotnet-docfx-digest/SKILL.md index f8350b2e..b9ce7456 100644 --- a/skills/dotnet-docfx-digest/SKILL.md +++ b/skills/dotnet-docfx-digest/SKILL.md @@ -12,6 +12,10 @@ description: > Create and maintain developer-friendly DocFX documentation digests for .NET public APIs. Keep namespace pages, generated API pages, examples, availability notes, and verification aligned with the actual source code and tests. +## Opt-in run actions + +For the explicit logical command `dotnet-docfx-digest generate-run-actions`, read [run actions](references/run-actions.md) and invoke its deterministic repository-wide generator. This command generates assets and lightweight associations without executing examples by default. It is separate from normal authoring/auditing and their completion gates. Preserve readable C#, existing source links and template customizations; report unsupported examples honestly. No per-file agent sessions, engine/schema changes or Python. Runtime verification requires its explicit verification option; generation alone is Unverified. + ## Critical - Prefer complete standalone programs and genuine xUnit v3 tests, delivered through existing `dotnet-csrun` native and Docker one-shot blocks with identical source/dependencies. For APIs requiring an actual application, runner or distinct assembly identity, inspect the maintained example, test and project graph, then provide a pinned repository-backed one-shot test instead. Read [one-shot examples](references/one-shot-examples.md) before publishing execution instructions. Do not expand csrun manifest v1 or manufacture a substitute host. diff --git a/skills/dotnet-docfx-digest/evals/evals.json b/skills/dotnet-docfx-digest/evals/evals.json index dbac6d60..14f4050e 100644 --- a/skills/dotnet-docfx-digest/evals/evals.json +++ b/skills/dotnet-docfx-digest/evals/evals.json @@ -1325,6 +1325,18 @@ "C# target usage, one-shot reproduction, source-bound compilation and full DocFX completion checks remain required", "Does not implement a second repository search subsystem, fast-path network checks or subjective keyword heuristics" ] + }, + { + "id": 123, + "prompt": "Use dotnet-docfx-digest generate-run-actions on a DocFX repository containing the original ManagedApplicationFixture worker functional test, a complete console example and a partial integration excerpt. Generate assets and modern-template controls, then repeat generation unchanged. Preserve Context7 and source links. Do not execute the generated scripts.", + "expected_output": "Invokes the deterministic opt-in generator once for the repository, produces both independent execution scripts for faithful examples with pinned original repository/test integration, retains the original C# and explanatory links, supplies fallback script links plus reusable copy controls, records Unverified outcomes and reports unsupported excerpts. Second generation preserves unchanged bytes and timestamps. No per-file agents, csrun engine/schema changes or runtime execution.", + "expectations": [ + "Uses the shared DocFX inventory and existing csrun generation helpers without per-file model calls", + "Principal integration scripts retain the original pinned repository, project and exact test", + "Both copy controls fetch and copy the entire corresponding script without executing it", + "Source, overwrite UIDs, template customizations and no-JavaScript fallback remain intact", + "Repeated generation is incremental, source changes invalidate assets and generation does not claim Verified" + ] } ] } diff --git a/skills/dotnet-docfx-digest/references/run-actions.md b/skills/dotnet-docfx-digest/references/run-actions.md new file mode 100644 index 00000000..a12934c1 --- /dev/null +++ b/skills/dotnet-docfx-digest/references/run-actions.md @@ -0,0 +1,52 @@ +# Generated run actions (opt-in) + +`dotnet-docfx-digest generate-run-actions` enriches the active DocFX repository in one invocation. It does not invoke an AI agent per file or execute examples during generation. Resolve the loaded skill directory and invoke: + +```powershell +pwsh -NoProfile -File /scripts/generate-run-actions.ps1 -RepoRoot [-Docfx ] +``` + +The command uses `docfx.cs --run-action-inventory`, sharing discovery from `build.content`/`build.overwrite`, fence extraction, UID ownership and source-context validation with compilation. It generates `run-actions//native.ps1` and `docker.ps1` beside the active configuration and adds these as DocFX static resources. A small HTML association immediately follows the unchanged C# fence. UID, document identity and maintained source path (or source hash for inline examples) determine its identity; fence ordinals do not. Owned associations and assets are replaced when their source changes or disappears. Keep this directory and the generated template assets as intentional documentation source, not scratch output. The normal fast validator does not regenerate or execute them. + +Standalone programs with resolvable platform references and simple xUnit examples are discovered automatically. Their exact source is passed to the existing `New-CsrunExecutionPair`; manifest v1 and the engine are unchanged. The defaults are `-Framework net10.0` and `-CsrunImage codebeltnet/csrun:10`; select a reviewed compatible image/tag for publishing. The existing csrun native wrapper downloads the publisher's mutable latest engine. These defaults are not immutable execution provenance; inspect scripts before running them. Dependency-rich examples need explicit source-bound settings rather than guessed package versions. Partial fragments, unavailable dependencies and genuine assembly boundaries are reported as unsupported when no faithful recipe exists. + +For repository-backed execution, the generalized `New-RepositoryExamplePair` accepts a commit-pinned GitHub repository, project, exact xUnit v3/MTP method, framework and official SDK image. It downloads the original graph and requires an XML report proving exactly that method passed. It never synthesizes an application or test host. The inspected ManagedApplicationFixture source fingerprint has a bundled recipe for the original pinned worker functional test. A changed assertion invalidates that recipe, preserving the C# and source links while removing stale controls. + +Optional `run-actions.settings.json` beside docfx.json (or `-Settings `) supplies inspected recipes for other examples. Each entry matches both `uid` and the uppercase SHA-256 of LF-normalized C# without outer trailing newlines or the two source-context lines. The generator reports that hash for unsupported cases. This is DocFX generation configuration, not an extension to the csrun manifest: + +```json +{ + "examples": [ + { + "uid": "Example.Api", + "sourceSha256": "", + "repository": "owner/repository", + "commit": "<40 hex commit>", + "project": "test/FunctionalTests/FunctionalTests.csproj", + "test": "Example.FunctionalTest.ShouldStart", + "framework": "net10.0", + "image": "mcr.microsoft.com/dotnet/sdk:10.0" + }, + { + "uid": "Example.OtherApi", + "sourceSha256": "", + "manifest": { + "schemaVersion": 1, + "mode": "test", + "framework": "net10.0", + "dependsOn": ["xunit.v3@4.0.3", "Example.Package@1.2.3"] + } + } + ] +} +``` + +The generator fills `manifest.source` from the original example; if supplied, it must match. Inspect pinned source, original runner version/report switches and project dependencies before adding a repository recipe; this generator supports the existing xUnit v3/MTP XML protocol only. A recipe may supply `"unsupportedTransports": { "docker": "" }` (or `native`) to publish only the faithful transport and record the limitation; environment unavailability during authoring is never a platform limitation. A different runner, Windows-only dependency or external service may require a separate maintained reproduction. Do not publish a substitute merely to add buttons. Preserve contextual GitHub implementation, usage and test links and explain any unsupported execution limitation in the authoring pass. + +The reusable `assets/run-actions.js` module adds **Copy Native** and **Copy Docker** with tooltips, accessible names, keyboard focus and hover visibility. Each click fetches the whole script and writes it to the clipboard; it never evaluates the response. Ordinary **View Native Script**/**View Docker Script** links remain available without JavaScript and on copy failure. Generated imports compose with the last existing modern template `public/main.js`, retaining its exports/start hook and Context7 behavior. If none exists, the command adds a small template layer. Review the configuration/template diff before publishing; use the modern template. Clipboard writes require a secure browser context and permission. + +Generation reports `generated`, `unchanged`, `unsupported` and `failed` cases in JSON. `index.json` records source/script fingerprints and separate Native/Docker states. Unchanged fingerprints reuse intact assets, preserving bytes and modification times. `Unverified` means generation only. Explicitly pass `-Verify Native`, `-Verify Docker` or `-Verify Both` to execute each selected script in an independent fresh PowerShell process and retain separate exit outcomes/log paths under OS temp. Verification runs trusted repository/package code and may restore/build/pull images; do not enable it for a large repository merely to generate assets. A changed source/recipe/tool fingerprint invalidates previous verification. Failed execution returns nonzero; missing Docker or SDK affects verification, never valid artifact generation. + +Run the focused deterministic regression with `pwsh -NoProfile -File /scripts/test-run-actions.ps1`. It builds the shared inventory once, checks source/pin/association parity, unsupported cases, second-run bytes/timestamps, stale cleanup and a real DocFX modern render in OS temp. Existing `test-integration-example.ps1` checks exact execution/failure semantics with offline doubles. These checks do not assert live native/Docker integration execution. Normal authoring and the `agents.cs` plus `docfx.cs --build-api-model --validate-samples --verify-docfx-build` completion requirements remain unchanged when editing an actual documentation repository. + +For the browser check, install Playwright through your usual development environment, optionally set `PLAYWRIGHT_MODULE` to its module path, and run `node /scripts/test-run-actions-browser.cjs /_site` against the fixture path printed by the deterministic regression. It checks the actual modern page, both complete clipboard payloads, keyboard activation, Context7 startup, idempotent controls, no-JavaScript links and fetch failure. Windows clipboard newline conversion is compared separately from the exact payload passed to the Clipboard API. From a0ea5340079f70ca0d046717bd1bccd62605bdd7 Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Tue, 17 Nov 2026 21:51:04 +0100 Subject: [PATCH 45/95] =?UTF-8?q?=F0=9F=93=9A=20mention=20run=20actions=20?= =?UTF-8?q?in=20readme?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The README's dotnet-docfx-digest section should point readers at the opt-in generate-run-actions command, so its existence is discoverable without reading the skill. --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 4b5a904a..c1f0aea6 100644 --- a/README.md +++ b/README.md @@ -690,6 +690,8 @@ Dependency updates look simple until a repository encodes compatibility in its p ### Why dotnet-docfx-digest? +Opt in with `dotnet-docfx-digest generate-run-actions` to discover documentation examples repository-wide and generate reusable native/Docker PowerShell assets, compact source-bound associations, accessible copy controls and fallback script links. Generation stays separate from execution and fast validation; see [run actions](skills/dotnet-docfx-digest/references/run-actions.md). Existing template startup code, including Context7, is retained. + API documentation rots the moment code changes. A new public type ships without a namespace page, an extension method never makes it into the `Extension Members` table, a copy/paste example silently stops compiling, and "availability" drifts away from the real target frameworks. The usual fix — telling an agent to "remember to update the docs" — relies on AI memory, which is exactly the thing that fails on the next change. **dotnet-docfx-digest** moves the rules from prose into deterministic .NET 10 tooling, so guidance persists and verification is real. From 811fb74f66e723d5badc7f686c8d67d00df363dc Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Tue, 17 Nov 2026 22:21:53 +0100 Subject: [PATCH 46/95] =?UTF-8?q?=F0=9F=93=9D=20require=20paired=20native?= =?UTF-8?q?=20and=20docker=20run=20delivery?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Runnable examples must surface complete Native and Docker options together so developers get both copyable scripts, and each transport's verification status is tracked independently. Generated DocFX pages associate both assets with the same C# sample so their copy controls appear together. --- skills/dotnet-docfx-digest/SKILL.md | 1 + skills/dotnet-docfx-digest/references/csrun-composition.md | 2 +- skills/dotnet-docfx-digest/references/one-shot-examples.md | 6 +++++- skills/dotnet-docfx-digest/references/run-actions.md | 6 +++--- 4 files changed, 10 insertions(+), 5 deletions(-) diff --git a/skills/dotnet-docfx-digest/SKILL.md b/skills/dotnet-docfx-digest/SKILL.md index b9ce7456..b7287692 100644 --- a/skills/dotnet-docfx-digest/SKILL.md +++ b/skills/dotnet-docfx-digest/SKILL.md @@ -19,6 +19,7 @@ For the explicit logical command `dotnet-docfx-digest generate-run-actions`, rea ## Critical - Prefer complete standalone programs and genuine xUnit v3 tests, delivered through existing `dotnet-csrun` native and Docker one-shot blocks with identical source/dependencies. For APIs requiring an actual application, runner or distinct assembly identity, inspect the maintained example, test and project graph, then provide a pinned repository-backed one-shot test instead. Read [one-shot examples](references/one-shot-examples.md) before publishing execution instructions. Do not expand csrun manifest v1 or manufacture a substitute host. +- Whenever a runnable example is delivered, surface both complete Native and Docker execution options together unless one transport is genuinely unsupported. In a direct Codex response, include each as an independently copyable and executable script; never extract `## Native` alone when the corresponding `## Docker` option exists, point only to a reference/generated file, or require manual assembly. Track verification separately per transport: report `Verified`, `Failed`, `Unverified`, or `Unsupported` only from that transport's own execution or support evidence. For generated DocFX websites, associate both assets with the same C# sample so its Native and Docker copy controls appear together. - This skill is autonomous by default. If the user invokes it without naming a namespace, type, member, or changed API — including a bare direct skill call with no parsed arguments, a host-initiated continuation, or a host re-entry that invokes `dotnet-docfx-digest` directly with no extra arguments after the skill already auto-triggered — assume non-human/autonomous execution, treat the request as a repo-wide DocFX audit and repair task, and do not ask startup scoping or approval-to-continue questions. - Resolve bundled scripts from the loaded `dotnet-docfx-digest` skill directory first. If that install path is unavailable and the target repository contains the repo-managed source copy, fall back to `skills/dotnet-docfx-digest/scripts/*.cs`. Do not claim the scripts are unavailable until both locations have been checked. - `docfx.cs` is fast by default: a plain run validates Markdown, prose, DocFX overwrite layout, namespace pages, extension tables, and required examples **without building, restoring, or running DocFX/gh**. Use it freely during iteration — it discovers the public API from existing DocFX YAML metadata or a conservative source scan, and ends with a `[processes] dotnet=0 msbuild=0 docfx=0 gh=0` summary. Compilation and network access are opt-in. diff --git a/skills/dotnet-docfx-digest/references/csrun-composition.md b/skills/dotnet-docfx-digest/references/csrun-composition.md index b4cb02a6..ee9c58f1 100644 --- a/skills/dotnet-docfx-digest/references/csrun-composition.md +++ b/skills/dotnet-docfx-digest/references/csrun-composition.md @@ -12,4 +12,4 @@ Retain repository-aware validation for unpublished assemblies, project reference All existing gates remain mandatory for documentation completion: `docfx.cs --build-api-model --validate-samples --verify-docfx-build`. Standalone success cannot replace them. For an executable example, choose an allowed `// Program.cs` form or bind the genuine test source to its maintained project context. A standalone xUnit v3 test can be executed by csrun; a test requiring a separate application assembly belongs in the actual project/test graph. A class-library fence with no executed operation supports a compilation claim only. If a separate harness invokes it, disclose and identify both sources; do not claim byte identity. -csrun generates two independent PowerShell blocks from one canonical manifest. DocFX chooses presentation: a concise C# fence may be primary, with execution blocks linked or placed in a suitable conceptual page when useful. Extract the fence from the same canonical source and compare it before claiming exact source-to-execution parity. Do not hand-maintain three C# variants or force both full blocks onto every generated type page. Existing structured overwrite writing preserves BOM, line endings, mapping, prose and unrelated sections; use it where appropriate and inspect localized diffs after repairs. +csrun generates two independent PowerShell blocks from one canonical manifest. Keep the concise C# fence primary and pair Native and Docker delivery in the same presentation unit: complete script blocks in direct Codex responses, copy controls beside the same C# sample on generated DocFX pages, or both complete blocks together on a linked conceptual page. Long scripts need not be repeated inline in every API page when that page provides the paired controls or links to the page containing both options. Never link only to a reference file or require manual assembly. Extract the fence from the same canonical source and compare it before claiming exact source-to-execution parity. Do not hand-maintain three C# variants. Existing structured overwrite writing preserves BOM, line endings, mapping, prose and unrelated sections; use it where appropriate and inspect localized diffs after repairs. diff --git a/skills/dotnet-docfx-digest/references/one-shot-examples.md b/skills/dotnet-docfx-digest/references/one-shot-examples.md index 3b06a0aa..de8bfa94 100644 --- a/skills/dotnet-docfx-digest/references/one-shot-examples.md +++ b/skills/dotnet-docfx-digest/references/one-shot-examples.md @@ -2,9 +2,13 @@ Lead with the developer task, the smallest informative C# example, expected outcome, reproduction and optional further exploration. Keep the API page understandable without execution or external source reading. Follow [contextual source references](contextual-source-references.md): explain what selected links teach beyond the example, even when execution succeeds, and omit references that add no useful depth. Put long execution blocks in an immediately linked conceptual page or disclosure when needed; no manual project assembly, helper installation, repository-layout knowledge or full project dumps. +## Paired execution delivery + +Whenever DocFX Digest delivers a runnable example, deliver the complete Native and Docker options together unless one transport is genuinely unsupported. In a direct Codex response, include both complete, independently copyable and executable script blocks. Never extract only `## Native` when a corresponding `## Docker` section exists, make a reference file or generated asset path the only delivery, or require the developer to assemble a script from fragments. On a DocFX website, place both generated assets in one association with the same C# sample so its Native and Docker copy controls are available together. Keep verification independent: mark a transport `Verified` only after that transport passes; a successful Native run leaves unexecuted Docker `Unverified`, and vice versa. Mark genuine limitations `Unsupported` with the precise reason; do not infer one transport's status from the other. + ## Select and verify -1. Prefer a complete standalone console program or genuine xUnit v3 test. Use `dotnet-csrun`'s existing manifest and `New-CsrunExecutionPair`; publish both independent PowerShell 7 native and disposable Docker blocks. Both decode to identical source and dependencies. Verify each available transport separately; label unavailable transports Unverified with the precise prerequisite. +1. Prefer a complete standalone console program or genuine xUnit v3 test. Use `dotnet-csrun`'s existing manifest and `New-CsrunExecutionPair`; publish both independent PowerShell 7 native and disposable Docker blocks. Both decode to identical source and dependencies. Verify each available transport separately; if a supported transport was not run, label only that transport Unverified with its precise prerequisite. Use Unsupported only for a genuine source/platform incompatibility, with its reason. 2. For intrinsic integration/assembly identity, locate the maintained application/example and associated functional test, inspect project references, shared build settings, SDK, runner and package pins, infrastructure, signing and feeds. Select an exact test that proves the documented claim. Generate one block that downloads a commit-pinned repository snapshot to OS temp, builds/runs its original graph, verifies the intended test actually passed, and cleans up. No generated application, replacement test host, new test runner or multi-project manifest. 3. Use the runner's actual filtering/reporting conventions, inspected from its help and official documentation. MTP/xUnit v3 `--filter-method` is not VSTest `--filter FullyQualifiedName=...`. Report switches vary by version: xUnit v3 4.0.3 uses `--report-xunit-xml`. Require a fresh result report containing the exact intended test, positive executed/passed counts, no skips or runner errors, and matching process status. Exit zero or listing a discovered name alone never proves execution. 4. Verify the entire published block in a fresh PowerShell process, including download, quoting, result checks and cleanup. Offer an independent Docker block using a compatible official .NET SDK image when practical, with no host SDK dependency. Reuse `dotnet-test` for fixture/lifecycle guidance and `dotnet-remote-testing` for existing managed remote workloads; these blocks directly invoke the maintained native runner, not another test engine. The user-requested native path never requires Docker. diff --git a/skills/dotnet-docfx-digest/references/run-actions.md b/skills/dotnet-docfx-digest/references/run-actions.md index a12934c1..175d867c 100644 --- a/skills/dotnet-docfx-digest/references/run-actions.md +++ b/skills/dotnet-docfx-digest/references/run-actions.md @@ -43,10 +43,10 @@ Optional `run-actions.settings.json` beside docfx.json (or `-Settings `) s The generator fills `manifest.source` from the original example; if supplied, it must match. Inspect pinned source, original runner version/report switches and project dependencies before adding a repository recipe; this generator supports the existing xUnit v3/MTP XML protocol only. A recipe may supply `"unsupportedTransports": { "docker": "" }` (or `native`) to publish only the faithful transport and record the limitation; environment unavailability during authoring is never a platform limitation. A different runner, Windows-only dependency or external service may require a separate maintained reproduction. Do not publish a substitute merely to add buttons. Preserve contextual GitHub implementation, usage and test links and explain any unsupported execution limitation in the authoring pass. -The reusable `assets/run-actions.js` module adds **Copy Native** and **Copy Docker** with tooltips, accessible names, keyboard focus and hover visibility. Each click fetches the whole script and writes it to the clipboard; it never evaluates the response. Ordinary **View Native Script**/**View Docker Script** links remain available without JavaScript and on copy failure. Generated imports compose with the last existing modern template `public/main.js`, retaining its exports/start hook and Context7 behavior. If none exists, the command adds a small template layer. Review the configuration/template diff before publishing; use the modern template. Clipboard writes require a secure browser context and permission. +Each supported example gets one association immediately after its C# fence containing both the Native and Docker asset links; the assets therefore belong to the same sample. The reusable `assets/run-actions.js` module adds **Copy Native** and **Copy Docker** controls to that sample together, with tooltips, accessible names, keyboard focus and hover visibility. Each click fetches the whole corresponding script and writes it to the clipboard; it never evaluates the response. Ordinary **View Native Script**/**View Docker Script** links remain available without JavaScript and on copy failure. A genuinely unsupported transport is omitted from the association with its reason retained in `index.json`. Generated imports compose with the last existing modern template `public/main.js`, retaining its exports/start hook and Context7 behavior. If none exists, the command adds a small template layer. Review the configuration/template diff before publishing; use the modern template. Clipboard writes require a secure browser context and permission. -Generation reports `generated`, `unchanged`, `unsupported` and `failed` cases in JSON. `index.json` records source/script fingerprints and separate Native/Docker states. Unchanged fingerprints reuse intact assets, preserving bytes and modification times. `Unverified` means generation only. Explicitly pass `-Verify Native`, `-Verify Docker` or `-Verify Both` to execute each selected script in an independent fresh PowerShell process and retain separate exit outcomes/log paths under OS temp. Verification runs trusted repository/package code and may restore/build/pull images; do not enable it for a large repository merely to generate assets. A changed source/recipe/tool fingerprint invalidates previous verification. Failed execution returns nonzero; missing Docker or SDK affects verification, never valid artifact generation. +Generation reports `generated`, `unchanged`, `unsupported` and `failed` cases in JSON. `index.json` records source/script fingerprints and separate Native/Docker states. Unchanged fingerprints reuse intact assets, preserving bytes and modification times. `Unverified` means generation only. Explicitly pass `-Verify Native`, `-Verify Docker` or `-Verify Both` to execute each selected script in an independent fresh PowerShell process and retain separate exit outcomes/log paths under OS temp. Verification status is per transport: verifying Native alone must leave Docker `Unverified`, and verifying Docker alone must leave Native `Unverified`. Verification runs trusted repository/package code and may restore/build/pull images; do not enable it for a large repository merely to generate assets. A changed source/recipe/tool fingerprint invalidates previous verification. Failed execution returns nonzero; missing Docker or SDK affects verification, never valid artifact generation. -Run the focused deterministic regression with `pwsh -NoProfile -File /scripts/test-run-actions.ps1`. It builds the shared inventory once, checks source/pin/association parity, unsupported cases, second-run bytes/timestamps, stale cleanup and a real DocFX modern render in OS temp. Existing `test-integration-example.ps1` checks exact execution/failure semantics with offline doubles. These checks do not assert live native/Docker integration execution. Normal authoring and the `agents.cs` plus `docfx.cs --build-api-model --validate-samples --verify-docfx-build` completion requirements remain unchanged when editing an actual documentation repository. +Run the focused deterministic regression with `pwsh -NoProfile -File /scripts/test-run-actions.ps1`. It builds the shared inventory once, checks the direct paired-delivery rule, complete Native/Docker reference scripts, same-sample links and copy controls, independent verification status, source/pin parity, unsupported cases, second-run bytes/timestamps, stale cleanup and a real DocFX modern render in OS temp. Existing `test-integration-example.ps1` checks exact execution/failure semantics with offline doubles. These checks do not assert live native/Docker integration execution. Normal authoring and the `agents.cs` plus `docfx.cs --build-api-model --validate-samples --verify-docfx-build` completion requirements remain unchanged when editing an actual documentation repository. For the browser check, install Playwright through your usual development environment, optionally set `PLAYWRIGHT_MODULE` to its module path, and run `node /scripts/test-run-actions-browser.cjs /_site` against the fixture path printed by the deterministic regression. It checks the actual modern page, both complete clipboard payloads, keyboard activation, Context7 startup, idempotent controls, no-JavaScript links and fetch failure. Windows clipboard newline conversion is compared separately from the exact payload passed to the Clipboard API. From 4503d5654ebdb35a12c1a9ec58ec9f9244de769b Mon Sep 17 00:00:00 2001 From: aicia-bot Date: Tue, 17 Nov 2026 22:21:56 +0100 Subject: [PATCH 47/95] =?UTF-8?q?=E2=9C=85=20assert=20paired=20run=20actio?= =?UTF-8?q?n=20delivery=20and=20status?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The focused regression and browser checks now verify the paired Native and Docker contract: complete reference scripts, same-sample copy controls, and independent verification status per transport. --- .../scripts/test-run-actions-browser.cjs | 15 ++++-- .../scripts/test-run-actions.ps1 | 54 +++++++++++++++++-- 2 files changed, 61 insertions(+), 8 deletions(-) diff --git a/skills/dotnet-docfx-digest/scripts/test-run-actions-browser.cjs b/skills/dotnet-docfx-digest/scripts/test-run-actions-browser.cjs index a8a755d6..a8d742f3 100644 --- a/skills/dotnet-docfx-digest/scripts/test-run-actions-browser.cjs +++ b/skills/dotnet-docfx-digest/scripts/test-run-actions-browser.cjs @@ -28,12 +28,15 @@ const assert = require('node:assert/strict'); }); await page.goto(base + '/docs/integration.html'); await page.waitForFunction(() => window.context7 === true); - await page.getByRole('button', {name: 'Copy Native', exact: true}).waitFor(); + const sample = page.locator('pre.docfx-runnable').filter({hasText: 'ShouldBootstrapMinimalWorkerProgram'}); + assert.equal(await sample.count(), 1); + const toolbar = sample.locator('.docfx-run-toolbar'); + assert.equal(await toolbar.getByRole('button').count(), 2, 'both copy controls must belong to the same C# sample'); for (const label of ['Native', 'Docker']) { - const button = page.getByRole('button', {name: `Copy ${label}`, exact: true}); + const button = toolbar.getByRole('button', {name: `Copy ${label}`, exact: true}); await button.focus(); assert.equal(await button.evaluate(b => getComputedStyle(b.parentElement).opacity), '1'); - const href = await page.getByRole('link', {name: `View ${label} Script`}).getAttribute('href'); + const href = await page.locator('.docfx-run-actions').getByRole('link', {name: `View ${label} Script`}).getAttribute('href'); const expected = await (await page.request.get(new URL(href, page.url()).href)).text(); assert.ok(expected.includes('ShouldBootstrapMinimalWorkerProgram')); await button.press('Enter'); @@ -52,8 +55,12 @@ const assert = require('node:assert/strict'); assert.equal(await page.getByRole('button', {name: 'Copy Native', exact: true}).count(), 1); const apiPage = await context.newPage(); await apiPage.goto(base + '/api/fixture.html'); + const apiSample = apiPage.locator('pre.docfx-runnable').filter({hasText: 'ShouldBootstrapMinimalWorkerProgram'}); + assert.equal(await apiSample.count(), 1); + const apiToolbar = apiSample.locator('.docfx-run-toolbar'); + assert.equal(await apiToolbar.getByRole('button').count(), 2, 'overwrite sample must expose both copy controls together'); for (const label of ['Native', 'Docker']) { - const button = apiPage.getByRole('button', {name: `Copy ${label}`, exact: true}); + const button = apiToolbar.getByRole('button', {name: `Copy ${label}`, exact: true}); await button.waitFor(); await button.press('Enter'); await apiPage.getByRole('status').filter({hasText: `${label} script copied`}).waitFor(); diff --git a/skills/dotnet-docfx-digest/scripts/test-run-actions.ps1 b/skills/dotnet-docfx-digest/scripts/test-run-actions.ps1 index 0116e9c0..5313d62b 100644 --- a/skills/dotnet-docfx-digest/scripts/test-run-actions.ps1 +++ b/skills/dotnet-docfx-digest/scripts/test-run-actions.ps1 @@ -11,6 +11,30 @@ function dotnet { $work = if ($OutputRoot) { $OutputRoot } else { Join-Path ([IO.Path]::GetTempPath()) ('docfx-actions-' + [guid]::NewGuid().ToString('N')) } $null = New-Item -ItemType Directory -Path "$work/docs" -Force $reference = Get-Content (Join-Path $PSScriptRoot '../references/one-shot-examples.md') -Raw +$skill = Get-Content (Join-Path $PSScriptRoot '../SKILL.md') -Raw +if (-not $skill.Contains('Whenever a runnable example is delivered, surface both complete Native and Docker execution options together') -or + -not $skill.Contains('never extract `## Native` alone when the corresponding `## Docker` option exists')) { + throw 'The direct Codex delivery contract must require both complete supported transports.' +} +if (-not $reference.Contains('Whenever DocFX Digest delivers a runnable example, deliver the complete Native and Docker options together') -or + -not $reference.Contains('Keep verification independent: mark a transport `Verified` only after that transport passes')) { + throw 'The one-shot reference must preserve paired delivery and independent verification status.' +} +$nativeSection = [regex]::Match($reference, '(?ms)^## Native:[^\r\n]*\r?\n.*?(?=^## Docker:)') +$dockerSection = [regex]::Match($reference, '(?ms)^## Docker:[^\r\n]*\r?\n.*?(?=^## Further exploration)') +$nativeScript = [regex]::Match($nativeSection.Value, '(?s)```powershell\r?\n(?