diff --git a/CHANGELOG.md b/CHANGELOG.md index 69664a40..c6b7619c 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.1] - 2026-11-21 + +This is a minor release that adds a standalone run-action materializer to `dotnet-docfx-digest`, so the generated Native and Docker wrapper scripts are rebuilt at DocFX build time from a committed manifest instead of being committed themselves, and it adds validator gates for API include placement and redundant example headings, together with fixes to run-action toolbar fallback and sample build parallelism. + +### Added + +- `dotnet-docfx-digest` standalone `BuildRunActions.ps1` materializer that rebuilds the Native and Docker run-action scripts from `run-actions.manifest.json` beside `docfx.json` without requiring an installed skill, skips cleanly when the default manifest is absent, and removes generated scripts and emptied example directories that are no longer in the manifest, +- `dotnet-docfx-digest` `generate-run-actions.ps1` emission of `run-actions.manifest.json` and `BuildRunActions.ps1`, wiring of `BuildRunActions.ps1` before the Docker build in an existing `BuildDocfxImage.ps1` with removal of the generated `run-actions/` directory in `finally`, and a `templates/modern` fallback template that keeps `templates/ms-style` last in `build.template`, +- `dotnet-docfx-digest` DocFX verification build step that materializes run actions in its isolated temp workspace when a manifest and `BuildRunActions.ps1` are present, failing verification with the script output if materialization fails, +- `dotnet-docfx-digest` validator diagnostic `API_INCLUDE_OUTSIDE_NAMESPACES` for `[!INCLUDE ...]` directives under `.docfx/api/` outside `api/namespaces/`, +- `dotnet-docfx-digest` validator diagnostic `EXAMPLE_REDUNDANT_HEADING` for manual `Example`/`Examples` headings inside `example:`-mapped overwrite bodies, together with recognition of the `example: [*content]` flow-sequence form. + +### Changed + +- `dotnet-docfx-digest` run-action guidance now recommends committing the settings, manifest, materializer, and Markdown associations while ignoring the generated `run-actions/` directory, instead of committing that directory as documentation source, and the generator no longer writes `run-actions/` or `run-actions/index.json` into the working tree, +- `dotnet-docfx-digest` fast validator accepts `run-actions.manifest.json` and `BuildRunActions.ps1` as run-action deliverables, +- `dotnet-docfx-digest` guidance limits availability includes to namespace overview pages under `.docfx/api/namespaces/*` instead of type pages and after examples, and the README quality-gate entry describes the `example:` mapping forms and the heading gate. + +### Fixed + +- `dotnet-docfx-digest` run-action toolbar re-shows the original run links when copying or previewing a script fails, so the script remains reachable, +- `dotnet-docfx-digest` sample solution builds run with a single MSBuild node when a target framework is passed, avoiding concurrent builds of the same projects against shared `bin`/`obj` paths. + ## [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. @@ -833,6 +856,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.1]: https://github.com/codebeltnet/agentic/compare/v0.13.0...v0.13.1 [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 diff --git a/README.md b/README.md index 5959abb0..4ad23ecb 100644 --- a/README.md +++ b/README.md @@ -716,7 +716,7 @@ API documentation rots the moment code changes. A new public type ships without - **Examples that teach a real workflow** — examples start from package IDs and package-level evidence before falling back to type/member-only searches, prefer README, package docs, tooling, tuning, functional-test, and external GitHub usage when available, may include multiple related public types when that is what makes the consumer scenario understandable, keep extension-container prose focused on what callers can do with the receiver instead of on declaration syntax, discover public acquisition paths from signatures, docs, tests, and other evidence instead of assuming direct construction from implementation details, and rewrite copied test evidence into lean consumer-facing code rather than dragging obvious framework FQNs into the sample body, - **Optional depth after immediate learning** — examples explain purpose, essential usage, outcome and reproduction before offering precise maintained source references with a brief reason to explore each. Existing discovery supplies those links, including for runnable examples; simple APIs stay concise. Links complement required C#, one-shot execution and compilation/completion gates, and existing valid links and `Related:` sections remain preserved, - **Examples arrive with context** — design starts with the developer task, prerequisites, execution topology and observable result. Library snippets stay concise; standalone programs, genuine framework tests, multi-project integrations and partial excerpts use their actual execution context. Project-bound fences match maintained source, revalidate when their source/project changes, and require an active region under actual compiler symbols. Native per-project build evidence preserves successful samples when an unrelated sample fails. Human fly-ins explain setup and outcome, and compilation, runtime evidence and architectural review remain distinct, -- **Semantic example quality gates** — compilation-valid filler no longer passes: the validator rejects duplicate UID mappings, `Type.GetType`/assembly metadata scaffolds, runtime implementation names presented as outcomes (`EXAMPLE_RUNTIME_TYPE_NAME_OUTCOME`), empty local `Program` stubs in conventionally named application-entry-point samples such as `AppFactory`, `WebTestFactory`, or `HostFixture` (`EXAMPLE_EMPTY_ENTRY_POINT_STUB`) while excluding unrelated names such as `ApplicationRepositoryFactory`, generic `DocumentedTypeExample`/`Describe()` templates, type examples that never use the target in code, extension examples that mention a method only in prose instead of invoking it, examples without a human fly-in (`EXAMPLE_LEAD_MISSING`), advanced examples with shallow setup context (`EXAMPLE_ADVANCED_LEAD_MISSING`), `default!`/`null!` holder properties (`EXAMPLE_DEFAULT_PLACEHOLDER`), classes that only construct or return the target with no observable result (`EXAMPLE_NO_OBSERVABLE_OUTCOME`), mass-forwarding shells of one-line pass-throughs (`EXAMPLE_FORWARDING_SCAFFOLD`), one normalized code skeleton reused across three or more unrelated targets (`EXAMPLE_TEMPLATE_REPETITION`), and avoidable `System.*` / `Microsoft.*` fully qualified framework references in executable sample code (`EXAMPLE_FULLY_QUALIFIED_FRAMEWORK_TYPE`), +- **Semantic example quality gates** — compilation-valid filler no longer passes: the validator recognizes scalar (`example: *content`), flow-sequence (`example: [*content]`), and block-sequence (`example:\n- *content`) mappings while rejecting duplicate UID mappings, redundant manual `## Example`/`### Example`/`### Examples` headings inside `example:`-mapped bodies (`EXAMPLE_REDUNDANT_HEADING`) so complementary prose sits directly before the C# fence under DocFX's automatic `Examples` header, `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, - **Project-scoped packets and voluntary representative dry runs** — documentation is processed in bounded project packets grouped by DocFX `metadata[].dest`, with ownership of namespaces, targets, overwrite files, and git-dirty paths. A normal run always preserves the user's requested scope and continues packet-by-packet until the global completion contract is clean. Only an explicitly requested `--dry-run --build-api-model --project-manifest ` selects one **clean** project per destination group and writes both the initial baseline and a sibling changed-page review template; after evidence-based authoring and page-by-page review, `--resume-project-manifest --review-report --build-api-model --validate-samples --verify-docfx-build` verifies the same packets without mistaking new files for pre-existing work. Missing evidence, purpose/outcome, observable-result, or sibling-pattern review entries block dry-run completion. `--write-overwrite` preserves BOM/line endings and refuses dirty or duplicate-UID writes, diff --git a/skills/dotnet-docfx-digest/SKILL.md b/skills/dotnet-docfx-digest/SKILL.md index 5e02540a..99f23465 100644 --- a/skills/dotnet-docfx-digest/SKILL.md +++ b/skills/dotnet-docfx-digest/SKILL.md @@ -88,9 +88,11 @@ Read the reflection-backed packets from that manifest or from `scope.packets`. I - Treat example-lead diagnostics the same way. If examples compile but `EXAMPLE_LEAD_MISSING` or `EXAMPLE_ADVANCED_LEAD_MISSING` remains, the examples are still unfinished. Add source-grounded fly-ins directly to the implicated files in small batches, rerun the fast validator, and continue until the lead diagnostics reach zero. Do not stop because the work is mostly prose, because the examples were pre-existing, or because hundreds of leads are missing. - Treat `INTERIM_ARTIFACT_IN_WORKTREE` as active cleanup work, not a note for later. Classify each reported path, preserve legitimate deliverables, and move or remove scratch output before any completion claim. - Use this strict repair order for repo-wide and other full audits: (1) safety, encoding, overwrite-layout, and scope-establishing blockers; (2) a namespace-first pass across the active queue — namespace pages, namespace prose, availability/start-here guidance, embedded-overwrite cleanup, and `Extension Members` tables; (3) once that namespace layer is globally clean or the rerun shows only example-driven work remains, `EXAMPLE_MISSING` plus example-quality, extension-invocation, and unresolved symbol-ownership diagnostics, processed packet by packet or namespace by namespace; (4) remaining informational warnings. Do not start net-new type/example authoring while namespace-layer diagnostics still remain elsewhere in the active queue, except when moving misplaced namespace-embedded examples into type-targeted files is itself the namespace repair. -- Passing compilation is necessary but not sufficient. `EXAMPLE_PLACEHOLDER`, `EXAMPLE_REFLECTION_ONLY`, `EXAMPLE_TARGET_NOT_USED`, `EXTENSION_EXAMPLE_NOT_INVOKED`, `EXAMPLE_DEFAULT_PLACEHOLDER`, `EXAMPLE_NO_OBSERVABLE_OUTCOME`, `EXAMPLE_RUNTIME_TYPE_NAME_OUTCOME`, `EXAMPLE_EMPTY_ENTRY_POINT_STUB`, `EXAMPLE_FORWARDING_SCAFFOLD`, `EXAMPLE_TEMPLATE_REPETITION`, `EXAMPLE_LEAD_MISSING`, `EXAMPLE_ADVANCED_LEAD_MISSING`, and `EXAMPLE_UID_DUPLICATE` are blocking quality failures. Never satisfy the inventory with `Type.GetType`, assembly metadata inspection, runtime implementation names, an empty local `Program` stub, `DocumentedTypeExample`, `DocumentedExtensionExample`, generic `Describe()` helpers, repeated UID sections, prose that merely names the target, a missing or placeholder-only example fly-in, a `default!`/`null!` holder property that only parks the type, a class that just constructs or returns the target with no observable result, a mass-forwarding shell of one-line pass-through members, or one normalized code skeleton reused across unrelated types. +- Passing compilation is necessary but not sufficient. `EXAMPLE_PLACEHOLDER`, `EXAMPLE_REFLECTION_ONLY`, `EXAMPLE_TARGET_NOT_USED`, `EXTENSION_EXAMPLE_NOT_INVOKED`, `EXAMPLE_DEFAULT_PLACEHOLDER`, `EXAMPLE_NO_OBSERVABLE_OUTCOME`, `EXAMPLE_RUNTIME_TYPE_NAME_OUTCOME`, `EXAMPLE_EMPTY_ENTRY_POINT_STUB`, `EXAMPLE_FORWARDING_SCAFFOLD`, `EXAMPLE_TEMPLATE_REPETITION`, `EXAMPLE_LEAD_MISSING`, `EXAMPLE_ADVANCED_LEAD_MISSING`, `EXAMPLE_UID_DUPLICATE`, and `EXAMPLE_REDUNDANT_HEADING` are blocking quality failures. Never satisfy the inventory with `Type.GetType`, assembly metadata inspection, runtime implementation names, an empty local `Program` stub, `DocumentedTypeExample`, `DocumentedExtensionExample`, generic `Describe()` helpers, repeated UID sections, manual `## Example`/`### Example`/`### Examples` headings inside `example:`-mapped bodies, prose that merely names the target, a missing or placeholder-only example fly-in, a `default!`/`null!` holder property that only parks the type, a class that just constructs or returns the target with no observable result, a mass-forwarding shell of one-line pass-through members, or one normalized code skeleton reused across unrelated types. - Namespace prose must be decision-useful. `NAMESPACE_PROSE_INVENTORY_ONLY`, `NAMESPACE_APPEND_ONLY_REPAIR`, `NAMESPACE_PROSE_TEMPLATE_REPETITION`, `NAMESPACE_USAGE_GUIDANCE_MISSING`, and `NAMESPACE_START_HERE_MISSING` mean the page still needs a problem/outcome opening, a cohesively rewritten lead instead of a weak inventory sentence with guidance appended below it, an opening written from the namespace's own purpose rather than a shared template, concrete "when to use" guidance, and a named starting API when the namespace has multiple entry points. - Namespace overview files are single-UID deliverables. `NAMESPACE_EMBEDDED_OVERWRITE_SECTION` means the page mixed namespace guidance with secondary `uid:` / `example:` mappings after the overview, often below `Extension Members`. Move those type/member examples to readable type-targeted files under `.docfx/api/types/`, usually the declaring extension class page, and keep the namespace page limited to the namespace fly-in, availability, related links, and optional `Extension Members` table. +- Under `.docfx/api/`, Markdown `[!INCLUDE ...]` directives (including availability includes such as `../../includes/availability-*.md`) are **only allowed on namespace overview pages under `.docfx/api/namespaces/*`** — never on type pages (`.docfx/api/types/*`), never in any other file under `.docfx/api/`, and never after examples (`API_INCLUDE_OUTSIDE_NAMESPACES`). Only modify DocFX Markdown files under `.docfx/api/`; do not edit Markdown files outside `.docfx/api/` (such as guides, articles, or conceptual docs), where includes are allowed to follow different conventions. +- Never combine an `example:` front-matter mapping (`example: *content`, `example: [*content]`, or `example:\n- *content`) with a manual `## Example`, `### Example`, or `### Examples` heading in the Markdown body (`EXAMPLE_REDUNDANT_HEADING`). DocFX renders the `Examples` section heading automatically from the front matter; adding a manual heading produces duplicate `Examples` / `Example` headings on the rendered page. Place only the complementary explanatory prose directly before the C# fence. - Use the JSON completion contract as the final authority: completion requires `summary.fullVerificationRan` to be `true`, `summary.canClaimCompletion` to be `true`, `summary.remainingWorkItems` to be `0`, `summary.remainingGates` and `summary.remainingDiagnosticsByCode` to be empty, `summary.newlyIntroducedSkipMarkers` to be `0`, `summary.interimArtifacts` to be `0`, and the build-backed command to succeed. A clean fast run reports `completionState: verification-required`; it is an iteration checkpoint, not completion. Never describe `status: failed`, `completionState: incomplete`, or `completionState: verification-required` as completed work. - Warnings are reported separately from the completion contract, but unresolved ownership is not a warning escape hatch. `SYMBOL_COLLISION_UNRESOLVED` blocks until every colliding type has a C# example mapped to its exact type UID. `EXTENSION_OWNER_AMBIGUOUS` blocks until every affected extension example targets its exact declaring-type or method UID and invokes the method through receiver syntax rather than `Extensions.Method(receiver)`. These diagnostics clear when that evidence exists; do not chase the collision itself or invent a different owner. Residual informational warnings such as `TYPE_FORWARDING_UNRESOLVED` may be reported after a build-backed final run succeeds with `summary.canClaimCompletion = true`. - When you defer completion, name the exact endgame command `--build-api-model --validate-samples --verify-docfx-build` and the final JSON completion contract (`summary.fullVerificationRan = true`, `summary.canClaimCompletion = true`, `summary.remainingWorkItems = 0`, empty `summary.remainingGates`, empty `summary.remainingDiagnosticsByCode`, `summary.newlyIntroducedSkipMarkers = 0`, `summary.interimArtifacts = 0`). Do not replace that with generic "verify later" language. @@ -265,11 +267,11 @@ Apply this skill to: - public types and delegates - public constructors, properties, methods, fields, events, and enum members - public extension methods -- DocFX overwrite Markdown files +- DocFX overwrite Markdown files under `.docfx/api/` (`api/namespaces/` and `api/types/` only; never edit Markdown files outside `.docfx/api/`) - namespace overview pages - XML documentation comments - API examples -- availability includes or availability statements +- availability includes (only in `.docfx/api/namespaces/*`, never on type pages or after examples) or explicit availability statements Do not document private or internal API, implementation-only helpers, or namespaces that contain no public API. @@ -292,7 +294,7 @@ When public API is added or materially changed, update every relevant surface: 3. `Extension Members` tables for namespaces that expose public extension methods. 4. Type-targeting overwrite content for public non-abstraction types that require examples or richer guidance, under `.docfx/api/types/`. 5. Extension-method examples on the declaring extension class page or another readable type-targeted overwrite file under `.docfx/api/types/`. -6. Availability information. +6. Availability information (using `[!INCLUDE ...]` includes only on namespace pages under `.docfx/api/namespaces/*` — never on type pages or after examples). 7. Verification commands or artifacts that prove the documentation remains accurate and buildable. Namespace pages and type pages are both required deliverables in the same run. Do not generate namespace pages without type pages or vice versa. @@ -303,7 +305,7 @@ Material changes include new or removed public API, signature or nullability cha Every public non-abstraction type and every public extension method needs at least one realistic, copy/paste-ready example. A namespace fly-in or `Extension Members` table alone is not enough. -Every example needs a short human fly-in immediately before the first C# fence. Use it to name the consumer task and expected outcome so the sample does not arrive cold. Keep simple examples to one concise paragraph. When the code is large, multi-block, or carries setup such as DI, hosting, serialization options, async work, or configuration, write a more in-depth lead that explains the setup/prerequisite and why the workflow has those steps. The validator reports `EXAMPLE_LEAD_MISSING` or `EXAMPLE_ADVANCED_LEAD_MISSING` when this foreword is absent or too shallow. +Every example needs a short human fly-in immediately before the first C# fence. Use it to name the consumer task and expected outcome so the sample does not arrive cold. Keep simple examples to one concise paragraph. When the code is large, multi-block, or carries setup such as DI, hosting, serialization options, async work, or configuration, write a more in-depth lead that explains the setup/prerequisite and why the workflow has those steps. For `example:`-mapped overwrites (`example: *content`, `example: [*content]`, or `example:\n- *content`), place this complementary text directly before the C# fence with **no** manual `## Example`, `### Example`, or `### Examples` heading — DocFX renders the `Examples` heading automatically from the front matter (`EXAMPLE_REDUNDANT_HEADING`). The validator reports `EXAMPLE_LEAD_MISSING` or `EXAMPLE_ADVANCED_LEAD_MISSING` when this foreword is absent or too shallow. Prefer scenario examples over isolated constructor or method-call snippets. A strong type-page example shows the documented API inside the workflow a consumer is trying to complete, even when that means including nearby public types, a small local helper type, dependency-injection setup, configuration objects, or a short host entry point. The example should still be compact, but it should carry enough context that a developer can understand why the type exists and how it cooperates with the package. diff --git a/skills/dotnet-docfx-digest/assets/BuildRunActions.ps1 b/skills/dotnet-docfx-digest/assets/BuildRunActions.ps1 new file mode 100644 index 00000000..7a2680bd --- /dev/null +++ b/skills/dotnet-docfx-digest/assets/BuildRunActions.ps1 @@ -0,0 +1,283 @@ +#requires -Version 7.0 +[CmdletBinding()] +param( + [string] $ManifestPath = (Join-Path $PSScriptRoot 'run-actions.manifest.json'), + [string] $OutputRoot = (Join-Path $PSScriptRoot 'run-actions') +) +$ErrorActionPreference = 'Stop' +$PSNativeCommandUseErrorActionPreference = $false +Set-StrictMode -Version Latest + +if (-not (Test-Path -LiteralPath $ManifestPath -PathType Leaf)) { + if ($PSBoundParameters.ContainsKey('ManifestPath')) { + throw "Run-actions manifest not found: $ManifestPath" + } + Write-Host "No run-actions manifest found at $ManifestPath; skipping." + return +} + +$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 Normalize([string] $Text) { $Text.Replace("`r`n", "`n").TrimEnd("`n", "`r") } +function Quote-Literal([string] $Value) { "'" + $Value.Replace("'", "''") + "'" } + +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 +} + +function New-StandalonePair { + param( + [Parameter(Mandatory)][hashtable] $Manifest, + [Parameter(Mandatory)][string] $Image + ) + $ordered = Sort-ManifestValue $Manifest + $manifestJson = ConvertTo-Json -InputObject $ordered -Depth 100 + $verifyTests = $ordered.mode -eq 'test' + $prefix = "#requires -Version 7.0`n`$ErrorActionPreference = 'Stop'`n`$PSNativeCommandUseErrorActionPreference = `$false`n`$manifest = @'`n" + $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 = @' +# 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) } +'@ + $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 +'@).Replace('__IMAGE__', (Quote-Literal $Image)) + $engineCleanup = @' +} 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 = "& {`n" + ($prefix + $encoding + '$verifyTests = $' + $verifyTests.ToString().ToLowerInvariant() + "`n" + $CsrunTestVerificationTemplate + "`n" + $engineSetup + "`n" + $nativeInvoke + "`n" + $engineCleanup + "`n" + $suffix).TrimEnd() + "`n}`n" + $docker = "& {`n" + ($prefix + $encoding + '$verifyTests = $' + $verifyTests.ToString().ToLowerInvariant() + "`n" + $CsrunTestVerificationTemplate + "`n" + $engineSetup + "`n" + $dockerInvoke + "`n" + $engineCleanup + "`n" + $suffix).TrimEnd() + "`n}`n" + return @{ native = $native; docker = $docker } +} + +function New-RepositoryPair { + 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 } +'@).Replace('__FRAMEWORK__', $Framework) + $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" +'@).Replace('__FRAMEWORK__', $Framework).Replace('__IMAGE__', $Image) + $template = $template.Replace('__COMMIT__', $Commit).Replace('__REPOSITORY__', $Repository).Replace('__ARCHIVE__', $Repository.Split('/')[1]).Replace('__PROJECT__', $Project).Replace('__TEST__', $Test) + return @{ + 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) + } +} + +$doc = Get-Content -LiteralPath $ManifestPath -Raw | ConvertFrom-Json -AsHashtable +if ($doc.schemaVersion -ne 1) { throw "Unsupported run-actions manifest schemaVersion: $($doc.schemaVersion)" } +$examples = @($doc.examples) +$utf8NoBom = [Text.UTF8Encoding]::new($false) +$expectedScripts = [Collections.Generic.HashSet[string]]::new([StringComparer]::Ordinal) +$written = 0 + +foreach ($example in $examples) { + $id = [string] $example.id + if ($id -cnotmatch '^[a-f0-9]{24}$') { throw "Invalid run-action id: $id" } + $pair = if ($example.strategy -ceq 'repository') { + New-RepositoryPair -Repository $example.repository -Commit $example.commit -Project $example.project -Test $example.test -Framework $example.framework -Image $example.image + } elseif ($example.strategy -ceq 'standalone') { + New-StandalonePair -Manifest $example.manifest -Image $example.image + } else { + throw "Unsupported run-action strategy '$($example.strategy)' for $id" + } + $dir = Join-Path $OutputRoot $id + foreach ($transport in @($example.transports)) { + if ($transport -notin @('native', 'docker')) { throw "Unsupported transport '$transport' for $id" } + $scriptText = Normalize $pair[$transport] + $tokens = $null; $errors = $null + $null = [Management.Automation.Language.Parser]::ParseInput($scriptText, [ref]$tokens, [ref]$errors) + if ($errors.Count) { throw "Materialized $transport script for $id has syntax errors: $errors" } + $path = Join-Path $dir "$transport.ps1" + if (-not (Test-Path -LiteralPath $path) -or [IO.File]::ReadAllText($path) -cne $scriptText) { + $null = [IO.Directory]::CreateDirectory($dir) + [IO.File]::WriteAllText($path, $scriptText, $utf8NoBom) + } + $null = $expectedScripts.Add("$id/$transport.ps1") + $written++ + } +} + +if (Test-Path -LiteralPath $OutputRoot -PathType Container) { + foreach ($exampleDir in @(Get-ChildItem -LiteralPath $OutputRoot -Directory)) { + if ($exampleDir.Name -cnotmatch '^[a-f0-9]{24}$' -or + ($exampleDir.Attributes -band [IO.FileAttributes]::ReparsePoint)) { continue } + foreach ($name in @('native.ps1', 'docker.ps1')) { + if ($expectedScripts.Contains("$($exampleDir.Name)/$name")) { continue } + $stalePath = Join-Path $exampleDir.FullName $name + if (Test-Path -LiteralPath $stalePath -PathType Leaf) { + Remove-Item -LiteralPath $stalePath -Force + } + } + if (-not @(Get-ChildItem -LiteralPath $exampleDir.FullName -Force).Count) { + Remove-Item -LiteralPath $exampleDir.FullName + } + } +} + +Write-Host "Materialized $written run-action script(s) for $($examples.Count) example(s) into $OutputRoot." diff --git a/skills/dotnet-docfx-digest/assets/run-actions.js b/skills/dotnet-docfx-digest/assets/run-actions.js index 7106777f..6f57db68 100644 --- a/skills/dotnet-docfx-digest/assets/run-actions.js +++ b/skills/dotnet-docfx-digest/assets/run-actions.js @@ -40,7 +40,7 @@ function previewScript(script, label) { dialog.showModal(); } -function createAction(link, report) { +function createAction(link, report, onCopyFailure) { const transport = link.dataset.transport; const label = transport === 'native' ? 'Native' : 'Docker'; const name = 'Copy ' + label + ' run script'; @@ -97,21 +97,22 @@ function createAction(link, report) { report(label + ' script copied.', true); } } catch { + if (!preview) onCopyFailure?.(); report('Could not ' + (preview ? 'preview ' : 'copy ') + label + ' script.'); } finally { pending = false; } } - button.addEventListener('click', event => act(event.shiftKey)); + button.addEventListener('click', event => { void act(event.shiftKey); }); button.addEventListener('contextmenu', event => { event.preventDefault(); - act(true); + void act(true); }); button.addEventListener('keydown', event => { if (event.shiftKey && event.key === 'Enter') { event.preventDefault(); - act(true); + void act(true); } }); return button; @@ -144,7 +145,7 @@ export function enhanceRunActions(root = document) { } function attachToolbar(pre, links, assets) { - if (links.hasAttribute('data-enhanced')) return; + if ('enhanced' in links.dataset) return; const toolbar = document.createElement('span'); toolbar.className = 'docfx-run-toolbar'; toolbar.setAttribute('role', 'group'); @@ -159,7 +160,7 @@ function attachToolbar(pre, links, assets) { status.textContent = message; if (message) clearStatus = setTimeout(() => { status.textContent = ''; }, 3000); } - toolbar.append(...assets.map(link => createAction(link, report))); + toolbar.append(...assets.map(link => createAction(link, report, () => { links.hidden = false; }))); // 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'); diff --git a/skills/dotnet-docfx-digest/evals/evals.json b/skills/dotnet-docfx-digest/evals/evals.json index d7a89518..8c53b315 100644 --- a/skills/dotnet-docfx-digest/evals/evals.json +++ b/skills/dotnet-docfx-digest/evals/evals.json @@ -493,14 +493,14 @@ }, { "id": 38, - "prompt": "A developer created a DocFX overwrite for `Acme.Widgets.Spinner` using `example: *content` front matter but accidentally added a `### Examples` heading before the csharp fence. Confirm that the validator still passes (the redundant heading is tolerated by the validator) and that the prose guidance advises removing it to prevent a duplicate heading on the rendered page.", - "expected_output": "The validator runs and does not emit EXAMPLE_MISSING because the csharp fence is present regardless of the redundant heading. The agent flags the redundant heading as producing a duplicate 'Examples' section on the rendered DocFX page and advises removing it, citing the Form A guidance. The validator result is a pass; the rendered-page duplication is a separate documentation quality concern.", - "expectations": [ - "Validator does not emit EXAMPLE_MISSING because a csharp fence is present", - "Agent identifies the `### Examples` heading as redundant for Form A (example: *content) overwrites", - "Agent explains that DocFX adds the section header automatically, so the manual heading causes a duplicate on the rendered page", - "Agent recommends removing the heading to avoid the duplicate-heading rendering defect", - "Validator exit code is 0 (or non-EXAMPLE_MISSING failure) — the redundant heading does not itself cause a validation error" + "prompt": "A developer created a DocFX overwrite for `Acme.Widgets.Spinner` using `example: [*content]` front matter (or `example: *content` / `example:\\n- *content`) and also added a `### Example` heading before the complementary prose and csharp fence. Confirm how the validator handles this and how to fix it so DocFX does not render duplicate headings.", + "expected_output": "The validator recognizes `example: [*content]` as Form A (MappedToExample=true), does not emit EXAMPLE_MISSING, and rejects the manual `### Example` heading with `EXAMPLE_REDUNDANT_HEADING` because DocFX already renders the `Examples` section heading automatically from the front matter. The agent removes the manual `### Example` heading and keeps the complementary explanatory prose directly before the csharp fence.", + "expectations": [ + "Validator recognizes `example: [*content]` (alongside `example: *content` and `example:\\n- *content`) as an `example:`-mapped overwrite section and does not emit EXAMPLE_MISSING", + "Validator emits `EXAMPLE_REDUNDANT_HEADING` for the manual `### Example` or `### Examples` heading inside the `example:`-mapped body", + "Agent explains that DocFX renders the `Examples` section heading automatically from front matter, so a manual `Example`/`Examples` heading produces duplicate headings on the rendered page", + "Agent removes the manual `### Example` heading and keeps the complementary explanatory prose directly before the csharp fence", + "After removing the manual heading, validator no longer emits `EXAMPLE_REDUNDANT_HEADING`" ] }, { diff --git a/skills/dotnet-docfx-digest/references/docfx-overwrite-files.md b/skills/dotnet-docfx-digest/references/docfx-overwrite-files.md index cfc95c05..c6baffda 100644 --- a/skills/dotnet-docfx-digest/references/docfx-overwrite-files.md +++ b/skills/dotnet-docfx-digest/references/docfx-overwrite-files.md @@ -43,17 +43,17 @@ Console.WriteLine(value); ``` ``` -`example: - *content` maps the Markdown body to the first slot of the `example` string array. DocFX renders this as the "Examples" section on the type page **alongside** the auto-generated constructors, methods, and other members — it does not replace them. The `example` property has **Replace** overwrite behavior, so setting it via an overwrite replaces any example already present in generated metadata. +`example: - *content` (as well as the equivalent inline `example: *content` and flow-sequence `example: [*content]` forms) maps the Markdown body to the `example` property. DocFX renders this as the "Examples" section on the type page **alongside** the auto-generated constructors, methods, and other members — it does not replace them. The `example` property has **Replace** overwrite behavior, so setting it via an overwrite replaces any example already present in generated metadata. -Do **not** include a `### Examples` heading in the body. DocFX adds the section header automatically from the template. +Do **not** include a manual `## Example`, `### Example`, `## Examples`, or `### Examples` heading in the body. DocFX adds the `Examples` section header automatically from the template, so a manual heading renders duplicate `Examples` / `Example` headings on the page. Place only the complementary explanatory prose directly before the C# fence. > The validator distinguishes two example forms by the front matter, not by headings in the body. Do not rely on a body heading to make the validator happy. > -> **Form A — front matter `example: *content` (or the `- *content` list form).** This is the recommended form for type pages and extension-class pages. The body must contain at least one fenced `csharp` (or `cs`) block. Do **not** add a `## Example` or `### Example` heading; DocFX renders the section header automatically and a manual heading produces a duplicate "Examples" heading on the rendered page. +> **Form A — front matter `example: *content`, `example: [*content]`, or `example:\n- *content`.** This is the recommended form for type pages and extension-class pages. The body must contain complementary explanatory prose directly before at least one fenced `csharp` (or `cs`) block. Do **not** add a `## Example`, `### Example`, `## Examples`, or `### Examples` heading; DocFX renders the `Examples` section header automatically, and `docfx.cs` rejects a manual `Example`/`Examples` heading inside an `example:`-mapped section with `EXAMPLE_REDUNDANT_HEADING`. > > **Form B — front matter `summary: *content`.** The body must contain a `## Example` or `### Example` heading followed by a fenced `csharp` (or `cs`) block. This form is only for the rare case where the example is embedded inside conceptual content. > -> The validator recognizes Form A by the YAML anchor, not by a body heading; Form B by the body heading. Mixing them produces duplicate sections or validator failures. +> The validator recognizes Form A by the YAML `example:` anchor (scalar, flow sequence, or block sequence), not by a body heading; Form B by the body heading. Mixing them produces duplicate rendered headings and fails validation with `EXAMPLE_REDUNDANT_HEADING`. Do **not** use `summary: *content` for type example files. That replaces only the summary text and does nothing to add a visible Examples section to the page. @@ -89,6 +89,7 @@ If a public non-abstraction type lacks an example, create a matching type-UID ov - Keep examples and remarks close to the API item or namespace they explain. - Create per-type overwrite files for missing concrete-type examples even when the repository currently has only namespace overview files. - Keep namespace overview Markdown under `.docfx/api/namespaces/` and type overwrite Markdown under `.docfx/api/types/`. Move legacy `.docfx/api/*.md` files into the appropriate subdirectory: namespace UIDs go to `api/namespaces/`, type UIDs go to `api/types/`. +- Under `.docfx/api/`, `[!INCLUDE ...]` directives (such as availability includes) are only allowed in `.docfx/api/namespaces/*` — never in `.docfx/api/types/*` or after examples. Only modify DocFX Markdown files under `.docfx/api/`; leave Markdown files outside `.docfx/api/` untouched. - Keep `api/namespaces/**/*.md` and `api/types/**/*.md` under `build.overwrite` only; do not use `api/**/*.md` under `build.content` or `build.overwrite`. - Add examples through overwrite sections when XML comments or generated metadata do not already provide developer-friendly examples. - Preserve existing hand-written overwrite sections unless they are stale or contradictory. diff --git a/skills/dotnet-docfx-digest/references/run-actions.md b/skills/dotnet-docfx-digest/references/run-actions.md index 61328bf4..d01393ef 100644 --- a/skills/dotnet-docfx-digest/references/run-actions.md +++ b/skills/dotnet-docfx-digest/references/run-actions.md @@ -6,7 +6,13 @@ The logical command `dotnet-docfx-digest csrun` covers the active DocFX reposito 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. +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.manifest.json` (the single source-of-truth config containing per-example data with no PowerShell boilerplate) and syncs the self-contained deterministic materializer `BuildRunActions.ps1` beside `docfx.json`, without physically creating `run-actions/` in the working tree. When a `BuildDocfxImage.ps1` exists beside `docfx.json`, the generator also wires `& (Join-Path $PSScriptRoot 'BuildRunActions.ps1')` before `try { docker buildx build ... }` and removes the generated `run-actions` directory in `finally`, updating uncustomized scripts into the standard `try`/`finally` shape and surgically patching customized scripts around their Docker build step without breaking existing customizations. 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 manifest entries are replaced when their source changes or disappears. Keep `run-actions.settings.json`, `run-actions.manifest.json`, `BuildRunActions.ps1`, the Markdown associations, `docfx.json`, and the generated template assets as committed documentation source; ignore the build-time `run-actions/` directory in `.gitignore` (for example `/.docfx/run-actions/`) and invoke `BuildRunActions.ps1` at DocFX build time (for example in `BuildDocfxImage.ps1` right before `try { docker buildx build ... }`, with no AI or skill dependency) so duplicated `.ps1` wrapper scripts are never created during authoring, committed to Git, or flagged by static analysis. The normal fast validator does not regenerate or execute them. + +```powershell +pwsh -NoProfile -File /BuildRunActions.ps1 +``` + +`BuildRunActions.ps1` is 100% deterministic and self-contained: it reads `run-actions.manifest.json` and materializes `run-actions//{native,docker}.ps1` without modifying Markdown pages, `docfx.json`, or requiring any external skill installation. 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. @@ -60,7 +66,7 @@ Use the pinned repository path for the original application startup or assembly 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. +Each JSON result includes `coverage`, generation `status`, and independent Native and Docker verification 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. Verification records and logs live in a private `.docfx-run-verification` directory under the current user's home on Unix or Local AppData on Windows. Reruns reuse a transport's state and log path when its script SHA-256 matches and both cache files pass ownership and link checks. 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. diff --git a/skills/dotnet-docfx-digest/references/scripts.md b/skills/dotnet-docfx-digest/references/scripts.md index 8a1c6baa..4e5ef579 100644 --- a/skills/dotnet-docfx-digest/references/scripts.md +++ b/skills/dotnet-docfx-digest/references/scripts.md @@ -131,7 +131,7 @@ Every run records a process tally, per-phase timings, and execution settings. No Every report also carries a deterministic completion contract under the top-level `summary` object near the start of JSON stdout. `summary.completionState` is `complete` only when there are no errors and the run enabled `--build-api-model`, `--validate-samples`, and `--verify-docfx-build`. A clean fast run reports `verification-required`. `summary.fullVerificationRan` tells you whether that full command family actually ran. `summary.canClaimCompletion` must be `true`; `summary.remainingWorkItems` must be `0`; both `summary.remainingGates` and `summary.remainingDiagnosticsByCode` must be empty; `summary.newlyIntroducedSkipMarkers` must be `0`; and `summary.interimArtifacts` must be `0` before an agent can claim a full digest. `summary.warningDiagnosticsByCode` reports warning-level counts separately, and `summary.preExistingApprovedSkipMarkers` reports the remaining approved waivers that were already present before the run. Any other result is an active repair or verification queue. Diagnostic age, pre-existing status, and volume do not convert repair work into an external blocker. If long output is truncated, search saved stdout for `completionState`, `canClaimCompletion`, `fullVerificationRan`, `remainingWorkItems`, `remainingGates`, `remainingDiagnosticsByCode`, `newlyIntroducedSkipMarkers`, and `interimArtifacts`. -Error codes emitted in JSON include `AGENTS_BLOCK_MISSING`, `DOCFX_CONFIG_MISSING`, `API_OVERWRITE_CONFIG_INVALID`, `API_OVERWRITE_FILE_MISPLACED`, `API_OVERWRITE_SYNTHETIC_UID_FILENAME`, `BUILD_FAILED`, `PUBLIC_API_DISCOVERY_FAILED`, `INTERIM_ARTIFACT_IN_WORKTREE`, `SYMBOL_COLLISION_UNRESOLVED`, `EXTENSION_OWNER_AMBIGUOUS`, `NAMESPACE_PAGE_MISSING`, `NAMESPACE_UID_MISSING`, `NAMESPACE_UID_MISMATCH`, `NAMESPACE_SUMMARY_MISSING`, `NAMESPACE_FLYIN_MISSING`, `NAMESPACE_PROSE_INVENTORY_ONLY`, `NAMESPACE_APPEND_ONLY_REPAIR`, `NAMESPACE_PROSE_TEMPLATE_REPETITION`, `NAMESPACE_USAGE_GUIDANCE_MISSING`, `NAMESPACE_START_HERE_MISSING`, `AVAILABILITY_MISSING`, `EXTENSION_SECTION_MISSING`, `EXTENSION_TABLE_MISSING`, `EXTENSION_TABLE_ENCODING`, `EXTENSION_RECEIVER_MISMATCH`, `EXTENSION_METHOD_SIGNATURE_MISSING`, `EXTENSION_METHOD_MISSING`, `EXTENSION_METHOD_UNKNOWN`, `ENCODING_CORRUPTION`, `EXAMPLE_MISSING`, `EXAMPLE_UID_DUPLICATE`, `EXAMPLE_PLACEHOLDER`, `EXAMPLE_DEFAULT_PLACEHOLDER`, `EXAMPLE_NO_OBSERVABLE_OUTCOME`, `EXAMPLE_FORWARDING_SCAFFOLD`, `EXAMPLE_TEMPLATE_REPETITION`, `EXAMPLE_EXTENSION_CONTAINER_LANGUAGE_FOCUS`, `EXAMPLE_FULLY_QUALIFIED_FRAMEWORK_TYPE`, `EXAMPLE_LEAD_MISSING`, `EXAMPLE_ADVANCED_LEAD_MISSING`, `EXAMPLE_RUNTIME_TYPE_NAME_OUTCOME`, `EXAMPLE_EMPTY_ENTRY_POINT_STUB`, `EXAMPLE_REFLECTION_ONLY`, `EXAMPLE_TARGET_NOT_USED`, `EXTENSION_EXAMPLE_NOT_INVOKED`, `SAMPLE_COMPILE_FAILED`, `SAMPLE_SKIP_REASON_MISSING`, `SAMPLE_SKIP_REASON_INSUFFICIENT`, `SAMPLE_SKIP_NOT_ALLOWLISTED`, `FAIL_NEW_SKIP_MARKER_INTRODUCED`, `SKIP_ALLOWLIST_INVALID`, `DOCFX_BUILD_FAILED`, `ASSESSMENT_QUEUE_WRITE_FAILED`, `GENERATED_METADATA_CLEANUP_FAILED`, `GENERATED_METADATA_CLEANUP_SKIPPED`, `GENERATED_OUTPUT_CLEANUP_FAILED`, and `GENERATED_OUTPUT_CLEANUP_SKIPPED`. `SYMBOL_COLLISION_UNRESOLVED` clears only when every colliding type has a C# example mapped to its exact type UID. `EXTENSION_OWNER_AMBIGUOUS` clears only when every affected method has receiver-style invocation evidence under its exact declaring-type or method UID; namespace-level mappings and static container calls do not count. Project-scoped error codes are `PROJECT_HINT_NOT_FOUND` and `PROJECT_HINT_AMBIGUOUS` for `--project` hints, `FAMILY_ANCHOR_EXAMPLE_MISSING` and `FAMILY_NAMESPACE_GUIDANCE_MISSING` for auto-detected generic-arity family skips, and `OVERWRITE_UID_DUPLICATE`, `OVERWRITE_FENCE_UNBALANCED`, `OVERWRITE_DIRTY_REFUSED`, `OVERWRITE_REQUEST_MISSING`, and `OVERWRITE_REQUEST_INVALID` for the `--write-overwrite` writer. `API_OVERWRITE_SYNTHETIC_UID_FILENAME` rejects authored Markdown filenames that mirror compiler-generated C# extension-block UIDs such as literal `$...`, percent-encoded `%3CG%3E%24...`, or DocFX private-use angle forms. The semantic example codes reject the filler patterns that pass a naive token match: `EXAMPLE_DEFAULT_PLACEHOLDER` for a target parked in a `default!`/`null!` holder property or field, `EXAMPLE_NO_OBSERVABLE_OUTCOME` for an example that only holds, returns, or constructs the target with no visible result, `EXAMPLE_FORWARDING_SCAFFOLD` for a shell dominated by one-line pass-through members, `EXAMPLE_TEMPLATE_REPETITION` for one normalized code skeleton reused across three or more distinct authored sections, `EXAMPLE_EXTENSION_CONTAINER_LANGUAGE_FOCUS` for an extension-container lead paragraph that foregrounds C# extension-block syntax instead of the caller task/outcome, `EXAMPLE_FULLY_QUALIFIED_FRAMEWORK_TYPE` for avoidable `System.*` / `Microsoft.*` framework references carried into the sample body instead of simplified `using`-based code, `EXAMPLE_LEAD_MISSING` for a C# example that starts with code or thin placeholder prose instead of a human fly-in, `EXAMPLE_ADVANCED_LEAD_MISSING` for a large or multi-part example whose lead does not explain setup, prerequisites, or workflow outcome, `EXAMPLE_RUNTIME_TYPE_NAME_OUTCOME` for `.GetType().Name` or `.GetType().FullName` used as a reader-facing result, and `EXAMPLE_EMPTY_ENTRY_POINT_STUB` for an application factory or fixture sample that declares an empty local `Program` type to make a generic entry-point call compile. The empty-entry-point check applies to `ApplicationFactory`, `ApplicationTestFactory`, `WebApplicationFactory`, `WebApplicationTestFactory`, `AppFactory`, `WebTestFactory`, `HostFactory`, and the corresponding `Fixture` suffixes; anchoring this convention avoids treating unrelated types such as `ApplicationRepositoryFactory` as application bootstrap targets. Both diagnostics require source-backed application behavior such as configured state, a resolved domain service, an HTTP response, or lifecycle evidence. One type- or namespace-level section may legitimately satisfy several extension targets and is counted once. `NAMESPACE_APPEND_ONLY_REPAIR` flags an inventory-led opening left intact while usage or start-here guidance is appended below it (rewrite the opening cohesively instead), and `NAMESPACE_PROSE_TEMPLATE_REPETITION` flags three or more namespace overviews that share one normalized prose skeleton. `INTERIM_ARTIFACT_IN_WORKTREE` flags unexpected new repo-root or DocFX-workspace files that are not known `dotnet-docfx-digest` deliverables, so scratch output must live in temp/session storage and authored Markdown must map to real public namespace/type targets. `EXTENSION_METHOD_UNKNOWN` flags invented or stale method names in `Extension Members` tables, such as plausible `AddX` setup names that do not exist in the public extension API model. `SAMPLE_SKIP_NOT_ALLOWLISTED` means the marker exists but does not match a pre-existing approved entry in `skip-compile-allowlist.json`, so compilation still runs. `FAIL_NEW_SKIP_MARKER_INTRODUCED` is an execution-protocol failure: the working tree now contains a new skip marker, which remains fail-level even when an allowlist entry was added in the same run. `SKIP_ALLOWLIST_INVALID` means the allowlist file itself is malformed or missing required fields. Warnings include `API_MODEL_SOURCE_SCANNER_LIMITED` when the no-build source scanner is the API-model source (run `--build-api-model` for reflection-backed precision), `API_MODEL_SOURCE_SCANNER_INCOMPLETE` when the scanner cannot pair a block namespace declaration with its opening brace and may under-report public types, `BUILD_BACKED_SCOPE_REQUIRED` when authoring scope is requested on the provisional source-scan model, `PROJECT_DIRTY_SKIPPED` when an explicitly selected project has pre-existing related changes, `DRY_RUN_GROUP_UNSELECTED` when an explicitly requested dry run has no clean project to sample, `TYPE_FORWARDING_UNRESOLVED` when source forwarding cannot be attributed safely, `API_MODEL_EMPTY` when no-build discovery found no public API (Markdown, encoding, and overwrite-layout checks still run; `--build-api-model` is required for namespace and required-example validation), `DOCFX_EXTENSION_BLOCK_UNSUPPORTED` when C# 14 extension blocks are detected in the public API (see DocFX issue #11010), and `API_OVERWRITE_CONFIG_UNREADABLE` when the validator cannot parse the DocFX config well enough to inspect the overwrite layout. Warnings remain separate from `remainingDiagnosticsByCode`; unresolved collision and extension ownership do not use that warning path. +Error codes emitted in JSON include `AGENTS_BLOCK_MISSING`, `DOCFX_CONFIG_MISSING`, `API_OVERWRITE_CONFIG_INVALID`, `API_OVERWRITE_FILE_MISPLACED`, `API_OVERWRITE_SYNTHETIC_UID_FILENAME`, `API_INCLUDE_OUTSIDE_NAMESPACES`, `BUILD_FAILED`, `PUBLIC_API_DISCOVERY_FAILED`, `INTERIM_ARTIFACT_IN_WORKTREE`, `SYMBOL_COLLISION_UNRESOLVED`, `EXTENSION_OWNER_AMBIGUOUS`, `NAMESPACE_PAGE_MISSING`, `NAMESPACE_UID_MISSING`, `NAMESPACE_UID_MISMATCH`, `NAMESPACE_SUMMARY_MISSING`, `NAMESPACE_FLYIN_MISSING`, `NAMESPACE_PROSE_INVENTORY_ONLY`, `NAMESPACE_APPEND_ONLY_REPAIR`, `NAMESPACE_PROSE_TEMPLATE_REPETITION`, `NAMESPACE_USAGE_GUIDANCE_MISSING`, `NAMESPACE_START_HERE_MISSING`, `AVAILABILITY_MISSING`, `EXTENSION_SECTION_MISSING`, `EXTENSION_TABLE_MISSING`, `EXTENSION_TABLE_ENCODING`, `EXTENSION_RECEIVER_MISMATCH`, `EXTENSION_METHOD_SIGNATURE_MISSING`, `EXTENSION_METHOD_MISSING`, `EXTENSION_METHOD_UNKNOWN`, `ENCODING_CORRUPTION`, `EXAMPLE_MISSING`, `EXAMPLE_UID_DUPLICATE`, `EXAMPLE_REDUNDANT_HEADING`, `EXAMPLE_PLACEHOLDER`, `EXAMPLE_DEFAULT_PLACEHOLDER`, `EXAMPLE_NO_OBSERVABLE_OUTCOME`, `EXAMPLE_FORWARDING_SCAFFOLD`, `EXAMPLE_TEMPLATE_REPETITION`, `EXAMPLE_EXTENSION_CONTAINER_LANGUAGE_FOCUS`, `EXAMPLE_FULLY_QUALIFIED_FRAMEWORK_TYPE`, `EXAMPLE_LEAD_MISSING`, `EXAMPLE_ADVANCED_LEAD_MISSING`, `EXAMPLE_RUNTIME_TYPE_NAME_OUTCOME`, `EXAMPLE_EMPTY_ENTRY_POINT_STUB`, `EXAMPLE_REFLECTION_ONLY`, `EXAMPLE_TARGET_NOT_USED`, `EXTENSION_EXAMPLE_NOT_INVOKED`, `SAMPLE_COMPILE_FAILED`, `SAMPLE_SKIP_REASON_MISSING`, `SAMPLE_SKIP_REASON_INSUFFICIENT`, `SAMPLE_SKIP_NOT_ALLOWLISTED`, `FAIL_NEW_SKIP_MARKER_INTRODUCED`, `SKIP_ALLOWLIST_INVALID`, `DOCFX_BUILD_FAILED`, `ASSESSMENT_QUEUE_WRITE_FAILED`, `GENERATED_METADATA_CLEANUP_FAILED`, `GENERATED_METADATA_CLEANUP_SKIPPED`, `GENERATED_OUTPUT_CLEANUP_FAILED`, and `GENERATED_OUTPUT_CLEANUP_SKIPPED`. `SYMBOL_COLLISION_UNRESOLVED` clears only when every colliding type has a C# example mapped to its exact type UID. `EXTENSION_OWNER_AMBIGUOUS` clears only when every affected method has receiver-style invocation evidence under its exact declaring-type or method UID; namespace-level mappings and static container calls do not count. Project-scoped error codes are `PROJECT_HINT_NOT_FOUND` and `PROJECT_HINT_AMBIGUOUS` for `--project` hints, `FAMILY_ANCHOR_EXAMPLE_MISSING` and `FAMILY_NAMESPACE_GUIDANCE_MISSING` for auto-detected generic-arity family skips, and `OVERWRITE_UID_DUPLICATE`, `OVERWRITE_FENCE_UNBALANCED`, `OVERWRITE_DIRTY_REFUSED`, `OVERWRITE_REQUEST_MISSING`, and `OVERWRITE_REQUEST_INVALID` for the `--write-overwrite` writer. `API_OVERWRITE_SYNTHETIC_UID_FILENAME` rejects authored Markdown filenames that mirror compiler-generated C# extension-block UIDs such as literal `$...`, percent-encoded `%3CG%3E%24...`, or DocFX private-use angle forms. The semantic example codes reject the filler patterns that pass a naive token match: `EXAMPLE_DEFAULT_PLACEHOLDER` for a target parked in a `default!`/`null!` holder property or field, `EXAMPLE_NO_OBSERVABLE_OUTCOME` for an example that only holds, returns, or constructs the target with no visible result, `EXAMPLE_FORWARDING_SCAFFOLD` for a shell dominated by one-line pass-through members, `EXAMPLE_TEMPLATE_REPETITION` for one normalized code skeleton reused across three or more distinct authored sections, `EXAMPLE_EXTENSION_CONTAINER_LANGUAGE_FOCUS` for an extension-container lead paragraph that foregrounds C# extension-block syntax instead of the caller task/outcome, `EXAMPLE_FULLY_QUALIFIED_FRAMEWORK_TYPE` for avoidable `System.*` / `Microsoft.*` framework references carried into the sample body instead of simplified `using`-based code, `EXAMPLE_LEAD_MISSING` for a C# example that starts with code or thin placeholder prose instead of a human fly-in, `EXAMPLE_ADVANCED_LEAD_MISSING` for a large or multi-part example whose lead does not explain setup, prerequisites, or workflow outcome, `EXAMPLE_RUNTIME_TYPE_NAME_OUTCOME` for `.GetType().Name` or `.GetType().FullName` used as a reader-facing result, and `EXAMPLE_EMPTY_ENTRY_POINT_STUB` for an application factory or fixture sample that declares an empty local `Program` type to make a generic entry-point call compile. The empty-entry-point check applies to `ApplicationFactory`, `ApplicationTestFactory`, `WebApplicationFactory`, `WebApplicationTestFactory`, `AppFactory`, `WebTestFactory`, `HostFactory`, and the corresponding `Fixture` suffixes; anchoring this convention avoids treating unrelated types such as `ApplicationRepositoryFactory` as application bootstrap targets. Both diagnostics require source-backed application behavior such as configured state, a resolved domain service, an HTTP response, or lifecycle evidence. One type- or namespace-level section may legitimately satisfy several extension targets and is counted once. `NAMESPACE_APPEND_ONLY_REPAIR` flags an inventory-led opening left intact while usage or start-here guidance is appended below it (rewrite the opening cohesively instead), and `NAMESPACE_PROSE_TEMPLATE_REPETITION` flags three or more namespace overviews that share one normalized prose skeleton. `INTERIM_ARTIFACT_IN_WORKTREE` flags unexpected new repo-root or DocFX-workspace files that are not known `dotnet-docfx-digest` deliverables, so scratch output must live in temp/session storage and authored Markdown must map to real public namespace/type targets. `EXTENSION_METHOD_UNKNOWN` flags invented or stale method names in `Extension Members` tables, such as plausible `AddX` setup names that do not exist in the public extension API model. `SAMPLE_SKIP_NOT_ALLOWLISTED` means the marker exists but does not match a pre-existing approved entry in `skip-compile-allowlist.json`, so compilation still runs. `FAIL_NEW_SKIP_MARKER_INTRODUCED` is an execution-protocol failure: the working tree now contains a new skip marker, which remains fail-level even when an allowlist entry was added in the same run. `SKIP_ALLOWLIST_INVALID` means the allowlist file itself is malformed or missing required fields. Warnings include `API_MODEL_SOURCE_SCANNER_LIMITED` when the no-build source scanner is the API-model source (run `--build-api-model` for reflection-backed precision), `API_MODEL_SOURCE_SCANNER_INCOMPLETE` when the scanner cannot pair a block namespace declaration with its opening brace and may under-report public types, `BUILD_BACKED_SCOPE_REQUIRED` when authoring scope is requested on the provisional source-scan model, `PROJECT_DIRTY_SKIPPED` when an explicitly selected project has pre-existing related changes, `DRY_RUN_GROUP_UNSELECTED` when an explicitly requested dry run has no clean project to sample, `TYPE_FORWARDING_UNRESOLVED` when source forwarding cannot be attributed safely, `API_MODEL_EMPTY` when no-build discovery found no public API (Markdown, encoding, and overwrite-layout checks still run; `--build-api-model` is required for namespace and required-example validation), `DOCFX_EXTENSION_BLOCK_UNSUPPORTED` when C# 14 extension blocks are detected in the public API (see DocFX issue #11010), and `API_OVERWRITE_CONFIG_UNREADABLE` when the validator cannot parse the DocFX config well enough to inspect the overwrite layout. Warnings remain separate from `remainingDiagnosticsByCode`; unresolved collision and extension ownership do not use that warning path. `ENCODING_CORRUPTION` fires when a documentation file contains the byte sequence `C3 A2 C2 AC` — the UTF-8 re-encoding of the `â¬` pair produced by a Windows-1252 round-trip of `U+2B07` (⬇, the Extension Members table arrow). Restore the affected file with `git checkout HEAD -- ` if the committed version was correct, or rewrite the content using the edit tool or byte-level operations. Never use `Get-Content` / `Set-Content` or `[System.Text.Encoding]::UTF8.GetBytes(Get-Content)` to rewrite documentation files that contain multi-byte characters. @@ -174,10 +174,10 @@ Only a pre-existing allowlisted entry suppresses compilation. If the marker is n The validator first locates example code in one of: -- A DocFX front-matter anchor (`example: *content` or the list form `example:\n- *content`) followed by a body that contains a fenced `csharp`/`cs` block; **or** +- A DocFX front-matter anchor (`example: *content`, the flow-sequence form `example: [*content]`, or the block-sequence form `example:\n- *content`) followed by a body that contains a fenced `csharp`/`cs` block; **or** - A `## Example` / `### Example` heading in the body followed by a fenced `csharp`/`cs` block. -The first form is preferred for type pages and extension-class pages. Add a `### Examples` heading only when the front matter anchors the body to `summary` and you intend the heading to delimit the embedded example. Locating a fence is only the structural gate. The validator then rejects duplicate example mappings for the same UID, generated placeholder phrases and helper names, reflection-only metadata lookup, type examples that never use the target in C# code, extension examples that never invoke the method, examples that start with code or thin placeholder prose instead of a human fly-in, large or multi-part examples whose fly-in does not explain setup/prerequisites/workflow outcome, extension-container pages whose lead paragraph foregrounds C# extension-block syntax instead of the caller task/outcome, and avoidable `System.*` / `Microsoft.*` fully qualified framework references left in the sample body when a normal `using` keeps the code clearer. It additionally rejects examples that name the target but never exercise it: `default!`/`null!` holder properties, classes whose only interaction is holding or returning the target with no observable result, mass-forwarding shells of one-line pass-through members, and a single normalized code skeleton reused across three or more unrelated targets. Prose, comments, and string literals do not prove target use. +The first form is preferred for type pages and extension-class pages. Do **not** include a manual `## Example`, `### Example`, or `### Examples` heading inside an `example:`-mapped body: DocFX renders the `Examples` section heading automatically from the front matter, so the validator rejects manual `Example`/`Examples` headings outside fenced code blocks with `EXAMPLE_REDUNDANT_HEADING` — keep only the complementary explanatory prose directly before the C# fence. Add a `### Example` / `### Examples` heading only when the front matter anchors the body to `summary` and you intend the heading to delimit the embedded example. Locating a fence is only the structural gate. The validator then rejects duplicate example mappings for the same UID, redundant `Example`/`Examples` headings in `example:`-mapped sections, generated placeholder phrases and helper names, reflection-only metadata lookup, type examples that never use the target in C# code, extension examples that never invoke the method, examples that start with code or thin placeholder prose instead of a human fly-in, large or multi-part examples whose fly-in does not explain setup/prerequisites/workflow outcome, extension-container pages whose lead paragraph foregrounds C# extension-block syntax instead of the caller task/outcome, and avoidable `System.*` / `Microsoft.*` fully qualified framework references left in the sample body when a normal `using` keeps the code clearer. It additionally rejects examples that name the target but never exercise it: `default!`/`null!` holder properties, classes whose only interaction is holding or returning the target with no observable result, mass-forwarding shells of one-line pass-through members, and a single normalized code skeleton reused across three or more unrelated targets. Prose, comments, and string literals do not prove target use. ### Extension-method detection note diff --git a/skills/dotnet-docfx-digest/references/workflow.md b/skills/dotnet-docfx-digest/references/workflow.md index 19c4360b..6c93b870 100644 --- a/skills/dotnet-docfx-digest/references/workflow.md +++ b/skills/dotnet-docfx-digest/references/workflow.md @@ -108,7 +108,7 @@ Use this path when the user invokes the skill without naming a specific API or n 17. Audit related namespace pages together so fixes are consistent across the public API family. 18. Add or repair `Extension Members` tables for namespaces with public extension methods. Use the literal `⬇️` (U+2B07 U+FE0F) in the Ext column. If `EXTENSION_METHOD_MISSING` or `EXTENSION_METHOD_SIGNATURE_MISSING` appears after `EXTENSION_SECTION_MISSING` drops, treat that as the same namespace-layer queue getting more specific: finish table contents and signature fidelity before resuming net-new examples. 19. Finish the namespace-layer pass across the active queue before net-new type/example authoring: repair namespace prose, availability/start-here guidance, and `NAMESPACE_EMBEDDED_OVERWRITE_SECTION` ownership problems, moving misplaced type/member examples into readable type-targeted files under `.docfx/api/types/` when needed. Rerun the fast validator until namespace-layer diagnostics are gone or only example-driven work remains. -20. Add or repair overwrite content for public API items that need examples, remarks, corrected summaries, availability notes, or exact ownership evidence. For colliding type names, target every exact type UID. For colliding extension containers, target the exact declaring-type or method UID and use receiver syntax. Put a short human fly-in before every C# fence; when an example is large, multi-block, or setup-heavy, make the lead explain the setup/prerequisite and workflow outcome. Keep extension-container openings focused on the caller outcome and receiver scenario rather than C# declaration trivia unless a DocFX limitation genuinely needs a note. +20. Add or repair overwrite content under `.docfx/api/types/` for public API items that need examples, remarks, corrected summaries, or exact ownership evidence. Never place `[!INCLUDE ...]` availability includes on type pages (`.docfx/api/types/*`) or after examples — under `.docfx/api/`, includes are only allowed in `.docfx/api/namespaces/*`, and Markdown edits must stay strictly under `.docfx/api/`. For colliding type names, target every exact type UID. For colliding extension containers, target the exact declaring-type or method UID and use receiver syntax. Put a short human fly-in before every C# fence; when an example is large, multi-block, or setup-heavy, make the lead explain the setup/prerequisite and workflow outcome. Keep extension-container openings focused on the caller outcome and receiver scenario rather than C# declaration trivia unless a DocFX limitation genuinely needs a note. 21. Create separate type-page overwrite files for public non-abstraction types that have no example yet, under `.docfx/api/types/{TypeUid}.md` in Codebelt repositories. 22. Create explicit examples for public extension methods that still have none. 23. Build or refresh the example inventory. @@ -312,7 +312,7 @@ Remove the `Extension Members` section when the namespace has no public extensio Do not unwrap decorated receivers or flatten generic method names in this table. Keep signatures such as `IDecorator` and `As` intact instead of rewriting them as `Type` or bare `As`. -Namespace overview files stay single-UID and stop after the fly-in, availability, related links, and optional `Extension Members` table. Do not append secondary `uid:` / `example:` mappings there; put extension-method examples on the declaring extension class page or another readable type-targeted file under `.docfx/api/types/`. +Namespace overview files stay single-UID and stop after the fly-in, availability, related links, and optional `Extension Members` table. Do not append secondary `uid:` / `example:` mappings there; put extension-method examples on the declaring extension class page or another readable type-targeted file under `.docfx/api/types/`. Under `.docfx/api/`, `[!INCLUDE ...]` directives (including availability includes) are only allowed in `.docfx/api/namespaces/*` — never in `.docfx/api/types/*` or after examples — and Markdown edits must stay under `.docfx/api/`. ## Type example shape @@ -343,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. 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. +Do not include a manual `## Example`, `### Example`, `## Examples`, or `### Examples` heading in the body when front matter maps `example` (`example: *content`, `example: [*content]`, or `example:\n- *content`). DocFX renders the `Examples` heading automatically for the `example` property, and `docfx.cs` rejects manual `Example`/`Examples` headings inside `example:`-mapped bodies with `EXAMPLE_REDUNDANT_HEADING`. Place only the complementary explanatory prose directly before the C# fence. 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 @@ -404,6 +404,7 @@ Before completing documentation work, verify: - [ ] Every inventory row names exact evidence paths and a consumer task; generated metadata and the target overwrite file are not the sole evidence. - [ ] The example inventory maps each required public type and extension method to its example file, UID, source evidence, and chosen scenario. - [ ] Every example has a human-written fly-in immediately before the C# fence; advanced examples explain setup, prerequisites, or workflow outcome before the code. +- [ ] Overwrite sections mapped via `example:` (`example: *content`, `example: [*content]`, or `example:\n- *content`) contain no manual `## Example`, `### Example`, or `### Examples` heading in the body (`EXAMPLE_REDUNDANT_HEADING`); complementary explanatory prose sits directly before the C# fence. - [ ] Examples show a coherent consumer workflow, use related public types when helpful, and avoid placeholder-only `Consumer`/`MyNamespace` shells when a domain name is available. - [ ] No example is reflection-only, metadata-only, duplicated by UID, or built from `DocumentedTypeExample`, `DocumentedExtensionExample`, or generic `Describe()` scaffolding. - [ ] The C# fence itself uses the documented type or invokes the documented extension method; prose, comments, and strings are not counted as usage. @@ -417,7 +418,8 @@ Before completing documentation work, verify: - [ ] 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. -- [ ] Availability is included or explicitly stated and matches actual target frameworks and conditions. +- [ ] Availability is included (via `[!INCLUDE ...]` only on namespace pages under `.docfx/api/namespaces/*` — never on type pages or after examples) or explicitly stated and matches actual target frameworks and conditions. +- [ ] All Markdown edits remained strictly under `.docfx/api/` (no Markdown files outside `.docfx/api/` were modified). - [ ] Existing manual edits are preserved, stale documentation is corrected, and no contradictory documentation remains. - [ ] `git diff` for touched documentation paths was inspected before final verification. - [ ] `dotnet build` has been run, using `-p:SkipSignAssembly=true` when a Codebelt repository has no root `.snk`, or the failure is reported. diff --git a/skills/dotnet-docfx-digest/scripts/agents.cs b/skills/dotnet-docfx-digest/scripts/agents.cs index 6f6366b6..cc4e4677 100644 --- a/skills/dotnet-docfx-digest/scripts/agents.cs +++ b/skills/dotnet-docfx-digest/scripts/agents.cs @@ -34,7 +34,7 @@ internal static class AgentsScript For public non-abstraction types, include at least one realistic, copy/paste-ready usage example on the generated type page/overwrite section for that type UID. For example, a public `Class1` requires an example on the `Class1` API page, not only on the namespace page. Prefer deriving examples from existing unit, functional, or integration tests, but convert test code into real-life consumer-oriented usage. - Missing type examples must be added through per-type DocFX overwrite files under `.docfx/api/types/{TypeUid}.md` in Codebelt repositories. Namespace overview text and `Extension Members` tables are not substitutes for type-page examples. + Missing type examples must be added through per-type DocFX overwrite files under `.docfx/api/types/{TypeUid}.md` in Codebelt repositories. Namespace overview text and `Extension Members` tables are not substitutes for type-page examples. When front matter maps the body to `example` (`example: *content`, `example: [*content]`, or `example:\n- *content`), DocFX renders the `Examples` section heading automatically — never add a manual `## Example`, `### Example`, or `### Examples` heading in the body; place the complementary explanatory prose directly before the C# fence instead. Public extension methods must have examples too. Listing an extension method in an `Extension Members` table is required, but it is not enough. @@ -52,7 +52,7 @@ Both namespace overwrite files and type overwrite files are required deliverable `docfx.json` must keep namespace and type overwrite files in separate subdirectories. `build.overwrite` must include both `api/namespaces/**/*.md` (for namespace pages) and `api/types/**/*.md` (for type pages). `build.content` must exclude both `api/namespaces/**` and `api/types/**` to prevent overwrite Markdown from being treated as conceptual content. Do not use `api/**/*.md` under `build.overwrite` or `build.content`. - Availability must be documented by referencing the appropriate include file when one exists, or by adding explicit availability text when no suitable include exists. Availability must reflect the actual target frameworks, conditional compilation, and project configuration. + Availability must be documented on namespace overview pages under `.docfx/api/namespaces/*` by referencing the appropriate `[!INCLUDE ...]` file when one exists, or by adding explicit availability text when no suitable include exists. Under `.docfx/api/`, `[!INCLUDE ...]` directives are only allowed in `.docfx/api/namespaces/*` — never on type pages (`.docfx/api/types/*`), never in other files under `.docfx/api/`, and never after examples. Only modify DocFX Markdown files under `.docfx/api/`; leave Markdown files outside `.docfx/api/` untouched. Availability must reflect the actual target frameworks, conditional compilation, and project configuration. For conditionally compiled APIs, choose the executable test framework from the asset that contains the API. Inspect the preprocessor condition, project TFMs, package `lib/` assets, and resolved consumer asset before changing a sample. For APIs under `NETSTANDARD2_0` or `NETSTANDARD2_0_OR_GREATER`, when modern `lib/netX.0/` assets also exist, use `net48` (or another supported .NET Framework target from `net462` onward) so the consumer selects `lib/netstandard2.0/`. Never use `netstandard*` as an executable target, and never use a modern `netX.0` target when it selects an asset where the API is absent. For other TFM guards, select a runnable consumer TFM that resolves to the containing asset and confirm that selection from restore or build evidence. diff --git a/skills/dotnet-docfx-digest/scripts/docfx.cs b/skills/dotnet-docfx-digest/scripts/docfx.cs index 1f8620fa..f48804bf 100644 --- a/skills/dotnet-docfx-digest/scripts/docfx.cs +++ b/skills/dotnet-docfx-digest/scripts/docfx.cs @@ -117,6 +117,7 @@ public static int Run(string[] args) 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 associatedPages = files.Where(file => workspace.ReadMarkdown(file).Contains("", StringComparison.Ordinal)); var examples = files.SelectMany(file => { var sections = ExtractOverwriteSections(file); @@ -152,7 +153,7 @@ public static int Run(string[] args) .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)); + Console.WriteLine(JsonSerializer.Serialize(new { config, examples, associatedPages, projects = projectEvidence, warnings = report.Warnings }, JsonOptions)); return 0; } if (options.WriteOverwriteRequestPath is not null) @@ -485,6 +486,7 @@ private static int Validate(Options options) phaseTimer.Restart(); ValidateXrefMemberLinks(repoRoot, markdownFiles, workspace, ReadDocfxSiteBaseUrl(docfxPath), api, apiModelSource, report); + ValidateApiIncludePlacement(repoRoot, docfxWorkspace, markdownFiles, workspace, report); WritePhase(options, report, "xref link validation", phaseTimer.Elapsed); // 8. Verify mandatory examples exist before compiling the examples that were found. @@ -1452,6 +1454,21 @@ private static DocfxVerificationResult VerifyDocfxBuild( CopyDirectory(repoRoot, tempRoot, cancellationToken); var relativeDocfxPath = Path.GetRelativePath(repoRoot, docfxPath); var tempDocfxPath = Path.Combine(tempRoot, relativeDocfxPath); + var tempDocfxDir = Path.GetDirectoryName(tempDocfxPath) ?? tempRoot; + var buildRunActionsScript = Path.Combine(tempDocfxDir, "BuildRunActions.ps1"); + var runActionsManifest = Path.Combine(tempDocfxDir, "run-actions.manifest.json"); + if (File.Exists(buildRunActionsScript) && File.Exists(runActionsManifest)) + { + var materialize = RunProcess("pwsh", $"-NoProfile -NonInteractive -File \"{buildRunActionsScript}\"", + tempDocfxDir, null, ProcessPermission.DocfxBuild, cancellationToken, + new ProcessProgress("Materialize run-actions", "isolated temp workspace")); + if (materialize.ExitCode != 0) + { + return new DocfxVerificationResult(false, + $"BuildRunActions.ps1 failed in a temp workspace (exit {materialize.ExitCode}).\n{Trim(materialize.StdOut + materialize.StdErr)}", + stopwatch.Elapsed, materialize.ExitCode == -2); + } + } var environment = hasStrongNameKey ? null : new Dictionary { ["SkipSignAssembly"] = "true" }; @@ -4445,6 +4462,56 @@ private static bool HasAvailability(string body) return Regex.IsMatch(body, @"(?im)^\s*Availability\s*:"); } + private static void ValidateApiIncludePlacement( + string repoRoot, + string docfxWorkspace, + IReadOnlyList markdownFiles, + ValidationWorkspace workspace, + Report report) + { + var apiRoot = Path.GetFullPath(Path.Combine(docfxWorkspace, "api")) + .TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) + Path.DirectorySeparatorChar; + var namespacesRoot = Path.GetFullPath(Path.Combine(docfxWorkspace, "api", "namespaces")) + .TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) + Path.DirectorySeparatorChar; + + foreach (var md in markdownFiles) + { + var fullPath = Path.GetFullPath(md); + if (!fullPath.StartsWith(apiRoot, StringComparison.OrdinalIgnoreCase)) + { + // Rule applies strictly under .docfx/api/; Markdown outside .docfx/api/ is allowed to use includes freely. + continue; + } + + var isNamespace = fullPath.StartsWith(namespacesRoot, StringComparison.OrdinalIgnoreCase); + var text = workspace.ReadMarkdown(md); + if (!text.Contains("[!INCLUDE", StringComparison.OrdinalIgnoreCase)) + { + continue; + } + + var afterExamples = false; + foreach (var (line, offset, fenceInfo) in ScanMarkdownLines(text)) + { + afterExamples |= IsExampleHeading(line) || fenceInfo is "cs" or "csharp"; + if ((isNamespace && !afterExamples) || + !Regex.IsMatch(line, @"(? section.MappedToExample) + .Where(section => !options.ChangedOnly || changedFiles is null || + changedFiles.Contains(Path.GetFullPath(section.File)) || + changedFiles.Any(IsChangedDocfxConfig))) + { + var sectionNs = NamespaceFromUid(section.Uid); + var declaringNs = NamespaceFromUid(DeclaringTypeUidFromMethodUid(section.Uid)); + if (scope.ScopeRestricted && + !scope.IncludesNamespace(sectionNs) && + !scope.IncludesNamespace(declaringNs)) + { + continue; + } + + if (TryFindRedundantExampleHeading(section.Body, out var lineOffset, out var headingLine)) + { + report.Errors.Add(new Diagnostic( + "EXAMPLE_REDUNDANT_HEADING", + Rel(repoRoot, section.File), + sectionNs, + $"Line {section.BodyStartLine + lineOffset} in UID `{section.Uid}` includes a redundant `{headingLine}` heading inside an `example:`-mapped overwrite section (`example: *content`, `example: [*content]`, or `example:\\n- *content`). " + + "DocFX renders the `Examples` section heading automatically from the front matter, so adding a manual `Example`/`Examples` heading produces duplicate headings on the rendered page. Remove the heading and keep the complementary explanatory prose directly before the C# fence.", + uid: section.Uid)); + } + } + var exampleFingerprints = new List<(string SectionUid, string Path, string Fingerprint)>(); foreach (var target in api.RequiredExampleTargets) @@ -5954,11 +6048,16 @@ private static ProcessResult CompileSampleBatch( // 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\""; + // Passing -p:TargetFramework on a solution build causes MSBuild to evaluate direct solution + // projects with TargetFramework in global properties while ProjectReference edges strip it + // via GlobalPropertiesToRemove. With -m:>1, MSBuild schedules both instances concurrently + // against the same bin/obj paths (e.g. GenerateDepsFile IOException on *.deps.json). + var batchParallelism = framework is null ? parallelism : 1; return RunProcess("dotnet", - $"build \"{solutionPath}\" -c {configuration} --nologo -m:{parallelism}{signingProperty}{frameworkProperty}{contextIsolation}{binaryLog}", + $"build \"{solutionPath}\" -c {configuration} --nologo -m:{batchParallelism}{signingProperty}{frameworkProperty}{contextIsolation}{binaryLog}", tempRoot, permission: ProcessPermission.SampleCompile, progress: new ProcessProgress("sample compilation", - $"{workers.Count} sample project(s), {parallelism} runner(s)")); + $"{workers.Count} sample project(s), {batchParallelism} runner(s)")); } private static List ReadSampleBuildEvidence(string path, out string? error) @@ -6269,22 +6368,152 @@ private static int GetLineNumberForIndex(string text, int index) return line; } + private static bool TryFindRedundantExampleHeading(string body, out int relativeLineOffset, out string headingLine) + { + relativeLineOffset = 0; + headingLine = string.Empty; + if (string.IsNullOrWhiteSpace(body)) + { + return false; + } + + foreach (var (line, offset, _) in ScanMarkdownLines(body)) + { + if (IsExampleHeading(line)) + { + relativeLineOffset = offset; + headingLine = line.Trim(); + return true; + } + } + + return false; + } + + private static bool IsExampleHeading(string line) => + Regex.IsMatch(line, @"^ {0,3}#{1,6}\s+Examples?:?(?:\s+#+)?\s*$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + + private static IEnumerable<(string Text, int Offset, string? FenceInfo)> ScanMarkdownLines(string text) + { + var lines = text.Replace("\r\n", "\n", StringComparison.Ordinal).Replace('\r', '\n').Split('\n'); + var inComment = false; + var fenceChar = '\0'; + var fenceLength = 0; + var fenceListDepth = 0; + var listIndents = new Stack(); + + for (var i = 0; i < lines.Length; i++) + { + var line = lines[i]; + if (!inComment) + { + var leadingLength = 0; + var indent = 0; + while (leadingLength < line.Length && line[leadingLength] is ' ' or '\t') + { + indent += line[leadingLength++] == '\t' ? 4 - indent % 4 : 1; + } + if (leadingLength < line.Length) + { + while (listIndents.TryPeek(out var listIndent) && indent < listIndent) + { + listIndents.Pop(); + } + if (listIndents.Count < fenceListDepth) + { + fenceLength = 0; + fenceListDepth = 0; + } + var contentIndent = indent - (listIndents.TryPeek(out var activeIndent) ? activeIndent : 0); + var content = line[leadingLength..]; + var marker = fenceLength == 0 && contentIndent < 4 + ? Regex.Match(content, @"^(?:[-+*]|[0-9]{1,9}[.)]) {1,4}(?=\S)") + : Match.Empty; + if (marker.Success) + { + listIndents.Push(indent + marker.Length); + line = content[marker.Length..]; + } + else + { + line = new string(' ', contentIndent) + content; + } + } + var fence = Regex.Match(line, @"^ {0,3}(?`{3,}|~{3,})(?.*)$"); + if (fenceLength != 0) + { + if (fence.Success && fence.Groups["marker"].Value[0] == fenceChar && + fence.Groups["marker"].Length >= fenceLength && string.IsNullOrWhiteSpace(fence.Groups["info"].Value)) + { + fenceLength = 0; + fenceListDepth = 0; + } + continue; + } + if (fence.Success) + { + fenceChar = fence.Groups["marker"].Value[0]; + fenceLength = fence.Groups["marker"].Length; + fenceListDepth = listIndents.Count; + yield return (string.Empty, i, fence.Groups["info"].Value.Trim().ToLowerInvariant()); + continue; + } + if (Regex.IsMatch(line, @"^(?: {4}| {0,3}\t)")) + { + continue; + } + } + + // Consume inline code and comments in source order, so delimiters inside either are literal. + var visible = new StringBuilder(); + var start = 0; + while (start < line.Length) + { + if (inComment) + { + var close = line.IndexOf("-->", start, StringComparison.Ordinal); + if (close < 0) break; + inComment = false; + start = close + 3; + continue; + } + + var token = MarkdownLiteral.Match(line, start); + if (!token.Success) + { + visible.Append(line.AsSpan(start)); + break; + } + visible.Append(line.AsSpan(start, token.Index - start)); + inComment = token.Value == ".*?')) { + foreach ($block in [regex]::Matches($original, '(?s)(?:\A|(?:\r\n|\n|\r){1,2}).*?')) { $edits.Add(@{ Offset = $block.Index; Length = $block.Length; Text = '' }) } if ($associations.ContainsKey($page)) { @@ -226,26 +304,6 @@ foreach ($page in $pages) { } 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) @@ -259,23 +317,255 @@ foreach ($template in $templates) { $candidate = Join-Path $workspace "$template/public/main.js" if (Test-Path $candidate) { $main=$candidate } } +$templatesChanged = $false if (-not $main) { - $main = Join-Path $workspace 'run-actions-template/public/main.js' + $main = Join-Path $workspace 'templates/modern/public/main.js' $null = Write-Changed $main "export default {};`n" - if ('run-actions-template' -notin $templates) { $config.build.template = $templates + @('run-actions-template') } + if ('templates/modern' -notin $templates) { + $templates = $templates + @('templates/modern') + $templatesChanged = $true + } } +$msStyleTemplates = @($templates | Where-Object { $_ -eq 'templates/ms-style' }) +if ($msStyleTemplates.Count -gt 0) { + $reorderedTemplates = @($templates | Where-Object { $_ -ne 'templates/ms-style' }) + $msStyleTemplates + if (($reorderedTemplates -join "`0") -ne ($templates -join "`0")) { + $templates = $reorderedTemplates + $templatesChanged = $true + } +} +if ($templatesChanged) { $config.build.template = $templates } 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") +$sortedManifest = @($manifestEntries | Sort-Object { $_.id }) +$null = Write-Changed $manifestPath (([ordered]@{ schemaVersion = 1; examples = $sortedManifest } | ConvertTo-Json -Depth 30) + "`n") +$null = Write-Changed (Join-Path $workspace 'BuildRunActions.ps1') ([IO.File]::ReadAllText((Join-Path $PSScriptRoot '../assets/BuildRunActions.ps1'))) +function Test-DockerBuildCommand($CommandAst) { + if ($CommandAst.CommandElements.Count -lt 2) { return $false } + $cmdName = $CommandAst.GetCommandName() + if (-not $cmdName -or $cmdName -inotmatch '(^|[\\/])docker(\.exe)?$') { return $false } + $firstArg = $CommandAst.CommandElements[1].Extent.Text.Trim("'`"") + if ($firstArg -ieq 'build') { return $true } + if ($firstArg -ieq 'buildx' -and $CommandAst.CommandElements.Count -ge 3) { + return $CommandAst.CommandElements[2].Extent.Text.Trim("'`"") -ieq 'build' + } + return $false +} +function Test-ApiCleanupPipeline($PipelineAst) { + if ($PipelineAst -isnot [Management.Automation.Language.PipelineAst]) { return $false } + if ($PipelineAst.PipelineElements.Count -ne 2) { return $false } + $first = $PipelineAst.PipelineElements[0] -as [Management.Automation.Language.CommandAst] + $second = $PipelineAst.PipelineElements[1] -as [Management.Automation.Language.CommandAst] + if (-not $first -or -not $second) { return $false } + $firstName = $first.GetCommandName() + $secondName = $second.GetCommandName() + return ($firstName -ieq 'Get-ChildItem' -or $firstName -ieq 'gci') -and + ($secondName -ieq 'Remove-Item' -or $secondName -ieq 'ri') -and + ($PipelineAst.Extent.Text -match '(?i)\bapi\b') +} +function Get-LineIndent([string] $Text, [int] $Offset) { + if ($Offset -eq 0) { return '' } + $lineStart = $Text.LastIndexOf("`n", $Offset - 1) + $lineStart = if ($lineStart -lt 0) { 0 } else { $lineStart + 1 } + $prefix = $Text.Substring($lineStart, $Offset - $lineStart) + if ($prefix -notmatch '^[ \t]*$') { return $null } + return $prefix +} +function Update-BuildDocfxImageScript([string] $Original) { + $standardFlatPattern = '(?i)\A\s*(?\$version\s*=\s*minver[^\r\n]*)(?:\r?\n[ \t]*)+(?docfx\s+metadata[^\r\n]*)(?:\r?\n[ \t]*)+(?:&\s*\(Join-Path\s+\$PSScriptRoot\s+[''"]BuildRunActions\.ps1[''"]\)(?:\r?\n[ \t]*)+)?(?docker\s+buildx\s+build[^\r\n]*)(?:\r?\n[ \t]*)+(?get-childitem\b[^\r\n]*\|\s*remove-item[^\r\n]*)\s*\z' + $standardTryPattern = '(?i)\A\s*(?\$version\s*=\s*minver[^\r\n]*)(?:\r?\n[ \t]*)+(?docfx\s+metadata[^\r\n]*)(?:\r?\n[ \t]*)+(?:&\s*\(Join-Path\s+\$PSScriptRoot\s+[''"]BuildRunActions\.ps1[''"]\)(?:\r?\n[ \t]*)+)?try\s*\{(?:\r?\n[ \t]*)+(?docker\s+buildx\s+build[^\r\n]*)(?:\r?\n[ \t]*)+\}(?:\r?\n[ \t]*)+finally\s*\{(?:\r?\n[ \t]*)+(?get-childitem\b[^\r\n]*\|\s*remove-item[^\r\n]*)(?:(?:\r?\n[ \t]*)+if\s*\(\s*Test-Path\s+-LiteralPath\s+\(Join-Path\s+\$PSScriptRoot\s+[''"]run-actions[''"]\)\s*\)\s*\{(?:\r?\n[ \t]*)+Remove-Item\s+-LiteralPath\s+\(Join-Path\s+\$PSScriptRoot\s+[''"]run-actions[''"]\)\s+-Recurse\s+-Force(?:\r?\n[ \t]*)+\})?(?:\r?\n[ \t]*)+\}\s*\z' + $nl = if ($Original.Contains("`r`n")) { "`r`n" } else { "`n" } + $trailingNewline = if ($Original -match '\r?\n\z') { $nl } else { '' } + $match = [regex]::Match($Original, $standardFlatPattern) + if (-not $match.Success) { $match = [regex]::Match($Original, $standardTryPattern) } + if ($match.Success) { + return (@( + $match.Groups['version'].Value.Trim() + $match.Groups['metadata'].Value.Trim() + "& (Join-Path `$PSScriptRoot 'BuildRunActions.ps1')" + 'try {' + (' ' + $match.Groups['docker'].Value.Trim()) + '}' + 'finally {' + (' ' + $match.Groups['cleanup'].Value.Trim()) + " if (Test-Path -LiteralPath (Join-Path `$PSScriptRoot 'run-actions')) {" + " Remove-Item -LiteralPath (Join-Path `$PSScriptRoot 'run-actions') -Recurse -Force" + ' }' + '}' + ) -join $nl) + $trailingNewline + } + + $tokens = $null; $parseErrors = $null + $ast = [Management.Automation.Language.Parser]::ParseInput($Original, [ref]$tokens, [ref]$parseErrors) + if ($parseErrors.Count) { return $Original } + + $hasInvoke = $null -ne $ast.Find({ + param($node) + if ($node -isnot [Management.Automation.Language.CommandAst]) { return $false } + if ($node.GetCommandName() -match '(^|[\\/])BuildRunActions\.ps1$') { return $true } + if ($node.InvocationOperator -notin @('Ampersand', 'Dot')) { return $false } + $target = $node.CommandElements[0] + if ($target -is [Management.Automation.Language.ParenExpressionAst] -and $target.Pipeline.PipelineElements.Count -eq 1) { + $join = $target.Pipeline.PipelineElements[0] + if ($join -is [Management.Automation.Language.CommandAst] -and $join.GetCommandName() -eq 'Join-Path') { + return $null -ne ($join.CommandElements | Where-Object { + $_ -is [Management.Automation.Language.StringConstantExpressionAst] -and $_.Value -ieq 'BuildRunActions.ps1' + } | Select-Object -First 1) + } + } + return $target.Extent.Text -match '\A"\$(?:PSScriptRoot|\{PSScriptRoot\})[\\/]BuildRunActions\.ps1"\z' + }, $true) + $hasCleanup = $Original -match "(?i)['""]run-actions['""]" + if ($hasInvoke -and $hasCleanup) { return $Original } + + $dockerCommands = @($ast.FindAll({ param($n) $n -is [Management.Automation.Language.CommandAst] -and (Test-DockerBuildCommand $n) }, $true)) + if (-not $dockerCommands.Count) { return $Original } + + $enclosingTries = [Collections.Generic.List[object]]::new() + $directStmts = [Collections.Generic.List[object]]::new() + foreach ($cmd in $dockerCommands) { + $tryNode = $null + $stmtNode = $null + for ($cur = $cmd; $cur; $cur = $cur.Parent) { + if (-not $stmtNode -and $cur -is [Management.Automation.Language.StatementAst] -and + ($cur.Parent -is [Management.Automation.Language.StatementBlockAst] -or $cur.Parent -is [Management.Automation.Language.NamedBlockAst])) { + $stmtNode = $cur + } + if ($cur.Parent -is [Management.Automation.Language.TryStatementAst] -and [object]::ReferenceEquals($cur, $cur.Parent.Body)) { + $tryNode = $cur.Parent + break + } + } + $enclosingTries.Add($tryNode) + $directStmts.Add($stmtNode) + } + + $edits = [Collections.Generic.List[object]]::new() + $allInSameTry = ($null -ne $enclosingTries[0]) -and (@($enclosingTries | Where-Object { -not [object]::ReferenceEquals($_, $enclosingTries[0]) }).Count -eq 0) + if ($allInSameTry) { + $tryAst = $enclosingTries[0] + $tryIndent = Get-LineIndent $Original $tryAst.Extent.StartOffset + if ($null -eq $tryIndent) { return $Original } + if (-not $hasInvoke) { + $edits.Add(@{ + Offset = $tryAst.Extent.StartOffset + Length = 0 + Text = "& (Join-Path `$PSScriptRoot 'BuildRunActions.ps1')$nl$tryIndent" + }) + } + if (-not $hasCleanup) { + if ($tryAst.Finally) { + $bodyIndent = $tryIndent + ' ' + if ($tryAst.Finally.Statements.Count -gt 0) { + $lastFinallyIndent = Get-LineIndent $Original $tryAst.Finally.Statements[-1].Extent.StartOffset + if ($null -ne $lastFinallyIndent) { $bodyIndent = $lastFinallyIndent } + } + $cleanupLines = @( + "${bodyIndent}if (Test-Path -LiteralPath (Join-Path `$PSScriptRoot 'run-actions')) {" + "${bodyIndent} Remove-Item -LiteralPath (Join-Path `$PSScriptRoot 'run-actions') -Recurse -Force" + "${bodyIndent}}" + ) -join $nl + $closeOffset = $tryAst.Finally.Extent.EndOffset - 1 + $closeIndent = Get-LineIndent $Original $closeOffset + if ($null -ne $closeIndent) { + $insertAt = $closeOffset - $closeIndent.Length + $edits.Add(@{ Offset = $insertAt; Length = 0; Text = $cleanupLines + $nl }) + } else { + $edits.Add(@{ Offset = $closeOffset; Length = 0; Text = $nl + $cleanupLines + $nl + $tryIndent }) + } + } else { + $finallyBlock = @( + "${tryIndent}finally {" + "${tryIndent} if (Test-Path -LiteralPath (Join-Path `$PSScriptRoot 'run-actions')) {" + "${tryIndent} Remove-Item -LiteralPath (Join-Path `$PSScriptRoot 'run-actions') -Recurse -Force" + "${tryIndent} }" + "${tryIndent}}" + ) -join $nl + $edits.Add(@{ Offset = $tryAst.Extent.EndOffset; Length = 0; Text = $nl + $finallyBlock }) + } + } + } else { + $parentBlock = if ($directStmts[0]) { $directStmts[0].Parent } else { $null } + $allInSameBlock = ($null -ne $parentBlock) -and (@($directStmts | Where-Object { $null -eq $_ -or -not [object]::ReferenceEquals($_.Parent, $parentBlock) }).Count -eq 0) + if (-not $allInSameBlock) { return $Original } + $orderedStmts = @($directStmts | Sort-Object { $_.Extent.StartOffset } -Unique) + $firstStmt = $orderedStmts[0] + $lastStmt = $orderedStmts[-1] + $indent = Get-LineIndent $Original $firstStmt.Extent.StartOffset + if ($null -eq $indent) { return $Original } + if ($hasCleanup) { + if (-not $hasInvoke) { + $edits.Add(@{ + Offset = $firstStmt.Extent.StartOffset + Length = 0 + Text = "& (Join-Path `$PSScriptRoot 'BuildRunActions.ps1')$nl$indent" + }) + } + } else { + $dockerSlice = $Original.Substring($firstStmt.Extent.StartOffset, $lastStmt.Extent.EndOffset - $firstStmt.Extent.StartOffset) + $indentedDocker = (@($dockerSlice -split '\r?\n' | ForEach-Object { + if ($_ -match '^[ \t]*$') { '' } + elseif ($indent.Length -gt 0 -and $_.StartsWith($indent, [StringComparison]::Ordinal)) { $indent + ' ' + $_.Substring($indent.Length) } + else { $indent + ' ' + $_ } + }) -join $nl) + $replaceEnd = $lastStmt.Extent.EndOffset + $cleanupBody = [Collections.Generic.List[string]]::new() + $stmtList = @($parentBlock.Statements) + $lastIdx = -1 + for ($i = 0; $i -lt $stmtList.Count; $i++) { + if ([object]::ReferenceEquals($stmtList[$i], $lastStmt)) { $lastIdx = $i; break } + } + if ($lastIdx -ge 0 -and ($lastIdx + 1) -lt $stmtList.Count) { + $nextStmt = $stmtList[$lastIdx + 1] + $gap = $Original.Substring($lastStmt.Extent.EndOffset, $nextStmt.Extent.StartOffset - $lastStmt.Extent.EndOffset) + if ($gap -match '^\s*$' -and (Test-ApiCleanupPipeline $nextStmt)) { + $cleanupBody.Add($indent + ' ' + $nextStmt.Extent.Text.Trim()) + $replaceEnd = $nextStmt.Extent.EndOffset + } + } + $cleanupBody.Add("${indent} if (Test-Path -LiteralPath (Join-Path `$PSScriptRoot 'run-actions')) {") + $cleanupBody.Add("${indent} Remove-Item -LiteralPath (Join-Path `$PSScriptRoot 'run-actions') -Recurse -Force") + $cleanupBody.Add("${indent} }") + $replacementLines = [Collections.Generic.List[string]]::new() + if (-not $hasInvoke) { + $replacementLines.Add("& (Join-Path `$PSScriptRoot 'BuildRunActions.ps1')") + $replacementLines.Add("${indent}try {") + } else { + $replacementLines.Add('try {') + } + $replacementLines.Add($indentedDocker) + $replacementLines.Add("${indent}}") + $replacementLines.Add("${indent}finally {") + foreach ($line in $cleanupBody) { $replacementLines.Add($line) } + $replacementLines.Add("${indent}}") + $edits.Add(@{ + Offset = $firstStmt.Extent.StartOffset + Length = $replaceEnd - $firstStmt.Extent.StartOffset + Text = ($replacementLines -join $nl) + }) + } + } + + if (-not $edits.Count) { return $Original } + $updated = $Original + foreach ($edit in $edits | Sort-Object -Property Offset, Length -Descending) { + $updated = $updated.Remove($edit.Offset, $edit.Length).Insert($edit.Offset, $edit.Text) + } + $verifyTokens = $null; $verifyErrors = $null + $null = [Management.Automation.Language.Parser]::ParseInput($updated, [ref]$verifyTokens, [ref]$verifyErrors) + if ($verifyErrors.Count) { return $Original } + return $updated +} +$buildImagePath = Join-Path $workspace 'BuildDocfxImage.ps1' +if (Test-Path -LiteralPath $buildImagePath) { + Assert-RepositoryPath $buildImagePath + $buildImageOriginal = [IO.File]::ReadAllText($buildImagePath) + $buildImageUpdated = Update-BuildDocfxImageScript $buildImageOriginal + Write-Page $buildImagePath $buildImageOriginal $buildImageUpdated +} 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/test-quality.ps1 b/skills/dotnet-docfx-digest/scripts/test-quality.ps1 index 7eb0f731..b6c3b9af 100644 --- a/skills/dotnet-docfx-digest/scripts/test-quality.ps1 +++ b/skills/dotnet-docfx-digest/scripts/test-quality.ps1 @@ -1,4 +1,4 @@ -param( +param( [string]$ValidatorPath = (Join-Path $PSScriptRoot 'docfx.cs') ) @@ -2738,6 +2738,221 @@ public static class StockReport if (Test-Path $architecture) { Remove-Item -LiteralPath $architecture -Recurse -Force } } +# Regression: YAML flow-sequence `example: [*content]` must be recognized as MappedToExample, +# and manual Example/Examples headings inside any `example:`-mapped body must fail with EXAMPLE_REDUNDANT_HEADING. +$headingWorkspace = Join-Path ([System.IO.Path]::GetTempPath()) ('dotnet-docfx-redundant-heading-' + [guid]::NewGuid().ToString('N')) +try { + Write-Utf8File (Join-Path $headingWorkspace 'AGENTS.md') @' + +Managed DocFX guidance. + +'@ + Write-Utf8File (Join-Path $headingWorkspace 'src/Widgets/Widgets.csproj') $projectCsproj + Write-Utf8File (Join-Path $headingWorkspace 'src/Widgets/Spinner.cs') @' +namespace Acme.Widgets; + +public sealed class Spinner +{ + public string Spin(string label) => $"Spinning: {label}"; +} +'@ + Write-Utf8File (Join-Path $headingWorkspace '.docfx/docfx.json') (New-DocfxJson @('src/Widgets/Widgets.csproj')) + Write-Utf8File (Join-Path $headingWorkspace '.docfx/api/namespaces/Acme.Widgets.md') @' +--- +uid: Acme.Widgets +summary: *content +--- +The `Acme.Widgets` namespace helps console applications render deterministic spinner labels without duplicating status formatting. Use it when long-running tasks need clear progress text; start with `Spinner` to format and display each state. + +Availability: .NET 10. +'@ + $spinnerPage = Join-Path $headingWorkspace '.docfx/api/types/Acme.Widgets.Spinner.md' + $sampleCode = @' +```csharp +using System; +using Acme.Widgets; + +namespace Acme.Samples; + +public sealed class ProgressPrinter +{ + public void Run() + { + var spinner = new Spinner(); + Console.WriteLine(spinner.Spin("Indexing")); + } +} +``` +'@ + + # 1. Valid YAML flow sequence `example: [*content]` with complementary prose and no manual heading passes. + Write-Utf8File $spinnerPage @" +--- +uid: Acme.Widgets.Spinner +example: [*content] +--- +The ``Spinner`` formats progress labels for command-line tools. The following example creates a spinner and prints the formatted status text to standard output: + + ### Example + + + +$sampleCode +"@ + $flowClean = Invoke-Validator -Workspace $headingWorkspace + Assert-NoDiagnostic $flowClean 'EXAMPLE_MISSING' + Assert-NoDiagnostic $flowClean 'EXAMPLE_REDUNDANT_HEADING' + Assert-NoDiagnostic $flowClean 'EXAMPLE_LEAD_MISSING' + + # 2. Valid spaced flow sequence `example: [ *content ]` with descriptive subheading and heading inside fence passes. + Write-Utf8File $spinnerPage @' +--- +uid: Acme.Widgets.Spinner +example: [ *content ] +--- +The `Spinner` formats progress labels for command-line tools. The following example creates a spinner and prints the formatted status text to standard output: + +### Custom label formatting + +```csharp +using System; +using Acme.Widgets; + +namespace Acme.Samples; + +public sealed class ProgressPrinter +{ + public void Run() + { + var spinner = new Spinner(); + var note = @" +### Example +"; + Console.WriteLine(spinner.Spin(note.Trim())); + } +} +``` +'@ + $spacedFlowClean = Invoke-Validator -Workspace $headingWorkspace + Assert-NoDiagnostic $spacedFlowClean 'EXAMPLE_MISSING' + Assert-NoDiagnostic $spacedFlowClean 'EXAMPLE_REDUNDANT_HEADING' + + # 3. `example: [*content]` + `### Example` in body must fail with EXAMPLE_REDUNDANT_HEADING (not EXAMPLE_MISSING). + Write-Utf8File $spinnerPage @" +--- +uid: Acme.Widgets.Spinner +example: [*content] +--- +The ``Spinner`` formats progress labels for command-line tools. + +### Example + +The following example creates a spinner and prints the formatted status text to standard output: + +$sampleCode +"@ + $flowRedundant = Invoke-Validator -Workspace $headingWorkspace + Assert-NoDiagnostic $flowRedundant 'EXAMPLE_MISSING' + Assert-Diagnostic $flowRedundant 'EXAMPLE_REDUNDANT_HEADING' + Assert-DiagnosticMessageContains $flowRedundant 'EXAMPLE_REDUNDANT_HEADING' '### Example' + + # 4. `example: *content` + `### Examples` in body must fail with EXAMPLE_REDUNDANT_HEADING. + Write-Utf8File $spinnerPage @" +--- +uid: Acme.Widgets.Spinner +example: *content +--- +### Examples + +The following example creates a spinner and prints the formatted status text to standard output: + +$sampleCode +"@ + $scalarRedundant = Invoke-Validator -Workspace $headingWorkspace + Assert-Diagnostic $scalarRedundant 'EXAMPLE_REDUNDANT_HEADING' + Assert-DiagnosticMessageContains $scalarRedundant 'EXAMPLE_REDUNDANT_HEADING' '### Examples' + + # 5. `example:\n - *content` + `## Example` in body must fail with EXAMPLE_REDUNDANT_HEADING. + Write-Utf8File $spinnerPage @" +--- +uid: Acme.Widgets.Spinner +example: + - *content +--- +## Example + +The following example creates a spinner and prints the formatted status text to standard output: + +$sampleCode +"@ + $listRedundant = Invoke-Validator -Workspace $headingWorkspace + Assert-Diagnostic $listRedundant 'EXAMPLE_REDUNDANT_HEADING' + Assert-DiagnosticMessageContains $listRedundant 'EXAMPLE_REDUNDANT_HEADING' '## Example' + + # 6. Form B (`summary: *content` + `### Example`) remains valid without EXAMPLE_REDUNDANT_HEADING. + Write-Utf8File $spinnerPage @" +--- +uid: Acme.Widgets.Spinner +summary: *content +--- +Formats progress labels for command-line tools. + +### Example + +The following example creates a spinner and prints the formatted status text to standard output: + +$sampleCode +"@ + $formBValid = Invoke-Validator -Workspace $headingWorkspace + Assert-NoDiagnostic $formBValid 'EXAMPLE_MISSING' + Assert-NoDiagnostic $formBValid 'EXAMPLE_REDUNDANT_HEADING' + + $includeNamespace = Join-Path $headingWorkspace '.docfx/api/namespaces/Acme.Widgets.md' + $include = '[!INCLUDE [availability](../../includes/availability.md)]' + Write-Utf8File $includeNamespace @" +$include + +## Examples + +$sampleCode + + +"@ + Write-Utf8File $spinnerPage @' +--- +uid: Acme.Widgets.Spinner +summary: *content +--- +Write the directive as `[!INCLUDE [availability](example.md)]`. + + + + [!INCLUDE [availability](example.md)] + +1. Literal directive example + + [!INCLUDE [availability](example.md)] +'@ + $literalIncludes = Invoke-Validator -Workspace $headingWorkspace + Assert-NoDiagnostic $literalIncludes 'API_INCLUDE_OUTSIDE_NAMESPACES' + + [IO.File]::AppendAllText($includeNamespace, "`n`n$include`n") + $lateInclude = Invoke-Validator -Workspace $headingWorkspace + Assert-DiagnosticMessageContains $lateInclude 'API_INCLUDE_OUTSIDE_NAMESPACES' 'after the examples begin' + + [IO.File]::AppendAllText($spinnerPage, "`n`n1. Availability`n`n $include`n") + $typeInclude = Invoke-Validator -Workspace $headingWorkspace + Assert-DiagnosticMessageContains $typeInclude 'API_INCLUDE_OUTSIDE_NAMESPACES' 'outside' + + Write-Host 'DocFX example: [*content], heading, and include placement regressions passed.' +} finally { + if (Test-Path $headingWorkspace) { Remove-Item -LiteralPath $headingWorkspace -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.ps1 b/skills/dotnet-docfx-digest/scripts/test-run-actions.ps1 index ada44f97..f52f6cdf 100644 --- a/skills/dotnet-docfx-digest/scripts/test-run-actions.ps1 +++ b/skills/dotnet-docfx-digest/scripts/test-run-actions.ps1 @@ -47,6 +47,7 @@ $partial = "# Partial`r`n`n``````csharp`nvar fixture = new ManagedApplicationFix [IO.File]::WriteAllText("$work/docs/partial.md", $partial) $null = New-Item -ItemType Directory "$work/template/public" -Force [IO.File]::WriteAllText("$work/template/public/main.js", "// Context7 customization`nexport default { start() { window.context7 = true; } };`n") +[IO.File]::WriteAllText("$work/BuildDocfxImage.ps1", "`$version = minver -i -t v -v w`ndocfx metadata docfx.json`ndocker buildx build -t xunit-docfx:`$version --platform linux/arm64,linux/amd64 --load -f Dockerfile.docfx .`nget-childItem -recurse -path api -include *.yml, .manifest | remove-item`n") [IO.File]::WriteAllText("$work/docfx.json", '{"build":{"content":[{"files":["docs/*.md"]}],"template":["default","modern","template"],"dest":"_site"}}') [IO.File]::WriteAllText("$work/docs/test.md", "# Test`n`n``````csharp`nusing Xunit;`npublic class ExampleTest { [Fact] public void ParsesInventoryCount() { Assert.Equal(42, int.Parse(`"42`")); } }`n```````n") $packageSource = @' @@ -137,6 +138,10 @@ $settingsPath = "$work/run-actions.settings.json" [IO.File]::WriteAllText($settingsPath, (@{examples=@($packageRecipe)} | ConvertTo-Json -Depth 20)) $first = (& $generator -RepoRoot $work) | ConvertFrom-Json if ($LASTEXITCODE -ne 2 -or @($first | Where-Object coverage -eq 'Paired').Count -ne 5 -or @($first | Where-Object coverage -eq 'Unresolved').Count -ne 1) { throw "Unexpected generation: $($first | ConvertTo-Json -Depth 10)" } +if (Test-Path -LiteralPath "$work/run-actions") { throw 'Generator must not physically create run-actions/ in the working tree; BuildRunActions.ps1 owns materialization.' } +$global:LASTEXITCODE = 0 +& "$work/BuildRunActions.ps1" | Out-Null +if ($LASTEXITCODE -ne 0) { throw 'BuildRunActions.ps1 failed to materialize scripts from run-actions.manifest.json.' } $resolved = $first | Where-Object uid -ceq $packageUid # The same envelope assets/run-actions.js accepts: one complete paste unit, so execution and verification run together. $completeScript = '\A& \{\r?\n#requires -Version 7\.0\r?\n[\s\S]*\r?\n\}\r?\n?\z' @@ -173,6 +178,27 @@ if (-not $association.Success -or $transports.Count -ne 2 -or 'native' -notin $t throw 'Both runnable assets must be delivered in one association with the same C# sample.' } if (-not (Get-Content "$work/template/public/main.js" -Raw).Contains('window.context7 = true')) { throw 'Existing template was overwritten.' } +$buildImageText = Get-Content "$work/BuildDocfxImage.ps1" -Raw +$expectedBuildImage = @( + '$version = minver -i -t v -v w' + 'docfx metadata docfx.json' + "& (Join-Path `$PSScriptRoot 'BuildRunActions.ps1')" + 'try {' + ' docker buildx build -t xunit-docfx:$version --platform linux/arm64,linux/amd64 --load -f Dockerfile.docfx .' + '}' + 'finally {' + ' get-childItem -recurse -path api -include *.yml, .manifest | remove-item' + " if (Test-Path -LiteralPath (Join-Path `$PSScriptRoot 'run-actions')) {" + " Remove-Item -LiteralPath (Join-Path `$PSScriptRoot 'run-actions') -Recurse -Force" + ' }' + '}' +) -join "`n" +if ($buildImageText -cne ($expectedBuildImage + "`n")) { + throw "Generator must rewrite an uncustomized BuildDocfxImage.ps1 to run BuildRunActions.ps1 and clean up run-actions in finally. Actual:`n$buildImageText" +} +$buildImageTokens = $null; $buildImageParseErrors = $null +$null = [Management.Automation.Language.Parser]::ParseInput($buildImageText, [ref]$buildImageTokens, [ref]$buildImageParseErrors) +if ($buildImageParseErrors.Count) { throw "Rewritten BuildDocfxImage.ps1 is not valid PowerShell: $buildImageParseErrors" } $files = @(Get-ChildItem $work -Recurse -File) $before = @{} foreach ($file in $files) { $before[$file.FullName] = @((Get-FileHash $file.FullName).Hash, $file.LastWriteTimeUtc.Ticks) } @@ -184,7 +210,7 @@ foreach ($file in Get-ChildItem $work -Recurse -File) { # Mock only the fresh-process result to exercise independent status bookkeeping without running generated code. function pwsh { $fileIndex = [Array]::IndexOf($args, '-File') - if ($fileIndex -lt 0 -or [string]$args[$fileIndex + 1] -notmatch '[\\/]native\.ps1$') { throw 'The focused verification should invoke Native only.' } + if ($fileIndex -lt 0 -or [string]$args[$fileIndex + 1] -notmatch '-native-[a-f0-9]{32}\.ps1$') { throw 'The focused verification should invoke Native only.' } $global:LASTEXITCODE = 0 } try { @@ -200,12 +226,36 @@ $toolbarModule = "$work/template/public/run-actions.js" $toolbarHash = (Get-FileHash $toolbarSource).Hash [IO.File]::WriteAllText($toolbarModule, '// Stale toolbar from a previous skill revision.') $refresh = (& $generator -RepoRoot $work) | ConvertFrom-Json -$refreshedEntry = $refresh | Where-Object id -eq $entry.id if ((Get-FileHash $toolbarModule).Hash -cne $toolbarHash -or - @($refresh | Where-Object status -eq 'unchanged').Count -ne 5 -or - $refreshedEntry.native -ne 'Verified' -or $refreshedEntry.docker -ne 'Unverified') { - throw 'Refreshing a stale toolbar must preserve the execution payloads and verification evidence.' + @($refresh | Where-Object status -eq 'unchanged').Count -ne 5) { + throw 'Refreshing a stale toolbar must preserve the manifest payloads.' +} +$refreshEntry = $refresh | Where-Object id -eq $entry.id +if ($refreshEntry.native -ne 'Verified' -or $refreshEntry.docker -ne 'Unverified' -or + $refreshEntry.nativeEvidence -cne $nativeOnlyEntry.nativeEvidence -or -not (Test-Path -LiteralPath $refreshEntry.nativeEvidence)) { + throw 'Toolbar refresh lost independent verification evidence.' } +$cacheDirectory = Split-Path $refreshEntry.nativeEvidence -Parent +$cacheRecord = Get-ChildItem -LiteralPath $cacheDirectory -Filter "*-$($entry.id)-native-$($refreshEntry.nativeSha256).json" | + Where-Object { ([IO.File]::ReadAllText($_.FullName) | ConvertFrom-Json).log -eq (Split-Path $refreshEntry.nativeEvidence -Leaf) } | + Select-Object -First 1 +if (-not $cacheRecord) { throw 'Verification record and log must share the private cache.' } +$originalRecord = [IO.File]::ReadAllText($cacheRecord.FullName) +$outsideLog = Join-Path $work (Split-Path $refreshEntry.nativeEvidence -Leaf) +[IO.File]::WriteAllText($outsideLog, 'untrusted verification log') +try { + [IO.File]::WriteAllText($cacheRecord.FullName, (@{ state = 'Verified'; log = $outsideLog } | ConvertTo-Json)) + $untrusted = ((& $generator -RepoRoot $work) | ConvertFrom-Json) | Where-Object id -eq $entry.id + if ($untrusted.native -ne 'Unverified' -or $untrusted.nativeEvidence) { throw 'Verification trusted a log outside the private cache.' } + + [IO.File]::WriteAllText($cacheRecord.FullName, $originalRecord) + $linkedLog = Join-Path $cacheDirectory ('linked-' + [guid]::NewGuid().ToString('N') + '.log') + $null = New-Item -ItemType HardLink -Path $linkedLog -Target $refreshEntry.nativeEvidence + try { + $untrusted = ((& $generator -RepoRoot $work) | ConvertFrom-Json) | Where-Object id -eq $entry.id + if ($untrusted.native -ne 'Unverified' -or $untrusted.nativeEvidence) { throw 'Verification trusted a hard-linked log.' } + } finally { [IO.File]::Delete($linkedLog) } +} finally { [IO.File]::WriteAllText($cacheRecord.FullName, $originalRecord) } foreach ($script in Get-ChildItem "$work/run-actions" -Filter '*.ps1' -Recurse -File) { if ($before[$script.FullName][0] -cne (Get-FileHash $script.FullName).Hash -or $before[$script.FullName][1] -ne $script.LastWriteTimeUtc.Ticks) { @@ -239,15 +289,114 @@ $settings = [ordered]@{ examples=@($packageRecipe, [ordered]@{ [IO.File]::WriteAllText("$work/run-actions.settings.json", ($settings | ConvertTo-Json -Depth 20)) $limited = (& $generator -RepoRoot $work) | ConvertFrom-Json $limitedEntry = $limited | Where-Object id -eq $entry.id +$global:LASTEXITCODE = 0 +& "$work/BuildRunActions.ps1" | Out-Null +if ($LASTEXITCODE -ne 0) { throw 'BuildRunActions.ps1 failed after single-transport update.' } if ($limitedEntry.coverage -ne 'Partially supported' -or $limitedEntry.docker -ne 'Unsupported' -or -not (Test-Path "$work/run-actions/$($entry.id)/native.ps1") -or (Test-Path "$work/run-actions/$($entry.id)/docker.ps1")) { throw 'Single-transport limitation was misrepresented.' } if ((Get-Content "$work/docs/integration.md" -Raw).Contains('View Docker Script')) { throw 'Unsupported Docker still has a control.' } $limitedAgain = (& $generator -RepoRoot $work) | ConvertFrom-Json if (($limitedAgain | Where-Object id -eq $entry.id).status -ne 'unchanged') { throw 'Single-transport cache requires the unsupported script.' } -# Mutating the principal source invalidates its recipe and removes both associations and owned scripts. + +# Standalone BuildRunActions.ps1 materializes byte-identical native/docker scripts from run-actions.manifest.json +# (including recipe-provided standalone manifests with custom package pins and single-transport examples) and prunes stale generated scripts. +if (-not (Test-Path "$work/run-actions.manifest.json") -or -not (Test-Path "$work/BuildRunActions.ps1")) { + throw 'Generator must emit run-actions.manifest.json and BuildRunActions.ps1 beside docfx.json.' +} +$expectedHashes = @{} +foreach ($example in $limitedAgain) { + foreach ($transport in @('native', 'docker')) { + $hash = $example."${transport}Sha256" + if ($hash) { $expectedHashes["$($example.id)/$transport.ps1"] = $hash } + } +} +if (-not $expectedHashes.ContainsKey("$($resolved.id)/native.ps1") -or + -not $expectedHashes.ContainsKey("$($resolved.id)/docker.ps1") -or + -not $expectedHashes.ContainsKey("$($entry.id)/native.ps1") -or + $expectedHashes.ContainsKey("$($entry.id)/docker.ps1")) { + throw 'Expected recipe-backed standalone scripts and single-transport repository script before testing standalone materializer.' +} +$assetsOnlyPage = "$work/docs/console.md" +$pageBefore = [IO.File]::ReadAllText($assetsOnlyPage) +$configBefore = [IO.File]::ReadAllText("$work/docfx.json") +Get-ChildItem -LiteralPath "$work/run-actions" -Directory | Remove-Item -Recurse -Force +$staleExampleDir = "$work/run-actions/deadbeefdeadbeefdeadbeef" +$null = [IO.Directory]::CreateDirectory($staleExampleDir) +[IO.File]::WriteAllText("$staleExampleDir/native.ps1", '# stale example native') +[IO.File]::WriteAllText("$staleExampleDir/docker.ps1", '# stale example docker') +$staleTransportDir = "$work/run-actions/$($entry.id)" +$null = [IO.Directory]::CreateDirectory($staleTransportDir) +$staleTransportPath = "$staleTransportDir/docker.ps1" +[IO.File]::WriteAllText($staleTransportPath, '# stale transport') +$unrelatedRootFile = "$work/run-actions/unrelated.txt" +[IO.File]::WriteAllText($unrelatedRootFile, 'keep root') +$unrelatedDir = "$work/run-actions/custom" +$null = [IO.Directory]::CreateDirectory($unrelatedDir) +$unrelatedDirScript = "$unrelatedDir/native.ps1" +[IO.File]::WriteAllText($unrelatedDirScript, '# unrelated script') +$mixedExampleDir = "$work/run-actions/0123456789abcdef01234567" +$null = [IO.Directory]::CreateDirectory($mixedExampleDir) +[IO.File]::WriteAllText("$mixedExampleDir/native.ps1", '# stale mixed native') +$mixedKeepFile = "$mixedExampleDir/keep.txt" +[IO.File]::WriteAllText($mixedKeepFile, 'keep inside example dir') +$global:LASTEXITCODE = 0 +& "$work/BuildRunActions.ps1" | Out-Null +if ($LASTEXITCODE -ne 0) { throw 'Standalone BuildRunActions.ps1 failed.' } +if ((Test-Path -LiteralPath $staleExampleDir) -or + (Test-Path -LiteralPath $staleTransportPath) -or + (Test-Path -LiteralPath "$mixedExampleDir/native.ps1")) { + throw 'BuildRunActions.ps1 left stale generated scripts or empty stale directories behind.' +} +if (-not (Test-Path -LiteralPath $unrelatedRootFile) -or + -not (Test-Path -LiteralPath $unrelatedDirScript) -or + -not (Test-Path -LiteralPath $mixedKeepFile)) { + throw 'BuildRunActions.ps1 deleted unrelated files.' +} +Remove-Item -LiteralPath $unrelatedRootFile, $unrelatedDir, $mixedExampleDir -Recurse -Force +$actualFiles = @(Get-ChildItem -Path "$work/run-actions" -Recurse -Filter '*.ps1') +if ($actualFiles.Count -ne $expectedHashes.Count) { throw "BuildRunActions.ps1 produced $($actualFiles.Count) scripts; expected $($expectedHashes.Count)." } +foreach ($psFile in $actualFiles) { + $rel = [IO.Path]::GetRelativePath("$work/run-actions", $psFile.FullName).Replace('\', '/') + $actualHash = (Get-FileHash -LiteralPath $psFile.FullName -Algorithm SHA256).Hash + if ($expectedHashes[$rel] -cne $actualHash) { throw "BuildRunActions.ps1 drifted from generator output for $rel." } +} +if ([IO.File]::ReadAllText($assetsOnlyPage) -cne $pageBefore -or [IO.File]::ReadAllText("$work/docfx.json") -cne $configBefore) { + throw 'BuildRunActions.ps1 must not modify Markdown or docfx.json.' +} +$noManifestDir = Join-Path $work 'no-manifest' +$null = [IO.Directory]::CreateDirectory($noManifestDir) +Copy-Item -LiteralPath "$work/BuildRunActions.ps1" -Destination (Join-Path $noManifestDir 'BuildRunActions.ps1') +$global:LASTEXITCODE = 0 +& (Join-Path $noManifestDir 'BuildRunActions.ps1') | Out-Null +if ($LASTEXITCODE -ne 0 -or (Test-Path (Join-Path $noManifestDir 'run-actions'))) { + throw 'BuildRunActions.ps1 must no-op cleanly when no default run-actions.manifest.json exists.' +} + +# A changed script under the same example ID must discard that transport's verification. +$retargeted = (& $generator -RepoRoot $work -Framework net9.0) | ConvertFrom-Json +$verifiedConsole = $nativeOnly | Where-Object { $_.file -like '*console.md' } +$retargetedConsole = $retargeted | Where-Object id -eq $verifiedConsole.id +if (-not $retargetedConsole.nativeSha256 -or $retargetedConsole.nativeSha256 -ceq $verifiedConsole.nativeSha256 -or + $retargetedConsole.native -ne 'Unverified' -or $retargetedConsole.nativeEvidence) { + throw 'A changed Native script reused stale verification evidence.' +} + +# Mutating the principal source invalidates its recipe and removes both associations and manifest entries. [IO.File]::WriteAllText("$work/docs/integration.md", $updated.Replace('Bootstrapper Minimal Worker', 'Changed assertion')) $third = (& $generator -RepoRoot $work) | ConvertFrom-Json +$global:LASTEXITCODE = 0 +& "$work/BuildRunActions.ps1" | Out-Null if ((Test-Path "$work/run-actions/$($entry.id)/native.ps1") -or (Get-Content "$work/docs/integration.md" -Raw).Contains('data-example-id')) { throw 'Stale recipe/assets survived source change.' } +# Deleting the only fence must remove its association even when the page no longer has inventory entries. +$consolePage = "$work/docs/console.md" +$consoleWithActions = [IO.File]::ReadAllText($consolePage) +[IO.File]::WriteAllText($consolePage, [regex]::Replace($consoleWithActions, '(?s)\x60{3}csharp.*?\x60{3}', '')) +$withoutConsole = (& $generator -RepoRoot $work) | ConvertFrom-Json +if (($withoutConsole | Where-Object file -eq $consolePage) -or [IO.File]::ReadAllText($consolePage).Contains('docfx-run-actions:start')) { + throw 'Removing the last C# fence left a stale association.' +} +[IO.File]::WriteAllText($consolePage, $consoleWithActions) + # A legacy hidden harness is a failed recipe, while an intrinsic limitation has no assets. $invalidRecipe = $packageRecipe | ConvertTo-Json -Depth 20 | ConvertFrom-Json -AsHashtable $invalidRecipe.harness = @{members='public sealed class HiddenTest { [Fact] public void Hidden() {} }'} @@ -256,9 +405,12 @@ $intrinsic = @{uid=$partialResult.uid; sourceSha256=$partialResult.sourceSha256; $customSettings = "$work/custom-settings.json" [IO.File]::WriteAllText($customSettings, (@{examples=@($invalidRecipe,$intrinsic)} | ConvertTo-Json -Depth 20)) $classified = (& $generator -RepoRoot $work -Settings $customSettings) | ConvertFrom-Json +$classifiedExit = $LASTEXITCODE +$global:LASTEXITCODE = 0 +& "$work/BuildRunActions.ps1" | Out-Null $invalid = $classified | Where-Object id -eq $resolved.id $limitedPartial = $classified | Where-Object id -eq $partialResult.id -if ($LASTEXITCODE -ne 1 -or $invalid.coverage -ne 'Unresolved' -or $invalid.reason -notlike '*Move the executable C# into the displayed sample*' -or +if ($classifiedExit -ne 1 -or $invalid.coverage -ne 'Unresolved' -or $invalid.reason -notlike '*Move the executable C# into the displayed sample*' -or (Test-Path "$work/run-actions/$($resolved.id)/native.ps1") -or (Test-Path "$work/run-actions/$($resolved.id)/docker.ps1") -or $limitedPartial.coverage -ne 'Intrinsically non-executable' -or $limitedPartial.native -ne 'Unsupported' -or $limitedPartial.docker -ne 'Unsupported' -or (Test-Path "$work/run-actions/$($limitedPartial.id)/native.ps1")) { @@ -287,4 +439,201 @@ try { } if ([IO.File]::ReadAllText($externalPage) -cne $console) { throw 'Rejected inventory changed the external page.' } } finally { $inventoryOverride = $null } -Write-Host "Run-action delivery passed: paired console, test, dependency-backed test and repository test; exact pins and source, coverage classifications, independent verification state, incremental assets, stale cleanup and modern DocFX render. Fixture: $work" + +# Verify BuildDocfxImage.ps1 variants: standard try/finally, partially-wired CRLF flat script, customized scripts (flat, existing try/finally, try/catch, multiline docker build), and non-docker wrapper preservation. +$buildImageVariants = @( + @{ + Name = 'already-try-finally' + Input = "`$version = minver -i -t v -v w`ndocfx metadata docfx.json`ntry {`n docker buildx build -t sample-docfx:`$version --platform linux/arm64,linux/amd64 --load -f Dockerfile.docfx .`n}`nfinally {`n Get-ChildItem -Recurse -Path api -Include *.yml, .manifest | Remove-Item`n}`n" + Expected = @( + '$version = minver -i -t v -v w' + 'docfx metadata docfx.json' + "& (Join-Path `$PSScriptRoot 'BuildRunActions.ps1')" + 'try {' + ' docker buildx build -t sample-docfx:$version --platform linux/arm64,linux/amd64 --load -f Dockerfile.docfx .' + '}' + 'finally {' + ' Get-ChildItem -Recurse -Path api -Include *.yml, .manifest | Remove-Item' + " if (Test-Path -LiteralPath (Join-Path `$PSScriptRoot 'run-actions')) {" + " Remove-Item -LiteralPath (Join-Path `$PSScriptRoot 'run-actions') -Recurse -Force" + ' }' + '}' + ) -join "`n" + Trailing = "`n" + } + @{ + Name = 'partially-wired-crlf' + Input = "`$version = minver -i -t v -v w`r`ndocfx metadata docfx.json`r`n& (Join-Path `$PSScriptRoot 'BuildRunActions.ps1')`r`ndocker buildx build -t xunit-docfx:`$version --platform linux/arm64,linux/amd64 --load -f Dockerfile.docfx .`r`nget-childItem -recurse -path api -include *.yml, .manifest | remove-item`r`n" + Expected = @( + '$version = minver -i -t v -v w' + 'docfx metadata docfx.json' + "& (Join-Path `$PSScriptRoot 'BuildRunActions.ps1')" + 'try {' + ' docker buildx build -t xunit-docfx:$version --platform linux/arm64,linux/amd64 --load -f Dockerfile.docfx .' + '}' + 'finally {' + ' get-childItem -recurse -path api -include *.yml, .manifest | remove-item' + " if (Test-Path -LiteralPath (Join-Path `$PSScriptRoot 'run-actions')) {" + " Remove-Item -LiteralPath (Join-Path `$PSScriptRoot 'run-actions') -Recurse -Force" + ' }' + '}' + ) -join "`r`n" + Trailing = "`r`n" + } + @{ + Name = 'customized-flat' + Input = "param([string] `$Registry = 'ghcr.io/example')`n`$version = minver -i -t v -v w`nWrite-Host `"Building `$Registry/docs:`$version`"`n# & (Join-Path `$PSScriptRoot 'BuildRunActions.ps1')`ndocfx metadata docfx.json`ndocker buildx build -t `"`$Registry/docs:`$version`" -f Dockerfile.docfx .`nget-childItem -recurse -path api -include *.yml, .manifest | remove-item`n" + Expected = @( + "param([string] `$Registry = 'ghcr.io/example')" + '$version = minver -i -t v -v w' + 'Write-Host "Building $Registry/docs:$version"' + "# & (Join-Path `$PSScriptRoot 'BuildRunActions.ps1')" + 'docfx metadata docfx.json' + "& (Join-Path `$PSScriptRoot 'BuildRunActions.ps1')" + 'try {' + ' docker buildx build -t "$Registry/docs:$version" -f Dockerfile.docfx .' + '}' + 'finally {' + ' get-childItem -recurse -path api -include *.yml, .manifest | remove-item' + " if (Test-Path -LiteralPath (Join-Path `$PSScriptRoot 'run-actions')) {" + " Remove-Item -LiteralPath (Join-Path `$PSScriptRoot 'run-actions') -Recurse -Force" + ' }' + '}' + ) -join "`n" + Trailing = "`n" + } + @{ + Name = 'customized-try-finally' + Input = "param([string] `$Tag = 'dev')`ndocfx metadata docfx.json`ntry {`n Write-Host `"Start `$Tag`"`n docker buildx build -t `"custom:`$Tag`" -f Dockerfile.docfx .`n}`nfinally {`n get-childItem -recurse -path api -include *.yml, .manifest | remove-item`n Write-Host 'Done'`n}`n" + Expected = @( + "param([string] `$Tag = 'dev')" + 'docfx metadata docfx.json' + "& (Join-Path `$PSScriptRoot 'BuildRunActions.ps1')" + 'try {' + ' Write-Host "Start $Tag"' + ' docker buildx build -t "custom:$Tag" -f Dockerfile.docfx .' + '}' + 'finally {' + ' get-childItem -recurse -path api -include *.yml, .manifest | remove-item' + " Write-Host 'Done'" + " if (Test-Path -LiteralPath (Join-Path `$PSScriptRoot 'run-actions')) {" + " Remove-Item -LiteralPath (Join-Path `$PSScriptRoot 'run-actions') -Recurse -Force" + ' }' + '}' + ) -join "`n" + Trailing = "`n" + } + @{ + Name = 'customized-try-catch' + Input = "`$version = minver -i -t v -v w`ndocfx metadata docfx.json`ntry {`n docker buildx build -t custom-docfx:`$version -f Dockerfile.docfx .`n}`ncatch {`n Write-Error `$_`n throw`n}`n" + Expected = @( + '$version = minver -i -t v -v w' + 'docfx metadata docfx.json' + "& (Join-Path `$PSScriptRoot 'BuildRunActions.ps1')" + 'try {' + ' docker buildx build -t custom-docfx:$version -f Dockerfile.docfx .' + '}' + 'catch {' + ' Write-Error $_' + ' throw' + '}' + 'finally {' + " if (Test-Path -LiteralPath (Join-Path `$PSScriptRoot 'run-actions')) {" + " Remove-Item -LiteralPath (Join-Path `$PSScriptRoot 'run-actions') -Recurse -Force" + ' }' + '}' + ) -join "`n" + Trailing = "`n" + } + @{ + Name = 'customized-multiline-poststep' + Input = "param([string] `$Tag = 'latest')`ndocfx metadata docfx.json`ndocker buildx build ```n -t `"custom-docs:`$Tag`" ```n -f Dockerfile.docfx .`nWrite-Host `"Built `$Tag`"`n" + Expected = @( + "param([string] `$Tag = 'latest')" + 'docfx metadata docfx.json' + "& (Join-Path `$PSScriptRoot 'BuildRunActions.ps1')" + 'try {' + ' docker buildx build `' + ' -t "custom-docs:$Tag" `' + ' -f Dockerfile.docfx .' + '}' + 'finally {' + " if (Test-Path -LiteralPath (Join-Path `$PSScriptRoot 'run-actions')) {" + " Remove-Item -LiteralPath (Join-Path `$PSScriptRoot 'run-actions') -Recurse -Force" + ' }' + '}' + 'Write-Host "Built $Tag"' + ) -join "`n" + Trailing = "`n" + } + @{ + Name = 'customized-non-docker' + Input = "param([string] `$Env = 'prod')`n& (Join-Path `$PSScriptRoot 'CustomPipeline.ps1') -Env `$Env`n" + Expected = "param([string] `$Env = 'prod')`n& (Join-Path `$PSScriptRoot 'CustomPipeline.ps1') -Env `$Env" + Trailing = "`n" + } +) +foreach ($variant in $buildImageVariants) { + $variantRoot = Join-Path $work ("build-image-" + $variant.Name) + $null = [IO.Directory]::CreateDirectory($variantRoot) + $variantConfig = Join-Path $variantRoot 'docfx.json' + $variantScript = Join-Path $variantRoot 'BuildDocfxImage.ps1' + [IO.File]::WriteAllText($variantConfig, '{"build":{"template":["default","modern"]}}') + [IO.File]::WriteAllText($variantScript, $variant.Input) + $inventoryOverride = @{ config = $variantConfig; examples = @() } | ConvertTo-Json -Depth 5 + try { + $null = & $generator -RepoRoot $variantRoot + if ($LASTEXITCODE -ne 0) { throw "Generator failed for BuildDocfxImage variant $($variant.Name)." } + $actualVariant = [IO.File]::ReadAllText($variantScript) + if ($actualVariant -cne ($variant.Expected + $variant.Trailing)) { + throw "BuildDocfxImage variant $($variant.Name) did not match expected output. Actual:`n$actualVariant" + } + $vTokens = $null; $vErrors = $null + $null = [Management.Automation.Language.Parser]::ParseInput($actualVariant, [ref]$vTokens, [ref]$vErrors) + if ($vErrors.Count) { throw "BuildDocfxImage variant $($variant.Name) produced invalid PowerShell: $vErrors" } + $beforeHash = (Get-FileHash $variantScript).Hash + $beforeTicks = (Get-Item $variantScript).LastWriteTimeUtc.Ticks + $null = & $generator -RepoRoot $variantRoot + if ($LASTEXITCODE -ne 0 -or (Get-FileHash $variantScript).Hash -cne $beforeHash -or (Get-Item $variantScript).LastWriteTimeUtc.Ticks -ne $beforeTicks) { + throw "BuildDocfxImage variant $($variant.Name) was not idempotent on second run." + } + } finally { $inventoryOverride = $null } +} + +# Template ordering: templates/modern must come before templates/ms-style, with templates/ms-style always last. +$templateOrderCases = @( + @{ + Name = 'ms-style-without-modern' + Initial = @('default', 'modern', 'templates/ms-style') + CreateModernMain = $false + Expected = @('default', 'modern', 'templates/modern', 'templates/ms-style') + } + @{ + Name = 'ms-style-before-existing-modern' + Initial = @('default', 'modern', 'templates/ms-style', 'templates/modern') + CreateModernMain = $true + Expected = @('default', 'modern', 'templates/modern', 'templates/ms-style') + } +) +foreach ($case in $templateOrderCases) { + $caseRoot = Join-Path $work ("template-order-" + $case.Name) + $null = [IO.Directory]::CreateDirectory($caseRoot) + $caseConfig = Join-Path $caseRoot 'docfx.json' + [IO.File]::WriteAllText($caseConfig, (@{ build = @{ template = $case.Initial } } | ConvertTo-Json -Depth 5 -Compress)) + if ($case.CreateModernMain) { + $modernPublic = Join-Path $caseRoot 'templates/modern/public' + $null = [IO.Directory]::CreateDirectory($modernPublic) + [IO.File]::WriteAllText((Join-Path $modernPublic 'main.js'), "export default {};`n") + } + $inventoryOverride = @{ config = $caseConfig; examples = @() } | ConvertTo-Json -Depth 5 + try { + $null = & $generator -RepoRoot $caseRoot + if ($LASTEXITCODE -ne 0) { throw "Generator failed for template-order case $($case.Name)." } + $actualTemplates = @((Get-Content $caseConfig -Raw | ConvertFrom-Json).build.template) + if (($actualTemplates -join ',') -cne ($case.Expected -join ',')) { + throw "Template order case $($case.Name) expected [$($case.Expected -join ', ')], got [$($actualTemplates -join ', ')]." + } + } finally { $inventoryOverride = $null } +} + +Write-Host "Run-action delivery passed: paired console, test, dependency-backed test and repository test; exact pins and source, coverage classifications, independent verification state, incremental assets, stale cleanup, standalone BuildRunActions.ps1 materialization and modern DocFX render. Fixture: $work"