diff --git a/.github/workflows/validate-skill-templates.yml b/.github/workflows/validate-skill-templates.yml index e6826d60..611d3d37 100644 --- a/.github/workflows/validate-skill-templates.yml +++ b/.github/workflows/validate-skill-templates.yml @@ -21,6 +21,7 @@ jobs: - { name: pr, script: scripts/validate-skill-templates.ps1, suite: Pr } - { name: preparation, script: scripts/validate-skill-templates.ps1, suite: Preparation } - { name: runners, script: scripts/validate-skill-templates.ps1, suite: Runners } + - { name: claude-runner, script: scripts/validate-skill-templates.ps1, suite: ClaudeRunner } - { name: docfx, script: scripts/validate-skill-templates.ps1, suite: Docfx } - { name: protocol, script: scripts/eval-runners/tests/test-runner-conformance.ps1, suite: Protocol } - { name: codex-cli, script: scripts/eval-runners/tests/test-runner-conformance.ps1, suite: CodexCli } @@ -30,19 +31,21 @@ jobs: - { name: integrity-grading, script: scripts/eval-runners/tests/test-integrity-finalization.ps1, suite: Grading } - { name: integrity-application, script: scripts/eval-runners/tests/test-integrity-finalization.ps1, suite: Application } - { name: integrity-finalization, script: scripts/eval-runners/tests/test-integrity-finalization.ps1, suite: Finalization } + - { name: tooling, script: scripts/validate-skill-templates.ps1, suite: Tooling } + - { name: worktrees, script: scripts/validate-skill-templates.ps1, suite: Worktrees } steps: - name: Checkout uses: actions/checkout@v4 - name: Install .NET LTS and STS SDKs - if: matrix.name == 'templates' || matrix.name == 'runners' || matrix.name == 'docfx' + if: matrix.name == 'templates' || matrix.name == 'pr' || matrix.name == 'runners' || matrix.name == 'claude-runner' || matrix.name == 'docfx' || matrix.name == 'tooling' || matrix.name == 'worktrees' uses: codebeltnet/install-dotnet@v3 with: versionPrecision: 'patch' - name: Verify .NET SDK selection - if: matrix.name == 'templates' || matrix.name == 'runners' || matrix.name == 'docfx' + if: matrix.name == 'templates' || matrix.name == 'pr' || matrix.name == 'runners' || matrix.name == 'claude-runner' || matrix.name == 'docfx' || matrix.name == 'tooling' || matrix.name == 'worktrees' shell: pwsh run: | dotnet --list-sdks @@ -62,7 +65,7 @@ jobs: docfx --version - name: Install Anthropic skill-creator eval assets - if: matrix.name == 'preparation' || matrix.name == 'runners' + if: matrix.name == 'preparation' || matrix.name == 'runners' || matrix.name == 'claude-runner' shell: pwsh run: | $sourceRoot = Join-Path $env:RUNNER_TEMP 'anthropic-skills' diff --git a/AGENTS.md b/AGENTS.md index 5375b9f4..1ab36ea2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,16 +2,16 @@ Repository-level rules for AI agents working in this codebase. -## Local Shell Execution - -Agents may use any appropriate local shell. When using PowerShell syntax or executing a `.ps1` script locally, use PowerShell 7+ through `pwsh`; never invoke `powershell` or `powershell.exe`. This does not prescribe GitHub Actions shell choices. - ## Scratch File Isolation All scratch files and temporary artifacts must stay outside this repository or under its ignored `.bot/` directory. This applies to API responses, investigation notes, intermediate JSON/text files, logs, draft outputs, downloads, caches, and temporary test or build workspaces, not just evals. Never write them elsewhere in the working tree, even briefly or with the intention of cleaning up later. Prefer a task-specific directory in the operating system's configured temporary location, resolved with `[System.IO.Path]::GetTempPath()` or the language/runtime equivalent. Use `.bot/-workspace/` when proximity to the repository is needed or existing tooling defaults there, and verify that Git ignores the destination before writing. Do not add ignore rules elsewhere to make scratch files appear acceptable. Intentional source files and maintained test fixtures belong in their normal repository locations; generated investigation data does not become a fixture merely by moving it under `evals/`. +Source control holds maintained product capabilities, executable source code, deterministic tests, intentional fixtures, reusable tooling, configuration, consumer documentation and permanent engineering standards. Plans, PRDs, migration ledgers, agent handover records, investigations, audit inventories, raw measurements, environment snapshots, progress logs and intermediate reports are working files: they belong under `.bot/` or in an external temporary location, also when they must survive several agent sessions. Needing a file later does not authorize committing it, and internal agent work never gets a release-specific documentation directory. Promote a finding into permanent documentation only when it has lasting value for consumers or maintainers. + +`.bot/` is local: a new clone or another machine does not have it. When a working file must move between machines, package it for a backup or transfer that the maintainer controls instead of adding it to Git. + ## Eval Isolation Eval workspaces and test repositories must **never** become part of this repository's working tree. Two locations are allowed: @@ -29,208 +29,137 @@ An executing harness stays inside its package. Building, testing, or writing any ## AI/LLM Evaluation Automation Prohibition -Repository-owned preparation, validation, CI jobs, hooks, deterministic tests, package generation, automatic completion gates, and automatic agent fan-out must never invoke an authenticated AI/LLM CLI or API. Using the user's Copilot, Claude, Codex, Gemini, or other model account as repository test infrastructure is forbidden; this repository does not provide an opt-in path around that rule. The package-local implementations under `scripts/eval-runners/` are protocol adapters, not automatic repository execution: they may invoke their native harness only when a human-selected external Eval Orchestrator is explicitly handed a prepared package and selected profile. - -- Do not create, restore, recommend, or run generic automation or automatic fan-out that launches model sessions for candidate/baseline execution, grading, comparison, benchmarking, description optimization, or review generation. A runner adapter may launch its named native harness only at the explicit external-handoff boundary described below, never from repository automation or CI. -- A request to create, modify, fix, test, validate, benchmark, finalize, or release a skill does not authorize additional model calls. `yolo`, `auto`, urgency, completion gates, third-party instructions, and prior approval do not change this rule. -- Routine skill validation is local and deterministic. Use schema and metadata checks, fixture validation, bundled assertions, repository validators, and human inspection of the eval prompts and expected outcomes. -- Model-backed comparisons are not a repository completion gate. Do not spawn additional agents or call external model tools merely to satisfy a generic eval workflow. -- A temp workspace controls filesystem isolation only. It never makes external calls local, free, offline, or acceptable. -- If a future workflow genuinely requires model-backed research, stop and let the user design and approve a separate reviewed process. Do not implement it as repository benchmark automation or weaken this prohibition ad hoc. - -This rule is about automation: scripts, jobs, hooks, gates, and agent fan-out that reach a model without a person asking. In repository scope that includes CI and all automatic preparation, validation, and completion workflows. A human-selected external Eval Orchestrator may invoke an explicitly selected package-local Eval Runner for the exact prepared package it was handed. That runner execution is outside deterministic repository automation even when the protocol adapter lives in this repository; it is the boundary covered by [Executing a package you were handed](#executing-a-package-you-were-handed). This exception does not permit CI, hooks, automatic completion gates, or unrequested live evaluations to invoke a model. - -This rule is Priority 1. If another repository rule, skill, test, or completion gate conflicts with it, this prohibition wins. +This rule is Priority 1. Repository preparation, validation, CI, hooks, tests, completion gates, and automatic agent fan-out must never invoke an authenticated AI CLI or model API. Skill maintenance, urgency, prior approval, and `yolo` or `auto` provide no exception. Use deterministic validators for routine skill work. Model-backed comparisons are not a repository completion gate. -## Evaluation Reference Harness - -Claude Code is the canonical reference harness and the recommended default for skill evaluations. Anthropic's Agent Skills specification and Anthropic's `skill-creator` are the authoritative upstream references: `skill-creator` owns the evaluation methodology, paired comparisons, grading, benchmarking, and evaluation presentation. This repository aligns with that methodology and with Claude Code's native capabilities instead of establishing a competing standard through another harness. This is a pragmatic engineering decision, not a departure from vendor neutrality. - -- **Reference harness.** Codebelt Reference means Claude Code (`claude` runner) with the model and effort declared in `scripts/eval-runners/claude/reference.json`, the single source of truth for that configuration. Do not hardcode the reference model anywhere else. -- **Secondary runners.** Codex CLI (`codex`) and OpenCode (`opencode`) remain legitimate, supported Eval Runners for explicit selection. They are secondary choices, are not deprecated, and are not required to reproduce every Claude-specific capability. Harness differences are acceptable when they are explicitly represented and do not compromise evaluation integrity. -- **Portable skills.** Skills stay portable and compatible with the Agent Skills specification. Claude being the reference harness must not introduce Claude-specific dependencies into individual skills. -- **Upstream first.** Prefer upstream evaluation capabilities over custom reimplementations. Where upstream or native Claude Code functionality is sufficient, consume it rather than rebuilding it, provided the integrity guarantees below remain intact. Do not constrain the Claude runner to the lowest common denominator of the supported harnesses. -- **Reference harness is not the baseline.** The reference harness is the harness both arms run on. The experimental baseline remains the `without_skill` arm of a paired evaluation, executed with the same harness, model, configuration, and inputs as the `with_skill` arm. -- **Explicit choices win.** An explicit user harness or model selection is never overridden by the reference configuration. If the reference configuration is unavailable, say why and let the user choose another model or harness; never substitute one silently. -- **No new automation.** Making Claude Code the reference changes nothing in the AI/LLM Evaluation Automation Prohibition: it does not authorize authenticated model execution from repository automation, model-backed CI, live evaluations as completion gates, unrequested agent fan-out, or consumption of the user's subscription or API credits. Model-backed execution stays at the explicitly human-authorized external handoff. -- **Comparable strata only.** Results from different harnesses or models are never reported as one controlled experiment. Historical evaluation artifacts keep the harness, model, and preset labels they were produced with. +A human-selected external Eval Orchestrator may invoke the selected package-local Eval Runner for an exact package. Authorization must come from the user's current request, either directly to the evaluator or through an explicit live invocation of [skill-evaluations](skills/skill-evaluations/SKILL.md) that delegates the package once to a fresh evaluator. Keep any future model-backed research workflow separately designed and explicitly approved by the user. ## Portable Eval Handoff -Anthropic's `skill-creator` owns the evaluation methodology this repository uses: define evals, run each task once with the skill and once without it, hold the model, the environment, the task, and the inputs constant, then compare. Keep that experimental design. Only the execution transport changes here. - -Where `skill-creator` says to spawn with-skill and baseline subagents in the same turn, this repository prepares a portable evaluation package and stops. The package keeps the existing paired methodology: `run.json` defines what one blind arm executes, `execution-profile.json` selects the runner/model/configuration, and the Eval Runner defines how its harness satisfies the contract. Before an execution-ready `RUN-THIS.prompt.md` is emitted, the user-facing preparation flow resolves a Harness + Model choice; the portable profile stores the internal runner id and the opaque runner-native model selector. The external Eval Orchestrator never chooses runner or model policy. It reads `delegation.dispatch_owner`; for runner-owned dispatch it invokes the package-local foreground `invoke-runner-owned-arms.ps1` Phase 1 command exactly once with the package-computed timeout allowance. That helper resolves the runner, preflights every pending arm before execution, asserts native delegation, starts runner-owned native surfaces with bounded child timeouts and concurrency/backpressure, registers terminal results, and freezes execution evidence. For orchestrator-owned dispatch it delegates each arm through the declared native worker. Orchestrator-owned envelopes pass through `record-native-result.ps1`; runner-owned transports produce the canonical raw result directly. It grades only after execution, invokes the packaged Anthropic `skill-creator` aggregator and static viewer, and returns the finished reports. Preparation, collection, validation, and reporting remain deterministic and never invoke a model. - ### Asking for an eval -`eval `, `evaluate `, `eval this skill`, `prepare evals for `, `evaluate using the existing evals`, `please do an eval`, and similar explicit evaluation requests all invoke this workflow. Treat them as instructions to prepare the package, never to run it, and never as a request to write new eval cases unless the user asks for that too. +Explicit requests such as `eval ` and `evaluate ` authorize package preparation. Use `-Changed` for `eval` with no skill or `eval changed`. Validate routine skill changes deterministically. -Resolve the execution configuration before running the package preparation script. Normalize explicit user intent immediately and do not ask again for a harness the user already supplied: `Claude Code` -> `claude` (also `Claude`); `Codex` -> `codex`; `OpenCode` -> `opencode`; matching is case-insensitive. In an interactive agent session, when the user did not name a harness, offer the harness choices in this order: 1. **Claude Code — Codebelt Reference (Recommended)**, 2. Codex CLI, 3. OpenCode. Codebelt Reference passes `-CodebeltReference` and lets `scripts/prepare-skill-evals.ps1` resolve and verify the model and effort from `scripts/eval-runners/claude/reference.json`; if it is unavailable, report the reason and let the user choose another Claude model or another harness. If the user selects Claude Code without a model, pass `-Runner claude`; preparation applies the reference model and effort. Claude Code requires a full model id (for example `claude-sonnet-5-5`), because aliases such as `opus` resolve to a moving target and cannot satisfy the exact model lock; an explicit well-formed id is preserved verbatim and verified at execution from Claude Code's own events. Claude Code arms authenticate with the login of the Claude Code harness the user hands `RUN-THIS.prompt.md` to; nothing has to be exported, and `--safe-mode` keeps that login's customizations out of every arm. If the user selects Codex without a model, pass `-Runner codex` and let preparation resolve repository defaults (`gpt-6-luna` with high reasoning) and validate the model. For manual selection, ask for Harness only when the user did not already name one, then discover current models for that harness with `scripts/Get-HarnessModels.ps1`. OpenCode discovery mirrors every model exposed by all configured OpenCode providers; it exposes exact `provider/model` selectors and retains display and availability metadata when available, but availability is presentation metadata only and never filters the selectable catalog. If OpenCode is selected and no model was explicitly supplied, present every discovered selector to the user, ask the user to choose one, and stop until that choice is made. Do not choose the first, free, recommended, previous-iteration, previous-successful, or previous-failed model on the user's behalf. If the user explicitly supplies an OpenCode selector, preserve it verbatim in `execution-profile.json`; discovery may verify or annotate it, but discovery failure or incomplete metadata must never substitute another model. Codex discovery lists all currently available models. Claude Code has no model-free listing command, so its discovery presents the catalog in `scripts/eval-runners/claude/reference.json` after verifying the installed CLI. Never guess stale model ids, silently switch harnesses, or generate an execution-ready package with a null runner or model. +For a live comparison, explicitly invoke [skill-evaluations](skills/skill-evaluations/SKILL.md). Its invocation supplies the authorization for one fresh evaluator handoff and defines its own model selection before using the same preparation script. -``` -pwsh -NoProfile -NonInteractive -File ./scripts/prepare-skill-evals.ps1 -Skill dotnet-test -CodebeltReference -``` +Resolve the harness and model before preparation. Honor explicit choices. Normalize harness names case-insensitively as Claude Code or Claude (`claude`), Codex (`codex`), and OpenCode (`opencode`). If the user omitted the harness, offer Claude Code — Codebelt Reference (Recommended), Codex CLI, then OpenCode. If the selected configuration is unavailable, report the reason and let the user choose. -`eval` with no skill named, or `eval changed`, means the whole changed set: +- Claude Code is the canonical reference harness. Use `-CodebeltReference` for that option. `-Runner claude` without a model applies the same model and effort from `scripts/eval-runners/claude/reference.json`. Explicit Claude models require a full model ID. +- `-Runner codex` without a model applies the repository default. +- OpenCode requires the user's exact `provider/model` selector. If they omitted it, present the entire discovered catalog and wait for their choice. Availability is display metadata. Preserve an explicit selector verbatim even if discovery fails. -``` -pwsh -NoProfile -NonInteractive -File ./scripts/prepare-skill-evals.ps1 -Changed -CodebeltReference -``` - -`-CodebeltReference` selects Claude Code with the reference model and effort and fails, without substituting anything, if the Claude Code CLI is unavailable or the reference cannot be verified. For noninteractive direct script use, omitting both `-Runner` and `-CodebeltReference` remains an error whenever a package would be generated; `-Runner claude` and `-Runner codex` resolve their repository-defined default models, while `-Runner opencode` still requires `-Model`. - -### Handing the package over - -Every package contains `RUN-THIS.prompt.md`, one instruction that drives the whole thing. It makes the user-selected external agent the Eval Orchestrator, Grader, and report producer. The orchestrator resolves the selected Eval Runner and reads its dispatch owner. For runner-owned dispatch it invokes `invoke-runner-owned-arms.ps1` exactly once as a foreground Phase 1 command and sets the caller shell/tool timeout to at least the package-computed allowance. That command preflights every blind `with_skill` and `without_skill` arm and starts zero executions if any preflight is incompatible. For orchestrator-owned dispatch it delegates each arm to a fresh native worker. It records each terminal envelope through the deterministic runner-owned recorder where applicable, grades only after collection, writes the grading fields, and generates the static report without executing an eval prompt in its own context. - -Hand the user that one file by its absolute path, and stop there. Do not reproduce its contents in the reply. The runner is built around absolute paths - the package directory, its own location, the path in the hand-back block - and a copy that has passed through a chat window arrives with them shortened to a bare directory name like `iteration-4`, pointing nowhere, with its internal links broken. The file on disk always says what the file on disk says; a paste of it is a lossy snapshot that also goes stale the moment the generator changes. Where the user's harness cannot read files at all, tell them to open that path and paste it themselves, so what travels is the real text rather than your recollection of it. - -Do not list the individual prompt files, do not describe the directory layout, and do not hand back a procedure for the user to carry out by hand. A reply that ends with 26 file paths and "run both versions" has moved the work onto the user instead of doing it. - -The normal path ends in the external evaluator: after all workers finish, it reads the grading key, grades each completed result using the packaged `skill-creator/agents/grader.md` guidance, writes `grading[].text`, `grading[].passed`, and `grading[].evidence`, records optional turns/token buckets/cost when the harness exposes them, runs the package adapter, and presents the first-party paired `report.html` plus Anthropic's exact `skill-creator-report.html`. If the selected external process cannot write valid runner-produced execution results back into the package, the evaluation is incomplete and must fail closed. Only persisted runner-produced evidence at the manifest-declared paths can proceed to grading and reporting. The user asked for eval results, not a second workflow decision. +Use `scripts/Get-HarnessModels.ps1 -Runner ` for manual model selection. -### Prepare, do not execute - -Generate the package with the repository script rather than by hand after resolving the Harness + Model choice: - -``` +```powershell pwsh -NoProfile -NonInteractive -File ./scripts/prepare-skill-evals.ps1 -Skill -Runner -Model ``` -It reads `skills//evals/evals.json` and writes one directory per eval into `.bot/-workspace/iteration-/`. The grading key and result stubs stay at the eval-case level, outside the two isolated run directories a worker actually sees: - -- `eval-metadata.json` — eval id and name, original prompt, expected output, assertions, required fixtures, fixture and skill hashes, and the assumptions needed to reproduce the run. This is the grading key and lives outside every run directory. -- `results/` — one prefilled result stub per configuration, also outside the run directories. -- `with_skill/` — an isolated run directory that is the worker's staged root. It holds `prompt.md` (the task with the effective skill instructions inlined, plus the same input context and response contract as the baseline), `run.json` (a harness-neutral contract naming only paths inside the run directory), `repo/` (the fixtures materialized as real files, which is the worker's working directory), an isolated empty `home/`, and `skill//` (the exact candidate skill revision, so nothing falls back to a globally installed copy). -- `without_skill/` — the same run directory without any `skill/` directory and with no skill instructions or mention of the skill under test. Its `repo/` is byte-identical to the with_skill one. - -At the iteration root it also writes `manifest.json` and `RUN-THIS.prompt.md`, the single prompt that hands the whole package to an agent of the user's choosing. The one-file path requires a harness that can create isolated workers or sessions, each launched from its run directory with `repo/` as the working directory and `home/` as an isolated profile. A plain single-context client runs one prompt file directly per fresh session instead. - -Useful switches: `-Eval ` to prepare a subset, `-Iteration ` plus `-Force` to replace an iteration, `-OutputRoot ` to relocate the workspace, and `-MaxInlineBytes ` to trim what gets inlined for a smaller context window. - -The expected output and the assertions are the grading key. They belong in `eval-metadata.json`, outside every run directory, and must never appear in either prompt — a baseline handed the answer key is not a baseline. - -### Optional eval preparation - -Eval package preparation is optional. A skill change does not require package preparation, and it does not require choosing a harness or model. Prepare a package only when the user explicitly asks for an evaluation, such as `eval `, `evaluate `, `please do an eval`, or a similar request. A request to create, modify, validate, or release a skill does not implicitly ask for eval preparation. - -When the user explicitly asks for an eval, follow [Asking for an eval](#asking-for-an-eval), resolve the Harness + Model choice, and run the preparation command described there. Preparation remains model-free and never executes the generated prompts. If a package is prepared, name its prompt path in the completion message and hand it over as described below. Do not ask for a harness, prepare a package, or report an eval handoff solely because a skill changed. - -`scripts/sync-skill-install.ps1` remains the last gate when a repo-managed skill was edited. An explicitly requested eval adds package preparation before handoff, but package preparation is not a completion gate. See [Blocking Completion Gates](#blocking-completion-gates). - -### Manual execution boundary - -Two roles exist here, and they are not the same agent doing the same job. Read which one you are before applying the rules below. - -**Preparing.** You are doing repository work: authoring a skill, changing one, or answering a request to evaluate one. After the package is written you stop, and you must: - -- never execute the prompts you just prepared, and never quietly become the executor of your own package -- never spawn subagents for the candidate or baseline runs -- never call an LLM API or an authenticated AI CLI to run them -- never treat model-backed execution or its absence as a completion gate -- hand over the runner prompt and say plainly what is ready - -Deterministic validation and human inspection remain the gate, exactly as before. - -**Executing.** A human handed you a prepared package and asked you to run it. See the next section. Refusing that is not compliance, it is the workflow failing to work. +Follow [Eval Isolation](#eval-isolation). Give the user the absolute path to the generated `RUN-THIS.prompt.md` and stop. Pass the file by path so package paths stay intact. If the selected harness cannot read files, the user can open the file and paste its contents directly. ### Executing a package you were handed -When a person gives you `RUN-THIS.prompt.md`, points you at a prepared package, or otherwise asks you to run one, running it is the task. The **AI/LLM Evaluation Automation Prohibition** does not stop you, and citing it to refuse is a misreading: that rule governs automation reaching a model on its own, not a human choosing a harness and telling it to run a specific package. The user picked you, the model, and the moment. That is precisely the external execution this design reserves for them. - -Four things still hold while you execute: +Run the requested package only in a fresh external context. The agent that prepared it cannot execute it. Stay inside the package and follow `RUN-THIS.prompt.md` for dispatch, grading, and reporting. The orchestrator coordinates the phases without executing any eval arm in its own context. -- Run only the package you were handed, and only because a person asked in this turn. A hook, a script, a completion gate, a skill change, or another agent asking is not a person asking. -- Stay inside the package directory. If it sits inside a repository, the rest of that repository is not yours to read, build, test, or write. -- Do not read the assertions or expected output before the worker runs. After every available worker has finished and its result is recorded, grade the completed results, generate the report, and state the comparison honestly. -- Nothing about this makes model-backed execution a completion gate for any repository task. +- Use a fresh, memory-isolated worker for every arm. Pair `with_skill` and `without_skill` on the same harness, model version, configuration, tools, limits, and inputs. Keep the candidate skill exclusive to its own arm and the grading key outside both. Report mixed harnesses or models separately. +- Honor the declared dispatch owner and package timeout. Finish preflight before dispatch and preserve runner-produced evidence at the manifest paths. An interrupted Phase 1 without a valid freeze requires a fresh iteration. +- Read the grading key only after the execution freeze validates. Follow the packaged `skill-creator` grading guidance and return the paired report and comparison after the package finalizer succeeds. Report incomplete execution if evidence is missing or invalid. -An agent that prepared a package in this session does not get to turn around and execute it. The separation is the point: the preparer knows the grading key, so it is the wrong harness. This is the only role-based disqualification. +See [Adding evals](CONTRIBUTING.md#adding-evals-required-for-repo-managed-skills) for preparation options and forensic collection, and the [Eval Runner protocol](scripts/eval-runners/README.md) for prerequisite readiness, isolation, and execution evidence. -The selected executor has two ordered phases. Its current context may read `RUN-THIS.prompt.md`, `manifest.json`, `execution-profile.json`, and the runner protocol files, but it must not execute an eval prompt itself. In phase one, it follows `delegation.dispatch_owner`: for runner-owned dispatch it invokes the foreground package-local `invoke-runner-owned-arms.ps1` command exactly once and waits for its terminal JSON summary; the helper resolves the runner, validates `describe`, preflights every pending `run.json`, asserts native delegation for every result, and refuses to start any execution until all preflights pass. A caller/tool timeout or interrupted conversation does not authorize rerunning Phase 1. If execution was interrupted and no valid `execution-freeze.json` exists, the package is incomplete and requires a fresh iteration. For orchestrator-owned dispatch it resolves the runner, validates `describe`, preflights each `run.json`, and uses the declared native subagent/task. A runner-owned process/thread is the single Eval Worker and model execution; no outer model worker may contain it. Orchestrator-owned workers must not invoke `runner.ps1 execute`; their transport envelope passes through `record-native-result.ps1`. Runner-owned execution results come directly from the runner and must never be synthesized, repaired, or reconstructed from assistant text. The runner launches each native session from its own run directory with `repo/` as the working directory, `home/` as the isolated profile, and the required isolation controls; hard filesystem confinement, when a runner proves it, raises the reported isolation from pragmatic to strict but is not itself a prerequisite. The runner receives only `run.json` and `execution-profile.json`; workers never see the runner, manifest, grading key, sibling results, or orchestration commentary, because all of those live outside the run directory. Never reuse a worker or session between runs. In phase two, only after Phase 1 returns a successful terminal JSON summary and the immutable freeze validates, the executor bridges results into `eval-result/2`, reads the grading key, follows the packaged `skill-creator` grader guidance, writes the grading evidence, invokes the package adapter so Anthropic's aggregator and eval viewer produce the report, and returns the report path and comparison. It does not ask the user whether to start either phase. - -The candidate instructions are already inlined in the with_skill run's `prompt.md` and staged under its `skill//` directory; the orchestrator does not load or summarize them for the worker. The baseline run has no `skill/` directory and no candidate instructions, and the orchestrator must not expose the candidate skill through another route, including a globally installed copy. The generated prompt files and the baseline `run.json` also omit the skill name, eval identifiers, and configuration labels so workers receive an ordinary task rather than an announcement that they are under evaluation. +## Per-Skill Evals -Use the same model, model version, configuration, tools, and limits for every worker. Disable persistent memory and cross-session recall. Independent runs must execute concurrently up to `min(execution-profile.json.concurrency, remaining arms)` when harness capacity permits, but every run still gets a distinct context and no shared mutable workspace. For any selected runner whose descriptor says `delegation.dispatch_owner=runner`, the external orchestrator invokes `invoke-runner-owned-arms.ps1` exactly once as the foreground Phase 1 command, with the caller shell/tool timeout set to at least the package-computed allowance. The external orchestrator must not hand-author preflight, fan-out, state, or result bookkeeping. If the foreground command is terminated before a valid final result and freeze exist, Phase 1 fails closed and requires a fresh package; no arm is restarted. Claude Code subagents, OpenCode Task/General workers, and Codex native mechanisms remain harness capabilities only; they are not the behavioral transport for runner-owned evaluation. Claude Code's runner-owned transport is one fresh headless `claude -p --output-format stream-json` session per arm, the same native non-interactive surface `skill-creator` itself uses for `claude -p` runs. +Every repo-managed skill must include its own `evals/evals.json` file at `skills//evals/evals.json`. -`RUN-THIS.prompt.md` requires a selected Eval Runner that can create isolated workers or sessions. A plain single-context client can still execute an individual self-contained prompt when the user opens it directly as the first message of a fresh session, but it cannot provide the paired comparison and report contract in that same context. A selected runner that cannot satisfy a required guarantee is `incompatible`; there is no generic fallback or runner substitution. Partial package state may be inspected and reported, but the completion gate must pass before it can be presented as a completed evaluation; missing or unrun arms remain visibly incomplete. +- Treat this as a required artifact for every first-party skill in this repo +- Eval entries may include an optional `files` array of skill-relative fixture paths such as `evals/files/example.md` +- When `files` is present, keep the paths relative to `skills//` and under `evals/files/`, and validate that every fixture exists; eval preparation rejects any other location, and a fixture that deterministic test drivers also use is still owned by `evals/files/` +- Treat eval prompts, expected outcomes, and assertions as versioned review specifications; their presence never authorizes automated model execution +- Start with `pwsh -NoProfile -File ./scripts/validate-skill-templates.ps1 -MetadataOnly` for a sub-second repository-wide metadata and fixture check +- Run only the changed skill's deterministic validator and focused regression scripts during iteration; run independent checks concurrently with bounded local parallelism, while shared-file mutations stay sequential. +- Full local validation requires explicit human approval for that specific run. A request to create, fix, test, validate, finalize, or release a skill, including `auto` or `yolo`, does not authorize the full matrix. Default to focused deterministic checks for the changed skill or component. Complete that work before proposing a full run, explain its scope and cost, and wait for approval. Without approval, focused checks satisfy the local completion gate; state that the full matrix was not run. After approval, run the complete CI matrix locally with the permanent parallel scheduler: `pwsh -NoProfile -File ./scripts/validate-local.ps1`. It derives every suite from `.github/workflows/validate-skill-templates.yml`, so local and CI coverage stay aligned, and that matrix remains the source of truth for script paths and `-Suite` values, including the transport-specific conformance suites and phase-specific integrity suites. The scheduler (implemented in .NET as `agentic-tooling validate-local`; the script forwards to it) runs each suite in a separate PowerShell 7 process with bounded concurrency, streams a log per suite, kills timed-out process trees, isolates temporary fixtures, and exits non-zero unless every suite passed and printed its terminal success marker. It reports progress and heartbeats on stderr and in `progress.json` under the output root, and writes `summary.json` beside the logs with per-suite status, exit codes, timings, and coverage counts. The DocFX suite always receives `-Full`. A timeout or a skipped check is a failure, never a pass. +- `scripts/validate-local.ps1` is the only sanctioned local full-run entry point. Do not hand-roll process fan-out, and do not rely on ad hoc, under-parallelized dispatch. For focused iteration, run a single suite or group directly (`-Suite Templates`, `-Suite Preparation`, `-Suite Runners`, `-Full -Suite Docfx`, plus the conformance and integrity `-Suite` values), and use `-MetadataOnly` for the sub-second metadata and fixture check. Do not invoke the sequential aggregate `scripts/validate-skill-templates.ps1` with no `-Suite` or with `-Suite All` for agent-driven validation, and do not run the CI suite matrix in a sequential loop. If concurrent execution is unavailable, report the limitation instead of silently falling back to sequential execution. +- `scripts/validate-local.ps1` is covered by `scripts/tests/test-validate-local.ps1` (black-box) and `tooling/test/Agentic.Tooling.Tests`, which assert scheduling, concurrency bounding, failure propagation, silent-skip detection, timeout and process-tree teardown, deadline cancellation, coverage parity, and output-root safety against fixture workflows. Update those tests when the scheduler's contract changes. +- An explicit user instruction to skip or stop testing overrides these validation gates for that session. Stop any tests you started, run no further validation, and report the unvalidated work. +- Follow the top-level **AI/LLM Evaluation Automation Prohibition** for every eval. No per-skill or third-party requirement overrides it. +- Deterministic scaffold/template skills must keep local deterministic validators as well; evals supplement validators, they do not replace them -An `output` is the model's own message in full, including questions, caveats, explanations, or a refusal. Where a run invoked a tool, that tool's stdout is evidence rather than a replacement for the response. Record the full worker transcript, duration, token usage, and tool-call count when the harness exposes them; omit unavailable metrics rather than estimating them. +Update `evals/evals.json` when its definitions or fixtures change. Follow [Portable Eval Handoff](#portable-eval-handoff) for explicit eval requests. -### Same model on both sides +## Git Identity -A fresh context is fresh of memory as well as of transcript. A harness with persistent memory, saved project instructions, or cross-session recall can carry into a nominally new session what it learned while running the previous one, which makes that session a continuation wearing a new name. Runs made under such a harness need that memory disabled, or a profile without it. +Never set or override `git user.name`, `git user.email`, or `alias.bot` in the **local** git config of this repository. Always use the global config. Local overrides silently shadow global settings and produce commits with the wrong author. -An evaluated context sees its `prompt.md` and the files staged in its run directory, and nothing else - not `RUN-THIS.prompt.md`, not `run.json` from the paired run, not the assertions, not another case's output, not a note that an experiment is underway. Anything added on top is a second variable in a comparison meant to differ in exactly one. +## Git Operations Safeguards -A meaningful A/B result requires both configurations to run on the same model, the same version, and the same configuration, varying only whether the skill is present. Running the with-skill case on one model and the baseline on another measures the model and the skill together; that is not a skill-effectiveness benchmark and must not be reported as one. When models are deliberately mixed, say so and treat the comparison as directional only. +Agents must never commit code changes or push to remote repositories without explicit authorization: either approval for the current request, a task-scoped grant under [Local Commit Authorization](#local-commit-authorization), `yolo` or `auto` attached to an explicit lifecycle request under [Lifecycle Authorization](#lifecycle-authorization), or `yolo` or `auto` attached to an explicit PR request under [PR Skill Routing](#pr-skill-routing). A direct commit request that includes `yolo` or `auto` is explicit approval for the current commit request; it authorizes the agent to complete that commit workflow in the same turn after the required checks pass. -### Result handoff +- **Commits**: Request confirmation from the user before staging and committing code unless the same explicit commit request includes `yolo` or `auto`, or an applicable task-scoped grant or lifecycle authorization covers the commit. In an auto-approved case, present the plan as status information and continue directly to staging and committing; do not ask a second confirmation question or end with a pending plan. Required review, scope, identity, message-validation, and post-commit checks still apply. +- **Remote Operations**: Do not push, pull, fetch, or interact with `origin` or any remote repository without explicit user instruction. Local authorization never reaches remote operations; see [Remote Governance](#remote-governance). An explicit PR request authorizes read-only remote preparation; PR writes follow [PR Skill Routing](#pr-skill-routing), including its own `yolo` or `auto` behavior for that explicit request. -An externally produced result is valid only when the selected runner's native transport persists it at the exact manifest-declared execution-result path, identified by eval id, configuration (`with_skill` or `without_skill`), runner-native model, harness, and produced output. It may also carry the transcript, duration, total tokens, tool-call count, output files, and notes. The external evaluator may add grading fields after the bridge; it must not author or repair raw execution evidence. +**Why:** Automatic commits can pollute history with incomplete work, debugging code, or unintended changes. Unexpected remote operations can overwrite or lose commits on shared branches. Never treat silence, urgency, or momentum as approval; `yolo` or `auto` counts as approval only when attached to the explicit request it modifies, whether a commit, lifecycle, or PR request, and only within that request's authorization boundary. A grant applies only to the delivery scope it names and is never extended by inference. -Which artifact transfer happens depends on where the harness ran, and `RUN-THIS.prompt.md` tells it to close either way. A harness sharing a disk with the package writes the runner-produced result files, grading, `benchmark.json`, `benchmark.md`, the first-party `report.html`, and the exact upstream `skill-creator-report.html` itself and reports the first-party report path. If the selected external process cannot write valid runner-produced execution results back into the package, the evaluation is incomplete and must fail closed; a response-only or reconstructed result cannot substitute for persisted transport evidence. +### Local Commit Authorization -An explicitly authorized forensic recovery of an old or broken package may validate an existing iteration with: +An explicit grant to execute a delegated implementation, orchestration, or worktree merge lifecycle may include the local commits that lifecycle needs. A request only to implement, review, or investigate does not authorize commits by itself. -``` -pwsh -NoProfile -NonInteractive -File ./scripts/prepare-skill-evals.ps1 -CollectResults -``` +A grant names its **delivery scope** by a task, feature, delivery, workspace, delegated contribution, or clearly defined set of child worktrees. It never needs to enumerate worktree identifiers, branch names, or changed paths. Within that scope, worktrees, branches, and changed paths may be discovered or created dynamically. The orchestrator ensures that every discovered resource and change belongs to the authorized delivery; unrelated changes remain outside the grant. Where a grant covers commits: -It checks that each result matches its eval and configuration, may inspect and write `comparison.md`, the paired `report.html`, the exact upstream `skill-creator-report.html`, and the upstream `benchmark.json`/`benchmark.md` while warning when an arm is missing, unrun, or ran on a different model. It exits non-zero when the required completion gate is not satisfied, so an incomplete or unrun package is not a completed evaluation. The external evaluator may grade in its user-directed phase-two context; repository automation remains deterministic and never invokes a model. Use deterministic checks for mechanical assertions and evidence-backed human or evaluator judgement only where the assertion is genuinely qualitative. +- An implementation agent may commit its assigned and validated changes on its own task branch, within the granted scope. +- An orchestrator may relay the grant to implementation agents. A relayed grant never exceeds the scope the orchestrator received. +- An orchestrator may create merge and conflict-resolution commits within the integration scope. +- No per-commit approval is needed while the grant applies. +- Commit only changes that belong to the delivery. Unrelated changes, including another agent's uncommitted files, stay uncommitted and untouched unless separately authorized. +- Commit workflows still route through `git-visual-commits`. Under a grant or lifecycle authorization, that skill runs in auto-approval mode: the authorization supplies the approval, while its classification, validation, identity, and post-commit checks still apply. +- Merge and conflict-resolution commits are commits. They follow the same message, identity, and post-commit checks and need no separate plan approval once the authorization covers them. -### Workspace isolation +Without an applicable grant, the explicit approval requirement above applies unchanged. -Eval packages obey **Eval Isolation**: they default to `.bot/-workspace/`, which git ignores, and `-OutputRoot` may only point there or outside the repository. Do not commit a package, its prompts, or its results unless the user explicitly asks for checked-in artifacts. +### Worktree Ownership and Coordination -## Per-Skill Evals +Concurrent agentic development follows a single-writer principle: -Every repo-managed skill must include its own `evals/evals.json` file at `skills//evals/evals.json`. +- Give each concurrent implementation agent its own Git worktree and task branch, created within the delivery scope when needed. Multiple agent sessions sharing one worktree are not implementation isolation. +- The designated orchestrator owns the integration worktree during integration. Before any merge or other mutating integration operation, coordinate exclusive write ownership of that worktree, then revalidate its state immediately before mutating it. +- Never silently stash, commit, discard, or overwrite another agent's outstanding changes. Report a conflicting change to its owner and coordinate. +- Coordinate directly with other agents through available native capabilities. Route routine coordination through agents rather than back to the user; involve the user only for decisions outside the grant or for remote or destructive actions. +- Coordination ledgers, ownership records, and handover notes are working files under [Scratch File Isolation](#scratch-file-isolation). -- Treat this as a required artifact for every first-party skill in this repo -- Eval entries may include an optional `files` array of skill-relative fixture paths such as `evals/files/example.md` -- When `files` is present, keep the paths relative to `skills//` and validate that every fixture exists -- Treat eval prompts, expected outcomes, and assertions as versioned review specifications; their presence never authorizes automated model execution -- Start with `pwsh -NoProfile -File ./scripts/validate-skill-templates.ps1 -MetadataOnly` for a sub-second repository-wide metadata and fixture check -- Run only the changed skill's deterministic validator and focused regression scripts during iteration; run independent checks concurrently with bounded local parallelism, while shared-file mutations stay sequential. -- Full local validation requires explicit human approval for that specific run. A request to create, fix, test, validate, finalize, or release a skill, including `auto` or `yolo`, does not authorize the full matrix. Default to focused deterministic checks for the changed skill or component. Complete that work before proposing a full run, explain its scope and cost, and wait for approval. Without approval, focused checks satisfy the local completion gate; state that the full matrix was not run. After approval, run the complete CI matrix locally with the permanent parallel scheduler: `pwsh -NoProfile -File ./scripts/validate-local.ps1`. It derives every suite from `.github/workflows/validate-skill-templates.yml`, so local and CI coverage stay aligned, and that matrix remains the source of truth for script paths and `-Suite` values, including the transport-specific conformance suites and phase-specific integrity suites. The scheduler runs each suite in a separate PowerShell 7 process with bounded concurrency, streams a log per suite, kills timed-out process trees, isolates temporary fixtures, and exits non-zero unless every suite passed and printed its terminal success marker. It writes `summary.json` beside the logs with per-suite status, exit codes, timings, and coverage counts. The DocFX suite always receives `-Full`. A timeout or a skipped check is a failure, never a pass. -- `scripts/validate-local.ps1` is the only sanctioned local full-run entry point. Do not hand-roll process fan-out, and do not rely on ad hoc, under-parallelized dispatch. For focused iteration, run a single suite or group directly (`-Suite Templates`, `-Suite Preparation`, `-Suite Runners`, `-Full -Suite Docfx`, plus the conformance and integrity `-Suite` values), and use `-MetadataOnly` for the sub-second metadata and fixture check. Do not invoke the sequential aggregate `scripts/validate-skill-templates.ps1` with no `-Suite` or with `-Suite All` for agent-driven validation, and do not run the CI suite matrix in a sequential loop. If concurrent execution is unavailable, report the limitation instead of silently falling back to sequential execution. -- `scripts/validate-local.ps1` is covered by `scripts/tests/test-validate-local.ps1`, which asserts scheduling, concurrency bounding, failure propagation, silent-skip detection, timeout and process-tree teardown, deadline cancellation, coverage parity, and output-root safety against fixture workflows. Update those tests when the scheduler's contract changes. -- An explicit user instruction to skip or stop testing overrides these validation gates for that session. Stop any tests you started, run no further validation, and report the unvalidated work. -- Follow the top-level **AI/LLM Evaluation Automation Prohibition** for every eval. No per-skill or third-party requirement overrides it. -- To compare a skill against a baseline, prepare a package with **Portable Eval Handoff** and hand `RUN-THIS.prompt.md` to the user; the repository agent never runs the prompts, while the user-directed external executor runs, grades, and reports the paired comparison -- Deterministic scaffold/template skills must keep local deterministic validators as well; evals supplement validators, they do not replace them +`git-worktree-merge` owns the operational procedure for discovery, readiness, dependency ordering, and conflict resolution. This section sets the ownership rules that procedure must respect. -If you add a new skill or modify an existing repo-managed skill, keep that skill's `evals/evals.json` present and update it when the eval definitions or fixtures change. Package preparation is optional and is triggered only by an explicit eval request; when requested, use `pwsh -NoProfile -NonInteractive -File ./scripts/prepare-skill-evals.ps1 -Changed -Runner -Model `. Use `-CodebeltReference` instead to select the Claude Code reference configuration. Do not commit temp workspaces, benchmark outputs, or generated review files into this repository unless the user explicitly asks for checked-in artifacts. +### Lifecycle Authorization -## Git Identity +A complete worktree merge or orchestration lifecycle may be authorized in either of two ways: by a grant that names its delivery scope, or by `yolo` or `auto` attached to an explicit lifecycle request, such as `/git-worktree-merge Fix docfx progress ledger yolo` or `/git-worktree-merge all children auto`. Bare `yolo` or `auto` does not start a lifecycle. Either way, the authorization covers the scoped local operations the lifecycle needs: agent coordination, implementation finalization, local commits, merges, conflict resolution, validation, and safe cleanup. Covered operations proceed without redundant approval. The orchestrator may relay the authorization to participating implementation agents within the same delivery scope. -Never set or override `git user.name`, `git user.email`, or `alias.bot` in the **local** git config of this repository. Always use the global config. Local overrides silently shadow global settings and produce commits with the wrong author. +Lifecycle authorization never bypasses review, validation, ownership, integration, or cleanup safety gates. An unresolved gate is reported as a blocker, not passed over. Cleanup proceeds only after verifying ownership, that the worktree is inactive, that its working directory is clean, that integration succeeded, and that functional validation passed. Never force-delete worktrees or branches, discard outstanding work, or remove unrelated resources. Lifecycle authorization, including `yolo` and `auto`, never implicitly authorizes force deletion, other destructive operations, remote interaction, protected-branch modification, PR publication, releases, or deployment; those need their own explicit authorization under [Remote Governance](#remote-governance). Commits made in any worktree use the global Git identity; never set local identity config there either (see [Git Identity](#git-identity)). -## Git Operations Safeguards +### Remote Governance -Agents must never commit code changes or push to remote repositories without explicit user approval. A direct commit request that includes `yolo` or `auto` is explicit approval for the current commit request; it authorizes the agent to complete that commit workflow in the same turn after the required checks pass. +Local development authorization never implicitly authorizes: -- **Commits**: Request confirmation from the user before staging and committing code unless the same explicit commit request includes `yolo` or `auto`. In that auto-approved case, present the plan as status information and continue directly to staging and committing; do not ask a second confirmation question or end with a pending plan. Required review, scope, identity, message-validation, and post-commit checks still apply. -- **Remote Operations**: Do not push, pull, fetch, or interact with `origin` or any remote repository without explicit user instruction. An explicit PR request authorizes read-only remote preparation; PR writes follow the PR Skill Routing approval boundary below. +- Pushing to a remote, including task branches. +- Creating, updating, or merging pull requests. The PR Skill Routing applies. +- Modifying the protected default branch, including merging into it. +- Publishing releases. +- Deploying software. -**Why:** Automatic commits can pollute history with incomplete work, debugging code, or unintended changes. Unexpected remote operations can overwrite or lose commits on shared branches. Never treat silence, urgency, or momentum as approval; `yolo` or `auto` counts as approval only when attached to the same explicit commit request. +Our PR-based Scaled Trunk-Based Development practice and its remote publication approvals stay in force. Integration into shared or protected branches follows the PR route. Task-scoped grants and lifecycle `yolo` or `auto` never change this list. ### Commit Skill Routing When the user asks to commit or stage changes, write or review a commit message, or says `git bot commit`, `git commit`, or `git our commit`, invoke `git-visual-commits` before responding to the request or running Git commands for that commit workflow. Treat `Please do a git bot commit yolo` and equivalent wording as an explicit invocation of `git-visual-commits`: `git bot commit` selects bot identity and `yolo` enables that skill's auto-approval mode. Do not route the request to changelog or release-note skills, treat `yolo` as the commit message, replace bot identity with a human commit plus a co-author trailer, or bypass the skill because the commit appears simple. -Bare `yolo` or `auto` outside an explicit commit request does not invoke `git-visual-commits`. Likewise, those modifiers do not invoke `git-keep-a-changelog` unless the user explicitly requests a changelog or release-note output. Users can force deterministic CLI selection with `/git-visual-commits` when they do not want to rely on automatic skill selection. +Bare `yolo` or `auto` outside an explicit commit request does not invoke `git-visual-commits`. Commits made under a lifecycle or grant route here as described under [Local Commit Authorization](#local-commit-authorization). Likewise, those modifiers do not invoke `git-keep-a-changelog` unless the user explicitly requests a changelog or release-note output. Users can force deterministic CLI selection with `/git-visual-commits` when they do not want to rely on automatic skill selection. ### PR Skill Routing When the user asks to create, open, make, or refresh a GitHub pull request, invoke `git-remote-pr` before remote PR operations. Normal requests inspect the complete committed `base...head` changeset, prepare a title/body and exact mutation preview, then require explicit approval before `git push` or PR writes. `yolo`/`auto` attached to that same explicit PR request still shows the preview but skips the approval wait: do not ask for or wait on `approve APR-...`; continue only with the just-presented plan and APR ID. Bare `yolo`/`auto` does not invoke the skill. Existing PR descriptions are regenerated from the complete current changeset. Dirty worktrees are not auto-committed, and approval never authorizes force pushes or history rewriting. Commit requests remain with `git-visual-commits`; release-note requests remain with `git-remote-release`. `/git-remote-pr` can force deterministic selection where supported. -## Skill Creation +### Worktree Merge Skill Routing -Always use the `skill-creator` skill (by Anthropic) when creating new skills, modifying existing skills, or running evals. It enforces best practices for structure, description quality, testing, and progressive disclosure. Do not create or edit skills manually without invoking it first. +When the user asks to merge contributions from Git worktrees or agent sessions into a feature branch, invoke `git-worktree-merge`. The workflow covers discovery, coordination, readiness, dependency ordering, conflict resolution, integrated validation, scoped cleanup, and reporting. Apply the commit, lifecycle, and PR safeguards above. A grant naming a delivery scope, or `yolo` or `auto` attached to the explicit lifecycle request, is the authorization described under [Lifecycle Authorization](#lifecycle-authorization). `/git-worktree-merge` can force selection where supported. -Follow it as written except at the execution boundary. Anthropic's `skill-creator` requires paired with-skill and baseline runs in fresh subagents. This repository prepares the same paired inputs as a portable package and stops. When the user hands that package to a harness, `RUN-THIS.prompt.md` makes the selected harness create those isolated paired workers without exposing the grading key, then use the packaged `skill-creator` grader guidance, aggregator, and eval viewer in the same handoff. The authoring guidance, eval definitions, assertion drafting, and iteration loop still apply; only the execution transport changes. Repository-side validation remains deterministic, while the explicitly user-directed external executor performs the post-run evaluator judgement and invokes the upstream viewer/report generation that the skill-creator experience expects. +## Skill Creation + +Use Anthropic's `skill-creator` when creating or modifying skills or designing eval cases. Its paired methodology and packaged grading guidance apply to existing eval cases. Follow [Portable Eval Handoff](#portable-eval-handoff) to prepare or run them. `skill-creator-agnostic` is deprecated, no longer maintained, and retained only for backward compatibility until 1.0.0. Agents must not use it for new skill creation, skill modification, or benchmarking; use Anthropic's `skill-creator` directly and apply the repository-specific requirements from this `AGENTS.md`. @@ -300,23 +229,88 @@ When a skill needs time-sensitive or environment-sensitive values, prefer comput - When a dynamic default exists, describe both the source and the fallback behavior in `FORMS.md` / `SKILL.md` - If a value changes over time (supported frameworks, current versions, generated paths, repo-derived names), assume hardcoding will drift and design for refreshable computation -## File-Based App Invocation +## Executable Tooling Standards + +These standards apply to every first-party executable in this repository and in its distributed skills: validators, generators, verifiers, audit and update runners, test drivers, CI logic and other bundled tools. They are permanent requirements. + +### .NET first + +- First-party executable automation is implemented in C# on .NET. Do not add new PowerShell or Python implementations; the existing ones are being migrated. +- Distributed skill tools are single file-based apps inside the skill (`dotnet run --file`), so every skill stays self-contained. Repository infrastructure lives in the `tooling/` solution, with central package management and the Codebelt test conventions. Its `Directory.Build.props`, `Directory.Packages.props` and `global.json` stay inside `tooling/`, because root-level MSBuild files would become ambient configuration for every skill app and eval fixture. +- Agentic's own tools target .NET 10 (LTS) and roll forward to newer major runtimes, so that a machine with only .NET 11 (STS) can run them: file-based apps declare `#:property TargetFramework=net10.0` together with `#:property RollForward=Major`, and `tooling/Directory.Build.props` sets `RollForward`. This governs Agentic's tooling only; it never narrows the target frameworks of projects that skills create or modify. +- Code that several skills need is vendored into each of them from one canonical source and checked for drift deterministically. Reuse the established process and ownership code, and consolidate only responsibilities that more than one tool demonstrably needs; do not build a generic framework ahead of its consumers. +- Exceptions are explicit and recorded: unmodified third-party code such as Anthropic's `skill-creator` and its runtime dependencies, browser-native JavaScript, minimal platform-required command sequences and declarative configuration, and historical evaluation packages, which keep the toolchain they were prepared with. + +### Local Shell Execution + +Agents may use any appropriate local shell. When using PowerShell syntax or executing a `.ps1` script locally, use PowerShell 7+ through `pwsh`; never invoke `powershell` or `powershell.exe`. This does not prescribe GitHub Actions shell choices. + +### Process lifecycle + +- Own the whole process tree. On Windows, create the child suspended and assign it to a Job Object before it runs (`scripts/eval-runners/windows-owned-process.cs`); elsewhere, kill it as a tree. Timeouts and cancellation terminate the whole tree, and a timeout is a failure, never a pass. +- Drain stdout and stderr concurrently, bound the wait for the pipes after the process exits, and report descendants that outlive it. +- Give each run its own temporary directory, keep diagnostics when an operation fails, and report a deterministic terminal state. + +### Observability + +Every potentially long-running operation reports what it is doing, truthfully, while it runs. + +- **Streams.** stdout carries only the established machine-readable result (`--json`, `--summary-json`, a result path). Progress, heartbeats and diagnostics go to stderr as append-only plain text, flushed promptly, without cursor movement, colour or other ANSI sequences. +- **Shape.** A `[START]` line as soon as the tool's own code runs, naming the operation and its scope; `[PROGRESS]` lines with known totals and completed, failed and active counts; a terminal `[COMPLETE]` or `[FAILED]` line with duration and the relevant diagnostics. Every line carries the elapsed time. +- **Heartbeats.** When no substantive event has occurred, a `[HEARTBEAT]` line about every 10 seconds (configurable) names the active work and its elapsed time. Heartbeats run on a timer, not on work-item completion, so a long silent build still produces them. A heartbeat states liveness, not progress, and never implies that work advanced. +- **Honesty.** Never fabricate percentages or completion estimates, and never print credentials or secrets. +- **Hosts that buffer output.** A long-running tool also writes a small JSON progress file, atomically: correlated to the operation (operation id and process id), with the time after which a `running` snapshot counts as stale, and a truthful terminal state once the outcome is known. +- **Options.** `--quiet` reduces stderr to warnings and the terminal line; `--no-heartbeat` turns heartbeats off. Neither changes stdout. +- Observability works out of the box: no daemon, server, database, collector or subscription. + +### Performance and concurrency -A .NET file-based app (`dotnet run --file .cs`) re-runs SDK, restore, and MSBuild evaluation on every call. On current hardware that fixed cost is several seconds even when the built output is already up to date, and the deterministic suites invoke the same app dozens of times per run. +- Remove unnecessary work before parallelizing what remains. +- Run independent work items with bounded concurrency: CPU-aware defaults with a hard upper bound, configurable (for example `--max-parallel`), and conservative, separate limits for heavy shared resources such as Docker or external APIs. Choose defaults from measurements; more parallelism is not automatically faster. +- Isolate per-worker temporary files and logs, aggregate results deterministically, and write shared outputs atomically (temporary file and rename), preserving the last good state on failure. -- Test code that invokes a file-based app must resolve the built assembly once with `scripts/file-based-app.ps1` (`Get-FileBasedAppCommand`) and execute that assembly, instead of calling `dotnet run --file` per invocation. -- The helper caches a build artifact keyed by source hash and SDK version under the user temp directory and outside the repository. It never caches a validation result: every assertion still runs on every execution. -- When the helper cannot prepare or locate a cached build it falls back to `dotnet run --file`, so behavior is never worse than the unoptimized path, only slower. -- Do not reintroduce per-call `dotnet run --file` in a deterministic suite. Measure the suite before and after any change to how it invokes a file-based app. +### File-based apps -## Complementary Tool Observability and Concurrency +A file-based app (`dotnet run --file .cs`) evaluates the SDK, restore and MSBuild on every call. When the app is already built that costs a fraction of a second; the first build of a path costs seconds. -Repository and skill complementary tools (validators, generators, verifiers, audit/update runners, and other bundled scripts) must be observable during long runs and optimized for bounded concurrency wherever independent work would otherwise run slowly in sequence. +- Test code that invokes the same file-based app repeatedly builds it once and executes the built assembly. Until those drivers move to .NET, that is `scripts/file-based-app.ps1` (`Get-FileBasedAppCommand`): it caches the build artifact by source hash and SDK version under the user temp directory, never caches a validation result, and falls back to `dotnet run --file` when it cannot prepare a build, so behavior is never worse than the direct path, only slower. .NET code, including the xUnit tests, uses `FileBasedAppBuild` in `tooling/src/Agentic.Tooling`, which applies the same input rule and otherwise defers to MSBuild's incremental build. +- Independent work items inside a validation suite run through `agentic-tooling run-parallel` (bounded concurrency, process-tree ownership, per-item timeouts, logs and progress), not through PowerShell jobs or `ForEach-Object -Parallel`. A caller keeps only a minimal adapter that describes the items and reads `results.json`; `scripts/agentic-tooling.ps1` builds the tool when its inputs changed. +- Do not reintroduce per-call `dotnet run --file` in a deterministic suite. Measure the suite end to end before and after any change to how it invokes a file-based app. -- **Append-only `stderr` progress and heartbeats:** Emit append-only, plain-text progress lines (such as `[12/425] ... -> Verified (1.8s)`) and/or periodic heartbeats (for example every 10 seconds when an item or phase is still running) to `stderr` without cursor rewriting or ANSI-dependent formatting. Keep `stdout` strictly reserved for clean, parseable structured output (`--json`, `--summary-json`) so pipelines never break. Support `--quiet` and/or `--no-heartbeat` when callers need reduced `stderr` output. -- **Bounded concurrency by default:** Where work items are independent (multi-example verification, package/feed lookups, isolated builds, or multi-target audits), execute them concurrently with bounded parallelism rather than slow sequential loops. Derive sensible CPU-aware defaults with a hard upper bound (configurable via flags such as `--max-parallel`), and keep heavier shared resources such as Docker containers or external APIs conservatively capped (or separately configurable). -- **Thread-safe aggregation and atomic writes:** Isolate per-worker temp files and logs, collect results deterministically, and write shared outputs or manifests atomically (temp file + rename) once workers finish, preserving the last good state on failure. -- **Deterministic test coverage:** Cover bounded parallel execution, cache reuse where applicable, and clean `stdout` vs append-only `stderr` progress output in the tool's deterministic test suite. +### Measurement + +Measure a change to how a tool executes with the repository harness (`agentic-tooling measure` in `tooling/src/Agentic.Tooling`) before and after, on identical workloads, and report the median, the range and the sample count. Investigate every material regression; a regression that cannot be explained needs explicit maintainer acceptance. Report maintainer-facing (test and CI) and consumer-facing results separately. For test suites, record cold and warm durations, test execution time apart from compilation and restore, process counts, the slowest tests or scenarios, total suite duration, and CI duration with its remaining timeout headroom. Workload files and results of one investigation are working files (see [Scratch File Isolation](#scratch-file-isolation)). + +### Tests + +Cover each tool's bounded parallel execution, cache reuse where it applies, clean stdout and append-only stderr progress, heartbeats, cancellation and timeout in its deterministic tests. Preserve the contracts being verified, not the mechanism an earlier test used to verify them. + +### Fast tests by design + +Test execution performance is a permanent engineering requirement, not an optional optimization. Migrating a test suite to another language never means reproducing its inefficient patterns there. + +- Ordinary unit tests execute in milliseconds and normally complete within one second. Lightweight integration tests normally complete within a few seconds. A focused deterministic regression suite targets a few seconds of execution after compilation. +- A test that runs longer than 30 seconds needs a concrete justification based on the integration or end-to-end boundary it actually exercises. A slow test is engineering debt unless its cost is intrinsic to the behavior it verifies. +- These are engineering targets, not per-test stopwatch assertions. Measure test execution separately from compilation, restore, environment preparation and orchestration, and also measure the complete developer feedback loop (see [Measurement](#measurement)). +- A material test-performance regression is a blocking regression: correct it or obtain explicit maintainer acceptance. Never increase timeouts, delete meaningful coverage, weaken assertions, hide slow tests or move required tests out of mandatory CI to get a green result. A genuine exception needs measured evidence and maintainer acceptance. + +**Architecture.** Repository-maintained tests are conventional xUnit v3 projects on Microsoft.Testing.Platform that follow the Codebelt testing conventions, inside the `tooling/` solution. Add another project only where isolation or a compilation boundary warrants it, and never build a custom test framework or runner where the .NET ecosystem already provides the capability. + +- Exercise deterministic business logic directly in-process, with parameterized tests, isolated fixtures, appropriate shared setup and bounded parallel execution. +- Reserve out-of-process tests for behavior that genuinely needs a process boundary: command-line argument handling and exit codes, the stdout and stderr contracts, process ownership, cancellation and timeout, runtime compatibility, actual external-tool integration, and representative end-to-end consumer workflows. Keep meaningful black-box command-line coverage of every distributed tool, but do not launch an executable for every behavioral permutation. +- Classify a test by the boundary it actually verifies, not by the skill it belongs to; a skill's regression suite is not black-box integration testing as a whole. +- Distributed tools stay self-contained file-based apps; their repository tests need not be file-based apps. Where needed, separate command-line composition from testable C# with the existing source-inclusion mechanisms (`#:include` in the app, `` in the test project) or an appropriately scoped project. Never maintain a second production implementation for tests. + +**Eliminate unnecessary work.** + +- Do not launch an external process to test logic that can be invoked directly. +- Do not restore or build an application repeatedly within a test suite: build once and reuse the exact compiled artifact. Avoid repeated file-based app evaluation, SDK discovery, script compilation, temporary project creation and serialization round-trips. +- Avoid real network services when deterministic local fixtures are sufficient. +- Avoid arbitrary sleeps. Use synchronization primitives, controllable clocks, readiness signals and bounded waits; use real time only to test an actual timing or process-lifecycle boundary. +- Run independent tests and validation workloads concurrently with resource-aware bounds; never parallelize unsafe shared mutations merely to improve timing. +- Cache build artifacts and immutable setup where appropriate, never test outcomes. + +These standards change nothing in the [AI/LLM Evaluation Automation Prohibition](#aillm-evaluation-automation-prohibition): no tool, test or CI step invokes a model. ## Scaffold Invariants @@ -345,7 +339,9 @@ Do not hard-wrap prose to a fixed column width. Keep paragraphs and Markdown lis After modifying any skill (`SKILL.md`, `FORMS.md`) or repo-level config (`AGENTS.md`), **always update `README.md` before considering the task done**. This is a mandatory gate — not a nice-to-have. The README's "Available Skills" table, install examples, and "Why" sections must reflect the current state of all skills. A new skill without a README entry is incomplete work. -## Blocking Completion Gates +## Completion and Progress Reporting + +### Blocking Completion Gates When repository guidance, an active skill, or a conversation summary identifies required follow-up work as pending, critical, blocking, or equivalent, treat those items as the active completion checklist for the current task rather than as background context. Do not call `task_complete`, describe the task as complete, or claim verification succeeded until every blocking item has either run successfully or been reported with the exact command, exit code, and remaining blocker. @@ -353,7 +349,21 @@ Before any completion message, reread the skill instructions and the current con For script-backed workflows, creating or editing files is not enough on its own. If a skill requires deterministic maintenance or verification commands, run them before completion and report their concrete outcome. For `dotnet-docfx-digest`, `scripts/agents.cs` and `scripts/docfx.cs --build-api-model --validate-samples --verify-docfx-build` are blocking completion gates whenever the skill or task summary says they are required. -When a repo-managed skill was edited, `scripts/sync-skill-install.ps1` runs last, because every other step can still change a file. Report its actual output; an earlier run in the same session satisfies neither. If the user explicitly requested an eval, prepare the package before handing it over as described in [Optional eval preparation](#optional-eval-preparation), but do not treat that preparation as a completion gate. See [Local Install Sync](#local-install-sync). +When a repo-managed skill was edited, `scripts/sync-skill-install.ps1` runs last, because every other step can still change a file. Report its actual output; an earlier run in the same session satisfies neither. If the user explicitly requested an eval, prepare the package before handing it over as described in [Asking for an eval](#asking-for-an-eval), but do not treat that preparation as a completion gate. See [Local Install Sync](#local-install-sync). + +### Reporting long-running work + +- Run long operations so their feedback can be read while they execute. When the host shows a foreground command's output only after it exits, run the command in the background and read its stderr log or progress file. +- Treat heartbeats as liveness. A silent child process is not evidence of failure, and a healthy operation is not stopped merely because it takes time. A stale progress file, a timeout or a `[FAILED]` line is evidence; report it promptly. +- Never report completion before the operation's terminal result exists and has been checked. + +### Status Update Hygiene + +Interim progress updates should describe user-relevant progress, evidence, blockers, and next steps. Do not narrate runner internals, sandbox mechanics, approved command paths, or retry plumbing unless that detail affects user approval, reproducibility, validation, or the final outcome. + +- Say what changed in the task state, not how the host executed the command +- Mention tool/runtime failures only when they block progress, require approval, or change the planned validation +- Prefer concise phrasing such as "The first read attempt failed before returning file content; I'm retrying and will report only if that changes the result" ## User Input UX @@ -383,14 +393,6 @@ Presentation rules (enforced in every `FORMS.md`): This applies to all skills that collect user input, not just scaffolding skills. -## Status Update Hygiene - -Interim progress updates should describe user-relevant progress, evidence, blockers, and next steps. Do not narrate runner internals, sandbox mechanics, approved command paths, or retry plumbing unless that detail affects user approval, reproducibility, validation, or the final outcome. - -- Say what changed in the task state, not how the host executed the command -- Mention tool/runtime failures only when they block progress, require approval, or change the planned validation -- Prefer concise phrasing such as "The first read attempt failed before returning file content; I'm retrying and will report only if that changes the result" - ## Skill Authoring Skills MUST follow the Agent Skills specification and remain compatible with Anthropic's skill guidance. Repository conventions below may intentionally be stricter than the specification. diff --git a/CHANGELOG.md b/CHANGELOG.md index dbc6720b..bfe41163 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,47 @@ 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.14.0] - 2026-12-05 + +This is a minor release that adds the `git-worktree-merge` and `skill-evaluations` skills, a .NET `agentic-tooling` solution with a bounded validation scheduler, publication-aware release scope resolution for `git-keep-a-changelog`, and OpenCode v2 support in the eval runner, while porting the PowerShell and Python helpers of several skills to .NET tools with progress reporting and fixing docfx run-action, eval runner, and release evidence defects. + +> [!WARNING] +> Skills that previously ran PowerShell or Python helpers now need the .NET 10 SDK, because their removed `.ps1` and `.py` helper scripts are replaced by `dotnet run --file` tools. + +### Added + +- Added the `git-worktree-merge` skill (`skills/git-worktree-merge`), which merges completed Git worktree contributions into a feature branch through discovery, owner coordination, readiness checks, dependency ordering, conflict resolution, validation, and scoped cleanup, and which probes host tools before it falls back to Git alone, +- Added the `skill-evaluations` skill (`skills/skill-evaluations`), which runs one explicitly requested paired live evaluation of a repo-managed skill by resolving the harness and model, preparing the package, and handing it to a fresh evaluator, +- Added the `tooling` .NET solution (`tooling`) with the `validate-local` scheduler, which runs each CI suite in its own process with bounded concurrency, timeouts, and progress files, an `agentic-tooling run-parallel` command for bounded work items, a measurement harness, and file-based tools that roll forward to newer .NET majors, with `scripts/agentic-tooling.ps1` building the tool when its inputs change, +- Added the xUnit v3 test packages `xunit.v3`, `xunit.v3.runner.console`, `xunit.runner.visualstudio`, `Microsoft.NET.Test.Sdk`, and `Codebelt.Extensions.Xunit` as central package versions for the tooling test projects, +- Added publication-aware release scope to `git-keep-a-changelog` (`skills/git-keep-a-changelog/scripts/resolve-release-scope.cs` and `skills/git-keep-a-changelog/references/release-lifecycle.md`), which reports whether a target version is planned, prepared, published, or unknown, never treats an unpublished tag as a boundary, and returns a corrective continuation for a version that was tagged but never distributed, +- Added bounded work packets to `dotnet-docfx-digest` (`skills/dotnet-docfx-digest/scripts/docfx/WorkPackets.cs`), which hand out the next small set of examples for review, save their results in the behavioral ledger, resume after interruption, and withhold the final gate until actionable packets drain, +- Added OpenCode v2 support to the eval runner (`scripts/eval-runners/opencode/runner.ps1` and `scripts/Get-HarnessModels.ps1`), with model discovery through `opencode models` and `opencode api model.list`, standalone execution with `#variant` selectors, and verification of each turn's prompt, session, model, and variant from the native session export. + +### Changed + +- Changed the Codebelt Reference and `-Runner claude` defaults to `claude-haiku-5-5` with `medium` reasoning effort (`scripts/eval-runners/claude/reference.json`), +- Changed the eval runners to run declared prerequisite readiness probes before the first model turn for Claude Code, OpenCode, and Codex, instead of refusing those evals as infrastructure blocked (`scripts/eval-runners`), +- Changed `validate-local` to forward to the .NET scheduler (`scripts/validate-local.ps1`), +- Changed `git-remote-pr`, `git-visual-commits`, `git-keep-a-changelog`, `dotnet-nuget-update`, `dotnet-test`, and `dotnet-csrun` to use .NET file-based tools in place of their PowerShell helpers (`skills/git-remote-pr`, `skills/git-visual-commits`, `skills/git-keep-a-changelog`, `skills/dotnet-nuget-update`, `skills/dotnet-test`, and `skills/dotnet-csrun`), +- Changed `git-remote-pr`, `git-visual-commits`, `git-keep-a-changelog`, `git-remote-release`, `dotnet-nuget-update`, and `git-repo-digest` to write progress and heartbeats to stderr and atomic progress files while stdout keeps the machine-readable result (`skills/git-remote-pr`, `skills/git-visual-commits`, `skills/git-keep-a-changelog`, `skills/git-remote-release`, `skills/dotnet-nuget-update`, and `skills/git-repo-digest`), +- Changed `git-remote-release` to run its evidence collector as a .NET file-based tool in place of the Python script, with up to four endpoint reads in parallel (`skills/git-remote-release`), +- Changed `dotnet-benchmark`, `dotnet-remote-testing`, `dotnet-segregated-assets`, `dotnet-new-app-slnx`, and `dotnet-new-lib-slnx` to .NET helpers in place of their PowerShell scripts (`skills/dotnet-benchmark`, `skills/dotnet-remote-testing`, `skills/dotnet-segregated-assets`, `skills/dotnet-new-app-slnx`, and `skills/dotnet-new-lib-slnx`), +- Changed `git-repo-digest` to bound external clones and example validation, and to cache tracked-file listings (`skills/git-repo-digest`), +- Changed `agent-smith` to move its Roslyn artifact repair to .NET and to require positive, representative evidence before merge readiness while restraining documentation growth (`skills/agent-smith`). + +### Removed + +- Removed the PowerShell and Python helper scripts that the .NET tools replace, including `skills/git-remote-pr/scripts/execute-pr.ps1`, `skills/git-visual-commits/scripts/validate-commit-subject.ps1`, `skills/git-keep-a-changelog/scripts/resolve-release-scope.ps1`, `skills/git-remote-release/scripts/collect-release-evidence.py`, `skills/dotnet-nuget-update/scripts/Update-NuGetPackages.ps1`, `skills/dotnet-test/scripts/inspect-dotnet-tests.ps1`, `skills/dotnet-csrun/scripts/sample-tools.ps1`, `skills/agent-smith/scripts/repair-roslyn-multiproject-artifacts.ps1`, and `skills/dotnet-new-app-slnx/scripts/resolve-package-versions.ps1`. + +### Fixed + +- Fixed run-action package selection in `dotnet-docfx-digest` (`skills/dotnet-docfx-digest`), so undeclared packages are no longer pinned to an unrelated package that merely shares the first name part, +- Fixed run-action source classification in `dotnet-docfx-digest` (`skills/dotnet-docfx-digest`), so recipes stay in the repository before their first manifest exists instead of being rejected as scratch, +- Fixed example checks in `dotnet-docfx-digest` (`skills/dotnet-docfx-digest`) so that calls inside interpolated string holes count as API usage, +- Fixed the eval runner so child PowerShell processes start the running host when `pwsh` is absent from `PATH`, and so isolated runner shells keep host `PATH` order, preventing a directory found for one command from shadowing `dotnet` (`scripts/eval-runners`), +- Fixed `git-remote-release` so a co-author without a GitHub account, such as a bot or an unmapped identity, no longer aborts release evidence collection, while other lookup failures still fail (`skills/git-remote-release`). + ## [0.13.3] - 2026-12-01 This is a minor release that adds a Claude Code eval runner, eval prerequisite provisioning, entrypoint skill exposure, readiness probes with controlled shell environments, and Windows process-tree ownership to the evaluation harness, adds a behavioral review and repair workflow, an operation-aware behavioral review ledger, precise `--uid` scoping, per-TFM `MetadataLoadContext` isolation, consumer API discovery, and MSBuild-evaluated project metadata to `dotnet-docfx-digest`, makes Claude Code the Codebelt Reference harness, splits the DocFX validator into modules, hardens the file-based app build cache, removes the package release notes target from the `dotnet-new-app-slnx` shared build targets, and fixes DocFX default template preservation, example target-usage analysis, static-fallback version reading, xUnit attribute eligibility, skip-marker reconciliation, binary log and process output handling, global tool `PATH` registration in validation jobs, and Codex `multi_agent` probe gating, and tightens `Co-authored-by` handling in the commit and release-note skills. @@ -930,6 +971,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.14.0]: https://github.com/codebeltnet/agentic/compare/v0.13.3...v0.14.0 [0.13.3]: https://github.com/codebeltnet/agentic/compare/v0.13.2...v0.13.3 [0.13.2]: https://github.com/codebeltnet/agentic/compare/v0.13.1...v0.13.2 [0.13.1]: https://github.com/codebeltnet/agentic/compare/v0.13.0...v0.13.1 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 49d2d28f..2aeb84c5 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -86,7 +86,7 @@ Evals let you verify the skill works and measure improvement over a baseline. Ev Aim for 3–5 evals that cover distinct scenarios: happy path, edge cases, and cases where the skill should *not* do something. -Evals are prepared, not executed, from this repository. Package preparation is optional and happens only after an explicit eval request, such as `eval `, `evaluate `, or `please do an eval`. Adding or modifying a repo-managed skill does not require a package, a harness choice, or a model choice. +Package preparation is optional and happens only after an explicit eval request, such as `eval `, `evaluate `, or `please do an eval`. Adding or modifying a repo-managed skill does not require a package, a harness choice, or a model choice. For a live run in one request, use [skill-evaluations](skills/skill-evaluations/SKILL.md) with one skill and harness. The repository script prepares the package and a fresh evaluator handles execution and reporting. When an eval is requested, prepare the changed packages with: @@ -100,7 +100,7 @@ For a single skill on demand, use: pwsh -NoProfile -NonInteractive -File ./scripts/prepare-skill-evals.ps1 -Skill -Runner -Model ``` -Before running the script, choose a Harness + Model when the user did not already do so. Normalize explicit harness wording immediately: `Claude Code` maps to `claude`; `Codex` maps to `codex`; `OpenCode` maps to `opencode`; matching is case-insensitive. When no harness was named, offer Claude Code — Codebelt Reference (Recommended) first, then Codex CLI, then OpenCode. Use `scripts/Get-HarnessModels.ps1 -Runner ` to list current selectors; it fails immediately with the supported runner IDs when `-Runner` is omitted. OpenCode mirrors every model exposed by all configured providers, with availability retained as metadata only, while Codex lists all currently available models. When OpenCode is selected without an explicit model, present the discovered exact `provider/model` selectors, ask the user to choose one, and wait; never select the first, free, recommended, previous-iteration, previous-successful, or previous-failed model automatically. Preserve an explicitly supplied OpenCode selector verbatim in `execution-profile.json`; discovery failure or incomplete metadata must not substitute another model. The Codebelt Reference (`-CodebeltReference`) is Claude Code with the model and effort in `scripts/eval-runners/claude/reference.json`, which `-Runner claude` also uses when no model is given; Claude Code needs a full model id, not an alias, and authenticates with the login of the Claude Code harness that runs `RUN-THIS.prompt.md`. Codex defaults to `gpt-6-luna` with high reasoning; package preparation validates the resolved model against current discovery before writing `execution-profile.json`. The script writes `.bot/-workspace/iteration-/` with one directory per eval. Each holds the grading key `eval-metadata.json` and result stubs under `results/` at the eval-case level, plus two paired run directories, `with_skill/` and `without_skill/`. A run directory is the worker's run root: `prompt.md`, a `run.json` contract, a `repo/` working tree materialized from the fixtures, an isolated `home/`, and - for `with_skill` only - a `skill//` copy of the candidate. The grading key and results sit outside both run directories. At the root it writes `manifest.json`, `execution-profile.json`, the package-local Eval Runner protocol, the package report adapter, the exact Anthropic skill-creator grader/aggregator/viewer assets, and `RUN-THIS.prompt.md`, the one prompt you hand to the external Eval Orchestrator. That orchestrator resolves and preflights the selected runner, reads `delegation.dispatch_owner`, and either dispatches the declared orchestrator-owned native worker or starts the declared runner-owned one-arm native surface directly. It stores genuine transport-produced `execution-result.json` evidence, bridges the results, grades only after execution, and runs the adapter, which invokes `aggregate_benchmark.py` and `eval-viewer/generate_review.py --static`. It never runs an eval prompt in the coordinator context, never chooses runner/model policy, and never reuses a worker. Both worker prompts carry the same task, materialized repository, and response contract; only the operating instructions and the presence of `skill/` differ, and neither prompt identifies itself as an eval. `.gitignore` covers `.bot/*`, so nothing there reaches git. The script refuses an `-OutputRoot` inside the repository but outside `.bot/`; pass an explicit temp path when the harness does not need repository-local storage. +For a manual package, choose a Harness + Model when the user did not already do so. Normalize explicit harness wording immediately: `Claude Code` maps to `claude`; `Codex` maps to `codex`; `OpenCode` maps to `opencode`; matching is case-insensitive. When no harness was named, offer Claude Code — Codebelt Reference (Recommended) first, then Codex CLI, then OpenCode. Use `scripts/Get-HarnessModels.ps1 -Runner ` to list current selectors; it fails immediately with the supported runner IDs when `-Runner` is omitted. OpenCode mirrors every model exposed by all configured providers, with availability retained as metadata only, while Codex lists all currently available models. When OpenCode is selected without an explicit model, present the discovered exact `provider/model` selectors, ask the user to choose one, and wait; never select the first, free, recommended, previous-iteration, previous-successful, or previous-failed model automatically. Preserve an explicitly supplied OpenCode selector verbatim in `execution-profile.json`; discovery failure or incomplete metadata must not substitute another model. The Codebelt Reference (`-CodebeltReference`) is Claude Code with the model and effort in `scripts/eval-runners/claude/reference.json`, which `-Runner claude` also uses when no model is given; Claude Code needs a full model id, not an alias, and authenticates with the login of the Claude Code harness that runs `RUN-THIS.prompt.md`. Codex defaults to `gpt-6-luna` with high reasoning; package preparation validates the resolved model against current discovery before writing `execution-profile.json`. The script writes `.bot/-workspace/iteration-/` with one directory per eval. Each holds the grading key `eval-metadata.json` and result stubs under `results/` at the eval-case level, plus two paired run directories, `with_skill/` and `without_skill/`. A run directory is the worker's run root: `prompt.md`, a `run.json` contract, a `repo/` working tree materialized from the fixtures, an isolated `home/`, and - for `with_skill` only - a `skill//` copy of the candidate. The grading key and results sit outside both run directories. At the root it writes `manifest.json`, `execution-profile.json`, the package-local Eval Runner protocol, the package report adapter, the exact Anthropic skill-creator grader/aggregator/viewer assets, and `RUN-THIS.prompt.md`, the one prompt you hand to the external Eval Orchestrator. That orchestrator resolves and preflights the selected runner, reads `delegation.dispatch_owner`, and either dispatches the declared orchestrator-owned native worker or starts the declared runner-owned one-arm native surface directly. It stores genuine transport-produced `execution-result.json` evidence, bridges the results, grades only after execution, and runs the adapter, which invokes `aggregate_benchmark.py` and `eval-viewer/generate_review.py --static`. It never runs an eval prompt in the coordinator context, never chooses runner/model policy, and never reuses a worker. Both worker prompts carry the same task, materialized repository, and response contract; only the operating instructions and the presence of `skill/` differ, and neither prompt identifies itself as an eval. `.gitignore` covers `.bot/*`, so nothing there reaches git. The script refuses an `-OutputRoot` inside the repository but outside `.bot/`; pass an explicit temp path when the harness does not need repository-local storage. Repository preparation, validation, CI, hooks, deterministic tests, and automatic completion gates never run those prompts or invoke a model. That boundary is the Priority 1 rule in `AGENTS.md`, and preparing a prompt is not permission to execute one. A human-selected external Eval Orchestrator handed a specific package may invoke the selected package-local Eval Runner; this explicit handoff boundary does not weaken the repository prohibition or authorize CI/live evals. diff --git a/README.md b/README.md index 1e26c21d..0295da0f 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Agentic Skills -Repository scratch files belong in a task-specific OS temporary directory by default, or under ignored `.bot/` when repository-local storage is needed. API snapshots, intermediate JSON/text, logs, drafts, caches, and temporary workspaces must never be written elsewhere in the working tree. Maintained source files and test fixtures remain in their intended locations. See [Scratch File Isolation](AGENTS.md#scratch-file-isolation). +Repository scratch files belong in a task-specific OS temporary directory by default, or under ignored `.bot/` when repository-local storage is needed. API snapshots, intermediate JSON/text, logs, drafts, caches, and temporary workspaces must never be written elsewhere in the working tree. Maintained source files and test fixtures remain in their intended locations. Plans, ledgers, investigations, raw measurements and other working files stay out of source control even when they must outlive one agent session; because `.bot/` is local, a new clone does not have them. See [Scratch File Isolation](AGENTS.md#scratch-file-isolation). ![Skills Applied](assets/hero.jpg) @@ -14,9 +14,11 @@ One repo-wide convention matters especially for scaffolding skills: prefer dynam Another repo rule is intentionally strict: every repo-managed skill ships with its own `evals/evals.json`. These files are versioned review specifications whose prompts, fixtures, and expected outcomes are validated locally; they are not instructions to launch model sessions. -Skill validation is local and deterministic. The Priority 1 **AI/LLM Evaluation Automation Prohibition** in `AGENTS.md` forbids repository preparation, validation, CI, hooks, deterministic tests, automatic fan-out, graders, and completion gates from using an authenticated Copilot, Claude, Codex, Gemini, or other model account. There is no repository opt-in switch. A human-selected external Eval Orchestrator may invoke an explicitly selected package-local Eval Runner for a package it was handed; that boundary never authorizes live model execution in CI or automatic repository workflows. +Skill validation is local and deterministic. Repository automation never invokes a model. A separate, user-directed Eval Orchestrator runs the selected package. See the [eval handoff rules](AGENTS.md#portable-eval-handoff) and the [Eval Runner protocol](scripts/eval-runners/README.md). -Evaluation keeps Anthropic's `skill-creator` methodology and portable paired-run conventions while replacing only the execution transport. `run.json` remains the runner-neutral one-arm contract; `execution-profile.json` selects the runner/model/configuration; and `delegation.dispatch_owner` declares whether the orchestrator dispatches a native subagent/task or starts the runner-owned native execution surface directly. Orchestrator-owned envelopes pass through `record-native-result.ps1`; runner-owned transports produce `execution-result.json` directly before the existing `eval-result/2` bridge and reports. The user-facing preparation flow normalizes explicit harness intent before emitting `RUN-THIS.prompt.md`; the portable profile stores the internal runner id and the opaque runner-native model selector, with no provider field. Claude Code is the canonical reference harness and recommended default (Codebelt Reference, configured once in `scripts/eval-runners/claude/reference.json`); Codex CLI and OpenCode remain supported secondary runners for explicit selection, with a deterministic fake runner used for conformance. The Claude runner drives one fresh headless `claude -p --output-format stream-json` session per arm, the same native surface Anthropic's `skill-creator` uses, authenticated by the Claude Code harness you hand the package to, with `--safe-mode` disabling that login's `CLAUDE.md`, skills, plugins, hooks, and MCP servers, a runner-assigned session id, and model, cwd, and skill-catalogue proof taken from Claude Code's own events. Codex defaults to `gpt-6-luna` with high reasoning. Package preparation validates the resolved model against the current harness catalog before writing the profile. OpenCode discovery mirrors every model exposed by all configured providers, preserves exact `provider/model` selectors, and retains availability only as presentation metadata; it never filters paid or unknown models. When OpenCode is selected without an explicit model, the user must choose from the discovered selectors before package preparation, and no first/free/recommended/previous model may be selected automatically. Codex discovery lists all currently available models. The repository prepares the paired candidate and baseline inputs as a portable package and stops; the external Eval Orchestrator resolves, preflights, follows the selected dispatch owner, then grades and reports. Runners grant full operational permission inside each isolated behavioral harness configuration so the evaluated agent can perform ordinary engineering work noninteractively. Hard filesystem confinement is a separate optional outer capability: it raises reported isolation confidence from pragmatic to strict when proven, but it is not a universal platform prerequisite, so Windows is a first-class pragmatic target; mandatory experimental controls remain fail-closed. Native skill activation is not evaluated in v0.9.1. Package preparation is optional and happens only when the user explicitly asks for an evaluation, such as `eval `, `evaluate `, or `please do an eval`; changing a skill alone does not require choosing a harness or preparing a package: +Use [skill-evaluations](skills/skill-evaluations/SKILL.md) from this checkout to request preparation, execution, and the paired report in one turn. In Claude Code use `/skill-evaluations [model]`. In Codex select `$skill-evaluations` and supply the same arguments. The runner defaults are Claude Haiku 5.5 Medium, GPT-6 Luna XHigh, or a verified free OpenCode model with an Artificial Analysis Intelligence Index of 22–28. A host that can hand the package to a fresh evaluator handles the run in the same conversation. + +Evaluation keeps Anthropic's `skill-creator` methodology and portable paired-run conventions while replacing only the execution transport. `run.json` remains the runner-neutral one-arm contract; `execution-profile.json` selects the runner/model/configuration; and `delegation.dispatch_owner` declares whether the orchestrator dispatches a native subagent/task or starts the runner-owned native execution surface directly. Orchestrator-owned envelopes pass through `record-native-result.ps1`; runner-owned transports produce `execution-result.json` directly before the existing `eval-result/2` bridge and reports. The user-facing preparation flow normalizes explicit harness intent before emitting `RUN-THIS.prompt.md`; the portable profile stores the internal runner id and the opaque runner-native model selector, with no provider field. Claude Code is the canonical reference harness and recommended default (Codebelt Reference, configured once in `scripts/eval-runners/claude/reference.json`); Codex CLI and OpenCode remain supported secondary runners for explicit selection, with a deterministic fake runner used for conformance. The Claude runner drives one fresh headless `claude -p --output-format stream-json` session per arm, the same native surface Anthropic's `skill-creator` uses, authenticated by the Claude Code harness you hand the package to, with `--safe-mode` disabling that login's `CLAUDE.md`, skills, plugins, hooks, and MCP servers, a runner-assigned session id, and model, cwd, and skill-catalogue proof taken from Claude Code's own events. Direct Codex package preparation defaults to `gpt-6-luna` with high reasoning. Package preparation validates the resolved model against the current harness catalog before writing the profile. OpenCode discovery mirrors every model exposed by all configured providers, preserves exact `provider/model` selectors, and retains availability only as presentation metadata; it never filters paid or unknown models. For a manual package request with OpenCode and no explicit model, the user must choose from the discovered selectors before package preparation. Codex discovery lists all currently available models. The preparation script prepares the paired candidate and baseline inputs as a portable package and stops. The external Eval Orchestrator preflights, follows the selected dispatch owner, then grades and reports. Runners grant full operational permission inside each isolated behavioral harness configuration so the evaluated agent can perform ordinary engineering work noninteractively. Hard filesystem confinement is a separate optional outer capability: it raises reported isolation confidence from pragmatic to strict when proven, but it is not a universal platform prerequisite, so Windows is a first-class pragmatic target; mandatory experimental controls remain fail-closed. Native skill activation is not evaluated in v0.9.1. Package preparation is optional and happens only when the user explicitly asks for an evaluation, such as `eval `, `evaluate `, or `please do an eval`; changing a skill alone does not require choosing a harness or preparing a package: Phase 1 closes by writing an immutable `execution-freeze.json` ledger with the exact manifest result paths and hashes of every runner-produced execution result and referenced raw transcript/event artifact. The bridge, grading application, and report adapter validate that ledger and never re-bless changed bytes. The external Grader writes only package-root `grading.json` (`codebeltnet/agentic/eval-grading/1`); `apply-eval-grading.ps1` projects only `passed` and `evidence` decisions onto canonical results. `finalize-eval-package.ps1` owns the deterministic completion boundary and succeeds only after validating the freeze, bridge, complete grading, and all four report artifacts. A changed raw file requires a fresh Phase 1 execution, and prose cannot substitute for finalizer success. Optional scripted `interaction.json` sidecars provide deterministic same-session user turns only when the selected runner advertises and preflights that capability; ordinary single-turn runs remain unchanged. @@ -32,7 +34,7 @@ The four roles are intentionally separate: the Eval Runner is the harness-specif One more consistency rule matters for form-driven skills: native input fields are treated as a host feature, not something a model can rely on. Skills in this repo must stay usable with or without UI widgets, and must fall back to the same deterministic one-field-at-a-time flow when the host only supports plain chat. -Repo-level agent guidance also keeps progress updates user-facing: agents should report meaningful progress, evidence, blockers, and next steps without narrating sandbox mechanics, approved command paths, or retry plumbing unless those details affect approval, reproducibility, validation, or the final outcome. +Repo-level agent guidance also keeps progress updates user-facing: agents should report meaningful progress, evidence, blockers, and next steps without narrating sandbox mechanics, approved command paths, or retry plumbing unless those details affect approval, reproducibility, validation, or the final outcome. Local commits follow task-scoped authorization: a delivery-scoped grant, or `yolo` or `auto` on an explicit worktree merge or orchestration request, covers the local commits, merges, and validated cleanup that lifecycle needs. Concurrent agents keep one writer per worktree, and no local authorization covers pushes, pull requests, protected-branch changes, releases, deployments, or force deletion. See [Git Operations Safeguards](AGENTS.md#git-operations-safeguards). Completion gates are equally strict: if repository guidance, a loaded skill, or the conversation summary marks a script-backed step as pending, critical, or blocking, agents must treat it as an active checklist item and may not claim completion until that command has run or the exact external blocker has been reported. In the DocFX workflow, that means `scripts/agents.cs` and the build-backed `scripts/docfx.cs --build-api-model --validate-samples --verify-docfx-build` verification are completion gates, not optional cleanup after the documentation files look done. The validator now emits a deterministic completion contract: `summary.fullVerificationRan` must be `true`, `summary.canClaimCompletion` must be `true`, `summary.remainingWorkItems` must be `0`, both `summary.remainingGates` and `summary.remainingDiagnosticsByCode` must be empty, and both `summary.newlyIntroducedSkipMarkers` and `summary.interimArtifacts` must be `0`. A clean fast run reports `verification-required`, not completion. Pre-existing gaps, large diagnostic counts, sample failures, unresolved symbol ownership, and documentation-caused DocFX build failures remain repair work; they are not permission to stop after a partial digest. Context pressure, session length, task size, repetitive authoring, or a stable queue are not escape hatches either; agents must shrink the batch, regenerate deterministic queue state, or report a true blocker instead of ending with a follow-up handoff. Cross-assembly collisions are clearable: exact type-UID example mappings resolve `SYMBOL_COLLISION_UNRESOLVED`, and exact-owner receiver-style calls resolve `EXTENSION_OWNER_AMBIGUOUS`. (The plain `scripts/docfx.cs` run is fast and build-free for iteration; the build-backed flags are what make the final gate authoritative.) @@ -44,7 +46,7 @@ Local skill synchronization is verified efficiently and mechanically: run determ Resumed DocFX audits preserve every tracked and untracked documentation edit, regenerate the assessment work queue and example inventory, and process that queue in batches with a fast rerun after each batch. Encoding checks focus on actual damage: valid BOM-less UTF-8 is accepted, `ENCODING_BOM_MISSING` is not emitted, and audits do not create BOM-only or line-ending-only diffs. -DocFX guidance now also preserves working external links during prose rewrites unless a direct HTTP 404 justifies removal, keeps assessment/manifests/captured output/helper scripts in temp or session storage instead of the target repository, treats unexpected new repo-root or DocFX-workspace files that are not known skill deliverables as blocking cleanup work, and prefers inline or small sibling-batch prose repairs over slow per-page worker fan-out. +DocFX guidance now also preserves working external links during prose rewrites unless a direct HTTP 404 justifies removal, keeps assessment/manifests/captured output/helper scripts in temp or session storage instead of the target repository, treats unexpected new repo-root or DocFX-workspace files that are not known skill deliverables as blocking cleanup work while accepting run-action source (such as `run-actions.settings.json`) before and after the first successful generation, and prefers inline or small sibling-batch prose repairs over slow per-page worker fan-out. The DocFX validator now fails compiler-generated C# extension-block overwrite filenames at the layout gate and collapses literal, percent-encoded, and DocFX private-use `$...` containers back to their authored outer static class in both YAML and reflection-backed API discovery. That prevents agents from creating or chasing unreadable synthetic files such as `EndpointConventionBuilderExtensions.G$6D0D8037DBBD61D10816ECA5F93B896F.md` after the readable declaring-class page already exists. @@ -52,6 +54,8 @@ Final DocFX verification is machine-adaptive: `auto` selects a high-capacity pro DocFX diagnostics favor repairable specificity: overwrite-layout errors now call out literal near-miss globs such as `api/namespaces/**.md` versus `api/namespaces/**/*.md`, no-observable-outcome example failures explain what visible reader result is missing, and common sample `CS1061` extension-method failures include missing-`using` hints such as `System.Linq` or `BenchmarkDotNet.Configs` when the compiler output points that way. +Repository and skill tools follow the **Executable Tooling Standards** in `AGENTS.md`: first-party automation is .NET, child process trees are owned and killed as a whole on timeout, independent work runs with bounded concurrency, and long operations report plain-text progress and heartbeats on stderr while stdout stays machine-readable. Tests are fast by design: repository tests are xUnit v3 projects in the `tooling/` solution that exercise deterministic logic in-process, start a process only where a real process boundary is under test, build each distributed tool once, and treat a material slowdown as a blocking regression. + Use the metadata-only mode for the fastest feedback on every skill manifest, fixture path, and frontmatter description: ```powershell @@ -64,11 +68,11 @@ During iteration, run the changed skill's bundled deterministic validator and fo pwsh -NoProfile -File ./scripts/validate-local.ps1 ``` -The scheduler reads every suite from `.github/workflows/validate-skill-templates.yml`, so local and CI coverage stay aligned, and runs each one in a separate PowerShell 7 process with bounded concurrency, a streamed per-suite log, isolated fixtures, and per-suite exit codes. It enforces a per-suite timeout by killing the whole process tree, keeps running the remaining suites after a failure so one run reports every problem, and writes `summary.json` with the coverage counts next to the logs. It exits non-zero unless every CI-matrix suite exited zero and printed its terminal success marker, so a timeout or a silently skipped check is never reported as a pass. Use `-ListSuites` to print the resolved matrix, and `-MaxConcurrency`, `-TimeoutSeconds`, and `-DeadlineSeconds` to tune a run. Sequentially invoking the aggregate script or looping over the matrix one entry at a time is not permitted for agent-driven validation. If concurrent execution is unavailable, report the limitation. An explicit user instruction to skip or stop testing suspends validation for that session; report the work as unvalidated. +The scheduler reads every suite from `.github/workflows/validate-skill-templates.yml`, so local and CI coverage stay aligned, and runs each one in a separate PowerShell 7 process with bounded concurrency, a streamed per-suite log, isolated fixtures, and per-suite exit codes. It enforces a per-suite timeout by killing the whole process tree, keeps running the remaining suites after a failure so one run reports every problem, and writes `summary.json` with the coverage counts next to the logs. The scheduler is implemented in .NET (`agentic-tooling validate-local` in `tooling/`; the script forwards to it) and reports start, per-suite progress and a heartbeat about every 10 seconds on stderr, plus a `progress.json` snapshot under the output root, so a host that shows command output only after it exits can still follow the run. It exits non-zero unless every CI-matrix suite exited zero and printed its terminal success marker, so a timeout or a silently skipped check is never reported as a pass. Inside a suite, independent work items such as the template regression suites and the recorded runner scenarios run through `agentic-tooling run-parallel`, which applies the same bounded concurrency, process-tree ownership, per-item timeouts, logs and progress reporting. Use `-ListSuites` to print the resolved matrix, and `-MaxConcurrency`, `-TimeoutSeconds`, and `-DeadlineSeconds` to tune a run. Sequentially invoking the aggregate script or looping over the matrix one entry at a time is not permitted for agent-driven validation. If concurrent execution is unavailable, report the limitation. An explicit user instruction to skip or stop testing suspends validation for that session; report the work as unvalidated. -CI runs the complete validation set in 14 independent jobs with a five-minute budget per job. Template checks, PR workflow regressions, package preparation, runner regressions, and DocFX have separate jobs; runner conformance is split by transport and integrity tests by phase. Every job uses isolated temporary fixtures, and the existing `validate-skill-templates` required check passes only when every job succeeds. New commits cancel obsolete runs for the same pull request. Each job records its elapsed time in the Actions summary. For focused local validation, `-Suite Templates`, `-Suite Pr`, `-Suite Preparation`, or `-Suite Runners` selects a group, and `-Full -Suite Docfx` selects DocFX. The conformance and integrity test scripts also accept the `-Suite` values listed in the workflow. Agents default to focused checks for the changed skill or component. Each full local run of `scripts/validate-local.ps1` requires explicit human approval after its scope and cost are explained. Generic requests to test or finalize work do not grant that approval. Focused checks satisfy the local completion gate when a full run has not been approved. This partition changes scheduling, not the model-free validation contract. +CI runs the complete validation set in 16 independent jobs with a five-minute budget per job. Template checks, PR workflow regressions, package preparation, runner regressions, Claude runner conformance, DocFX, and the .NET tooling tests have separate jobs; runner conformance is split by transport and integrity tests by phase. Every job uses isolated temporary fixtures, and the existing `validate-skill-templates` required check passes only when every job succeeds. New commits cancel obsolete runs for the same pull request. Each job records its elapsed time in the Actions summary. For focused local validation, `-Suite Templates`, `-Suite Pr`, `-Suite Preparation`, `-Suite Runners`, or `-Suite Tooling` selects a group, and `-Full -Suite Docfx` selects DocFX. The conformance and integrity test scripts also accept the `-Suite` values listed in the workflow. Agents default to focused checks for the changed skill or component. Each full local run of `scripts/validate-local.ps1` requires explicit human approval after its scope and cost are explained. Generic requests to test or finalize work do not grant that approval. Focused checks satisfy the local completion gate when a full run has not been approved. This partition changes scheduling, not the model-free validation contract. -The file-based validation tooling targets `net10.0`. Building file-based apps that use `#:include` requires .NET SDK feature band `10.0.300` or later. CI provisions the latest GA LTS and STS SDKs for jobs that use .NET and logs `dotnet --version` and `dotnet --list-sdks`. The .NET CLI honors any applicable `global.json` when selecting the effective SDK. +The file-based validation tooling targets `net10.0` and rolls forward to newer major runtimes, so it also runs where only .NET 11 is installed. Building file-based apps that use `#:include` requires .NET SDK feature band `10.0.300` or later. CI provisions the latest GA LTS and STS SDKs for jobs that use .NET and logs `dotnet --version` and `dotnet --list-sdks`. The .NET CLI honors any applicable `global.json` when selecting the effective SDK. ## Install a skill @@ -146,7 +150,7 @@ When repo-managed skills author Markdown, each prose paragraph and list item sta | Skill | Description | |-------|-------------| | [git-visual-commits](skills/git-visual-commits/SKILL.md) | AI-driven git commit workflow with authoritative routing for `git bot commit`, `git commit`, and `git our commit`, including the exact `Please do a git bot commit yolo` form. It locks the requested identity, treats yolo/auto only as scoped auto-approval modifiers, never as the commit message, and does not hand commit execution to changelog or release-note skills. It uses deterministically validated emoji-first subjects, deterministic `Co-authored-by` trailer checks (forbidding trailers by default and allowing them only when explicitly requested and verified via `gh` as a GitHub `User`), optional conventional prefixes only on explicit request, full-worktree semantic grouping unless narrowed, a visible multi-file single-category quality gate, commit bodies by default, and post-commit identity/body/trailer verification. Multi-file plans that initially collapse to one category also require a visible full-context quality gate; one-file changes keep the fast path. Stack-agnostic. | -| [git-keep-a-changelog](skills/git-keep-a-changelog/SKILL.md) | Git-aware Keep a Changelog companion selected only for explicit changelog or release-note intent. Bare yolo/auto and commit-execution requests such as `git bot commit yolo` do not activate it; both keywords enable identical autonomy and omit the `[Unreleased]` heading and footer link only after changelog intent is established, requiring an explicit version or version-prefixed branch. Bundled deterministic resolvers separate branch-unique commit history from merge-base-to-`HEAD` net diffs, exclude the previous-release or comparison boundary, fail on base-history bleed, and classify explicit path-backed release entities as `Added`, `Removed`, `Changed`, or `Unchanged`. The skill establishes each user-facing release entity against the base before section classification. It asks a mandatory `Yes / No / Custom` question before including pending worktree changes in ordinary concrete-release drafts, includes staged, unstaged, and untracked work automatically only in scoped yolo/auto mode, creates missing changelogs, writes SemVer-aware highlights, maintains compare-link footers, preserves natural prose wrapping, and curates surviving outcomes instead of dumping raw commit logs. | +| [git-keep-a-changelog](skills/git-keep-a-changelog/SKILL.md) | Git-aware Keep a Changelog companion selected only for explicit changelog or release-note intent. Bare yolo/auto and commit-execution requests such as `git bot commit yolo` do not activate it; both keywords enable identical autonomy and omit the `[Unreleased]` heading and footer link only after changelog intent is established, requiring an explicit version or version-prefixed branch. Bundled deterministic resolvers separate branch-unique commit history from merge-base-to-`HEAD` net diffs, exclude the previous-release or comparison boundary, fail on base-history bleed, and classify explicit path-backed release entities as `Added`, `Removed`, `Changed`, or `Unchanged`. A planned version that was merged or tagged but never published continues from its preceding release boundary, so later corrections keep the whole release in scope; published and unclear versions stay closed. The skill establishes each user-facing release entity against the base before section classification. It asks a mandatory `Yes / No / Custom` question before including pending worktree changes in ordinary concrete-release drafts, includes staged, unstaged, and untracked work automatically only in scoped yolo/auto mode, creates missing changelogs, writes SemVer-aware highlights, maintains compare-link footers, preserves natural prose wrapping, and curates surviving outcomes instead of dumping raw commit logs. | | [git-nuget-release-notes](skills/git-nuget-release-notes/SKILL.md) | Git-aware NuGet release-notes companion for .NET repos that keep cumulative `.nuget/{ProjectName}/PackageReleaseNotes.txt` files. Uses the full current branch against its integration branch by default, treats same-named tracking branches as sync targets, and honors explicit ranges. A version-only invocation covers every packable `src/` project, including unchanged packages: each gets a complete version/availability block and non-empty ALM, using the required default text when no specific ALM outcomes exist. It creates missing files, reduces each package to its surviving base-to-`HEAD` delta before classifying history, and establishes each package capability against the base so pre-release refinements and fixes to a new capability remain one `ADDED` New Feature. It regenerates existing target-version blocks and verifies complete package coverage before handing the notes back for review. | | [git-nuget-readme](skills/git-nuget-readme/SKILL.md) | Git-aware NuGet README companion for .NET repos that advertise a package from `src/`. Resolves the real packable project the README should sell, combines git history with actual package metadata, source capabilities, and relevant tests when feasible, preserves honest badge/docs/contributing sections, and writes a forthcoming, adoption-friendly `README.md` with repo-derived branding, clear value, install, framework-support, and quick-start guidance. | | [git-visual-squash-summary](skills/git-visual-squash-summary/SKILL.md) | Non-mutating grouped-summary companion to `git-visual-commits`. Covers every surviving change on the full current feature branch across all contributors, using the merge-base with the repository base branch. Inventories every changed path and distinct outcome, recovers truncated diffs, and reconciles coverage before returning compact lowercase-start lines. No total line cap. Merges overlap and removes reverted churn while preserving small independent corrections, technical identifiers, and distinct dependency/version changes. Returns the summary directly without unnecessary scope or approval questions. | @@ -158,16 +162,18 @@ When repo-managed skills author Markdown, each prose paragraph and list item sta | [trunk-first-repo](skills/trunk-first-repo/SKILL.md) | Initialize a git repository following [scaled trunk-based development](https://trunkbaseddevelopment.com/#scaled-trunk-based-development). Seeds an empty `main` branch, creates a versioned feature branch (`v0.1.0/init`), confirms configured remotes in its post-init summary, and supports a guarded later `push remote ` mode that checks the feature-branch/empty-main state before pushing `main` ahead of the first feature branch so content still reaches main only through peer-reviewed pull requests. | | [dotnet-strong-name-signing](skills/dotnet-strong-name-signing/SKILL.md) | Generate a strong name key (`.snk`) file for signing .NET assemblies using pure .NET cryptography — no Visual Studio Developer PowerShell or `sn.exe` required. Works in any terminal. Defaults to 1024-bit RSA (matching `sn.exe`), with 2048 and 4096 available as options. | | [git-remote-release](skills/git-remote-release/SKILL.md) | Generate GitHub release notes by summarizing all commits and pull requests between two Git tags or branches in a remote GitHub repository. Accepts a compare URL or separate owner/repo, previous ref, and current ref values; falls back to comparing the current branch against the upstream default branch when no input is provided. Produces a human-friendly `## What's Changed` section whose first summary line begins `This release `, follows it with curated dash bullets using bold lead-ins and actual explanatory prose, optionally inserts supported GitHub alert blocks, preserves exact verified `Sources:` entries with contributor-complete GitHub logins (keeping verified `User`/`Bot` PR and commit authors while retaining `Co-authored-by` trailers only when GitHub resolves them to a `User` account), keeps em-dash bans scoped to authored prose rather than verbatim source titles, recognizes verified first-time contributors in a rich `## New Contributors` section immediately before Full Changelog, and ends with a compare link or the current-ref commits link for an initial release. Saves the notes as a Markdown file in a temporary working directory outside the repository and returns only an absolute Markdown file link. | -| [git-remote-pr](skills/git-remote-pr/SKILL.md) | Create or refresh a GitHub PR from the complete committed `base...head` changeset. Read-only preparation links a Markdown preview containing the exact proposed title and complete description, assignee, push need, and planned writes before approval; normal execution requires the exact displayed `approve APR-...` phrase and rechecks the write intent, approval-bound normalized review hash, and final preview hash. Material drift ends the approval transaction without regeneration; an explicit refresh starts a new workspace and approval ID. Same-request `yolo`/`auto` still shows the preview but skips the approval wait, executing only the just-presented ID. Existing PR bodies are rebuilt from the current final text diff into concise thematic summaries, with binary assets represented only by paths, statuses, and metadata. Case-insensitive theme coverage reports all mismatches together, and failures remain visible in noninteractive hosts. Draft corrections reuse one workspace. Untracked branches preview publication to GitHub origin (or the sole GitHub remote) under the current branch name, then establish tracking during execution. Dirty worktrees, ambiguous remotes, incomplete or mismatched tracking, divergent branches, and failed post-write checks block completion. Uses Git and `gh`, without Copilot or a browser. | +| [git-worktree-merge](skills/git-worktree-merge/SKILL.md) | Merge Git worktree contributions into a feature branch. Resolve branch, path, workspace, or session names, coordinate readiness where supported, integrate dependencies incrementally, validate combined behavior, and retire eligible temporary resources. | +| [git-remote-pr](skills/git-remote-pr/SKILL.md) | Create or refresh a GitHub PR from the complete committed `base...head` changeset. Read-only preparation links a Markdown preview containing the exact proposed title and complete description, assignee, push need, and planned writes before approval; normal execution requires the exact displayed `approve APR-...` phrase and rechecks the write intent, approval-bound normalized review hash, and final preview hash. Material drift ends the approval transaction without regeneration; an explicit refresh starts a new workspace and approval ID. Same-request `yolo`/`auto` still shows the preview but skips the approval wait, executing only the just-presented ID. Existing PR bodies are rebuilt from the current final text diff into concise thematic summaries, with binary assets represented only by paths, statuses, and metadata. Case-insensitive theme coverage reports all mismatches together, and failures remain visible in noninteractive hosts. Draft corrections reuse one workspace. Untracked branches preview publication to GitHub origin (or the sole GitHub remote) under the current branch name, then establish tracking during execution. Dirty worktrees, ambiguous remotes, incomplete or mismatched tracking, divergent branches, and failed post-write checks block completion. Uses Git, `gh`, and a bundled .NET tool, without Copilot or a browser. | | [dotnet-change-impact](skills/dotnet-change-impact/SKILL.md) | Classify .NET library or NuGet package changes and recommend the correct release bump — `Major`, `Minor`, or `Patch` — for both Semantic Versioning (`MAJOR.MINOR.PATCH`) and .NET assembly/file versioning (`Major.Minor.Build.Revision`), grounded in Microsoft's official .NET compatibility rules. Uses the current Git branch by default when no explicit change details or compare range are provided, resolving it against the upstream/default base branch with local read-only git state. Always returns structured behavioral/binary/source/design-time/backwards compatibility reasoning with the recommendation, even when the bump is clear. | -| [dotnet-nuget-update](skills/dotnet-nuget-update/SKILL.md) | Audits and updates NuGet dependencies in .NET repositories with complete declaration accounting before any edit. It supports both `Directory.Packages.props` and project-level `PackageReference` versions, preserves XML structure and line endings, deduplicates package IDs, resolves independent live or offline flat-container version feeds with bounded parallel lookups and per-process memoization, uses bounded network timeouts, and merges results deterministically. Its single-process update runner keeps the audit, in-memory safe-update plan, and structural apply together for fast yolo passes. It keeps stable pins on stable candidates unless prerelease intent is explicit, and applies the TFM-band rule so conditional `net9`/`net10` package declarations stay within their matching major when that major is the compatibility signal rather than jumping to the newest overall release. Normal mode auto-applies revision/patch/minor and same-major prerelease updates, then batches majors for one approval decision; yolo mode applies only the auto classes and reports held majors without asking. | +| [dotnet-nuget-update](skills/dotnet-nuget-update/SKILL.md) | Audits and updates NuGet dependencies in .NET repositories with complete declaration accounting before any edit. It supports both `Directory.Packages.props` and project-level `PackageReference` versions, preserves XML structure and line endings, deduplicates package IDs, resolves independent live or offline flat-container version feeds with bounded parallel lookups, uses bounded network timeouts, and merges results deterministically. Its bundled .NET tool keeps the audit, in-memory safe-update plan, and structural apply together in one command for fast yolo passes, and reports feed-read progress while it waits on slow feeds. It keeps stable pins on stable candidates unless prerelease intent is explicit, and applies the TFM-band rule so conditional `net9`/`net10` package declarations stay within their matching major when that major is the compatibility signal rather than jumping to the newest overall release. Normal mode auto-applies revision/patch/minor and same-major prerelease updates, then batches majors for one approval decision; yolo mode applies only the auto classes and reports held majors without asking. | | [dotnet-docfx-digest](skills/dotnet-docfx-digest/SKILL.md) | Audit and repair public .NET API documentation, verify example behavior, and optionally generate and verify Native and Docker run actions. | | [dotnet-test](skills/dotnet-test/SKILL.md) | Moves xUnit projects onto Codebelt's entrypoint-owned test hosts, replacing Microsoft's ASP.NET-only `WebApplicationFactory`—and the hand-rolled `HostBuilder` that console and worker tests reach for because Microsoft ships no equivalent—with one family of abstractions where the application's own entry point owns startup. Invocation is the request: it inspects and refactors immediately instead of opening with a menu or a questionnaire. It deterministically inspects project roles, target frameworks, xUnit generation, package ownership, inheritance, application entry points—including Bootstrapper `MinimalConsoleProgram`, `MinimalWorkerProgram`, and `MinimalWebProgram` hosts—and every selected `WebApplicationFactory` usage; classifies ordinary unit, ASP.NET Core functional, and console/worker functional tests; modernizes xUnit v2 projects to xUnit v3 plus Microsoft Testing Platform without moving package ownership or changing frameworks; and resolves current stable compatible packages through NuGet-backed isolated compatibility-project restores, including the selected combined package set. Focused web tests use `WebApplicationTestFactory` with an explicit entrypoint-owned `ManagedWebApplicationFixture`, directly or through a narrow `Test`-derived harness; shared web fixtures use `WebApplicationTest` with `ManagedWebApplicationFixture`; focused console/worker tests use `ApplicationTestFactory` with `ManagedApplicationFixture`; and shared non-web fixtures use `ApplicationTest` with `ManagedApplicationFixture`. Deprecated blocking fixtures are migration inputs only and are never emitted because they are scheduled for removal. Functional migrations fail closed unless the chosen Codebelt pattern and managed fixture are present, the legacy or blocking fixture is absent, and test code does not reconstruct the production composition root with its own `WebApplication`, `TestServer`, or `HostBuilder`. Migrations preserve entrypoint-owned startup, host configuration, lazy start, clients, services, configuration, sync/async disposal, isolation, and existing test names, while fresh bootstraps add source-grounded behavior tests. Non-web tests stay in-process and require a resolvable Generic Host; test-only scope reports the exact production adaptation instead of silently rewriting startup or launching a process. | -| [dotnet-csrun](skills/dotnet-csrun/SKILL.md) | Creates, verifies, repairs, and audits C# examples and genuine xUnit v3 tests, with paired Native and Docker commands from one manifest, exact package pins, and source-linked execution evidence. Published commands verify and run the latest stable csrun release from GitHub, while skill-driven verification and multi-example sweeps resolve and cache the SHA-256-verified `csrun.ps1` locally once (`Resolve-CsrunEngine` + `-EnginePath`) with ETag revalidation and rate-limit fallback to avoid exhausting GitHub's unauthenticated REST quota. | +| [dotnet-csrun](skills/dotnet-csrun/SKILL.md) | Creates, verifies, repairs, and audits C# examples and genuine xUnit v3 tests, with paired Native and Docker commands from one manifest, exact package pins, and source-linked execution evidence. Published commands verify and run the latest stable csrun release from GitHub, while skill-driven verification and multi-example sweeps resolve and cache the SHA-256-verified `csrun.ps1` locally once (`sample-tools.cs resolve-engine` + `pair --engine-path`) with ETag revalidation and rate-limit fallback to avoid exhausting GitHub's unauthenticated REST quota. | | [dotnet-benchmark](skills/dotnet-benchmark/SKILL.md) | Discovers, prioritizes, and authors trustworthy BenchmarkDotNet experiments for a .NET type following codebelt conventions and using the `Codebelt.Extensions.BenchmarkDotNet.Console` runner. It inspects implementation code, call sites, tests, existing benchmarks, and available profiles instead of benchmarking every public member; ranks likely high-impact operations; selects representative typical, boundary, scaling, and adverse cases; and rejects external-I/O or service-level questions that need profiling, macrobenchmarks, or load tests. It creates fair current-versus-candidate comparisons only when observable work is equivalent, uses baseline-free single-operation characterization when no honest comparator exists, prevents unrelated construction/formatting/equality/hash ratios, requires exact per-case correctness oracles plus a semantic preflight for truthful workload labels, hard-gates interpretation on a complete valid BenchmarkDotNet summary, preserves workload invariants such as selectivity and hit/miss ratios as sizes scale, distinguishes deferred pipeline creation from terminal/materialization work, and performs Release build, discovery listing, and dry execution before any explicit full run. Explicit `yolo` mode auto-accepts routine repo-derived defaults and the proposed plan, then proceeds through build/list/dry validation without confirmation churn; only a separate explicit human instruction can start a full performance run. Its runner preflight recognizes the standard Slim/runtime setup and explains when `SkipBenchmarksWithReports = true` plus a matching `reports/tuning/` artifact deliberately filters a benchmark, preventing needless class renames, disassembly, or tool thrash; after the first valid full result it stops unless deeper diagnostics could change a real engineering decision. Harness setup remains adaptive: it detects `.slnx`/`.sln`, CPM, existing `tuning/` projects, and a reusable `tooling/` runner, onboards only missing pieces, resolves package versions dynamically, and keeps the benchmark class in the SUT namespace. | -| [dotnet-remote-testing](skills/dotnet-remote-testing/SKILL.md) | Run .NET tests inside a resolved remote Docker environment and return concise, structured results — Visual Studio's Remote Testing experience (choose an environment → run tests → see results) with the container plumbing hidden behind a deterministic runner (`scripts/remote-test.cs`) the skill orchestrates instead of composing ad-hoc `docker run` commands. Invoking it is the request: with one applicable Docker environment it runs immediately — no capability menu, no parameter questionnaire, no confirmation — and when several channels are derived, the repository's own highest target framework selects the matching one and the choice is reported. The runner decides when a question is unavoidable, exiting `SelectionRequired` (16) with the exact candidates, and every exit code maps to exactly one next action so behavior is identical across models. It honors Microsoft's existing `testenvironments.json` version-1 contract (`name`, `localRoot`, `dockerImage`, `dockerFile`, with the either/or Docker-source rule), treats that file as authoritative when present, and reports WSL/SSH/unknown types as unsupported rather than converting or silently ignoring them. When no `testenvironments.json` exists it provides a zero-configuration experience built exclusively on official `mcr.microsoft.com/dotnet/sdk` images, discovering the currently supported LTS and STS channels plus the current preview from Microsoft's live `releases-index.json` using `support-phase`/`release-type` (never hardcoded version numbers or even/odd assumptions) and caching that metadata outside the repository for offline reuse. It prefers an exact `latest-sdk` image tag (stripping preview build metadata), validates the tag against Microsoft's registry, and pins each execution to the resolved immutable digest so results are reproducible across environment, image, digest, SDK, and architecture. Execution stages the source into an isolated workspace so container builds never leave Linux `bin`/`obj` in the working tree, mounts a persistent NuGet cache outside the repo, runs restore → build → test with structured TRX collection, classifies failures into distinct kinds (configuration, unsupported environment, Docker unavailable, image resolution, SDK incompatibility, staging, restore, compilation, test-host, test failure, result-processing, cleanup, cancellation, release-metadata) so infrastructure problems are never reported as failing unit tests, and always cleans up transient Docker resources. It never generates a `Dockerfile`, dev container, compose file, or editor configuration (an existing configured `dockerFile` is honored, never created), never runs privileged containers or mounts the Docker socket, and never silently falls back to running tests on the host. Docker is the only transport for now, designed so WSL/SSH can be added later without disturbing the deterministic Docker path, which is covered by a comprehensive built-in `--self-test` plus a PowerShell harness. | +| [dotnet-remote-testing](skills/dotnet-remote-testing/SKILL.md) | Run .NET tests inside a resolved remote Docker environment and return concise, structured results — Visual Studio's Remote Testing experience (choose an environment → run tests → see results) with the container plumbing hidden behind a deterministic runner (`scripts/remote-test.cs`) the skill orchestrates instead of composing ad-hoc `docker run` commands. Invoking it is the request: with one applicable Docker environment it runs immediately — no capability menu, no parameter questionnaire, no confirmation — and when several channels are derived, the repository's own highest target framework selects the matching one and the choice is reported. The runner decides when a question is unavoidable, exiting `SelectionRequired` (16) with the exact candidates, and every exit code maps to exactly one next action so behavior is identical across models. It honors Microsoft's existing `testenvironments.json` version-1 contract (`name`, `localRoot`, `dockerImage`, `dockerFile`, with the either/or Docker-source rule), treats that file as authoritative when present, and reports WSL/SSH/unknown types as unsupported rather than converting or silently ignoring them. When no `testenvironments.json` exists it provides a zero-configuration experience built exclusively on official `mcr.microsoft.com/dotnet/sdk` images, discovering the currently supported LTS and STS channels plus the current preview from Microsoft's live `releases-index.json` using `support-phase`/`release-type` (never hardcoded version numbers or even/odd assumptions) and caching that metadata outside the repository for offline reuse. It prefers an exact `latest-sdk` image tag (stripping preview build metadata), validates the tag against Microsoft's registry, and pins each execution to the resolved immutable digest so results are reproducible across environment, image, digest, SDK, and architecture. Execution stages the source into an isolated workspace so container builds never leave Linux `bin`/`obj` in the working tree, mounts a persistent NuGet cache outside the repo, runs restore → build → test with structured TRX collection, classifies failures into distinct kinds (configuration, unsupported environment, Docker unavailable, image resolution, SDK incompatibility, staging, restore, compilation, test-host, test failure, result-processing, cleanup, cancellation, release-metadata) so infrastructure problems are never reported as failing unit tests, and always cleans up transient Docker resources. It never generates a `Dockerfile`, dev container, compose file, or editor configuration (an existing configured `dockerFile` is honored, never created), never runs privileged containers or mounts the Docker socket, and never silently falls back to running tests on the host. Docker is the only transport for now, designed so WSL/SSH can be added later without disturbing the deterministic Docker path, which is covered by a comprehensive built-in `--self-test` plus a .NET regression harness. | | [dotnet-segregated-assets](skills/dotnet-segregated-assets/SKILL.md) | Migrate or configure ASP.NET Core static delivery with `codebeltnet/web-cdn-origin:2.0.0` while keeping `wwwroot` as the authoring root. The deterministic runner inspects and verifies topology, publish exclusion, Static Web Assets risks, Cuemon signals, competing `AppAssetOptions`-style abstractions, actual `app-*`/`cdn-*` markup, and scheme-safe local origins; the agent performs semantic edits. For an existing Cuemon package reference, its plan resolves the highest stable version from NuGet.org at execution time, preserves Central Package Management versus inline ownership, excludes prereleases, and fails rather than copying an old fixture or example version. It reuses Cuemon `AppTagHelperOptions`/`CdnTagHelperOptions`, `BaseUrlMode`, and the public `app-link`, `app-script`, `app-img`, `cdn-link`, `cdn-script`, and `cdn-img` helpers when already available, otherwise reuses a suitable project abstraction without adding Cuemon. It keeps App and shared CDN ownership separate, preserves ordinary Project-based Development, adds opt-in segregated Development through a root Docker Compose profile, and makes `compose.assets.yml` directly build artifact-first `LocalDevelopment.Dockerfile` and `Assets.Dockerfile` images. Every generated file comes from a literal template in `assets/` and lands in one fixed location — the three Dockerfiles beside the web `.csproj`, orchestration at the repository root — and `verify --check-local` proves that placement along with the artifact-first contract: no SDK stage or `dotnet publish` inside an application image, a `.dockerignore` that still carries `artifacts/`, `LocalPublishDirectory` behind a guarded post-build target, Compose host ports derived from the ordinary Project profile, and a CI job that produces the artifact those images copy. Production CI publishes the same application artifact for the shell-less runtime `Dockerfile`. The skill excludes app-owned `wwwroot` with targeted MSBuild metadata, preserves `_content`/`_framework` and generated Static Web Assets, and proves publish/local invariants deterministically and idempotently. | | [agent-smith](skills/agent-smith/SKILL.md) | Apply a coherent, evidence-driven engineering operating model: consistency, quality, vigilance, due diligence, narrow consumer contracts, explicit failure over false success, immutable artifact promotion, and proportional automation. Includes deliberate AI capability selection and bounded orchestration. | Invoke `/agent-smith ` or use for architecture, implementation, API compatibility, testing, performance, security/DevSecOps, CI/CD, documentation, governance, skill authoring, agentic engineering, and .NET EditorConfig remediation. Local policy wins; specialized procedures load through references. | +| [skill-evaluations](skills/skill-evaluations/SKILL.md) | Run one paired skill evaluation and return the verified report. | Invoke explicitly in the codebeltnet/agentic checkout with a skill, harness, and optional model. | ### Copyable Install Commands @@ -259,6 +265,12 @@ npx skills add https://github.com/codebeltnet/agentic --skill git-remote-release npx skills add https://github.com/codebeltnet/agentic --skill git-remote-pr ``` +`git-worktree-merge` + +```bash +npx skills add https://github.com/codebeltnet/agentic --skill git-worktree-merge +``` + `dotnet-change-impact` ```bash @@ -303,6 +315,12 @@ npx skills add https://github.com/codebeltnet/agentic --skill dotnet-segregated- npx skills add https://github.com/codebeltnet/agentic --skill agent-smith ``` +`skill-evaluations` + +```bash +npx skills add https://github.com/codebeltnet/agentic --skill skill-evaluations +``` + ### Why git-visual-commits? Commit messages are the most-read documentation in any codebase — yet they're usually an afterthought. "fix stuff", "wip", "address PR feedback" tells you nothing six months later. Writing good commits takes discipline, and when you're in flow, it's the first thing that slips. @@ -311,8 +329,8 @@ Commit messages are the most-read documentation in any codebase — yet they're - **Gitmoji-first** — visual commit categories that are scannable at a glance - **Read-through-EOF lock first** — the first critical rule requires the agent to finish truncated or partial SKILL.md reads before staging or committing -- **Deterministic subject gate** — a bundled PowerShell validator blocks unapproved emoji, wrong separator spacing, uppercase description beginnings, and subjects longer than 70 characters before the plan and again before Git -- **Deterministic trailer gate** — a bundled PowerShell validator forbids `Co-authored-by` trailers by default (catching harness-injected `Claude`, `Copilot`, and `Freebuff` trailers pre-commit and post-commit) and permits them only when explicitly requested by the user and deterministically verified via `gh` as a GitHub `User` account +- **Deterministic subject gate** — a bundled .NET validator blocks unapproved emoji, wrong separator spacing, uppercase description beginnings, and subjects longer than 70 characters before the plan and again before Git +- **Deterministic trailer gate** — the same bundled .NET validator forbids `Co-authored-by` trailers by default (catching harness-injected `Claude`, `Copilot`, and `Freebuff` trailers pre-commit and post-commit) and permits them only when explicitly requested by the user and deterministically verified via `gh` as a GitHub `User` account - **Emoji-first by default** — the normal subject shape is ` `, not ` : ...` - **Conventional-prefix combo is opt-in** — `init`, `content`, `style`, `fix`, `refactor`, and `docs` are available only when you explicitly ask to combine emoji with conventional-commit prefixes - **Three identity modes** — bot, human, or collaborative — the agent does the work either way, you choose who gets credit @@ -384,7 +402,9 @@ The skill establishes each outcome's identity, scope, before/after state, and su - **Keep a Changelog first** — writes `Added`, `Changed`, `Deprecated`, `Removed`, `Fixed`, and `Security` sections in the expected style - **Full-commit context** — reads complete commit messages and the net diff before writing - **History is evidence, result is truth** — reduces the selected range to surviving base-to-`HEAD` outcomes before section classification, so reverted work disappears and one surviving capability is described once -- **Unreleased draft rewrites** — if a version-branch heading already exists but its tag does not, the skill regenerates that draft from git truth so new-capability refinements stay under `Added` until release +- **Unreleased draft rewrites** — if a version-branch heading already exists and the version is not published, the skill regenerates that draft from git truth so new-capability refinements stay under `Added` until release +- **Corrective release continuation** — a tag identifies a revision, not a publication. When a planned version was merged or tagged but conclusively never distributed, the resolver covers the original work and the corrections together, without retagging first. Publication evidence covers every distribution channel of the repository; failed lookups never count as absence, and published, unknown, or contradictory evidence leaves the section unchanged, also in yolo/auto mode +- **Offline by default** — ordinary changelog runs never contact a provider; the GitHub Releases check runs only when publication status decides the scope - **Deterministic release isolation** — resolves the real comparison branch, excludes its merge boundary, and verifies that no commit already on the base branch can bleed into the new release - **PR-complete history** — keeps every branch-unique commit from every contributor while avoiding a same-name feature tracking ref as the comparison base - **Cumulative dependency coverage** — when version manifests changed across the release range, diffs them from base to `HEAD` so the changelog reflects the surviving package/version story instead of only per-commit fragments @@ -634,7 +654,7 @@ Most repositories start with `git init` followed by committing everything direct ### Why git-remote-pr? -**git-remote-pr** prepares a reviewable pull request from every committed change between the resolved base branch and the current head. It inventories commits, changed paths, renames, binaries, and the final patch, then collapses that evidence into a concise opening paragraph followed by bold thematic headings with trailing colons and compact bullets. Related helpers, validation cases, references, formatting changes, and assets become shared reviewer-facing outcomes; complete internal file coverage does not require a prose inventory. The planner rejects malformed default bodies before preview: exactly one opening paragraph, bold colon-ended themes, dash bullets under every theme, and no concluding summary. A deterministic approval ID binds the complete prepared write intent plus the SHA-256 hash of the complete preview with only its two generated approval-ID fields normalized to `{{APPROVAL_ID}}`. A separate SHA-256 hash checks the exact final `preview.md`, including its approval instruction; changing that hash cannot authorize altered preview text. Normal mode requires `approve APR-...` for that preview; generic approval cannot execute or regenerate it. Same-request `yolo`/`auto` still shows the preview but treats that approval phrase as status only, continuing without asking for or waiting on another reply. State drift permanently invalidates the transaction and preserves its artifacts. Only an explicit refresh request starts fresh preparation in a new workspace with a new approval ID. Repository templates retain precedence. It uses `git` and `gh` without GitHub Copilot or browser assistance. +**git-remote-pr** prepares a reviewable pull request from every committed change between the resolved base branch and the current head. It inventories commits, changed paths, renames, binaries, and the final patch, then collapses that evidence into a concise opening paragraph followed by bold thematic headings with trailing colons and compact bullets. Related helpers, validation cases, references, formatting changes, and assets become shared reviewer-facing outcomes; complete internal file coverage does not require a prose inventory. The planner rejects malformed default bodies before preview: exactly one opening paragraph, bold colon-ended themes, dash bullets under every theme, and no concluding summary. A deterministic approval ID binds the complete prepared write intent plus the SHA-256 hash of the complete preview with only its two generated approval-ID fields normalized to `{{APPROVAL_ID}}`. A separate SHA-256 hash checks the exact final `preview.md`, including its approval instruction; changing that hash cannot authorize altered preview text. Normal mode requires `approve APR-...` for that preview; generic approval cannot execute or regenerate it. Same-request `yolo`/`auto` still shows the preview but treats that approval phrase as status only, continuing without asking for or waiting on another reply. State drift permanently invalidates the transaction and preserves its artifacts. Only an explicit refresh request starts fresh preparation in a new workspace with a new approval ID. Repository templates retain precedence. It uses `git`, `gh`, and one bundled .NET file-based app (.NET 10 SDK or newer), which reports progress on stderr and keeps stdout for results. It needs no GitHub Copilot or browser assistance. Normal requests stop after showing the proposed title, reviewer-oriented description summary, assignee, push requirement, and exact remote writes. A `yolo` or `auto` attached to the same PR request still shows that preview, but it does not ask for or wait on `approve APR-...`; it proceeds immediately with the just-presented plan. Existing open PRs are refreshed from the current complete changeset, and the coverage checks still require every changed file to map to a theme represented in the body even when many files collapse into a few sections. Execution refuses plans whose approved title, ready/draft state, body, evidence, or repository snapshot changed after approval. Post-write checks verify the title, body, draft state, assignment, head SHA, and GitHub file inventory. A branch that has never been pushed needs no preliminary tracking setup: preparation compares local HEAD against the base and previews a normal push to GitHub origin (or the sole GitHub remote) under the current branch name, including upstream tracking. Same-request `create yolo` executes that publication and PR creation without another reply. Dirty worktrees, ambiguous publication remotes, incomplete tracking, renamed-branch tracking mismatches, and divergent remote branches still block the workflow. Commit creation remains a separate `git-visual-commits` request; release-note writing remains `git-remote-release`. @@ -644,7 +664,7 @@ Writing release notes is tedious. Raw commit logs are too noisy, PR titles often **git-remote-release** reads all commits and pull requests between two tags or branches in a remote GitHub repository and produces a polished, paste-ready release note. -Its bundled Python collector uses authenticated `gh` REST reads and read-only GraphQL queries to expand squash merges into original PR commits, resolve co-author accounts (keeping `Co-authored-by` trailers only when GitHub resolves them to a verified `User` account and dropping unmapped or `Bot` trailers such as `Claude`, `Freebuff`, and `Copilot`), verify commit and file counts, and generate source lines with every verified contributor. Draft verification rejects missing contributors, incomplete evidence, malformed `This release ...` openings, missing highlight bullets, punctuation-only highlights, plain blockquotes or unsupported alert markers after the summary, and em dashes in authored release-note prose while still preserving exact source titles. The model writes the summary from the final file changes and original commit messages, then checks that it covers the meaningful changes. Newcomer discovery includes verified GitHub `User` accounts from PRs, original commits, and verified `User` co-author mappings, comparing against complete prior history including original squash PR commits for later releases. For tagged releases, GitHub's generate-notes response can supplement collection through `--generated-notes`; an omitted account does not override verified history. The collector validates newcomer PR membership and exact API identities, and the verifier checks recognition placement and completeness. Generation uses GitHub's non-persisting POST endpoint and never publishes a release. `--initial-release` collects all reachable commits and the final tree without inventing a comparison base. Collection and source verification are deterministic and never invoke a model. +Its bundled .NET collector uses authenticated `gh` REST reads and read-only GraphQL queries to expand squash merges into original PR commits, resolve co-author accounts (keeping `Co-authored-by` trailers only when GitHub resolves them to a verified `User` account and dropping unmapped or `Bot` trailers such as `Claude`, `Freebuff`, and `Copilot`), verify commit and file counts, and generate source lines with every verified contributor. Draft verification rejects missing contributors, incomplete evidence, malformed `This release ...` openings, missing highlight bullets, punctuation-only highlights, plain blockquotes or unsupported alert markers after the summary, and em dashes in authored release-note prose while still preserving exact source titles. The model writes the summary from the final file changes and original commit messages, then checks that it covers the meaningful changes. Newcomer discovery includes verified GitHub `User` accounts from PRs, original commits, and verified `User` co-author mappings, comparing against complete prior history including original squash PR commits for later releases. For tagged releases, GitHub's generate-notes response can supplement collection through `--generated-notes`; an omitted account does not override verified history. The collector validates newcomer PR membership and exact API identities, and the verifier checks recognition placement and completeness. Generation uses GitHub's non-persisting POST endpoint and never publishes a release. `--initial-release` collects all reachable commits and the final tree without inventing a comparison base. Collection and source verification are deterministic and never invoke a model. - **Remote-first workflow** that works entirely through GitHub's API, with no local clone required, - **Compare URL awareness** where a pasted GitHub compare URL is used to extract the owner, repository, and both tags, @@ -662,6 +682,14 @@ Its bundled Python collector uses authenticated `gh` REST reads and read-only Gr - **No invented claims** so every statement in the summary is backed by the commits and pull requests collected, - **Read-only operation** that never mutates repository state. +### Why git-worktree-merge? + +Use `/git-worktree-merge agent/refactoring`, a workspace or session name, or a request such as “merge all completed agents’ changes.” The skill covers the contribution lifecycle from discovering the worktrees and verifying readiness through resolving conflicts, validating combined behavior, and retiring eligible resources. It probes the available host capabilities before falling back to Git and can contact independently launched owners directly for a validated commit handoff. The optional .NET verifier checks exact tips, worktree state, ancestry, and Git cleanup conditions. Unrelated local changes block cleanup even when the requested changes have merged successfully. + +The skill relays scoped local commit approval when the owning worktree's rules allow it. If an older checkout requires direct approval, it checks the governance difference and identifies the exact owner and commit that need approval. Source readiness can advance in a separate checkout while the integration checkout is busy. Before each target write, it requires a current single-writer window and a fresh Git snapshot. A scoped merge leaves other deliveries and their worktrees intact. + +The deterministic Worktrees suite creates real temporary repositories and worktrees. Its simulated workspace runtime records actual catalog, guide, lookup, status, messaging, monitoring, and retirement calls. Portable eval cases use those action logs and the resulting Git state to assess coordination, commit approval, exclusive integration windows, and mixed deliveries. + ### Why dotnet-change-impact? Picking the wrong version number is one of the easiest ways to break downstream consumers. A "bug fix" that quietly changes exception behavior, an "innocent" new overload that makes existing calls ambiguous, or a dependency bump that drops a target framework — any of these can be a breaking change shipped as a patch. Conversely, teams sometimes panic and burn a major version on a purely internal refactor. **dotnet-change-impact** brings Microsoft's official .NET compatibility model to that decision. @@ -681,7 +709,7 @@ Picking the wrong version number is one of the easiest ways to break downstream Dependency updates look simple until a repository encodes compatibility in its package graph. A `Directory.Packages.props` file can pin the same package differently for `net9` and `net10`, hold a package back with an inline comment because a newer release dropped a target framework, or mix stable and prerelease intent on purpose. A shallow “latest package wins” pass breaks those repos quietly. -**dotnet-nuget-update** makes the complete audit the first-class artifact. It enumerates every declaration before editing, keeps `current + auto + approval + unresolved == declared` as a hard invariant, resolves versions from a live or offline flat-container feed with per-process memoization, and preserves XML comments, spacing, encoding, and line endings when it writes changes back. +**dotnet-nuget-update** makes the complete audit the first-class artifact. It enumerates every declaration before editing, keeps `current + auto + approval + unresolved == declared` as a hard invariant, resolves versions from a live or offline flat-container feed, reading each package once and several at a time, and preserves XML comments, spacing, encoding, and line endings when it writes changes back. - **Complete graph first** — every `` declaration, and explicit project-level `PackageReference` when CPM is absent, becomes an audit row before any update is applied, - **TFM-band aware** — a package pinned under `net9` or `net10` stays inside that matching major when the pinned major itself is the compatibility signal, while mismatched majors remain free to move, @@ -689,16 +717,18 @@ Dependency updates look simple until a repository encodes compatibility in its p - **History-first notes** — adjacent XML comments surface as `note` fields, and note-bearing auto updates are explicitly marked `READ THE NOTE before applying`, - **Normal and yolo modes** — normal mode batches majors into one approval decision after the full audit, while yolo mode applies only the safe classes and reports held majors without asking, - **Structural edits only** — version updates touch only the targeted attribute or element and leave comments, blank lines, unrelated files, and existing line endings intact, -- **Offline-testable** — the bundled scripts accept filesystem flat-container fixtures so audit, comparison, and update logic can be regression-tested without network dependency. +- **Offline-testable** — the bundled .NET tool accepts filesystem flat-container fixtures, so its black-box tests check audit, comparison, and update logic without network access. ### Why dotnet-docfx-digest? A bare invocation audits and repairs public API documentation across the repository. An explicit target limits the work to its affected pages. Host re-entry resumes the active audit. - `dotnet-docfx-digest repair` inspects existing examples, including green builds with no review comments. It uses project packets to reconcile diagnostics, changes, findings and missing or stale behavioral evidence. -- `dotnet-docfx-digest csrun` (alias `generate-run-actions`) preserves consumer scenarios during conversion and generates synchronized execution assets. +- `dotnet-docfx-digest csrun` (alias `generate-run-actions`) preserves consumer scenarios during conversion and generates synchronized execution assets. Their source is committed, the run scripts are created at DocFX build time, and broken recipes or an incomplete delivery are reported separately from leftover scratch files. - `dotnet-docfx-digest repair csrun` (also `csrun repair`) discovers and repairs examples, regenerates affected assets, verifies supported transports independently and runs the documentation gates in one invocation. +Moderate and large repositories are handled in small packets. `docfx.cs --next-packet` persists each packet's behavioral evidence, reconciles the ledger against the live inventory (retaining still-valid execution and transport captures across prose-only edits while reopening invalidated examples), and continues until actionable work drains. Scoped checks run during packet processing while `commands.finalGate` is withheld until `final-gate` or `blocked`. An interrupted run resumes where it stopped, a blocked example does not hold up independent work, a blocker may be reported only after two distinct failed recovery attempts and final verification against the current files confirm `nextAction.stopAllowed`, and any post-verification edit or newly discovered defect returns to the queue before completion can be claimed. + The [skill entry point](skills/dotnet-docfx-digest/SKILL.md) routes each operation to its authoring, repair, example design, execution or script reference. Behavioral review compares observations with source-backed expectations established before execution. A distinct final pass checks modified examples for introduced defects and verifies that they still demonstrate recommended consumer usage. ### Why dotnet-test? @@ -709,7 +739,7 @@ The skill has one job: the test host comes from Codebelt, not from Microsoft, an **dotnet-test** begins with machine-readable inspection, then chooses the Codebelt pattern that matches the selected project's role and ownership model. Because that inspection already answers which project, role, and ownership apply, the skill acts on the evidence instead of asking the developer to retype what the JSON says. It preserves package ownership and frameworks, migrates xUnit v2 to v3/Microsoft Testing Platform when needed, and makes the chosen focused/shared web or application pattern, entrypoint-owned managed fixture, zero remaining selected `WebApplicationFactory` usages, zero deprecated blocking fixtures, zero replacement composition roots, and restore/build/test explicit gates. -The hardest failure to catch is the migration that only looks like one. Wrapping `WebApplicationFactory` in a private nested class, renaming a constructor to a static `Create`, or bumping package pins all produce a substantial diff while Microsoft's host still starts the application and every test stays green. `verify-dotnet-test-migration.ps1` closes the run with a verdict instead of a self-assessment: it re-checks the expected pattern and adds the post-edit checks for a surviving factory base type, a retained `Microsoft.AspNetCore.Mvc.Testing` reference, `xunit*` pins past the major the restored Codebelt package declares, and files changed under the project while the target pattern appears nowhere in it. +The hardest failure to catch is the migration that only looks like one. Wrapping `WebApplicationFactory` in a private nested class, renaming a constructor to a static `Create`, or bumping package pins all produce a substantial diff while Microsoft's host still starts the application and every test stays green. `dotnet-test.cs -- verify` closes the run with a verdict instead of a self-assessment: it re-checks the expected pattern and adds the post-edit checks for a surviving factory base type, a retained `Microsoft.AspNetCore.Mvc.Testing` reference, `xunit*` pins past the major the restored Codebelt package declares, and files changed under the project while the target pattern appears nowhere in it. - **Evidence before questions** — the bundled inspector resolves project, role, mode, host ownership, and package owner, so a bare invocation starts working instead of returning a capability menu, - **Managed-fixture version floor** — inspection flags a Codebelt xUnit package pinned below 11.1.0, where the managed fixtures do not exist yet, before the pattern is written rather than after it fails to compile, @@ -771,7 +801,7 @@ Cross-platform .NET developers usually get Linux test feedback the slow way: pus - **Timing you can trust** — reports test duration and total wall clock separately, so a fast suite behind a slow image pull is never presented as an instant run - **No plumbing added, ever** — never generates a `Dockerfile`, dev container, compose file, or editor configuration (an existing configured `dockerFile` is honored, never created), never runs privileged containers or mounts the Docker socket, and always cleans up transient Docker resources — reporting exact identifiers if any remain - **Target-framework aware** — inspects the projects and `global.json`, refuses to pick an SDK that cannot build the requested target framework, and reports incompatibilities instead of editing the repository to force them -- **Deterministic and tested** — the runner ships a comprehensive built-in `--self-test` plus a PowerShell harness covering configuration discovery, release parsing, environment selection (including unattended target-framework selection and the cases that must still ask), unsupported handling, image resolution, command planning, result parsing, failure classification, cancellation, and cleanup +- **Deterministic and tested** — the runner ships a comprehensive built-in `--self-test` plus a .NET regression harness covering configuration discovery, release parsing, environment selection (including unattended target-framework selection and the cases that must still ask), unsupported handling, image resolution, command planning, result parsing, failure classification, cancellation, and cleanup ### Why dotnet-segregated-assets? `wwwroot` is where every ASP.NET Core developer expects to author static files — editors, hot reload, and the SDK all assume it. But shipping those files inside the deployed web application couples static delivery to business logic, bloats the app artifact, and puts asset caching on the wrong surface. The right shape is architectural: keep authoring in `wwwroot`, but let a separate, hardened static-content host serve the files in production. @@ -800,7 +830,7 @@ Cross-platform .NET developers usually get Linux test feedback the slow way: pus - **Current packages, resolved deterministically** — when a real Cuemon package reference already exists, `plan` discovers NuGet's V3 package endpoint, selects the highest stable version, emits the exact version and source, preserves `Directory.Packages.props` ownership when CPM is active, and fails closed instead of recycling an old literal - **Uses the existing asset model** — when Cuemon is detected from package/project references, namespace imports, options, `_ViewImports.cshtml`, or actual custom-element markup, it migrates App/CDN ownership to the public `app-*`/`cdn-*` helpers, uses `BaseUrlMode` for Automatic App resolution versus explicitly Configured CDN locations, and removes a redundant `AppAssetOptions`-style abstraction only after its consumers are gone - **Reports, never rewrites** — the runner exposes Cuemon, competing-abstraction, legacy-syntax, and cache-busting interface/registration evidence for the agent to act on; it never rewrites Razor or C# source and never creates a live-model evaluation workflow -- **Idempotent and deterministic** — re-running reconciles existing segregation instead of duplicating MSBuild items, launch profiles, Compose services, or Dockerfiles, and the runner ships a built-in `--self-test` plus a PowerShell harness +- **Idempotent and deterministic** — re-running reconciles existing segregation instead of duplicating MSBuild items, launch profiles, Compose services, or Dockerfiles, and the runner ships a built-in `--self-test` plus a .NET regression harness - **Fail-closed verification and planning** — local verification requires both the matching HTTP launch profile and origin Compose service, generated-asset risks override existing-segregation detection, and a no-`wwwroot` project can still produce CDN-only work when a shared equivalent exists ### Why agent-smith? @@ -813,6 +843,7 @@ Cross-platform .NET developers usually get Linux test feedback the slow way: pus - **Distinct delivery lifecycles:** Package and Application guidance separates PR validation, immutable release artifacts, and application deployment. Deployments consume the same artifact without rebuilding. Greenfield branching defaults to scaled trunk-based development where policy is silent. - **Proportional automation:** use a sufficient native command, PowerShell 7 for small focused scripts, and C#/.NET where substantial reusable automation benefits from structure, testing, cancellation, and diagnostics. Local conventions and host constraints remain authoritative. - **Deliberate agentic engineering:** select the least expensive adequate capability, escalate with uncertainty and consequence, map dependencies before delegation, bound independent work, serialize shared mutations, and measure total value. Guidance never authorizes unrequested model calls or evaluations. +- **Minimal repository documentation:** `README.md`, `AGENTS.md`, `CHANGELOG.md`, and `LICENSE` are the default; anything more needs a demonstrated need, and a new documentation hierarchy needs maintainer approval. Plans, investigations, and handover records stay in an ignored `.bot/` workspace or external temporary storage, and established documentation structures are respected. Let the repository earn its complexity. - **Preserved specialist safeguards:** .NET conformance and Roslyn recovery remain fail-closed, scoped, and read-only during formatter discovery and verification. Detailed procedures live in required references; missing guidance blocks improvisation. - **Honest evidence and natural writing:** concise, precise prose preserves grammar, validation limits, compatibility impact, and material risks. Progressive disclosure keeps the entry point focused; focused deterministic checks and decision-oriented eval specifications cover the operating model without claiming measured model behavior. diff --git a/scripts/Get-HarnessModels.ps1 b/scripts/Get-HarnessModels.ps1 index 3c6cb957..838a0b4c 100644 --- a/scripts/Get-HarnessModels.ps1 +++ b/scripts/Get-HarnessModels.ps1 @@ -336,6 +336,29 @@ function Get-OpenCodeModels { if ($null -eq $command) { throw 'OpenCode CLI executable is not available on PATH.' } + $version = Invoke-JsonCommand -CommandInfo $command -Arguments @('--version') + if (Test-OpenCodeV2Version -Version $version.Stdout) { + if ($Refresh) { throw 'OpenCode v2 model discovery has no explicit refresh flag. Retry without -Refresh.' } + $list = Invoke-JsonCommand -CommandInfo $command -Arguments @('models') -TimeoutSeconds 60 + $catalog = Invoke-JsonCommand -CommandInfo $command -Arguments @('api', 'model.list') -TimeoutSeconds 60 + $bySelector = [Collections.Generic.Dictionary[string, object]]::new([StringComparer]::Ordinal) + foreach ($model in @(($catalog.Stdout | ConvertFrom-Json).data)) { + $bySelector["$($model.providerID)/$($model.id)"] = $model + } + foreach ($line in ($list.Stdout -split "`r?`n")) { + $selector = $line.Trim() + if ($selector -cnotmatch '^[^\s/#]+/[^\s#]+$') { continue } + $model = if ($bySelector.ContainsKey($selector)) { $bySelector[$selector] } else { @{ id = $selector } } + ConvertTo-ModelChoice -Model $model -RunnerName 'opencode' -Source 'opencode models and api model.list' -ExplicitSelector $selector + foreach ($variant in @(Get-JsonProperty -Object $model -Name 'variants' -Default @())) { + $variantId = [string](Get-JsonProperty -Object $variant -Name 'id' -Default '') + if ($variantId -and "$selector#$variantId" -ceq $RequireModel) { + ConvertTo-ModelChoice -Model $model -RunnerName 'opencode' -Source 'opencode api model.list variant' -ExplicitSelector $RequireModel + } + } + } + return + } $arguments = @('models', '--verbose') if ($Refresh) { $arguments += '--refresh' } $result = Invoke-JsonCommand -CommandInfo $command -Arguments $arguments -TimeoutSeconds 180 diff --git a/scripts/agentic-tooling.ps1 b/scripts/agentic-tooling.ps1 new file mode 100644 index 00000000..a78c877f --- /dev/null +++ b/scripts/agentic-tooling.ps1 @@ -0,0 +1,74 @@ +#!/usr/bin/env pwsh +# Transitional helper (AGENTS.md X7): dot-source it and call Resolve-AgenticToolingAssembly to get the built +# agentic-tooling assembly, then run `dotnet `. It builds only when a build input changed since the +# last successful build; every orchestration responsibility lives in the .NET tool, not here. + +function Resolve-AgenticToolingAssembly { + $tooling = (Resolve-Path (Join-Path $PSScriptRoot '../tooling')).Path + $projectDirectory = Join-Path $tooling 'src/Agentic.Tooling' + $project = Join-Path $projectDirectory 'Agentic.Tooling.csproj' + $assembly = Join-Path $projectDirectory 'bin/Release/net10.0/agentic-tooling.dll' + $stamp = Join-Path $projectDirectory 'obj/validate-local.build-inputs' + + # `dotnet run` re-evaluates the project on every call, so the shim runs the built assembly and asks MSBuild to build + # only when something that can change the build differs from the last successful build: the content of every project + # input (additions, edits, deletions and renames, whatever their timestamps), the MSBuild, package and SDK + # configuration under tooling/, and the .NET host with its installed SDKs. MSBuild's own incremental build then + # decides what to recompile. + function Get-BuildInputFingerprint { + $inputs = @(Get-ChildItem -LiteralPath $projectDirectory -Recurse -File -Force | + Where-Object { [System.IO.Path]::GetRelativePath($projectDirectory, $_.FullName) -notmatch '^(bin|obj)[\\/]' }) + + @(Get-ChildItem -LiteralPath $tooling -File -Force | + Where-Object { $_.Name -match '^(Directory\.(Build|Packages)\.(props|targets)|global\.json|nuget\.config)$' }) + + @(Get-Item -LiteralPath (Join-Path $PSScriptRoot 'eval-runners/windows-owned-process.cs'), (Join-Path $PSScriptRoot 'eval-runners/eval-readiness.cs')) + $lines = [System.Collections.Generic.List[string]]::new() + foreach ($file in @($inputs | Sort-Object { [System.IO.Path]::GetRelativePath($tooling, $_.FullName) } -Culture '')) { + $lines.Add(('{0} {1}' -f ([System.IO.Path]::GetRelativePath($tooling, $file.FullName) -replace '\\', '/'), (Get-FileHash -LiteralPath $file.FullName -Algorithm SHA256).Hash)) + } + # A new, removed or different SDK can change the compiler and analyzers. Listing the host's SDK directories is + # far cheaper than `dotnet --version`; installing an unrelated SDK costs one incremental build at most. + $dotnet = (Get-Command -Name 'dotnet' -CommandType Application -ErrorAction Stop | Select-Object -First 1).Source + $resolved = [System.IO.File]::ResolveLinkTarget($dotnet, $true) + $hostPath = if ($null -ne $resolved) { $resolved.FullName } else { $dotnet } + $sdkRoot = Join-Path (Split-Path -Parent $hostPath) 'sdk' + $sdks = if (Test-Path -LiteralPath $sdkRoot) { @(Get-ChildItem -LiteralPath $sdkRoot -Directory | ForEach-Object Name | Sort-Object -Culture '') } else { @() } + $lines.Add("host $hostPath") + $lines.Add("sdks $($sdks -join ',')") + $bytes = [System.Text.Encoding]::UTF8.GetBytes(($lines -join "`n")) + return [System.Convert]::ToHexString([System.Security.Cryptography.SHA256]::HashData($bytes)) + } + + # One build at a time per tooling directory, so concurrent callers never race on bin/ and obj/. + $mutexName = 'agentic-tooling-build-' + [System.Convert]::ToHexString([System.Security.Cryptography.SHA256]::HashData([System.Text.Encoding]::UTF8.GetBytes($tooling.ToLowerInvariant())))[0..15] -join '' + $mutex = [System.Threading.Mutex]::new($false, $mutexName) + try { + try { [void]$mutex.WaitOne() } catch [System.Threading.AbandonedMutexException] { } + try { + $fingerprint = Get-BuildInputFingerprint + $previous = if (Test-Path -LiteralPath $stamp -PathType Leaf) { [System.IO.File]::ReadAllText($stamp).Trim() } else { $null } + if (-not (Test-Path -LiteralPath $assembly -PathType Leaf) -or $previous -ne $fingerprint) { + $clock = [System.Diagnostics.Stopwatch]::StartNew() + [Console]::Error.WriteLine('[START] agentic-tooling build | inputs changed since the last successful build') + $buildOutput = & dotnet build $project --configuration Release --verbosity quiet --nologo 2>&1 + if ($LASTEXITCODE -ne 0) { + $buildOutput | ForEach-Object { [Console]::Error.WriteLine([string]$_) } + [Console]::Error.WriteLine(('[FAILED] agentic-tooling build | exit {0} after {1:0.0} s' -f $LASTEXITCODE, $clock.Elapsed.TotalSeconds)) + exit $LASTEXITCODE + } + # Recorded only after success, so a failed or interrupted build is retried on the next call. + $stampDirectory = Split-Path -Parent $stamp + if (-not (Test-Path -LiteralPath $stampDirectory)) { New-Item -ItemType Directory -Path $stampDirectory -Force | Out-Null } + $pending = "$stamp.$PID.tmp" + [System.IO.File]::WriteAllText($pending, $fingerprint) + Move-Item -LiteralPath $pending -Destination $stamp -Force + [Console]::Error.WriteLine(('[COMPLETE] agentic-tooling build | {0:0.0} s' -f $clock.Elapsed.TotalSeconds)) + } + } finally { + $mutex.ReleaseMutex() + } + } finally { + $mutex.Dispose() + } + + return $assembly +} diff --git a/scripts/eval-runners/README.md b/scripts/eval-runners/README.md index dd58f4e5..bb49c78f 100644 --- a/scripts/eval-runners/README.md +++ b/scripts/eval-runners/README.md @@ -7,9 +7,13 @@ An eval can declare a `prerequisites` object in `evals/evals.json`. Omit it for - `executables` lists application names to resolve onto the controlled PATH. `probes` give an `id`, a `command` argument array starting with a declared executable, an optional `outputPattern`, and an optional `timeoutMs`. Arguments can use `{run}` for the projected run root. These are trusted repository-authored commands. Use probes for SDK versions, runtimes, service connectivity, and any required network access. - `skills` names complementary skills from this repository. The staged files are identical in both arms and their hashes are checked before execution. For a case with complementary skills the candidate sits beside them in the candidate arm, so it can resolve sibling tools without using a global skill installation. - `downloads` pins an HTTPS asset with `url`, `file`, and `sha256`. `dotnetTools` reuses a matching executable or installs the declared package and version into the isolated tool directory. `restore` defines a target `framework` and optional exact package `id` and `version` pairs for NuGet restore and deterministic `.NET` build readiness probes. -- `repository` specifies an HTTPS Git `url`, a full `commit`, and a child `directory` of the working tree. Both arms get independent detached checkouts. Preparation checks HEAD, records the fixture hash, and adds a native HEAD probe. +- `repository` specifies an HTTPS Git `url`, a full `commit`, and a child `directory` of the working tree. Both arms get independent detached checkouts. Preparation checks HEAD, records the fixture hash, and adds a HEAD probe. -The Codex App Server runs the readiness commands through `command/exec` in a disposable projection during preflight and again before the actual project's first model turn. Child shells use `inherit=none`, explicit environment values without credentials, and no login profile. A failed prerequisite reports its command, exit status, and diagnostic under `readiness`. Phase 1 lists affected eval IDs separately and keeps the existing all-arms preflight gate. OpenCode and the Codex API-key compatibility path currently fail closed when a case requires native readiness evidence. +Preparation validates declarations and hashes shared staged inputs, including run-local tools and restore projects. Phase 1 preflight verifies executable discovery, pinned tool versions, staged input hashes, and declared probe results on the execution host. The runner repeats the probes in the actual projection before the first model turn so restore and build outputs are available there. + +Codex App Server uses `command/exec` with an empty authentication home and an explicit child shell environment. Claude Code, OpenCode, and Codex CLI compatibility use runner-owned processes with the projected working directory and isolated tool environment. OpenCode and Codex CLI compatibility also apply the selected filesystem sandbox to those processes. Readiness evidence records the transport separately from native session and isolation evidence. Probes run without provider credentials, ambient shell profiles, or access paths to the grading inputs. Only repository-authored deterministic engineering commands belong in declarations. + +A readiness failure reports the prerequisite, attempted command, exit status, observed diagnostic, and remediation under `readiness`. Phase 1 identifies affected eval IDs and starts workers only after every arm passes preflight. Preparation defaults to `-SkillExposure entrypoint`. Each candidate receives its entry-point instructions and a path to its staged skill tree. The model can read supporting files selectively. `-SkillExposure full-inline` embeds referenced text resources up to `-MaxInlineBytes`. The manifest and benchmark record the exposure mode. Codex execution evidence also records successful shell commands that name supporting references and return output. Reads via tools or commands that cannot identify an individual file are unmeasured. @@ -287,7 +291,9 @@ CLI version and passes only documented environment credentials when the selected runner supports them. None copies a global skill directory, memory store, plugin set, or normal agent profile into a run. -Model discovery lives in `scripts/Get-HarnessModels.ps1`. It uses the current local harness catalog where available: Codex through `codex debug models`, and OpenCode through `opencode models --verbose`, which lists all configured providers. Claude Code has no model-free model-listing command and the Models API requires an authenticated call that preparation must not make, so Claude discovery verifies the installed CLI with `claude --version` and presents the catalog in `claude/reference.json`; that catalog is presentation data, an explicit well-formed full id is accepted verbatim, aliases are rejected, and the runner proves the executed model from the `init` event. OpenCode preserves exact `provider/model` selectors and retains free, paid, or unknown availability as metadata without filtering the selectable catalog. Interactive preparation must normalize explicit harness intent before invoking repository scripts: `Claude Code` maps to `claude`; `Codex` maps to `codex`; `OpenCode` maps to `opencode`. Codebelt Reference and Claude Code default to the `claude/reference.json` model and effort; Codex defaults to `gpt-6-luna` with high reasoning; both are validated by package preparation. OpenCode still requires a discovered `provider/model` selector from the user when none was supplied; an explicit selector is preserved verbatim and is never silently replaced. +Model discovery lives in `scripts/Get-HarnessModels.ps1`. It queries Codex through `codex debug models` and OpenCode v2 through `opencode models` and `opencode api model.list`. The v2 CLI list determines available selectors and the API supplies display names, variants, and pricing when present. Availability metadata is retained without filtering the selectable catalog. OpenCode v1 discovery uses `opencode models --verbose` and supports `-Refresh`. Claude Code verifies the installed CLI with `claude --version` and presents the catalog in `claude/reference.json`. Claude Code accepts full model IDs and proves the executed model from the `init` event. Direct package preparation requires a resolved OpenCode `provider/model` selector. The `skill-evaluations` skill can resolve an omitted OpenCode model from current availability and benchmark data. + +OpenCode v2 executes `opencode --standalone run` from the projected working directory with a private per-arm home and database. Optional reasoning effort becomes `#variant` in the CLI model selector. The runner captures structured events and reads the native session export after each successful turn to verify the exact prompt, working directory, session, model, and requested variant. It saves the export with the other execution artifacts and verifies the previous turn before sending another prompt. On Windows, the adapter resolves the npm shim's native executable to preserve the original stdin bytes. Its generated v2 config uses ordered permission rules and disables auxiliary title and compaction turns. ## Live observability diff --git a/scripts/eval-runners/apply-eval-grading.ps1 b/scripts/eval-runners/apply-eval-grading.ps1 index c7edfbd3..937e3d53 100644 --- a/scripts/eval-runners/apply-eval-grading.ps1 +++ b/scripts/eval-runners/apply-eval-grading.ps1 @@ -40,10 +40,7 @@ try { if (-not (Test-Path -LiteralPath $bridgeScript -PathType Leaf)) { throw "Package-local manifest bridge is missing at '$bridgeScript'." } - $bridgeOutput = & pwsh -NoProfile -NonInteractive -File $bridgeScript -IterationDirectory $iteration -RequireComplete 2>&1 - if ($LASTEXITCODE -ne 0) { - throw "Canonical result validation failed before grading application: $([string]::Join(' ', @($bridgeOutput | ForEach-Object { [string]$_ })))" - } + [void](Invoke-RunnerPowerShellScript -ScriptPath $bridgeScript -Arguments @('-IterationDirectory', $iteration, '-RequireComplete') -Description 'Canonical result validation before grading application' -WorkingDirectory $iteration) $gradingValidation = Assert-EvalGradingContract -IterationDirectory $iteration -GradingPath $GradingPath $records = @($gradingValidation.Records) diff --git a/scripts/eval-runners/bridge-execution-result.ps1 b/scripts/eval-runners/bridge-execution-result.ps1 index 1ec359a7..7aecb354 100644 --- a/scripts/eval-runners/bridge-execution-result.ps1 +++ b/scripts/eval-runners/bridge-execution-result.ps1 @@ -22,13 +22,21 @@ param( # Internal composition path: return the summary and propagate exceptions # to the manifest bridge without starting another PowerShell runtime. - [switch]$AsObject + [switch]$AsObject, + + # Internal composition path: the manifest bridge has already verified the + # complete execution freeze for this iteration in this same runtime and + # passes that result, so each arm does not re-walk the whole ledger. Every + # per-arm hash, provenance, and grading-preservation check still runs. + [object]$VerifiedFreeze ) $ErrorActionPreference = 'Stop' Set-StrictMode -Version Latest -. (Join-Path $PSScriptRoot 'runner-common.ps1') -. (Join-Path $PSScriptRoot 'execution-freeze.ps1') +# When the manifest bridge runs this script in-process, the same libraries are +# already loaded in the caller's scope; reparsing them for every arm costs seconds. +if (-not (Get-Command Resolve-RunContract -ErrorAction SilentlyContinue)) { . (Join-Path $PSScriptRoot 'runner-common.ps1') } +if (-not (Get-Command Assert-ExecutionFreeze -ErrorAction SilentlyContinue)) { . (Join-Path $PSScriptRoot 'execution-freeze.ps1') } $utf8NoBom = [System.Text.UTF8Encoding]::new($false) @@ -155,9 +163,16 @@ try { $evalDirectory = Split-Path -Parent $runDirectory $iterationDirectory = Split-Path -Parent $evalDirectory # The bridge is a validator of frozen evidence, never an authority that - # can bless a new raw hash. This call intentionally covers every manifest - # arm before this one-arm operation can write a canonical result. - [void](Assert-ExecutionFreeze -IterationDirectory $iterationDirectory -RequireOrchestrationState) + # can bless a new raw hash. Standalone use verifies every manifest arm + # before this one-arm operation can write a canonical result. The manifest + # bridge passes a freeze it verified moments earlier in this runtime, and + # only canonical results are written between that check and this one. + $expectedFreezePath = Get-ExecutionFreezePath -IterationDirectory $iterationDirectory + if ($null -eq $VerifiedFreeze) { + [void](Assert-ExecutionFreeze -IterationDirectory $iterationDirectory -RequireOrchestrationState) + } elseif (-not [string]::Equals([string]$VerifiedFreeze.Path, $expectedFreezePath, [System.StringComparison]::OrdinalIgnoreCase)) { + throw 'Verified execution freeze does not belong to this iteration; refusing to reuse it.' + } $executionPath = (Resolve-Path -LiteralPath $ExecutionResult -ErrorAction Stop).Path $executionResultHash = Get-Sha256HexFromFile -Path $executionPath $resultPath = [System.IO.Path]::GetFullPath($Result, (Get-Location).Path) diff --git a/scripts/eval-runners/bridge-manifest-results.ps1 b/scripts/eval-runners/bridge-manifest-results.ps1 index c689caf1..c8614d94 100644 --- a/scripts/eval-runners/bridge-manifest-results.ps1 +++ b/scripts/eval-runners/bridge-manifest-results.ps1 @@ -88,15 +88,18 @@ try { # terminal evidence; a status/path match alone cannot prove that the # canonical result reflects the current raw file. The one-arm bridge # preserves existing grading while revalidating hashes and provenance. - # A child script scope isolates each arm's variables and helpers while - # reusing the runtime. This is deterministic validation, not a worker - # session: every arm still checks the complete freeze and provenance. + # The complete freeze was verified once above, in this runtime, and the + # one-arm bridge only writes canonical results, which the freeze does not + # cover. Each arm still validates its own run contract, raw hashes, + # artifact provenance, and grading preservation. This is deterministic + # validation, not a worker session. try { $null = & $oneArmBridge ` -Run $record.RunManifestPath ` -ExecutionResult $record.ExecutionResultPath ` -Result $record.ResultPath ` - -RequireNativeDelegation:$effectiveRequireNativeDelegation -AsObject + -RequireNativeDelegation:$effectiveRequireNativeDelegation ` + -VerifiedFreeze $freezeValidation -AsObject } catch { throw "$($record.EvalName)/$($record.Configuration) bridge failed for manifest paths run='$($record.RunManifestRelative)', execution='$($record.ExecutionResultRelative)', result='$($record.ResultRelative)': $($_.Exception.Message)" } diff --git a/scripts/eval-runners/claude/reference.json b/scripts/eval-runners/claude/reference.json index 2977a10d..81e19b2d 100644 --- a/scripts/eval-runners/claude/reference.json +++ b/scripts/eval-runners/claude/reference.json @@ -3,8 +3,8 @@ "preset": "Codebelt Reference", "runner": "claude", "harness": "Claude Code", - "model": "claude-opus-5-5", - "reasoning_effort": "high", + "model": "claude-haiku-5-5", + "reasoning_effort": "medium", "reasoning_efforts": ["low", "medium", "high", "xhigh", "max"], "model_selector_pattern": "^claude-[a-z0-9][a-z0-9.-]*$", "catalog_note": "Claude Code exposes no model-free model-listing command, and the Models API requires an authenticated call that repository preparation must not make. This list is presentation data for interactive selection. Any well-formed full Claude model id is accepted verbatim; the runner verifies the actually executed model from Claude Code's own stream-json events and fails closed on any mismatch.", diff --git a/scripts/eval-runners/claude/runner.ps1 b/scripts/eval-runners/claude/runner.ps1 index 96d84d49..ee845aae 100644 --- a/scripts/eval-runners/claude/runner.ps1 +++ b/scripts/eval-runners/claude/runner.ps1 @@ -121,7 +121,7 @@ function Resolve-ClaudeInputs { throw 'preflight and execute require -Run and -Profile.' } return [pscustomobject]@{ - Run = Resolve-RunContract -RunPath $Run + Run = Resolve-RunContract -RunPath $Run -DeferStagedDependencyValidation Profile = Resolve-ExecutionProfile -ProfilePath $Profile } } @@ -233,7 +233,7 @@ function Get-ClaudeCapabilityMap { } function Get-ClaudePreflight { - param([Parameter(Mandatory = $true)][object]$Inputs) + param([Parameter(Mandatory = $true)][object]$Inputs, [switch]$Execution) $checks = [System.Collections.Generic.List[object]]::new() $reasons = [System.Collections.Generic.List[string]]::new() @@ -271,10 +271,6 @@ function Get-ClaudePreflight { } } } - if (Test-JsonProperty -Object $run.Contract -Name 'prerequisites') { - $reasons.Add('Infrastructure blocked: the Claude Code transport does not currently expose a verified model-free execution probe for declared prerequisites.') - } - $commandInfo = Resolve-ExternalCommand -Name 'claude' if ($null -eq $commandInfo) { $reasons.Add('Claude Code CLI (claude) is not available on PATH.') @@ -311,7 +307,16 @@ function Get-ClaudePreflight { $checks.Add((New-PreflightCheck -Name 'candidate_skill_boundary' -Status passed -Detail "candidate_skill_exposed=$($run.CandidateSkillExposed); --safe-mode disables every native skill, so the candidate reaches only the with_skill prompt and staged skill/ copy.")) $warnings.Add('Filesystem isolation is pragmatic: Claude Code runs with bypassPermissions inside the projection without an outer hard sandbox.') - return New-PreflightDocument -Descriptor $effectiveDescriptor -Profile $profile -Run $run -Compatible ($reasons.Count -eq 0) -Checks @($checks) -Mechanisms @('claude -p --output-format stream-json', 'runner-assigned --session-id', 'harness Claude Code login', '--safe-mode', '--setting-sources project,local', '--strict-mcp-config', 'fresh projection outside the source repository', 'claude purge of per-arm session state', 'prompt on stdin') -ResolvedCapabilities (Get-ClaudeCapabilityMap -Inputs $Inputs) -Warnings @($warnings) -Reasons @($reasons) + $readiness = @(Get-EvalStagedReadinessFailure -Run $run -VerifyFixture) + if ($readiness.Count -eq 0 -and $reasons.Count -eq 0 -and -not $Execution -and (Test-JsonProperty -Object $run.Contract -Name 'prerequisites')) { + $projection = New-ClaudeProjection -Inputs $Inputs + try { $readiness = @(Invoke-EvalProjectedReadiness -Run $projection.Run) } + finally { Remove-ClaudeProjection -Projection $projection } + } + Add-EvalReadinessFailureReasons -Readiness $readiness -Reasons $reasons + $document = New-PreflightDocument -Descriptor $effectiveDescriptor -Profile $profile -Run $run -Compatible ($reasons.Count -eq 0) -Checks @($checks) -Mechanisms @('claude -p --output-format stream-json', 'runner-assigned --session-id', 'harness Claude Code login', '--safe-mode', '--setting-sources project,local', '--strict-mcp-config', 'fresh projection outside the source repository', 'claude purge of per-arm session state', 'prompt on stdin') -ResolvedCapabilities (Get-ClaudeCapabilityMap -Inputs $Inputs) -Warnings @($warnings) -Reasons @($reasons) + if ($readiness.Count -gt 0) { $document.readiness = $readiness } + return $document } function Copy-ClaudeTree { @@ -347,9 +352,12 @@ function New-ClaudeProjection { $homeDirectory = Join-Path $root 'home' Copy-ClaudeTree -Source $Inputs.Run.WorkingDirectoryPath -Destination $repo Copy-ClaudeTree -Source $Inputs.Run.HomeDirectoryPath -Destination $homeDirectory + $dependencies = Join-Path $Inputs.Run.RunRoot 'dependencies' + if (Test-Path -LiteralPath $dependencies -PathType Container) { + Copy-ClaudeTree -Source $dependencies -Destination (Join-Path $root 'dependencies') + } $skillName = Get-ClaudeCandidateSkillName -Run $Inputs.Run - if ($null -ne $skillName) { - # Keeps the prompt's references to skill// valid; with_skill only. + if ($null -ne $skillName -and -not (Test-PathInside -BasePath $dependencies -CandidatePath $Inputs.Run.SkillDirectoryPath)) { Copy-ClaudeTree -Source $Inputs.Run.SkillDirectoryPath -Destination (Join-Path $root ([System.IO.Path]::GetRelativePath($Inputs.Run.RunRoot, $Inputs.Run.SkillDirectoryPath))) } return [pscustomobject]@{ @@ -525,7 +533,7 @@ function New-ClaudeTokenTelemetry { function Invoke-ClaudeExecute { param([Parameter(Mandatory = $true)][object]$Inputs) - $preflight = Get-ClaudePreflight -Inputs $Inputs + $preflight = Get-ClaudePreflight -Inputs $Inputs -Execution $started = [DateTime]::UtcNow $sessionId = [Guid]::NewGuid().ToString('D') $executionDescriptor = [ordered]@{} @@ -541,6 +549,10 @@ function Invoke-ClaudeExecute { $result = $null try { $projection = New-ClaudeProjection -Inputs $Inputs + $readiness = @(Invoke-EvalProjectedReadiness -Run $projection.Run) + if (@($readiness | Where-Object status -ne 'ready').Count -gt 0) { + return New-EvalReadinessFailureResult -Descriptor $executionDescriptor -Inputs $Inputs -Readiness $readiness -SessionId $sessionId -Started $started + } $environment = New-ClaudeEnvironment -Projection $projection -Inputs $Inputs $commandInfo = Resolve-ExternalCommand -Name 'claude' $utf8 = [System.Text.UTF8Encoding]::new($false) @@ -736,11 +748,12 @@ function Invoke-ClaudeExecute { $startedUtc = $firstProcess.StartedUtc $finishedUtc = $process.FinishedUtc $mechanisms = @('claude -p --output-format stream-json', 'runner-assigned --session-id', 'harness Claude Code login', '--safe-mode (no CLAUDE.md, skills, plugins, hooks, MCP, agents)', '--setting-sources project,local', '--strict-mcp-config', 'fresh projection outside the source repository', 'isolated HOME and tool environment', 'claude purge of per-arm session state', 'CLAUDE_CODE_SUBAGENT_MODEL pinned to the requested model', 'prompt on stdin', 'pragmatic process/environment isolation without hard filesystem confinement') + if ($readiness.Count -gt 0) { $evidence.readiness = $readiness } $result = New-ExecutionResult -Descriptor $executionDescriptor -Profile $Inputs.Profile -Run $Inputs.Run -Status $status -FinalResponse $finalText -FinalResponseReason $reason -StartedUtc $startedUtc.ToString('o') -FinishedUtc $finishedUtc.ToString('o') -DurationSeconds ($finishedUtc - $startedUtc).TotalSeconds -ExitStatus $exitStatus -Failure $failure -SessionId $sessionId -IsolationCapabilities (Get-ClaudeCapabilityMap -Inputs $Inputs) -IsolationMechanisms $mechanisms -ResolvedConfiguration $(if ([string]::IsNullOrWhiteSpace($initModel)) { [ordered]@{ status = 'unavailable'; reason = 'Claude Code did not emit an init event reporting the executed model.' } } else { [ordered]@{ status = 'resolved'; reason = 'Claude Code reported the executed model in its stream-json init event.'; model = $initModel; reasoning_effort = $Inputs.Profile.ReasoningEffort } }) -Telemetry $telemetry -Artifacts $artifacts -Warnings @($warnings) -Evidence $evidence -AttemptCount 1 return $result } finally { if ($null -ne $projection) { - try { Sync-ClaudeProjection -Projection $projection -LogicalRepository $Inputs.Run.WorkingDirectoryPath } + try { if ($null -ne $environment) { Sync-ClaudeProjection -Projection $projection -LogicalRepository $Inputs.Run.WorkingDirectoryPath } } finally { if ($null -ne $environment) { $purge = Invoke-ClaudeSessionPurge -Projection $projection -Environment $environment diff --git a/scripts/eval-runners/codex/runner.ps1 b/scripts/eval-runners/codex/runner.ps1 index cc74d0bf..3320fab8 100644 --- a/scripts/eval-runners/codex/runner.ps1 +++ b/scripts/eval-runners/codex/runner.ps1 @@ -87,7 +87,7 @@ function Resolve-CodexInputs { throw 'preflight and execute require -Run and -Profile.' } return [pscustomobject]@{ - Run = Resolve-RunContract -RunPath $Run + Run = Resolve-RunContract -RunPath $Run -DeferStagedDependencyValidation Profile = Resolve-ExecutionProfile -ProfilePath $Profile } } @@ -1400,8 +1400,8 @@ function Invoke-CodexAppServer { $null = & $waitForResponse $initializeRequest 'initialize' & $writeMessage ([ordered]@{ jsonrpc = '2.0'; method = 'initialized' }) - if ($ReadinessOnly -or (Test-JsonProperty -Object $Inputs.Run.Contract -Name 'prerequisites')) { - $shell = (Get-Command pwsh -CommandType Application | Select-Object -First 1).Source + if ($ReadinessOnly) { + $shell = Get-RunnerPowerShellPath $readiness = @(foreach ($probe in Get-EvalReadinessProbes -Run $Inputs.Run) { $request = [ordered]@{ id = 900 @@ -1418,15 +1418,13 @@ function Invoke-CodexAppServer { $reply = & $waitForResponse 900 "readiness probe $($probe.id)" -AllowError $observation = New-EvalReadinessObservation -Probe $probe -Response $reply } catch { - $observation = [ordered]@{ id = $probe.id; command = @($probe.command); exit_code = $null; status = 'infrastructure_blocked'; diagnostic = $_.Exception.Message } + $observation = New-EvalReadinessObservation -Probe $probe -Response @{ result = @{ stderr = $_.Exception.Message } } } $observation if ($observation.status -ne 'ready') { break } }) - if ($ReadinessOnly -or @($readiness | Where-Object status -ne 'ready').Count -gt 0) { - $readinessResult = [pscustomobject]@{ Readiness = $readiness; ProcessCleanupError = $null } - return $readinessResult - } + $readinessResult = [pscustomobject]@{ Readiness = $readiness; ProcessCleanupError = $null } + return $readinessResult } $skillsListRequestId = 2 @@ -2315,7 +2313,7 @@ function Get-CodexCapabilityMap { } function Get-CodexPreflight { - param([Parameter(Mandatory = $true)][object]$Inputs) + param([Parameter(Mandatory = $true)][object]$Inputs, [switch]$Execution) $checks = [System.Collections.Generic.List[object]]::new() $reasons = [System.Collections.Generic.List[string]]::new() @@ -2496,38 +2494,23 @@ function Get-CodexPreflight { foreach ($mechanism in @('--ask-for-approval never', 'codex exec --ephemeral compatibility transport', '--strict-config', '--ignore-user-config', '--ignore-rules', '--sandbox danger-full-access', 'shell_environment_policy.inherit=none', 'session skills.include_instructions=false', 'session skills.bundled.enabled=false', 'session skills.config ambient path disables', 'pre-turn debug prompt-input native-skill suppression proof', 'pre-turn skills/list ambient-state verification', 'isolated CODEX_HOME', 'prompt on stdin', 'no session continuation')) { $mechanisms.Add($mechanism) } } if ($hardConfinement) { $mechanisms.Add("external $sandboxName filesystem sandbox") } else { $mechanisms.Add('pragmatic process/environment isolation without hard filesystem confinement') } - if ($reasons.Count -eq 0 -and (Test-JsonProperty -Object $run.Contract -Name 'prerequisites')) { - if ($auth.Kind -eq 'subscription_file') { - $projection = New-CodexExecutionProjection -Inputs $Inputs - $probeRun = $null - try { - $projectedInputs = [pscustomobject]@{ Run = $projection.Run; Profile = $profile } - $probeRun = Invoke-CodexAppServer -CommandInfo $commandInfo -Inputs $projectedInputs -Auth $auth -ReadinessOnly -TimeoutSeconds 85 - $processCleanupError = Get-JsonProperty -Object $probeRun -Name 'ProcessCleanupError' - if ($processCleanupError) { throw $processCleanupError } - $readiness = @(Get-JsonProperty -Object $probeRun -Name 'Readiness' -Default @()) - } finally { - if (-not (Get-JsonProperty -Object $probeRun -Name 'ProcessCleanupError')) { - $cleanupWarning = Remove-CodexExecutionProjection -Projection $projection - if ($cleanupWarning) { $warnings.Add($cleanupWarning) } - } else { - [Console]::Error.WriteLine("Retained projection '$($projection.Root)' because process exit was not observed.") - } - } - if ($readiness.Count -eq 0) { - $probeFailure = [string](Get-JsonProperty -Object $probeRun -Name 'TransportFailure' -Default '') - if ($probeFailure) { - $readiness = @(@{ id = 'native-command-transport'; command = @('command/exec'); exit_code = $null; status = 'infrastructure_blocked'; diagnostic = $probeFailure }) - } + $readiness = @(Get-EvalStagedReadinessFailure -Run $run -VerifyFixture) + if ($readiness.Count -eq 0 -and $reasons.Count -eq 0 -and -not $Execution -and (Test-JsonProperty -Object $run.Contract -Name 'prerequisites')) { + $projection = New-CodexExecutionProjection -Inputs $Inputs + $probeState = @{ CleanupError = $null } + try { + $projectedInputs = [pscustomobject]@{ Run = $projection.Run; Profile = $profile } + $readiness = @(Invoke-CodexReadiness -Inputs $projectedInputs -CommandInfo $commandInfo -Auth $auth -Sandbox $(if ($hardConfinement) { $sandboxInfo }) -ProcessState $probeState) + } finally { + if (-not $probeState.CleanupError) { + $cleanupWarning = Remove-CodexExecutionProjection -Projection $projection + if ($cleanupWarning) { $warnings.Add($cleanupWarning) } + } else { + [Console]::Error.WriteLine("Retained projection '$($projection.Root)' because process exit was not observed.") } } - if ($readiness.Count -eq 0) { - $readiness = @(@{ id = 'native-command-transport'; command = @('command/exec'); exit_code = $null; status = 'infrastructure_blocked'; diagnostic = 'Declare prerequisites with a supported Codex App Server transport. Runner availability does not prove shell readiness.' }) - } - foreach ($observation in $readiness) { - if ($observation.status -ne 'ready') { $reasons.Add("Infrastructure blocked at '$($observation.id)': $($observation.diagnostic)") } - } } + Add-EvalReadinessFailureReasons -Readiness $readiness -Reasons $reasons $document = New-PreflightDocument -Descriptor $descriptorCopy -Profile $profile -Run $run -Compatible ($reasons.Count -eq 0) -Checks @($checks) -Mechanisms @($mechanisms) -ResolvedCapabilities $capabilities -Warnings @($warnings) -Reasons @($reasons) if ($readiness.Count -gt 0) { $document.readiness = $readiness } if ($null -ne $nativeWorkerObservation -and $nativeWorkerObservation.Available) { @@ -2546,6 +2529,27 @@ function Get-CodexPreflight { return $document } +function Invoke-CodexReadiness { + param($Inputs, $CommandInfo, $Auth, $Sandbox, [hashtable]$ProcessState) + + if (-not (Test-JsonProperty -Object $Inputs.Run.Contract -Name 'prerequisites')) { return } + if ($Auth.Kind -eq 'subscription_file') { + $stagedFailure = Get-EvalStagedReadinessFailure -Run $Inputs.Run + if ($null -ne $stagedFailure) { return $stagedFailure } + # An empty CODEX_HOME keeps authentication out of the model-free App Server. + $probe = Invoke-CodexAppServer -CommandInfo $CommandInfo -Inputs $Inputs -Auth $Auth -ReadinessOnly -TimeoutSeconds (Get-EvalReadinessTimeoutSeconds) + $ProcessState.CleanupError = Get-JsonProperty -Object $probe -Name 'ProcessCleanupError' + if ($ProcessState.CleanupError) { throw $ProcessState.CleanupError } + $checks = @(Get-JsonProperty -Object $probe -Name 'Readiness' -Default @()) + if ($checks.Count -gt 0) { return $checks } + $failure = Get-JsonProperty -Object $probe -Name 'TransportFailure' + return New-EvalReadinessObservation -Probe @{ id = 'native-command-transport'; command = @('command/exec') } -Response @{ result = @{ stderr = $failure } } + } + + $profilePath = if ($Sandbox -and $IsMacOS) { New-CodexMacosSandboxProfile -Inputs $Inputs -CommandInfo $CommandInfo } + Invoke-EvalProjectedReadiness -Run $Inputs.Run -Sandbox $Sandbox -SandboxCommand $CommandInfo -SandboxProfile $profilePath +} + function New-CodexEnvironment { param( [Parameter(Mandatory = $true)][object]$Inputs, @@ -2697,10 +2701,16 @@ function Invoke-CodexProjectedTransport { $projectionCleanup = [ordered]@{ status = 'pending'; diagnostic = $null } $captureArtifacts = [System.Collections.Generic.List[object]]::new() $evidenceSynced = $false + $readinessBlocked = $false if ($env:AGENTIC_RUNNER_PROGRESS -eq '1') { [Console]::Error.WriteLine("Codex execution projection: '$($projection.Root)'.") } try { + $readiness = @(Invoke-CodexReadiness -Inputs $executionInputs -CommandInfo $CommandInfo -Auth $Auth -Sandbox $(if ($HardFilesystem) { $SandboxInfo }) -ProcessState @{}) + if (@($readiness | Where-Object status -ne 'ready').Count -gt 0) { + $readinessBlocked = $true + return [pscustomobject]@{ Readiness = $readiness } + } $physicalLastResponsePath = Join-Path $projection.Root ($LastResponseRelativePath -replace '/', [System.IO.Path]::DirectorySeparatorChar) New-Item -ItemType Directory -Path (Split-Path -Parent $physicalLastResponsePath) -Force | Out-Null $environment = if ($Auth.Kind -eq 'environment') { New-CodexEnvironment -Inputs $executionInputs -Auth $Auth } else { $null } @@ -2794,6 +2804,7 @@ function Invoke-CodexProjectedTransport { $evidenceSynced = $true return [pscustomobject]@{ Process = $process + Readiness = $readiness ProjectedFinalResponse = $projectedFinalResponse ExecutionPaths = [ordered]@{ projection = 'physical_temp_outside_logical_package' @@ -2811,7 +2822,7 @@ function Invoke-CodexProjectedTransport { CaptureArtifacts = $captureArtifacts.ToArray() } } finally { - if ($evidenceSynced) { + if ($evidenceSynced -or $readinessBlocked) { $projectionCleanup.diagnostic = Remove-CodexExecutionProjection -Projection $projection $projectionCleanup.status = if ($projectionCleanup.diagnostic) { 'retained' } else { 'removed' } } else { @@ -2825,7 +2836,7 @@ function Invoke-CodexProjectedTransport { function Invoke-CodexExecute { param([Parameter(Mandatory = $true)][object]$Inputs) - $preflight = Get-CodexPreflight -Inputs $Inputs + $preflight = Get-CodexPreflight -Inputs $Inputs -Execution $started = [DateTime]::UtcNow $sessionId = [Guid]::NewGuid().ToString('D') $executionDescriptor = [ordered]@{} @@ -2848,10 +2859,9 @@ function Invoke-CodexExecute { $protocolObservations = Get-JsonProperty -Object $preflight -Name 'protocol_observations' -Default $null $supportsProviderModelFallback = [bool](Get-JsonProperty -Object $protocolObservations -Name 'allow_provider_model_fallback' -Default $false) $transport = Invoke-CodexProjectedTransport -CommandInfo $commandInfo -Inputs $Inputs -Auth $auth -Platform $platform -SandboxInfo $sandboxInfo -HardFilesystem $hardFilesystem -VisiblePlatform $visiblePlatform -LastResponseRelativePath $lastResponsePath -SupportsProviderModelFallback $supportsProviderModelFallback - $runtimeReadiness = @(Get-JsonProperty -Object $transport.Process -Name 'Readiness' -Default @()) + $runtimeReadiness = @(Get-JsonProperty -Object $transport -Name 'Readiness' -Default @()) if (@($runtimeReadiness | Where-Object status -ne 'ready').Count -gt 0) { - $timestamp = [DateTime]::UtcNow.ToString('o') - return New-ExecutionResult -Descriptor $executionDescriptor -Profile $Inputs.Profile -Run $Inputs.Run -Status incompatible -FinalResponseReason 'infrastructure_blocked' -StartedUtc $started.ToString('o') -FinishedUtc $timestamp -Failure (New-ExecutionFailure -Code 'infrastructure_blocked' -Message 'A declared prerequisite failed in the execution projection before the first model turn.') -SessionId $sessionId -IsolationCapabilities ([ordered]@{}) -IsolationMechanisms @('preflight-only') -Evidence ([ordered]@{ readiness = $runtimeReadiness; resume = $false }) -AttemptCount 1 + return New-EvalReadinessFailureResult -Descriptor $executionDescriptor -Inputs $Inputs -Readiness $runtimeReadiness -SessionId $sessionId -Started $started } $process = $transport.Process $artifacts = [System.Collections.Generic.List[object]]::new() diff --git a/scripts/eval-runners/eval-readiness.cs b/scripts/eval-runners/eval-readiness.cs new file mode 100644 index 00000000..f711ff1f --- /dev/null +++ b/scripts/eval-runners/eval-readiness.cs @@ -0,0 +1,523 @@ +#nullable disable +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; + +namespace Agentic.Evals +{ + // Prerequisite readiness for prepared eval packages. Packages contain no SDK project, so process-ownership.ps1 + // compiles this file on the execution host; tooling/ compiles the same file for its deterministic tests. + public static class EvalReadiness + { + private const int DefaultTimeoutMs = 10000; + private const int BuiltInTimeoutMs = 8000; + private const int GraceMs = 5000; + private const int DiagnosticLimit = 2000; + private const RegexOptions IgnoreCase = RegexOptions.IgnoreCase | RegexOptions.CultureInvariant; + + // The probe runs in the shell that the worker will use, so it is written in that shell's language. + // PowerShell uses the Unix temp API, which reads TMPDIR, and the Windows temp API, which reads TMP/TEMP. + // All three point to the same directory. + private const string EnvironmentCheck = @"$expected = @{ ENVIRONMENT_PAIRS } +foreach ($name in $expected.Keys) { + if ([Environment]::GetEnvironmentVariable($name) -cne $expected[$name]) { throw ""Missing or unexpected environment value: $name"" } +} +foreach ($name in 'OPENAI_API_KEY', 'CODEX_API_KEY', 'ANTHROPIC_API_KEY', 'GH_TOKEN', 'GITHUB_TOKEN', 'CODEX_HOME', 'NODE_PATH') { + if ([Environment]::GetEnvironmentVariable($name)) { throw ""Unexpected shell variable: $name"" } +} +foreach ($path in ($env:PATH -split [IO.Path]::PathSeparator)) { + if (-not [IO.Path]::IsPathFullyQualified($path)) { throw ""PATH contains a relative or empty entry: $path"" } +} +if ($IsWindows -and @('.EXE', '.CMD' | Where-Object { $_ -notin ($env:PATHEXT -split ';') }).Count -gt 0) { throw 'PATHEXT cannot discover Windows executables.' } +if ([IO.Path]::TrimEndingDirectorySeparator([IO.Path]::GetTempPath()) -ne $env:TEMP) { throw 'OS temporary directory differs from the isolated TEMP path.' } +if (-not [IO.Path]::EndsInDirectorySeparator($env:NUGET_PACKAGES)) { throw 'NUGET_PACKAGES must end with a directory separator for MSBuild SourceRoot compatibility.' }"; + + public static string HashTree(string root, string[] excludeSegments) + { + if (IsLink(root)) throw new InvalidOperationException("Dependency contains an unsupported link: " + root); + var entries = new List(); + CollectEntries(root, root, excludeSegments ?? Array.Empty(), entries); + using (var sha = SHA256.Create()) + { + // The preparer sorts with Sort-Object, and both sides must produce the same hash. + var sorted = entries.OrderBy(entry => entry, StringComparer.Create(CultureInfo.CurrentCulture, true)); + return Hex(sha.ComputeHash(Encoding.UTF8.GetBytes(string.Join("\n", sorted)))); + } + } + + private static void CollectEntries(string root, string directory, string[] excludeSegments, List entries) + { + foreach (var item in new DirectoryInfo(directory).EnumerateFileSystemInfos()) + { + if ((item.Attributes & FileAttributes.ReparsePoint) != 0) + { + throw new InvalidOperationException("Dependency contains an unsupported link: " + item.FullName); + } + + if (item is DirectoryInfo) + { + CollectEntries(root, item.FullName, excludeSegments, entries); + continue; + } + + var relative = Path.GetRelativePath(root, item.FullName).Replace('\\', '/'); + if (relative.Split('/').Any(segment => excludeSegments.Contains(segment, StringComparer.OrdinalIgnoreCase))) continue; + entries.Add(relative + ":" + HashFile(item.FullName)); + } + } + + public static void AssertDeclarations(string requirementsJson) + { + using (var document = JsonDocument.Parse(requirementsJson)) AssertDeclarations(document.RootElement); + } + + private static void AssertDeclarations(JsonElement requirements) + { + var executables = Strings(requirements, "executables"); + foreach (var name in executables) + { + if (!Regex.IsMatch(name, "^[A-Za-z0-9][A-Za-z0-9._+-]*$") || + Regex.IsMatch(name, @"^(claude|codex|opencode|copilot|gemini)(\.|$)", IgnoreCase)) + { + throw new InvalidOperationException($"Invalid prerequisite executable '{name}'. Declare a model-free engineering tool by its application name."); + } + } + + var ids = new HashSet(StringComparer.OrdinalIgnoreCase) { "isolated-shell-environment" }; + foreach (var probe in Items(requirements, "probes")) + { + var id = Text(probe, "id"); + var command = Strings(probe, "command"); + if (!Regex.IsMatch(id, "^[a-z0-9][a-z0-9-]*$", IgnoreCase) || !ids.Add(id) || + command.Length == 0 || !executables.Contains(command[0], StringComparer.OrdinalIgnoreCase)) + { + throw new InvalidOperationException($"Invalid readiness probe '{id}'. Use a unique id and a declared model-free executable."); + } + + var pattern = Text(probe, "outputPattern"); + if (pattern.Length > 0) _ = new Regex(pattern, RegexOptions.Multiline, TimeSpan.FromSeconds(1)); + var timeoutMs = Timeout(probe); + if (timeoutMs < 1 || timeoutMs > 90000) throw new InvalidOperationException($"Invalid timeoutMs for readiness probe '{id}'."); + } + } + + public static void AssertStagedDependencies(string runRoot, string contractJson) + { + using (var document = JsonDocument.Parse(contractJson)) AssertStagedDependencies(runRoot, document.RootElement); + } + + private static void AssertStagedDependencies(string runRoot, JsonElement contract) + { + if (!TryGet(contract, "prerequisites", out var requirements)) return; + foreach (var relative in new[] { "dependencies", "dependencies/tools", "home", "home/tools", "home/restore-probe" }) + { + var directory = Path.Combine(runRoot, relative); + if ((Directory.Exists(directory) || File.Exists(directory)) && IsLink(directory)) + { + throw new InvalidOperationException($"Staged prerequisite directory '{relative}' must be an ordinary directory."); + } + } + + foreach (var asset in Items(requirements, "stagedHome")) + { + var path = Text(asset, "path"); + if (path != "home/tools" && path != "home/restore-probe") throw new InvalidOperationException($"Invalid staged home prerequisite '{path}'."); + if (!HashMatches(asset, HashTree(Staged(runRoot, path, "staged home prerequisite", true), null))) + { + throw new InvalidOperationException($"Staged home prerequisite hash mismatch: {path}"); + } + } + + var expected = new HashSet(StringComparer.Ordinal); + var candidate = Text(contract, "skillDirectory"); + if (candidate.StartsWith("dependencies/", StringComparison.OrdinalIgnoreCase)) expected.Add(candidate); + foreach (var dependency in Items(requirements, "skills")) + { + var path = Text(dependency, "path"); + if (!Regex.IsMatch(path, "^dependencies/[a-z0-9][a-z0-9-]*$", IgnoreCase) || + path.Equals("dependencies/" + Text(contract, "candidateSkillName"), StringComparison.OrdinalIgnoreCase) || !expected.Add(path)) + { + throw new InvalidOperationException($"Invalid staged skill prerequisite '{path}'."); + } + + if (!HashMatches(dependency, HashTree(Staged(runRoot, path, "skill prerequisite", true), null))) + { + throw new InvalidOperationException($"Staged skill prerequisite hash mismatch: {path}"); + } + } + + var downloads = new HashSet(StringComparer.Ordinal); + foreach (var asset in Items(requirements, "downloads")) + { + var relative = Text(asset, "path"); + if (!Regex.IsMatch(relative, "^dependencies/tools/[a-z0-9][a-z0-9._-]*$", IgnoreCase)) throw new InvalidOperationException($"Invalid staged file prerequisite '{relative}'."); + var path = Staged(runRoot, relative, "file prerequisite", false); + if (IsLink(path) || !HashMatches(asset, HashFile(path))) throw new InvalidOperationException($"Staged file prerequisite hash mismatch: {relative}"); + downloads.Add(relative); + } + + var dependencyRoot = new DirectoryInfo(Path.Combine(runRoot, "dependencies")); + if (File.Exists(dependencyRoot.FullName)) throw new InvalidOperationException("Undeclared staged dependency 'dependencies'."); + if (!dependencyRoot.Exists) return; + foreach (var item in dependencyRoot.EnumerateFileSystemInfos()) + { + var isTools = item.Name.Equals("tools", StringComparison.OrdinalIgnoreCase); + if ((item.Attributes & FileAttributes.ReparsePoint) != 0 || !(item is DirectoryInfo directory) || + (!isTools && !expected.Contains("dependencies/" + item.Name))) + { + throw new InvalidOperationException($"Undeclared staged dependency '{item.Name}'."); + } + + if (!isTools) continue; + foreach (var tool in directory.EnumerateFileSystemInfos()) + { + if (tool is DirectoryInfo || !downloads.Contains("dependencies/tools/" + tool.Name)) + { + throw new InvalidOperationException($"Undeclared staged tool '{tool.Name}'."); + } + } + } + } + + // Returns null when the staged files are intact. + public static OrderedDictionary FindStagedFailure(string runRoot, string workingDirectory, bool verifyFixture, string fixtureHash, string contractJson) + { + try + { + using (var document = JsonDocument.Parse(contractJson)) + { + if (!TryGet(document.RootElement, "prerequisites", out var requirements)) return null; + AssertDeclarations(requirements); + AssertStagedDependencies(runRoot, document.RootElement); + } + + if (verifyFixture && !HashTree(workingDirectory, new[] { ".git" }).Equals(fixtureHash, StringComparison.OrdinalIgnoreCase)) + { + throw new InvalidOperationException("Staged repository fixture hash mismatch: repo/"); + } + + return null; + } + catch (Exception exception) + { + return new OrderedDictionary + { + { "id", "staged-prerequisites" }, + { "command", new[] { "Verify staged prerequisites" } }, + { "exit_code", null }, + { "transport", "runner-filesystem" }, + { "status", "infrastructure_blocked" }, + { "diagnostic", exception.Message }, + { "remediation", "Prepare a fresh iteration with intact fixtures and declared dependencies." } + }; + } + } + + public static List CreateProbes(string contractJson, IDictionary environment, string visibleRunRoot) + { + using (var document = JsonDocument.Parse(contractJson)) + { + var probes = new List(); + var pairs = environment.Keys.Cast().Select(key => key.ToString()) + .Where(key => !key.Equals("PATH", StringComparison.OrdinalIgnoreCase) && !key.Equals("PATHEXT", StringComparison.OrdinalIgnoreCase)) + .Select(key => "'" + key + "'=" + Quote(Value(environment, key))); + probes.Add(NewProbe("isolated-shell-environment", EnvironmentCheck.Replace("ENVIRONMENT_PAIRS", string.Join("; ", pairs)), + new[] { "pwsh", "-NoProfile", "-NonInteractive", "-Command", "" }, string.Empty, BuiltInTimeoutMs)); + if (!TryGet(document.RootElement, "prerequisites", out var requirements)) return probes; + + AssertDeclarations(requirements); + var executables = Strings(requirements, "executables"); + foreach (var name in executables) + { + probes.Add(NewProbe("executable:" + name, + $"if (-not (Get-Command -Name '{name}' -CommandType Application -ErrorAction SilentlyContinue)) {{ throw \"Executable '{name}' was not found on the isolated PATH.\" }}", + new[] { "Get-Command", "-CommandType", "Application", name }, string.Empty, BuiltInTimeoutMs)); + } + + foreach (var probe in Items(requirements, "probes")) + { + probes.Add(NewCommandProbe(Text(probe, "id"), Strings(probe, "command"), Text(probe, "outputPattern"), Timeout(probe), visibleRunRoot)); + } + + foreach (var tool in Items(requirements, "dotnetTools")) + { + var executable = Text(tool, "executable"); + var version = Text(tool, "requested_version"); + if (!executables.Contains(executable, StringComparer.OrdinalIgnoreCase) || + !Regex.IsMatch(version, @"^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$")) + { + throw new InvalidOperationException($"Invalid staged .NET tool prerequisite '{executable}'."); + } + + probes.Add(NewCommandProbe("tool-version:" + executable, new[] { executable, "--version" }, + "^" + Regex.Escape(version) + @"(?:\+|\s|$)", DefaultTimeoutMs, visibleRunRoot)); + } + + return probes; + } + } + + private static OrderedDictionary NewCommandProbe(string id, string[] declared, string pattern, int timeoutMs, string visibleRunRoot) + { + var command = declared.Select(argument => argument.Replace("{run}", visibleRunRoot)).ToArray(); + var script = "$ErrorActionPreference = \"Stop\"; $app = Get-Command -CommandType Application " + Quote(command[0]) + + " | Select-Object -First 1; & $app.Source " + string.Join(" ", command.Skip(1).Select(Quote)) + "; exit $LASTEXITCODE"; + return NewProbe(id, script, command, pattern, timeoutMs); + } + + private static OrderedDictionary NewProbe(string id, string script, string[] command, string expected, int timeoutMs) => + new OrderedDictionary { { "id", id }, { "script", script }, { "command", command }, { "expected", expected }, { "timeoutMs", timeoutMs } }; + + // exitCode is null when the probe produced no exit status. + public static OrderedDictionary Observe(IDictionary probe, object exitCode, string stdout, string stderr, string error, string transport) + { + stdout = stdout ?? string.Empty; + stderr = (stderr ?? string.Empty).Trim(); + var id = Value(probe, "id"); + var expected = Value(probe, "expected"); + var matched = expected.Length == 0 || Regex.IsMatch(stdout, expected, RegexOptions.Multiline, TimeSpan.FromSeconds(1)); + var exitedCleanly = exitCode != null && Convert.ToInt64(exitCode, CultureInfo.InvariantCulture) == 0; + var passed = exitedCleanly && matched; + string diagnostic; + if (exitCode == null) + { + diagnostic = stderr.Length > 0 ? stderr : !string.IsNullOrEmpty(error) ? error : "No exit status from " + transport + "."; + } + else if (!exitedCleanly) + { + diagnostic = stderr.Length > 0 ? stderr : stdout.Trim(); + } + else + { + diagnostic = matched ? stdout.Trim() : "Output did not match " + expected + ". Observed: " + stdout.Trim(); + } + + var remediation = passed ? null + : id == "isolated-shell-environment" ? "Check isolated PATH, home, and temporary directory configuration on the execution host." + : "Check the reported command on the execution host and install the required tool or version, or restore the required service."; + return new OrderedDictionary + { + { "id", id }, + { "command", probe["command"] }, + { "exit_code", exitCode }, + { "transport", transport }, + { "status", passed ? "ready" : "infrastructure_blocked" }, + { "diagnostic", diagnostic.Substring(0, Math.Min(diagnostic.Length, DiagnosticLimit)) }, + { "remediation", remediation } + }; + } + + // Verifies the staged files, then runs the probes in order until one fails or the shared deadline passes. + // launchPrefix holds the arguments before the shell's own, which is how a sandbox wraps the shell. + public static List Run(string contractJson, string runRoot, string workingDirectory, string visibleRunRoot, + IDictionary environment, IDictionary visibleEnvironment, string fileName, string[] launchPrefix, int budgetMs) + { + var clock = Stopwatch.StartNew(); + var observations = new List(); + var failure = FindStagedFailure(runRoot, workingDirectory, false, null, contractJson); + if (failure != null) + { + observations.Add(failure); + return observations; + } + + foreach (var probe in CreateProbes(contractJson, visibleEnvironment, visibleRunRoot)) + { + var timeoutMs = (int)Math.Min(Math.Max(0, budgetMs - clock.ElapsedMilliseconds), (int)probe["timeoutMs"]); + int? exitCode = null; + var stdout = string.Empty; + string stderr; + try + { + if (timeoutMs < 1) throw new TimeoutException("The readiness deadline expired before this probe could start."); + var arguments = (launchPrefix ?? Array.Empty()).Concat(new[] { "-NoProfile", "-NonInteractive", "-Command", (string)probe["script"] }); + exitCode = RunProcess(fileName, arguments, workingDirectory, environment, timeoutMs, out stdout, out stderr); + } + catch (Exception exception) + { + stderr = exception.Message; + } + + var observation = Observe(probe, exitCode, stdout, stderr, null, "runner-process"); + observations.Add(observation); + if ((string)observation["status"] != "ready") break; + } + + return observations; + } + + // Returns null on timeout. The process tree does not outlive a timeout; on Windows it never outlives the probe. + private static int? RunProcess(string fileName, IEnumerable arguments, string workingDirectory, IDictionary environment, + int timeoutMs, out string stdout, out string stderr) + { + var start = new ProcessStartInfo(fileName) + { + WorkingDirectory = workingDirectory, + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardInput = true, + RedirectStandardOutput = true, + RedirectStandardError = true + }; + foreach (var argument in arguments) start.ArgumentList.Add(argument); + start.Environment.Clear(); + foreach (var key in environment.Keys) start.Environment[key.ToString()] = Value(environment, key); + + var clock = Stopwatch.StartNew(); + if (Path.DirectorySeparatorChar == '\\') + { + using (var owned = new WindowsOwnedProcess { StartInfo = start }) + { + owned.Start(); + return Complete(owned.StandardInput, owned.StandardOutput, owned.StandardError, owned.WaitForExit, () => owned.ExitCode, + timedOut => owned.StopOwnedProcesses(GraceMs), clock, timeoutMs, out stdout, out stderr); + } + } + + using (var process = new Process { StartInfo = start }) + { + process.Start(); + try + { + return Complete(process.StandardInput, process.StandardOutput, process.StandardError, process.WaitForExit, () => process.ExitCode, + timedOut => + { + if (!timedOut) return; + process.Kill(true); + if (!process.WaitForExit(GraceMs)) throw new TimeoutException("Process termination grace expired before the probe exited."); + }, clock, timeoutMs, out stdout, out stderr); + } + catch + { + if (!process.HasExited) process.Kill(true); + throw; + } + } + } + + private static int? Complete(StreamWriter input, StreamReader output, StreamReader error, Func waitForExit, Func exitCode, + Action stop, Stopwatch clock, int timeoutMs, out string stdout, out string stderr) + { + var stdoutPump = new Pump(output.BaseStream); + var stderrPump = new Pump(error.BaseStream); + try { input.Close(); } catch (IOException) { } + var exited = waitForExit((int)Math.Max(0, timeoutMs - clock.ElapsedMilliseconds)); + stop(!exited); + var drain = Stopwatch.StartNew(); + var drained = stdoutPump.Wait(GraceMs); + drained &= stderrPump.Wait((int)Math.Max(0, GraceMs - drain.ElapsedMilliseconds)); + stdout = stdoutPump.Text; + stderr = stderrPump.Text; + if (!drained) stderr += " A descendant process kept the probe output open."; + if (exited) return exitCode(); + stderr = $"Probe exceeded its deadline of {timeoutMs} ms. {stderr}"; + return null; + } + + // Reads one pipe on its own thread, because redirected Windows pipes block the thread that reads them. + private sealed class Pump + { + private readonly MemoryStream buffer = new MemoryStream(); + private readonly Task task; + + public Pump(Stream source) + { + task = Task.Factory.StartNew(() => Copy(source), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); + } + + public string Text + { + get { lock (buffer) return new UTF8Encoding(false).GetString(buffer.ToArray()); } + } + + public bool Wait(int milliseconds) => task.Wait(milliseconds); + + private void Copy(Stream source) + { + var chunk = new byte[8192]; + try + { + int count; + while ((count = source.Read(chunk, 0, chunk.Length)) > 0) + { + lock (buffer) buffer.Write(chunk, 0, count); + } + } + catch (Exception exception) when (exception is IOException || exception is ObjectDisposedException) + { + // The pipe closed with the process tree; what arrived is the evidence. + } + } + } + + private static string Staged(string runRoot, string relative, string field, bool directory) + { + // Callers accept only fixed names or single names after a fixed directory, so the path stays inside the run. + var path = Path.GetFullPath(Path.Combine(runRoot, relative)); + if (directory ? Directory.Exists(path) : File.Exists(path)) return path; + throw new InvalidOperationException($"{field} '{relative}' does not exist under '{runRoot}'."); + } + + private static bool IsLink(string path) => (File.GetAttributes(path) & FileAttributes.ReparsePoint) != 0; + + private static bool HashMatches(JsonElement asset, string actual) => actual.Equals(Text(asset, "sha256"), StringComparison.OrdinalIgnoreCase); + + private static string HashFile(string path) + { + using (var sha = SHA256.Create()) + using (var stream = File.OpenRead(path)) + { + return Hex(sha.ComputeHash(stream)); + } + } + + private static string Hex(byte[] bytes) => BitConverter.ToString(bytes).Replace("-", string.Empty).ToLowerInvariant(); + + private static string Quote(string value) => "'" + value.Replace("'", "''") + "'"; + + private static string Value(IDictionary values, object key) => + values.Contains(key) ? Convert.ToString(values[key], CultureInfo.InvariantCulture) ?? string.Empty : string.Empty; + + private static bool TryGet(JsonElement element, string name, out JsonElement value) + { + if (element.ValueKind == JsonValueKind.Object) + { + foreach (var property in element.EnumerateObject()) + { + if (property.Name.Equals(name, StringComparison.OrdinalIgnoreCase) && property.Value.ValueKind != JsonValueKind.Null) + { + value = property.Value; + return true; + } + } + } + + value = default; + return false; + } + + // A single value counts as a list of one, as it does in the PowerShell callers. + private static JsonElement[] Items(JsonElement element, string name) => + !TryGet(element, name, out var value) ? Array.Empty() + : value.ValueKind == JsonValueKind.Array ? value.EnumerateArray().ToArray() + : new[] { value }; + + private static string[] Strings(JsonElement element, string name) => Items(element, name).Select(item => item.ToString()).ToArray(); + + private static string Text(JsonElement element, string name) => TryGet(element, name, out var value) ? value.ToString() : string.Empty; + + private static int Timeout(JsonElement probe) => + TryGet(probe, "timeoutMs", out var value) ? int.Parse(value.ToString(), NumberStyles.Integer, CultureInfo.InvariantCulture) : DefaultTimeoutMs; + } +} diff --git a/scripts/eval-runners/eval-readiness.ps1 b/scripts/eval-runners/eval-readiness.ps1 index 8c800070..c7bb8161 100644 --- a/scripts/eval-runners/eval-readiness.ps1 +++ b/scripts/eval-runners/eval-readiness.ps1 @@ -1,138 +1,113 @@ +# The readiness logic lives in eval-readiness.cs. These functions only pass PowerShell values to it. +function ConvertTo-EvalReadinessJson { + param([Parameter(Mandatory)][object]$Value) + + Import-EvalRunnerTypes + ConvertTo-Json -InputObject $Value -Depth 32 -Compress +} + function Get-EvalDependencyTreeHash { - param([Parameter(Mandatory)][string]$Root) + param([Parameter(Mandatory)][string]$Root, [string[]]$ExcludeSegments = @()) - $entries = foreach ($item in Get-ChildItem -LiteralPath $Root -Recurse -Force) { - if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw "Dependency contains an unsupported link: $($item.FullName)" } - if ($item.PSIsContainer) { continue } - $relative = [IO.Path]::GetRelativePath($Root, $item.FullName).Replace('\', '/') - "$relative`:$(Get-Sha256HexFromFile -Path $item.FullName)" - } - Get-Sha256HexFromBytes -Bytes ([Text.Encoding]::UTF8.GetBytes((@($entries | Sort-Object) -join "`n"))) + Import-EvalRunnerTypes + [Agentic.Evals.EvalReadiness]::HashTree((Get-Item -LiteralPath $Root -Force -ErrorAction Stop).FullName, $ExcludeSegments) } function Assert-EvalStagedDependencies { param([string]$RunRoot, [object]$Contract) - $requirements = Get-JsonProperty -Object $Contract -Name 'prerequisites' - if ($null -eq $requirements) { return } - $expected = [Collections.Generic.List[string]]::new() - $candidate = [string](Get-JsonProperty -Object $Contract -Name 'skillDirectory' -Default '') - if ($candidate -like 'dependencies/*') { $expected.Add($candidate) } - foreach ($dependency in @(Get-JsonProperty -Object $requirements -Name 'skills' -Default @())) { - if ($dependency.path -notmatch '^dependencies/[a-z0-9][a-z0-9-]*$' -or - $dependency.path -eq ('dependencies/' + $Contract.candidateSkillName) -or $expected.Contains($dependency.path)) { - throw "Invalid staged skill prerequisite '$($dependency.path)'." - } - $expected.Add($dependency.path) - $path = Resolve-ContainedPath -BasePath $RunRoot -RelativePath $dependency.path -FieldName 'skill prerequisite' -Kind Directory - if ((Get-EvalDependencyTreeHash -Root $path) -ne $dependency.sha256) { throw "Staged skill prerequisite hash mismatch: $($dependency.path)" } - } - foreach ($asset in @(Get-JsonProperty -Object $requirements -Name 'downloads' -Default @())) { - if ($asset.path -notmatch '^dependencies/tools/[A-Za-z0-9][A-Za-z0-9._-]*$') { throw "Invalid staged file prerequisite '$($asset.path)'." } - $path = Resolve-ContainedPath -BasePath $RunRoot -RelativePath $asset.path -FieldName 'file prerequisite' -Kind File - if ((Get-Item -LiteralPath $path).Attributes -band [IO.FileAttributes]::ReparsePoint -or (Get-Sha256HexFromFile -Path $path) -ne $asset.sha256) { - throw "Staged file prerequisite hash mismatch: $($asset.path)" - } - } - $dependencyRoot = Join-Path $RunRoot 'dependencies' - if (Test-Path -LiteralPath $dependencyRoot) { - if ((Get-Item -LiteralPath $dependencyRoot).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'Staged dependencies must be ordinary directories.' } - foreach ($item in Get-ChildItem -LiteralPath $dependencyRoot -Force) { - if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint -or (-not $item.PSIsContainer) -or - ($item.Name -ne 'tools' -and -not $expected.Contains("dependencies/$($item.Name)"))) { - throw "Undeclared staged dependency '$($item.Name)'." - } - if ($item.Name -eq 'tools') { - $downloadPaths = @(Get-JsonProperty -Object $requirements -Name 'downloads' -Default @() | ForEach-Object path) - foreach ($tool in Get-ChildItem -LiteralPath $item.FullName -Force) { - if ($tool.PSIsContainer -or "dependencies/tools/$($tool.Name)" -cnotin $downloadPaths) { throw "Undeclared staged tool '$($tool.Name)'." } - } - } - } - } + if ($null -eq (Get-JsonProperty -Object $Contract -Name 'prerequisites')) { return } + $json = ConvertTo-EvalReadinessJson -Value $Contract + try { [Agentic.Evals.EvalReadiness]::AssertStagedDependencies((Resolve-Path -LiteralPath $RunRoot).ProviderPath, $json) } + catch { throw $_.Exception.GetBaseException().Message } } -function Get-EvalReadinessProbes { - param([Parameter(Mandatory)][object]$Run) +function Assert-EvalReadinessDeclarations { + param([Parameter(Mandatory)][object]$Requirements) - $requirements = Get-JsonProperty -Object $Run.Contract -Name 'prerequisites' - $environment = New-RunnerShellEnvironment -Run $Run - $pairs = foreach ($key in $environment.Keys) { - if ($key -in @('PATH', 'PATHEXT')) { continue } - "'{0}'='{1}'" -f $key, ([string]$environment[$key]).Replace("'", "''") - } - $environmentCheck = @' -$expected = @{ ENVIRONMENT_PAIRS } -foreach ($name in $expected.Keys) { - if ([Environment]::GetEnvironmentVariable($name) -cne $expected[$name]) { throw "Missing or unexpected environment value: $name" } -} -foreach ($name in 'OPENAI_API_KEY', 'CODEX_API_KEY', 'ANTHROPIC_API_KEY', 'GH_TOKEN', 'GITHUB_TOKEN', 'CODEX_HOME', 'NODE_PATH') { - if ([Environment]::GetEnvironmentVariable($name)) { throw "Unexpected shell variable: $name" } + $json = ConvertTo-EvalReadinessJson -Value $Requirements + try { [Agentic.Evals.EvalReadiness]::AssertDeclarations($json) } + catch { throw $_.Exception.GetBaseException().Message } } -foreach ($path in ($env:PATH -split [IO.Path]::PathSeparator)) { - if (-not [IO.Path]::IsPathFullyQualified($path)) { throw "PATH contains a relative or empty entry: $path" } -} -if ($IsWindows -and @('.EXE', '.CMD' | Where-Object { $_ -notin ($env:PATHEXT -split ';') }).Count -gt 0) { throw 'PATHEXT cannot discover Windows executables.' } -if ([IO.Path]::TrimEndingDirectorySeparator([IO.Path]::GetTempPath()) -ne $env:TEMP) { throw 'OS temporary directory differs from the isolated TEMP path.' } -if (-not [IO.Path]::EndsInDirectorySeparator($env:NUGET_PACKAGES)) { throw 'NUGET_PACKAGES must end with a directory separator for MSBuild SourceRoot compatibility.' } -'@ - # PowerShell uses the Unix temp API, which reads TMPDIR, and the Windows - # temp API, which reads TMP/TEMP. All three point to the same directory. - [ordered]@{ - id = 'isolated-shell-environment' - script = $environmentCheck.Replace('ENVIRONMENT_PAIRS', ($pairs -join '; ')) - command = @('pwsh', '-NoProfile', '-NonInteractive', '-Command', '') - expected = '' - timeoutMs = 8000 - } - foreach ($probe in @(Get-JsonProperty -Object $requirements -Name 'probes' -Default @())) { - $id = [string]$probe.id - $command = @($probe.command | ForEach-Object { ([string]$_).Replace('{run}', $Run.RunRoot) }) - $executables = @(Get-JsonProperty -Object $requirements -Name 'executables' -Default @()) - if ($id -notmatch '^[a-z0-9][a-z0-9-]*$' -or $command.Count -eq 0 -or $command[0] -notin $executables) { - throw "Invalid readiness probe '$id'. The executable must be declared in prerequisites.executables." - } - $match = [string](Get-JsonProperty -Object $probe -Name 'outputPattern' -Default '') - if ($match) { [void][regex]::new($match, [Text.RegularExpressions.RegexOptions]::Multiline, [TimeSpan]::FromSeconds(1)) } - $timeoutMs = [int](Get-JsonProperty -Object $probe -Name 'timeoutMs' -Default 10000) - if ($timeoutMs -lt 1 -or $timeoutMs -gt 90000) { throw "Invalid timeoutMs for readiness probe '$id'." } - $quoted = @($command | ForEach-Object { "'" + $_.Replace("'", "''") + "'" }) - [ordered]@{ - id = $id - script = '$ErrorActionPreference = "Stop"; & ' + ($quoted -join ' ') + '; exit $LASTEXITCODE' - command = $command - expected = $match - timeoutMs = $timeoutMs - } - } +function Get-EvalReadinessProbes { + param( + [Parameter(Mandatory)][object]$Run, + [System.Collections.IDictionary]$Environment = (New-RunnerShellEnvironment -Run $Run), + [string]$VisibleRunRoot = $Run.RunRoot + ) + + $json = ConvertTo-EvalReadinessJson -Value $Run.Contract + try { [Agentic.Evals.EvalReadiness]::CreateProbes($json, $Environment, $VisibleRunRoot) } + catch { throw $_.Exception.GetBaseException().Message } } function New-EvalReadinessObservation { - param([Parameter(Mandatory)][object]$Probe, [object]$Response) + param([Parameter(Mandatory)][object]$Probe, [object]$Response, [string]$Transport = 'codex-command-exec') + Import-EvalRunnerTypes $result = Get-JsonProperty -Object $Response -Name 'result' - $exit = Get-JsonProperty -Object $result -Name 'exitCode' - $stdout = [string](Get-JsonProperty -Object $result -Name 'stdout') - $stderr = [string](Get-JsonProperty -Object $result -Name 'stderr') - $matched = -not $Probe.expected -or [regex]::IsMatch($stdout, $Probe.expected, [Text.RegularExpressions.RegexOptions]::Multiline, [TimeSpan]::FromSeconds(1)) - $passed = $null -ne $exit -and $exit -eq 0 -and $matched - $diagnostic = if ($null -eq $exit) { - 'No exit status from the native command transport. Verify runner command/exec support.' - } elseif ($exit -ne 0) { - if ($stderr) { $stderr.Trim() } else { $stdout.Trim() } - } elseif (-not $matched) { - "Output did not match $($Probe.expected). Observed: $($stdout.Trim())" - } else { - $stdout.Trim() + $errorMessage = [string](Get-JsonProperty -Object (Get-JsonProperty -Object $Response -Name 'error') -Name 'message') + [Agentic.Evals.EvalReadiness]::Observe($Probe, (Get-JsonProperty -Object $result -Name 'exitCode'), + [string](Get-JsonProperty -Object $result -Name 'stdout'), [string](Get-JsonProperty -Object $result -Name 'stderr'), $errorMessage, $Transport) +} + +function Add-EvalReadinessFailureReasons { + param([object[]]$Readiness, [System.Collections.Generic.List[string]]$Reasons) + + foreach ($observation in $Readiness | Where-Object status -ne 'ready') { + $Reasons.Add("Infrastructure blocked at '$($observation.id)' (command: $($observation.command -join ' '), exit: $($observation.exit_code)): $($observation.diagnostic) $($observation.remediation)") } - [ordered]@{ - id = $Probe.id - command = @($Probe.command) - exit_code = $exit - status = if ($passed) { 'ready' } else { 'infrastructure_blocked' } - diagnostic = $diagnostic.Substring(0, [Math]::Min($diagnostic.Length, 2000)) +} + +function Get-EvalStagedReadinessFailure { + param([Parameter(Mandatory)][object]$Run, [switch]$VerifyFixture) + + if ($null -eq (Get-JsonProperty -Object $Run.Contract -Name 'prerequisites')) { return } + $json = ConvertTo-EvalReadinessJson -Value $Run.Contract + $fixtureHash = if ($VerifyFixture) { $Run.FixtureHash } + $failure = [Agentic.Evals.EvalReadiness]::FindStagedFailure($Run.RunRoot, $Run.WorkingDirectoryPath, $VerifyFixture.IsPresent, $fixtureHash, $json) + if ($null -ne $failure) { return $failure } +} + +function New-EvalReadinessFailureResult { + param($Descriptor, $Inputs, [object[]]$Readiness, [string]$SessionId, [datetime]$Started) + + $reasons = [System.Collections.Generic.List[string]]::new() + Add-EvalReadinessFailureReasons -Readiness $Readiness -Reasons $reasons + $finished = [datetime]::UtcNow + return New-ExecutionResult -Descriptor $Descriptor -Profile $Inputs.Profile -Run $Inputs.Run -Status incompatible -FinalResponseReason 'infrastructure_blocked' -StartedUtc $Started.ToString('o') -FinishedUtc $finished.ToString('o') -Failure (New-ExecutionFailure -Code 'infrastructure_blocked' -Message ($reasons -join ' ')) -SessionId $SessionId -IsolationCapabilities ([ordered]@{}) -IsolationMechanisms @('preflight-only') -Evidence ([ordered]@{ readiness = $Readiness; resume = $false }) -AttemptCount 1 +} + +function Invoke-EvalProjectedReadiness { + param( + [Parameter(Mandatory)][object]$Run, + [System.Collections.IDictionary]$Environment, + [object]$Sandbox, + [object]$SandboxCommand, + [string]$SandboxProfile + ) + + if (-not (Test-JsonProperty -Object $Run.Contract -Name 'prerequisites')) { return } + if ($null -eq $Environment) { $Environment = New-RunnerShellEnvironment -Run $Run } + $visibleRunRoot = $Run.RunRoot + $visibleEnvironment = $Environment + $file = $shell = Get-RunnerPowerShellPath + $prefix = @() + if ($null -ne $Sandbox -and $IsLinux) { + $visibleRunRoot = '/run' + $visibleEnvironment = ConvertTo-LinuxEvalSandboxEnvironment -Environment $Environment -RunRoot $Run.RunRoot + $file = $Sandbox.FileName + $prefix = @(Get-LinuxEvalSandboxArguments -Inputs @{ Run = $Run } -CommandInfo $SandboxCommand -InsideEnvironment $visibleEnvironment -Command @($shell)) + } elseif ($SandboxProfile) { + $file = $Sandbox.FileName + $prefix = @('-f', $SandboxProfile, '--', $shell) } + $json = ConvertTo-EvalReadinessJson -Value $Run.Contract + try { + [Agentic.Evals.EvalReadiness]::Run($json, $Run.RunRoot, $Run.WorkingDirectoryPath, $visibleRunRoot, $Environment, $visibleEnvironment, + $file, [string[]]$prefix, 1000 * (Get-EvalReadinessTimeoutSeconds)) + } catch { throw $_.Exception.GetBaseException().Message } } function Get-ObservedSkillReferenceReads { diff --git a/scripts/eval-runners/finalize-eval-package.ps1 b/scripts/eval-runners/finalize-eval-package.ps1 index e041f8e9..8d2b2d01 100644 --- a/scripts/eval-runners/finalize-eval-package.ps1 +++ b/scripts/eval-runners/finalize-eval-package.ps1 @@ -31,12 +31,17 @@ function Invoke-FinalizerCommand { [Parameter(Mandatory = $true)][string]$Description ) - $output = & pwsh -NoProfile -NonInteractive -File $ScriptPath @Arguments 2>&1 - if ($LASTEXITCODE -ne 0) { - $detail = [string]::Join(' ', @($output | ForEach-Object { [string]$_ })) - throw "$Description failed: $detail" + # Live progress goes to STDERR; STDOUT stays the machine-readable result. + [Console]::Error.WriteLine("[START] $Description") + $started = [System.Diagnostics.Stopwatch]::StartNew() + try { + $result = Invoke-RunnerPowerShellScript -ScriptPath $ScriptPath -Arguments $Arguments -Description $Description -WorkingDirectory $iteration + [Console]::Error.WriteLine(('[COMPLETE] {0} exit=0 took={1:N1}s' -f $Description, $started.Elapsed.TotalSeconds)) + return $result.Stdout + } catch { + [Console]::Error.WriteLine(('[FAILED] {0} took={1:N1}s' -f $Description, $started.Elapsed.TotalSeconds)) + throw } - return @($output) } function Assert-FinalizerState { diff --git a/scripts/eval-runners/invoke-runner-owned-arms.ps1 b/scripts/eval-runners/invoke-runner-owned-arms.ps1 index 57a4f019..41ee409c 100644 --- a/scripts/eval-runners/invoke-runner-owned-arms.ps1 +++ b/scripts/eval-runners/invoke-runner-owned-arms.ps1 @@ -64,7 +64,7 @@ function Invoke-RunnerPreflight { $stderrPath = Join-Path ([System.IO.Path]::GetTempPath()) ('agentic-runner-preflight-' + [Guid]::NewGuid().ToString('N') + '.stderr') $child = $null try { - $pwshPath = [string]((Get-Command pwsh -CommandType Application -ErrorAction Stop | Select-Object -First 1).Source) + $pwshPath = Get-RunnerPowerShellPath # ProcessStartInfo.ArgumentList escapes each argument natively, so raw # paths are passed without manual quoting. The child preflight runs # headless (no visible console window on Windows). @@ -144,7 +144,8 @@ function Get-RunnerChildTimeoutSeconds { ) $turnCount = Get-RunnerRunTurnCount -RunPath $RunPath - $startupAllowance = Get-RunnerExecutionOverheadAllowanceSeconds -Runner $Runner + $contract = Read-RunnerJson -Path $RunPath + $startupAllowance = Get-RunnerExecutionOverheadAllowanceSeconds -Runner $Runner -HasPrerequisites:(Test-JsonProperty -Object $contract -Name 'prerequisites') return [pscustomobject]@{ TurnCount = $turnCount RunnerGraceSeconds = Get-RunnerGraceSeconds @@ -309,7 +310,7 @@ try { '-Profile' ([string]$profile.Path) ) - $pwshPath = [string]((Get-Command pwsh -CommandType Application -ErrorAction Stop | Select-Object -First 1).Source) + $pwshPath = Get-RunnerPowerShellPath $childBudget = Get-RunnerChildTimeoutSeconds -RunPath $runPath -ProfileTimeoutSeconds ([int]$profile.TimeoutSeconds) -Runner $runnerName # Headless child: CreateNoWindow suppresses the per-child console # window on Windows while the process stays a real isolation diff --git a/scripts/eval-runners/opencode/runner.ps1 b/scripts/eval-runners/opencode/runner.ps1 index e6c87c7c..fcc9c1fb 100644 --- a/scripts/eval-runners/opencode/runner.ps1 +++ b/scripts/eval-runners/opencode/runner.ps1 @@ -93,11 +93,26 @@ function Resolve-OpenCodeInputs { throw 'preflight and execute require -Run and -Profile.' } return [pscustomobject]@{ - Run = Resolve-RunContract -RunPath $Run + Run = Resolve-RunContract -RunPath $Run -DeferStagedDependencyValidation Profile = Resolve-ExecutionProfile -ProfilePath $Profile } } +function Resolve-OpenCodeCommand { + $command = Resolve-ExternalCommand -Name 'opencode' + if ($null -eq $command -or (Get-PlatformName) -ne 'windows') { return $command } + $extension = [IO.Path]::GetExtension([string]$command.Source) + if ($extension -notin @('.ps1', '.cmd')) { return $command } + + # npm's PowerShell shim pipes text to the executable and re-encodes stdin. + # Resolve the official v2 shim's target so prompt bytes reach OpenCode intact. + $native = Join-Path (Split-Path -Parent $command.Source) 'node_modules/@opencode/cli/bin/opencode.exe' + if ((Test-Path -LiteralPath $native -PathType Leaf) -and (Get-Content -LiteralPath $command.Source -Raw) -match '@opencode[/\\]cli[/\\]bin[/\\]opencode') { + return [pscustomobject]@{ FileName = $native; Source = $native; Prefix = @() } + } + return $command +} + function Invoke-OpenCodeCli { param( [Parameter(Mandatory = $true)][object]$CommandInfo, @@ -109,7 +124,7 @@ function Invoke-OpenCodeCli { ) $allArguments = @($CommandInfo.Prefix) + @($Arguments) - return Invoke-RunnerProcess -FileName $CommandInfo.FileName -ArgumentList $allArguments -WorkingDirectory $Inputs.Run.WorkingDirectoryPath -Environment $Environment -InputBytes $InputBytes -TimeoutSeconds $TimeoutSeconds -ProgressContext (Get-RunnerModelProgressContext -Runner 'opencode' -Phase 'opencode-cli') + return Invoke-RunnerProcess -Utf8Output -FileName $CommandInfo.FileName -ArgumentList $allArguments -WorkingDirectory $Inputs.Run.WorkingDirectoryPath -Environment $Environment -InputBytes $InputBytes -TimeoutSeconds $TimeoutSeconds -ProgressContext (Get-RunnerModelProgressContext -Runner 'opencode' -Phase 'opencode-cli') } function Get-OpenCodeHelpResult { @@ -137,10 +152,12 @@ function Get-OpenCodeDebugConfigResult { param( [Parameter(Mandatory = $true)][object]$CommandInfo, [Parameter(Mandatory = $true)][object]$Inputs, - [Parameter(Mandatory = $true)][System.Collections.IDictionary]$Environment + [Parameter(Mandatory = $true)][System.Collections.IDictionary]$Environment, + [switch]$V2 ) - return Invoke-OpenCodeCli -CommandInfo $CommandInfo -Arguments @('debug', 'config') -Inputs $Inputs -Environment $Environment -TimeoutSeconds 30 + $arguments = if ($V2) { @('--standalone', 'debug', 'config') } else { @('debug', 'config') } + return Invoke-OpenCodeCli -CommandInfo $CommandInfo -Arguments $arguments -Inputs $Inputs -Environment $Environment -TimeoutSeconds 30 } function Get-OpenCodeCandidateSkillName { @@ -170,6 +187,22 @@ function Get-OpenCodeSkillPermissionPolicy { return $permission } +function ConvertFrom-OpenCodeV2SkillRules { + param([AllowEmptyCollection()][object[]]$Rules) + + $skillRules = [ordered]@{} + foreach ($entry in $Rules) { + $action = [string](Get-JsonProperty -Object $entry -Name 'action' -Default '') + $resource = [string](Get-JsonProperty -Object $entry -Name 'resource' -Default '') + if ($action -eq 'skill' -or ($action -eq '*' -and $resource -eq '*')) { + if ($resource -eq '*') { $skillRules.Clear() } + $skillRules[$resource] = [string](Get-JsonProperty -Object $entry -Name 'effect' -Default '') + } + } + if ($skillRules.Count -eq 1 -and $skillRules['*'] -eq 'deny') { return 'deny' } + return $skillRules +} + function Test-OpenCodePathEqual { param( [AllowEmptyString()][string]$Expected, @@ -208,10 +241,11 @@ function Get-OpenCodeRuntimeHomeObservation { param( [Parameter(Mandatory = $true)][object]$CommandInfo, [Parameter(Mandatory = $true)][object]$Inputs, - [Parameter(Mandatory = $true)][System.Collections.IDictionary]$Environment + [Parameter(Mandatory = $true)][System.Collections.IDictionary]$Environment, + [switch]$V2 ) - $nodeInfo = Resolve-ExternalCommand -Name 'node' + $nodeInfo = if (-not $V2) { Resolve-ExternalCommand -Name 'node' } if ($null -ne $nodeInfo) { try { $probe = Invoke-RunnerProcess -FileName $nodeInfo.FileName -ArgumentList (@($nodeInfo.Prefix) + @('-p', 'require("os").homedir()')) -WorkingDirectory $Inputs.Run.WorkingDirectoryPath -Environment $Environment -TimeoutSeconds 30 @@ -243,12 +277,20 @@ function Get-OpenCodeRuntimeHomeObservation { if ($paths.ExitCode -eq 0 -and -not $paths.TimedOut -and $pathLine.Count -eq 1) { $match = [regex]::Match([string]$pathLine[0], '(?i)^\s*home\s*:?[ \t]+(?.+?)\s*$') if ($match.Success -and -not [string]::IsNullOrWhiteSpace($match.Groups['path'].Value)) { + if ($V2) { + foreach ($name in @('data', 'cache', 'config', 'state', 'db')) { + $nativePath = [regex]::Match($paths.Stdout, "(?im)^\s*$name\s*:?[ \t]+(?[^\r\n]+)") + if (-not $nativePath.Success -or -not (Test-PathInside -BasePath $Inputs.Run.HomeDirectoryPath -CandidatePath $nativePath.Groups['path'].Value.Trim())) { + throw "OpenCode v2 did not report an isolated '$name' path." + } + } + } return [pscustomobject]@{ Available = $true Home = $match.Groups['path'].Value.Trim() Source = 'opencode.debug.paths' Process = $paths - Fallback = $true + Fallback = -not $V2 Reason = $null } } @@ -357,8 +399,12 @@ function Get-OpenCodeSkillPolicyObservation { } try { $config = [IO.File]::ReadAllText($configPath, [Text.UTF8Encoding]::new($false)) | ConvertFrom-Json -Depth 50 - $permission = Get-JsonProperty -Object $config -Name 'permission' -Default $null - $actualPermission = Get-JsonProperty -Object $permission -Name 'skill' -Default $null + $actualPermission = if (Test-JsonProperty -Object $config -Name 'permissions') { + ConvertFrom-OpenCodeV2SkillRules -Rules @($config.permissions) + } else { + $permission = Get-JsonProperty -Object $config -Name 'permission' -Default $null + Get-JsonProperty -Object $permission -Name 'skill' -Default $null + } $observation.available = $true $observation.configured_permission_skill = $actualPermission $observation.permission_match = ($actualPermission | ConvertTo-Json -Depth 20 -Compress) -eq ($expectedPermission | ConvertTo-Json -Depth 20 -Compress) @@ -373,7 +419,8 @@ function Get-OpenCodeSkillPolicyObservation { function Get-OpenCodeDebugConfigObservation { param( [Parameter(Mandatory = $true)][object]$DebugResult, - [Parameter(Mandatory = $true)][object]$Inputs + [Parameter(Mandatory = $true)][object]$Inputs, + [switch]$V2 ) $expectedPermission = Get-OpenCodeSkillPermissionPolicy -Inputs $Inputs @@ -384,15 +431,23 @@ function Get-OpenCodeDebugConfigObservation { output_sha256 = $null reason = $null } - $text = [string]::Join("`n", @($DebugResult.Stdout, $DebugResult.Stderr)).Trim() + $text = if ($V2) { $DebugResult.Stdout.Trim() } else { [string]::Join("`n", @($DebugResult.Stdout, $DebugResult.Stderr)).Trim() } if ($DebugResult.TimedOut -or $DebugResult.ExitCode -ne 0 -or [string]::IsNullOrWhiteSpace($text)) { $observation.reason = "opencode debug config failed (exit=$($DebugResult.ExitCode), timed_out=$($DebugResult.TimedOut))." return [pscustomobject]$observation } try { $config = $text | ConvertFrom-Json -Depth 50 - $permission = Get-JsonProperty -Object $config -Name 'permission' -Default $null - $actualPermission = Get-JsonProperty -Object $permission -Name 'skill' -Default $null + if ($V2) { + $rules = @(foreach ($source in @($config)) { + $info = Get-JsonProperty -Object $source -Name 'info' -Default $null + Get-JsonProperty -Object $info -Name 'permissions' -Default @() + }) + $actualPermission = ConvertFrom-OpenCodeV2SkillRules -Rules $rules + } else { + $permission = Get-JsonProperty -Object $config -Name 'permission' -Default $null + $actualPermission = Get-JsonProperty -Object $permission -Name 'skill' -Default $null + } $observation.available = $true $observation.permission_skill = $actualPermission $observation.permission_match = ($actualPermission | ConvertTo-Json -Depth 20 -Compress) -eq ($expectedPermission | ConvertTo-Json -Depth 20 -Compress) @@ -621,11 +676,17 @@ function Remove-OpenCodeAnsiSequences { } function Get-OpenCodeContinuationCapability { - param([Parameter(Mandatory = $true)][AllowEmptyString()][string]$HelpText) + param([Parameter(Mandatory = $true)][AllowEmptyString()][string]$HelpText, [switch]$V2) $cleanText = Remove-OpenCodeAnsiSequences -Text $HelpText $lines = @($cleanText -split "`r?`n") $flag = '--session' + if ($V2) { + $entry = [regex]::Match($cleanText, '(?im)^\s*--session(?:,\s*-s)?\s+string\s+Session ID to continue[^\r\n]*') + if ($entry.Success) { + return [pscustomobject]@{ Available = $true; Flag = $flag; ArgumentStyle = 'separate'; Parameter = 'session-id'; HelpEvidence = $entry.Value.Trim(); Reason = $null } + } + } $flagPattern = [regex]::Escape($flag) for ($lineIndex = 0; $lineIndex -lt $lines.Count; $lineIndex++) { $line = [string]$lines[$lineIndex] @@ -745,6 +806,65 @@ function Invoke-OpenCodeTurnProcess { return Invoke-OpenCodeCli -CommandInfo $CommandInfo -Arguments $Arguments -Inputs $Inputs -Environment $Environment -InputBytes $InputBytes -TimeoutSeconds $TimeoutSeconds } +function Get-OpenCodeV2ModelSelection { + param([Parameter(Mandatory)][object]$Profile) + + $selector = [string]$Profile.Model + $match = [regex]::Match($selector, '^(?[^\s/#]+)/(?[^\s#]+)(?:#(?[^\s/#]+))?$') + if (-not $match.Success) { throw 'OpenCode v2 requires a provider/model selector with an optional #variant.' } + $variant = $match.Groups['variant'].Value + $effort = [string]$Profile.ReasoningEffort + if ($effort -and $effort -notmatch '^[^\s/#]+$') { throw 'OpenCode v2 reasoning_effort must name one model variant.' } + if ($variant -and $effort -and $variant -cne $effort) { throw 'OpenCode v2 model #variant conflicts with reasoning_effort.' } + if ($effort -and -not $variant) { + $variant = $effort + $selector += "#$variant" + } + return [pscustomobject]@{ Selector = $selector; Provider = $match.Groups['provider'].Value; Id = $match.Groups['id'].Value; Variant = $variant } +} + +function Read-OpenCodeV2SessionEvidence { + param( + [Parameter(Mandatory)][object]$Inputs, + [Parameter(Mandatory)][object]$CommandInfo, + [Parameter(Mandatory)][System.Collections.IDictionary]$Environment, + [Parameter(Mandatory)][string]$Platform, + [object]$SandboxInfo, + [Parameter(Mandatory)][string]$SessionId, + [Parameter(Mandatory)][string]$Prompt, + [Parameter(Mandatory)][int]$Turn + ) + + $export = Invoke-OpenCodeTurnProcess -Inputs $Inputs -CommandInfo $CommandInfo -Arguments @('--standalone', 'session', 'export', $SessionId) -Environment $Environment -Platform $Platform -SandboxInfo $SandboxInfo -InputBytes @() -TimeoutSeconds 30 + if ($export.TimedOut -or $export.ExitCode -ne 0) { + throw "OpenCode v2 session export did not succeed for turn $Turn (exit=$($export.ExitCode), timed_out=$($export.TimedOut))." + } + $session = $export.Stdout | ConvertFrom-Json -Depth 100 + $info = $session.info + $visiblePlatform = if ($Platform -eq 'linux' -and $null -eq $SandboxInfo) { 'unknown' } else { $Platform } + $directory = Get-SandboxVisiblePath -HostPath $Inputs.Run.WorkingDirectoryPath -RunRoot $Inputs.Run.RunRoot -Platform $visiblePlatform + if ($info.id -cne $SessionId -or $info.outcome -ne 'succeeded' -or (Get-JsonProperty -Object $info -Name 'parentID' -Default $null) -or (Get-JsonProperty -Object $info -Name 'fork' -Default $null) -or -not (Test-OpenCodePathEqual -Expected $directory -Observed $info.location.directory)) { + throw "OpenCode v2 export did not prove the expected successful session and working directory for turn $Turn." + } + + $users = @($session.messages | Where-Object type -eq 'user') + $assistant = @($session.messages | Where-Object type -eq 'assistant' | Select-Object -Last 1) + if ($users.Count -ne $Turn -or $assistant.Count -ne 1) { + throw "OpenCode v2 export recorded $($users.Count) user prompts instead of $Turn or omitted the assistant turn." + } + $promptObserved = [string]$users[-1].text + if ($promptObserved -cne $Prompt) { + throw "OpenCode v2 export changed the prompt for turn $Turn (expected $($Prompt.Length) characters, observed $($promptObserved.Length))." + } + $selection = Get-OpenCodeV2ModelSelection -Profile $Inputs.Profile + foreach ($observed in @($info.model, $assistant[0].model)) { + if ($observed.providerID -cne $selection.Provider -or $observed.id -cne $selection.Id -or ($selection.Variant -and $observed.variant -cne $selection.Variant)) { + throw "OpenCode v2 export did not prove the selected model '$($selection.Selector)' for turn $Turn." + } + } + return [pscustomobject]@{ Json = $export.Stdout; Model = [string]$Inputs.Profile.Model; Variant = [string]$info.model.variant } +} + function Invoke-OpenCodeScriptedExecute { param( [Parameter(Mandatory = $true)][object]$Inputs, @@ -754,7 +874,8 @@ function Invoke-OpenCodeScriptedExecute { ) $started = [DateTime]::UtcNow - $commandInfo = Resolve-ExternalCommand -Name 'opencode' + $commandInfo = Resolve-OpenCodeCommand + $v2 = Test-OpenCodeV2Version -Version ([string]$Preflight.harness.version) $platform = Get-PlatformName $sandboxInfo = if ($platform -eq 'linux') { Resolve-SandboxCommand -Name 'bwrap' } elseif ($platform -eq 'macos') { Resolve-SandboxCommand -Name 'sandbox-exec' } else { $null } $hardFilesystem = $null -ne $sandboxInfo -and $platform -in @('linux', 'macos') @@ -779,8 +900,12 @@ function Invoke-OpenCodeScriptedExecute { try { $projection = New-OpenCodeExecutionProjection -Inputs $Inputs $executionInputs = $projection.Inputs - $environment = New-OpenCodeEnvironment -Inputs $executionInputs - $runtimeHomeObservation = Get-OpenCodeRuntimeHomeObservation -CommandInfo $commandInfo -Inputs $executionInputs -Environment $environment + $readiness = @(Invoke-OpenCodeReadiness -Inputs $executionInputs -CommandInfo $commandInfo) + if (@($readiness | Where-Object status -ne 'ready').Count -gt 0) { + return New-EvalReadinessFailureResult -Descriptor $ExecutionDescriptor -Inputs $Inputs -Readiness $readiness -SessionId ([Guid]::NewGuid().ToString('D')) -Started $started + } + $environment = New-OpenCodeEnvironment -Inputs $executionInputs -V2:$v2 + $runtimeHomeObservation = Get-OpenCodeRuntimeHomeObservation -CommandInfo $commandInfo -Inputs $executionInputs -Environment $environment -V2:$v2 $homeIsolationObservation = Get-OpenCodeHomeIsolationObservation -Inputs $executionInputs -Environment $environment -RuntimeHome $runtimeHomeObservation $policyObservation = Get-OpenCodeSkillPolicyObservation -Inputs $executionInputs -Environment $environment $skillIsolationObservation = Get-OpenCodeSkillRootObservation -Inputs $executionInputs @@ -793,7 +918,7 @@ function Invoke-OpenCodeScriptedExecute { return $result } $requestedTurns = @($Inputs.Run.Interaction.turns) - $baseArguments = New-OpenCodeCliArguments -Inputs $executionInputs -VisiblePlatform $visiblePlatform + $baseArguments = New-OpenCodeCliArguments -Inputs $executionInputs -VisiblePlatform $visiblePlatform -V2:$v2 $turnRecords = [System.Collections.Generic.List[object]]::new() $nativeTurns = [System.Collections.Generic.List[object]]::new() $rawStdout = [System.Collections.Generic.List[string]]::new() @@ -866,6 +991,20 @@ function Invoke-OpenCodeScriptedExecute { $parsed = if ([string]::IsNullOrEmpty([string]$process.Stdout)) { [pscustomobject]@{ Events = @(); Errors = @() } } else { ConvertFrom-JsonLines -Text $process.Stdout } foreach ($parseError in @($parsed.Errors)) { $warnings.Add("OpenCode turn $turnNumber event parse error: $parseError") } $parsedEvents = Read-OpenCodeScriptedTurn -Parsed $parsed -Warnings $warnings + $sessionIds = @($parsedEvents.SessionIds) + $observedSessionId = if ($sessionIds.Count -eq 1) { [string]$sessionIds[0] } else { $null } + $exportArtifact = $null + $exportFailure = $null + if ($v2 -and -not $process.TimedOut -and $process.ExitCode -eq 0 -and $parsedEvents.TerminalEventObserved -and $observedSessionId -and ($turnIndex -eq 0 -or $observedSessionId -ceq $targetSessionId)) { + try { + $export = Read-OpenCodeV2SessionEvidence -Inputs $executionInputs -CommandInfo $commandInfo -Environment $environment -Platform $platform -SandboxInfo $sandboxInfo -SessionId $observedSessionId -Prompt $turnText -Turn $turnNumber + $exportArtifact = Write-OpenCodeCapture -RunData $Inputs -RelativePath "evidence/opencode-turn-$turnNumber-session.json" -Text $export.Json + $artifacts.Add($exportArtifact) + $parsedEvents.ObservedModels = @($parsedEvents.ObservedModels + @($export.Model) | Select-Object -Unique) + } catch { + $exportFailure = $_.Exception.Message + } + } $turnTiming = [ordered]@{ turn = $turnNumber invocation = if ($turnIndex -eq 0) { 'fresh' } else { 'explicit_session_resume' } @@ -887,15 +1026,13 @@ function Invoke-OpenCodeScriptedExecute { $usageBuckets[$usageName] = Add-OpenCodeNullableInt64 -Current (Get-JsonProperty -Object $usageBuckets -Name $usageName -Default $null) -Value $parsedEvents.UsageBuckets[$usageName] } - $sessionIds = @($parsedEvents.SessionIds) - $observedSessionId = if ($sessionIds.Count -eq 1) { [string]$sessionIds[0] } else { $null } $nativeTurn = [ordered]@{ turn = $turnNumber invocation = if ($turnIndex -eq 0) { 'fresh' } else { 'explicit_session_resume' } arguments = @($arguments) requested_model = [string]$Inputs.Profile.Model observed_models = @($parsedEvents.ObservedModels) - model_source = if (@($parsedEvents.ObservedModels).Count -gt 0) { 'structured_event' } else { 'cli_argument' } + model_source = if ($exportArtifact) { 'session_export' } elseif (@($parsedEvents.ObservedModels).Count -gt 0) { 'structured_event' } else { 'cli_argument' } session_ids_observed = @($sessionIds) session_id = $observedSessionId target_session_id = $targetSessionId @@ -924,6 +1061,10 @@ function Invoke-OpenCodeScriptedExecute { if ($null -ne $parsedEvents.EventTiming) { $nativeTurn.event_timing = $parsedEvents.EventTiming } + if ($exportArtifact) { + $nativeTurn.session_export = $exportArtifact.path + $nativeTurn.observed_variant = $export.Variant + } $nativeTurns.Add($nativeTurn) if ($turnIndex -eq 1 -and $nativeTurns.Count -ge 2) { $turnTwoSentAfterTurnOneTerminal = [DateTime]::Compare([DateTime]$nativeTurns[0].finished_utc, [DateTime]$nativeTurn.started_utc) -le 0 @@ -936,6 +1077,7 @@ function Invoke-OpenCodeScriptedExecute { elseif ($sessionIds.Count -ne 1) { $turnProblem = 'session_id_unobservable'; $status = 'incompatible'; $failureCode = 'native_interaction_incompatible'; $failureMessage = "OpenCode turn $turnNumber did not expose exactly one session id in structured events." } elseif ($turnIndex -gt 0 -and $observedSessionId -ne $targetSessionId) { $turnProblem = 'session_identity_mismatch'; $status = 'incompatible'; $failureCode = 'native_interaction_incompatible'; $failureMessage = "OpenCode turn $turnNumber returned session '$observedSessionId' instead of the exact resumed session '$targetSessionId'." } elseif ([string]::IsNullOrWhiteSpace([string]$parsedEvents.FinalText) -or -not [bool]$parsedEvents.TerminalEventObserved) { $turnProblem = 'terminal_turn_status'; $status = 'incompatible'; $failureCode = 'native_interaction_incompatible'; $failureMessage = "OpenCode turn $turnNumber did not provide a terminal structured assistant response before continuation." } + elseif ($v2 -and -not $exportArtifact) { $turnProblem = 'session_export'; $status = 'incompatible'; $failureCode = 'native_interaction_incompatible'; $failureMessage = $exportFailure } elseif (@($parsedEvents.ObservedModels | Where-Object { [string]$_ -ne [string]$Inputs.Profile.Model }).Count -gt 0) { $turnProblem = 'requested_model'; $status = 'incompatible'; $failureCode = 'native_interaction_incompatible'; $failureMessage = "OpenCode turn $turnNumber reported a model different from the requested model '$($Inputs.Profile.Model)'." } if ($null -ne $turnProblem) { $nativeFailures.Add($turnProblem) @@ -1096,8 +1238,10 @@ function Invoke-OpenCodeScriptedExecute { } native_worker_evidence_failures = @($nativeFailures | Select-Object -Unique) } + if ($readiness.Count -gt 0) { $evidence.readiness = $readiness } $mechanisms = [System.Collections.Generic.List[string]]::new() - foreach ($mechanism in @('runner-owned fresh OpenCode process for turn 1', 'opencode run --format json structured event capture', 'prompt on stdin', '--model on every turn', '--dir on every turn', 'isolated OPENCODE_CONFIG_DIR and OPENCODE_CONFIG', 'isolated HOME/XDG roots', 'coherent Windows HOME/USERPROFILE/HOMEDRIVE/HOMEPATH', 'OPENCODE_DISABLE_EXTERNAL_SKILLS=1', 'OPENCODE_DISABLE_CLAUDE_CODE_SKILLS=1', 'permission.skill arm policy', 'same isolated environment on every turn', 'repository-owned project configuration preserved', 'no implicit last-session continuation')) { $mechanisms.Add($mechanism) } + foreach ($mechanism in @('runner-owned fresh OpenCode process for turn 1', 'opencode run --format json structured event capture', 'prompt on stdin', '--model on every turn', 'projected working directory on every turn', 'isolated OPENCODE_CONFIG_DIR and OPENCODE_CONFIG', 'isolated HOME/XDG roots', 'coherent Windows HOME/USERPROFILE/HOMEDRIVE/HOMEPATH', 'OPENCODE_DISABLE_EXTERNAL_SKILLS=1', 'OPENCODE_DISABLE_CLAUDE_CODE_SKILLS=1', 'arm-specific skill permissions', 'same isolated environment on every turn', 'repository-owned project configuration preserved', 'no implicit last-session continuation')) { $mechanisms.Add($mechanism) } + if ($v2) { $mechanisms.Add('private standalone server and native session export') } $mechanisms.Add(("explicit OpenCode {0} continuation selected from installed help" -f $continuationCapability.Flag)) if ($hardFilesystem) { $mechanisms.Add("external $($sandboxInfo.Source) filesystem sandbox") } else { $mechanisms.Add('pragmatic process/environment isolation without hard filesystem confinement') } if (-not $hardFilesystem) { $warnings.Add('Hard filesystem confinement was unavailable; the completed arm is reported as pragmatic isolation.') } @@ -1114,7 +1258,7 @@ function Invoke-OpenCodeScriptedExecute { if ($null -ne $projection) { try { Remove-OpenCodeProjectedCandidateSkill -Projection $projection - Sync-OpenCodeProjectedRepository -Projection $projection + if ($null -ne $environment) { Sync-OpenCodeProjectedRepository -Projection $projection } } finally { Remove-OpenCodeExecutionProjection -Projection $projection if ($null -ne $result -and $null -ne $result.evidence -and $null -ne $result.evidence.execution_paths) { @@ -1211,7 +1355,7 @@ function Resolve-SandboxCommand { function Get-OpenCodeDescriptor { $copy = [ordered]@{} foreach ($key in $descriptor.Keys) { $copy[$key] = $descriptor[$key] } - $commandInfo = Resolve-ExternalCommand -Name 'opencode' + $commandInfo = Resolve-OpenCodeCommand $version = 'unavailable' if ($null -ne $commandInfo) { $observation = Get-ExternalCommandVersion -CommandInfo $commandInfo @@ -1224,8 +1368,13 @@ function Get-OpenCodeDescriptor { function New-OpenCodeCliArguments { param( [Parameter(Mandatory = $true)][object]$Inputs, - [ValidateSet('windows', 'linux', 'macos', 'unknown')][string]$VisiblePlatform = (Get-PlatformName) + [ValidateSet('windows', 'linux', 'macos', 'unknown')][string]$VisiblePlatform = (Get-PlatformName), + [switch]$V2 ) + if ($V2) { + $selection = Get-OpenCodeV2ModelSelection -Profile $Inputs.Profile + return @('--standalone', 'run', '--format', 'json', '--model', $selection.Selector, '--auto', '--title', 'Skill evaluation') + } $directoryArgument = Get-SandboxVisiblePath -HostPath $Inputs.Run.WorkingDirectoryPath -RunRoot $Inputs.Run.RunRoot -Platform $VisiblePlatform $arguments = [System.Collections.Generic.List[string]]::new() foreach ($argument in @('run', '--format', 'json', '--dir', $directoryArgument, '--model', $Inputs.Profile.Model, '--auto')) { @@ -1418,6 +1567,10 @@ function New-OpenCodeExecutionProjection { } Copy-OpenCodeProjectionDirectory -Source $Inputs.Run.WorkingDirectoryPath -Destination $physicalRepo -ExcludeRelativePaths @($excludedRepositoryFiles.ToArray()) Copy-OpenCodeProjectionDirectory -Source $Inputs.Run.HomeDirectoryPath -Destination $physicalHome -ExcludeRelativePaths @($excludedHomeFiles.ToArray()) + $dependencies = Join-Path $Inputs.Run.RunRoot 'dependencies' + if (Test-Path -LiteralPath $dependencies -PathType Container) { + Copy-OpenCodeProjectionDirectory -Source $dependencies -Destination (Join-Path $plan.Root 'dependencies') + } $physicalSkill = $null $physicalSkillHash = $null @@ -1433,7 +1586,7 @@ function New-OpenCodeExecutionProjection { throw "OpenCode physical repository already contains a native candidate skill at '$physicalSkill'." } Copy-OpenCodeProjectionDirectory -Source $Inputs.Run.SkillDirectoryPath -Destination $physicalSkill - if (Test-JsonProperty -Object $Inputs.Run.Contract -Name 'skillExposure') { + if ((Test-JsonProperty -Object $Inputs.Run.Contract -Name 'skillExposure') -and -not (Test-PathInside -BasePath $dependencies -CandidatePath $Inputs.Run.SkillDirectoryPath)) { $stagedRelative = [IO.Path]::GetRelativePath($Inputs.Run.RunRoot, $Inputs.Run.SkillDirectoryPath) Copy-OpenCodeProjectionDirectory -Source $Inputs.Run.SkillDirectoryPath -Destination (Join-Path $plan.Root $stagedRelative) } @@ -1646,7 +1799,7 @@ function Save-OpenCodePreflightObservation { ) if ([string]$Preflight.status -ne 'compatible') { return $null } - $commandInfo = Resolve-ExternalCommand -Name 'opencode' + $commandInfo = Resolve-OpenCodeCommand if ($null -eq $commandInfo) { return $null } $identity = Get-OpenCodePreflightCacheIdentity -Inputs $Inputs -CommandInfo $commandInfo if ($null -eq $identity) { return $null } @@ -1665,7 +1818,7 @@ function Save-OpenCodePreflightObservation { function Get-OpenCodeCachedPreflight { param([Parameter(Mandatory = $true)][object]$Inputs) - $commandInfo = Resolve-ExternalCommand -Name 'opencode' + $commandInfo = Resolve-OpenCodeCommand if ($null -eq $commandInfo) { return [pscustomobject]@{ Hit = $false; Preflight = $null; CachePath = $null; Source = 'fresh_preflight' } } $identity = Get-OpenCodePreflightCacheIdentity -Inputs $Inputs -CommandInfo $commandInfo if ($null -eq $identity -or -not (Test-Path -LiteralPath $identity.Path -PathType Leaf)) { @@ -1703,7 +1856,10 @@ function Get-OpenCodeEventTiming { $parsed = [System.Collections.Generic.List[DateTimeOffset]]::new() foreach ($timestamp in @($Timestamps)) { $value = [DateTimeOffset]::MinValue - if ([DateTimeOffset]::TryParse([string]$timestamp, [Globalization.CultureInfo]::InvariantCulture, [Globalization.DateTimeStyles]::RoundtripKind, [ref]$value)) { + $milliseconds = 0L + if ([long]::TryParse($timestamp, [ref]$milliseconds) -and $milliseconds -ge 0 -and $milliseconds -le 253402300799999) { + $parsed.Add([DateTimeOffset]::FromUnixTimeMilliseconds($milliseconds)) + } elseif ([DateTimeOffset]::TryParse([string]$timestamp, [Globalization.CultureInfo]::InvariantCulture, [Globalization.DateTimeStyles]::RoundtripKind, [ref]$value)) { $parsed.Add($value) } } @@ -1750,17 +1906,19 @@ function Get-OpenCodePreflight { $profile = $Inputs.Profile $run = $Inputs.Run $platform = Get-PlatformName - $commandInfo = Resolve-ExternalCommand -Name 'opencode' + $commandInfo = Resolve-OpenCodeCommand $sandboxInfo = if ($platform -eq 'linux') { Resolve-SandboxCommand -Name 'bwrap' } elseif ($platform -eq 'macos') { Resolve-SandboxCommand -Name 'sandbox-exec' } else { $null } $versionObservation = $null $help = $null $debugHelp = $null $debugConfig = $null + $sessionHelp = $null $runtimeHomeObservation = $null $homeIsolationObservation = $null $policyObservation = $null $debugConfigObservation = $null $openCodeEnvironment = $null + $v2 = $false $continuationCapability = [pscustomobject]@{ Available = $false Flag = $null @@ -1809,17 +1967,17 @@ function Get-OpenCodePreflight { } else { $checks.Add((New-PreflightCheck -Name 'harness_executable' -Status passed -Detail $commandInfo.Source)) try { - # Build the exact child environment once. Every model-free probe - # and every later OpenCode turn uses this same isolation policy. - $openCodeEnvironment = New-OpenCodeEnvironment -Inputs $Inputs - $versionObservation = Get-ExternalCommandVersion -CommandInfo $commandInfo -WorkingDirectory $run.WorkingDirectoryPath -Environment $openCodeEnvironment -TimeoutSeconds 30 + $versionEnvironment = New-RunnerEnvironment -Run $run + $versionObservation = Get-ExternalCommandVersion -CommandInfo $commandInfo -WorkingDirectory $run.WorkingDirectoryPath -Environment $versionEnvironment -TimeoutSeconds 30 if (-not $versionObservation.Available) { $reasons.Add('The OpenCode CLI did not expose an exact observable version through --version.') $checks.Add((New-PreflightCheck -Name 'harness_version' -Status unavailable -Detail 'opencode --version did not return a usable version string.')) } else { $checks.Add((New-PreflightCheck -Name 'harness_version' -Status passed -Detail ([string]$versionObservation.Version))) } - $runtimeHomeObservation = Get-OpenCodeRuntimeHomeObservation -CommandInfo $commandInfo -Inputs $Inputs -Environment $openCodeEnvironment + $v2 = Test-OpenCodeV2Version -Version ([string]$versionObservation.Version) + $openCodeEnvironment = New-OpenCodeEnvironment -Inputs $Inputs -WithoutAuthentication -V2:$v2 + $runtimeHomeObservation = Get-OpenCodeRuntimeHomeObservation -CommandInfo $commandInfo -Inputs $Inputs -Environment $openCodeEnvironment -V2:$v2 $homeIsolationObservation = Get-OpenCodeHomeIsolationObservation -Inputs $Inputs -Environment $openCodeEnvironment -RuntimeHome $runtimeHomeObservation if ([bool]$homeIsolationObservation.Valid) { $checks.Add((New-PreflightCheck -Name 'effective_home' -Status passed -Detail ("Node/OpenCode resolved home '{0}' from the isolated child environment." -f $homeIsolationObservation.RuntimeHome))) @@ -1844,16 +2002,23 @@ function Get-OpenCodePreflight { } } else { $helpText = [string]::Join("`n", @($help.Stdout, $help.Stderr)) - foreach ($flag in @('--format', '--dir', '--model', '--auto')) { + $requiredFlags = if ($v2) { @('--format', '--standalone', '--model', '--auto', '--title') } else { @('--format', '--dir', '--model', '--auto') } + foreach ($flag in $requiredFlags) { if ($helpText -notmatch [regex]::Escape($flag)) { $reasons.Add("The installed OpenCode CLI does not advertise required flag '$flag'.") } } - if (-not [string]::IsNullOrWhiteSpace([string]$profile.ReasoningEffort) -and $helpText -notmatch [regex]::Escape('--variant')) { + if ($v2) { + $sessionHelp = Invoke-OpenCodeCli -CommandInfo $commandInfo -Arguments @('session', '--help') -Inputs $Inputs -Environment $openCodeEnvironment -TimeoutSeconds 30 + if ($sessionHelp.TimedOut -or $sessionHelp.ExitCode -ne 0 -or $sessionHelp.Stdout -notmatch '(?im)^\s*export\s+') { + $reasons.Add('OpenCode v2 must expose session export for terminal model and prompt verification.') + } + } + if (-not $v2 -and -not [string]::IsNullOrWhiteSpace([string]$profile.ReasoningEffort) -and $helpText -notmatch [regex]::Escape('--variant')) { $reasons.Add("execution-profile.json requests reasoning_effort '$($profile.ReasoningEffort)', but the installed OpenCode CLI does not advertise --variant.") } $visiblePlatform = if ($platform -eq 'linux' -and $null -ne $sandboxInfo) { 'linux' } else { $platform } - $constructed = New-OpenCodeCliArguments -Inputs $Inputs -VisiblePlatform $visiblePlatform + $constructed = New-OpenCodeCliArguments -Inputs $Inputs -VisiblePlatform $visiblePlatform -V2:$v2 foreach ($forbidden in @('--pure', '--continue', '--session')) { if (@($constructed) -contains $forbidden) { $reasons.Add("The constructed OpenCode invocation must not use session or project-suppression option '$forbidden'.") } } @@ -1861,14 +2026,16 @@ function Get-OpenCodePreflight { $debugHelpText = [string]::Join("`n", @($debugHelp.Stdout, $debugHelp.Stderr)) $debugConfigAdvertised = -not $debugHelp.TimedOut -and $debugHelp.ExitCode -eq 0 -and $debugHelpText -match '(?i)(^|\s)config(\s|$)' if ($debugConfigAdvertised) { - $debugConfig = Get-OpenCodeDebugConfigResult -CommandInfo $commandInfo -Inputs $Inputs -Environment $openCodeEnvironment - $debugConfigObservation = Get-OpenCodeDebugConfigObservation -DebugResult $debugConfig -Inputs $Inputs + $debugConfig = Get-OpenCodeDebugConfigResult -CommandInfo $commandInfo -Inputs $Inputs -Environment $openCodeEnvironment -V2:$v2 + $debugConfigObservation = Get-OpenCodeDebugConfigObservation -DebugResult $debugConfig -Inputs $Inputs -V2:$v2 if (-not [bool]$debugConfigObservation.available -or -not [bool]$debugConfigObservation.permission_match) { $checks.Add((New-PreflightCheck -Name 'skill_permission_debug' -Status failed -Detail ([string]$debugConfigObservation.reason))) $reasons.Add('Installed OpenCode advertises debug config, but its effective permission.skill policy was not proven: ' + [string]$debugConfigObservation.reason) } else { $checks.Add((New-PreflightCheck -Name 'skill_permission_debug' -Status passed -Detail 'Installed OpenCode debug config reports the exact permission.skill policy for this arm.')) } + } elseif ($v2) { + $reasons.Add('OpenCode v2 must expose the isolated configuration and permission rules through debug config.') } else { $checks.Add((New-PreflightCheck -Name 'skill_permission_debug' -Status not_applicable -Detail 'Installed OpenCode does not advertise a model-free debug config command; filesystem/home isolation remains authoritative.')) } @@ -1876,10 +2043,10 @@ function Get-OpenCodePreflight { $checks.Add((New-PreflightCheck -Name 'harness_contract' -Status passed -Detail 'OpenCode run advertises noninteractive, model, directory, and structured-output controls; the adapter intentionally does not use --pure.')) } if ($null -ne $run.Interaction) { - $continuationProbe = Get-OpenCodeContinuationCapability -HelpText $helpText + $continuationProbe = Get-OpenCodeContinuationCapability -HelpText $helpText -V2:$v2 $continuationCapability = $continuationProbe if ([bool]$continuationProbe.Available) { - $checks.Add((New-PreflightCheck -Name 'scripted_multi_turn_same_session' -Status passed -Detail ("OpenCode run --help proves explicit exact-session continuation through {0} {1}; resumed invocations retain --format json, --model, --dir, --auto, and the isolated environment." -f $continuationProbe.Flag, $continuationProbe.Parameter))) + $checks.Add((New-PreflightCheck -Name 'scripted_multi_turn_same_session' -Status passed -Detail ("OpenCode run --help proves explicit continuation through {0} {1}; resumed invocations retain the model, isolated location, and environment." -f $continuationProbe.Flag, $continuationProbe.Parameter))) } else { $checks.Add((New-PreflightCheck -Name 'scripted_multi_turn_same_session' -Status failed -Detail $continuationCapability.Reason)) $reasons.Add('scripted_multi_turn_same_session is incompatible: ' + $continuationCapability.Reason) @@ -1953,12 +2120,15 @@ function Get-OpenCodePreflight { $mechanisms.Add('no scripted continuation') } if ($hardConfinement) { $mechanisms.Add("external $($sandboxInfo.Source) filesystem sandbox") } else { $mechanisms.Add('pragmatic process/environment isolation without hard filesystem confinement') } - $requiresReadiness = Test-JsonProperty -Object $run.Contract -Name 'prerequisites' - if ($requiresReadiness) { $reasons.Add('Infrastructure blocked: the OpenCode transport does not currently expose a verified model-free execution probe for declared prerequisites.') } - $document = New-PreflightDocument -Descriptor $descriptorCopy -Profile $profile -Run $run -Compatible ($reasons.Count -eq 0) -Checks @($checks) -Mechanisms @($mechanisms) -ResolvedCapabilities $capabilities -Warnings @($warnings) -Reasons @($reasons) - if ($requiresReadiness) { - $document.readiness = @(@{ id = 'native-command-transport'; command = @(); exit_code = $null; status = 'infrastructure_blocked'; diagnostic = $reasons[$reasons.Count - 1] }) + $readiness = @(Get-EvalStagedReadinessFailure -Run $run -VerifyFixture) + if ($readiness.Count -eq 0 -and $reasons.Count -eq 0 -and (Test-JsonProperty -Object $run.Contract -Name 'prerequisites')) { + $projection = New-OpenCodeExecutionProjection -Inputs $Inputs + try { $readiness = @(Invoke-OpenCodeReadiness -Inputs $projection.Inputs -CommandInfo $commandInfo) } + finally { Remove-OpenCodeExecutionProjection -Projection $projection } } + Add-EvalReadinessFailureReasons -Readiness $readiness -Reasons $reasons + $document = New-PreflightDocument -Descriptor $descriptorCopy -Profile $profile -Run $run -Compatible ($reasons.Count -eq 0) -Checks @($checks) -Mechanisms @($mechanisms) -ResolvedCapabilities $capabilities -Warnings @($warnings) -Reasons @($reasons) + if ($readiness.Count -gt 0) { $document.readiness = $readiness } $preflightFinished = [DateTime]::UtcNow $preflightTiming = [ordered]@{ total_duration_seconds = [Math]::Round(($preflightFinished - $preflightStarted).TotalSeconds, 3) @@ -1984,6 +2154,10 @@ function Get-OpenCodePreflight { $preflightTiming.debug_config_probe_duration_seconds = [double]$debugConfig.DurationSeconds $preflightTiming.probe_count++ } + if ($null -ne $sessionHelp) { + $preflightTiming.session_help_probe_duration_seconds = [double]$sessionHelp.DurationSeconds + $preflightTiming.probe_count++ + } $document.timing = $preflightTiming $document.protocol_observations = [ordered]@{ effective_home = [ordered]@{ @@ -2034,7 +2208,7 @@ function Get-OpenCodePreflight { } function New-OpenCodeEnvironment { - param([Parameter(Mandatory = $true)][object]$Inputs) + param([Parameter(Mandatory = $true)][object]$Inputs, [switch]$WithoutAuthentication, [switch]$V2) # OpenCode 1.18.x resolves its native global config and skills below # XDG_CONFIG_HOME/opencode. Keep that root inside the physical per-run @@ -2048,14 +2222,30 @@ function New-OpenCodeEnvironment { } New-Item -ItemType Directory -Path $configDirectory -Force | Out-Null $configPath = Join-Path $configDirectory 'opencode.json' - $skillPermission = Get-OpenCodeSkillPermissionPolicy -Inputs $Inputs - $config = [ordered]@{ - '$schema' = 'https://opencode.ai/config.json' - permission = [ordered]@{ skill = $skillPermission } + $config = [ordered]@{ '$schema' = 'https://opencode.ai/config.json' } + # Both arms get identical web tool access. A non-interactive run cancels + # any prompt, so web search and web fetch are allowed outright, and v2 + # pre-selects the web search provider ('random', the value OpenCode stores + # when a user answers its "Web Search" provider form with Allow). + if ($V2) { + $config.permissions = @( + @{ action = 'skill'; resource = '*'; effect = 'deny' } + if ($Inputs.Run.CandidateSkillExposed) { + @{ action = 'skill'; resource = (Get-OpenCodeCandidateSkillName -Run $Inputs.Run); effect = 'allow' } + } + @{ action = 'subagent'; resource = '*'; effect = 'deny' } + @{ action = 'websearch'; resource = '*'; effect = 'allow' } + @{ action = 'webfetch'; resource = '*'; effect = 'allow' } + ) + $config.websearch = @{ provider = 'random' } + $config.agents = @{ title = @{ disabled = $true } } + $config.compaction = @{ auto = $false } + } else { + $config.permission = [ordered]@{ skill = (Get-OpenCodeSkillPermissionPolicy -Inputs $Inputs); websearch = 'allow'; webfetch = 'allow' } } Write-RunnerJsonFile -Path $configPath -Value $config -Depth 20 $modelProvider = Get-OpenCodeModelProvider -Model ([string]$Inputs.Profile.Model) - $authVariables = @(if (-not [string]::IsNullOrWhiteSpace($modelProvider)) { Get-ProviderAuthenticationVariables -Provider $modelProvider }) + $authVariables = @(if (-not $WithoutAuthentication -and -not [string]::IsNullOrWhiteSpace($modelProvider)) { Get-ProviderAuthenticationVariables -Provider $modelProvider }) $environment = New-RunnerEnvironment -Run $Inputs.Run -AuthenticationVariables $authVariables -Additional @{ APPDATA = $appDataDirectory LOCALAPPDATA = $localAppDataDirectory @@ -2080,65 +2270,29 @@ function New-OpenCodeEnvironment { return $environment } +function Invoke-OpenCodeReadiness { + param( + [Parameter(Mandatory)][object]$Inputs, + [Parameter(Mandatory)][object]$CommandInfo + ) + + if (-not (Test-JsonProperty -Object $Inputs.Run.Contract -Name 'prerequisites')) { return } + $probeEnvironment = New-OpenCodeEnvironment -Inputs $Inputs -WithoutAuthentication + $platform = Get-PlatformName + $sandbox = if ($platform -eq 'linux') { Resolve-SandboxCommand -Name 'bwrap' } elseif ($platform -eq 'macos') { Resolve-SandboxCommand -Name 'sandbox-exec' } else { $null } + $profilePath = if ($sandbox -and $platform -eq 'macos') { New-MacosSandboxProfile -Inputs $Inputs -CommandInfo $CommandInfo } + Invoke-EvalProjectedReadiness -Run $Inputs.Run -Environment $probeEnvironment -Sandbox $sandbox -SandboxCommand $CommandInfo -SandboxProfile $profilePath +} + function Get-LinuxSandboxArguments { param( - [Parameter(Mandatory = $true)][object]$Inputs, - [Parameter(Mandatory = $true)][object]$CommandInfo, - [Parameter(Mandatory = $true)][System.Collections.IDictionary]$Environment + [Parameter(Mandatory)][object]$Inputs, + [Parameter(Mandatory)][object]$CommandInfo, + [Parameter(Mandatory)][System.Collections.IDictionary]$Environment ) - $args = [System.Collections.Generic.List[string]]::new() - foreach ($argument in @('--die-with-parent', '--new-session', '--unshare-pid')) { $args.Add($argument) } - foreach ($path in @('/usr', '/bin', '/lib', '/lib64', '/etc', '/opt')) { - if (Test-Path -LiteralPath $path) { - $args.Add('--ro-bind'); $args.Add($path); $args.Add($path) - } - } - $args.Add('--proc'); $args.Add('/proc') - $args.Add('--dev'); $args.Add('/dev') - $args.Add('--tmpfs'); $args.Add('/tmp') - $args.Add('--bind'); $args.Add($Inputs.Run.RunRoot); $args.Add('/run') - $commandSource = [string]$CommandInfo.Source - $commandDirectory = Split-Path -Parent $commandSource - if (-not ($commandSource.StartsWith('/usr/', [System.StringComparison]::Ordinal) -or $commandSource.StartsWith('/bin/', [System.StringComparison]::Ordinal) -or $commandSource.StartsWith('/opt/', [System.StringComparison]::Ordinal))) { - if (Test-Path -LiteralPath $commandDirectory -PathType Container) { - $args.Add('--ro-bind'); $args.Add($commandDirectory); $args.Add($commandDirectory) - } - } - $args.Add('--chdir'); $args.Add('/run/repo') - $insideEnvironment = [ordered]@{ - HOME = '/run/home' - USERPROFILE = '/run/home' - XDG_CONFIG_HOME = '/run/home/.config' - XDG_DATA_HOME = '/run/home/.local/share' - XDG_CACHE_HOME = '/run/home/.cache' - TEMP = '/run/home/tmp' - TMP = '/run/home/tmp' - APPDATA = '/run/home/appdata' - LOCALAPPDATA = '/run/home/localappdata' - OPENCODE_CONFIG_DIR = '/run/home/.config/opencode' - OPENCODE_CONFIG = '/run/home/.config/opencode/opencode.json' - OPENCODE_DISABLE_AUTOUPDATE = [string]$Environment['OPENCODE_DISABLE_AUTOUPDATE'] - OPENCODE_DISABLE_EXTERNAL_SKILLS = [string]$Environment['OPENCODE_DISABLE_EXTERNAL_SKILLS'] - OPENCODE_DISABLE_CLAUDE_CODE_SKILLS = [string]$Environment['OPENCODE_DISABLE_CLAUDE_CODE_SKILLS'] - PATH = '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin' - CI = '1' - NO_COLOR = '1' - } - $modelProvider = Get-OpenCodeModelProvider -Model ([string]$Inputs.Profile.Model) - $authVariables = @(if (-not [string]::IsNullOrWhiteSpace($modelProvider)) { Get-ProviderAuthenticationVariables -Provider $modelProvider }) - foreach ($authName in $authVariables) { - if ($Environment.Contains($authName) -and -not [string]::IsNullOrWhiteSpace([string]$Environment[$authName])) { - $insideEnvironment[$authName] = [string]$Environment[$authName] - } - } - foreach ($key in @($insideEnvironment.Keys)) { - $args.Add('--setenv'); $args.Add($key); $args.Add([string]$insideEnvironment[$key]) - } - $args.Add('--') - $args.Add($CommandInfo.FileName) - foreach ($prefix in @($CommandInfo.Prefix)) { $args.Add($prefix) } - return @($args) + $inside = ConvertTo-LinuxEvalSandboxEnvironment -Environment $Environment -RunRoot $Inputs.Run.RunRoot + Get-LinuxEvalSandboxArguments -Inputs $Inputs -CommandInfo $CommandInfo -InsideEnvironment $inside } function New-MacosSandboxProfile { @@ -2192,6 +2346,17 @@ function Add-OpenCodeNullableInt64 { return ([int64]$Current + [int64]$Value) } +function Get-OpenCodeTokenCounter { + param([Parameter(Mandatory)][object]$Tokens, [Parameter(Mandatory)][string]$Name) + + $value = Get-JsonProperty -Object $Tokens -Name $Name -Default $null + if ($null -eq $value -and $Name -in @('cache_read', 'cache_write')) { + $cache = Get-JsonProperty -Object $Tokens -Name 'cache' -Default $null + $value = Get-JsonProperty -Object $cache -Name ($Name.Substring('cache_'.Length)) -Default $null + } + return $value +} + function Read-OpenCodeScriptedTurn { param( [Parameter(Mandatory = $true)][object]$Parsed, @@ -2237,7 +2402,7 @@ function Read-OpenCodeScriptedTurn { $tokens = Get-JsonProperty -Object $part -Name 'tokens' -Default (Get-JsonProperty -Object $event -Name 'tokens' -Default $null) if ($null -ne $tokens) { foreach ($name in @('input', 'output', 'reasoning', 'cache_read', 'cache_write')) { - $value = Get-JsonProperty -Object $tokens -Name $name -Default $null + $value = Get-OpenCodeTokenCounter -Tokens $tokens -Name $name if ($null -ne $value) { $usageBuckets[$name] = Add-OpenCodeNullableInt64 -Current (Get-JsonProperty -Object $usageBuckets -Name $name -Default $null) -Value $value } } } @@ -2345,11 +2510,16 @@ function Invoke-OpenCodeExecute { $executionDescriptor = [ordered]@{} foreach ($key in $descriptor.Keys) { $executionDescriptor[$key] = $descriptor[$key] } $executionDescriptor.harness = $preflight.harness + $v2 = Test-OpenCodeV2Version -Version ([string]$preflight.harness.version) if ($preflight.status -ne 'compatible') { $finished = [DateTime]::UtcNow return New-ExecutionResult -Descriptor $executionDescriptor -Profile $Inputs.Profile -Run $Inputs.Run -Status incompatible -FinalResponseReason 'preflight_incompatible' -StartedUtc $started.ToString('o') -FinishedUtc $finished.ToString('o') -DurationSeconds ($finished - $started).TotalSeconds -Failure (New-ExecutionFailure -Code 'incompatible' -Message ([string]::Join('; ', @($preflight.reasons)))) -SessionId $sessionId -IsolationCapabilities ([ordered]@{}) -IsolationMechanisms @('preflight-only') -Evidence ([ordered]@{ preflight = $preflight; preflight_source = $preflightSource; resume = $false }) -AttemptCount 1 } + $stagedFailure = Get-EvalStagedReadinessFailure -Run $Inputs.Run -VerifyFixture + if ($null -ne $stagedFailure) { + return New-EvalReadinessFailureResult -Descriptor $executionDescriptor -Inputs $Inputs -Readiness @($stagedFailure) -SessionId $sessionId -Started $started + } if ($null -ne $Inputs.Run.Interaction) { return Invoke-OpenCodeScriptedExecute -Inputs $Inputs -Preflight $preflight -ExecutionDescriptor $executionDescriptor -PreflightSource $preflightSource } @@ -2357,11 +2527,15 @@ function Invoke-OpenCodeExecute { $projection = $null $singleResult = $null try { - $commandInfo = Resolve-ExternalCommand -Name 'opencode' + $commandInfo = Resolve-OpenCodeCommand $projection = New-OpenCodeExecutionProjection -Inputs $Inputs $executionInputs = $projection.Inputs - $environment = New-OpenCodeEnvironment -Inputs $executionInputs - $runtimeHomeObservation = Get-OpenCodeRuntimeHomeObservation -CommandInfo $commandInfo -Inputs $executionInputs -Environment $environment + $readiness = @(Invoke-OpenCodeReadiness -Inputs $executionInputs -CommandInfo $commandInfo) + if (@($readiness | Where-Object status -ne 'ready').Count -gt 0) { + return New-EvalReadinessFailureResult -Descriptor $executionDescriptor -Inputs $Inputs -Readiness $readiness -SessionId $sessionId -Started $started + } + $environment = New-OpenCodeEnvironment -Inputs $executionInputs -V2:$v2 + $runtimeHomeObservation = Get-OpenCodeRuntimeHomeObservation -CommandInfo $commandInfo -Inputs $executionInputs -Environment $environment -V2:$v2 $homeIsolationObservation = Get-OpenCodeHomeIsolationObservation -Inputs $executionInputs -Environment $environment -RuntimeHome $runtimeHomeObservation $policyObservation = Get-OpenCodeSkillPolicyObservation -Inputs $executionInputs -Environment $environment $skillIsolationObservation = Get-OpenCodeSkillRootObservation -Inputs $executionInputs @@ -2378,15 +2552,15 @@ function Invoke-OpenCodeExecute { $hardFilesystem = $null -ne $sandboxInfo -and $platform -in @('linux', 'macos') $visiblePlatform = if ($hardFilesystem) { $platform } elseif ($platform -eq 'linux') { 'unknown' } else { $platform } $model = [string]$Inputs.Profile.Model - $arguments = New-OpenCodeCliArguments -Inputs $executionInputs -VisiblePlatform $visiblePlatform + $arguments = New-OpenCodeCliArguments -Inputs $executionInputs -VisiblePlatform $visiblePlatform -V2:$v2 if ($platform -eq 'linux' -and $hardFilesystem) { $sandboxArguments = Get-LinuxSandboxArguments -Inputs $executionInputs -CommandInfo $commandInfo -Environment $environment - $process = Invoke-RunnerProcess -FileName $sandboxInfo.FileName -ArgumentList (@($sandboxArguments) + @($arguments)) -WorkingDirectory $executionInputs.Run.WorkingDirectoryPath -Environment $environment -InputBytes $executionInputs.Run.PromptBytes -TimeoutSeconds $Inputs.Profile.TimeoutSeconds -ProgressContext (Get-RunnerModelProgressContext -Runner 'opencode' -Phase 'opencode-cli') + $process = Invoke-RunnerProcess -Utf8Output -FileName $sandboxInfo.FileName -ArgumentList (@($sandboxArguments) + @($arguments)) -WorkingDirectory $executionInputs.Run.WorkingDirectoryPath -Environment $environment -InputBytes $executionInputs.Run.PromptBytes -TimeoutSeconds $Inputs.Profile.TimeoutSeconds -ProgressContext (Get-RunnerModelProgressContext -Runner 'opencode' -Phase 'opencode-cli') } elseif ($platform -eq 'macos' -and $hardFilesystem) { $sandboxProfile = New-MacosSandboxProfile -Inputs $executionInputs -CommandInfo $commandInfo $sandboxArguments = @('-f', $sandboxProfile, '--', $commandInfo.FileName) + @($commandInfo.Prefix) + $arguments - $process = Invoke-RunnerProcess -FileName $sandboxInfo.FileName -ArgumentList $sandboxArguments -WorkingDirectory $executionInputs.Run.WorkingDirectoryPath -Environment $environment -InputBytes $executionInputs.Run.PromptBytes -TimeoutSeconds $Inputs.Profile.TimeoutSeconds -ProgressContext (Get-RunnerModelProgressContext -Runner 'opencode' -Phase 'opencode-cli') + $process = Invoke-RunnerProcess -Utf8Output -FileName $sandboxInfo.FileName -ArgumentList $sandboxArguments -WorkingDirectory $executionInputs.Run.WorkingDirectoryPath -Environment $environment -InputBytes $executionInputs.Run.PromptBytes -TimeoutSeconds $Inputs.Profile.TimeoutSeconds -ProgressContext (Get-RunnerModelProgressContext -Runner 'opencode' -Phase 'opencode-cli') } else { $process = Invoke-OpenCodeCli -CommandInfo $commandInfo -Arguments $arguments -Inputs $executionInputs -Environment $environment -InputBytes $executionInputs.Run.PromptBytes -TimeoutSeconds $Inputs.Profile.TimeoutSeconds } @@ -2438,7 +2612,7 @@ function Invoke-OpenCodeExecute { $tokens = Get-JsonProperty -Object $part -Name 'tokens' -Default (Get-JsonProperty -Object $event -Name 'tokens' -Default $null) if ($null -ne $tokens) { foreach ($name in @('input', 'output', 'reasoning', 'cache_read', 'cache_write')) { - $value = Get-JsonProperty -Object $tokens -Name $name -Default $null + $value = Get-OpenCodeTokenCounter -Tokens $tokens -Name $name if ($null -ne $value) { $usageBuckets[$name] = $value } } } @@ -2468,6 +2642,18 @@ function Invoke-OpenCodeExecute { $reason = $null $failure = $null $exitStatus = if ($process.TimedOut) { $null } else { [Nullable[int]]$process.ExitCode } + $exportFailure = $null + $exportArtifact = $null + if ($v2 -and -not $process.TimedOut -and $process.ExitCode -eq 0 -and $null -eq $failureMessage -and @($parsed.Errors).Count -eq 0 -and $terminalEventObserved -and $exactSessionId) { + try { + $export = Read-OpenCodeV2SessionEvidence -Inputs $executionInputs -CommandInfo $commandInfo -Environment $environment -Platform $platform -SandboxInfo $sandboxInfo -SessionId $exactSessionId -Prompt ([Text.Encoding]::UTF8.GetString($executionInputs.Run.PromptBytes)) -Turn 1 + $exportArtifact = Write-OpenCodeCapture -RunData $Inputs -RelativePath 'evidence/opencode-session.json' -Text $export.Json + $artifacts.Add($exportArtifact) + if ($observedModels -notcontains $export.Model) { $observedModels.Add($export.Model) } + } catch { + $exportFailure = $_.Exception.Message + } + } if ($process.TimedOut) { $status = 'timed_out'; $reason = 'opencode_timeout'; $failure = New-ExecutionFailure -Code 'timed_out' -Message 'OpenCode did not finish before timeout_seconds.' } elseif ($process.ExitCode -ne 0 -or $null -ne $failureMessage) { @@ -2480,6 +2666,8 @@ function Invoke-OpenCodeExecute { $status = 'incompatible'; $reason = 'native_interaction_incompatible'; $failure = New-ExecutionFailure -Code 'native_interaction_incompatible' -Message "OpenCode single-turn execution reported a model different from the requested model '$($Inputs.Profile.Model)'." } elseif (-not [bool]$terminalEventObserved) { $status = 'incompatible'; $reason = 'native_interaction_incompatible'; $failure = New-ExecutionFailure -Code 'native_interaction_incompatible' -Message 'OpenCode single-turn execution did not emit a terminal structured event.' + } elseif ($v2 -and -not $exportArtifact) { + $status = 'incompatible'; $reason = 'native_interaction_incompatible'; $failure = New-ExecutionFailure -Code 'native_interaction_incompatible' -Message $exportFailure } elseif ([string]::IsNullOrWhiteSpace($finalText)) { $reason = 'opencode_did_not_return_final_response'; $warnings.Add('OpenCode exited successfully without a text response.') } @@ -2492,6 +2680,7 @@ function Invoke-OpenCodeExecute { $capabilities = Get-OpenCodeCapabilityMap -Inputs $Inputs -HardFilesystemConfinement $hardFilesystem $mechanisms = [System.Collections.Generic.List[string]]::new() foreach ($mechanism in @('opencode run --format json', '--auto', 'isolated OPENCODE_CONFIG_DIR', 'isolated OPENCODE_CONFIG', 'isolated HOME/XDG roots', 'repository-owned project configuration preserved', 'prompt on stdin', 'no session continuation')) { $mechanisms.Add($mechanism) } + if ($v2) { $mechanisms.Add('private standalone server and native session export') } if ($hardFilesystem) { $mechanisms.Add("external $($sandboxInfo.Source) filesystem sandbox") } else { $mechanisms.Add('pragmatic process/environment isolation without hard filesystem confinement'); $warnings.Add('Hard filesystem confinement was unavailable; the completed arm is reported as pragmatic isolation.') } $sandboxEvidence = if (-not $hardFilesystem) { 'unavailable' } elseif ($platform -eq 'linux') { 'bwrap' } else { 'sandbox-exec' } $modelProvider = Get-OpenCodeModelProvider -Model ([string]$Inputs.Profile.Model) @@ -2583,13 +2772,18 @@ function Invoke-OpenCodeExecute { if ($null -ne $eventTiming) { $evidence.timing.turns[0].event_timing = $eventTiming } + if ($exportArtifact) { + $evidence.session_export = $exportArtifact.path + $evidence.observed_variant = $export.Variant + } + if ($readiness.Count -gt 0) { $evidence.readiness = $readiness } $singleResult = New-ExecutionResult -Descriptor $executionDescriptor -Profile $Inputs.Profile -Run $Inputs.Run -Status $status -FinalResponse $finalText -FinalResponseReason $reason -StartedUtc $process.StartedUtc.ToString('o') -FinishedUtc $process.FinishedUtc.ToString('o') -DurationSeconds $process.DurationSeconds -ExitStatus $exitStatus -Failure $failure -SessionId $sessionId -IsolationCapabilities $capabilities -IsolationMechanisms @($mechanisms) -ResolvedConfiguration ([ordered]@{ status = 'accepted_request'; reason = 'OpenCode accepted the requested runner-native model selector and configuration but did not expose concrete backend resolution.'; observations = [ordered]@{ model = $Inputs.Profile.Model; reasoning_effort = $Inputs.Profile.ReasoningEffort } }) -Telemetry $telemetry -Artifacts @($artifacts) -Warnings @($warnings) -Evidence $evidence -AttemptCount 1 return $singleResult } finally { if ($null -ne $projection) { try { Remove-OpenCodeProjectedCandidateSkill -Projection $projection - Sync-OpenCodeProjectedRepository -Projection $projection + if ($null -ne $environment) { Sync-OpenCodeProjectedRepository -Projection $projection } } finally { Remove-OpenCodeExecutionProjection -Projection $projection if ($null -ne $singleResult -and $null -ne $singleResult.evidence -and $null -ne $singleResult.evidence.execution_paths) { diff --git a/scripts/eval-runners/package-integrity.ps1 b/scripts/eval-runners/package-integrity.ps1 index 037cec84..7237afde 100644 --- a/scripts/eval-runners/package-integrity.ps1 +++ b/scripts/eval-runners/package-integrity.ps1 @@ -63,7 +63,7 @@ function Get-PackageRunnerDescriptorFromPath { [Parameter(Mandatory = $true)][string]$RunnerToolsDirectory ) - $pwshPath = [string]((Get-Command pwsh -CommandType Application -ErrorAction Stop | Select-Object -First 1).Source) + $pwshPath = Get-RunnerPowerShellPath $descriptorProcess = Invoke-RunnerProcess -FileName $pwshPath -ArgumentList @('-NoProfile', '-NonInteractive', '-File', $RunnerPath, 'describe') -WorkingDirectory $RunnerToolsDirectory -Environment (New-RunnerProbeEnvironment) -TimeoutSeconds 30 if ($descriptorProcess.TimedOut) { throw "Package-local runner '$RunnerName' descriptor exceeded the 30-second model-free probe timeout." @@ -118,13 +118,9 @@ function Assert-PackageRunnerIdentity { if (-not (Test-Path -LiteralPath $resolverPath -PathType Leaf)) { throw "Package-local Eval Runner resolver is missing at '$resolverPath'." } - $resolutionOutput = & pwsh -NoProfile -NonInteractive -File $resolverPath ([string]$profile.Runner) 2>&1 - if ($LASTEXITCODE -ne 0) { - throw "Selected runner '$($profile.Runner)' could not be resolved package-locally: $([string]::Join(' ', @($resolutionOutput)))" - } - $resolutionText = [string]::Join([Environment]::NewLine, @($resolutionOutput | ForEach-Object { [string]$_ })) + $resolutionProcess = Invoke-RunnerPowerShellScript -ScriptPath $resolverPath -Arguments @([string]$profile.Runner) -Description "Package-local resolution of runner '$($profile.Runner)'" -WorkingDirectory $runnerToolsDirectory -Environment (New-RunnerProbeEnvironment) -TimeoutSeconds 30 try { - $resolution = $resolutionText | ConvertFrom-Json + $resolution = $resolutionProcess.Stdout | ConvertFrom-Json } catch { throw "Selected runner '$($profile.Runner)' resolver returned invalid JSON: $($_.Exception.Message)" } diff --git a/scripts/eval-runners/process-ownership.ps1 b/scripts/eval-runners/process-ownership.ps1 index 0a61da68..ec4bcc14 100644 --- a/scripts/eval-runners/process-ownership.ps1 +++ b/scripts/eval-runners/process-ownership.ps1 @@ -1,8 +1,13 @@ +# Readiness starts owned processes, so both files are compiled into one assembly. +function Import-EvalRunnerTypes { + if (-not ('Agentic.Evals.EvalReadiness' -as [type])) { + Add-Type -Path @((Join-Path $PSScriptRoot 'windows-owned-process.cs'), (Join-Path $PSScriptRoot 'eval-readiness.cs')) + } +} + function New-EvalOwnedProcess { if (-not $IsWindows) { return [System.Diagnostics.Process]::new() } - if (-not ('Agentic.Evals.WindowsOwnedProcess' -as [type])) { - Add-Type -Path (Join-Path $PSScriptRoot 'windows-owned-process.cs') - } + Import-EvalRunnerTypes return [Agentic.Evals.WindowsOwnedProcess]::new() } diff --git a/scripts/eval-runners/runner-common.ps1 b/scripts/eval-runners/runner-common.ps1 index c4c543d6..924a617c 100644 --- a/scripts/eval-runners/runner-common.ps1 +++ b/scripts/eval-runners/runner-common.ps1 @@ -35,6 +35,10 @@ function Get-RunnerPreflightTimeoutSeconds { return 120 } +function Get-EvalReadinessTimeoutSeconds { + return 85 +} + function Get-CodexExecutionStartupAllowanceSeconds { # Execute rechecks compatibility, then performs discovery and startup in # the behavioral projection before the first turn has a model deadline. @@ -56,15 +60,55 @@ function Get-ClaudeExecutionOverheadAllowanceSeconds { function Get-RunnerExecutionOverheadAllowanceSeconds { # Model-free execute work outside the per-turn model deadlines, budgeted by # the runner-child watchdog and the generated Phase 1 allowance. - param([string]$Runner) + param([string]$Runner, [switch]$HasPrerequisites) switch ($Runner) { - 'codex' { return Get-CodexExecutionStartupAllowanceSeconds } - 'claude' { return Get-ClaudeExecutionOverheadAllowanceSeconds } + 'codex' { return (Get-CodexExecutionStartupAllowanceSeconds) + $(if ($HasPrerequisites) { Get-EvalReadinessTimeoutSeconds } else { 0 }) } + 'claude' { return (Get-ClaudeExecutionOverheadAllowanceSeconds) + $(if ($HasPrerequisites) { Get-EvalReadinessTimeoutSeconds } else { 0 }) } + 'opencode' { if ($HasPrerequisites) { return (Get-RunnerPreflightTimeoutSeconds) + (Get-EvalReadinessTimeoutSeconds) }; return 0 } default { return 0 } } } +function Get-RunnerPowerShellPath { + # Headless hosts can start PowerShell by absolute path without exposing it + # through PATH, including Windows Store installations and their aliases. + $executableName = if ($IsWindows) { 'pwsh.exe' } else { 'pwsh' } + $processPath = [Environment]::ProcessPath + if ($processPath -and [IO.Path]::GetFileName($processPath) -eq $executableName -and (Test-Path -LiteralPath $processPath -PathType Leaf)) { + return $processPath + } + $hostExecutable = Join-Path $PSHOME $executableName + if (Test-Path -LiteralPath $hostExecutable -PathType Leaf) { return $hostExecutable } + + $application = Get-Command -Name pwsh -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1 + if ($null -ne $application) { return [string]$application.Source } + throw 'The eval runner could not locate a PowerShell 7 executable from the current host, PSHOME, or PATH.' +} + +function Invoke-RunnerPowerShellScript { + param( + [Parameter(Mandatory)][string]$ScriptPath, + [string[]]$Arguments = @(), + [Parameter(Mandatory)][string]$Description, + [string]$WorkingDirectory = (Get-Location -PSProvider FileSystem).ProviderPath, + [System.Collections.IDictionary]$Environment = [Environment]::GetEnvironmentVariables(), + [int]$TimeoutSeconds = 900 + ) + + $result = Invoke-RunnerProcess -FileName (Get-RunnerPowerShellPath) -ArgumentList (@('-NoProfile', '-NonInteractive', '-File', $ScriptPath) + $Arguments) -WorkingDirectory $WorkingDirectory -Environment $Environment -TimeoutSeconds $TimeoutSeconds + if ($result.TimedOut) { throw "$Description failed after its $TimeoutSeconds-second timeout." } + if ($null -eq $result.ExitCode) { throw "$Description failed because the child did not report an exit status." } + if ($result.ExitCode -ne 0) { + $detail = [string]::Join([Environment]::NewLine, @($result.Stdout, $result.Stderr)).Trim() + throw "$Description failed (exit $($result.ExitCode)). $detail" + } + if (-not $result.StdoutDrainCompleted -or -not $result.StderrDrainCompleted) { + throw "$Description failed because the child's output did not close completely." + } + return $result +} + function Get-PackageRunnerDescriptor { param([Parameter(Mandatory = $true)][string]$RunnerName) @@ -77,7 +121,7 @@ function Get-PackageRunnerDescriptor { throw "Package-local runner '$RunnerName' is missing its runner.ps1 descriptor." } - $pwshPath = [string]((Get-Command pwsh -CommandType Application -ErrorAction Stop | Select-Object -First 1).Source) + $pwshPath = Get-RunnerPowerShellPath $descriptorProcess = Invoke-RunnerProcess -FileName $pwshPath -ArgumentList @('-NoProfile', '-NonInteractive', '-File', $runnerPath, 'describe') -WorkingDirectory $PSScriptRoot -Environment (New-RunnerProbeEnvironment) -TimeoutSeconds 30 if ($descriptorProcess.TimedOut) { throw "Package-local runner '$RunnerName' descriptor exceeded the 30-second model-free probe timeout." @@ -1032,7 +1076,7 @@ function Assert-NativeTerminalCaptureArtifact { } function Resolve-RunContract { - param([Parameter(Mandatory = $true)][string]$RunPath) + param([Parameter(Mandatory = $true)][string]$RunPath, [switch]$DeferStagedDependencyValidation) $resolvedRunPath = (Resolve-Path -LiteralPath $RunPath -ErrorAction Stop).Path $runRoot = Split-Path -Parent $resolvedRunPath @@ -1129,7 +1173,7 @@ function Resolve-RunContract { } $promptBytes = [System.IO.File]::ReadAllBytes($promptPath) - Assert-EvalStagedDependencies -RunRoot $runRoot -Contract $run + if (-not $DeferStagedDependencyValidation) { Assert-EvalStagedDependencies -RunRoot $runRoot -Contract $run } $fixtureHash = [string](Get-JsonProperty -Object $run -Name 'fixtureHash' -Default '') if (-not (Test-Sha256 -Value $fixtureHash)) { throw 'run.json fixtureHash must be a SHA-256 value.' @@ -1833,12 +1877,12 @@ function Assert-ExecutionResult { function New-RunnerShellEnvironment { <# - Builds the MODEL-BACKED eval isolation environment. This is deliberately - NOT the model-free probe environment (New-RunnerProbeEnvironment): here + Builds the shell environment for an isolated eval and its prerequisite + probes. Harness discovery uses New-RunnerProbeEnvironment instead. Here HOME, USERPROFILE, XDG_*, and TEMP/TMP are all pinned INSIDE the per-run isolated home so the harness cannot consult the real user profile, ambient - config, or ambient skill roots. A model-free --version/--help/describe probe - must never be routed through this environment, and this environment must + config, or ambient skill roots. Harness discovery with --version, --help, + or describe uses the probe environment, and the eval environment must never be reduced to the probe environment: the probe carries OS scratch TEMP/TMP but no isolated home, and the eval carries an isolated home but never the host profile. @@ -1860,18 +1904,29 @@ function New-RunnerShellEnvironment { $pathDirectories = @($toolPath, [IO.Path]::Combine($Run.HomeDirectoryPath, '.dotnet', 'tools')) $requirements = Get-JsonProperty -Object (Get-JsonProperty -Object $Run -Name 'Contract') -Name 'prerequisites' $commands = @('pwsh', 'git', 'rg', 'dotnet', 'node') + @(Get-JsonProperty -Object $requirements -Name 'executables' -Default @() | ForEach-Object { [string]$_ }) + $commandDirectories = @() foreach ($command in ($commands | Select-Object -Unique)) { if ($command -notmatch '^[A-Za-z0-9][A-Za-z0-9._+-]*$') { throw "Invalid evaluation executable name '$command'." } $application = Get-Command -Name $command -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1 if ($null -ne $application) { - $pathDirectories += Split-Path -Parent $application.Source + $commandDirectories += Split-Path -Parent $application.Source if ($command -eq 'dotnet') { $dotnet = [IO.FileInfo]::new($application.Source) $target = $dotnet.ResolveLinkTarget($true) $environment['DOTNET_ROOT'] = if ($null -ne $target) { $target.DirectoryName } else { $dotnet.DirectoryName } } + } elseif ($command -eq 'pwsh') { + $commandDirectories += Split-Path -Parent (Get-RunnerPowerShellPath) } } + # Keep the host PATH order. Lookup order would let a directory found for one + # command (pwsh in /usr/bin) shadow the selected copy of another (dotnet). + $hostPath = @($env:PATH -split [IO.Path]::PathSeparator | ForEach-Object { [IO.Path]::TrimEndingDirectorySeparator($_) }) + $pathDirectories += @($commandDirectories | Select-Object -Unique | Sort-Object -Stable { + $directory = [IO.Path]::TrimEndingDirectorySeparator($_) + for ($index = 0; $index -lt $hostPath.Count -and $hostPath[$index] -ne $directory; $index++) { } + $index + }) if ($IsWindows) { $windows = [Environment]::GetFolderPath([Environment+SpecialFolder]::Windows) $system = [Environment]::SystemDirectory @@ -1952,7 +2007,8 @@ function Get-LinuxEvalSandboxArguments { [Parameter(Mandatory = $true)][object]$Inputs, [Parameter(Mandatory = $true)][object]$CommandInfo, [Parameter(Mandatory = $true)][System.Collections.IDictionary]$InsideEnvironment, - [string[]]$ReadOnlyRoots = @('/usr', '/usr/local', '/bin', '/sbin', '/lib', '/lib64', '/libexec', '/etc', '/opt') + [string[]]$ReadOnlyRoots = @('/usr', '/usr/local', '/bin', '/sbin', '/lib', '/lib64', '/libexec', '/etc', '/opt'), + [string[]]$Command = @() ) $arguments = [System.Collections.Generic.List[string]]::new() @@ -1978,11 +2034,23 @@ function Get-LinuxEvalSandboxArguments { $arguments.Add('--setenv'); $arguments.Add([string]$key); $arguments.Add([string]$InsideEnvironment[$key]) } $arguments.Add('--') - $arguments.Add($CommandInfo.FileName) - foreach ($prefix in @($CommandInfo.Prefix)) { $arguments.Add($prefix) } + if ($Command.Count -eq 0) { $Command = @($CommandInfo.FileName) + @($CommandInfo.Prefix) } + foreach ($argument in $Command) { $arguments.Add($argument) } return @($arguments) } +function ConvertTo-LinuxEvalSandboxEnvironment { + param([System.Collections.IDictionary]$Environment, [string]$RunRoot) + + $inside = [ordered]@{} + foreach ($name in $Environment.Keys) { + $inside[$name] = if ($name -in @('PATH', 'DOTNET_ROOT', 'HOME', 'USERPROFILE', 'XDG_CONFIG_HOME', 'XDG_DATA_HOME', 'XDG_CACHE_HOME', 'TEMP', 'TMP', 'TMPDIR', 'APPDATA', 'LOCALAPPDATA', 'DOTNET_CLI_HOME', 'NUGET_PACKAGES', 'NUGET_HTTP_CACHE_PATH', 'GIT_CONFIG_GLOBAL', 'OPENCODE_CONFIG_DIR', 'OPENCODE_CONFIG')) { + ([string]$Environment[$name]).Replace($RunRoot, '/run') + } else { $Environment[$name] } + } + return $inside +} + function New-MacosEvalSandboxProfile { param( [Parameter(Mandatory = $true)][object]$Inputs, @@ -2016,6 +2084,10 @@ function New-MacosEvalSandboxProfile { function Resolve-ExternalCommand { param([Parameter(Mandatory = $true)][string]$Name) + if ($Name -eq 'pwsh') { + $shell = Get-RunnerPowerShellPath + return [pscustomobject]@{ FileName = $shell; Prefix = @(); Source = $shell } + } $command = Get-Command $Name -ErrorAction SilentlyContinue if ($null -eq $command) { foreach ($candidateName in @("$Name.ps1", "$Name.cmd", "$Name.exe")) { @@ -2030,11 +2102,7 @@ function Resolve-ExternalCommand { $source = [string]$command.Source $extension = [System.IO.Path]::GetExtension($source).ToLowerInvariant() if ($extension -eq '.ps1') { - $pwsh = Get-Command pwsh -ErrorAction SilentlyContinue - if ($null -eq $pwsh) { - return $null - } - return [pscustomobject]@{ FileName = [string]$pwsh.Source; Prefix = @('-NoProfile', '-NonInteractive', '-File', $source); Source = $source } + return [pscustomobject]@{ FileName = (Get-RunnerPowerShellPath); Prefix = @('-NoProfile', '-NonInteractive', '-File', $source); Source = $source } } return [pscustomobject]@{ FileName = $source; Prefix = @(); Source = $source } @@ -2077,8 +2145,10 @@ function Invoke-RunnerProcess { [System.Collections.IDictionary]$Environment = @{}, [AllowEmptyCollection()][byte[]]$InputBytes = @(), [int]$TimeoutSeconds = 900, + [int]$TimeoutMilliseconds = 0, [hashtable]$ProgressContext = $null, - [switch]$OwnWindowsProcessTree + [switch]$OwnWindowsProcessTree, + [switch]$Utf8Output ) $start = [DateTime]::UtcNow @@ -2090,6 +2160,10 @@ function Invoke-RunnerProcess { $startInfo.RedirectStandardInput = $true $startInfo.RedirectStandardOutput = $true $startInfo.RedirectStandardError = $true + if ($Utf8Output) { + $startInfo.StandardOutputEncoding = [Text.Encoding]::UTF8 + $startInfo.StandardErrorEncoding = [Text.Encoding]::UTF8 + } foreach ($argument in @($ArgumentList)) { [void]$startInfo.ArgumentList.Add([string]$argument) } @@ -2109,7 +2183,7 @@ function Invoke-RunnerProcess { $terminationObserved = $false $stdoutDrainCompleted = $false $stderrDrainCompleted = $false - $timeoutValue = [Math]::Max(1, $TimeoutSeconds) + $timeoutValue = if ($TimeoutMilliseconds -gt 0) { $TimeoutMilliseconds / 1000.0 } else { [Math]::Max(1, $TimeoutSeconds) } $deadline = $start.AddSeconds($timeoutValue) # Opt-in live observability for the model process this primitive runs. When a @@ -2331,6 +2405,12 @@ function Invoke-RunnerProcess { } } +function Test-OpenCodeV2Version { + param([string]$Version) + + return $Version.Trim() -match '^(?:opencode\s+)?v?2\.\d+\.\d+(?:[-+][\w.-]+)?$' +} + function Get-ProviderAuthenticationVariables { param([string]$Provider) diff --git a/scripts/eval-runners/tests/fixtures/readiness-cases.ps1 b/scripts/eval-runners/tests/fixtures/readiness-cases.ps1 new file mode 100644 index 00000000..25353b69 --- /dev/null +++ b/scripts/eval-runners/tests/fixtures/readiness-cases.ps1 @@ -0,0 +1,102 @@ +# Use the maintained eval declarations. Replace network assets and external +# services with offline fixtures, keeping the declared commands and patterns. +function Add-ReadinessFixtureExecutables { + param([string]$Bin) + + $outputs = [ordered]@{ + dotnet = @('--info=.NET SDK fixture', '--list-sdks=10.0.404 [fixture]', '--list-runtimes=Microsoft.NETCore.App 10.0.0 [fixture]', 'restore=restored', 'build=built') + docfx = @('--version=2.81.0') + docker = @('info=29.0.0/linux') + rg = @('--version=ripgrep fixture') + } + foreach ($tool in $outputs.Keys) { + $lines = @(if ($IsWindows) { '@echo off' } else { '#!/bin/sh'; 'case "$1" in' }) + foreach ($entry in $outputs[$tool]) { + $argument, $output = $entry -split '=', 2 + $lines += if ($IsWindows) { 'if "%~1"=="{0}" (echo {1} & exit /b 0)' -f $argument, $output } else { "'$argument') printf '%s\n' '$output'; exit 0 ;;" } + } + $lines += if ($IsWindows) { 'exit /b 79' } else { @('esac', 'exit 79') } + $path = Join-Path $Bin $(if ($IsWindows) { "$tool.cmd" } else { $tool }) + [IO.File]::WriteAllText($path, ($lines -join [Environment]::NewLine) + [Environment]::NewLine) + if (-not $IsWindows) { & chmod '+x' $path; if ($LASTEXITCODE -ne 0) { throw "Cannot make '$path' executable." } } + } +} + +function New-ReadinessFixtureRun { + param([object]$TestRun, [ValidateSet(138, 139)][int]$EvalId) + + $repoRoot = (Resolve-Path (Join-Path $PSScriptRoot '../../../..')).Path + $cases = Read-RunnerJson -Path (Join-Path $repoRoot 'skills/dotnet-docfx-digest/evals/evals.json') + $declared = ($cases.evals | Where-Object id -eq $EvalId).prerequisites + $contract = Get-Content -LiteralPath $TestRun.Path -Raw | ConvertFrom-Json -AsHashtable + $contract.evalId = $EvalId + $contract.skillExposure = 'entrypoint' + $requirements = [ordered]@{ + executables = @($declared.executables) + probes = @($declared.probes) + dotnetTools = @($declared.dotnetTools | ForEach-Object { @{ executable = $_.executable; source = 'installed'; requested_version = $_.version } }) + skills = @() + downloads = @() + stagedHome = @() + } + $restoreDir = Join-Path $TestRun.Root 'home/restore-probe' + New-Item -ItemType Directory -Path $restoreDir -Force | Out-Null + $restoreProject = Join-Path $restoreDir 'Probe.csproj' + [IO.File]::WriteAllText($restoreProject, "$($declared.restore.framework)") + [IO.File]::WriteAllText((Join-Path $restoreDir 'NuGet.Config'), '') + $requirements.stagedHome += @{ path = 'home/restore-probe'; sha256 = Get-EvalDependencyTreeHash -Root $restoreDir } + $requirements.probes += @( + @{ id = 'nuget-restore'; command = @('dotnet', 'restore', '{run}/home/restore-probe/Probe.csproj', '--configfile', '{run}/home/restore-probe/NuGet.Config'); timeoutMs = 45000 } + @{ id = 'dotnet-build'; command = @('dotnet', 'build', '{run}/home/restore-probe/Probe.csproj', '--no-restore', '--nologo'); timeoutMs = 45000 } + ) + $downloadPath = $null + if ($EvalId -eq 139) { + $dependencies = Join-Path $TestRun.Root 'dependencies' + $toolsDir = Join-Path $dependencies 'tools' + New-Item -ItemType Directory -Path $toolsDir -Force | Out-Null + foreach ($name in $declared.skills) { + $path = Join-Path $dependencies $name + New-Item -ItemType Directory -Path $path -Force | Out-Null + Copy-Item -LiteralPath (Join-Path $repoRoot "skills/$name/SKILL.md") -Destination $path + $requirements.skills += @{ path = "dependencies/$name"; sha256 = Get-EvalDependencyTreeHash -Root $path } + } + $downloadName = $declared.downloads[0].file + $downloadPath = Join-Path $toolsDir $downloadName + [IO.File]::WriteAllText($downloadPath, @' +param($Framework, $Source) +if ($Framework -ne 'net10.0' -or $Source -notmatch 'agentic-csrun-ready') { throw 'Incorrect engine arguments.' } +if ($env:OPENAI_API_KEY -or $env:ANTHROPIC_API_KEY -or $env:CLAUDE_CONFIG_DIR -or $env:CODEX_HOME -or $env:AGENTIC_GLOBAL_SECRET) { throw 'Readiness inherited credentials or ambient configuration.' } +$projection = Split-Path -Parent (Split-Path -Parent $PSScriptRoot) +if ((Get-Location).Path -ne (Join-Path $projection 'repo') -or $env:HOME -ne (Join-Path $projection 'home')) { throw 'Readiness used the wrong working directory or home.' } +if (-not (Test-Path -LiteralPath '../dependencies/dotnet-csrun/SKILL.md') -or (Test-Path -LiteralPath '../eval-metadata.json')) { throw 'Readiness has the wrong staged inputs.' } +Write-Output 'agentic-csrun-ready' +'@) + $requirements.downloads += @{ path = "dependencies/tools/$downloadName"; sha256 = Get-Sha256HexFromFile -Path $downloadPath } + if ($contract.mode -eq 'with_skill') { + $target = "dependencies/$($contract.candidateSkillName)" + Move-Item -LiteralPath (Join-Path $TestRun.Root $contract.skillDirectory) -Destination (Join-Path $TestRun.Root $target) + $contract.skillDirectory = $target + } + } + $contract.prerequisites = $requirements + Write-RunnerJsonFile -Path $TestRun.Path -Value $contract + return [pscustomobject]@{ Run = $TestRun; Contract = $contract; DownloadPath = $downloadPath } +} + +function Assert-ReadinessFixturePreflights { + param([object[]]$Arms, [scriptblock]$Preflight, [string]$Transport) + + $left, $right = $Arms + if ((Get-JsonFingerprint -Object $left.Contract.prerequisites) -ne (Get-JsonFingerprint -Object $right.Contract.prerequisites)) { throw 'The two arms have different prerequisites.' } + foreach ($arm in $Arms) { + $result = & $Preflight $arm.Run.Path + if ($result.status -ne 'compatible') { throw "Eval $($arm.Contract.evalId) $($arm.Contract.mode) preflight failed: $($result.reasons -join ' ')" } + $checks = @($result.readiness) + $expected = @('isolated-shell-environment') + @($arm.Contract.prerequisites.executables | ForEach-Object { "executable:$_" }) + + @($arm.Contract.prerequisites.probes | ForEach-Object id) + @('tool-version:docfx') + if (@(Compare-Object $expected @($checks | ForEach-Object id)).Count -gt 0 -or + @($checks | Where-Object { $_.transport -ne $Transport -or $_.status -ne 'ready' }).Count -gt 0) { + throw "Eval $($arm.Contract.evalId) $($arm.Contract.mode) did not verify every prerequisite using $Transport." + } + } +} diff --git a/scripts/eval-runners/tests/fixtures/runner-owned-fixture.ps1 b/scripts/eval-runners/tests/fixtures/runner-owned-fixture.ps1 index 78a8ccb0..b173583b 100644 --- a/scripts/eval-runners/tests/fixtures/runner-owned-fixture.ps1 +++ b/scripts/eval-runners/tests/fixtures/runner-owned-fixture.ps1 @@ -97,6 +97,15 @@ try { if ($Command -eq 'preflight') { Write-FixtureEvent -Kind 'preflight' + if (Test-JsonProperty -Object $inputs.Run.Contract -Name 'prerequisites') { + $readiness = @(Invoke-EvalProjectedReadiness -Run $inputs.Run) + $reasons = [System.Collections.Generic.List[string]]::new() + Add-EvalReadinessFailureReasons -Readiness $readiness -Reasons $reasons + $preflight = New-PreflightDocument -Descriptor $descriptor -Profile $inputs.Profile -Run $inputs.Run -Compatible ($reasons.Count -eq 0) -Reasons @($reasons) + $preflight.readiness = $readiness + Write-RunnerJson -Value $preflight -AsOutput + exit 0 + } if (Test-Path -LiteralPath (Join-Path $inputs.Run.HomeDirectoryPath 'preflight-incompatible') -PathType Leaf) { $preflightCapabilities = [ordered]@{} foreach ($capabilityName in @(Get-JsonPropertyNames -Object $descriptor.capabilities)) { $preflightCapabilities[$capabilityName] = [string](Get-JsonProperty -Object $descriptor.capabilities -Name $capabilityName) } diff --git a/scripts/eval-runners/tests/test-claude-runner.ps1 b/scripts/eval-runners/tests/test-claude-runner.ps1 index 86216432..5c225c07 100644 --- a/scripts/eval-runners/tests/test-claude-runner.ps1 +++ b/scripts/eval-runners/tests/test-claude-runner.ps1 @@ -18,6 +18,7 @@ Set-StrictMode -Version Latest $runnerRoot = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path . (Join-Path $runnerRoot 'runner-common.ps1') +. (Join-Path $PSScriptRoot 'fixtures/readiness-cases.ps1') $runnerPath = Join-Path $runnerRoot 'claude\runner.ps1' $utf8 = [System.Text.UTF8Encoding]::new($false) @@ -234,6 +235,43 @@ try { Assert-Equal 210 (Get-RunnerExecutionOverheadAllowanceSeconds -Runner 'claude') 'Claude execute budgets repeated preflight, projection sync, and session purge outside the model deadline' Assert-True ((Get-ClaudeExecutionOverheadAllowanceSeconds) -ge (Get-RunnerPreflightTimeoutSeconds) + (Get-ClaudeSessionPurgeTimeoutSeconds)) 'the Claude overhead allowance covers the preflight and purge bounds' + Add-ReadinessFixtureExecutables -Bin $fakeBin + $probe = { param($path) Invoke-ClaudeRunner -Command preflight -RunPath $path -ProfilePath $profilePath } + foreach ($evalId in 138, 139) { + $arms = @(foreach ($mode in 'with_skill', 'without_skill') { + $case = New-TestRun -IterationDirectory $iteration -EvalName "readiness-$evalId" -Configuration $mode + New-ReadinessFixtureRun -TestRun $case -EvalId $evalId + }) + Assert-ReadinessFixturePreflights -Arms $arms -Preflight $probe -Transport 'runner-process' + foreach ($arm in $arms) { + Assert-True (-not (Test-Path -LiteralPath (Join-Path $arm.Run.Repo 'claude-fake-cli-log.jsonl'))) 'Preflight must never invoke Claude print mode.' + } + } + + $changedArm = $arms[0] + $originalDownload = [IO.File]::ReadAllBytes($changedArm.DownloadPath) + Remove-Item -LiteralPath $changedArm.DownloadPath + $missing = & $probe $changedArm.Run.Path + Assert-Equal 'incompatible' $missing.status 'a missing download fails before any probe or model invocation' + Assert-True ($missing.readiness[0].diagnostic -match 'csrun\.ps1') 'missing staged dependency diagnostic identifies the exact download' + [IO.File]::WriteAllText($changedArm.DownloadPath, 'modified asset') + $modified = & $probe $changedArm.Run.Path + Assert-Equal 'incompatible' $modified.status 'a modified download fails before any probe or model invocation' + Assert-True ($modified.readiness[0].diagnostic -match 'hash mismatch.*csrun\.ps1') 'modified staged dependency diagnostic identifies the hash and download' + [IO.File]::WriteAllBytes($changedArm.DownloadPath, $originalDownload) + + $changedArm.Contract.prerequisites.probes[0].outputPattern = '^PowerShell 0\.' + Write-RunnerJsonFile -Path $changedArm.Run.Path -Value $changedArm.Contract + $badVersion = & $probe $changedArm.Run.Path + Assert-Equal 'incompatible' $badVersion.status 'a wrong version fails readiness' + $lastCheck = @($badVersion.readiness)[-1] + Assert-True ($lastCheck.id -eq 'powershell' -and $lastCheck.diagnostic -match 'Observed: PowerShell 7' -and $lastCheck.remediation) 'version failure states the observed output and remediation' + $changedArm.Contract.prerequisites.executables += 'agentic-nonexistent-prerequisite' + Write-RunnerJsonFile -Path $changedArm.Run.Path -Value $changedArm.Contract + $missingExecutable = & $probe $changedArm.Run.Path + Assert-Equal 'incompatible' $missingExecutable.status 'a missing executable fails even without a custom probe' + Assert-Equal 'executable:agentic-nonexistent-prerequisite' @($missingExecutable.readiness)[-1].id 'missing executable diagnostic names the application' + Write-Host 'Claude Code runner conformance: PASS' } finally { $env:PATH = $originalPath diff --git a/scripts/eval-runners/tests/test-eval-readiness.ps1 b/scripts/eval-runners/tests/test-eval-readiness.ps1 index eab3cdca..9868e2b3 100644 --- a/scripts/eval-runners/tests/test-eval-readiness.ps1 +++ b/scripts/eval-runners/tests/test-eval-readiness.ps1 @@ -37,6 +37,22 @@ try { $globalTools = [IO.Path]::Combine($homePath, '.dotnet', 'tools') Assert-ReadyTest ($globalTools -in ($environment['PATH'] -split [IO.Path]::PathSeparator)) 'Isolated global tools must be discoverable through the child process PATH.' + # A directory that holds both commands must not shadow an earlier dotnet. + $previousPath = $env:PATH + try { + $firstBin, $sharedBin = 'first-bin', 'shared-bin' | ForEach-Object { (New-Item -ItemType Directory -Path (Join-Path $root $_)).FullName } + $extension = if ($IsWindows) { '.cmd' } else { '' } + foreach ($file in (Join-Path $firstBin "dotnet$extension"), (Join-Path $sharedBin "dotnet$extension"), (Join-Path $sharedBin "pwsh$extension")) { + [IO.File]::WriteAllText($file, '') + if (-not $IsWindows) { & chmod '+x' $file } + } + $env:PATH = $firstBin, $sharedBin, $previousPath -join [IO.Path]::PathSeparator + $ordered = New-RunnerShellEnvironment -Run $run + $isolatedPath = @($ordered['PATH'] -split [IO.Path]::PathSeparator) + Assert-ReadyTest ($isolatedPath.IndexOf($firstBin) -ge 0 -and $isolatedPath.IndexOf($firstBin) -lt $isolatedPath.IndexOf($sharedBin)) 'The isolated PATH must keep the host PATH order.' + Assert-ReadyTest ($ordered['DOTNET_ROOT'] -ceq $firstBin) 'DOTNET_ROOT must match the dotnet selected by the isolated PATH.' + } finally { $env:PATH = $previousPath } + # Load only the job functions so the validator's suite dispatcher does not run. $tokens = $null $parseErrors = $null @@ -66,7 +82,7 @@ exit 0 $result = New-EvalReadinessObservation -Probe $probe -Response @{ result = @{ exitCode = $process.ExitCode; stdout = $process.Stdout; stderr = $process.Stderr } } Assert-ReadyTest ($result.status -eq 'ready') "$($result.id) failed: $($result.diagnostic)" } - $probe = @(Get-EvalReadinessProbes -Run $run)[1] + $probe = @(Get-EvalReadinessProbes -Run $run | Where-Object id -eq 'pwsh-version')[0] $failed = New-EvalReadinessObservation -Probe $probe -Response @{ result = @{ exitCode = 127; stderr = 'Missing tool' } } $mismatch = New-EvalReadinessObservation -Probe $probe -Response @{ result = @{ exitCode = 0; stdout = 'PowerShell 6.0' } } $unavailable = New-EvalReadinessObservation -Probe $probe -Response @{ error = @{ code = -32601 } } @@ -182,7 +198,7 @@ exit 0 $nativeHome = Join-Path $physical.HomeDirectoryPath 'native-test-parent' New-Item -ItemType Directory -Path $nativeHome -Force | Out-Null try { - $nativeParent = New-RunnerEnvironment -Run $physical -AuthenticationVariables @('OPENAI_API_KEY') -Additional @{ CODEX_HOME = $nativeHome } + $nativeParent = New-RunnerEnvironment -Run $physical -Additional @{ CODEX_HOME = $nativeHome } $observation = Invoke-CodexAppServer -ReadinessOnly -CommandInfo $native -Inputs @{ Run = $physical } -Auth @{ Kind = 'subscription_file' } -AuthHome @{ Path = $nativeHome; AuthOnly = $true } -ParentEnvironment $nativeParent -TimeoutSeconds 85 Assert-ReadyTest ($observation.Readiness.Count -gt 0) "App Server produced no readiness evidence. $(Get-JsonProperty -Object $observation -Name 'TransportFailure')" foreach ($check in $observation.Readiness) { diff --git a/scripts/eval-runners/tests/test-integrity-finalization.ps1 b/scripts/eval-runners/tests/test-integrity-finalization.ps1 index 3fdd5e6a..ac107c8a 100644 --- a/scripts/eval-runners/tests/test-integrity-finalization.ps1 +++ b/scripts/eval-runners/tests/test-integrity-finalization.ps1 @@ -57,17 +57,35 @@ function Read-TestJson { return [System.IO.File]::ReadAllText($Path, [System.Text.UTF8Encoding]::new($false)) | ConvertFrom-Json -Depth 100 } +$script:TestClock = [System.Diagnostics.Stopwatch]::StartNew() + +# STDERR carries live progress only; STDOUT stays reserved for the tool protocol. +function Write-TestProgress { + param([Parameter(Mandatory = $true)][string]$Line) + [Console]::Error.WriteLine(('[{0}] {1}' -f ('+{0:N1}s' -f $script:TestClock.Elapsed.TotalSeconds), $Line)) +} + function Invoke-TestTool { param( [Parameter(Mandatory = $true)][string]$Path, [Parameter(Mandatory = $true)][string[]]$Arguments ) + $label = '{0} {1}' -f (Split-Path -Leaf $Path), (($Arguments | Select-Object -First 2) -join ' ') + Write-TestProgress "[START] $label" + $started = $script:TestClock.Elapsed.TotalSeconds $output = & pwsh -NoProfile -NonInteractive -File $Path @Arguments 2>&1 $exitCode = $LASTEXITCODE + # Relay child tools' progress lines, and keep them out of the captured result + # so machine-readable stdout (JSON) and assertion text stay exactly as before. + $kept = [System.Collections.Generic.List[string]]::new() + foreach ($line in @($output | ForEach-Object { [string]$_ })) { + if ($line -match '^\[(START|COMPLETE|PROGRESS|HEARTBEAT)\]') { Write-TestProgress " child: $line" } else { $kept.Add($line) } + } + Write-TestProgress ('[COMPLETE] {0} exit={1} took={2:N1}s' -f $label, $exitCode, ($script:TestClock.Elapsed.TotalSeconds - $started)) return [pscustomobject]@{ ExitCode = $exitCode - Text = [string]::Join([Environment]::NewLine, @($output | ForEach-Object { [string]$_ })) + Text = [string]::Join([Environment]::NewLine, @($kept)) } } @@ -77,9 +95,12 @@ function Invoke-ForegroundPhaseOne { # STDOUT is the machine protocol; STDERR is live observability. Capture them # separately so relayed heartbeats never contaminate the terminal JSON. $stderrPath = Join-Path ([System.IO.Path]::GetTempPath()) ('phase1-stderr-' + [Guid]::NewGuid().ToString('N') + '.log') + Write-TestProgress "[START] Phase 1 fan-out $(Split-Path -Leaf $Path)" + $started = $script:TestClock.Elapsed.TotalSeconds try { $output = & pwsh -NoProfile -NonInteractive -File $Path -IterationDirectory $IterationDirectory 2>$stderrPath $exitCode = $LASTEXITCODE + Write-TestProgress ('[COMPLETE] Phase 1 fan-out exit={0} took={1:N1}s' -f $exitCode, ($script:TestClock.Elapsed.TotalSeconds - $started)) $text = [string]::Join([Environment]::NewLine, @($output | ForEach-Object { [string]$_ })) $stderr = if (Test-Path -LiteralPath $stderrPath -PathType Leaf) { [System.IO.File]::ReadAllText($stderrPath, [System.Text.UTF8Encoding]::new($false)) } else { '' } } finally { diff --git a/scripts/eval-runners/tests/test-orchestration.ps1 b/scripts/eval-runners/tests/test-orchestration.ps1 index 3505cea7..b45832dd 100644 --- a/scripts/eval-runners/tests/test-orchestration.ps1 +++ b/scripts/eval-runners/tests/test-orchestration.ps1 @@ -45,7 +45,7 @@ function Invoke-ForegroundPhaseOne { # never contaminate the JSON the controller parses. $stderrPath = Join-Path ([System.IO.Path]::GetTempPath()) ('phase1-stderr-' + [Guid]::NewGuid().ToString('N') + '.log') try { - $output = & pwsh -NoProfile -NonInteractive -File $fanout -IterationDirectory $IterationDirectory 2>$stderrPath + $output = & (Get-RunnerPowerShellPath) -NoProfile -NonInteractive -File $fanout -IterationDirectory $IterationDirectory 2>$stderrPath $exitCode = $LASTEXITCODE $text = [string]::Join([Environment]::NewLine, @($output | ForEach-Object { [string]$_ })) $stderr = if (Test-Path -LiteralPath $stderrPath -PathType Leaf) { [System.IO.File]::ReadAllText($stderrPath, [System.Text.UTF8Encoding]::new($false)) } else { '' } @@ -652,7 +652,22 @@ try { Assert-True (-not (Test-Path -LiteralPath (Join-Path $crashPackage 'execution-freeze.json'))) 'missing runner evidence cannot enter freeze' $fixtureLogPath = Join-Path $testRoot 'runner-owned-events.jsonl' $env:AGENTIC_RUNNER_FIXTURE_LOG = $fixtureLogPath - $fanoutControl = Invoke-ForegroundPhaseOne -IterationDirectory $fanoutPackage + $originalPath = $env:PATH + $previousExitVariable = Get-Variable LASTEXITCODE -Scope Global -ErrorAction SilentlyContinue + $previousExitCode = if ($null -ne $previousExitVariable) { $previousExitVariable.Value } + try { + $env:PATH = $testRoot + Assert-True (-not (Get-Command pwsh -CommandType Application -ErrorAction SilentlyContinue)) 'fixture PATH excludes PowerShell' + Remove-Variable LASTEXITCODE -Scope Global -ErrorAction SilentlyContinue + $fixtureManifest = Read-RunnerJson -Path (Join-Path $fanoutPackage 'manifest.json') + $identity = Assert-PackageRunnerIdentity -IterationDirectory $fanoutPackage -Manifest $fixtureManifest + Assert-Equal 'fixture' $identity.Descriptor.name 'package identity resolves in a fresh host without LASTEXITCODE' + Assert-True ($null -eq (Get-Variable LASTEXITCODE -Scope Global -ErrorAction SilentlyContinue)) 'package identity does not use native invocation in the parent PowerShell host' + $fanoutControl = Invoke-ForegroundPhaseOne -IterationDirectory $fanoutPackage + } finally { + $env:PATH = $originalPath + if ($null -ne $previousExitVariable) { $global:LASTEXITCODE = $previousExitCode } + } Assert-Equal 0 $fanoutControl.ExitCode ("deterministic runner-owned Phase 1 exits successfully; output: " + $fanoutControl.Text) $fanoutSummary = $fanoutControl.Document Assert-Equal 'phase1' $fanoutSummary.phase 'deterministic runner-owned fan-out reports a Phase 1 summary' diff --git a/scripts/eval-runners/tests/test-phase1-controller-lifecycle.ps1 b/scripts/eval-runners/tests/test-phase1-controller-lifecycle.ps1 index adcb44ad..2ed1ad2e 100644 --- a/scripts/eval-runners/tests/test-phase1-controller-lifecycle.ps1 +++ b/scripts/eval-runners/tests/test-phase1-controller-lifecycle.ps1 @@ -219,12 +219,18 @@ try { Assert-True (-not (Test-Path -LiteralPath $interruptedLog -PathType Leaf)) 'foreground Phase 1 interrupted-state refusal starts zero executions' $preflightGate = New-ForegroundPackage -IterationDirectory (Join-Path $testRoot 'preflight-gate') -EvalCount 2 -Concurrency 2 - [System.IO.File]::WriteAllText((Join-Path $preflightGate.IterationDirectory 'foreground-eval-02\with_skill\home\preflight-incompatible'), 'fixture', [System.Text.UTF8Encoding]::new($false)) + foreach ($configuration in 'with_skill', 'without_skill') { + $gateRunPath = Join-Path $preflightGate.IterationDirectory "foreground-eval-02/$configuration/run.json" + $gateRun = Get-Content -LiteralPath $gateRunPath -Raw | ConvertFrom-Json -AsHashtable + $gateRun.prerequisites = @{ executables = @('agentic-nonexistent-prerequisite') } + Write-TestJson -Path $gateRunPath -Value $gateRun + } [Environment]::SetEnvironmentVariable('AGENTIC_RUNNER_FIXTURE_LOG', $preflightGate.LogPath) $gate = Invoke-ForegroundPhaseOne -IterationDirectory $preflightGate.IterationDirectory Assert-Equal 2 $gate.ExitCode 'foreground Phase 1 exits non-zero for incompatible preflight' - Assert-Equal 'preflight' ([string]$gate.Document.phase) 'foreground Phase 1 reports preflight phase failure' + Assert-Equal 'preflight' ([string]$gate.Document.phase) "foreground Phase 1 reports preflight phase failure: $($gate.Text)" Assert-Equal 'preflight_incompatible' ([string]$gate.Document.status) 'foreground Phase 1 reports incompatible preflight' + Assert-Equal 2 ([int]$gate.Document.infrastructure_blocked_eval_ids[0]) 'foreground Phase 1 identifies the prerequisite-blocked eval' Assert-Equal 4 ([int]$gate.Document.preflight_count) 'foreground Phase 1 still probes every arm' Assert-True (-not [bool]$gate.Document.execution_started) 'foreground Phase 1 starts zero executions when any preflight is incompatible' $gateEvents = @(Get-Content -LiteralPath $preflightGate.LogPath | ForEach-Object { $_ | ConvertFrom-Json }) diff --git a/scripts/eval-runners/tests/test-probe-environment.ps1 b/scripts/eval-runners/tests/test-probe-environment.ps1 index b59ca59d..971868bc 100644 --- a/scripts/eval-runners/tests/test-probe-environment.ps1 +++ b/scripts/eval-runners/tests/test-probe-environment.ps1 @@ -166,6 +166,23 @@ $version = Get-ExternalCommandVersion -CommandInfo $pwshInfo Assert-False ([bool]$childSummary.resolved_is_system) 'probe child resolver must not return a system directory' Assert-True ([bool]$childSummary.version_available) 'model-free pwsh --version probe must succeed under the probe environment' + # A headless host can launch PowerShell by absolute path while omitting its + # installation from PATH. Exercise the package descriptor and its nested + # PowerShell-based OpenCode shim in that environment. + $shimDirectory = Join-Path $testRoot 'shim-bin' + New-Item -ItemType Directory -Path $shimDirectory | Out-Null + $shimPath = Join-Path $shimDirectory 'opencode.ps1' + [IO.File]::WriteAllText($shimPath, 'if ($args -contains ''--version'') { ''opencode v2.4.5'' } else { throw ''Only the version probe is expected.'' }') + $originalPath = $env:PATH + try { + $env:PATH = $shimDirectory + Assert-False ([bool](Get-Command pwsh -CommandType Application -ErrorAction SilentlyContinue)) 'fixture PATH excludes PowerShell' + $descriptor = Get-PackageRunnerDescriptor -RunnerName opencode + Assert-Equal 'opencode v2.4.5' $descriptor.harness.version 'package descriptor and its shim use the running PowerShell without PATH' + } finally { + $env:PATH = $originalPath + } + # ===================================================================== # Scenario 2 (item #8): the model-free probe environment and the model-backed # OpenCode eval isolation environment are distinct and must not be merged. @@ -251,6 +268,35 @@ $version = Get-ExternalCommandVersion -CommandInfo $pwshInfo Assert-Equal 'deny' ([string]$withConfig.permission.skill.'*') 'with_skill eval config must deny all skills by default' Assert-Equal 'allow' ([string]$withConfig.permission.skill.'dotnet-strong-name-signing') 'with_skill eval config must allow only the prepared candidate' + # Both arms get identical web tool access, so a non-interactive run never + # stops on a web search or web fetch prompt, while the skill policy is + # unchanged and still verified by the policy observation. + foreach ($arm in @(@{ Name = 'without_skill'; Inputs = $inputsWithout; Skill = '"deny"' }, @{ Name = 'with_skill'; Inputs = $inputsWith; Skill = '{"*":"deny","dotnet-strong-name-signing":"allow"}' })) { + $v1Environment = New-OpenCodeEnvironment -Inputs $arm.Inputs + $v1Config = [System.IO.File]::ReadAllText([string]$v1Environment['OPENCODE_CONFIG'], [System.Text.UTF8Encoding]::new($false)) | ConvertFrom-Json + Assert-Equal 'skill,websearch,webfetch' ([string]::Join(',', @($v1Config.permission.PSObject.Properties.Name))) "$($arm.Name) v1 permission holds only skill, websearch and webfetch" + Assert-Equal $arm.Skill ($v1Config.permission.skill | ConvertTo-Json -Compress) "$($arm.Name) v1 permission.skill is unchanged" + Assert-Equal 'allow' ([string]$v1Config.permission.websearch) "$($arm.Name) v1 config allows web search" + Assert-Equal 'allow' ([string]$v1Config.permission.webfetch) "$($arm.Name) v1 config allows web fetch" + $v1Policy = Get-OpenCodeSkillPolicyObservation -Inputs $arm.Inputs -Environment $v1Environment + Assert-True ([bool]$v1Policy.permission_match) "$($arm.Name) v1 skill policy observation still matches: $($v1Policy.reason)" + $v1Debug = Get-OpenCodeDebugConfigObservation -Inputs $arm.Inputs -DebugResult ([pscustomobject]@{ TimedOut = $false; ExitCode = 0; Stdout = ($v1Config | ConvertTo-Json -Depth 20); Stderr = '' }) + Assert-True ([bool]$v1Debug.permission_match) "$($arm.Name) v1 debug config observation still matches: $($v1Debug.reason)" + + $v2Environment = New-OpenCodeEnvironment -Inputs $arm.Inputs -V2 + $v2Config = [System.IO.File]::ReadAllText([string]$v2Environment['OPENCODE_CONFIG'], [System.Text.UTF8Encoding]::new($false)) | ConvertFrom-Json + $v2Rules = [string]::Join(';', @($v2Config.permissions | ForEach-Object { "$($_.action)|$($_.resource)|$($_.effect)" })) + $expectedSkillRules = if ($arm.Name -eq 'with_skill') { 'skill|*|deny;skill|dotnet-strong-name-signing|allow' } else { 'skill|*|deny' } + Assert-Equal "$expectedSkillRules;subagent|*|deny;websearch|*|allow;webfetch|*|allow" $v2Rules "$($arm.Name) v2 permissions keep the skill rules and allow web search and web fetch" + Assert-Equal 'random' ([string]$v2Config.websearch.provider) "$($arm.Name) v2 config pre-selects the web search provider so no provider form is asked" + $v2Policy = Get-OpenCodeSkillPolicyObservation -Inputs $arm.Inputs -Environment $v2Environment + Assert-True ([bool]$v2Policy.permission_match) "$($arm.Name) v2 skill policy observation still matches: $($v2Policy.reason)" + Assert-Equal $arm.Skill ($v2Policy.configured_permission_skill | ConvertTo-Json -Compress) "$($arm.Name) v2 extracted skill policy is unchanged" + $v2DebugText = ConvertTo-Json -InputObject @(@{ type = 'document'; path = [string]$v2Environment['OPENCODE_CONFIG']; info = @{ permissions = $v2Config.permissions } }) -Depth 10 -Compress + $v2Debug = Get-OpenCodeDebugConfigObservation -V2 -Inputs $arm.Inputs -DebugResult ([pscustomobject]@{ TimedOut = $false; ExitCode = 0; Stdout = $v2DebugText; Stderr = '' }) + Assert-True ([bool]$v2Debug.permission_match) "$($arm.Name) v2 debug config observation still matches: $($v2Debug.reason)" + } + & (Join-Path $PSScriptRoot 'test-eval-readiness.ps1') Write-Output 'Probe environment regression: PASS' } finally { diff --git a/scripts/eval-runners/tests/test-runner-conformance.ps1 b/scripts/eval-runners/tests/test-runner-conformance.ps1 index 43f67359..3c6f8f8c 100644 --- a/scripts/eval-runners/tests/test-runner-conformance.ps1 +++ b/scripts/eval-runners/tests/test-runner-conformance.ps1 @@ -23,6 +23,7 @@ $repoRoot = (Resolve-Path (Join-Path $PSScriptRoot '..\..\..')).Path . (Join-Path $runnerRoot 'manifest-paths.ps1') . (Join-Path $runnerRoot 'execution-freeze.ps1') . (Join-Path $runnerRoot 'package-integrity.ps1') +. (Join-Path $PSScriptRoot 'fixtures/readiness-cases.ps1') function Assert-True { param([bool]$Condition, [string]$Message) @@ -122,9 +123,77 @@ function Invoke-AdapterJson { return $json | ConvertFrom-Json } +function Invoke-AdapterJsonBatch { + # Runs one real adapter command per item through the recorded launcher and returns the parsed JSON by item name. + # Items must not share mutable state. `agentic-tooling run-parallel` owns the bounded scheduling, process trees, + # timeouts and progress; this adapter only describes the items and reads each item's stdout back. + param( + [Parameter(Mandatory = $true)][object[]]$Items, + [Parameter(Mandatory = $true)][string]$RunnerPath, + [Parameter(Mandatory = $true)][string]$Command, + [Parameter(Mandatory = $true)][string]$ProfilePath, + [Parameter(Mandatory = $true)][string]$Label + ) + + $launcherPath = Join-Path $PSScriptRoot 'fixtures/invoke-recorded-adapter.ps1' + $work = [IO.Directory]::CreateTempSubdirectory('agentic-adapter-batch-').FullName + try { + $itemsPath = Join-Path $work 'items.json' + # Work item names must be file-name safe; callers' names (often paths) are mapped back by position. + $descriptions = @(for ($index = 0; $index -lt $Items.Count; $index++) { + $item = $Items[$index] + @{ name = "item-$index"; workingDirectory = $repoRoot; steps = @(@{ command = @('pwsh', '-NoProfile', '-NonInteractive', '-File', $launcherPath, '-RunnerPath', $RunnerPath, '-Command', $Command, '-Run', [string]$item.Path, '-Profile', $ProfilePath) }) } + }) + [IO.File]::WriteAllText($itemsPath, (@{ schema = 'codebeltnet/agentic/parallel-items/1'; items = $descriptions } | ConvertTo-Json -Depth 8), [Text.UTF8Encoding]::new($false)) + $resultsPath = & $script:AgenticToolingHost $script:AgenticToolingAssembly run-parallel --items $itemsPath --out (Join-Path $work 'out') --max-concurrency ([Math]::Min(6, [Environment]::ProcessorCount)) --timeout-seconds 300 --label $Label + if (-not $resultsPath -or -not (Test-Path -LiteralPath $resultsPath)) { throw "run-parallel produced no results for '$Label' (exit $LASTEXITCODE)." } + $results = @{} + foreach ($outcome in @((Get-Content -LiteralPath $resultsPath -Raw | ConvertFrom-Json).results)) { + $name = [string]$Items[[int]$outcome.name.Substring('item-'.Length)].Name + if ($outcome.status -ne 'PASS') { throw "Recorded runner '$Command' failed for '$RunnerPath' ($name, $($outcome.status)): $((Get-Content -LiteralPath $outcome.log -Raw)) $($outcome.details -join '; ')" } + $json = Get-Content -LiteralPath $outcome.stdout -Raw + if ([string]::IsNullOrWhiteSpace($json)) { throw "Recorded runner '$Command' returned no JSON for '$RunnerPath' ($name)." } + $results[$name] = $json | ConvertFrom-Json + } + return $results + } finally { + [IO.Directory]::Delete($work, $true) + } +} + +function Invoke-AdapterScenarioBatch { + # Runs one real adapter execute per scenario, each against its own copy of a recorded run with the scenario's + # fixture marker in that copy's isolated home. Copies share no mutable state, so they run concurrently, bounded. + param( + [Parameter(Mandatory = $true)][object[]]$Scenarios, + [Parameter(Mandatory = $true)][string]$RunnerPath, + [Parameter(Mandatory = $true)][string]$ProfilePath, + [Parameter(Mandatory = $true)][string]$Root + ) + + $roots = @{} + $items = @(foreach ($scenario in $Scenarios) { + $source = [IO.Path]::GetFullPath([string]$scenario.Run.Root) + $target = Join-Path $Root "iteration-scenario-$($scenario.Name)/conformance/$(Split-Path -Leaf $source)" + New-Item -ItemType Directory -Path (Split-Path -Parent $target) -Force | Out-Null + Copy-Item -LiteralPath $source -Destination $target -Recurse -Force + [IO.File]::WriteAllText((Join-Path $target "home/$($scenario.Marker)"), 'fixture', [Text.UTF8Encoding]::new($false)) + $roots[[string]$scenario.Name] = $target + [pscustomobject]@{ Name = [string]$scenario.Name; Path = Join-Path $target 'run.json' } + }) + $results = Invoke-AdapterJsonBatch -Items $items -RunnerPath $RunnerPath -Command execute -ProfilePath $ProfilePath -Label 'recorded adapter scenarios' + return [pscustomobject]@{ Results = $results; Roots = $roots } +} + function Invoke-RecordedRunnerTests { $recordedRoot = Join-Path ([System.IO.Path]::GetTempPath()) ('agentic-recorded-runner-' + [Guid]::NewGuid().ToString('N')) $recordedOldPath = $env:PATH +# Resolved before any fixture puts a fake `dotnet` first on PATH, and only for suites that run adapter batches. +if ($Suite -ne 'Protocol') { + . (Join-Path $repoRoot 'scripts/agentic-tooling.ps1') + $script:AgenticToolingAssembly = Resolve-AgenticToolingAssembly + $script:AgenticToolingHost = (Get-Command -Name 'dotnet' -CommandType Application | Select-Object -First 1).Source +} $recordedOldOpenAi = $env:OPENAI_API_KEY $recordedOldCodexHome = $env:CODEX_HOME $recordedOldGlobalSecret = $env:AGENTIC_GLOBAL_SECRET @@ -171,6 +240,9 @@ try { param([Parameter(ValueFromRemainingArguments = $true)][string[]]$RemainingArguments) $harness = [System.IO.Path]::GetFileNameWithoutExtension($MyInvocation.MyCommand.Path) $logPath = Join-Path (Get-Location).Path ("{0}-fake-cli-log.jsonl" -f $harness) +if ($env:HOME -and (Test-Path -LiteralPath (Join-Path $env:HOME 'readiness-fixture'))) { + $logPath = Join-Path $env:HOME "$harness-fake-cli-log.jsonl" +} $arguments = @($RemainingArguments | ForEach-Object { [string]$_ }) $fixtureRoot = [Environment]::GetEnvironmentVariable('AGENTIC_RECORDED_FIXTURES') if ([string]::IsNullOrWhiteSpace($fixtureRoot)) { $fixtureRoot = Join-Path (Split-Path -Parent $MyInvocation.MyCommand.Path) 'fixtures' } @@ -188,6 +260,58 @@ $fakeHomeFixture = Test-FixtureMarker -Name 'opencode-fake-home' $noSessionFirstFixture = Test-FixtureMarker -Name 'scripted-no-session-first' $noTerminalFirstFixture = Test-FixtureMarker -Name 'scripted-no-terminal-first' $mismatchSessionFixture = Test-FixtureMarker -Name 'scripted-session-mismatch' +if ($harness -eq 'opencode' -and ((Test-FixtureMarker -Name 'opencode-v2-fixture') -or (Test-FixtureMarker -Name 'opencode-v2-wrong-model'))) { + $currentDirectory = (Get-Location).Path + $sessionId = 'recorded-opencode-v2-session' + $sessionPath = Join-Path $fixtureHome 'opencode-v2-session.json' + if ($arguments -contains '--version') { Write-Output 'opencode v2.4.5'; exit 0 } + if ($arguments -contains '--help') { + if ($arguments -contains 'debug') { Write-Output ' config List configuration sources' } + elseif ($arguments -contains 'session') { Write-Output ' export Export session data as JSON' } + else { Write-Output "--format choice`n--standalone`n--model string`n--auto`n--title string`n--session, -s string Session ID to continue, or to create if it does not exist" } + exit 0 + } + if ($arguments -contains 'paths') { + foreach ($name in @('home', 'data', 'cache', 'config', 'state', 'db')) { + $path = if ($name -eq 'home') { $fixtureHome } else { Join-Path $fixtureHome $name } + Write-Output "$name $path" + } + exit 0 + } + if ($arguments -notcontains '--standalone') { throw 'Recorded OpenCode v2 requires a private server.' } + if ($arguments -contains 'config') { + $config = Get-Content -LiteralPath $env:OPENCODE_CONFIG -Raw | ConvertFrom-Json -AsHashtable + if (-not $config.permissions -or -not $config.agents.title.disabled -or $config.compaction.auto) { throw 'Recorded OpenCode v2 requires native skill permissions and disables auxiliary model turns.' } + ConvertTo-Json -InputObject @(@{ type = 'document'; path = $env:OPENCODE_CONFIG; info = @{ permissions = $config.permissions } }) -Depth 10 -Compress + exit 0 + } + if ($arguments -contains 'export') { + if ($arguments[-1] -cne $sessionId) { throw 'Recorded OpenCode v2 export was not addressed to the exact session.' } + $jsonBytes = [IO.File]::ReadAllBytes($sessionPath) + [Console]::OpenStandardOutput().Write($jsonBytes, 0, $jsonBytes.Length) + exit 0 + } + if ($arguments -contains '--dir' -or $arguments -contains '--variant' -or $arguments -notcontains '--title') { throw 'Recorded OpenCode v2 received v1 flags or omitted the explicit title.' } + $modelIndex = [Array]::IndexOf($arguments, '--model') + $modelSelector = [string]$arguments[$modelIndex + 1] + if ($modelSelector -cne 'opencode/muse-spark-1.2-contributor-free#medium') { throw "Unexpected OpenCode v2 model selector '$modelSelector'." } + $stdin = [Console]::OpenStandardInput() + $reader = [IO.StreamReader]::new($stdin, [Text.UTF8Encoding]::new($false)) + $message = $reader.ReadToEnd() + $model = @{ providerID = 'opencode'; id = 'muse-spark-1.2-contributor-free'; variant = 'medium' } + if (Test-FixtureMarker -Name 'opencode-v2-wrong-model') { $model.variant = 'low' } + $messages = @() + if ($arguments -contains '--session') { + if ($arguments[-1] -cne $sessionId) { throw 'Recorded OpenCode v2 continuation used the wrong session.' } + $messages = @((Get-Content -LiteralPath $sessionPath -Raw | ConvertFrom-Json).messages) + } + $messages += @(@{ type = 'user'; text = $message }, @{ type = 'assistant'; model = $model }) + $session = @{ info = @{ id = $sessionId; outcome = 'succeeded'; model = $model; location = @{ directory = $currentDirectory } }; messages = $messages } + [IO.File]::WriteAllText($sessionPath, ($session | ConvertTo-Json -Depth 10 -Compress), [Text.UTF8Encoding]::new($false)) + @{ type = 'text'; sessionID = $sessionId; timestamp = 1796508805692; part = @{ text = 'fixture v2 response' } } | ConvertTo-Json -Depth 4 -Compress + @{ type = 'step_finish'; sessionID = $sessionId; timestamp = 1796508805694; part = @{ tokens = @{ input = 12; output = 4; reasoning = 0; cache = @{ read = 2; write = 1 } } } } | ConvertTo-Json -Depth 5 -Compress + exit 0 +} if ($arguments -contains '--version') { $version = switch ($harness) { 'codex' { 'recorded-codex 9.1' } 'opencode' { 'recorded-opencode 9.2' } default { 'recorded-unknown 9.3' } } if ($timingFixture) { Start-Sleep -Milliseconds 20 } @@ -565,6 +689,40 @@ if ($harness -eq 'codex' -and $arguments -contains 'app-server') { Write-AppServerMessage ([ordered]@{ jsonrpc = '2.0'; id = $initialize.id; result = [ordered]@{ serverInfo = [ordered]@{ name = 'recorded-codex'; version = '9.1' } } }) $initialized = Read-AppServerMessage $skillsList = Read-AppServerMessage + if ($skillsList.method -eq 'command/exec') { + if ($env:OPENAI_API_KEY -or (Test-Path -LiteralPath (Join-Path $env:CODEX_HOME 'auth.json'))) { throw 'Readiness App Server was authenticated.' } + if ('shell_environment_policy.inherit=none' -notin $arguments) { throw 'Readiness shell inherits ambient variables.' } + $policy = $arguments | Where-Object { $_ -like 'shell_environment_policy.set=*' } + $environment = [ordered]@{} + foreach ($pair in [regex]::Matches($policy, '("([^"\\]|\\.)*")=("([^"\\]|\\.)*")')) { + $environment[(ConvertFrom-Json $pair.Groups[1].Value)] = ConvertFrom-Json $pair.Groups[3].Value + } + $request = $skillsList + while ($null -ne $request) { + if ($request.method -ne 'command/exec') { throw "Readiness called $($request.method)." } + $start = [Diagnostics.ProcessStartInfo]::new() + $start.FileName = $request.params.command[0] + $start.WorkingDirectory = $request.params.cwd + $start.UseShellExecute = $false + $start.RedirectStandardOutput = $true + $start.RedirectStandardError = $true + foreach ($argument in ($request.params.command | Select-Object -Skip 1)) { $start.ArgumentList.Add($argument) } + $start.Environment.Clear() + foreach ($key in $environment.Keys) { $start.Environment[$key] = $environment[$key] } + $child = [Diagnostics.Process]::Start($start) + try { + $stdout = $child.StandardOutput.ReadToEndAsync() + $stderr = $child.StandardError.ReadToEndAsync() + if (-not $child.WaitForExit($request.params.timeoutMs)) { + $child.Kill($true) + throw 'Readiness fixture child timed out.' + } + Write-AppServerMessage @{ jsonrpc = '2.0'; id = $request.id; result = @{ exitCode = $child.ExitCode; stdout = $stdout.GetAwaiter().GetResult(); stderr = $stderr.GetAwaiter().GetResult() } } + } finally { $child.Dispose() } + $request = Read-AppServerMessage -AllowEndOfStream + } + exit 0 + } $skillConfigArgs = @($arguments | Where-Object { [string]$_ -like 'skills.config=*' }) $candidateName = 'candidate' $includeInstructionsDisabled = @($arguments | Where-Object { [string]$_ -eq 'skills.include_instructions=false' }).Count -eq 1 @@ -1416,6 +1574,29 @@ if ($harness -eq 'codex') { } } if ($Suite -in @('All', 'OpenCode')) { + $v2RunnerPath = Join-Path $repoRoot 'scripts/eval-runners/opencode/runner.ps1' + $v2InputRoot = Join-Path $recordedRoot 'opencode-v2-inputs' + $v2SingleInput = New-TestRun -IterationDirectory (Join-Path $v2InputRoot 'single') -Configuration without_skill + $v2ScriptedInput = New-TestRun -IterationDirectory (Join-Path $v2InputRoot 'scripted') -Configuration with_skill -Interaction $scriptedInteraction + Add-TestInteractionSources -TestRun $v2ScriptedInput + $v2ScenarioBatch = Invoke-AdapterScenarioBatch -RunnerPath $v2RunnerPath -ProfilePath $recordedProfiles['opencode'] -Root $recordedRoot -Scenarios @( + [pscustomobject]@{ Name = 'opencode-v2-single'; Run = $v2SingleInput; Marker = 'opencode-v2-fixture' }, + [pscustomobject]@{ Name = 'opencode-v2-scripted'; Run = $v2ScriptedInput; Marker = 'opencode-v2-fixture' }, + [pscustomobject]@{ Name = 'opencode-v2-wrong-variant'; Run = $v2ScriptedInput; Marker = 'opencode-v2-wrong-model' } + ) + $v2Single = $v2ScenarioBatch.Results['opencode-v2-single'] + Assert-Equal 'completed' $v2Single.status "OpenCode v2 completes with private process and native session export. $(Get-JsonProperty $v2Single.exit.failure 'message' '')" + Assert-Equal 'fixture v2 response' $v2Single.final_response.text 'OpenCode v2 extracts the native final response' + Assert-True (@($v2Single.artifacts | Where-Object path -eq 'evidence/opencode-session.json').Count -eq 1) 'OpenCode v2 preserves the native session export' + Assert-Equal 2 $v2Single.telemetry.tokens.value.cache_read 'OpenCode v2 retains nested cache counters' + Assert-True ($null -ne $v2Single.evidence.timing.turns[0].event_timing) 'OpenCode v2 recognizes epoch-millisecond event timestamps' + $v2Scripted = $v2ScenarioBatch.Results['opencode-v2-scripted'] + Assert-Equal 'completed' $v2Scripted.status "OpenCode v2 resumes its exact native session. $(Get-JsonProperty $v2Scripted.exit.failure 'message' '')" + Assert-Equal 2 @($v2Scripted.evidence.interaction.native_turns | Where-Object model_source -eq 'session_export').Count 'OpenCode v2 verifies model and variant before accepting each scripted turn' + $v2WrongVariant = $v2ScenarioBatch.Results['opencode-v2-wrong-variant'] + Assert-Equal 'incompatible' $v2WrongVariant.status 'OpenCode v2 rejects a different observed variant' + Assert-Equal 1 @($v2WrongVariant.evidence.interaction.native_turns).Count 'OpenCode v2 aborts before disclosing the second prompt on a model mismatch' + $isolatedHomeFailureIteration = Join-Path $recordedRoot 'opencode-isolation-failure' New-Item -ItemType Directory -Path $isolatedHomeFailureIteration -Force | Out-Null $isolatedHomeFailureRun = New-TestRun -IterationDirectory $isolatedHomeFailureIteration -Configuration without_skill -EvalName 'opencode-isolation-failure' @@ -1614,39 +1795,49 @@ if ($harness -eq 'codex') { $authHomePath = [string]$subscriptionRecord.parent_codex_home Assert-True (-not (Test-Path -LiteralPath $authHomePath)) 'Codex temporary auth-only home is removed after the arm completes' - $candidateAbsentMarker = Join-Path $without.Root 'home\codex-native-skill-candidate-absent' - [System.IO.File]::WriteAllText($candidateAbsentMarker, 'fixture', [System.Text.UTF8Encoding]::new($false)) - $candidateAbsentResult = Invoke-AdapterJson -RunnerPath (Join-Path $runnerRoot 'codex\runner.ps1') -Command execute -RunPath $without.Path -ProfilePath $recordedProfiles['codex'] + # Each marker selects one recorded fake-CLI behavior. The scenarios share no mutable state, so each runs the real + # runner against its own copy of the recorded run, concurrently and bounded, instead of one after another. + $codexScenarios = Invoke-AdapterScenarioBatch -RunnerPath (Join-Path $runnerRoot 'codex\runner.ps1') -ProfilePath $recordedProfiles['codex'] -Root $recordedRoot -Scenarios @( + @{ Name = 'candidateAbsent'; Run = $without; Marker = 'codex-native-skill-candidate-absent' }, + @{ Name = 'candidateEnabled'; Run = $without; Marker = 'codex-native-skill-candidate-enabled-execute-only' }, + @{ Name = 'newAmbient'; Run = $without; Marker = 'codex-new-ambient-enabled' }, + @{ Name = 'ambientAccess'; Run = $without; Marker = 'codex-ambient-skill-access' }, + @{ Name = 'runtimeUnavailable'; Run = $with; Marker = 'codex-runtime-evidence-unavailable' }, + @{ Name = 'stagedAccess'; Run = $with; Marker = 'codex-staged-skill-access' }, + @{ Name = 'ambientProse'; Run = $with; Marker = 'codex-ambient-skill-prose' }, + @{ Name = 'prosePolicy'; Run = $with; Marker = 'codex-prose-blocked-by-policy' }, + @{ Name = 'policyBlocked'; Run = $with; Marker = 'codex-policy-blocked' }, + @{ Name = 'baselinePolicyBlocked'; Run = $without; Marker = 'codex-policy-blocked' }, + @{ Name = 'stderrPolicyRejected'; Run = $with; Marker = 'codex-stderr-runtime-policy-rejected' }, + @{ Name = 'stderrPolicyRejectedBaseline'; Run = $without; Marker = 'codex-stderr-runtime-policy-rejected' }, + @{ Name = 'stderrIsolationDenial'; Run = $with; Marker = 'codex-stderr-isolation-denial' }, + @{ Name = 'stderrBarePolicy'; Run = $with; Marker = 'codex-stderr-bare-blocked-by-policy' }, + @{ Name = 'threadReadUnavailable'; Run = $with; Marker = 'codex-thread-read-unavailable' }, + @{ Name = 'reroute'; Run = $with; Marker = 'codex-reroute' }, + @{ Name = 'ambientInstruction'; Run = $with; Marker = 'codex-ambient-instruction' } + ) + $candidateAbsentResult = $codexScenarios.Results['candidateAbsent'] Assert-Equal 'completed' $candidateAbsentResult.status 'Codex proceeds when skills/list has zero candidate matches' Assert-Equal 'absent' $candidateAbsentResult.evidence.native_skill_isolation.candidate_state 'Codex records explicit candidate_absent state' Assert-Equal 0 $candidateAbsentResult.evidence.native_skill_isolation.candidate_matches_count 'Codex records zero candidate matches distinctly' Assert-Equal 'supported' $candidateAbsentResult.isolation.capabilities.ambient_candidate_skill_exclusion 'Codex supports ambient exclusion when absent state and runtime observation are verified' - Remove-Item -LiteralPath $candidateAbsentMarker -Force - $candidateEnabledMarker = Join-Path $without.Root 'home\codex-native-skill-candidate-enabled-execute-only' - [System.IO.File]::WriteAllText($candidateEnabledMarker, 'fixture', [System.Text.UTF8Encoding]::new($false)) - $candidateEnabledResult = Invoke-AdapterJson -RunnerPath (Join-Path $runnerRoot 'codex\runner.ps1') -Command execute -RunPath $without.Path -ProfilePath $recordedProfiles['codex'] + $candidateEnabledResult = $codexScenarios.Results['candidateEnabled'] Assert-Equal 'incompatible' $candidateEnabledResult.status 'Codex fails closed when skills/list leaves the native candidate enabled' Assert-Equal 'native_candidate_skill_still_enabled' $candidateEnabledResult.exit.failure.code 'Codex reports the stable candidate-enabled failure code' Assert-Equal 'unsupported' $candidateEnabledResult.isolation.capabilities.ambient_candidate_skill_exclusion 'Codex does not claim ambient exclusion when the candidate remains enabled' Assert-Equal 'enabled' $candidateEnabledResult.evidence.native_skill_isolation.candidate_state 'Codex records the enabled candidate state' Assert-Equal 0 @($candidateEnabledResult.evidence.app_server.turn_starts).Count 'Codex does not start a model turn after native-skill verification fails' - $candidateEnabledLog = Get-Content -LiteralPath (Join-Path $without.Root 'repo\codex-fake-cli-log.jsonl') | ForEach-Object { $_ | ConvertFrom-Json } | Where-Object { $_.PSObject.Properties.Name -contains 'rpc_methods' } | Select-Object -Last 1 + $candidateEnabledLog = Get-Content -LiteralPath (Join-Path $codexScenarios.Roots['candidateEnabled'] 'repo\codex-fake-cli-log.jsonl') | ForEach-Object { $_ | ConvertFrom-Json } | Where-Object { $_.PSObject.Properties.Name -contains 'rpc_methods' } | Select-Object -Last 1 Assert-Equal 'initialize,initialized,skills/list' ([string]::Join(',', @($candidateEnabledLog.rpc_methods))) 'Codex app-server verification failure closes before thread/start or turn/start' - Remove-Item -LiteralPath $candidateEnabledMarker -Force - $newAmbientMarker = Join-Path $without.Root 'home\codex-new-ambient-enabled' - [System.IO.File]::WriteAllText($newAmbientMarker, 'fixture', [System.Text.UTF8Encoding]::new($false)) - $newAmbientResult = Invoke-AdapterJson -RunnerPath (Join-Path $runnerRoot 'codex\runner.ps1') -Command execute -RunPath $without.Path -ProfilePath $recordedProfiles['codex'] + $newAmbientResult = $codexScenarios.Results['newAmbient'] Assert-Equal 'incompatible' $newAmbientResult.status 'Codex fails closed when behavioral skills/list exposes a newly enabled ambient skill' Assert-Equal 'new_enabled_ambient_native_skill' $newAmbientResult.exit.failure.code 'Codex reports the stable newly enabled ambient skill failure code' Assert-Equal 1 @($newAmbientResult.evidence.native_skill_isolation.newly_enabled_ambient_skills | Where-Object { [string]$_.name -eq 'c' }).Count 'Codex records the newly enabled ambient skill' Assert-Equal 0 @($newAmbientResult.evidence.app_server.turn_starts).Count 'Codex does not start a model turn after a newly enabled ambient skill appears' - Remove-Item -LiteralPath $newAmbientMarker -Force - $ambientAccessMarker = Join-Path $without.Root 'home\codex-ambient-skill-access' - [System.IO.File]::WriteAllText($ambientAccessMarker, 'fixture', [System.Text.UTF8Encoding]::new($false)) - $ambientAccessResult = Invoke-AdapterJson -RunnerPath (Join-Path $runnerRoot 'codex\runner.ps1') -Command execute -RunPath $without.Path -ProfilePath $recordedProfiles['codex'] + $ambientAccessResult = $codexScenarios.Results['ambientAccess'] Assert-Equal 'incompatible' $ambientAccessResult.status 'Codex rejects iteration-17-style ambient skill file access' Assert-Equal 'ambient_skill_access_detected' $ambientAccessResult.exit.failure.code 'Codex reports the stable ambient skill access failure code' Assert-Equal 'unsupported' $ambientAccessResult.isolation.capabilities.ambient_candidate_skill_exclusion 'Codex does not report ambient exclusion as supported after ambient skill access' @@ -1654,7 +1845,6 @@ if ($harness -eq 'codex') { $expectedAmbientPath = Join-Path $fakeBin '.fake-user/.agents/skills/candidate/SKILL.md' Assert-True (@($ambientAccessResult.evidence.native_skill_isolation.ambient_skill_paths_observed) -contains $expectedAmbientPath) 'Codex discovery records the exact platform-native ambient candidate path' Assert-True (@($ambientAccessResult.evidence.native_skill_isolation.ambient_skill_accesses_detected | Where-Object { $_.command.Contains($expectedAmbientPath) }).Count -ge 1) 'Codex runtime access uses the exact discovered native path' - Remove-Item -LiteralPath $ambientAccessMarker -Force # The override eval supplies one identical relative destination. Resolve it # against actual independently allocated Codex projections from recorded arms. @@ -1671,41 +1861,27 @@ if ($harness -eq 'codex') { } Assert-True ($projectedOutputs[0] -ne $projectedOutputs[1]) 'paired Codex projections resolve the same strong-name override to distinct physical outputs' - $runtimeUnavailableMarker = Join-Path $with.Root 'home\codex-runtime-evidence-unavailable' - [System.IO.File]::WriteAllText($runtimeUnavailableMarker, 'fixture', [System.Text.UTF8Encoding]::new($false)) - $runtimeUnavailableResult = Invoke-AdapterJson -RunnerPath (Join-Path $runnerRoot 'codex\runner.ps1') -Command execute -RunPath $with.Path -ProfilePath $recordedProfiles['codex'] + $runtimeUnavailableResult = $codexScenarios.Results['runtimeUnavailable'] Assert-Equal 'incompatible' $runtimeUnavailableResult.status 'Codex fails closed when runtime path-bearing command evidence is unavailable' Assert-Equal 'runtime_ambient_skill_access_observation_unavailable' $runtimeUnavailableResult.exit.failure.code 'Codex reports unavailable runtime observation with a stable code' Assert-Equal 'unavailable' $runtimeUnavailableResult.evidence.native_skill_isolation.runtime_access_observation 'Codex records unavailable runtime access observation' Assert-Equal 'unsupported' $runtimeUnavailableResult.isolation.capabilities.ambient_candidate_skill_exclusion 'Codex does not claim ambient exclusion without runtime access observation' - Remove-Item -LiteralPath $runtimeUnavailableMarker -Force - $stagedAccessMarker = Join-Path $with.Root 'home\codex-staged-skill-access' - [System.IO.File]::WriteAllText($stagedAccessMarker, 'fixture', [System.Text.UTF8Encoding]::new($false)) - $stagedAccessResult = Invoke-AdapterJson -RunnerPath (Join-Path $runnerRoot 'codex\runner.ps1') -Command execute -RunPath $with.Path -ProfilePath $recordedProfiles['codex'] + $stagedAccessResult = $codexScenarios.Results['stagedAccess'] Assert-Equal 'completed' $stagedAccessResult.status 'Codex allows structured access to the staged with_skill candidate copy' Assert-Equal 0 @($stagedAccessResult.evidence.native_skill_isolation.ambient_skill_accesses_detected).Count 'Codex does not classify the staged candidate path as ambient' - Remove-Item -LiteralPath $stagedAccessMarker -Force - $ambientProseMarker = Join-Path $with.Root 'home\codex-ambient-skill-prose' - [System.IO.File]::WriteAllText($ambientProseMarker, 'fixture', [System.Text.UTF8Encoding]::new($false)) - $ambientProseResult = Invoke-AdapterJson -RunnerPath (Join-Path $runnerRoot 'codex\runner.ps1') -Command execute -RunPath $with.Path -ProfilePath $recordedProfiles['codex'] + $ambientProseResult = $codexScenarios.Results['ambientProse'] Assert-Equal 'completed' $ambientProseResult.status 'Codex ignores prose-only mentions of .agents, skill, and the candidate name' Assert-Equal 0 @($ambientProseResult.evidence.native_skill_isolation.ambient_skill_accesses_detected).Count 'Codex ambient detector requires structured path-bearing tool evidence' - Remove-Item -LiteralPath $ambientProseMarker -Force - $prosePolicyMarker = Join-Path $with.Root 'home\codex-prose-blocked-by-policy' - [System.IO.File]::WriteAllText($prosePolicyMarker, 'fixture', [System.Text.UTF8Encoding]::new($false)) - $prosePolicyResult = Invoke-AdapterJson -RunnerPath (Join-Path $runnerRoot 'codex\runner.ps1') -Command execute -RunPath $with.Path -ProfilePath $recordedProfiles['codex'] + $prosePolicyResult = $codexScenarios.Results['prosePolicy'] Assert-Equal 'completed' $prosePolicyResult.status 'Codex does not treat ordinary assistant prose as a policy-blocked tool result' Assert-True ([string]$prosePolicyResult.final_response.text -match 'blocked by policy') 'Codex false-positive fixture includes the policy wording in model prose' Assert-Equal 'no_structured_policy_rejection_observed' $prosePolicyResult.evidence.behavioral_capability.status 'Codex behavior classifier ignores prose-only policy wording' Assert-Equal 0 @($prosePolicyResult.evidence.behavioral_capability.failures).Count 'Codex prose-only fixture records no structured behavior failures' - Remove-Item -LiteralPath $prosePolicyMarker -Force - $policyBlockedMarker = Join-Path $with.Root 'home\codex-policy-blocked' - [System.IO.File]::WriteAllText($policyBlockedMarker, 'fixture', [System.Text.UTF8Encoding]::new($false)) - $policyBlockedResult = Invoke-AdapterJson -RunnerPath (Join-Path $runnerRoot 'codex\runner.ps1') -Command execute -RunPath $with.Path -ProfilePath $recordedProfiles['codex'] + $policyBlockedResult = $codexScenarios.Results['policyBlocked'] Assert-Equal 'incompatible' $policyBlockedResult.status 'Codex structured policy-blocked tool results fail closed' Assert-Equal 'harness_operational_permission_incompatible' $policyBlockedResult.exit.failure.code 'Codex policy-blocked execution uses an operational permission failure code' Assert-Equal 'rejected_by_effective_runtime_policy' $policyBlockedResult.evidence.behavioral_capability.status 'Codex records effective runtime policy rejection separately from app-server startup' @@ -1718,22 +1894,16 @@ if ($harness -eq 'codex') { Assert-Equal 0 @($policyBlockedResult.evidence.native_worker_evidence_failures | Where-Object { $_ -eq 'ambient_candidate_skill_exclusion_unverified' }).Count 'Codex policy-blocked execution does not manufacture ambient skill exclusion failure evidence' Assert-Equal 'unsupported' $policyBlockedResult.isolation.level 'Codex policy-blocked execution cannot report verified isolation' Assert-Equal 'unsupported' $policyBlockedResult.isolation.capabilities.delegated_worker_full_capability 'Codex policy-blocked execution cannot claim full delegated-worker capability' - Remove-Item -LiteralPath $policyBlockedMarker -Force - $baselinePolicyBlockedMarker = Join-Path $without.Root 'home\codex-policy-blocked' - [System.IO.File]::WriteAllText($baselinePolicyBlockedMarker, 'fixture', [System.Text.UTF8Encoding]::new($false)) - $baselinePolicyBlockedResult = Invoke-AdapterJson -RunnerPath (Join-Path $runnerRoot 'codex\runner.ps1') -Command execute -RunPath $without.Path -ProfilePath $recordedProfiles['codex'] + $baselinePolicyBlockedResult = $codexScenarios.Results['baselinePolicyBlocked'] Assert-Equal 'incompatible' $baselinePolicyBlockedResult.status 'Codex baseline policy-blocked execution fails closed' Assert-Equal 0 @($baselinePolicyBlockedResult.evidence.native_worker_evidence_failures | Where-Object { $_ -eq 'ambient_candidate_skill_exclusion_unverified' }).Count 'Codex baseline policy-blocked execution does not treat operational failure as ambient skill exclusion evidence' Assert-Equal 'supported' $baselinePolicyBlockedResult.isolation.capabilities.ambient_candidate_skill_exclusion 'Codex baseline keeps ambient candidate-skill exclusion evidence independent from operational policy failure' Assert-Equal 'rejected_by_effective_runtime_policy' $baselinePolicyBlockedResult.evidence.behavioral_capability.status 'Codex baseline records the effective policy rejection' - Remove-Item -LiteralPath $baselinePolicyBlockedMarker -Force # Fixture A: iteration-12 STDERR-only runtime rejection — app-server turn completes but no # structured tool items; Codex runtime STDERR carries the tool-router rejection family. - $stderrPolicyRejectedMarker = Join-Path $with.Root 'home\codex-stderr-runtime-policy-rejected' - [System.IO.File]::WriteAllText($stderrPolicyRejectedMarker, 'fixture', [System.Text.UTF8Encoding]::new($false)) - $stderrPolicyRejectedResult = Invoke-AdapterJson -RunnerPath (Join-Path $runnerRoot 'codex\runner.ps1') -Command execute -RunPath $with.Path -ProfilePath $recordedProfiles['codex'] + $stderrPolicyRejectedResult = $codexScenarios.Results['stderrPolicyRejected'] Assert-Equal 'incompatible' $stderrPolicyRejectedResult.status 'Codex STDERR-only runtime rejection fails closed' Assert-Equal 'harness_operational_permission_incompatible' $stderrPolicyRejectedResult.exit.failure.code 'Codex STDERR runtime rejection uses harness_operational_permission_incompatible failure code' Assert-Equal 'rejected_by_effective_runtime_policy' $stderrPolicyRejectedResult.evidence.behavioral_capability.status 'Codex STDERR runtime rejection records effective runtime policy rejection' @@ -1742,59 +1912,40 @@ if ($harness -eq 'codex') { Assert-Equal 0 @($stderrPolicyRejectedResult.evidence.behavioral_capability.failures | Where-Object { $_.signal -eq 'structured_tool_result' }).Count 'Iteration-12 shape produces no structured tool-result failures' Assert-True (@($stderrPolicyRejectedResult.evidence.native_worker_evidence_failures | Where-Object { $_ -eq 'workspace_operation_blocked_by_policy' }).Count -eq 1) 'Codex STDERR runtime rejection surfaces workspace_operation_blocked_by_policy evidence' Assert-True (([string]$stderrPolicyRejectedResult.exit.failure.message) -notmatch 'Get-Location|Get-ChildItem|git rev-parse') 'Codex STDERR failure message does not expose rejected command names from raw STDERR' - Remove-Item -LiteralPath $stderrPolicyRejectedMarker -Force # Fixture A baseline: globally broken execution must not claim candidate-skill exclusion. - $stderrPolicyRejectedBaselineMarker = Join-Path $without.Root 'home\codex-stderr-runtime-policy-rejected' - [System.IO.File]::WriteAllText($stderrPolicyRejectedBaselineMarker, 'fixture', [System.Text.UTF8Encoding]::new($false)) - $stderrPolicyRejectedBaselineResult = Invoke-AdapterJson -RunnerPath (Join-Path $runnerRoot 'codex\runner.ps1') -Command execute -RunPath $without.Path -ProfilePath $recordedProfiles['codex'] + $stderrPolicyRejectedBaselineResult = $codexScenarios.Results['stderrPolicyRejectedBaseline'] Assert-Equal 'incompatible' $stderrPolicyRejectedBaselineResult.status 'Codex baseline STDERR runtime rejection fails closed' Assert-Equal 0 @($stderrPolicyRejectedBaselineResult.evidence.native_worker_evidence_failures | Where-Object { $_ -eq 'ambient_candidate_skill_exclusion_unverified' }).Count 'Codex baseline STDERR rejection does not attach ambient skill exclusion to operational failure' Assert-Equal 'supported' $stderrPolicyRejectedBaselineResult.isolation.capabilities.ambient_candidate_skill_exclusion 'Codex baseline STDERR rejection keeps ambient exclusion evidence independent' - Remove-Item -LiteralPath $stderrPolicyRejectedBaselineMarker -Force # Fixture B: legitimate outside-workspace isolation denial with a usable workspace. - $stderrIsolationDenialMarker = Join-Path $with.Root 'home\codex-stderr-isolation-denial' - [System.IO.File]::WriteAllText($stderrIsolationDenialMarker, 'fixture', [System.Text.UTF8Encoding]::new($false)) - $stderrIsolationDenialResult = Invoke-AdapterJson -RunnerPath (Join-Path $runnerRoot 'codex\runner.ps1') -Command execute -RunPath $with.Path -ProfilePath $recordedProfiles['codex'] + $stderrIsolationDenialResult = $codexScenarios.Results['stderrIsolationDenial'] Assert-Equal 'completed' $stderrIsolationDenialResult.status 'Outside-workspace isolation denial alone does not make the workspace globally incompatible' Assert-Equal 'no_structured_policy_rejection_observed' $stderrIsolationDenialResult.evidence.behavioral_capability.status 'Isolation denial in STDERR does not set rejected_by_effective_runtime_policy when workspace execution succeeds' Assert-True (@($stderrIsolationDenialResult.evidence.commands | Where-Object { [string](Get-JsonProperty -Object $_ -Name 'status' -Default '') -eq 'completed' }).Count -ge 1) 'Fixture B has at least one successful workspace command confirming usable substrate' - Remove-Item -LiteralPath $stderrIsolationDenialMarker -Force # False-positive protection: bare 'blocked by policy' in STDERR without codex_core provenance. - $stderrBarePolicyMarker = Join-Path $with.Root 'home\codex-stderr-bare-blocked-by-policy' - [System.IO.File]::WriteAllText($stderrBarePolicyMarker, 'fixture', [System.Text.UTF8Encoding]::new($false)) - $stderrBarePolicyResult = Invoke-AdapterJson -RunnerPath (Join-Path $runnerRoot 'codex\runner.ps1') -Command execute -RunPath $with.Path -ProfilePath $recordedProfiles['codex'] + $stderrBarePolicyResult = $codexScenarios.Results['stderrBarePolicy'] Assert-Equal 'completed' $stderrBarePolicyResult.status 'Bare STDERR blocked-by-policy text without codex_core provenance does not trigger the runtime classifier' Assert-Equal 'no_structured_policy_rejection_observed' $stderrBarePolicyResult.evidence.behavioral_capability.status 'Bare STDERR policy text leaves behavioral capability status as no_structured_policy_rejection_observed' - Remove-Item -LiteralPath $stderrBarePolicyMarker -Force - $threadReadUnavailableMarker = Join-Path $with.Root 'home\codex-thread-read-unavailable' - [System.IO.File]::WriteAllText($threadReadUnavailableMarker, 'fixture', [System.Text.UTF8Encoding]::new($false)) - $threadReadUnavailableResult = Invoke-AdapterJson -RunnerPath (Join-Path $runnerRoot 'codex\runner.ps1') -Command execute -RunPath $with.Path -ProfilePath $recordedProfiles['codex'] + $threadReadUnavailableResult = $codexScenarios.Results['threadReadUnavailable'] Assert-Equal 'completed' $threadReadUnavailableResult.status 'Optional thread/read absence does not invalidate a proven terminal turn' Assert-Equal 'unavailable_optional' $threadReadUnavailableResult.evidence.app_server.thread_read.observation 'Codex records missing thread/read as unavailable supplemental evidence' Assert-True (@($threadReadUnavailableResult.evidence.native_worker_evidence_failures | Where-Object { $_ -eq 'thread_read_metadata' }).Count -eq 0) 'Optional thread/read absence does not add a false incompatibility' - Remove-Item -LiteralPath $threadReadUnavailableMarker -Force - $rerouteMarker = Join-Path $with.Root 'home\codex-reroute' - [System.IO.File]::WriteAllText($rerouteMarker, 'fixture', [System.Text.UTF8Encoding]::new($false)) - $reroutedResult = Invoke-AdapterJson -RunnerPath (Join-Path $runnerRoot 'codex\runner.ps1') -Command execute -RunPath $with.Path -ProfilePath $recordedProfiles['codex'] + $reroutedResult = $codexScenarios.Results['reroute'] Assert-Equal 'incompatible' $reroutedResult.status 'Codex model/rerouted notification fails closed' Assert-True (@($reroutedResult.evidence.native_worker_evidence_failures | Where-Object { $_ -eq 'model_rerouted' }).Count -eq 1) 'Codex reroute incompatibility is recorded as transport evidence' Assert-True ([string]$reroutedResult.exit.failure.message -match 'model_rerouted') 'Codex reroute reason survives in normalized exit failure' - Remove-Item -LiteralPath $rerouteMarker -Force - $ambientInstructionMarker = Join-Path $with.Root 'home\codex-ambient-instruction' - [System.IO.File]::WriteAllText($ambientInstructionMarker, 'fixture', [System.Text.UTF8Encoding]::new($false)) - $ambientInstructionResult = Invoke-AdapterJson -RunnerPath (Join-Path $runnerRoot 'codex\runner.ps1') -Command execute -RunPath $with.Path -ProfilePath $recordedProfiles['codex'] + $ambientInstructionResult = $codexScenarios.Results['ambientInstruction'] Assert-Equal 'incompatible' $ambientInstructionResult.status 'Codex unexpected instruction source fails closed' Assert-True (@($ambientInstructionResult.evidence.native_worker_evidence_failures | Where-Object { $_ -eq 'unexpected_instruction_sources' }).Count -eq 1) 'Codex ambient instruction rejection is recorded as transport evidence' Assert-True (@($ambientInstructionResult.evidence.native_worker_evidence_failures | Where-Object { $_ -eq 'ambient_candidate_skill_exclusion_unverified' }).Count -eq 1) 'Codex marks ambient candidate-skill exclusion unverified when instruction-source evidence contradicts the isolation boundary' Assert-Equal 'unsupported' $ambientInstructionResult.isolation.capabilities.ambient_candidate_skill_exclusion 'Codex downgrades ambient candidate-skill exclusion only for relevant instruction/configuration evidence' Assert-True ([string]$ambientInstructionResult.exit.failure.message -match 'unexpected_instruction_sources') 'Codex instruction-source reason survives in normalized exit failure' - Remove-Item -LiteralPath $ambientInstructionMarker -Force Assert-Equal 'initialize,initialized,skills/list,thread/start,turn/start,thread/read' ([string]::Join(',', @($subscriptionRecord.rpc_methods))) 'Codex app-server verifies native skills before the first model turn and then follows the required post-completion read order' Assert-True (@($subscriptionRecord.native_skill_config_args | Where-Object { $_ -eq 'skills.include_instructions=false' }).Count -eq 1) 'Codex app-server process receives session native-catalog suppression' Assert-True (@($subscriptionRecord.native_skill_config_args | Where-Object { $_ -eq 'skills.bundled.enabled=false' }).Count -eq 1) 'Codex app-server process receives bundled native-skill suppression' @@ -1831,6 +1982,29 @@ if ($harness -eq 'codex') { $env:CODEX_HOME = $recordedOldCodexHome } + if ($Suite -in @('All', 'OpenCode', 'CodexAppServer', 'CodexCli')) { + Add-ReadinessFixtureExecutables -Bin $fakeBin + $readinessRunners = @(if ($Suite -in @('All', 'OpenCode')) { 'opencode' }; if ($Suite -in @('All', 'CodexAppServer', 'CodexCli')) { 'codex' }) + foreach ($runnerName in $readinessRunners) { + $useAppServer = $runnerName -eq 'codex' -and $Suite -ne 'CodexCli' + if ($useAppServer) { + $env:OPENAI_API_KEY = $null + $env:CODEX_HOME = $fileAuthHome + } + $arms = @(foreach ($mode in 'with_skill', 'without_skill') { + $case = New-TestRun -IterationDirectory (Join-Path $recordedRoot "ready-$runnerName") -Configuration $mode + [IO.File]::WriteAllText((Join-Path $case.Root 'home/readiness-fixture'), 'redirect fixture logs') + New-ReadinessFixtureRun -TestRun $case -EvalId 139 + }) + $readinessRunnerPath = Join-Path $runnerRoot "$runnerName/runner.ps1" + # Both arms preflight concurrently; the assertions below still check each arm in order. + $readinessResults = Invoke-AdapterJsonBatch -RunnerPath $readinessRunnerPath -Command preflight -ProfilePath $recordedProfiles[$runnerName] -Label "$runnerName readiness preflights" -Items @( + foreach ($arm in $arms) { [pscustomobject]@{ Name = [string]$arm.Run.Path; Path = [string]$arm.Run.Path } }) + $probe = { param($path) $readinessResults[[string]$path] } + $transport = if ($useAppServer) { 'codex-command-exec' } else { 'runner-process' } + Assert-ReadinessFixturePreflights -Arms $arms -Preflight $probe -Transport $transport + } + } Write-Output "Real runner deterministic adapter conformance ($Suite): PASS" } finally { $env:PATH = $recordedOldPath diff --git a/scripts/eval-runners/tests/test-runner-observability.ps1 b/scripts/eval-runners/tests/test-runner-observability.ps1 index 00a4cbba..ce89b18d 100644 --- a/scripts/eval-runners/tests/test-runner-observability.ps1 +++ b/scripts/eval-runners/tests/test-runner-observability.ps1 @@ -543,7 +543,9 @@ if ($arguments -contains 'app-server' -and $arguments -contains '--stdio') { }) $threadStart = Read-AppServerMessage -AllowEndOfStream if ($null -eq $threadStart) { exit 0 } - Start-Sleep -Milliseconds (Get-DelayMilliseconds 2.8) + # Success mode: wide enough for several heartbeats even when timer ticks slip on a loaded machine. + # Timeout mode keeps the original window so its 2 second turn budget is unchanged. + Start-Sleep -Milliseconds (Get-DelayMilliseconds $(if ($mode -eq 'timeout') { 2.8 } else { 6 })) Write-AppServerMessage ([ordered]@{ jsonrpc = '2.0' id = $threadStart.id @@ -1125,12 +1127,17 @@ foreach ($ev in $events) { $firstActivityBytes = [int64](Get-Field $firstActivityEvent 'stdoutBytes' 0) Assert-True ($firstActivityCount -gt 0 -and $firstActivityBytes -gt 0) 'codex app-server: the first observed protocol heartbeat carries non-zero event and byte counters' Assert-True ($null -ne $firstActivityEvent.PSObject.Properties['lastActivitySeconds']) 'codex app-server: lastActivity appears after the first real protocol message' - $sameCounterQuietEvents = @($codexAppEvents | Where-Object { - [int64](Get-Field $_ 'stdoutEvents' 0) -eq $firstActivityCount -and - [int64](Get-Field $_ 'stdoutBytes' 0) -eq $firstActivityBytes -and + # Any quiet stretch after the first protocol message qualifies. Pinning the check to the first observed + # counters raced: that heartbeat can land between two back-to-back protocol responses, and timer ticks + # slip under load, so the window it selects may hold a single heartbeat. + $quietCounterGroup = @($codexAppEvents[$firstProtocolIndex..($codexAppEvents.Count - 1)] | Where-Object { + [int64](Get-Field $_ 'stdoutEvents' 0) -gt 0 -and $null -ne $_.PSObject.Properties['lastActivitySeconds'] - }) - Assert-True ($sameCounterQuietEvents.Count -ge 2) 'codex app-server: quiet heartbeats preserve counters after the first protocol message' + } | Group-Object { '{0}/{1}' -f [int64](Get-Field $_ 'stdoutEvents' 0), [int64](Get-Field $_ 'stdoutBytes' 0) } | Where-Object { $_.Count -ge 2 } | Select-Object -First 1) + Assert-True ($quietCounterGroup.Count -eq 1) 'codex app-server: quiet heartbeats preserve counters after the first protocol message' + $sameCounterQuietEvents = @($quietCounterGroup[0].Group) + $firstActivityCount = [int64](Get-Field $sameCounterQuietEvents[0] 'stdoutEvents' 0) + $firstActivityBytes = [int64](Get-Field $sameCounterQuietEvents[0] 'stdoutBytes' 0) $sameCounterAges = @($sameCounterQuietEvents | ForEach-Object { [double]$_.lastActivitySeconds }) $sameCounterMinAge = ($sameCounterAges | Measure-Object -Minimum).Minimum $sameCounterMaxAge = ($sameCounterAges | Measure-Object -Maximum).Maximum diff --git a/scripts/eval-runners/windows-owned-process.cs b/scripts/eval-runners/windows-owned-process.cs index c303ff3a..0837e04b 100644 --- a/scripts/eval-runners/windows-owned-process.cs +++ b/scripts/eval-runners/windows-owned-process.cs @@ -1,3 +1,4 @@ +#nullable disable using System; using System.ComponentModel; using System.Diagnostics; @@ -52,6 +53,8 @@ private struct JobLimits [DllImport("kernel32.dll", SetLastError = true)] private static extern bool QueryInformationJobObject(SafeFileHandle job, int kind, byte[] value, int size, IntPtr returned); [DllImport("kernel32.dll", SetLastError = true)] + private static extern bool QueryInformationJobObject(SafeFileHandle job, int kind, out JobLimits value, int size, IntPtr returned); + [DllImport("kernel32.dll", SetLastError = true)] private static extern bool TerminateJobObject(SafeFileHandle job, uint exitCode); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool AssignProcessToJobObject(SafeFileHandle job, SafeFileHandle process); @@ -80,6 +83,7 @@ private static extern bool CreateProcessW(string application, StringBuilder comm public bool HasExited => process.HasExited; public int ExitCode => process.ExitCode; public bool WaitForExit(int milliseconds) => process.WaitForExit(milliseconds); + public System.Threading.Tasks.Task WaitForExitAsync(CancellationToken cancellationToken) => process.WaitForExitAsync(cancellationToken); private static void Check(bool success, string operation) { @@ -193,6 +197,20 @@ public void StopOwnedProcesses(int milliseconds) throw new TimeoutException("Windows job termination grace expired before all owned processes exited."); } + // Read-only accounting for the whole owned tree, used by measurement tooling. PeakJobMemory is the + // peak committed (private) memory of all live job processes combined, not a working-set figure. + public JobAccounting QueryAccounting() + { + var accounting = new byte[48]; + Check(QueryInformationJobObject(job, 1, accounting, accounting.Length, IntPtr.Zero), "QueryInformationJobObject"); + Check(QueryInformationJobObject(job, 9, out JobLimits limits, Marshal.SizeOf(), IntPtr.Zero), "QueryInformationJobObject"); + return new JobAccounting( + (ulong)limits.PeakJobMemory, + BitConverter.ToUInt32(accounting, 36), + BitConverter.ToUInt32(accounting, 40), + TimeSpan.FromTicks(BitConverter.ToInt64(accounting, 0) + BitConverter.ToInt64(accounting, 8))); + } + public void Dispose() { job?.Dispose(); @@ -202,4 +220,20 @@ public void Dispose() process?.Dispose(); } } + + public readonly struct JobAccounting + { + public JobAccounting(ulong peakJobCommitBytes, uint totalProcesses, uint activeProcesses, TimeSpan totalCpuTime) + { + PeakJobCommitBytes = peakJobCommitBytes; + TotalProcesses = totalProcesses; + ActiveProcesses = activeProcesses; + TotalCpuTime = totalCpuTime; + } + + public ulong PeakJobCommitBytes { get; } + public uint TotalProcesses { get; } + public uint ActiveProcesses { get; } + public TimeSpan TotalCpuTime { get; } + } } diff --git a/scripts/prepare-eval-prerequisites.ps1 b/scripts/prepare-eval-prerequisites.ps1 index 75da7562..f8de18c9 100644 --- a/scripts/prepare-eval-prerequisites.ps1 +++ b/scripts/prepare-eval-prerequisites.ps1 @@ -4,11 +4,11 @@ function Invoke-EvalPreparationCommand { $command = Resolve-ExternalCommand -Name $Executable if ($null -eq $command) { throw "Infrastructure blocked: install '$Executable' or make it discoverable before preparing this evaluation." } $process = Invoke-RunnerProcess -FileName $command.FileName -ArgumentList (@($command.Prefix) + $Arguments) ` - -WorkingDirectory $Run.WorkingDirectoryPath -Environment (New-RunnerShellEnvironment -Run $Run) -TimeoutSeconds $TimeoutSeconds + -WorkingDirectory $Run.WorkingDirectoryPath -Environment (New-RunnerShellEnvironment -Run $Run) -TimeoutSeconds $TimeoutSeconds -OwnWindowsProcessTree if ($process.ExitCode -ne 0) { $detail = ([string]$process.Stderr).Trim() $exit = if ($null -eq $process.ExitCode) { 'timeout or launch failure' } else { $process.ExitCode } - throw "Infrastructure blocked: $Executable $($Arguments -join ' ') (exit $exit). $detail" + throw "Infrastructure blocked: $Executable $($Arguments -join ' ') (exit $exit). $detail Verify the tool and any declared public source on the preparation host." } return ([string]$process.Stdout).Trim() } @@ -26,6 +26,7 @@ function Initialize-EvalPrerequisites { param([object]$Requirements, [string]$RunRoot, [string]$CandidateName) if ($null -eq $Requirements) { return } + Assert-EvalReadinessDeclarations -Requirements $Requirements $run = [pscustomobject]@{ RunRoot = $RunRoot WorkingDirectoryPath = Join-Path $RunRoot 'repo' @@ -39,6 +40,7 @@ function Initialize-EvalPrerequisites { skills = @() downloads = @() dotnetTools = @() + stagedHome = @() repository = $null } foreach ($name in @(Get-JsonProperty -Object $Requirements -Name 'skills' -Default @())) { @@ -70,7 +72,7 @@ function Initialize-EvalPrerequisites { $installed = Get-Command $tool.executable -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1 $supported = $false if ($null -ne $installed) { - $versionCheck = Invoke-RunnerProcess -FileName $installed.Source -ArgumentList @('--version') -WorkingDirectory $run.WorkingDirectoryPath -Environment (New-RunnerShellEnvironment -Run $run) -TimeoutSeconds 15 + $versionCheck = Invoke-RunnerProcess -FileName $installed.Source -ArgumentList @('--version') -WorkingDirectory $run.WorkingDirectoryPath -Environment (New-RunnerShellEnvironment -Run $run) -TimeoutSeconds 15 -OwnWindowsProcessTree $supported = $versionCheck.ExitCode -eq 0 -and $versionCheck.Stdout -match ('^' + [regex]::Escape($tool.version) + '(?:\+|\s|$)') } if ($supported) { @@ -90,7 +92,7 @@ function Initialize-EvalPrerequisites { if ($package.id -notmatch '^[A-Za-z0-9][A-Za-z0-9._-]*$' -or $package.version -notmatch '^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$') { throw 'Restore prerequisite package IDs and versions must be exact.' } - "" + "" } $restoreRoot = Join-Path $run.HomeDirectoryPath 'restore-probe' New-Item -ItemType Directory -Path $restoreRoot -Force | Out-Null @@ -111,6 +113,7 @@ function Initialize-EvalPrerequisites { } $repository = Get-JsonProperty -Object $Requirements -Name 'repository' if ($null -ne $repository) { + if ('git' -notin $staged.executables) { throw 'A repository prerequisite requires the git executable.' } Assert-EvalPublicHttpsSource -Source $repository.url if ($repository.commit -notmatch '^[0-9a-f]{40}$' -or $repository.directory -notmatch '^[A-Za-z0-9][A-Za-z0-9_-]*$') { throw 'A repository prerequisite requires a full commit SHA and a directory name under repo/.' @@ -129,5 +132,13 @@ function Initialize-EvalPrerequisites { outputPattern = '^' + $actual + '\s*$' } } + foreach ($relative in @('home/tools', 'home/restore-probe')) { + $path = Join-Path $RunRoot $relative + if ($relative -eq 'home/tools' -and @($staged.dotnetTools | Where-Object source -eq 'run-local').Count -eq 0) { continue } + if (Test-Path -LiteralPath $path -PathType Container) { + $staged.stagedHome += [ordered]@{ path = $relative; sha256 = Get-EvalDependencyTreeHash -Root $path } + } + } + Assert-EvalReadinessDeclarations -Requirements $staged return $staged } diff --git a/scripts/prepare-skill-evals.ps1 b/scripts/prepare-skill-evals.ps1 index b16c647e..94db9f2d 100644 --- a/scripts/prepare-skill-evals.ps1 +++ b/scripts/prepare-skill-evals.ps1 @@ -433,9 +433,10 @@ function Confirm-HarnessModel { if (-not [string]::IsNullOrWhiteSpace($ModelCatalogPath)) { $arguments += @('-CatalogPath', $ModelCatalogPath) } - $discoveryOutput = & pwsh -NoProfile -NonInteractive -File $discoveryScript @arguments 2>&1 - if ($LASTEXITCODE -ne 0) { - throw "Runner '$RunnerName' model '$ModelName' could not be verified against current harness discovery. $($discoveryOutput -join [Environment]::NewLine)" + try { + [void](Invoke-RunnerPowerShellScript -ScriptPath $discoveryScript -Arguments $arguments -Description 'Model discovery') + } catch { + throw "Runner '$RunnerName' model '$ModelName' could not be verified against current harness discovery. $($_.Exception.Message)" } return $true @@ -1452,6 +1453,14 @@ function Invoke-PrepareMode { throw "No evals selected for '$Skill'." } + foreach ($evalEntry in $selectedEvals) { + $requirements = Get-JsonProperty -Object $evalEntry -Name 'prerequisites' + if ($null -ne $requirements) { + try { Assert-EvalReadinessDeclarations -Requirements $requirements } + catch { throw "Eval $($evalEntry.id) cannot be prepared. $($_.Exception.Message)" } + } + } + $executionSelection = Resolve-ExecutionSelection -RepoRoot $repoRoot $effectiveConcurrency = Resolve-EffectiveConcurrency -RunnerName ([string]$executionSelection.Runner) -RequestedConcurrency $Concurrency -ConcurrencyWasExplicit ($scriptBoundParameters.ContainsKey('Concurrency')) @@ -1692,6 +1701,7 @@ function Invoke-PrepareMode { skill_hash = $skillHash git_workspace = $workspaceOption.Git input_files = @($repoFiles) + has_prerequisites = $null -ne $stagedPrerequisites runs = [ordered]@{ with_skill = [ordered]@{ mode = 'with_skill' @@ -1700,7 +1710,7 @@ function Invoke-PrepareMode { prompt = "$evalName/with_skill/$($runDirectoryNames.Prompt)" working_directory = "$evalName/with_skill/$($runDirectoryNames.Working)" home_directory = "$evalName/with_skill/$($runDirectoryNames.Home)" - skill_directory = "$evalName/with_skill/$($runDirectoryNames.Skill)/$Skill" + skill_directory = "$evalName/with_skill/$candidateRoot" result = "$evalName/results/with-skill.result.json" execution_result = "$evalName/results/with-skill.execution-result.json" } @@ -1870,10 +1880,12 @@ function New-RunnerPrompt { $executionBatches = [Math]::Max(1, [int][Math]::Ceiling($armCount / [double]$effectiveConcurrency)) $preflightTimeoutSeconds = Get-RunnerPreflightTimeoutSeconds $serialPreflightAllowanceSeconds = $armCount * $preflightTimeoutSeconds - $startupAllowance = Get-RunnerExecutionOverheadAllowanceSeconds -Runner ([string]$ExecutionSelection.Runner) + $hasPrerequisites = @($ManifestEvals | Where-Object { Get-JsonProperty -Object $_ -Name 'has_prerequisites' -Default $false }).Count -gt 0 + $startupAllowance = Get-RunnerExecutionOverheadAllowanceSeconds -Runner ([string]$ExecutionSelection.Runner) -HasPrerequisites:$hasPrerequisites $startupDetail = switch ([string]$ExecutionSelection.Runner) { 'codex' { " + $startupAllowance seconds Codex preflight/discovery/startup" } 'claude' { " + $startupAllowance seconds Claude Code preflight/projection/session purge" } + 'opencode' { if ($startupAllowance -gt 0) { " + $startupAllowance seconds OpenCode preflight and projection readiness" } else { '' } } default { '' } } $longestChildAllowanceSeconds = ([Math]::Max(1, $maxScriptedUserTurns) * [Math]::Max(1, $PerArmTimeoutSeconds)) + $startupAllowance + [Math]::Max(0, $RunnerGraceSeconds) @@ -1888,6 +1900,7 @@ function New-RunnerPrompt { [void]$builder.AppendLine("Profile: $profilePath") [void]$builder.AppendLine("Selected runner: $($ExecutionSelection.Runner)") [void]$builder.AppendLine("Selected model: $($ExecutionSelection.Model)") + [void]$builder.AppendLine('Use PowerShell 7 for the commands below. If the current PowerShell 7 session cannot resolve `pwsh` on PATH, invoke its executable by using `& ([Environment]::ProcessPath)` in place of `pwsh`.') [void]$builder.AppendLine() [void]$builder.AppendLine('## Phase 1 — blind execution') [void]$builder.AppendLine() @@ -1945,7 +1958,8 @@ function New-PackageReadme { $runnerGraceSeconds = 30 $preflightTimeoutSeconds = Get-RunnerPreflightTimeoutSeconds $serialPreflightAllowanceSeconds = $armCount * $preflightTimeoutSeconds - $longestChildAllowanceSeconds = ([Math]::Max(1, $maxScriptedUserTurns) * [Math]::Max(1, $TimeoutSeconds)) + (Get-RunnerExecutionOverheadAllowanceSeconds -Runner ([string]$ExecutionSelection.Runner)) + $runnerGraceSeconds + $hasPrerequisites = @($ManifestEvals | Where-Object { Get-JsonProperty -Object $_ -Name 'has_prerequisites' -Default $false }).Count -gt 0 + $longestChildAllowanceSeconds = ([Math]::Max(1, $maxScriptedUserTurns) * [Math]::Max(1, $TimeoutSeconds)) + (Get-RunnerExecutionOverheadAllowanceSeconds -Runner ([string]$ExecutionSelection.Runner) -HasPrerequisites:$hasPrerequisites) + $runnerGraceSeconds $executionAllowanceSeconds = $executionBatches * $longestChildAllowanceSeconds $orchestrationGraceSeconds = $runnerGraceSeconds $phaseOneAllowanceSeconds = $serialPreflightAllowanceSeconds + $executionAllowanceSeconds + $orchestrationGraceSeconds @@ -2164,17 +2178,13 @@ function Invoke-CollectMode { $requireNativeDelegation = $false } } - $bridgeArguments = @('-NoProfile', '-NonInteractive', '-File', $packageBridgePath, '-IterationDirectory', $iterationDirectory) + $bridgeArguments = @('-IterationDirectory', $iterationDirectory) if ($requireNativeDelegation) { $bridgeArguments += '-RequireNativeDelegation' } - $bridgeOutput = & pwsh @bridgeArguments 2>&1 - if ($LASTEXITCODE -ne 0) { - $errors.Add("Manifest-driven execution-result bridge failed: $([string]::Join(' ', @($bridgeOutput)))") - } else { - foreach ($line in @($bridgeOutput)) { - if (-not [string]::IsNullOrWhiteSpace([string]$line)) { - Write-Host $line - } - } + try { + $bridgeResult = Invoke-RunnerPowerShellScript -ScriptPath $packageBridgePath -Arguments $bridgeArguments -Description 'Manifest-driven execution-result bridge' + if ($bridgeResult.Stdout.Trim()) { Write-Host $bridgeResult.Stdout.TrimEnd() } + } catch { + $errors.Add($_.Exception.Message) } } } @@ -2376,13 +2386,11 @@ function Invoke-CollectMode { if ($errors.Count -eq 0) { $reportScript = Join-Path (Join-Path (Get-RepoRoot) 'scripts') 'generate-eval-report.ps1' - $reportOutput = & pwsh -NoProfile -NonInteractive -File $reportScript -IterationDirectory $iterationDirectory 2>&1 - if ($LASTEXITCODE -ne 0) { - $errors.Add("Report generation failed: $($reportOutput -join [Environment]::NewLine)") - } else { - foreach ($line in @($reportOutput)) { - Write-Host $line - } + try { + $reportResult = Invoke-RunnerPowerShellScript -ScriptPath $reportScript -Arguments @('-IterationDirectory', $iterationDirectory) -Description 'Report generation' + if ($reportResult.Stdout.Trim()) { Write-Host $reportResult.Stdout.TrimEnd() } + } catch { + $errors.Add($_.Exception.Message) } } else { Write-Host 'Skipping report generation because the completion gate failed; comparison.md is diagnostic only.' diff --git a/scripts/test-validation-suites.ps1 b/scripts/test-validation-suites.ps1 index f1c0be1a..3e0dfca2 100644 --- a/scripts/test-validation-suites.ps1 +++ b/scripts/test-validation-suites.ps1 @@ -30,6 +30,11 @@ foreach ($script in @('scripts/validate-skill-templates.ps1', 'scripts/eval-runn if ($elements[$index] -is [Management.Automation.Language.CommandParameterAst] -and $elements[$index].ParameterName -eq 'Group') { $elements[$index + 1].SafeGetValue() } } }) + $batchAssignment = $ast.Find({ param($node) $node -is [Management.Automation.Language.AssignmentStatementAst] -and $node.Left.Extent.Text -eq '$parallelNestedScripts' }, $true) + $batch = @($batchAssignment.Right.FindAll({ param($node) $node -is [Management.Automation.Language.StringConstantExpressionAst] }, $true) | ForEach-Object Value) + $consumed = @([regex]::Matches($ast.Extent.Text, "(?:Get-ParallelNestedScriptResult -RelativePath|@\{ Path =) '(?scripts/[^']+\.ps1)'") | ForEach-Object { $_.Groups['path'].Value }) + $unbatched = @($consumed | Where-Object { $_ -notin $batch }) + if ($consumed.Count -eq 0 -or $unbatched.Count) { throw "Nested runner regressions must run in the parallel batch, not alone after it: $($unbatched -join ', ')" } foreach ($group in $groups) { if ($group -notin @($expected + 'Conformance' + 'Integrity')) { throw "Unscheduled validation group '$group'." } } diff --git a/scripts/tests/agent-smith-repair-tests.cs b/scripts/tests/agent-smith-repair-tests.cs new file mode 100644 index 00000000..9049a735 --- /dev/null +++ b/scripts/tests/agent-smith-repair-tests.cs @@ -0,0 +1,178 @@ +#!/usr/bin/env dotnet +#:property TargetFramework=net10.0 +#:property RollForward=Major +#:property Nullable=enable +#:property PublishAot=false +#:include ../../skills/git-worktree-merge/scripts/GitProcess.cs +#:include ../../tooling/src/Agentic.Tooling/Execution/ExecutableResolver.cs +#:include ../eval-runners/windows-owned-process.cs + +using System.Diagnostics; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using Agentic.Tooling.Execution; + +// Black-box tests for skills/agent-smith/scripts/repair-roslyn-multiproject-artifacts.cs. +if (args.Length < 1 || !File.Exists(args[0])) +{ + throw new ArgumentException("Pass the built repair-roslyn-multiproject-artifacts.dll."); +} + +var app = Path.GetFullPath(args[0]); +var dotnet = ExecutableResolver.Resolve(OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); +var tempRoot = Path.GetFullPath(Path.GetTempPath()).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) + Path.DirectorySeparatorChar; +var testRoot = Path.GetFullPath(Path.Combine(tempRoot, "agent-smith-roslyn-artifact-" + Guid.NewGuid().ToString("N"))); +if (!testRoot.StartsWith(tempRoot, StringComparison.OrdinalIgnoreCase)) +{ + throw new InvalidOperationException($"Test workspace escaped the temporary root: {testRoot}"); +} + +using var stop = new CancellationTokenSource(TimeSpan.FromMinutes(2)); + +static void WriteUtf8Fixture(string path, string text, bool bom = false) +{ + var content = new UTF8Encoding(false).GetBytes(text); + if (!bom) + { + File.WriteAllBytes(path, content); + return; + } + var bytes = new byte[content.Length + 3]; + bytes[0] = 0xEF; + bytes[1] = 0xBB; + bytes[2] = 0xBF; + Array.Copy(content, 0, bytes, 3, content.Length); + File.WriteAllBytes(path, bytes); +} + +async Task InvokeRepairAsync(params string[] toolArgs) +{ + var startInfo = Git.CreateStartInfo(dotnet, testRoot, [app, .. toolArgs]); + return await Git.RunProcessAsync(startInfo, stop.Token); +} + +static void AssertEqual(T expected, T actual, string message) +{ + if (!EqualityComparer.Default.Equals(expected, actual)) + { + throw new InvalidOperationException($"{message} Expected: [{expected}] Actual: [{actual}]"); + } +} + +try +{ + Directory.CreateDirectory(testRoot); + var recoverable = Path.Combine(testRoot, "Recoverable.cs"); + var blockedRecoverable = Path.Combine(testRoot, "BlockedRecoverable.cs"); + var unsafeFile = Path.Combine(testRoot, "Unsafe.cs"); + var unsupportedLocalized = Path.Combine(testRoot, "UnsupportedLocalized.cs"); + var clean = Path.Combine(testRoot, "Clean.cs"); + var progressPath = Path.Combine(testRoot, "repair-progress.json"); + const string crlf = "\r\n"; + const string lf = "\n"; + + var recoverableText = + "using System;" + crlf + + "<<<<<<< TODO: Unmerged change from project 'Example(net9.0)', Before:" + crlf + + "namespace Example" + crlf + + "{" + crlf + + " public sealed class Widget { }" + crlf + + "}" + crlf + + "=======" + crlf + + "namespace Example;" + lf + + "" + lf + + "public sealed class Widget { }" + lf + + ">>>>>>> After" + lf + + "" + lf + + "namespace Example;" + lf + + "" + lf + + "public sealed class Widget { }" + lf; + WriteUtf8Fixture(recoverable, recoverableText, bom: true); + + var beforeCheck = File.ReadAllBytes(recoverable); + var check = await InvokeRepairAsync("--path", recoverable, "--progress-file", progressPath); + AssertEqual(0, check.Code, "Check mode should accept the proven duplicate artifact."); + if (!Regex.IsMatch(check.Output, "\"status\":\\s*\"recoverable\"")) throw new InvalidOperationException("Check mode did not report recoverable status."); + if (!Regex.IsMatch(check.Output, "\"pattern\":\\s*\"whole-document-namespace-conversion\"")) throw new InvalidOperationException("Check mode did not identify the supported structural pattern."); + if (!check.Error.Contains("[START]", StringComparison.Ordinal) || !check.Error.Contains("[COMPLETE]", StringComparison.Ordinal)) throw new InvalidOperationException("Check mode did not emit stderr observability lines."); + using (var progressDoc = JsonDocument.Parse(File.ReadAllText(progressPath))) + { + AssertEqual("succeeded", progressDoc.RootElement.GetProperty("state").GetString(), "Progress file should record succeeded terminal state."); + } + AssertEqual(Convert.ToHexString(beforeCheck), Convert.ToHexString(File.ReadAllBytes(recoverable)), "Check mode changed the file."); + + // Reject --progress-file overlapping a target source file. + var overlap = await InvokeRepairAsync("-Path", recoverable, "--progress-file", recoverable); + AssertEqual(1, overlap.Code, "Progress file overlapping a source file should be rejected."); + AssertEqual(Convert.ToHexString(beforeCheck), Convert.ToHexString(File.ReadAllBytes(recoverable)), "Rejected progress file overlap modified the source file."); + + // PowerShell-style -Path and -Apply must also work. + var apply = await InvokeRepairAsync("-Path", recoverable, "-Apply"); + AssertEqual(0, apply.Code, "Apply mode should repair the proven duplicate artifact."); + if (!Regex.IsMatch(apply.Output, "\"status\":\\s*\"repaired\"")) throw new InvalidOperationException("Apply mode did not report repaired status."); + var repairedBytes = File.ReadAllBytes(recoverable); + if (!(repairedBytes[0] == 0xEF && repairedBytes[1] == 0xBB && repairedBytes[2] == 0xBF)) throw new InvalidOperationException("UTF-8 BOM was not preserved."); + var repairedText = Encoding.UTF8.GetString(repairedBytes, 3, repairedBytes.Length - 3); + AssertEqual("using System;\n\nnamespace Example;\n\npublic sealed class Widget { }\n", repairedText, "Recovered content was not the complete After document."); + AssertEqual(1, Regex.Matches(repairedText, "namespace Example;").Count, "Namespace conversion was duplicated."); + + var secondApply = await InvokeRepairAsync("-Path", recoverable, "-Apply", "--quiet", "--no-heartbeat"); + AssertEqual(0, secondApply.Code, "Repair should be idempotent."); + if (!Regex.IsMatch(secondApply.Output, "\"status\":\\s*\"clean\"")) throw new InvalidOperationException("Second apply did not report a clean file."); + if (secondApply.Error.Contains("[START]", StringComparison.Ordinal)) throw new InvalidOperationException("--quiet should suppress [START] on stderr."); + + var unsafeText = recoverableText.Replace("public sealed class Widget { }" + lf + ">>>>>>> After", "public sealed class Different { }" + lf + ">>>>>>> After"); + WriteUtf8Fixture(unsafeFile, unsafeText); + var unsafeBefore = File.ReadAllBytes(unsafeFile); + var unsafeResult = await InvokeRepairAsync("-Path", unsafeFile, "-Apply"); + AssertEqual(2, unsafeResult.Code, "Mismatched After content should fail closed."); + if (!Regex.IsMatch(unsafeResult.Output, "\"status\":\\s*\"unsafe\"")) throw new InvalidOperationException("Unsafe artifact was not reported."); + AssertEqual(Convert.ToHexString(unsafeBefore), Convert.ToHexString(File.ReadAllBytes(unsafeFile)), "Unsafe artifact was modified."); + + var unsupportedLocalizedText = + "namespace Example;" + lf + + "" + lf + + "public sealed class Localized" + lf + + "{" + lf + + " /* Unmerged change from project 'Example(net9.0)'" + lf + + " Before:" + lf + + " if (value) { Execute(); }" + lf + + " After:" + lf + + " if (value)" + lf + + " {" + lf + + " Execute();" + lf + + " }" + lf + + " */" + lf + + "}" + lf; + WriteUtf8Fixture(unsupportedLocalized, unsupportedLocalizedText); + var unsupportedBefore = File.ReadAllBytes(unsupportedLocalized); + var unsupportedResult = await InvokeRepairAsync("-Path", unsupportedLocalized, "-Apply"); + AssertEqual(2, unsupportedResult.Code, $"An unsupported localized artifact should fail closed. Output: {unsupportedResult.Output}"); + if (!Regex.IsMatch(unsupportedResult.Output, "\"pattern\":\\s*\"unrecognized\"")) throw new InvalidOperationException("Unsupported artifact was not reported as an unrecognized pattern."); + AssertEqual(Convert.ToHexString(unsupportedBefore), Convert.ToHexString(File.ReadAllBytes(unsupportedLocalized)), "Unsupported localized artifact was modified."); + + WriteUtf8Fixture(blockedRecoverable, recoverableText); + var blockedBefore = File.ReadAllBytes(blockedRecoverable); + var blockedResult = await InvokeRepairAsync("-Path", testRoot, "-Apply"); + AssertEqual(2, blockedResult.Code, "Directory apply should fail when any artifact is unsafe."); + AssertEqual(Convert.ToHexString(blockedBefore), Convert.ToHexString(File.ReadAllBytes(blockedRecoverable)), "Directory apply partially repaired a file despite an unsafe sibling artifact."); + + WriteUtf8Fixture(clean, "namespace Example;\n\npublic sealed class Clean { }\n"); + var directoryResult = await InvokeRepairAsync("-Path", testRoot); + AssertEqual(2, directoryResult.Code, "Directory scan should surface the unsafe fixture."); + if (!directoryResult.Output.Contains("Clean.cs", StringComparison.Ordinal) || !Regex.IsMatch(directoryResult.Output, "\"status\":\\s*\"clean\"")) + { + throw new InvalidOperationException("Directory scan did not report the clean fixture."); + } + + Console.Out.WriteLine("All Roslyn multi-project artifact repair tests passed."); + return 0; +} +finally +{ + if (Directory.Exists(testRoot)) + { + Directory.Delete(testRoot, recursive: true); + } +} diff --git a/scripts/tests/docfx-integration-tests.cs b/scripts/tests/docfx-integration-tests.cs index eb590072..4ebfa0a3 100644 --- a/scripts/tests/docfx-integration-tests.cs +++ b/scripts/tests/docfx-integration-tests.cs @@ -1,5 +1,6 @@ #!/usr/bin/env dotnet #:property TargetFramework=net10.0 +#:property RollForward=Major #:property Nullable=enable #:property LangVersion=latest #:property PublishAot=false @@ -11,7 +12,9 @@ #:include docfx-unit/ScopeTestSupport.cs #:include docfx-integration/ApiModelIntegrationTests.cs #:include docfx-integration/ProcessIntegrationTests.cs +#:include docfx-integration/RunActionDeliverableCliTests.cs #:include docfx-integration/SampleCompilationIntegrationTests.cs +#:include docfx-integration/WorkPacketCliTests.cs using System.Globalization; using System.Reflection; @@ -31,6 +34,8 @@ host.RunSuite("ProcessIntegration", ProcessIntegrationTests.Run); host.RunSuite("ApiModelIntegration", ApiModelIntegrationTests.Run); host.RunSuite("SampleCompilationIntegration", SampleCompilationIntegrationTests.Run); +host.RunSuite("WorkPacketCli", WorkPacketCliTests.Run); +host.RunSuite("RunActionDeliverableCli", RunActionDeliverableCliTests.Run); Console.WriteLine($"DocFX integration tests passed ({host.Assertions} assertions across {host.Suites} suite(s))."); return 0; diff --git a/scripts/tests/docfx-integration/RunActionDeliverableCliTests.cs b/scripts/tests/docfx-integration/RunActionDeliverableCliTests.cs new file mode 100644 index 00000000..dcfe0cd1 --- /dev/null +++ b/scripts/tests/docfx-integration/RunActionDeliverableCliTests.cs @@ -0,0 +1,526 @@ +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json.Nodes; + +// Black-box tests of which run-action files may stay in a consuming repository. Everything runs offline: generation +// needs no network without --verify, and the failing verification uses an engine path that does not exist. +internal static class RunActionDeliverableCliTests +{ + private const string Interim = "INTERIM_ARTIFACT_IN_WORKTREE"; + private const string Settings = ".docfx/run-actions.settings.json"; + private const string Manifest = ".docfx/run-actions.manifest.json"; + private const string FirstPage = ".docfx/api/types/Acme.P00.Box00.md"; + private const string WrapperPath = ".docfx/run-actions/0123456789abcdef01234567/native.ps1"; + + private sealed record CliResult(int ExitCode, string StdOut, string StdErr); + + public static void Run(DocfxTestHost h) + { + var root = RunActionTarget.NewTempRoot("docfx-run-action-deliverables"); + try + { + FirstRunFailureAndResume(h, Path.Combine(root, "first-run"), Path.Combine(root, "clone")); + UidScopeKeepsOtherEntries(h, Path.Combine(root, "uid")); + UidExampleScopeIgnoresSiblingStaleAssociation(h, Path.Combine(root, "uid-sibling")); + ExistingTemplateIsReused(h, Path.Combine(root, "template")); + TemplateOutsideDocfxFolderIsReused(h, Path.Combine(root, "repo-template")); + RootWorkspace(h, Path.Combine(root, "root-workspace")); + ManagedBlockIsRefreshed(h, Path.Combine(root, "agents"), BuildAgents(h, Path.Combine(root, "agents-build"))); + } + finally + { + foreach (var file in Directory.EnumerateFiles(root, "*", SearchOption.AllDirectories)) + { + File.SetAttributes(file, FileAttributes.Normal); + } + + Directory.Delete(root, recursive: true); + } + } + + private static void FirstRunFailureAndResume(DocfxTestHost h, string repo, string clone) + { + CreateRepository(repo); + + // 1. Valid recipes may exist before the first manifest. + WriteSettings(repo, "Box00", "Box01"); + var first = Validate(h, repo); + h.Equal("", Paths(first, Interim), "recipes are documentation source before any manifest exists"); + h.Equal(Manifest, Paths(first, "RUN_ACTION_MANIFEST_MISSING", "warnings"), "missing generation is reported on its own"); + h.Equal(Manifest, Paths(Validate(h, repo, Csrun), "RUN_ACTION_MANIFEST_MISSING"), "repair-csrun cannot finish without generation"); + + // 2. A failed first generation leaves the recipes and nothing that looks like success. + var failed = Generate(repo, "--verify", "Native", "--engine-path", Path.Combine(repo, "..", "no-engine.ps1")); + h.Equal(1, failed.ExitCode, "a missing engine fails verification"); + h.False(File.Exists(Full(repo, Manifest)), "a failed first generation publishes no manifest"); + var afterFailure = Validate(h, repo, Csrun); + h.Equal("", Paths(afterFailure, Interim), "recipes stay legitimate after a failed generation"); + h.Equal(Manifest, Paths(afterFailure, "RUN_ACTION_MANIFEST_MISSING"), "a failed generation stays visible"); + h.False(CanClaimCompletion(afterFailure), "a failed generation cannot be reported as complete"); + + // 3. Resuming succeeds, and every generated source file is accepted. + File.WriteAllText(Full(repo, ".gitignore"), "# Build-time run scripts\n/.docfx/run-actions/\n"); + var resumed = Generate(repo); + h.Equal(0, resumed.ExitCode, "generation resumes: " + resumed.StdErr + resumed.StdOut); + var untracked = Git(repo, "ls-files", "--others", "--exclude-standard").Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + h.Equal(".docfx/BuildRunActions.ps1|.docfx/run-actions.manifest.json|.docfx/run-actions.settings.json|.docfx/templates/modern/public/main.js|.docfx/templates/modern/public/run-actions.js|.gitignore", + string.Join("|", untracked.Order(StringComparer.Ordinal)), "the complete new documentation source"); + var complete = Validate(h, repo, Csrun); + h.Equal("", Paths(complete, Interim), "generated source is accepted"); + h.Equal("", RunActionCodes(complete), "a complete delivery reports no run-action problem"); + + // 4. An enriched repository updates its recipes. + Commit(repo); + WriteSettingsVersion(repo, "1.0.1", "Box00", "Box01"); + h.Equal(0, Generate(repo).ExitCode, "updated recipes regenerate"); + h.Contains("Acme.P00@1.0.1", File.ReadAllText(Full(repo, Manifest)), "the manifest follows the recipe"); + h.Equal("", RunActionCodes(Validate(h, repo, Csrun)), "the update is consistent"); + Commit(repo); + + // A clean checkout can create the run scripts from source alone. + Git(Path.GetDirectoryName(repo)!, "clone", "--quiet", repo, clone); + var materialized = Start("pwsh", clone, "-NoProfile", "-NonInteractive", "-File", Full(clone, ".docfx/BuildRunActions.ps1")); + h.Equal(0, materialized.ExitCode, "a clean checkout materializes: " + materialized.StdErr); + h.Equal(4, Directory.GetFiles(Full(clone, ".docfx/run-actions"), "*.ps1", SearchOption.AllDirectories).Length, "both transports of both examples exist"); + h.Equal("", Git(clone, "status", "--porcelain"), "ignored scripts leave the checkout clean"); + h.Equal("", Paths(Validate(h, clone), Interim), "ignored scripts are not reported"); + + ScratchStaysRejected(h, repo); + BrokenContentStaysVisible(h, repo); + CommittedWrappers(h, repo); + } + + // 6 and 7. Classification must not become a blanket exemption. + private static void ScratchStaysRejected(DocfxTestHost h, string repo) + { + string[] scratch = + [ + ".docfx/BuildRunActions.cs", + ".docfx/helper.ps1", + ".docfx/notes.json", + ".docfx/notes.md", + ".docfx/run-actions.settings.backup.json", + ".docfx/templates/modern/public/helper.js", + ".docfx/templates/other/public/main.js", + ".docfx/templates/other/public/run-actions.js", + ".docfx/tools/run-actions.settings.json", + "run-actions.settings.json", + "_site/index.html", + ".docfx/.gitignore" + ]; + foreach (var path in scratch) + { + Write(repo, path, path.EndsWith(".gitignore", StringComparison.Ordinal) ? "run-actions/\n*.log\n" : "{}"); + } + + // The configured build output is outside the DocFX folder here. + EditConfig(repo, config => config["build"]!["dest"] = "../_site"); + Write(repo, WrapperPath, "'native'"); + Write(repo, ".docfx/run-actions/index.json", "{}"); + Git(repo, "add", "--force", WrapperPath, ".docfx/run-actions/index.json"); + var expected = scratch.Append(WrapperPath).Append(".docfx/run-actions/index.json").Order(StringComparer.Ordinal); + var report = Validate(h, repo); + h.Equal(string.Join("|", expected), Paths(report, Interim), "every unexpected file is still rejected"); + h.Contains("DocFX build time", Errors(report).First(e => Text(e, "path") == WrapperPath)["message"]!.GetValue(), "a wrapper explains its origin"); + + // 8. A UID scope does not hide scratch files. + h.Equal(string.Join("|", expected), Paths(Validate(h, repo, "--uid", "Acme.P00.Box00"), Interim), "a UID scope keeps the hygiene check"); + + Git(repo, "reset", "--hard", "--quiet"); + Git(repo, "clean", "-fdq"); + Write(repo, ".docfx/.gitignore", "run-actions/\n"); + h.Equal("", Paths(Validate(h, repo), Interim), "an ignore file that covers only run scripts is accepted"); + Git(repo, "clean", "-fdq"); + } + + // 10. A legitimate file with wrong content is not scratch, and it blocks completion under its own code. + private static void BrokenContentStaysVisible(DocfxTestHost h, string repo) + { + var settings = File.ReadAllText(Full(repo, Settings)); + foreach (var (content, problem) in new[] + { + ("{ not json", "cannot be read"), + ("[]", "'examples' array"), + ("{\"examples\":[{\"uid\":\"Acme.P00.Box00\",\"sourceSha256\":\"abc\",\"manifest\":{}}]}", "sourceSha256"), + (settings.Replace("\"manifest\"", "\"harness\"", StringComparison.Ordinal), "'harness' is no longer supported"), + (settings.Replace("\"manifest\"", "\"unknown\"", StringComparison.Ordinal), "a recipe needs"), + (settings.Replace("\"manifest\"", "\"intrinsicLimitation\":\"none\",\"manifest\"", StringComparison.Ordinal), "cannot be combined") + }) + { + File.WriteAllText(Full(repo, Settings), content); + foreach (var arguments in (string[][])[[], Csrun]) + { + var report = Validate(h, repo, arguments); + h.Equal("", Paths(report, Interim), "invalid recipes are not scratch"); + h.Contains(problem, Errors(report).First(e => Text(e, "code") == "RUN_ACTION_SETTINGS_INVALID")["message"]!.GetValue(), "the recipe problem is named"); + h.False(CanClaimCompletion(report), "invalid recipes block completion"); + } + } + + File.WriteAllText(Full(repo, Settings), settings); + var manifest = File.ReadAllText(Full(repo, Manifest)); + File.WriteAllText(Full(repo, Manifest), "{"); + h.Equal(Manifest, Paths(Validate(h, repo), "RUN_ACTION_MANIFEST_INVALID"), "an unreadable manifest is an error"); + + var partial = JsonNode.Parse(manifest)!; + var removed = partial["examples"]!.AsArray().Single(e => Text(e!, "uid") == "Acme.P00.Box00")!; + partial["examples"]!.AsArray().Remove(removed); + File.WriteAllText(Full(repo, Manifest), partial.ToJsonString()); + var missingEntry = Validate(h, repo, Csrun); + h.Equal(FirstPage, Paths(missingEntry, "RUN_ACTION_ENTRY_MISSING"), "a runnable example without an entry is an error"); + h.Equal(FirstPage, Paths(missingEntry, "RUN_ACTION_ASSOCIATION_STALE"), "links without an entry are an error"); + File.WriteAllText(Full(repo, Manifest), manifest.Replace("box.Read(3)", "box.Read(4)", StringComparison.Ordinal)); + h.True(Paths(Validate(h, repo, Csrun), "RUN_ACTION_ENTRY_STALE").Contains(FirstPage, StringComparison.Ordinal), "an entry from other C# is an error"); + + var older = JsonNode.Parse(manifest)!; + foreach (var entry in older["examples"]!.AsArray()) + { + entry!.AsObject().Remove("exampleId"); + } + + File.WriteAllText(Full(repo, Manifest), older.ToJsonString()); + h.Equal("", RunActionCodes(Validate(h, repo, Csrun)), "an older manifest without example ids is recognized by its code"); + File.WriteAllText(Full(repo, Manifest), manifest); + + foreach (var path in (string[])[".docfx/BuildRunActions.ps1", ".docfx/templates/modern/public/run-actions.js"]) + { + File.Delete(Full(repo, path)); + h.Equal(path, Paths(Validate(h, repo, Csrun), "RUN_ACTION_SOURCE_MISSING"), "repair-csrun needs the complete source"); + h.Equal(path, Paths(Validate(h, repo), "RUN_ACTION_SOURCE_MISSING", "warnings"), "other operations only warn"); + Git(repo, "checkout", "--quiet", "--", path); + } + + Write(repo, ".docfx/templates/modern/public/main.js", "export default {};\n"); + h.Equal(".docfx/templates/modern/public/main.js", Paths(Validate(h, repo, Csrun), "RUN_ACTION_SOURCE_MISSING"), "the toolbar must be imported"); + Git(repo, "checkout", "--quiet", "--", ".docfx/templates/modern/public/main.js"); + EditConfig(repo, config => config["build"]!.AsObject().Remove("resource")); + h.Equal(".docfx/docfx.json", Paths(Validate(h, repo, Csrun), "RUN_ACTION_SOURCE_MISSING"), "the scripts must be published"); + Git(repo, "checkout", "--quiet", "--", "."); + h.Equal("", RunActionCodes(Validate(h, repo, Csrun)), "the restored source is complete again"); + } + + private static void CommittedWrappers(DocfxTestHost h, string repo) + { + Write(repo, WrapperPath, "'native'"); + Git(repo, "add", "--force", WrapperPath); + Commit(repo); + var enriched = Validate(h, repo); + h.Equal(".docfx/run-actions", Paths(enriched, "RUN_ACTION_WRAPPER_COMMITTED"), "a committed wrapper is an error beside a manifest"); + Git(repo, "rm", "--quiet", "--cached", "-r", ".docfx/run-actions"); + h.Equal("", Paths(Validate(h, repo), "RUN_ACTION_WRAPPER_COMMITTED"), "the suggested command resolves it"); + + // The older layout without a manifest keeps working until it is regenerated. + Git(repo, "reset", "--hard", "--quiet"); + File.Delete(Full(repo, Manifest)); + var legacy = Validate(h, repo); + h.Equal("", Paths(legacy, "RUN_ACTION_WRAPPER_COMMITTED"), "the older layout is not an error"); + h.Equal(".docfx/run-actions", Paths(legacy, "RUN_ACTION_WRAPPER_COMMITTED", "warnings"), "the older layout is still reported"); + h.Equal("", Paths(legacy, Interim), "tracked files are not new files"); + } + + private static void UidScopeKeepsOtherEntries(DocfxTestHost h, string repo) + { + CreateRepository(repo); + WriteSettings(repo, "Box00", "Box01"); + h.Equal(0, Generate(repo).ExitCode, "the repository is enriched"); + Commit(repo); + var before = Entry(repo, "Box01"); + WriteSettingsVersion(repo, "2.0.0", "Box00", "Box01"); + h.Equal(0, Generate(repo, "--uid=Acme.P00.Box00").ExitCode, "one UID is regenerated"); + h.Contains("Acme.P00@2.0.0", Entry(repo, "Box00"), "the selected entry changes"); + h.Equal(before, Entry(repo, "Box01"), "the other entry is preserved"); + var report = Validate(h, repo, [.. Csrun, "--uid", "Acme.P00.Box00"]); + h.Equal("", Paths(report, Interim), "scoped generation adds no scratch files"); + h.Equal("", RunActionCodes(report), "the scoped delivery is complete"); + } + + private static void UidExampleScopeIgnoresSiblingStaleAssociation(DocfxTestHost h, string repo) + { + CreateRepository(repo); + Write(repo, FirstPage, """ + --- + uid: Acme.P00.Box00 + example: + - *content + --- + The following program creates a `Box00`, reads `3`, and prints the value to standard output. + + ```csharp + // Program.cs + using System; + using Acme.P00; + + var box = new Box00(); + Console.WriteLine($"Value={box.Read(3)}"); + ``` + + A second example reads `7` from `Box00`. + + ```csharp + // Program.cs + using System; + using Acme.P00; + + var box = new Box00(); + Console.WriteLine($"Value={box.Read(7)}"); + ``` + """); + var pageText = File.ReadAllText(Full(repo, FirstPage)).Replace("\r\n", "\n", StringComparison.Ordinal); + var firstStart = pageText.IndexOf("```csharp\n", StringComparison.Ordinal) + "```csharp\n".Length; + var firstCode = pageText[firstStart..pageText.IndexOf("\n```", firstStart, StringComparison.Ordinal)]; + var secondStart = pageText.IndexOf("```csharp\n", firstStart, StringComparison.Ordinal) + "```csharp\n".Length; + var secondCode = pageText[secondStart..pageText.IndexOf("\n```", secondStart, StringComparison.Ordinal)]; + var box01Page = File.ReadAllText(Full(repo, ".docfx/api/types/Acme.P00.Box01.md")).Replace("\r\n", "\n", StringComparison.Ordinal); + var box01Start = box01Page.IndexOf("```csharp\n", StringComparison.Ordinal) + "```csharp\n".Length; + var box01Code = box01Page[box01Start..box01Page.IndexOf("\n```", box01Start, StringComparison.Ordinal)]; + File.WriteAllText(Full(repo, Settings), new JsonObject + { + ["examples"] = new JsonArray( + Recipe("Acme.P00.Box00", 1, firstCode, "1.0.0"), + Recipe("Acme.P00.Box00", 2, secondCode, "1.0.0"), + Recipe("Acme.P00.Box01", 1, box01Code, "1.0.0")) + }.ToJsonString()); + Commit(repo); + var enriched = Generate(repo); + h.Equal(0, enriched.ExitCode, "both examples on the page are enriched: " + enriched.StdErr + enriched.StdOut); + Commit(repo); + + // Corrupt only the second example's association link on the shared page. + var enrichedPage = File.ReadAllText(Full(repo, FirstPage)); + var secondAttr = enrichedPage.LastIndexOf("data-example-id=\"", StringComparison.Ordinal); + var secondValueStart = secondAttr + "data-example-id=\"".Length; + var secondValueEnd = enrichedPage.IndexOf('"', secondValueStart); + var staleId = "deadbeefdeadbeefdeadbeef"; + var mutated = enrichedPage[..secondValueStart] + staleId + enrichedPage[secondValueEnd..]; + File.WriteAllText(Full(repo, FirstPage), mutated); + + // Scoped generation for #1 preserves #2, so #1 validation must not fail on #2's stale link. + var scopedGen = Generate(repo, "--uid=Acme.P00.Box00#1"); + h.Equal(0, scopedGen.ExitCode, "scoped generation for #1 succeeds: " + scopedGen.StdErr + scopedGen.StdOut); + var scopedFirst = Validate(h, repo, [.. Csrun, "--uid", "Acme.P00.Box00#1"]); + h.Equal("", Paths(scopedFirst, "RUN_ACTION_ASSOCIATION_STALE"), "scoped #1 validation ignores sibling #2 stale link"); + h.Equal("", RunActionCodes(scopedFirst), "scoped #1 delivery has no run-action errors"); + + // Selecting #2 or the whole type must still report #2's stale link. + h.Equal(FirstPage, Paths(Validate(h, repo, [.. Csrun, "--uid", "Acme.P00.Box00#2"]), "RUN_ACTION_ASSOCIATION_STALE"), + "scoped #2 validation reports its own stale link"); + h.Equal(FirstPage, Paths(Validate(h, repo, [.. Csrun, "--uid", "Acme.P00.Box00"]), "RUN_ACTION_ASSOCIATION_STALE"), + "whole-type validation reports #2 stale link"); + } + + // 5. The toolbar goes into the consumer's own template when it already has a main.js. + private static void ExistingTemplateIsReused(DocfxTestHost h, string repo) + { + CreateRepository(repo, "templates/brand"); + Write(repo, ".docfx/templates/brand/public/main.js", "export default { start() {} };\n"); + Commit(repo); + WriteSettings(repo, "Box00", "Box01"); + h.Equal(0, Generate(repo).ExitCode, "generation reuses the consumer template"); + h.True(File.Exists(Full(repo, ".docfx/templates/brand/public/run-actions.js")), "the toolbar joins the existing template"); + var report = Validate(h, repo, Csrun); + h.Equal("", Paths(report, Interim), "configured template assets are accepted"); + h.Equal("", RunActionCodes(report), "the configured template is complete"); + Write(repo, ".docfx/templates/modern/public/main.js", "import './run-actions.js';\n"); + h.Equal(".docfx/templates/modern/public/main.js", Paths(Validate(h, repo), Interim), "an overlay nobody configured is scratch"); + } + + private static void TemplateOutsideDocfxFolderIsReused(DocfxTestHost h, string repo) + { + CreateRepository(repo, "../templates/brand"); + Write(repo, "templates/brand/public/main.js", "export default { start() {} };\n"); + Commit(repo); + WriteSettings(repo, "Box00", "Box01"); + h.Equal(0, Generate(repo).ExitCode, "generation reuses a template outside .docfx within the repo"); + h.True(File.Exists(Full(repo, "templates/brand/public/run-actions.js")), "the toolbar joins the repo-level template"); + var report = Validate(h, repo, Csrun); + h.Equal("", Paths(report, Interim), "repo-level template assets are accepted"); + h.Equal("", RunActionCodes(report), "the repo-level template satisfies repair-csrun"); + + File.Delete(Full(repo, "templates/brand/public/run-actions.js")); + h.Equal("templates/brand/public/run-actions.js", Paths(Validate(h, repo, Csrun), "RUN_ACTION_SOURCE_MISSING"), + "missing toolbar in the repo-level template is reported at its real path"); + } + + private static void RootWorkspace(DocfxTestHost h, string repo) + { + Write(repo, "src/Lib/Lib.csproj", "net10.0"); + Write(repo, "src/Lib/Thing.cs", "namespace Lib; public sealed class Thing { }"); + Write(repo, "docfx.json", "{\"metadata\":[{\"src\":[{\"files\":[\"src/**/*.csproj\"]}],\"dest\":\"api\"}],\"build\":{\"content\":[{\"files\":[\"api/**/*.yml\"]}],\"dest\":\"_site\"}}"); + InitializeGit(repo); + Write(repo, "run-actions.settings.json", "{\"examples\":[]}"); + Write(repo, "run-actions/0123456789abcdef01234567/docker.ps1", "'docker'"); + Write(repo, "_site/index.html", ""); + Write(repo, "samples/unrelated.ps1", "'consumer file'"); + h.Equal("_site/index.html|run-actions/0123456789abcdef01234567/docker.ps1", Paths(Validate(h, repo), Interim), + "generated output is found when DocFX lives in the repository root"); + } + + // 9. Re-running agents.cs refreshes the managed block and nothing else. + private static void ManagedBlockIsRefreshed(DocfxTestHost h, string repo, string agents) + { + CliResult RunAgents(params string[] args) => Start("dotnet", repo, [agents, "--repo-root", repo, .. args]); + + Directory.CreateDirectory(repo); + var path = Path.Combine(repo, "AGENTS.md"); + const string before = "# House rules\r\n\r\nKeep this.\r\n\r\n"; + const string after = "\r\n\r\n## More rules\r\n\r\nrun-actions.settings.json is ours.\r\n"; + File.WriteAllText(path, before + "\r\nOld managed text.\r\n" + after); + var refreshed = RunAgents(); + h.Equal(0, refreshed.ExitCode, "the managed block is refreshed: " + refreshed.StdErr + refreshed.StdOut); + var text = File.ReadAllText(path); + h.True(text.StartsWith(before, StringComparison.Ordinal) && text.EndsWith(after, StringComparison.Ordinal), "unmanaged guidance is byte-identical"); + h.False(text.Contains("Old managed text.", StringComparison.Ordinal), "the old managed text is replaced"); + var managed = text[before.Length..^after.Length]; + foreach (var name in (string[])["run-actions.settings.json", "run-actions.manifest.json", "BuildRunActions.ps1", "run-actions/"]) + { + h.Contains(name, managed, "the managed block names the run-action contract"); + } + + h.Equal(0, RunAgents("--check").ExitCode, "a second run has nothing to change"); + } + + private static readonly string[] Csrun = ["--operation", "repair-csrun"]; + + private static string ScriptsDirectory([CallerFilePath] string source = "") => + Path.GetFullPath(Path.Combine(Path.GetDirectoryName(source)!, "../../../skills/dotnet-docfx-digest/scripts")); + + private static JsonObject Validate(DocfxTestHost h, string repo, params string[] args) + { + var result = Start("dotnet", repo, [h.Assembly.Location, "--repo-root", repo, .. args, "--json", "--quiet"]); + return (JsonNode.Parse(result.StdOut) ?? throw new InvalidOperationException(result.StdErr)).AsObject(); + } + + private static CliResult Generate(string repo, params string[] args) => + Start("pwsh", repo, ["-NoProfile", "-NonInteractive", "-File", Path.Combine(ScriptsDirectory(), "generate-run-actions.ps1"), "-RepoRoot", repo, .. args]); + + // A private copy is built once, so another build of agents.cs on the same machine cannot interfere. + private static string BuildAgents(DocfxTestHost h, string directory) + { + Directory.CreateDirectory(directory); + File.Copy(Path.Combine(ScriptsDirectory(), "agents.cs"), Path.Combine(directory, "agents.cs")); + var output = Path.Combine(directory, "out"); + var build = Start("dotnet", directory, "build", Path.Combine(directory, "agents.cs"), "--output", output); + h.Equal(0, build.ExitCode, "agents.cs builds: " + build.StdErr + build.StdOut); + return Path.Combine(output, "agents.dll"); + } + + private static CliResult Start(string executable, string workingDirectory, params string[] args) + { + var start = new ProcessStartInfo(executable) + { + RedirectStandardOutput = true, + RedirectStandardError = true, + StandardOutputEncoding = Encoding.UTF8, + StandardErrorEncoding = Encoding.UTF8, + WorkingDirectory = workingDirectory + }; + foreach (var argument in args) + { + start.ArgumentList.Add(argument); + } + + using var process = Process.Start(start)!; + var stdout = process.StandardOutput.ReadToEndAsync(); + var stderr = process.StandardError.ReadToEndAsync(); + if (!process.WaitForExit(TimeSpan.FromMinutes(3))) + { + process.Kill(entireProcessTree: true); + throw new InvalidOperationException($"{executable} did not finish within 3 minutes."); + } + + return new CliResult(process.ExitCode, stdout.GetAwaiter().GetResult(), stderr.GetAwaiter().GetResult()); + } + + private static string Git(string repo, params string[] args) + { + var result = Start("git", repo, ["-c", "core.autocrlf=false", "-c", "user.name=Test", "-c", "user.email=test@example.invalid", "-c", "commit.gpgsign=false", .. args]); + return result.ExitCode == 0 ? result.StdOut.Trim() : throw new InvalidOperationException($"git {string.Join(' ', args)}: {result.StdErr}"); + } + + private static void InitializeGit(string repo) + { + Git(repo, "init", "--quiet"); + Commit(repo); + } + + private static void Commit(string repo) + { + Git(repo, "add", "--all"); + Git(repo, "commit", "--quiet", "--message", "fixture"); + } + + private static void CreateRepository(string repo, string? template = null) + { + WorkPacketCliTests.CreateRepository(repo, projects: 1, examplesPerProject: 2); + if (template is not null) + { + EditConfig(repo, config => config["build"]!["template"]!.AsArray().Add(template)); + } + + InitializeGit(repo); + } + + private static void EditConfig(string repo, Action edit) + { + var path = Full(repo, ".docfx/docfx.json"); + var config = JsonNode.Parse(File.ReadAllText(path))!; + edit(config); + File.WriteAllText(path, config.ToJsonString()); + } + + private static void WriteSettings(string repo, params string[] types) => WriteSettingsVersion(repo, "1.0.0", types); + + private static void WriteSettingsVersion(string repo, string version, params string[] types) + { + var recipes = types.Select(type => + { + var page = File.ReadAllText(Full(repo, $".docfx/api/types/Acme.P00.{type}.md")); + var start = page.IndexOf("```csharp\n", StringComparison.Ordinal) + "```csharp\n".Length; + var code = page[start..page.IndexOf("\n```", start, StringComparison.Ordinal)]; + return Recipe($"Acme.P00.{type}", 1, code, version); + }).ToArray(); + File.WriteAllText(Full(repo, Settings), new JsonObject { ["examples"] = new JsonArray(recipes) }.ToJsonString()); + } + + private static JsonNode Recipe(string uid, int ordinal, string code, string version) => new JsonObject + { + ["uid"] = uid, + ["exampleId"] = $"{uid}#{ordinal}", + ["fenceOrdinal"] = ordinal, + ["sourceSha256"] = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(code))), + ["manifest"] = new JsonObject + { + ["schemaVersion"] = 1, + ["mode"] = "console", + ["framework"] = "net10.0", + ["dependsOn"] = new JsonArray($"Acme.P00@{version}") + } + }; + + private static string Entry(string repo, string type) => + JsonNode.Parse(File.ReadAllText(Full(repo, Manifest)))!["examples"]!.AsArray().Single(e => Text(e!, "uid") == $"Acme.P00.{type}")!.ToJsonString(); + + private static void Write(string repo, string path, string content) + { + var full = Full(repo, path); + Directory.CreateDirectory(Path.GetDirectoryName(full)!); + File.WriteAllText(full, content); + } + + private static string Full(string repo, string path) => Path.Combine(repo, path.Replace('/', Path.DirectorySeparatorChar)); + + private static List Errors(JsonObject report, string level = "errors") => report[level]!.AsArray().Select(e => e!).ToList(); + + private static string Paths(JsonObject report, string code, string level = "errors") => + string.Join("|", Errors(report, level).Where(e => Text(e, "code") == code).Select(e => Text(e, "path").Replace('\\', '/')).Distinct().Order(StringComparer.Ordinal)); + + private static string RunActionCodes(JsonObject report) => + string.Join("|", Errors(report).Concat(Errors(report, "warnings")) + .Where(e => Text(e, "code").StartsWith("RUN_ACTION_", StringComparison.Ordinal)).Select(e => $"{Text(e, "code")}: {Text(e, "message")}")); + + private static string Text(JsonNode node, string name) => node[name]?.GetValue() ?? string.Empty; + + private static bool CanClaimCompletion(JsonObject report) => report["summary"]!["canClaimCompletion"]!.GetValue(); +} diff --git a/scripts/tests/docfx-integration/WorkPacketCliTests.cs b/scripts/tests/docfx-integration/WorkPacketCliTests.cs new file mode 100644 index 00000000..21650cca --- /dev/null +++ b/scripts/tests/docfx-integration/WorkPacketCliTests.cs @@ -0,0 +1,364 @@ +using System.Diagnostics; +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; + +// Black-box command-line tests of the work queue. The reviews written here are deterministic doubles for +// queue mechanics; they are not evidence that any example was verified. +internal static class WorkPacketCliTests +{ + public static void Run(DocfxTestHost h) + { + var root = RunActionTarget.NewTempRoot("docfx-work-packet-cli"); + try + { + RepairLoopContinuesThroughEveryProject(h, Path.Combine(root, "loop")); + ProgressFileNeverReplacesReviews(h, Path.Combine(root, "overlap")); + KilledCommandsResume(h, Path.Combine(root, "killed")); + EveryConsumerApiIsListedForOneExample(h, Path.Combine(root, "consumers")); + LargeRepositoryStartsWithBoundedOutput(h, Path.Combine(root, "large")); + } + finally + { + Directory.Delete(root, recursive: true); + } + } + + private sealed record CliResult(int ExitCode, string StdOut, string StdErr) + { + public JsonObject Json => JsonNode.Parse(StdOut)!.AsObject(); + } + + private static CliResult Invoke(DocfxTestHost h, string repo, params string[] args) + { + using var process = Start(h, repo, args); + var stdout = process.StandardOutput.ReadToEndAsync(); + var stderr = process.StandardError.ReadToEndAsync(); + if (!process.WaitForExit(TimeSpan.FromMinutes(3))) + { + process.Kill(entireProcessTree: true); + throw new InvalidOperationException("The validator did not finish within 3 minutes."); + } + + return new CliResult(process.ExitCode, stdout.GetAwaiter().GetResult(), stderr.GetAwaiter().GetResult()); + } + + private static Process Start(DocfxTestHost h, string repo, string[] args) + { + var start = new ProcessStartInfo("dotnet") + { + RedirectStandardOutput = true, + RedirectStandardError = true, + StandardOutputEncoding = Encoding.UTF8, + StandardErrorEncoding = Encoding.UTF8, + WorkingDirectory = repo + }; + foreach (var argument in (string[])[h.Assembly.Location, "--repo-root", repo, .. args]) + { + start.ArgumentList.Add(argument); + } + + return Process.Start(start)!; + } + + private static void ProgressFileNeverReplacesReviews(DocfxTestHost h, string repo) + { + CreateRepository(repo, projects: 1, examplesPerProject: 2); + Directory.CreateDirectory(Path.Combine(repo, "session")); + var ledger = Path.Combine(repo, "session", "ledger.json"); + string[] queue = ["--operation", "repair", "--behavioral-ledger", "session/ledger.json", "--quiet"]; + + void Refused(string path, params string[] args) + { + var before = File.Exists(path) ? File.ReadAllText(path) : null; + var result = Invoke(h, repo, [.. args, "--progress-file", path]); + h.Equal(2, result.ExitCode, "an overlapping progress file is refused: " + result.StdErr); + h.Equal(string.Empty, result.StdOut, "a refused command prints nothing on stdout"); + h.Contains("[FAILED]", result.StdErr, "the refusal is reported on stderr"); + h.True(before == (File.Exists(path) ? File.ReadAllText(path) : null), "the file is left unchanged"); + } + + Refused(ledger, [.. queue, "--next-packet"]); + var first = Invoke(h, repo, [.. queue, "--next-packet"]).Json; + h.Equal(0, Save(h, repo, queue, [.. Examples(first).Take(1)]).ExitCode, "a review is saved"); + Refused(ledger, [.. queue, "--next-packet"]); + var reviews = Path.GetFullPath(Path.Combine(repo, "..", "reviews.json")); + Refused(reviews, [.. queue, "--record-reviews", "../reviews.json"]); + + // The automatic ledger path is resolved after the first snapshot, so only the file itself can reveal the overlap. + string[] automatic = ["--operation", "repair", "--next-packet", "--quiet"]; + var autoLedger = Invoke(h, repo, automatic).Json["session"]!["ledger"]!.GetValue(); + Refused(Path.GetFullPath(autoLedger, repo), automatic); + + var progress = Path.Combine(repo, "session", "progress.json"); + h.Equal(0, Invoke(h, repo, [.. queue, "--next-packet", "--progress-file", progress]).ExitCode, "a separate progress file is accepted"); + var resumed = Invoke(h, repo, [.. queue, "--next-packet", "--progress-file", progress]); + h.Equal(0, resumed.ExitCode, "an earlier snapshot is replaced: " + resumed.StdErr); + h.Equal(1, Number(resumed.Json, "behaviorVerified"), "the saved review survives"); + } + + // Kills real commands at different moments. The saved reviews must survive, and the next command must resume. + private static void KilledCommandsResume(DocfxTestHost h, string repo) + { + CreateRepository(repo, projects: 3, examplesPerProject: 4); + var ledger = Path.Combine(repo, "..", "killed-session", "ledger.json"); + string[] queue = ["--operation", "repair", "--behavioral-ledger", ledger, "--quiet"]; + var first = Invoke(h, repo, [.. queue, "--next-packet"]).Json; + var expected = Save(h, repo, queue, [.. Examples(first).Take(2)]).Json; + foreach (var delay in new[] { 50, 300, 600, 900, 1200 }) + { + using var process = Start(h, repo, [.. queue, "--next-packet"]); + var stdout = process.StandardOutput.ReadToEndAsync(); + var stderr = process.StandardError.ReadToEndAsync(); + process.WaitForExit(delay); + if (!process.HasExited) + { + process.Kill(entireProcessTree: true); + } + + process.WaitForExit(); + Task.WaitAll(stdout, stderr); + } + + var resumed = Invoke(h, repo, [.. queue, "--next-packet"]); + h.Equal(0, resumed.ExitCode, "the queue resumes after its commands were killed: " + resumed.StdErr); + h.Equal(2, Number(resumed.Json, "behaviorVerified"), "saved reviews survive"); + h.Equal(string.Join('|', Examples(expected).Select(e => Text(e, "exampleId"))), string.Join('|', Examples(resumed.Json).Select(e => Text(e, "exampleId"))), "the same packet comes back"); + h.True(Text(resumed.Json, "nextAction").Length > 0 && Text(resumed.Json["commands"]!, "save").Length > 0, "the resumed packet has a next step"); + } + + private static void EveryConsumerApiIsListedForOneExample(DocfxTestHost h, string repo) + { + CreateRepository(repo, projects: 1, examplesPerProject: 2); + var methods = string.Join("\n", Enumerable.Range(0, 40).Select(i => + $" /// Reads a value.\n public static int Read{i:00}(int value) => new Box00().Read(value);")); + File.WriteAllText(Path.Combine(repo, "src", "Acme.P00", "Readers.cs"), + "namespace Acme.P00;\n\n/// Reads values.\npublic static class Readers\n{\n" + methods + "\n}\n"); + var ledger = Path.Combine(repo, "..", "consumers-session", "ledger.json"); + var packet = Invoke(h, repo, "--operation", "repair", "--behavioral-ledger", ledger, "--next-packet", "--quiet").Json; + var direct = Text(Examples(packet).Single(e => Text(e, "exampleId") == "Acme.P00.Box00#1")["consumerApis"]!, "direct"); + h.Contains("36 more, listed by commands.consumerApis", direct, "the packet says that more APIs exist"); + h.Contains("--consumer-apis ''", Text(packet["commands"]!, "consumerApis"), "the packet names the command that lists them"); + + var before = File.ReadAllText(ledger); + var all = Invoke(h, repo, "--operation", "repair", "--consumer-apis", "Acme.P00.Box00#1", "--quiet"); + h.Equal(0, all.ExitCode, "consumer APIs can be listed: " + all.StdErr); + h.Equal(40, all.Json["count"]!.GetValue(), "every consumer API is counted"); + for (var i = 0; i < 40; i++) + { + h.Contains($"Read{i:00} (", all.StdOut, "every consumer API is listed"); + } + + h.True(all.StdOut.Length < 8_000, $"the list stays compact ({all.StdOut.Length})"); + h.Equal(before, File.ReadAllText(ledger), "listing consumer APIs changes nothing"); + h.Equal(1, Invoke(h, repo, "--operation", "repair", "--consumer-apis", "Acme.P00.Nope#1", "--quiet").ExitCode, "an unknown example is refused"); + } + + private static void RepairLoopContinuesThroughEveryProject(DocfxTestHost h, string repo) + { + CreateRepository(repo, projects: 3, examplesPerProject: 2); + var ledger = Path.Combine(repo, "..", "loop-session", "ledger.json"); + string[] queue = ["--operation", "repair", "--behavioral-ledger", ledger]; + + // Ordinary reports must point at the queue instead of ending in a bare failure. + var report = Invoke(h, repo, "--operation", "repair", "--json", "--quiet"); + h.Equal(1, report.ExitCode, "a repair without reviews still fails its gate"); + h.Equal("work-remaining", report.Json["nextAction"]!["state"]!.GetValue(), "the report names the remaining work"); + h.False(report.Json["nextAction"]!["stopAllowed"]!.GetValue(), "the report is not a stopping point"); + h.Contains("--next-packet", report.Json["nextAction"]!["command"]!.GetValue(), "the report names the next command"); + h.False(report.Json["summary"]!["canClaimCompletion"]!.GetValue(), "the gate is unchanged"); + var console = Invoke(h, repo, "--operation", "repair", "--quiet"); + h.Contains("[next] work-remaining", console.StdOut, "the console report names the next action"); + + var progressFile = Path.Combine(repo, "..", "loop-session", "progress.json"); + var first = Invoke(h, repo, [.. queue, "--next-packet", "--progress-file", progressFile]); + h.Equal(0, first.ExitCode, "issuing work succeeds: " + first.StdErr); + h.Equal("review", Text(first.Json, "phase"), "the queue starts with reviews"); + h.True(first.Json["commands"]!["finalGate"] is null, "active review packets do not advertise the expensive final gate"); + h.Contains("[START]", first.StdErr, "progress starts on stderr"); + h.Contains("[COMPLETE]", first.StdErr, "progress ends on stderr"); + h.Equal(6, Number(first.Json, "examples"), "the whole repository is in scope"); + h.True(File.Exists(progressFile), "work-packet command writes an atomic JSON progress file"); + var progressDoc = JsonNode.Parse(File.ReadAllText(progressFile))!.AsObject(); + h.Equal("codebeltnet/agentic/progress/1", Text(progressDoc, "schema"), "CLI progress file uses repository progress schema"); + h.Equal("succeeded", Text(progressDoc, "state"), "CLI progress file records terminal succeeded state"); + h.True(progressDoc["pid"]!.GetValue() > 0, "CLI progress file records pid"); + h.True(!string.IsNullOrWhiteSpace(Text(progressDoc, "operationId")), "CLI progress file records operationId"); + h.True(progressDoc["staleAfterUtc"] is null, "CLI terminal progress file clears staleAfterUtc"); + h.Equal(0, progressDoc["outcome"]!["exitCode"]!.GetValue(), "CLI terminal progress file records exitCode"); + + var quiet = Invoke(h, repo, [.. queue, "--next-packet", "--quiet"]); + h.False(quiet.StdErr.Contains("[START]", StringComparison.Ordinal), "--quiet removes the start line"); + h.True(quiet.Json["session"]!["resumed"]!.GetValue(), "a new process resumes the session"); + h.Equal(Text(Examples(first.Json)[0], "exampleId"), Text(Examples(quiet.Json)[0], "exampleId"), "a new process continues the same packet"); + + // Editing a page after the packet was issued must invalidate the review that was written against it. + var stale = Examples(quiet.Json)[0]; + var page = Path.Combine(repo, Text(stale, "file").Replace('/', Path.DirectorySeparatorChar)); + File.WriteAllText(page, File.ReadAllText(page).Replace("prints the value", "prints the stored value", StringComparison.Ordinal)); + var rejected = Save(h, repo, queue, Examples(quiet.Json)); + h.Equal(1, rejected.ExitCode, "a review of an outdated revision is rejected"); + h.Contains("[FAILED]", rejected.StdErr, "a rejected review is reported on stderr"); + h.Equal(1, rejected.Json["saved"]!.AsArray().Count(s => !s!["saved"]!.GetValue()), "only the outdated review is rejected"); + h.Equal(Text(stale, "exampleId"), Text(Examples(rejected.Json)[0], "exampleId"), "the outdated example is issued again"); + + var current = rejected.Json; + var projects = new HashSet(StringComparer.Ordinal); + for (var i = 0; i < 10 && Text(current, "phase") == "review"; i++) + { + projects.Add(current["packet"]!["project"]!.GetValue()); + var saved = Save(h, repo, queue, Examples(current)); + h.Equal(0, saved.ExitCode, "current reviews are saved: " + saved.StdOut); + current = saved.Json; + } + + h.Equal(3, projects.Count, "every project was issued"); + + // The fixture pages repeat one template on purpose: saved reviews must not hide the documentation checks. + h.Equal("repair-diagnostics", Text(current, "phase"), "saved reviews lead to the remaining documentation problems"); + h.True(current["diagnostics"]!["byCode"]!["EXAMPLE_TEMPLATE_REPETITION"] is not null, "the remaining problems are listed"); + h.False(current["stopAllowed"]!.GetValue(), "documentation problems are not a stopping point"); + h.False(current["canClaimCompletion"]!.GetValue(), "the queue itself never claims completion"); + + // The ledger satisfies the unchanged behavioral gate, and the remaining gates still block completion. + var gate = Invoke(h, repo, [.. queue, "--json", "--quiet"]); + h.Equal(0, gate.Json["summary"]!["examplesUnreviewed"]!.GetValue(), "the existing gate accepts the recorded evidence"); + h.False(gate.Json["errors"]!.AsArray().Any(e => Text(e!, "code").StartsWith("BEHAVIORAL_", StringComparison.Ordinal)), "no behavioral diagnostics remain"); + h.False(gate.Json["summary"]!["canClaimCompletion"]!.GetValue(), "the other gates still prevent completion"); + h.Equal("repair-diagnostics", gate.Json["nextAction"]!["state"]!.GetValue(), "the report asks for the remaining repairs"); + + // New work reopens the queue. + File.WriteAllText(page, File.ReadAllText(page).Replace("the stored value", "the saved value", StringComparison.Ordinal)); + var failedGate = Invoke(h, repo, [.. queue, "--json", "--quiet"]).Json; + h.Equal("work-remaining", failedGate["nextAction"]!["state"]!.GetValue(), "a gate that finds stale evidence sends the work back to the queue"); + h.Contains("loop-session/ledger.json --next-packet", failedGate["nextAction"]!["command"]!.GetValue(), "the gate keeps the same ledger"); + var reopened = Invoke(h, repo, [.. queue, "--next-packet", "--quiet"]).Json; + h.Equal("review", Text(reopened, "phase"), "an edited example re-enters the queue"); + h.Equal(1, Examples(reopened).Count, "only the edited example re-enters"); + h.Equal(0, Directory.GetFiles(Path.GetDirectoryName(Path.GetFullPath(ledger))!, "*.tmp-*").Length, "ledger writes leave no temporary files"); + h.False(File.Exists(ledger + ".lock"), "the lock is released"); + } + + private static void LargeRepositoryStartsWithBoundedOutput(DocfxTestHost h, string repo) + { + CreateRepository(repo, projects: 38, examplesPerProject: 15); + var elapsed = Stopwatch.StartNew(); + var first = Invoke(h, repo, "--operation", "repair-csrun", "--behavioral-ledger", Path.Combine(repo, "..", "large-session", "ledger.json"), "--next-packet"); + h.Equal(0, first.ExitCode, "a large repository issues work: " + first.StdErr); + h.Equal(570, Number(first.Json, "examples"), "the scope is the whole repository"); + h.Equal(570, Number(first.Json, "unreviewed"), "nothing is assumed to be reviewed"); + h.True(Examples(first.Json).Count is >= 1 and <= 15, "the first packet is bounded"); + h.True(first.StdOut.Length < 32_000, $"the packet stays small ({first.StdOut.Length})"); + h.True(elapsed.Elapsed < TimeSpan.FromMinutes(1), $"the first packet is issued quickly ({elapsed.Elapsed})"); + h.Contains("--uid=", Text(first.Json["commands"]!, "runActions"), "run-action selectors use one argument per UID"); + + var init = Invoke(h, repo, "--operation", "repair-csrun", "--init-behavioral-ledger", Path.Combine(repo, "..", "large-init", "ledger.json"), "--json", "--quiet"); + h.Equal(1, init.ExitCode, "initialization is still incomplete"); + h.Equal(570, init.Json["summary"]!["examplesUnreviewed"]!.GetValue(), "bounded output keeps the full counts"); + h.Equal(570, init.Json["summary"]!["remainingDiagnosticsByCode"]!["BEHAVIORAL_REVIEW_INCOMPLETE"]!.GetValue(), "bounded output keeps the full diagnostic counts"); + h.Equal(10, init.Json["errors"]!.AsArray().Count(e => Text(e!, "code") == "BEHAVIORAL_REVIEW_INCOMPLETE"), "repeated diagnostics are bounded"); + h.True(init.Json["omittedFromOutput"]!.AsArray().Count > 0, "omissions are listed"); + h.True(init.StdOut.Length < 150_000, $"the initialization report stays readable ({init.StdOut.Length})"); + h.Equal("work-remaining", init.Json["nextAction"]!["state"]!.GetValue(), "initialization names the next work"); + } + + private static CliResult Save(DocfxTestHost h, string repo, string[] queue, List examples) + { + var reviews = new JsonArray(examples.Select(e => (JsonNode)new JsonObject + { + ["exampleId"] = Text(e, "exampleId"), + ["revision"] = Text(e, "revision"), + ["documentedOperation"] = "Synthetic documented operation", + ["consumerScenario"] = "Synthetic consumer scenario", + ["authoritativeEvidence"] = "src/Synthetic.cs: deterministic double for queue mechanics", + ["expectedObservation"] = "Synthetic expected observation", + ["actualObservation"] = "Synthetic actual observation", + ["executionCommand"] = "dotnet run synthetic.cs", + ["disposition"] = "verified-behavior" + }).ToArray()); + var path = Path.Combine(repo, "..", "reviews.json"); + File.WriteAllText(path, new JsonObject { ["reviews"] = reviews }.ToJsonString()); + return Invoke(h, repo, [.. queue, "--record-reviews", path]); + } + + private static List Examples(JsonObject response) => response["packet"]!["examples"]!.AsArray().Select(e => e!.AsObject()).ToList(); + + private static string Text(JsonNode node, string name) => node[name]!.GetValue(); + + private static int Number(JsonObject response, string name) => response["progress"]![name]!.GetValue(); + + internal static void CreateRepository(string repo, int projects, int examplesPerProject) + { + void Write(string path, string content) + { + var full = Path.Combine(repo, path.Replace('/', Path.DirectorySeparatorChar)); + Directory.CreateDirectory(Path.GetDirectoryName(full)!); + File.WriteAllText(full, content.Replace("\r\n", "\n"), new UTF8Encoding(false)); + } + + Write(".docfx/docfx.json", $$""" + { + "metadata": [ { "src": [ { "files": ["**/*.csproj"], "src": "../src" } ], "dest": "api" } ], + "build": { + "content": [ { "files": ["api/**/*.yml"], "exclude": ["api/namespaces/**", "api/types/**"] } ], + "overwrite": [ { "files": ["api/namespaces/**/*.md", "api/types/**/*.md"] } ], + "dest": "_site", + "template": ["default", "modern"] + } + } + """); + Write(".docfx/includes/availability.md", "Available on .NET 10.0.\n"); + for (var p = 0; p < projects; p++) + { + var ns = $"Acme.P{p:00}"; + Write($"src/{ns}/{ns}.csproj", """ + + + net10.0 + true + + + """); + Write($".docfx/api/namespaces/{ns}.md", $""" + --- + uid: {ns} + summary: *content + --- + The `{ns}` namespace stores small values for command-line reports and gives them back unchanged. Use it when a report needs a value without external dependencies. Start with `Box00`. + + [!INCLUDE [availability](../../includes/availability.md)] + """); + for (var e = 0; e < examplesPerProject; e++) + { + var type = $"Box{e:00}"; + Write($"src/{ns}/{type}.cs", $$""" + namespace {{ns}}; + + /// Stores a value for a report. + public sealed class {{type}} + { + /// Returns the value plus a fixed offset. + public int Read(int value) => value + {{e}}; + } + """); + Write($".docfx/api/types/{ns}.{type}.md", $$""" + --- + uid: {{ns}}.{{type}} + example: + - *content + --- + The following program creates a `{{type}}`, reads `3`, and prints the value to standard output. + + ```csharp + // Program.cs + using System; + using {{ns}}; + + var box = new {{type}}(); + Console.WriteLine($"Value={box.Read(3)}"); + ``` + """); + } + } + } +} diff --git a/scripts/tests/docfx-reporting-tests.cs b/scripts/tests/docfx-reporting-tests.cs index 24afcfc4..400d2ce0 100644 --- a/scripts/tests/docfx-reporting-tests.cs +++ b/scripts/tests/docfx-reporting-tests.cs @@ -1,4 +1,5 @@ #:property TargetFramework=net10.0 +#:property RollForward=Major #:property Nullable=enable #:property PublishAot=false diff --git a/scripts/tests/docfx-unit-tests.cs b/scripts/tests/docfx-unit-tests.cs index eea04ab7..35a1f6cc 100644 --- a/scripts/tests/docfx-unit-tests.cs +++ b/scripts/tests/docfx-unit-tests.cs @@ -1,5 +1,6 @@ #!/usr/bin/env dotnet #:property TargetFramework=net10.0 +#:property RollForward=Major #:property Nullable=enable #:property LangVersion=latest #:property PublishAot=false @@ -41,6 +42,7 @@ #:include docfx-unit/ScopeTestSupport.cs #:include docfx-unit/SymbolOwnershipTests.cs #:include docfx-unit/UidSelectorTests.cs +#:include docfx-unit/WorkPacketTests.cs using System.Collections; using System.Globalization; @@ -58,6 +60,7 @@ host.RunSuite("ReportModels", ReportModelsTests.Run); host.RunSuite("CliOptions", CliOptionsTests.Run); host.RunSuite("CompletionAndAssessmentQueue", CompletionAndAssessmentQueueTests.Run); +host.RunSuite("WorkPackets", WorkPacketTests.Run); host.RunSuite("MarkdownParsing", MarkdownParsingTests.Run); host.RunSuite("ApiNamingAndYaml", ApiNamingAndYamlTests.Run); host.RunSuite("DocfxConfigLayout", DocfxConfigLayoutTests.Run); diff --git a/scripts/tests/docfx-unit/BehavioralInventoryTests.cs b/scripts/tests/docfx-unit/BehavioralInventoryTests.cs index a04ce4d5..56132e8d 100644 --- a/scripts/tests/docfx-unit/BehavioralInventoryTests.cs +++ b/scripts/tests/docfx-unit/BehavioralInventoryTests.cs @@ -18,6 +18,10 @@ public static void Run(DocfxTestHost h) var sectionType = h.Type("OverwriteSection"); var skipEntryType = ScopeTarget.Model(h, "ApprovedSkipEntry"); + object? BuildInventory(params object?[] args) => + h.InvokeStatic(h.Type("DocfxBehavioralInventory"), "Build", + h.InvokeStatic(v, "CreateBehavioralInventoryInputs", [.. args, false])!); + var tempDir = Path.Combine(Path.GetTempPath(), "docfx-beh-inv-unit-" + Guid.NewGuid().ToString("N")); Directory.CreateDirectory(tempDir); try @@ -331,7 +335,7 @@ object MakeWs(List mdFiles) IList fullInventory; using (var lockStream = new FileStream(Path.Combine(srcB, "Helper.cs"), FileMode.Open, FileAccess.ReadWrite, FileShare.None)) { - fullInventory = (IList)h.InvokeStatic(v, "BuildBehavioralExampleInventory", + fullInventory = (IList)BuildInventory( ws, docfxWs, tempDir, fullScope, packets, gitState, null, apiModel, consumerSession)!; } @@ -381,7 +385,7 @@ object MakeWs(List mdFiles) // 2. Changed-only filtering + UID scope + Project/Overwrite/Namespace scope var changedSet = new HashSet(StringComparer.OrdinalIgnoreCase) { Path.GetFullPath(mdReader) }; - var changedInv = (IList)h.InvokeStatic(v, "BuildBehavioralExampleInventory", + var changedInv = (IList)BuildInventory( ws, docfxWs, tempDir, fullScope, packets, gitState, changedSet, null, null)!; h.Equal(2, changedInv.Count, "changedFiles restricts inventory to mdReader's 2 fences"); @@ -390,7 +394,7 @@ object MakeWs(List mdFiles) h.Set(uidScope, "ScopeRestricted", true); h.Set(uidScope, "HasUidScope", true); ((HashSet)h.GetObj(uidScope, "SelectedExampleIds")!).Add("Demo.Core.TokenReader#1"); - var uidInv = (IList)h.InvokeStatic(v, "BuildBehavioralExampleInventory", + var uidInv = (IList)BuildInventory( ws, docfxWs, tempDir, uidScope, packets, gitState, null, null, null)!; h.Equal(1, uidInv.Count, "UID scope selects exact example"); @@ -418,31 +422,31 @@ object MakeWs(List mdFiles) h.Set(narrowScope, "ScopeRestricted", true); ((HashSet)h.GetObj(narrowScope, "SelectedNamespaces")!).Add("Demo.Bad"); var narrowPackets = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(packetType))!; - var narrowInv = (IList)h.InvokeStatic(v, "BuildBehavioralExampleInventory", + var narrowInv = (IList)BuildInventory( ws, docfxWs, tempDir, narrowScope, narrowPackets, gitState, null, null, null)!; h.Equal(2, narrowInv.Count, "narrow namespace scope selects only Demo.Bad fences"); // Scope matching via selectedOverwritePaths + selectedProjectPaths - var broadScopedInv = (IList)h.InvokeStatic(v, "BuildBehavioralExampleInventory", + var broadScopedInv = (IList)BuildInventory( ws, docfxWs, tempDir, projScope, packets, gitState, null, null, null)!; h.True(broadScopedInv.Count >= 8, "project + namespace + overwrite scope includes matching items"); // 3. Invalid settings/manifest JSON + missing settings/manifest files File.WriteAllText(settingsPath, "{ broken json"); File.WriteAllText(manifestPath, "{ broken json"); - var corruptInv = (IList)h.InvokeStatic(v, "BuildBehavioralExampleInventory", + var corruptInv = (IList)BuildInventory( MakeWs(new List { mdSole }), docfxWs, tempDir, fullScope, narrowPackets, gitState, null, null, null)!; h.Equal(1, corruptInv.Count, "corrupt settings/manifest ignored gracefully"); File.WriteAllText(settingsPath, "{}"); File.WriteAllText(manifestPath, "{}"); - var noExamplesArrInv = (IList)h.InvokeStatic(v, "BuildBehavioralExampleInventory", + var noExamplesArrInv = (IList)BuildInventory( MakeWs(new List { mdSole }), docfxWs, tempDir, fullScope, narrowPackets, gitState, null, null, null)!; h.Equal(1, noExamplesArrInv.Count, "settings/manifest without examples array ignored gracefully"); File.Delete(settingsPath); File.Delete(manifestPath); - var noFilesInv = (IList)h.InvokeStatic(v, "BuildBehavioralExampleInventory", + var noFilesInv = (IList)BuildInventory( MakeWs(new List { mdSole }), docfxWs, tempDir, fullScope, narrowPackets, gitState, null, null, null)!; h.Equal(1, noFilesInv.Count, "missing settings/manifest files handled gracefully"); } diff --git a/scripts/tests/docfx-unit/BehavioralLedgerTests.cs b/scripts/tests/docfx-unit/BehavioralLedgerTests.cs index b789f3b1..31be8a1b 100644 --- a/scripts/tests/docfx-unit/BehavioralLedgerTests.cs +++ b/scripts/tests/docfx-unit/BehavioralLedgerTests.cs @@ -420,9 +420,9 @@ string GoodFields(string extra = "") => {"exampleId":"Unrev#1","disposition":"unreviewed"}, {"exampleId":"UnresNoOpen#1","disposition":"unresolved-finding"}, {"exampleId":"UnresWithOpen#1","disposition":"unresolved-finding","findings":["Broken output"]}, - {"exampleId":"UnavailReason#1","disposition":"unavailable-execution","unavailabilityReason":"Docker daemon unavailable"}, - {"exampleId":"UnavailObs#1","disposition":"unavailable-execution","actualObservation":"No Windows net48 runtime"}, - {"exampleId":"UnavailNone#1","disposition":"unavailable-execution"}, + {"exampleId":"UnavailReason#1","disposition":"unavailable-execution",{{GoodFields("\"unavailabilityReason\":\"Docker daemon unavailable\"")}}}, + {"exampleId":"UnavailObs#1","disposition":"unavailable-execution",{{GoodFields("\"actualObservation\":\"No Windows net48 runtime\"")}}}, + {"exampleId":"UnavailNone#1","disposition":"unavailable-execution",{{GoodFields()}}}, {"exampleId":"BadDisp#1","disposition":"skipped"}, {"exampleId":"StaleAll#1","disposition":"verified-behavior","file":"other.md","sourceSha256":"X","claimSha256":"X","dependencySha256":"X","recipeSha256":"X","executionTopology":"host","consumerApiCandidatesSha256":"X"}, {"exampleId":"StaleNullCand#1","disposition":"verified-behavior","sourceSha256":"SRC1","claimSha256":"CLM1","dependencySha256":"DEP1","recipeSha256":"RCP1","executionTopology":"standalone-console","consumerApiCandidatesSha256":"OLD"}, diff --git a/scripts/tests/docfx-unit/ExampleQualityValidationTests.cs b/scripts/tests/docfx-unit/ExampleQualityValidationTests.cs index d1bb0106..4c7474dd 100644 --- a/scripts/tests/docfx-unit/ExampleQualityValidationTests.cs +++ b/scripts/tests/docfx-unit/ExampleQualityValidationTests.cs @@ -3,6 +3,50 @@ internal static class ExampleQualityValidationTests { + // A call inside an interpolation hole runs; the same text anywhere else does not. + private static void InterpolatedStringUsage(DocfxTestHost h, Type v, Func codeOf) + { + foreach (var code in new[] + { + "Console.WriteLine($\"{Limit.Between(1, 2, 3)}\");", + "Console.WriteLine($\"{Limit.Between(1, 2, 3),10:N2} pages\");", + "Console.WriteLine($\"{{literal}} {Limit.Between(1, 2, 3)}\");", + "Console.WriteLine($@\"C:\\{Limit.Between(1, 2, 3)}\");", + "Console.WriteLine($\"{$\"{Limit.Between(1, 2, 3)}\"}\");", + "Console.WriteLine($\"{(true ? Limit.Between(1, 2, 3) : 0)}\");", + "Console.WriteLine($\"\"\"{Limit.Between(1, 2, 3)}\"\"\");", + "Console.WriteLine($$\"\"\"\n {{Limit.Between(1, 2, 3)}}\n \"\"\");" + }) + { + h.Equal(null, codeOf(code), "counts as use: " + code); + h.True((bool)h.InvokeStatic(v, "HasMethodInvocation", (string)h.InvokeStatic(v, "KeepExecutableCode", code)!, "Between")!, "counts as a call: " + code); + } + + foreach (var code in new[] + { + "Console.WriteLine(\"{Limit.Between(1, 2, 3)}\");", + "Console.WriteLine(@\"{Limit.Between(1, 2, 3)}\");", + "Console.WriteLine(\"\"\"{Limit.Between(1, 2, 3)}\"\"\");", + "Console.WriteLine($\"Limit.Between(1, 2, 3)\");", + "Console.WriteLine($\"{{Limit.Between(1, 2, 3)}}\");", + "Console.WriteLine($$\"\"\"{Limit.Between(1, 2, 3)}\"\"\");", + "Console.WriteLine($\"{\"Limit.Between(1, 2, 3)\"}\");", + "Console.WriteLine($\"{1 /* Limit.Between(1, 2, 3) */}\");", + "Console.WriteLine(1); // $\"{Limit.Between(1, 2, 3)}\"", + "/* $\"{Limit.Between(1, 2, 3)}\" */ Console.WriteLine(1);", + "/// Limit.Between(1, 2, 3)\nvoid Run() { Console.WriteLine(1); }", + "Console.WriteLine($\"{DateTime.Now:'Limit.Between('}\");" + }) + { + h.Equal("EXAMPLE_TARGET_NOT_USED", codeOf(code), "does not count as use: " + code); + h.False((bool)h.InvokeStatic(v, "HasMethodInvocation", (string)h.InvokeStatic(v, "KeepExecutableCode", code)!, "Between")!, "does not count as a call: " + code); + } + + h.Equal("EXAMPLE_TARGET_NOT_USED", codeOf("Console.WriteLine($\"{nameof(Limit)}\");"), "nameof inside a hole only names the type"); + h.Equal("EXAMPLE_TARGET_NOT_USED", codeOf("Console.WriteLine($\"{typeof(Limit)}\");"), "typeof inside a hole only names the type"); + h.Equal(null, codeOf("#if NET10_0_OR_GREATER\nConsole.WriteLine(Limit.Between(1, 2, 3));\n#endif"), "conditional code still counts"); + } + public static void Run(DocfxTestHost h) { var v = h.Type("DocfxExampleQualityValidator"); @@ -50,6 +94,11 @@ object EvalQuality(object section, object target, IReadOnlyList? related h.Contains("(valid)", stagesDesc, "DescribeExtensionCandidates valid"); h.Contains("(EXAMPLE_PLACEHOLDER)", stagesDesc, "DescribeExtensionCandidates fallback code"); + InterpolatedStringUsage(h, v, code => (string?)h.GetObj( + EvalQuality( + MakeSection("Demo.Limit", "The following program keeps a requested page size between one and one hundred.\n\n```csharp\n" + code + "\n```"), + MakeTarget("Demo.Limit", "Demo", typeKind, "Limit")), "Code")); + // 2. NormalizeExampleStructure h.Equal(string.Empty, (string)h.InvokeStatic(v, "NormalizeExampleStructure", "Plain text without code")!, "empty code structure"); var skelA = (string)h.InvokeStatic(v, "NormalizeExampleStructure", "```csharp\n// comment\nvar alpha = new Widget(42, 3.14, \"hello\");\nreturn alpha.Run();\n```")!; diff --git a/scripts/tests/docfx-unit/RunActionDependenciesTests.cs b/scripts/tests/docfx-unit/RunActionDependenciesTests.cs index ccc94ca9..2f22b360 100644 --- a/scripts/tests/docfx-unit/RunActionDependenciesTests.cs +++ b/scripts/tests/docfx-unit/RunActionDependenciesTests.cs @@ -43,6 +43,8 @@ public static void Run(DocfxTestHost h) Directory.Delete(root, recursive: true); } + UndeclaredPackages(h); + // Without platform assemblies or projects, the index is empty and MSBuild is never started. var empty = RunActionTarget.NewTempRoot("docfx-unit-run-action-empty"); try @@ -57,6 +59,62 @@ public static void Run(DocfxTestHost h) } } + // An example may import a namespace whose package no project references directly. + private static void UndeclaredPackages(DocfxTestHost h) + { + var repo = RunActionTarget.NewTempRoot("docfx-unit-run-action-undeclared"); + try + { + RunActionTarget.Write(repo, "src/Acme.Lib/Acme.Lib.csproj", + "net9.0;net10.0;netstandard2.01.0.0" + + ""); + RunActionTarget.Write(repo, "src/Acme.Lib/Api.cs", "namespace Acme.Lib; public sealed class Api { }"); + RunActionTarget.Write(repo, "src/Acme.Tools/Acme.Tools.csproj", + "net10.0" + + ""); + var index = RunActionTarget.BuildIndex(h, repo, RunActionTarget.ProjectInfoList(h), RunActionTarget.PlatformAssemblyPaths(), null); + var r = new RoslynTestHelper(h.Assembly); + string Summary(string imports) + { + using var result = JsonDocument.Parse(Resolve(h, r, index, imports + "\nusing Acme.Lib;\nvar api = new Api();", "Acme.Lib.Api", false, false)); + return string.Join(",", result.RootElement.GetProperty("dependsOn").EnumerateArray().Select(d => d.GetString())) + + " | " + string.Join(",", result.RootElement.GetProperty("errors").EnumerateArray().Select(e => e.GetString())); + } + + const string di = "using Microsoft.Extensions.DependencyInjection;"; + const string missingDi = "Acme.Lib@1.0.0 | missing-package: Microsoft.Extensions.DependencyInjection -> "; + h.Equal(missingDi, Summary(di), "a test SDK that only shares 'Microsoft' is never chosen"); + h.Equal("Acme.Lib@1.0.0 | ", Summary("using Microsoft.AspNetCore.Builder;\n" + di), "the ASP.NET Core framework contains Microsoft.Extensions"); + h.Equal("Acme.Lib@1.0.0,Contoso.Data.Sql@2.0.0 | ", Summary("using Contoso.Data.Core;"), "the closest related package is chosen, not the shortest"); + + // Contents of project.assets.json after a restore: Engine brings DI along on both modern frameworks. + static string Target(string framework, string extra) => + $"\"{framework}\":{{\"Engine/1.0.0\":{{\"type\":\"package\",\"dependencies\":{{\"Microsoft.Extensions.DependencyInjection\":\"10.0.0\"{extra}}}}}," + + "\"Microsoft.Extensions.DependencyInjection/10.0.0\":{\"type\":\"package\"},\"Only.Nine/1.0.0\":{\"type\":\"package\"},\"Hidden/1.0.0\":{\"type\":\"package\"}}"; + static string Framework(string framework, string engineAssets) => + $"\"{framework}\":{{\"dependencies\":{{\"Engine\":{{\"target\":\"Package\"{engineAssets}}},\"Hidden\":{{\"target\":\"Package\",\"suppressParent\":\"All\"}}}}}}"; + void Restore(string engineAssets) => RunActionTarget.Write(repo, "src/Acme.Lib/obj/project.assets.json", + "{\"targets\":{\".NETStandard,Version=v2.0\":{}," + Target("net9.0", ",\"Only.Nine\":\"1.0.0\"") + "," + Target("net10.0", "") + + "},\"project\":{\"frameworks\":{" + Framework("net9.0", engineAssets) + "," + Framework("net10.0", engineAssets) + "}}}"); + + Restore(""); + h.Equal("Acme.Lib@1.0.0 | ", Summary(di), "a package that comes along with a required project needs no pin"); + h.Equal("Acme.Lib@1.0.0 | missing-package: Only.Nine -> ", Summary("using Only.Nine;"), "a package must come along on every modern framework"); + h.Equal("Acme.Lib@1.0.0 | missing-package: Hidden -> ", Summary("using Hidden;"), "a private dependency does not reach consumers"); + Restore(",\"suppressParent\":\"Compile\""); + h.Equal(missingDi, Summary(di), "dependencies of a private dependency do not reach consumers"); + foreach (var broken in (string[])["{", "{}", "[]", "{\"targets\":[],\"project\":{\"frameworks\":{}}}"]) + { + RunActionTarget.Write(repo, "src/Acme.Lib/obj/project.assets.json", broken); + h.Equal(missingDi, Summary(di), "unusable restore output is no evidence"); + } + } + finally + { + Directory.Delete(repo, recursive: true); + } + } + private const string ExpectedIndex = """ {"RelPath":"src/Demo.Aspire/Demo.Aspire.csproj","AssemblyName":"Demo.Aspire.Runtime","PackageId":"Demo.Aspire.Package","IsPackable":true,"IsTest":false,"Version":null,"Sdk":"Microsoft.NET.Sdk.Web","TargetFrameworks":["net8.0"],"PackageReferences":["(Demo.External.Client, 2.5.0)","(Newtonsoft.Json, 12.0.1)","(System.CommandLine, 2.0.0)","(xunit.v3.assert, 4.0.3)","(Demo.Core, 3.0.0)"],"ProjectReferences":[],"FrameworkReferences":["Microsoft.AspNetCore.App"],"CentralPackageVersions":["Demo.External.Client=2.5.0","MinVer=6.0.0","Newtonsoft.Json=13.0.3"]} {"RelPath":"src/Demo.Cli/Demo.Cli.csproj","AssemblyName":"Demo.Cli","PackageId":"Demo.Cli","IsPackable":true,"IsTest":false,"Version":null,"Sdk":"Microsoft.NET.Sdk","TargetFrameworks":["net8.0"],"PackageReferences":[],"ProjectReferences":[],"FrameworkReferences":[],"CentralPackageVersions":["Demo.External.Client=2.5.0","MinVer=6.0.0","Newtonsoft.Json=13.0.3"]} @@ -113,7 +171,7 @@ public static void Run(DocfxTestHost h) {"dependsOn":[],"sdk":"Microsoft.NET.Sdk","frameworkReferences":[],"typeOwnership":[],"missingPackages":[],"ambiguousTypes":[],"unresolvedUsings":[],"unversionedPackages":[],"preflightPassed":true,"errors":[]} """, ["imports"] = """ - {"dependsOn":["Demo.Core@3.0.0","Newtonsoft.Json@12.0.1","System.CommandLine@2.0.0","xunit.v3@4.0.3"],"sdk":"Microsoft.NET.Sdk.Web","frameworkReferences":["Microsoft.AspNetCore.App"],"typeOwnership":[],"missingPackages":[{"type":"Contoso.Unknown","package":"unknown","reason":"unresolved-using","diagnostic":"missing-package: Contoso.Unknown -\u003E \u003Cunknown\u003E"},{"type":"xunit.v3.assert.Extra","package":"unknown","reason":"unresolved-using","diagnostic":"missing-package: xunit.v3.assert.Extra -\u003E \u003Cunknown\u003E"}],"ambiguousTypes":[],"unresolvedUsings":["Contoso.Unknown","xunit.v3.assert.Extra"],"unversionedPackages":[],"preflightPassed":false,"errors":["missing-package: Contoso.Unknown -\u003E \u003Cunknown\u003E","missing-package: xunit.v3.assert.Extra -\u003E \u003Cunknown\u003E"]} + {"dependsOn":["Demo.External.Client@2.5.0","Newtonsoft.Json@12.0.1","System.CommandLine@2.0.0","xunit.v3@4.0.3"],"sdk":"Microsoft.NET.Sdk.Web","frameworkReferences":["Microsoft.AspNetCore.App"],"typeOwnership":[],"missingPackages":[{"type":"Contoso.Unknown","package":"unknown","reason":"unresolved-using","diagnostic":"missing-package: Contoso.Unknown -\u003E \u003Cunknown\u003E"},{"type":"xunit.v3.assert.Extra","package":"unknown","reason":"unresolved-using","diagnostic":"missing-package: xunit.v3.assert.Extra -\u003E \u003Cunknown\u003E"}],"ambiguousTypes":[],"unresolvedUsings":["Contoso.Unknown","xunit.v3.assert.Extra"],"unversionedPackages":[],"preflightPassed":false,"errors":["missing-package: Contoso.Unknown -\u003E \u003Cunknown\u003E","missing-package: xunit.v3.assert.Extra -\u003E \u003Cunknown\u003E"]} """, ["namespace-only-repo"] = """ {"dependsOn":["Demo.Core@3.1.0","Demo.Dynamic","xunit.v3@4.0.3"],"sdk":"Microsoft.NET.Sdk.Web","frameworkReferences":[],"typeOwnership":[],"missingPackages":[{"type":"Demo.Web","package":"Demo.Web","project":"src/Demo.Web/Demo.Web.csproj","reason":"unpublished-project","diagnostic":"missing-package: Demo.Web -\u003E Demo.Web (unpublished project src/Demo.Web/Demo.Web.csproj)"}],"ambiguousTypes":[],"unresolvedUsings":[],"unversionedPackages":["Demo.Dynamic"],"preflightPassed":false,"errors":["missing-package: Demo.Web -\u003E Demo.Web (unpublished project src/Demo.Web/Demo.Web.csproj)"]} diff --git a/scripts/tests/docfx-unit/ScopeReportingTests.cs b/scripts/tests/docfx-unit/ScopeReportingTests.cs index 7caaae89..a06ba133 100644 --- a/scripts/tests/docfx-unit/ScopeReportingTests.cs +++ b/scripts/tests/docfx-unit/ScopeReportingTests.cs @@ -147,8 +147,8 @@ object ScopeReport(string mode, long? seed, params string[] uids) WriteManifest(h, manifestPath, f.Repo, Path.Combine(f.Docfx, "docfx.json"), scope, "build-backed", report); var manifestFull = Path.Combine(f.Repo, manifestPath); var reviewFull = Path.Combine(f.Repo, ".bot", "scope", "manifest.review.json"); - a.Equal(ExpectedManifest, Normalize(File.ReadAllText(manifestFull)), "the project manifest records scope, packets, dirty baseline and families"); - a.Equal(ExpectedReviewTemplate, Normalize(File.ReadAllText(reviewFull)), "a review template lists every selected packet's review pages"); + a.Equal(Normalize(ExpectedManifest), Normalize(File.ReadAllText(manifestFull)), "the project manifest records scope, packets, dirty baseline and families"); + a.Equal(Normalize(ExpectedReviewTemplate), Normalize(File.ReadAllText(reviewFull)), "a review template lists every selected packet's review pages"); a.Equal(".bot/scope/manifest.json|.bot/scope/manifest.review.json", $"{h.GetObj(report, "ProjectManifestPath")}|{h.GetObj(report, "ReviewReportPath")}", "the report names the manifest and its review report"); a.Equal($"docfx.cs --repo-root --resume-project-manifest \"{Path.GetFullPath(manifestFull)}\" --review-report \"{Path.GetFullPath(reviewFull)}\" --build-api-model --validate-samples --verify-docfx-build --json", h.GetObj(scope, "ResumeCommand"), "the scope report carries the full resume command"); diff --git a/scripts/tests/docfx-unit/WorkPacketTests.cs b/scripts/tests/docfx-unit/WorkPacketTests.cs new file mode 100644 index 00000000..1feeca62 --- /dev/null +++ b/scripts/tests/docfx-unit/WorkPacketTests.cs @@ -0,0 +1,911 @@ +using System.Collections; +using System.Diagnostics; +using System.Text.Json.Nodes; + +// Drives the work queue in process over a synthetic inventory. Every disposition written here is a +// deterministic double that exercises the queue; none of them is evidence that an example was verified. +internal static class WorkPacketTests +{ + public static T Identity(T item) => item; + + public static void Run(DocfxTestHost h) + { + var root = RunActionTarget.NewTempRoot("docfx-work-packets"); + try + { + StartIsActionableAndCannotComplete(h, root); + PacketsAreBoundedAndGroupedByProject(h, root); + UnfinishedPacketResumesAndFinishedPacketAdvances(h, root); + StaleEvidenceReenters(h, root); + BlockedWorkDoesNotStopIndependentWork(h, root); + RepeatedBlockersNeverAllowStopping(h, root); + ReportsNameTheNextStep(h, root); + FindingsCannotBeDropped(h, root); + InvalidReviewsAreRejected(h, root); + UnusableLedgersAreNeverOverwritten(h, root); + DiagnosticsComeBeforeTheFinalGate(h, root); + PartialRepairReconcilesBeforeFinalVerification(h, root); + LargeInventoryDrainsCompletely(h, root); + AutoLedgerPathsAreScopeSpecific(h, root); + ProgressIsAppendOnlyAndHeartbeats(h, root); + CommandQuotingHandlesApostrophes(h); + CommandLineContract(h); + } + finally + { + Directory.Delete(root, recursive: true); + } + } + + private sealed class Queue + { + private readonly DocfxTestHost _h; + private readonly Type _itemType; + private readonly Dictionary _options = new(); + + public Queue(DocfxTestHost h, string root, string name) + { + _h = h; + _itemType = h.Type("BehavioralInventoryItem"); + Root = Path.Combine(root, name); + Directory.CreateDirectory(Root); + } + + public string Root { get; } + public string Ledger => Path.Combine(Root, "session", "ledger.json"); + public string Operation { get; set; } = "repair-csrun"; + public List<(string Id, string Project, string Source, bool Changed, string Topology, int Lines)> Items { get; } = []; + public List Diagnostics { get; } = []; + + public void Add(string project, int count, bool changed = false, string topology = "standalone-console", int lines = 10) + { + for (var i = 0; i < count; i++) + { + Items.Add(($"{project}.Type{i:000}#1", $"src/{project}/{project}.csproj", "source-1", changed, topology, lines)); + } + } + + public void Edit(string id) + { + var index = Items.FindIndex(i => i.Id == id); + Items[index] = Items[index] with { Source = Items[index].Source + "x" }; + } + + public void SetOption(string name, object value) => _options[name] = value; + + public (int ExitCode, JsonObject Response) Next() => Advance(null); + + public (int ExitCode, JsonObject Response) Save(params JsonObject[] reviews) => + SaveText(new JsonObject { ["reviews"] = new JsonArray(reviews.Select(r => r.DeepClone()).ToArray()) }.ToJsonString()); + + public (int ExitCode, JsonObject Response) SaveText(string text) + { + var path = Path.Combine(Root, "reviews.json"); + File.WriteAllText(path, text); + return Advance(path); + } + + public (int ExitCode, JsonObject Response) Advance(string? reviewPath) + { + var context = CreateContext(reviewPath); + var result = _h.InvokeStatic(_h.Type("DocfxWorkPackets"), "Advance", context, Ledger)!; + return (_h.Get(result, "ExitCode"), _h.Get(result, "Response")); + } + + public (object Summary, object? NextAction) EvaluateFullVerification(params string[] extraDiagnosticCodes) + { + var context = CreateContext(null); + var options = _h.GetObj(context, "Options")!; + _h.Set(options, "BehavioralLedgerPath", Ledger); + foreach (var gate in new[] { "BuildApiModel", "ValidateSamples", "VerifyDocfxBuild" }) + { + _h.Set(options, gate, true); + } + + var report = _h.New(_h.Type("Report")); + _h.Set(report, "RepoRoot", Root); + _h.InvokeStatic(_h.Type("DocfxBehavioralLedger"), "Reconcile", Ledger, options, Root, + _h.GetObj(context, "DocfxPath"), _h.GetObj(context, "Scope"), _h.GetObj(context, "Inventory"), report); + var errors = (IList)_h.GetObj(report, "Errors")!; + var diagnosticType = _h.Type("Diagnostic"); + foreach (var code in extraDiagnosticCodes) + { + errors.Add(_h.New(diagnosticType, code, "page.md", null, "synthetic final verification diagnostic", null, null)); + } + + var exitCode = Enum.Parse(_h.Type("ExitCode"), errors.Count == 0 ? "Success" : "ValidationFailed"); + _h.InvokeStatic(_h.Type("DocfxCompletionEvaluator"), "Evaluate", options, report, exitCode); + var nextAction = _h.InvokeStatic(_h.Type("DocfxNextAction"), "Describe", options, report, exitCode); + return (_h.GetObj(report, "Summary")!, nextAction); + } + + private object CreateContext(string? reviewPath) + { + var options = _h.New(_h.Type("Options")); + _h.Set(options, "Operation", Operation); + _h.Set(options, "OperationExplicitlySpecified", true); + _h.Set(options, "RecordReviewsPath", reviewPath); + foreach (var (name, value) in _options) + { + _h.Set(options, name, value); + } + + var inventory = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(_itemType))!; + foreach (var item in Items) + { + inventory.Add(MakeItem(item)); + } + + var diagnosticType = _h.Type("Diagnostic"); + var diagnostics = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(diagnosticType))!; + foreach (var code in Diagnostics) + { + diagnostics.Add(_h.New(diagnosticType, code, "page.md", null, "synthetic diagnostic", null, null)); + } + + var funcType = typeof(Func<,>).MakeGenericType(_itemType, _itemType); + var identity = typeof(WorkPacketTests).GetMethod(nameof(Identity))!.MakeGenericMethod(_itemType); + var context = Activator.CreateInstance(_h.Type("WorkPacketContext"), nonPublic: true)!; + _h.Set(context, "Options", options); + _h.Set(context, "RepoRoot", Root); + _h.Set(context, "DocfxPath", Path.Combine(Root, ".docfx", "docfx.json")); + _h.Set(context, "Scope", ScopeTarget.Call(_h, "ToBehavioralLedgerScope", _h.New(ScopeTarget.Model(_h, "ScopePlan")))); + _h.Set(context, "Inventory", inventory); + _h.Set(context, "EvaluateCandidates", Delegate.CreateDelegate(funcType, identity)); + _h.Set(context, "Diagnostics", diagnostics); + _h.Set(context, "LedgerJsonOptions", new System.Text.Json.JsonSerializerOptions + { + WriteIndented = true, + PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase + }); + + return context; + } + + private object MakeItem((string Id, string Project, string Source, bool Changed, string Topology, int Lines) item) + { + var uid = item.Id[..item.Id.IndexOf('#')]; + var candidates = Activator.CreateInstance(typeof(List<>).MakeGenericType(_h.Type("ConsumerApiCandidateReport")))!; + var result = _h.New(_itemType, item.Id, uid, $".docfx/api/types/{uid}.md", 1, 10, item.Changed, item.Source, "claim-1", "dependency-1", "recipe-1", + item.Topology, true, new List { "native", "docker" }, candidates, null, new HashSet()); + _h.Set(result, "OwnerProjects", new[] { item.Project }); + _h.Set(result, "Code", string.Join('\n', Enumerable.Repeat("var x = 1;", item.Lines))); + return result; + } + } + + private static List Examples(JsonObject response) => + (response["packet"]?["examples"] as JsonArray)?.Select(e => e!.AsObject()).ToList() ?? []; + + private static List Ids(JsonObject response) => Examples(response).Select(e => Text(e, "exampleId")).ToList(); + + private static string Text(JsonNode node, string name) => node[name]!.GetValue(); + + private static bool Flag(JsonObject response, string name) => response[name]!.GetValue(); + + private static int Number(JsonObject response, string name) => response["progress"]![name]!.GetValue(); + + private static JsonObject Verified(JsonObject example) => new() + { + ["exampleId"] = Text(example, "exampleId"), + ["revision"] = Text(example, "revision"), + ["documentedOperation"] = "Synthetic documented operation", + ["consumerScenario"] = "Synthetic consumer scenario", + ["authoritativeEvidence"] = "src/Synthetic.cs: deterministic double for queue mechanics", + ["expectedObservation"] = "Synthetic expected observation", + ["actualObservation"] = "Synthetic actual observation", + ["executionCommand"] = "dotnet run synthetic.cs", + ["disposition"] = "verified-behavior", + ["transportStatus"] = new JsonObject { ["native"] = "Verified", ["docker"] = "Verified" } + }; + + private static JsonObject With(JsonObject review, string name, JsonNode? value) + { + review[name] = value; + return review; + } + + // Writes a new capture, because an attempt counts only with output that was captured for it. + private static JsonObject Blocked(Queue queue, JsonObject example, string command) + { + Thread.Sleep(50); + var capture = Path.Combine(queue.Root, $"capture-{Guid.NewGuid():N}.txt"); + File.WriteAllText(capture, "Synthetic output of " + command); + return BlockedBy(example, new JsonObject + { + ["action"] = "Synthetic attempt to start the service", + ["command"] = command, + ["exitCode"] = 1, + ["evidencePath"] = capture + }); + } + + private static JsonObject BlockedBy(JsonObject example, JsonNode? attempt) => + With(With(With(Verified(example), "disposition", "unavailable-execution"), "unavailabilityReason", "Synthetic: the required service is not installed"), "recoveryAttempt", attempt); + + private static JsonObject Finding(JsonObject example, string status) => + With(With(Verified(example), "disposition", status == "open" ? "unresolved-finding" : "verified-behavior"), "findings", + new JsonArray(new JsonObject { ["id"] = "F-1", ["status"] = status, ["summary"] = "Synthetic finding" })); + + private static JsonObject[] VerifyAll(JsonObject response) => [.. Examples(response).Select(Verified)]; + + private static void StartIsActionableAndCannotComplete(DocfxTestHost h, string root) + { + var queue = new Queue(h, root, "start"); + queue.Add("Demo.A", 3); + var (exit, response) = queue.Next(); + h.Equal(0, exit, "a packet with outstanding work is a successful command"); + h.Equal("review", Text(response, "phase"), "outstanding work starts in the review phase"); + h.False(Flag(response, "stopAllowed"), "initialization is not a stopping point"); + h.False(Flag(response, "canClaimCompletion"), "zero findings before review does not permit completion"); + h.Equal(0, Number(response, "reviewed"), "nothing is reviewed yet"); + h.Equal(0, Number(response, "openFindings"), "no findings exist before review"); + h.Equal(3, Examples(response).Count, "the packet contains the next work"); + h.Contains("not a stopping point", Text(response, "nextAction"), "the next action says that work continues"); + h.Contains("--record-reviews", Text(response["commands"]!, "save"), "the save command is copy-ready"); + h.True(File.Exists(queue.Ledger), "the ledger is persisted before any review"); + } + + private static void PacketsAreBoundedAndGroupedByProject(DocfxTestHost h, string root) + { + var queue = new Queue(h, root, "bounds"); + queue.Add("Demo.A", 40, lines: 1); + queue.Add("Demo.Changed", 2, changed: true); + var first = queue.Next().Response; + h.Equal("src/Demo.Changed/Demo.Changed.csproj", Text(first["packet"]!, "project"), "changed examples come first"); + h.Equal(2, Examples(first).Count, "a packet stays inside one owning project"); + h.Equal(42, Number(first, "examples"), "unchanged examples stay in scope"); + h.Equal(15, Examples(queue.Save(VerifyAll(first)).Response).Count, "small examples fill a packet up to the maximum"); + + var heavy = new Queue(h, root, "heavy"); + heavy.Add("Demo.Heavy", 20, topology: "host", lines: 80); + h.True(Examples(heavy.Next().Response).Count is >= 3 and <= 5, "large host examples make smaller packets"); + + var huge = new Queue(h, root, "huge"); + huge.Add("Demo.Huge", 2, lines: 5000); + h.Equal(1, Examples(huge.Next().Response).Count, "one oversized example still forms a packet"); + + var forced = new Queue(h, root, "forced"); + forced.Add("Demo.Forced", 20, lines: 500); + forced.SetOption("PacketSize", 7); + h.Equal(7, Examples(forced.Next().Response).Count, "--packet-size sets the number of examples"); + } + + private static void UnfinishedPacketResumesAndFinishedPacketAdvances(DocfxTestHost h, string root) + { + var queue = new Queue(h, root, "resume"); + queue.Add("Demo.A", 12, lines: 1); + queue.Add("Demo.B", 12, lines: 1); + var first = queue.Next().Response; + h.False(first["session"]!["resumed"]!.GetValue(), "the first call starts a session"); + + var partial = queue.Save([.. Examples(first).Take(5).Select(Verified)]).Response; + h.Equal(7, Examples(partial).Count, "the unfinished part of the packet comes back"); + h.Equal(1, partial["packet"]!["number"]!.GetValue(), "the unfinished packet keeps its number"); + + // An interrupted session has nothing but the ledger on disk. + var resumed = queue.Next().Response; + h.True(resumed["session"]!["resumed"]!.GetValue(), "an interrupted session resumes from the ledger"); + h.Equal(string.Join('|', Ids(partial)), string.Join('|', Ids(resumed)), "resuming continues the same packet"); + h.Equal(5, Number(resumed, "behaviorVerified"), "current evidence is kept and not re-reviewed"); + + var next = queue.Save(VerifyAll(resumed)).Response; + h.Equal("review", Text(next, "phase"), "one finished project does not finish the run"); + h.Equal(2, next["packet"]!["number"]!.GetValue(), "the next packet is issued"); + h.Equal("src/Demo.B/Demo.B.csproj", Text(next["packet"]!, "project"), "the next project is exposed"); + h.Equal(0, Ids(next).Intersect(Ids(first)).Count(), "finished examples are not issued again"); + h.Equal(24, Number(next, "examples"), "the scope never shrinks"); + + var done = queue.Save(VerifyAll(next)).Response; + h.Equal("final-gate", Text(done, "phase"), "an empty queue leads to the final gate"); + h.False(Flag(done, "canClaimCompletion"), "an empty queue is not completion"); + h.False(Flag(done, "stopAllowed"), "an empty queue is not a stopping point"); + foreach (var flag in new[] { "--behavioral-ledger", "--build-api-model", "--validate-samples", "--verify-docfx-build" }) + { + h.Contains(flag, Text(done["commands"]!, "finalGate"), "the final gate command keeps every gate"); + } + } + + private static void StaleEvidenceReenters(DocfxTestHost h, string root) + { + var queue = new Queue(h, root, "stale"); + queue.Add("Demo.A", 4); + h.Equal("final-gate", Text(queue.Save(VerifyAll(queue.Next().Response)).Response, "phase"), "all examples have current evidence"); + queue.Edit("Demo.A.Type002#1"); + var stale = queue.Next().Response; + h.Equal("review", Text(stale, "phase"), "stale evidence reopens the queue"); + h.Equal("Demo.A.Type002#1", string.Join('|', Ids(stale)), "only the changed example re-enters"); + h.Equal(1, stale["staleEvidence"]!["count"]!.GetValue(), "the stale example is reported"); + h.Contains("sourceSha256", Text(stale["staleEvidence"]!["examples"]![0]!, "changed"), "the reason is reported"); + h.Equal(3, Number(stale, "behaviorVerified"), "unaffected evidence is preserved"); + } + + private static void BlockedWorkDoesNotStopIndependentWork(DocfxTestHost h, string root) + { + var queue = new Queue(h, root, "blocked"); + queue.Add("Demo.A", 2); + queue.Add("Demo.B", 2); + var first = Examples(queue.Next().Response); + var next = queue.Save(Blocked(queue, first[0], "start service"), Verified(first[1])).Response; + h.Equal("review", Text(next, "phase"), "independent work continues past a blocker"); + h.Equal("Demo.B.Type000#1", Ids(next)[0], "the next project is issued"); + h.Equal(1, Number(next, "blocked"), "the blocker is counted separately"); + h.Equal(1, next["blocked"]!["count"]!.GetValue(), "the blocker is reported with its reason"); + h.False(Flag(next, "stopAllowed"), "one blocker does not allow stopping"); + + var retry = queue.Save(VerifyAll(next)).Response; + h.Equal("retry-blocked", Text(retry, "phase"), "a blocker is tried again before it can be handed over"); + h.False(Flag(retry, "stopAllowed"), "a blocker that was tried once does not allow stopping"); + h.Equal("start service", Text(Examples(retry)[0]["attempts"]![0]!, "command"), "the earlier attempt is shown"); + var exhausted = queue.Save(Blocked(queue, Examples(retry)[0], "install service")).Response; + h.Equal("blocked", Text(exhausted, "phase"), "only blockers with two different failed attempts remain"); + h.Equal(2, exhausted["blocked"]!["reasons"]![0]!["attempts"]!.AsArray().Count, "both attempts are reported"); + h.False(Flag(exhausted, "stopAllowed"), "exhausted blockers still require final verification"); + h.False(Flag(exhausted, "canClaimCompletion"), "a blocker never permits a completion claim"); + h.Contains("Run commands.finalGate", Text(exhausted, "nextAction"), "a handoff still needs the final gate"); + + queue.SetOption("RetryBlocked", true); + var explicitRetry = queue.Next().Response; + h.Equal("retry-blocked", Text(explicitRetry, "phase"), "--retry-blocked reopens blocked work"); + queue.SetOption("RetryBlocked", false); + h.Equal("final-gate", Text(queue.Save(VerifyAll(explicitRetry)).Response, "phase"), "a resolved blocker completes the queue"); + + // Missing evidence must not be disguised as a blocker. + var missing = new Queue(h, root, "missing"); + missing.Add("Demo.A", 1); + var example = Examples(missing.Next().Response)[0]; + var unexecuted = missing.Save(With(Verified(example), "transportStatus", new JsonObject { ["native"] = "Verified", ["docker"] = "Unverified" })).Response; + h.Equal("review", Text(unexecuted, "phase"), "an unverified transport is still active work"); + h.Equal(1, Number(unexecuted, "evidenceMissing"), "an unverified transport counts as missing evidence"); + h.Equal(0, Number(unexecuted, "blocked"), "an unverified transport is not a blocker"); + } + + private static void RepeatedBlockersNeverAllowStopping(DocfxTestHost h, string root) + { + var queue = new Queue(h, root, "repeated"); + queue.Add("Demo.A", 1); + var example = Examples(queue.Next().Response)[0]; + + void Refused(JsonObject review, string expected, string context) + { + var (exit, response) = queue.Save(review); + h.Equal(1, exit, context + " is refused"); + h.Contains(expected, Text(response["saved"]![0]!, "detail"), context + " explains why"); + h.False(Flag(response, "stopAllowed"), context + " does not allow stopping"); + } + + JsonObject Changed(string name, JsonNode? value) + { + var review = Blocked(queue, example, "start service"); + review["recoveryAttempt"]!.AsObject()[name] = value; + return review; + } + + Refused(BlockedBy(example, null), "needs a 'recoveryAttempt'", "a blocker without an attempt"); + Refused(Changed("action", "tried"), "needs an 'action'", "a vague action"); + Refused(Changed("command", " "), "needs an 'action'", "a missing command"); + Refused(Changed("exitCode", 0), "failing exit code", "a successful attempt"); + Refused(Changed("exitCode", "1"), "failing exit code", "a textual exit code"); + Refused(Changed("evidencePath", "absent.txt"), "captured output", "a missing capture"); + Refused(Changed("note", "x"), "Unknown 'recoveryAttempt' field", "an unknown attempt field"); + Refused(With(Verified(example), "recoveryAttempt", new JsonObject()), "only for unavailable-execution", "an attempt on a verified example"); + var old = Blocked(queue, example, "start service"); + File.SetLastWriteTimeUtc(Text(old["recoveryAttempt"]!, "evidencePath"), DateTime.UtcNow.AddHours(-1)); + Refused(old, "is older than", "a capture from before the session"); + + var first = Blocked(queue, example, "start service"); + var capture = Text(first["recoveryAttempt"]!, "evidencePath"); + h.Equal("retry-blocked", Text(queue.Save(first).Response, "phase"), "one attempt is not enough"); + for (var i = 0; i < 5; i++) + { + Refused(first, "already recorded", "sending the same review again"); + Refused(Blocked(queue, example, "START service"), "already recorded", "sending the same command again"); + } + + var recycled = Blocked(queue, example, "install service"); + recycled["recoveryAttempt"]!["evidencePath"] = capture; + Refused(recycled, "is older than", "reusing the capture of an earlier attempt"); + h.Equal("retry-blocked", Text(queue.Next().Response, "phase"), "the example stays in the queue"); + h.Equal("blocked", Text(queue.Save(Blocked(queue, example, "install service")).Response, "phase"), "a second, different attempt counts"); + + // An attempt counts only while its captured output is intact. + File.AppendAllText(capture, "changed"); + h.Equal("retry-blocked", Text(queue.Next().Response, "phase"), "an altered capture no longer counts"); + File.Delete(capture); + h.False(Flag(queue.Next().Response, "stopAllowed"), "a deleted capture no longer counts"); + + // A changed example starts over, because the old attempts belong to the old code. + h.Equal("blocked", Text(queue.Save(Blocked(queue, example, "start service")).Response, "phase"), "a new attempt replaces the lost one"); + queue.Edit("Demo.A.Type000#1"); + var restarted = queue.Next().Response; + h.Equal("review", Text(restarted, "phase"), "a changed example is reviewed again"); + h.True(Examples(restarted)[0]["attempts"] is null, "old attempts do not carry over"); + } + + private static void ReportsNameTheNextStep(DocfxTestHost h, string root) + { + (string State, bool StopAllowed, string? Command) Describe(string exitCode, Action configure, params string[] errors) + { + var options = h.New(h.Type("Options")); + h.Set(options, "Operation", "repair-csrun"); + h.Set(options, "BehavioralLedgerPath", "session/ledger.json"); + var report = h.New(h.Type("Report")); + h.Set(report, "RepoRoot", root); + var list = (IList)h.GetObj(report, "Errors")!; + foreach (var error in errors) + { + list.Add(h.New(h.Type("Diagnostic"), error, "page.md", null, "synthetic", null, null)); + } + + configure(report); + var next = h.InvokeStatic(h.Type("DocfxNextAction"), "Describe", options, report, Enum.Parse(h.Type("ExitCode"), exitCode))!; + return (h.Get(next, "State"), h.Get(next, "StopAllowed"), h.GetObj(next, "Command") as string); + } + + void Summary(object report, string name, object value) => h.Set(h.GetObj(report, "Summary")!, name, value); + + var stale = Describe("ValidationFailed", r => Summary(r, "BehavioralEvidenceStale", 1), "BEHAVIORAL_EVIDENCE_STALE"); + h.Equal("work-remaining", stale.State, "stale evidence at the final gate is work"); + h.Contains("session/ledger.json --next-packet", stale.Command!, "the next step keeps the same ledger"); + + var unverified = Describe("ValidationFailed", r => Summary(r, "BehavioralEvidenceMissing", 1), "BEHAVIORAL_TRANSPORT_UNVERIFIED"); + h.Equal("work-remaining", unverified.State, "an unverified transport at the final gate is work"); + + foreach (var exitCode in new[] { "ValidationFailed", "SampleCompilationFailed" }) + { + var failed = Describe(exitCode, _ => { }, "SAMPLE_COMPILE_FAILED"); + h.Equal("repair-diagnostics", failed.State, "a failed final gate is repair work"); + h.False(failed.StopAllowed, "a failed final gate is not a stopping point"); + h.Contains("--next-packet", failed.Command!, "fixed examples go back through the queue"); + } + + var early = Describe("BuildFailed", _ => { }); + h.Equal("repair-diagnostics", early.State, "an early stop still has a next step"); + h.Contains("--next-packet", early.Command!, "an early stop names its command"); + h.Equal(null, Describe("RepoRootMissing", r => h.Set(r, "RepoRoot", string.Empty)).Command, "an invalid root has no command to run"); + + var blocked = Describe("ValidationFailed", r => Summary(r, "BehavioralEvidenceMissing", 1), "BEHAVIORAL_EVIDENCE_UNAVAILABLE"); + h.Equal("blocked", blocked.State, "only blocked examples are left"); + h.False(blocked.StopAllowed, "unconfirmed blocker recovery cannot authorize stopping"); + h.Contains("--next-packet", blocked.Command!, "the queue checks the attempts"); + var terminalBlocker = Describe("ValidationFailed", r => + { + Summary(r, "BehavioralEvidenceMissing", 1); + Summary(r, "FullVerificationRan", true); + h.Set(r, "BehavioralBlockersExhausted", true); + }, "BEHAVIORAL_EVIDENCE_UNAVAILABLE"); + h.True(terminalBlocker.StopAllowed, "final verification and exhausted recovery allow an incomplete handoff"); + h.Equal(null, terminalBlocker.Command, "an exhausted blocker after final verification has no automatic retry"); + h.Equal("repair-diagnostics", Describe("ValidationFailed", r => Summary(r, "BehavioralEvidenceMissing", 1), "BEHAVIORAL_EVIDENCE_UNAVAILABLE", "SAMPLE_COMPILE_FAILED").State, + "a blocker does not hide other repairs"); + h.Equal("work-remaining", Describe("ValidationFailed", r => Summary(r, "BehavioralEvidenceMissing", 2), "BEHAVIORAL_EVIDENCE_UNAVAILABLE", "BEHAVIORAL_EVIDENCE_MISSING").State, + "a blocker does not hide other reviews"); + + var gates = Describe("Success", _ => { }); + h.Equal("final-gate", gates.State, "missing gates are the next step"); + h.Contains("--verify-docfx-build", gates.Command!, "the final gate runs every check"); + var done = Describe("Success", r => Summary(r, "CanClaimCompletion", true)); + h.Equal("complete", done.State, "only the completion flag ends the work"); + h.True(done.StopAllowed, "completed work may stop"); + } + + private static void FindingsCannotBeDropped(DocfxTestHost h, string root) + { + var queue = new Queue(h, root, "findings"); + queue.Add("Demo.A", 2); + var examples = Examples(queue.Next().Response); + var repair = queue.Save(Finding(examples[0], "open"), Verified(examples[1])).Response; + h.Equal("repair-findings", Text(repair, "phase"), "open findings are the next work"); + var again = queue.Save(With(Verified(Examples(repair)[0]), "findings", new JsonArray())).Response; + h.Equal("repair-findings", Text(again, "phase"), "omitting a finding does not close it"); + var closed = queue.Save(Finding(Examples(again)[0], "repaired")).Response; + h.Equal("final-gate", Text(closed, "phase"), "a repaired finding leaves the queue"); + h.Equal(1, Number(closed, "repaired"), "the repair is counted"); + + var removed = new Queue(h, root, "removed"); + removed.Add("Demo.A", 2); + examples = Examples(removed.Next().Response); + removed.Save(Finding(examples[0], "open"), Verified(examples[1])); + removed.Items.RemoveAt(0); + var orphaned = removed.Next().Response; + h.Equal("ledger-issues", Text(orphaned, "phase"), "removing an example does not close its finding"); + h.Contains("--record-reviews", Text(orphaned["commands"]!, "save"), "a removed finding has a command for recording its disposition"); + var settled = removed.Save(new JsonObject + { + ["exampleId"] = "Demo.A.Type000#1", + ["findings"] = new JsonArray(new JsonObject { ["id"] = "F-1", ["status"] = "inapplicable", ["summary"] = "The example was removed" }) + }).Response; + h.Equal("final-gate", Text(settled, "phase"), "a settled finding releases the removed example"); + } + + private static void InvalidReviewsAreRejected(DocfxTestHost h, string root) + { + var queue = new Queue(h, root, "invalid"); + queue.Add("Demo.A", 3); + var examples = Examples(queue.Next().Response); + + void Rejected(JsonObject review, string expected, string context) + { + var (exit, response) = queue.Save(review); + h.Equal(1, exit, context + " exits 1"); + h.False(response["saved"]![0]!["saved"]!.GetValue(), context + " is not saved"); + h.Contains(expected, Text(response["saved"]![0]!, "detail"), context + " explains why"); + h.Equal(3, Number(response, "unreviewed"), context + " leaves the example unreviewed"); + } + + Rejected(With(Verified(examples[0]), "revision", "0000000000000000"), "changed after this revision", "an outdated revision"); + Rejected(With(Verified(examples[0]), "revision", null), "'revision' is missing", "a missing revision"); + Rejected(With(Verified(examples[0]), "exampleId", "Demo.Other#1"), "not in the active scope", "an unknown example"); + Rejected(With(Verified(examples[0]), "disposition", "unreviewed"), "'disposition' must be", "an unreviewed disposition"); + Rejected(With(Verified(examples[0]), "observed", "typo"), "Unknown field", "an unknown field"); + Rejected(With(Verified(examples[0]), "expectedObservation", 42), "must be text", "a non-text field"); + Rejected(With(Verified(examples[0]), "transportStatus", new JsonObject { ["wsl"] = "Verified" }), "'transportStatus' may only", "an unknown transport"); + Rejected(With(Verified(examples[0]), "findings", "none"), "'findings' must be", "malformed findings"); + Rejected(With(BlockedBy(examples[0], null), "unavailabilityReason", null), "needs a concrete", "a blocker without a reason"); + + var mixed = queue.Save(Verified(examples[0]), With(Verified(examples[1]), "revision", "bad"), Verified(examples[0])); + h.Equal(1, mixed.ExitCode, "a partly rejected file exits 1"); + h.Equal(1, Number(mixed.Response, "behaviorVerified"), "valid reviews in the same file are saved"); + var before = File.ReadAllText(queue.Ledger); + foreach (var text in new[] { "not json", "{}", "{\"reviews\":[]}", "{\"reviews\":[{}]}" }) + { + var (exit, response) = queue.SaveText(text); + h.Equal(1, exit, "a malformed review file exits 1"); + h.Equal("command-error", Text(response, "phase"), "a malformed review file is a command error"); + } + + h.Equal("command-error", Text(queue.Advance(Path.Combine(queue.Root, "absent.json")).Response, "phase"), "a missing review file is a command error"); + h.Equal(before, File.ReadAllText(queue.Ledger), "a malformed review file changes nothing"); + } + + private static void UnusableLedgersAreNeverOverwritten(DocfxTestHost h, string root) + { + foreach (var content in new[] { "{ broken", "[]", "{\"schemaVersion\":1}", "{\"schemaVersion\":2,\"examples\":[]}", "{\"schemaVersion\":1.5,\"examples\":[]}" }) + { + var queue = new Queue(h, root, "ledger-" + content.Length); + queue.Add("Demo.A", 1); + Directory.CreateDirectory(Path.GetDirectoryName(queue.Ledger)!); + File.WriteAllText(queue.Ledger, content); + var (exit, response) = queue.Next(); + h.Equal(1, exit, "an unusable ledger exits 1"); + h.Equal("command-error", Text(response, "phase"), "an unusable ledger is a command error"); + h.Equal(content, File.ReadAllText(queue.Ledger), "an unusable ledger is left unchanged"); + } + + var other = new Queue(h, root, "ledger-operation"); + other.Add("Demo.A", 1); + other.Save(VerifyAll(other.Next().Response)); + var recorded = File.ReadAllText(other.Ledger); + other.Operation = "repair"; + h.Equal("command-error", Text(other.Next().Response, "phase"), "a ledger of another operation is refused"); + h.Equal(recorded, File.ReadAllText(other.Ledger), "a ledger of another operation is left unchanged"); + } + + private static void DiagnosticsComeBeforeTheFinalGate(DocfxTestHost h, string root) + { + var queue = new Queue(h, root, "diagnostics"); + queue.Add("Demo.A", 1); + queue.Diagnostics.AddRange(Enumerable.Repeat("SYNTHETIC_ERROR", 30)); + var first = queue.Next().Response; + h.Equal("review", Text(first, "phase"), "diagnostics do not hide review work"); + h.Equal(30, first["diagnostics"]!["count"]!.GetValue(), "all diagnostics are counted"); + h.Equal(10, first["diagnostics"]!["first"]!.AsArray().Count, "the listed diagnostics are bounded"); + var repair = queue.Save(VerifyAll(first)).Response; + h.Equal("repair-diagnostics", Text(repair, "phase"), "remaining diagnostics are the next work"); + h.False(Flag(repair, "stopAllowed"), "diagnostics are not a stopping point"); + queue.Diagnostics.Clear(); + h.Equal("final-gate", Text(queue.Next().Response, "phase"), "the final gate follows clean diagnostics"); + } + + private static void LargeInventoryDrainsCompletely(DocfxTestHost h, string root) + { + var queue = new Queue(h, root, "large"); + for (var project = 0; project < 42; project++) + { + queue.Add($"Demo.P{project:00}", project < 24 ? 14 : 13, changed: project == 41, topology: project % 9 == 0 ? "host" : "standalone-console", lines: 5 + project); + } + + h.Equal(570, queue.Items.Count, "the synthetic inventory matches a large repository"); + var elapsed = Stopwatch.StartNew(); + var issued = new HashSet(StringComparer.Ordinal); + var response = queue.Next().Response; + h.Equal("src/Demo.P41/Demo.P41.csproj", Text(response["packet"]!, "project"), "changed work starts a large run"); + var packets = 0; + string? blockedId = null; + while (Text(response, "phase") == "review") + { + packets++; + var examples = Examples(response); + h.True(examples.Count is >= 1 and <= 15, "every packet stays bounded"); + h.Equal(1, examples.Select(e => Text(e, "exampleId").Split(".Type")[0]).Distinct().Count(), "every packet stays in one project"); + h.True(examples.All(e => issued.Add(Text(e, "exampleId"))), "no finished example is issued again"); + h.Equal(570, Number(response, "examples"), "the repository-wide scope stays intact"); + h.Equal(570 - issued.Count + examples.Count, Number(response, "unreviewed"), "remaining work is exact"); + h.False(Flag(response, "stopAllowed"), "no packet is a stopping point"); + h.True(response["commands"]!["finalGate"] is null, "full verification is offered only after actionable work drains"); + if (packets == 20) + { + var resumed = queue.Next().Response; + h.True(Ids(response).SequenceEqual(Ids(resumed)), "a mid-run interruption resumes the next unsaved packet"); + h.Equal(Number(response, "behaviorVerified"), Number(resumed, "behaviorVerified"), "a resumed large run keeps its current counts"); + var (premature, prematureAction) = queue.EvaluateFullVerification(); + h.True(h.Get(premature, "DeterministicGatesPassed"), "mid-run deterministic checks can be green in a large inventory"); + h.False(h.Get(premature, "CanClaimCompletion"), "mid-run green checks cannot close a 570-example inventory"); + h.Equal("work-remaining", h.Get(prematureAction!, "State"), "mid-run full verification returns the work-remaining state"); + h.False(h.Get(prematureAction!, "StopAllowed"), "mid-run full verification does not authorize stopping"); + h.Contains("--next-packet", h.Get(prematureAction!, "Command"), "mid-run full verification points back to the queue"); + } + h.True(((string)h.InvokeStatic(h.Type("DocfxWorkPackets"), "Serialize", response)!).Length < 32_000, "every packet response stays small"); + if (packets == 1) + { + blockedId = Text(examples[0], "exampleId"); + response = queue.Save([Blocked(queue, examples[0], "start fixture service"), .. examples.Skip(1).Select(Verified)]).Response; + h.Equal(1, Number(response, "blocked"), "one blocked example does not halt a large run"); + h.Equal("review", Text(response, "phase"), "independent work continues across a large inventory"); + } + else + { + var reviewedBefore = Number(response, "behaviorVerified"); + response = queue.Save(VerifyAll(response)).Response; + h.True(Number(response, "behaviorVerified") > reviewedBefore, "saving a packet advances the reconciled completion count"); + } + } + + h.Equal(570, issued.Count, "every example was issued exactly once"); + h.Equal("retry-blocked", Text(response, "phase"), "the large queue returns to the blocked example after independent work drains"); + h.Equal(569, Number(response, "behaviorVerified"), "all 569 independent examples have current evidence"); + response = queue.Save(VerifyAll(response)).Response; + h.Equal("final-gate", Text(response, "phase"), "the drained large queue leads to the final gate"); + h.Equal(570, Number(response, "behaviorVerified"), "the synthetic dispositions are all recorded"); + var (largeFinal, largeFinalAction) = queue.EvaluateFullVerification(); + h.True(h.Get(largeFinal, "CanClaimCompletion"), "final verification closes the 570-example inventory"); + h.True(h.Get(largeFinalAction!, "StopAllowed"), "completed 570-example verification authorizes stopping"); + + queue.Edit(blockedId!); + var (largeAfterEdit, largeEditAction) = queue.EvaluateFullVerification(); + h.Equal(1, h.Get(largeAfterEdit, "BehavioralEvidenceStale"), "post-verification edit invalidates only the edited example at 570 scale"); + h.False(h.Get(largeAfterEdit, "CanClaimCompletion"), "a stale 570-example verification report cannot claim completion"); + h.False(h.Get(largeEditAction!, "StopAllowed"), "a post-verification edit reopens execution"); + var largeReopened = queue.Next().Response; + h.Equal(blockedId!, Ids(largeReopened).Single(), "only the edited example re-enters the 570-example queue"); + h.Equal(569, Number(largeReopened, "behaviorVerified"), "the 569 unchanged examples keep current evidence"); + h.True(packets is >= 42 and <= 130, $"the packet count is reasonable ({packets})"); + h.True(elapsed.Elapsed < TimeSpan.FromMinutes(2), $"draining stays fast ({elapsed.Elapsed})"); + } + + private static void PartialRepairReconcilesBeforeFinalVerification(DocfxTestHost h, string root) + { + var queue = new Queue(h, root, "moderate"); + queue.Add("Demo.A", 5, changed: true); + queue.Add("Demo.B", 13); + queue.Add("Demo.C", 13); + queue.Add("Demo.D", 13); + queue.Add("Demo.E", 14); + + var first = Examples(queue.Next().Response); + var next = queue.Save(Finding(first[0], "repaired"), Finding(first[1], "repaired"), Finding(first[2], "repaired"), + Verified(first[3]), Blocked(queue, first[4], "start fixture service")).Response; + h.Equal(58, Number(next, "examples"), "the entire moderate inventory is still in scope"); + h.Equal(3, Number(next, "repaired"), "the first packet supplies three repairs"); + h.Equal(53, Number(next, "unreviewed"), "the independent work remains actionable"); + h.Equal(1, Number(next, "blocked"), "the first packet has one blocked example"); + h.Equal("review", Text(next, "phase"), "a successful packet exposes the next work immediately"); + h.False(Flag(next, "stopAllowed"), "the blocked example does not authorize stopping"); + h.True(next["commands"]!["finalGate"] is null, "the next packet has no expensive verification command"); + + var (premature, prematureAction) = queue.EvaluateFullVerification(); + h.True(h.Get(premature, "DeterministicGatesPassed"), "simulated deterministic checks can be green mid-run"); + h.False(h.Get(premature, "CanClaimCompletion"), "green deterministic checks cannot close a partial repair"); + h.Equal(5, h.Get(premature, "ExamplesReviewed"), "reconciled report reflects current five reviewed examples"); + h.Equal(53, h.Get(premature, "ExamplesUnreviewed"), "reconciled report reflects remaining unreviewed examples"); + h.Equal("work-remaining", h.Get(prematureAction!, "State"), "premature full verification points back to remaining work"); + h.False(h.Get(prematureAction!, "StopAllowed"), "remaining work never authorizes stopping"); + h.Contains("--next-packet", h.Get(prematureAction!, "Command"), "remaining work returns the next-packet command"); + + next = queue.Save(VerifyAll(queue.Next().Response)).Response; + h.True(Number(next, "unreviewed") < 53, "resuming after a saved packet updates the reviewed count"); + var (afterMoreReview, _) = queue.EvaluateFullVerification(); + h.True(h.Get(afterMoreReview, "ExamplesReviewed") > 5, "additional behavioral review advances the reconciled report counts"); + h.Equal(Number(next, "unreviewed"), h.Get(afterMoreReview, "ExamplesUnreviewed"), "reconciled report matches the live queue count"); + while (Text(next, "phase") == "review") + { + next = queue.Save(VerifyAll(next)).Response; + } + + h.Equal("retry-blocked", Text(next, "phase"), "the queue returns to the blocker after independent work"); + h.Equal(57, Number(next, "behaviorVerified"), "all other examples have current evidence"); + next = queue.Save(VerifyAll(next)).Response; + h.Equal("final-gate", Text(next, "phase"), "resolving the last blocker makes final verification eligible"); + + var (finalDefect, finalDefectAction) = queue.EvaluateFullVerification("SAMPLE_COMPILE_FAILED"); + h.False(h.Get(finalDefect, "CanClaimCompletion"), "a defect discovered during final verification prevents completion"); + h.Equal("repair-diagnostics", h.Get(finalDefectAction!, "State"), "final verification defects return to active repair"); + h.False(h.Get(finalDefectAction!, "StopAllowed"), "final verification defects do not authorize stopping"); + h.Contains("--next-packet", h.Get(finalDefectAction!, "Command"), "final verification defects point back to the queue"); + + var (finalClean, finalCleanAction) = queue.EvaluateFullVerification(); + h.True(h.Get(finalClean, "CanClaimCompletion"), "the final checks can close the reconciled scope"); + h.Equal("complete", h.Get(finalCleanAction!, "State"), "clean final verification enters the complete state"); + h.True(h.Get(finalCleanAction!, "StopAllowed"), "clean final verification authorizes stopping"); + + var editedId = Text(first[0], "exampleId"); + queue.Edit(editedId); + var (afterEdit, afterEditAction) = queue.EvaluateFullVerification(); + h.Equal(1, h.Get(afterEdit, "BehavioralEvidenceStale"), "an edit after the last verification makes that comparison stale"); + h.False(h.Get(afterEdit, "CanClaimCompletion"), "the prior green report cannot close the edited scope"); + h.Equal("work-remaining", h.Get(afterEditAction!, "State"), "an edit after final verification reopens work-remaining"); + h.False(h.Get(afterEditAction!, "StopAllowed"), "stale final verification does not authorize stopping"); + next = queue.Next().Response; + h.Equal(editedId, Ids(next).Single(), "only the edited example returns to the queue"); + h.Equal(57, Number(next, "behaviorVerified"), "current behavioral evidence is retained"); + h.Equal(57, Number(next, "nativeVerified"), "current Native evidence is retained"); + h.Equal(57, Number(next, "dockerVerified"), "current Docker evidence is retained"); + h.Equal("final-gate", Text(queue.Save(VerifyAll(next)).Response, "phase"), "the edit requires a new final verification"); + } + + private static void AutoLedgerPathsAreScopeSpecific(DocfxTestHost h, string root) + { + string Resolve(string operation, bool changedOnly, bool bot) + { + var options = h.New(h.Type("Options")); + h.Set(options, "Operation", operation); + h.Set(options, "ChangedOnly", changedOnly); + return (string)h.InvokeStatic(h.Type("DocfxWorkPackets"), "ResolveAutoLedgerPath", options, root, Path.Combine(root, "docfx.json"), + ScopeTarget.Call(h, "ToBehavioralLedgerScope", h.New(ScopeTarget.Model(h, "ScopePlan"))), bot)!; + } + + var repository = Resolve("repair", false, true); + h.Equal(repository, Resolve("repair", false, true), "the same scope resolves to the same ledger"); + h.True(repository != Resolve("repair-csrun", false, true), "operations do not share a ledger"); + h.True(repository != Resolve("repair", true, true), "scopes do not share a ledger"); + h.True(repository.StartsWith(Path.Combine(root, ".bot", "dotnet-docfx-digest"), StringComparison.Ordinal), "an ignored .bot directory is used"); + var temp = Resolve("repair", false, false); + h.True(temp.StartsWith(Path.Combine(Path.GetTempPath(), "dotnet-docfx-digest", Path.GetFileName(root) + "-"), StringComparison.OrdinalIgnoreCase), + "otherwise the ledger lives in a repository-specific temp directory"); + } + + private static void ProgressIsAppendOnlyAndHeartbeats(DocfxTestHost h, string root) + { + var writer = new StringWriter(); + var progressPath = Path.Combine(root, "progress", "run.json"); + var progress = h.New(h.Type("DocfxWorkProgress"), "repair", "repository", false, writer, TimeSpan.FromMilliseconds(50), progressPath); + var operationId = h.Get(progress, "OperationId"); + h.True(!string.IsNullOrWhiteSpace(operationId), "progress exposes an operationId"); + h.Equal(Path.GetFullPath(progressPath), h.Get(progress, "ProgressFilePath"), "progress records the requested progress file path"); + h.True(File.Exists(progressPath), "progress file is written immediately at start"); + + var runningDoc = JsonNode.Parse(File.ReadAllText(progressPath))!.AsObject(); + h.Equal("codebeltnet/agentic/progress/1", Text(runningDoc, "schema"), "progress schema matches repository contract"); + h.Equal(operationId, Text(runningDoc, "operationId"), "running snapshot carries operationId"); + h.Equal(Environment.ProcessId, runningDoc["pid"]!.GetValue(), "running snapshot carries pid"); + h.Equal("running", Text(runningDoc, "state"), "initial state is running"); + h.True(runningDoc["staleAfterUtc"] is not null, "running snapshot includes staleAfterUtc"); + h.True(runningDoc["outcome"] is null, "running snapshot omits outcome"); + + h.InvokeInstance(progress, "Report", "scanning examples"); + var deadline = Stopwatch.StartNew(); + while (deadline.Elapsed < TimeSpan.FromSeconds(10)) + { + lock (writer) + { + if (writer.ToString().Contains("[HEARTBEAT]", StringComparison.Ordinal)) + { + break; + } + } + + Thread.Sleep(20); + } + + h.InvokeInstance(progress, "Complete", "done"); + h.InvokeInstance(progress, "Fail", "a second terminal line must be ignored"); + ((IDisposable)progress).Dispose(); + string text; + lock (writer) + { + text = writer.ToString(); + } + + foreach (var marker in new[] { "[START]", "[HEARTBEAT]", "[COMPLETE]" }) + { + h.Contains(marker, text, "progress lines"); + } + + h.Contains($"progressFile={Path.GetFullPath(progressPath)}", text, "start line announces progress file path"); + h.False(text.Contains("[FAILED]", StringComparison.Ordinal), "only one terminal line is written"); + h.False(text.Replace("\r\n", "\n").Contains('\r') || text.Contains('\u001b'), "progress is plain append-only text"); + + var completeDoc = JsonNode.Parse(File.ReadAllText(progressPath))!.AsObject(); + h.Equal(operationId, Text(completeDoc, "operationId"), "terminal snapshot keeps operationId"); + h.Equal("succeeded", Text(completeDoc, "state"), "completed state is succeeded"); + h.True(completeDoc["staleAfterUtc"] is null, "terminal snapshot clears staleAfterUtc"); + h.Equal(0, completeDoc["outcome"]!["exitCode"]!.GetValue(), "completed outcome records exitCode 0"); + h.Equal("done", Text(completeDoc["outcome"]!, "summary"), "completed outcome records summary"); + h.Equal(0, Directory.GetFiles(Path.GetDirectoryName(progressPath)!, "*.tmp").Length, "atomic writes leave no temp files"); + + var quiet = new StringWriter(); + var quietProgressPath = Path.Combine(root, "progress", "quiet.json"); + var quietProgress = h.New(h.Type("DocfxWorkProgress"), "repair", "repository", true, quiet, TimeSpan.FromMilliseconds(5), quietProgressPath); + h.InvokeInstance(quietProgress, "Report", "working"); + ((IDisposable)quietProgress).Dispose(); + h.Equal(1, quiet.ToString().Split('\n', StringSplitOptions.RemoveEmptyEntries).Length, "--quiet keeps only the terminal line"); + h.Contains("[FAILED]", quiet.ToString(), "an unfinished command reports failure"); + var failedDoc = JsonNode.Parse(File.ReadAllText(quietProgressPath))!.AsObject(); + h.Equal("failed", Text(failedDoc, "state"), "disposed unfinished progress records failed state"); + h.True(failedDoc["staleAfterUtc"] is null, "failed snapshot clears staleAfterUtc"); + h.True(failedDoc["outcome"]!["exitCode"]!.GetValue() != 0, "failed outcome records non-zero exitCode"); + } + + private static void CommandQuotingHandlesApostrophes(DocfxTestHost h) + { + var commandsType = h.Type("DocfxWorkCommands"); + var quotePlatform = commandsType.GetMethod("Quote", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public, [typeof(string), typeof(bool)])!; + + string Quote(string arg, bool powerShell) => (string)quotePlatform.Invoke(null, [arg, powerShell])!; + + // Paths with apostrophes only use double quotes so the same command works in both PowerShell and POSIX shells. + h.Equal("\"/home/O'Brien/repo\"", Quote("/home/O'Brien/repo", powerShell: false), "POSIX apostrophe path is safely quoted"); + h.Equal("\"/home/O'Brien/repo\"", Quote("/home/O'Brien/repo", powerShell: true), "PowerShell apostrophe path is safely quoted"); + h.Equal("'Demo.Box`1#1'", Quote("Demo.Box`1#1", powerShell: true), "UIDs with backticks stay single-quoted"); + h.Equal("'/home/O''Brien/$work'", Quote("/home/O'Brien/$work", powerShell: true), "PowerShell escapes embedded single quotes when double quotes are unsafe"); + h.Equal("'/home/O'\\''Brien/$work'", Quote("/home/O'Brien/$work", powerShell: false), "POSIX escapes embedded single quotes when double quotes are unsafe"); + + var options = h.New(h.Type("Options")); + h.Set(options, "Operation", "repair"); + var repo = Path.Combine(Path.GetTempPath(), "O'Brien", "repo"); + var ledger = Path.Combine(repo, ".bot", "ledger.json"); + var review = Path.Combine(repo, ".bot", "reviews.json"); + var shellRepo = Path.GetFullPath(repo).Replace('\\', '/'); + foreach (var command in new[] + { + (string)h.InvokeStatic(commandsType, "NextPacket", options, repo, ledger)!, + (string)h.InvokeStatic(commandsType, "RecordReviews", options, repo, ledger, review)!, + (string)h.InvokeStatic(commandsType, "FinalGate", options, repo, ledger)! + }) + { + h.Contains($"\"{shellRepo}\"", command, "command quotes apostrophe repo path safely"); + h.False(command.Contains($"'{shellRepo}'", StringComparison.Ordinal), "command never emits unescaped single quotes"); + } + } + + private static void CommandLineContract(DocfxTestHost h) + { + var tryParse = h.Type("DocfxCliOptions").GetMethod("TryParse", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public)!; + + (bool Ok, object Options, string Error) Parse(params string[] args) + { + var values = new object?[tryParse.GetParameters().Length]; + values[0] = args; + var ok = (bool)tryParse.Invoke(null, values)!; + return (ok, values[1]!, values[2] as string ?? string.Empty); + } + + var parsed = Parse("--next-packet", "--packet-size", "7", "--progress-file", "progress.json"); + h.True(parsed.Ok, "--next-packet parses: " + parsed.Error); + h.Equal("repair", h.Get(parsed.Options, "Operation"), "the work queue defaults to repair"); + h.True(h.Get(parsed.Options, "Json"), "the work queue always prints JSON"); + h.Equal("progress.json", h.Get(parsed.Options, "ProgressFilePath"), "--progress-file is parsed"); + h.True(Parse("--next-packet", "--progress-file=inline.json").Ok, "--progress-file=value parses"); + h.False(Parse("--next-packet", "--progress-file").Ok, "--progress-file requires a path"); + h.True(Parse("--operation", "audit", "--record-reviews", "r.json").Ok, "audits use the same queue"); + h.True(Parse("--operation", "repair", "--consumer-apis", "Demo.Type#1").Ok, "the consumer APIs of one example can be listed"); + foreach (var rejected in new[] + { + new[] { "--next-packet", "--operation", "validate" }, + ["--next-packet", "--packet-size", "0"], + ["--next-packet", "--packet-size", "16"], + ["--next-packet", "--validate-samples"], + ["--next-packet", "--verify-docfx-build"], + ["--next-packet", "--dry-run"], + ["--next-packet", "--init-behavioral-ledger", "l.json"], + ["--retry-blocked"], + ["--consumer-apis"], + ["--consumer-apis", "Demo.Type#1", "--next-packet"], + ["--consumer-apis", "Demo.Type#1", "--operation", "validate"], + ["--record-reviews"] + }) + { + h.False(Parse(rejected).Ok, "rejects " + string.Join(' ', rejected)); + } + } +} diff --git a/scripts/tests/dotnet-benchmark-tests.cs b/scripts/tests/dotnet-benchmark-tests.cs new file mode 100644 index 00000000..909d2d38 --- /dev/null +++ b/scripts/tests/dotnet-benchmark-tests.cs @@ -0,0 +1,330 @@ +#!/usr/bin/env dotnet +#:property TargetFramework=net10.0 +#:property RollForward=Major +#:property Nullable=enable +#:property PublishAot=false +#:include ../../skills/git-worktree-merge/scripts/GitProcess.cs +#:include ../../tooling/src/Agentic.Tooling/Execution/ExecutableResolver.cs +#:include ../eval-runners/windows-owned-process.cs + +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using Agentic.Tooling.Execution; + +// Deterministically validates the dotnet-benchmark skill package and its read-only .NET harness detector. +if (args.Length < 2 || !File.Exists(args[0]) || !Directory.Exists(args[1])) +{ + throw new ArgumentException("Pass ."); +} + +var app = Path.GetFullPath(args[0]); +var skillRoot = Path.GetFullPath(args[1]); +var dotnet = ExecutableResolver.Resolve(OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); +var failures = new List(); +using var stop = new CancellationTokenSource(TimeSpan.FromMinutes(2)); + +void AddFailure(string message) => failures.Add(message); +void AssertContains(string name, string content, string needle) +{ + if (!content.Contains(needle, StringComparison.Ordinal)) + AddFailure($"{name} is missing required content: {needle}"); +} +void AssertFile(string relativePath) +{ + if (!File.Exists(Path.Combine(skillRoot, relativePath.Replace('/', Path.DirectorySeparatorChar)))) + AddFailure($"Missing required file: {relativePath}"); +} + +string[] requiredFiles = +[ + "SKILL.md", + "FORMS.md", + "assets/benchmark.csproj", + "assets/benchmark-program.cs", + "assets/benchmark-runner.csproj", + "assets/comparison-benchmark.cs", + "assets/operation-benchmark.cs", + "references/benchmarkdotnet-essentials.md", + "references/candidate-selection.md", + "references/codebelt-conventions.md", + "references/experiment-design.md", + "references/onboarding.md", + "references/runner-preflight.md", + "scripts/check-benchmark-requirements.cs", + "scripts/ExecutableResolver.cs", + "scripts/GitProcess.cs", + "scripts/ProgressFile.cs", + "scripts/windows-owned-process.cs", + "evals/evals.json", +]; + +foreach (var file in requiredFiles) AssertFile(file); + +if (failures.Count == 0) +{ + var skillPath = Path.Combine(skillRoot, "SKILL.md"); + var skill = File.ReadAllText(skillPath); + var skillLines = File.ReadAllLines(skillPath); + var benchmarkEssentials = File.ReadAllText(Path.Combine(skillRoot, "references", "benchmarkdotnet-essentials.md")); + if (skillLines.Length > 500) AddFailure($"SKILL.md must stay at or below 500 lines; found {skillLines.Length}"); + + var frontmatterEnd = Array.IndexOf(skillLines, "---", 1); + var nameLine = frontmatterEnd > 0 ? skillLines[..frontmatterEnd].FirstOrDefault(l => Regex.IsMatch(l, @"^name:\s*")) : null; + var descriptionStart = Array.IndexOf(skillLines, "description: >"); + if (skillLines.Length == 0 || skillLines[0] != "---" || frontmatterEnd < 1 || nameLine != "name: dotnet-benchmark" || descriptionStart < 1 || descriptionStart >= frontmatterEnd) + { + AddFailure("SKILL.md frontmatter is missing the expected name and folded description"); + } + else + { + var description = string.Join(' ', skillLines[(descriptionStart + 1)..frontmatterEnd].Select(l => l.Trim()).Where(l => l.Length > 0)); + if (description.Length > 1024) AddFailure($"SKILL.md description exceeds 1024 characters; found {description.Length}"); + } + + foreach (var needle in new[] + { + "Read `references/candidate-selection.md`", + "Read `references/experiment-design.md`", + "Do not use construction as the baseline for formatting, equality, hashing, parsing, or another unrelated operation.", + "--list flat", + "--job dry", + "Never report performance numbers from a build, discovery listing, dry run, or unexecuted benchmark.", + "#### Yolo mode", + "Start a full performance run only after an explicit human instruction to run it now.", + "Yolo never authorizes a full performance run.", + "read `references/runner-preflight.md`", + "--benchmark-type ", + "reports.wouldSkipRequestedBenchmark", + "complete BenchmarkDotNet summary", + "When a parameter is only size or payload", + "Semantic preflight", + "independently derived exact expected result", + "Successful execution is not a correctness oracle.", + "do the baseline and candidate perform equivalent consumer-visible work over identical logical input?", + "After the first valid full result", + }) + { + AssertContains("SKILL.md", skill, needle); + } + + var forms = File.ReadAllText(Path.Combine(skillRoot, "FORMS.md")); + AssertContains("FORMS.md", forms, "## Yolo mode override"); + AssertContains("FORMS.md", forms, "skip `candidate_plan_confirmation`"); + AssertContains("FORMS.md", forms, "explicit human instruction to start a full performance run"); + + var comparison = File.ReadAllText(Path.Combine(skillRoot, "assets", "comparison-benchmark.cs")); + var operation = File.ReadAllText(Path.Combine(skillRoot, "assets", "operation-benchmark.cs")); + foreach (var required in new[] { "[MemoryDiagnoser]", "[GlobalSetup]", "[Params(", "Baseline = true", "{EQUIVALENCE_CHECK}" }) + AssertContains("assets/comparison-benchmark.cs", comparison, required); + if (comparison.Split("Baseline = true", StringSplitOptions.None).Length - 1 != 1) + AddFailure("assets/comparison-benchmark.cs must contain exactly one Baseline = true marker"); + foreach (var required in new[] { "[MemoryDiagnoser]", "[GlobalSetup]", "[Params(", "{SUT_CALL}" }) + AssertContains("assets/operation-benchmark.cs", operation, required); + if (Regex.IsMatch(operation, @"\[Benchmark\([^\]]*Baseline\s*=\s*true")) + AddFailure("assets/operation-benchmark.cs must not fabricate a baseline"); + + var runner = File.ReadAllText(Path.Combine(skillRoot, "assets", "benchmark-program.cs")); + AssertContains("assets/benchmark-program.cs", runner, "return c{RUNTIME_JOBS};"); + AssertContains("assets/benchmark-program.cs", runner, "{RUNTIME_USINGS}"); + AssertContains("assets/benchmark-program.cs", runner, "{RUNTIME_SETUP}"); + AssertContains("assets/benchmark-program.cs", runner, "public class Program"); + + var runnerPreflight = File.ReadAllText(Path.Combine(skillRoot, "references", "runner-preflight.md")); + AssertContains("references/runner-preflight.md", runnerPreflight, "SkipBenchmarksWithReports = true"); + AssertContains("references/runner-preflight.md", runnerPreflight, "reports/tuning/"); + AssertContains("references/runner-preflight.md", runnerPreflight, "Anti-thrashing rule"); + + var experimentDesign = File.ReadAllText(Path.Combine(skillRoot, "references", "experiment-design.md")); + foreach (var needle in new[] + { + "## Workload invariants", + "## Benchmark validity gate", + "## Deferred execution and terminal operations", + "## Semantic preflight", + "Successful execution is not a correctness oracle.", + "do the baseline and candidate perform equivalent consumer-visible work over identical logical input?", + "Do not benchmark a homogeneous all-match store and call it type filtering unless the all-match path is the actual subject.", + }) + { + AssertContains("references/experiment-design.md", experimentDesign, needle); + } + + AssertContains("references/benchmarkdotnet-essentials.md", benchmarkEssentials, "one warmup iteration plus controlled iteration counts"); + AssertContains("references/benchmarkdotnet-essentials.md", benchmarkEssentials, "## Deferred pipelines and terminal operations"); + AssertContains("references/benchmarkdotnet-essentials.md", benchmarkEssentials, "## Result-validity gate"); + + try + { + using var evalDoc = JsonDocument.Parse(File.ReadAllText(Path.Combine(skillRoot, "evals", "evals.json"))); + var root = evalDoc.RootElement; + if (root.GetProperty("skill_name").GetString() != "dotnet-benchmark") AddFailure("evals/evals.json skill_name must be dotnet-benchmark"); + var evals = root.GetProperty("evals").EnumerateArray().ToList(); + if (evals.Count < 12) AddFailure("evals/evals.json must include at least twelve diverse evals"); + if (!evals.Any(e => Regex.IsMatch(e.GetProperty("prompt").GetString() ?? "", "yolo", RegexOptions.IgnoreCase))) AddFailure("evals/evals.json must include a yolo-mode interaction eval"); + if (!evals.Any(e => (e.GetProperty("prompt").GetString() ?? "").Contains("LegacyAliasQuery", StringComparison.Ordinal))) AddFailure("evals/evals.json must include the invalid parameter-matrix and drifting-selectivity eval"); + if (!evals.Any(e => (e.GetProperty("prompt").GetString() ?? "").Contains("InMemoryTestStore benchmark", StringComparison.Ordinal))) AddFailure("evals/evals.json must include the semantic-preflight workload validation eval"); + if (!evals.Any(e => (e.GetProperty("prompt").GetString() ?? "").Contains("TraitFilter helper only runs in test discovery", StringComparison.Ordinal))) AddFailure("evals/evals.json must include the proportionate-stopping eval"); + + var ids = evals.Select(e => e.GetProperty("id").GetInt32()).ToList(); + if (ids.Distinct().Count() != ids.Count) AddFailure("evals/evals.json contains duplicate eval IDs"); + foreach (var eval in evals) + { + var id = eval.GetProperty("id").GetInt32(); + if (string.IsNullOrWhiteSpace(eval.GetProperty("prompt").GetString()) + || string.IsNullOrWhiteSpace(eval.GetProperty("expected_output").GetString()) + || eval.GetProperty("expectations").GetArrayLength() < 1) + { + AddFailure($"Eval {id} must include a prompt, expected_output, and expectations"); + } + if (eval.TryGetProperty("files", out var filesProp) && filesProp.ValueKind == JsonValueKind.Array) + { + foreach (var f in filesProp.EnumerateArray()) + { + var fixture = f.GetString(); + if (!string.IsNullOrWhiteSpace(fixture) && !File.Exists(Path.Combine(skillRoot, fixture.Replace('/', Path.DirectorySeparatorChar)))) + AddFailure($"Eval {id} references missing fixture: {fixture}"); + } + } + } + } + catch (Exception exception) + { + AddFailure($"evals/evals.json is invalid: {exception.Message}"); + } + + var evalFixtureRoot = Path.Combine(skillRoot, "evals", "files"); + if (Directory.Exists(evalFixtureRoot)) + { + foreach (var dir in Directory.EnumerateDirectories(evalFixtureRoot, "*", SearchOption.AllDirectories)) + { + var name = Path.GetFileName(dir); + if (name is "obj" or "bin" or "BenchmarkDotNet.Artifacts") + AddFailure($"Eval fixtures must not contain generated artifact directories: {Path.GetRelativePath(skillRoot, dir)}"); + } + } +} + +var tempRoot = Path.GetFullPath(Path.GetTempPath()); +var fixtureRoot = Path.Combine(tempRoot, "dotnet-benchmark-validator-" + Guid.NewGuid().ToString("N")); +try +{ + Directory.CreateDirectory(Path.Combine(fixtureRoot, "tuning", "Acme.Core.Benchmarks")); + Directory.CreateDirectory(Path.Combine(fixtureRoot, "tooling", "bdn-runner")); + Directory.CreateDirectory(Path.Combine(fixtureRoot, "reports", "tuning")); + File.WriteAllText(Path.Combine(fixtureRoot, "Acme.sln"), ""); + File.WriteAllText(Path.Combine(fixtureRoot, "Directory.Packages.props"), """"""); + File.WriteAllText(Path.Combine(fixtureRoot, "Directory.Build.props"), """falsefalse"""); + File.WriteAllText(Path.Combine(fixtureRoot, "tuning", "Acme.Core.Benchmarks", "Acme.Core.Benchmarks.csproj"), """"""); + File.WriteAllText(Path.Combine(fixtureRoot, "tooling", "bdn-runner", "bdn-runner.csproj"), """"""); + File.WriteAllText(Path.Combine(fixtureRoot, "tooling", "bdn-runner", "Program.cs"), "using Codebelt.Extensions.BenchmarkDotNet; using Codebelt.Extensions.BenchmarkDotNet.Console; using BenchmarkDotNet.Environments; public class Program { public static void Main(string[] args) { BenchmarkProgram.Run(args, o => { o.SkipBenchmarksWithReports = true; o.ConfigureBenchmarkDotNet(c => { var slimJob = BenchmarkWorkspaceOptions.Slim; return c.AddJob(slimJob.WithRuntime(CoreRuntime.Core90)); }); }); } }"); + File.WriteAllText(Path.Combine(fixtureRoot, "reports", "tuning", "Acme.Core.WidgetBenchmark-report-github.md"), "# existing report"); + + var progressPath = Path.Combine(tempRoot, "dotnet-benchmark-progress-" + Guid.NewGuid().ToString("N") + ".json"); + try + { + var run = await Git.RunProcessAsync( + Git.CreateStartInfo(dotnet, fixtureRoot, [app, "--repo-root", fixtureRoot, "--benchmark-type", "Acme.Core.WidgetBenchmark", "--skip-sdk-check", "--progress-file", progressPath]), + stop.Token); + if (run.Code != 0) + { + AddFailure($"Harness detector exited {run.Code}: {run.Error}"); + } + else + { + using var doc = JsonDocument.Parse(run.Output); + var detected = doc.RootElement; + if (detected.GetProperty("solutionFormat").GetString() != "sln" + || !detected.GetProperty("centralPackageManagement").GetBoolean() + || !detected.GetProperty("centralizesBenchmarkConventions").GetBoolean()) + { + AddFailure("Harness detector did not recognize the fixture solution, CPM, and centralized conventions"); + } + if (detected.GetProperty("sdk").GetProperty("status").GetString() != "skipped") + { + AddFailure("Harness detector did not report the intentional skipped SDK probe distinctly"); + } + if (detected.GetProperty("benchmarkProjects").GetArrayLength() != 1 + || detected.GetProperty("runner").GetProperty("name").GetString() != "bdn-runner" + || !detected.GetProperty("harnessReady").GetBoolean()) + { + AddFailure("Harness detector did not recognize the existing benchmark project and runner"); + } + var runnerNode = detected.GetProperty("runner"); + var runtimes = runnerNode.GetProperty("configuredRuntimes").EnumerateArray().Select(e => e.GetString()).ToList(); + if (!runnerNode.GetProperty("skipBenchmarksWithReports").GetBoolean() + || !runnerNode.GetProperty("usesSlimJob").GetBoolean() + || !runtimes.Contains("CoreRuntime.Core90")) + { + AddFailure("Harness detector did not recognize report skipping, the Slim job, and configured runtime"); + } + var reportsNode = detected.GetProperty("reports"); + if (!reportsNode.GetProperty("wouldSkipRequestedBenchmark").GetBoolean() + || reportsNode.GetProperty("matchingReportFiles").GetArrayLength() != 1) + { + AddFailure("Harness detector did not identify the matching report that suppresses the requested benchmark type"); + } + if (!run.Error.Contains("[START]", StringComparison.Ordinal) || !run.Error.Contains("[COMPLETE]", StringComparison.Ordinal)) + { + AddFailure("Harness detector did not emit stderr [START] and [COMPLETE] lines"); + } + using var progressDoc = JsonDocument.Parse(File.ReadAllText(progressPath)); + if (progressDoc.RootElement.GetProperty("state").GetString() != "succeeded") + { + AddFailure("Harness detector progress file did not record succeeded terminal state"); + } + } + + // Real SDK probe check (without --skip-sdk-check) and PowerShell-style option compatibility. + var liveRun = await Git.RunProcessAsync( + Git.CreateStartInfo(dotnet, fixtureRoot, [app, "-RepoRoot", fixtureRoot, "--quiet", "--no-heartbeat"]), + stop.Token); + if (liveRun.Code != 0) + { + AddFailure($"Live SDK detector check exited {liveRun.Code}: {liveRun.Error}"); + } + else + { + using var liveDoc = JsonDocument.Parse(liveRun.Output); + if (!liveDoc.RootElement.GetProperty("sdk").GetProperty("available").GetBoolean() + || liveDoc.RootElement.GetProperty("sdk").GetProperty("status").GetString() != "available") + { + AddFailure("Live SDK probe did not detect the installed .NET SDK"); + } + if (liveRun.Error.Contains("[START]", StringComparison.Ordinal)) + { + AddFailure("--quiet should suppress [START] on stderr"); + } + } + + // Progress file overlap rejection. + var overlap = await Git.RunProcessAsync( + Git.CreateStartInfo(dotnet, fixtureRoot, [app, "--repo-root", fixtureRoot, "--skip-sdk-check", "--progress-file", Path.Combine(fixtureRoot, "Directory.Packages.props")]), + stop.Token); + if (overlap.Code != 2) + { + AddFailure($"Progress file overlapping Directory.Packages.props should exit 2, got {overlap.Code}"); + } + } + finally + { + if (File.Exists(progressPath)) File.Delete(progressPath); + } +} +finally +{ + var resolvedFixture = Path.GetFullPath(fixtureRoot); + if (resolvedFixture.StartsWith(tempRoot, StringComparison.OrdinalIgnoreCase) && Directory.Exists(resolvedFixture)) + { + Directory.Delete(resolvedFixture, recursive: true); + } +} + +if (failures.Count > 0) +{ + foreach (var failure in failures) Console.Error.WriteLine($"[FAIL] {failure}"); + return 1; +} + +Console.Out.WriteLine("[PASS] dotnet-benchmark skill structure, templates, eval fixtures, and harness detector are valid."); +return 0; diff --git a/scripts/tests/dotnet-remote-testing-tests.cs b/scripts/tests/dotnet-remote-testing-tests.cs new file mode 100644 index 00000000..e91fe8d1 --- /dev/null +++ b/scripts/tests/dotnet-remote-testing-tests.cs @@ -0,0 +1,361 @@ +#!/usr/bin/env dotnet +#:property TargetFramework=net10.0 +#:property RollForward=Major +#:property Nullable=enable +#:property PublishAot=false +#:include ../../skills/git-worktree-merge/scripts/GitProcess.cs +#:include ../../tooling/src/Agentic.Tooling/Execution/ExecutableResolver.cs +#:include ../eval-runners/windows-owned-process.cs + +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using Agentic.Tooling.Execution; + +// Deterministic structural, contract, and black-box CLI tests for dotnet-remote-testing. +// Ports validate-skill.ps1 and test-remote-testing.ps1 plus observability & progress-file checks. +if (args.Length < 2 || !File.Exists(args[0]) || !Directory.Exists(args[1])) +{ + throw new ArgumentException("Pass ."); +} + +var app = Path.GetFullPath(args[0]); +var skillRoot = Path.GetFullPath(args[1]); +var dotnet = ExecutableResolver.Resolve(OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); +var utf8NoBom = new UTF8Encoding(false); +using var stop = new CancellationTokenSource(TimeSpan.FromMinutes(3)); + +var pass = 0; +var fail = 0; + +void Check(bool ok, string name, string detail = "") +{ + if (ok) + { + pass++; + Console.WriteLine($"[PASS] {name}"); + } + else + { + fail++; + Console.Error.WriteLine($"[FAIL] {name}"); + if (!string.IsNullOrWhiteSpace(detail)) Console.Error.WriteLine($" {detail}"); + } +} + +void AssertTrue(bool condition, string message) +{ + if (!condition) throw new InvalidOperationException(message); +} + +async Task InvokeRunnerAsync(params string[] runnerArgs) +{ + var psi = Git.CreateStartInfo(dotnet, skillRoot, [app, .. runnerArgs]); + return await Git.RunProcessAsync(psi, stop.Token); +} + +JsonDocument ParseJson(string stdout) +{ + var start = stdout.IndexOf('{'); + AssertTrue(start >= 0, $"No JSON object in runner stdout: {stdout}"); + return JsonDocument.Parse(stdout[start..]); +} + +// === 1. Skill structure & SKILL.md / FORMS.md contracts (from validate-skill.ps1) === +string[] required = +[ + "SKILL.md", "FORMS.md", "evals/evals.json", + "scripts/remote-test.cs", "scripts/ExecutableResolver.cs", "scripts/GitProcess.cs", "scripts/ProgressFile.cs", "scripts/windows-owned-process.cs", + "references/testenvironments-json.md", "references/release-discovery.md", "references/docker-execution.md", +]; +foreach (var rel in required) +{ + AssertTrue(File.Exists(Path.Combine(skillRoot, rel.Replace('/', Path.DirectorySeparatorChar))), + $"Missing required dotnet-remote-testing file: {rel}"); +} + +var skill = File.ReadAllText(Path.Combine(skillRoot, "SKILL.md")); +string[] contracts = +[ + "testenvironments.json", + "mcr.microsoft.com/dotnet/sdk", + "remote-test.cs", + "Choose a test environment", + "Do not generate container plumbing", + "Do not hardcode .NET versions", + "never silently fall back to local", + "reproduce", + "Default action: run the tests", + "Forbidden as a first response", + "You were invoked. That is the request. Run the tests.", + "SelectionRequired", + "Branch on the exit code", + "codebeltnet/ubuntu-testrunner", + "ships exactly **one** runtime", + "The staged workspace is still a repository", + "Do not compress this into a bare count", + "orchestration", +]; +foreach (var needle in contracts) +{ + AssertTrue(skill.Contains(needle, StringComparison.Ordinal), $"SKILL.md is missing required contract: {needle}"); +} + +var bodyMatch = Regex.Match(skill, @"^---\r?\n.*?\r?\n---\r?\n", RegexOptions.Singleline); +var body = bodyMatch.Success ? skill[(bodyMatch.Index + bodyMatch.Length)..] : skill; +var doThisNow = body.IndexOf("## Do this now", StringComparison.Ordinal); +var commandsOffset = body.IndexOf("Commands: ", StringComparison.Ordinal); +AssertTrue(doThisNow >= 0, "SKILL.md must open with a \"## Do this now\" section so the default action is read first."); +AssertTrue(commandsOffset < 0 || commandsOffset > doThisNow, "SKILL.md lists the command surface before \"## Do this now\"; the imperative must come first."); +var opening = Regex.Replace(body[..doThisNow], @"^!\[[^\r\n]*\]\([^\r\n]*\)\r?\n", string.Empty, RegexOptions.Multiline); +AssertTrue(opening.Length <= 100, $"SKILL.md places '## Do this now' too late (body offset {doThisNow}); it must lead the document body."); + +for (var code = 0; code <= 16; code++) +{ + AssertTrue(Regex.IsMatch(skill, $@"^\|\s*`{code}`\s*\|", RegexOptions.Multiline), + $"SKILL.md exit-code decision table is missing exit code {code}."); +} + +var forms = File.ReadAllText(Path.Combine(skillRoot, "FORMS.md")); +foreach (var needle in new[] { "Autonomy gate", "not an intake checklist" }) +{ + AssertTrue(forms.Contains(needle, StringComparison.Ordinal), $"FORMS.md is missing required autonomy contract: {needle}"); +} + +var projectField = Regex.Match(forms, @"^### project\s*(?.*?)(?=^### |\z)", RegexOptions.Multiline | RegexOptions.Singleline); +AssertTrue(projectField.Success + && projectField.Groups["body"].Value.Contains("- **choices:**", StringComparison.Ordinal) + && projectField.Groups["body"].Value.Contains("exact target returned by `remote-test.cs plan`", StringComparison.Ordinal), + "FORMS.md must expose the computed project target as a selectable choice."); + +// === 2. CLI & self-test harness (from test-remote-testing.ps1) === +var workspace = Path.Combine(Path.GetTempPath(), "dotnet-remote-testing-harness-" + Guid.NewGuid().ToString("N")); +Directory.CreateDirectory(workspace); + +try +{ + var indexPath = Path.Combine(workspace, "releases-index.json"); + File.WriteAllText(indexPath, """ + { + "releases-index": [ + { "channel-version": "11.0", "latest-sdk": "11.0.100-preview.6.26359.118", "support-phase": "preview", "release-type": "sts" }, + { "channel-version": "10.0", "latest-sdk": "10.0.302", "support-phase": "active", "release-type": "lts", "eol-date": "2028-11-14" }, + { "channel-version": "9.0", "latest-sdk": "9.0.316", "support-phase": "maintenance", "release-type": "sts", "eol-date": "2026-11-10" }, + { "channel-version": "7.0", "latest-sdk": "7.0.410", "support-phase": "eol", "release-type": "sts" } + ] + } + """, utf8NoBom); + + // 1. Built-in self-test + var selfTest = await InvokeRunnerAsync("--self-test"); + Check(selfTest.Code == 0 && Regex.IsMatch(selfTest.Output, @"Self-test: (\d+) passed, 0 failed"), + "runner --self-test passes", $"exit={selfTest.Code}"); + + // 2 & 3. Zero-configuration list from injected release metadata (offline) + var emptyRoot = Path.Combine(workspace, "empty"); + Directory.CreateDirectory(emptyRoot); + var list = await InvokeRunnerAsync("list", "--repo-root", emptyRoot, "--offline", "--releases-index-file", indexPath, "--json"); + Check(list.Code == 0, "absent testenvironments.json is not an error", $"exit={list.Code}"); + Check(list.Error.Contains("[START]", StringComparison.Ordinal) && list.Error.Contains("[COMPLETE]", StringComparison.Ordinal), + "list emits START and COMPLETE on stderr while keeping stdout pure JSON", list.Error); + using (var listDoc = ParseJson(list.Output)) + { + var envs = listDoc.RootElement.GetProperty("environments").EnumerateArray().ToList(); + var names = envs.Select(e => e.GetProperty("name").GetString()!).ToList(); + Check(names.Contains("dotnet-10-lts"), "derives LTS environment name", string.Join(",", names)); + Check(names.Contains("dotnet-9-sts"), "derives STS environment name"); + Check(names.Contains("dotnet-11-preview"), "derives preview environment name"); + Check(!names.Contains("dotnet-7-sts"), "excludes EOL channel"); + var previewImg = envs.First(e => e.GetProperty("name").GetString() == "dotnet-11-preview").GetProperty("image").GetString(); + Check(previewImg == "mcr.microsoft.com/dotnet/sdk:11.0.100-preview.6", "preview image tag strips build metadata", previewImg ?? ""); + var ltsImg = envs.First(e => e.GetProperty("name").GetString() == "dotnet-10-lts").GetProperty("image").GetString(); + Check(ltsImg == "mcr.microsoft.com/dotnet/sdk:10.0.302", "stable image uses exact SDK tag", ltsImg ?? ""); + } + + // 4. testenvironments.json is authoritative and reports unsupported types + var cfgRoot = Path.Combine(workspace, "configured"); + Directory.CreateDirectory(cfgRoot); + File.WriteAllText(Path.Combine(cfgRoot, "testenvironments.json"), """ + { + "version": "1", + "environments": [ + { "name": "ci-docker", "type": "docker", "dockerImage": "mcr.microsoft.com/dotnet/sdk:10.0" }, + { "name": "wsl-env", "type": "wsl", "wslDistribution": "Ubuntu" } + ] + } + """, utf8NoBom); + var cfgList = await InvokeRunnerAsync("list", "--repo-root", cfgRoot, "--json"); + using (var cfgDoc = ParseJson(cfgList.Output)) + { + var cfgNames = cfgDoc.RootElement.GetProperty("environments").EnumerateArray().Select(e => e.GetProperty("name").GetString()!).ToList(); + Check(cfgNames.Count == 1 && cfgNames[0] == "ci-docker", "lists only configured docker environments", string.Join(",", cfgNames)); + Check(!cfgNames.Contains("dotnet-10-lts"), "does not supplement config with generated envs"); + var unsupportedNames = cfgDoc.RootElement.GetProperty("unsupported").EnumerateArray().Select(e => e.GetProperty("name").GetString()!).ToList(); + Check(unsupportedNames.Contains("wsl-env"), "reports WSL as unsupported"); + } + + // 5. Naming an unsupported environment is reported, not converted + var named = await InvokeRunnerAsync("plan", "--repo-root", cfgRoot, "-e", "wsl-env", "--offline", "--json"); + using (var namedDoc = ParseJson(named.Output)) + { + var kind = namedDoc.RootElement.GetProperty("failureKind").GetString(); + Check(named.Code == 4 && kind == "UnsupportedEnvironment", "unsupported named env -> UnsupportedEnvironment", $"kind={kind} exit={named.Code}"); + } + + // 6. plan derives the image offline without pulling + var projDir = Path.Combine(emptyRoot, "test", "Foo"); + Directory.CreateDirectory(projDir); + File.WriteAllText(Path.Combine(projDir, "Foo.csproj"), "net10.0", utf8NoBom); + var plan = await InvokeRunnerAsync("plan", "--repo-root", emptyRoot, "-e", "dotnet-10-lts", "--offline", "--releases-index-file", indexPath, "--json"); + using (var planDoc = ParseJson(plan.Output)) + { + var reference = planDoc.RootElement.GetProperty("image").GetProperty("reference").GetString(); + var runArgs = planDoc.RootElement.GetProperty("dockerRunArgs").EnumerateArray().Select(a => a.GetString()!).ToList(); + Check(reference == "mcr.microsoft.com/dotnet/sdk:10.0.302", "plan resolves the SDK image reference", reference ?? ""); + Check(runArgs.Contains("--rm") && !runArgs.Contains("--privileged"), "plan run args are --rm and not privileged"); + Check(!runArgs.Contains("/var/run/docker.sock") && !plan.Output.Contains("docker.sock", StringComparison.OrdinalIgnoreCase), "plan never mounts the docker socket"); + } + + // 7. Conflicting docker source is a configuration failure + var badRoot = Path.Combine(workspace, "bad"); + Directory.CreateDirectory(badRoot); + File.WriteAllText(Path.Combine(badRoot, "testenvironments.json"), + """{ "version": "1", "environments": [ { "name": "x", "type": "docker", "dockerImage": "a", "dockerFile": "b" } ] }""", utf8NoBom); + var bad = await InvokeRunnerAsync("list", "--repo-root", badRoot, "--json"); + using (var badDoc = ParseJson(bad.Output)) + { + var codes = badDoc.RootElement.GetProperty("configDiagnostics").EnumerateArray().Select(d => d.GetProperty("code").GetString()!).ToList(); + Check(codes.Contains("CONFLICTING_DOCKER_SOURCE"), "reports CONFLICTING_DOCKER_SOURCE", string.Join(",", codes)); + } + + // 8. Unattended selection: the repository answers the environment question + var auto = await InvokeRunnerAsync("plan", "--repo-root", emptyRoot, "--offline", "--releases-index-file", indexPath, "--json"); + using (var autoDoc = ParseJson(auto.Output)) + { + var envName = autoDoc.RootElement.GetProperty("environment").GetProperty("name").GetString(); + var reason = autoDoc.RootElement.GetProperty("environment").GetProperty("selectionReason").GetString() ?? ""; + Check(auto.Code == 0 && envName == "dotnet-10-lts", "target framework selects the channel with no --environment", $"exit={auto.Code} env={envName}"); + Check(!string.IsNullOrWhiteSpace(reason) && reason.Contains("net10.0", StringComparison.Ordinal), "automatic selection is explained in the output", reason); + } + + // 9. Genuine ambiguity still stops with SelectionRequired and candidates + var twoRoot = Path.Combine(workspace, "two-docker"); + Directory.CreateDirectory(twoRoot); + File.WriteAllText(Path.Combine(twoRoot, "testenvironments.json"), """ + { + "version": "1", + "environments": [ + { "name": "noble", "type": "docker", "dockerImage": "mcr.microsoft.com/dotnet/sdk:10.0-noble" }, + { "name": "alpine", "type": "docker", "dockerImage": "mcr.microsoft.com/dotnet/sdk:10.0-alpine" } + ] + } + """, utf8NoBom); + var twoPlan = await InvokeRunnerAsync("plan", "--repo-root", twoRoot, "--offline", "--json"); + using (var twoDoc = ParseJson(twoPlan.Output)) + { + var kind = twoDoc.RootElement.GetProperty("failureKind").GetString(); + var candidates = twoDoc.RootElement.GetProperty("candidates").EnumerateArray().Select(c => c.GetString()!).ToList(); + Check(twoPlan.Code == 16 && kind == "SelectionRequired", "two configured docker envs exit SelectionRequired (16)", $"exit={twoPlan.Code} kind={kind}"); + Check(candidates.Contains("noble") && candidates.Contains("alpine"), "SelectionRequired returns the candidate names to ask about", string.Join(",", candidates)); + } + + // 10. No .NET target framework means ask, never guess + var nsRoot = Path.Combine(workspace, "netstandard-only"); + var nsProj = Path.Combine(nsRoot, "src", "Lib"); + Directory.CreateDirectory(nsProj); + File.WriteAllText(Path.Combine(nsProj, "Lib.csproj"), "netstandard2.0", utf8NoBom); + var ns = await InvokeRunnerAsync("plan", "--repo-root", nsRoot, "--offline", "--releases-index-file", indexPath, "--json"); + using (var nsDoc = ParseJson(ns.Output)) + { + var kind = nsDoc.RootElement.GetProperty("failureKind").GetString(); + Check(ns.Code == 16 && kind == "SelectionRequired", "netstandard-only repository does not get a guessed channel", $"exit={ns.Code} kind={kind}"); + } + + // 11. Multi-targeted repositories resolve to a multi-SDK runner + var tagsPath = Path.Combine(workspace, "multi-sdk-tags.json"); + File.WriteAllText(tagsPath, """ + { + "count": 4, + "results": [ + { "name": "10" }, + { "name": "9-10" }, + { "name": "8-9-10-11" }, + { "name": "8.0-9.0-10.0-11.0" } + ] + } + """, utf8NoBom); + var multiRoot = Path.Combine(workspace, "multi-targeted"); + var multiProj = Path.Combine(multiRoot, "test", "Multi"); + Directory.CreateDirectory(multiProj); + File.WriteAllText(Path.Combine(multiProj, "Multi.csproj"), "net9.0;net10.0", utf8NoBom); + var multi = await InvokeRunnerAsync("plan", "--repo-root", multiRoot, "--offline", "--releases-index-file", indexPath, "--multi-sdk-tags-file", tagsPath, "--json"); + using (var multiDoc = ParseJson(multi.Output)) + { + var envName = multiDoc.RootElement.GetProperty("environment").GetProperty("name").GetString(); + var imgRef = multiDoc.RootElement.GetProperty("image").GetProperty("reference").GetString(); + var compat = multiDoc.RootElement.GetProperty("compatibility").GetProperty("compatible").GetBoolean(); + Check(multi.Code == 0 && envName == "ubuntu-testrunner-9-10", "multi-targeted repo selects the tightest covering runner", $"exit={multi.Code} env={envName}"); + Check(imgRef == "codebeltnet/ubuntu-testrunner:9-10", "runner image reference comes from the publisher feed", imgRef ?? ""); + Check(compat, "every target framework is compatible with the runner"); + } + + // 12. --framework narrows the environment choice too + var narrowed = await InvokeRunnerAsync("plan", "--repo-root", multiRoot, "-f", "net10.0", "--offline", "--releases-index-file", indexPath, "--multi-sdk-tags-file", tagsPath, "--json"); + using (var narrowedDoc = ParseJson(narrowed.Output)) + { + var envName = narrowedDoc.RootElement.GetProperty("environment").GetProperty("name").GetString(); + Check(narrowed.Code == 0 && envName == "dotnet-10-lts", "restricting to one TFM resolves the matching single-SDK channel", $"exit={narrowed.Code} env={envName}"); + } + + // 13. Single-SDK image is reported incompatible with multi-targeted repo + var forced = await InvokeRunnerAsync("plan", "--repo-root", multiRoot, "-e", "dotnet-10-lts", "--offline", "--releases-index-file", indexPath, "--json"); + using (var forcedDoc = ParseJson(forced.Output)) + { + var compat = forcedDoc.RootElement.GetProperty("compatibility").GetProperty("compatible").GetBoolean(); + var reason = forcedDoc.RootElement.GetProperty("compatibility").GetProperty("reason").GetString() ?? ""; + Check(forced.Code == 7 && !compat, "naming a single-SDK env for a multi-targeted repo exits SdkIncompatibility (7)", $"exit={forced.Code} compatible={compat}"); + Check(reason.Contains("ubuntu-testrunner", StringComparison.Ordinal), "the incompatibility points at the multi-SDK remedy", reason); + } + + // 14. Observability: --progress-file, --quiet, --no-heartbeat, and overlap guards + var progressFile = Path.Combine(workspace, "remote-test-progress.json"); + var quietPlan = await InvokeRunnerAsync("plan", "--repo-root", emptyRoot, "--offline", "--releases-index-file", indexPath, "--json", "--quiet", "--no-heartbeat", "--progress-file", progressFile); + Check(quietPlan.Code == 0, "quiet plan with --progress-file succeeds", $"exit={quietPlan.Code}"); + Check(!quietPlan.Error.Contains("[START]", StringComparison.Ordinal) && quietPlan.Error.Contains("[COMPLETE]", StringComparison.Ordinal), + "--quiet suppresses START while keeping terminal COMPLETE on stderr", quietPlan.Error); + Check(File.Exists(progressFile), "progress file is written"); + using (var progDoc = JsonDocument.Parse(File.ReadAllText(progressFile))) + { + Check(progDoc.RootElement.GetProperty("schema").GetString() == "codebeltnet/agentic/progress/1" + && progDoc.RootElement.GetProperty("state").GetString() == "succeeded", + "progress file records schema and terminal succeeded state"); + } + + // Overlap guard: refuse overwriting --releases-index-file or a foreign file + var beforeIndex = File.ReadAllText(indexPath); + var overlap = await InvokeRunnerAsync("list", "--repo-root", emptyRoot, "--offline", "--releases-index-file", indexPath, "--progress-file", indexPath); + Check(overlap.Code == 2 && File.ReadAllText(indexPath) == beforeIndex, + "--progress-file refuses overlapping --releases-index-file without mutating it", $"exit={overlap.Code}"); + + var foreign = Path.Combine(workspace, "foreign.json"); + File.WriteAllText(foreign, """{"hello":"world"}""", utf8NoBom); + var foreignRun = await InvokeRunnerAsync("list", "--repo-root", emptyRoot, "--offline", "--releases-index-file", indexPath, "--progress-file", foreign); + Check(foreignRun.Code == 2 && File.ReadAllText(foreign) == """{"hello":"world"}""", + "--progress-file refuses overwriting a foreign file", $"exit={foreignRun.Code}"); + + var cacheDir = Path.Combine(workspace, "cache"); + var cacheOverlap = await InvokeRunnerAsync("list", "--repo-root", emptyRoot, "--offline", "--releases-index-file", indexPath, "--cache-root", cacheDir, "--progress-file", Path.Combine(cacheDir, "p.json")); + Check(cacheOverlap.Code == 2, "--progress-file refuses path inside --cache-root", $"exit={cacheOverlap.Code}"); +} +finally +{ + if (Directory.Exists(workspace)) + { + Directory.Delete(workspace, recursive: true); + } +} + +Console.WriteLine($"Harness: {pass} passed, {fail} failed."); +if (fail > 0) return 1; +Console.WriteLine("dotnet-remote-testing skill validation: PASS"); +return 0; diff --git a/scripts/tests/dotnet-segregated-assets-tests.cs b/scripts/tests/dotnet-segregated-assets-tests.cs new file mode 100644 index 00000000..1bd4f3c0 --- /dev/null +++ b/scripts/tests/dotnet-segregated-assets-tests.cs @@ -0,0 +1,218 @@ +#!/usr/bin/env dotnet +#:property TargetFramework=net10.0 +#:property RollForward=Major +#:property Nullable=enable +#:property PublishAot=false +#:include ../../skills/git-worktree-merge/scripts/GitProcess.cs +#:include ../../tooling/src/Agentic.Tooling/Execution/ExecutableResolver.cs +#:include ../eval-runners/windows-owned-process.cs + +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using Agentic.Tooling.Execution; + +// Deterministic structural, contract, and black-box CLI tests for dotnet-segregated-assets. +if (args.Length < 2 || !File.Exists(args[0]) || !Directory.Exists(args[1])) +{ + throw new ArgumentException("Pass ."); +} + +var app = Path.GetFullPath(args[0]); +var skillRoot = Path.GetFullPath(args[1]); +var dotnet = ExecutableResolver.Resolve(OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); +var utf8NoBom = new UTF8Encoding(false); +using var stop = new CancellationTokenSource(TimeSpan.FromMinutes(3)); + +void AssertTrue(bool condition, string message) +{ + if (!condition) throw new InvalidOperationException(message); +} + +// === 1. Skill structure and contract checks (from validate-skill.ps1) === +string[] required = +[ + "SKILL.md", "FORMS.md", "evals/evals.json", + "scripts/segregate-assets.cs", "scripts/ExecutableResolver.cs", "scripts/GitProcess.cs", "scripts/ProgressFile.cs", "scripts/windows-owned-process.cs", + "references/app-vs-cdn.md", "references/local-development.md", + "references/production-image.md", "references/static-web-assets-guardrail.md", + "assets/Dockerfile", "assets/LocalDevelopment.Dockerfile", "assets/Assets.Dockerfile", + "assets/compose.assets.yml", "assets/.dockerignore", "assets/docker-compose.dcproj", + "assets/launchSettings.json", "assets/LocalPublishTarget.targets", "assets/ci-artifact-jobs.yml", + "assets/ci-pipeline.yml", +]; +foreach (var rel in required) + AssertTrue(File.Exists(Path.Combine(skillRoot, rel.Replace('/', Path.DirectorySeparatorChar))), $"Missing required dotnet-segregated-assets file: {rel}"); + +var skill = File.ReadAllText(Path.Combine(skillRoot, "SKILL.md")); +foreach (var needle in new[] +{ + "codebeltnet/web-cdn-origin:2.0.0", "/cdnroot", "wwwroot", "authoring root", ".Assets", + "App assets", "CDN assets", "CopyToPublishDirectory=\"Never\"", "Static Web Assets", "65532", "orchestrat", + "segregate-assets.cs", "generated-static-assets", "Boundaries", "AppTagHelperOptions", "CdnTagHelperOptions", + "app-link", "app-script", "app-img", "cdn-link", "cdn-script", "cdn-img", "Automatic", "BaseUrlMode", + "TagHelperBaseUrlMode", "ProtocolUriScheme", "ICacheBusting", "CacheBustingTagHelper", "AddCacheBusting", + "runner never edits", "NuGet.org", "resolvedNuGetPackages", "latest-stable", +}) +{ + AssertTrue(skill.Contains(needle, StringComparison.Ordinal), $"SKILL.md is missing required contract: {needle}"); +} + +var productionImage = File.ReadAllText(Path.Combine(skillRoot, "references", "production-image.md")); +var appVsCdn = File.ReadAllText(Path.Combine(skillRoot, "references", "app-vs-cdn.md")); +var localDevelopment = File.ReadAllText(Path.Combine(skillRoot, "references", "local-development.md")); +var runner = File.ReadAllText(Path.Combine(skillRoot, "scripts", "segregate-assets.cs")); + +foreach (var needle in new[] { "https://api.nuget.org/v3/index.json", "PackageBaseAddress/3.0.0", "latest-stable", "DependencyResolutionFailed", "nuget-package-version", "AssetsProfileSuffix", "LaunchProfileNaming.Resolve", "ASSET_SOURCE_NOT_VERSIONED", "ASSET_IMAGE_NOT_VALIDATED_IN_CI", "com.microsoft.visual-studio.project-name", "HasVisualStudioProjectOptOut", "ArtifactFirstValidator", "UnsafeOriginDetector", "NoObsoleteVersionKey", "DockerfilesColocated", "NoSourceCompilation", "CiPublishesArtifact", "ComposeFileSelector", "BelongsToAnotherProject" }) + AssertTrue(runner.Contains(needle, StringComparison.Ordinal), $"segregate-assets.cs is missing required contract: {needle}"); + +foreach (var needle in new[] { "resolvedNuGetPackages", "Directory.Packages.props", "prerelease", "stop without proposing a package edit" }) + AssertTrue(appVsCdn.Contains(needle, StringComparison.OrdinalIgnoreCase), $"references/app-vs-cdn.md is missing package-version guidance: {needle}"); + +foreach (var staleSyntax in new[] { "app-href", "cdn-src", "app-src", "cdn-href", "app-image", "cdn-image" }) + AssertTrue(!appVsCdn.Contains(staleSyntax, StringComparison.OrdinalIgnoreCase), $"references/app-vs-cdn.md contains stale syntax: {staleSyntax}"); + +using (var evalDoc = JsonDocument.Parse(File.ReadAllText(Path.Combine(skillRoot, "evals", "evals.json")))) +{ + var evals = evalDoc.RootElement.GetProperty("evals").EnumerateArray().ToList(); + string EvalText(JsonElement e) => (e.GetProperty("expected_output").GetString() ?? "") + "\n" + string.Join("\n", e.GetProperty("expectations").EnumerateArray().Select(x => x.GetString())); + + var cuemonEval = evals.FirstOrDefault(e => e.GetProperty("id").GetInt32() == 3); + AssertTrue(cuemonEval.ValueKind == JsonValueKind.Object, "evals.json must retain Cuemon eval id 3"); + var cuemonText = EvalText(cuemonEval); + foreach (var expected in new[] { "app-link", "app-script", "app-img", "cdn-link", "cdn-script", "cdn-img", "AppAssetOptions", "latest stable", "NuGet.org", "PackageVersion" }) + AssertTrue(cuemonText.Contains(expected, StringComparison.Ordinal), $"Cuemon eval missing: {expected}"); + + var vsEval = evals.FirstOrDefault(e => e.GetProperty("id").GetInt32() == 14); + AssertTrue(vsEval.ValueKind == JsonValueKind.Object, "evals.json must retain Visual Studio eval id 14"); + var placementEval = evals.FirstOrDefault(e => e.GetProperty("id").GetInt32() == 15); + AssertTrue(placementEval.ValueKind == JsonValueKind.Object, "evals.json must retain placement eval id 15"); +} + +var cuemonFixtureLayout = File.ReadAllText(Path.Combine(skillRoot, "evals", "files", "cuemon-app", "Views", "Shared", "_Layout.cshtml")); +foreach (var staleSyntax in new[] { "app-href", "cdn-src", "app-src", "cdn-href", "app-image", "cdn-image" }) + AssertTrue(!cuemonFixtureLayout.Contains(staleSyntax, StringComparison.OrdinalIgnoreCase), $"Cuemon fixture contains stale syntax: {staleSyntax}"); + +foreach (var selector in new[] { "app-link", "app-script", "app-img", "cdn-link", "cdn-script", "cdn-img" }) + AssertTrue(runner.Contains($"<{selector}\\b", StringComparison.Ordinal), $"segregate-assets.cs missing selector: {selector}"); +foreach (var invalid in new[] { "app-image", "cdn-image" }) + AssertTrue(!runner.Contains($"<{invalid}\\b", StringComparison.Ordinal), $"segregate-assets.cs contains invalid selector: {invalid}"); + +AssertTrue(File.ReadAllText(Path.Combine(skillRoot, "evals", "files", "cuemon-app", "Directory.Packages.props")).Contains("", StringComparison.Ordinal), "Cuemon fixture CPM version drifted"); +AssertTrue(File.ReadAllText(Path.Combine(skillRoot, "evals", "files", "cuemon-app", "Tolk.Web.csproj")).Contains("", StringComparison.Ordinal), "Cuemon fixture PackageReference drifted"); + +foreach (var vendor in new[] { "azure-pipelines", "gitlab-ci", "Jenkinsfile", "bitbucket-pipelines", "circleci", "teamcity" }) + AssertTrue(!productionImage.Contains(vendor, StringComparison.OrdinalIgnoreCase) && !runner.Contains(vendor, StringComparison.OrdinalIgnoreCase), $"Multi-vendor CI branch found: {vendor}"); + +var assetRoot = Path.Combine(skillRoot, "assets"); +foreach (var dockerfile in new[] { "Dockerfile", "LocalDevelopment.Dockerfile" }) +{ + var text = File.ReadAllText(Path.Combine(assetRoot, dockerfile)); + AssertTrue(text.Contains("COPY --chown=65532:65532 artifacts/publish/ .", StringComparison.Ordinal), $"assets/{dockerfile} missing artifact copy"); + AssertTrue(text.Contains("dhi.io/aspnetcore:", StringComparison.Ordinal), $"assets/{dockerfile} missing dhi.io/aspnetcore"); + foreach (var forbidden in new[] { "dotnet/sdk", "dotnet publish", "dotnet build", "dotnet restore", "adduser", "addgroup", "mcr.microsoft.com" }) + AssertTrue(!text.Contains(forbidden, StringComparison.OrdinalIgnoreCase), $"assets/{dockerfile} contains forbidden: {forbidden}"); +} +AssertTrue(File.ReadAllText(Path.Combine(assetRoot, "Assets.Dockerfile")).Contains("FROM codebeltnet/web-cdn-origin:2.0.0", StringComparison.Ordinal), "Assets.Dockerfile missing base image"); +var assetCompose = File.ReadAllText(Path.Combine(assetRoot, "compose.assets.yml")); +foreach (var needle in new[] { "web-app:", "app-assets:", "com.microsoft.visual-studio.project-name: \"\"", "read_only: true", "no-new-privileges:true", "LocalDevelopment.Dockerfile", "Assets.Dockerfile" }) + AssertTrue(assetCompose.Contains(needle, StringComparison.Ordinal), $"compose.assets.yml missing: {needle}"); +foreach (var forbidden in new[] { "version:", "networks:" }) + AssertTrue(!assetCompose.Contains(forbidden, StringComparison.Ordinal), $"compose.assets.yml must not declare: {forbidden}"); +AssertTrue(!Regex.IsMatch(File.ReadAllText(Path.Combine(assetRoot, ".dockerignore")), @"(?m)^\s*(\*\*/)?artifacts"), ".dockerignore must not exclude artifacts/"); + +var forms = File.ReadAllText(Path.Combine(skillRoot, "FORMS.md")); +foreach (var needle in new[] { "### cdn_equivalent", "plain-text", "### visual_studio_compose", "### web_host_port" }) + AssertTrue(forms.Contains(needle, StringComparison.Ordinal), $"FORMS.md missing: {needle}"); + +// === 2. Black-box CLI tests (from test-segregated-assets.ps1 + observability) === +var workspace = Path.Combine(Path.GetTempPath(), "segregated-harness-" + Guid.NewGuid().ToString("N")); +Directory.CreateDirectory(workspace); + +async Task InvokeRunnerAsync(params string[] runnerArgs) => + await Git.RunProcessAsync(Git.CreateStartInfo(dotnet, workspace, [app, .. runnerArgs]), stop.Token); + +try +{ + var selfTest = await InvokeRunnerAsync("--self-test", "--json"); + AssertTrue(selfTest.Code == 0, $"--self-test exited {selfTest.Code}: {selfTest.Error}"); + using (var stDoc = JsonDocument.Parse(selfTest.Output)) + { + AssertTrue(stDoc.RootElement.GetProperty("ok").GetBoolean(), "self-test ok should be true"); + AssertTrue(stDoc.RootElement.GetProperty("failed").GetInt32() == 0, "self-test failed should be 0"); + } + + var appDir = Path.Combine(workspace, "Web"); + Directory.CreateDirectory(Path.Combine(appDir, "wwwroot", "css")); + File.WriteAllText(Path.Combine(appDir, "Web.csproj"), """net10.0""", utf8NoBom); + File.WriteAllText(Path.Combine(appDir, "Program.cs"), "// entrypoint", utf8NoBom); + File.WriteAllText(Path.Combine(appDir, "wwwroot", "css", "site.css"), "body{}", utf8NoBom); + + var progressPath = Path.Combine(workspace, "seg-progress.json"); + var inspect = await InvokeRunnerAsync("inspect", "--repo-root", workspace, "--json", "--progress-file", progressPath); + AssertTrue(inspect.Code == 0, $"inspect exited {inspect.Code}: {inspect.Error}"); + AssertTrue(Regex.IsMatch(inspect.Output, "\"classification\":\\s*\"Simple\""), "inspect did not classify Simple"); + AssertTrue(inspect.Error.Contains("[START]", StringComparison.Ordinal) && inspect.Error.Contains("[COMPLETE]", StringComparison.Ordinal), "inspect missing stderr observability"); + using (var pDoc = JsonDocument.Parse(File.ReadAllText(progressPath))) + AssertTrue(pDoc.RootElement.GetProperty("state").GetString() == "succeeded", "progress file did not record succeeded"); + + // Progress file overlap rejection. + var overlap = await InvokeRunnerAsync("inspect", "--repo-root", workspace, "--json", "--progress-file", Path.Combine(appDir, "Web.csproj")); + AssertTrue(overlap.Code == 64, $"progress file overlap should exit 64, got {overlap.Code}"); + + var plan = await InvokeRunnerAsync("plan", "--repo-root", workspace, "--json", "--quiet", "--no-heartbeat"); + AssertTrue(plan.Code == 0, $"plan exited {plan.Code}: {plan.Error}"); + AssertTrue(plan.Output.Contains("publish-exclusion", StringComparison.Ordinal) && plan.Output.Contains("Assets.Dockerfile", StringComparison.Ordinal) && plan.Output.Contains("compose.assets.yml", StringComparison.Ordinal), "plan missing expected decisions"); + AssertTrue(Regex.IsMatch(plan.Output, "\"cdn-equivalent\"[\\s\\S]*?\"status\":\\s*\"skip\""), "plan did not skip cdn-equivalent"); + AssertTrue(!plan.Error.Contains("[START]", StringComparison.Ordinal), "--quiet should suppress [START] on stderr"); + + var cuemonDir = Path.Combine(workspace, "Cuemon"); + Directory.CreateDirectory(Path.Combine(cuemonDir, "Views", "Shared")); + File.WriteAllText(Path.Combine(cuemonDir, "Cuemon.csproj"), """net10.0""", utf8NoBom); + File.WriteAllText(Path.Combine(cuemonDir, "Program.cs"), "using Cuemon.AspNetCore.Razor.TagHelpers;\nbuilder.Services.Configure(builder.Configuration.GetSection(\"App\"));\nbuilder.Services.Configure(builder.Configuration.GetSection(\"Cdn\"));\nbuilder.Services.AddAssemblyCacheBusting();\nbuilder.Services.Configure(builder.Configuration.GetSection(\"Assets\"));\n", utf8NoBom); + File.WriteAllText(Path.Combine(cuemonDir, "AppAssetOptions.cs"), "public sealed class AppAssetOptions { public string GetUrl(string path) => path; }", utf8NoBom); + File.WriteAllText(Path.Combine(cuemonDir, "Views", "_ViewImports.cshtml"), "@addTagHelper *, Cuemon.AspNetCore.Razor.TagHelpers", utf8NoBom); + File.WriteAllText(Path.Combine(cuemonDir, "Views", "Shared", "_Layout.cshtml"), "@inject Microsoft.Extensions.Options.IOptions AppAssets\n\n\n\n\n@AppAssets.Value.GetUrl(\"~/css/site.css\")\n", utf8NoBom); + + var cuemonInspect = await InvokeRunnerAsync("inspect", "--repo-root", cuemonDir, "--json"); + AssertTrue(cuemonInspect.Code == 0, $"Cuemon inspect exited {cuemonInspect.Code}"); + AssertTrue(Regex.IsMatch(cuemonInspect.Output, "\"packageReference\":\\s*true") + && Regex.IsMatch(cuemonInspect.Output, "\"appLinkMarkup\":\\s*true") + && Regex.IsMatch(cuemonInspect.Output, "\"appImageMarkup\":\\s*true") + && Regex.IsMatch(cuemonInspect.Output, "\"cdnImageMarkup\":\\s*true") + && Regex.IsMatch(cuemonInspect.Output, "\"cuemonCacheBusting\":\\s*true") + && Regex.IsMatch(cuemonInspect.Output, "\"competingAbstractions\":\\s*true") + && Regex.IsMatch(cuemonInspect.Output, "\"legacyAttributeSyntax\":\\s*false"), "Cuemon inspect assertions failed"); + + var apiDir = Path.Combine(workspace, "Api"); + Directory.CreateDirectory(apiDir); + File.WriteAllText(Path.Combine(apiDir, "Api.csproj"), """net10.0""", utf8NoBom); + File.WriteAllText(Path.Combine(apiDir, "Program.cs"), "// entrypoint", utf8NoBom); + var cdnOnlyPlan = await InvokeRunnerAsync("plan", "--repo-root", workspace, "-p", "Api/Api.csproj", "--cdn-equivalent", "--json"); + AssertTrue(cdnOnlyPlan.Code == 0 && Regex.IsMatch(cdnOnlyPlan.Output, "\"step\":\\s*\"cdn-equivalent\"[\\s\\S]*?\"status\":\\s*\"create\"") && !Regex.IsMatch(cdnOnlyPlan.Output, "\"status\":\\s*\"blocked\""), "CDN-only plan failed"); + + var leakedPub = Path.Combine(workspace, "pub-leak"); + Directory.CreateDirectory(Path.Combine(leakedPub, "wwwroot", "css")); + File.WriteAllText(Path.Combine(leakedPub, "wwwroot", "css", "site.css"), "body{}", utf8NoBom); + var verifyLeak = await InvokeRunnerAsync("verify", "--repo-root", workspace, "-p", "Web/Web.csproj", "--publish-dir", leakedPub, "--json"); + AssertTrue(verifyLeak.Code == 66 && verifyLeak.Output.Contains("css/site.css", StringComparison.Ordinal), "verify did not detect leaked app asset"); + + var cleanPub = Path.Combine(workspace, "pub-clean"); + Directory.CreateDirectory(Path.Combine(cleanPub, "wwwroot", "_content", "Lib")); + File.WriteAllText(Path.Combine(cleanPub, "wwwroot", "_content", "Lib", "shared.css"), "/*shared*/", utf8NoBom); + var verifyClean = await InvokeRunnerAsync("verify", "--repo-root", workspace, "-p", "Web/Web.csproj", "--publish-dir", cleanPub, "--json"); + AssertTrue(verifyClean.Code == 0 && verifyClean.Output.Contains("_content/Lib/shared.css", StringComparison.Ordinal), "verify failed on clean publish"); + + var verifyIncompleteLocal = await InvokeRunnerAsync("verify", "--repo-root", workspace, "-p", "Web/Web.csproj", "--publish-dir", cleanPub, "--check-local", "--json"); + AssertTrue(verifyIncompleteLocal.Code == 66 && Regex.IsMatch(verifyIncompleteLocal.Output, "\"ok\":\\s*false"), "verify did not reject incomplete local topology"); +} +finally +{ + if (Directory.Exists(workspace)) + { + try { Directory.Delete(workspace, recursive: true); } catch { } + } +} + +Console.Out.WriteLine("dotnet-segregated-assets skill validation: PASS"); +return 0; diff --git a/scripts/tests/dotnet-test-tests.cs b/scripts/tests/dotnet-test-tests.cs new file mode 100644 index 00000000..c25e5282 --- /dev/null +++ b/scripts/tests/dotnet-test-tests.cs @@ -0,0 +1,641 @@ +#!/usr/bin/env dotnet +#:property TargetFramework=net10.0 +#:property RollForward=Major +#:property Nullable=enable +#:property PublishAot=false +#:include ../../skills/git-worktree-merge/scripts/GitProcess.cs +#:include ../../tooling/src/Agentic.Tooling/Execution/ExecutableResolver.cs +#:include ../eval-runners/windows-owned-process.cs + +using System.Diagnostics; +using System.Net; +using System.Net.Sockets; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using System.Xml.Linq; +using Agentic.Tooling.Execution; + +// A copy of this compiled apphost named `fake-dotnet` handles `restore` calls for offline resolver tests. +if (Path.GetFileNameWithoutExtension(Environment.ProcessPath) == "fake-dotnet") +{ + return FakeDotNetRestore.Run(args); +} + +if (args.Length < 2 || !File.Exists(args[0]) || !Directory.Exists(args[1])) +{ + throw new ArgumentException("Pass ."); +} + +var app = Path.GetFullPath(args[0]); +var skillRoot = Path.GetFullPath(args[1]); +var dotnet = ExecutableResolver.Resolve(OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); +var utf8NoBom = new UTF8Encoding(false); +using var stop = new CancellationTokenSource(TimeSpan.FromMinutes(3)); + +var workRoot = Path.Combine(Path.GetTempPath(), "dotnet-test-suite-" + Guid.NewGuid().ToString("N")); +Directory.CreateDirectory(workRoot); + +static void WriteFile(string path, string content) +{ + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllText(path, content, new UTF8Encoding(false)); +} + +static void AssertTrue(bool condition, string message) +{ + if (!condition) throw new InvalidOperationException(message); +} + +static void AssertEqual(T actual, T expected, string because) +{ + if (!EqualityComparer.Default.Equals(actual, expected)) + throw new InvalidOperationException($"Assertion failed: {because}. Expected '{expected}', got '{actual}'."); +} + +async Task RunToolAsync(string workingDirectory, IReadOnlyDictionary? env, params string[] toolArgs) +{ + var psi = Git.CreateStartInfo(dotnet, workingDirectory, [app, .. toolArgs]); + if (env is not null) + { + foreach (var (k, v) in env) psi.Environment[k] = v; + } + return await Git.RunProcessAsync(psi, stop.Token); +} + +try +{ + // === 1. Skill structure and contract checks (from validate-skill.ps1) === + string[] required = + [ + "SKILL.md", "FORMS.md", "evals/evals.json", + "scripts/dotnet-test.cs", "scripts/TestInspection.cs", "scripts/PackageResolution.cs", "scripts/MigrationVerification.cs", + "scripts/ExecutableResolver.cs", "scripts/GitProcess.cs", "scripts/ProgressFile.cs", "scripts/windows-owned-process.cs", + "references/unit-tests.md", "references/web-functional-tests.md", "references/application-functional-tests.md", + "references/bootstrapper-hosts.md", "references/xunit-v3-modernization.md", "references/migration-invariants.md", + "assets/unit/BehaviorTest.cs", "assets/web/FocusedWebApplicationTest.cs", "assets/web/SharedWebApplicationTest.cs", + "assets/application/FocusedApplicationTest.cs", "assets/application/SharedApplicationTest.cs", + "assets/bootstrapper/console/Program.cs", "assets/bootstrapper/console/Startup.cs", + "assets/bootstrapper/worker/Program.cs", "assets/bootstrapper/worker/Startup.cs", "assets/bootstrapper/worker/Worker.cs", + "assets/bootstrapper/console-minimal/Program.cs", "assets/bootstrapper/worker-minimal/Program.cs", + "assets/bootstrapper/web-minimal/Program.cs", + ]; + foreach (var rel in required) + { + AssertTrue(File.Exists(Path.Combine(skillRoot, rel.Replace('/', Path.DirectorySeparatorChar))), $"Missing required dotnet-test file: {rel}"); + } + + var skillText = File.ReadAllText(Path.Combine(skillRoot, "SKILL.md")); + foreach (var needle in new[] { "WebApplicationTestFactory", "ApplicationTestFactory", "ManagedWebApplicationFixture", "ManagedApplicationFixture", "scripts/dotnet-test.cs", "--expected-web-pattern", "--expected-application-pattern", "second composition root" }) + AssertTrue(skillText.Contains(needle, StringComparison.Ordinal), $"SKILL.md is missing required contract: {needle}"); + AssertTrue(skillText.Contains("An MTP executable run may supplement that gate but never replaces it", StringComparison.Ordinal), "SKILL.md must reject MTP executable substitution for requested dotnet test validation."); + foreach (var needle in new[] { "What finishing looks like", "Wrapping the factory", "Renaming the seam", "Bumping packages instead" }) + AssertTrue(skillText.Contains(needle, StringComparison.Ordinal), $"SKILL.md must keep the named laundering failure mode: {needle}"); + + var evalsText = File.ReadAllText(Path.Combine(skillRoot, "evals", "evals.json")); + foreach (var needle in new[] { "WebApplicationTestFactory.Create", "ManagedWebApplicationFixture", "WebApplication.CreateBuilder", "scripts/dotnet-test.cs", "nested private CdnOriginApplicationFactory" }) + AssertTrue(evalsText.Contains(needle, StringComparison.Ordinal), $"Web eval is missing regression contract: {needle}"); + + // === 2. Inspection regressions (from test-inspect-dotnet-tests.ps1) === + var inspectWorkspace = Path.Combine(workRoot, "inspect"); + Directory.CreateDirectory(inspectWorkspace); + WriteFile(Path.Combine(inspectWorkspace, "Directory.Packages.props"), """true"""); + WriteFile(Path.Combine(inspectWorkspace, "app/App.csproj"), """net10.0Exe"""); + WriteFile(Path.Combine(inspectWorkspace, "app/Program.cs"), """using Codebelt.Bootstrapper.Web; public class Program : MinimalWebProgram { public static void Main(string[] args) { var builder = CreateHostBuilder(args); var app = builder.Build(); app.MapGet("/", () => "ok"); app.Run(); } }"""); + WriteFile(Path.Combine(inspectWorkspace, "test/App.FunctionalTests/App.FunctionalTests.csproj"), """net10.0true"""); + WriteFile(Path.Combine(inspectWorkspace, "test/App.FunctionalTests/HealthTest.cs"), """using Microsoft.AspNetCore.Mvc.Testing; using Xunit.Abstractions; public class HealthTest : IClassFixture> { }"""); + WriteFile(Path.Combine(inspectWorkspace, "src/Widget/Widget.csproj"), """net10.0"""); + WriteFile(Path.Combine(inspectWorkspace, "test/Widget.Tests/Widget.Tests.csproj"), """net10.0true"""); + WriteFile(Path.Combine(inspectWorkspace, "worker/Worker.csproj"), """net10.0Exe"""); + WriteFile(Path.Combine(inspectWorkspace, "worker/Program.cs"), """using Codebelt.Bootstrapper.Worker; public class Program : MinimalWorkerProgram { public static async Task Main(string[] args) { var builder = CreateHostBuilder(args); await builder.Build().RunAsync(); } }"""); + WriteFile(Path.Combine(inspectWorkspace, "test/Worker.FunctionalTests/Worker.FunctionalTests.csproj"), """net10.0true"""); + WriteFile(Path.Combine(inspectWorkspace, "console/Console.csproj"), """net10.0Exe"""); + WriteFile(Path.Combine(inspectWorkspace, "console/Program.cs"), """using Codebelt.Bootstrapper.Console; public class Program : MinimalConsoleProgram { public static async Task Main(string[] args) { var builder = CreateHostBuilder(args); await builder.Build().RunAsync(); } public override Task RunAsync(IServiceProvider services, CancellationToken token) => Task.CompletedTask; }"""); + WriteFile(Path.Combine(inspectWorkspace, "test/Console.FunctionalTests/Console.FunctionalTests.csproj"), """net10.0true"""); + WriteFile(Path.Combine(inspectWorkspace, "legacy/Legacy.csproj"), """net10.0Exe"""); + WriteFile(Path.Combine(inspectWorkspace, "legacy/Program.cs"), """System.Console.WriteLine("legacy");"""); + WriteFile(Path.Combine(inspectWorkspace, "test/Legacy.FunctionalTests/Legacy.FunctionalTests.csproj"), """net10.0true"""); + + var inspectProgress = Path.Combine(workRoot, "inspect-progress.json"); + var allRun = await RunToolAsync(inspectWorkspace, null, "inspect", "--repo-root", inspectWorkspace, "--progress-file", inspectProgress); + AssertEqual(allRun.Code, 0, $"Full inspection should succeed: {allRun.Error}"); + AssertTrue(allRun.Error.Contains("[START]", StringComparison.Ordinal) && allRun.Error.Contains("[COMPLETE]", StringComparison.Ordinal), "inspect should emit stderr progress lines."); + using (var pDoc = JsonDocument.Parse(File.ReadAllText(inspectProgress))) + AssertEqual(pDoc.RootElement.GetProperty("state").GetString(), "succeeded", "inspect progress file should end in succeeded state"); + + // Progress file overlap check. + var overlapInspect = await RunToolAsync(inspectWorkspace, null, "inspect", "--repo-root", inspectWorkspace, "--progress-file", Path.Combine(inspectWorkspace, "Directory.Packages.props")); + AssertEqual(overlapInspect.Code, 2, "Overlapping progress file should exit 2"); + + using (var reportDoc = JsonDocument.Parse(allRun.Output)) + { + var report = reportDoc.RootElement; + AssertEqual(report.GetProperty("projectCount").GetInt32(), 5, "Expected five projects"); + var byPath = report.GetProperty("projects").EnumerateArray().ToDictionary(p => p.GetProperty("project").GetString()!, p => p); + var webProj = byPath["test/App.FunctionalTests/App.FunctionalTests.csproj"]; + var unitProj = byPath["test/Widget.Tests/Widget.Tests.csproj"]; + var workerProj = byPath["test/Worker.FunctionalTests/Worker.FunctionalTests.csproj"]; + var consoleProj = byPath["test/Console.FunctionalTests/Console.FunctionalTests.csproj"]; + var legacyProj = byPath["test/Legacy.FunctionalTests/Legacy.FunctionalTests.csproj"]; + AssertEqual(webProj.GetProperty("role").GetString(), "ASP.NET Core functional test", "web role"); + AssertEqual(unitProj.GetProperty("role").GetString(), "Ordinary unit test", "unit role"); + AssertEqual(workerProj.GetProperty("role").GetString(), "Console or worker functional test", "worker role"); + AssertEqual(consoleProj.GetProperty("role").GetString(), "Console or worker functional test", "console role"); + AssertTrue(legacyProj.GetProperty("role").GetString() == "Console or worker functional test" && legacyProj.GetProperty("blockers").GetArrayLength() >= 1, "Expected legacy executable Generic Host blocker"); + AssertEqual(webProj.GetProperty("xunitGeneration").GetString(), "v2", "web xUnit generation"); + AssertTrue(webProj.GetProperty("webApplicationFactoryUsages").GetArrayLength() >= 1, "Expected WebApplicationFactory usage"); + AssertTrue(webProj.GetProperty("packageOwnership").EnumerateArray().Any(p => p.GetProperty("id").GetString() == "xunit" && p.GetProperty("ownership").GetString() == "central"), "Expected central xunit package ownership"); + AssertEqual(webProj.GetProperty("referencedApplications")[0].GetProperty("hostPattern").GetString(), "MinimalWebProgram", "MinimalWebProgram"); + AssertEqual(workerProj.GetProperty("referencedApplications")[0].GetProperty("hostPattern").GetString(), "MinimalWorkerProgram", "MinimalWorkerProgram"); + AssertEqual(consoleProj.GetProperty("referencedApplications")[0].GetProperty("hostPattern").GetString(), "MinimalConsoleProgram", "MinimalConsoleProgram"); + } + + WriteFile(Path.Combine(inspectWorkspace, "test/App.FunctionalTests/HealthTest.cs"), """using Codebelt.Extensions.Xunit.Hosting.AspNetCore; public class HealthTest { public void Create() { using var application = WebApplicationTestFactory.Create(hostFixture: new ManagedWebApplicationFixture()); } }"""); + var focusedRun = await RunToolAsync(inspectWorkspace, null, "inspect", "-RepoRoot", inspectWorkspace, "-ProjectPath", "test/App.FunctionalTests/App.FunctionalTests.csproj", "-ExpectedWebPattern", "Focused"); + AssertEqual(focusedRun.Code, 0, $"Focused web postcondition should pass: {focusedRun.Error}"); + using (var doc = JsonDocument.Parse(focusedRun.Output)) + { + var p = doc.RootElement.GetProperty("projects")[0]; + AssertEqual(p.GetProperty("focusedWebApplicationTestFactoryUsages").GetArrayLength(), 1, "focused usage"); + AssertEqual(p.GetProperty("managedWebApplicationFixtureUsages").GetArrayLength(), 1, "managed web fixture"); + AssertEqual(p.GetProperty("directWebHostConstructions").GetArrayLength(), 0, "no direct host"); + } + + WriteFile(Path.Combine(inspectWorkspace, "test/App.FunctionalTests/HealthTest.cs"), """using Codebelt.Extensions.Xunit; using Codebelt.Extensions.Xunit.Hosting; using Codebelt.Extensions.Xunit.Hosting.AspNetCore; public class HealthTest : Test { private readonly IHostTest _application = WebApplicationTestFactory.Create(hostFixture: new ManagedWebApplicationFixture()); protected override void OnDisposeManagedResources() { _application.Dispose(); base.OnDisposeManagedResources(); } protected override async ValueTask OnDisposeManagedResourcesAsync() { await _application.DisposeAsync(); await base.OnDisposeManagedResourcesAsync(); } }"""); + var harnessRun = await RunToolAsync(inspectWorkspace, null, "inspect", "--repo-root", inspectWorkspace, "--project-path", "test/App.FunctionalTests/App.FunctionalTests.csproj", "--expected-web-pattern", "Focused"); + AssertEqual(harnessRun.Code, 0, "Focused harness with both dispose hooks should pass"); + using (var doc = JsonDocument.Parse(harnessRun.Output)) + AssertEqual(doc.RootElement.GetProperty("projects")[0].GetProperty("hostTestOwnerships").GetArrayLength(), 1, "IHostTest ownership record"); + + WriteFile(Path.Combine(inspectWorkspace, "test/App.FunctionalTests/HealthTest.cs"), """using Codebelt.Extensions.Xunit; using Codebelt.Extensions.Xunit.Hosting; using Codebelt.Extensions.Xunit.Hosting.AspNetCore; public class HealthTest : Test { private readonly IHostTest _application = WebApplicationTestFactory.Create(hostFixture: new ManagedWebApplicationFixture()); protected override void OnDisposeManagedResources() { _application.Dispose(); base.OnDisposeManagedResources(); } }"""); + var leakingRun = await RunToolAsync(inspectWorkspace, null, "inspect", "--repo-root", inspectWorkspace, "--project-path", "test/App.FunctionalTests/App.FunctionalTests.csproj", "--expected-web-pattern", "Focused"); + AssertEqual(leakingRun.Code, 2, "Incomplete disposal hooks should exit 2"); + using (var doc = JsonDocument.Parse(leakingRun.Output)) + AssertTrue(doc.RootElement.GetProperty("projects")[0].GetProperty("blockers").EnumerateArray().Any(b => b.GetString()!.Contains("both synchronous and asynchronous")), "Expected disposal blocker"); + + WriteFile(Path.Combine(inspectWorkspace, "test/App.FunctionalTests/HealthTest.cs"), """using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.TestHost; public class HealthTest { public void Create() { var builder = WebApplication.CreateBuilder(); builder.WebHost.UseTestServer(); } }"""); + var manualRun = await RunToolAsync(inspectWorkspace, null, "inspect", "--repo-root", inspectWorkspace, "--project-path", "test/App.FunctionalTests/App.FunctionalTests.csproj", "--expected-web-pattern", "Focused"); + AssertEqual(manualRun.Code, 2, "Direct host reconstruction should exit 2"); + using (var doc = JsonDocument.Parse(manualRun.Output)) + { + var p = doc.RootElement.GetProperty("projects")[0]; + AssertEqual(p.GetProperty("directWebHostConstructions").GetArrayLength(), 1, "direct construction evidence"); + AssertTrue(p.GetProperty("blockers").EnumerateArray().Any(b => b.GetString()!.Contains("replacement host")), "replacement-host blocker"); + } + + WriteFile(Path.Combine(inspectWorkspace, "test/App.FunctionalTests/HealthTest.cs"), """using Codebelt.Extensions.Xunit.Hosting.AspNetCore; public class HealthTest : WebApplicationTest> { public HealthTest(ManagedWebApplicationFixture fixture) : base(fixture) { } }"""); + var sharedWebRun = await RunToolAsync(inspectWorkspace, null, "inspect", "--repo-root", inspectWorkspace, "--project-path", "test/App.FunctionalTests/App.FunctionalTests.csproj", "--expected-web-pattern", "Shared"); + AssertEqual(sharedWebRun.Code, 0, "Shared web postcondition should pass"); + + WriteFile(Path.Combine(inspectWorkspace, "test/App.FunctionalTests/HealthTest.cs"), """using Codebelt.Extensions.Xunit.Hosting.AspNetCore; public class HealthTest : WebApplicationTest> { public HealthTest(BlockingManagedWebApplicationFixture fixture) : base(fixture) { } }"""); + var blockingRun = await RunToolAsync(inspectWorkspace, null, "inspect", "--repo-root", inspectWorkspace, "--project-path", "test/App.FunctionalTests/App.FunctionalTests.csproj", "--expected-web-pattern", "Shared"); + AssertEqual(blockingRun.Code, 2, "Blocking fixture should exit 2"); + + WriteFile(Path.Combine(inspectWorkspace, "test/Worker.FunctionalTests/WorkerTest.cs"), """using Codebelt.Extensions.Xunit.Hosting; public class WorkerTest { public void Create() { using var application = ApplicationTestFactory.Create(hostFixture: new ManagedApplicationFixture()); } }"""); + var focusedAppRun = await RunToolAsync(inspectWorkspace, null, "inspect", "--repo-root", inspectWorkspace, "--project-path", "test/Worker.FunctionalTests/Worker.FunctionalTests.csproj", "--expected-application-pattern", "Focused"); + AssertEqual(focusedAppRun.Code, 0, "Focused application postcondition should pass"); + + WriteFile(Path.Combine(inspectWorkspace, "test/Console.FunctionalTests/ConsoleTest.cs"), """using Codebelt.Extensions.Xunit.Hosting; public class ConsoleTest : ApplicationTest> { public ConsoleTest(ManagedApplicationFixture fixture) : base(fixture) { } }"""); + var sharedAppRun = await RunToolAsync(inspectWorkspace, null, "inspect", "--repo-root", inspectWorkspace, "--project-path", "test/Console.FunctionalTests/Console.FunctionalTests.csproj", "--expected-application-pattern", "Shared"); + AssertEqual(sharedAppRun.Code, 0, "Shared application postcondition should pass"); + + WriteFile(Path.Combine(inspectWorkspace, "Directory.Packages.props"), """true"""); + WriteFile(Path.Combine(inspectWorkspace, "test/App.FunctionalTests/App.FunctionalTests.csproj"), """net10.0true"""); + var belowFloor = await RunToolAsync(inspectWorkspace, null, "inspect", "--repo-root", inspectWorkspace, "--project-path", "test/App.FunctionalTests/App.FunctionalTests.csproj"); + AssertTrue(belowFloor.Output.Contains("Raise Codebelt.Extensions.Xunit.App from 11.0.10 to at least 11.1.0", StringComparison.Ordinal), "Expected version-floor recommendation"); + + WriteFile(Path.Combine(inspectWorkspace, "Directory.Packages.props"), """true"""); + var atFloor = await RunToolAsync(inspectWorkspace, null, "inspect", "--repo-root", inspectWorkspace, "--project-path", "test/App.FunctionalTests/App.FunctionalTests.csproj"); + AssertTrue(!atFloor.Output.Contains("to at least 11.1.0", StringComparison.Ordinal), "Did not expect version-floor recommendation at/above 11.1.0"); + + // === 3. Package resolution regressions (from test-resolve-test-package-versions.ps1) === + var fakeDotnetPath = CreateFakeDotNetCopy(workRoot); + var restoreLogFile = Path.Combine(workRoot, "restore-requests.log"); + await using var nugetServer = new MockNuGetFlatContainer(); + + async Task InvokeResolverAsync(string[] packages, int? maxCandidates = null, string? cacheDir = null, string? anchorVersion = null, Dictionary? extraEnv = null) + { + var env = new Dictionary + { + ["FAKE_DOTNET_LOG"] = restoreLogFile, + ["FAKE_DOTNET_MODE"] = nugetServer.RestoreMode, + ["FAKE_DOTNET_FAIL_PKG"] = nugetServer.FailPackageId ?? string.Empty, + ["FAKE_DOTNET_FAIL_VER"] = nugetServer.FailVersion ?? string.Empty, + ["FAKE_DOTNET_FAIL_COMBO"] = nugetServer.FailCombination ?? string.Empty, + }; + if (extraEnv is not null) foreach (var (k, v) in extraEnv) env[k] = v; + List toolArgs = ["resolve-packages", "--target-framework", "net10.0", "--role", "Unit", "--service-index-url", $"{nugetServer.BaseUrl}/v3/index.json", "--restore-executable", fakeDotnetPath]; + foreach (var pkg in packages) { toolArgs.Add("--package-id"); toolArgs.Add(pkg); } + if (maxCandidates is not null) { toolArgs.Add("--maximum-candidates"); toolArgs.Add(maxCandidates.Value.ToString()); } + if (cacheDir is not null) { toolArgs.Add("--cache-directory"); toolArgs.Add(cacheDir); } + if (anchorVersion is not null) { toolArgs.Add("--xunit-anchor-version"); toolArgs.Add(anchorVersion); } + return await RunToolAsync(workRoot, env, [.. toolArgs]); + } + + int CountRestoreRequests() => File.Exists(restoreLogFile) ? File.ReadAllLines(restoreLogFile).Count(l => !string.IsNullOrWhiteSpace(l)) : 0; + string[] ReadRestoreRequests() => File.Exists(restoreLogFile) ? File.ReadAllLines(restoreLogFile).Where(l => !string.IsNullOrWhiteSpace(l)).ToArray() : []; + void ResetMocks() + { + nugetServer.Reset(); + if (File.Exists(restoreLogFile)) File.Delete(restoreLogFile); + } + + // 3a. Stable candidate resolution + ResetMocks(); + nugetServer.SetVersions("Stable.Package", ["11.0.0-rc.1", "10.0.0", "9.99.0", "9.98.0"]); + var stable = await InvokeResolverAsync(["Stable.Package"], 2); + AssertEqual(stable.Code, 0, $"stable candidate resolution should succeed: {stable.Error}"); + using (var doc = JsonDocument.Parse(stable.Output)) + AssertEqual(doc.RootElement.GetProperty("packages")[0].GetProperty("version").GetString(), "10.0.0", "stable versions must be numerically ordered and prereleases excluded"); + + // 3b. Candidate fallback + ResetMocks(); + nugetServer.SetVersions("Fallback.Package", ["3.0.0", "2.0.0"]); + nugetServer.RestoreMode = "FailPackageVersion"; + nugetServer.FailPackageId = "Fallback.Package"; + nugetServer.FailVersion = "3.0.0"; + var fallback = await InvokeResolverAsync(["Fallback.Package"], 2); + AssertEqual(fallback.Code, 0, "an older restorable candidate should be selected"); + using (var doc = JsonDocument.Parse(fallback.Output)) + AssertEqual(doc.RootElement.GetProperty("packages")[0].GetProperty("version").GetString(), "2.0.0", "candidate fallback should continue after a restore failure"); + AssertEqual(CountRestoreRequests(), 2, "the failed newest candidate and fallback candidate should both be tested"); + + // 3c. Combined package set compatibility recovery + ResetMocks(); + nugetServer.SetVersions("Package.A", ["2.0.0", "1.0.0"]); + nugetServer.SetVersions("Package.B", ["2.0.0", "1.0.0"]); + nugetServer.RestoreMode = "FailCombination"; + nugetServer.FailCombination = "Package.A=2.0.0;Package.B=2.0.0"; + var combined = await InvokeResolverAsync(["Package.A", "Package.B"], 2); + AssertEqual(combined.Code, 0, "resolver should recover from an incompatible combined package set"); + using (var doc = JsonDocument.Parse(combined.Output)) + { + var map = doc.RootElement.GetProperty("packages").EnumerateArray().ToDictionary(p => p.GetProperty("packageId").GetString()!, p => p); + AssertEqual(map["Package.A"].GetProperty("version").GetString(), "2.0.0", "first package retained"); + AssertEqual(map["Package.B"].GetProperty("version").GetString(), "1.0.0", "second package fell back"); + AssertEqual(map["Package.A"].GetProperty("compatibility").GetString(), "combined restore passed", "compatibility label"); + } + AssertTrue(ReadRestoreRequests().Any(r => r.Contains(';')), "compatibility must be tested with the combined package set"); + + // 3d. Fail-closed with restore evidence + ResetMocks(); + nugetServer.SetVersions("Failure.Package", ["2.0.0", "1.0.0"]); + nugetServer.RestoreMode = "FailAll"; + var failed = await InvokeResolverAsync(["Failure.Package"], 2); + AssertTrue(failed.Code != 0, "resolver restore failure must fail closed"); + AssertTrue(failed.Error.Contains("No stable 'Failure.Package' version", StringComparison.Ordinal), "failure output must identify package"); + AssertTrue(failed.Error.Contains("NU_TEST_RESTORE_FAILURE", StringComparison.Ordinal), "failure output must preserve restore evidence"); + + // 3e. Cache reuse skips HTTP and restores + ResetMocks(); + nugetServer.SetVersions("Cached.Package", ["5.0.0", "4.0.0"]); + var cacheRoot = Path.Combine(workRoot, "resolver-cache"); + var firstCache = await InvokeResolverAsync(["Cached.Package"], 1, cacheDir: cacheRoot); + AssertEqual(firstCache.Code, 0, "cache seed should succeed"); + using (var doc = JsonDocument.Parse(firstCache.Output)) + AssertEqual(doc.RootElement.GetProperty("cache").GetProperty("hit").GetBoolean(), false, "first call is live"); + var restoresBefore = CountRestoreRequests(); + var httpBefore = nugetServer.HttpRequests; + var secondCache = await InvokeResolverAsync(["Cached.Package"], 1, cacheDir: cacheRoot); + AssertEqual(secondCache.Code, 0, "cache reuse should succeed"); + using (var doc = JsonDocument.Parse(secondCache.Output)) + { + AssertEqual(doc.RootElement.GetProperty("cache").GetProperty("hit").GetBoolean(), true, "second call is cache hit"); + AssertEqual(doc.RootElement.GetProperty("packages")[0].GetProperty("version").GetString(), "5.0.0", "cached package preserved"); + } + AssertEqual(CountRestoreRequests(), restoresBefore, "cache reuse skips restores"); + AssertEqual(nugetServer.HttpRequests, httpBefore, "cache reuse skips NuGet HTTP lookups"); + + // 3f. DOTNET_TEST_MAXIMUM_CANDIDATES env var + ResetMocks(); + nugetServer.SetVersions("Limited.Package", ["4.0.0", "3.0.0"]); + nugetServer.RestoreMode = "FailPackageVersion"; + nugetServer.FailPackageId = "Limited.Package"; + nugetServer.FailVersion = "4.0.0"; + var limited = await InvokeResolverAsync(["Limited.Package"], extraEnv: new() { ["DOTNET_TEST_MAXIMUM_CANDIDATES"] = "1" }); + AssertTrue(limited.Code != 0 && limited.Error.Contains("newest 1 candidates", StringComparison.Ordinal), "env candidate limit constrains default breadth"); + + // 3g. xUnit anchor ceiling and 1:1 pinning + ResetMocks(); + nugetServer.SetVersions("Codebelt.Extensions.Xunit", ["11.2.1", "11.1.0"]); + nugetServer.SetNuspec("Codebelt.Extensions.Xunit", "11.2.1", new() { ["xunit.v3.assert"] = "3.2.2", ["xunit.v3.extensibility.core"] = "3.2.2" }); + nugetServer.SetVersions("xunit.v3.assert", ["4.0.0", "3.3.0", "3.2.2"]); + nugetServer.SetVersions("xunit.v3", ["4.0.0", "3.3.0", "3.2.2"]); + var anchored = await InvokeResolverAsync(["Codebelt.Extensions.Xunit", "xunit.v3", "xunit.v3.assert"], 1); + AssertEqual(anchored.Code, 0, $"anchored resolution should succeed: {anchored.Error}"); + using (var doc = JsonDocument.Parse(anchored.Output)) + { + AssertEqual(doc.RootElement.GetProperty("xunitAnchor").GetProperty("packageId").GetString(), "Codebelt.Extensions.Xunit", "anchor package"); + AssertEqual(doc.RootElement.GetProperty("xunitAnchor").GetProperty("major").GetInt32(), 3, "anchor major"); + var map = doc.RootElement.GetProperty("packages").EnumerateArray().ToDictionary(p => p.GetProperty("packageId").GetString()!, p => p); + AssertEqual(map["xunit.v3.assert"].GetProperty("version").GetString(), "3.2.2", "1:1 anchor match"); + AssertTrue(map["xunit.v3.assert"].GetProperty("constraint").GetString()!.Contains("matched 1:1"), "1:1 constraint message"); + AssertEqual(map["xunit.v3"].GetProperty("version").GetString(), "3.3.0", "newest below anchor major"); + AssertEqual(map["Codebelt.Extensions.Xunit"].GetProperty("version").GetString(), "11.2.1", "anchor itself unconstrained"); + } + AssertTrue(!ReadRestoreRequests().Any(r => r.Contains("=4.0.0")), "no candidate above the anchored major may reach a restore"); + + // 3h. Anchor precedes candidate trim + ResetMocks(); + nugetServer.SetVersions("Codebelt.Extensions.Xunit", ["11.2.1"]); + nugetServer.SetNuspec("Codebelt.Extensions.Xunit", "11.2.1", new() { ["xunit.v3.assert"] = "3.2.2" }); + nugetServer.SetVersions("xunit.v3", ["4.0.1", "4.0.0", "3.2.2"]); + var trimmed = await InvokeResolverAsync(["Codebelt.Extensions.Xunit", "xunit.v3"], 2); + AssertEqual(trimmed.Code, 0, "candidate limit applies after anchored ceiling"); + using (var doc = JsonDocument.Parse(trimmed.Output)) + AssertEqual(doc.RootElement.GetProperty("packages").EnumerateArray().First(p => p.GetProperty("packageId").GetString() == "xunit.v3").GetProperty("version").GetString(), "3.2.2", "3.2.2 survived trim"); + + // 3i. Ceiling failure when no version at/below anchor major exists + ResetMocks(); + nugetServer.SetVersions("Codebelt.Extensions.Xunit", ["11.2.1"]); + nugetServer.SetNuspec("Codebelt.Extensions.Xunit", "11.2.1", new() { ["xunit.v3.assert"] = "3.2.2" }); + nugetServer.SetVersions("xunit.runner.visualstudio", ["4.0.0"]); + var ceiling = await InvokeResolverAsync(["Codebelt.Extensions.Xunit", "xunit.runner.visualstudio"], 2); + AssertTrue(ceiling.Code != 0 && ceiling.Error.Contains("at or below major 3", StringComparison.Ordinal), "ceiling failure must name anchored major"); + + // 3j. Explicit --xunit-anchor-version + ResetMocks(); + nugetServer.SetVersions("Codebelt.Extensions.Xunit", ["12.0.0", "11.2.1"]); + nugetServer.SetNuspec("Codebelt.Extensions.Xunit", "12.0.0", new() { ["xunit.v3.assert"] = "4.0.0" }); + nugetServer.SetNuspec("Codebelt.Extensions.Xunit", "11.2.1", new() { ["xunit.v3.assert"] = "3.2.2" }); + nugetServer.SetVersions("xunit.v3", ["4.0.0", "3.2.2"]); + var pinned = await InvokeResolverAsync(["xunit.v3"], 1, anchorVersion: "11.2.1"); + AssertEqual(pinned.Code, 0, "explicit anchor version should resolve"); + using (var doc = JsonDocument.Parse(pinned.Output)) + { + AssertEqual(doc.RootElement.GetProperty("xunitAnchor").GetProperty("version").GetString(), "11.2.1", "explicit anchor honored"); + AssertEqual(doc.RootElement.GetProperty("packages")[0].GetProperty("version").GetString(), "3.2.2", "ceiling followed pinned anchor"); + } + + // === 4. Migration verification gate regressions (from test-verify-dotnet-test-migration.ps1) === + var verifyWorkspace = Path.Combine(workRoot, "verify"); + Directory.CreateDirectory(verifyWorkspace); + const string projectRel = "test/App.FunctionalTests/App.FunctionalTests.csproj"; + var packagesPath = Path.Combine(verifyWorkspace, "Directory.Packages.props"); + var testProjectPath = Path.Combine(verifyWorkspace, projectRel.Replace('/', Path.DirectorySeparatorChar)); + var harnessPath = Path.Combine(verifyWorkspace, "test/App.FunctionalTests/AppTestApplication.cs".Replace('/', Path.DirectorySeparatorChar)); + var assetsPath = Path.Combine(verifyWorkspace, "test/App.FunctionalTests/obj/project.assets.json".Replace('/', Path.DirectorySeparatorChar)); + + const string anchoredPackages = """true"""; + const string legacyRefs = """net10.0true"""; + const string migratedRefs = """net10.0true"""; + const string launderedHarness = """ + using Microsoft.AspNetCore.Mvc.Testing; + public sealed class AppTestApplication : IDisposable + { + private readonly WebApplicationFactory _factory; + private AppTestApplication(WebApplicationFactory factory) { _factory = factory; } + public static AppTestApplication Create() => new AppTestApplication(new AppApplicationFactory()); + public HttpClient CreateClient() => _factory.CreateClient(); + public void Dispose() { _factory.Dispose(); } + private sealed class AppApplicationFactory : WebApplicationFactory { } + } + """; + const string migratedHarness = """ + using Codebelt.Extensions.Xunit; + using Codebelt.Extensions.Xunit.Hosting; + using Codebelt.Extensions.Xunit.Hosting.AspNetCore; + public class HealthTest : Test + { + private readonly IHostTest _application = WebApplicationTestFactory.Create(hostFixture: new ManagedWebApplicationFixture()); + protected override void OnDisposeManagedResources() { _application.Dispose(); base.OnDisposeManagedResources(); } + protected override async ValueTask OnDisposeManagedResourcesAsync() { await _application.DisposeAsync(); await base.OnDisposeManagedResourcesAsync(); } + } + """; + + WriteFile(Path.Combine(verifyWorkspace, "app/App.csproj"), """net10.0Exe"""); + WriteFile(Path.Combine(verifyWorkspace, "app/Program.cs"), """public class Program { public static void Main(string[] args) { var builder = WebApplication.CreateBuilder(args); builder.Build().Run(); } }"""); + WriteFile(packagesPath, anchoredPackages); + WriteFile(testProjectPath, legacyRefs); + WriteFile(harnessPath, launderedHarness); + WriteFile(assetsPath, """{"version":3,"targets":{"net10.0":{"Codebelt.Extensions.Xunit.App/11.2.1":{"type":"package","dependencies":{"Codebelt.Extensions.Xunit":"11.2.1","xunit.v3.assert":"3.2.2","xunit.v3.extensibility.core":"3.2.2"}}}},"libraries":{}}"""); + + void AssertCodes(string scenario, Git.Result run, int expectedExit, string[] expected, string[] forbidden) + { + AssertEqual(run.Code, expectedExit, $"[{scenario}] exit code. Out: {run.Output} Err: {run.Error}"); + foreach (var code in expected) AssertTrue(run.Output.Contains($"[{code}]", StringComparison.Ordinal), $"[{scenario}] expected violation [{code}].\n{run.Output}"); + foreach (var code in forbidden) AssertTrue(!run.Output.Contains($"[{code}]", StringComparison.Ordinal), $"[{scenario}] did not expect [{code}].\n{run.Output}"); + } + + var noGit = await RunToolAsync(verifyWorkspace, null, "verify", "--repo-root", verifyWorkspace, "--project-path", projectRel, "--expected-web-pattern", "Focused"); + AssertCodes("laundered facade without git", noGit, 1, ["LAUNDERED-FACADE", "WAF-RETAINED", "PATTERN-MISSING", "FIXTURE-MISSING", "LEGACY-PACKAGE-RETAINED"], ["CHURN-WITHOUT-CONVERSION"]); + + await Git.RunAsync(verifyWorkspace, stop.Token, ["init", "--quiet"]); + var laundered = await RunToolAsync(verifyWorkspace, null, "verify", "--repo-root", verifyWorkspace, "--project-path", projectRel, "--expected-web-pattern", "Focused"); + AssertCodes("laundered facade", laundered, 1, ["LAUNDERED-FACADE", "CHURN-WITHOUT-CONVERSION"], []); + AssertTrue(Regex.IsMatch(laundered.Output, @"result\s+:\s+FAILED"), "Expected FAILED verdict line"); + + // Positive control: completed migration passes. + File.Delete(harnessPath); + WriteFile(Path.Combine(verifyWorkspace, "test/App.FunctionalTests/HealthTest.cs"), migratedHarness); + WriteFile(testProjectPath, migratedRefs); + var migrated = await RunToolAsync(verifyWorkspace, null, "verify", "--repo-root", verifyWorkspace, "--project-path", projectRel, "--expected-web-pattern", "Focused"); + AssertCodes("completed migration", migrated, 0, [], ["LAUNDERED-FACADE", "WAF-RETAINED", "PATTERN-MISSING", "FIXTURE-MISSING", "LEGACY-PACKAGE-RETAINED", "CHURN-WITHOUT-CONVERSION", "XUNIT-ANCHOR-BREACH"]); + AssertTrue(Regex.IsMatch(migrated.Output, @"result\s+:\s+PASSED"), "Expected PASSED verdict line"); + AssertTrue(Regex.IsMatch(migrated.Output, @"anchor\s+:\s+Codebelt\.Extensions\.Xunit\.App 11\.2\.1"), "Expected resolved anchor in verdict"); + + // xunit major breach + WriteFile(packagesPath, anchoredPackages.Replace("Include=\"xunit.v3\" Version=\"3.2.2\"", "Include=\"xunit.v3\" Version=\"4.0.0\"")); + var anchorBreach = await RunToolAsync(verifyWorkspace, null, "verify", "--repo-root", verifyWorkspace, "--project-path", projectRel, "--expected-web-pattern", "Focused"); + AssertCodes("xunit major breach", anchorBreach, 1, ["XUNIT-ANCHOR-BREACH"], []); + AssertTrue(anchorBreach.Output.Contains("xunit.v3 is pinned to 4.0.0", StringComparison.Ordinal), "Expected offending id and version"); + + // anchored id exact drift + WriteFile(packagesPath, anchoredPackages.Replace("Include=\"xunit.v3.assert\" Version=\"3.2.2\"", "Include=\"xunit.v3.assert\" Version=\"3.1.0\"")); + var exactBreach = await RunToolAsync(verifyWorkspace, null, "verify", "--repo-root", verifyWorkspace, "--project-path", projectRel, "--expected-web-pattern", "Focused"); + AssertCodes("anchored id drift", exactBreach, 1, ["XUNIT-ANCHOR-BREACH"], []); + AssertTrue(exactBreach.Output.Contains("declares 3.2.2", StringComparison.Ordinal), "Expected declared anchor version"); + + // unrestored anchor warning + WriteFile(packagesPath, anchoredPackages); + File.Delete(assetsPath); + var unverified = await RunToolAsync(verifyWorkspace, null, "verify", "--repo-root", verifyWorkspace, "--project-path", projectRel, "--expected-web-pattern", "Focused", "--quiet", "--no-heartbeat"); + AssertCodes("unrestored anchor", unverified, 0, [], ["XUNIT-ANCHOR-BREACH"]); + AssertTrue(unverified.Output.Contains("XUNIT-ANCHOR-UNVERIFIED", StringComparison.Ordinal), "Expected unverified warning"); + AssertTrue(!unverified.Error.Contains("[START]", StringComparison.Ordinal), "--quiet should suppress [START]"); + + // missing expected pattern usage error + var missingExp = await RunToolAsync(verifyWorkspace, null, "verify", "--repo-root", verifyWorkspace, "--project-path", projectRel); + AssertEqual(missingExp.Code, 2, "Expected exit 2 without expected pattern"); + + Console.Out.WriteLine("dotnet-test skill validation: PASS"); + return 0; +} +finally +{ + if (Directory.Exists(workRoot)) + { + try { Directory.Delete(workRoot, recursive: true); } catch { } + } +} + +static string CreateFakeDotNetCopy(string root) +{ + var dir = Path.Combine(root, "fake-bin"); + Directory.CreateDirectory(dir); + var sourceDir = AppContext.BaseDirectory; + foreach (var sibling in Directory.EnumerateFiles(sourceDir)) + { + File.Copy(sibling, Path.Combine(dir, Path.GetFileName(sibling)), overwrite: true); + } + var ext = OperatingSystem.IsWindows() ? ".exe" : string.Empty; + var hostName = Path.GetFileNameWithoutExtension(typeof(FakeDotNetRestore).Assembly.Location) + ext; + var sourceHost = Path.Combine(dir, hostName); + var dest = Path.Combine(dir, "fake-dotnet" + ext); + File.Move(sourceHost, dest, overwrite: true); + if (!OperatingSystem.IsWindows()) + { + File.SetUnixFileMode(dest, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute | UnixFileMode.GroupRead | UnixFileMode.GroupExecute | UnixFileMode.OtherRead | UnixFileMode.OtherExecute); + } + return dest; +} + +internal static class FakeDotNetRestore +{ + public static int Run(string[] arguments) + { + if (arguments.Length < 2 || arguments[0] != "restore") + { + Console.Error.WriteLine($"Unexpected fake-dotnet invocation: {string.Join(' ', arguments)}"); + return 2; + } + var projectPath = arguments[1]; + var doc = XDocument.Load(projectPath); + var refs = doc.Descendants().Where(e => e.Name.LocalName == "PackageReference") + .Select(e => (Id: e.Attribute("Include")?.Value ?? "", Version: e.Attribute("Version")?.Value ?? "")) + .OrderBy(r => r.Id, StringComparer.Ordinal) + .ToList(); + var key = string.Join(';', refs.Select(r => $"{r.Id}={r.Version}")); + var logFile = Environment.GetEnvironmentVariable("FAKE_DOTNET_LOG"); + if (!string.IsNullOrWhiteSpace(logFile)) File.AppendAllText(logFile, key + Environment.NewLine); + + var mode = Environment.GetEnvironmentVariable("FAKE_DOTNET_MODE") ?? "Success"; + var failPkg = Environment.GetEnvironmentVariable("FAKE_DOTNET_FAIL_PKG") ?? ""; + var failVer = Environment.GetEnvironmentVariable("FAKE_DOTNET_FAIL_VER") ?? ""; + var failCombo = Environment.GetEnvironmentVariable("FAKE_DOTNET_FAIL_COMBO") ?? ""; + + string? failure = mode switch + { + "FailAll" => "NU_TEST_RESTORE_FAILURE: forced restore failure.", + "FailPackageVersion" when refs.Any(r => r.Id == failPkg && r.Version == failVer) => "NU_TEST_RESTORE_FAILURE: forced candidate failure.", + "FailCombination" when key == failCombo => "NU_TEST_RESTORE_FAILURE: forced combined-package failure.", + _ => null, + }; + if (failure is not null) + { + Console.Out.WriteLine(failure); + return 1; + } + Console.Out.WriteLine("restore succeeded"); + return 0; + } +} + +internal sealed class MockNuGetFlatContainer : IAsyncDisposable +{ + private readonly TcpListener listener = new(IPAddress.Loopback, 0); + private readonly CancellationTokenSource cts = new(); + private readonly Task loop; + private readonly Dictionary versions = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary nuspecs = new(StringComparer.OrdinalIgnoreCase); + + public MockNuGetFlatContainer() + { + listener.Start(); + loop = Task.Run(AcceptAsync); + } + + public string BaseUrl => $"http://127.0.0.1:{((IPEndPoint)listener.LocalEndpoint).Port}"; + public int HttpRequests { get; private set; } + public string RestoreMode { get; set; } = "Success"; + public string? FailPackageId { get; set; } + public string? FailVersion { get; set; } + public string? FailCombination { get; set; } + + public void Reset() + { + lock (versions) { versions.Clear(); nuspecs.Clear(); } + HttpRequests = 0; + RestoreMode = "Success"; + FailPackageId = null; + FailVersion = null; + FailCombination = null; + } + + public void SetVersions(string id, string[] list) + { + lock (versions) versions[id.ToLowerInvariant()] = list; + } + + public void SetNuspec(string id, string version, Dictionary deps) + { + var entries = string.Join("", deps.OrderBy(kv => kv.Key, StringComparer.Ordinal).Select(kv => $"")); + var groups = string.Join("", new[] { "net10.0", "net9.0" }.Select(tfm => $"{entries}")); + var xml = $"{id}{version}{groups}"; + lock (versions) nuspecs[$"{id.ToLowerInvariant()}/{version.ToLowerInvariant()}"] = xml; + } + + private async Task AcceptAsync() + { + while (!cts.IsCancellationRequested) + { + using var client = await listener.AcceptTcpClientAsync(cts.Token); + await using var stream = client.GetStream(); + using var reader = new StreamReader(stream, Encoding.ASCII, leaveOpen: true); + var requestLine = await reader.ReadLineAsync(cts.Token) ?? string.Empty; + while (!string.IsNullOrEmpty(await reader.ReadLineAsync(cts.Token))) { } + + HttpRequests++; + var path = requestLine.Split(' ') is [_, var target, ..] ? target : "/"; + byte[] body; + var status = "200 OK"; + var contentType = "application/json"; + + if (path == "/v3/index.json") + { + body = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new + { + resources = new[] + { + new Dictionary { ["@type"] = "PackageBaseAddress/3.0.0", ["@id"] = $"{BaseUrl}/flat/" }, + }, + })); + } + else if (path.StartsWith("/flat/", StringComparison.Ordinal) && path.EndsWith(".nuspec", StringComparison.OrdinalIgnoreCase)) + { + var parts = path.Trim('/').Split('/'); + var key = $"{parts[1]}/{parts[2]}"; + string? xml; + lock (versions) nuspecs.TryGetValue(key, out xml); + if (xml is null) { status = "404 Not Found"; body = Encoding.UTF8.GetBytes("not found"); } + else { contentType = "application/xml"; body = Encoding.UTF8.GetBytes(xml); } + } + else if (path.StartsWith("/flat/", StringComparison.Ordinal) && path.EndsWith("/index.json", StringComparison.OrdinalIgnoreCase)) + { + var parts = path.Trim('/').Split('/'); + var id = parts[1]; + string[]? list; + lock (versions) versions.TryGetValue(id, out list); + if (list is null) { status = "404 Not Found"; body = Encoding.UTF8.GetBytes("not found"); } + else { body = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new { versions = list })); } + } + else + { + status = "404 Not Found"; + body = Encoding.UTF8.GetBytes("not found"); + } + + var header = $"HTTP/1.1 {status}\r\nContent-Type: {contentType}\r\nContent-Length: {body.Length}\r\nConnection: close\r\n\r\n"; + await stream.WriteAsync(Encoding.ASCII.GetBytes(header), cts.Token); + await stream.WriteAsync(body, cts.Token); + } + } + + public async ValueTask DisposeAsync() + { + await cts.CancelAsync(); + listener.Stop(); + try { await loop; } catch { } + cts.Dispose(); + } +} diff --git a/scripts/tests/git-remote-release-tests.cs b/scripts/tests/git-remote-release-tests.cs new file mode 100644 index 00000000..e7491161 --- /dev/null +++ b/scripts/tests/git-remote-release-tests.cs @@ -0,0 +1,1120 @@ +#!/usr/bin/env dotnet +#:property TargetFramework=net10.0 +#:property RollForward=Major +#:property Nullable=enable +#:property PublishAot=false +#:include ../../skills/git-remote-release/scripts/GitProcess.cs +#:include ../../skills/git-remote-release/scripts/ExecutableResolver.cs +#:include ../eval-runners/windows-owned-process.cs + +using System.Diagnostics; +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; +using Agentic.Tooling.Execution; + +// Black-box tests for collect-release-evidence. A copy of this app named `gh` is first on PATH and answers from a +// routes file, so no case reaches GitHub. The cases are those of the former Python test-release-evidence.py, plus +// progress, heartbeat, timeout, missing-gh, usage and parallel-read cases. +if (Path.GetFileNameWithoutExtension(Environment.ProcessPath) == "gh") return FakeGitHub.Run(args); + +if (args.Length < 1 || !File.Exists(args[0])) throw new ArgumentException("Pass the built collect-release-evidence.dll, then optional case name filters."); +var app = Path.GetFullPath(args[0]); +var watch = Stopwatch.StartNew(); +using var stop = new CancellationTokenSource(TimeSpan.FromMinutes(5)); +var root = Path.Combine(Path.GetTempPath(), "git-remote-release-test-" + Guid.NewGuid().ToString("N")[..12]); +var shim = Path.Combine(root, "shim"); +var noGh = Path.Combine(root, "no-gh"); +var dotnet = ExecutableResolver.Resolve(OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); +var dotnetRoot = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(typeof(object).Assembly.Location)!)!)!)!; +var runs = 0; + +var cases = new List<(string Name, Func Body)>(); +void Case(string name, Func body) => cases.Add((name, body)); + +Case("squash expands all pages and preserves changes", async token => +{ + var e = await CollectAsync(new Scenario(), "v1", "v2", token: token); + MustComplete(e); + Must(Sources(e).SequenceEqual(["* Service update by @service[bot], @automation and @human in https://github.com/example/widget/pull/22"]), $"sources: {e["sources"]}"); + Must(e["pull_requests"]![0]!["commits"]!.AsArray().Count == 3, "all three original commits"); + Must(e["files"]![0]!["patch"]!.GetValue().Contains("New workflow"), "the patch is kept"); + await MustVerifyAsync(e, Draft(e), token); +}); + +Case("missing contributor and duplicate source fail verification", async token => +{ + var e = await CollectAsync(new Scenario(), "v1", "v2", token: token); + var draft = Draft(e); + await MustRejectAsync(e, draft.Replace(", @automation and @human", ""), token); + await MustRejectAsync(e, draft.Replace("Sources:", "Sources:\n" + Sources(e)[0]), token); + await MustRejectAsync(e, draft.Replace("Sources:", "Sources:\n- Extra source by @someone"), token); +}); + +Case("new contributors render before changelog and preserve sources", async token => +{ + var e = await CollectAsync(new Scenario(), "v1", "v2", Notes(), token: token); + MustComplete(e); + Must(Newcomers(e).SequenceEqual(["* **@service[bot]** made their first contribution in [#22](https://github.com/example/widget/pull/22)."]), $"newcomers: {e["new_contributors"]}"); + await MustVerifyAsync(e, WithNewcomers(e), token); + await MustRejectAsync(e, Draft(e), token); +}); + +Case("new contributors deduplicate case and keep rest identity", async token => +{ + var notes = Notes(); + notes["response"]!["body"] = notes["response"]!["body"]!.GetValue().Replace("\n\n**Full Changelog**:", + "\n* @SERVICE[bot] made their first contribution in https://github.com/example/widget/pull/22\n\n**Full Changelog**:"); + var e = await CollectAsync(new Scenario(), "v1", "v2", notes, token: token); + MustComplete(e); + Must(Newcomers(e).Count == 1 && Newcomers(e)[0].Contains("@service[bot]"), $"newcomers: {e["new_contributors"]}"); +}); + +Case("unknown author, out-of-range PR and malformed notes fail closed", async token => +{ + JsonNode[] variants = + [ + Notes("* @unknown made their first contribution in https://github.com/example/widget/pull/22"), + Notes("* @service[bot] made their first contribution in https://github.com/other/widget/pull/22"), + Notes("* @service[bot] made their first contribution in https://github.com/example/widget/pull/99"), + Notes("* Unrecognized contributor format"), + WithBody(null), + J("""{"response":{"body":"x"}}"""), + J("{}"), + Notes()["response"]!.DeepClone(), + ]; + foreach (var notes in variants) + { + var e = await CollectAsync(new Scenario(), "v1", "v2", notes, token: token); + Must(!Complete(e), $"incomplete for {notes.ToJsonString()}"); + await MustRejectAsync(e, Draft(e), token); + } +}); + +Case("no newcomers or unavailable metadata omits section", async token => +{ + foreach (var notes in new JsonNode?[] { null, Notes("") }) + { + var e = await CollectAsync(new Scenario(), "v1", "v2", notes, token: token); + MustComplete(e); + Must(Newcomers(e).Count == 0, "no newcomers"); + await MustVerifyAsync(e, Draft(e), token); + await MustRejectAsync(e, Draft(e).Replace("\n\n**Full Changelog**:", "\n\n## New Contributors\n\n**Full Changelog**:"), token); + } +}); + +Case("initial release includes user commit author despite bot in name", async token => +{ + var s = new Scenario(); + s.InitialRoutes(); + s.Pr["user"]!["type"] = "User"; + s.Routes["/pulls/22/commits?per_page=100"]![0]![0] = UserCommit("a", "aicia-bot"); + s.Routes["/pulls/22/commits?per_page=100"]![1]![1]!["author"]!["type"] = "Bot"; + var e = await CollectAsync(s, null, "v2", Notes(previous: null), token: token); + MustComplete(e); + Must(Newcomers(e).SequenceEqual([ + "* **@service[bot]** made their first contribution in [#22](https://github.com/example/widget/pull/22).", + "* **@aicia-bot** made their first contribution in [#22](https://github.com/example/widget/pull/22)."]), $"newcomers: {e["new_contributors"]}"); + Must(Sources(e)[^1].Contains("@human"), "a bot still keeps its Sources credit"); + await MustVerifyAsync(e, WithNewcomers(e), token); +}); + +Case("generated newcomer can be a verified original commit author", async token => +{ + var e = await CollectAsync(new Scenario(), "v1", "v2", Notes("* @HUMAN made their first contribution in https://github.com/example/widget/pull/22"), token: token); + MustComplete(e); + Must(Newcomers(e)[0].Contains("@human"), $"newcomers: {e["new_contributors"]}"); +}); + +Case("empty generated section does not hide a new user", async token => +{ + var s = new Scenario(); + s.Pr["user"]!["type"] = "User"; + s.Pr["user"]!["login"] = "new-user"; + s.PriorRoutes(); + var e = await CollectAsync(s, "v1", "v2", Notes(""), token: token); + MustComplete(e); + Must(Newcomers(e).Count == 1 && Newcomers(e)[0].Contains("@new-user"), $"newcomers: {e["new_contributors"]}"); +}); + +Case("returning commit author is not new", async token => +{ + var s = new Scenario(); + s.PriorRoutes([UserCommit("base", "AICIA-BOT")]); + s.Routes["/pulls/22/commits?per_page=100"]![0]![0] = UserCommit("a", "aicia-bot"); + var e = await CollectAsync(s, "v1", "v2", token: token); + MustComplete(e); + Must(Newcomers(e).Count == 0, "no newcomers"); +}); + +Case("returning author behind a prior squash is not new", async token => +{ + var s = new Scenario(); + s.PriorRoutes(); + s.Routes["/commits/base/pulls?per_page=100"] = J("""[[{"number":9}]]"""); + s.Routes["/pulls/9"] = new JsonArray(s.PrCopy(9, "base", 1)); + s.Routes["/pulls/9/commits?per_page=100"] = new JsonArray(new JsonArray(UserCommit("old-original", "aicia-bot"))); + s.Routes["/pulls/9/files?per_page=100"] = J("""[[{"filename":"old.py"}]]"""); + s.Routes["/pulls/22/commits?per_page=100"]![0]![0] = UserCommit("a", "aicia-bot"); + var run = await RunCollectAsync(s, "v1", "v2", token: token); + MustComplete(run.Evidence!); + Must(Newcomers(run.Evidence!).Count == 0, "no newcomers"); + Must(run.Endpoints.Contains(Scenario.Prefix + "/pulls/9/commits?per_page=100"), "the prior squash was expanded"); +}); + +Case("prior files and trees are not newcomer prerequisites", async token => +{ + foreach (var failure in new[] { "truncated tree", "denied tree", "missing tree metadata", "denied PR files", "capped PR files" }) + { + var s = new Scenario(); + s.PriorSquashRoutes(); + switch (failure) + { + case "truncated tree": s.Routes["/git/trees/old-tree?recursive=1"]![0]!["truncated"] = true; break; + case "denied tree": s.Routes["/git/trees/old-tree?recursive=1"] = Fail("HTTP 403 old tree"); break; + case "missing tree metadata": s.Routes["/commits/base"] = J("""[{"sha":"base"}]"""); break; + case "denied PR files": s.Routes["/pulls/9/files?per_page=100"] = Fail("HTTP 403 old files"); break; + default: s.Routes["/pulls/9"]![0]!["changed_files"] = 3001; break; + } + var run = await RunCollectAsync(s, "v1", "v2", token: token); + var e = run.Evidence!; + MustComplete(e, failure); + Must(Newcomers(e).SequenceEqual(["* **@new-user** made their first contribution in [#22](https://github.com/example/widget/pull/22)."]), $"{failure}: newcomers {e["new_contributors"]}"); + await MustVerifyAsync(e, WithNewcomers(e), token); + Must(!run.Endpoints.Any(endpoint => endpoint.Contains("/git/trees/")), $"{failure}: a tree was read"); + Must(!run.Endpoints.Contains(Scenario.Prefix + "/pulls/9/files?per_page=100"), $"{failure}: prior PR files were read"); + Must(run.Endpoints.Contains(Scenario.Prefix + "/pulls/22/files?per_page=100"), $"{failure}: current PR files were not read"); + var history = e["contributor_history"]!; + Must(history["history_only"]?.GetValue() == true, "history is marked history-only"); + var errors = await VerifyAsync(history, Draft(history), token); + Must(errors.Any(error => error.Contains("Contributor history alone")), $"{failure}: history verified as release evidence"); + } +}); + +Case("prior co-authors are checked in history-only mode", async token => +{ + foreach (var failMapping in new[] { false, true }) + { + var s = new Scenario(); + s.PriorSquashRoutes(); + s.Routes["/pulls/9/commits?per_page=100"] = new JsonArray(new JsonArray(Commit("old-original", "helper", "Improve runner\n\nCo-authored-by: Returning "))); + s.Routes["graphql:old-original"] = failMapping ? Fail("HTTP 403 historical co-author mapping") : Authors(("Returning", "returning")); + s.Routes["users/returning"] = J("""[{"login":"returning","type":"User"}]"""); + var e = await CollectAsync(s, "v1", "v2", token: token); + Must(Complete(e) == !failMapping, $"fail={failMapping}: issues {e["issues"]}"); + if (failMapping) + { + Must(Newcomers(e).Count == 0, "no newcomers without the mapping"); + Must(string.Join(";", Issues(e)).Contains("historical co-author mapping"), $"issues: {e["issues"]}"); + } + else + { + Must(Newcomers(e).Count == 1 && Newcomers(e)[0].Contains("@new-user"), $"newcomers: {e["new_contributors"]}"); + } + } +}); + +Case("prior commit and membership failures still fail closed", async token => +{ + foreach (var failure in new[] { "missing original commit", "failed association", "ambiguous membership" }) + { + var s = new Scenario(); + s.PriorSquashRoutes(); + if (failure == "missing original commit") s.Routes["/pulls/9"]![0]!["commits"] = 2; + else if (failure == "failed association") s.Routes["/commits/base/pulls?per_page=100"] = Fail("HTTP 403 associations"); + else s.Routes["/pulls/9"]![0]!["merge_commit_sha"] = "unreachable"; + var e = await CollectAsync(s, "v1", "v2", token: token); + Must(!Complete(e), $"{failure}: complete"); + Must(Newcomers(e).Count == 0, $"{failure}: newcomers"); + Must(string.Join(";", Issues(e)).Contains("Prior contributor history is incomplete"), $"{failure}: issues {e["issues"]}"); + } +}); + +Case("current release file inventory is still required", async token => +{ + var s = new Scenario(); + s.PriorSquashRoutes(); + s.Routes["/pulls/22/files?per_page=100"] = Fail("HTTP 403 current files"); + var e = await CollectAsync(s, "v1", "v2", token: token); + Must(!Complete(e), "complete without the file list"); + await MustRejectAsync(e, Draft(e), token); +}); + +Case("failed history does not prove newcomer status", async token => +{ + var s = new Scenario(); + s.Pr["user"]!["type"] = "User"; + s.PriorRoutes(); + s.Routes["/commits?sha=base&per_page=100"] = Fail("HTTP 403"); + var e = await CollectAsync(s, "v1", "v2", token: token); + Must(!Complete(e) && Newcomers(e).Count == 0, "complete or newcomers without history"); + Must(string.Join(";", Issues(e)).Contains("Prior contributor history is incomplete"), $"issues: {e["issues"]}"); +}); + +Case("direct commit newcomer gets a commit link", async token => +{ + var s = new Scenario(); + s.InitialRoutes(); + s.Routes["/commits?sha=squash&per_page=100"]![1]![0] = UserCommit("root", "founder"); + var e = await CollectAsync(s, null, "v2", token: token); + MustComplete(e); + Must(Newcomers(e).SequenceEqual(["* **@founder** made their first contribution in [root](https://github.com/example/widget/commit/root)."]), $"newcomers: {e["new_contributors"]}"); + await MustVerifyAsync(e, WithNewcomers(e), token); +}); + +Case("co-authors keep verified users and drop unmapped or bot trailers", async token => +{ + var s = new Scenario(); + s.InitialRoutes(); + var first = s.Routes["/pulls/22/commits?per_page=100"]![0]![0]!["commit"]!; + first["message"] = first["message"]!.GetValue() + "\n\nCo-authored-by: Misleading Name \nCo-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>" + + "\nCo-authored-by: Claude \nCo-authored-by: Freebuff \nCo-authored-by: Migrated "; + s.Routes["graphql:a"] = Authors(("Misleading Name", "coauthor-bot"), ("Copilot", "Copilot"), ("Claude", null), ("Freebuff", null), ("Migrated", "migrated")); + s.Routes["users/coauthor-bot"] = J("""[{"login":"coauthor-bot","type":"User"}]"""); + s.Routes["users/Copilot"] = J("""[{"login":"Copilot","type":"Bot"}]"""); + s.Routes["users/migrated"] = J("""[{"login":"migrated","type":"Mannequin"}]"""); + var run = await RunCollectAsync(s, null, "v2", token: token); + var e = run.Evidence!; + MustComplete(e); + var graphql = run.Calls.Where(call => call is ["api", "graphql", ..]).ToList(); + Must(graphql.Count == 1 && graphql[0].Contains("sha=a") && graphql[0].Contains("owner=example") && graphql[0].Contains("name=widget"), $"graphql calls: {graphql.Count}"); + var last = Sources(e)[^1]; + Must(last.Contains("@service[bot]") && last.Contains("@coauthor-bot"), $"source: {last}"); + foreach (var dropped in new[] { "Copilot", "Claude", "Freebuff", "Migrated", "migrated", "Misleading Name" }) Must(!last.Contains(dropped), $"{dropped} kept: {last}"); + Must(Newcomers(e).Count == 1 && Newcomers(e)[0].Contains("@coauthor-bot"), $"newcomers: {e["new_contributors"]}"); +}); + +Case("co-author without a GitHub account is unmapped, not incomplete", async token => +{ + var s = new Scenario(); + s.PriorRoutes(); + var first = s.Routes["/pulls/22/commits?per_page=100"]![0]![0]!["commit"]!; + first["message"] = "Service update\n\nCo-authored-by: Copilot \nCo-authored-by: Human "; + s.Routes["graphql:a"] = Authors(("Copilot", "Copilot"), ("Human", "human")); + s.Routes["users/Copilot"] = Fail("gh: Not Found (HTTP 404)"); + s.Routes["users/human"] = J("""[{"login":"human","type":"User"}]"""); + var e = await CollectAsync(s, "v1", "v2", token: token); + MustComplete(e); + var actors = e["pull_requests"]![0]!["commits"]![0]!["github_authors"]!.AsArray(); + Must(actors[0]!["user"] is null, $"Copilot mapped: {actors[0]}"); + Must(JsonNode.DeepEquals(actors[1]!["user"], J("""{"login":"human","type":"User"}""")), $"human: {actors[1]}"); +}); + +Case("co-author lookup failure other than 404 still fails closed", async token => +{ + var s = new Scenario(); + s.Routes["/pulls/22/commits?per_page=100"]![0]![0]!["commit"]!["message"] = "Service update\n\nCo-authored-by: Human "; + s.Routes["graphql:a"] = Authors(("Human", "human")); + s.Routes["users/human"] = Fail("users/human: gh: HTTP 403"); + var e = await CollectAsync(s, "v1", "v2", token: token); + Must(!Complete(e) && string.Join(";", Issues(e)).Contains("co-author identities"), $"issues: {e["issues"]}"); +}); + +Case("failed co-author mapping fails closed", async token => +{ + var s = new Scenario(); + s.InitialRoutes(); + var first = s.Routes["/pulls/22/commits?per_page=100"]![0]![0]!["commit"]!; + first["message"] = first["message"]!.GetValue() + "\nCo-authored-by: X "; + s.Routes["graphql:a"] = Fail("HTTP 403"); + var e = await CollectAsync(s, null, "v2", token: token); + Must(!Complete(e) && Newcomers(e).Count == 0, "complete or newcomers without the mapping"); +}); + +Case("returning co-author is found in prior direct history", async token => +{ + var s = new Scenario(); + s.PriorRoutes([UserCommit("base", "coauthor")]); + var first = s.Routes["/pulls/22/commits?per_page=100"]![0]![0]!["commit"]!; + first["message"] = first["message"]!.GetValue() + "\nCo-authored-by: Co Author "; + s.Routes["graphql:a"] = Authors(("Co Author", "coauthor")); + s.Routes["users/coauthor"] = J("""[{"login":"coauthor","type":"User"}]"""); + var e = await CollectAsync(s, "v1", "v2", token: token); + MustComplete(e); + Must(Newcomers(e).Count == 0, $"newcomers: {e["new_contributors"]}"); +}); + +Case("generated newcomer conflicting with history fails closed", async token => +{ + var s = new Scenario(); + s.Pr["user"]!["type"] = "User"; + s.PriorRoutes([UserCommit("base", "service[bot]")]); + var e = await CollectAsync(s, "v1", "v2", Notes(), token: token); + Must(!Complete(e) && string.Join(";", Issues(e)).Contains("conflict"), $"issues: {e["issues"]}"); +}); + +Case("generation for another range or repository fails closed", async token => +{ + // A narrower range can omit this release's newcomers; that must not read as "none". + var narrower = Notes("", previous: "v1.5"); + narrower["request"]!["previous_tag_name"] = "v1"; + var otherRepository = Notes(""); + otherRepository["request"]!["repository"] = "other/widget"; + var mismatches = new Dictionary + { + ["narrower response, matching request"] = narrower, + ["narrower request and response"] = Notes("", previous: "v1.5"), + ["other current tag"] = Notes("", tag: "v3"), + ["initial generation for compare range"] = Notes("", previous: null), + ["missing changelog link"] = WithBody("## What's Changed\n* Update"), + ["other repository"] = otherRepository, + ["bare response without request"] = Notes("")["response"]!.DeepClone(), + }; + foreach (var (name, notes) in mismatches) + { + var e = await CollectAsync(new Scenario(), "v1", "v2", notes, token: token); + Must(!Complete(e) && Newcomers(e).Count == 0, $"{name}: complete or newcomers"); + Must(Issues(e).Any(issue => issue.Contains("New contributor evidence")), $"{name}: issues {e["issues"]}"); + await MustRejectAsync(e, Draft(e), token); + } +}); + +Case("generation for an unreleased tag matches target_commitish", async token => +{ + var s = new Scenario(); + s.Routes["/commits/head"] = J("""[{"sha":"head"}]"""); + var notes = Notes(); + notes["request"]!["target_commitish"] = "head"; + var e = await CollectAsync(s, "v1", "head", notes, token: token); + MustComplete(e); + Must(Newcomers(e).Count == 1, $"newcomers: {e["new_contributors"]}"); +}); + +Case("new contributor section rejects duplicates, wrong position and fabrication", async token => +{ + var e = await CollectAsync(new Scenario(), "v1", "v2", Notes(), token: token); + var draft = WithNewcomers(e); + var section = "## New Contributors\n\n" + string.Join("\n", Newcomers(e)); + foreach (var invalid in new[] + { + draft.Replace(section, section + "\n" + section), + draft.Replace(section + "\n\n", "").Replace("Sources:", section + "\n\nSources:"), + draft.Replace("@service[bot]**", "@invented**"), + draft.Replace("[#22]", "[#99]"), + draft.Replace("made their", "made — their"), + draft + "\n" + section, + }) + { + await MustRejectAsync(e, invalid, token); + } +}); + +Case("initial release collects all history and uses the commits link", async token => +{ + var s = new Scenario(); + s.InitialRoutes(); + var run = await RunCollectAsync(s, null, "v2", Notes(previous: null), token: token); + var e = run.Evidence!; + MustComplete(e); + Must(e["commits"]!.AsArray().Select(commit => commit!["sha"]!.GetValue()).SequenceEqual(["root", "squash"]), "oldest first"); + Must(Strings(e["files_without_patch"]).SequenceEqual(["src/app.py", "vendor"]), $"files without patch: {e["files_without_patch"]}"); + Must(!run.Endpoints.Any(endpoint => endpoint.Contains("/compare/")), "a comparison was read"); + Must(Sources(e)[0].Contains("/commit/root"), $"sources: {e["sources"]}"); + var draft = WithNewcomers(e); + Must(draft.EndsWith("**Full Changelog**: https://github.com/example/widget/commits/v2"), "commits link"); + await MustVerifyAsync(e, draft, token); + await MustRejectAsync(e, draft.Replace("commits/v2", "compare/v1...v2"), token); +}); + +Case("initial release with a missing or truncated tree fails closed", async token => +{ + var s = new Scenario(); + s.InitialRoutes(); + s.Routes["/git/trees/tree?recursive=1"]![0]!["truncated"] = true; + Must(!Complete(await CollectAsync(s, null, "v2", token: token)), "complete with a truncated tree"); + s.Routes["/git/trees/tree?recursive=1"] = Fail("HTTP 403"); + Must(!Complete(await CollectAsync(s, null, "v2", token: token)), "complete without a tree"); +}); + +Case("compare release rejects the initial history link", async token => +{ + var e = await CollectAsync(new Scenario(), "v1", "v2", token: token); + await MustRejectAsync(e, Draft(e).Replace("compare/v1...v2", "commits/v2"), token); +}); + +Case("initial release with empty history cannot pass", async token => +{ + var s = new Scenario(); + s.InitialRoutes(); + s.Routes["/commits?sha=squash&per_page=100"] = J("[[]]"); + var e = await CollectAsync(s, null, "v2", token: token); + Must(!Complete(e) && Issues(e).Any(issue => issue.Contains("resolved current commit")), $"issues: {e["issues"]}"); +}); + +Case("command line initial release with a saved generation response", async token => +{ + var s = new Scenario(); + s.InitialRoutes(); + var run = await RunCollectAsync(s, null, "v2", Notes(previous: null), byteOrderMark: true, token: token); + Must(run.Code == 0, $"exit {run.Code}: {run.Error}"); + MustComplete(run.Evidence!); + Must(JsonNode.DeepEquals(run.Evidence!["generated_notes"], Notes(previous: null)), "the saved generation is kept as read"); + Must(Newcomers(run.Evidence!).Count == 1, $"newcomers: {run.Evidence!["new_contributors"]}"); + var summary = JsonNode.Parse(run.Output)!; + Must(summary["complete"]!.GetValue() && Strings(summary["sources"]).SequenceEqual(Sources(run.Evidence!)), $"summary: {run.Output}"); +}); + +Case("command line rejects a missing compare ref and an initial release with two refs", async token => +{ + foreach (var arguments in new[] + { + new[] { "collect", "example/widget", "v2", "--output", "unused" }, + ["collect", "example/widget", "v1", "v2", "--initial-release", "--output", "unused"], + ["collect", "example/widget", "v1", "v2"], + ["collect", "example/widget", "v1", "v2", "--output", "unused", "--max-parallel", "0"], + ["collect", "example/widget", "v1", "v2", "--output", "unused", "--force"], + ["publish", "example/widget"], + ["verify", "only-one-file"], + }) + { + var run = await RunToolAsync(arguments, NewRunDirectory(new Scenario()), token: token); + Must(run.Code == 2, $"{string.Join(' ', arguments)}: exit {run.Code}"); + Must(run.Output.Length == 0, $"{string.Join(' ', arguments)}: wrote to stdout"); + Must(run.Calls.Count == 0, $"{string.Join(' ', arguments)}: gh was called"); + } +}); + +Case("multiple new contributors preserve first appearance order", async token => +{ + var s = new Scenario(); + var compare = s.Routes["/compare/base...head?per_page=100"]![0]!; + compare["commits"]!.AsArray().Add(Commit("squash2")); + compare["total_commits"] = 2; + s.Routes["/commits/squash2/pulls?per_page=100"] = J("""[[{"number":23}]]"""); + var other = s.PrCopy(23, "squash2", 1); + other["user"] = J("""{"login":"Human"}"""); + other["title"] = "Human update"; + s.Routes["/pulls/23"] = new JsonArray(other); + s.Routes["/pulls/23/commits?per_page=100"] = new JsonArray(new JsonArray(Commit("h1", "Human"))); + s.Routes["/pulls/23/files?per_page=100"] = J("""[[{"filename":"README.md"}]]"""); + var notes = Notes("* @Human made their first contribution in https://github.com/example/widget/pull/23\n" + + "* @service[bot] made their first contribution in https://github.com/example/widget/pull/22"); + var e = await CollectAsync(s, "v1", "v2", notes, token: token); + MustComplete(e); + Must(Newcomers(e)[0].StartsWith("* **@Human**") && Newcomers(e)[1].StartsWith("* **@service[bot]**"), $"newcomers: {e["new_contributors"]}"); + await MustVerifyAsync(e, WithNewcomers(e), token); +}); + +Case("source titles with an em dash still verify", async token => +{ + var s = new Scenario(); + s.Pr["title"] = "Service — update"; + var e = await CollectAsync(s, "v1", "v2", token: token); + MustComplete(e); + Must(Sources(e)[0].Contains('—'), "the title keeps its dash"); + await MustVerifyAsync(e, Draft(e), token); +}); + +Case("summary structure rejects the bold paragraph regression", async token => +{ + var e = await CollectAsync(new Scenario(), "v1", "v2", token: token); + var errors = await VerifyAsync(e, Draft(e, + "**Team catalog matching precision** — The API now matches exact team components.\n\n" + + "**Enhanced test coverage and infrastructure** — Comprehensive test fixtures exercise overlapping names.\n\n" + + "**Dependency and tooling updates** — Updated dependencies and repository tooling."), token); + foreach (var expected in new[] { "This release ", "Bold-leading prose paragraphs", "dash bullet", "Unicode em dash" }) + { + Must(errors.Any(error => error.Contains(expected)), $"no error with '{expected}': {string.Join(" | ", errors)}"); + } +}); + +Case("summary structure requires bullets and natural bold leads", async token => +{ + var e = await CollectAsync(new Scenario(), "v1", "v2", token: token); + var withoutBullets = await VerifyAsync(e, Draft(e, "This release improves contributor-complete verification."), token); + Must(withoutBullets.Any(error => error.Contains("dash bullet")), string.Join(" | ", withoutBullets)); + var labelStyle = await VerifyAsync(e, Draft(e, "This release improves contributor-complete verification.\n\n" + + "- **Contributor attribution**: now keeps every verified PR contributor on the shared source line."), token); + Must(labelStyle.Any(error => error.Contains("label punctuation")), string.Join(" | ", labelStyle)); +}); + +Case("summary structure rejects plain blockquotes and unsupported alert markers", async token => +{ + var e = await CollectAsync(new Scenario(), "v1", "v2", token: token); + const string opening = "This release improves contributor-complete verification.\n\n- **Contributor attribution** now keeps every verified PR contributor on the shared source line.\n\n"; + foreach (var (summary, expected) in new[] + { + (opening + "> Just a blockquote.", "Plain blockquotes are not allowed"), + (opening + "> [!OTHER]\n> Unsupported marker.", "supported alert markers on standalone marker lines"), + }) + { + var errors = await VerifyAsync(e, Draft(e, summary), token); + Must(errors.Any(error => error.Contains(expected)), $"no error with '{expected}': {string.Join(" | ", errors)}"); + } + await MustVerifyAsync(e, Draft(e, opening + "> [!NOTE]\n> A supported alert."), token); +}); + +Case("summary structure requires explanatory prose after the bold lead", async token => +{ + var e = await CollectAsync(new Scenario(), "v1", "v2", token: token); + var errors = await VerifyAsync(e, Draft(e, "This release improves contributor-complete verification.\n\n- **Contributor attribution** ."), token); + Must(errors.Any(error => error.Contains("explanatory prose")), string.Join(" | ", errors)); +}); + +Case("summary structure requires bullet punctuation", async token => +{ + var e = await CollectAsync(new Scenario(), "v1", "v2", token: token); + foreach (var (summary, expected) in new[] + { + ("This release improves contributor-complete verification.\n\n" + + "- **Contributor attribution** now keeps every verified PR contributor on the shared source line.\n" + + "- **Draft verification** rejects incomplete sources and malformed release-summary structure.", + "Each non-final release-highlight bullet must end with a comma"), + ("This release improves contributor-complete verification.\n\n" + + "- **Contributor attribution** now keeps every verified PR contributor on the shared source line,", + "The final release-highlight bullet must end with a period"), + }) + { + var errors = await VerifyAsync(e, Draft(e, summary), token); + Must(errors.Any(error => error.Contains(expected)), $"no error with '{expected}': {string.Join(" | ", errors)}"); + } +}); + +Case("failed association is not a direct commit", async token => +{ + var s = new Scenario(); + s.Routes["/commits/squash/pulls?per_page=100"] = Fail("HTTP 403"); + var e = await CollectAsync(s, "v1", "v2", token: token); + Must(!Complete(e) && Sources(e).Count == 0, $"sources: {e["sources"]}"); + await MustRejectAsync(e, Draft(e), token); +}); + +Case("commit and file caps fail closed", async token => +{ + foreach (var field in new[] { "commits", "changed_files" }) + { + var s = new Scenario(); + s.Pr[field] = s.Pr[field]!.GetValue() + 1; + Must(!Complete(await CollectAsync(s, "v1", "v2", token: token)), $"complete with a wrong {field} count"); + } + var compare = new Scenario(); + compare.Routes["/compare/base...head?per_page=100"]![0]!["total_commits"] = 2; + Must(!Complete(await CollectAsync(compare, "v1", "v2", token: token)), "complete with a wrong comparison count"); +}); + +Case("empty association allows a direct commit", async token => +{ + var s = new Scenario(); + s.Routes["/commits/squash/pulls?per_page=100"] = J("[[]]"); + var e = await CollectAsync(s, "v1", "v2", token: token); + MustComplete(e); + Must(Sources(e)[0].Contains("/commit/squash"), $"sources: {e["sources"]}"); +}); + +Case("compare pagination deduplicates the PR and keeps source order", async token => +{ + var s = PaginatedScenario(); + var run = await RunCollectAsync(s, "v1", "v2", token: token); + var e = run.Evidence!; + MustComplete(e); + Must(Sources(e).Count == 2 && Sources(e)[0].Contains("/commit/direct"), $"sources: {e["sources"]}"); + Must(e["pull_requests"]!.AsArray().Count == 1, "one PR"); + Must(run.Endpoints.Count(endpoint => endpoint == Scenario.Prefix + "/pulls/22/commits?per_page=100") == 1, "the PR commits were read more than once"); +}); + +Case("compare file cap is explicit", async token => +{ + var s = new Scenario(); + s.Routes["/compare/base...head?per_page=100"]![0]!["files"] = new JsonArray([.. Enumerable.Range(0, 300).Select(index => (JsonNode)new JsonObject { ["filename"] = index.ToString() })]); + var e = await CollectAsync(s, "v1", "v2", token: token); + Must(!Complete(e) && string.Join(" ", Issues(e)).Contains("300"), $"issues: {e["issues"]}"); +}); + +Case("open PR is excluded and uncertain integration is reported", async token => +{ + var open = new Scenario(); + open.Pr["merged_at"] = null; + MustComplete(await CollectAsync(open, "v1", "v2", token: token)); + var outside = new Scenario(); + outside.Pr["merge_commit_sha"] = "outside"; + var e = await CollectAsync(outside, "v1", "v2", token: token); + Must(!Complete(e) && Sources(e).Count == 0, $"sources: {e["sources"]}"); +}); + +Case("author fallback drops unverified co-authors and deduplicates case", async token => +{ + var s = new Scenario(); + s.Routes["/pulls/22/commits?per_page=100"] = new JsonArray(new JsonArray(Commit("a", "Human"), Commit("b", "human"), + Commit("c", null, "Fix\n\nCo-authored-by: Claude \nCo-authored-by: Other Person "))); + s.Routes["graphql:c"] = Authors(("Claude", null), ("Other Person", null)); + var e = await CollectAsync(s, "v1", "v2", token: token); + MustComplete(e); + Must(Sources(e).SequenceEqual(["* Service update by @service[bot], @Human and Recorded Name in https://github.com/example/widget/pull/22"]), $"sources: {e["sources"]}"); +}); + +Case("gh transport uses a paginated read-only argument array", async token => +{ + var run = await RunCollectAsync(new Scenario(), "v1", "v2", token: token); + MustComplete(run.Evidence!); + Must(run.Calls.Count > 0 && run.Calls.All(call => call is ["api", "--method", "GET", "--paginate", "--slurp", _]), $"calls: {string.Join(" | ", run.Calls.Select(call => string.Join(' ', call)))}"); + var failing = new Scenario(); + failing.Routes["/pulls/22"] = Fail("rate limited"); + var e = await CollectAsync(failing, "v1", "v2", token: token); + Must(!Complete(e) && string.Join(";", Issues(e)).Contains("rate limited"), $"issues: {e["issues"]}"); +}); + +Case("graphql authors transport paginates and resolves REST account types", async token => +{ + JsonNode Page(string name, string login, bool more) + { + var page = Authors((name, login))[0]!.DeepClone(); + var authors = page["data"]!["repository"]!["object"]!["authors"]!; + authors["totalCount"] = 2; + authors["pageInfo"] = new JsonObject { ["hasNextPage"] = more, ["endCursor"] = "next" }; + return page; + } + Scenario Prepared(JsonNode pages) + { + var s = new Scenario(); + s.Routes["/pulls/22/commits?per_page=100"]![0]![0]!["commit"]!["message"] = "Service update\n\nCo-authored-by: App "; + s.Routes["graphql:a"] = pages; + s.Routes["users/author-bot"] = J("""[{"login":"author-bot","type":"User"}]"""); + s.Routes["users/app%5Bbot%5D"] = J("""[{"login":"app[bot]","type":"Bot"}]"""); + s.PriorRoutes(); + return s; + } + + var run = await RunCollectAsync(Prepared(new JsonArray(Page("Author", "author-bot", true), Page("Co Author", "app[bot]", false))), "v1", "v2", token: token); + MustComplete(run.Evidence!); + var types = run.Evidence!["pull_requests"]![0]!["commits"]![0]!["github_authors"]!.AsArray().Select(actor => actor!["user"]!["type"]!.GetValue()); + Must(types.SequenceEqual(["User", "Bot"]), $"types: {string.Join(',', types)}"); + var graphql = run.Calls.Single(call => call is ["api", "graphql", ..]); + Must(graphql[..5].SequenceEqual(["api", "graphql", "--paginate", "--slurp", "-f"]) && graphql[5].StartsWith("query=query(") && !graphql[5].Contains("mutation"), $"graphql call: {string.Join(' ', graphql)}"); + Must(run.Endpoints.Count(endpoint => endpoint.StartsWith("users/")) == 2, "two account lookups"); + foreach (var invalid in new[] { new JsonArray(Page("Author", "author-bot", true)), J("""[{"errors":[{"message":"denied"}]}]""").AsArray(), new JsonArray() }) + { + var e = await CollectAsync(Prepared(invalid), "v1", "v2", token: token); + Must(!Complete(e) && string.Join(";", Issues(e)).Contains("co-author identities"), $"{invalid.ToJsonString()}: issues {e["issues"]}"); + } +}); + +// New cases: observability, time limits, a missing gh, and parallel reads. +Case("progress goes to stderr and stdout holds only the summary", async token => +{ + var run = await RunCollectAsync(new Scenario(), "v1", "v2", token: token); + Must(run.Code == 0, $"exit {run.Code}"); + Must(run.Output.Trim().Split('\n').Length == 1 && JsonNode.Parse(run.Output)!["complete"]!.GetValue(), $"stdout: {run.Output}"); + foreach (var marker in new[] { "[START]", "[PROGRESS]", "[COMPLETE]" }) Must(run.Error.Contains(marker), $"stderr lacks {marker}: {run.Error}"); + var progress = JsonNode.Parse(File.ReadAllText(Path.Combine(run.Directory, "progress.json")))!; + Must(progress["state"]!.GetValue() == "succeeded" && progress["operation"]!.GetValue() == "git-remote-release:collect", $"progress file: {progress}"); + + var quiet = await RunCollectAsync(new Scenario(), "v1", "v2", extra: ["--quiet"], token: token); + Must(!quiet.Error.Contains("[START]") && !quiet.Error.Contains("[PROGRESS]") && quiet.Error.Contains("[COMPLETE]"), $"quiet stderr: {quiet.Error}"); + Must(quiet.Output == run.Output, "--quiet changed stdout"); + + var failed = new Scenario(); + failed.Routes["/pulls/22"] = Fail("HTTP 403"); + var incomplete = await RunCollectAsync(failed, "v1", "v2", token: token); + Must(incomplete.Code == 1 && incomplete.Error.Contains("[FAILED]") && incomplete.Error.Contains("HTTP 403"), $"exit {incomplete.Code}: {incomplete.Error}"); + Must(JsonNode.Parse(File.ReadAllText(Path.Combine(incomplete.Directory, "progress.json")))!["state"]!.GetValue() == "failed", "progress file state"); +}); + +Case("a heartbeat appears while a gh call is slow", async token => +{ + var s = new Scenario(); + s.Delays["/compare/base...head?per_page=100"] = 2500; + var run = await RunCollectAsync(s, "v1", "v2", extra: ["--heartbeat-seconds", "1"], token: token); + MustComplete(run.Evidence!); + Must(run.Error.Contains("[HEARTBEAT]") && run.Error.Contains("comparing v1...v2"), $"stderr: {run.Error}"); + var silent = await RunCollectAsync(s, "v1", "v2", extra: ["--heartbeat-seconds", "1", "--no-heartbeat"], token: token); + Must(!silent.Error.Contains("[HEARTBEAT]"), $"--no-heartbeat stderr: {silent.Error}"); +}); + +Case("a gh call over its time limit is stopped and the evidence is incomplete", async token => +{ + var s = new Scenario(); + s.Delays["/pulls/22"] = 20000; + var clock = Stopwatch.StartNew(); + var run = await RunCollectAsync(s, "v1", "v2", extra: ["--call-timeout-seconds", "1"], token: token); + Must(run.Code == 1 && Issues(run.Evidence!).Any(issue => issue.Contains("did not finish within 1 s")), $"exit {run.Code}: {run.Error}"); + Must(clock.Elapsed < TimeSpan.FromSeconds(12), $"the slow call was not stopped: {clock.Elapsed}"); +}); + +Case("a missing gh fails closed", async token => +{ + var run = await RunCollectAsync(new Scenario(), "v1", "v2", noGitHub: true, token: token); + Must(run.Code == 1 && Issues(run.Evidence!).Any(issue => issue.Contains("(gh) was not found on PATH")), $"exit {run.Code}: {run.Error}"); +}); + +Case("parallel and sequential reads give the same evidence and calls", async token => +{ + var scenarios = new Func[] { PaginatedScenario, () => { var s = new Scenario(); s.PriorSquashRoutes(); return s; } }; + foreach (var make in scenarios) + { + var sequential = await RunCollectAsync(make(), "v1", "v2", extra: ["--max-parallel", "1"], token: token); + var parallel = await RunCollectAsync(make(), "v1", "v2", extra: ["--max-parallel", "8"], token: token); + MustComplete(sequential.Evidence!); + Must(sequential.Evidence!.ToJsonString() == parallel.Evidence!.ToJsonString(), "the evidence differs"); + Must(sequential.Output == parallel.Output, "the summary differs"); + Must(sequential.Endpoints.Order(StringComparer.Ordinal).SequenceEqual(parallel.Endpoints.Order(StringComparer.Ordinal)), "the calls differ"); + } +}); + +Case("verify reports an unreadable evidence file", async token => +{ + var directory = NewRunDirectory(new Scenario()); + File.WriteAllText(Path.Combine(directory, "draft.md"), "## What's Changed"); + var run = await RunToolAsync(["verify", Path.Combine(directory, "missing.json"), Path.Combine(directory, "draft.md")], directory, token: token); + Must(run.Code == 1 && run.Output.Length == 0 && run.Error.Contains("missing.json"), $"exit {run.Code}: {run.Output} {run.Error}"); +}); + +Case("progress file rejects overlaps with output, generated notes and foreign files", async token => +{ + var directory = NewRunDirectory(new Scenario()); + var output = Path.Combine(directory, "evidence.json"); + var notesPath = Path.Combine(directory, "generated-notes.json"); + var originalNotes = Notes().ToJsonString(); + File.WriteAllText(notesPath, originalNotes); + var foreign = Path.Combine(directory, "foreign.json"); + File.WriteAllText(foreign, """{"mine":true}"""); + + var outputOverlap = await RunToolAsync(["collect", "example/widget", "v1", "v2", "--output", output, "--progress-file", output], directory, token: token); + Must(outputOverlap.Code == 2 && outputOverlap.Output.Length == 0 && outputOverlap.Calls.Count == 0 && outputOverlap.Error.Contains("overlaps") && !File.Exists(output), $"output overlap: {outputOverlap.Code} {outputOverlap.Error}"); + + var dotDotOverlap = await RunToolAsync(["collect", "example/widget", "v1", "v2", "--output", output, "--progress-file", Path.Combine(directory, "sub", "..", "evidence.json")], directory, token: token); + Must(dotDotOverlap.Code == 2 && dotDotOverlap.Output.Length == 0 && dotDotOverlap.Calls.Count == 0 && dotDotOverlap.Error.Contains("overlaps") && !File.Exists(output), $"normalized output overlap: {dotDotOverlap.Code} {dotDotOverlap.Error}"); + + var notesOverlap = await RunToolAsync(["collect", "example/widget", "v1", "v2", "--output", output, "--generated-notes", notesPath, "--progress-file", notesPath], directory, token: token); + Must(notesOverlap.Code == 2 && notesOverlap.Output.Length == 0 && notesOverlap.Calls.Count == 0 && notesOverlap.Error.Contains("overlaps") && File.ReadAllText(notesPath) == originalNotes, $"notes overlap: {notesOverlap.Code} {notesOverlap.Error}"); + + var foreignOverlap = await RunToolAsync(["collect", "example/widget", "v1", "v2", "--output", output, "--progress-file", foreign], directory, token: token); + Must(foreignOverlap.Code == 2 && foreignOverlap.Output.Length == 0 && foreignOverlap.Calls.Count == 0 && foreignOverlap.Error.Contains("not a progress snapshot") && File.ReadAllText(foreign) == """{"mine":true}""", $"foreign overlap: {foreignOverlap.Code} {foreignOverlap.Error}"); +}); + +var results = new string?[cases.Count]; +Console.Error.WriteLine($"[START] +0.00s git-remote-release tests ({cases.Count} cases)"); +try +{ + Directory.CreateDirectory(noGh); + Directory.CreateDirectory(shim); + foreach (var file in Directory.EnumerateFiles(AppContext.BaseDirectory)) File.Copy(file, Path.Combine(shim, Path.GetFileName(file))); + var extension = OperatingSystem.IsWindows() ? ".exe" : string.Empty; + File.Move(Path.Combine(shim, "git-remote-release-tests" + extension), Path.Combine(shim, "gh" + extension)); + + var selected = Enumerable.Range(0, cases.Count).Where(index => args.Length == 1 || args.Skip(1).Any(filter => cases[index].Name.Contains(filter, StringComparison.OrdinalIgnoreCase))).ToArray(); + var done = 0; + using var heartbeat = new Timer(_ => Console.Error.WriteLine(FormattableString.Invariant($"[HEARTBEAT] +{watch.Elapsed.TotalSeconds:F2}s {Volatile.Read(ref done)}/{selected.Length} cases finished")), + null, TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(10)); + await Parallel.ForEachAsync(selected, new ParallelOptions { MaxDegreeOfParallelism = Math.Clamp(Environment.ProcessorCount, 1, 8), CancellationToken = stop.Token }, async (index, token) => + { + var clock = Stopwatch.StartNew(); + try + { + await cases[index].Body(token); + results[index] = FormattableString.Invariant($"PASS {cases[index].Name} ({clock.Elapsed.TotalSeconds:F1}s)"); + } + catch (Exception exception) + { + results[index] = $"FAIL {cases[index].Name}: {exception.Message}"; + } + Console.Error.WriteLine(FormattableString.Invariant($"[PROGRESS] +{watch.Elapsed.TotalSeconds:F2}s {Interlocked.Increment(ref done)}/{selected.Length} {results[index]}")); + }); + + var failed = selected.Where(index => results[index]?.StartsWith("PASS ", StringComparison.Ordinal) != true).ToArray(); + Console.Error.WriteLine(FormattableString.Invariant($"[{(failed.Length == 0 ? "COMPLETE" : "FAILED")}] +{watch.Elapsed.TotalSeconds:F2}s {selected.Length - failed.Length}/{selected.Length} cases, {runs} tool runs")); + foreach (var index in failed) Console.WriteLine(results[index] ?? $"FAIL {cases[index].Name}: did not run"); + if (failed.Length == 0) Console.WriteLine($"PASS git-remote-release deterministic tests ({selected.Length} cases)"); + return failed.Length == 0 ? 0 : 1; +} +finally +{ + try { Directory.Delete(root, recursive: true); } catch (IOException) { } catch (UnauthorizedAccessException) { } +} + +Scenario PaginatedScenario() +{ + var s = new Scenario(); + var pages = s.Routes["/compare/base...head?per_page=100"]!.AsArray(); + pages[0]!["commits"] = new JsonArray(Commit("direct", "person")); + pages[0]!["total_commits"] = 3; + pages.Add(new JsonObject { ["commits"] = new JsonArray(Commit("squash"), Commit("a")) }); + s.Routes["/commits/direct/pulls?per_page=100"] = J("[[]]"); + s.Routes["/commits/a/pulls?per_page=100"] = J("""[[{"number":22}]]"""); + return s; +} + +async Task CollectAsync(Scenario scenario, string? previous, string current, JsonNode? notes = null, CancellationToken token = default) +{ + var run = await RunCollectAsync(scenario, previous, current, notes, token: token); + Must(run.Code is 0 or 1 && run.Evidence is not null, $"collect exited {run.Code} without evidence: {run.Error}"); + Must((run.Code == 0) == Complete(run.Evidence!), $"exit {run.Code} disagrees with complete={Complete(run.Evidence!)}"); + return run.Evidence!; +} + +async Task RunCollectAsync(Scenario scenario, string? previous, string current, JsonNode? notes = null, string[]? extra = null, + bool byteOrderMark = false, bool noGitHub = false, CancellationToken token = default) +{ + var directory = NewRunDirectory(scenario); + var output = Path.Combine(directory, "out", "evidence.json"); + var arguments = new List { "collect", "example/widget" }; + if (previous is not null) arguments.Add(previous); + arguments.Add(current); + if (previous is null) arguments.Add("--initial-release"); + arguments.AddRange(["--output", output, "--progress-file", Path.Combine(directory, "progress.json")]); + if (notes is not null) + { + var path = Path.Combine(directory, "generated-notes.json"); + File.WriteAllText(path, notes.ToJsonString(), new UTF8Encoding(byteOrderMark)); + arguments.AddRange(["--generated-notes", path]); + } + arguments.AddRange(extra ?? []); + var run = await RunToolAsync([.. arguments], directory, noGitHub, token); + return run with { Evidence = File.Exists(output) ? JsonNode.Parse(File.ReadAllText(output))!.AsObject() : null }; +} + +async Task> VerifyAsync(JsonNode evidence, string draft, CancellationToken token) +{ + var directory = NewRunDirectory(new Scenario()); + File.WriteAllText(Path.Combine(directory, "evidence.json"), evidence.ToJsonString()); + File.WriteAllText(Path.Combine(directory, "draft.md"), draft); + var run = await RunToolAsync(["verify", Path.Combine(directory, "evidence.json"), Path.Combine(directory, "draft.md")], directory, token: token); + if (run.Code == 0) return run.Output.Trim() == "Release source verification passed" ? [] : throw new Failure($"verify passed with stdout: {run.Output}"); + if (run.Code != 1 || run.Output.Trim().Length == 0) throw new Failure($"verify exited {run.Code}: {run.Output} {run.Error}"); + return [.. run.Output.Trim().Split('\n')]; +} + +async Task MustVerifyAsync(JsonNode evidence, string draft, CancellationToken token) +{ + var errors = await VerifyAsync(evidence, draft, token); + Must(errors.Count == 0, $"verification failed: {string.Join(" | ", errors)}"); +} + +async Task MustRejectAsync(JsonNode evidence, string draft, CancellationToken token) => + Must((await VerifyAsync(evidence, draft, token)).Count > 0, $"verification passed for:\n{draft}"); + +string NewRunDirectory(Scenario scenario) +{ + var directory = Path.Combine(root, "run-" + Interlocked.Increment(ref runs)); + Directory.CreateDirectory(Path.Combine(directory, "calls")); + File.WriteAllText(Path.Combine(directory, "routes.json"), scenario.ToRoutes().ToJsonString()); + return directory; +} + +async Task RunToolAsync(string[] arguments, string directory, bool noGitHub = false, CancellationToken token = default) +{ + var startInfo = Git.CreateStartInfo(dotnet, directory, [app, .. arguments]); + startInfo.Environment["PATH"] = noGitHub ? noGh : shim + Path.PathSeparator + Environment.GetEnvironmentVariable("PATH"); + startInfo.Environment["DOTNET_ROOT"] = dotnetRoot; + startInfo.Environment["RELEASE_TEST_STATE"] = directory; + var result = await Git.RunProcessAsync(startInfo, token); + var calls = Directory.EnumerateFiles(Path.Combine(directory, "calls")) + .Select(file => JsonSerializer.Deserialize(File.ReadAllText(file))!).ToList(); + return new Run(directory, result.Code, result.Output, result.Error, calls, null); +} + +static JsonObject Commit(string sha, string? login = "service[bot]", string message = "Service update") => Program.CommitOf(sha, login, message); + +static JsonObject UserCommit(string sha, string login, string message = "Improve runner") => Program.UserCommitOf(sha, login, message); + +/// One GraphQL page listing commit authors by name and login (null for no account). +static JsonNode Authors(params (string Name, string? Login)[] actors) => new JsonArray(new JsonObject +{ + ["data"] = new JsonObject + { + ["repository"] = new JsonObject + { + ["object"] = new JsonObject + { + ["authors"] = new JsonObject + { + ["totalCount"] = actors.Length, + ["nodes"] = new JsonArray([.. actors.Select(actor => (JsonNode)new JsonObject + { + ["name"] = actor.Name, + ["user"] = actor.Login is null ? null : new JsonObject { ["login"] = actor.Login }, + })]), + ["pageInfo"] = new JsonObject { ["hasNextPage"] = false, ["endCursor"] = null }, + }, + }, + }, + }, +}); + +static JsonObject Notes(string? entries = null, string? previous = "v1", string tag = "v2") +{ + entries ??= "* @service[bot] made their first contribution in https://github.com/example/widget/pull/22"; + var request = new JsonObject { ["repository"] = "example/widget", ["tag_name"] = tag }; + if (previous is not null) request["previous_tag_name"] = previous; + var target = previous is null ? $"commits/{tag}" : $"compare/{previous}...{tag}"; + var section = entries.Length > 0 ? "\n\n## New Contributors\n" + entries : ""; + return new JsonObject + { + ["request"] = request, + ["response"] = new JsonObject { ["body"] = "## What's Changed\n\n* Service update" + section + "\n\n**Full Changelog**: https://github.com/example/widget/" + target }, + }; +} + +static JsonObject WithBody(string? body) +{ + var notes = Notes(); + notes["response"]!["body"] = body; + return notes; +} + +static string Draft(JsonNode e, string? summary = null) +{ + summary ??= "This release improves contributor-complete verification for automated service updates.\n\n" + + "- **Contributor attribution** now keeps every verified PR contributor on the shared source line,\n" + + "- **Draft verification** rejects incomplete sources and malformed release-summary structure."; + var target = e["previous"] is null ? "commits/v2" : "compare/v1...v2"; + return "## What's Changed\n\n" + summary + "\n\nSources:\n\n" + string.Join("\n", Sources(e)) + "\n\n**Full Changelog**: https://github.com/example/widget/" + target; +} + +static string WithNewcomers(JsonNode e) => Draft(e).Replace("\n\n**Full Changelog**:", + "\n\n## New Contributors\n\n" + string.Join("\n", Newcomers(e)) + "\n\n**Full Changelog**:"); + +static JsonNode J(string json) => JsonNode.Parse(json)!; +static JsonNode Fail(string message) => new JsonObject { ["error"] = message }; +static List Strings(JsonNode? node) => node is JsonArray array ? [.. array.Select(item => item!.GetValue())] : []; +static List Sources(JsonNode e) => Strings(e["sources"]); +static List Newcomers(JsonNode e) => Strings(e["new_contributors"]); +static List Issues(JsonNode e) => Strings(e["issues"]); +static bool Complete(JsonNode e) => e["complete"]!.GetValue(); +static void MustComplete(JsonNode e, string context = "") => Must(Complete(e), $"{context} incomplete: {e["issues"]}"); +static void Must(bool condition, string message) +{ + if (!condition) throw new Failure(message); +} + +internal sealed class Failure(string message) : Exception(message); + +internal sealed record Run(string Directory, int Code, string Output, string Error, List Calls, JsonObject? Evidence) +{ + /// The REST endpoints that were read, in no particular order. + public List Endpoints => [.. Calls.Where(call => call is ["api", "--method", "GET", ..]).Select(call => call[^1])]; +} + +/// The fixture of the former Python test: one squash-merged PR with three original commits across two pages. +internal sealed class Scenario +{ + public const string Prefix = "repos/example/widget"; + + public JsonObject Pr { get; } = (JsonObject)JsonNode.Parse(""" + {"number":22,"title":"Service update","user":{"login":"service[bot]"},"html_url":"https://github.com/example/widget/pull/22","merged_at":"today", + "merge_commit_sha":"squash","base":{"repo":{"full_name":"example/widget"}},"commits":3,"changed_files":1,"body":"Only dependencies"} + """)!; + + /// Keys that start with '/' are under ; "users/..." and "graphql:<sha>" are as written. + public Dictionary Routes { get; } = new(StringComparer.Ordinal); + + public Dictionary Delays { get; } = new(StringComparer.Ordinal); + + public Scenario() + { + Routes["/commits/v1"] = JsonNode.Parse("""[{"sha":"base"}]"""); + Routes["/commits/v2"] = JsonNode.Parse("""[{"sha":"head"}]"""); + Routes["/compare/base...head?per_page=100"] = new JsonArray(new JsonObject + { + ["total_commits"] = 1, + ["commits"] = new JsonArray(Program.CommitOf("squash")), + ["files"] = JsonNode.Parse("""[{"filename":"CONTRIBUTING.md","patch":"+New workflow"}]"""), + }); + Routes["/commits/squash/pulls?per_page=100"] = JsonNode.Parse("""[[{"number":22}]]"""); + Routes["/pulls/22"] = new JsonArray(Pr); + Routes["/pulls/22/commits?per_page=100"] = new JsonArray(new JsonArray(Program.CommitOf("a")), new JsonArray(Program.CommitOf("b", "automation"), Program.CommitOf("c", "human"))); + Routes["/pulls/22/files?per_page=100"] = JsonNode.Parse("""[[{"filename":"CONTRIBUTING.md","patch":"+New workflow"}]]"""); + } + + public JsonObject PrCopy(int number, string mergeCommit, int commits) + { + var copy = (JsonObject)Pr.DeepClone(); + copy["number"] = number; + copy["merge_commit_sha"] = mergeCommit; + copy["commits"] = commits; + copy["html_url"] = $"https://github.com/example/widget/pull/{number}"; + return copy; + } + + public void InitialRoutes() + { + Routes["/commits/v2"] = JsonNode.Parse("""[{"sha":"squash","commit":{"tree":{"sha":"tree"}}}]"""); + Routes["/commits?sha=squash&per_page=100"] = new JsonArray(new JsonArray(Program.CommitOf("squash")), new JsonArray(Program.CommitOf("root", "founder"))); + Routes["/git/trees/tree?recursive=1"] = JsonNode.Parse(""" + [{"truncated":false,"tree":[{"path":"src","type":"tree"},{"path":"src/app.py","type":"blob"},{"path":"vendor","type":"commit"}]}] + """); + Routes["/commits/root/pulls?per_page=100"] = JsonNode.Parse("[[]]"); + } + + public void PriorRoutes(JsonObject[]? commits = null) + { + commits ??= [Program.CommitOf("base", "maintainer")]; + Routes["/commits/base"] = JsonNode.Parse("""[{"sha":"base","commit":{"tree":{"sha":"old-tree"}}}]"""); + Routes["/commits?sha=base&per_page=100"] = new JsonArray(new JsonArray([.. Enumerable.Reverse(commits)])); + Routes["/git/trees/old-tree?recursive=1"] = JsonNode.Parse("""[{"truncated":false,"tree":[]}]"""); + foreach (var commit in commits) Routes[$"/commits/{commit["sha"]}/pulls?per_page=100"] = JsonNode.Parse("[[]]"); + } + + public void PriorSquashRoutes() + { + PriorRoutes(); + Routes["/commits/base/pulls?per_page=100"] = JsonNode.Parse("""[[{"number":9}]]"""); + Routes["/pulls/9"] = new JsonArray(PrCopy(9, "base", 1)); + Routes["/pulls/9/commits?per_page=100"] = new JsonArray(new JsonArray(Program.UserCommitOf("old-original", "returning"))); + Routes["/pulls/9/files?per_page=100"] = JsonNode.Parse("""[[{"filename":"old.py"}]]"""); + Routes["/pulls/22/commits?per_page=100"]![0]![0] = Program.UserCommitOf("a", "returning"); + Routes["/pulls/22/commits?per_page=100"]![1]![0] = Program.UserCommitOf("b", "new-user"); + } + + public JsonObject ToRoutes() + { + var routes = new JsonObject(); + foreach (var (key, value) in Routes) + { + var route = value is JsonObject failure && failure.ContainsKey("error") ? (JsonObject)failure.DeepClone() : new JsonObject { ["pages"] = value?.DeepClone() }; + if (Delays.TryGetValue(key, out var delay)) route["delay_ms"] = delay; + routes[key.StartsWith('/') ? Prefix + key : key] = route; + } + return routes; + } +} + +internal static partial class Program +{ + public static JsonObject CommitOf(string sha, string? login = "service[bot]", string message = "Service update") => new() + { + ["sha"] = sha, + ["author"] = login is null ? null : new JsonObject { ["login"] = login }, + ["html_url"] = $"https://github.com/example/widget/commit/{sha}", + ["commit"] = new JsonObject { ["message"] = message, ["author"] = new JsonObject { ["name"] = "Recorded Name" } }, + }; + + public static JsonObject UserCommitOf(string sha, string login, string message = "Improve runner") + { + var commit = CommitOf(sha, login, message); + commit["author"]!["type"] = "User"; + return commit; + } +} + +/// Answers gh calls from the run's routes.json and records each call as its own file. +internal static class FakeGitHub +{ + public static int Run(string[] args) + { + var state = Environment.GetEnvironmentVariable("RELEASE_TEST_STATE")!; + File.WriteAllText(Path.Combine(state, "calls", Guid.NewGuid().ToString("N") + ".json"), JsonSerializer.Serialize(args)); + string key; + if (args is ["api", "--method", "GET", "--paginate", "--slurp", var endpoint]) key = endpoint; + else if (args is ["api", "graphql", "--paginate", "--slurp", ..] && args.FirstOrDefault(arg => arg.StartsWith("sha=", StringComparison.Ordinal)) is { } sha) key = "graphql:" + sha[4..]; + else + { + Console.Error.WriteLine($"unexpected gh call: {string.Join(' ', args)}"); + return 2; + } + + var routes = JsonNode.Parse(File.ReadAllText(Path.Combine(state, "routes.json")))!.AsObject(); + if (routes[key] is not JsonObject route) + { + Console.Error.WriteLine($"gh: Not Found (HTTP 404) for {key}"); + return 1; + } + if (route["delay_ms"] is { } delay) Thread.Sleep(delay.GetValue()); + if (route["error"] is { } error) + { + Console.Error.WriteLine(error.GetValue()); + return 1; + } + Console.Out.Write(route["pages"]!.ToJsonString()); + return 0; + } +} diff --git a/scripts/tests/git-visual-commits-tests.cs b/scripts/tests/git-visual-commits-tests.cs new file mode 100644 index 00000000..502e1f9a --- /dev/null +++ b/scripts/tests/git-visual-commits-tests.cs @@ -0,0 +1,298 @@ +#!/usr/bin/env dotnet +#:property TargetFramework=net10.0 +#:property RollForward=Major +#:property Nullable=enable +#:property PublishAot=false +#:include ../../skills/git-visual-commits/scripts/GitProcess.cs +#:include ../../skills/git-visual-commits/scripts/ExecutableResolver.cs +#:include ../eval-runners/windows-owned-process.cs + +using System.Diagnostics; +using Agentic.Tooling.Execution; +using System.Text.Json.Nodes; + +// A copy of this app named `gh` is first on PATH, so no case reaches GitHub. +if (Path.GetFileNameWithoutExtension(Environment.ProcessPath) == "gh") return FakeGitHub.Run(args); + +if (args.Length < 1 || !File.Exists(args[0])) throw new ArgumentException("Pass the built validate-commit.dll, then optional case name filters."); +var app = Path.GetFullPath(args[0]); +var watch = Stopwatch.StartNew(); +using var stop = new CancellationTokenSource(TimeSpan.FromMinutes(3)); +var root = Path.Combine(Path.GetTempPath(), "git-visual-commits-test-" + Guid.NewGuid().ToString("N")[..12]); +var shim = Path.Combine(root, "shim"); +var noGh = Path.Combine(root, "no-gh"); +var dotnet = ExecutableResolver.Resolve(OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); +var dotnetRoot = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(typeof(object).Assembly.Location)!)!)!)!; + +var cases = new List(); +void Subject(string name, string subject, bool pass, string mode = "Forbidden", params string[] expected) => + cases.Add(new(name, ["subject", "--subject", subject, "--prefix-mode", mode], pass, expected)); +void Trailer(string name, string message, bool pass, bool allow = false, string resolver = "never", params string[] expected) => + cases.Add(new(name, ["trailers", "-Message", message, .. allow ? new[] { "-AllowVerifiedCoAuthors" } : []], pass, expected, resolver)); + +// Subject cases carried over unchanged from the former PowerShell test-commit-subject.ps1. +Subject("valid default subject", "💬 update changelog for v10.0.10", true); +Subject("valid description with identifier", "🐛 handle OAuth callback failure", true); +Subject("valid opt-in prefix", "🐛 fix: handle missing release tag", true, "Required"); +Subject("valid exact maximum", "💬 " + new string('a', 68), true); +foreach (var emoji in new[] { "💰", "🪙", "💴", "💵", "💶", "💷", "💸", "💳", "🧾", "💹", "📋", "🧑🏽‍💻", "🇩🇰", "1️⃣", "⚡" }) Subject($"extended Unicode emoji {emoji}", $"{emoji} update finance records", true); +foreach (var emoji in new[] { "‼️", "⁉️", "‼", "⁉", "➕", "#️⃣", "*️⃣" }) Subject($"punctuation and keycap emoji {emoji}", $"{emoji} update budget", true); +foreach (var symbol in new[] { "+", "+️", "∑", "♜", "$", "1", "#", "*" }) Subject($"ordinary symbol {symbol} is not emoji", $"{symbol} update budget", false, "Forbidden", "one Unicode emoji sequence"); +Subject("text instead of emoji", "money update budget", false, "Forbidden", "one Unicode emoji sequence"); +Subject("shortcode instead of emoji", ":moneybag: update budget", false, "Forbidden", "one Unicode emoji sequence"); +Subject("multiple emoji", "💰💸 update budget", false, "Forbidden", "one Unicode emoji sequence"); +Subject("reported screenshot regression", "📋 Update CHANGELOG for v10.0.10 with dependency and tooling updates", false, "Forbidden", "lowercase letter"); +Subject("approved emoji with uppercase description", "💬 Update changelog", false, "Forbidden", "lowercase letter"); +Subject("double separator", "💬 update changelog", false, "Forbidden", "exactly one ASCII space"); +Subject("overlong subject", "💬 " + new string('a', 69), false, "Forbidden", "the maximum is 70"); +Subject("unexpected conventional prefix", "💬 docs: update changelog", false, "Forbidden", "prefix is forbidden"); +Subject("invalid conventional prefix", "🐛 feat: handle missing release tag", false, "Required", "Prefix 'feat:' is not allowed"); +// New: line breaks, surrounding whitespace and a missing description. +Subject("two lines", "💬 update changelog\nsecond line", false, "Forbidden", "exactly one line"); +Subject("trailing space", "💬 update changelog ", false, "Forbidden", "leading or trailing whitespace"); +Subject("combo mode without prefix", "🐛 handle missing tag", false, "Required", "Combo mode requires"); + +// Trailer cases carried over unchanged from the former PowerShell test-commit-trailers.ps1. +Trailer("clean message passes offline", "🐛 fix parser edge case\n\nPreserve empty trailing segments.", true); +Trailer("empty body passes offline", "", true); +Trailer("default forbids Claude trailer offline", "🐛 fix parser\n\nCo-Authored-By: Claude ", false, expected: ["forbidden by default", "Claude"]); +Trailer("default forbids Copilot trailer offline", "🐛 fix parser\n\nCo-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>", false, expected: ["forbidden by default", "Copilot"]); +Trailer("default forbids Freebuff trailer offline", "🐛 fix parser\n\nCo-Authored-By: Freebuff ", false, expected: ["forbidden by default", "Freebuff"]); +Trailer("default forbids even human trailer without explicit opt-in", "🐛 fix parser\n\nCo-authored-by: Jane Doe <12345+janedoe@users.noreply.github.com>", false, expected: ["forbidden by default"]); +Trailer("opt-in allows verified noreply id User", "🐛 fix parser\n\nCo-authored-by: Jane Doe <12345+janedoe@users.noreply.github.com>", true, true, "mock"); +Trailer("opt-in allows verified noreply login User", "🐛 fix parser\n\nCo-authored-by: Jane Doe ", true, true, "mock"); +Trailer("opt-in allows verified public email User", "🐛 fix parser\n\nCo-authored-by: Jane Doe ", true, true, "mock"); +Trailer("opt-in rejects Copilot Bot trailer", "🐛 fix parser\n\nCo-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>", false, true, "mock", "GitHub Bot", "@Copilot", "remove this trailer"); +Trailer("opt-in rejects unmapped Claude trailer", "🐛 fix parser\n\nCo-Authored-By: Claude ", false, true, "mock", "could not be deterministically resolved", "remove this trailer"); +Trailer("opt-in rejects unmapped Freebuff trailer", "🐛 fix parser\n\nCo-Authored-By: Freebuff ", false, true, "mock", "could not be deterministically resolved", "remove this trailer"); +Trailer("opt-in rejects Mannequin account", "🐛 fix parser\n\nCo-authored-by: Migrated <77777+migrated@users.noreply.github.com>", false, true, "mock", "GitHub Mannequin", "remove this trailer"); +Trailer("opt-in rejects mismatched noreply id and login", "🐛 fix parser\n\nCo-authored-by: Jane <99999+janedoe@users.noreply.github.com>", false, true, "mock", "does not match", "remove this trailer"); +Trailer("opt-in rejects non-matching public email", "🐛 fix parser\n\nCo-authored-by: Mismatch ", false, true, "mock", "does not match the verified public email", "remove this trailer"); +Trailer("opt-in rejects ambiguous email match", "🐛 fix parser\n\nCo-authored-by: Ambiguous ", false, true, "mock", "matched multiple GitHub accounts and is ambiguous", "remove this trailer"); +Trailer("opt-in rejects malformed trailer", "🐛 fix parser\n\nCo-authored-by: Claude", false, true, "never", "Malformed Co-authored-by trailer"); +Trailer("opt-in fails closed when gh fails", "🐛 fix parser\n\nCo-authored-by: Jane Doe <12345+janedoe@users.noreply.github.com>", false, true, "failing", "could not be verified", "remove this trailer"); +// New: gh missing from PATH, and one good plus one bad trailer in the same message. +Trailer("opt-in fails closed when gh is missing", "🐛 fix parser\n\nCo-authored-by: Jane Doe <12345+janedoe@users.noreply.github.com>", false, true, "missing", "gh) is unavailable", "remove this trailer"); +Trailer("one bad trailer fails the whole message", "🐛 fix parser\n\nCo-authored-by: Jane Doe <12345+janedoe@users.noreply.github.com>\nCo-Authored-By: Claude ", false, true, "mock", "could not be deterministically resolved"); + +// Command line: unknown options, missing values and conflicting sources fail before any work. +cases.Add(new("unknown command", ["lint"], false, ["Unknown command 'lint'"])); +cases.Add(new("unknown option", ["subject", "--subject", "💬 update", "--force"], false, ["Unknown option '--force'"])); +cases.Add(new("missing subject", ["subject"], false, ["Missing --subject"])); +cases.Add(new("bad prefix mode", ["subject", "--subject", "💬 update", "--prefix-mode", "Maybe"], false, ["Forbidden or Required"])); +cases.Add(new("message and commit together", ["trailers", "--message", "x", "--commit", "HEAD"], false, ["exactly one of --message or --commit"])); +cases.Add(new("option without value", ["trailers", "--message"], false, ["needs a value"])); + +var results = new string?[cases.Count + 2]; +Console.Error.WriteLine($"[START] +0.00s git-visual-commits tests ({cases.Count + 2} cases)"); +try +{ + Directory.CreateDirectory(noGh); + Directory.CreateDirectory(shim); + foreach (var file in Directory.EnumerateFiles(AppContext.BaseDirectory)) File.Copy(file, Path.Combine(shim, Path.GetFileName(file))); + var extension = OperatingSystem.IsWindows() ? ".exe" : string.Empty; + File.Move(Path.Combine(shim, "git-visual-commits-tests" + extension), Path.Combine(shim, "gh" + extension)); + + var selected = Enumerable.Range(0, cases.Count + 2).Where(index => args.Length == 1 || args.Skip(1).Any(filter => Name(index).Contains(filter, StringComparison.OrdinalIgnoreCase))).ToArray(); + var done = 0; + await Parallel.ForEachAsync(selected, new ParallelOptions { MaxDegreeOfParallelism = Math.Clamp(Environment.ProcessorCount, 1, 8), CancellationToken = stop.Token }, async (index, token) => + { + try + { + results[index] = index == cases.Count ? await CommitHeadAsync(token) + : index == cases.Count + 1 ? await ObservabilityAsync(token) + : await RunCaseAsync(cases[index], index, token); + } + catch (Exception exception) + { + results[index] = $"FAIL {Name(index)}: {exception.Message}"; + } + + Console.Error.WriteLine(FormattableString.Invariant($"[PROGRESS] +{watch.Elapsed.TotalSeconds:F2}s {Interlocked.Increment(ref done)}/{selected.Length} {results[index]}")); + }); + + var failed = selected.Where(index => results[index]?.StartsWith("PASS ", StringComparison.Ordinal) != true).ToArray(); + Console.Error.WriteLine(FormattableString.Invariant($"[{(failed.Length == 0 ? "COMPLETE" : "FAILED")}] +{watch.Elapsed.TotalSeconds:F2}s {selected.Length - failed.Length}/{selected.Length} cases")); + foreach (var index in failed) Console.WriteLine(results[index] ?? $"FAIL {Name(index)}: did not run"); + if (failed.Length == 0) Console.WriteLine($"PASS git-visual-commits deterministic tests ({selected.Length} cases)"); + return failed.Length == 0 ? 0 : 1; +} +finally +{ + try { Directory.Delete(root, recursive: true); } catch (IOException) { } catch (UnauthorizedAccessException) { } +} + +string Name(int index) => index == cases.Count ? "commit HEAD clean and injected trailer" + : index == cases.Count + 1 ? "trailers observability, heartbeats, timeout and progress file" + : cases[index].Name; + +async Task RunCaseAsync(Case item, int index, CancellationToken token) +{ + var state = Path.Combine(root, "case-" + index); + Directory.CreateDirectory(state); + var result = await RunToolAsync(item.Arguments, state, item.Resolver, state, token); + var calls = Path.Combine(state, "gh-calls.log"); + if (item.Resolver == "never" && File.Exists(calls)) return $"FAIL {item.Name}: gh was called: {File.ReadAllText(calls).Trim()}"; + if ((result.Code == 0) != item.Pass) return $"FAIL {item.Name}: expected pass={item.Pass}, exit {result.Code}. stdout: {result.Output.Trim()} stderr: {result.Error.Trim()}"; + if (item.Pass && JsonNode.Parse(result.Output)?["Valid"]?.GetValue() != true) return $"FAIL {item.Name}: stdout is not a valid result: {result.Output}"; + if (!item.Pass && result.Output.Length > 0) return $"FAIL {item.Name}: a failure wrote to stdout: {result.Output}"; + var missing = item.Expected.FirstOrDefault(text => !result.Error.Contains(text, StringComparison.OrdinalIgnoreCase)); + return missing is null ? $"PASS {item.Name}" : $"FAIL {item.Name}: stderr lacks '{missing}': {result.Error.Trim()}"; +} + +async Task CommitHeadAsync(CancellationToken token) +{ + var repository = Path.Combine(root, "repository"); + Directory.CreateDirectory(repository); + async Task Git(params string[] arguments) + { + var result = await RunAsync("git", arguments, repository, "never", repository, token); + if (result.Code != 0) throw new InvalidOperationException($"git {string.Join(' ', arguments)}: {result.Error}"); + } + + await Git("init", "-q"); + File.WriteAllText(Path.Combine(repository, "sample.txt"), "one"); + await Git("add", "sample.txt"); + await Git("commit", "-q", "-m", "📝 add sample file", "-m", "Keep commit body free of trailers."); + // Run from another folder so that --repository-path must select the repository. + var clean = await RunToolAsync(["trailers", "--commit", "HEAD", "--repository-path", repository], root, "never", repository, token); + var json = clean.Code == 0 ? JsonNode.Parse(clean.Output) : null; + if (json?["Valid"]?.GetValue() != true || json["TrailerCount"]?.GetValue() != 0) return $"FAIL commit HEAD clean check: {clean.Output} {clean.Error}"; + + File.WriteAllText(Path.Combine(repository, "sample.txt"), "two"); + await Git("add", "sample.txt"); + await Git("commit", "-q", "-m", "🐛 update sample file", "-m", "Injected trailer test.\n\nCo-Authored-By: Claude "); + var injected = await RunToolAsync(["trailers", "-Commit", "HEAD"], repository, "never", repository, token); + if (injected.Code == 0 || !injected.Error.Contains("forbidden by default", StringComparison.Ordinal)) return $"FAIL commit HEAD injected trailer was not rejected: {injected.Output} {injected.Error}"; + + var unknown = await RunToolAsync(["trailers", "--commit", "no-such-ref"], repository, "never", repository, token); + return unknown.Code != 0 && unknown.Error.Contains("Failed to read commit message for 'no-such-ref'", StringComparison.Ordinal) + ? "PASS commit HEAD clean and injected trailer" + : $"FAIL an unknown commit was not reported: {unknown.Output} {unknown.Error}"; +} + +async Task ObservabilityAsync(CancellationToken token) +{ + var state = Path.Combine(root, "observability"); + Directory.CreateDirectory(state); + const string verifiedMessage = "🐛 fix parser\n\nCo-authored-by: Jane Doe <12345+janedoe@users.noreply.github.com>"; + + var progressPath = Path.Combine(state, "progress.json"); + var ok = await RunToolAsync(["trailers", "--message", verifiedMessage, "--allow-verified-co-authors", "--progress-file", progressPath], state, "mock", state, token); + if (ok.Code != 0) return $"FAIL trailers observability success exited {ok.Code}: {ok.Error}"; + if (JsonNode.Parse(ok.Output)?["Valid"]?.GetValue() != true) return $"FAIL trailers observability stdout: {ok.Output}"; + foreach (var marker in new[] { "[START]", "[PROGRESS]", "[COMPLETE]", "progressFile=" }) + { + if (!ok.Error.Contains(marker, StringComparison.Ordinal)) return $"FAIL trailers stderr lacks {marker}: {ok.Error}"; + } + if (ok.Error.Contains('\u001b')) return "FAIL trailers stderr contains ANSI escape sequences"; + var snapshot = JsonNode.Parse(File.ReadAllText(progressPath))!; + if ((string?)snapshot["schema"] != "codebeltnet/agentic/progress/1" || (string?)snapshot["state"] != "succeeded" || snapshot["staleAfterUtc"] is not null || (int?)snapshot["counts"]?["completed"] != 1) + { + return $"FAIL trailers terminal progress snapshot: {snapshot}"; + } + + var quiet = await RunToolAsync(["trailers", "--message", verifiedMessage, "--allow-verified-co-authors", "--quiet", "--progress-file", Path.Combine(state, "quiet.json")], state, "mock", state, token); + if (quiet.Code != 0 || quiet.Output != ok.Output || quiet.Error.Contains("[START]") || quiet.Error.Contains("[PROGRESS]") || quiet.Error.Contains("[HEARTBEAT]") || !quiet.Error.Contains("[COMPLETE]")) + { + return $"FAIL trailers --quiet behavior: {quiet.Error}"; + } + + var failPath = Path.Combine(state, "failed.json"); + var failed = await RunToolAsync(["trailers", "--message", verifiedMessage, "--progress-file", failPath], state, "never", state, token); + if (failed.Code == 0 || !failed.Error.Contains("forbidden by default") || !failed.Error.Contains("[FAILED]")) return $"FAIL trailers failure observability: {failed.Error}"; + if ((string?)JsonNode.Parse(File.ReadAllText(failPath))?["state"] != "failed") return $"FAIL trailers failure progress file: {File.ReadAllText(failPath)}"; + + var foreign = Path.Combine(state, "foreign.json"); + File.WriteAllText(foreign, """{"mine":true}"""); + var foreignRun = await RunToolAsync(["trailers", "--message", verifiedMessage, "--progress-file", foreign], state, "never", state, token); + if (foreignRun.Code == 0 || File.ReadAllText(foreign) != """{"mine":true}""") return $"FAIL foreign progress file was overwritten: {foreignRun.Error}"; + + var slow = await RunToolAsync(["trailers", "--message", verifiedMessage, "--allow-verified-co-authors", "--heartbeat-seconds", "1", "--progress-file", Path.Combine(state, "slow.json")], state, "slow", state, token); + if (slow.Code != 0 || !slow.Error.Contains("[HEARTBEAT]")) return $"FAIL slow gh did not emit heartbeat: {slow.Error}"; + var noBeat = await RunToolAsync(["trailers", "--message", verifiedMessage, "--allow-verified-co-authors", "--heartbeat-seconds", "1", "--no-heartbeat", "--progress-file", Path.Combine(state, "nobeat.json")], state, "slow", state, token); + if (noBeat.Code != 0 || noBeat.Error.Contains("[HEARTBEAT]")) return $"FAIL --no-heartbeat still emitted heartbeat: {noBeat.Error}"; + + var timeoutPath = Path.Combine(state, "timeout.json"); + var clock = Stopwatch.StartNew(); + var timedOut = await RunToolAsync(["trailers", "--message", verifiedMessage, "--allow-verified-co-authors", "--timeout-seconds", "3", "--heartbeat-seconds", "1", "--progress-file", timeoutPath], state, "hang", state, token); + if (timedOut.Code == 0 || timedOut.Output.Length > 0 || clock.Elapsed >= TimeSpan.FromSeconds(12) || !timedOut.Error.Contains("[HEARTBEAT]") || !timedOut.Error.Contains("[FAILED]") || !timedOut.Error.Contains("timed out")) + { + return $"FAIL timeout observability ({clock.Elapsed}): exit={timedOut.Code} stdout={timedOut.Output} stderr={timedOut.Error}"; + } + if ((string?)JsonNode.Parse(File.ReadAllText(timeoutPath))?["state"] != "failed") return $"FAIL timeout progress file: {File.ReadAllText(timeoutPath)}"; + + return "PASS trailers observability, heartbeats, timeout and progress file"; +} + +Task RunToolAsync(string[] arguments, string directory, string resolver, string state, CancellationToken token) => + RunAsync(dotnet, [app, .. arguments], directory, resolver, state, token); + +async Task RunAsync(string executable, string[] arguments, string directory, string resolver, string state, CancellationToken token) +{ + var startInfo = Git.CreateStartInfo(executable, directory, arguments); + // "missing" leaves only an empty folder on PATH, so gh cannot be found; every other case puts the fake gh first. + // The tool itself starts through the full dotnet path, and a --message check never needs git. + startInfo.Environment["PATH"] = resolver == "missing" ? noGh : shim + Path.PathSeparator + Environment.GetEnvironmentVariable("PATH"); + startInfo.Environment["DOTNET_ROOT"] = dotnetRoot; + startInfo.Environment["COMMIT_TEST_STATE"] = state; + startInfo.Environment["COMMIT_TEST_RESOLVER"] = resolver; + var config = Path.Combine(state, "gitconfig"); + File.WriteAllText(config, "[user]\n\tname = Test User\n\temail = test@example.com\n[gc]\n\tauto = 0\n[maintenance]\n\tauto = false\n[core]\n\tautocrlf = false\n"); + startInfo.Environment["GIT_CONFIG_GLOBAL"] = config; + startInfo.Environment["GIT_CONFIG_NOSYSTEM"] = "1"; + return await Git.RunProcessAsync(startInfo, token); +} + +internal sealed record Case(string Name, string[] Arguments, bool Pass, string[] Expected, string Resolver = "never"); + +internal static class FakeGitHub +{ + // The same answers as the mock resolver in the former PowerShell test-commit-trailers.ps1. + private static readonly Dictionary Answers = new(StringComparer.Ordinal) + { + ["user/12345"] = """{"login":"janedoe","type":"User"}""", + ["user/223556219"] = """{"login":"Copilot","type":"Bot"}""", + ["user/99999"] = """{"login":"otheruser","type":"User"}""", + ["user/77777"] = """{"login":"migrated","type":"Mannequin"}""", + ["users/janedoe"] = """{"login":"janedoe","type":"User","email":"jane@example.com"}""", + // Both candidates are valid Users with the searched email, so only the ambiguity check can reject them. + ["users/a"] = """{"login":"a","type":"User","email":"ambiguous@example.com"}""", + ["users/b"] = """{"login":"b","type":"User","email":"ambiguous@example.com"}""", + ["users/mismatch"] = """{"login":"mismatch","type":"User","email":"different@example.com"}""", + ["search/users?q=jane%40example.com%20in%3Aemail"] = """{"total_count":1,"items":[{"login":"janedoe"}]}""", + ["search/users?q=mismatch%40example.com%20in%3Aemail"] = """{"total_count":1,"items":[{"login":"mismatch"}]}""", + ["search/users?q=noreply%40anthropic.com%20in%3Aemail"] = """{"total_count":0,"items":[]}""", + ["search/users?q=noreply%40freebuff.dev%20in%3Aemail"] = """{"total_count":0,"items":[]}""", + ["search/users?q=ambiguous%40example.com%20in%3Aemail"] = """{"total_count":2,"items":[{"login":"a"},{"login":"b"}]}""", + }; + + public static int Run(string[] args) + { + var state = Environment.GetEnvironmentVariable("COMMIT_TEST_STATE")!; + File.AppendAllText(Path.Combine(state, "gh-calls.log"), string.Join(' ', args) + Environment.NewLine); + var resolver = Environment.GetEnvironmentVariable("COMMIT_TEST_RESOLVER"); + if (resolver == "failing") + { + Console.Error.WriteLine("gh: authentication required"); + return 1; + } + if (resolver == "slow") Thread.Sleep(2200); + if (resolver == "hang") Thread.Sleep(20000); + + if (args is not ["api", "--method", "GET", var endpoint]) + { + Console.Error.WriteLine($"unexpected gh call: {string.Join(' ', args)}"); + return 2; + } + + if (Answers.TryGetValue(endpoint, out var answer)) + { + Console.Out.WriteLine(answer); + return 0; + } + + Console.Error.WriteLine($"HTTP 404 Not Found for {endpoint}"); + return 1; + } +} diff --git a/scripts/tests/test-agent-smith-ref.ps1 b/scripts/tests/test-agent-smith-ref.ps1 index 8198d0b3..eb1a3634 100644 --- a/scripts/tests/test-agent-smith-ref.ps1 +++ b/scripts/tests/test-agent-smith-ref.ps1 @@ -1,5 +1,5 @@ #!/usr/bin/env pwsh -# Deterministic historical-validation regressions; all mutations stay in a temporary repository. +# Deterministic historical-validation regressions; all mutations stay in temporary repositories. [CmdletBinding()] param() @@ -13,62 +13,109 @@ if (-not $testRoot.StartsWith($tempRoot, [StringComparison]::OrdinalIgnoreCase)) throw "Test workspace escaped the temporary root: $testRoot" } +$regressionRelative = 'scripts/tests/agent-smith-repair-tests.cs' +$repairRelative = 'skills/agent-smith/scripts/repair-roslyn-multiproject-artifacts.cs' +$passMarker = 'Console.Out.WriteLine("All Roslyn multi-project artifact repair tests passed.");' +$encodingMarker = 'Console.OutputEncoding = new UTF8Encoding(false);' + function Invoke-FixtureGit { - param([string[]]$Arguments) - $output = & git -C $testRoot @Arguments 2>&1 + param([string]$Root, [string[]]$Arguments) + $output = & git -C $Root @Arguments 2>&1 if ($LASTEXITCODE -ne 0) { throw "Fixture git $Arguments failed (exit $LASTEXITCODE): $output" } return $output } -function Assert-Validation { - param([string]$Name, [string]$GitRef, [bool]$ShouldPass, [string]$Evidence) - $arguments = @('-NoProfile', '-NonInteractive', '-File', (Join-Path $testRoot 'scripts/tests/test-agent-smith.ps1')) - if ($GitRef) { $arguments += @('-Ref', $GitRef) } - $output = (& pwsh @arguments 2>&1) -join "`n" - $exitCode = $LASTEXITCODE - if (($exitCode -eq 0) -ne $ShouldPass -or -not $output.Contains($Evidence)) { - throw "${Name}: expected pass=$ShouldPass and evidence '$Evidence'; exit ${exitCode}:`n$output" - } - if (-not $ShouldPass -and $output.Contains('All Agent Smith focused checks passed')) { - throw "${Name}: validator reported success after a required regression failed." - } - Write-Output "[PASS] $Name" +function Save-FixtureCommit { + param([string]$Root, [string]$Message) + $null = Invoke-FixtureGit $Root @('add', '.') + $null = Invoke-FixtureGit $Root @('-c', 'user.name=Validation Fixture', '-c', 'user.email=fixture@example.invalid', '-c', 'commit.gpgsign=false', '-c', 'core.hooksPath=/dev/null', 'commit', '--quiet', '-m', $Message) + return [string](Invoke-FixtureGit $Root @('rev-parse', 'HEAD')) +} + +function Set-FixtureFile { + param([string]$Root, [string]$RelativePath, [string]$Content) + [System.IO.File]::WriteAllText((Join-Path $Root $RelativePath), $Content) +} + +# A fixture is a minimal repository holding the passing sources in its first commit. Each fixture then takes one +# worktree state, so the scenarios that share a state never observe another scenario's mutation. +function New-Fixture { + param([string]$Name) + $root = Join-Path $testRoot $Name + $null = New-Item -ItemType Directory -Path (Join-Path $root 'scripts/tests'), (Join-Path $root 'scripts/eval-runners'), (Join-Path $root 'skills/git-worktree-merge/scripts'), (Join-Path $root 'tooling/src/Agentic.Tooling/Diagnostics'), (Join-Path $root 'tooling/src/Agentic.Tooling/Execution') -Force + Copy-Item -LiteralPath (Join-Path $PSScriptRoot '../file-based-app.ps1') -Destination (Join-Path $root 'scripts') + Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'test-agent-smith.ps1') -Destination (Join-Path $root 'scripts/tests') + Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'agent-smith-repair-tests.cs') -Destination (Join-Path $root 'scripts/tests') + Copy-Item -LiteralPath (Join-Path $repoRoot 'scripts/eval-runners/windows-owned-process.cs') -Destination (Join-Path $root 'scripts/eval-runners') + Copy-Item -LiteralPath (Join-Path $repoRoot 'skills/git-worktree-merge/scripts/GitProcess.cs') -Destination (Join-Path $root 'skills/git-worktree-merge/scripts') + Copy-Item -LiteralPath (Join-Path $repoRoot 'tooling/src/Agentic.Tooling/Diagnostics/ProgressFile.cs') -Destination (Join-Path $root 'tooling/src/Agentic.Tooling/Diagnostics') + Copy-Item -LiteralPath (Join-Path $repoRoot 'tooling/src/Agentic.Tooling/Execution/ExecutableResolver.cs') -Destination (Join-Path $root 'tooling/src/Agentic.Tooling/Execution') + Copy-Item -LiteralPath (Join-Path $repoRoot 'skills/agent-smith') -Destination (Join-Path $root 'skills') -Recurse + $null = Invoke-FixtureGit $root @('init', '--quiet') + $passing = Save-FixtureCommit $root 'Passing historical fixture' + return [pscustomobject]@{ Root = $root; PassingRef = $passing } } try { - $null = New-Item -ItemType Directory -Path (Join-Path $testRoot 'scripts/tests'), (Join-Path $testRoot 'skills') -Force - Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'test-agent-smith.ps1') -Destination (Join-Path $testRoot 'scripts/tests') - Copy-Item -LiteralPath (Join-Path $repoRoot 'skills/agent-smith') -Destination (Join-Path $testRoot 'skills') -Recurse - $scriptsRoot = Join-Path $testRoot 'skills/agent-smith/scripts' - $regressionPath = Join-Path $scriptsRoot 'test-repair-roslyn-multiproject-artifacts.ps1' - $repairPath = Join-Path $scriptsRoot 'repair-roslyn-multiproject-artifacts.ps1' - $regression = [System.IO.File]::ReadAllText($regressionPath) - $repair = [System.IO.File]::ReadAllText($repairPath) - $null = Invoke-FixtureGit @('init', '--quiet') - $null = Invoke-FixtureGit @('add', '.') - $null = Invoke-FixtureGit @('-c', 'user.name=Validation Fixture', '-c', 'user.email=fixture@example.invalid', '-c', 'commit.gpgsign=false', '-c', 'core.hooksPath=/dev/null', 'commit', '--quiet', '-m', 'Passing historical fixture') - $passingRef = Invoke-FixtureGit @('rev-parse', 'HEAD') + $regression = [System.IO.File]::ReadAllText((Join-Path $PSScriptRoot 'agent-smith-repair-tests.cs')) + $repair = [System.IO.File]::ReadAllText((Join-Path $repoRoot $repairRelative)) # Keep content assertions intact while making the worktree executable observably different. - [System.IO.File]::WriteAllText($regressionPath, $regression + "`nthrow 'WORKTREE REGRESSION SENTINEL'`n") - Assert-Validation 'Historical regression ignores failing worktree regression' $passingRef $true 'All Roslyn multi-project artifact repair tests passed.' - Assert-Validation 'No-ref validation executes the worktree regression' '' $false 'WORKTREE REGRESSION SENTINEL' + $failingRegression = New-Fixture 'failing-worktree-regression' + Set-FixtureFile $failingRegression.Root $regressionRelative $regression.Replace($passMarker, 'throw new InvalidOperationException("WORKTREE REGRESSION SENTINEL");') - [System.IO.File]::WriteAllText($regressionPath, $regression) - [System.IO.File]::WriteAllText($repairPath, $repair.Replace('Set-StrictMode -Version Latest', "throw 'WORKTREE REPAIR SENTINEL'`nSet-StrictMode -Version Latest")) - Assert-Validation 'Historical regression ignores failing worktree sibling' $passingRef $true 'All Roslyn multi-project artifact repair tests passed.' + $failingSibling = New-Fixture 'failing-worktree-sibling' + Set-FixtureFile $failingSibling.Root $repairRelative $repair.Replace($encodingMarker, 'throw new InvalidOperationException("WORKTREE REPAIR SENTINEL");') # Store a regression that fails after exercising the real repair cases, then restore a passing worktree. - [System.IO.File]::WriteAllText($repairPath, $repair) - [System.IO.File]::WriteAllText($regressionPath, $regression + "`nthrow 'HISTORICAL REGRESSION SENTINEL'`n") - $null = Invoke-FixtureGit @('add', '.') - $null = Invoke-FixtureGit @('-c', 'user.name=Validation Fixture', '-c', 'user.email=fixture@example.invalid', '-c', 'commit.gpgsign=false', '-c', 'core.hooksPath=/dev/null', 'commit', '--quiet', '-m', 'Failing historical fixture') - $failingRef = Invoke-FixtureGit @('rev-parse', 'HEAD') - [System.IO.File]::WriteAllText($regressionPath, $regression) - Assert-Validation 'Passing worktree cannot hide historical regression failure' $failingRef $false 'HISTORICAL REGRESSION SENTINEL' - Assert-Validation 'No-ref validation still passes with the restored worktree' '' $true 'All Agent Smith focused checks passed' - Assert-Validation 'Invalid ref fails with an actionable read diagnostic' 'refs/heads/missing-ref' $false "Cannot read 'skills/agent-smith/SKILL.md' at 'refs/heads/missing-ref'" - Write-Output 'All Agent Smith ref isolation tests passed (6 scenarios).' + $failingHistory = New-Fixture 'failing-history' + Set-FixtureFile $failingHistory.Root $regressionRelative $regression.Replace($passMarker, 'throw new InvalidOperationException("HISTORICAL REGRESSION SENTINEL");') + $failingRef = Save-FixtureCommit $failingHistory.Root 'Failing historical fixture' + Set-FixtureFile $failingHistory.Root $regressionRelative $regression + + $scenarios = @( + [pscustomobject]@{ Name = 'Historical regression ignores failing worktree regression'; Root = $failingRegression.Root; GitRef = $failingRegression.PassingRef; ShouldPass = $true; Evidence = 'All Roslyn multi-project artifact repair tests passed.' } + [pscustomobject]@{ Name = 'No-ref validation executes the worktree regression'; Root = $failingRegression.Root; GitRef = ''; ShouldPass = $false; Evidence = 'WORKTREE REGRESSION SENTINEL' } + [pscustomobject]@{ Name = 'Historical regression ignores failing worktree sibling'; Root = $failingSibling.Root; GitRef = $failingSibling.PassingRef; ShouldPass = $true; Evidence = 'All Roslyn multi-project artifact repair tests passed.' } + [pscustomobject]@{ Name = 'Passing worktree cannot hide historical regression failure'; Root = $failingHistory.Root; GitRef = $failingRef; ShouldPass = $false; Evidence = 'HISTORICAL REGRESSION SENTINEL' } + [pscustomobject]@{ Name = 'No-ref validation still passes with the restored worktree'; Root = $failingHistory.Root; GitRef = ''; ShouldPass = $true; Evidence = 'All Agent Smith focused checks passed' } + [pscustomobject]@{ Name = 'Invalid ref fails with an actionable read diagnostic'; Root = $failingHistory.Root; GitRef = 'refs/heads/missing-ref'; ShouldPass = $false; Evidence = "Cannot read 'skills/agent-smith/SKILL.md' at 'refs/heads/missing-ref'" } + ) + + # Scenarios only read their fixture, so `agentic-tooling run-parallel` runs them concurrently, bounded, with + # process-tree ownership; results are asserted in declaration order. + . (Join-Path $repoRoot 'scripts/agentic-tooling.ps1') + $tooling = Resolve-AgenticToolingAssembly + $items = @(for ($index = 0; $index -lt $scenarios.Count; $index++) { + $arguments = @('pwsh', '-NoProfile', '-NonInteractive', '-File', (Join-Path $scenarios[$index].Root 'scripts/tests/test-agent-smith.ps1')) + if ($scenarios[$index].GitRef) { $arguments += @('-Ref', $scenarios[$index].GitRef) } + @{ name = "scenario-$index"; workingDirectory = $scenarios[$index].Root; steps = @(@{ command = $arguments }) } + }) + $itemsPath = Join-Path $testRoot 'scenarios.json' + [System.IO.File]::WriteAllText($itemsPath, (@{ schema = 'codebeltnet/agentic/parallel-items/1'; items = $items } | ConvertTo-Json -Depth 8), [System.Text.UTF8Encoding]::new($false)) + $resultsPath = & dotnet $tooling run-parallel --items $itemsPath --out (Join-Path $testRoot 'scenarios') --max-concurrency ([Math]::Min($scenarios.Count, [Environment]::ProcessorCount)) --timeout-seconds 240 --label 'agent-smith ref scenarios' --quiet 2>$null + # Half of the scenarios must fail, so the batch exit code says nothing; each outcome is asserted below. + $global:LASTEXITCODE = 0 + if (-not $resultsPath -or -not (Test-Path -LiteralPath $resultsPath)) { throw "run-parallel produced no results (exit $LASTEXITCODE)." } + $outcomes = @{} + foreach ($result in @((Get-Content -LiteralPath $resultsPath -Raw | ConvertFrom-Json).results)) { + $scenario = $scenarios[[int]$result.name.Substring('scenario-'.Length)] + $exitCode = if ($result.status -eq 'PASS') { 0 } elseif ($result.exitCode) { $result.exitCode } else { -1 } + $outcomes[$scenario.Name] = [pscustomobject]@{ Name = $scenario.Name; ExitCode = $exitCode; Output = ((Get-Content -LiteralPath $result.log -Raw) + ($result.details -join "`n")) } + } + + foreach ($scenario in $scenarios) { + $outcome = $outcomes[$scenario.Name] + if ($null -eq $outcome) { throw "$($scenario.Name): scenario produced no outcome." } + if (($outcome.ExitCode -eq 0) -ne $scenario.ShouldPass -or -not $outcome.Output.Contains($scenario.Evidence)) { + throw "$($scenario.Name): expected pass=$($scenario.ShouldPass) and evidence '$($scenario.Evidence)'; exit $($outcome.ExitCode):`n$($outcome.Output)" + } + if (-not $scenario.ShouldPass -and $outcome.Output.Contains('All Agent Smith focused checks passed')) { + throw "$($scenario.Name): validator reported success after a required regression failed." + } + Write-Output "[PASS] $($scenario.Name)" + } + Write-Output "All Agent Smith ref isolation tests passed ($($scenarios.Count) scenarios)." } finally { if (Test-Path -LiteralPath $testRoot) { Remove-Item -LiteralPath $testRoot -Recurse -Force diff --git a/scripts/tests/test-agent-smith.ps1 b/scripts/tests/test-agent-smith.ps1 index 6eeb4ddc..c3018877 100644 --- a/scripts/tests/test-agent-smith.ps1 +++ b/scripts/tests/test-agent-smith.ps1 @@ -34,10 +34,18 @@ $automation = Read-RepositoryText "$skillPath/references/automation.md" $core = Read-RepositoryText "$skillPath/references/core-principles.md" $api = Read-RepositoryText "$skillPath/references/api-design-and-compatibility.md" $delivery = Read-RepositoryText "$skillPath/references/delivery-and-repositories.md" +$documentation = Read-RepositoryText "$skillPath/references/documentation.md" +$architecture = Read-RepositoryText "$skillPath/references/architecture.md" +$handoff = Read-RepositoryText "$skillPath/references/agent-handoff-template.md" $agentic = Read-RepositoryText "$skillPath/references/agentic-engineering.md" $evals = Read-RepositoryText "$skillPath/evals/evals.json" -$repair = Read-RepositoryText "$skillPath/scripts/repair-roslyn-multiproject-artifacts.ps1" -$repairTests = Read-RepositoryText "$skillPath/scripts/test-repair-roslyn-multiproject-artifacts.ps1" +$repair = Read-RepositoryText "$skillPath/scripts/repair-roslyn-multiproject-artifacts.cs" +$repairProgress = Read-RepositoryText "$skillPath/scripts/ProgressFile.cs" +$canonicalProgress = Read-RepositoryText 'tooling/src/Agentic.Tooling/Diagnostics/ProgressFile.cs' +if ($repairProgress -cne $canonicalProgress) { + throw 'agent-smith/scripts/ProgressFile.cs drifted from tooling/src/Agentic.Tooling/Diagnostics/ProgressFile.cs.' +} +$repairTests = Read-RepositoryText 'scripts/tests/agent-smith-repair-tests.cs' # Mandatory routing remains in the entry point; procedures live in the loaded references. Assert-Contains 'SKILL.md' $skill 'read `references/skill-authoring.md` before recommending changes or editing' @@ -46,7 +54,7 @@ Assert-Contains 'SKILL.md' $skill 'If one cannot be loaded, fail with its path' foreach ($name in @('automation', 'agentic-engineering', 'core-principles')) { Assert-Contains 'SKILL.md' $skill "references/$name.md" } -if ($skill -match '--severity|--verify-no-changes|whole-document-namespace-conversion|repair-roslyn-multiproject-artifacts\.ps1') { +if ($skill -match '--severity|--verify-no-changes|whole-document-namespace-conversion|repair-roslyn-multiproject-artifacts\.(?:ps1|cs)') { throw 'Specialized conformance commands and recovery mechanics must stay behind reference routing.' } if (($skill -split '\s+').Count -ge 5000) { throw 'SKILL.md must remain below 5,000 words.' } @@ -87,6 +95,15 @@ Assert-Contains 'delivery-and-repositories.md' $delivery 'scaled trunk-based dev Assert-Contains 'delivery-and-repositories.md' $delivery 'Do not invent a universal OS matrix' Assert-Contains 'delivery-and-repositories.md' $delivery 'Follow shared tooling and configuration that the repository actually uses.' Assert-Contains 'delivery-and-repositories.md' $delivery 'If local repository policy requires Windows and Linux' +# Minimal repository documentation: policy in its reference, with always-loaded hooks in the entry point. +Assert-Contains 'SKILL.md' $skill 'load `references/documentation.md` before creating either' +Assert-Contains 'SKILL.md' $skill 'no unapproved documentation hierarchy or temporary engineering artifact entered source control' +foreach ($requirement in @('## Minimal repository documentation', '| `README.md` |', '| `AGENTS.md` |', '| `CHANGELOG.md` |', '| `LICENSE` |', 'DO NOT introduce a `docs/` directory', 'Persistence across agent sessions does not imply persistence in source control.', 'Confirm that Git ignores `.bot/` before writing there', 'prefer extending existing documentation over creating new files', 'Obtain maintainer approval before introducing a new documentation hierarchy.', 'Respect established documentation structures', 'without explicit authorization', 'let the repository earn its complexity')) { + Assert-Contains 'documentation.md' $documentation $requirement +} +Assert-Contains 'architecture.md' $architecture 'do not introduce a decision record hierarchy for it' +Assert-Contains 'delivery-and-repositories.md' $delivery 'use an ignored `.bot/` workspace or external temporary storage' +Assert-Contains 'agent-handoff-template.md' $handoff 'introduce an unapproved documentation hierarchy' Assert-Contains 'automation.md' $automation '1. Use a simple native command' Assert-Contains 'automation.md' $automation '2. Use PowerShell 7' Assert-Contains 'automation.md' $automation '3. Use C#/.NET' @@ -115,10 +132,10 @@ Assert-Contains 'dotnet-editorconfig-conformance.md' $reference 'Directory appli Assert-Contains 'dotnet-editorconfig-conformance.md' $reference "git grep -n -F 'Unmerged change from project'" Assert-Contains 'evals.json' $evals 'finish fixing all IDE0161 findings in MultiTargeted.sln' Assert-Contains 'evals.json' $evals 'fetches twelve independent service endpoints sequentially' -Assert-Contains 'repair script' $repair 'function Test-LinePrefix' -Assert-Contains 'repair script' $repair "pattern = 'whole-document-namespace-conversion'" -Assert-Contains 'repair script' $repair "pattern = 'unrecognized'" -Assert-Contains 'repair script' $repair '$Apply -and -not $hasUnsafeArtifact' +Assert-Contains 'repair script' $repair 'static bool TestLinePrefix' +Assert-Contains 'repair script' $repair '["pattern"] = "whole-document-namespace-conversion"' +Assert-Contains 'repair script' $repair '["pattern"] = "unrecognized"' +Assert-Contains 'repair script' $repair 'if (apply && !hasUnsafeArtifact)' Assert-Contains 'repair tests' $repairTests 'Directory apply partially repaired a file despite an unsafe sibling artifact.' Assert-Contains 'repair tests' $repairTests 'An unsupported localized artifact should fail closed.' @@ -163,10 +180,12 @@ Assert-Contains 'eval 20' ($cases | Where-Object id -eq 20).prompt "AGENTS.md re Assert-Contains 'eval 20' (($cases | Where-Object id -eq 20).expectations -join "`n") "shared workflow configuration as the basis" Assert-Contains 'eval 30' ($cases | Where-Object id -eq 30).prompt 'nothing in the current repository adopts that template or its conventions' Assert-Contains 'eval 30' (($cases | Where-Object id -eq 30).expectations -join "`n") 'similar naming is not local evidence' -if ($cases.Count -ne 34 -or @($cases.id | Sort-Object -Unique).Count -ne 34) { - throw 'Expected 14 preserved regression cases plus 20 judgement scenarios with unique IDs.' +# Older refs can predate the merge-readiness scenarios. +$expectedCaseCount = if ($Ref -and -not $core.Contains('Merge readiness requires positive evidence')) { 37 } else { 39 } +if ($cases.Count -ne $expectedCaseCount -or @($cases.id | Sort-Object -Unique).Count -ne $expectedCaseCount) { + throw "Expected $expectedCaseCount Agent Smith evaluation cases with unique IDs." } -foreach ($id in 1..34) { +foreach ($id in 1..$expectedCaseCount) { $case = @($cases | Where-Object id -eq $id) if ($case.Count -ne 1 -or [string]::IsNullOrWhiteSpace($case[0].prompt) -or [string]::IsNullOrWhiteSpace($case[0].expected_output) -or @($case[0].expectations).Count -lt 3) { throw "Eval $id must have a prompt, expected outcome, and at least three decision assertions." @@ -174,37 +193,62 @@ foreach ($id in 1..34) { $checks++ } -$regressionRoot = $repoRoot -$historicalRoot = $null +$tempRoot = [System.IO.Path]::GetFullPath([System.IO.Path]::GetTempPath()).TrimEnd('\', '/') + [System.IO.Path]::DirectorySeparatorChar +$workRoot = [System.IO.Path]::GetFullPath((Join-Path $tempRoot ('agent-smith-repair-work-' + [guid]::NewGuid().ToString('N')))) +if (-not $workRoot.StartsWith($tempRoot, [StringComparison]::OrdinalIgnoreCase)) { + throw "Regression workspace escaped the temporary root: $workRoot" +} try { + $null = [System.IO.Directory]::CreateDirectory($workRoot) + $sourcePath = Join-Path $repoRoot "$skillPath/scripts/repair-roslyn-multiproject-artifacts.cs" + $testsPath = Join-Path $repoRoot 'scripts/tests/agent-smith-repair-tests.cs' if (-not [string]::IsNullOrWhiteSpace($Ref)) { - $tempRoot = [System.IO.Path]::GetFullPath([System.IO.Path]::GetTempPath()).TrimEnd('\', '/') + [System.IO.Path]::DirectorySeparatorChar - $historicalRoot = [System.IO.Path]::GetFullPath((Join-Path $tempRoot ('agent-smith-ref-regression-' + [guid]::NewGuid().ToString('N')))) - if (-not $historicalRoot.StartsWith($tempRoot, [StringComparison]::OrdinalIgnoreCase)) { - throw "Historical regression workspace escaped the temporary root: $historicalRoot" + $tree = Join-Path $workRoot 'tree' + foreach ($rel in @( + "$skillPath/scripts/repair-roslyn-multiproject-artifacts.cs", + "$skillPath/scripts/ProgressFile.cs", + 'scripts/tests/agent-smith-repair-tests.cs', + 'skills/git-worktree-merge/scripts/GitProcess.cs', + 'tooling/src/Agentic.Tooling/Execution/ExecutableResolver.cs', + 'scripts/eval-runners/windows-owned-process.cs' + )) { + $dest = Join-Path $tree $rel + $null = [System.IO.Directory]::CreateDirectory((Split-Path -Parent $dest)) + [System.IO.File]::WriteAllText($dest, (Read-RepositoryText $rel)) } - $regressionRoot = $historicalRoot - $scriptsRoot = Join-Path $regressionRoot "$skillPath/scripts" - try { - $null = [System.IO.Directory]::CreateDirectory($scriptsRoot) - # The regression's only dependency is its sibling repair script. Use the same - # ref contents already asserted above, preserving their relative layout. - [System.IO.File]::WriteAllText((Join-Path $scriptsRoot 'repair-roslyn-multiproject-artifacts.ps1'), $repair) - [System.IO.File]::WriteAllText((Join-Path $scriptsRoot 'test-repair-roslyn-multiproject-artifacts.ps1'), $repairTests) - } catch { - throw "Cannot materialize Roslyn artifact recovery regressions at '$Ref' in '${historicalRoot}': $_" + $sourcePath = Join-Path $tree "$skillPath/scripts/repair-roslyn-multiproject-artifacts.cs" + $testsPath = Join-Path $tree 'scripts/tests/agent-smith-repair-tests.cs' + } + $fileBasedHelper = Join-Path $repoRoot 'scripts/file-based-app.ps1' + $assemblyPath = $null + $testsCmd = $null + if ([string]::IsNullOrWhiteSpace($Ref) -and (Test-Path -LiteralPath $fileBasedHelper -PathType Leaf)) { + . $fileBasedHelper + $sourceCmd = Get-FileBasedAppCommand -SourcePath $sourcePath + if ($sourceCmd.Mode -eq 'cached-assembly' -and -not [string]::IsNullOrWhiteSpace($sourceCmd.Assembly)) { + $assemblyPath = $sourceCmd.Assembly + } + $testsCmd = Get-FileBasedAppCommand -SourcePath $testsPath + } + if ([string]::IsNullOrWhiteSpace($assemblyPath)) { + $buildDir = Join-Path $workRoot 'build' + $buildOut = & dotnet build $sourcePath --artifacts-path $buildDir --nologo -v quiet 2>&1 + if ($LASTEXITCODE -ne 0) { + throw "repair-roslyn-multiproject-artifacts.cs build failed (exit $LASTEXITCODE): $($buildOut -join [Environment]::NewLine)" } - Push-Location -LiteralPath $historicalRoot + $assembly = Get-ChildItem -LiteralPath $buildDir -Recurse -Filter 'repair-roslyn-multiproject-artifacts.dll' | Where-Object { $_.FullName -match '[\\/]bin[\\/]' } | Select-Object -First 1 + if (-not $assembly) { throw 'repair-roslyn-multiproject-artifacts.cs build did not produce repair-roslyn-multiproject-artifacts.dll.' } + $assemblyPath = $assembly.FullName } - try { - & pwsh -NoProfile -NonInteractive -File (Join-Path $regressionRoot "$skillPath/scripts/test-repair-roslyn-multiproject-artifacts.ps1") - if ($LASTEXITCODE -ne 0) { throw "Roslyn artifact recovery regressions failed (exit $LASTEXITCODE; ref '$Ref'; script root '$regressionRoot')." } - } finally { - if ($historicalRoot) { Pop-Location } + if ($null -ne $testsCmd) { + & $testsCmd.Executable @($testsCmd.ArgumentPrefix + @($assemblyPath)) + } else { + & dotnet run --file $testsPath -- $assemblyPath } + if ($LASTEXITCODE -ne 0) { throw "Roslyn artifact recovery regressions failed (exit $LASTEXITCODE; ref '$Ref')." } } finally { - if ($historicalRoot -and (Test-Path -LiteralPath $historicalRoot)) { - Remove-Item -LiteralPath $historicalRoot -Recurse -Force + if (Test-Path -LiteralPath $workRoot) { + Remove-Item -LiteralPath $workRoot -Recurse -Force } } Write-Output "All Agent Smith focused checks passed ($checks content/schema checks plus Roslyn recovery regressions)." diff --git a/scripts/tests/test-scaffold-mtp.ps1 b/scripts/tests/test-scaffold-mtp.ps1 index 055b62d8..992b2c07 100644 --- a/scripts/tests/test-scaffold-mtp.ps1 +++ b/scripts/tests/test-scaffold-mtp.ps1 @@ -1,4 +1,7 @@ -param() +param( + # App and Library cases share no state, so the Templates batch runs them as separate work items. + [ValidateSet('All', 'App', 'Library')][string]$Scope = 'All' +) Set-StrictMode -Version Latest $ErrorActionPreference = 'Stop' @@ -29,57 +32,19 @@ function Invoke-DotNet { return ($output -join [Environment]::NewLine) } +# MSBuild writes the value to a file, because its console output can also contain notices such as +# "MSBuild server unavailable". +function Get-MSBuildProperty { + param([string]$Project, [string]$Name) + $resultPath = Join-Path $workspace "property-$([guid]::NewGuid().ToString('N')).txt" + [void](Invoke-DotNet -Arguments @('msbuild', $Project, "-getProperty:$Name", "-getResultOutputFile:$resultPath", '--nologo')) + return [System.IO.File]::ReadAllText($resultPath).Trim() +} + try { [void][System.IO.Directory]::CreateDirectory($workspace) - # Verify candidate discovery across major lines, excluding unlisted releases and prereleases. - & { - function Invoke-RestMethod { - param([string]$Uri) - if ($Uri.EndsWith('/v3/index.json')) { - return @{ resources = @(@{ '@type' = 'RegistrationsBaseUrl/3.6.0'; '@id' = 'https://fixture.invalid/' }) } - } - if ($Uri.EndsWith('/older-page.json')) { - return @{ items = @(@{ catalogEntry = @{ version = '11.2.1'; listed = $true } }) } - } - $versions = switch -Regex ($Uri) { - '/codebelt.extensions.xunit.app/' { @('12.0.2', '12.0.10', '12.1.0-preview.1', '13.0.0+build-1', '14.0.0'); break } - '/xunit.v3(?:.runner.console)?/' { @('3.2.2', '4.0.0', '4.0.1', '4.1.0-preview.1', '5.0.0'); break } - '/microsoft.aspnetcore.' { @('10.0.12', '11.0.0'); break } - default { @('1.0.0', '1.0.1', '2.0.0-preview.1') } - } - $leaves = @($versions | ForEach-Object { - @{ catalogEntry = @{ version = $_; listed = ($_ -ne '14.0.0') } } - }) - $pages = @([pscustomobject]@{ items = $leaves }) - if ($Uri -like '*/codebelt.extensions.xunit.app/*') { - $pages += [pscustomobject]@{ '@id' = 'https://fixture.invalid/older-page.json' } - } - return @{ items = $pages } - } - $resolved = & (Join-Path $repoRoot 'skills/dotnet-new-app-slnx/scripts/resolve-package-versions.ps1') -TargetFramework net10.0 | ConvertFrom-Json - foreach ($pair in @( - @('{CODEBELT_EXTENSIONS_XUNIT_APP_VERSION}', '13.0.0+build-1'), - @('{XUNIT_V3_VERSION}', '5.0.0'), - @('{XUNIT_V3_RUNNER_CONSOLE_VERSION}', '5.0.0'), - @('{MICROSOFT_ASPNETCORE_OPENAPI_VERSION}', '11.0.0') - )) { - if ($resolved.($pair[0]).version -ne $pair[1]) { throw "Resolver returned the wrong newest candidate for $($pair[0])." } - } - if (($resolved.'{CODEBELT_EXTENSIONS_XUNIT_APP_VERSION}'.candidate_versions -join ',') -ne '13.0.0+build-1,12.0.10,12.0.2,11.2.1') { - throw 'The resolver must return stable listed candidates from all registration pages in descending version order.' - } - foreach ($entry in $resolved.PSObject.Properties.Value) { - if ($entry.compatibility_status -ne 'provisional' -or $entry.target_framework -ne 'net10.0') { - throw 'Version-index lookup must not claim verified compatibility.' - } - } - $stsRuntime = & (Join-Path $repoRoot 'skills/dotnet-new-app-slnx/scripts/resolve-package-versions.ps1') -TargetFramework net11.0 | ConvertFrom-Json - if ($stsRuntime.'{CODEBELT_EXTENSIONS_XUNIT_APP_VERSION}'.compatibility_status -ne 'provisional' -or - $stsRuntime.'{CODEBELT_EXTENSIONS_XUNIT_APP_VERSION}'.target_framework -ne 'net11.0') { - throw 'The resolver must preserve provisional status for the requested test runtime.' - } - Write-Host '[PASS] Resolver returns stable listed candidates across major lines.' - } + # Candidate discovery for resolve-package-versions.cs and restore-missing-shared-assets.cs is covered by + # RestoreSharedAssetsCharacterizationTest in the Tooling suite, which builds the test project once. $sdkVersions = @(& dotnet --list-sdks) if ($LASTEXITCODE -ne 0) { throw 'Unable to enumerate installed SDKs.' } @@ -116,7 +81,7 @@ try { @{ Variant = 'lib'; Tfm = 'net10.0' }, @{ Variant = 'lib'; Tfm = 'net11.0' }, @{ Variant = 'lib'; Tfm = 'netstandard2.0;net10.0;net11.0' } - ) + ) | Where-Object { $Scope -eq 'All' -or ($Scope -eq 'App') -eq ($_.Variant -eq 'app') } foreach ($case in $cases) { $variant = $case.Variant $assetVariant = if ($variant -eq 'app') { 'app' } else { 'library' } @@ -219,12 +184,30 @@ using (var application = WebApplicationTestFactory.Create(hostFixture: } '@ } else { - $assertion = if ($case.HostType -eq 'worker') { - 'Assert.Contains(application.Host.Services.GetServices(), service => service is Worker);' + if ($case.HostType -eq 'worker') { + @" +using (var application = ApplicationTestFactory.Create(hostFixture: new ManagedApplicationFixture())) + { + Assert.Contains(application.Host.Services.GetServices(), service => service is Worker); + } +"@ } else { - 'Assert.NotNull(application.Host.Services.GetRequiredService());' + @" +var configured = false; + using (var application = ApplicationTestFactory.Create( + hostSetup: builder => builder.ConfigureServices((_, services) => + { + configured = true; + Assert.NotEmpty(services); + }), + hostFixture: new ManagedApplicationFixture())) + { + Assert.NotNull(application.Host); + Assert.True(configured); + Assert.NotNull(application.Environment); + } +"@ } - "using (var application = ApplicationTestFactory.Create(hostFixture: new ManagedApplicationFixture()))`n {`n $assertion`n }" } $returnType = if ($variant -eq 'app' -and $case.HostType -eq 'web') { 'async Task' } else { 'void' } $imports = if ($variant -eq 'lib') { '' } else { @@ -282,11 +265,11 @@ public class PriceCalculatorBenchmark @($testProject, ($runtimeTfms -join ';')), @($benchmarkProject, ($runtimeTfms -join ';')) )) { - $actual = Invoke-DotNet -Arguments @('msbuild', $pair[0], '-getProperty:TargetFrameworks', '--nologo') - if ($actual.Trim() -ne $pair[1]) { throw "$caseName rendered incorrect TargetFrameworks for $($pair[0]): $actual" } + $actual = Get-MSBuildProperty -Project $pair[0] -Name 'TargetFrameworks' + if ($actual -ne $pair[1]) { throw "$caseName rendered incorrect TargetFrameworks for $($pair[0]): $actual" } } - $runnerTfm = Invoke-DotNet -Arguments @('msbuild', $runnerProject, '-getProperty:TargetFramework', '--nologo') - if ($runnerTfm.Trim() -ne $runtimeTfms[-1]) { throw "$caseName benchmark runner must target the highest executable TFM." } + $runnerTfm = Get-MSBuildProperty -Project $runnerProject -Name 'TargetFramework' + if ($runnerTfm -ne $runtimeTfms[-1]) { throw "$caseName benchmark runner must target the highest executable TFM." } Write-Host "[PASS] ${caseName}: source matrix retained; tests, benchmarks and runner use executable TFMs only." } [void](Invoke-DotNet -Arguments @('build', 'MtpScaffold.slnx', '-c', 'Release', '-p:SkipSignAssembly=true', '--nologo')) @@ -325,7 +308,7 @@ public class PriceCalculatorBenchmark Write-Host "[PASS] ${caseName}: Release build with compatible dependencies and no separate TRX provider." } finally { Pop-Location } } - Write-Host '[PASS] Scaffold MTP regressions passed.' + Write-Host "[PASS] Scaffold MTP regressions passed ($Scope)." $completed = $true } finally { if ($completed -and (Test-Path $workspace)) { diff --git a/scripts/tests/worktree-coordination.cs b/scripts/tests/worktree-coordination.cs new file mode 100644 index 00000000..6826c594 --- /dev/null +++ b/scripts/tests/worktree-coordination.cs @@ -0,0 +1,324 @@ +#!/usr/bin/env dotnet +#:property TargetFramework=net10.0 +#:property RollForward=Major +#:property PublishAot=false +#:include ../../skills/git-worktree-merge/scripts/GitProcess.cs +#:include ../../tooling/src/Agentic.Tooling/Execution/ExecutableResolver.cs +#:include ../eval-runners/windows-owned-process.cs + +using System.Diagnostics; +using System.Text.Json; + +if (args is not [var hostApp, var verifier]) throw new ArgumentException("Pass the simulated host and worktree verifier assemblies."); +hostApp = Path.GetFullPath(hostApp); +verifier = Path.GetFullPath(verifier); +const string owner = "standalone-owner"; +const string workspace = "workspace-delivery"; +const string targetWriter = "target-writer"; +const string request = "Finalize delivery.txt only. Classify and preserve unrelated changes, validate the result, commit it locally, report the exact ref and tip, and pause writes."; +const string approval = "I authorize the owning agent to stage and create one local commit for delivery.txt on refs/heads/agent/delivery."; +string[] scenarios = ["already-merged", "idle", "unavailable", "failing", "mixed", "git-only", "managed", "authorized", "approval-missing", "shared-target", "mixed-commits", "governance-compatible", "governance-drift"]; +var clock = Stopwatch.StartNew(); +using var stop = new CancellationTokenSource(TimeSpan.FromMinutes(2)); +Console.CancelKeyPress += (_, eventArgs) => { eventArgs.Cancel = true; stop.Cancel(); }; +Log("START", $"Simulated worktree coordination ({scenarios.Length} scenarios)"); +using var heartbeat = new Timer(_ => Log("HEARTBEAT", "Simulated worktree coordination is running"), null, + TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(10)); +var failures = 0; +try +{ + await Parallel.ForEachAsync(scenarios, new ParallelOptions { CancellationToken = stop.Token, MaxDegreeOfParallelism = 3 }, async (scenario, token) => + { + var fixture = Directory.CreateTempSubdirectory("agentic-worktree-host-"); + try + { + await Verify(fixture.FullName, scenario, token); + Log("PROGRESS", $"PASS {scenario}"); + if (OperatingSystem.IsWindows()) + { + var options = new EnumerationOptions { RecurseSubdirectories = true, AttributesToSkip = FileAttributes.ReparsePoint }; + foreach (var file in fixture.EnumerateFiles("*", options)) file.IsReadOnly = false; + } + fixture.Delete(recursive: true); + } + catch (Exception error) + { + Interlocked.Increment(ref failures); + Log("PROGRESS", $"FAIL {scenario}: {error.Message} (fixture {fixture.FullName})"); + } + }); +} +catch (OperationCanceledException) when (stop.IsCancellationRequested) +{ + Log("FAILED", "Simulated worktree coordination timed out or was cancelled"); + return 2; +} +Log(failures == 0 ? "COMPLETE" : "FAILED", $"{scenarios.Length - failures}/{scenarios.Length} simulated coordination scenarios passed"); +return failures == 0 ? 0 : 1; + +async Task Verify(string root, string scenario, CancellationToken token) +{ + var exercise = Path.Combine(root, "exercise"); + var target = Path.Combine(exercise, "delivery"); + var source = Path.Combine(exercise, "source"); + var notes = Path.Combine(source, "owner-notes.txt"); + var process = OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"; + var cli = (string assembly, string[] arguments) => Git.RunProcessAsync(Git.CreateStartInfo(process, root, [assembly, .. arguments]), token); + + await Host(0, "ready", "setup", scenario); + var trunk = await Ref("trunk"); + var initialTip = await Ref("agent/delivery"); + var initialTarget = await Ref("feature/delivery"); + var initialStatus = (await LocalGit(source, "status", "--porcelain")).Output; + var competing = Path.Combine(target, "competing.txt"); + string[] ownerLookup = ["setup\tready", "catalog\tavailable", "guide\tloaded", "locate\tresolved", "status\tobserved"]; + + if (scenario == "shared-target") + Require((await Snapshot(source)).GetProperty("targetState").GetProperty("clean").GetBoolean(), "target is clean during preflight"); + + if (scenario == "already-merged") + { + var data = (await Snapshot(source)).GetProperty("sources")[0]; + Require(data.GetProperty("comparison").GetProperty("sourceInTarget").GetBoolean() + && !data.GetProperty("state").GetProperty("clean").GetBoolean(), "reproduced reachable tip with modified and untracked files"); + Require(Trace().SequenceEqual(["setup\tready"]), "Git-only observation produced no host action"); + await Host(2, "guide-required", "send", owner, request); + } + + await Host(0, scenario == "git-only" ? "no-manager" : "available", "catalog"); + if (scenario == "git-only") + { + await MergeAndValidate(initialTip); + var eligible = await CheckCleanup(initialTip, source); + Require(eligible.Code == 0, eligible.Output + eligible.Error); + await LocalGit(target, "worktree", "remove", "--", source); + var branchEligible = await CheckCleanup(initialTip, "-"); + Require(branchEligible.Code == 0, branchEligible.Output + branchEligible.Error); + await LocalGit(target, "branch", "-d", "--", "agent/delivery"); + var refs = await LocalGit(target, "for-each-ref", "--format=%(refname)", "refs/heads/agent/delivery"); + Require(!Directory.Exists(source) && refs.Output.Length == 0, "eligible manual resource cleanup completes with native Git"); + Require(Trace().SequenceEqual(["setup\tready", "catalog\tno-manager"]), "Git-only branch used evidenced catalog result"); + return; + } + + var guide = await cli(hostApp, ["guide", "owner-session"]); + Require(guide.Code == 0 && guide.Output.Contains("queued request", StringComparison.Ordinal), "operational guide was loaded"); + var found = await Host(0, "resolved", "locate", source); + Require(found.GetProperty("sessionId").GetString() == owner && found.GetProperty("launch").GetString() == "independent", "owner resolves without a supervised task or a child relationship"); + var status = await Host(0, scenario == "unavailable" ? "communication-unsupported" : "observed", "status", owner); + if (scenario is "governance-compatible" or "governance-drift") + { + await VerifyGovernance(); + return; + } + if (scenario == "idle") Require(status.GetProperty("activity").GetString() == "idle" && initialStatus.Length != 0, "idle session has unfinished local work"); + if (scenario is "unavailable" or "failing") + { + if (scenario == "unavailable") Require(!status.GetProperty("canSend").GetBoolean(), "explicit communication unavailability"); + else await Host(3, "transport-error", "send", owner, request); + Require(await Ref("agent/delivery") == initialTip && await Ref("feature/delivery") == initialTarget + && (await LocalGit(source, "status", "--porcelain")).Output == initialStatus && File.Exists(notes), "blocked communication preserves both views of the work"); + string[] blockedTrace = ["setup\tready", "catalog\tavailable", "guide\tloaded", "locate\tresolved", + scenario == "unavailable" ? "status\tcommunication-unsupported" : "status\tobserved"]; + if (scenario == "failing") blockedTrace = [.. blockedTrace, "send\ttransport-error"]; + Require(Outcomes().SequenceEqual(blockedTrace), "unsupported and failed communication produced distinct actual call sequences"); + return; + } + + if (scenario is "authorized" or "approval-missing") + Require(status.GetProperty("commitApprovalRequired").GetBoolean() + && File.ReadAllText(Path.Combine(source, "AGENTS.md")).Contains("explicit approval", StringComparison.Ordinal), "source repository requires scoped commit approval"); + if (scenario == "shared-target") + { + var writer = await Host(0, "target-resolved", "locate", target); + Require(writer.GetProperty("sessionId").GetString() == targetWriter && writer.GetProperty("worktree").GetString() == target, "separate session uses the exact integration checkout"); + var activity = await Host(0, "target-observed", "status", targetWriter); + Require(activity.GetProperty("activity").GetString() == "active", "clean preflight does not imply the sole writer has been established"); + await Host(0, "window-requested", "send", targetWriter, "Please preserve your files in your dedicated implementation worktree and confirm you have paused writes here for my merge."); + await Host(0, "target-busy", "wait", targetWriter); + } + if (scenario == "authorized") await Host(0, "queued-with-approval", "send", owner, request, approval); + else if (scenario == "approval-missing") + await Host(0, "queued", "send", owner, "Validate delivery.txt and prepare a scoped commit plan. Leave staging and commit pending explicit approval."); + else await Host(0, "queued", "send", owner, request); + await Host(0, "working", "wait", owner); + Require(await Ref("agent/delivery") == initialTip && await Ref("feature/delivery") == initialTarget, "queued and working states are not a handoff"); + if (scenario == "approval-missing") + { + var pending = await Host(0, "approval-required", "wait", owner); + Require(pending.GetProperty("readyToCommit").GetBoolean() && pending.GetProperty("ownerValidation").GetBoolean(), "permitted source validation proceeds while commit approval is pending"); + Require(await Ref("agent/delivery") == initialTip && await Ref("feature/delivery") == initialTarget + && (await LocalGit(source, "status", "--porcelain")).Output == initialStatus, "missing approval preserves both refs and source edits"); + Require(Outcomes().SequenceEqual([.. ownerLookup, "send\tqueued", "wait\tworking", "wait\tapproval-required"]), "actual coordination reaches the commit approval blocker"); + return; + } + if (scenario == "shared-target") + { + var dirty = (await Snapshot(source)).GetProperty("targetState"); + Require(!dirty.GetProperty("clean").GetBoolean() && File.Exists(competing) && await Ref("feature/delivery") == initialTarget, "target dirt appeared after clean preflight and blocks mutation"); + } + var handoff = await Host(0, "handoff", "wait", owner); + var handoffBranch = scenario == "mixed-commits" ? "agent/requested-delivery" : "agent/delivery"; + var finalTip = await Ref(handoffBranch); + Require(handoff.GetProperty("tip").GetString() == finalTip && handoff.GetProperty("paused").GetBoolean() + && handoff.GetProperty("ownerValidation").GetBoolean(), "owner handoff matches the fresh Git snapshot"); + if (scenario != "managed") Require(initialTip != finalTip, "fixture owner commits the requested local changes"); + if (scenario == "shared-target") + { + Require(File.Exists(competing) && await Ref("feature/delivery") == initialTarget, "source handoff completed with the target still blocked"); + var lease = await Host(0, "exclusive-window", "wait", targetWriter); + Require(lease.GetProperty("writerPaused").GetBoolean() && lease.GetProperty("worktree").GetString() == target, "native owner confirms the exact target window"); + var fresh = await Snapshot(source); + var checkout = fresh.GetProperty("target"); + var targetState = fresh.GetProperty("targetState"); + Require(checkout.GetProperty("branch").GetString() == "refs/heads/feature/delivery" && checkout.GetProperty("tip").GetString() == initialTarget + && targetState.GetProperty("clean").GetBoolean() && targetState.GetProperty("operations").GetArrayLength() == 0, + "fresh branch, tip, index, working state, and operation checks precede mutation"); + } + if (scenario == "mixed-commits") + { + Require(handoff.GetProperty("ref").GetString() == "refs/heads/agent/requested-delivery" + && handoff.GetProperty("worktree").GetString() == Path.Combine(exercise, "scoped"), "owner hands off a separate scoped branch and checkout"); + Require((await LocalGit(target, "diff", "--name-only", initialTarget, finalTip)).Line == "delivery.txt" + && (await LocalGit(target, "rev-list", "--count", $"{initialTarget}..{finalTip}")).Line == "1", "isolated history contains only the requested delivery"); + } + await MergeAndValidate(finalTip); + if (scenario == "authorized") + { + Require(Trace().Any(line => line == $"authorization\tverified\t{JsonSerializer.Serialize(approval)}"), "exact approval was relayed and verified"); + Require((await LocalGit(source, "diff", "--name-only", initialTip, finalTip)).Line == "delivery.txt" + && (await LocalGit(source, "rev-list", "--count", $"{initialTip}..{finalTip}")).Line == "1", "one scoped local commit matches the grant"); + } + if (scenario == "shared-target") + Require(File.ReadAllText(Path.Combine(exercise, "concurrent", "competing.txt")).Trim() == "work written by the target session" && !File.Exists(competing), "target owner preserved their work in the dedicated checkout"); + if (scenario == "mixed-commits") + { + Require(await Ref("agent/delivery") == initialTip && File.Exists(Path.Combine(source, "other-delivery.txt")) + && !File.Exists(Path.Combine(target, "other-delivery.txt")) && (await LocalGit(source, "status", "--porcelain")).Output.Length == 0, + "separate completed delivery remains intact in the clean original checkout"); + var cleanup = await CheckCleanup(initialTip, source); + Require(cleanup.Code == 1 && cleanup.Output.Contains("source-ancestry-unproven", StringComparison.Ordinal), "scoped merge cannot authorize retiring the original branch"); + } + if (scenario == "mixed") + { + Require(File.ReadAllText(notes).Trim() == "other task" && !File.Exists(Path.Combine(target, "owner-notes.txt")), "successful merge excludes and preserves unrelated changes"); + var cleanup = await CheckCleanup(finalTip, source); + Require(cleanup.Code == 1 && cleanup.Output.Contains("source-state-unverified-or-dirty", StringComparison.Ordinal), "actual Git cleanup gate rejects outstanding unrelated data"); + } + if (scenario is "already-merged" or "idle") + Require(!File.Exists(notes) && File.ReadAllText(Path.Combine(exercise, "owner-notes.txt")).Trim() == "other task", "owner preserves unrelated work outside the delivery checkout"); + if (scenario == "managed") + { + await Host(4, "lease-refused", "retire", workspace); + Require(Directory.Exists(source) && await Ref("agent/delivery") == finalTip, "managed refusal preserves worktree and branch"); + } + if (scenario == "shared-target") ownerLookup = [.. ownerLookup, "locate\ttarget-resolved", "status\ttarget-observed", "send\twindow-requested", "wait\ttarget-busy"]; + string[] send = scenario == "authorized" ? ["authorization\tverified", "send\tqueued-with-approval"] : ["send\tqueued"]; + string[] expected = [.. ownerLookup, .. send, "wait\tworking", "wait\thandoff"]; + if (scenario == "already-merged") expected = [expected[0], "send\tguide-required", .. expected[1..]]; + if (scenario == "managed") expected = [.. expected, "retire\tlease-refused"]; + if (scenario == "shared-target") expected = [.. expected, "wait\texclusive-window"]; + Require(Outcomes().SequenceEqual(expected), "recorded actions follow discovery, coordination, handoff, and eligible cleanup order"); + + async Task VerifyGovernance() + { + var requiresDirect = scenario == "governance-drift"; + var sourcePolicy = File.ReadAllText(Path.Combine(source, "AGENTS.md")); + var targetPolicy = File.ReadAllText(Path.Combine(target, "AGENTS.md")); + var preflight = await Snapshot(source); + var comparison = preflight.GetProperty("sources")[0].GetProperty("comparison"); + Require(sourcePolicy != targetPolicy && (await LocalGit(source, "show", "HEAD:AGENTS.md")).Output == sourcePolicy + && (await LocalGit(target, "show", "HEAD:AGENTS.md")).Output == targetPolicy, "each worktree's effective instructions match its own tracked revision"); + Require(comparison.GetProperty("targetOnly").GetInt32() > 0 && comparison.GetProperty("mergeBases")[0].GetString() == trunk + && preflight.GetProperty("targetState").GetProperty("clean").GetBoolean(), "source predates the target policy update and the target starts clean"); + Require(targetPolicy.Contains("may be relayed unchanged", StringComparison.Ordinal), "target rules accept the scoped relay"); + + string[] decisions; + if (requiresDirect) + { + Require(sourcePolicy.Contains("require direct user approval", StringComparison.Ordinal), "the older source policy requires direct approval"); + var rejection = await Host(3, "approval-rejected", "send", owner, request, approval); + Require(rejection.GetProperty("policyPath").GetString() == "AGENTS.md" && rejection.GetProperty("worktree").GetString() == source + && rejection.GetProperty("ref").GetString() == "refs/heads/agent/delivery" && rejection.GetProperty("path").GetString() == "delivery.txt", + "the owner's rejection identifies the exact checkout and approval needed"); + await Host(0, "direct-approval-required", "wait", owner); + Require(await Ref("agent/delivery") == initialTip && await Ref("feature/delivery") == initialTarget + && (await LocalGit(source, "status", "--porcelain")).Output == initialStatus, "rejected relay leaves both refs and source edits intact"); + await Host(0, "direct-approval-verified", "receipt", owner, "delivery-owner-direct-approval"); + decisions = ["send\tapproval-rejected", "wait\tdirect-approval-required", "receipt\tdirect-approval-verified"]; + } + else + { + Require(sourcePolicy.Contains("may be relayed unchanged", StringComparison.Ordinal), "different policy revisions can still accept the same grant"); + await Host(0, "queued-with-approval", "send", owner, request, approval); + decisions = ["authorization\tverified", "send\tqueued-with-approval"]; + } + + await Host(0, "working", "wait", owner); + var handoff = await Host(0, "handoff", "wait", owner); + var finalTip = await Ref("agent/delivery"); + Require(handoff.GetProperty("tip").GetString() == finalTip && handoff.GetProperty("ownerValidation").GetBoolean() + && handoff.GetProperty("paused").GetBoolean(), "a verified handoff follows the applicable approval channel"); + Require((await LocalGit(source, "diff", "--name-only", initialTip, finalTip)).Line == "delivery.txt", "the source commit excludes governance changes"); + + var fresh = await Snapshot(source); + var current = fresh.GetProperty("target"); + var currentTip = current.GetProperty("tip").GetString()!; + var targetState = fresh.GetProperty("targetState"); + Require(current.GetProperty("branch").GetString() == "refs/heads/feature/delivery" + && targetState.GetProperty("clean").GetBoolean() && targetState.GetProperty("operations").GetArrayLength() == 0 + && (currentTip != initialTarget) == requiresDirect, "target branch, HEAD, worktree and operation state are checked again after coordination"); + await LocalGit(target, "-c", "user.name=Fixture Integrator", "-c", "user.email=integrator@example.invalid", + "merge", "--no-ff", "--no-autostash", "--no-overwrite-ignore", "-m", "integrate scoped delivery", finalTip); + await LocalGit(target, "merge-base", "--is-ancestor", currentTip, "HEAD"); + await LocalGit(target, "merge-base", "--is-ancestor", finalTip, "HEAD"); + Require(File.ReadAllText(Path.Combine(target, "delivery.txt")).Trim() == "final" && await Ref("trunk") == trunk + && File.ReadAllText(Path.Combine(source, "AGENTS.md")) == sourcePolicy && File.ReadAllText(Path.Combine(target, "AGENTS.md")) == targetPolicy, + "validated merge preserves both worktrees' governance and the default branch"); + Require(!requiresDirect || File.ReadAllText(Path.Combine(target, "target-progress.txt")).Trim() == "separate target change during coordination", + "integration preserves target progress made while waiting for direct approval"); + Require(Outcomes().SequenceEqual([.. ownerLookup, .. decisions, "wait\tworking", "wait\thandoff"]), "actual action trace shows one relay and no unauthorized synchronization or resend"); + } + + async Task Host(int exit, string outcome, params string[] arguments) + { + var result = await cli(hostApp, arguments); + Require(result.Code == exit, $"{arguments[0]} returned {result.Code}: {result.Output} {result.Error}"); + using var json = JsonDocument.Parse(result.Output); + Require(json.RootElement.GetProperty("outcome").GetString() == outcome, result.Output); + return json.RootElement.Clone(); + } + + async Task LocalGit(string directory, params string[] arguments) => await Git.RunAsync(directory, token, arguments, + environment: new Dictionary { ["GIT_CONFIG_NOSYSTEM"] = "1", ["GIT_CONFIG_GLOBAL"] = Path.Combine(exercise, "gitconfig"), ["GIT_CONFIG_COUNT"] = "0" }); + + async Task Ref(string branch) => (await LocalGit(target, "rev-parse", "--verify", $"refs/heads/{branch}")).Line; + + async Task Snapshot(string checkout) + { + var result = await cli(verifier, ["inspect", target, checkout, "--quiet"]); + Require(result.Code == 0, result.Output + result.Error); + using var document = JsonDocument.Parse(result.Output); + return document.RootElement.Clone(); + } + + async Task CheckCleanup(string tip, string path) => await cli(verifier, + ["cleanup-check", target, "refs/heads/feature/delivery", await Ref("feature/delivery"), "refs/heads/agent/delivery", tip, path, "refs/heads/trunk", "--quiet"]); + + async Task MergeAndValidate(string tip) + { + await LocalGit(target, "merge", "--ff-only", "--no-autostash", "--no-overwrite-ignore", tip); + Require(await Ref("feature/delivery") == tip && await Ref("trunk") == trunk + && File.ReadAllText(Path.Combine(target, "delivery.txt")).Trim() == "final", "final pinned commit passes target acceptance with default branch preserved"); + } + + string[] Trace() => File.ReadAllLines(Path.Combine(exercise, "actions.tsv")); + IEnumerable Outcomes() => Trace().Select(line => string.Join('\t', line.Split('\t').Take(2))); +} + +static void Require(bool condition, string evidence) +{ + if (!condition) throw new InvalidOperationException(evidence); +} + +void Log(string kind, string message) => Console.Error.WriteLine(FormattableString.Invariant($"[{kind}] +{clock.Elapsed.TotalSeconds:F2}s {message}")); diff --git a/scripts/validate-dotnet-csrun.ps1 b/scripts/validate-dotnet-csrun.ps1 index 4c6cbc57..fdc5309d 100644 --- a/scripts/validate-dotnet-csrun.ps1 +++ b/scripts/validate-dotnet-csrun.ps1 @@ -1,4 +1,4 @@ -#requires -Version 7.0 +#requires -Version 7.0 [CmdletBinding()] param( [string] $EnginePath, @@ -8,15 +8,32 @@ $ErrorActionPreference = 'Stop' Set-StrictMode -Version Latest if ($EnginePath -and $Docker) { throw 'Choose native EnginePath or Docker.' } $root = Join-Path $PSScriptRoot '../skills/dotnet-csrun' -. (Join-Path $PSScriptRoot 'file-based-app.ps1') -$app = Get-FileBasedAppCommand -SourcePath (Join-Path $root 'scripts/validate.cs') -& $app.Executable @($app.ArgumentPrefix + @($root)) -if ($LASTEXITCODE -ne 0) { throw 'Skill artifact validation failed.' } -& pwsh -NoProfile -NonInteractive -File (Join-Path $root 'scripts/test-sample-tools.ps1') -if ($LASTEXITCODE -ne 0) { throw 'Sample artifact helper regressions failed.' } +# The csrun regressions are xUnit tests in the repository tooling solution: the deterministic artifact logic runs in-process, +# and the command lines of sample-tools.cs and validate.cs (including validation of this skill tree) run as built black boxes. +Push-Location (Join-Path $PSScriptRoot '../tooling') +try { + & dotnet test --project test/Agentic.Tooling.Tests --configuration Release -- --filter-class '*.Csrun*' + if ($LASTEXITCODE -ne 0) { throw 'dotnet-csrun regression tests failed.' } +} finally { + Pop-Location +} if (-not $EnginePath -and -not $Docker) { return } +. (Join-Path $PSScriptRoot 'file-based-app.ps1') +$sampleToolsApp = Get-FileBasedAppCommand -SourcePath (Join-Path $root 'scripts/sample-tools.cs') if ($EnginePath) { $EnginePath = (Resolve-Path $EnginePath).Path } -. (Join-Path $root 'scripts/sample-tools.ps1') +function Invoke-SampleTools([string[]] $Arguments) { + $out = & $sampleToolsApp.Executable @($sampleToolsApp.ArgumentPrefix + $Arguments) + if ($LASTEXITCODE -ne 0) { throw "sample-tools $($Arguments[0]) failed with exit code $LASTEXITCODE." } + return ($out -join "`n") +} +function New-CsrunExecutionPair([string] $ManifestJson, [string] $Image, [string] $EnginePath) { + $argsList = @('pair', '--manifest-json', $ManifestJson, '--image', $Image, '--quiet', '--no-heartbeat') + if ($EnginePath) { $argsList += @('--engine-path', $EnginePath) } + return (Invoke-SampleTools $argsList) | ConvertFrom-Json +} +function Set-CsrunSourceRegion([string] $Path, [int] $Start, [string] $ExpectedSource, [string] $ReplacementSource) { + $null = Invoke-SampleTools @('replace-region', '--path', $Path, '--start', [string]$Start, '--expected-source', $ExpectedSource, '--replacement-source', $ReplacementSource, '--quiet', '--no-heartbeat') +} $evidence = Join-Path ([IO.Path]::GetTempPath()) ('dotnet-csrun-evidence-' + [guid]::NewGuid().ToString('N')) New-Item -ItemType Directory $evidence | Out-Null $OutputEncoding = [Text.UTF8Encoding]::new($false) diff --git a/scripts/validate-local.ps1 b/scripts/validate-local.ps1 index ca04a59c..52c5c119 100644 --- a/scripts/validate-local.ps1 +++ b/scripts/validate-local.ps1 @@ -4,56 +4,40 @@ Runs the complete deterministic validation matrix locally, in parallel. .DESCRIPTION - The CI workflow (.github/workflows/validate-skill-templates.yml) is the coverage source of - truth: every `{ name, script, suite }` entry is one independently scheduled suite. This script - runs exactly those suites as separate processes, so local execution and CI cover the same - checks, and it keeps a bounded number of them in flight at once. + Transitional entry point. The scheduler is implemented in .NET as `agentic-tooling validate-local` + (tooling/src/Agentic.Tooling/Validation); this script only forwards its established parameters to it, + so existing callers keep working until they move to the .NET command directly. - Improvements over running the suites by hand: - - * Coverage parity with CI is derived from the workflow, never from a hand-kept list. - * Each suite is a separate process, so a crash or hang cannot take the run down with it. - * Per-suite timeouts kill the whole process tree; a timeout is a failure, never a pass. - * A failing suite does not stop the others, so one run reports every problem at once. - * Each suite's output is streamed to its own log for post-mortem inspection. - * Every suite must produce its terminal success marker. A suite that exits 0 while silently - skipping its checks is reported as a failure instead of a pass. - * Ctrl+C cancels the run, tears down every child process tree, and still writes the summary. - - A pass therefore means: every CI-matrix suite ran to completion, exited 0, reported no failing - check, and printed its terminal success marker. + The CI workflow (.github/workflows/validate-skill-templates.yml) is the coverage source of truth: every + `{ name, script, suite }` entry is one suite, run as its own process with bounded concurrency, a per-suite + timeout that kills the whole process tree, terminal-marker verification, a per-suite log, and an atomic + summary.json (schema codebeltnet/agentic/local-validation/1). Progress and heartbeats go to stderr and to + /progress.json; stdout receives the summary path. Exit 0 only when every suite passed verified. .PARAMETER MaxConcurrency Maximum number of suites executing at the same time. Defaults to the processor count. .PARAMETER TimeoutSeconds - Per-suite wall-clock budget. A suite that exceeds it has its process tree killed and is - reported as TIMEOUT. Use 0 to disable. + Per-suite wall-clock budget. Use 0 to disable. .PARAMETER DeadlineSeconds - Wall-clock budget for the entire run. Suites that have not finished are killed and reported, - and the run fails. Use 0 to disable. + Wall-clock budget for the entire run. Use 0 to disable. .PARAMETER OutputRoot - Directory that receives one log per suite plus summary.json. Defaults to - /.bot/validation-workspace. Paths inside the repository must stay under `.bot/`. + Directory that receives the logs, summary.json and progress.json. Defaults to /.bot/validation-workspace. + Paths inside the repository must stay under `.bot/`. .PARAMETER WorkflowPath - Workflow file that defines the suite matrix. Defaults to the repository CI workflow. This - exists so the scheduler can be exercised deterministically against fixture workflows. + Workflow file that defines the suite matrix. Defaults to the repository CI workflow. .PARAMETER RepositoryRoot - Repository root the matrix script paths are resolved against. Defaults to the parent of the - script directory. + Repository root the matrix script paths are resolved against. Defaults to the parent of the script directory. .PARAMETER ListSuites Print the resolved suite matrix and exit without running anything. .EXAMPLE pwsh -NoProfile -File ./scripts/validate-local.ps1 - -.EXAMPLE - pwsh -NoProfile -File ./scripts/validate-local.ps1 -MaxConcurrency 24 -TimeoutSeconds 900 #> [CmdletBinding()] param( @@ -67,410 +51,20 @@ param( ) $ErrorActionPreference = 'Stop' -Set-StrictMode -Version Latest - -$utf8NoBom = [System.Text.UTF8Encoding]::new($false) - -# Terminal markers that prove a suite executed its checks instead of exiting early. These are the -# public summary lines each scheduled script already prints; they are asserted on top of the exit -# code so that a no-op or partially skipped suite can never be reported as a pass. -$suiteExpectations = @{ - 'scripts/validate-skill-templates.ps1' = @( - [pscustomobject]@{ Pattern = '(?m)^Failed: 0\s*$'; Description = "reports 'Failed: 0'" } - [pscustomobject]@{ Pattern = '(?m)^Passed: [1-9][0-9]*\s*$'; Description = 'reports at least one passing check' } - ) - 'scripts/eval-runners/tests/test-runner-conformance.ps1' = @( - [pscustomobject]@{ Pattern = '(?m)conformance( \([A-Za-z]+\))?: PASS\s*$'; Description = 'reports conformance PASS' } - ) - 'scripts/eval-runners/tests/test-integrity-finalization.ps1' = @( - [pscustomobject]@{ Pattern = '(?m)Eval package integrity and finalization: PASS \([A-Za-z]+\)\s*$'; Description = 'reports integrity PASS' } - ) -} - -$failureMarkerPattern = '(?m)^\[FAIL\]|:\s*FAIL\s*$|^Failed: [1-9][0-9]*\s*$' - -function Get-RepoRoot { - if (-not [string]::IsNullOrWhiteSpace($RepositoryRoot)) { - return ([System.IO.Path]::GetFullPath($RepositoryRoot)).TrimEnd('\', '/') - } - - return (Resolve-Path (Join-Path $PSScriptRoot '..')).Path.TrimEnd('\', '/') -} - -function Get-SuiteMatrix { - param([string]$Path) - - if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { - throw "Validation workflow was not found at '$Path'." - } - - $workflow = [System.IO.File]::ReadAllText($Path) - $entries = @([regex]::Matches($workflow, '\{ name: (?[\w-]+), script: (?