diff --git a/.github/workflows/validate-skill-templates.yml b/.github/workflows/validate-skill-templates.yml index eb5aac2e..52bed3ee 100644 --- a/.github/workflows/validate-skill-templates.yml +++ b/.github/workflows/validate-skill-templates.yml @@ -35,6 +35,14 @@ jobs: - name: Checkout uses: actions/checkout@v4 + - name: Install .NET LTS and STS SDKs + if: matrix.name == 'templates' + uses: actions/setup-dotnet@v4 + with: + dotnet-version: | + 10.0.x + 11.0.x + - name: Install DocFX CLI if: matrix.name == 'docfx' shell: pwsh diff --git a/CHANGELOG.md b/CHANGELOG.md index 7fd42da4..69664a40 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,29 @@ 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-20 + +This is a minor release that adds the `dotnet-csrun` skill for executable C# evidence, adds source-bound samples, contextual source references, repository-backed one-shot examples, and opt-in run actions to `dotnet-docfx-digest`, changes its example authoring to match the execution context, updates the .NET scaffolds to resolve current compatible test packages across major lines, and fixes sample compile attribution and comma-separated `-Skill` lists in the sync script. + +### Added + +- `dotnet-csrun` skill for creating, verifying, repairing, and auditing small standalone C# console examples and genuine xUnit v3 tests, executed through native or Docker transports with independent verified, compiled only, or unverified status per transport, together with its validator and eval fixtures, +- `dotnet-docfx-digest` source-bound sample contexts that bind each C# fence to a maintained project and source file, and reject bindings that are not evaluated Compile items for the selected framework and configuration, +- `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-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-docfx-digest` optional contextual source references that link maintained source after each example's outcome and execution guidance, +- `dotnet-docfx-digest` `csrun` command (also accepted as `generate-run-actions`) that inventories documentation examples, resolves their published dependencies or maintained integration tests, and generates paired Native and Docker PowerShell assets with a coverage report. + +### 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 requiring every generated `csharp` fence to be a complete compilation unit, and composes with `dotnet-csrun` for compatible standalone runtime examples while keeping its discovery, placement, project-aware compilation, and DocFX build gates authoritative, +- `dotnet-new-app-slnx` and `dotnet-new-lib-slnx` resolve package versions to the newest listed stable candidate that is compatible with each selected target framework, instead of pinning the Codebelt 12.x and xUnit 4.x test-stack lines, and `dotnet-new-app-slnx` no longer aligns ASP.NET Core packages to the target framework major. + +### 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, +- `scripts/sync-skill-install.ps1` splits comma-separated `-Skill` values, so `pwsh -File` invocations with `a,b` sync each named skill instead of treating the whole list as one name. + ## [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 +833,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 diff --git a/README.md b/README.md index 11b276a7..5959abb0 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, verifies, repairs, and audits C# examples and genuine xUnit v3 tests, with paired Native and Docker commands from one manifest, exact package pins, and source-linked execution evidence. Both commands verify and run the latest stable csrun release. | | [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` @@ -687,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 csrun` to inventory documentation examples, resolve their published dependencies or maintained integration tests, and generate paired Native and Docker PowerShell assets. Standalone run scripts execute the C# shown on the page. Each visible sample includes its entry point or test, required inputs, and any assertions. Pinned repository tests are identified by name. The coverage report identifies examples that still need investigation, and verification remains independent for each transport. Generated copy controls and fallback links compose with existing template startup code, including Context7. See [run actions](skills/dotnet-docfx-digest/references/run-actions.md). + 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. @@ -709,7 +714,8 @@ 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, +- **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, - **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, @@ -747,6 +753,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 supports the complete sample lifecycle: create, read-only verify, semantics-preserving repair, and scoped audit. It generates independent Native and disposable Docker PowerShell commands from one manifest, verifies the latest stable csrun release in both, 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? 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. diff --git a/scripts/sync-skill-install.ps1 b/scripts/sync-skill-install.ps1 index 7f495e35..6a4a9786 100644 --- a/scripts/sync-skill-install.ps1 +++ b/scripts/sync-skill-install.ps1 @@ -109,7 +109,14 @@ function Test-SkillTree { $repoRoot = Get-RepoRoot $skillsRoot = Join-Path $repoRoot 'skills' -if (-not $Skill -or $Skill.Count -eq 0) { +if ($PSBoundParameters.ContainsKey('Skill')) { + # `pwsh -File` passes `-Skill a,b` as one string. Split it before validating each name below. + $Skill = @($Skill | ForEach-Object { $_ -split ',' } | ForEach-Object { $_.Trim() } | Where-Object { $_ }) + if ($Skill.Count -eq 0) { + throw 'Specify at least one skill name with -Skill.' + } +} +else { $Skill = @(Get-ChildItem -LiteralPath $skillsRoot -Directory | ForEach-Object { $_.Name }) } diff --git a/scripts/tests/test-scaffold-mtp.ps1 b/scripts/tests/test-scaffold-mtp.ps1 index 0f38662b..055b62d8 100644 --- a/scripts/tests/test-scaffold-mtp.ps1 +++ b/scripts/tests/test-scaffold-mtp.ps1 @@ -29,61 +29,64 @@ function Invoke-DotNet { return ($output -join [Environment]::NewLine) } -function Assert-DotNetFailure { - param([string[]]$Arguments, [string]$ExpectedError) - $output = @(& dotnet @Arguments 2>&1) - $exitCode = $LASTEXITCODE - $diagnostics = $output -join [Environment]::NewLine - if ($exitCode -eq 0 -or $diagnostics -notmatch $ExpectedError) { - throw "dotnet $($Arguments -join ' ') must fail with '$ExpectedError' (exit $exitCode):`n$diagnostics" - } -} - try { [void][System.IO.Directory]::CreateDirectory($workspace) - # Test version-line selection with a newer future major, prereleases, and mismatched ASP.NET majors. + # Verify candidate discovery across major lines, excluding unlisted releases and prereleases. & { function Invoke-RestMethod { param([string]$Uri) if ($Uri.EndsWith('/v3/index.json')) { - return @{ resources = @(@{ '@type' = 'PackageBaseAddress/3.0.0'; '@id' = 'https://fixture.invalid/' }) } + return @{ resources = @(@{ '@type' = 'RegistrationsBaseUrl/3.6.0'; '@id' = 'https://fixture.invalid/' }) } + } + if ($Uri.EndsWith('/older-page.json')) { + return @{ items = @(@{ catalogEntry = @{ version = '11.2.1'; listed = $true } }) } } $versions = switch -Regex ($Uri) { - '/codebelt.extensions.xunit.app/' { @('11.2.1', '12.0.0', '12.0.1', '12.1.0-preview.1', '13.0.0'); break } + '/codebelt.extensions.xunit.app/' { @('12.0.2', '12.0.10', '12.1.0-preview.1', '13.0.0+build-1', '14.0.0'); break } '/xunit.v3(?:.runner.console)?/' { @('3.2.2', '4.0.0', '4.0.1', '4.1.0-preview.1', '5.0.0'); break } - '/microsoft.aspnetcore.' { @('8.0.31', '9.0.14', '10.0.12', '11.0.0'); break } + '/microsoft.aspnetcore.' { @('10.0.12', '11.0.0'); break } default { @('1.0.0', '1.0.1', '2.0.0-preview.1') } } - return @{ versions = $versions } + $leaves = @($versions | ForEach-Object { + @{ catalogEntry = @{ version = $_; listed = ($_ -ne '14.0.0') } } + }) + $pages = @([pscustomobject]@{ items = $leaves }) + if ($Uri -like '*/codebelt.extensions.xunit.app/*') { + $pages += [pscustomobject]@{ '@id' = 'https://fixture.invalid/older-page.json' } + } + return @{ items = $pages } } $resolved = & (Join-Path $repoRoot 'skills/dotnet-new-app-slnx/scripts/resolve-package-versions.ps1') -TargetFramework net10.0 | ConvertFrom-Json foreach ($pair in @( - @('{CODEBELT_EXTENSIONS_XUNIT_APP_VERSION}', '12.0.1'), - @('{XUNIT_V3_VERSION}', '4.0.1'), - @('{XUNIT_V3_RUNNER_CONSOLE_VERSION}', '4.0.1'), - @('{MICROSOFT_ASPNETCORE_OPENAPI_VERSION}', '10.0.12') + @('{CODEBELT_EXTENSIONS_XUNIT_APP_VERSION}', '13.0.0+build-1'), + @('{XUNIT_V3_VERSION}', '5.0.0'), + @('{XUNIT_V3_RUNNER_CONSOLE_VERSION}', '5.0.0'), + @('{MICROSOFT_ASPNETCORE_OPENAPI_VERSION}', '11.0.0') )) { - if ($resolved.($pair[0]).version -ne $pair[1]) { throw "Resolver selected the wrong API line for $($pair[0])." } + if ($resolved.($pair[0]).version -ne $pair[1]) { throw "Resolver returned the wrong newest candidate for $($pair[0])." } + } + if (($resolved.'{CODEBELT_EXTENSIONS_XUNIT_APP_VERSION}'.candidate_versions -join ',') -ne '13.0.0+build-1,12.0.10,12.0.2,11.2.1') { + throw 'The resolver must return stable listed candidates from all registration pages in descending version order.' } foreach ($entry in $resolved.PSObject.Properties.Value) { if ($entry.compatibility_status -ne 'provisional' -or $entry.target_framework -ne 'net10.0') { throw 'Version-index lookup must not claim verified compatibility.' } } - $olderRuntime = & (Join-Path $repoRoot 'skills/dotnet-new-app-slnx/scripts/resolve-package-versions.ps1') -TargetFramework net8.0 | ConvertFrom-Json - if ($olderRuntime.'{CODEBELT_EXTENSIONS_XUNIT_APP_VERSION}'.compatibility_status -ne 'provisional' -or - $olderRuntime.'{CODEBELT_EXTENSIONS_XUNIT_APP_VERSION}'.target_framework -ne 'net8.0') { - throw 'The resolver must preserve provisional status for an unsupported test runtime.' + $stsRuntime = & (Join-Path $repoRoot 'skills/dotnet-new-app-slnx/scripts/resolve-package-versions.ps1') -TargetFramework net11.0 | ConvertFrom-Json + if ($stsRuntime.'{CODEBELT_EXTENSIONS_XUNIT_APP_VERSION}'.compatibility_status -ne 'provisional' -or + $stsRuntime.'{CODEBELT_EXTENSIONS_XUNIT_APP_VERSION}'.target_framework -ne 'net11.0') { + throw 'The resolver must preserve provisional status for the requested test runtime.' } - Write-Host '[PASS] Resolver preserves authorized test-stack majors and excludes prereleases.' + Write-Host '[PASS] Resolver returns stable listed candidates across major lines.' } $sdkVersions = @(& dotnet --list-sdks) if ($LASTEXITCODE -ne 0) { throw 'Unable to enumerate installed SDKs.' } $sdk = @($sdkVersions | ForEach-Object { - if ($_ -match '^(\d+\.\d+\.\d+)\s' -and [version]$Matches[1] -ge [version]'10.0.100') { $Matches[1] } + if ($_ -match '^(\d+\.\d+\.\d+)\s' -and [version]$Matches[1] -ge [version]'11.0.100') { $Matches[1] } } | Sort-Object { [version]$_ } -Descending | Select-Object -First 1) - if ($sdk.Count -ne 1) { throw 'A supported non-preview .NET 10+ SDK is required for scaffold MTP tests.' } + if ($sdk.Count -ne 1) { throw 'A supported non-preview .NET 11+ SDK is required for scaffold MTP tests.' } # Fixed package versions are reproducible regression fixtures, not generated scaffold defaults. $versions = @{ @@ -105,17 +108,14 @@ try { '{BENCHMARKDOTNET_DIAGNOSTICS_WINDOWS_VERSION}' = '0.15.8' '{CODEBELT_EXTENSIONS_BENCHMARKDOTNET_CONSOLE_VERSION}' = '1.3.4' } - # net8 is an incompatibility regression for the fixed v12 stack, not an older-stack workaround. # Only libraries support multiple source TFMs, including source-only netstandard. $cases = @( @{ Variant = 'app'; HostType = 'web'; AppType = 'Web'; Tfm = 'net10.0' }, - @{ Variant = 'app'; HostType = 'console'; AppType = 'Console'; Tfm = 'net9.0' }, - @{ Variant = 'app'; HostType = 'worker'; AppType = 'Worker'; Tfm = 'net10.0' }, - @{ Variant = 'app'; HostType = 'console'; AppType = 'Console'; Tfm = 'net8.0' }, + @{ Variant = 'app'; HostType = 'console'; AppType = 'Console'; Tfm = 'net10.0' }, + @{ Variant = 'app'; HostType = 'worker'; AppType = 'Worker'; Tfm = 'net11.0' }, @{ Variant = 'lib'; Tfm = 'net10.0' }, - @{ Variant = 'lib'; Tfm = 'net9.0' }, - @{ Variant = 'lib'; Tfm = 'net8.0' }, - @{ Variant = 'lib'; Tfm = 'netstandard2.0;net9.0;net10.0' } + @{ Variant = 'lib'; Tfm = 'net11.0' }, + @{ Variant = 'lib'; Tfm = 'netstandard2.0;net10.0;net11.0' } ) foreach ($case in $cases) { $variant = $case.Variant @@ -136,9 +136,8 @@ try { $map['{EXECUTABLE_TARGET_FRAMEWORKS}'] = $runtimeTfms -join ';' $map['{BENCHMARK_RUNNER_TARGET_FRAMEWORK}'] = $runtimeTfms[-1] $map['{BENCHMARK_RUNNER_NAMESPACE}'] = 'benchmark_runner' - $benchmarkRuntimes = @{ 'net8.0' = 'Core80'; 'net9.0' = 'Core90'; 'net10.0' = 'Core10_0' } $map['{BENCHMARK_RUNTIME_JOBS}'] = ($runtimeTfms | ForEach-Object { - " .AddJob(slimJob.WithRuntime(CoreRuntime.$($benchmarkRuntimes[$_])))" + " .AddJob(slimJob.WithRuntime(CoreRuntime.CreateForNewVersion(`"$_`", `"$_`")))" }) -join [Environment]::NewLine $map['{AUTHOR}'] = 'Scaffold Regression' $map['{AUTHOR_EMAIL}'] = 'fixture@example.invalid' @@ -165,8 +164,12 @@ try { throw "$caseName must keep the functional-test namespace rule exactly once." } $bot = [System.IO.File]::ReadAllText((Join-Path $caseRoot '.bot/README.md')) - if (-not $bot.Contains('into root `AGENTS.md`.') -or $bot -match '(?i)Copilot') { - throw "$caseName .bot guidance must point only to root AGENTS.md." + if (-not $agents.Contains('`.bot/README.md` is intentionally tracked. Include it in the initial scaffold commit.') -or + -not $agents.Contains('Never stage or commit any other file under `.bot/`.')) { + throw "$caseName AGENTS.md must explicitly allow the .bot README and prohibit staging or committing other .bot files." + } + if (-not $bot.Contains('Move only finalized, non-confidential guidance into `AGENTS.md`.') -or $bot -match '(?i)Copilot') { + throw "$caseName .bot guidance must direct finalized, non-confidential guidance to AGENTS.md." } Write-Host "[PASS] $caseName emits the complete shared inventory with vendor-neutral root AGENTS.md." # Select a stable installed SDK only in this isolated regression workspace. @@ -286,27 +289,6 @@ public class PriceCalculatorBenchmark if ($runnerTfm.Trim() -ne $runtimeTfms[-1]) { throw "$caseName benchmark runner must target the highest executable TFM." } Write-Host "[PASS] ${caseName}: source matrix retained; tests, benchmarks and runner use executable TFMs only." } - if ($case.Tfm -eq 'net8.0') { - if ($variant -eq 'lib') { - [void](Invoke-DotNet -Arguments @('build', $benchmarkProject, '-c', 'Release', '-p:SkipSignAssembly=true', '--nologo')) - Assert-DotNetFailure -Arguments @('build', $runnerProject, '-c', 'Release', '-p:SkipSignAssembly=true', '--nologo') -ExpectedError 'error NU1202: Package Codebelt.Extensions.BenchmarkDotNet.Console' - } - $expectedError = if ($variant -eq 'app') { 'error NU1202: Package Codebelt.Bootstrapper.Console' } else { "error CS0246: The type or namespace name 'Codebelt'" } - Assert-DotNetFailure -Arguments @('build', $testProject, '-c', 'Release', '-p:SkipSignAssembly=true', '--nologo') -ExpectedError $expectedError - $testAssetsPath = Join-Path $caseRoot (Join-Path (Split-Path $testProject) 'obj/project.assets.json') - $testAssets = [System.IO.File]::ReadAllText($testAssetsPath) | ConvertFrom-Json - $nuspecPaths = @($testAssets.packageFolders.PSObject.Properties.Name | ForEach-Object { - Join-Path $_ 'codebelt.extensions.xunit.app/12.0.1/codebelt.extensions.xunit.app.nuspec' - } | Where-Object { Test-Path -LiteralPath $_ -PathType Leaf }) - if ($nuspecPaths.Count -ne 1) { throw "$caseName could not locate the restored Codebelt app meta-package metadata." } - [xml]$nuspec = [System.IO.File]::ReadAllText($nuspecPaths[0]) - $groups = @($nuspec.package.metadata.dependencies.group.targetFramework) - if ($groups -contains 'net8.0' -or $groups.Count -ne 2 -or $groups -notcontains 'net9.0' -or $groups -notcontains 'net10.0') { - throw "$caseName expected only net9/net10 dependency groups in the fixed Codebelt app meta-package." - } - Write-Host "[PASS] ${caseName}: incompatible net8 stack fails explicitly; Codebelt app meta-package has no net8 dependency group." - continue - } [void](Invoke-DotNet -Arguments @('build', 'MtpScaffold.slnx', '-c', 'Release', '-p:SkipSignAssembly=true', '--nologo')) foreach ($runtimeTfm in $runtimeTfms) { $help = Invoke-DotNet -Arguments @('test', '--project', $testProject, '--framework', $runtimeTfm, '-c', 'Release', '--no-build', '--help') diff --git a/scripts/validate-dotnet-csrun.ps1 b/scripts/validate-dotnet-csrun.ps1 new file mode 100644 index 00000000..4c6cbc57 --- /dev/null +++ b/scripts/validate-dotnet-csrun.ps1 @@ -0,0 +1,111 @@ +#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.' } +& 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) +[Console]::OutputEncoding = $OutputEncoding +$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'), + @('standalone-host', 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'), + @('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" + # 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 } + } + $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 + 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 { + $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}); 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" + } + $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: $($cases.Count)" + diff --git a/scripts/validate-skill-templates.ps1 b/scripts/validate-skill-templates.ps1 index b435caf7..c377ac2f 100644 --- a/scripts/validate-skill-templates.ps1 +++ b/scripts/validate-skill-templates.ps1 @@ -633,7 +633,7 @@ function Get-AppPlaceholderMap { $targetMajor = if ($TargetFramework -match '^net(\d+)\.0$') { [int]$Matches[1] } else { throw "Unsupported TargetFramework for test map: $TargetFramework" } $ubuntuTag = "codebeltnet/ubuntu-testrunner:$targetMajor" $aspNetAlignedVersion = switch ($targetMajor) { - 9 { '9.0.14' } + 11 { '11.0.0' } 10 { '10.0.5' } default { throw "No test fixture version configured for TFM major $targetMajor" } } @@ -827,6 +827,23 @@ 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) } + } + 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 { if (-not [string]::IsNullOrWhiteSpace($Ref)) { return } $prSkill = Get-FileText -RepoRoot $repoRoot -RelativePath 'skills/git-remote-pr/SKILL.md' -GitRef $Ref @@ -1057,7 +1074,6 @@ Add-ValidationResult -Results $results -Name 'App skill documents web-family App Assert-Contains -Name 'dotnet-new-app-slnx/SKILL.md' -Content $skill -Needle 'treat a blank response as accepting that shown value' Assert-Contains -Name 'dotnet-new-app-slnx/SKILL.md' -Content $skill -Needle 'Web` as the host family' Assert-Contains -Name 'dotnet-new-app-slnx/SKILL.md' -Content $skill -Needle 'Do **not** substitute vanilla .NET hosting code as a workaround.' - Assert-Contains -Name 'dotnet-new-app-slnx/SKILL.md' -Content $skill -Needle 'resolve the latest stable version whose **major** matches the selected `{TARGET_FRAMEWORK}` major' Assert-Contains -Name 'dotnet-new-app-slnx/SKILL.md' -Content $skill -Needle '`Directory.Packages.props` is the authoritative source of NuGet package versions for the generated app scaffold.' Assert-Contains -Name 'dotnet-new-app-slnx/SKILL.md' -Content $skill -Needle 'Do **not** inline `Version=` attributes into `.csproj` files or `Directory.Build.props` as a workaround for restore or build issues.' Assert-Contains -Name 'dotnet-new-app-slnx/SKILL.md' -Content $skill -Needle 'If the lookup step fails, halt and report it instead of guessing.' @@ -1098,8 +1114,8 @@ Add-ValidationResult -Results $results -Name 'Both scaffolds select xUnit 4, Cod Assert-NotContains -Name $skillRoot -Content $props -Needle "Include=`"$id`"" Assert-NotContains -Name $skillRoot -Content $packages -Needle "Include=`"$id`"" } - Assert-Contains -Name $skillRoot -Content $skill -Needle '12.x' - Assert-Contains -Name $skillRoot -Content $skill -Needle '4.x' + Assert-Contains -Name $skillRoot -Content $skill -Needle 'Consider releases across all major lines.' + Assert-Contains -Name $skillRoot -Content $skill -Needle 'try the next newest listed stable candidate' Assert-Contains -Name $skillRoot -Content $skill -Needle '--report-xunit-trx --coverlet --coverlet-output-format opencover' if ($variant -eq 'lib') { $pipeline = Get-FileText -RepoRoot $repoRoot -RelativePath "$skillRoot/assets/shared/.github/workflows/ci-pipeline.yml" -GitRef $Ref @@ -1210,13 +1226,13 @@ Add-ValidationResult -Results $results -Name 'App reference guide uses ROOT_NAME Assert-Contains -Name 'dotnet-new-app-slnx/references/app.md' -Content $guide -Needle '`web-api` (`Web API`)' Assert-Contains -Name 'dotnet-new-app-slnx/references/app.md' -Content $guide -Needle '`web-mvc` (`MVC`)' Assert-Contains -Name 'dotnet-new-app-slnx/references/app.md' -Content $guide -Needle '`webapp` (`Web App / Razor`)' - Assert-Contains -Name 'dotnet-new-app-slnx/references/app.md' -Content $guide -Needle 'a `net9.0` app should resolve these packages to the latest stable `9.x` version, not `10.x`' + Assert-Contains -Name 'dotnet-new-app-slnx/references/app.md' -Content $guide -Needle 'Verify framework assets, ASP.NET Core runtime requirements, dependency ranges, restore, and build for the selected TFM' } Add-ValidationResult -Results $results -Name 'App skill ships deterministic package version resolver script' -Action { $script = Get-FileText -RepoRoot $repoRoot -RelativePath 'skills/dotnet-new-app-slnx/scripts/resolve-package-versions.ps1' -GitRef $Ref Assert-Contains -Name 'resolve-package-versions.ps1' -Content $script -Needle 'https://api.nuget.org/v3/index.json' - Assert-Contains -Name 'resolve-package-versions.ps1' -Content $script -Needle 'PackageBaseAddress/3.0.0' + Assert-Contains -Name 'resolve-package-versions.ps1' -Content $script -Needle 'RegistrationsBaseUrl/3.6.0' Assert-Contains -Name 'resolve-package-versions.ps1' -Content $script -Needle 'TargetFramework' Assert-Contains -Name 'resolve-package-versions.ps1' -Content $script -Needle 'if ([string]::IsNullOrWhiteSpace($TemplatePath))' Assert-Contains -Name 'resolve-package-versions.ps1' -Content $script -Needle "Directory.Packages.props'" @@ -1336,7 +1352,7 @@ Add-ValidationResult -Results $results -Name 'Scaffolds use root AGENTS.md as th } # Check small semantic anchors and prohibitions, rather than duplicating entire prose sections. foreach ($needle in @( - 'xunit.v3', 'Codebelt.Extensions.Xunit.App v12', 'Codebelt.Extensions.Xunit', + 'xunit.v3', 'Codebelt.Extensions.Xunit.App base classes', 'Codebelt.Extensions.Xunit', 'ITestOutputHelper', 'base(output)', 'TestOutput.WriteLine', '[Fact]', '[Theory]', '[InlineData]', 'ShouldReturnTrue_WhenConditionIsMet', 'Assert.Equal', 'System Under Test (SUT)', 'RootNamespace', 'dummies, fakes, stubs and spies', 'Moq', 'virtual or abstract', 'JsonMarshaller', @@ -1421,7 +1437,9 @@ Add-ValidationResult -Results $results -Name 'Scaffolds use root AGENTS.md as th } } $bot = Get-FileText -RepoRoot $repoRoot -RelativePath "$skillRoot/assets/shared/.bot/README.md" -GitRef $Ref - Assert-Contains -Name "$skillRoot .bot README" -Content $bot -Needle 'into root `AGENTS.md`.' + Assert-Contains -Name "$skillRoot .bot README" -Content $bot -Needle 'The `.bot/README.md` file itself is intentionally tracked in source control.' + Assert-Contains -Name "$skillRoot .bot README" -Content $bot -Needle 'All other `.bot/` working material remains local-only and excluded from source control.' + Assert-Contains -Name "$skillRoot .bot README" -Content $bot -Needle 'Move only finalized, non-confidential guidance into `AGENTS.md`.' foreach ($path in (Get-RepoFileList -RepoRoot $repoRoot -RelativePath $skillRoot -GitRef $Ref)) { if ([System.IO.Path]::GetExtension($path) -notin @('.md', '.json', '.ps1')) { continue } $content = Get-FileText -RepoRoot $repoRoot -RelativePath "$skillRoot/$path" -GitRef $Ref @@ -3659,17 +3677,17 @@ Add-ValidationResult -Results $results -Name 'Rendered app templates compile in $sharedAssetFiles = Get-RepoFileList -RepoRoot $repoRoot -RelativePath 'skills/dotnet-new-app-slnx/assets/shared' -GitRef $Ref $cases = @( [pscustomobject]@{ - Name = 'ConsoleMinimal-net9' + Name = 'ConsoleMinimal-net10' AppType = 'Console' - TargetFramework = 'net9.0' + TargetFramework = 'net10.0' Csproj = 'skills/dotnet-new-app-slnx/assets/app/console.csproj' Program = 'skills/dotnet-new-app-slnx/assets/app/console/Program.minimal.cs' ExtraFiles = @() } [pscustomobject]@{ - Name = 'ConsoleStartup-net9' + Name = 'ConsoleStartup-net10' AppType = 'Console' - TargetFramework = 'net9.0' + TargetFramework = 'net10.0' Csproj = 'skills/dotnet-new-app-slnx/assets/app/console.csproj' Program = 'skills/dotnet-new-app-slnx/assets/app/console/Program.startup.cs' ExtraFiles = @( @@ -3677,9 +3695,9 @@ Add-ValidationResult -Results $results -Name 'Rendered app templates compile in ) } [pscustomobject]@{ - Name = 'WorkerMinimal-net9' + Name = 'WorkerMinimal-net10' AppType = 'Worker' - TargetFramework = 'net9.0' + TargetFramework = 'net10.0' Csproj = 'skills/dotnet-new-app-slnx/assets/app/worker.csproj' Program = 'skills/dotnet-new-app-slnx/assets/app/worker/Program.minimal.cs' ExtraFiles = @( @@ -3687,25 +3705,25 @@ Add-ValidationResult -Results $results -Name 'Rendered app templates compile in ) } [pscustomobject]@{ - Name = 'WebMinimal-net9' + Name = 'WebMinimal-net10' AppType = 'Web' - TargetFramework = 'net9.0' + TargetFramework = 'net10.0' Csproj = 'skills/dotnet-new-app-slnx/assets/app/web.csproj' Program = 'skills/dotnet-new-app-slnx/assets/app/web/Program.minimal.cs' ExtraFiles = @() } [pscustomobject]@{ - Name = 'WebApiMinimal-net9' + Name = 'WebApiMinimal-net11' AppType = 'Api' - TargetFramework = 'net9.0' + TargetFramework = 'net11.0' Csproj = 'skills/dotnet-new-app-slnx/assets/app/web-api.csproj' Program = 'skills/dotnet-new-app-slnx/assets/app/web-api/Program.minimal.cs' ExtraFiles = @() } [pscustomobject]@{ - Name = 'MvcStartup-net9' + Name = 'MvcStartup-net10' AppType = 'Mvc' - TargetFramework = 'net9.0' + TargetFramework = 'net10.0' Csproj = 'skills/dotnet-new-app-slnx/assets/app/web-mvc.csproj' Program = 'skills/dotnet-new-app-slnx/assets/app/web-mvc/Program.startup.cs' ExtraFiles = @( @@ -3718,9 +3736,9 @@ Add-ValidationResult -Results $results -Name 'Rendered app templates compile in ) } [pscustomobject]@{ - Name = 'WebAppMinimal-net9' + Name = 'WebAppMinimal-net10' AppType = 'WebApp' - TargetFramework = 'net9.0' + TargetFramework = 'net10.0' Csproj = 'skills/dotnet-new-app-slnx/assets/app/webapp.csproj' Program = 'skills/dotnet-new-app-slnx/assets/app/webapp/Program.minimal.cs' ExtraFiles = @( @@ -3822,8 +3840,8 @@ Add-ValidationResult -Results $results -Name 'Rendered library templates leave n '{REPOSITORY_URL}' = 'https://github.com/acme/mylibrary' '{REPO_OWNER}' = 'acme' '{REPO_SLUG}' = 'mylibrary' - '{TARGET_FRAMEWORKS}' = 'net10.0;net8.0' - '{EXECUTABLE_TARGET_FRAMEWORKS}' = 'net10.0;net8.0' + '{TARGET_FRAMEWORKS}' = 'net11.0;net10.0' + '{EXECUTABLE_TARGET_FRAMEWORKS}' = 'net11.0;net10.0' '{DOCFX_TARGET_FRAMEWORK}' = 'net10.0' '{BENCHMARK_RUNNER_PROJECT_NAME}' = 'benchmark-runner' '{BENCHMARK_RUNNER_NAMESPACE}' = 'benchmark_runner' @@ -3845,6 +3863,18 @@ 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' + } + [pscustomobject]@{ + Name = 'DocFX run actions report coverage and deliver paired source-bound recipes' + Path = Join-Path $repoRoot 'skills/dotnet-docfx-digest/scripts/test-run-actions.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' diff --git a/skills/dotnet-csrun/SKILL.md b/skills/dotnet-csrun/SKILL.md new file mode 100644 index 00000000..3bcc2f4b --- /dev/null +++ b/skills/dotnet-csrun/SKILL.md @@ -0,0 +1,66 @@ +--- +name: dotnet-csrun +description: > + 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. + +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 and dependencies. Both resolve and verify the latest stable csrun release asset at runtime. Docker supplies the SDK and PowerShell and executes that verified asset. + +## 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. 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; 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. + +## 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. | + +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 + +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 = @{ + schemaVersion = 1 + mode = 'console' + framework = 'net10.0' + source = @' +using System; +Console.WriteLine(42); +'@ +} | ConvertTo-Json -Depth 8 +``` + +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 new file mode 100644 index 00000000..6f524806 --- /dev/null +++ b/skills/dotnet-csrun/evals/evals.json @@ -0,0 +1,377 @@ +{ + "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 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 two independent native and Docker blocks 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 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.", + "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 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.", + "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 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.", + "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 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);", + "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 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.", + "id": 6, + "files": [ + "evals/files/console-net11.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 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.", + "id": 7, + "files": [ + "evals/files/unicode.json" + ] + }, + { + "expectations": [ + "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 two independently complete native and Docker copy/paste blocks without project scaffolding or floating package versions." + ], + "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": [ + "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 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?", + "id": 9, + "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." + ] + }, + { + "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." + ] + }, + { + "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/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" +} 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/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/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/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/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/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/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/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 new file mode 100644 index 00000000..2837bbb0 --- /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; 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 +} 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/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"; +} diff --git a/skills/dotnet-csrun/references/docfx.md b/skills/dotnet-csrun/references/docfx.md new file mode 100644 index 00000000..03fb37df --- /dev/null +++ b/skills/dotnet-csrun/references/docfx.md @@ -0,0 +1,13 @@ +# 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. + +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. + +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 new file mode 100644 index 00000000..ef3e2971 --- /dev/null +++ b/skills/dotnet-csrun/references/execution.md @@ -0,0 +1,38 @@ +# 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. + +The paired wrappers fetch the latest stable csrun release from GitHub and check the asset SHA-256 digest before execution. The Docker wrapper streams the verified asset and UTF-8 manifest over stdin and runs the asset in a Linux image that provides PowerShell and the target SDK. 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. + +## 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. Record the observed image digest for the SDK environment and the downloaded engine release and digest separately. + +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. + +```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." } +``` + +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/feasibility.md b/skills/dotnet-csrun/references/feasibility.md new file mode 100644 index 00000000..1d523742 --- /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. + +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/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/manifest.md b/skills/dotnet-csrun/references/manifest.md new file mode 100644 index 00000000..09d7d048 --- /dev/null +++ b/skills/dotnet-csrun/references/manifest.md @@ -0,0 +1,21 @@ +# 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. + +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 new file mode 100644 index 00000000..3b7fe24f --- /dev/null +++ b/skills/dotnet-csrun/references/presentation.md @@ -0,0 +1,28 @@ +# Readable examples and honest evidence + +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 ''` to use a reviewed local engine. By default, the generated native block queries GitHub at runtime for the latest stable release and verifies the downloaded script against the SHA-256 digest in that release's asset metadata. Both this release selection and SDK-oriented Docker tags can change over time. The helper generates the blocks without making network requests or executing samples. Its JSON literal preserves multiline C#, Unicode, quotes, raw strings, dollars, and PowerShell here-string terminators. [csrun source and releases](https://github.com/codebeltnet/csrun) + +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/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. + +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/standalone-example.md b/skills/dotnet-csrun/references/standalone-example.md new file mode 100644 index 00000000..07648448 --- /dev/null +++ b/skills/dotnet-csrun/references/standalone-example.md @@ -0,0 +1,208 @@ +# 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 + +The native block requires access to GitHub and NuGet. It downloads the latest stable release and checks the SHA-256 digest published by GitHub before executing the script with your permissions. [csrun source and releases](https://github.com/codebeltnet/csrun) + +```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 +$verifyTests = $true +function Assert-CsrunTestOutput([string] $Output) { + $lines = @($Output -split '\r?\n') + $headers = @($lines | Where-Object { $_ -match '^Test run summary: Passed! - .+\)$' }) + if ($headers.Count -ne 1) { throw 'Expected exactly one completed xUnit test summary.' } + $headerIndex = [Array]::IndexOf($lines, $headers[0]) + $summaryLines = @($lines | Select-Object -Skip ($headerIndex + 1) -First 4) + $counts = @{} + foreach ($line in $summaryLines) { + if ($line -match '^\s*(total|failed|succeeded|skipped):\s*(\d+)\s*$') { $counts[$Matches[1]] = [int]$Matches[2] } + } + if ($counts.Count -ne 4) { throw 'The xUnit test summary counts are incomplete or ambiguous.' } + $failed = $counts.failed + $passed = $counts.succeeded + $skipped = $counts.skipped + $total = $counts.total + if ($total -lt 1 -or $passed -lt 1 -or $failed -ne 0 -or $skipped -ne 0 -or $passed -ne $total) { + throw 'Tests must execute at least once, all pass, and none fail or skip.' + } +} +# Downloads and executes the latest stable csrun release with your permissions. +# Source and release history: https://github.com/codebeltnet/csrun +$engineDirectory = Join-Path ([IO.Path]::GetTempPath()) ('csrun-' + [guid]::NewGuid().ToString('N')) +$null = New-Item -ItemType Directory -Path $engineDirectory +$enginePath = Join-Path $engineDirectory 'csrun.ps1' +$process = $null +try { + $release = Invoke-RestMethod 'https://api.github.com/repos/codebeltnet/csrun/releases/latest' + $assets = @($release.assets | Where-Object name -CEQ 'csrun.ps1') + if ($assets.Count -ne 1 -or $assets[0].digest -notmatch '^sha256:[0-9a-f]{64}$') { + throw "csrun release $($release.tag_name) must publish one csrun.ps1 asset with a SHA-256 digest." + } + $asset = $assets[0] + Invoke-WebRequest $asset.browser_download_url -OutFile $enginePath + $actualHash = (Get-FileHash -LiteralPath $enginePath -Algorithm SHA256).Hash + if ("sha256:$actualHash" -ne $asset.digest) { throw "csrun asset checksum mismatch: $actualHash" } +$startInfo = [Diagnostics.ProcessStartInfo]::new('pwsh') +foreach ($argument in @('-NoProfile','-NonInteractive','-File')) { $startInfo.ArgumentList.Add($argument) } +$startInfo.ArgumentList.Add($enginePath) +$startInfo.ArgumentList.Add('-ManifestJson') +$startInfo.ArgumentList.Add($manifest) +$startInfo.RedirectStandardOutput = $true +$startInfo.RedirectStandardError = $true +$startInfo.UseShellExecute = $false +$process = [Diagnostics.Process]::new() +$process.StartInfo = $startInfo +if (-not $process.Start()) { throw 'Could not start csrun.' } +$stdoutTask = $process.StandardOutput.ReadToEndAsync() +$stderrTask = $process.StandardError.ReadToEndAsync() +$process.WaitForExit() +$output = $stdoutTask.GetAwaiter().GetResult() +$diagnostics = $stderrTask.GetAwaiter().GetResult() +Write-Output $output +if ($diagnostics) { [Console]::Error.Write($diagnostics) } +} catch { + [Console]::Error.WriteLine("csrun diagnostics retained in: $engineDirectory") + throw +} finally { + $resolvedTemp = [IO.Path]::TrimEndingDirectorySeparator([IO.Path]::GetFullPath([IO.Path]::GetTempPath())) + $resolvedEngineDirectory = [IO.Path]::GetFullPath($engineDirectory) + if ([IO.Path]::GetDirectoryName($resolvedEngineDirectory) -ne $resolvedTemp -or + [IO.Path]::GetFileName($resolvedEngineDirectory) -cnotmatch '^csrun-[a-f0-9]{32}$') { throw 'Unsafe cleanup path.' } + if ($process -and $process.ExitCode -eq 0) { Remove-Item -LiteralPath $resolvedEngineDirectory -Recurse -Force } +} +if ($process.ExitCode -ne 0) { throw "csrun execution failed with exit code $($process.ExitCode). $diagnostics" } +if ($verifyTests) { Assert-CsrunTestOutput $output } +} +``` + +## Disposable Docker: PowerShell 7 and Docker with Linux containers + +Docker provides the .NET SDK and PowerShell. This block fetches and verifies the latest csrun release using the same procedure as Native. The Docker wrapper streams the asset and manifest over stdin. The command needs network access to GitHub and NuGet. + +```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 +$verifyTests = $true +function Assert-CsrunTestOutput([string] $Output) { + $lines = @($Output -split '\r?\n') + $headers = @($lines | Where-Object { $_ -match '^Test run summary: Passed! - .+\)$' }) + if ($headers.Count -ne 1) { throw 'Expected exactly one completed xUnit test summary.' } + $headerIndex = [Array]::IndexOf($lines, $headers[0]) + $summaryLines = @($lines | Select-Object -Skip ($headerIndex + 1) -First 4) + $counts = @{} + foreach ($line in $summaryLines) { + if ($line -match '^\s*(total|failed|succeeded|skipped):\s*(\d+)\s*$') { $counts[$Matches[1]] = [int]$Matches[2] } + } + if ($counts.Count -ne 4) { throw 'The xUnit test summary counts are incomplete or ambiguous.' } + $failed = $counts.failed + $passed = $counts.succeeded + $skipped = $counts.skipped + $total = $counts.total + if ($total -lt 1 -or $passed -lt 1 -or $failed -ne 0 -or $skipped -ne 0 -or $passed -ne $total) { + throw 'Tests must execute at least once, all pass, and none fail or skip.' + } +} +# Downloads and executes the latest stable csrun release with your permissions. +# Source and release history: https://github.com/codebeltnet/csrun +$engineDirectory = Join-Path ([IO.Path]::GetTempPath()) ('csrun-' + [guid]::NewGuid().ToString('N')) +$null = New-Item -ItemType Directory -Path $engineDirectory +$enginePath = Join-Path $engineDirectory 'csrun.ps1' +$process = $null +try { + $release = Invoke-RestMethod 'https://api.github.com/repos/codebeltnet/csrun/releases/latest' + $assets = @($release.assets | Where-Object name -CEQ 'csrun.ps1') + if ($assets.Count -ne 1 -or $assets[0].digest -notmatch '^sha256:[0-9a-f]{64}$') { + throw "csrun release $($release.tag_name) must publish one csrun.ps1 asset with a SHA-256 digest." + } + $asset = $assets[0] + Invoke-WebRequest $asset.browser_download_url -OutFile $enginePath + $actualHash = (Get-FileHash -LiteralPath $enginePath -Algorithm SHA256).Hash + if ("sha256:$actualHash" -ne $asset.digest) { throw "csrun asset checksum mismatch: $actualHash" } +$enginePayload = [Convert]::ToBase64String([IO.File]::ReadAllBytes($enginePath)) +$containerInput = $enginePayload + "`n" + $manifest +$command = ' +$ErrorActionPreference = "Stop" +$enginePath = Join-Path ([IO.Path]::GetTempPath()) ("csrun-release-" + [guid]::NewGuid().ToString("N") + ".ps1") +$engineBytes = [Convert]::FromBase64String([Console]::In.ReadLine()) +[IO.File]::WriteAllBytes($enginePath, $engineBytes) +$manifest = [Console]::In.ReadToEnd() +& $enginePath -ManifestJson $manifest +exit $LASTEXITCODE +' +$output = (@($containerInput | & docker run --rm -i --entrypoint pwsh 'codebeltnet/csrun:10' -NoProfile -NonInteractive -Command $command) -join [Environment]::NewLine) +$process = [pscustomobject]@{ ExitCode = $LASTEXITCODE } +$diagnostics = '' +Write-Output $output +} catch { + [Console]::Error.WriteLine("csrun diagnostics retained in: $engineDirectory") + throw +} finally { + $resolvedTemp = [IO.Path]::TrimEndingDirectorySeparator([IO.Path]::GetFullPath([IO.Path]::GetTempPath())) + $resolvedEngineDirectory = [IO.Path]::GetFullPath($engineDirectory) + if ([IO.Path]::GetDirectoryName($resolvedEngineDirectory) -ne $resolvedTemp -or + [IO.Path]::GetFileName($resolvedEngineDirectory) -cnotmatch '^csrun-[a-f0-9]{32}$') { throw 'Unsafe cleanup path.' } + if ($process -and $process.ExitCode -eq 0) { Remove-Item -LiteralPath $resolvedEngineDirectory -Recurse -Force } +} +if ($process.ExitCode -ne 0) { throw "csrun execution failed with exit code $($process.ExitCode). $diagnostics" } +if ($verifyTests) { Assert-CsrunTestOutput $output } +} +``` + +The native wrapper resolves the latest stable release each time it runs. For reproducible runs, use a reviewed local engine via the sample helper's `-EnginePath` option and pin the Docker image by digest. The focused helper tests enforce parity with the maintained manifest. [Presentation guidance](presentation.md) diff --git a/skills/dotnet-csrun/references/verification.md b/skills/dotnet-csrun/references/verification.md new file mode 100644 index 00000000..2357a712 --- /dev/null +++ b/skills/dotnet-csrun/references/verification.md @@ -0,0 +1,47 @@ +# 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, 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 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 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. + +## 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. + +## 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 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. + +## 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. diff --git a/skills/dotnet-csrun/scripts/sample-tools.ps1 b/skills/dotnet-csrun/scripts/sample-tools.ps1 new file mode 100644 index 00000000..c6f7440d --- /dev/null +++ b/skills/dotnet-csrun/scripts/sample-tools.ps1 @@ -0,0 +1,222 @@ +#requires -Version 7.0 +# Dot-source these artifact helpers. They do not validate manifests or execute samples. +Set-StrictMode -Version Latest + +$script:CsrunTestVerificationTemplate = @' +function Assert-CsrunTestOutput([string] $Output) { + $lines = @($Output -split '\r?\n') + $headers = @($lines | Where-Object { $_ -match '^Test run summary: Passed! - .+\)$' }) + if ($headers.Count -ne 1) { throw 'Expected exactly one completed xUnit test summary.' } + $headerIndex = [Array]::IndexOf($lines, $headers[0]) + $summaryLines = @($lines | Select-Object -Skip ($headerIndex + 1) -First 4) + $counts = @{} + foreach ($line in $summaryLines) { + if ($line -match '^\s*(total|failed|succeeded|skipped):\s*(\d+)\s*$') { $counts[$Matches[1]] = [int]$Matches[2] } + } + if ($counts.Count -ne 4) { throw 'The xUnit test summary counts are incomplete or ambiguous.' } + $failed = $counts.failed + $passed = $counts.succeeded + $skipped = $counts.skipped + $total = $counts.total + if ($total -lt 1 -or $passed -lt 1 -or $failed -ne 0 -or $skipped -ne 0 -or $passed -ne $total) { + throw 'Tests must execute at least once, all pass, and none fail or skip.' + } +} +'@ + +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 + $verifyTests = (ConvertFrom-Json -InputObject $identity.ManifestJson).mode -eq 'test' + 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 = @' +if ($process.ExitCode -ne 0) { throw "csrun execution failed with exit code $($process.ExitCode). $diagnostics" } +if ($verifyTests) { Assert-CsrunTestOutput $output } +'@ + $engineSetup = if ($EnginePath) { + '$enginePath = ' + (Quote-Literal ([IO.Path]::GetFullPath($EnginePath))) + "`nif (-not (Test-Path -LiteralPath `$enginePath -PathType Leaf)) { throw 'csrun engine asset not found.' }" + } else { + @' +# Downloads and executes the latest stable csrun release with your permissions. +# Source and release history: https://github.com/codebeltnet/csrun +$engineDirectory = Join-Path ([IO.Path]::GetTempPath()) ('csrun-' + [guid]::NewGuid().ToString('N')) +$null = New-Item -ItemType Directory -Path $engineDirectory +$enginePath = Join-Path $engineDirectory 'csrun.ps1' +$process = $null +try { + $release = Invoke-RestMethod 'https://api.github.com/repos/codebeltnet/csrun/releases/latest' + $assets = @($release.assets | Where-Object name -CEQ 'csrun.ps1') + if ($assets.Count -ne 1 -or $assets[0].digest -notmatch '^sha256:[0-9a-f]{64}$') { + throw "csrun release $($release.tag_name) must publish one csrun.ps1 asset with a SHA-256 digest." + } + $asset = $assets[0] + Invoke-WebRequest $asset.browser_download_url -OutFile $enginePath + $actualHash = (Get-FileHash -LiteralPath $enginePath -Algorithm SHA256).Hash + if ("sha256:$actualHash" -ne $asset.digest) { throw "csrun asset checksum mismatch: $actualHash" } +'@ + } + $nativeInvoke = @' +$startInfo = [Diagnostics.ProcessStartInfo]::new('pwsh') +foreach ($argument in @('-NoProfile','-NonInteractive','-File')) { $startInfo.ArgumentList.Add($argument) } +$startInfo.ArgumentList.Add($enginePath) +$startInfo.ArgumentList.Add('-ManifestJson') +$startInfo.ArgumentList.Add($manifest) +$startInfo.RedirectStandardOutput = $true +$startInfo.RedirectStandardError = $true +$startInfo.UseShellExecute = $false +$process = [Diagnostics.Process]::new() +$process.StartInfo = $startInfo +if (-not $process.Start()) { throw 'Could not start csrun.' } +$stdoutTask = $process.StandardOutput.ReadToEndAsync() +$stderrTask = $process.StandardError.ReadToEndAsync() +$process.WaitForExit() +$output = $stdoutTask.GetAwaiter().GetResult() +$diagnostics = $stderrTask.GetAwaiter().GetResult() +Write-Output $output +if ($diagnostics) { [Console]::Error.Write($diagnostics) } +'@ + # The image supplies the SDK and PowerShell. Execute the same release asset as Native. + $dockerInvoke = @' +$enginePayload = [Convert]::ToBase64String([IO.File]::ReadAllBytes($enginePath)) +$containerInput = $enginePayload + "`n" + $manifest +$command = ' +$ErrorActionPreference = "Stop" +$enginePath = Join-Path ([IO.Path]::GetTempPath()) ("csrun-release-" + [guid]::NewGuid().ToString("N") + ".ps1") +$engineBytes = [Convert]::FromBase64String([Console]::In.ReadLine()) +[IO.File]::WriteAllBytes($enginePath, $engineBytes) +$manifest = [Console]::In.ReadToEnd() +& $enginePath -ManifestJson $manifest +exit $LASTEXITCODE +' +$output = (@($containerInput | & docker run --rm -i --entrypoint pwsh __IMAGE__ -NoProfile -NonInteractive -Command $command) -join [Environment]::NewLine) +$process = [pscustomobject]@{ ExitCode = $LASTEXITCODE } +$diagnostics = '' +Write-Output $output +'@ + $dockerInvoke = $dockerInvoke.Replace('__IMAGE__', (Quote-Literal $Image)) + $engineCleanup = if (-not $EnginePath) { + @' +} catch { + [Console]::Error.WriteLine("csrun diagnostics retained in: $engineDirectory") + throw +} finally { + $resolvedTemp = [IO.Path]::TrimEndingDirectorySeparator([IO.Path]::GetFullPath([IO.Path]::GetTempPath())) + $resolvedEngineDirectory = [IO.Path]::GetFullPath($engineDirectory) + if ([IO.Path]::GetDirectoryName($resolvedEngineDirectory) -ne $resolvedTemp -or + [IO.Path]::GetFileName($resolvedEngineDirectory) -cnotmatch '^csrun-[a-f0-9]{32}$') { throw 'Unsafe cleanup path.' } + if ($process -and $process.ExitCode -eq 0) { Remove-Item -LiteralPath $resolvedEngineDirectory -Recurse -Force } +} +'@ + } + $encoding = '$OutputEncoding = [Text.UTF8Encoding]::new($false)' + "`n" + '[Console]::OutputEncoding = $OutputEncoding' + "`n" + $native = $prefix + $encoding + '$verifyTests = $' + $verifyTests.ToString().ToLowerInvariant() + "`n" + $script:CsrunTestVerificationTemplate + "`n" + $engineSetup + "`n" + $nativeInvoke + "`n" + $engineCleanup + "`n" + $suffix + $docker = $prefix + $encoding + '$verifyTests = $' + $verifyTests.ToString().ToLowerInvariant() + "`n" + $script:CsrunTestVerificationTemplate + "`n" + $engineSetup + "`n" + $dockerInvoke + "`n" + $engineCleanup + "`n" + $suffix + # PowerShell's interactive parser buffers an incomplete script block. Keep all + # execution and post-execution checks inside the same complete paste unit. + $native = "& {`n" + $native.TrimEnd() + "`n}`n" + $docker = "& {`n" + $docker.TrimEnd() + "`n}`n" + [pscustomobject]@{ + SourceSha256 = $identity.SourceSha256 + ManifestSha256 = $identity.ManifestSha256 + ManifestJson = $identity.ManifestJson + Native = $native + Docker = $docker + } +} + +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..29e635dd --- /dev/null +++ b/skills/dotnet-csrun/scripts/test-sample-tools.ps1 @@ -0,0 +1,135 @@ +#requires -Version 7.0 +$ErrorActionPreference = 'Stop' +. (Join-Path $PSScriptRoot 'sample-tools.ps1') +$root = Split-Path $PSScriptRoot -Parent +$fakeEngine = Join-Path ([IO.Path]::GetTempPath()) ('csrun-fake-' + [guid]::NewGuid().ToString('N') + '.ps1') +[IO.File]::WriteAllText($fakeEngine, "param([string]`$ManifestJson)`n[Console]::Write(`$ManifestJson)") +$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 +} + +$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").TrimEnd("`n") -ceq $expected.Replace("`r`n", "`n").TrimEnd("`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 + if (-not $item.Contains('source')) { continue } + $pair = New-CsrunExecutionPair $json -Image 'codebeltnet/csrun:10' -EnginePath $fakeEngine + foreach ($block in @($pair.Native, $pair.Docker)) { + $tokens = $null; $parseErrors = $null + $ast = [Management.Automation.Language.Parser]::ParseInput($block, [ref]$tokens, [ref]$parseErrors) + Assert-True (-not $parseErrors.Count -and $ast.EndBlock.Statements[0] -is [Management.Automation.Language.PipelineAst] -and $ast.EndBlock.Statements[0].Extent.Text.StartsWith('& {')) 'Complete wrapper is not parsed as one outer script block.' + $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 $fakeEngine +$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.' + +Assert-True ($pair.Docker.Contains('$containerInput | & docker run --rm -i')) 'Docker no longer streams the manifest to the release script.' +Assert-True ($pair.Native.Contains("'-ManifestJson'")) 'Native invocation no longer uses the published parameter.' + +# The wrapper verifies the published engine's ordinary output and status contract. +$testManifest = @{ schemaVersion = 1; mode = 'test'; source = 'using Xunit;' } | ConvertTo-Json +$testPair = New-CsrunExecutionPair $testManifest -Image 'codebeltnet/csrun:10' -EnginePath $fakeEngine +$remotePair = New-CsrunExecutionPair $testManifest -Image 'codebeltnet/csrun:10' +foreach ($transport in @('Native', 'Docker')) { + Assert-True ($remotePair.$transport.Contains('releases/latest') -and $remotePair.$transport.Contains('Get-FileHash')) "$transport does not verify the latest release asset." +} +Assert-True ($remotePair.Docker.Contains('--entrypoint pwsh') -and $remotePair.Docker.Contains('WriteAllBytes($enginePath, $engineBytes)') -and $remotePair.Docker.Contains('& $enginePath -ManifestJson')) 'Docker does not execute the verified release asset.' +foreach ($transport in @('Native', 'Docker')) { + Assert-True ($testPair.$transport.Contains('Assert-CsrunTestOutput')) "$transport lacks generated verification." + Assert-True ($testPair.$transport -cnotmatch 'RequirePassingTests|ManifestStdin') "$transport uses undocumented parameters." + Assert-True ((Get-CsrunWrapperManifest $testPair.$transport) -ceq $testPair.ManifestJson) "$transport changed manifest v1." +} +foreach ($output in @( + 'Passed! - Failed: 0, Passed: 1, Skipped: 0, Total: 1', + 'Passed! - Failed: 1, Passed: 0, Skipped: 0, Total: 1', + 'Passed! - Failed: 0, Passed: 0, Skipped: 1, Total: 1', + 'Passed! - Failed: 0, Passed: 0, Skipped: 0, Total: 0', + 'Passed! - Failed: 0, Passed: 1, Skipped: 0, Total: 1' + "`n" + 'Passed! - Failed: 0, Passed: 1, Skipped: 0, Total: 1', + 'build failed' +)) { + $valid = $output -match '(?m)^Passed!.*Failed: 0, Passed: 1, Skipped: 0, Total: 1$' -and $output -notmatch '(?m)^Passed!.*(?:Failed: [1-9]|Skipped: [1-9]|Total: 0)' + Assert-True ($valid -eq ($output -ceq 'Passed! - Failed: 0, Passed: 1, Skipped: 0, Total: 1')) 'Test-summary acceptance boundary failed.' +}# 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)." diff --git a/skills/dotnet-csrun/scripts/validate.cs b/skills/dotnet-csrun/scripts/validate.cs new file mode 100644 index 00000000..256d1c7e --- /dev/null +++ b/skills/dotnet-csrun/scripts/validate.cs @@ -0,0 +1,93 @@ +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", + ["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-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"))); + 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}"); +} +// 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; +if (documented.Replace("\r\n", "\n") != console.RootElement.GetProperty("source").GetString()!.Replace("\r\n", "\n")) + throw new InvalidDataException("Published console source differs from fixture."); +// 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", "safe-adaptation-corrected" }) +{ + 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."); diff --git a/skills/dotnet-docfx-digest/SKILL.md b/skills/dotnet-docfx-digest/SKILL.md index 59062dc8..5e02540a 100644 --- a/skills/dotnet-docfx-digest/SKILL.md +++ b/skills/dotnet-docfx-digest/SKILL.md @@ -1,7 +1,7 @@ --- name: dotnet-docfx-digest description: > - Use when the user wants to create, repair, audit, or complete DocFX docs for .NET public APIs, or has changed public API that needs namespace pages, XML comments, overwrite files, extension-member tables, examples, or build verification. Exclude private/internal APIs. + Use when the user wants to create, repair, audit, or complete DocFX docs for .NET public APIs, or has changed public API that needs namespace pages, XML comments, overwrite files, extension-member tables, examples, or build verification. Also use when the user wants Native and Docker run actions for DocFX examples. Exclude private/internal APIs. --- # .NET DocFX Digest Steward @@ -12,8 +12,17 @@ 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 `dotnet-docfx-digest csrun` (also accepted as `dotnet-docfx-digest generate-run-actions`), read [run actions](references/run-actions.md). Run the deterministic generator across the active DocFX repository, then resolve its outstanding examples in bounded project batches within the same skill invocation. Inspect source projects, evaluated references, published package assets and maintained tests, persist source-bound recipes, and regenerate until every example is paired or has a demonstrated technical limitation. Keep C#, source links and template customizations readable. Runtime verification is opt-in and independent for each transport. The generator uses the existing csrun contract and runs without model calls. + +For an existing site, always run the current skill's generator, including for toolbar-only updates. An `unchanged` example status applies to its PowerShell scripts. Verify the template's refreshed `public/run-actions.js` against the skill asset, then rebuild and verify the JavaScript in the site output. For a UI-only refresh, preserve existing examples, recipes and script verification evidence. + ## 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. +- Put the complete executable C# in the visible fence. Include every entry point, input, and assertion used by the standalone scripts in that fence. Use console mode and print the result when the example demonstrates output. Label pinned repository tests as related executions. +- 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. @@ -30,7 +39,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 +317,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. + +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. -**Complete C# example contract:** +**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`. @@ -338,7 +349,11 @@ For managed reference pages, map type and extension-method examples to the `exam ## Example Verification -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. +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. **Gate 1 — Static structure (`SAMPLE_STRUCTURE_INVALID`):** @@ -352,7 +367,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 @@ -385,7 +400,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/assets/run-actions.js b/skills/dotnet-docfx-digest/assets/run-actions.js new file mode 100644 index 00000000..7106777f --- /dev/null +++ b/skills/dotnet-docfx-digest/assets/run-actions.js @@ -0,0 +1,269 @@ +// Optional modern-template enhancement. The association remains usable without JavaScript. +const icons = { + native: '' + + '', + docker: '' + + '', +}; +const waitingForCopy = new WeakSet(); +// Generated scripts are one complete `& { ... }` paste unit, so execution and verification run together. +const executionScript = /^& \{\r?\n#requires -Version 7\.0\r?\n[\s\S]*\r?\n\}\r?\n?$/; + +async function fetchScript(link) { + const url = new URL(link.href); + if (url.origin !== location.origin) throw new Error('Script must be hosted on this site.'); + // Asset URLs are stable per example, so always revalidate rather than copy a stale cached script. + const response = await fetch(url, { mode: 'same-origin', cache: 'no-cache' }); + if (!response.ok) throw new Error('Script unavailable.'); + const script = await response.text(); + if (!executionScript.test(script)) throw new Error('Response is not an execution script.'); + return script; +} + +function previewScript(script, label) { + const dialog = document.createElement('dialog'); + dialog.className = 'docfx-run-preview'; + dialog.setAttribute('aria-label', label + ' run script'); + const heading = document.createElement('h2'); + heading.textContent = label + ' run script'; + const source = document.createElement('pre'); + source.tabIndex = 0; + source.textContent = script; + const close = document.createElement('button'); + close.type = 'button'; + close.className = 'btn btn-secondary'; + close.textContent = 'Close'; + close.addEventListener('click', () => dialog.close()); + dialog.addEventListener('close', () => dialog.remove(), { once: true }); + dialog.append(heading, source, close); + document.body.append(dialog); + dialog.showModal(); +} + +function createAction(link, report) { + const transport = link.dataset.transport; + const label = transport === 'native' ? 'Native' : 'Docker'; + const name = 'Copy ' + label + ' run script'; + const button = document.createElement('button'); + button.type = 'button'; + button.className = 'btn border-0 docfx-run-copy'; + button.title = name + '\nShift-click or right-click to preview'; + button.setAttribute('aria-label', name); + button.setAttribute('aria-description', 'Press Shift+Enter to preview the PowerShell script.'); + button.innerHTML = ''; + const icon = button.firstElementChild; + const check = document.createElement('i'); + check.className = 'bi bi-check-lg'; + check.setAttribute('aria-hidden', 'true'); + + let pending = false; + let resetIcon; + async function act(preview) { + if (pending) return; + pending = true; + report(''); + try { + const script = fetchScript(link); + if (preview) { + previewScript(await script, label); + } else { + // Start the clipboard write during the user's gesture, including while the fetch is pending. + const clipboard = navigator.clipboard; + if (clipboard?.write && typeof ClipboardItem === 'function') { + const text = script.then(value => new Blob([value], { type: 'text/plain' })); + await Promise.all([text, clipboard.write([new ClipboardItem({ 'text/plain': text })])]); + } else { + const text = await script; + await clipboard.writeText(text); + } + clearTimeout(resetIcon); + // Measure DocFX's success markup in the same code block so template overrides apply. + const reference = document.createElement('a'); + reference.className = 'btn border-0 link-success code-action'; + reference.hidden = true; + reference.setAttribute('aria-hidden', 'true'); + reference.style.transition = 'none'; + const referenceIcon = check.cloneNode(false); + referenceIcon.removeAttribute('style'); + reference.append(referenceIcon); + button.closest('pre').prepend(reference); + const appearance = getComputedStyle(referenceIcon, '::before'); + check.style.color = appearance.color; + check.style.fontSize = appearance.fontSize; + reference.remove(); + button.replaceChildren(check); + resetIcon = setTimeout(() => button.replaceChildren(icon), 1000); + report(label + ' script copied.', true); + } + } catch { + report('Could not ' + (preview ? 'preview ' : 'copy ') + label + ' script.'); + } finally { + pending = false; + } + } + + button.addEventListener('click', event => act(event.shiftKey)); + button.addEventListener('contextmenu', event => { + event.preventDefault(); + act(true); + }); + button.addEventListener('keydown', event => { + if (event.shiftKey && event.key === 'Enter') { + event.preventDefault(); + act(true); + } + }); + return button; +} + +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(':scope > code:is(.lang-csharp, .language-csharp, .lang-cs, .language-cs)')) continue; + const assets = [...links.querySelectorAll('a[data-transport="native"], a[data-transport="docker"]')]; + if (!assets.length) continue; + + // DocFX imports the custom module before rendering its Lit-managed copy anchor. + if (!pre.querySelector(':scope > a.code-action')) { + if (waitingForCopy.has(pre)) continue; + waitingForCopy.add(pre); + const observer = new MutationObserver(() => { + if (!pre.querySelector(':scope > a.code-action')) return; + observer.disconnect(); + waitingForCopy.delete(pre); + attachToolbar(pre, links, assets); + }); + observer.observe(pre, { childList: true }); + continue; + } + + attachToolbar(pre, links, assets); + } +} + +function attachToolbar(pre, links, assets) { + if (links.hasAttribute('data-enhanced')) return; + const toolbar = document.createElement('span'); + toolbar.className = 'docfx-run-toolbar'; + toolbar.setAttribute('role', 'group'); + toolbar.setAttribute('aria-label', 'Run scripts'); + const status = document.createElement('span'); + status.setAttribute('role', 'status'); + status.className = 'docfx-run-status'; + let clearStatus; + function report(message, visuallyHidden = false) { + clearTimeout(clearStatus); + status.classList.toggle('visually-hidden', visuallyHidden); + status.textContent = message; + if (message) clearStatus = setTimeout(() => { status.textContent = ''; }, 3000); + } + toolbar.append(...assets.map(link => createAction(link, report))); + // Keep our nodes before DocFX's Lit render range, which replaces the original anchor on copy. + pre.prepend(toolbar, status); + pre.classList.add('docfx-runnable'); + links.dataset.enhanced = 'true'; + // Keep the recipe explanation visible when the toolbar replaces the fallback links. + links.after(...links.querySelectorAll(':scope > p')); + links.hidden = true; +} + +if (typeof document !== 'undefined') { + const style = document.createElement('style'); + style.textContent = ` +pre.docfx-runnable { + --run-action-size: 2.25rem; +} +.docfx-run-icon-native { + color: #926bbb; +} +.docfx-run-icon-docker { + color: #4d79d7; +} +.docfx-run-play { + color: #628b2f; +} +pre.docfx-runnable > .code-action, +.docfx-run-toolbar { + display: flex; + position: absolute; + top: .25rem; + opacity: 0; + pointer-events: none; + z-index: 1; +} +pre.docfx-runnable > .code-action, +.docfx-run-copy { + align-items: center; + justify-content: center; + inline-size: var(--run-action-size); + block-size: var(--run-action-size); + padding: 0; + background-color: var(--bs-body-bg); +} +.docfx-run-toolbar { + right: calc(.35rem + var(--run-action-size)); + gap: .15rem; +} +.docfx-run-copy { + display: inline-flex; +} +.docfx-run-copy .bi-check-lg { + pointer-events: none; +} +.docfx-run-copy:hover { + background-color: var(--bs-tertiary-bg); +} +pre.docfx-runnable:hover > :is(.code-action, .docfx-run-toolbar), +pre.docfx-runnable:focus-within > :is(.code-action, .docfx-run-toolbar) { + opacity: 1; + pointer-events: auto; +} +pre.docfx-runnable > .code-action:focus-visible, +.docfx-run-copy:focus-visible { + outline: 2px solid currentColor; + outline-offset: -2px; +} +.docfx-run-status { + position: absolute; + z-index: 1; + top: .25rem; + left: .25rem; + max-inline-size: calc(100% - 3 * var(--run-action-size) - 1rem); + white-space: normal; + pointer-events: none; +} +.docfx-run-status:not(:empty) { + padding: .3rem .5rem; + border-radius: .25rem; + background: var(--bs-body-bg); + color: var(--bs-body-color); +} +.docfx-run-preview { + inline-size: min(52rem, 94vw); + padding: 1rem; + color: var(--bs-body-color); + background: var(--bs-body-bg); + border: 1px solid var(--bs-border-color); + border-radius: .5rem; +} +.docfx-run-preview::backdrop { + background: rgb(0 0 0 / 45%); +} +.docfx-run-preview pre { + max-block-size: 65vh; + padding: .75rem; + background: var(--bs-tertiary-bg); +} +@media (hover: none), (any-pointer: coarse) { + pre.docfx-runnable > :is(.code-action, .docfx-run-toolbar) { + opacity: 1; + pointer-events: auto; + } +} +`; + document.head.append(style); + if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', () => enhanceRunActions(), { once: true }); + else enhanceRunActions(); +} diff --git a/skills/dotnet-docfx-digest/evals/evals.json b/skills/dotnet-docfx-digest/evals/evals.json index d9b8fb0e..d7a89518 100644 --- a/skills/dotnet-docfx-digest/evals/evals.json +++ b/skills/dotnet-docfx-digest/evals/evals.json @@ -1193,6 +1193,152 @@ "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." + ] + }, + { + "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" + ] + }, + { + "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.", + "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" + ] + }, + { + "id": 124, + "prompt": "Use dotnet-docfx-digest csrun on a DocFX repository containing the original ManagedApplicationFixture worker test, a complete console example, a class-library example using Codebelt, Cuemon and Microsoft.Extensions with centrally versioned package references, and a partial integration excerpt. Resolve dependencies and add execution actions across the repository in this invocation. Preserve Context7 and source links. Do not execute the scripts.", + "expected_output": "Uses repository-wide discovery and reports every example. Inspects the source project, central pins and published assets, then completes the visible library example and saves a source-bound manifest recipe. Generates both transports for faithful cases, keeps all generated scripts unverified, and accounts for any unresolved excerpt. Preserves the documented operation, source references, modern template controls and static fallback links. Both standalone scripts embed the complete visible C#. Identical reruns preserve bytes and timestamps.", + "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", + "The library recipe uses exact dependency pins from project and package evidence. The visible C# includes its invocation and observable result or assertion, and both standalone scripts execute that same source.", + "Unexplored dependencies or missing context remain Unresolved, so the report cannot imply full paired coverage", + "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/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/csrun-composition.md b/skills/dotnet-docfx-digest/references/csrun-composition.md new file mode 100644 index 00000000..ee9c58f1 --- /dev/null +++ b/skills/dotnet-docfx-digest/references/csrun-composition.md @@ -0,0 +1,15 @@ +# 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. + +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 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. 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/example-architecture.md b/skills/dotnet-docfx-digest/references/example-architecture.md new file mode 100644 index 00000000..27a22206 --- /dev/null +++ b/skills/dotnet-docfx-digest/references/example-architecture.md @@ -0,0 +1,72 @@ +# 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. + +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 | +| --- | --- | +| 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, 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 + +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. 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. + +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 + +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): 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. 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..cee03ac8 --- /dev/null +++ b/skills/dotnet-docfx-digest/references/one-shot-examples.md @@ -0,0 +1,195 @@ +# One-shot documentation examples + +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; 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. +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 + +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: + +```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()); + } +} +``` + +Expected: exactly `ShouldBootstrapMinimalWorkerProgram` executes, with 1 passed, 0 failed and 0 skipped, followed by `Verified:`. These observations verify the application's registered marker value, Development environment and lifetime service through the fixture. + +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. + +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. 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 + $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' + $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}") + } + # Let Docker's init reap orphaned build processes and keep build servers disposable. + docker run --rm --init @dockerUser --env HOME=/tmp --env DOTNET_CLI_HOME=/tmp --env MSBUILDDISABLENODEREUSE=1 --mount "type=bind,source=$work,target=/work" --workdir /work/repo mcr.microsoft.com/dotnet/sdk:11.0 dotnet run --disable-build-servers --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 + } +} +``` + +## Further exploration + +The [worker application entry point](https://github.com/codebeltnet/xunit/blob/84b13767cb9484f8f3a36a71875662edfdb3e511/app/Codebelt.Extensions.Xunit.Hosting.BootstrapperMinimalWorker.App/Program.cs) shows the setup omitted from the concise test: host construction, marker and hosted-service registration, and `RunAsync`. The [corresponding functional test](https://github.com/codebeltnet/xunit/blob/84b13767cb9484f8f3a36a71875662edfdb3e511/test/Codebelt.Extensions.Xunit.Hosting.FunctionalTests/BootstrapperMinimalWorkerApplicationTestTest.cs) places the displayed fixture usage and assertions in their maintained source context. To understand the separate application/test assemblies and supported frameworks, inspect the [referencing test project](https://github.com/codebeltnet/xunit/blob/84b13767cb9484f8f3a36a71875662edfdb3e511/test/Codebelt.Extensions.Xunit.Hosting.FunctionalTests/Codebelt.Extensions.Xunit.Hosting.FunctionalTests.csproj) and its inherited build settings. For the lifecycle mechanism behind this usage, the [fixture implementation](https://github.com/codebeltnet/xunit/blob/84b13767cb9484f8f3a36a71875662edfdb3e511/src/Codebelt.Extensions.Xunit.Hosting/ManagedApplicationFixture.cs) shows how it selects the entry-point assembly and connects the deferred host. + +These links retain the exact revision executed by the blocks. For ongoing maintained branch exploration, see the [contextual reference example](contextual-source-references.md#principal-example-managedapplicationfixture); branch content can evolve independently of this verification. Following source links is optional and is not required to understand or run the example. + +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 + +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. + +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. + +During the repository-wide run-action verification, the Docker wrapper used `--init` and disabled persistent build servers. All four pinned application/test examples completed from fresh archive downloads on Linux Docker. Each wrapper exited 0 after validating the XML report for exactly its selected test. + +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/references/run-actions.md b/skills/dotnet-docfx-digest/references/run-actions.md new file mode 100644 index 00000000..61328bf4 --- /dev/null +++ b/skills/dotnet-docfx-digest/references/run-actions.md @@ -0,0 +1,69 @@ +# Generated run actions (opt-in) + +The logical command `dotnet-docfx-digest csrun` covers the active DocFX repository in one skill invocation. Resolve the loaded skill directory and start with the deterministic generator: + +```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. + +Programs that resolve against the platform and simple xUnit examples can generate immediately through `New-CsrunExecutionPair` and manifest v1. Defaults are `net10.0` and `codebeltnet/csrun:10`. A recipe can set `csrunImage` for a different reviewed tag. Both wrappers download and verify the publisher's latest stable csrun release at execution time. Docker uses the selected image for its SDK and PowerShell. + +## Refresh an existing site's toolbar + +Use the generator from the skill revision that contains the requested UI change. Its sibling `assets/run-actions.js` is the source copied into the target's effective template. Run the command above even when the C# examples and their recipes are already current. Each example's `unchanged` status describes its PowerShell payloads. The same run still refreshes the toolbar module beside the effective template's `public/main.js`. + +Compare the skill asset with that generated template module, rebuild the active DocFX configuration, and verify that the built site's `public/run-actions.js` matches. For a browser check, reload the rebuilt site with caching disabled and exercise the changed control. Report the toolbar refresh separately from script generation and runtime verification. For a toolbar-only request, keep existing C#, recipes, intact scripts and their verification evidence. + +## Resolve the outstanding examples + +1. Review each `Unresolved` result with `docfx.cs --repo-root --run-action-inventory`. Pass the same `--docfx` if applicable. The inventory includes C#, UID, maintained source context, owner project candidates, metadata frameworks and shared build input paths. +2. Work in small batches grouped by owner project and execution context. Evaluate the project references and target framework with MSBuild, including central package management, conditional imports and shared framework references. Check published NuGet metadata and compatible assets for the exact version implementing the documented operation. Use imports as leads for investigation. +3. Persist a source-bound recipe in `run-actions.settings.json`. Prefer published dependencies with unchanged C#. Make a library excerpt runnable by putting its invocation and inputs in the visible C# fence. Print a demonstration result or include a visible test and its assertions. Import xUnit with `using Xunit;` and use `[Fact]` or `[Theory]` and `Assert` in the test. Check the maintained source and tests when execution needs the original application assembly, runner or unpublished implementation. +4. Regenerate after each project batch. Continue in this invocation until every example is paired or its technical limitation has evidence. For each exception report the UID, specific limitation and recommended documentation treatment. The generator has no model execution or per-file sessions. + +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 uses the visible C# as the standalone manifest source, including source-context comments. A supplied `manifest.source` must match the fence after newline normalization. Legacy `harness` recipes fail generation until the executable code is moved into the fence and its recipe hash is updated. + +Use the pinned repository path for the original application startup or assembly graph. Check the maintained runner, report switches and exact test. For a recipe backed by a different maintained test, explain the relationship to the displayed source and link to the original. A recipe can declare `"unsupportedTransports": { "docker": "" }` (or `native`) to deliver the other transport. Use `"intrinsicLimitation": ""` without an execution recipe only after demonstrating that faithful one-shot execution is impossible. A missing local SDK or Docker installation affects runtime verification. + +Each supported C# fence is followed by an association with its Native and Docker assets. Repository-backed associations explicitly name the pinned test. In the modern template, `assets/run-actions.js` places **Copy Native run script** and **Copy Docker run script** beside DocFX's copy icon. The controls appear on hover and keyboard focus and stay visible on touch devices. Activating either control fetches the complete PowerShell script and copies it to the clipboard. Shift-click, right-click or Shift+Enter opens the full script in an in-page preview. The fallback asset links are visible until the toolbar is enhanced. 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. Clipboard writes require a secure browser context and permission. + +Each JSON result and `index.json` entry includes `coverage` alongside generation `status` and independent Native/Docker states. `Paired` means both scripts were generated. `Partially supported` requires a documented transport limitation. `Unresolved` includes missing dependency evidence, invalid recipes and source context errors. `Intrinsically non-executable` requires a limitation bound to the source. Exit 2 means unresolved coverage remains. Exit 1 takes precedence for recipe, generation or runtime failures. Unchanged fingerprints reuse intact assets and retain verification evidence. + +Explicitly pass `-Verify Native`, `-Verify Docker` or `-Verify Both` to run the selected scripts in separate PowerShell processes and record exit outcomes and log paths under OS temp. Standalone tests require an executed-test summary with every test passing and zero skips. Unrun transports stay `Unverified`. Changes to source, recipe or generator invalidate previous verification. Regular DocFX completion requirements still apply when editing documentation. + +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. The check covers alignment, the C# and PowerShell clipboard payloads, pointer and keyboard interactions, touch, preview, feedback, Context7 startup, idempotence and the no-JavaScript fallback. It detects navigation, new pages and downloads even when the server marks the scripts as attachments. Pass an additional built xUnit site directory to check the `TestOutputHelperAccessor` API example and set `DOCFX_ACTIONS_SCREENSHOT` to capture its toolbar. diff --git a/skills/dotnet-docfx-digest/references/scripts.md b/skills/dotnet-docfx-digest/references/scripts.md index ff3ffac6..8a1c6baa 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, 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 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 4f4d7bff..19c4360b 100644 --- a/skills/dotnet-docfx-digest/references/workflow.md +++ b/skills/dotnet-docfx-digest/references/workflow.md @@ -4,7 +4,9 @@ Use this reference when you need the full step-by-step workflow, example invento ## Example inventory shape -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 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. 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 | @@ -23,12 +25,14 @@ 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. +13. Reuse this discovery to select optional further reading under [contextual source references](contextual-source-references.md). Inspect each new target and record its API relationship, revision and added learning value in the existing evidence cell. Keep purpose, essential example, outcome and execution understandable on the page before optional exploration. Explain what each link adds; runnable examples can benefit, while simple APIs need no arbitrary references. Preserve existing valid links and `Related:` sections. ## Key entry-point and upstream comparison pass @@ -312,7 +316,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: @@ -339,7 +343,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 @@ -406,8 +410,10 @@ 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. +- [ ] Optional source references reuse discovered evidence, target inspected authoritative usage and explain the additional learning value. Simple pages remain concise; runnable examples may offer depth; partial examples state limitations. Links preserve existing valid references and `Related:` sections and never substitute for required C#, executable verification or completion gates. - [ ] 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. diff --git a/skills/dotnet-docfx-digest/scripts/docfx.cs b/skills/dotnet-docfx-digest/scripts/docfx.cs index eee6aa8c..1f8620fa 100644 --- a/skills/dotnet-docfx-digest/scripts/docfx.cs +++ b/skills/dotnet-docfx-digest/scripts/docfx.cs @@ -1,8 +1,10 @@ +#:package MSBuild.StructuredLogger@2.3.269 #:property TargetFramework=net10.0 #:property Nullable=enable #: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 +16,11 @@ using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; +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); @@ -92,6 +99,62 @@ 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 directory = Path.GetDirectoryName(config)!; + var projects = DiscoverProjects(config, directory, report, out var groups); + var files = DiscoverMarkdown(root, config, directory, report); + var workspace = new ValidationWorkspace + { + RepoRoot = root, DocfxPath = config, DocfxWorkspace = directory, Projects = projects, + LibraryProjects = projects.Where(p => !p.IsTest).ToList(), MarkdownFiles = files, + MarkdownTextByPath = new(StringComparer.OrdinalIgnoreCase), OverwriteSections = [], SkipAllowlistEntries = [] + }; + EnsureNamespaceProjectMap(workspace); + 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 = files.SelectMany(file => + { + var sections = ExtractOverwriteSections(file); + return ExtractFences(file).Select(sample => + { + var owner = ResolveSampleOwner(sections, 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 sourceHash = Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(Encoding.UTF8.GetBytes(code.Replace("\r\n", "\n").TrimEnd('\r', '\n')))); + var ns = LongestNamespacePrefix(owner.Uid ?? Path.GetFileNameWithoutExtension(file), workspace); + 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.GetLastToken().ValueText is "Fact" or "Theory" or "FactAttribute" or "TheoryAttribute"); + 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, Project = context?.Project, ContextError = error, Standalone = standalone, + Eligible = eligible, IsTest = isTest, SourceSha256 = sourceHash, + OwnerProjects = ns is null ? [] : workspace.NamespaceProjects[ns].Select(p => Rel(root, p.Path)).ToArray(), + Imports = syntax.DescendantNodes().OfType().Select(u => u.Name?.ToString()).ToArray() }; + }); + }).ToArray(); + var projectEvidence = projects.Select(p => new + { + Path = Rel(root, p.Path), p.PackageId, p.AssemblyName, p.TargetFrameworks, + MetadataFrameworks = groups.Where(g => g.ProjectPaths.Any(path => PathsEqual(path, p.Path))) + .Select(g => g.Properties.GetValueOrDefault("TargetFramework")).Where(f => f is not null).Distinct(), + BuildInputs = RunActionProjectInputs(root, p.Path) + }); + Console.WriteLine(JsonSerializer.Serialize(new { config, examples, projects = projectEvidence, warnings = report.Warnings }, JsonOptions)); + return 0; + } if (options.WriteOverwriteRequestPath is not null) { _quietProgress = options.QuietProgress; @@ -119,6 +182,21 @@ public static int Run(string[] args) } } + private static IEnumerable RunActionProjectInputs(string root, string project) + { + // These are inspection inputs. Imports and conditions still require MSBuild evaluation + // for the chosen TFM before a package/framework pin can be authored. + for (var directory = Path.GetDirectoryName(project); directory is not null && (PathsEqual(directory, root) || IsPathUnderDirectory(directory, root)); + directory = Path.GetDirectoryName(directory)) + { + foreach (var name in new[] { "Directory.Packages.props", "Directory.Build.props", "Directory.Build.targets" }) + { + var path = Path.Combine(directory, name); + if (File.Exists(path)) { yield return Rel(root, path); } + } + } + } + private static int Validate(Options options) { var report = new Report { Script = ScriptId }; @@ -414,6 +492,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 && !ShouldValidateSamplePage(workspace, md, changedFiles)) { 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 +567,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 +1579,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; } @@ -1897,7 +1991,10 @@ private static ProjectInfo ReadProject(string projectPath) case "PackageReference": var include = el.Attribute("Include")?.Value ?? string.Empty; if (include.Contains("Microsoft.NET.Test.Sdk", StringComparison.OrdinalIgnoreCase) || - include.Contains("xunit", StringComparison.OrdinalIgnoreCase) || + include.Equals("xunit", StringComparison.OrdinalIgnoreCase) || + include.Equals("xunit.v3", StringComparison.OrdinalIgnoreCase) || + include.StartsWith("xunit.runner.", StringComparison.OrdinalIgnoreCase) || + include.StartsWith("xunit.v3.runner.", StringComparison.OrdinalIgnoreCase) || include.StartsWith("NUnit", StringComparison.OrdinalIgnoreCase) || include.Contains("MSTest", StringComparison.OrdinalIgnoreCase)) { @@ -4707,6 +4804,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) @@ -4814,6 +4934,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 +5078,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 +5400,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) { @@ -5236,7 +5462,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; } @@ -5254,6 +5480,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 +5539,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 +5576,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,17 +5603,116 @@ 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); + 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 || File.Exists(outputAssembly); @@ -5599,27 +5933,132 @@ 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"; + // 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}", + $"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; @@ -6230,7 +6669,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; @@ -6390,6 +6831,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); } @@ -8350,7 +8805,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 +8815,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"); @@ -8555,6 +9010,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; @@ -8785,6 +9243,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: @@ -8822,6 +9281,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 @@ -8883,6 +9343,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"; @@ -9068,6 +9529,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 +9615,8 @@ private sealed record SampleWorker( string Directory, string ProjectPath, string SourcePath, - string AssemblyName); + string AssemblyName, + bool ProjectContext = false); private sealed record SampleReferenceSet( string Kind, @@ -9163,6 +9626,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 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); + } +} 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..764b7bc8 --- /dev/null +++ b/skills/dotnet-docfx-digest/scripts/generate-run-actions.ps1 @@ -0,0 +1,281 @@ +#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' +$PSNativeCommandUseErrorActionPreference = $false +. (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]::TrimEndingDirectorySeparator([IO.Path]::GetFullPath($RepoRoot)) +$rootPrefix = $root +if (-not [IO.Path]::EndsInDirectorySeparator($rootPrefix)) { $rootPrefix += [IO.Path]::DirectorySeparatorChar } +function Assert-RepositoryPath([string] $Path) { + $full = [IO.Path]::GetFullPath($Path) + # Require exact casing even on filesystems that accept aliases for the same path. + if (-not $full.StartsWith($rootPrefix, [StringComparison]::Ordinal)) { 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 'docfx.cs') -Raw) + (Get-Content (Join-Path $PSScriptRoot 'integration-example.ps1') -Raw) + (Get-Content $helpers -Raw) + $script:Csrun021Asset + $script:Csrun021Sha256 + $script:CsrunTestVerificationTemplate) +$results = [Collections.Generic.List[object]]::new() +$associations = [hashtable]::new([StringComparer]::Ordinal) +$previousPages = foreach ($entry in $old) { + if (-not $entry.file) { continue } + $path = [IO.Path]::GetFullPath($entry.file, $root) + # Legacy indexes stored absolute paths. After moving the checkout, only current + # inventory paths and prior paths inside this checkout can own associations. + if ($path.StartsWith($rootPrefix, [StringComparison]::Ordinal)) { $path } +} +$pages = @(@($inventory.examples.file) + @($previousPages) | Where-Object { $_ } | Sort-Object -CaseSensitive -Unique) +foreach ($page in $pages) { Assert-RepositoryPath $page } +$oldByFingerprint = @{} +foreach ($entry in $old) { + if ($entry.fingerprint) { $oldByFingerprint["$($entry.id)|$($entry.fingerprint)"] = $entry } +} +$recipeBySource = [hashtable]::new([StringComparer]::Ordinal) +foreach ($recipe in $recipes) { + $key = "$($recipe.uid)|$($recipe.sourceSha256.ToUpperInvariant())" + if ($recipeBySource.ContainsKey($key)) { throw "Duplicate recipe for $key" } + $recipeBySource[$key] = $recipe +} +foreach ($example in $inventory.examples) { + $displayedSource = Normalize $example.code + $source = $displayedSource + 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='unresolved'; coverage='Unresolved'; reason=$null; native='Unverified'; docker='Unverified' } + try { + if ($example.contextError) { $result.reason = $example.contextError; continue } + if ($example.sourceSha256 -and $example.sourceSha256 -cne $sourceHash) { throw 'The inventory and generator disagree on the displayed source hash.' } + + $recipe = $recipeBySource["$($example.uid)|$sourceHash"] + if ($recipe -and $recipe.PSObject.Properties['harness']) { + throw 'Move the executable C# into the displayed sample and update its recipe hash.' + } + $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 = $example.isTest + if ($recipe.intrinsicLimitation) { + if ($recipe.manifest -or $recipe.repository) { throw 'An intrinsic limitation cannot also supply an execution recipe.' } + $result.status = 'unsupported'; $result.coverage = 'Intrinsically non-executable'; $result.reason = $recipe.intrinsicLimitation + $result.native = 'Unsupported'; $result.docker = 'Unsupported' + continue + } + if ($recipe -and $recipe.PSObject.Properties['repository']) { $strategy = 'repository' } + elseif ($example.source -and -not ($recipe -and $recipe.PSObject.Properties['manifest'])) { + $result.reason = 'Inspect the maintained project and source for exact published dependencies or a pinned repository test.' + continue + } + elseif (-not $recipe -and (-not $example.eligible -or $example.standalone -eq $isTest -or $source -match '(?m)^#:')) { + $result.reason = 'Resolve the dependencies and entry point from the source project, published assets, and maintained tests.' + continue + } + if ($recipe -and -not $recipe.manifest -and $strategy -ne 'repository') { throw 'A recipe must supply a standalone manifest or a pinned repository test.' } + $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.status = 'unsupported'; $result.coverage = 'Intrinsically non-executable' + $result.reason = "Native: $($result.nativeReason) Docker: $($result.dockerReason)" + continue + } + $result.strategy = $strategy + if ($strategy -eq 'standalone') { $result.executionSourceSha256 = Hash $displayedSource } + $image = if ($recipe.csrunImage) { $recipe.csrunImage } else { $CsrunImage } + $fingerprint = Hash ("$toolHash|$sourceHash|$strategy|$Framework|$image|$($result.executionSourceSha256)|" + ($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 | Select-Object * } 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 $displayedSource) { throw 'Manifest source differs from displayed C#.' } + $manifest | Add-Member -NotePropertyName source -NotePropertyValue $displayedSource -Force + $pair = New-CsrunExecutionPair -ManifestJson ($manifest | ConvertTo-Json -Depth 30) -Image $image + } + $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.coverage = if ($transports.Count -eq 2) { 'Paired' } else { 'Partially supported' } + if ($recipe.explanation) { $result.explanation = $recipe.explanation } + $result.fingerprint = $fingerprint + $links = @($transports | ForEach-Object { + $label = if ($_ -eq 'native') { 'Native' } else { 'Docker' } + 'View ' + $label + ' Script' + }) + $note = if ($strategy -eq 'repository') { '

Runs the pinned repository test ' + [Net.WebUtility]::HtmlEncode($recipe.test) + '.

' } else { '' } + $note += if ($recipe.explanation) { '

' + [Net.WebUtility]::HtmlEncode($recipe.explanation) + '

' } else { '' } + $link = '
' + ($links -join ' · ') + $note + '
' + 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 edits by offset in the original text so each existing line ending is preserved. +foreach ($page in $pages) { + if (-not (Test-Path -LiteralPath $page)) { continue } + $original = [IO.File]::ReadAllText($page) + $edits = [Collections.Generic.List[object]]::new() + foreach ($block in [regex]::Matches($original, '(?s)(?:\r\n|\n|\r){2}.*?')) { + $edits.Add(@{ Offset = $block.Index; Length = $block.Length; Text = '' }) + } + if ($associations.ContainsKey($page)) { + $lines = [regex]::Matches($original, '(?[^\r\n]*)(?\r\n|\n|\r|$)') + foreach ($line in $associations[$page].Keys) { + $end = $line + while ($end -lt $lines.Count -and $lines[$end].Groups['text'].Value -notmatch '^\s*```') { $end++ } + if ($end -ge $lines.Count) { throw "Unclosed fence in $page" } + $fence = $lines[$end] + $newline = $fence.Groups['ending'].Value + if (-not $newline) { $newline = $lines[$end - 1].Groups['ending'].Value } + $edits.Add(@{ + Offset = $fence.Index + $fence.Groups['text'].Length + Length = 0 + Text = $newline + $newline + $associations[$page][$line].Replace("`n", $newline) + }) + } + } + $updated = $original + # At a shared offset remove the previous association before inserting its replacement. + foreach ($edit in $edits | Sort-Object -Property Offset, Length -Descending) { + $updated = $updated.Remove($edit.Offset, $edit.Length).Insert($edit.Offset, $edit.Text) + } + 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 * + $entry.file = [IO.Path]::GetRelativePath($root, $entry.file).Replace('\','/') + if ($entry.status -in @('generated','unchanged')) { $entry.status = 'ready' } + $entry +}) +$null = Write-Changed $indexPath (([ordered]@{ examples=$persisted } | ConvertTo-Json -Depth 30) + "`n") +if ($results.Count) { $results | ConvertTo-Json -Depth 30 } else { '[]' } +if (@($results | Where-Object { $_.status -eq 'failed' -or $_.native -eq 'Failed' -or $_.docker -eq 'Failed' }).Count) { exit 1 } +if (@($results | Where-Object coverage -eq 'Unresolved').Count) { exit 2 } 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..ec91e3b3 --- /dev/null +++ b/skills/dotnet-docfx-digest/scripts/integration-example.ps1 @@ -0,0 +1,98 @@ +#requires -Version 7.0 +# Artifact generation only: no downloads, builds or test execution when dot-sourced. +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 + $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 = '__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/__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" } + # 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 __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 } +'@ + $docker = @' +$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}") + } + # Let Docker's init reap orphaned build processes and keep build servers disposable. + docker run --rm --init @dockerUser --env HOME=/tmp --env DOTNET_CLI_HOME=/tmp --env MSBUILDDISABLENODEREUSE=1 --mount "type=bind,source=$work,target=/work" --workdir /work/repo __IMAGE__ dotnet run --disable-build-servers --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 +} 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 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..ea0a090d --- /dev/null +++ b/skills/dotnet-docfx-digest/scripts/test-integration-example.ps1 @@ -0,0 +1,121 @@ +#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', '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.$artifact.Replace("`r`n", "`n")) { throw "Published $artifact block drifted." } + $tokens = $null; $errors = $null + $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 ($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. + 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 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 ($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" } + } + if ('--init' -notin $options -or 'MSBUILDDISABLENODEREUSE=1' -notin $options -or '--disable-build-servers' -notin $args) { throw 'A disposable SDK run must reap orphaned processes and avoid persistent build servers.' } + 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) } + # 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.' } + } + # 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)." +# Expected negative controls leave LASTEXITCODE nonzero; only assertion failures fail this suite. +exit 0 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..7eb0f731 100644 --- a/skills/dotnet-docfx-digest/scripts/test-quality.ps1 +++ b/skills/dotnet-docfx-digest/scripts/test-quality.ps1 @@ -2438,6 +2438,306 @@ 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')) +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. 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..5c4baa2f --- /dev/null +++ b/skills/dotnet-docfx-digest/scripts/test-run-actions-browser.cjs @@ -0,0 +1,303 @@ +// Run against the OS-temp fixture produced by test-run-actions.ps1. +// Set PLAYWRIGHT_MODULE if Playwright is not on NODE_PATH. +const { chromium, devices } = 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'); + +const mimeTypes = { + '.js': 'text/javascript', '.html': 'text/html', '.css': 'text/css', + '.woff2': 'font/woff2', '.woff': 'font/woff', '.json': 'application/json', +}; +const permissions = ['clipboard-read', 'clipboard-write']; +const normalizeNewlines = text => text.replace(/\r\n/g, '\n'); +const executionScript = /^& \{\r?\n#requires -Version 7\.0\r?\n[\s\S]*\r?\n\}\r?\n?$/; + +async function openExample(context, url, marker) { + const page = await context.newPage(); + await page.addInitScript(() => { + const clipboard = navigator.clipboard; + const writeText = clipboard.writeText.bind(clipboard); + clipboard.writeText = text => { + window.copiedText = Promise.resolve(text); + return writeText(text); + }; + const write = clipboard.write.bind(clipboard); + clipboard.write = items => { + window.copiedText = items[0].getType('text/plain').then(blob => blob.text()).catch(() => null); + return write(items); + }; + }); + await page.goto(url); + await page.waitForFunction(() => window.docfx?.ready); + const sample = page.locator('pre.docfx-runnable').filter({ hasText: marker }); + const toolbar = sample.locator('.docfx-run-toolbar'); + const original = sample.locator(':scope > a.code-action'); + const status = sample.getByRole('status'); + await sample.waitFor(); + assert.equal(await original.count(), 1); + assert.equal(await toolbar.locator('button').count(), 2); + assert.equal(await sample.locator('code.hljs').count(), 1); + assert.equal(await page.getByRole('link', { name: /View (Native|Docker) Script/ }).count(), 0); + const association = sample.locator('xpath=following-sibling::*[1]'); + assert.equal(await association.getAttribute('hidden'), ''); + const actions = await Promise.all(['Native', 'Docker'].map(async label => { + const name = 'Copy ' + label + ' run script'; + const button = toolbar.getByRole('button', { name, exact: true }); + assert.ok((await button.getAttribute('title')).startsWith(name)); + assert.equal(await button.locator('svg[aria-hidden=true]').count(), 1); + const href = await association.locator('a[data-transport=' + label.toLowerCase() + ']').getAttribute('href'); + const asset = new URL(href, url).href; + const response = await page.request.get(asset); + assert.ok(response.ok()); + const script = await response.text(); + assert.match(script, executionScript, label + ' asset must be one complete script block'); + assert.doesNotMatch(script, /RequirePassingTests|ManifestStdin/); + return { label, button, asset, script }; + })); + const navigations = []; + const downloads = []; + const popups = []; + page.on('framenavigated', frame => { if (frame === page.mainFrame()) navigations.push(frame.url()); }); + page.on('download', download => downloads.push(download.suggestedFilename())); + page.on('popup', popup => popups.push(popup)); + const checkPageUnchanged = () => { + assert.equal(page.url(), url); + assert.deepEqual(navigations, []); + assert.deepEqual(downloads, []); + assert.deepEqual(popups, []); + }; + return { page, sample, original, toolbar, status, actions, checkPageUnchanged }; +} + +async function checkGeometry({ sample, original, actions }) { + const block = await sample.boundingBox(); + const controls = [...actions.map(action => action.button), original]; + const boxes = await Promise.all(controls.map(control => control.boundingBox())); + for (const box of boxes) { + assert.ok(box.y >= block.y && box.y - block.y < 10, 'actions must start in the top row'); + assert.ok(Math.abs(box.y - boxes[2].y) < 1, 'all three actions must share a row'); + } + for (let index = 1; index < boxes.length; index++) { + const previous = boxes[index - 1]; + assert.ok(Math.abs(boxes[index].x - previous.x - previous.width) < 5, 'controls must be adjacent'); + } + assert.ok(Math.abs(block.x + block.width - boxes[2].x - boxes[2].width) < 8, 'copy stays at the top right'); +} + +async function checkClipboard(page, expected) { + assert.equal(await page.evaluate(() => window.copiedText), expected); + assert.equal(normalizeNewlines(await page.evaluate(() => navigator.clipboard.readText())), normalizeNewlines(expected)); +} + +function checkmarkAppearance(icon) { + return icon.evaluate(async node => { + await Promise.all(node.parentElement.getAnimations().map(animation => animation.finished)); + const glyph = getComputedStyle(node, '::before'); + const { width, height, x, y } = node.getBoundingClientRect(); + const control = node.parentElement.getBoundingClientRect(); + return { + content: glyph.content, + font: glyph.fontFamily, + size: glyph.fontSize, + color: glyph.color, + width, + height, + x: Math.round(x - control.x), + y: Math.round(y - control.y), + }; + }); +} + +async function checkCopy(example, index, activate) { + const { page, actions, status, sample, checkPageUnchanged } = example; + const { label, button, asset, script } = actions[index]; + const block = await sample.boundingBox(); + await Promise.all([ + page.waitForResponse(response => response.url() === asset && response.ok()), + activate(button), + ]); + await status.filter({ hasText: label + ' script copied.' }).waitFor(); + const check = button.locator('.bi-check-lg'); + await check.waitFor(); + if (example.clipboardCheckmark) { + const appearance = await checkmarkAppearance(check); + assert.deepEqual(appearance, example.clipboardCheckmark); + console.log(label + ' checkmark matches DocFX clipboard:', JSON.stringify(appearance)); + } + assert.equal(await button.locator('svg').count(), 0); + await checkClipboard(page, script); + assert.deepEqual(await sample.boundingBox(), block, 'copy feedback must not move or resize the code block'); + await button.locator('svg').waitFor(); + checkPageUnchanged(); +} + +(async () => { + const site = path.resolve(process.argv[2]); + const representative = process.argv[3] && path.resolve(process.argv[3]); + const server = http.createServer((req, res) => { + let pathname = decodeURIComponent(new URL(req.url, 'http://localhost').pathname); + let root = site; + if (representative && pathname.startsWith('/representative/')) { + root = representative; + pathname = pathname.slice('/representative'.length); + } + const file = path.resolve(root, '.' + pathname); + if (!file.startsWith(root + path.sep)) { res.writeHead(403).end(); return; } + try { + const content = fs.readFileSync(file); + res.setHeader('Content-Type', mimeTypes[path.extname(file)] || 'text/plain'); + if (file.endsWith('.ps1')) { + res.setHeader('Content-Disposition', 'attachment'); + // Model a host that lets browsers cache scripts; a regenerated script must still be copied fresh. + res.setHeader('Cache-Control', 'max-age=3600'); + res.setHeader('Last-Modified', fs.statSync(file).mtime.toUTCString()); + } + 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, viewport: { width: 1280, height: 900 } }); + const harnessUrl = base + '/docs/packages.html'; + const explanation = 'The test runs the displayed method and checks the correlation identifier returned from the DI container.'; + const harness = await openExample(context, harnessUrl, 'class CorrelationStore'); + assert.ok(await harness.page.getByText(explanation, { exact: true }).isVisible(), + 'the recipe explanation must remain visible after the toolbar is attached'); + await harness.page.close(); + + const marker = 'ShouldBootstrapMinimalWorkerProgram'; + const desktop = await openExample(context, base + '/docs/integration.html', marker); + const { page, sample, original, toolbar, actions, status, checkPageUnchanged } = desktop; + assert.ok(await page.evaluate(() => window.context7 === true)); + await page.addStyleTag({ content: ` + pre > a.code-action { color: #005fb8; } + [data-bs-theme="dark"] pre > a.code-action { color: #75b6f2; } + ` }); + const opacity = () => toolbar.evaluate(node => getComputedStyle(node).opacity); + assert.equal(await opacity(), '0'); + await sample.hover(); + assert.equal(await opacity(), '1'); + await checkGeometry(desktop); + + const code = await sample.locator('code').innerText(); + await original.click(); + const clipboardCheck = original.locator('.bi-check-lg'); + await clipboardCheck.waitFor(); + await sample.hover({ position: { x: 5, y: 5 } }); + desktop.clipboardCheckmark = await checkmarkAppearance(clipboardCheck); + await checkClipboard(page, code); + await page.evaluate(async () => (await import('../public/run-actions.js')).enhanceRunActions()); + await sample.locator('a.code-action .bi-clipboard').waitFor({ state: 'attached' }); + assert.equal(await toolbar.locator('button').count(), 2); + + await page.mouse.move(0, 0); + await sample.locator('xpath=preceding-sibling::*[1]').locator('a').last().focus(); + assert.equal(await opacity(), '0'); + await page.keyboard.press('Tab'); + assert.ok(await actions[0].button.evaluate(button => button === document.activeElement && button.matches(':focus-visible'))); + assert.equal(await opacity(), '1'); + await checkCopy(desktop, 0, button => button.press('Enter')); + await checkCopy(desktop, 1, button => button.click()); + await page.evaluate(() => document.documentElement.setAttribute('data-bs-theme', 'dark')); + await original.click(); + await clipboardCheck.waitFor(); + await sample.hover({ position: { x: 5, y: 5 } }); + desktop.clipboardCheckmark = await checkmarkAppearance(clipboardCheck); + console.log('DocFX dark-theme clipboard checkmark:', JSON.stringify(desktop.clipboardCheckmark)); + await checkCopy(desktop, 0, button => button.click()); + await checkCopy(desktop, 1, button => button.click()); + await status.filter({ hasText: 'Docker script copied.' }).waitFor({ state: 'hidden' }); + + await actions[0].button.press('Shift+Enter'); + const preview = page.getByRole('dialog', { name: 'Native run script' }); + await preview.waitFor(); + assert.equal(await preview.locator('pre').textContent(), actions[0].script); + await checkClipboard(page, actions[1].script); + await page.keyboard.press('Escape'); + await preview.waitFor({ state: 'detached' }); + assert.ok(await actions[0].button.evaluate(button => button === document.activeElement)); + checkPageUnchanged(); + + const api = await openExample(context, base + '/api/fixture.html', marker); + await checkCopy(api, 0, button => button.press('Enter')); + await checkCopy(api, 1, button => button.press('Enter')); + // Regeneration keeps the asset URL; the copy must reflect the current bytes, not the cached response. + const assetFile = path.resolve(site, '.' + decodeURIComponent(new URL(api.actions[0].asset).pathname)); + const published = fs.readFileSync(assetFile); + const regenerated = api.actions[0].script.replace(/\r?\n\}\r?\n?$/, '\n# regenerated\n}\n'); + try { + fs.writeFileSync(assetFile, regenerated); + await api.status.filter({ hasText: 'Docker script copied.' }).waitFor({ state: 'hidden' }); + await api.actions[0].button.press('Enter'); + await api.status.filter({ hasText: 'Native script copied.' }).waitFor(); + await checkClipboard(api.page, regenerated); + } finally { fs.writeFileSync(assetFile, published); } + await api.page.close(); + + const mobile = await browser.newContext({ ...devices['iPhone 13'], permissions }); + const touch = await openExample(mobile, base + '/docs/integration.html', marker); + assert.ok(await touch.page.evaluate(() => matchMedia('(hover: none)').matches)); + assert.equal(await touch.toolbar.evaluate(node => getComputedStyle(node).opacity), '1'); + await touch.sample.scrollIntoViewIfNeeded(); + await checkGeometry(touch); + assert.ok(await touch.sample.locator('code').evaluate(code => { + code.scrollLeft = code.scrollWidth; + return code.scrollLeft > 0; + }), 'wide C# still scrolls horizontally'); + await checkGeometry(touch); + await checkCopy(touch, 0, button => button.tap()); + await checkCopy(touch, 1, button => button.tap()); + await mobile.close(); + + 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')); + await fallback.goto(harnessUrl); + assert.ok(await fallback.getByText(explanation, { exact: true }).isVisible()); + await noJs.close(); + + await page.bringToFront(); + await page.route('**/native.ps1', route => route.fulfill({ status: 404, body: 'missing' })); + const block = await sample.boundingBox(); + await actions[0].button.press('Enter'); + await status.filter({ hasText: 'Could not copy Native script.' }).waitFor(); + assert.deepEqual(await sample.boundingBox(), block); + assert.equal(normalizeNewlines(await page.evaluate(() => navigator.clipboard.readText())), normalizeNewlines(actions[1].script)); + checkPageUnchanged(); + + // Legacy unwrapped and truncated scripts are not complete paste units and must never reach the clipboard. + const unwrapped = actions[0].script.replace(/^& \{\r?\n/, '').replace(/\r?\n\}\r?\n?$/, '\n'); + const truncated = actions[0].script.replace(/\r?\n\}\r?\n?$/, '\n'); + for (const body of [unwrapped, truncated]) { + await status.filter({ hasText: 'Could not copy Native script.' }).waitFor({ state: 'hidden' }); + await page.unroute('**/native.ps1'); + await page.route('**/native.ps1', route => route.fulfill({ status: 200, contentType: 'text/plain', body })); + await actions[0].button.press('Enter'); + await status.filter({ hasText: 'Could not copy Native script.' }).waitFor(); + assert.equal(normalizeNewlines(await page.evaluate(() => navigator.clipboard.readText())), normalizeNewlines(actions[1].script)); + checkPageUnchanged(); + } + + if (representative) { + await context.route('https://context7.com/widget.js', route => route.fulfill({ contentType: 'text/javascript', body: '' })); + const visual = await openExample(context, base + '/representative/api/Codebelt.Extensions.Xunit.TestOutputHelperAccessor.html', 'ShouldExposeCurrentOutput'); + await visual.page.locator('script[src="https://context7.com/widget.js"][data-library="/codebeltnet/xunit"]').waitFor({ state: 'attached' }); + await visual.sample.hover(); + await checkGeometry(visual); + if (process.env.DOCFX_ACTIONS_SCREENSHOT) await visual.sample.screenshot({ path: process.env.DOCFX_ACTIONS_SCREENSHOT }); + await checkCopy(visual, 0, button => button.click()); + await checkCopy(visual, 1, button => button.click()); + } + console.log('Browser checks passed: aligned controls, full clipboard payloads, keyboard and touch, preview and feedback, no navigation or downloads, Context7 and DocFX rendering.'); + } finally { + await browser.close(); + server.close(); + } +})().catch(error => { console.error(error); process.exitCode = 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..ada44f97 --- /dev/null +++ b/skills/dotnet-docfx-digest/scripts/test-run-actions.ps1 @@ -0,0 +1,290 @@ +#requires -Version 7.0 +param([string] $OutputRoot) +$ErrorActionPreference = 'Stop' +. (Join-Path $PSScriptRoot '../../../scripts/file-based-app.ps1') +. (Join-Path $PSScriptRoot '../../dotnet-csrun/scripts/sample-tools.ps1') +Set-StrictMode -Off +$app = Get-FileBasedAppCommand -SourcePath (Join-Path $PSScriptRoot 'docfx.cs') +function dotnet { + if ($inventoryOverride) { $global:LASTEXITCODE = 0; return $inventoryOverride } + # Cache the file-based inventory build once; every inventory assertion still executes. + & (Get-Command $app.Executable -CommandType Application | Select-Object -First 1).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 +$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(?