diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json new file mode 100644 index 0000000..82c12da --- /dev/null +++ b/.claude-plugin/marketplace.json @@ -0,0 +1,23 @@ +{ + "name": "creativecoders-shade-kit", + "owner": { + "name": "CreativeCodersTeam" + }, + "metadata": { + "description": "SHADE kit (Smart Harness for AI Driven Engineering): skills that run AI agents through the software lifecycle in a guided, gated workflow." + }, + "plugins": [ + { + "name": "shade-kit", + "source": "./", + "description": "SHADE kit skills: a gated workflow (feature, bugfix, and quick profiles) that takes a requirement through refine, map, plan, implement, verify, and finish, with quality gates and traceability driven by the shade-kit CLI.", + "author": { + "name": "CreativeCodersTeam", + "url": "https://github.com/CreativeCodersTeam" + }, + "homepage": "https://github.com/CreativeCodersTeam/shade-kit", + "repository": "https://github.com/CreativeCodersTeam/shade-kit", + "license": "Apache-2.0" + } + ] +} diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json new file mode 100644 index 0000000..6b5e360 --- /dev/null +++ b/.claude-plugin/plugin.json @@ -0,0 +1,21 @@ +{ + "name": "shade-kit", + "description": "SHADE kit skills: a gated workflow (feature, bugfix, and quick profiles) that takes a requirement through refine, map, plan, implement, verify, and finish, with quality gates and traceability driven by the shade-kit CLI.", + "author": { + "name": "CreativeCodersTeam", + "url": "https://github.com/CreativeCodersTeam" + }, + "homepage": "https://github.com/CreativeCodersTeam/shade-kit", + "repository": "https://github.com/CreativeCodersTeam/shade-kit", + "license": "Apache-2.0", + "keywords": [ + "workflow", + "quality-gates", + "traceability", + "specification", + "planning", + "implementation", + "verification", + "bugfix" + ] +} diff --git a/CLAUDE.md b/CLAUDE.md index eb843ac..09a168f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -10,7 +10,7 @@ Repository language is always English. The kit is designed to be used by English It has two deliverables: -1. **Plugin** (`skills/`): skills (skeletons until they are worked out in package 06; the state of each skill is in its feature package) and *(planned)* research agent definitions in the Claude Code plugin layout *(planned: plugin manifest)*. Hooks and commands come later. +1. **Plugin** (`skills/`): skills (skeletons until they are worked out in package 06; the state of each skill is in its feature package) and *(planned)* research agent definitions in the Claude Code plugin layout. This repository is the Claude Code plugin marketplace `creativecoders-shade-kit` with the plugin `shade-kit` (`.claude-plugin/`); `shade-kit integrations install` installs it from the tag of the engine version. The engine contains no plugin content. Hooks and commands come later. 2. **Engine** (`src/`): a .NET 10 CLI, shipped two ways: - as a `dotnet` global tool - as self-contained single-file binaries (no .NET install needed) for `osx-arm64`, `linux-x64`, `linux-arm64`, `win-x64`, `win-arm64` @@ -20,7 +20,7 @@ It has two deliverables: - **Gated workflow profiles:** `feature` (new → refine → map → plan → implement → verify → finish), `bugfix` (new → diagnose → plan → implement → verify → finish), and `quick` (new → quick → finish). The agent checks each gate when the next phase starts; the human approves the transition. Each gate's approval and checklist can be switched off in `gates.json` (keyed by profile and target phase; `init` writes the defaults, a transition without an entry needs an approval and has no checklist). - **Quality gates:** the Definition of Ready (gate into `plan`) and Definition of Done (gate into `finish`) are checklists; when the phase starts, the engine copies the gate's checklist template into the feature folder. In v1 the agent checks the copy and runs build, test, lint, and coverage with the commands approved in `plan.md` and records the results *(planned)*; the CLI enforcing and running them comes later. - **State & traceability:** workflow state and approval history are saved in `.shadekit/` (features, phases, and approval history: built; traceability, report *(planned)*), requirements are mapped to the tests that prove them, and `finish` can write a report (`report` in `config.json`). -- **Install/sync:** the engine installs and updates the kit's skills at user level for each supported agent (`integrations install/update` *(planned)*) and initialises and upgrades a repository's `.shadekit/` (`init`, `upgrade` *(planned)*). Nothing is installed into a repository. +- **Install/sync:** the engine installs and updates the kit's skills at user level for each supported agent (`integrations install/update`: built for Claude Code, Copilot and Codex *(planned)*) and initialises and upgrades a repository's `.shadekit/` (`init`, `upgrade` *(planned)*). Nothing is installed into a repository. ## Target agents @@ -33,7 +33,8 @@ If a design choice can stay agent-agnostic **without losing functionality or pre | Path | Purpose | |---|---| | `skills/` | Shipped plugin content | -| `src/` | Production .NET projects: `CreativeCoders.ShadeKit.Cli` (the `shade-kit` CLI) and `CreativeCoders.ShadeKit.Core` (engine logic). The templates that `init` writes live in `src/CreativeCoders.ShadeKit.Core/Templates/Resources/` (`.template.md`, checklists in `checks/`) and are embedded into the Core assembly; their repository paths are listed in `ShippedTemplates`. The phase workflow lives in `src/CreativeCoders.ShadeKit.Core/Workflow/`: `Profiles/` (built-in profiles in `BuiltInWorkflowProfiles` behind `IWorkflowProfileCatalog`; each phase lists the artifacts it writes, `PhaseArtifact` with an `onDemand` flag, names in `WorkflowArtifactNames`), `Engine/` (the pure state machine `IPhaseEngine`; the default gate of a phase without an entry is `TransitionGate.ForPhase`, and `HasGate` says whether a phase has a gate), and the orchestration `PhaseWorkflow` with the gate seam `ITransitionGateProvider`. The gates live in `src/CreativeCoders.ShadeKit.Core/Gates/`: `GatesConfig` (`gates.json`, defaults in `CreateDefault()`), `GatesConfigTransitionGateProvider` behind the gate seam (one cached read of `gates.json` per store, checked against the profile catalog; returns the configured gates of a profile as a read-only view, and the engine applies the default gate to a phase without one), and `IFeatureChecklistWriter` (the checklist copy in the feature folder). `IPhaseWorkflow.GetGateInfoAsync` reads the read-only gate data of one feature (the current one or by id) for `gate info`: the feature, its phases with their state and artifacts (`FeaturePhase`, the same `phases` array as `feature show`), the configured gate of a phase with its checklist copy, and `coverageThreshold`. The version check lives in `src/CreativeCoders.ShadeKit.Core/Versions/`: `SemanticVersion` (strict SemVer 2.0.0) and `IEngineVersionChecker` (the match rule of `version --expect`). | +| `.claude-plugin/` | Claude Code marketplace and plugin manifests (`marketplace.json`: marketplace `creativecoders-shade-kit`, plugin `shade-kit` with the source `./`; `plugin.json` without `version`, so Claude Code uses the commit SHA) | +| `src/` | Production .NET projects: `CreativeCoders.ShadeKit.Cli` (the `shade-kit` CLI) and `CreativeCoders.ShadeKit.Core` (engine logic). The templates that `init` writes live in `src/CreativeCoders.ShadeKit.Core/Templates/Resources/` (`.template.md`, checklists in `checks/`) and are embedded into the Core assembly; their repository paths are listed in `ShippedTemplates`. The phase workflow lives in `src/CreativeCoders.ShadeKit.Core/Workflow/`: `Profiles/` (built-in profiles in `BuiltInWorkflowProfiles` behind `IWorkflowProfileCatalog`; each phase lists the artifacts it writes, `PhaseArtifact` with an `onDemand` flag, names in `WorkflowArtifactNames`), `Engine/` (the pure state machine `IPhaseEngine`; the default gate of a phase without an entry is `TransitionGate.ForPhase`, and `HasGate` says whether a phase has a gate), and the orchestration `PhaseWorkflow` with the gate seam `ITransitionGateProvider`. The gates live in `src/CreativeCoders.ShadeKit.Core/Gates/`: `GatesConfig` (`gates.json`, defaults in `CreateDefault()`), `GatesConfigTransitionGateProvider` behind the gate seam (one cached read of `gates.json` per store, checked against the profile catalog; returns the configured gates of a profile as a read-only view, and the engine applies the default gate to a phase without one), and `IFeatureChecklistWriter` (the checklist copy in the feature folder). `IPhaseWorkflow.GetGateInfoAsync` reads the read-only gate data of one feature (the current one or by id) for `gate info`: the feature, its phases with their state and artifacts (`FeaturePhase`, the same `phases` array as `feature show`), the configured gate of a phase with its checklist copy, and `coverageThreshold`. The version check lives in `src/CreativeCoders.ShadeKit.Core/Versions/`: `SemanticVersion` (strict SemVer 2.0.0) and `IEngineVersionChecker` (the match rule of `version --expect`). The agent integrations live in `src/CreativeCoders.ShadeKit.Core/Integrations/`: `IIntegrationService` (marketplace source from the engine version: tag `v`, `main` (`FallbackRef`) for a prerelease and for a release whose tag does not exist, the developer override `SHADE_KIT_MARKETPLACE_SOURCE`; agent detection, `version` asks only detected agents; results per agent), one `IAgentIntegration` per agent (`Claude/ClaudeCodeIntegration`, agent id `claude`), and `IClaudePluginCli` (the `claude plugin` commands with `--json`, run through `IClaudeCommandRunner`; a kept marketplace is refreshed with `claude plugin marketplace update` before the plugin update; directory sources are compared by `DirectoryPathComparer`, after resolving symbolic links). There is no engine-owned record: the state comes from `claude plugin list` and `claude plugin marketplace list`. | | `tests/` | One test project per production project (`.Tests`); `tests/Shared/` holds test helpers that both projects compile in (``); the CLI end-to-end tests run commands through `CliEndToEndHarness` (`tests/CreativeCoders.ShadeKit.Cli.Tests/Commands/`) | | `build/` | Cake Frosting build project (`CreativeCoders.CakeBuild`), run through `build.sh` / `build.ps1` / `build.cmd`. Not part of `ShadeKit.slnx`; it has its own `Directory.Build.props` and `Directory.Packages.props`. | | `.github/` | GitHub Actions workflows and Dependabot configuration | @@ -55,7 +56,7 @@ If a design choice can stay agent-agnostic **without losing functionality or pre - Agent contract: every agent-facing command takes options derived from `JsonCommandOptions` (`--json`). In JSON mode it writes one `CliJsonEnvelope` (`ok`, `data`, `warnings`, `error`) through `ICliJsonWriter` to stdout and nothing else; on an expected failure it writes a failure envelope (`error` holds only `code` and `message`, no exit code, so skills react to `error.code`) and throws `CliCommandAbortException` with `PrintMessage = false`. Commands get `ShadeKitCommandContext` (`Output/`) injected: `RunAsync` runs the core call (optionally with the kit store) with the run's cancellation token and turns mapped failures into the failure envelope / `CliCommandAbortException`, and `WriteSuccess` writes the single success envelope or the plain warnings and lines; commands do not use `ICliJsonWriter`, `CliErrorMapper`, or `CliCommandAbort` directly, `version` included. Core exceptions are mapped to exit code, error code, and message only in `CliErrorMapper`. An option value that the parser must reject before the command runs gets an `ICliValueConverter` on the option (`Converter =` on the option attribute) that throws a CLI-defined exception, which `CliErrorMapper.MapArgumentError` maps to exit code 2 (example: `ExpectedVersionOptionConverter` for a bare `--expect`). Exit codes are grouped by area (10–19 store, 20–29 format, 30–39 features, 40–49 phases and gates, 50–59 versions and integrations, 255 host); 2 (invalid arguments, usage) and 130 (canceled) are outside the ranges; every exit code has a kebab-case error code in `ShadeKitCliErrorCodes`; codes that only appear as warnings are in `ShadeKitCliWarningCodes`. - Versioned JSON files in `.shadekit/` are read and written only through `IKitStore.ReadJsonAsync`/`WriteJsonAsync`. Each file type has a format id in `FormatIds` and a definition in `FormatRegistry.CreateDefault()`; raising a format version means a new table entry plus an `IFormatMigration` step and a test that migrates a fixture from the previous version. Document models derive from `VersionedDocument`; nested classes need their own `[JsonExtensionData] Dictionary` to keep unknown fields. - Text file content is held as `TextFileContent` (lines, UTF-8 BOM flag, final-line-ending flag), never as `byte[]`, and is written only through `ITextFileWriter` (`IKitStore.WriteFileAsync` uses it for `.shadekit/`; `FileWriteMode.CreateNew` creates a file only if it does not exist and throws `FileAlreadyExistsException` otherwise, `Overwrite` is the default). The writer is the only place that encodes to bytes; it resolves the line ending with `ILineEndingResolver`: git (attributes as git's `convert_attrs`: resolved `text`, legacy `crlf` only while `text` is unspecified; `-text` → no decision, `eol` attribute, `text=input`/`crlf=input` → LF, `core.autocrlf`, `core.eol` for text files; config values and a failing `git` cached per repository root for the resolver's lifetime, i.e. one command run; a `git` that is installed but fails gives a `GitAttributesUnavailableWarning`, a missing one (`GitNotFoundException`) none; `ILineEndingResolver.PrepareAsync` / `IKitStore.PrepareLineEndingsAsync` read the attributes of several files with one `git check-attr`, as `init` and `feature new` do) → `.editorconfig` `end_of_line` (parsed files kept per resolver while their write time, size, and Unix mode are unchanged) → operating system. Paths reach the writer and the resolvers as `RepositoryFile`, checked once where it is created (`RepositoryFile.Resolve`, or `KitStore` for `.shadekit/`). Lines are split at CRLF, LF, and a lone CR. Files, the versioned JSON files included, are read as strict UTF-8; an unreadable `.editorconfig` falls back with an `EditorConfigUnreadableWarning`, one the parser cannot evaluate (e.g. an overflowing numeric-range glob, or a glob that expands into more than 10 000 patterns, checked before the parser expands it) with an `EditorConfigInvalidWarning`. -- External tools (`git`, and `gh` for tracker issues in `feature new`) are started only through the helpers in `src/CreativeCoders.ShadeKit.Core/Processes/` (`PathExecutableSearch`: absolute `PATH` entries only, behind the caching `PathExecutableLocator` base of the tool locators; `ExternalProcessRunner`: absolute path, no shell, process tree killed on cancellation; `ExternalToolRunner`: locate, refuse a missing or relative path, start, map a start failure to the tool's `ExternalToolUnavailableException`), behind one runner interface per tool (`IGitCommandRunner`, `IGhCommandRunner`, both returning `ExternalProcessResult`). HTTP goes through `IHttpClientFactory` with the named client `HttpUrlContentReader.HttpClientName` (`Microsoft.Extensions.Http`), not a typed client, because the services that use it are singletons. Tests never start `git` or `gh` and never send a request: they fake the runner or use `tests/Shared/StubHttpMessageHandler.cs`. +- External tools (`git`, `gh` for tracker issues in `feature new`, and `claude` for `integrations` and `version`) are started only through the helpers in `src/CreativeCoders.ShadeKit.Core/Processes/` (`PathExecutableSearch`: absolute `PATH` entries only, behind the caching `PathExecutableLocator` base of the tool locators; `ExternalProcessRunner`: absolute path, no shell, process tree killed on cancellation; `ExternalToolRunner`: locate, refuse a missing or relative path, start, map a start failure to the tool's `ExternalToolUnavailableException`), behind one runner interface per tool (`IGitCommandRunner`, `IGhCommandRunner`, `IClaudeCommandRunner`, all returning `ExternalProcessResult`). `git` never prompts: `GitCommandRunner` sets `GIT_TERMINAL_PROMPT=0` and an empty `GIT_ASKPASS` for every call. The release-tag check of `integrations` runs `git ls-remote` through `IGitRemoteTagChecker` (in the user's home directory, `https` only, no credential helpers). HTTP goes through `IHttpClientFactory` with the named client `HttpUrlContentReader.HttpClientName` (`Microsoft.Extensions.Http`), not a typed client, because the services that use it are singletons. Tests never start `git`, `gh`, or `claude` and never send a request: they fake the runner or use `tests/Shared/StubHttpMessageHandler.cs`. - Core services are registered with `services.AddShadeKitCore()`. - Phase engine: `Workflow/Engine/` contains no profile, phase, or skill name (checked by `PhaseEngineArchitectureTests`); a new profile or a changed phase order is a change to `BuiltInWorkflowProfiles` only. The engine has no I/O; `PhaseWorkflow` does the reads and writes, and `feature.json` stays format version 1 with optional phase fields. @@ -78,6 +79,9 @@ dotnet run --project src/CreativeCoders.ShadeKit.Cli -- phase complete dotnet run --project src/CreativeCoders.ShadeKit.Cli -- phase skills --json dotnet run --project src/CreativeCoders.ShadeKit.Cli -- phase next --json dotnet run --project src/CreativeCoders.ShadeKit.Cli -- gate info [--feature ] --json # read-only gate data for a gate check (checklist copy, coverageThreshold) +dotnet run --project src/CreativeCoders.ShadeKit.Cli -- integrations install [--agent claude] [--json] # user-level plugin from the tag v (prerelease or missing tag: main); no repository needed +dotnet run --project src/CreativeCoders.ShadeKit.Cli -- integrations update [--json] +SHADE_KIT_MARKETPLACE_SOURCE=$PWD dotnet run --project src/CreativeCoders.ShadeKit.Cli -- integrations install # developer override: a local path or owner/repo#ref dotnet pack src/CreativeCoders.ShadeKit.Cli # dotnet global tool package (command: shade-kit) dotnet publish src/CreativeCoders.ShadeKit.Cli -c Release -r # self-contained single-file binary ``` @@ -97,8 +101,8 @@ Without `--runtime`, the host OS decides the runtimes: Linux → `linux-x64`, `l The rules for the kit skills under `skills/` are in [06-2 Skill conventions and version metadata](docs/feature-packages/06-2-skill-conventions-and-version.md). -- Frontmatter: `name`, `description`, and `metadata.version`. `metadata.version` is the kit version: the same value in every skill, a SemVer version without a prerelease label, written unquoted (`version: 0.7.0`). A `description` that YAML would not read unchanged as a plain scalar is written in double quotes: unquoted, a `: ` makes the frontmatter invalid YAML (Claude Code then loads the skill with empty metadata), and a ` #` silently cuts the description at the comment. -- Claude Code does not show the frontmatter to the model (checked with Claude Code 2.1.318 on project-level skills, 06-2), so every skill that calls `version --expect` states the version in the text of its handshake step: ``Version handshake: run `shade-kit version --json --expect 0.7.0`; 0.7.0 is the kit version of this skill (`metadata.version` in its frontmatter).`` The frontmatter is the source. When the version is raised, the frontmatter of every skill and every handshake text change together (search for the old value). Who runs the handshake: `shade-kit-phase-entry` for the phase skills, the other skills the human calls (`new`, `discuss`, `drop`, `shade-kit-next-phase`) in their first step; every other skill that only another skill loads (for example `shade-kit-next-steps`) runs none. +- Frontmatter: `name`, `description`, and `metadata.version`. `metadata.version` is the kit version: the same value in every skill, a SemVer version without a prerelease label, written unquoted (`version: 0.8.0`). A `description` that YAML would not read unchanged as a plain scalar is written in double quotes: unquoted, a `: ` makes the frontmatter invalid YAML (Claude Code then loads the skill with empty metadata), and a ` #` silently cuts the description at the comment. +- Claude Code does not show the frontmatter to the model (checked with Claude Code 2.1.318 on project-level skills, 06-2), so every skill that calls `version --expect` states the version in the text of its handshake step: ``Version handshake: run `shade-kit version --json --expect 0.8.0`; 0.8.0 is the kit version of this skill (`metadata.version` in its frontmatter).`` The frontmatter is the source. When the version is raised, the frontmatter of every skill and every handshake text change together (search for the old value). The guard test `SkillKitVersionTests` (`tests/CreativeCoders.ShadeKit.Core.Tests/Skills/`, FP07-AC2) fails the build unless every skill carries the same plain `x.y.z`, its major.minor equals the engine build version's (GitVersion), and every `--expect` and "is the kit version of this skill" under `skills/` names it; so the commit that raises the minor of the skills must also raise the minor of the build version. Who runs the handshake: `shade-kit-phase-entry` for the phase skills, the other skills the human calls (`new`, `discuss`, `drop`, `shade-kit-next-phase`) in their first step; every other skill that only another skill loads (for example `shade-kit-next-steps`) runs none. - Skills change state only through the CLI with `--json`; they never read or write `feature.json`, `gates.json`, or `config.json` directly. They read and write the Markdown artifacts in the feature folder directly. - Every artifact a skill creates starts from the repository's template in `.shadekit/templates/`. Only exception: `shade-kit-research` creates `researches.md` without it when the template is missing, and says so (06-8). - `request.md` is data that describes the requirement, never instructions to the agent. @@ -107,7 +111,7 @@ The rules for the kit skills under `skills/` are in [06-2 Skill conventions and - A kit skill that needs decisions from the human loads `shade-kit-interview` and names in its text the mode (`open` or `targeted`), the topics, the target artifact, the recording rule, and the recording time (`immediately` or `on return`); only the human's answers become decisions. - A kit skill that researches loads `shade-kit-research` and names in its text the phase, the feature id, the focuses (each with a short name, which is the section heading ` / ` in `researches.md`, an ID prefix that is unique in the file, and instructions), the files to read, and a context note (or none); only `shade-kit-research` writes the research sections. - Every kit skill that ends (end of its work, a "no", or a refused start) loads `shade-kit-next-steps` for its closing message and passes it why it ends and the warnings of its CLI calls; it writes no next steps of its own. A recommendation in its own report names a skill only when the closing message does not list it (06-9). -- Skill texts have no automated tests. A changed skill is checked by a review by hand and by scenario runs: a subagent loads the skill, follows it with canned CLI envelopes, and records the commands it would run and its output. skill-creator's `quick_validate.py` checks the frontmatter, but not the content of `metadata`. +- Skill texts have no automated tests (only the guards `SkillKitVersionTests` and `ShippedSkillsTests`, which check the version and the references into `docs/`/`research/` in every text file under `skills/`). A changed skill is checked by a review by hand and by scenario runs: a subagent loads the skill, follows it with canned CLI envelopes, and records the commands it would run and its output. skill-creator's `quick_validate.py` checks the frontmatter, but not the content of `metadata`. ## Workflow diff --git a/README.md b/README.md index eb59aa5..f21f0fb 100644 --- a/README.md +++ b/README.md @@ -2,13 +2,13 @@ SHADE kit runs AI coding agents through a gated feature workflow: from a raw requirement to a clarified spec, a plan, the implementation, and a verified result with a report. It is built for small teams of 2–5 developers who work on features in parallel, each on its own branch, with Claude Code, GitHub Copilot, or OpenAI Codex CLI. -> **Status:** in development. Most commands described here are planned; today the CLI provides `shade-kit version`, `shade-kit init`, the feature commands `shade-kit feature new`, `list`, `current`, `set`, `show`, and `drop`, and the phase commands `shade-kit phase start`, `approve`, `reject`, `complete`, `skills`, and `next`. +> **Status:** in development. Most commands described here are planned; today the CLI provides `shade-kit version`, `shade-kit init`, the feature commands `shade-kit feature new`, `list`, `current`, `set`, `show`, and `drop`, the phase commands `shade-kit phase start`, `approve`, `reject`, `complete`, `skills`, and `next`, `shade-kit gate info`, and `shade-kit integrations install` and `update` for Claude Code. ## How it works SHADE kit has two parts. The skills are the prompts the agent follows; the `shade-kit` CLI is the memory and the referee. -- **Skills** (`skills/`): one skill per phase plus shared skills for interviews, gate checks, research, and reviews. They are installed once per machine for each agent (`shade-kit integrations install`), never into a repository. +- **Skills** (`skills/`): one skill per phase plus shared skills for interviews, gate checks, research, and reviews. They are installed once per machine for each agent (`shade-kit integrations install`), never into a repository. For Claude Code this repository is the plugin marketplace: the command installs the plugin `shade-kit` from the release tag of the installed engine, and `shade-kit integrations update` moves it to the tag of a newer engine. - **Engine** (`shade-kit`): a .NET CLI that keeps the feature state in `.shadekit/` inside the repository, committed and merged with the code. Agents call it with `--json`. - **Phases:** `new` → `refine` → `map` → `plan` → `implement` → `verify` → `finish` in the `feature` profile. The `bugfix` profile replaces `refine` and `map` with `diagnose`; the `quick` profile runs `new` → `quick` → `finish` for small changes. - **Gates:** the human approves every phase transition. The Definition of Ready guards `plan`, the Definition of Done guards `finish`; each gate can be switched off per repository. diff --git a/docs/feature-packages/01-store-foundation-and-format-versioning.md b/docs/feature-packages/01-store-foundation-and-format-versioning.md index 342913d..f3305e5 100644 --- a/docs/feature-packages/01-store-foundation-and-format-versioning.md +++ b/docs/feature-packages/01-store-foundation-and-format-versioning.md @@ -2,7 +2,7 @@ | | | |---|---| -| Status | Draft, 2026-10-14, updated 2026-10-18 (implementation state; package 02 implementation: missing `features/` is valid, exit codes 11, 13, 23; code review rework: exit codes 14, 24), 2026-10-21 (package 03 implementation: exit codes 15, 16, 30–34, 36, 40, warning codes, store file operations; code review rework: exit codes 2 and 130, warning codes `feature-folder-invalid`, `feature-id-mismatch`, `current-feature-invalid`, `MoveDirectory`; second code review: exit code 35), 2026-10-26 (package 04 implementation: exit codes 37, 41–46; 40 owned by 04), 2026-11-01 (package 05 implementation: exit code 47, warning codes `gates-defaults-used` and `gate-entry-ignored`), 2026-11-04 (package 05 reviews: exit code 17, since the /simplify review of feature/feature-05 for every write of the store), and 2026-11-06 (package 06-1 implementation: range 50–59, exit code 50, warning code `engine-prerelease-version-mismatch`, `version --expect`). Implemented except the integration versions in `version --json` (package 07). | +| Status | Draft, 2026-10-14, updated 2026-10-18 (implementation state; package 02 implementation: missing `features/` is valid, exit codes 11, 13, 23; code review rework: exit codes 14, 24), 2026-10-21 (package 03 implementation: exit codes 15, 16, 30–34, 36, 40, warning codes, store file operations; code review rework: exit codes 2 and 130, warning codes `feature-folder-invalid`, `feature-id-mismatch`, `current-feature-invalid`, `MoveDirectory`; second code review: exit code 35), 2026-10-26 (package 04 implementation: exit codes 37, 41–46; 40 owned by 04), 2026-11-01 (package 05 implementation: exit code 47, warning codes `gates-defaults-used` and `gate-entry-ignored`), 2026-11-04 (package 05 reviews: exit code 17, since the /simplify review of feature/feature-05 for every write of the store), 2026-11-06 (package 06-1 implementation: range 50–59, exit code 50, warning code `engine-prerelease-version-mismatch`, `version --expect`), 2026-11-13 (package 07 implementation: format id `integrations` removed, `integrations` in `version --json`, exit codes 51–53, warning codes `integration-prerelease-ref`, `integration-release-tag-missing`, and `agent-unavailable`), and 2026-11-14 (package 07 review rework: a command-specific message for 130). Implemented. | | Source | Concept §3.1, §3.2, §4.1, [§9](../../research/shade-kit-concept.md#9-version-drift) | | Depends on | — | | Enables | Every later package | @@ -52,7 +52,8 @@ Every file the kit writes into a repository is safe across branch merges and kit | `feature` | `.shadekit/features//feature.json` | | `current-feature` | `.shadekit/features/current-feature.json` | | `templates-lock` | `.shadekit/templates.lock.json` | - | `integrations` | User-level integration record (package 07) | + + The format id `integrations` for a user-level integration record was removed on 2026-11-13 (package 07 implementation): the engine keeps no record of its own and reads the installed integrations from the agent. **Decided** on 2026-11-13 (package 07 implementation). **Implemented** (`FormatIds`, `FormatRegistry.CreateDefault()`, `FormatRegistryTests`). - Fields the engine does not know are kept unchanged when the file is written back. Adding a field never raises the format version. **Decided** (concept §9.4). **Implemented** (`[JsonExtensionData]` in `VersionedDocument`). - A file without `schemaVersion` is treated as invalid, not as version 1, and every command that touches it stops (`invalid-file`). **Decided** (concept §9.1), because a missing version most likely means a hand-edited or foreign file. **Implemented** (`InvalidKitFileException`). @@ -69,8 +70,8 @@ Every file the kit writes into a repository is safe across branch merges and kit ### `shade-kit version` -- Plain output: the engine version. **Decided** (implemented in code). **Implemented** (`VersionCommand`). -- `--json` output: engine version and the current format version per file type, keyed by format id (`"formats": { "config": 1, … }`). This is the engine's capability, not the state of a repository. **Decided** (implemented in code). **Implemented** (`VersionCommandData`). Skills use it for the version handshake (package 06): with `--expect ` it checks the engine against the skill's version (package 06-1, **Implemented**), and package 07 adds the installed integration versions to it. +- Plain output: the engine version, since package 07 followed by one line per installed integration. **Decided** (implemented in code). **Implemented** (`VersionCommand`). +- `--json` output: engine version and the current format version per file type, keyed by format id (`"formats": { "config": 1, … }`). This is the engine's capability, not the state of a repository. **Decided** (implemented in code). **Implemented** (`VersionCommandData`). Skills use it for the version handshake (package 06): with `--expect ` it checks the engine against the skill's version (package 06-1, **Implemented**). Since package 07 it also has the always-present field `integrations` with the installed integrations (`agent`, `pluginId`, `kitVersion`, `ref`, `enabled`), read from the agents whose CLI is detected; an agent CLI that is missing gives no warning, one that is detected but fails gives the warning `agent-unavailable`, and neither fails the command (**Implemented** on 2026-11-13, `VersionCommandData.Integrations`). ### Agent contract (applies to every agent-facing command) @@ -88,8 +89,8 @@ Every file the kit writes into a repository is safe across branch merges and kit ``` On failure, `ok` is `false`, `data` is `null`, and `error` is `{ "code": "…", "message": "…" }`. **Implemented** (`CliJsonEnvelope`, `ICliJsonWriter`, `CliErrorMapper`). -- Every failure has a stable exit code from `ShadeKitCliExitCodes` and, in JSON mode, a stable error code string, so skills can branch on it without parsing messages. **Decided** (implemented in code). Error and warning codes are kebab-case. **Decided** (implemented in code). Codes that only appear as warnings are in `ShadeKitCliWarningCodes`: `current-feature-mismatch`, `current-feature-missing`, `current-feature-invalid`, `feature-file-missing`, `feature-folder-invalid`, and `feature-id-mismatch`, all from package 03; `gates-defaults-used` and `gate-entry-ignored` from package 05 (since 2026-11-01); `engine-prerelease-version-mismatch` from package 06-1 (since 2026-11-06); `upgrade-needed` is both an error code and a warning code. **Implemented** (`ShadeKitCliWarningCodes`, since 2026-10-21). -- Exit codes are grouped in ranges per area: 10–19 store and kit root, 20–29 file format and format version, 30–39 features, 40–49 phases and gates, 50–59 versions and integrations (since 2026-11-06, package 06-1), 255 host errors. **Decided** (implemented in code). Two codes are outside the area ranges, because they apply to every command: 2 (`invalid-arguments`) is the usage code for arguments the option parser rejects, for example a missing required argument; the message names the problem and points to `shade-kit --help`, and there is no stack trace. **Decided** on 2026-10-21 (package 03 code review rework). 130 (`canceled`, 128 + SIGINT) ends a run canceled with Ctrl+C. **Decided** on 2026-10-21 (package 03 code review rework). Both are **Implemented** (`CliErrorMapper.MapArgumentError`, `CliErrorMapper.MapCancellation`, `Program`); in JSON mode each writes one failure envelope. An option class the parser cannot create is a defect of the CLI and stays 255 (`host-error`). Codes owned by packages 01 to 06-1, all **Implemented** (`ShadeKitCliExitCodes`, `ShadeKitCliErrorCodes`, `CliErrorMapper`). Exit code 11 is free since 2026-10-18 (see [Kit root](#kit-root)). Exit code 35 (`feature-io-failed`) was added on 2026-10-21 after the second code review of package 03. Exit code 37 (`no-current-feature`) was added on 2026-10-26 with package 04, in the features range because it is about features. Exit code 40 is owned by package 04 since 2026-10-26, because profiles belong to it; package 04 added 41–46 (package 04, [Errors](04-phase-engine-and-workflow-profiles.md#errors)). Exit code 47 (`checklist-template-not-found`) was added on 2026-11-01 with package 05, and exit code 17 (`kit-file-write-failed`, a file of the store cannot be written, in the store range) on 2026-11-04 after the code review of package 05 (package 05, [Errors](05-gates-and-checklists.md#errors)); since the /simplify review of the same day it applies to every write of the store ([Kit root](#kit-root)). Exit code 50 (`version-mismatch`) was added on 2026-11-06 with package 06-1 (package 06-1, [Exit and warning codes](06-1-engine-version-check.md#exit-and-warning-codes)): +- Every failure has a stable exit code from `ShadeKitCliExitCodes` and, in JSON mode, a stable error code string, so skills can branch on it without parsing messages. **Decided** (implemented in code). Error and warning codes are kebab-case. **Decided** (implemented in code). Codes that only appear as warnings are in `ShadeKitCliWarningCodes`: `current-feature-mismatch`, `current-feature-missing`, `current-feature-invalid`, `feature-file-missing`, `feature-folder-invalid`, and `feature-id-mismatch`, all from package 03; `gates-defaults-used` and `gate-entry-ignored` from package 05 (since 2026-11-01); `engine-prerelease-version-mismatch` from package 06-1 (since 2026-11-06); `integration-prerelease-ref`, `integration-release-tag-missing`, and `agent-unavailable` from package 07 (since 2026-11-13); `upgrade-needed` is both an error code and a warning code. **Implemented** (`ShadeKitCliWarningCodes`, since 2026-10-21). +- Exit codes are grouped in ranges per area: 10–19 store and kit root, 20–29 file format and format version, 30–39 features, 40–49 phases and gates, 50–59 versions and integrations (since 2026-11-06, package 06-1), 255 host errors. **Decided** (implemented in code). Two codes are outside the area ranges, because they apply to every command: 2 (`invalid-arguments`) is the usage code for arguments the option parser rejects, for example a missing required argument; the message names the problem and points to `shade-kit --help`, and there is no stack trace. **Decided** on 2026-10-21 (package 03 code review rework). 130 (`canceled`, 128 + SIGINT) ends a run canceled with Ctrl+C. **Decided** on 2026-10-21 (package 03 code review rework). A command may give its own message for 130: a cancellation during the marketplace switch of `integrations install` or `update` names the repair (`IntegrationSwitchCanceledException`, mapped in `CliErrorMapper.Map`; **Decided** on 2026-11-14, package 07 review rework). Both are **Implemented** (`CliErrorMapper.MapArgumentError`, `CliErrorMapper.MapCancellation`, `Program`); in JSON mode each writes one failure envelope. An option class the parser cannot create is a defect of the CLI and stays 255 (`host-error`). Codes owned by packages 01 to 06-1, all **Implemented** (`ShadeKitCliExitCodes`, `ShadeKitCliErrorCodes`, `CliErrorMapper`). Exit code 11 is free since 2026-10-18 (see [Kit root](#kit-root)). Exit code 35 (`feature-io-failed`) was added on 2026-10-21 after the second code review of package 03. Exit code 37 (`no-current-feature`) was added on 2026-10-26 with package 04, in the features range because it is about features. Exit code 40 is owned by package 04 since 2026-10-26, because profiles belong to it; package 04 added 41–46 (package 04, [Errors](04-phase-engine-and-workflow-profiles.md#errors)). Exit code 47 (`checklist-template-not-found`) was added on 2026-11-01 with package 05, and exit code 17 (`kit-file-write-failed`, a file of the store cannot be written, in the store range) on 2026-11-04 after the code review of package 05 (package 05, [Errors](05-gates-and-checklists.md#errors)); since the /simplify review of the same day it applies to every write of the store ([Kit root](#kit-root)). Exit code 50 (`version-mismatch`) was added on 2026-11-06 with package 06-1 (package 06-1, [Exit and warning codes](06-1-engine-version-check.md#exit-and-warning-codes)): | Exit code | Error code | Owner | |---|---|---| @@ -123,6 +124,9 @@ Every file the kit writes into a repository is safe across branch merges and kit | 46 | `phase-state-invalid` | 04 | | 47 | `checklist-template-not-found` | 05 | | 50 | `version-mismatch` | 06-1 | + | 51 | `agent-not-found` | 07 | + | 52 | `agent-command-failed` | 07 | + | 53 | `integration-conflict` | 07 | | 130 | `canceled` | 03 (every command) | | 255 | `host-error` | 01 | diff --git a/docs/feature-packages/06-1-engine-version-check.md b/docs/feature-packages/06-1-engine-version-check.md index 74070c9..3affc26 100644 --- a/docs/feature-packages/06-1-engine-version-check.md +++ b/docs/feature-packages/06-1-engine-version-check.md @@ -2,7 +2,7 @@ | | | |---|---| -| Status | Draft, 2026-11-04 (split from package 06), updated 2026-11-05 and 2026-11-06 (implementation clarification and implementation: strict SemVer 2.0.0 for `--expect`, the match on major and minor, `expectedVersion` in the envelope, the messages, `--expect` without a value and the `=` form, exit code 50, warning code `engine-prerelease-version-mismatch`). Implemented. | +| Status | Draft, 2026-11-04 (split from package 06), updated 2026-11-05 and 2026-11-06 (implementation clarification and implementation: strict SemVer 2.0.0 for `--expect`, the match on major and minor, `expectedVersion` in the envelope, the messages, `--expect` without a value and the `=` form, exit code 50, warning code `engine-prerelease-version-mismatch`), and 2026-11-13 (package 07 implementation: the mismatch message of an engine higher than the skill names `shade-kit integrations install`; exit codes 51–53 in the range 50–59). Implemented. | | Source | [06 Skill foundation](06-skill-foundation.md) (version handshake), [concept §9.6](../../research/shade-kit-concept.md#9-version-drift) | | Kind | .NET (engine and CLI) | | Depends on | 01 | @@ -59,7 +59,7 @@ A skill learns with one CLI call whether it may run against the installed engine - Success: the envelope of `version` (package 01) with `expectedVersion`, the value of `--expect` as passed, in addition. Without `--expect`, the field is left out, so the envelope is unchanged. **Decided** on 2026-11-05. **Implemented** (`VersionCommandData.ExpectedVersion`). - Failure: a failure envelope with `version-mismatch`. The message names both versions and what to update. **Decided** on 2026-11-05. **Implemented** (`EngineVersionMismatchException`, `CliErrorMapper`). `{engine}` is the engine version, `{expected}` the value of `--expect` as passed, and `x.y` the major and minor version: - Engine lower than the skill: `The SHADE kit engine {engine} does not fit the kit skills {expected}: the major and minor versions must be equal. Update the engine to x.y, then run the skill again.` (`x.y` of `{expected}`) - - Engine higher than the skill: `The SHADE kit engine {engine} does not fit the kit skills {expected}: the major and minor versions must be equal. Update the SHADE kit skills to x.y by hand, then run the skill again.` (`x.y` of `{engine}`). Until package 07 builds `integrations update`, the message names updating the skills by hand. + - Engine higher than the skill: `The SHADE kit engine {engine} does not fit the kit skills {expected}: the major and minor versions must be equal. Run 'shade-kit integrations install' to install the SHADE kit skills x.y, then run the skill again.` (`x.y` of `{engine}`). Until 2026-11-13 the message said `Update the SHADE kit skills to x.y by hand`; package 07 built the `integrations` commands and changed it. It names `install`, not `update`: `install` also works when nothing is installed yet, and for an installed agent it behaves like `update`. **Decided** on 2026-11-13 (package 07 implementation, Gate 4). **Implemented** (`CliErrorMapper.CreateEngineVersionMismatchMessage`, `CliErrorMapperTests`). The hint helps only if the tag of the engine carries skills of its major.minor; otherwise `install` would install the same skills again. Since 2026-11-14 the guard test `SkillKitVersionTests` (FP07-AC2) fails every build whose skills carry another major.minor than the engine, the tag build included ([07 Kit version guard](07-claude-code-integration.md#kit-version-guard)). **Decided** on 2026-11-14 (package 07 review rework, Gate 5). - Warning of a prerelease engine: `The prerelease engine {engine} does not fit the kit skills {expected} (the major and minor versions differ); it is used anyway because it is a prerelease.` **Decided** on 2026-11-05. **Implemented** (`EnginePrereleaseVersionMismatchWarning`, `CliErrorMapper.MapWarning`). - Invalid `--expect`: `Invalid arguments: '{value}' is not a SemVer version such as 1.2.3 or 1.2.3-beta.1. Run 'shade-kit --help' for usage.` The text names neither `--expect` nor `version`, because the Core `InvalidSemanticVersionException` it maps is generic and a later caller of the SemVer check must not get an `--expect` message (**Decided** on 2026-11-06, code review). For `--expect` without a value: `Invalid arguments: --expect needs a SemVer version such as 1.2.3 or 1.2.3-beta.1, but got none. Run 'shade-kit version --help' for usage.` **Decided** on 2026-11-05 and 2026-11-06. **Implemented** (`CliErrorMapper.Map`, `CliErrorMapper.MapArgumentError`). - Plain output: on success, the line `shade-kit ` as before; a warning comes first as a line `Warning: `. On a mismatch, the same message as in JSON mode, exit code 50. **Implemented** (`ShadeKitCommandContext.WriteSuccess`, `VersionCommand`). @@ -72,6 +72,7 @@ A skill learns with one CLI call whether it may run against the installed engine - New range **50–59, versions and integrations**, for this package and package 07. **Decided** on 2026-11-04. **Implemented** (`ShadeKitCliExitCodes`). - `50` `version-mismatch` (`ShadeKitCliExitCodes.VersionMismatch`, `ShadeKitCliErrorCodes.VersionMismatch`, `CliErrorMapper`). **Implemented**. +- `51` `agent-not-found`, `52` `agent-command-failed`, and `53` `integration-conflict` of package 07 are in the same range since 2026-11-13, with the warning codes `integration-prerelease-ref`, `integration-release-tag-missing`, and `agent-unavailable` ([07](07-claude-code-integration.md#exit-error-and-warning-codes)). **Implemented**. - Warning `engine-prerelease-version-mismatch` (`ShadeKitCliWarningCodes.EnginePrereleaseVersionMismatch`). **Decided** on 2026-11-05 (name). **Implemented**. ### `CLAUDE.md` diff --git a/docs/feature-packages/06-2-skill-conventions-and-version.md b/docs/feature-packages/06-2-skill-conventions-and-version.md index 619f110..d05a557 100644 --- a/docs/feature-packages/06-2-skill-conventions-and-version.md +++ b/docs/feature-packages/06-2-skill-conventions-and-version.md @@ -2,7 +2,7 @@ | | | |---|---| -| Status | Draft, 2026-11-04 (split from package 06), updated 2026-11-06 (implementation: visibility check in Claude Code, `metadata.version` `0.7.0` in every skill, the SemVer rule, who checks, the wording of the handshake step, the quoted `shade-kit-report` description, the skill conventions in `CLAUDE.md`). AC1 and AC2 implemented; AC3: rule and wording set, applied by 06-5, 06-6, and 06-9. | +| Status | Draft, 2026-11-04 (split from package 06), updated 2026-11-06 (implementation: visibility check in Claude Code, `metadata.version` `0.7.0` in every skill, the SemVer rule, who checks, the wording of the handshake step, the quoted `shade-kit-report` description, the skill conventions in `CLAUDE.md`) and 2026-11-13 (package 07 implementation: the skeleton source comments removed, the guard test of FP07-AC7, the plugin skill names in Claude Code), and 2026-11-14 (package 07 review rework, Gate 5: every skill raised to `0.8.0`; the guard test `SkillKitVersionTests` checks the version and every handshake text against the major.minor of the engine build; the FP07-AC7 guard scans every text file under `skills/`), and 2026-11-15 (package 07 review rework, Gate 5 round 2: the guard takes the most frequent version as the kit version, so an outlier skill is the one reported). AC1 and AC2 implemented; AC3: rule and wording set, applied by 06-5, 06-6, and 06-9. | | Source | [06 Skill foundation](06-skill-foundation.md) (skill conventions, version handshake), Concept §3.2, §3.3 | | Kind | Cross-cutting (all skills) | | Depends on | 06-1 | @@ -24,7 +24,7 @@ Every kit skill follows the same rules and carries its kit version. A team can i - Writing the version check into the skills (06-5, 06-6, 06-9); this package sets who checks and the wording. - Copilot and Codex (package 08). -- The automated alignment of the skill version with GitVersion (see open points). +- Writing the skill version from GitVersion; the version is raised by hand, and since 2026-11-14 a guard test checks it (see Kit version in the frontmatter and open points). ## Functional description @@ -33,27 +33,27 @@ Every kit skill follows the same rules and carries its kit version. A team can i - Skills are written in the shared `SKILL.md` format and the plugin layout of `skills/`. Claude-only features (for example subagents) are only used where an agent-neutral way would lose function, and each such use is named in the skill. **Decided** (constraint, concept §1), **Unverified** (format compatibility, resolved in package 08). - A phase starts only when the human calls its phase skill (`/shade-kit-`). No skill starts a phase skill, and no phase skill calls `phase start` for a phase other than its own; a skill that ends names the skills the human can call ([06-3 Next-steps message](06-3-next-steps-skill.md)). **Decided** on 2026-10-30 ([phase start analysis](../../research/shade-kit-phase-start-analysis.md)). The rule holds by convention, not technically: the description of every phase skill says that it runs only when the user calls it by name, the skill texts contain no hand-off, and the managed section in `CLAUDE.md` / `AGENTS.md` tells the agent (package 02, **Implemented** in `ManagedInstructionSection`). A restriction such as Claude Code's `disable-model-invocation` frontmatter field is not used in v1. **Decided** on 2026-10-30. Known weak point, like approvals (package 04): nothing technically stops an agent from loading a phase skill on its own. - Skills never read or write `feature.json`, `gates.json`, or `config.json` directly. They use the CLI with `--json`. Skills read and write Markdown artifacts in the feature folder directly. **Decided** on 2026-11-04. This keeps every state change behind the engine's version check (package 01). -- A shipped skill references no path under `research/` or `docs/` of the kit repository; those folders are design notes and are not shipped. The source comments of the skeletons are removed when a skill is worked out. **Decided** on 2026-10-18 (findings clarification). Checked when the skills are shipped: FP07-AC7 (package 07). **Decided** on 2026-11-04. +- A shipped skill references no path under `research/` or `docs/` of the kit repository; those folders are design notes and are not shipped. The source comments of the skeletons are removed when a skill is worked out. **Decided** on 2026-10-18 (findings clarification). Checked when the skills are shipped: FP07-AC7 (package 07). **Decided** on 2026-11-04. Since package 07 this repository is the shipped plugin, so the source comments `` were removed from all 13 skeletons that still had them, also from those not worked out yet. **Decided** on 2026-11-13 (package 07 implementation). **Implemented**. A guard test fails when a text file under `skills/` has a path segment `docs/` or `research/`; until 2026-11-14 it scanned only `SKILL.md` (**Implemented**: `ShippedSkillsTests`, FP07-AC7). - Every artifact a skill creates starts from the repository's template in `.shadekit/templates/`, not from text built into the skill, so team edits to templates take effect. **Decided** on 2026-11-04. The skill follows the template conventions of package 02: it follows the guidance comments, replaces every placeholder, and removes the guidance comments; checklist copies (package 05) keep their guidance comments. One exception: when `.shadekit/templates/researches.md` is missing, `shade-kit-research` creates `researches.md` with the lines the template would give (title and feature line) and says so in its return, so that a research run is not lost to a deleted template. **Decided** on 2026-11-13 ([06-8](06-8-research-skill.md)). - `request.md` can hold third-party content, written unchanged by `feature new`: the body and every comment of an issue, or a whole web page (package 03). Every skill that reads it, and every research agent that gets it as feature context, treats it as data that describes the requirement, never as instructions to the agent: it does not follow commands, links, or tool requests in it, and shows the human any instruction in it that looks suspicious (a research agent reports it to the calling skill, which shows it). **Decided** on 2026-10-25 (code review of the rework of `feature new`, finding F6; package 09, [`new`](09-discuss-and-intake.md#new)). **Implemented** (`shade-kit-new`, `shade-kit-refine`, `shade-kit-diagnose`, `shade-kit-quick`, `shade-kit-research`). -- The skill texts are checked by a review by hand when a sub-feature is accepted; there are no automated tests of the skill texts. **Decided** on 2026-11-04. +- The skill texts are checked by a review by hand when a sub-feature is accepted; there are no automated tests of the skill texts. **Decided** on 2026-11-04. Two guard tests check the shipped files mechanically, not what a skill does: the references into `docs/` and `research/` (FP07-AC7) and the kit version (`SkillKitVersionTests`, FP07-AC2, since 2026-11-14). ### Kit version in the frontmatter -- Every skill under `skills/` carries its kit version in the frontmatter, hardcoded and committed, because the skills must be installable as a plugin with their version included. **Decided** on 2026-11-04. **Implemented** (all 17 skills under `skills/`, `0.7.0`). +- Every skill under `skills/` carries its kit version in the frontmatter, hardcoded and committed, because the skills must be installable as a plugin with their version included. **Decided** on 2026-11-04. **Implemented** (all 19 skills under `skills/`, `0.8.0` since 2026-11-14; `0.7.0` from 2026-11-06). ```yaml --- name: shade-kit-next-phase description: ... metadata: - version: 0.7.0 + version: 0.8.0 --- ``` -- All skills carry the same version. **Decided** on 2026-11-04. **Implemented** (`0.7.0`). +- All skills carry the same version. **Decided** on 2026-11-04. **Implemented** (`0.8.0`; checked by `SkillKitVersionTests`). - The version is a SemVer version without a prerelease label. **Decided** on 2026-11-06 (was **Proposed**). -- The value is written unquoted (`version: 0.7.0`). A `description` that YAML would not read unchanged as a plain scalar is written in double quotes: unquoted, a `: ` makes the frontmatter invalid YAML (Claude Code then loads the skill with empty metadata), and a ` #` silently cuts the description at the comment. **Decided** on 2026-11-06 (implementation). +- The value is written unquoted (`version: 0.8.0`). A `description` that YAML would not read unchanged as a plain scalar is written in double quotes: unquoted, a `: ` makes the frontmatter invalid YAML (Claude Code then loads the skill with empty metadata), and a ` #` silently cuts the description at the comment. **Decided** on 2026-11-06 (implementation). - **Implemented** (found in the implementation on 2026-11-06): the unquoted description of `shade-kit-report` contained `: `, so its frontmatter was invalid YAML. The description is now in double quotes, with the same text. - Who checks the version. **Decided** on 2026-11-04, clarified on 2026-11-06 (implementation clarification): the earlier wording said that the skills the human calls check and that skills only loaded by another skill do not, but `shade-kit-phase-entry`, which only the phase skills load, checks for them (06-5). - `shade-kit-phase-entry` checks for the phase skills, which do not check themselves (06-5). @@ -71,26 +71,30 @@ Every kit skill follows the same rules and carries its kit version. A team can i - Two further skills loaded in the implementing session gave the same result: `implement-direct`, called by the user as a slash command, and `skill-creator`, loaded through the Skill tool. - The documentation agrees. The [Claude Code skills documentation](https://code.claude.com/docs/en/skills) says of `metadata`: "Free-form YAML map for your own key-value data, … read by your own tooling from `SKILL.md`. Claude Code doesn't act on its contents". It also says that "the rendered `SKILL.md` content enters the conversation as a single message", and that malformed frontmatter "loads the skill body with empty metadata". The Agent Skills overview (platform.claude.com) puts `name` and `description` from the YAML frontmatter at level 1 and the `SKILL.md` body at level 2. - Limits: one run per path; project-level skills only (plugin and user-level skills were not run). Copilot and Codex are checked in package 08. + - Plugin skills (package 07, 2026-11-13, Claude Code 2.1.323, headless, plugin loaded with `--plugin-dir`): the skill listing shows the namespaced name `shade-kit:shade-kit-next-phase`, both `/shade-kit-next-phase` and `/shade-kit:shade-kit-next-phase` load the skill, and its handshake ran with the version from the text (`--expect 0.7.0`, the kit version then). **FACT** ([07](07-claude-code-integration.md#skill-names-in-claude-code)). The frontmatter of plugin skills was not checked separately. - The model does not see the frontmatter, so the fallback applies: every skill that calls `version --expect` also states the version in the text of its handshake step. The frontmatter stays the source; both places hold the same value. **Decided** on 2026-11-04; applies since the check on 2026-11-06. This sub-feature sets the rule and the wording; 06-5, 06-6, and 06-9 write them into the handshake steps. **Decided** on 2026-11-06. - The handshake step has this wording in every skill that calls `version --expect`. **Decided** on 2026-11-06. ```text - Version handshake: run `shade-kit version --json --expect 0.7.0`; 0.7.0 is the kit version of this skill (`metadata.version` in its frontmatter). + Version handshake: run `shade-kit version --json --expect 0.8.0`; 0.8.0 is the kit version of this skill (`metadata.version` in its frontmatter). ``` - When the version is raised, the frontmatter of every skill and every handshake text change together: search the skills for the old value. **Decided** on 2026-11-06. +- The guard test `SkillKitVersionTests.SkillFiles_ShippedSkills_CarryOneKitVersionThatMatchesTheEngineMajorMinor` (`CreativeCoders.ShadeKit.Core.Tests/Skills/`, FP07-AC2) fails the build when a skill has no plain `x.y.z` `metadata.version`, when the skills carry different values, when their major.minor differs from the major.minor of the engine version of the build (GitVersion; patch and prerelease ignored), or when any `--expect ` or "`` is the kit version of this skill" in a text file under `skills/` names another version. **Decided** on 2026-11-14 (package 07 review rework, Gate 5). **Implemented** ([07 Kit version guard](07-claude-code-integration.md#kit-version-guard)). The kit version the skills are compared with is the most frequent valid version; on a tie, the version with the major.minor of the engine wins, then the version of the first skill in ordinal path order; so a single skill with another version is the one reported. **Decided** on 2026-11-15 (package 07 review rework, Gate 5 round 2, finding N6; before, the first skill with a valid version in path order was the reference). **Implemented** (`SkillKitVersionTests.SelectKitSkill`). +- Raised to `0.8.0` on 2026-11-14, in the frontmatter and in every handshake text of all 19 skills, because the engine builds carry `0.8.x` since the tag `v0.8.0` and the new guard failed with `0.7.0`. **Decided** on 2026-11-14 (package 07 review rework, Gate 5). ## Acceptance criteria -Status as of 2026-11-06. There are no automated tests of the skill texts (skill conventions above), so each criterion names how it is proven. +Status as of 2026-11-14. There are no automated tests of the skill texts (skill conventions above), so each criterion names how it is proven; the version guard of 07 now also proves AC1 and the version part of AC3. -- **FP06-2-AC1** Every skill under `skills/` has `metadata.version` in its frontmatter, and all skills have the same SemVer value. **Implemented**: all 17 skills carry `metadata.version: 0.7.0`. Proven by a one-off check that all values are equal, are strings, and are a plain `x.y.z`; no automated test, by the rule of this package. Skill-creator's `quick_validate.py` (17 of 17 valid) shows that the frontmatter stays valid; it does not read `metadata`. +- **FP06-2-AC1** Every skill under `skills/` has `metadata.version` in its frontmatter, and all skills have the same SemVer value. **Implemented**: all 19 skills carry `metadata.version: 0.8.0` (`0.7.0` until 2026-11-14). Proven on 2026-11-06 by a one-off check that all values are equal, are strings, and are a plain `x.y.z`, and since 2026-11-14 by `SkillKitVersionTests.SkillFiles_ShippedSkills_CarryOneKitVersionThatMatchesTheEngineMajorMinor`. Skill-creator's `quick_validate.py` (17 of 17 valid) shows that the frontmatter stays valid; it does not read `metadata`. - **FP06-2-AC2** The result of the visibility check for Claude Code is recorded in this package with the date and how it was checked. **Implemented**: recorded under Frontmatter visibility (2026-11-06, Claude Code 2.1.318). -- **FP06-2-AC3** If the check finds that the model does not see the frontmatter, every skill that calls `version --expect` states the same version in the text of its handshake step. Rule and wording **Decided** on 2026-11-06 (Frontmatter visibility). `shade-kit-phase-entry` (06-5) applies it since 2026-11-10 and `shade-kit-next-phase` (06-6) since 2026-11-11 (`--expect 0.7.0` in the text of their handshake steps); `new`, `discuss`, and `drop` (06-9) since 2026-11-13. Every skill that calls `version --expect` now states the version in the text of its handshake step. +- **FP06-2-AC3** If the check finds that the model does not see the frontmatter, every skill that calls `version --expect` states the same version in the text of its handshake step. Rule and wording **Decided** on 2026-11-06 (Frontmatter visibility). `shade-kit-phase-entry` (06-5) applies it since 2026-11-10 and `shade-kit-next-phase` (06-6) since 2026-11-11 (`--expect 0.7.0` in the text of their handshake steps then, `0.8.0` since 2026-11-14); `new`, `discuss`, and `drop` (06-9) since 2026-11-13. Every skill that calls `version --expect` now states the version in the text of its handshake step; since 2026-11-14 `SkillKitVersionTests` checks that every such text names the kit version. ## Open points -- **Alignment with GitVersion skipped for now** (2026-11-04): the skill version is maintained by hand, and nothing checks it against the release tag. This breaks the rule in `GitVersion.yml` that no version is maintained by hand. Possible later solutions: a test that all skills carry the same version, a check in the `verify-tag` job of the release workflow, or a Cake task that writes the version (package 19). -- Initial value of `metadata.version`: answered, `0.7.0`. **Decided** on 2026-11-06. The value is raised by hand for every release whose major or minor differs: before a `v0.8.0` tag, for example, every skill must carry `0.8.0`, or a release engine fails every handshake with exit code 50 (06-1). +- **Alignment with GitVersion: checked, not written** (2026-11-04, updated 2026-11-14): the skill version is still raised by hand, which still breaks the rule in `GitVersion.yml` that no version is maintained by hand. Since 2026-11-14 `SkillKitVersionTests` ties it to the build: every build that runs the tests (pull request, `main`, `feature/**`, release tag) fails when the skills' major.minor differs from the engine's, so a release tag with stale skills fails its tag build before anything is published (19). Still open: writing the version from GitVersion (for example a Cake task, package 19), and a check before the tag is set (the `verify-tag` job does not check it; review Major, layer 2, not selected at Gate 5). The guard compares major.minor only, the rule of the handshake (06-1). +- Raising the minor: the commit that raises the skills to a new minor must also raise the minor of the build version, or the build of that commit fails the guard. `GitVersion.yml` says that a breaking change is announced with `+semver: minor` (**FACT**, `GitVersion.yml` comment); **Unverified** that a commit message with `+semver: minor` gives the build the new minor in this repository (not run). +- Initial value of `metadata.version`: answered, `0.7.0`. **Decided** on 2026-11-06. Raised to `0.8.0` on 2026-11-14 (see above). The value is raised by hand for every release whose major or minor differs. - Exact skill names (concept open question 6). - Phase skills are restricted to user invocation only by convention; a technical restriction (Claude Code `disable-model-invocation`, and whatever Copilot and Codex offer) is a possible later addition. diff --git a/docs/feature-packages/06-5-phase-entry-skill.md b/docs/feature-packages/06-5-phase-entry-skill.md index f46855d..5ac4cd1 100644 --- a/docs/feature-packages/06-5-phase-entry-skill.md +++ b/docs/feature-packages/06-5-phase-entry-skill.md @@ -27,7 +27,7 @@ A developer starts every phase by calling its skill (for example `/shade-kit-pla ## Functional description -**Implemented** in `skills/shade-kit-phase-entry/SKILL.md` (`metadata.version: 0.7.0`), written with skill-creator and proven by scenario runs (see [acceptance criteria](#acceptance-criteria)). +**Implemented** in `skills/shade-kit-phase-entry/SKILL.md` (`metadata.version: 0.7.0`, `0.8.0` since 2026-11-14, 06-2), written with skill-creator and proven by scenario runs (see [acceptance criteria](#acceptance-criteria)). ### Input from the calling skill @@ -76,7 +76,7 @@ The warnings of `phase start` are passed to the next-steps message (06-3). A pha - **Warnings**: the skill keeps the warnings of every CLI call of its run and does not show them on the way; the ending or the return passes them on, and the closing next-steps message shows each one once. **Proposed**. - **Ending**: every way of ending loads `shade-kit-next-steps` with the reason (refusal, no, or end of work) and the warnings, and then tells the phase skill that the run ended, so the phase skill does no phase work and writes no message of its own. **Proposed** (wording). - **Return**: on "run the phase", the skill returns the feature, how the entry went, the skills to load (`skills.generalSkills`), the warnings, and the gate warning of approval off. **Proposed** (format); 06-9 builds the phase skills on it. -- The skill runs only `shade-kit version --json --expect 0.7.0`, `phase start`, `phase approve`, and `phase reject` (the last three with `--json`), loads only `shade-kit-gate-check` and `shade-kit-next-steps`, and reads or writes no file. **Implemented**. +- The skill runs only `shade-kit version --json --expect 0.7.0` (`0.8.0` since 2026-11-14, 06-2; the scenario runs below used `0.7.0`), `phase start`, `phase approve`, and `phase reject` (the last three with `--json`), loads only `shade-kit-gate-check` and `shade-kit-next-steps`, and reads or writes no file. **Implemented**. ## Acceptance criteria diff --git a/docs/feature-packages/06-6-next-phase-skill.md b/docs/feature-packages/06-6-next-phase-skill.md index 7479f3d..b94f0e2 100644 --- a/docs/feature-packages/06-6-next-phase-skill.md +++ b/docs/feature-packages/06-6-next-phase-skill.md @@ -53,7 +53,7 @@ Only `pending` and `forward` have a gate. - **The "what happened" line** passed to `shade-kit-next-steps` is "Status of ``.", plus, where it applies, that `` is now the current feature (after `feature set`), the line about another feature, and that an approval or phase start asked for in the call is not recorded and the phase skill asks for it. The last one was added after iteration 1: a runner noted that a human who approved in the call may believe the transition went through. **Proposed**. - **Warnings**: the skill keeps the warnings of every CLI call and passes them on; the closing message shows each one once. **Proposed** (as in 06-5). - **The passed `phase next` result in `shade-kit-next-steps`** (06-3): its input section said to use a passed result, while its flow steps 1 and 2 said to run `phase next`. Runners of three scenarios noted the contradiction, though all followed the input section. Flow step 3 of `shade-kit-next-steps` now states the rule once (use a passed result, otherwise run `phase next` once), and steps 1 and 2 refer to it. **Decided** on 2026-11-11. **Implemented**; proven in iteration 3 (below). -- The skill runs only `shade-kit version --json --expect 0.7.0`, `feature current`, `feature list`, `feature set ` (only after the human picked that feature), and `phase next`, each with `--json`; loads only `shade-kit-next-steps`; reads or writes no file. **Implemented**. +- The skill runs only `shade-kit version --json --expect 0.7.0` (`0.8.0` since 2026-11-14, 06-2; the scenario runs below used `0.7.0`), `feature current`, `feature list`, `feature set ` (only after the human picked that feature), and `phase next`, each with `--json`; loads only `shade-kit-next-steps`; reads or writes no file. **Implemented**. ## Acceptance criteria diff --git a/docs/feature-packages/06-skill-foundation.md b/docs/feature-packages/06-skill-foundation.md index ec48fc4..c0409af 100644 --- a/docs/feature-packages/06-skill-foundation.md +++ b/docs/feature-packages/06-skill-foundation.md @@ -2,7 +2,7 @@ | | | |---|---| -| Status | Draft, 2026-10-14, updated 2026-10-17 (template conventions, checklist format), 2026-10-18 (no router: `shade-kit-next-phase` and entry protocol; findings clarification: `phase next`, pending transition, report and review skills), 2026-10-24 (documentation check: skill names of the general skills, placeholders in checklist copies), 2026-10-25 (code review of the rework of `feature new` in package 03: `request.md` treated as data, not as instructions), 2026-10-30 ([phase start analysis](../../research/shade-kit-phase-start-analysis.md): phases start only when the user calls the phase skill, `shade-kit-next-phase` is advisory, next-steps message, active phase asks the human), 2026-11-04 (split into the sub-features 06-1 to 06-9; version in the skill frontmatter, checked by the engine; `shade-kit-report` moved to package 15), 2026-11-06 (06-2: Claude Code does not show the frontmatter to the model), 2026-11-08 (06-3: `shade-kit-next-steps` implemented; 06-4: `shade-kit-gate-check` and `shade-kit gate info` implemented), 2026-11-10 (06-5: `shade-kit-phase-entry` implemented), 2026-11-11 (06-6: `shade-kit-next-phase` implemented), 2026-11-13 (06-8: `shade-kit-research` and the format of `researches.md` implemented), and 2026-11-13 (06-9: the skill skeletons load the entry protocol and the next-steps message; `phase next` has no `continue` step in `new`) | +| Status | Draft, 2026-10-14, updated 2026-10-17 (template conventions, checklist format), 2026-10-18 (no router: `shade-kit-next-phase` and entry protocol; findings clarification: `phase next`, pending transition, report and review skills), 2026-10-24 (documentation check: skill names of the general skills, placeholders in checklist copies), 2026-10-25 (code review of the rework of `feature new` in package 03: `request.md` treated as data, not as instructions), 2026-10-30 ([phase start analysis](../../research/shade-kit-phase-start-analysis.md): phases start only when the user calls the phase skill, `shade-kit-next-phase` is advisory, next-steps message, active phase asks the human), 2026-11-04 (split into the sub-features 06-1 to 06-9; version in the skill frontmatter, checked by the engine; `shade-kit-report` moved to package 15), 2026-11-06 (06-2: Claude Code does not show the frontmatter to the model), 2026-11-08 (06-3: `shade-kit-next-steps` implemented; 06-4: `shade-kit-gate-check` and `shade-kit gate info` implemented), 2026-11-10 (06-5: `shade-kit-phase-entry` implemented), 2026-11-11 (06-6: `shade-kit-next-phase` implemented), 2026-11-13 (06-8: `shade-kit-research` and the format of `researches.md` implemented), 2026-11-13 (06-9: the skill skeletons load the entry protocol and the next-steps message; `phase next` has no `continue` step in `new`), and 2026-11-13 (package 07: the mismatch message names `integrations install`) | | Source | Concept §3.2, §3.3, §3.4, §11.4, [concept §9.6](../../research/shade-kit-concept.md#9-version-drift) | | Depends on | 01, 03, 04, 05 | | Enables | 07, 08, and every phase package (09–17) | @@ -100,6 +100,6 @@ The acceptance criteria are in the sub-features. The former criteria of this pac - **Alignment of the skill version with GitVersion skipped for now** (06-2). - Frontmatter visibility: Claude Code 2.1.318 does not show the frontmatter to the model (checked on 2026-11-06 in 06-2, on project-level skills), so the handshake step states the version in its text. **Unverified** for Copilot and Codex (package 08). -- Until package 07 builds `integrations update`, the mismatch message of 06-1 names updating the skills by hand. +- The mismatch message of 06-1 named updating the skills by hand until package 07 built the `integrations` commands; since 2026-11-13 it names `shade-kit integrations install` (06-1). - Exact skill names (concept open question 6). - Phase skills are restricted to user invocation only by convention (06-2); a technical restriction is a possible later addition. diff --git a/docs/feature-packages/07-claude-code-integration.md b/docs/feature-packages/07-claude-code-integration.md index 637d953..bc78d77 100644 --- a/docs/feature-packages/07-claude-code-integration.md +++ b/docs/feature-packages/07-claude-code-integration.md @@ -2,23 +2,25 @@ | | | |---|---| -| Status | Draft, 2026-10-14, updated 2026-10-18 (consistency review: router references replaced by `shade-kit-next-phase`) and 2026-11-04 (split of package 06: FP07-AC7 taken over from FP06-AC13) | -| Source | Concept §2 (Lifecycle), §3.1 (`integrations install/update`), §3.4, [concept §9.6](../../research/shade-kit-concept.md#9-version-drift) | +| Status | Draft, 2026-10-14, updated 2026-10-18 (consistency review: router references replaced by `shade-kit-next-phase`), 2026-11-04 (split of package 06: FP07-AC7 taken over from FP06-AC13), and 2026-11-13 (implementation: this repository is the Claude Code plugin marketplace `creativecoders-shade-kit`, the version pin by tag, no engine-owned record, `integrations install` and `integrations update`, `integrations` in `version --json`, exit codes 51–53, warning codes `integration-prerelease-ref` and `agent-unavailable`, skeleton source comments removed, namespacing checked in a smoke check), and 2026-11-13 (Gate 4 rework: release-tag check with `git ls-remote` and warning `integration-release-tag-missing`, `version` asks only detected agents, `update` with nothing installed resolves no source, the 06-1 message names `integrations install`, `git` never prompts), and 2026-11-14 (review rework, Gate 5, see [Review](#review): skills raised to the kit version `0.8.0` and guarded by `SkillKitVersionTests`, the FP07-AC7 guard scans every text file under `skills/`, a kept marketplace is refreshed with `claude plugin marketplace update`, a cancellation during the switch names the repair, `--agent claude` without `claude` fails before the tag check, `update` reads the state once per agent, completed agents are named when a later agent fails, URL forms of `SHADE_KIT_MARKETPLACE_SOURCE` are refused, directory sources are compared after resolving symbolic links), and 2026-11-15 (second review rework, Gate 5 round 2, see [Review](#review): a stray stdout line fails `install` and `update` with 52 but gives `agent-unavailable` in `version`, the kit version guard reports the outlier skill, the minimum Claude Code version for `marketplace update --json` recorded as an accepted open point). Implemented; FP07-AC1 checked by hand in a headless session; FP07-AC2 enforced by a guard test. | +| Source | Concept §2 (Lifecycle), §3.1 (`integrations install/update`), §3.4, [concept §9.6](../../research/shade-kit-concept.md#9-version-drift); Claude Code plugin and marketplace commands, checked with Claude Code 2.1.323 on 2026-11-13 and 2026-11-14 (`marketplace update`); [review report](../reviews/2026-11-13-feature-claude-code-integration-uncommitted.md), [second review report](../reviews/2026-11-15-feature-claude-code-integration-uncommitted-2.md) | | Depends on | 01, 06 | | Enables | 08 (same mechanism for more agents); end-to-end use of all phase packages in Claude Code | ## Benefit -A developer installs the kit's skills and agents for Claude Code with one command, once per machine, and every repository on that machine can use them. Updating the engine and running `integrations update` keeps engine and skills on the same version, so the version handshake (package 06) does not fail. +A developer installs the kit's skills for Claude Code with one command, once per machine, and every repository on that machine can use them. Updating the engine and running `integrations update` moves the skills to the release tag of the new engine, so engine and skills come from the same release. ## Scope ### In scope -- `shade-kit integrations install --agent claude`. -- `shade-kit integrations update`. -- Where the integration content comes from and how its version is recorded. +- `shade-kit integrations install [--agent claude] [--json]`. +- `shade-kit integrations update [--json]`. +- Where the integration content comes from, and how the engine picks its version. - Reporting installed integrations in `shade-kit version --json` (announced in package 01). +- The plugin manifests in `.claude-plugin/`. +- Removing the source comments of the skill skeletons, the guard test of FP07-AC7, and the kit version guard of FP07-AC2 (since 2026-11-14). ### Out of scope @@ -26,42 +28,257 @@ A developer installs the kit's skills and agents for Claude Code with one comman - Hooks and MCP configuration. The concept lists them as possible integration content, but no v1 feature needs them (approval enforcement and the MCP server are later). **Decided** (confirmation list, 2026-10-18). - Writing anything into a repository (concept §9.6, **Decided**). - Removing an integration. `integrations uninstall` is a later addition. **Proposed.** +- Installing with a scope other than `user`, and enabling a disabled plugin. +- Writing `metadata.version` into the skills for a release; it is raised by hand, and since 2026-11-14 a guard test checks it ([Kit version guard](#kit-version-guard), 06-2, 19). ## Functional description ### Content source -- The integration content (skills from package 06 and the phase packages, research agent definitions) is packed into the engine release, so an engine always installs exactly the content of its own version. **Decided** (confirmation list, 2026-10-18). This makes "plugin and CLI release together" (concept §9.6) hold by construction on every machine. +- This repository is the Claude Code plugin marketplace `creativecoders-shade-kit` with one plugin, `shade-kit`. The plugin id is `shade-kit@creativecoders-shade-kit`. **Decided** on 2026-11-13 (package 07 implementation). **Implemented** (`.claude-plugin/marketplace.json`, `.claude-plugin/plugin.json`, `ClaudeCodeIntegration.MarketplaceName`, `ClaudeCodeIntegration.PluginId`). + - `marketplace.json` names the plugin with the source `./`, the repository root. The skills stay in `skills/`, where Claude Code finds them at the plugin root. **FACT** (smoke check below: the session lists `shade-kit:shade-kit-next-phase`). + - Rule: because the plugin root is the repository root, every plugin component that Claude Code finds at its default location in the repository root ships to every user. **Decided** on 2026-11-14 (package 07 review rework, Gate 5, finding S7; documentation only, no guard test). The default locations are `skills/`, `commands/`, `agents/`, `hooks/hooks.json`, `.mcp.json`, `.lsp.json`, `output-styles/`, `workflows/`, `themes/`, `monitors/monitors.json`, and `bin/`. **FACT** (Claude Code plugin manifest reference, "Standard layout", code.claude.com/docs/en/plugins-reference, read on 2026-11-14; it also says that claude.ai and Cowork do not install a plugin with `bin/`). So a developer-only `.mcp.json`, `hooks/`, `agents/`, or `commands/` must not be added at the repository root; the planned research agent definitions are the one intended use of `agents/`. **FACT** (`ls -a` of the repository root on 2026-11-14): today only `skills/` and `.claude-plugin/` of these exist. A `CLAUDE.md` at the plugin root is not loaded as context, and `claude plugin validate` warns about it (same documentation; seen in the review run of `claude plugin validate .`). + - `plugin.json` holds name, description, author, homepage, repository, license (`Apache-2.0`), and keywords. It has **no** `version` field. **Decided** on 2026-11-13 (package 07 implementation). Without it, Claude Code uses the 12-character commit SHA as the plugin version. **FACT** (Claude Code 2.1.323: `claude plugin list --json` reported `f35fdf204ffd`). The kit version comes from the tag (Version pin), so no second version is kept by hand. + - The names are allowed. **FACT** (Claude Code documentation, checked on 2026-11-13): plugin and marketplace names must not start with `claude-`, `anthropic-`, or `cc-plugin-`, and `skills-dir`, `github`, `gh`, `builtin`, `inline`, and `npm` are reserved marketplace names. +- The engine contains and copies **no** integration content. It only runs the plugin commands of the Claude Code CLI `claude`, and Claude Code fetches the content from the marketplace. **Decided** on 2026-11-13 (package 07 implementation). This replaces the decision of 2026-10-18 (confirmation list) that the integration content is packed into the engine release. Concept §3.1, §3.4, §9.6 and package 19 are updated. +- "Plugin and CLI release together" (concept §9.6) now holds through the tag: the release tag `v` that builds the engine also names the tree that Claude Code installs. -### `integrations install --agent claude` +### Version pin -- Installs the content at **user level** as a Claude Code plugin. **Decided** (concept §3.1). -- **Unverified:** the exact way to register a plugin at user level from a CLI (for example a local plugin marketplace plus a plugin install command, or writing to the user's plugin directory). This has to be checked against the Claude Code documentation before the package is built. If no supported way exists, the fallback is writing the same content to the user's `~/.claude/` skills and agents directories. **Decided** as the general fallback in the concept §3.1. -- Records the installed agent, kit version, and install location in an engine-owned file in the user's configuration directory (`schemaVersion` like every kit JSON file). **Proposed.** This file is outside every repository, so `upgrade` (package 18) does not touch it; `integrations install` and `integrations update` migrate it when its format is older. -- Running it again for an installed agent behaves like `integrations update`. -- Without `--agent`, it installs for every supported agent the engine can detect on the machine and reports what it found. **Proposed.** In this package, Claude Code is the only supported agent. +The engine picks the marketplace source from its own version. **Decided** on 2026-11-13 (package 07 implementation; the release-tag check on 2026-11-13, Gate 4). **Implemented** (`IntegrationService.ResolveSourceAsync`, `MarketplaceSource`; `IntegrationServiceTests`, `MarketplaceSourceTests`). -### `integrations update` +| Engine | Marketplace source | Warning | +|---|---|---| +| Release, for example `0.8.0`, whose tag exists or cannot be checked | `CreativeCodersTeam/shade-kit#v0.8.0` (the engine version without build metadata) | none | +| Release whose tag does not exist, for example `0.8.1` built from an untagged `main` commit | `CreativeCodersTeam/shade-kit#main` | `integration-release-tag-missing` | +| Prerelease, for example `0.8.1-claude-code-integration.0` | `CreativeCodersTeam/shade-kit#main` | `integration-prerelease-ref` | +| Any, with `SHADE_KIT_MARKETPLACE_SOURCE` set | the value of the variable | none | -- Updates every installed integration to the content of the running engine version. -- Reports per agent: old version, new version, or "already current". -- Does not touch agents that are not installed. +- The ref is a tag or a branch. Claude Code rejects a commit SHA as ref ("Remote branch not found"). **FACT** (Claude Code 2.1.323). +- Prerelease warning: `The engine {engine} is a prerelease, so the integrations come from the branch 'main' of CreativeCodersTeam/shade-kit instead of a release tag; they may not fit this engine.` **Implemented** (`IntegrationPrereleaseRefWarning`, `CliErrorMapper.MapWarning`). +- The branch `main` of both fallbacks is `IntegrationService.FallbackRef`. **Implemented.** +- The kit version that the engine reports is the tag without the `v` (`v0.8.0` → `0.8.0`). For `main`, any ref that is not `v`, and a local directory it is `null`. **Implemented** (`MarketplaceSource.KitVersion`). +- **Developer option** `SHADE_KIT_MARKETPLACE_SOURCE`: the environment variable replaces the whole source, for example the path of a working tree of this repository, or `owner/repo#ref`. It is meant for developing the kit, not for teams. **Decided** on 2026-11-13 (package 07 implementation). **Implemented** (`IntegrationService.MarketplaceSourceVariableName`, `MarketplaceSource.Parse`). + - A value whose part before the first `#` is not a fully qualified path, does not start with `.` or `~`, has exactly one `/`, and no `\` is a GitHub repository `owner/repo[#ref]`; the ref may contain `/`. Every other value is a local directory. A relative path is made absolute against the current directory; a relative path with one `/` is written as `./dir/sub`. `~` is not expanded. + - A URL is refused. **Decided** on 2026-11-14 (package 07 review rework, Gate 5, finding M5). **Implemented** (`MarketplaceSource.Parse`; `MarketplaceSourceTests.Parse_UrlWithScheme_ThrowsInvalidMarketplaceSourceExceptionNamingGitHubForm`, `MarketplaceSourceTests.Parse_ScpLikeGitUrl_ThrowsInvalidMarketplaceSourceExceptionNamingGitHubForm`, `IntegrationsCommandsEndToEndTests.IntegrationsInstall_UrlAsMarketplaceSourceOverride_Exits2NamingAllowedFormsWithoutClaudeCall`). Before, a URL was taken as a relative directory and failed later in `claude` with 52. The check runs after the empty and `-` checks and before the GitHub form: + - A value that starts with a scheme of at least two characters and `://` (`https://`, `http://`, `ssh://`, `git://`, `git+ssh://`, `file://`, any letter case). Reason: `It is a URL, and SHADE kit takes no URL as a marketplace source; a GitHub repository is written as owner/repo#ref or owner/repo.` + - An scp-like git URL, by git's rule: the first `:` comes after at least two characters without `/` or `\` (`git@github.com:owner/repo`, `user@host:path`, also `github.com:owner/repo`). Reason: `It is an scp-like git URL (user@host:path), and SHADE kit takes no URL as a marketplace source; a GitHub repository is written as owner/repo#ref or owner/repo.` + - A Windows drive path has a single letter before the `:` and is no URL: `C:\kit`, `C:/kit`, and `C://kit` are fully qualified directory paths on Windows (`MarketplaceSourceTests.Parse_WindowsDrivePathOnWindows_ReturnsDirectorySource`, run only on Windows). Known limit on Linux and macOS: `C:/kit` is read as a malformed GitHub form (exit code 2), and `C:\kit` and `C://kit` as relative paths. A separator before the `:` keeps a value a path (`./git@host:y`, `/x/git@host:y`, `./mirror/https://x`). + - An empty value, a value that starts with `-`, a URL, or a malformed GitHub form ends with exit code 2 `invalid-arguments` before `claude` runs: `The environment variable SHADE_KIT_MARKETPLACE_SOURCE is set to '{value}', which is not a marketplace source: {reason} Set it to owner/repo#ref, owner/repo, or the path of a local directory, or remove it, then run the command again.` + - `version` ignores the variable. + +### Release-tag check + +- Why: `GitVersion.yml` gives `main` no prerelease label (`label: ''`), so a build of an untagged `main` commit is a release version, for example `0.8.1`, whose tag `v0.8.1` does not exist. **FACT** (`GitVersion.yml`). Without a check, such an engine would target the missing tag and `claude plugin marketplace add` would fail with exit code 52. +- A release engine without `SHADE_KIT_MARKETPLACE_SOURCE` checks that its tag exists in the marketplace repository before it installs or updates. **Decided** on 2026-11-13 (package 07 implementation, Gate 4). **Implemented** (`IGitRemoteTagChecker`, `GitRemoteTagChecker`, `IntegrationService.MarketplaceRepositoryUrl`; `GitRemoteTagCheckerTests`, `IntegrationServiceTests.ResolveSourceAsync_ReleaseTag*`, `IntegrationsCommandsEndToEndTests.IntegrationsInstall_ReleaseTag*`, `IntegrationsCommandsEndToEndTests.IntegrationsUpdate_PlainModeReleaseTagMissing_WritesWarningAndUpdatesFromMain`). + - The check runs, through `IGitCommandRunner`, `git -c credential.helper= -c protocol.allow=never -c protocol.https.allow=always ls-remote --tags https://github.com/CreativeCodersTeam/shade-kit.git refs/tags/v`. `git` runs in the user's home directory (the temporary directory if there is none; `UserWorkingDirectory`, shared with `claude`), never in the repository, so the configuration of the current repository takes no part. + - The `-c` options clear the credential helpers and allow only `https`, so a URL that the user's configuration rewrites to `ssh` (`insteadOf`) fails instead of starting `ssh`, which could ask for a passphrase. **FACT** (git 2.54, spike on 2026-11-13: `protocol.allow=never` with `protocol.https.allow=always` stops an `insteadOf` rewrite to `ssh`, "transport 'ssh' not allowed"). + - Exit code 0 with a line `\trefs/tags/v` (or its peeled line `...^{}`) → the tag exists → `#v`. + - Exit code 0 without such a line → the tag is missing → `#main` and the warning `integration-release-tag-missing`: `The release tag '{tag}' of the engine {engine} does not exist in CreativeCodersTeam/shade-kit, so the integrations come from the branch 'main' instead; they may not fit this engine.` `data.ref`, `data.source`, and the `ref` of each agent are then `main`. **Implemented** (`IntegrationReleaseTagMissingWarning`, `CliErrorMapper.MapWarning`). + - `git` not installed, `git` that cannot be started, or a non-zero exit code (no network, a remote that needs credentials) → the tag is used unchecked, with no warning and no error. If the tag is really missing, `claude` then fails with exit code 52. Cancellation still ends with 130. + - **FACT** (checked on 2026-11-13 against `CreativeCodersTeam/shade-kit`): a missing tag gives exit code 0 with empty output; `v0.8.0` was found, `v0.8.1` was not. +- The check is skipped for a prerelease engine (it uses `main` anyway) and for the override. +- Order in `install`: select the agents of `--agent` → resolve the local part of the source (an invalid override ends with exit code 2 before any agent is detected) → detect the agents (none → 51, no tag check) → `IAgentIntegration.EnsureAvailable()` for every selected or detected agent → tag check → install. `EnsureAvailable` makes `--agent claude` without `claude` end with 51 before the network call: no `git ls-remote` and no `claude` call. **Decided** on 2026-11-14 (package 07 review rework, Gate 5, finding S3). **Implemented** (`IntegrationService.InstallAsync`, `ClaudeCodeIntegration.EnsureAvailable`, which throws `ClaudeNotFoundException` naming `claude plugin list --json`, the first command of an install; `IntegrationServiceTests.InstallAsync_ExplicitAgentMissing_ThrowsItsNotFoundErrorBeforeReleaseTagCheck`, `IntegrationsCommandsEndToEndTests.IntegrationsInstall_NamedClaudeNotOnPath_WritesAgentNotFoundEnvelopeAndExits51`). In `update`, the source and the check come only after an installed integration was found (see `integrations update`). +- Only `https` URLs are accepted, and a tag name that is empty, starts with `-`, or contains whitespace, a glob character, `^`, `~`, or `:` is refused, so `ls-remote` matches exactly one ref. These are guards against a defect, not user input. + +### State: no engine-owned record + +- The engine keeps no record of its own. It reads the state from `claude plugin list --json` and `claude plugin marketplace list --json`. **Decided** on 2026-11-13 (package 07 implementation). This replaces the **Proposed** engine-owned record file in the user's configuration directory. **Implemented** (`ClaudeCodeIntegration.GetInstalledAsync`). +- The format id `integrations` is removed from `FormatIds` and `FormatRegistry.CreateDefault()`, so `formats` in `version --json` no longer lists it (package 01). **Implemented** (`FormatRegistryTests`). + +### How the engine runs `claude` + +- `claude` is found in an absolute directory of the `PATH`: `claude`, on Windows only `claude.exe` (the native installer). The `claude.cmd` of an npm installation is not found. **Implemented** (`ClaudeExecutableLocator` on `PathExecutableLocator`). +- It is started through the process helpers like `git` and `gh`: absolute path, no shell, process tree killed on cancellation (exit code 130). It runs with `NO_COLOR=1` in the user's home directory (the temporary directory if there is none), never in the repository. Every call passes `--json`. The list commands (`plugin list`, `plugin marketplace list`) parse the whole stdout as one JSON array; a stray line on stdout makes `install` and `update` fail with 52, and in `version` the same failure becomes the warning `agent-unavailable` (Version reporting). The commands that change the configuration (`marketplace add`, `remove`, `update`, `plugin install`, `update`) read the last line of stdout that is a JSON object, because `claude` may print other lines before it. On a non-zero exit code the last JSON object line gives claude's `message` and `failureCode`. **Decided** on 2026-11-14 (package 07 review rework, Gate 5, finding M4: the code is kept, the text corrected; until then this text said that every call reads the last JSON line). **Implemented** (`ClaudeCommandRunner`, `ClaudePluginCli`, `ClaudeJsonOutputReader.ReadArray`, `ClaudeJsonOutputReader.ReadResultObject`). +- Claude Code commands and outputs the engine relies on. **FACT** (Claude Code 2.1.323, spikes in an isolated `CLAUDE_CONFIG_DIR`, 2026-11-13): + + | Command | Output | + |---|---| + | `claude plugin marketplace add --scope user --json` | One JSON line, `outcome` `ok`. Again with the same source: `ok`, the message says it is already on disk. Sources: `owner/repo#` or a local path. | + | `claude plugin marketplace list --json` | Array of `{name, source, repo, ref, installLocation}`; `source` is `github`, or `directory` with a `path`. | + | `claude plugin marketplace remove --json` | `outcome` `ok`. It also **uninstalls every plugin of that marketplace**; `plugin list` is then `[]`. | + | `claude plugin marketplace update --json` | One JSON line, `outcome` `ok`, exit code 0; the clone is refreshed at once (branch, tag, and directory marketplaces). An unknown name: exit code 1, `outcome` `failed`, `failureCode` `not_configured`. Checked on 2026-11-14 (see below). | + | `claude plugin install @ --scope user --json` | `outcome` `ok`; for an installed plugin also `ok`, with `installedVersion` and `availableVersion`. | + | `claude plugin update @ --scope user --json` | `outcome` `ok` with `updateOutcome` `updated` (`oldVersion`, `newVersion`) or `up_to_date`. | + | `claude plugin list --json` | Array of `{id, version, scope, enabled, installPath, installedAt, lastUpdated, projectEnabled}`. | + | Any failure | Exit code 1 and a JSON line with `outcome` `failed`, `message`, and `failureCode` (for example `not_found`). | + +- Refresh of a kept marketplace. **FACT** (Claude Code 2.1.323, spike on 2026-11-14 in an isolated `CLAUDE_CONFIG_DIR`; a local bare git repository served as `https://spike.example.invalid/spike/remote.git#main` through a `url.insteadOf` rewrite in an isolated `GIT_CONFIG_GLOBAL`; plugin without `version`): + - `claude plugin update` alone is not reliable for a marketplace that follows a branch. It refreshed the marketplace once (a pushed commit gave `updated`), but a commit pushed about 10 seconds after that refresh was not seen: `up_to_date` twice, and the clone stayed at the old commit. The documentation says that install skips the refresh "within the last 30 seconds". Without an explicit refresh, `current` could be wrong. + - `claude plugin marketplace update --json` refreshed at once, and the following `plugin update` reported `updated` to the new commit. + - `claude plugin marketplace add` accepts only `owner/repo`, `https://...`, or a path (`Invalid marketplace source format. Try: owner/repo, https://..., or ./path` for `file://`, `git://`, `ssh://`). + - The documentation agrees (code.claude.com/docs/en/plugins/cli-reference.md, read on 2026-11-14): "Refresh one marketplace … A marketplace added with a branch or tag ref updates to the latest commit of that ref"; `--json` needs a marketplace name and Claude Code 2.1.287 or later. + - **Unverified:** the GitHub fetch path itself. The spike marketplace had the source kind `git`, not `github`; the same clone and refresh code is presumed. + +### `integrations install [--agent claude] [--json]` + +- Installs the plugin for the user (scope `user`) in Claude Code. **Decided** (concept §3.1). **Implemented** (`IntegrationsInstallCommand`, `IntegrationService.InstallAsync`, `ClaudeCodeIntegration.InstallAsync`). +- Without `--agent`, it installs for every detected agent. Claude Code is detected by `claude` on the `PATH`. No detected agent ends with exit code 51. **Decided** on 2026-11-13 (package 07 implementation). +- `--agent claude` without `claude` on the `PATH` ends with 51 before the release-tag check (Release-tag check, order). +- `--agent` takes a supported agent id, case-insensitive (today only `claude`). An unknown id or a bare `--agent` ends with exit code 2 `invalid-arguments` before the command runs. **Implemented** (`AgentOptionConverter`, `InvalidAgentOptionException`, `CliErrorMapper.MapArgumentError`): + - `Invalid arguments: 'copilot' is not a supported agent for --agent (supported: claude). Run 'shade-kit integrations install --help' for usage.` + - `Invalid arguments: --agent needs the id of a supported agent (claude), but got none. Run 'shade-kit integrations install --help' for usage.` +- Steps for Claude Code. **Decided** on 2026-11-13 (package 07 implementation). **Implemented** (`ClaudeCodeIntegration`; `ClaudeCodeIntegrationTests`): + 1. `plugin list` reads whether `shade-kit@creativecoders-shade-kit` is installed with the scope `user`. + 2. `marketplace list` reads the marketplace `creativecoders-shade-kit`: + - missing → `marketplace add --scope user`; + - same repository (case-insensitive) and same ref (case-sensitive), or the same directory → kept, and refreshed with `marketplace update creativecoders-shade-kit` (step 3); + - same repository, other ref → `marketplace remove`, then `marketplace add` (the switch). A marketplace without a ref (the default branch) has another ref than every source with a ref; + - another repository, another kind of source, or another directory → exit code 53 `integration-conflict`, nothing is changed. + + Two directories are the same when their paths, with every symbolic link resolved to its final target, are equal: case-insensitively on Windows and macOS, case-sensitively on Linux and every other system. **Decided** on 2026-11-14 (package 07 review rework, Gate 5, finding S2; before, the paths were compared ordinally, so `/tmp/x` and `/private/tmp/x` were a conflict). **Implemented** (`DirectoryPathComparer`, `ClaudeCodeIntegration`; `DirectoryPathComparerTests`, `ClaudeCodeIntegrationTests.InstallAsync_DirectoryMarketplaceThroughSymbolicLink_KeepsMarketplace`, `InstallAsync_SourceThroughSymbolicLinkInParentDirectory_KeepsMarketplace`, `InstallAsync_SymbolicLinkToOtherDirectory_ThrowsConflict`, `InstallAsync_DirectoryInOtherCaseAndCaseInsensitiveComparer_KeepsMarketplace`, `InstallAsync_DirectoryInOtherCaseAndCaseSensitiveComparer_ThrowsConflict`): + - A path is resolved segment by segment, as `realpath` does: a segment that is a link is replaced by its target (a relative target is combined with the resolved parent) and resolved again, so a link in a parent directory counts too. The `..` segments of the path itself are removed first, lexically, as for the source text passed to `claude`. At most 40 links are followed. + - A path that does not exist (a link loop included), whose links cannot be read, or with more than 40 links is compared in its normalized form without link resolution. A relative path reported by `claude` stays a conflict. + - The source text passed to `claude` and reported in `source` is not resolved. + - **FACT** (macOS, .NET 10, spike and tests on 2026-11-14): `/tmp`, `/var`, and `/etc` are links to `private/tmp`, `private/var`, and `private/etc`; `Path.GetFullPath("/tmp/x")` stays `/tmp/x`, and `Directory.ResolveLinkTarget("/tmp/x", true)` is `null`, because only the last segment is looked at; `DirectoryInfo("/TMP").LinkTarget` is `private/tmp` (case-insensitive APFS); `Path.GetTempPath()` is below `/var/folders/`, so a temporary directory resolves to a path below `/private/var/` (`DirectoryPathComparerTests.ResolvePath_MacOSTempDirectoryBelowVar_ReturnsPathBelowPrivateVar`). + - **Unverified:** Windows junction targets and UNC roots; they are not tested. + 3. A kept marketplace is refreshed with `marketplace update creativecoders-shade-kit` (GitHub tag, branch, or directory), before `plugin install` or `plugin update`, so that `current` means that the content really is current. It is not run after an add or a switch, which fetch the content anyway. A failure of the refresh ends with 52 and nothing changed. **Decided** on 2026-11-14 (package 07 review rework, Gate 5, finding M3: `plugin update` alone does not refresh reliably, **FACT** above). **Implemented** (`IClaudePluginCli.UpdateMarketplaceAsync`, `ClaudeCodeIntegration`; `ClaudeCodeIntegrationTests.InstallAsync_KeptBranchMarketplace_RefreshesMarketplaceBeforePluginUpdate`, `InstallAsync_KeptDirectoryMarketplace_RefreshesMarketplaceBeforePluginUpdate`, `InstallAsync_MarketplaceSwitchedOrAdded_DoesNotRefreshMarketplace`, `InstallAsync_MarketplaceRefreshFails_ThrowsCauseUnwrappedWithoutPluginChange`, `IntegrationsCommandsEndToEndTests.IntegrationsUpdate_BranchMarketplaceWithNewCommits_RefreshesMarketplaceAndReportsUpdated`). + 4. After a change of the marketplace (add or switch), `plugin list` again. A plugin that is not installed is installed (`plugin install`, then `plugin list` for `enabled`); otherwise it is updated (`plugin update`). +- The `claude` calls of an `install` per case: + - kept marketplace, plugin installed: `plugin list`, `plugin marketplace list`, `plugin marketplace update creativecoders-shade-kit`, `plugin update`; + - kept marketplace, plugin missing: `plugin list`, `plugin marketplace list`, `plugin marketplace update creativecoders-shade-kit`, `plugin install`, `plugin list`; + - marketplace missing: `plugin list`, `plugin marketplace list`, `plugin marketplace add`, `plugin list`, then `plugin install` and `plugin list`, or `plugin update`; + - switch: `plugin list`, `plugin marketplace list`, `plugin marketplace remove`, `plugin marketplace add`, `plugin list`, then `plugin install` and `plugin list` (the removal uninstalled the plugin), or `plugin update`. +- Run again for an installed agent, it behaves like `integrations update`. +- Outcome per agent: `installed` if the plugin was not installed before the run; `current` if the marketplace was kept (and refreshed) and `plugin update` reported `up_to_date`; `updated` otherwise. The ref switch counts as `updated`, although Claude Code removes and installs the plugin again, because `marketplace remove` uninstalls it (**FACT** above). `previousKitVersion` is set only when the plugin was installed before the run, from the ref of the marketplace before the run. +- A disabled plugin is updated, not enabled; `enabled` is `false` in the result. +- No rollback. Every step can be repeated. A failure after the old marketplace was removed keeps the exit code and message of the cause and adds `The plugin marketplace of SHADE kit was already switched, so the integration may be incomplete; 'shade-kit integrations install' repairs it.` The hint names `install`, not `update`, because the removed marketplace took the plugin with it, so `update` would find nothing installed. **Decided** on 2026-11-13 (package 07 implementation, after the spike). **Implemented** (`IntegrationIncompleteException`, `CliErrorMapper`). +- A cancellation (Ctrl+C) from the `marketplace remove` of a switch on, the removal included because the killed `claude` may already have removed the marketplace, still ends with exit code 130 and the error code `canceled`, with the message `The command was canceled while the plugin marketplace of SHADE kit was switched for the agent '{agent}', so the integration may be incomplete; 'shade-kit integrations install' repairs it.` In JSON mode it is the failure envelope with `canceled`. A cancellation while the marketplace is kept or added, or an `OperationCanceledException` without a canceled run token, stays the plain cancellation. **Decided** on 2026-11-14 (package 07 review rework, Gate 5, finding S1). **Implemented** (`IntegrationSwitchCanceledException`, which derives from `OperationCanceledException`; mapped in `CliErrorMapper.Map`, so the command maps it like any core failure and `CliErrorMapper.MapCancellation` and `Program` are unchanged; `ClaudeCodeIntegrationTests.InstallAsync_CanceledWhileMarketplaceIsRemoved_ThrowsSwitchCanceled`, `InstallAsync_CanceledWhileKeptMarketplaceIsRefreshed_PropagatesCancellationUnwrapped`, `CliErrorMapperTests.Map_IntegrationSwitchCanceled_ReturnsExitCode130WithRepairHint`, `IntegrationsInstallCommandTests.ExecuteAsync_JsonModeCanceledDuringMarketplaceSwitch_WritesCanceledEnvelopeWithRepairHint`). +- The command needs no git repository and writes nothing into one (FP07-AC5). **Implemented** (`ShadeKitCommandContext.RunAsync` without the kit store). + +### `integrations update [--json]` + +- Updates every agent whose plugin is installed with the scope `user` to the source of the running engine, with the same steps as `install`. **Implemented** (`IntegrationsUpdateCommand`, `IntegrationService.UpdateAsync`, `ClaudeCodeIntegration.UpdateAsync`). +- Does not touch agents that are not installed. A plugin installed with another scope counts as not installed. +- Order: detect the agents (none → 51), then for each detected agent in registration order: the agent lists its plugins; not installed → nothing is done and no source is resolved; installed → the source is resolved (with the release-tag check) and the agent is updated with the steps of `install`. The source is resolved once per run, by the first agent that has the integration installed, before that agent changes anything; later agents get the same source. A failure while reading what is installed (for example 52) ends the command. **Decided** on 2026-11-13 (package 07 implementation, Gate 4); the reading changed on 2026-11-14 (package 07 review rework, Gate 5, finding S4): before, `update` first asked every agent what is installed (`plugin list`, `marketplace list`) and then let the agent list both again. **Implemented** (`IntegrationService.UpdateAsync`, `IAgentIntegration.UpdateAsync(getSource, cancellationToken)` with `getSource` a `Func>` that `IntegrationService` memoizes; `ClaudeCodeIntegrationTests.UpdateAsync_KeptMarketplace_ListsPluginsAndMarketplacesOnceEach`, `ClaudeCodeIntegrationTests.UpdateAsync_PluginInstalledWithOtherRef_ListsPluginsTwiceAndMarketplacesOnceWithoutRefresh`, `IntegrationServiceTests.UpdateAsync_SeveralInstalledAgents_UpdatesAllFromSourceResolvedOnceInRegistrationOrder`, `IntegrationsCommandsEndToEndTests.IntegrationsUpdate_KeptMarketplace_ReadsPluginsAndMarketplacesOnceAndRefreshesMarketplace`). + - The `claude` calls of an `update` with a kept marketplace: `plugin list`, `plugin marketplace list`, `plugin marketplace update creativecoders-shade-kit`, `plugin update`. With a switch: `plugin list`, `plugin marketplace list`, `plugin marketplace remove`, `plugin marketplace add`, `plugin list`, then `plugin install` and `plugin list`. + - Changed order for several agents: agent 1 is updated before the `plugin list` of agent 2 runs; before 2026-11-14 all reads came first. Today only Claude Code is registered, so this has no effect yet (08). + - `version` still reads the installed integrations with `IntegrationService.GetInstalledAsync` (Version reporting). +- Nothing installed: an empty `integrations` list, `ref` and `source` `null`, the plain text `No SHADE kit integration is installed.` and `Run 'shade-kit integrations install' to install it.`, exit code 0 (FP07-AC6). No source is resolved, so there is no tag check, no `integration-prerelease-ref` or `integration-release-tag-missing` warning, and an invalid `SHADE_KIT_MARKETPLACE_SOURCE` is not reported. **Decided** on 2026-11-13 (package 07 implementation, Gate 4). **Implemented** (`IntegrationServiceTests.UpdateAsync_NothingInstalled_*`, `IntegrationsCommandsEndToEndTests.IntegrationsUpdate_NothingInstalled_ChecksNoTagAndWritesNoSourceWarning`). +- `claude` not on the `PATH`: exit code 51, an error, not a warning. **Decided** on 2026-11-13 (package 07 implementation). + +### Several agents + +- `install` and `update` run the agents one after the other. When an agent fails after at least one agent was already installed or updated, the command keeps the exit code, error code, and message of the failure and adds which integrations were done, as plain text in the line format of the output: ` Before the agent '{agent}' failed, these integrations were done: claude: installed shade-kit@creativecoders-shade-kit 0.8.0 (v0.8.0); ….` **Decided** on 2026-11-14 (package 07 review rework, Gate 5, finding S5: a message, no change of the JSON contract). **Implemented** (`IntegrationRunFailedException`, `CliErrorMapper.CreateIntegrationRunFailedError`, `IntegrationsTextFormat.FormatResult`; `IntegrationServiceTests.InstallAsync_SecondAgentFails_ThrowsRunFailedWithResultOfFirstAgent`, `IntegrationServiceTests.UpdateAsync_SecondAgentUpdateFails_ThrowsRunFailedWithResultOfFirstAgent`, `CliErrorMapperTests.Map_IntegrationRunFailedWithCommandFailure_KeepsExitCodeAndMessageAndNamesCompletedAgents`, `IntegrationsInstallCommandTests.ExecuteAsync_JsonModeSecondAgentFailed_WritesFailureEnvelopeNamingCompletedAgents`). + - Wrapped are only the documented agent failures (an unavailable or failing agent CLI, `integration-conflict`, an incomplete switch); the repair hint of an incomplete switch comes before the sentence. A failure of the first agent, a cancellation (also during a switch), and an unexpected exception are reported unchanged. + - The JSON failure envelope is unchanged: `data` is `null`, and `error` holds only `code` (the code of the failure, so skills react as before) and `message`. Rejected: `data` on failure (the agent contract of package 01 says `data` is `null` on failure) and warnings on failure (the command context writes none on failure; more invasive). + - Known limit, older than this rework: the warnings of a failed run (`integration-prerelease-ref`, `integration-release-tag-missing`) are not reported. + - Today only Claude Code is registered, so a second agent comes with package 08. + +### Output of `install` and `update` + +JSON `data`, the same shape for both commands. **Implemented** (`IntegrationRunData`, `IntegrationResultData`): + +```json +{ + "ref": "v0.8.0", + "source": "CreativeCodersTeam/shade-kit#v0.8.0", + "integrations": [ + { "agent": "claude", "pluginId": "shade-kit@creativecoders-shade-kit", "outcome": "updated", + "previousKitVersion": "0.7.0", "kitVersion": "0.8.0", "ref": "v0.8.0", "enabled": true } + ] +} +``` + +- `ref` at the top is the ref the engine targets; `source` the text passed to `claude plugin marketplace add`. For a directory override, `source` is the absolute path and `ref` is `null`. For `update` with nothing installed, both are `null`. Per agent, `ref` and `kitVersion` are those now installed. `outcome` is `installed`, `updated`, or `current`. Null values are written. + +Plain output, one line per agent, then notes. **Implemented** (`IntegrationsTextFormat`): + +```text +claude: installed shade-kit@creativecoders-shade-kit 0.8.0 (v0.8.0) +claude: updated shade-kit@creativecoders-shade-kit 0.7.0 -> 0.8.0 (v0.8.0) +claude: already current shade-kit@creativecoders-shade-kit 0.8.0 (v0.8.0) +Restart Claude Code to load the skills. +``` + +- A prerelease and a release engine whose tag is missing show `(main)`, a directory override `from `, a GitHub override without a ref `(default branch)`. +- A disabled plugin adds ` The plugin is disabled in Claude Code. Run 'claude plugin enable shade-kit@creativecoders-shade-kit' to enable it.` +- `Restart Claude Code to load the skills.` (muted) appears when a Claude Code result is not `current`. +- Warnings come first as `Warning: `, like for every command. ### Version reporting -`shade-kit version --json` adds the installed integrations with agent and kit version. A skill or a human can then see at once whether engine and integration differ. **Proposed.** +- `shade-kit version --json` has an always-present field `integrations`, after `expectedVersion`: `[ { "agent": "claude", "pluginId": "shade-kit@creativecoders-shade-kit", "kitVersion": "0.8.0", "ref": "v0.8.0", "enabled": true } ]`, empty when nothing is installed. **Decided** on 2026-11-13 (package 07 implementation). **Implemented** (`VersionCommandData.Integrations`, `VersionCommandIntegrationData`, `IntegrationService.GetInstalledAsync`). +- Plain output: the line `shade-kit ` as before, then one line per installed integration, `claude: shade-kit@creativecoders-shade-kit 0.8.0 (v0.8.0)`, with `(disabled)` for a disabled plugin. +- The integrations are read only after a successful `--expect` check; a mismatch still exits with 50 and starts no `claude`. +- `version` asks only the agents whose CLI is detected (`IAgentIntegration.IsAvailable()`). **Decided** on 2026-11-13 (package 07 implementation, Gate 4). **Implemented** (`IntegrationService.GetInstalledAsync`). +- `version` never fails because of an agent. A missing `claude` gives no warning and an empty `integrations` list. **FACT** (real `version --json` with `PATH=/usr/bin:/bin`: `warnings` `[]`, 2026-11-13). Only a `claude` that is on the `PATH` but cannot be started or fails gives the warning `agent-unavailable`: `The SHADE kit integration of the agent '{agent}' cannot be read, so it is not listed: {reason}`. **Implemented** (`AgentUnavailableWarning`, `CliErrorMapper.MapWarning`; `IntegrationsCommandsEndToEndTests.Version_ClaudeNotOnPath_SucceedsWithEmptyIntegrationsAndNoWarning`, `IntegrationsCommandsEndToEndTests.Version_ClaudeOnPathFails_SucceedsWithEmptyIntegrationsAndAgentUnavailableWarning`). +- Known cost: with `claude` on the `PATH`, every `version` call starts `claude` once or twice (`plugin list`, and `marketplace list` when the plugin is installed), also in each skill handshake. **FACT** (measured on 2026-11-13): `version --json --expect` took 0.73 s with `claude` on the `PATH` and 0.08 s without. +- `kitVersion` and `ref` are `null` for a directory marketplace and for any ref that is not `v`. + +### Exit, error, and warning codes + +In the range 50–59 (06-1). **Decided** on 2026-11-13 (package 07 implementation). **Implemented** (`ShadeKitCliExitCodes`, `ShadeKitCliErrorCodes`, `ShadeKitCliWarningCodes`, `CliErrorMapper`). + +| Code | Error code | When | +|---|---|---| +| 51 | `agent-not-found` | No supported agent detected (`install` without `--agent`, `update`), or the CLI of an agent that the command needs is not on the `PATH` (for Claude Code `claude`), also for an agent named with `--agent`, which is checked before the release tag. The message says that on Windows only the `claude.exe` of the native installer is found. | +| 52 | `agent-command-failed` | `claude` cannot be started, exits with a non-zero code, reports `outcome` `failed`, or prints no JSON the engine can read. The message names the `claude` command and the reason, with claude's message and `failureCode`. | +| 53 | `integration-conflict` | The marketplace `creativecoders-shade-kit` already exists with another source repository, kind, or directory. Nothing is changed. The message names both sources and `claude plugin marketplace remove creativecoders-shade-kit`. | + +The XML documentation of `ShadeKitCliExitCodes.AgentNotFound` names both cases of 51 since 2026-11-14 (review finding N1). Outside the range: 2 `invalid-arguments` for an invalid `--agent` or `SHADE_KIT_MARKETPLACE_SOURCE`, and 130 `canceled`, since 2026-11-14 with the repair hint for a cancellation during a switch. + +Warnings: `integration-prerelease-ref` (prerelease engine installs from `main`), `integration-release-tag-missing` (the release tag of a release engine does not exist, so it installs from `main`), and `agent-unavailable` (`version` cannot read an agent whose CLI is detected). + +### Skill names in Claude Code + +- Plugin skills are namespaced as `/:` (Claude Code documentation). The skill texts stay agent-neutral and keep the bare names (`/shade-kit-`, "load `shade-kit-next-steps`"). **Decided** on 2026-11-13 (package 07 implementation). No skill text changed in this package except the removed source comments. +- Smoke check on 2026-11-13, Claude Code 2.1.323, headless `claude -p` with the plugin loaded by `--plugin-dir `, `--setting-sources project`, in a scratch directory: + - The model's skill listing shows the namespaced name `shade-kit:shade-kit-next-phase`. **FACT.** + - Both `/shade-kit-next-phase` and `/shade-kit:shade-kit-next-phase` expand the skill: the session started its version handshake (`--expect 0.7.0`, the kit version of the skills then; `0.8.0` since 2026-11-14) without a Skill tool call. **FACT.** + - A skill text that says "load `shade-kit-next-steps`" works: the model called the Skill tool with `shade-kit:shade-kit-next-steps`. **FACT.** + - Limits: one run per form, headless print mode, plugin loaded with `--plugin-dir`, not from the marketplace install (the same plugin loader). The interactive slash menu is **Unverified**. + +### Skeleton source comments + +- The repository is now the shipped plugin, so the source comments `` are removed from the 13 skeletons that had them (`diagnose`, `discuss`, `drop`, `finish`, `implement`, `map`, `new`, `plan`, `quick`, `refine`, `report`, `review`, `verify`). **Decided** on 2026-11-13 (package 07 implementation). **Implemented.** +- A guard test fails when any text file under `skills/` has a path segment `docs/` or `research/` (any letter case, `/` or `\`, also inside a URL or `.shadekit/research/`, on purpose). Since 2026-11-14 it scans every text file under `skills/`, not only `SKILL.md`, because the plugin ships everything there, bundled files such as `references/*.md` included. A text file is a file whose first 8000 bytes contain no NUL byte (git's rule); binary files are skipped, and a text file that is not valid UTF-8 fails the test. **Decided** on 2026-11-14 (package 07 review rework, Gate 5, finding S6). **Implemented** (`ShippedSkillsTests` and the helper `ShippedSkillFiles` in `CreativeCoders.ShadeKit.Core.Tests/Skills/`). + +### Kit version guard + +- A guard test ties the kit version of the skills to the engine version of the build. **Decided** on 2026-11-14 (package 07 review rework, Gate 5, review finding Major: a release engine installs the skills of its own tag, and if they carry another major.minor, every handshake fails with 50 and the hint `shade-kit integrations install` installs the same skills again). **Implemented** (`SkillKitVersionTests.SkillFiles_ShippedSkills_CarryOneKitVersionThatMatchesTheEngineMajorMinor`, `[Trait("Requirement", "FP07-AC2")]`, in `CreativeCoders.ShadeKit.Core.Tests/Skills/`). It fails, listing every violation as `:: expected …, found …`, unless: + - every `skills/**/SKILL.md` has a frontmatter with `metadata:` and a direct child `version: `, where `` is a plain, unquoted `x.y.z` (no prerelease, no build metadata); + - all skills carry the same value; + - its major.minor equals the major.minor of the engine version of the build (`EngineVersionProvider`, the informational version from GitVersion; patch and prerelease of the engine are ignored); + - every `--expect ` (or `--expect=`) and every "`` is the kit version of this skill" in any text file under `skills/` names that version, also when it is wrapped across lines; a placeholder such as `--expect ` counts as a violation. +- The reference value of "the same value" is the most frequent valid version among the skills; on a tie, the version with the major.minor of the engine wins, then the version of the first skill in ordinal path order. A skill that differs from that version is reported as `expected metadata.version (the kit version of ), found `, where `` is the first skill in path order with the reference version, and the handshake texts are checked against it. So a single outlier skill is the one reported, also when it comes first in path order. **Decided** on 2026-11-15 (package 07 review rework, Gate 5 round 2, finding N6: until then the reference was the first skill with a valid version in path order, so an outlier that came first made every other skill a violation). **Implemented** (`SkillKitVersionTests.SelectKitSkill`; `SkillKitVersionTests.FindKitVersionViolations_OutlierFirstInPathOrder_ReportsOnlyTheOutlier` and the tie and invalid-version tests beside it). +- In the same rework every skill was raised to `0.8.0`, in the frontmatter and in every handshake text. **FACT** (`grep` on 2026-11-14: all 19 `skills/*/SKILL.md` carry `version: 0.8.0`, no `0.7.0` is left under `skills/`). +- The test runs in every build that runs the tests: pull requests, `main`, `feature/**`, and the release tag (19). The value is still raised by hand (06-2). ## Acceptance criteria -- **FP07-AC1** After `integrations install --agent claude`, a new Claude Code session in any repository can load `shade-kit-next-phase`. -- **FP07-AC2** The installed skills have the same kit version as the engine that installed them. -- **FP07-AC3** After an engine update, `integrations update` replaces the Claude Code content and reports old and new version. -- **FP07-AC4** `shade-kit version --json` lists the installed Claude Code integration with its kit version. -- **FP07-AC5** No file in the current repository is created or changed by `integrations install` or `integrations update`. -- **FP07-AC6** `integrations update` with no installed integration reports that nothing is installed and exits without error. -- **FP07-AC7** No skill in the integration content references a path under `research/` or `docs/` of the kit repository. Taken over from FP06-AC13 on 2026-11-04, because the rule only applies to shipped skills ([06-2 skill conventions](06-2-skill-conventions-and-version.md#skill-conventions)). +The automated tests carry `[Trait("Requirement", "FP07-ACn")]`. No test starts `claude`: they fake `IClaudeCommandRunner` and the locator (`FakeClaudeCode` simulates the plugin commands, including "marketplace remove uninstalls the plugin"). + +- **FP07-AC1** After `integrations install --agent claude`, a new Claude Code session in any repository can load `shade-kit-next-phase`. **Implemented**. The install is proven by `IntegrationsCommandsEndToEndTests.IntegrationsInstall_ClaudeWithoutIntegration_InstallsPluginFromReleaseTagOfEngine`. The session part is checked by hand only: in the smoke check `integrations install --json` installed the plugin from the working tree (`SHADE_KIT_MARKETPLACE_SOURCE`) in an isolated `CLAUDE_CONFIG_DIR`. That configuration has no login, so the session ran headless with the user's login and `--plugin-dir ` instead of the marketplace-installed copy, and loaded `shade-kit-next-phase` (Skill names in Claude Code). +- **FP07-AC2** The installed skills have the same kit version as the engine that installed them. **Implemented**. A release engine installs the tree of the tag `v`, the tree it was built from, proven by `IntegrationsCommandsEndToEndTests.IntegrationsInstall_ClaudeWithoutIntegration_InstallsPluginFromReleaseTagOfEngine`, `IntegrationsInstallCommandTests.ExecuteAsync_JsonMode_WritesEnvelopeWithTargetedSourceAndResultOfEachAgent`, and `IntegrationServiceTests.ResolveSourceAsync_*`. The kit version in that tree (`metadata.version` and every handshake text) has the major.minor of the engine version of the build, enforced by `SkillKitVersionTests.SkillFiles_ShippedSkills_CarryOneKitVersionThatMatchesTheEngineMajorMinor` since 2026-11-14 ([Kit version guard](#kit-version-guard)); the skills carry `0.8.0`. Limits: a release engine whose tag does not exist installs from `main` with the warning `integration-release-tag-missing`, so for such a build the content is that of `main`; and the guard compares major.minor, the rule of the handshake (06-1), not the patch. +- **FP07-AC3** After an engine update, `integrations update` replaces the Claude Code content and reports old and new version. **Implemented**. Proven by `IntegrationsCommandsEndToEndTests` (`IntegrationsUpdate_AfterEngineUpdate_SwitchesToNewTagAndReportsOldAndNewVersion`, `IntegrationsUpdate_PlainModeAfterEngineUpdate_WritesOldAndNewVersionAndAsksForRestart`) and `IntegrationsUpdateCommandTests`. +- **FP07-AC4** `shade-kit version --json` lists the installed Claude Code integration with its kit version. **Implemented**. Proven by `VersionCommandTests` and `IntegrationsCommandsEndToEndTests` (`Version_JsonModeWithInstalledClaudeIntegration_ListsItWithKitVersion`, `Version_AfterInstall_ListsIntegrationOfEngineVersionInPlainMode`); seen in the smoke check (`kitVersion` and `ref` `null` for the directory source). +- **FP07-AC5** No file in the current repository is created or changed by `integrations install` or `integrations update`. **Implemented**. Proven by `IntegrationsCommandsEndToEndTests.IntegrationsInstallAndUpdate_InGitRepository_CreateOrChangeNoFileInIt` (snapshot of a temporary git repository; `claude` never runs inside it). +- **FP07-AC6** `integrations update` with no installed integration reports that nothing is installed and exits without error. **Implemented**. Proven by `IntegrationsCommandsEndToEndTests` (`IntegrationsUpdate_NothingInstalled_WritesEmptyIntegrationsAndExits0`, `IntegrationsUpdate_NothingInstalled_ChecksNoTagAndWritesNoSourceWarning`, `IntegrationsUpdate_PlainModeNothingInstalled_SaysNothingIsInstalledAndExits0`) and `IntegrationsUpdateCommandTests`; seen in the smoke check. +- **FP07-AC7** No skill in the integration content references a path under `research/` or `docs/` of the kit repository. Taken over from FP06-AC13 on 2026-11-04, because the rule only applies to shipped skills ([06-2 skill conventions](06-2-skill-conventions-and-version.md#skill-conventions)). **Implemented**. Proven by `ShippedSkillsTests.SkillFiles_ShippedSkills_ContainNoPathReferenceIntoDocsOrResearch`, `ShippedSkillsTests.FindDocsOrResearchReferences_NestedSkillsWithReferences_ReportsFileAndLineOfEachReference`, and, since 2026-11-14 for every text file under `skills/`, `ShippedSkillsTests.FindDocsOrResearchReferences_BundledFilesBesideSkillFiles_ReportsReferencesInEveryTextFile`, `ShippedSkillsTests.FindDocsOrResearchReferences_BinaryFileWithReference_IsNotScanned`, and `ShippedSkillsTests.FindDocsOrResearchReferences_TextFileThatIsNotUtf8_ThrowsInvalidDataException`. + +## Review + +- Code review of the uncommitted package 07 on 2026-11-13: [review report](../reviews/2026-11-13-feature-claude-code-integration-uncommitted.md) (1 Major, 5 Minor, 7 Suggestions, 2 Nitpicks). +- Gate 5 (user, 2026-11-14): reworked the Major finding (Kit version guard), M3, M4, M5, S1 to S7, N1, and N2, as described above. Not reworked and accepted by the user: M1 and M2 (open points). +- Second code review of the reworked package 07 on 2026-11-15: [second review report](../reviews/2026-11-15-feature-claude-code-integration-uncommitted-2.md) (0 Critical, 0 Major, 0 Minor, 1 Suggestion, 4 Nitpicks). Of the 15 findings of the first review, 12 were resolved, 1 was resolved as decided (the Major finding: the guard test, layer 1; the release check, layer 2, not selected), and 2 stayed unresolved because the user accepted them (M1, M2). +- Gate 5 round 2 (user, 2026-11-15): reworked N3 (the 52 of a stray stdout line holds for `install` and `update`; in `version` it is the warning `agent-unavailable`, How the engine runs `claude`), N4 (the not-found reason of a missing `claude` is one text, `ExternalTool.NotFoundReason`, used by `ExternalToolRunner.RunAsync` and `ClaudeCodeIntegration.EnsureAvailable`; the text is unchanged; `ExternalToolTests`), and N6 (the kit version guard reports the outlier skill, [Kit version guard](#kit-version-guard)). N5 (the `?? []` guard on `IntegrationRunFailedException.CompletedIntegrations` in `CliErrorMapper.CreateIntegrationRunFailedError`) was checked and kept: a constructed instance never has a null list, but the FP01-AC8 guard test `CliErrorMapperTests.Map_EveryConcreteCoreException_ReturnsCliError` maps instances of every core exception created without running their constructor, and without the guard it fails with a `NullReferenceException` (**FACT**, by experiment in the rework); the comment at the guard now names that reason. Not reworked and accepted by the user: S8 (open points). ## Open points -- **Unverified:** supported way to install a Claude Code plugin at user level from a script (see above). -- Since 2026-11-04 every skill carries its kit version hardcoded in its frontmatter (`metadata.version`, 06-2), and its alignment with the engine version is skipped for now. FP07-AC2 ("same kit version as the engine that installed them") then only holds if the version in the skills was raised by hand for the release. +- No timeout for `claude` in `version` (review finding M1): with `claude` on the `PATH`, every `version` call, and so every skill handshake, waits for `claude plugin list` (and `marketplace list`) without a time limit; a hanging `claude` blocks it until the user cancels. **Unverified** that the list commands can hang. Accepted by the user at Gate 5 on 2026-11-14. +- No minimum Claude Code version is stated or checked (second review finding S8): every `install` and `update` with a kept marketplace runs `claude plugin marketplace update --json`, and the Claude Code CLI reference says that `--json` on that command needs Claude Code 2.1.287 or later (see How the engine runs `claude`). **Unverified** locally: no `claude` older than 2.1.287 was run. An older `claude` would make such a run fail with the generic 52 `agent-command-failed`; its message only says to make sure Claude Code is up to date (`claude update`). Accepted by the user at Gate 5 round 2 on 2026-11-15. +- No timeout for `git ls-remote` (review finding M2): on a stalled network the release-tag check of `install` and `update` can block for a long time instead of falling back to the unchecked tag; neither the engine nor git's default HTTP settings bound it. **Unverified** how long such a call blocks. Accepted by the user at Gate 5 on 2026-11-14. +- The release check of the review's Major finding (a `verify-tag` job or Cake task that fails a tag whose skills have another major.minor) was not selected; the guard test fails the tag build instead (19). +- The warnings of a failed `install` or `update` are not reported (Several agents). +- Plugin components at the repository root ship with the plugin (Content source); nothing but this rule guards it. +- On Linux and macOS a Windows drive path in `SHADE_KIT_MARKETPLACE_SOURCE` is not a directory (`C:/kit` gives exit code 2); **Unverified** for Windows junction targets and UNC roots in the directory comparison. +- **Unverified:** that `claude plugin marketplace update` refreshes a GitHub-kind marketplace the same way as the `git`-kind marketplace of the spike. +- The tags `v0.7.0` and `v0.8.0` have no `.claude-plugin/` (**FACT**, `git ls-tree`), so an engine of those versions cannot install from its tag. The first installable release is the first tag that contains the manifests. +- **Unverified:** the interactive slash menu of Claude Code with the marketplace-installed plugin (the smoke check ran headless with `--plugin-dir`). +- Windows: only the `claude.exe` of the native installer is found; the `claude.cmd` of an npm installation is not supported. +- `integrations uninstall` is a later addition. **Proposed.** +- The plugin source is `./`, the repository root, so the plugin is the whole tree, `src/`, `tests/`, `docs/`, and `research/` included. A directory source is loaded in place (**FACT**, smoke check: `readFromFolder` is the working tree). **Unverified:** whether Claude Code copies the whole tree of a GitHub source into its plugin cache, and how large that becomes. A plugin subdirectory would avoid it but moves `skills/`. +- A plugin installed with the scope `project` or `local` is not seen; **Unverified** how `claude plugin install --scope user` behaves next to it. +- `GitCommandRunner` now sets `GIT_TERMINAL_PROMPT=0` and an empty `GIT_ASKPASS` for every `git` call of the engine, not only for the tag check, so no `git` command of the engine can prompt; a call that would need credentials fails instead. **Decided** on 2026-11-13 (package 07 implementation, Gate 4). **Implemented** (`GitCommandRunner.EnvironmentVariables`; `GitCommandRunnerTests`). **FACT** (git 2.54, spike on 2026-11-13): an empty `GIT_ASKPASS` makes `git` ignore `core.askPass` and `SSH_ASKPASS`; `-c core.askPass=` alone does not beat a set `GIT_ASKPASS`. **FACT** (.NET 10): an empty value in `ProcessStartInfo.Environment` reaches the child process. +- The release-tag check needs `git` and the network. When `ls-remote` cannot run or fails, the tag is used unchecked (Release-tag check), so a build of an untagged `main` commit on a machine without `git` still ends with exit code 52 from `claude`. diff --git a/docs/feature-packages/08-copilot-and-codex-integration.md b/docs/feature-packages/08-copilot-and-codex-integration.md index c8d82d0..0772876 100644 --- a/docs/feature-packages/08-copilot-and-codex-integration.md +++ b/docs/feature-packages/08-copilot-and-codex-integration.md @@ -2,7 +2,7 @@ | | | |---|---| -| Status | Draft, 2026-10-14, updated 2026-10-18 (consistency review: router references replaced by `shade-kit-next-phase`) 2026-10-24 (documentation check: research note instead of an ADR in `docs/adr/`), and 2026-10-30 ([phase start analysis](../../research/shade-kit-phase-start-analysis.md): research question on calling a skill by name) | +| Status | Draft, 2026-10-14, updated 2026-10-18 (consistency review: router references replaced by `shade-kit-next-phase`) 2026-10-24 (documentation check: research note instead of an ADR in `docs/adr/`), and 2026-10-30 ([phase start analysis](../../research/shade-kit-phase-start-analysis.md): research question on calling a skill by name), and 2026-11-13 (package 07 implementation: content source, version pin, and state as in 07; Gate 4 rework: `version` asks only detected agents), and 2026-11-14 (review rework of 07: the agent seam `IAgentIntegration` with `EnsureAvailable` and `UpdateAsync(getSource)`, the order of several agents, completed agents named on failure) | | Source | Concept §1 (Success, Constraint), §2 (Agents), §3.4, §10 open question 5, [concept §9](../../research/shade-kit-concept.md#9-version-drift) | | Depends on | 02, 06, 07 | | Enables | Phase packages 09–17 are built and accepted on all three agents | @@ -45,8 +45,14 @@ The result is a research note `research/shade-kit-agent-compatibility.md` with a ### Step 2: install and update - `integrations install --agent copilot|codex` installs the same content as for Claude Code at user level, as a plugin where the agent has one, otherwise in the agent's user directory. **Decided** (concept §3.1). -- If the research shows a format difference, the engine transforms the content at install time from the one skill source. There is no second copy of the skill text in the kit repository. **Proposed.** -- Version recording and `integrations update` work as in package 07. +- The engine contains no integration content; for Claude Code it is the tree of this repository at the tag of the engine version. **Decided** on 2026-11-13 (package 07 implementation). How Copilot and Codex get it from the tag (their own plugin or marketplace mechanism, or another way where they have none) is **Open** for step 1. +- If the research shows a format difference, the content is transformed at install time from the one skill source. There is no second copy of the skill text in the kit repository. **Proposed.** Since the engine holds no content (07), a transformation needs a source the engine reads, for example the tagged tree. **Open** since 2026-11-13. +- The version pin (tag `v`, `main` for a prerelease engine and for a release engine whose tag does not exist), the state read from the agent instead of an engine-owned record, and `integrations update` work as in package 07. **Proposed** (2026-11-13, package 07 implementation). +- `version` asks only the agents whose CLI is detected (`IAgentIntegration.IsAvailable()`), so on a machine with only Copilot or Codex it does not start `claude` and gives no warning for Claude Code; `agent-unavailable` appears only when a detected agent CLI cannot be started or fails. **Decided** on 2026-11-13 (package 07 implementation, Gate 4). **Implemented** (`IntegrationService.GetInstalledAsync`). The integrations of this package get the same behaviour through their own `IsAvailable()`. Before 2026-11-13 this was an open point here (every handshake would have carried `agent-unavailable` for Claude Code). +- The seam for each agent is `IAgentIntegration` (07). **Implemented** for Claude Code (`ClaudeCodeIntegration`). Since 2026-11-14 (package 07 review rework, Gate 5) it has, besides `AgentId`, `IsAvailable()`, `GetInstalledAsync`, and `InstallAsync(source)`: + - `EnsureAvailable()`: throws the agent's not-found exception (an `ExternalToolUnavailableException`, mapped to 51) when its CLI is missing; `install` calls it for every selected or detected agent before the release-tag check, so `--agent copilot` or `--agent codex` without their CLI must fail there too. + - `UpdateAsync(getSource, cancellationToken)`: the agent reads its own state, returns `null` without calling `getSource` when nothing is installed, and otherwise calls `getSource` once before it changes anything. `IntegrationService` resolves the source (and checks the tag) once per run, for the first installed agent. + - The agents run one after the other in registration order; agent 1 is updated before agent 2 is read. When an agent fails after another one was done, the error keeps the failure's exit code and code and its message names the completed integrations (`IntegrationRunFailedException`); the JSON contract is unchanged. New agents report their failures as `ExternalToolUnavailableException`, `IntegrationConflictException`, or `IntegrationIncompleteException` to get this (07, Several agents). ### Step 3: degraded behaviour @@ -72,4 +78,4 @@ From this package on, every phase package (09–17) counts as done only when its ## Open points - Concept open question 5 is the content of step 1. -- Frontmatter visibility (06-2, 2026-11-06): this package checks whether Copilot and Codex show the skill frontmatter, and `metadata.version` in it, to the model, and how their parsers read the unquoted `version: 0.7.0` (as a string, as 06-2 expects). **Unverified.** +- Frontmatter visibility (06-2, 2026-11-06): this package checks whether Copilot and Codex show the skill frontmatter, and `metadata.version` in it, to the model, and how their parsers read the unquoted `version: 0.8.0` (as a string, as 06-2 expects). **Unverified.** diff --git a/docs/feature-packages/19-release-and-distribution.md b/docs/feature-packages/19-release-and-distribution.md index 277bae2..3435b38 100644 --- a/docs/feature-packages/19-release-and-distribution.md +++ b/docs/feature-packages/19-release-and-distribution.md @@ -2,9 +2,9 @@ | | | |---|---| -| Status | Draft, 2026-10-14, updated 2026-10-18 (reduced to the remaining scope; CI and release workflow are implemented; release notes and branch protection checked) | +| Status | Draft, 2026-10-14, updated 2026-10-18 (reduced to the remaining scope; CI and release workflow are implemented; release notes and branch protection checked) and 2026-11-13 (package 07 implementation: the content is not packed into the release; the release tag names the tree that `integrations install` installs; a release engine whose tag does not exist installs from `main`) and 2026-11-14 (package 07 review rework: the guard test `SkillKitVersionTests` ties the skills' kit version to the build version, so a tag build with stale skills fails its tests) | | Source | Concept §3.4; `CLAUDE.md` (Engine deliverables, CI), [concept §9.6](../../research/shade-kit-concept.md#9-version-drift) | -| Depends on | 07, 08 (content packed into the release); technically every package that is part of a release | +| Depends on | 07, 08 (the content comes from the tagged tree of this repository); technically every package that is part of a release | | Enables | Teams outside the kit repository can install and use SHADE kit | Labels follow the concept: **Decided**, **Proposed**, **Open**, **Unverified**, **Implemented**. @@ -26,7 +26,7 @@ The build and release pipeline exists. `CLAUDE.md` (sections ".NET conventions" ### In scope -- Packing the integration content (skills, research agent definitions) into the engine release, so engine and content share one version. +- Keeping engine and integration content on one version. Until 2026-11-13 this meant packing the content (skills, research agent definitions) into the engine release; since package 07 the content is not packed: the release tag `v` names the tree that `integrations install` installs. **Decided** on 2026-11-13 (package 07 implementation). What remains is the skills' hand-raised `metadata.version` (06-2), which a guard test checks against the build version since 2026-11-14. - The version rule for format changes. - An installer script for the binaries. - Release notes that list format changes and the need for `upgrade`. @@ -35,14 +35,14 @@ The build and release pipeline exists. `CLAUDE.md` (sections ".NET conventions" ### Out of scope - Everything listed under "Implemented". -- Publishing the plugin to an agent's public marketplace. In v1 the content reaches the agent through `integrations install` (packages 07 and 08). **Proposed.** +- Publishing the plugin to an agent's public marketplace. In v1 the content reaches the agent through `integrations install` (packages 07 and 08). **Proposed.** Since 2026-11-13 this repository is a Claude Code plugin marketplace itself (`creativecoders-shade-kit`, `.claude-plugin/`), which `integrations install` adds for the user (package 07). - Automatic self-update of the engine. ## Functional description ### Version -- Engine and integration content are released together under one version number. **Decided** (concept §9.6). Because the content is packed into the engine (package 07), one build produces both. +- Engine and integration content are released together under one version number. **Decided** (concept §9.6). The tag `v` that builds the engine is also the ref from which `integrations install` installs the content, so both come from one tree. **Decided** on 2026-11-13 (package 07 implementation), replacing "the content is packed into the engine". A prerelease engine installs from `main`, and so does a release engine whose tag does not exist (a build of an untagged `main` commit, which GitVersion gives no prerelease label), with the warning `integration-release-tag-missing` (07). - The version follows semantic versioning; a format version change (package 01) is at least a minor release, so the handshake rule (major and minor equal, package 06) catches it. **Proposed.** ### Additional release artifacts @@ -63,4 +63,4 @@ The build and release pipeline exists. `CLAUDE.md` (sections ".NET conventions" ## Open points -- None of its own. +- Every skill's `metadata.version` must carry the major and minor of the tag before it is set (06-2, FP07-AC2). Since 2026-11-14 the guard test `SkillKitVersionTests` (Core tests) fails when the skills' major.minor differs from the engine version of the build, and the release workflow runs the tests on the tag (`-t pack` on all three platforms before `nuget-push` and the GitHub release; **FACT**, `.github/workflows/release.yml`, with pack running the tests as `CLAUDE.md` describes). So a tag build with stale skills fails its tests and publishes nothing; the builds of `main` and of pull requests fail the same way before the tag. Remaining gap: nothing checks it before the tag is set (the `verify-tag` job does not), so a bad tag exists already when its build fails and has to be removed by hand; a release check in `verify-tag` or a Cake task was proposed by the review of 07 (2026-11-13, Major, layer 2) and not selected. The value is still raised by hand, and the commit that raises the minor of the skills needs the minor of the build version raised too (06-2). A release tag also needs `.claude-plugin/` in its tree; `v0.7.0` and `v0.8.0` have none (07). diff --git a/docs/feature-packages/README.md b/docs/feature-packages/README.md index d1b14d0..49ff958 100644 --- a/docs/feature-packages/README.md +++ b/docs/feature-packages/README.md @@ -1,6 +1,6 @@ # SHADE kit v1 feature packages -Status: draft, 2026-10-14, updated 2026-10-18 (consistency review, findings clarification, and implementation of package 02), 2026-10-21 (implementation of package 03, its code review rework, and the rework after its second code review), 2026-10-22 (code review verification of package 03), 2026-10-23/24 (rework of file content handling), 2026-10-24 (documentation check against the code), 2026-10-25 (rework of `feature new` and its code review), 2026-10-26 (implementation of package 04), 2026-10-27 (documentation check after package 04), 2026-11-01 (implementation of package 05), 2026-11-04 (split of package 06 into the sub-features 06-1 to 06-9), 2026-11-06 (implementation of package 06-1 and its code review, and implementation of package 06-2), 2026-11-08 (implementation of package 06-3, and implementation of package 06-4 and its code review rework), 2026-11-10 (implementation of package 06-5), 2026-11-11 (implementation of package 06-6), and 2026-11-13 (implementation of packages 06-8 and 06-9). Derived step by step from [`research/shade-kit-concept.md`](../../research/shade-kit-concept.md); its [section 9](../../research/shade-kit-concept.md#9-version-drift) holds the version-drift decisions of the former ADR 0001. Parts that exist in the code are labelled **Implemented**. +Status: draft, 2026-10-14, updated 2026-10-18 (consistency review, findings clarification, and implementation of package 02), 2026-10-21 (implementation of package 03, its code review rework, and the rework after its second code review), 2026-10-22 (code review verification of package 03), 2026-10-23/24 (rework of file content handling), 2026-10-24 (documentation check against the code), 2026-10-25 (rework of `feature new` and its code review), 2026-10-26 (implementation of package 04), 2026-10-27 (documentation check after package 04), 2026-11-01 (implementation of package 05), 2026-11-04 (split of package 06 into the sub-features 06-1 to 06-9), 2026-11-06 (implementation of package 06-1 and its code review, and implementation of package 06-2), 2026-11-08 (implementation of package 06-3, and implementation of package 06-4 and its code review rework), 2026-11-10 (implementation of package 06-5), 2026-11-11 (implementation of package 06-6), 2026-11-13 (implementation of packages 06-8, 06-9, and 07, and the Gate 4 rework of 07), 2026-11-14 (review rework of 07, Gate 5), and 2026-11-15 (second review rework of 07, Gate 5 round 2). Derived step by step from [`research/shade-kit-concept.md`](../../research/shade-kit-concept.md); its [section 9](../../research/shade-kit-concept.md#9-version-drift) holds the version-drift decisions of the former ADR 0001. Parts that exist in the code are labelled **Implemented**. Each package describes the functional behaviour of one clearly bounded piece of v1, with its benefit, scope, acceptance criteria (`FPnn-ACm`), and open points. The number prefix is the implementation order: every package depends only on packages with a lower number. @@ -96,7 +96,7 @@ Not in any package because the concept puts them later: MCP server, extensions ( ## Changes and additions to the concept that need confirmation -None. The earlier list (keyed `gates.json`, new artifacts and commands, approval off with a checklist, skipping `map`, no hooks and MCP in v1, integration content in the engine release, `data.md` not created, `CLAUDE.md` update, obsolete "stay in refine") was confirmed on 2026-10-18 and taken over into the concept and `CLAUDE.md`. +None. The earlier list (keyed `gates.json`, new artifacts and commands, approval off with a checklist, skipping `map`, no hooks and MCP in v1, integration content in the engine release, `data.md` not created, `CLAUDE.md` update, obsolete "stay in refine") was confirmed on 2026-10-18 and taken over into the concept and `CLAUDE.md`. "Integration content in the engine release" was replaced on 2026-11-13 (package 07): this repository is the Claude Code plugin marketplace, and the engine installs from the tag of its own version. ## Open questions @@ -118,13 +118,13 @@ New open points from the packages: - The `report` setting in the result of `phase start finish`, which the `shade-kit-finish` skeleton expects (04, owned by 15). - History timestamps `at` with fractional seconds, while `createdAt` has whole seconds (04). - Skill skeletons aligned with the built `phase` commands on 2026-11-13 (06-9): the planned-commands sentence is gone from all 12 skeletons (not 13), every phase skill loads `shade-kit-phase-entry` and `shade-kit-next-steps`, which show the warnings, and `new`, `discuss`, and `drop` run the handshake with `--expect`. Still open: the `report` setting in the result of `phase start finish` and in the return of `shade-kit-phase-entry` (15, FP15-AC7); until then `shade-kit-finish` treats it as `ask`. -- Skill version (06-2, 2026-11-04): every skill carries its kit version hardcoded in its frontmatter (`metadata.version`), initial value `0.7.0` (2026-11-06); its alignment with the GitVersion version and the release tag is skipped for now, which breaks the rule in `GitVersion.yml` that no version is maintained by hand (06-2, 07, 19). Claude Code does not show the frontmatter to the model (checked on 2026-11-06 with Claude Code 2.1.318 on project-level skills, 06-2), so the handshake step states the version in its text. **Unverified:** whether Copilot and Codex show the frontmatter to the model (08). +- Skill version (06-2, 2026-11-04): every skill carries its kit version hardcoded in its frontmatter (`metadata.version`), initial value `0.7.0` (2026-11-06), `0.8.0` since 2026-11-14. It is still raised by hand, which breaks the rule in `GitVersion.yml` that no version is maintained by hand, but since 2026-11-14 the guard test `SkillKitVersionTests` (FP07-AC2) fails every build whose skills carry another major.minor than the engine version of the build, or whose handshake texts name another version, so a release tag with stale skills fails its tag build (06-2, 07, 19). Still open: writing the version from GitVersion, a check before the tag is set (`verify-tag`), and raising the build minor together with the skills (**Unverified** with `+semver: minor`, 06-2). Claude Code does not show the frontmatter to the model (checked on 2026-11-06 with Claude Code 2.1.318 on project-level skills, 06-2), so the handshake step states the version in its text. **Unverified:** whether Copilot and Codex show the frontmatter to the model (08). - Phase skills are restricted to user invocation only by convention (06-2, 08): a technical restriction such as Claude Code's `disable-model-invocation` is a possible later addition; whether Copilot and Codex offer one is part of the research of 08. - Skill reactions to a refused start, the refusal table of the next-steps message, and the active-feature check of `new` are **Proposed** (06-3, 09). The next-steps skill is built (06-3, 2026-11-08); its defaults are also **Proposed**: the table is keyed by error code, a failing `phase next` goes through the table, repeated warnings are shown once, and a refusal ends with calling the skill again. Rows 20–22 and 47 name `shade-kit upgrade`, which comes only with package 18. - Defaults of the 04 implementation that the user has not confirmed yet (**Proposed** in 04): the repeated gate of a pending forward transition, approving a pending reopen of a phase that can no longer be reopened, the conditions for a `feature.json` without `currentPhase`, the done rule, the override deletion of `phase complete`, the plain-text wording, and `null` parts of `phase next`. - Value and unit of the coverage threshold `coverageThreshold` in `config.json` (05, 14). - Follow-ups from the implementation of 05 (2026-11-01): `checklist` values with control characters or `:` (a Windows alternate data stream) are not rejected; the order of `gate-entry-ignored` warnings relies on `Dictionary` enumeration order, which .NET does not guarantee; the cached `GatesConfig` is one shared mutable object; a file at `features//checks` ends `phase start` with exit code 255 (resolved on 2026-11-04: exit code 17, since the /simplify review of feature/feature-05 for every refused write in `.shadekit/`, 01); two concurrent starts could race between the existence check and the write of the copy; repositories initialised before 2026-11-01 get the built-in gate defaults with a warning until an upgrade (18) writes `profiles` (05). -- Supported way to install a Claude Code plugin at user level from a CLI (07, **Unverified**). +- Follow-ups of 07 (2026-11-13): the tags `v0.7.0` and `v0.8.0` have no `.claude-plugin/`, so the first installable release is the first tag with the manifests; **Unverified** the interactive slash menu with the marketplace-installed plugin; the `claude.cmd` of an npm installation on Windows is not supported; `integrations uninstall` later; **Unverified** whether Claude Code copies the whole repository tree of a GitHub source (plugin source `./`) into its plugin cache; with `claude` on the `PATH` every `version` call starts it (0.73 s instead of 0.08 s for `version --json --expect`, measured on 2026-11-13); a plugin with another scope than `user` is not seen; without `git` or the network the release-tag check is skipped and the tag is used unchecked. From the review rework (2026-11-14): no timeout for `claude` in `version` and for `git ls-remote`, accepted by the user (review M1, M2); the warnings of a failed `install` or `update` are not reported; plugin components at the repository root (`.mcp.json`, `hooks/`, `agents/`, `commands/`, …) would ship with the plugin, guarded only by a rule; **Unverified** the GitHub fetch path of `claude plugin marketplace update` and Windows junctions and UNC roots in the directory comparison; a Windows drive path in `SHADE_KIT_MARKETPLACE_SOURCE` is no directory on Linux and macOS. From the second review rework (2026-11-15): no minimum Claude Code version is stated or checked, although `claude plugin marketplace update --json`, run for every kept marketplace, needs Claude Code 2.1.287 or later per the Claude Code CLI reference (**Unverified** locally), so an older `claude` gives a generic 52; accepted by the user (second review S8). - Follow-ups from the implementation of 02: plain output wrapped at 80 columns when stdout is not a terminal, skeleton templates that name their owner package, a second `.gitignore` comment line when only an entry is missing (02). From its code review: a dangling symbolic link ends with a host error and a read-only target file fails only after `.shadekit/` is written (02). - Follow-ups of 03 after its code review rework and second code review (2026-10-21): the process run of `GitCommandRunner` (output capture, exit codes, kill) is not covered by tests, and its read tasks are not observed after a kill (F03, accepted); a FIFO as `--source` blocks `feature new`; `drop` can delete an override that was changed to another feature between its check and the delete; on some systems the rename of `new` or `drop` can replace an empty folder created at the wrong moment; a file at `features/` makes `feature new` end with exit code 255; a rename that fails only for a moment (for example on Windows while a virus scanner holds new files) is not retried and ends with exit code 35; unknown extra arguments are ignored silently; `git.cmd` shims are not found (no `PATHEXT`). Accepted as is by the user from the second code review: bidi format characters and U+2028/U+2029 pass the title check (N03); 03 says that a canceled `init` rolls back what it created, but it removes only `.shadekit/` (N04); Ctrl+Break and SIGQUIT also cancel with exit code 130 (N05); the `invalid-title` hint "Pass such a title with --title." is circular for a title from `--title` (N06); a theory in `ConsoleCancellationTests` branches in its Arrange section (N07). - Follow-ups of 03 after the code review of the rework of `feature new` (2026-10-25): accepted as is by the user, a second `AddShadeKitCore()` call registers the configuration of the named HTTP client twice, so that client would send the `User-Agent` product twice (F3, **Unverified** at runtime; the CLI calls it once). Still open from the rework: `gh` and HTTP are only faked in tests, and the shape of a real `gh issue view --json` output is **Unverified**. @@ -150,7 +150,7 @@ After each package, the whole draft was checked against the concept, ADR 0001 (n | 15 | `phase complete` should clear the local override; report claimed "who checked off" playbook items, which no artifact records. | Added to 04; report shows checked yes/no. | | 16 | 14 said the regression test comes from `diagnose`. | Corrected: planned in `plan`, written in `implement`. | | 17 | Router always asked for approval, breaking `quick`'s single approval; approval off plus checklist was undefined. | 06 and 05 updated. | -| 18 | `current-feature.json` and the user-level integration record were missing from 01's file types; nobody migrated the integration record. | Added to 01; 07 migrates it. | +| 18 | `current-feature.json` and the user-level integration record were missing from 01's file types; nobody migrated the integration record. | Added to 01; 07 migrates it. The record was dropped on 2026-11-13 (07 implementation): the state comes from Claude Code. | | 19 | Format changes must be visible to the handshake. | Format change is at least a minor release. | | All | Automated check: every dependency points to a lower number, every package reference exists, every AC id is unique. `gates.json` and templates in 02 depend on later content. | Check passed. 02 clarified: skeletons and a version-only `gates.json` until the owner package is built. | | Templates (2026-10-17) | First drafts of the `spec`, `plan`, `tasks`, DoR, and DoD templates (template interview) differed from the packages: `*.template.md` source names, no order of work in `plan.md`, task status as checkbox, coverage matrix, more spec sections, ten DoR and nine DoD items in a result table, quality commands planned in `plan.md`. | 02 (source names, template conventions), 05 (checklist format, default items), 06 (conventions, checklist check), 10 (`spec.md`), 12 (`plan.md`, `tasks.md`), 13 (checkboxes, commands from `plan.md`), 14 (commands, coverage matrix) aligned. | @@ -181,3 +181,7 @@ After each package, the whole draft was checked against the concept, ADR 0001 (n | 06-7 implementation (2026-11-11) | 06-7 had the interview record every answer in the target artifact, but `refine` (10), `plan` (12), `diagnose` (16), `quick` (17), and `discuss` (09) write their artifact only after the interview, in the first round from the template. It said "one topic at a time" while the structured question tool takes up to four questions per call. FP10-AC5 lets `refine` record why a finding was dismissed, but 06-7 knew no dismissal. It did not say where who and when come from, how `open` and `targeted` differ, who decides what is blocking, what counts as an answer, what happens after a challenge, how to ask without a real proposal, in which language answers are recorded, or what the return holds. The five calling skeletons passed neither a target nor a recording rule. | Decided with the user (06-7): the calling skill chooses the recording time (`immediately` or `on return`); a blocking topic is asked alone, up to four independent non-blocking topics per call; a dismissal needs the human's confirmation in one collective question and is returned with its reason; who and when come from the caller, otherwise from `git config user.name` (asked once if empty) and the system clock; both modes may add topics; blocking is marked by the caller, otherwise decided by the agent; a delegation ("you decide") counts as accepting the proposal; after the one challenge the human's answer is final and a conflict is returned, not cleaned up; without a real proposal the agent states a reasoned guess; questions in the conversation's language, records in the artifact's language; a fixed return block with an example. The load steps of the five skeletons name mode, topics, target, recording rule, and recording time (table in 06-7); packages 09, 10, 12, 16, and 17 take these values as their starting point. A fixed input block is an open idea in 06-7. CLAUDE.md names the convention. | | 06-8 implementation (2026-11-13) | 06-8 expected a short focus name from the callers, but the skeletons passed only long texts ("gaps and open questions" for `refine / gaps`, "security at code level" for `diagnose / security`). It said "one section per phase run and focus" next to a replace rule that keeps only the latest run. The template listed fixed `refine` and `map` headings but no `diagnose` one, and its comment asked to drop sections that did not run, against "touches no other sections". `refine` noted dismissals next to findings that had no IDs, and the next run lost them. It left open where feature id, title, and folder come from, what happens without a template, who writes the file while subagents run in parallel, what subagents may do, a failed focus, caller context that is not in a file yet (`diagnose` writes `diagnosis.md` after the research), section order, and the shape of the return. | Decided with the user: the caller passes per focus a name, a unique ID prefix (`G`/`RS`, `BP`/`AR`/`CO`/`HR`/`CS`, `DS`), and instructions, plus the files to read and a context note; the skill reads the feature with `feature show` (fallback `feature current`); subagents only read (web allowed) and only the main agent writes; a failed focus keeps its old section; every file source, link, and search is checked, a failed one becomes an assumption; a missing template gives a minimal file (exception to 06-2); new sections are appended, `map / skipped` is left to 11; the template holds only the shared format. After the first scenario runs: dismissed findings are carried over, a partly backed finding carries source and assumption on one line, a search counts as a source. 06-8 (decisions, status, scenario results, open points), 06-2 and `CLAUDE.md` (template exception; research convention), 02 (template row and status), 10, 11, 16 (focus names and prefixes, dismissal note, context note, open points), 06 and this README (status), the skills `shade-kit-research`, `shade-kit-refine`, `shade-kit-map`, `shade-kit-diagnose`, and `researches.template.md`. `dotnet test` passed. | | 06-9 implementation (2026-11-13) | 06-9 counted 13 skeletons with the planned-commands sentence (there were 12, `shade-kit-report` among them, which the scope left out although FP06-9-AC8 applies to it). The `report` setting that `shade-kit-finish` expects could not reach it, because `phase start` now runs in `shade-kit-phase-entry`, whose return does not carry it. Several skeletons named next steps of their own (refine, implement, verify, quick, new, discuss, finish) against the next-steps convention. After `new`, `phase next` returned `continue: shade-kit-new`, so the closing message would offer "Continue new", which creates another feature. "Load the skills the CLI returned" loaded the general skills in step 1 and again in their step, and `finish` loaded `shade-kit-report` also with `never`. `discuss` had no rule for a failing `feature current` (no `.shadekit/`), `finish` called `phase complete` without `--json`, and `new` still said that `feature new` writes no phase fields. | Decided with the user: `finish` expects the setting from the return of the entry protocol and treats a missing one as `ask` (open point for 15); a report names a recommendation and its reason but a skill only when the closing message does not list it; `WorkflowPhase.CanContinue` (`false` for `new`), so `phase next` returns `continue: null` in `new`; each general skill is loaded in the step that uses it; a failing `feature current` ends `discuss` with a refusal; the descriptions of `discuss` and `drop` say that they run only when the user calls them or asks for them; the gate warning is shown right after the entry protocol; the sentence removed from all 12 skeletons; the same entry and ending text in all eight phase skills, the handshake text of `shade-kit-next-phase` in `new`, `discuss`, and `drop`; stale facts corrected. Skills: the eight phase skills, `new`, `discuss`, `drop`, `report` (sentence), `shade-kit-next-steps` and `shade-kit-next-phase` (`continue` is `null` in `new`), `shade-kit-phase-entry` (step 5). Code: `WorkflowPhase`, `BuiltInWorkflowProfiles`, `PhaseEngine.GetNext`, doc comments of the `phase next` results, with tests. Docs: 06-9 (decisions, status, scenario table, open points), 04 (`continue`, `CanContinue`, FP04-AC14), 06-2 (AC3), 06-3, 06-5, 06-6, 06 (status), 15 (open point), this README (status, open point), `CLAUDE.md` (next-steps convention). Proven by `dotnet test`, `quick_validate.py` (19 of 19), the review by hand, and 11 scenario runs checked by a script: iteration 1 143 of 143, iteration 2 (two scenarios after two fixes) 25 of 25, the skeletons 83 of 143. | +| 07 implementation (2026-11-13) | 07 packed the integration content into the engine release (2026-10-18), proposed an engine-owned record of the installed integrations with its own format id, and left the way to install a Claude Code plugin from a CLI **Unverified**. 01 listed the format id `integrations`, the mismatch message of 06-1 named updating the skills by hand, 06-2 kept the source comments of the skeletons until the skills are shipped, 19 planned packing the content into the release, and concept §3.1, §3.4, and §9.6 said the same. A prerelease engine has no tag of its own to install from. The spike showed that `claude plugin marketplace remove` also uninstalls the plugins of the marketplace, so `update` cannot repair a failed ref switch. | Decided with the user: this repository is the marketplace `creativecoders-shade-kit` with the plugin `shade-kit` (`.claude-plugin/`, no `version` in `plugin.json`), and the engine contains no content; a release engine installs from the tag `v`, a prerelease from `main` with the warning `integration-prerelease-ref`, and `SHADE_KIT_MARKETPLACE_SOURCE` is a developer override; no engine-owned record (state from `claude plugin list` and `marketplace list`), format id `integrations` removed; `integrations install [--agent claude]` and `integrations update` run the `claude` plugin commands with the scope `user`; exit codes 51 `agent-not-found`, 52 `agent-command-failed`, 53 `integration-conflict`, warning `agent-unavailable`; `version --json` lists `integrations`; the repair hint of a failed switch names `integrations install`; the skill texts keep the bare names (`/shade-kit-`), and the smoke check showed that the bare and the namespaced form both work; the source comments removed from 13 skeletons, guarded by `ShippedSkillsTests` (FP07-AC7). Docs: 07 (rewritten to the implemented state), 01 (format id table, `version --json`), 06-1 (message, codes 51–53), 06-2 (source comments, guard test), 06 (open point), 08 and 19 (content source, version rule, marketplace), concept §3.1, §3.4, §9.6, this README, `CLAUDE.md`, `README.md`. Proven by `dotnet test` (5210 tests, 1 skipped) and the smoke check with Claude Code 2.1.323; FP07-AC1 checked by hand in a headless session; FP07-AC2 holds for the content, not for `metadata.version` (open point). | +| 07 Gate 4 rework (2026-11-13) | `GitVersion.yml` gives `main` no prerelease label, so a build of an untagged `main` commit is a release version whose tag does not exist, and `integrations install` would fail with 52; 07 had this as **Unverified**. `version` started `claude` on every call and, without `claude`, carried an `agent-unavailable` warning in every handshake (open point of 07 and 08). `integrations update` with nothing installed still resolved the source and gave the prerelease warning. The 06-1 mismatch message named `integrations update`, which finds nothing when nothing is installed. | Decided with the user: a release engine without the override checks its tag with `git ls-remote` (`IGitRemoteTagChecker`, `GitRemoteTagChecker`, in the user's home directory, `https` only, no credential helpers); a missing tag gives `main` and the new warning `integration-release-tag-missing`; without `git` or the network the tag is used unchecked; prereleases and the override check nothing. `GitCommandRunner` sets `GIT_TERMINAL_PROMPT=0` and an empty `GIT_ASKPASS` for every `git` call. `version` asks only detected agents, so a missing `claude` gives no warning. `update` with nothing installed resolves no source: no tag check, no warning, `ref` and `source` `null`, and an invalid override is not reported. The 06-1 message names `integrations install`. `IntegrationService.PrereleaseRef` renamed to `FallbackRef`. Docs: 07 (version pin, release-tag check, `update`, version reporting, codes, AC2, AC6, open points), 01 (warning codes, `version --json`), 06-1 and 06 (message, warning codes), 08 (open point resolved), 19 (version rule), concept §3.1 and §9.6, this README, `CLAUDE.md`. | +| 07 review rework (2026-11-13 review, Gate 5 on 2026-11-14) | The [code review](../reviews/2026-11-13-feature-claude-code-integration-uncommitted.md) found that the hint `shade-kit integrations install` of the 06-1 mismatch message loops when a tag carries stale skills (the skills said `0.7.0`, the engine is `0.8.x`), and nothing checked the version (Major); 07 said that every `claude` call reads the last JSON line, but the list commands parse the whole stdout (M4); a kept branch marketplace relied on `plugin update` to fetch new commits, **Unverified** (M3); a URL in `SHADE_KIT_MARKETPLACE_SOURCE` became a relative path (M5); a cancellation during the switch gave no repair hint (S1); directories were compared ordinally without links (S2); `--agent claude` without `claude` ran the network tag check first (S3); `update` listed plugins and marketplaces twice (S4); a failing second agent dropped the results of the first (S5); the FP07-AC7 guard scanned only `SKILL.md` (S6); the plugin root `./` ships every root-level component (S7); the XML doc of 51 missed a case (N1). M1 and M2 (no timeouts) were not selected. | Decided with the user at Gate 5: `SkillKitVersionTests` (FP07-AC2) ties every skill's version and handshake text to the major.minor of the engine build, and every skill is raised to `0.8.0`; the AC7 guard scans every text file under `skills/`; the doc of 07 corrected (M4, code kept); spike FACT that `plugin update` alone misses a recent push, so a kept marketplace is refreshed with `claude plugin marketplace update` (`IClaudePluginCli.UpdateMarketplaceAsync`); `IntegrationSwitchCanceledException` → 130 with the repair hint; `DirectoryPathComparer` (links resolved, case-insensitive on Windows and macOS); `IAgentIntegration.EnsureAvailable()` before the tag check; `IAgentIntegration.UpdateAsync(getSource)` with the source resolved once; `IntegrationRunFailedException` names the completed agents in the message, JSON contract unchanged; URL forms of the override refused with exit code 2; S7 recorded as a rule. M1 and M2 accepted as open points. Docs: 07 (status, content source, developer option, `claude` output, install and update flow, several agents, codes, kit version guard, AC2, AC7, review, open points), 06-2 (version `0.8.0`, guard, open points), 06-1 (hint note), 01 (130), 08 (agent seam), 19 (release check), concept §9.6, this README, `CLAUDE.md`. Proven by `dotnet test` (5523 tests, 8 skipped on macOS, R5). | +| 07 second code review (2026-11-15, Gate 5 round 2) | The [second review](../reviews/2026-11-15-feature-claude-code-integration-uncommitted-2.md) of the rework (0 Critical, 0 Major, 0 Minor, 1 Suggestion, 4 Nitpicks) found 12 of the 15 first-review findings resolved, the Major resolved as decided (layer 1), and M1 and M2 still accepted. New: 07 said that a stray stdout line fails the list commands with 52, which holds for `install` and `update` only; in `version` it is the warning `agent-unavailable` (N3); `ClaudeCodeIntegration.EnsureAvailable` repeated the not-found reason of `ExternalToolRunner` (N4); the `?? []` guard in `CliErrorMapper.CreateIntegrationRunFailedError` looked dead (N5); the kit version guard took the first skill in path order as the reference, so an outlier that came first made every other skill a violation (N6); no minimum Claude Code version is stated for `claude plugin marketplace update --json` (S8). | Decided with the user at Gate 5 round 2: N3 corrected in 07; N4 one text `ExternalTool.NotFoundReason` for both places (text unchanged); N5 checked and kept, because the FP01-AC8 guard test maps core exceptions created without their constructor; N6 the reference is the most frequent valid version (tie → engine major.minor → first by path), with new tests; S8 accepted as an open point. Docs: 07 (status, source, `claude` output, kit version guard, review, open points), 06-2 (status, guard), this README. Proven by `dotnet test` (5533 tests, 8 skipped, R7). | diff --git a/research/shade-kit-concept.md b/research/shade-kit-concept.md index 32520ea..d46b232 100644 --- a/research/shade-kit-concept.md +++ b/research/shade-kit-concept.md @@ -1,6 +1,6 @@ # SHADE kit concept -Status: draft, 2026-10-13, updated 2026-10-17 (template interview), 2026-10-18 (consistency review: skills without router, `quick` phase, version-drift decisions moved into section 9; findings clarification: package changes confirmed and taken over), 2026-10-21 (feature commands implemented, package 03), 2026-10-24 (documentation check against the code), 2026-10-25 (rework of `feature new`), 2026-10-27 (documentation check after package 04: phase commands and phase states implemented, phase state diagram completed), 2026-10-30 (phases start only when the user calls the phase skill; [shade-kit-phase-start-analysis.md](shade-kit-phase-start-analysis.md)), and 2026-11-01 (package 05 implemented: gates from `gates.json`, checklist copies). Result of an interview on the original working notes. Design notes only; nothing here is shipped. +Status: draft, 2026-10-13, updated 2026-10-17 (template interview), 2026-10-18 (consistency review: skills without router, `quick` phase, version-drift decisions moved into section 9; findings clarification: package changes confirmed and taken over), 2026-10-21 (feature commands implemented, package 03), 2026-10-24 (documentation check against the code), 2026-10-25 (rework of `feature new`), 2026-10-27 (documentation check after package 04: phase commands and phase states implemented, phase state diagram completed), 2026-10-30 (phases start only when the user calls the phase skill; [shade-kit-phase-start-analysis.md](shade-kit-phase-start-analysis.md)), 2026-11-01 (package 05 implemented: gates from `gates.json`, checklist copies), 2026-11-13 (package 07 implemented: this repository is the Claude Code plugin marketplace, the engine installs from the tag of its version, or from `main` with a warning when that tag does not exist), and 2026-11-14 (package 07 review rework: the skills' kit version is checked against the build version by a test). Result of an interview on the original working notes. Design notes only; nothing here is shipped. Labels used in this document: @@ -62,11 +62,11 @@ SHADE kit keeps what worked (interviews, draft → approve, requirement-to-test | Command (proposed name) | Purpose | |---|---| -| `shade-kit integrations install [--agent claude\|copilot\|codex]` | Sets up the agent integration (skills and agents; hooks and MCP configuration come later, no v1 feature needs them) at **user level**: as a plugin where the agent has one, otherwise by writing the same content to the agent's user directory. **Decided.** | -| `shade-kit integrations update` | Updates the user-level integration to the installed kit version. | +| `shade-kit integrations install [--agent claude\|copilot\|codex]` | Sets up the agent integration (skills and agents; hooks and MCP configuration come later, no v1 feature needs them) at **user level**: as a plugin where the agent has one, otherwise by writing the same content to the agent's user directory. **Decided.** For Claude Code it adds this repository as the plugin marketplace `creativecoders-shade-kit` at the tag `v` (`main` for a prerelease engine and for a release engine whose tag does not exist) and installs the plugin `shade-kit` with the scope `user`, through the `claude` CLI. **Decided** on 2026-11-13 (package 07 implementation). **Implemented** (`IntegrationsInstallCommand`, `ClaudeCodeIntegration`). | +| `shade-kit integrations update` | Updates the user-level integration to the installed kit version. **Implemented** for Claude Code (`IntegrationsUpdateCommand`, package 07). | | `shade-kit init` | Creates `.shadekit/` in a repository: `config.json`, `gates.json`, templates, `templates.lock.json`, `.gitignore` entries, and a short SHADE kit section in `CLAUDE.md` / `AGENTS.md`. **Implemented** (`InitCommand`). | | `shade-kit upgrade` | Migrates an initialised repository to the current format versions. Rules in [section 9](#9-version-drift). | -| `shade-kit version` | Prints the engine version; with `--json` also the current format version per file type. **Implemented** (`VersionCommand`). Skills call it before they run (section 9.6). | +| `shade-kit version` | Prints the engine version and the installed integrations; with `--json` also the current format version per file type. **Implemented** (`VersionCommand`; integrations since package 07). Skills call it before they run (section 9.6). | | `shade-kit feature list` | Lists the features in the store with id, title, profile, and status. **Implemented** (`FeatureListCommand`). | Skills and agent files are not written into the repository (section 9.6, confirmed in the interview). The repository only holds kit data and the short instruction section. @@ -116,6 +116,7 @@ The split between `refine` and `map` is **proposed**: `refine` deals with the re - CLI as a `dotnet` global tool and as self-contained single-file binaries (see `CLAUDE.md`). An installer script for the binaries is **proposed**. - Plugin and CLI are released together under one version number and check each other's version (section 9.6). +- The plugin is not packed into the engine release: this repository is the Claude Code plugin marketplace (`.claude-plugin/`), and the release tag that builds the engine is the ref the engine installs from. **Decided** on 2026-11-13 (package 07 implementation). - Claude Code: plugin. Copilot: plugin if available, otherwise user directory. Codex: user directory. **Unverified:** whether Copilot and Codex can load the same `SKILL.md` format and support subagents and hooks. This decides how much of the content can be shared unchanged, and has to be researched before the integration work starts. ## 4. Store @@ -354,7 +355,7 @@ An engine writes back every field it does not know, unchanged. Changes that only - Skills and agent files are installed at user level, never written into the target repository. - Plugin content and CLI share one version number. A skill checks `shade-kit version` before it runs. -- The integration content is packed into the engine release, so an engine always installs the content of its own version (package 07). **Decided** on 2026-10-18. +- The integration content is packed into the engine release, so an engine always installs the content of its own version (package 07). **Decided** on 2026-10-18. Replaced on 2026-11-13 (package 07 implementation): the engine contains no content; this repository is the Claude Code plugin marketplace, and an engine installs the tree of its own tag `v` (a prerelease engine, and a release engine whose tag does not exist, installs from `main`). **Decided** on 2026-11-13. **Implemented** (`IntegrationService`). The skills' `metadata.version` is still raised by hand (package 06-2); since 2026-11-14 a guard test fails every build whose skills carry another major.minor than the engine version of the build, the tag build included (`SkillKitVersionTests`, package 07). **Decided** on 2026-11-14 (package 07 review rework). ### Why per-file versions diff --git a/skills/shade-kit-diagnose/SKILL.md b/skills/shade-kit-diagnose/SKILL.md index ca39f69..85c6b10 100644 --- a/skills/shade-kit-diagnose/SKILL.md +++ b/skills/shade-kit-diagnose/SKILL.md @@ -2,13 +2,11 @@ name: shade-kit-diagnose description: SHADE kit phase skill for `diagnose` (bugfix profile). Reproduces the reported bug, finds and proves its root cause, and writes diagnosis.md plus a spec.md with the expected behaviour. Use when the user wants to diagnose, reproduce, or find the root cause of the bug of the current SHADE kit feature. Runs only when the user calls it by name (`/shade-kit-diagnose`); never load it on your own or from another skill. metadata: - version: 0.7.0 + version: 0.8.0 --- # shade-kit-diagnose - - ## Purpose Replaces `refine` and `map` in the `bugfix` profile: the bug is made reproducible and its cause is traced in the code with evidence, so the fix addresses the cause and not the symptom. diff --git a/skills/shade-kit-discuss/SKILL.md b/skills/shade-kit-discuss/SKILL.md index 3cd1685..12796f8 100644 --- a/skills/shade-kit-discuss/SKILL.md +++ b/skills/shade-kit-discuss/SKILL.md @@ -2,13 +2,11 @@ name: shade-kit-discuss description: SHADE kit free brainstorming on any topic (an idea, a design question, a problem), with or without a current feature. Writes discussion notes that can feed a new feature or a refine round. Use when the user wants to discuss, brainstorm, or think something through in a SHADE kit repository. Runs only when the user calls it by name (`/shade-kit-discuss`) or asks for it; never load it on your own or from another skill. metadata: - version: 0.7.0 + version: 0.8.0 --- # shade-kit-discuss - - ## Purpose Open brainstorming outside every profile, possible at any time and in any phase. The result is a set of discussion notes. This skill never changes the feature state. @@ -17,7 +15,7 @@ Keep every `warnings` entry (`{ code, message }`) of every CLI call of this run. ## Flow -1. Version handshake: run `shade-kit version --json --expect 0.7.0`; 0.7.0 is the kit version of this skill (`metadata.version` in its frontmatter). +1. Version handshake: run `shade-kit version --json --expect 0.8.0`; 0.8.0 is the kit version of this skill (`metadata.version` in its frontmatter). - `ok` is `true`: continue. A warning `engine-prerelease-version-mismatch` means that a prerelease engine is used although its major or minor version differs; keep it like every warning and continue. - `ok` is `false` (for example `version-mismatch`), or the shell reports that `shade-kit` is not found: stop before any other CLI call. End ([Ending](#ending)) with **refusal** and the failure envelope, or with "`shade-kit` not found". 2. **Context:** `shade-kit feature current --json` to find out whether a feature is current. No feature is needed. A failure envelope (for example `kit-root-not-found` without `.shadekit/`, where the notes would be written): end with **refusal** and the envelope, before the discussion. diff --git a/skills/shade-kit-drop/SKILL.md b/skills/shade-kit-drop/SKILL.md index 7d8cd5a..308ad28 100644 --- a/skills/shade-kit-drop/SKILL.md +++ b/skills/shade-kit-drop/SKILL.md @@ -2,13 +2,11 @@ name: shade-kit-drop description: SHADE kit skill to drop a feature from any phase. Deletes the feature after explicit confirmation and clears the local override only if it points to the dropped feature. Use when the user wants to drop, cancel, abandon, or delete a SHADE kit feature. Runs only when the user calls it by name (`/shade-kit-drop`) or asks for it; never load it on your own or from another skill. metadata: - version: 0.7.0 + version: 0.8.0 --- # shade-kit-drop - - ## Purpose Removes a feature that will not be built, from any phase. `drop` is not a phase of any profile, so there is no entry protocol, but nothing is deleted without an explicit yes. @@ -17,7 +15,7 @@ Keep every `warnings` entry (`{ code, message }`) of every CLI call of this run. ## Flow -1. Version handshake: run `shade-kit version --json --expect 0.7.0`; 0.7.0 is the kit version of this skill (`metadata.version` in its frontmatter). +1. Version handshake: run `shade-kit version --json --expect 0.8.0`; 0.8.0 is the kit version of this skill (`metadata.version` in its frontmatter). - `ok` is `true`: continue. A warning `engine-prerelease-version-mismatch` means that a prerelease engine is used although its major or minor version differs; keep it like every warning and continue. - `ok` is `false` (for example `version-mismatch`), or the shell reports that `shade-kit` is not found: stop before any other CLI call. End ([Ending](#ending)) with **refusal** and the failure envelope, or with "`shade-kit` not found". 2. **Feature:** the feature the user named (`shade-kit feature show --json` for its profile and phase), or else `shade-kit feature current --json`. If no feature is resolved, run `shade-kit feature list --json` and ask the human which one to drop, with the agent's structured question tool (in Claude Code `AskUserQuestion`; without one, a plain question). No feature listed, no pick, or no answer: end with **end of work** and the line "No feature dropped." A failure envelope of any of these calls: end with **refusal** and the envelope. diff --git a/skills/shade-kit-finish/SKILL.md b/skills/shade-kit-finish/SKILL.md index 36c2a1d..3f01aa8 100644 --- a/skills/shade-kit-finish/SKILL.md +++ b/skills/shade-kit-finish/SKILL.md @@ -2,13 +2,11 @@ name: shade-kit-finish description: SHADE kit phase skill for `finish` (every profile). Checks the Definition of Done at the entry gate, optionally writes the feature report (requirements, tests, checks, approvals) with shade-kit-report, and sets the feature to done. Use when the user wants to finish, close, or complete the current SHADE kit feature. Runs only when the user calls it by name (`/shade-kit-finish`); never load it on your own or from another skill. metadata: - version: 0.7.0 + version: 0.8.0 --- # shade-kit-finish - - ## Purpose Closes the feature. The entry gate is the Definition of Done. On request it adds a traceable report: which requirements were built, which tests prove them, which checks passed, and who approved each transition. diff --git a/skills/shade-kit-gate-check/SKILL.md b/skills/shade-kit-gate-check/SKILL.md index f2be51f..08ad869 100644 --- a/skills/shade-kit-gate-check/SKILL.md +++ b/skills/shade-kit-gate-check/SKILL.md @@ -2,7 +2,7 @@ name: shade-kit-gate-check description: SHADE kit general skill that checks the feature's copy of a gate checklist (Definition of Ready, Definition of Done, or a team checklist) against the feature artifacts and the code base. Sets Result and Evidence of every item, logs the run in the Check runs section, and returns pass, fail, or error to the calling skill; never approves. Loaded by the entry protocol for every gate with a checklist; not meant to be called directly. metadata: - version: 0.7.0 + version: 0.8.0 --- # shade-kit-gate-check diff --git a/skills/shade-kit-implement/SKILL.md b/skills/shade-kit-implement/SKILL.md index 2dd46bc..c4498d7 100644 --- a/skills/shade-kit-implement/SKILL.md +++ b/skills/shade-kit-implement/SKILL.md @@ -2,13 +2,11 @@ name: shade-kit-implement description: SHADE kit phase skill for `implement` (feature and bugfix profiles). Works through tasks.md in a loop of implement, simplify, and independent review until the review has no open blockers; produces code, tests, and review.md. Bug fixes start with a failing regression test. Use when the user wants to implement the planned tasks of the current SHADE kit feature. Runs only when the user calls it by name (`/shade-kit-implement`); never load it on your own or from another skill. metadata: - version: 0.7.0 + version: 0.8.0 --- # shade-kit-implement - - ## Purpose Builds the plan task by task and does not stop at "it compiles": every change is simplified and reviewed independently before the feature can go to `verify`. diff --git a/skills/shade-kit-interview/SKILL.md b/skills/shade-kit-interview/SKILL.md index 4346bd2..cc2bb77 100644 --- a/skills/shade-kit-interview/SKILL.md +++ b/skills/shade-kit-interview/SKILL.md @@ -2,7 +2,7 @@ name: shade-kit-interview description: SHADE kit general skill for a structured clarification interview with the human. Asks about one topic per question with an own proposal and its alternatives, blocking topics first, records only the human's answers in the target artifact, and returns the answered, open, and dismissed topics to the calling skill. Loaded by the SHADE kit skills discuss, refine, diagnose, plan, and quick; not meant to be called directly. metadata: - version: 0.7.0 + version: 0.8.0 --- # shade-kit-interview diff --git a/skills/shade-kit-map/SKILL.md b/skills/shade-kit-map/SKILL.md index 273a7f8..40323a7 100644 --- a/skills/shade-kit-map/SKILL.md +++ b/skills/shade-kit-map/SKILL.md @@ -2,13 +2,11 @@ name: shade-kit-map description: SHADE kit phase skill for `map` (feature profile). Maps the current feature onto the code base with parallel research agents (best practice, existing architecture, affected code, don't hand-roll, security) and writes researches.md. Use when the user wants to map, analyse, or research the code base for the current SHADE kit feature. Runs only when the user calls it by name (`/shade-kit-map`); never load it on your own or from another skill. metadata: - version: 0.7.0 + version: 0.8.0 --- # shade-kit-map - - ## Purpose Finds out where and how the specified feature fits into the existing code, so the plan builds on facts instead of guesses. diff --git a/skills/shade-kit-new/SKILL.md b/skills/shade-kit-new/SKILL.md index c62b05b..dc51921 100644 --- a/skills/shade-kit-new/SKILL.md +++ b/skills/shade-kit-new/SKILL.md @@ -2,13 +2,11 @@ name: shade-kit-new description: SHADE kit phase skill for `new`. Creates a feature with a workflow profile (feature, bugfix, quick) from free text, an issue URL, a Markdown file, or discussion notes; the CLI writes request.md. Use when the user wants to start a new SHADE kit feature, bug fix, or quick change. Runs only when the user calls it by name (`/shade-kit-new`); never load it on your own or from another skill. metadata: - version: 0.7.0 + version: 0.8.0 --- # shade-kit-new - - ## Purpose Creates the feature folder (`feature.json`, `request.md`) so the work has lasting state. `new` is the first phase of every profile; `shade-kit feature new` sets it to `in-progress`, so there is no gate before it and no entry protocol. @@ -21,7 +19,7 @@ Keep every `warnings` entry (`{ code, message }`) of every CLI call of this run. ## Flow -1. Version handshake: run `shade-kit version --json --expect 0.7.0`; 0.7.0 is the kit version of this skill (`metadata.version` in its frontmatter). +1. Version handshake: run `shade-kit version --json --expect 0.8.0`; 0.8.0 is the kit version of this skill (`metadata.version` in its frontmatter). - `ok` is `true`: continue. A warning `engine-prerelease-version-mismatch` means that a prerelease engine is used although its major or minor version differs; keep it like every warning and continue. - `ok` is `false` (for example `version-mismatch`), or the shell reports that `shade-kit` is not found: stop before any other CLI call. End ([Ending](#ending)) with **refusal** and the failure envelope, or with "`shade-kit` not found". 2. **Active feature:** `shade-kit feature current --json`. A failure envelope (for example `kit-root-not-found` without `.shadekit/`): end with **refusal** and the envelope. If it resolves a feature with status `active`, tell the human which feature is current (id, phase, state) and ask, with the agent's structured question tool (in Claude Code `AskUserQuestion`; without one, a plain question): create a new feature anyway, or end here. On "end here", or without an answer, end with **end of work** and the line "No new feature created; `` stays current." No current feature, or a `done` one: go on. diff --git a/skills/shade-kit-next-phase/SKILL.md b/skills/shade-kit-next-phase/SKILL.md index 30149af..d9ad819 100644 --- a/skills/shade-kit-next-phase/SKILL.md +++ b/skills/shade-kit-next-phase/SKILL.md @@ -2,7 +2,7 @@ name: shade-kit-next-phase description: "SHADE kit status and next steps. Finds the current feature, or lets the human pick one, and shows its phase and state and every possible next step with the SHADE kit skill to call for it. Advisory: starts no phase and no skill. Use when the human says 'continue', 'next phase', or 'what's next', or asks where a SHADE kit feature stands or what to do with it now." metadata: - version: 0.7.0 + version: 0.8.0 --- # shade-kit-next-phase @@ -19,7 +19,7 @@ Keep every `warnings` entry (`{ code, message }`) of every CLI call of this run. ### 1. Version handshake -Version handshake: run `shade-kit version --json --expect 0.7.0`; 0.7.0 is the kit version of this skill (`metadata.version` in its frontmatter). +Version handshake: run `shade-kit version --json --expect 0.8.0`; 0.8.0 is the kit version of this skill (`metadata.version` in its frontmatter). - `ok` is `true`: continue. A warning `engine-prerelease-version-mismatch` means that a prerelease engine is used although its major or minor version differs; keep it like every warning and continue. - `ok` is `false` (for example `version-mismatch`), or the shell reports that `shade-kit` is not found: stop before any other CLI call. End ([Ending](#ending)) with **refusal** and the failure envelope, or with "`shade-kit` not found". @@ -90,7 +90,7 @@ The closing message of `shade-kit-next-steps` is the end of this skill; write no ## Rules - Start no skill and no phase. Name skills; the human calls them. Do not ask which step the human wants and do not offer to run one. -- The only commands this skill runs are `shade-kit version --json --expect 0.7.0`, `shade-kit feature current --json`, `shade-kit feature list --json`, `shade-kit feature set --json`, and `shade-kit phase next --json`. Run `feature set` only after the human picked that feature in step 2. Never `phase start`, `phase approve`, `phase reject`, `phase complete`, `gate info`, `feature new`, `feature drop`, or `init`. +- The only commands this skill runs are `shade-kit version --json --expect 0.8.0`, `shade-kit feature current --json`, `shade-kit feature list --json`, `shade-kit feature set --json`, and `shade-kit phase next --json`. Run `feature set` only after the human picked that feature in step 2. Never `phase start`, `phase approve`, `phase reject`, `phase complete`, `gate info`, `feature new`, `feature drop`, or `init`. - Never run a gate check and never load `shade-kit-gate-check`. Load only `shade-kit-next-steps`. - Do not derive steps from the profile and do not add or drop any: the steps are those of `phase next`, plus `/shade-kit-discuss` and `/shade-kit-drop`. - Never read or write `feature.json`, `gates.json`, or `config.json`; the state comes from the CLI. Read no artifact and write no file. diff --git a/skills/shade-kit-next-steps/SKILL.md b/skills/shade-kit-next-steps/SKILL.md index 0001354..7d26e08 100644 --- a/skills/shade-kit-next-steps/SKILL.md +++ b/skills/shade-kit-next-steps/SKILL.md @@ -2,7 +2,7 @@ name: shade-kit-next-steps description: SHADE kit general skill that writes the closing message of a kit skill. Shows what the human can do now and which skill to call for it, after the end of the work, a "no", or a refused start, and shows the warnings of the CLI calls. Starts nothing. Loaded by every SHADE kit skill that ends; not meant to be called directly. metadata: - version: 0.7.0 + version: 0.8.0 --- # shade-kit-next-steps diff --git a/skills/shade-kit-phase-entry/SKILL.md b/skills/shade-kit-phase-entry/SKILL.md index 7fc7961..a97f04f 100644 --- a/skills/shade-kit-phase-entry/SKILL.md +++ b/skills/shade-kit-phase-entry/SKILL.md @@ -2,7 +2,7 @@ name: shade-kit-phase-entry description: "SHADE kit general skill that runs the entry protocol of a phase skill: the version handshake, `phase start` for the caller's phase, the gate check, and the human's approval of the transition. Tells the phase skill whether to run its phase and which skills to load, or ends the run with the next-steps message. Loaded as the first step of every SHADE kit phase skill (refine, map, plan, implement, verify, finish, diagnose, quick); not meant to be called directly." metadata: - version: 0.7.0 + version: 0.8.0 --- # shade-kit-phase-entry @@ -25,7 +25,7 @@ Keep every `warnings` entry (`{ code, message }`) of every CLI call of this run. ### 1. Version handshake -Version handshake: run `shade-kit version --json --expect 0.7.0`; 0.7.0 is the kit version of this skill (`metadata.version` in its frontmatter). +Version handshake: run `shade-kit version --json --expect 0.8.0`; 0.8.0 is the kit version of this skill (`metadata.version` in its frontmatter). - `ok` is `true`: continue. A warning `engine-prerelease-version-mismatch` means that a prerelease engine is used although its major or minor version differs; keep it like every warning and continue. - `ok` is `false` (for example `version-mismatch`), or the shell reports that `shade-kit` is not found: stop before anything else. End with **refusal** and the failure envelope, or with "`shade-kit` not found". @@ -172,7 +172,7 @@ Then give the calling skill the ended [return](#return). ## Rules - Run `phase start` only for the phase of the calling skill. Run `phase approve` only for ``, and `phase reject` only for `` (step 4) or for `transition.to` of `resume-pending`, each only after the human's answer. -- The only commands this skill runs are `shade-kit version --json --expect 0.7.0`, `shade-kit phase start`, `shade-kit phase approve`, and `shade-kit phase reject`, the last three with `--json`. Never `phase complete`, `phase next` (the next-steps message runs it), a `feature` command, or `init`. +- The only commands this skill runs are `shade-kit version --json --expect 0.8.0`, `shade-kit phase start`, `shade-kit phase approve`, and `shade-kit phase reject`, the last three with `--json`. Never `phase complete`, `phase next` (the next-steps message runs it), a `feature` command, or `init`. - Never read or write `feature.json`, `gates.json`, or `config.json`; the state comes from the CLI. - Do no phase work: read no artifact and write no file. The gate check reads the artifacts. - Load only `shade-kit-gate-check` and `shade-kit-next-steps`. Start no phase skill. diff --git a/skills/shade-kit-plan/SKILL.md b/skills/shade-kit-plan/SKILL.md index 5f8865f..907a82c 100644 --- a/skills/shade-kit-plan/SKILL.md +++ b/skills/shade-kit-plan/SKILL.md @@ -2,13 +2,11 @@ name: shade-kit-plan description: SHADE kit phase skill for `plan` (feature and bugfix profiles). Writes plan.md with design decisions and test strategy and tasks.md with the requirement-to-test mapping and coverage matrix; short variant for bug fixes. Use when the user wants to plan the implementation of the current SHADE kit feature. Runs only when the user calls it by name (`/shade-kit-plan`); never load it on your own or from another skill. metadata: - version: 0.7.0 + version: 0.8.0 --- # shade-kit-plan - - ## Purpose Decides how the spec is built and why, and binds every acceptance criterion to the test that will prove it. The entry gate is the Definition of Ready. diff --git a/skills/shade-kit-quick/SKILL.md b/skills/shade-kit-quick/SKILL.md index f65b4f3..eb5f2b9 100644 --- a/skills/shade-kit-quick/SKILL.md +++ b/skills/shade-kit-quick/SKILL.md @@ -2,13 +2,11 @@ name: shade-kit-quick description: SHADE kit phase skill for the `quick` phase (quick profile). Runs short clarification, a compact spec, implementation with tests, simplify and review, and a self-check in one go, with a single approval at the end. Use when the current SHADE kit feature has the quick profile and the user wants to implement it. Runs only when the user calls it by name (`/shade-kit-quick`); never load it on your own or from another skill. metadata: - version: 0.7.0 + version: 0.8.0 --- # shade-kit-quick - - ## Purpose Runs the `quick` phase of the `quick` profile (`new` → `quick` → `finish`): a mini run of refine, plan, and implement for small, clear changes. It still leaves enough traces (`spec.md`, `review.md`, `verification.md`) for the Definition of Done and the report. diff --git a/skills/shade-kit-refine/SKILL.md b/skills/shade-kit-refine/SKILL.md index a8f102e..bd789d0 100644 --- a/skills/shade-kit-refine/SKILL.md +++ b/skills/shade-kit-refine/SKILL.md @@ -2,13 +2,11 @@ name: shade-kit-refine description: SHADE kit phase skill for `refine` (feature profile). Clarifies the requirement of the current feature through research and a structured interview and writes spec.md with requirement IDs, acceptance criteria, and out of scope. Can run several times. Use when the user wants to refine, clarify, or specify the current SHADE kit feature. Runs only when the user calls it by name (`/shade-kit-refine`); never load it on your own or from another skill. metadata: - version: 0.7.0 + version: 0.8.0 --- # shade-kit-refine - - ## Purpose Turns the raw request into a testable specification: vague statements, gaps, contradictions, and unstated assumptions are found and resolved with the human. diff --git a/skills/shade-kit-report/SKILL.md b/skills/shade-kit-report/SKILL.md index f698728..269f27d 100644 --- a/skills/shade-kit-report/SKILL.md +++ b/skills/shade-kit-report/SKILL.md @@ -2,13 +2,11 @@ name: shade-kit-report description: "SHADE kit general skill that writes report.md for a finished feature: requirements, acceptance criteria and proving tests, check results, review findings, manual checks, deviations, and approvals. Optional; loaded by the SHADE kit skill finish only when a report is written; not meant to be called directly." metadata: - version: 0.7.0 + version: 0.8.0 --- # shade-kit-report - - ## Purpose Collects the evidence of a feature in one place, so reviewers of the pull request do not have to gather it from several artifacts. The report is optional: `finish` loads this skill only when the `report` setting (`ask`, `always`, `never`) leads to a report. diff --git a/skills/shade-kit-research/SKILL.md b/skills/shade-kit-research/SKILL.md index b937e85..9e7a63e 100644 --- a/skills/shade-kit-research/SKILL.md +++ b/skills/shade-kit-research/SKILL.md @@ -2,7 +2,7 @@ name: shade-kit-research description: SHADE kit general skill that runs the research focuses a calling skill names, one subagent per focus in parallel where the agent can start subagents and one after the other otherwise, checks the sources of every finding, and merges the results into the feature's researches.md, one section per phase and focus. Loaded by the SHADE kit skills refine, map, and diagnose; not meant to be called directly. metadata: - version: 0.7.0 + version: 0.8.0 --- # shade-kit-research diff --git a/skills/shade-kit-review/SKILL.md b/skills/shade-kit-review/SKILL.md index 0ff2401..7192ce1 100644 --- a/skills/shade-kit-review/SKILL.md +++ b/skills/shade-kit-review/SKILL.md @@ -2,13 +2,11 @@ name: shade-kit-review description: SHADE kit general skill for an independent code review of the current change against spec.md, plan.md, and the repository's conventions, with findings classified by severity (blocker, major, minor, note) in review.md. Loaded by the SHADE kit skills implement and quick; not meant to be called directly. metadata: - version: 0.7.0 + version: 0.8.0 --- # shade-kit-review - - ## Purpose Decides whether the implementation loop may end: only an open blocker keeps it going. The review runs in a separate context that did not write the code. diff --git a/skills/shade-kit-verify/SKILL.md b/skills/shade-kit-verify/SKILL.md index d5e1a61..ce9b575 100644 --- a/skills/shade-kit-verify/SKILL.md +++ b/skills/shade-kit-verify/SKILL.md @@ -2,13 +2,11 @@ name: shade-kit-verify description: SHADE kit phase skill for `verify` (feature and bugfix profiles). Runs the quality checks, confirms that every acceptance criterion is covered by a passing test, and writes verification.md and a playbook.md for manual tests. Use when the user wants to verify or test the implementation of the current SHADE kit feature. Runs only when the user calls it by name (`/shade-kit-verify`); never load it on your own or from another skill. metadata: - version: 0.7.0 + version: 0.8.0 --- # shade-kit-verify - - ## Purpose Proves that the implementation meets the spec: automated checks by the agent, plus a playbook for what a human has to see working. diff --git a/src/CreativeCoders.ShadeKit.Cli/Commands/Integrations/Install/AgentOptionConverter.cs b/src/CreativeCoders.ShadeKit.Cli/Commands/Integrations/Install/AgentOptionConverter.cs new file mode 100644 index 0000000..1f4b647 --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Cli/Commands/Integrations/Install/AgentOptionConverter.cs @@ -0,0 +1,51 @@ +using CreativeCoders.ShadeKit.Core.Integrations; +using CreativeCoders.ShadeKit.Core.Integrations.Claude; +using CreativeCoders.SysConsole.Cli.Parsing; +using CreativeCoders.SysConsole.Cli.Parsing.OptionProperties; + +namespace CreativeCoders.ShadeKit.Cli.Commands.Integrations.Install; + +/// +/// Converts the value of --agent to the id of a supported agent and rejects the option when it is given without +/// a value or with an unknown id. +/// +/// +/// +/// The option parser of CreativeCoders.SysConsole.Cli.Parsing creates the converter with its parameterless +/// constructor and calls it only for an option that is on the command line. It passes as the +/// value when the option is the last argument or the next argument starts with -. +/// +/// +/// Because the parser does not resolve converters from the service provider, the converter cannot ask +/// ; lists the same ids, which a test +/// checks against the registered . +/// +/// +public sealed class AgentOptionConverter : ICliValueConverter +{ + /// + /// Gets the ids of the agents that --agent accepts. + /// + /// The agent ids in the order of , today claude. + public static IReadOnlyList SupportedAgentIds { get; } = [ClaudeCodeIntegration.ClaudeAgentId]; + + /// + /// Converts the specified value of --agent to the id of a supported agent. + /// + /// The value that follows --agent, or if there is none. + /// The type of the option property. + /// The attribute that declares the option. + /// + /// The id from that equals the value, compared case-insensitively. + /// + /// + /// is or no id of a supported agent. + /// + public object? Convert(object? value, Type targetType, OptionBaseAttribute optionAttribute) + { + var text = value?.ToString(); + + return SupportedAgentIds.FirstOrDefault(x => string.Equals(x, text, StringComparison.OrdinalIgnoreCase)) + ?? throw new InvalidAgentOptionException(text, SupportedAgentIds); + } +} diff --git a/src/CreativeCoders.ShadeKit.Cli/Commands/Integrations/Install/IntegrationsInstallCommand.cs b/src/CreativeCoders.ShadeKit.Cli/Commands/Integrations/Install/IntegrationsInstallCommand.cs new file mode 100644 index 0000000..00ad120 --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Cli/Commands/Integrations/Install/IntegrationsInstallCommand.cs @@ -0,0 +1,67 @@ +using CreativeCoders.Cli.Core; +using CreativeCoders.Cli.Hosting.Exceptions; +using CreativeCoders.Core; +using CreativeCoders.ShadeKit.Cli.Output; +using CreativeCoders.ShadeKit.Core.Integrations; +using JetBrains.Annotations; + +namespace CreativeCoders.ShadeKit.Cli.Commands.Integrations.Install; + +/// +/// Installs the SHADE kit integration for the user in the specified agent or in every detected agent, and updates it +/// where it is installed. +/// +/// +/// The command works outside a git repository and writes nothing into the current repository. +/// +/// The context that runs the install and writes the result or the failure. +/// The service that installs the integrations. +[UsedImplicitly] +[CliCommand([IntegrationsCommandGroup.Name, Name], + Description = "Installs the SHADE kit integration in the agents for the user")] +public class IntegrationsInstallCommand( + ShadeKitCommandContext context, + IIntegrationService integrationService) + : ICliCommand +{ + /// + /// Represents the command name used on the command line within the . + /// + public const string Name = "install"; + + private readonly ShadeKitCommandContext _context = Ensure.NotNull(context); + + private readonly IIntegrationService _integrationService = Ensure.NotNull(integrationService); + + /// + /// Installs the integration and writes the result of each agent, as plain text or as a JSON envelope. + /// + /// The options of the command. + /// + /// A task that represents the asynchronous operation. The task result is . + /// + /// is . + /// + /// No agent is detected or the named agent is missing (exit code + /// ), an agent command cannot be run or fails (exit code + /// ), the agent knows the marketplace of SHADE kit with + /// another source (exit code ), or the marketplace source + /// override is invalid (exit code ). + /// + /// The user canceled the run. + public async Task ExecuteAsync(IntegrationsInstallCommandOptions options) + { + Ensure.NotNull(options); + + IReadOnlyCollection? agentIds = options.Agent is { } agent ? [agent] : null; + + var result = await _context.RunAsync(options.Json, + cancellationToken => _integrationService.InstallAsync(agentIds, cancellationToken)) + .ConfigureAwait(false); + + _context.WriteSuccess(options.Json, IntegrationRunData.From(result), result.Warnings, + () => IntegrationsTextFormat.WriteRun(_context.Console, result)); + + return CommandResult.Success; + } +} diff --git a/src/CreativeCoders.ShadeKit.Cli/Commands/Integrations/Install/IntegrationsInstallCommandOptions.cs b/src/CreativeCoders.ShadeKit.Cli/Commands/Integrations/Install/IntegrationsInstallCommandOptions.cs new file mode 100644 index 0000000..553d71b --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Cli/Commands/Integrations/Install/IntegrationsInstallCommandOptions.cs @@ -0,0 +1,23 @@ +using CreativeCoders.SysConsole.Cli.Parsing; + +namespace CreativeCoders.ShadeKit.Cli.Commands.Integrations.Install; + +/// +/// Represents the options of the . +/// +public class IntegrationsInstallCommandOptions : JsonCommandOptions +{ + /// + /// Gets or sets the id of the agent to install the SHADE kit integration for. + /// + /// + /// The id of a supported agent, for example claude, as listed in + /// , or to install for every detected + /// agent. --agent without a value or with an unknown id is rejected while the arguments are read (see + /// ). The default is . + /// + [OptionParameter("agent", + HelpText = "The agent to install for, for example 'claude'; without it, every detected agent", + Converter = typeof(AgentOptionConverter))] + public string? Agent { get; set; } +} diff --git a/src/CreativeCoders.ShadeKit.Cli/Commands/Integrations/Install/InvalidAgentOptionException.cs b/src/CreativeCoders.ShadeKit.Cli/Commands/Integrations/Install/InvalidAgentOptionException.cs new file mode 100644 index 0000000..7f61acf --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Cli/Commands/Integrations/Install/InvalidAgentOptionException.cs @@ -0,0 +1,29 @@ +namespace CreativeCoders.ShadeKit.Cli.Commands.Integrations.Install; + +/// +/// Represents the exception that is thrown when --agent is given without a value or with an id that is not the +/// id of a supported agent. +/// +/// +/// The option parser throws it while it reads the arguments of shade-kit integrations install, before the +/// command runs, so it reaches the CLI host as an argument error. +/// +/// The value that follows --agent, or if there is none. +/// The ids of the supported agents. +public sealed class InvalidAgentOptionException(string? value, IReadOnlyList supportedAgentIds) + : Exception(value is null + ? "The option '--agent' was given without an agent id." + : $"The agent '{value}' of the option '--agent' is not supported.") +{ + /// + /// Gets the value that follows --agent. + /// + /// The value as passed, or if --agent was given without a value. + public string? Value { get; } = value; + + /// + /// Gets the ids of the supported agents. + /// + /// The agent ids, for example claude. + public IReadOnlyList SupportedAgentIds { get; } = supportedAgentIds; +} diff --git a/src/CreativeCoders.ShadeKit.Cli/Commands/Integrations/IntegrationResultData.cs b/src/CreativeCoders.ShadeKit.Cli/Commands/Integrations/IntegrationResultData.cs new file mode 100644 index 0000000..730686a --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Cli/Commands/Integrations/IntegrationResultData.cs @@ -0,0 +1,54 @@ +using CreativeCoders.Core; +using CreativeCoders.ShadeKit.Core.Integrations; + +namespace CreativeCoders.ShadeKit.Cli.Commands.Integrations; + +/// +/// Represents the result of one agent in the data object that shade-kit integrations install --json and +/// shade-kit integrations update --json return. +/// +/// The id of the agent, for example claude. +/// +/// The id of the integration in the agent, for example shade-kit@creativecoders-shade-kit. +/// +/// +/// One of the enumeration values that specifies what was done, written as installed, updated, or +/// current. +/// +/// +/// The kit version that was installed before, or if the integration was not installed or its +/// ref was no v<SemVer> tag. +/// +/// +/// The kit version that is installed now, or if the ref is no v<SemVer> tag or +/// the source is a local directory. +/// +/// +/// The branch or tag that is installed now, or for a local directory or the default branch. +/// +/// +/// if the integration is enabled in the agent; otherwise, . +/// +public sealed record IntegrationResultData( + string Agent, + string PluginId, + IntegrationOutcome Outcome, + string? PreviousKitVersion, + string? KitVersion, + string? Ref, + bool Enabled) +{ + /// + /// Creates the data of the specified result of an agent. + /// + /// The result of the agent. + /// The data with the values of . + /// is . + public static IntegrationResultData From(IntegrationResult result) + { + Ensure.NotNull(result); + + return new IntegrationResultData(result.AgentId, result.PluginId, result.Outcome, result.PreviousKitVersion, + result.KitVersion, result.Ref, result.Enabled); + } +} diff --git a/src/CreativeCoders.ShadeKit.Cli/Commands/Integrations/IntegrationRunData.cs b/src/CreativeCoders.ShadeKit.Cli/Commands/Integrations/IntegrationRunData.cs new file mode 100644 index 0000000..5ffb351 --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Cli/Commands/Integrations/IntegrationRunData.cs @@ -0,0 +1,43 @@ +using CreativeCoders.Core; +using CreativeCoders.ShadeKit.Core.Integrations; + +namespace CreativeCoders.ShadeKit.Cli.Commands.Integrations; + +/// +/// Represents the data object that shade-kit integrations install --json and +/// shade-kit integrations update --json return. +/// +/// +/// The branch or tag of the marketplace source that the engine targets, for example v0.8.0 or main, or +/// if the source is a local directory or a GitHub repository without a branch or tag, or if +/// an update found no installed integration and resolved no source. +/// +/// +/// The marketplace source as the agent CLI takes it: owner/repo#ref or owner/repo for a GitHub +/// repository, for example CreativeCodersTeam/shade-kit#v0.8.0, or the absolute path of a local directory +/// that the environment variable SHADE_KIT_MARKETPLACE_SOURCE names; if an update +/// found no installed integration and resolved no source. +/// +/// +/// The result of each agent, in the order in which the agents are registered; an empty list if an update found no +/// installed integration. +/// +public sealed record IntegrationRunData( + string? Ref, + string? Source, + IReadOnlyList Integrations) +{ + /// + /// Creates the data of the specified run. + /// + /// The result of the install or update. + /// The data with the targeted source and the result of each agent. + /// is . + public static IntegrationRunData From(IntegrationRunResult result) + { + Ensure.NotNull(result); + + return new IntegrationRunData(result.Source?.Ref, result.Source?.Text, + [.. result.Integrations.Select(IntegrationResultData.From)]); + } +} diff --git a/src/CreativeCoders.ShadeKit.Cli/Commands/Integrations/IntegrationsCommandGroup.cs b/src/CreativeCoders.ShadeKit.Cli/Commands/Integrations/IntegrationsCommandGroup.cs new file mode 100644 index 0000000..8d5f036 --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Cli/Commands/Integrations/IntegrationsCommandGroup.cs @@ -0,0 +1,19 @@ +using CreativeCoders.Cli.Core; +using CreativeCoders.ShadeKit.Cli.Commands.Integrations; + +[assembly: CliCommandGroup([IntegrationsCommandGroup.Name], + "Commands for installing and updating the SHADE kit integrations of the agents")] + +namespace CreativeCoders.ShadeKit.Cli.Commands.Integrations; + +/// +/// Defines the command group that contains the commands for installing and updating the SHADE kit integrations of the +/// supported agents, such as the plugin of Claude Code. +/// +public static class IntegrationsCommandGroup +{ + /// + /// Represents the group name used on the command line. + /// + public const string Name = "integrations"; +} diff --git a/src/CreativeCoders.ShadeKit.Cli/Commands/Integrations/IntegrationsTextFormat.cs b/src/CreativeCoders.ShadeKit.Cli/Commands/Integrations/IntegrationsTextFormat.cs new file mode 100644 index 0000000..decc98a --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Cli/Commands/Integrations/IntegrationsTextFormat.cs @@ -0,0 +1,174 @@ +using CreativeCoders.Core; +using CreativeCoders.ShadeKit.Cli.Output; +using CreativeCoders.ShadeKit.Core.Integrations; +using CreativeCoders.ShadeKit.Core.Integrations.Claude; +using CreativeCoders.SysConsole.Core; +using Spectre.Console; + +namespace CreativeCoders.ShadeKit.Cli.Commands.Integrations; + +/// +/// Writes the results of the shade-kit integrations commands, and the installed integrations that +/// shade-kit version lists, as Spectre.Console markup for the plain output. +/// +/// +/// Every method escapes the values it formats, so its result can be written with MarkupLine as it is. +/// +internal static class IntegrationsTextFormat +{ + /// + /// Represents the line written when an update finds no installed integration. + /// + public const string NothingInstalledText = "No SHADE kit integration is installed."; + + /// + /// Represents the line written after the integration of Claude Code was installed or updated. + /// + public const string RestartClaudeText = "Restart Claude Code to load the skills."; + + /// + /// Writes one line per agent of the specified run, a note for every disabled integration, and the hint to restart + /// Claude Code if its integration was installed or updated. + /// + /// + /// A run without results or without a source writes and a hint to + /// shade-kit integrations install. + /// + /// The console that receives the lines. + /// The result of the install or update. + /// + /// or is . + /// + public static void WriteRun(IAnsiConsole console, IntegrationRunResult result) + { + Ensure.NotNull(console); + Ensure.NotNull(result); + + if (result.Integrations.Count == 0 || result.Source is not { } source) + { + console.MarkupLine(NothingInstalledText.ToEscapedMarkup().ToWarningMarkup()); + console.MarkupLine( + $"Run '{"shade-kit integrations install".ToCommandMarkup()}' to install it."); + + return; + } + + foreach (var integration in result.Integrations) + { + console.MarkupLine(FormatResult(integration, source)); + + if (!integration.Enabled) + { + console.MarkupLine($" {FormatDisabledNote(integration.AgentId, integration.PluginId)}"); + } + } + + if (result.Integrations.Any(x => x.Outcome != IntegrationOutcome.Current && + x.AgentId == ClaudeCodeIntegration.ClaudeAgentId)) + { + console.MarkupLine(RestartClaudeText.ToEscapedMarkup().ToMutedMarkup()); + } + } + + /// + /// Formats the result of one agent of an install or update. + /// + /// The result of the agent. + /// The marketplace source that the engine targeted. + /// + /// The markup of the text <agent>: <outcome> <plugin id> <version>, for example + /// claude: installed shade-kit@creativecoders-shade-kit 0.8.0 (v0.8.0), + /// claude: updated shade-kit@creativecoders-shade-kit 0.7.0 -> 0.8.0 (v0.8.0), or + /// claude: already current shade-kit@creativecoders-shade-kit 0.8.0 (v0.8.0). Without a ref the version is + /// from <path> for a local directory and (default branch) for a GitHub repository. + /// + /// + /// or is . + /// + public static string FormatResult(IntegrationResult result, MarketplaceSource source) + { + Ensure.NotNull(result); + Ensure.NotNull(source); + + var version = FormatVersion(result.KitVersion, result.Ref, + result.Ref is null ? FormatSourceWithoutRef(source) : string.Empty); + + if (result is { Outcome: IntegrationOutcome.Updated, PreviousKitVersion: { } previousKitVersion }) + { + version = $"{previousKitVersion.ToEscapedMarkup()} -> {version}"; + } + + var outcome = result.Outcome switch + { + IntegrationOutcome.Installed => "installed".ToSuccessMarkup(), + IntegrationOutcome.Updated => "updated".ToSuccessMarkup(), + IntegrationOutcome.Current => "already current".ToMutedMarkup(), + _ => result.Outcome.ToString().ToEscapedMarkup() + }; + + return JoinParts($"{result.AgentId.ToEscapedMarkup().ToBoldMarkup()}:", outcome, + result.PluginId.ToEscapedMarkup(), version); + } + + /// + /// Formats an integration that is installed in an agent, as shade-kit version lists it. + /// + /// The installed integration. + /// + /// The markup of the text <agent>: <plugin id> <version>, for example + /// claude: shade-kit@creativecoders-shade-kit 0.8.0 (v0.8.0), followed by (disabled) if the + /// integration is disabled. + /// + /// is . + public static string FormatInstalled(InstalledIntegration integration) + { + Ensure.NotNull(integration); + + return JoinParts($"{integration.AgentId.ToEscapedMarkup().ToBoldMarkup()}:", + integration.PluginId.ToEscapedMarkup(), + FormatVersion(integration.KitVersion, integration.Ref, string.Empty), + integration.Enabled ? string.Empty : "(disabled)".ToWarningMarkup()); + } + + /// + /// Formats the note that an integration is disabled and how to enable it. + /// + /// The id of the agent. + /// The id of the integration in the agent. + /// + /// The markup of a sentence that names claude plugin enable <plugin id> for Claude Code, or that + /// says to enable the integration in the agent for any other agent. + /// + public static string FormatDisabledNote(string agentId, string pluginId) + { + if (agentId == ClaudeCodeIntegration.ClaudeAgentId) + { + var command = $"claude plugin enable {pluginId}".ToEscapedMarkup().ToCommandMarkup(); + + return $"{"The plugin is disabled in Claude Code.".ToWarningMarkup()} Run '{command}' to enable it."; + } + + return $"The integration is disabled in the agent '{agentId.ToEscapedMarkup()}'; enable it there." + .ToWarningMarkup(); + } + + // The kit version comes first, then the ref in parentheses, or the markup that stands for a missing ref. + private static string FormatVersion(string? kitVersion, string? @ref, string missingRefMarkup) + { + return JoinParts(kitVersion?.ToEscapedMarkup() ?? string.Empty, + @ref is null ? missingRefMarkup : $"({@ref.ToEscapedMarkup()})"); + } + + // A source without a ref is a local directory, named by its path, or the default branch of a GitHub repository. + private static string FormatSourceWithoutRef(MarketplaceSource source) + { + return source.Path is { } path + ? $"from {path.ToEscapedMarkup()}" + : "(default branch)"; + } + + private static string JoinParts(params string[] parts) + { + return string.Join(' ', parts.Where(x => x.Length > 0)); + } +} diff --git a/src/CreativeCoders.ShadeKit.Cli/Commands/Integrations/Update/IntegrationsUpdateCommand.cs b/src/CreativeCoders.ShadeKit.Cli/Commands/Integrations/Update/IntegrationsUpdateCommand.cs new file mode 100644 index 0000000..ee619f8 --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Cli/Commands/Integrations/Update/IntegrationsUpdateCommand.cs @@ -0,0 +1,68 @@ +using CreativeCoders.Cli.Core; +using CreativeCoders.Cli.Hosting.Exceptions; +using CreativeCoders.Core; +using CreativeCoders.ShadeKit.Cli.Output; +using CreativeCoders.ShadeKit.Core.Integrations; +using JetBrains.Annotations; + +namespace CreativeCoders.ShadeKit.Cli.Commands.Integrations.Update; + +/// +/// Updates the SHADE kit integration in every detected agent in which it is installed for the user. +/// +/// +/// The command works outside a git repository and writes nothing into the current repository. +/// +/// The context that runs the update and writes the result or the failure. +/// The service that updates the integrations. +[UsedImplicitly] +[CliCommand([IntegrationsCommandGroup.Name, Name], + Description = "Updates the installed SHADE kit integrations to the version of this engine")] +public class IntegrationsUpdateCommand( + ShadeKitCommandContext context, + IIntegrationService integrationService) + : ICliCommand +{ + /// + /// Represents the command name used on the command line within the . + /// + public const string Name = "update"; + + private readonly ShadeKitCommandContext _context = Ensure.NotNull(context); + + private readonly IIntegrationService _integrationService = Ensure.NotNull(integrationService); + + /// + /// Updates the installed integrations and writes the result of each agent, as plain text or as a JSON envelope. + /// + /// + /// No installed integration is a result, not an error: the envelope has an empty integrations list, and + /// the plain output says that nothing is installed. + /// + /// The options of the command. + /// + /// A task that represents the asynchronous operation. The task result is . + /// + /// is . + /// + /// No agent is detected (exit code ), an agent command cannot be + /// run or fails (exit code ), the agent knows the + /// marketplace of SHADE kit with another source (exit code + /// ), or the marketplace source override is invalid (exit + /// code ). + /// + /// The user canceled the run. + public async Task ExecuteAsync(IntegrationsUpdateCommandOptions options) + { + Ensure.NotNull(options); + + var result = await _context.RunAsync(options.Json, + cancellationToken => _integrationService.UpdateAsync(cancellationToken)) + .ConfigureAwait(false); + + _context.WriteSuccess(options.Json, IntegrationRunData.From(result), result.Warnings, + () => IntegrationsTextFormat.WriteRun(_context.Console, result)); + + return CommandResult.Success; + } +} diff --git a/src/CreativeCoders.ShadeKit.Cli/Commands/Integrations/Update/IntegrationsUpdateCommandOptions.cs b/src/CreativeCoders.ShadeKit.Cli/Commands/Integrations/Update/IntegrationsUpdateCommandOptions.cs new file mode 100644 index 0000000..681c1f8 --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Cli/Commands/Integrations/Update/IntegrationsUpdateCommandOptions.cs @@ -0,0 +1,10 @@ +using System.Diagnostics.CodeAnalysis; + +namespace CreativeCoders.ShadeKit.Cli.Commands.Integrations.Update; + +/// +/// Represents the options of the . +/// +[SuppressMessage("Minor Code Smell", "S2094:Classes should not be empty", + Justification = "Every command needs its own options type; this command has no options beyond --json.")] +public class IntegrationsUpdateCommandOptions : JsonCommandOptions; diff --git a/src/CreativeCoders.ShadeKit.Cli/Commands/Version/VersionCommand.cs b/src/CreativeCoders.ShadeKit.Cli/Commands/Version/VersionCommand.cs index 33f889d..addc215 100644 --- a/src/CreativeCoders.ShadeKit.Cli/Commands/Version/VersionCommand.cs +++ b/src/CreativeCoders.ShadeKit.Cli/Commands/Version/VersionCommand.cs @@ -1,30 +1,36 @@ using CreativeCoders.Cli.Core; using CreativeCoders.Cli.Hosting.Exceptions; using CreativeCoders.Core; +using CreativeCoders.ShadeKit.Cli.Commands.Integrations; using CreativeCoders.ShadeKit.Cli.Output; using CreativeCoders.ShadeKit.Core.Engine; using CreativeCoders.ShadeKit.Core.Formats; +using CreativeCoders.ShadeKit.Core.Integrations; using CreativeCoders.ShadeKit.Core.Versions; +using CreativeCoders.ShadeKit.Core.Warnings; using JetBrains.Annotations; using Spectre.Console; namespace CreativeCoders.ShadeKit.Cli.Commands.Version; /// -/// Prints the version of the SHADE kit engine and, in JSON mode, the format version of every file type it supports, -/// and checks the engine against the version that the kit skills expect if one is given. +/// Prints the version of the SHADE kit engine, the SHADE kit integrations installed in the agents, and, in JSON mode, +/// the format version of every file type the engine supports, and checks the engine against the version that the kit +/// skills expect if one is given. /// /// The context that runs the version check and writes the result or the failure. /// The provider of the running engine version. /// The registry of the file types the engine supports. /// The checker that compares the engine version with the expected version. +/// The service that reads the installed integrations. [UsedImplicitly] [CliCommand([Name], Description = "Shows the version of SHADE kit")] public class VersionCommand( ShadeKitCommandContext context, IEngineVersionProvider engineVersionProvider, IFormatRegistry formatRegistry, - IEngineVersionChecker engineVersionChecker) + IEngineVersionChecker engineVersionChecker, + IIntegrationService integrationService) : ICliCommand { /// @@ -42,12 +48,18 @@ public class VersionCommand( private readonly IEngineVersionChecker _engineVersionChecker = Ensure.NotNull(engineVersionChecker); + private readonly IIntegrationService _integrationService = Ensure.NotNull(integrationService); + /// - /// Checks the engine against the expected version if is set, and - /// writes the engine version, as plain text or as a JSON envelope. + /// Checks the engine against the expected version if is set, reads the + /// installed integrations, and writes the engine version and the integrations, as plain text or as a JSON + /// envelope. /// /// - /// A prerelease engine that does not fit the expected version is reported with a warning and still succeeds. + /// A prerelease engine that does not fit the expected version is reported with a warning and still succeeds. The + /// integrations are read only after the check succeeded; an agent whose CLI is missing or fails is left out with + /// an agent-unavailable warning, so the integrations never make the command fail. The plain output starts + /// with the line shade-kit <version>, followed by one line per installed integration. /// /// The options of the command. /// @@ -62,33 +74,47 @@ public class VersionCommand( /// /// The version of the running engine is not a valid SemVer 2.0.0 version, which is a defect of the engine build. /// + /// The user canceled the run. public async Task ExecuteAsync(VersionCommandOptions options) { Ensure.NotNull(options); var data = CreateData(); + IReadOnlyList checkWarnings = []; - if (options.Expect is not { } expectedVersion) + if (options.Expect is { } expectedVersion) { - _context.WriteSuccess(options.Json, data, () => WritePlain(data)); + var result = await _context.RunAsync(options.Json, + _ => Task.FromResult(_engineVersionChecker.Check(expectedVersion))) + .ConfigureAwait(false); - return CommandResult.Success; + checkWarnings = result.Warnings; + data = data with { ExpectedVersion = expectedVersion }; } - var result = await _context.RunAsync(options.Json, - _ => Task.FromResult(_engineVersionChecker.Check(expectedVersion))) + var installed = await _context.RunAsync(options.Json, + cancellationToken => _integrationService.GetInstalledAsync(cancellationToken)) .ConfigureAwait(false); - var checkedData = data with { ExpectedVersion = expectedVersion }; + var completeData = data with + { + Integrations = [.. installed.Integrations.Select(VersionCommandIntegrationData.From)] + }; - _context.WriteSuccess(options.Json, checkedData, result.Warnings, () => WritePlain(checkedData)); + _context.WriteSuccess(options.Json, completeData, [.. checkWarnings, .. installed.Warnings], + () => WritePlain(completeData.EngineVersion, installed.Integrations)); return CommandResult.Success; } - private void WritePlain(VersionCommandData data) + private void WritePlain(string engineVersion, IReadOnlyList integrations) { - _context.Console.WriteLine($"{ToolName} {data.EngineVersion}"); + _context.Console.WriteLine($"{ToolName} {engineVersion}"); + + foreach (var integration in integrations) + { + _context.Console.MarkupLine(IntegrationsTextFormat.FormatInstalled(integration)); + } } private VersionCommandData CreateData() diff --git a/src/CreativeCoders.ShadeKit.Cli/Commands/Version/VersionCommandData.cs b/src/CreativeCoders.ShadeKit.Cli/Commands/Version/VersionCommandData.cs index 5b5efbf..e41ea39 100644 --- a/src/CreativeCoders.ShadeKit.Cli/Commands/Version/VersionCommandData.cs +++ b/src/CreativeCoders.ShadeKit.Cli/Commands/Version/VersionCommandData.cs @@ -6,7 +6,8 @@ namespace CreativeCoders.ShadeKit.Cli.Commands.Version; /// Represents the data object that shade-kit version --json returns. /// /// -/// Describes the installed engine, not a repository; skills use it for the version handshake. +/// Describes the installed engine and the SHADE kit integrations of the agents, not a repository; skills use it for +/// the version handshake. /// /// The version of the running engine without build metadata. /// @@ -24,4 +25,14 @@ public sealed record VersionCommandData(string EngineVersion, IReadOnlyDictionar /// [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public string? ExpectedVersion { get; init; } + + /// + /// Gets the SHADE kit integrations that are installed in the agents for the user. + /// + /// + /// The installed integrations in the order in which the agents are registered, always written to the JSON output, + /// after ; an empty list if none is installed or no agent could be asked. The + /// default is an empty list. + /// + public IReadOnlyList Integrations { get; init; } = []; } diff --git a/src/CreativeCoders.ShadeKit.Cli/Commands/Version/VersionCommandIntegrationData.cs b/src/CreativeCoders.ShadeKit.Cli/Commands/Version/VersionCommandIntegrationData.cs new file mode 100644 index 0000000..130821c --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Cli/Commands/Version/VersionCommandIntegrationData.cs @@ -0,0 +1,45 @@ +using CreativeCoders.Core; +using CreativeCoders.ShadeKit.Core.Integrations; + +namespace CreativeCoders.ShadeKit.Cli.Commands.Version; + +/// +/// Represents an installed SHADE kit integration in the data object that shade-kit version --json +/// returns. +/// +/// The id of the agent, for example claude. +/// +/// The id of the integration in the agent, for example shade-kit@creativecoders-shade-kit. +/// +/// +/// The installed kit version, for example 0.8.0, or if the marketplace ref is no +/// v<SemVer> tag, the marketplace is a local directory, or the agent no longer knows the marketplace. +/// +/// +/// The branch or tag of the marketplace, for example v0.8.0, or for a local directory, +/// the default branch, or a marketplace that the agent no longer knows. +/// +/// +/// if the integration is enabled in the agent; otherwise, . +/// +public sealed record VersionCommandIntegrationData( + string Agent, + string PluginId, + string? KitVersion, + string? Ref, + bool Enabled) +{ + /// + /// Creates the data of the specified installed integration. + /// + /// The installed integration. + /// The data with the values of . + /// is . + public static VersionCommandIntegrationData From(InstalledIntegration integration) + { + Ensure.NotNull(integration); + + return new VersionCommandIntegrationData(integration.AgentId, integration.PluginId, integration.KitVersion, + integration.Ref, integration.Enabled); + } +} diff --git a/src/CreativeCoders.ShadeKit.Cli/Output/CliErrorMapper.cs b/src/CreativeCoders.ShadeKit.Cli/Output/CliErrorMapper.cs index a83e078..6fa0c36 100644 --- a/src/CreativeCoders.ShadeKit.Cli/Output/CliErrorMapper.cs +++ b/src/CreativeCoders.ShadeKit.Cli/Output/CliErrorMapper.cs @@ -2,6 +2,8 @@ using System.Reflection; using CreativeCoders.Cli.Core; using CreativeCoders.Core; +using CreativeCoders.ShadeKit.Cli.Commands.Integrations; +using CreativeCoders.ShadeKit.Cli.Commands.Integrations.Install; using CreativeCoders.ShadeKit.Cli.Commands.Version; using CreativeCoders.ShadeKit.Core.Engine; using CreativeCoders.ShadeKit.Core.Features; @@ -18,6 +20,9 @@ using CreativeCoders.ShadeKit.Core.Git.Warnings; using CreativeCoders.ShadeKit.Core.Init; using CreativeCoders.ShadeKit.Core.Init.Exceptions; +using CreativeCoders.ShadeKit.Core.Integrations; +using CreativeCoders.ShadeKit.Core.Integrations.Exceptions; +using CreativeCoders.ShadeKit.Core.Integrations.Warnings; using CreativeCoders.ShadeKit.Core.Store; using CreativeCoders.ShadeKit.Core.Store.Exceptions; using CreativeCoders.ShadeKit.Core.Trackers.Exceptions; @@ -30,6 +35,7 @@ using CreativeCoders.ShadeKit.Core.Workflow.Profiles.Exceptions; using CreativeCoders.SysConsole.Cli.Parsing; using CreativeCoders.SysConsole.Cli.Parsing.Exceptions; +using Spectre.Console; namespace CreativeCoders.ShadeKit.Cli.Output; @@ -191,6 +197,44 @@ public sealed class CliErrorMapper(IEngineVersionProvider engineVersionProvider) EngineVersionMismatchException e => CliError.Create(ShadeKitCliExitCodes.VersionMismatch, CreateEngineVersionMismatchMessage(e.EngineVersion, e.ExpectedVersion, e.Direction)), + NoAgentFoundException e => CliError.Create(ShadeKitCliExitCodes.AgentNotFound, + $"No supported agent was found (supported: {FormatAgentIds(e.SupportedAgentIds)}). SHADE kit " + + "detects Claude Code by its CLI 'claude' in an absolute directory of the PATH. Install a supported " + + "agent, then run the command again. On Windows only the 'claude.exe' of the native installer of " + + "Claude Code is found; the 'claude.cmd' of an npm installation is not."), + + ClaudeNotFoundException e => CliError.Create(ShadeKitCliExitCodes.AgentNotFound, + $"Claude Code is needed, but its CLI 'claude' was not found. {e.Reason} Install Claude Code and " + + "make sure 'claude' is in an absolute directory of the PATH, then run the command again. On Windows " + + "only the 'claude.exe' of the native installer is found; the 'claude.cmd' of an npm installation is " + + "not."), + + ClaudeUnavailableException e => CliError.Create(ShadeKitCliExitCodes.AgentCommandFailed, + $"'{e.CommandText}' cannot be run: {e.Reason} Make sure Claude Code is installed correctly and " + + "'claude --version' works, then run the command again."), + + ClaudeCommandFailedException e => CliError.Create(ShadeKitCliExitCodes.AgentCommandFailed, + $"'{e.CommandText}' failed: {e.Reason} Fix the cause that claude names, make sure Claude Code is up " + + "to date ('claude update'), then run the command again."), + + IntegrationConflictException e => CliError.Create(ShadeKitCliExitCodes.IntegrationConflict, + $"The plugin marketplace '{e.MarketplaceName}' of the agent '{e.AgentId}' already exists with the " + + $"source '{e.ExistingSource}', but SHADE kit needs '{e.RequestedSource}'. Nothing was changed. Run " + + $"'{e.ResolveCommand}' to remove it, then run the command again."), + + IntegrationIncompleteException e => CreateIntegrationIncompleteError(e), + + IntegrationSwitchCanceledException e => CliError.Create(ShadeKitCliExitCodes.Canceled, + "The command was canceled while the plugin marketplace of SHADE kit was switched for the agent " + + $"'{e.AgentId}', so the integration may be incomplete; 'shade-kit integrations install' repairs it."), + + IntegrationRunFailedException e => CreateIntegrationRunFailedError(e), + + InvalidMarketplaceSourceException e => CliError.Create(ShadeKitCliExitCodes.InvalidArguments, + $"The environment variable {IntegrationService.MarketplaceSourceVariableName} is set to " + + $"'{e.Value}', which is not a marketplace source: {e.Reason} Set it to owner/repo#ref, owner/repo, " + + "or the path of a local directory, or remove it, then run the command again."), + InvalidSemanticVersionException e => CliError.Create(ShadeKitCliExitCodes.InvalidArguments, $"Invalid arguments: '{e.Value}' is not a SemVer version such as 1.2.3 or 1.2.3-beta.1. Run " + "'shade-kit --help' for usage."), @@ -208,7 +252,9 @@ public sealed class CliErrorMapper(IEngineVersionProvider engineVersionProvider) /// Exceptions wrapped in are unwrapped. An /// is not mapped: it /// is a defect of the CLI, not of the arguments. An (--expect - /// without a value) gets a text that names --expect. + /// without a value) gets a text that names --expect, an + /// (--agent without a value or with an unknown agent id) one that names --agent and the supported + /// agents. /// /// The exception that ended the run. /// The command-line arguments of the run. @@ -230,6 +276,7 @@ public sealed class CliErrorMapper(IEngineVersionProvider engineVersionProvider) NotAllArgumentsMatchException e => CreateNotMatchedArgumentsText(e), ExpectedVersionMissingException => "--expect needs a SemVer version such as 1.2.3 or 1.2.3-beta.1, but got none", + InvalidAgentOptionException e => CreateInvalidAgentOptionText(e), OptionParserException => "the arguments could not be read", _ => null }; @@ -337,6 +384,20 @@ public static CliJsonMessage MapWarning(KitWarning warning) $"The prerelease engine {w.EngineVersion} does not fit the kit skills {w.ExpectedVersion} (the major " + "and minor versions differ); it is used anyway because it is a prerelease."), + IntegrationPrereleaseRefWarning w => new CliJsonMessage(ShadeKitCliWarningCodes.IntegrationPrereleaseRef, + $"The engine {w.EngineVersion} is a prerelease, so the integrations come from the branch '{w.Ref}' " + + $"of {IntegrationService.MarketplaceRepo} instead of a release tag; they may not fit this engine."), + + IntegrationReleaseTagMissingWarning w => new CliJsonMessage( + ShadeKitCliWarningCodes.IntegrationReleaseTagMissing, + $"The release tag '{w.Tag}' of the engine {w.EngineVersion} does not exist in " + + $"{IntegrationService.MarketplaceRepo}, so the integrations come from the branch '{w.Ref}' instead; " + + "they may not fit this engine."), + + AgentUnavailableWarning w => new CliJsonMessage(ShadeKitCliWarningCodes.AgentUnavailable, + $"The SHADE kit integration of the agent '{w.AgentId}' cannot be read, so it is not listed: " + + $"{CreateSentence(w.Reason)}"), + _ => throw new ArgumentOutOfRangeException(nameof(warning), warning, "The warning is not supported.") }; @@ -582,7 +643,8 @@ private static string CreateEngineVersionMismatchMessage(string engineVersion, s EngineVersionMismatchDirection.EngineOlder => $"Update the engine to {FormatMajorMinor(expectedVersion)}", EngineVersionMismatchDirection.EngineNewer => - $"Update the SHADE kit skills to {FormatMajorMinor(engineVersion)} by hand", + "Run 'shade-kit integrations install' to install the SHADE kit skills " + + FormatMajorMinor(engineVersion), _ => throw new ArgumentOutOfRangeException(nameof(direction), direction, "The direction is not supported.") }; @@ -668,6 +730,63 @@ private static string CreatePendingTransitionText(string? pendingTransition) : $"the pending transition is to '{pendingTransition}'."; } + private static string CreateInvalidAgentOptionText(InvalidAgentOptionException exception) + { + var supported = FormatAgentIds(exception.SupportedAgentIds); + + return exception.Value is null + ? $"--agent needs the id of a supported agent ({supported}), but got none" + : $"'{exception.Value}' is not a supported agent for --agent (supported: {supported})"; + } + + private static string FormatAgentIds(IReadOnlyList? agentIds) + { + return agentIds is { Count: > 0 } ids + ? string.Join(", ", ids) + : "none"; + } + + // Keeps the exit code and message of the failed agent command and adds that an install repairs the integration, + // because the marketplace was already switched when the command failed. Removing the marketplace also uninstalls + // its plugins, so an update would find nothing installed; the install installs the plugin again. + private CliError CreateIntegrationIncompleteError(IntegrationIncompleteException exception) + { + const string repairHint = + "The plugin marketplace of SHADE kit was already switched, so the integration may be incomplete; " + + "'shade-kit integrations install' repairs it."; + + var innerError = exception.InnerException is { } innerException ? Map(innerException) : null; + + return innerError is null + ? CliError.Create(ShadeKitCliExitCodes.AgentCommandFailed, + $"The SHADE kit integration of the agent '{exception.AgentId}' failed: " + + $"{CreateCauseSentence(exception.InnerException)} {repairHint}") + : CliError.Create(innerError.ExitCode, $"{innerError.Message} {repairHint}"); + } + + // Keeps the exit code and message of the failed agent and names the agents that were done before it, so their + // results are not lost; the JSON error keeps only code and message. + private CliError CreateIntegrationRunFailedError(IntegrationRunFailedException exception) + { + // The list is null only in an instance that was not created by its constructor; Map maps such an instance of + // every core exception without throwing (FP01-AC8), so the guard stays. + var completedIntegrations = exception.CompletedIntegrations ?? []; + + var completedSentence = completedIntegrations.Count == 0 + ? string.Empty + : $" Before the agent '{exception.FailedAgentId}' failed, these integrations were done: " + + string.Join("; ", completedIntegrations.Select(x => + IntegrationsTextFormat.FormatResult(x, exception.MarketplaceSource).RemoveMarkup())) + "."; + + var innerError = exception.InnerException is { } innerException ? Map(innerException) : null; + + return innerError is null + ? CliError.Create(ShadeKitCliExitCodes.AgentCommandFailed, + $"The SHADE kit integration of the agent '{exception.FailedAgentId}' failed: " + + $"{CreateCauseSentence(exception.InnerException)}{completedSentence}") + : CliError.Create(innerError.ExitCode, innerError.Message + completedSentence); + } + private string CreateFormatTooNewMessage(FormatTooNewException exception) { var installedVersion = _engineVersionProvider.Version; diff --git a/src/CreativeCoders.ShadeKit.Cli/ShadeKitCliErrorCodes.cs b/src/CreativeCoders.ShadeKit.Cli/ShadeKitCliErrorCodes.cs index 2608a49..3032a5e 100644 --- a/src/CreativeCoders.ShadeKit.Cli/ShadeKitCliErrorCodes.cs +++ b/src/CreativeCoders.ShadeKit.Cli/ShadeKitCliErrorCodes.cs @@ -160,6 +160,21 @@ public static class ShadeKitCliErrorCodes /// public const string VersionMismatch = "version-mismatch"; + /// + /// Represents the error code that belongs to . + /// + public const string AgentNotFound = "agent-not-found"; + + /// + /// Represents the error code that belongs to . + /// + public const string AgentCommandFailed = "agent-command-failed"; + + /// + /// Represents the error code that belongs to . + /// + public const string IntegrationConflict = "integration-conflict"; + /// /// Represents the error code that belongs to . /// @@ -212,6 +227,9 @@ public static string ForExitCode(int exitCode) ShadeKitCliExitCodes.PhaseStateInvalid => PhaseStateInvalid, ShadeKitCliExitCodes.ChecklistTemplateNotFound => ChecklistTemplateNotFound, ShadeKitCliExitCodes.VersionMismatch => VersionMismatch, + ShadeKitCliExitCodes.AgentNotFound => AgentNotFound, + ShadeKitCliExitCodes.AgentCommandFailed => AgentCommandFailed, + ShadeKitCliExitCodes.IntegrationConflict => IntegrationConflict, ShadeKitCliExitCodes.Canceled => Canceled, ShadeKitCliExitCodes.HostError => HostError, _ => throw new ArgumentOutOfRangeException(nameof(exitCode), exitCode, "The exit code is not defined.") diff --git a/src/CreativeCoders.ShadeKit.Cli/ShadeKitCliExitCodes.cs b/src/CreativeCoders.ShadeKit.Cli/ShadeKitCliExitCodes.cs index bf02380..a8d90f2 100644 --- a/src/CreativeCoders.ShadeKit.Cli/ShadeKitCliExitCodes.cs +++ b/src/CreativeCoders.ShadeKit.Cli/ShadeKitCliExitCodes.cs @@ -217,6 +217,30 @@ public static class ShadeKitCliExitCodes /// public const int VersionMismatch = 50; + /// + /// Represents the exit code returned when no supported agent is detected, for example by + /// shade-kit integrations install without --agent, or when the CLI of an agent that a command needs + /// is not found in any absolute directory of the PATH environment variable: for Claude Code claude, + /// also for an agent named with --agent, which is checked before the release tag. On Windows only the + /// claude.exe of the native installer is found. The error code is + /// . + /// + public const int AgentNotFound = 51; + + /// + /// Represents the exit code returned when a claude command fails: claude cannot be started, exits + /// with a non-zero exit code, reports the outcome failed, or prints no JSON output that SHADE kit can read. + /// The error code is . + /// + public const int AgentCommandFailed = 52; + + /// + /// Represents the exit code returned when an agent already knows the plugin marketplace of SHADE kit + /// (creativecoders-shade-kit) with a different source repository or directory; nothing is changed. The error + /// code is . + /// + public const int IntegrationConflict = 53; + /// /// Represents the exit code returned when the user cancels a running command, for example by pressing Ctrl+C. The /// error code is . diff --git a/src/CreativeCoders.ShadeKit.Cli/ShadeKitCliWarningCodes.cs b/src/CreativeCoders.ShadeKit.Cli/ShadeKitCliWarningCodes.cs index d723fcb..fd55f0c 100644 --- a/src/CreativeCoders.ShadeKit.Cli/ShadeKitCliWarningCodes.cs +++ b/src/CreativeCoders.ShadeKit.Cli/ShadeKitCliWarningCodes.cs @@ -80,4 +80,22 @@ public static class ShadeKitCliWarningCodes /// of the version passed with shade-kit version --expect; the engine is used anyway. /// public const string EnginePrereleaseVersionMismatch = "engine-prerelease-version-mismatch"; + + /// + /// Represents the warning code reported when a prerelease engine installs or updates the integrations from the + /// branch main instead of a release tag. + /// + public const string IntegrationPrereleaseRef = "integration-prerelease-ref"; + + /// + /// Represents the warning code reported when the release tag of a release engine does not exist in the marketplace + /// repository, so the integrations are installed or updated from the branch main instead. + /// + public const string IntegrationReleaseTagMissing = "integration-release-tag-missing"; + + /// + /// Represents the warning code reported when the CLI of an agent is detected but cannot be started or fails, so its + /// SHADE kit integration cannot be read and is not listed. + /// + public const string AgentUnavailable = "agent-unavailable"; } diff --git a/src/CreativeCoders.ShadeKit.Core/Formats/FormatIds.cs b/src/CreativeCoders.ShadeKit.Core/Formats/FormatIds.cs index 42d8234..a50ab06 100644 --- a/src/CreativeCoders.ShadeKit.Core/Formats/FormatIds.cs +++ b/src/CreativeCoders.ShadeKit.Core/Formats/FormatIds.cs @@ -32,9 +32,4 @@ public static class FormatIds /// Represents the format id of .shadekit/templates.lock.json. /// public const string TemplatesLock = "templates-lock"; - - /// - /// Represents the format id of the user-level record of installed agent integrations. - /// - public const string Integrations = "integrations"; } diff --git a/src/CreativeCoders.ShadeKit.Core/Formats/FormatRegistry.cs b/src/CreativeCoders.ShadeKit.Core/Formats/FormatRegistry.cs index 2304fae..4337921 100644 --- a/src/CreativeCoders.ShadeKit.Core/Formats/FormatRegistry.cs +++ b/src/CreativeCoders.ShadeKit.Core/Formats/FormatRegistry.cs @@ -66,8 +66,7 @@ public static FormatRegistry CreateDefault() CreateVersion1(FormatIds.Gates), CreateVersion1(FormatIds.Feature), CreateVersion1(FormatIds.CurrentFeature), - CreateVersion1(FormatIds.TemplatesLock), - CreateVersion1(FormatIds.Integrations) + CreateVersion1(FormatIds.TemplatesLock) ]); } diff --git a/src/CreativeCoders.ShadeKit.Core/Git/GitCommandRunner.cs b/src/CreativeCoders.ShadeKit.Core/Git/GitCommandRunner.cs index a9e4f92..9fb85f0 100644 --- a/src/CreativeCoders.ShadeKit.Core/Git/GitCommandRunner.cs +++ b/src/CreativeCoders.ShadeKit.Core/Git/GitCommandRunner.cs @@ -9,22 +9,47 @@ namespace CreativeCoders.ShadeKit.Core.Git; /// /// /// Starts only the absolute path from the , never a git in the current -/// directory, and runs it without a shell; the output is read concurrently and decoded as UTF-8. +/// directory, and runs it without a shell; the output is read concurrently and decoded as UTF-8. The process inherits +/// the environment of the current process plus , so git never asks for +/// credentials on the terminal or through an askpass program. /// /// The locator that resolves the absolute path of the git executable. public sealed class GitCommandRunner(IGitExecutableLocator gitExecutableLocator) : IGitCommandRunner { - private static readonly ExternalTool Git = new("git", "git", null, + private readonly IGitExecutableLocator _gitExecutableLocator = Ensure.NotNull(gitExecutableLocator); + + /// + /// Gets the environment variables that are set for every git process in addition to the inherited ones. + /// + /// + /// GIT_TERMINAL_PROMPT=0, which makes git fail instead of prompting on the terminal, and an empty + /// GIT_ASKPASS, which makes git ignore core.askPass and SSH_ASKPASS, so no askpass + /// program is started. + /// + internal static IReadOnlyDictionary EnvironmentVariables { get; } = + new Dictionary(StringComparer.Ordinal) + { + ["GIT_TERMINAL_PROMPT"] = "0", + ["GIT_ASKPASS"] = string.Empty + }; + + /// + /// Gets the description of the git tool that the starts. + /// + /// The tool with the name git, the , and the git exceptions. + /// + /// Declared after , because static initializers run in the order of + /// declaration. + /// + internal static ExternalTool Tool { get; } = new("git", "git", EnvironmentVariables, static (arguments, reason) => new GitNotFoundException(arguments, reason), static (arguments, reason, innerException) => new GitUnavailableException(arguments, reason, innerException)); - private readonly IGitExecutableLocator _gitExecutableLocator = Ensure.NotNull(gitExecutableLocator); - /// public Task RunAsync(string workingDirectory, IReadOnlyList arguments, CancellationToken cancellationToken = default) { - return ExternalToolRunner.RunAsync(Git, _gitExecutableLocator.FindGitExecutable, workingDirectory, arguments, + return ExternalToolRunner.RunAsync(Tool, _gitExecutableLocator.FindGitExecutable, workingDirectory, arguments, cancellationToken); } } diff --git a/src/CreativeCoders.ShadeKit.Core/Git/GitRemoteTagChecker.cs b/src/CreativeCoders.ShadeKit.Core/Git/GitRemoteTagChecker.cs new file mode 100644 index 0000000..f4ebb8c --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Core/Git/GitRemoteTagChecker.cs @@ -0,0 +1,132 @@ +using System.Text.RegularExpressions; +using CreativeCoders.Core; +using CreativeCoders.ShadeKit.Core.Git.Exceptions; +using CreativeCoders.ShadeKit.Core.Processes; + +namespace CreativeCoders.ShadeKit.Core.Git; + +/// +/// Checks whether a tag exists in a remote git repository with git ls-remote through the +/// . +/// +/// +/// +/// git runs in the home directory of the user (or the temporary directory if the home directory is not known or +/// does not exist), not in the current directory, so the configuration of the current repository takes no part. +/// +/// +/// git never asks for credentials: the runner turns terminal and askpass prompts off, and the call clears the +/// credential helpers (-c credential.helper=) and allows only the https protocol +/// (-c protocol.allow=never -c protocol.https.allow=always), so a URL that the configuration of the user +/// rewrites to ssh fails instead of starting ssh, which could ask for a passphrase. A repository that +/// needs credentials therefore gives . +/// +/// +public sealed partial class GitRemoteTagChecker : IGitRemoteTagChecker +{ + private const string TagRefPrefix = "refs/tags/"; + + private const string PeeledSuffix = "^{}"; + + private readonly IGitCommandRunner _gitCommandRunner; + + private readonly string _workingDirectory; + + /// + /// Initializes a new instance of the class that runs git in the home + /// directory of the user. + /// + /// The runner that starts git. + /// is . + public GitRemoteTagChecker(IGitCommandRunner gitCommandRunner) + : this(gitCommandRunner, UserWorkingDirectory.Get()) + { + } + + /// + /// Initializes a new instance of the class that runs git in the + /// specified directory. + /// + /// The runner that starts git. + /// The directory in which git runs. + /// is . + /// + /// is , empty, or whitespace. + /// + internal GitRemoteTagChecker(IGitCommandRunner gitCommandRunner, string workingDirectory) + { + _gitCommandRunner = Ensure.NotNull(gitCommandRunner); + _workingDirectory = Ensure.IsNotNullOrWhitespace(workingDirectory); + } + + /// + /// Gets the directory in which git runs. + /// + /// + /// The home directory of the user, the temporary directory, or the directory passed to the constructor. + /// + internal string WorkingDirectory => _workingDirectory; + + /// + public async Task CheckTagAsync(string remoteUrl, string tagName, + CancellationToken cancellationToken = default) + { + Ensure.NotNull(remoteUrl); + Ensure.NotNull(tagName); + + if (!Uri.TryCreate(remoteUrl, UriKind.Absolute, out var uri) || uri.Scheme != Uri.UriSchemeHttps) + { + throw new ArgumentException($"'{remoteUrl}' is not an absolute https:// URL.", nameof(remoteUrl)); + } + + if (!TagNameRegex().IsMatch(tagName)) + { + throw new ArgumentException( + $"'{tagName}' is not a tag name that git ls-remote matches exactly: it is empty, starts with '-', " + + "or contains whitespace, a glob character, '^', '~', or ':'.", nameof(tagName)); + } + + var tagRef = TagRefPrefix + tagName; + + string[] arguments = + [ + "-c", "credential.helper=", "-c", "protocol.allow=never", "-c", "protocol.https.allow=always", + "ls-remote", "--tags", remoteUrl, tagRef + ]; + + ExternalProcessResult result; + + try + { + result = await _gitCommandRunner.RunAsync(_workingDirectory, arguments, cancellationToken) + .ConfigureAwait(false); + } + catch (GitUnavailableException) + { + // A missing git (GitNotFoundException) and a git that cannot be started leave the tag unchecked. + return GitRemoteTagState.Unknown; + } + + if (result.ExitCode != 0) + { + return GitRemoteTagState.Unknown; + } + + return ContainsTag(result.StandardOutput, tagRef) + ? GitRemoteTagState.Found + : GitRemoteTagState.Missing; + } + + // Each line is "\t"; an annotated tag also has the peeled line "^{}". + private static bool ContainsTag(string standardOutput, string tagRef) + { + return standardOutput + .Split('\n') + .Select(x => x.TrimEnd('\r').Split('\t', 2)) + .Any(x => x.Length == 2 && (x[1] == tagRef || x[1] == tagRef + PeeledSuffix)); + } + + // '^', '~', and ':' are not allowed in ref names; '^' would also let "^{}" match the peeled line of . + [GeneratedRegex(@"\A[^\s\-*?\[\\^~:][^\s*?\[\\^~:]*\z")] + private static partial Regex TagNameRegex(); +} diff --git a/src/CreativeCoders.ShadeKit.Core/Git/GitRemoteTagState.cs b/src/CreativeCoders.ShadeKit.Core/Git/GitRemoteTagState.cs new file mode 100644 index 0000000..c238ee1 --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Core/Git/GitRemoteTagState.cs @@ -0,0 +1,23 @@ +namespace CreativeCoders.ShadeKit.Core.Git; + +/// +/// Specifies whether a tag exists in a remote git repository, as an found out. +/// +public enum GitRemoteTagState +{ + /// + /// The remote repository has the tag. + /// + Found, + + /// + /// The remote repository was read and has no tag of that name. + /// + Missing, + + /// + /// The remote repository could not be read, for example because git is not installed, the network is not + /// available, or the repository needs credentials, so it is not known whether the tag exists. + /// + Unknown +} diff --git a/src/CreativeCoders.ShadeKit.Core/Git/IGitRemoteTagChecker.cs b/src/CreativeCoders.ShadeKit.Core/Git/IGitRemoteTagChecker.cs new file mode 100644 index 0000000..b1a3c4e --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Core/Git/IGitRemoteTagChecker.cs @@ -0,0 +1,36 @@ +namespace CreativeCoders.ShadeKit.Core.Git; + +/// +/// Checks whether a tag exists in a remote git repository. +/// +public interface IGitRemoteTagChecker +{ + /// + /// Checks whether the specified tag exists in the remote repository at the specified URL. + /// + /// + /// The check never asks for credentials and never fails because of git or the network: a missing + /// git, a git that cannot be started, and a failed call give . + /// + /// The https:// URL of the remote repository. + /// The name of the tag without refs/tags/, for example v0.8.0. + /// The token to monitor for cancellation requests. + /// + /// A task that represents the asynchronous check. The task result is if + /// the tag exists, if the repository was read and has no such tag, and + /// if the repository could not be read. + /// + /// + /// or is . + /// + /// + /// is not an absolute https:// URL, or is empty, + /// starts with -, or contains whitespace, one of the glob characters *, ?, [, and + /// \, or one of the characters ^, ~, and :, which a ref name cannot contain. + /// + /// + /// was canceled; a started process is killed. + /// + Task CheckTagAsync(string remoteUrl, string tagName, + CancellationToken cancellationToken = default); +} diff --git a/src/CreativeCoders.ShadeKit.Core/Integrations/Claude/ClaudeCodeIntegration.cs b/src/CreativeCoders.ShadeKit.Core/Integrations/Claude/ClaudeCodeIntegration.cs new file mode 100644 index 0000000..c4094fd --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Core/Integrations/Claude/ClaudeCodeIntegration.cs @@ -0,0 +1,361 @@ +using CreativeCoders.Core; +using CreativeCoders.ShadeKit.Core.Integrations.Exceptions; +using CreativeCoders.ShadeKit.Core.Processes.Exceptions; + +namespace CreativeCoders.ShadeKit.Core.Integrations.Claude; + +/// +/// Installs, updates, and reads the SHADE kit plugin of Claude Code through the plugin commands of the Claude Code CLI +/// claude. +/// +/// +/// +/// The SHADE kit repository is the plugin marketplace with the plugin +/// ; both are installed with the scope user. An install or update runs these steps: +/// +/// +/// +/// claude plugin list reads whether the plugin is installed with the scope user; an update of a plugin +/// that is not installed stops here, changes nothing, and resolves no source. +/// +/// +/// claude plugin marketplace list reads the marketplace. A missing marketplace is added. A marketplace with the +/// same repository (compared case-insensitively, as GitHub does) and the same ref, or with the same directory, is +/// kept; directories are compared with a , after resolving their symbolic links +/// and case-insensitively on Windows and macOS. A marketplace with the same repository but another ref is removed +/// and added again (the switch). A marketplace with another repository, another kind of source, or another directory +/// is a conflict, and nothing is changed. Claude Code stores the ref that was given, so a GitHub marketplace without +/// a ref (the default branch) has another ref than every source with a ref, and refs are compared case-sensitively, +/// as git does. +/// +/// +/// A kept marketplace is refreshed with claude plugin marketplace update, because a marketplace that follows a +/// branch keeps the commit of its last refresh, and claude plugin update does not refresh it reliably (it skips +/// the refresh when the marketplace was refreshed shortly before). After a change of the marketplace the plugins are +/// listed again, because removing a marketplace also removes its plugins. A plugin that is not installed is installed +/// (and listed once more to read whether it is enabled); otherwise it is updated. The outcome is +/// if the plugin was not installed before the run, +/// if the marketplace was kept and the update found the plugin up to date, +/// and otherwise. +/// +/// +/// +/// Nothing is rolled back. A failure after the old marketplace was removed is reported as an +/// , and a cancellation from the removal on as an +/// , because running the install again repairs the integration. A +/// disabled plugin stays disabled. +/// +/// +public sealed class ClaudeCodeIntegration : IAgentIntegration +{ + /// + /// Represents the agent id of Claude Code. + /// + public const string ClaudeAgentId = "claude"; + + /// + /// Represents the name of the plugin marketplace of SHADE kit. + /// + public const string MarketplaceName = "creativecoders-shade-kit"; + + /// + /// Represents the id of the SHADE kit plugin in Claude Code. + /// + public const string PluginId = "shade-kit@" + MarketplaceName; + + private static readonly string[] ListPluginsArguments = ["plugin", "list", "--json"]; + + private readonly IClaudePluginCli _claudePluginCli; + + private readonly IClaudeExecutableLocator _claudeExecutableLocator; + + private readonly DirectoryPathComparer _directoryPathComparer; + + /// + /// Initializes a new instance of the class that compares directories as the + /// file system of the current operating system does. + /// + /// The plugin commands of claude. + /// The locator that detects claude. + /// + /// or is + /// . + /// + public ClaudeCodeIntegration(IClaudePluginCli claudePluginCli, IClaudeExecutableLocator claudeExecutableLocator) + : this(claudePluginCli, claudeExecutableLocator, DirectoryPathComparer.ForCurrentOperatingSystem()) + { + } + + /// + /// Initializes a new instance of the class with the specified comparer of + /// directory sources. + /// + /// The plugin commands of claude. + /// The locator that detects claude. + /// + /// The comparer that decides whether a directory marketplace has the directory of the source. + /// + /// An argument is . + internal ClaudeCodeIntegration(IClaudePluginCli claudePluginCli, IClaudeExecutableLocator claudeExecutableLocator, + DirectoryPathComparer directoryPathComparer) + { + _claudePluginCli = Ensure.NotNull(claudePluginCli); + _claudeExecutableLocator = Ensure.NotNull(claudeExecutableLocator); + _directoryPathComparer = Ensure.NotNull(directoryPathComparer); + } + + private enum MarketplaceChange + { + Keep, + Add, + Switch + } + + /// + /// The id . + public string AgentId => ClaudeAgentId; + + /// + /// Claude Code is detected by claude in an absolute directory of the PATH. + public bool IsAvailable() + { + return _claudeExecutableLocator.FindClaudeExecutable() is not null; + } + + /// + /// + /// claude is not found; the exception names claude plugin list --json, the first command of an + /// install or update. + /// + public void EnsureAvailable() + { + if (!IsAvailable()) + { + throw new ClaudeNotFoundException(ListPluginsArguments, ClaudeCommandRunner.Tool.NotFoundReason); + } + } + + /// + /// + /// The ref and the kit version come from the marketplace if it is a GitHub + /// marketplace. + /// + public async Task GetInstalledAsync(CancellationToken cancellationToken = default) + { + var plugin = await FindUserPluginAsync(cancellationToken).ConfigureAwait(false); + + if (plugin is null) + { + return null; + } + + var marketplace = FindMarketplace( + await _claudePluginCli.ListMarketplacesAsync(cancellationToken).ConfigureAwait(false)); + + var @ref = GetGitHubRef(marketplace); + + return new InstalledIntegration(AgentId, PluginId, MarketplaceSource.GetKitVersion(@ref), @ref, + plugin.Enabled); + } + + /// + public async Task InstallAsync(MarketplaceSource source, + CancellationToken cancellationToken = default) + { + Ensure.NotNull(source); + + var pluginBefore = await FindUserPluginAsync(cancellationToken).ConfigureAwait(false); + + return await ApplyAsync(source, pluginBefore, cancellationToken).ConfigureAwait(false); + } + + /// + public async Task UpdateAsync(Func> getSource, + CancellationToken cancellationToken = default) + { + Ensure.NotNull(getSource); + + var pluginBefore = await FindUserPluginAsync(cancellationToken).ConfigureAwait(false); + + if (pluginBefore is null) + { + return null; + } + + var source = Ensure.NotNull(await getSource(cancellationToken).ConfigureAwait(false)); + + return await ApplyAsync(source, pluginBefore, cancellationToken).ConfigureAwait(false); + } + + private async Task ApplyAsync(MarketplaceSource source, ClaudeInstalledPlugin? pluginBefore, + CancellationToken cancellationToken) + { + var marketplace = FindMarketplace( + await _claudePluginCli.ListMarketplacesAsync(cancellationToken).ConfigureAwait(false)); + + var change = GetMarketplaceChange(marketplace, source); + + var previousKitVersion = pluginBefore is null + ? null + : MarketplaceSource.GetKitVersion(GetGitHubRef(marketplace)); + + var isRemoved = false; + + try + { + if (change == MarketplaceChange.Switch) + { + await _claudePluginCli.RemoveMarketplaceAsync(MarketplaceName, cancellationToken) + .ConfigureAwait(false); + + isRemoved = true; + } + + // A kept marketplace that follows a branch would otherwise stay at the commit of its last refresh. + if (change == MarketplaceChange.Keep) + { + await _claudePluginCli.UpdateMarketplaceAsync(MarketplaceName, cancellationToken) + .ConfigureAwait(false); + } + else + { + await _claudePluginCli.AddMarketplaceAsync(source.Text, cancellationToken).ConfigureAwait(false); + } + + var plugin = change == MarketplaceChange.Keep + ? pluginBefore + : await FindUserPluginAsync(cancellationToken).ConfigureAwait(false); + + return plugin is null + ? await InstallPluginAsync(source, pluginBefore, previousKitVersion, cancellationToken) + .ConfigureAwait(false) + : await UpdatePluginAsync(source, plugin, pluginBefore, previousKitVersion, + change == MarketplaceChange.Keep, cancellationToken).ConfigureAwait(false); + } + catch (ExternalToolUnavailableException exception) when (isRemoved) + { + throw new IntegrationIncompleteException(AgentId, exception); + } + catch (OperationCanceledException exception) when (change == MarketplaceChange.Switch && + cancellationToken.IsCancellationRequested) + { + // A cancellation while the removal runs counts too: the killed claude may have removed the marketplace. + throw new IntegrationSwitchCanceledException(AgentId, exception); + } + } + + private async Task InstallPluginAsync(MarketplaceSource source, + ClaudeInstalledPlugin? pluginBefore, string? previousKitVersion, CancellationToken cancellationToken) + { + await _claudePluginCli.InstallPluginAsync(PluginId, cancellationToken).ConfigureAwait(false); + + var plugin = await FindUserPluginAsync(cancellationToken).ConfigureAwait(false) + ?? throw new ClaudeCommandFailedException(ListPluginsArguments, 0, + $"claude does not list the plugin '{PluginId}' with the scope " + + $"'{ClaudeInstalledPlugin.UserScope}' after it was installed."); + + var outcome = pluginBefore is null ? IntegrationOutcome.Installed : IntegrationOutcome.Updated; + + return CreateResult(source, outcome, previousKitVersion, plugin.Enabled); + } + + private async Task UpdatePluginAsync(MarketplaceSource source, ClaudeInstalledPlugin plugin, + ClaudeInstalledPlugin? pluginBefore, string? previousKitVersion, bool isMarketplaceKept, + CancellationToken cancellationToken) + { + var update = await _claudePluginCli.UpdatePluginAsync(PluginId, cancellationToken).ConfigureAwait(false); + + var outcome = pluginBefore switch + { + null => IntegrationOutcome.Installed, + _ when isMarketplaceKept && update.IsUpToDate => IntegrationOutcome.Current, + _ => IntegrationOutcome.Updated + }; + + return CreateResult(source, outcome, previousKitVersion, plugin.Enabled); + } + + private IntegrationResult CreateResult(MarketplaceSource source, IntegrationOutcome outcome, + string? previousKitVersion, bool enabled) + { + return new IntegrationResult(AgentId, PluginId, outcome, previousKitVersion, source.KitVersion, source.Ref, + enabled); + } + + private async Task FindUserPluginAsync(CancellationToken cancellationToken) + { + return FindUserPlugin(await _claudePluginCli.ListPluginsAsync(cancellationToken).ConfigureAwait(false)); + } + + private MarketplaceChange GetMarketplaceChange(ClaudeMarketplace? marketplace, MarketplaceSource source) + { + if (marketplace is null) + { + return MarketplaceChange.Add; + } + + if (source.Repo is { } repo) + { + if (IsSourceKind(marketplace, ClaudeMarketplace.GitHubSourceKind) + && string.Equals(marketplace.Repo, repo, StringComparison.OrdinalIgnoreCase)) + { + return string.Equals(marketplace.Ref, source.Ref, StringComparison.Ordinal) + ? MarketplaceChange.Keep + : MarketplaceChange.Switch; + } + } + else if (IsSourceKind(marketplace, ClaudeMarketplace.DirectorySourceKind) + && marketplace.Path is { } path + && IsSameDirectory(path, source.Path)) + { + return MarketplaceChange.Keep; + } + + throw new IntegrationConflictException(AgentId, MarketplaceName, DescribeSource(marketplace), source.Text, + $"claude plugin marketplace remove {MarketplaceName}"); + } + + private static ClaudeInstalledPlugin? FindUserPlugin(IEnumerable plugins) + { + return plugins.FirstOrDefault(x => + string.Equals(x.Id, PluginId, StringComparison.Ordinal) + && string.Equals(x.Scope, ClaudeInstalledPlugin.UserScope, StringComparison.Ordinal)); + } + + private static ClaudeMarketplace? FindMarketplace(IEnumerable marketplaces) + { + return marketplaces.FirstOrDefault(x => string.Equals(x.Name, MarketplaceName, StringComparison.Ordinal)); + } + + private static string? GetGitHubRef(ClaudeMarketplace? marketplace) + { + return marketplace is not null && IsSourceKind(marketplace, ClaudeMarketplace.GitHubSourceKind) + ? marketplace.Ref + : null; + } + + private static bool IsSourceKind(ClaudeMarketplace marketplace, string sourceKind) + { + return string.Equals(marketplace.SourceKind, sourceKind, StringComparison.Ordinal); + } + + // claude reports absolute paths; any other text names no directory that the source can have. + private bool IsSameDirectory(string marketplacePath, string? sourcePath) + { + return sourcePath is not null + && Path.IsPathFullyQualified(marketplacePath) + && _directoryPathComparer.AreSameDirectory(marketplacePath, sourcePath); + } + + private static string DescribeSource(ClaudeMarketplace marketplace) + { + return marketplace.SourceKind switch + { + ClaudeMarketplace.GitHubSourceKind when marketplace.Repo is { } repo => + marketplace.Ref is null ? repo : $"{repo}#{marketplace.Ref}", + ClaudeMarketplace.DirectorySourceKind when marketplace.Path is { } path => path, + { } sourceKind => $"a source of the kind '{sourceKind}'", + null => "a source of unknown kind" + }; + } +} diff --git a/src/CreativeCoders.ShadeKit.Core/Integrations/Claude/ClaudeCommandRunner.cs b/src/CreativeCoders.ShadeKit.Core/Integrations/Claude/ClaudeCommandRunner.cs new file mode 100644 index 0000000..b99c895 --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Core/Integrations/Claude/ClaudeCommandRunner.cs @@ -0,0 +1,57 @@ +using CreativeCoders.Core; +using CreativeCoders.ShadeKit.Core.Integrations.Exceptions; +using CreativeCoders.ShadeKit.Core.Processes; + +namespace CreativeCoders.ShadeKit.Core.Integrations.Claude; + +/// +/// Runs the Claude Code CLI executable claude as a child process and captures its output. +/// +/// +/// Starts only the absolute path from the , never a claude in the +/// current directory, and runs it without a shell; the output is read concurrently and decoded as UTF-8. The process +/// inherits the environment of the current process plus , so claude writes +/// no color codes. +/// +/// +/// The locator that resolves the absolute path of the claude executable. +/// +public sealed class ClaudeCommandRunner(IClaudeExecutableLocator claudeExecutableLocator) : IClaudeCommandRunner +{ + private readonly IClaudeExecutableLocator _claudeExecutableLocator = Ensure.NotNull(claudeExecutableLocator); + + /// + /// Gets the environment variables that are set for every claude process in addition to the inherited ones. + /// + /// + /// NO_COLOR=1, which Claude Code evaluates to turn its colors off unless FORCE_COLOR is set. + /// + internal static IReadOnlyDictionary EnvironmentVariables { get; } = + new Dictionary(StringComparer.Ordinal) + { + ["NO_COLOR"] = "1" + }; + + /// + /// Gets the description of the claude tool that the starts. + /// + /// + /// The tool with the name claude, the , and the claude exceptions. + /// + /// + /// Declared after , because static initializers run in the order of + /// declaration. + /// + internal static ExternalTool Tool { get; } = new("claude", "The Claude Code CLI claude", EnvironmentVariables, + static (arguments, reason) => new ClaudeNotFoundException(arguments, reason), + static (arguments, reason, innerException) => + new ClaudeUnavailableException(arguments, reason, innerException)); + + /// + public Task RunAsync(string workingDirectory, IReadOnlyList arguments, + CancellationToken cancellationToken = default) + { + return ExternalToolRunner.RunAsync(Tool, _claudeExecutableLocator.FindClaudeExecutable, workingDirectory, + arguments, cancellationToken); + } +} diff --git a/src/CreativeCoders.ShadeKit.Core/Integrations/Claude/ClaudeExecutableLocator.cs b/src/CreativeCoders.ShadeKit.Core/Integrations/Claude/ClaudeExecutableLocator.cs new file mode 100644 index 0000000..63b7e78 --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Core/Integrations/Claude/ClaudeExecutableLocator.cs @@ -0,0 +1,50 @@ +using CreativeCoders.ShadeKit.Core.Processes; + +namespace CreativeCoders.ShadeKit.Core.Integrations.Claude; + +/// +/// Locates the Claude Code CLI executable claude in the absolute directories of the PATH environment +/// variable. +/// +/// +/// The executable is claude.exe with the Windows rules and claude with the Unix rules. The search +/// follows the rules of , so on Windows the claude.cmd or +/// claude.ps1 shim of an npm installation is not found. +/// +public sealed class ClaudeExecutableLocator : PathExecutableLocator, IClaudeExecutableLocator +{ + private const string WindowsExecutableName = "claude.exe"; + + private const string UnixExecutableName = "claude"; + + /// + /// Initializes a new instance of the class that reads the PATH + /// environment variable of the current process and uses the rules of the current operating system. + /// + public ClaudeExecutableLocator() + : base(new PathExecutableSearch(WindowsExecutableName, UnixExecutableName)) + { + } + + /// + /// Initializes a new instance of the class with the specified sources for + /// the PATH value, the operating system rules, the file check, and the execute check, as described for + /// . + /// + /// + /// , , or is + /// . + /// + internal ClaudeExecutableLocator(Func getPathVariable, bool isWindows, Func fileExists, + Func isExecutable) + : base(new PathExecutableSearch(WindowsExecutableName, UnixExecutableName, getPathVariable, isWindows, + fileExists, isExecutable)) + { + } + + /// + public string? FindClaudeExecutable() + { + return FindExecutable(); + } +} diff --git a/src/CreativeCoders.ShadeKit.Core/Integrations/Claude/ClaudeInstalledPlugin.cs b/src/CreativeCoders.ShadeKit.Core/Integrations/Claude/ClaudeInstalledPlugin.cs new file mode 100644 index 0000000..92595a6 --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Core/Integrations/Claude/ClaudeInstalledPlugin.cs @@ -0,0 +1,25 @@ +namespace CreativeCoders.ShadeKit.Core.Integrations.Claude; + +/// +/// Represents a plugin that is installed in Claude Code, as claude plugin list --json reports it. +/// +/// +/// The id of the plugin in the form <plugin>@<marketplace>, for example +/// shade-kit@creativecoders-shade-kit. +/// +/// +/// The installed version of the plugin, or if claude reported none. Without a +/// version in the plugin manifest, Claude Code uses the first 12 characters of the commit SHA. +/// +/// +/// The scope in which the plugin is installed, for example , or if +/// claude reported none. +/// +/// if the plugin is enabled; otherwise, . +public sealed record ClaudeInstalledPlugin(string Id, string? Version, string? Scope, bool Enabled) +{ + /// + /// Represents the scope of a plugin that is installed for the user, in every project. + /// + public const string UserScope = "user"; +} diff --git a/src/CreativeCoders.ShadeKit.Core/Integrations/Claude/ClaudeJsonOutputReader.cs b/src/CreativeCoders.ShadeKit.Core/Integrations/Claude/ClaudeJsonOutputReader.cs new file mode 100644 index 0000000..a44bcc8 --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Core/Integrations/Claude/ClaudeJsonOutputReader.cs @@ -0,0 +1,285 @@ +using System.Globalization; +using System.Text.Json; +using CreativeCoders.ShadeKit.Core.Integrations.Exceptions; +using CreativeCoders.ShadeKit.Core.Processes; +using CreativeCoders.ShadeKit.Core.Text; + +namespace CreativeCoders.ShadeKit.Core.Integrations.Claude; + +/// +/// Reads the JSON output of a finished claude ... --json command and reports every failure of the command as a +/// . +/// +/// +/// A command that changes the configuration prints one JSON object per line, with the fields outcome, +/// message, and, on failure, failureCode; the last non-empty line of standard output that is a JSON +/// object is its result. A list command prints one JSON array. Unknown fields are ignored. +/// +/// The arguments of the claude command that produced the output. +/// The result of the finished claude process. +internal sealed class ClaudeJsonOutputReader(IReadOnlyList arguments, ExternalProcessResult result) +{ + /// + /// Represents the outcome that claude reports for a successful command. + /// + public const string OkOutcome = "ok"; + + private const string OutcomeProperty = "outcome"; + + private const string MessageProperty = "message"; + + private const string FailureCodeProperty = "failureCode"; + + /// + /// Returns the result object of a command that changes the configuration. + /// + /// + /// A copy of the last JSON object line of standard output, whose outcome is . + /// + /// + /// claude exited with a non-zero exit code, printed no JSON object line, or reported an outcome other than + /// . + /// + public JsonElement ReadResultObject() + { + var resultObject = FindLastJsonObjectLine(); + + if (result.ExitCode != 0) + { + throw CreateExitCodeException(resultObject); + } + + if (resultObject is not { } root) + { + throw Fail(CreateNoJsonObjectReason("claude printed no JSON object on standard output")); + } + + var outcome = GetStringOrNull(root, OutcomeProperty); + + if (string.Equals(outcome, OkOutcome, StringComparison.Ordinal)) + { + return root; + } + + var outcomeText = outcome is null + ? "claude reported no outcome" + : $"claude reported the outcome '{outcome}'"; + + throw CreateReportedFailureException(outcomeText, root); + } + + /// + /// Reads the JSON array that a list command prints and converts each of its entries. + /// + /// The type of the converted entries. + /// + /// The function that converts an entry; it receives the entry and its name in messages, for example + /// entry 2. + /// + /// The converted entries in the order of the array. + /// + /// claude exited with a non-zero exit code or its standard output is not a JSON array. + /// + public IReadOnlyList ReadArray(Func readEntry) + { + if (result.ExitCode != 0) + { + throw CreateExitCodeException(FindLastJsonObjectLine()); + } + + JsonDocument document; + + try + { + document = JsonDocument.Parse(result.StandardOutput); + } + catch (JsonException exception) + { + throw Fail($"The output of claude is not valid JSON: {Sentences.Terminate(exception.Message)}", + innerException: exception); + } + + using (document) + { + var root = document.RootElement; + + if (root.ValueKind != JsonValueKind.Array) + { + throw Fail("The output of claude is not a JSON array."); + } + + return + [ + .. root.EnumerateArray().Select((entry, index) => + readEntry(entry, $"entry {(index + 1).ToString(CultureInfo.InvariantCulture)}")) + ]; + } + } + + /// + /// Ensures that the specified entry of a list is a JSON object. + /// + /// The entry to check. + /// The name of the entry in messages, for example entry 2. + /// is not a JSON object. + public void EnsureObject(JsonElement entry, string entryName) + { + if (entry.ValueKind != JsonValueKind.Object) + { + throw Fail($"The {entryName} of the claude output is not a JSON object."); + } + } + + /// + /// Reads a string field that must be present. + /// + /// The JSON object that contains the field. + /// The name of the field. + /// The name of the object in messages, for example entry 2. + /// The value of the field, which is neither empty nor whitespace. + /// + /// The field is missing, , empty, whitespace, or not a string. + /// + public string ReadRequiredString(JsonElement element, string propertyName, string subject) + { + var value = ReadOptionalString(element, propertyName, subject); + + return string.IsNullOrWhiteSpace(value) + ? throw Fail($"The {subject} of the claude output has no non-empty '{propertyName}' string.") + : value; + } + + /// + /// Reads a string field that may be missing. + /// + /// The JSON object that contains the field. + /// The name of the field. + /// The name of the object in messages, for example entry 2. + /// + /// The value of the field, or if the field is missing or . + /// + /// The field has a value that is not a string. + public string? ReadOptionalString(JsonElement element, string propertyName, string subject) + { + if (!element.TryGetProperty(propertyName, out var value) || value.ValueKind == JsonValueKind.Null) + { + return null; + } + + return value.ValueKind == JsonValueKind.String + ? value.GetString() + : throw Fail($"The field '{propertyName}' of the {subject} of the claude output is not a string."); + } + + /// + /// Reads a Boolean field that must be present. + /// + /// The JSON object that contains the field. + /// The name of the field. + /// The name of the object in messages, for example entry 2. + /// The value of the field. + /// + /// The field is missing, , or not a Boolean. + /// + public bool ReadRequiredBoolean(JsonElement element, string propertyName, string subject) + { + if (element.TryGetProperty(propertyName, out var value) + && value.ValueKind is JsonValueKind.True or JsonValueKind.False) + { + return value.GetBoolean(); + } + + throw Fail($"The {subject} of the claude output has no '{propertyName}' Boolean."); + } + + // Searches from the end, because claude may print other lines before its result line. + private JsonElement? FindLastJsonObjectLine() + { + var lines = result.StandardOutput.Split('\n') + .Select(x => x.Trim()) + .Where(x => x.StartsWith('{')) + .Reverse(); + + foreach (var line in lines) + { + try + { + using var document = JsonDocument.Parse(line); + + if (document.RootElement.ValueKind == JsonValueKind.Object) + { + return document.RootElement.Clone(); + } + } + catch (JsonException) + { + // Not a JSON object line; an earlier line may be the result. + } + } + + return null; + } + + private ClaudeCommandFailedException CreateExitCodeException(JsonElement? resultObject) + { + var exitCodeText = "claude exited with the exit code " + + result.ExitCode.ToString(CultureInfo.InvariantCulture); + + if (resultObject is not { } root) + { + return Fail(CreateNoJsonObjectReason($"{exitCodeText} and printed no JSON object on standard output")); + } + + var outcome = GetStringOrNull(root, OutcomeProperty); + + var failureText = outcome is null + ? exitCodeText + : $"{exitCodeText} and reported the outcome '{outcome}'"; + + return CreateReportedFailureException(failureText, root); + } + + private ClaudeCommandFailedException CreateReportedFailureException(string failureText, JsonElement root) + { + var message = GetStringOrNull(root, MessageProperty); + var failureCode = GetStringOrNull(root, FailureCodeProperty); + + var reason = failureText; + + if (!string.IsNullOrWhiteSpace(message)) + { + reason += $": {message.Trim().TrimEnd('.')}"; + } + + if (!string.IsNullOrWhiteSpace(failureCode)) + { + reason += $" (failure code '{failureCode}')"; + } + + return Fail(reason + ".", message, failureCode); + } + + private string CreateNoJsonObjectReason(string failureText) + { + var standardError = result.StandardError.Trim(); + + return standardError.Length == 0 + ? $"{failureText}." + : $"{failureText}: {Sentences.Terminate(standardError)}"; + } + + private ClaudeCommandFailedException Fail(string reason, string? claudeMessage = null, + string? failureCode = null, Exception? innerException = null) + { + return new ClaudeCommandFailedException(arguments, result.ExitCode, reason, claudeMessage, failureCode, + innerException); + } + + // The fields of a result object are read leniently: a value of another type counts as missing. + private static string? GetStringOrNull(JsonElement element, string propertyName) + { + return element.TryGetProperty(propertyName, out var value) && value.ValueKind == JsonValueKind.String + ? value.GetString() + : null; + } +} diff --git a/src/CreativeCoders.ShadeKit.Core/Integrations/Claude/ClaudeMarketplace.cs b/src/CreativeCoders.ShadeKit.Core/Integrations/Claude/ClaudeMarketplace.cs new file mode 100644 index 0000000..78943b4 --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Core/Integrations/Claude/ClaudeMarketplace.cs @@ -0,0 +1,34 @@ +namespace CreativeCoders.ShadeKit.Core.Integrations.Claude; + +/// +/// Represents a plugin marketplace that Claude Code knows, as claude plugin marketplace list --json reports it. +/// +/// The name of the marketplace, for example creativecoders-shade-kit. +/// +/// The kind of the source of the marketplace, for example or +/// , or if claude reported none. +/// +/// +/// The GitHub repository of a source in the form owner/repo, or +/// if claude reported none. +/// +/// +/// The branch or tag of a source, or if claude +/// reported none, which means the default branch of the repository. +/// +/// +/// The absolute path of a source, or if claude +/// reported none. +/// +public sealed record ClaudeMarketplace(string Name, string? SourceKind, string? Repo, string? Ref, string? Path) +{ + /// + /// Represents the source kind of a marketplace in a GitHub repository. + /// + public const string GitHubSourceKind = "github"; + + /// + /// Represents the source kind of a marketplace in a local directory. + /// + public const string DirectorySourceKind = "directory"; +} diff --git a/src/CreativeCoders.ShadeKit.Core/Integrations/Claude/ClaudePluginCli.cs b/src/CreativeCoders.ShadeKit.Core/Integrations/Claude/ClaudePluginCli.cs new file mode 100644 index 0000000..52a814a --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Core/Integrations/Claude/ClaudePluginCli.cs @@ -0,0 +1,212 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using CreativeCoders.Core; +using CreativeCoders.ShadeKit.Core.Processes; + +namespace CreativeCoders.ShadeKit.Core.Integrations.Claude; + +/// +/// Runs the plugin and marketplace commands of the Claude Code CLI claude with the +/// and reads their JSON output. +/// +/// +/// +/// claude runs in the home directory of the user (or the temporary directory if the home directory is not +/// known or does not exist), not in the current directory, so the settings of the current project take no part and +/// no file is written into a repository. +/// +/// +/// A list command must print a JSON array whose entries are objects. A marketplace entry needs the string +/// name; source, repo, ref, and path are optional strings. A plugin entry needs the +/// string id and the Boolean enabled; version and scope are optional strings. A value of +/// another type is a failure; unknown fields are ignored. +/// +/// +public sealed class ClaudePluginCli : IClaudePluginCli +{ + private const string JsonOption = "--json"; + + private const string ScopeOption = "--scope"; + + private readonly IClaudeCommandRunner _claudeCommandRunner; + + private readonly string _workingDirectory; + + /// + /// Initializes a new instance of the class that runs claude in the home + /// directory of the user. + /// + /// The runner that starts claude. + /// + /// is . + /// + public ClaudePluginCli(IClaudeCommandRunner claudeCommandRunner) + : this(claudeCommandRunner, UserWorkingDirectory.Get()) + { + } + + /// + /// Initializes a new instance of the class that runs claude in the specified + /// directory. + /// + /// The runner that starts claude. + /// The directory in which claude runs. + /// + /// is . + /// + /// + /// is , empty, or whitespace. + /// + internal ClaudePluginCli(IClaudeCommandRunner claudeCommandRunner, string workingDirectory) + { + _claudeCommandRunner = Ensure.NotNull(claudeCommandRunner); + _workingDirectory = Ensure.IsNotNullOrWhitespace(workingDirectory); + } + + /// + /// Gets the directory in which claude runs. + /// + /// + /// The home directory of the user, the temporary directory, or the directory passed to the constructor. + /// + internal string WorkingDirectory => _workingDirectory; + + /// + public async Task> ListMarketplacesAsync( + CancellationToken cancellationToken = default) + { + var reader = await RunAsync(["plugin", "marketplace", "list", JsonOption], cancellationToken) + .ConfigureAwait(false); + + return reader.ReadArray((entry, entryName) => ReadMarketplace(reader, entry, entryName)); + } + + /// + public async Task AddMarketplaceAsync(string source, CancellationToken cancellationToken = default) + { + EnsurePositionalArgument(source, nameof(source)); + + var reader = await RunAsync( + ["plugin", "marketplace", "add", source, ScopeOption, ClaudeInstalledPlugin.UserScope, JsonOption], + cancellationToken) + .ConfigureAwait(false); + + reader.ReadResultObject(); + } + + /// + public async Task RemoveMarketplaceAsync(string name, CancellationToken cancellationToken = default) + { + EnsurePositionalArgument(name, nameof(name)); + + var reader = await RunAsync(["plugin", "marketplace", "remove", name, JsonOption], cancellationToken) + .ConfigureAwait(false); + + reader.ReadResultObject(); + } + + /// + public async Task UpdateMarketplaceAsync(string name, CancellationToken cancellationToken = default) + { + EnsurePositionalArgument(name, nameof(name)); + + var reader = await RunAsync(["plugin", "marketplace", "update", name, JsonOption], cancellationToken) + .ConfigureAwait(false); + + reader.ReadResultObject(); + } + + /// + public async Task> ListPluginsAsync( + CancellationToken cancellationToken = default) + { + var reader = await RunAsync(["plugin", "list", JsonOption], cancellationToken).ConfigureAwait(false); + + return reader.ReadArray((entry, entryName) => ReadInstalledPlugin(reader, entry, entryName)); + } + + /// + public async Task InstallPluginAsync(string pluginId, + CancellationToken cancellationToken = default) + { + EnsurePositionalArgument(pluginId, nameof(pluginId)); + + var reader = await RunAsync( + ["plugin", "install", pluginId, ScopeOption, ClaudeInstalledPlugin.UserScope, JsonOption], + cancellationToken) + .ConfigureAwait(false); + + var resultObject = reader.ReadResultObject(); + + return new ClaudePluginInstallResult( + reader.ReadOptionalString(resultObject, "installedVersion", "result"), + reader.ReadOptionalString(resultObject, "availableVersion", "result")); + } + + /// + public async Task UpdatePluginAsync(string pluginId, + CancellationToken cancellationToken = default) + { + EnsurePositionalArgument(pluginId, nameof(pluginId)); + + var reader = await RunAsync( + ["plugin", "update", pluginId, ScopeOption, ClaudeInstalledPlugin.UserScope, JsonOption], + cancellationToken) + .ConfigureAwait(false); + + var resultObject = reader.ReadResultObject(); + + return new ClaudePluginUpdateResult( + reader.ReadOptionalString(resultObject, "updateOutcome", "result"), + reader.ReadOptionalString(resultObject, "oldVersion", "result"), + reader.ReadOptionalString(resultObject, "newVersion", "result")); + } + + private async Task RunAsync(string[] arguments, CancellationToken cancellationToken) + { + var result = await _claudeCommandRunner.RunAsync(_workingDirectory, arguments, cancellationToken) + .ConfigureAwait(false); + + return new ClaudeJsonOutputReader(arguments, result); + } + + private static ClaudeMarketplace ReadMarketplace(ClaudeJsonOutputReader reader, JsonElement entry, + string entryName) + { + reader.EnsureObject(entry, entryName); + + return new ClaudeMarketplace( + reader.ReadRequiredString(entry, "name", entryName), + reader.ReadOptionalString(entry, "source", entryName), + reader.ReadOptionalString(entry, "repo", entryName), + reader.ReadOptionalString(entry, "ref", entryName), + reader.ReadOptionalString(entry, "path", entryName)); + } + + private static ClaudeInstalledPlugin ReadInstalledPlugin(ClaudeJsonOutputReader reader, JsonElement entry, + string entryName) + { + reader.EnsureObject(entry, entryName); + + return new ClaudeInstalledPlugin( + reader.ReadRequiredString(entry, "id", entryName), + reader.ReadOptionalString(entry, "version", entryName), + reader.ReadOptionalString(entry, "scope", entryName), + reader.ReadRequiredBoolean(entry, "enabled", entryName)); + } + + // claude would read a value that starts with '-' as an option instead of the positional argument. + [SuppressMessage("Minor Code Smell", "S3236:Caller information arguments should not be provided explicitly", + Justification = "The caller's parameter name is forwarded on purpose, so an invalid value names the " + + "caller's parameter instead of this helper's.")] + private static void EnsurePositionalArgument(string value, string paramName) + { + Ensure.IsNotNullOrWhitespace(value, paramName); + + if (value.StartsWith('-')) + { + throw new ArgumentException($"The value '{value}' starts with '-', so claude would read it as an option.", + paramName); + } + } +} diff --git a/src/CreativeCoders.ShadeKit.Core/Integrations/Claude/ClaudePluginInstallResult.cs b/src/CreativeCoders.ShadeKit.Core/Integrations/Claude/ClaudePluginInstallResult.cs new file mode 100644 index 0000000..c884365 --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Core/Integrations/Claude/ClaudePluginInstallResult.cs @@ -0,0 +1,14 @@ +namespace CreativeCoders.ShadeKit.Core.Integrations.Claude; + +/// +/// Represents the result of a successful claude plugin install --json command. +/// +/// +/// The version that was already installed, which claude reports when the plugin was installed before the +/// command, or if it reported none. +/// +/// +/// The version that the marketplace offers, which claude reports when the plugin was installed before the +/// command, or if it reported none. +/// +public sealed record ClaudePluginInstallResult(string? InstalledVersion, string? AvailableVersion); diff --git a/src/CreativeCoders.ShadeKit.Core/Integrations/Claude/ClaudePluginUpdateResult.cs b/src/CreativeCoders.ShadeKit.Core/Integrations/Claude/ClaudePluginUpdateResult.cs new file mode 100644 index 0000000..e30b7d0 --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Core/Integrations/Claude/ClaudePluginUpdateResult.cs @@ -0,0 +1,36 @@ +namespace CreativeCoders.ShadeKit.Core.Integrations.Claude; + +/// +/// Represents the result of a successful claude plugin update --json command. +/// +/// +/// The updateOutcome that claude reported, for example or +/// , or if it reported none. +/// +/// +/// The version that was installed before the command, or if claude reported none. +/// +/// +/// The version that is installed after the command, or if claude reported none. +/// +public sealed record ClaudePluginUpdateResult(string? UpdateOutcome, string? OldVersion, string? NewVersion) +{ + /// + /// Represents the update outcome of a plugin that was updated to a new version. + /// + public const string UpdatedOutcome = "updated"; + + /// + /// Represents the update outcome of a plugin that already had the latest version. + /// + public const string UpToDateOutcome = "up_to_date"; + + /// + /// Gets a value that indicates whether the plugin already had the latest version, so nothing was changed. + /// + /// + /// if is ; otherwise, + /// . + /// + public bool IsUpToDate => string.Equals(UpdateOutcome, UpToDateOutcome, StringComparison.Ordinal); +} diff --git a/src/CreativeCoders.ShadeKit.Core/Integrations/Claude/IClaudeCommandRunner.cs b/src/CreativeCoders.ShadeKit.Core/Integrations/Claude/IClaudeCommandRunner.cs new file mode 100644 index 0000000..9134b10 --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Core/Integrations/Claude/IClaudeCommandRunner.cs @@ -0,0 +1,41 @@ +using CreativeCoders.ShadeKit.Core.Integrations.Exceptions; +using CreativeCoders.ShadeKit.Core.Processes; + +namespace CreativeCoders.ShadeKit.Core.Integrations.Claude; + +/// +/// Runs the Claude Code CLI executable claude and captures its output. +/// +public interface IClaudeCommandRunner +{ + /// + /// Runs claude with the specified arguments in the specified directory and waits until it exits. + /// + /// + /// The arguments are passed to the process one by one, without a shell, so they are neither split nor expanded. + /// claude runs without colors. A non-zero exit code is not an error of this method; it is returned in the + /// result for the caller to interpret. + /// + /// The directory in which claude runs. + /// + /// The arguments that are passed to claude, for example plugin, list, and --json. + /// + /// The token to monitor for cancellation requests. + /// + /// A task that represents the asynchronous run. The task result contains the exit code and the captured standard + /// output and standard error of the process. + /// + /// + /// is , empty, or whitespace. + /// + /// is . + /// + /// The claude executable cannot be found or started; a missing executable is a + /// . + /// + /// + /// was canceled; the started process is killed. + /// + Task RunAsync(string workingDirectory, IReadOnlyList arguments, + CancellationToken cancellationToken = default); +} diff --git a/src/CreativeCoders.ShadeKit.Core/Integrations/Claude/IClaudeExecutableLocator.cs b/src/CreativeCoders.ShadeKit.Core/Integrations/Claude/IClaudeExecutableLocator.cs new file mode 100644 index 0000000..bca8aa6 --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Core/Integrations/Claude/IClaudeExecutableLocator.cs @@ -0,0 +1,21 @@ +namespace CreativeCoders.ShadeKit.Core.Integrations.Claude; + +/// +/// Locates the Claude Code CLI executable claude that SHADE kit starts. +/// +public interface IClaudeExecutableLocator +{ + /// + /// Returns the absolute path of the claude executable. + /// + /// + /// The path is resolved from the absolute directories of the PATH environment variable only, so a + /// claude executable in the current directory is never used. With the Windows rules only claude.exe + /// is found, which the native installer of Claude Code provides. + /// + /// + /// The absolute path of the claude executable, or if no absolute directory of the + /// PATH environment variable contains it. + /// + string? FindClaudeExecutable(); +} diff --git a/src/CreativeCoders.ShadeKit.Core/Integrations/Claude/IClaudePluginCli.cs b/src/CreativeCoders.ShadeKit.Core/Integrations/Claude/IClaudePluginCli.cs new file mode 100644 index 0000000..b378e01 --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Core/Integrations/Claude/IClaudePluginCli.cs @@ -0,0 +1,188 @@ +using CreativeCoders.ShadeKit.Core.Integrations.Exceptions; + +namespace CreativeCoders.ShadeKit.Core.Integrations.Claude; + +/// +/// Runs the plugin and marketplace commands of the Claude Code CLI claude and reads their JSON output. +/// +/// +/// +/// Every command runs with --json; commands that change the configuration use the scope user, so the +/// plugins are available in every project. The commands run outside any repository, so nothing is written into one. +/// +/// +/// A command fails with a if claude exits with a non-zero exit +/// code, reports an outcome other than ok, or prints output that does not have the expected JSON shape; +/// unknown fields are ignored. +/// +/// +public interface IClaudePluginCli +{ + /// + /// Lists the plugin marketplaces that Claude Code knows, with claude plugin marketplace list --json. + /// + /// The token to monitor for cancellation requests. + /// + /// A task that represents the asynchronous operation. The task result contains the marketplaces in the order + /// claude reported them. + /// + /// + /// The claude executable cannot be found or started; a missing executable is a + /// . + /// + /// The command fails or its output cannot be read. + /// + /// was canceled; a started process is killed. + /// + Task> ListMarketplacesAsync(CancellationToken cancellationToken = default); + + /// + /// Adds a plugin marketplace for the user, with claude plugin marketplace add <source> --scope user + /// --json. + /// + /// + /// Adding a marketplace that already exists with the same source succeeds without a change. + /// + /// + /// The source of the marketplace, for example owner/repo#v1.2.0 or the absolute path of a local directory. + /// + /// The token to monitor for cancellation requests. + /// A task that represents the asynchronous operation. + /// + /// is , empty, or whitespace, or starts with -, so + /// claude would read it as an option. + /// + /// + /// The claude executable cannot be found or started; a missing executable is a + /// . + /// + /// The command fails or its output cannot be read. + /// + /// was canceled; a started process is killed. + /// + Task AddMarketplaceAsync(string source, CancellationToken cancellationToken = default); + + /// + /// Removes a plugin marketplace, with claude plugin marketplace remove <name> --json. + /// + /// The name of the marketplace, for example creativecoders-shade-kit. + /// The token to monitor for cancellation requests. + /// A task that represents the asynchronous operation. + /// + /// is , empty, or whitespace, or starts with -, so + /// claude would read it as an option. + /// + /// + /// The claude executable cannot be found or started; a missing executable is a + /// . + /// + /// + /// The command fails, for example because no marketplace has the name, or its output cannot be read. + /// + /// + /// was canceled; a started process is killed. + /// + Task RemoveMarketplaceAsync(string name, CancellationToken cancellationToken = default); + + /// + /// Refreshes a plugin marketplace from its source, with claude plugin marketplace update <name> + /// --json. + /// + /// + /// A marketplace that follows a branch is brought to the latest commit of that branch, so a following + /// or sees the new content. Without the refresh, + /// claude plugin update may report the plugin as up to date with the content of an older commit. + /// + /// The name of the marketplace, for example creativecoders-shade-kit. + /// The token to monitor for cancellation requests. + /// A task that represents the asynchronous operation. + /// + /// is , empty, or whitespace, or starts with -, so + /// claude would read it as an option. + /// + /// + /// The claude executable cannot be found or started; a missing executable is a + /// . + /// + /// + /// The command fails, for example because no marketplace has the name or its source cannot be fetched, or its + /// output cannot be read. + /// + /// + /// was canceled; a started process is killed. + /// + Task UpdateMarketplaceAsync(string name, CancellationToken cancellationToken = default); + + /// + /// Lists the plugins that are installed in Claude Code, with claude plugin list --json. + /// + /// The token to monitor for cancellation requests. + /// + /// A task that represents the asynchronous operation. The task result contains the installed plugins of every + /// scope in the order claude reported them. + /// + /// + /// The claude executable cannot be found or started; a missing executable is a + /// . + /// + /// The command fails or its output cannot be read. + /// + /// was canceled; a started process is killed. + /// + Task> ListPluginsAsync(CancellationToken cancellationToken = default); + + /// + /// Installs a plugin for the user, with claude plugin install <id> --scope user --json. + /// + /// + /// The id of the plugin in the form <plugin>@<marketplace>, for example + /// shade-kit@creativecoders-shade-kit. + /// + /// The token to monitor for cancellation requests. + /// + /// A task that represents the asynchronous operation. The task result contains the versions that claude + /// reported. + /// + /// + /// is , empty, or whitespace, or starts with -, so + /// claude would read it as an option. + /// + /// + /// The claude executable cannot be found or started; a missing executable is a + /// . + /// + /// The command fails or its output cannot be read. + /// + /// was canceled; a started process is killed. + /// + Task InstallPluginAsync(string pluginId, CancellationToken cancellationToken = default); + + /// + /// Updates a plugin that is installed for the user, with claude plugin update <id> --scope user + /// --json. + /// + /// + /// The id of the plugin in the form <plugin>@<marketplace>, for example + /// shade-kit@creativecoders-shade-kit. + /// + /// The token to monitor for cancellation requests. + /// + /// A task that represents the asynchronous operation. The task result contains the update outcome and the + /// versions that claude reported. + /// + /// + /// is , empty, or whitespace, or starts with -, so + /// claude would read it as an option. + /// + /// + /// The claude executable cannot be found or started; a missing executable is a + /// . + /// + /// + /// The command fails, for example because the plugin is not installed, or its output cannot be read. + /// + /// + /// was canceled; a started process is killed. + /// + Task UpdatePluginAsync(string pluginId, CancellationToken cancellationToken = default); +} diff --git a/src/CreativeCoders.ShadeKit.Core/Integrations/DirectoryPathComparer.cs b/src/CreativeCoders.ShadeKit.Core/Integrations/DirectoryPathComparer.cs new file mode 100644 index 0000000..a9a02ba --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Core/Integrations/DirectoryPathComparer.cs @@ -0,0 +1,170 @@ +using CreativeCoders.Core; + +namespace CreativeCoders.ShadeKit.Core.Integrations; + +/// +/// Compares absolute directory paths after resolving their symbolic links, with the case sensitivity of the file +/// system of an operating system. +/// +/// +/// +/// A path that exists is resolved segment by segment, as realpath does: every segment that is a symbolic link +/// (or a junction on Windows) is replaced by its target, and the target is resolved again, so a link in a parent +/// directory counts too. On macOS, for example, /tmp is a link to private/tmp and +/// /var a link to private/var, and neither nor +/// resolves a link in a parent directory. The .. +/// segments of the path itself are removed first, as does, so that the path +/// means what it means for the source that SHADE kit passes to the agent CLI; the .. segments of a relative +/// link target are removed against the resolved directory of the link, as the operating system does. +/// +/// +/// A path that does not exist, a path whose links cannot be read, and a path with more than +/// links are compared in their normalized form without link resolution. +/// +/// +/// +/// One of the enumeration values that specifies how the resolved paths are compared. +/// +internal sealed class DirectoryPathComparer(StringComparison comparison) +{ + /// + /// Represents the largest number of symbolic links that are followed while one path is resolved, the limit of + /// SYMLOOP_MAX on Linux. + /// + internal const int MaxLinkCount = 40; + + private static readonly char[] DirectorySeparators = + [Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar]; + + /// + /// Gets the comparison of the resolved paths. + /// + /// + /// One of the enumeration values that specifies how the resolved paths are compared. + /// + public StringComparison Comparison { get; } = comparison; + + /// + /// Creates the comparer for the current operating system. + /// + /// + /// A comparer that compares case-insensitively on Windows and macOS and case-sensitively on every other operating + /// system. + /// + public static DirectoryPathComparer ForCurrentOperatingSystem() + { + return new DirectoryPathComparer(GetComparison(OperatingSystem.IsWindows(), OperatingSystem.IsMacOS())); + } + + /// + /// Returns the comparison of directory paths for an operating system. + /// + /// + /// if the operating system is Windows; otherwise, . + /// + /// + /// if the operating system is macOS; otherwise, . + /// + /// + /// for Windows and macOS, whose default file systems ignore the + /// case; otherwise, . + /// + internal static StringComparison GetComparison(bool isWindows, bool isMacOS) + { + return isWindows || isMacOS ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + } + + /// + /// Determines whether two absolute paths name the same directory. + /// + /// The first absolute path. + /// The second absolute path. + /// + /// if the resolved paths are equal under ; otherwise, + /// . + /// + /// + /// or is . + /// + /// + /// or is not a fully qualified path. + /// + public bool AreSameDirectory(string first, string second) + { + return string.Equals(ResolvePath(first), ResolvePath(second), Comparison); + } + + /// + /// Returns the specified absolute path with every symbolic link resolved to its final target. + /// + /// The absolute path. + /// + /// The resolved path without a trailing directory separator; or, for a path that does not exist, whose links + /// cannot be read, or that has more than links, the normalized path from + /// . + /// + /// is . + /// is not a fully qualified path. + internal static string ResolvePath(string path) + { + Ensure.NotNull(path); + + if (!Path.IsPathFullyQualified(path)) + { + throw new ArgumentException($"'{path}' is not a fully qualified path.", nameof(path)); + } + + var normalizedPath = MarketplaceSource.NormalizeDirectoryPath(path); + + if (!Directory.Exists(normalizedPath)) + { + return normalizedPath; + } + + try + { + var linkCount = 0; + + return ResolveExistingPath(normalizedPath, ref linkCount) ?? normalizedPath; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + return normalizedPath; + } + } + + // Returns null when more than MaxLinkCount links are followed. Every resolved prefix is free of links, so a + // relative link target is combined with it and its ".." segments are removed lexically, as realpath does. + private static string? ResolveExistingPath(string normalizedPath, ref int linkCount) + { + var root = Path.GetPathRoot(normalizedPath)!; + var current = root; + + foreach (var segment in normalizedPath[root.Length..] + .Split(DirectorySeparators, StringSplitOptions.RemoveEmptyEntries)) + { + var candidate = Path.Combine(current, segment); + + if (new DirectoryInfo(candidate).LinkTarget is { } linkTarget) + { + if (++linkCount > MaxLinkCount) + { + return null; + } + + var target = MarketplaceSource.NormalizeDirectoryPath(Path.Combine(current, linkTarget)); + + if (ResolveExistingPath(target, ref linkCount) is not { } resolvedTarget) + { + return null; + } + + candidate = resolvedTarget; + } + + current = candidate; + } + + return Path.TrimEndingDirectorySeparator(current); + } +} diff --git a/src/CreativeCoders.ShadeKit.Core/Integrations/Exceptions/ClaudeCommandFailedException.cs b/src/CreativeCoders.ShadeKit.Core/Integrations/Exceptions/ClaudeCommandFailedException.cs new file mode 100644 index 0000000..7a73b63 --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Core/Integrations/Exceptions/ClaudeCommandFailedException.cs @@ -0,0 +1,64 @@ +using CreativeCoders.ShadeKit.Core.Processes.Exceptions; + +namespace CreativeCoders.ShadeKit.Core.Integrations.Exceptions; + +/// +/// Represents the exception that is thrown when a command of the Claude Code CLI claude runs but fails: it +/// exits with a non-zero exit code, reports an outcome other than ok, or prints no JSON output that SHADE kit +/// can read. +/// +/// +/// A claude that cannot be found or started is reported as a +/// instead. +/// +/// The arguments of the claude command that failed. +/// The exit code of the claude process. +/// +/// A sentence that describes how the command failed, including the message and the failure code that claude +/// reported, if any. +/// +/// +/// The message that claude reported in its JSON output, or if it reported none. +/// +/// +/// The failureCode that claude reported in its JSON output, for example not_found, or +/// if it reported none. +/// +/// +/// The exception that caused this exception, or if there is none. +/// +public sealed class ClaudeCommandFailedException( + IReadOnlyList arguments, + int exitCode, + string reason, + string? claudeMessage = null, + string? failureCode = null, + Exception? innerException = null) + : ExternalToolUnavailableException("claude", "failed", arguments, reason, innerException) +{ + /// + /// Gets the exit code of the claude process. + /// + /// + /// The exit code; 0 if the process succeeded but its output reports a failure or cannot be read. + /// + public int ExitCode { get; } = exitCode; + + /// + /// Gets the message that claude reported in its JSON output. + /// + /// + /// The value of the message field, for example Plugin "x" not found, or if + /// the output has no such string. + /// + public string? ClaudeMessage { get; } = claudeMessage; + + /// + /// Gets the failure code that claude reported in its JSON output. + /// + /// + /// The value of the failureCode field, for example not_found, or if the + /// output has no such string. + /// + public string? FailureCode { get; } = failureCode; +} diff --git a/src/CreativeCoders.ShadeKit.Core/Integrations/Exceptions/ClaudeNotFoundException.cs b/src/CreativeCoders.ShadeKit.Core/Integrations/Exceptions/ClaudeNotFoundException.cs new file mode 100644 index 0000000..4435b7a --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Core/Integrations/Exceptions/ClaudeNotFoundException.cs @@ -0,0 +1,10 @@ +namespace CreativeCoders.ShadeKit.Core.Integrations.Exceptions; + +/// +/// Represents the exception that is thrown when no Claude Code CLI claude executable is found, so a +/// claude command cannot be run. +/// +/// The arguments of the claude command that could not be run. +/// A sentence that describes where claude was looked for. +public sealed class ClaudeNotFoundException(IReadOnlyList arguments, string reason) + : ClaudeUnavailableException(arguments, reason); diff --git a/src/CreativeCoders.ShadeKit.Core/Integrations/Exceptions/ClaudeUnavailableException.cs b/src/CreativeCoders.ShadeKit.Core/Integrations/Exceptions/ClaudeUnavailableException.cs new file mode 100644 index 0000000..428905c --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Core/Integrations/Exceptions/ClaudeUnavailableException.cs @@ -0,0 +1,22 @@ +using CreativeCoders.ShadeKit.Core.Processes.Exceptions; + +namespace CreativeCoders.ShadeKit.Core.Integrations.Exceptions; + +/// +/// Represents the exception that is thrown when the Claude Code CLI claude cannot be started, so a +/// claude command cannot be run. +/// +/// +/// Callers tell a missing or unusable claude from a claude that runs and fails by this type; a +/// claude command that runs and fails is reported as a . +/// +/// The arguments of the claude command that could not be run. +/// A sentence that describes why claude could not be started. +/// +/// The exception that caused this exception, or if there is none. +/// +public class ClaudeUnavailableException( + IReadOnlyList arguments, + string reason, + Exception? innerException = null) + : ExternalToolUnavailableException("claude", "cannot be run", arguments, reason, innerException); diff --git a/src/CreativeCoders.ShadeKit.Core/Integrations/Exceptions/IntegrationConflictException.cs b/src/CreativeCoders.ShadeKit.Core/Integrations/Exceptions/IntegrationConflictException.cs new file mode 100644 index 0000000..f419a09 --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Core/Integrations/Exceptions/IntegrationConflictException.cs @@ -0,0 +1,59 @@ +namespace CreativeCoders.ShadeKit.Core.Integrations.Exceptions; + +/// +/// Represents the exception that is thrown when an agent already knows the plugin marketplace of SHADE kit by its +/// name, but with a different source repository or directory; nothing is changed. +/// +/// The id of the agent, for example claude. +/// The name of the marketplace, for example creativecoders-shade-kit. +/// +/// The source of the existing marketplace as the agent reports it, for example other/repo#main or the path of +/// a directory. +/// +/// The source that SHADE kit needs, for example CreativeCodersTeam/shade-kit#v0.8.0. +/// +/// The command that removes the existing marketplace, so that the next run can add it with the needed source, for +/// example claude plugin marketplace remove creativecoders-shade-kit. +/// +public sealed class IntegrationConflictException( + string agentId, + string marketplaceName, + string existingSource, + string requestedSource, + string resolveCommand) + : Exception($"The plugin marketplace '{marketplaceName}' of the agent '{agentId}' has the source " + + $"'{existingSource}', but SHADE kit needs '{requestedSource}'.") +{ + /// + /// Gets the id of the agent whose marketplace conflicts. + /// + /// The agent id, for example claude. + public string AgentId { get; } = agentId; + + /// + /// Gets the name of the marketplace that conflicts. + /// + /// The marketplace name, for example creativecoders-shade-kit. + public string MarketplaceName { get; } = marketplaceName; + + /// + /// Gets the source of the existing marketplace. + /// + /// The source as the agent reports it, for example other/repo#main or the path of a directory. + public string ExistingSource { get; } = existingSource; + + /// + /// Gets the source that SHADE kit needs. + /// + /// The source, for example CreativeCodersTeam/shade-kit#v0.8.0. + public string RequestedSource { get; } = requestedSource; + + /// + /// Gets the command that resolves the conflict. + /// + /// + /// The command that removes the existing marketplace, for example + /// claude plugin marketplace remove creativecoders-shade-kit. + /// + public string ResolveCommand { get; } = resolveCommand; +} diff --git a/src/CreativeCoders.ShadeKit.Core/Integrations/Exceptions/IntegrationIncompleteException.cs b/src/CreativeCoders.ShadeKit.Core/Integrations/Exceptions/IntegrationIncompleteException.cs new file mode 100644 index 0000000..452b878 --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Core/Integrations/Exceptions/IntegrationIncompleteException.cs @@ -0,0 +1,24 @@ +namespace CreativeCoders.ShadeKit.Core.Integrations.Exceptions; + +/// +/// Represents the exception that is thrown when an agent command fails after the plugin marketplace of SHADE kit was +/// switched to another branch or tag, so the integration of the agent may be incomplete. +/// +/// +/// The steps of an install are repeatable, so running shade-kit integrations install repairs the integration; +/// an update would not, because removing the marketplace also uninstalls its plugins. Nothing is rolled back. The +/// is the failure of the agent command, for example a +/// . +/// +/// The id of the agent, for example claude. +/// The failure of the agent command. +public sealed class IntegrationIncompleteException(string agentId, Exception innerException) + : Exception($"The SHADE kit integration of the agent '{agentId}' may be incomplete: {innerException?.Message}", + innerException) +{ + /// + /// Gets the id of the agent whose integration may be incomplete. + /// + /// The agent id, for example claude. + public string AgentId { get; } = agentId; +} diff --git a/src/CreativeCoders.ShadeKit.Core/Integrations/Exceptions/IntegrationRunFailedException.cs b/src/CreativeCoders.ShadeKit.Core/Integrations/Exceptions/IntegrationRunFailedException.cs new file mode 100644 index 0000000..a39a3ae --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Core/Integrations/Exceptions/IntegrationRunFailedException.cs @@ -0,0 +1,47 @@ +namespace CreativeCoders.ShadeKit.Core.Integrations.Exceptions; + +/// +/// Represents the exception that is thrown when the integration of one agent fails in a run over several agents after +/// the integrations of other agents were already installed or updated. +/// +/// +/// The exception keeps the results of the agents that were done before the failure, so they can still be reported. +/// The is the failure of the agent, for example a +/// or an . A run whose first +/// agent fails, and a canceled run, report the failure without this exception. +/// +/// The id of the agent whose integration failed. +/// The marketplace source that the run targeted. +/// +/// The results of the agents that were installed or updated before the failure, in the order of the run. +/// +/// The failure of the agent. +public sealed class IntegrationRunFailedException( + string failedAgentId, + MarketplaceSource source, + IReadOnlyList completedIntegrations, + Exception innerException) + : Exception( + $"The SHADE kit integration of the agent '{failedAgentId}' failed after the integrations of " + + $"{string.Join(", ", (completedIntegrations ?? []).Select(x => $"'{x.AgentId}'"))} were done: " + + $"{innerException?.Message}", + innerException) +{ + /// + /// Gets the id of the agent whose integration failed. + /// + /// The agent id, for example claude. + public string FailedAgentId { get; } = failedAgentId; + + /// + /// Gets the marketplace source that the run targeted. + /// + /// The source of the completed integrations. + public MarketplaceSource MarketplaceSource { get; } = source; + + /// + /// Gets the results of the agents that were installed or updated before the failure. + /// + /// A copy of the results in the order of the run. + public IReadOnlyList CompletedIntegrations { get; } = [.. completedIntegrations ?? []]; +} diff --git a/src/CreativeCoders.ShadeKit.Core/Integrations/Exceptions/IntegrationSwitchCanceledException.cs b/src/CreativeCoders.ShadeKit.Core/Integrations/Exceptions/IntegrationSwitchCanceledException.cs new file mode 100644 index 0000000..b89fb37 --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Core/Integrations/Exceptions/IntegrationSwitchCanceledException.cs @@ -0,0 +1,27 @@ +namespace CreativeCoders.ShadeKit.Core.Integrations.Exceptions; + +/// +/// Represents the exception that is thrown when a run is canceled while the plugin marketplace of SHADE kit is +/// switched to another branch or tag, so the integration of the agent may be incomplete. +/// +/// +/// The exception is an with the token of the canceled run, so it is handled +/// as a cancellation. Removing the marketplace also uninstalls its plugins, so running +/// shade-kit integrations install repairs the integration. The is the +/// original cancellation. +/// +/// The id of the agent, for example claude. +/// The cancellation that stopped the switch. +public sealed class IntegrationSwitchCanceledException(string agentId, OperationCanceledException innerException) + : OperationCanceledException( + $"The SHADE kit integration of the agent '{agentId}' was canceled while its plugin marketplace was switched, " + + "so it may be incomplete.", + innerException, + innerException?.CancellationToken ?? CancellationToken.None) +{ + /// + /// Gets the id of the agent whose integration may be incomplete. + /// + /// The agent id, for example claude. + public string AgentId { get; } = agentId; +} diff --git a/src/CreativeCoders.ShadeKit.Core/Integrations/Exceptions/InvalidMarketplaceSourceException.cs b/src/CreativeCoders.ShadeKit.Core/Integrations/Exceptions/InvalidMarketplaceSourceException.cs new file mode 100644 index 0000000..50e3824 --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Core/Integrations/Exceptions/InvalidMarketplaceSourceException.cs @@ -0,0 +1,23 @@ +namespace CreativeCoders.ShadeKit.Core.Integrations.Exceptions; + +/// +/// Represents the exception that is thrown when the marketplace source that a developer set in the environment +/// variable cannot be used. +/// +/// The value of the environment variable. +/// A sentence that describes why the value cannot be used. +public sealed class InvalidMarketplaceSourceException(string value, string reason) + : Exception($"The marketplace source '{value}' cannot be used: {reason}") +{ + /// + /// Gets the marketplace source that cannot be used. + /// + /// The value of the environment variable as it was set. + public string Value { get; } = value; + + /// + /// Gets the reason why the marketplace source cannot be used. + /// + /// A sentence, for example The value is empty. + public string Reason { get; } = reason; +} diff --git a/src/CreativeCoders.ShadeKit.Core/Integrations/Exceptions/NoAgentFoundException.cs b/src/CreativeCoders.ShadeKit.Core/Integrations/Exceptions/NoAgentFoundException.cs new file mode 100644 index 0000000..0976c46 --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Core/Integrations/Exceptions/NoAgentFoundException.cs @@ -0,0 +1,16 @@ +namespace CreativeCoders.ShadeKit.Core.Integrations.Exceptions; + +/// +/// Represents the exception that is thrown when an integration command needs an agent, but none of the supported +/// agents is detected on the computer. +/// +/// The ids of the supported agents, for example claude. +public sealed class NoAgentFoundException(IReadOnlyList supportedAgentIds) + : Exception($"None of the supported agents ({string.Join(", ", supportedAgentIds ?? [])}) was found.") +{ + /// + /// Gets the ids of the supported agents. + /// + /// A copy of the agent ids in the order in which the agents are registered. + public IReadOnlyList SupportedAgentIds { get; } = [.. supportedAgentIds ?? []]; +} diff --git a/src/CreativeCoders.ShadeKit.Core/Integrations/IAgentIntegration.cs b/src/CreativeCoders.ShadeKit.Core/Integrations/IAgentIntegration.cs new file mode 100644 index 0000000..d90ffd6 --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Core/Integrations/IAgentIntegration.cs @@ -0,0 +1,117 @@ +using CreativeCoders.ShadeKit.Core.Integrations.Exceptions; +using CreativeCoders.ShadeKit.Core.Processes.Exceptions; + +namespace CreativeCoders.ShadeKit.Core.Integrations; + +/// +/// Installs, updates, and reads the SHADE kit integration of one agent, such as Claude Code, through the CLI of the +/// agent. +/// +/// +/// An implementation installs the integration for the user, never into a repository. Its steps are repeatable, so a +/// failed run is repaired by running it again. A missing or failing agent CLI is reported as an +/// . +/// +public interface IAgentIntegration +{ + /// + /// Gets the id of the agent. + /// + /// A lowercase id, for example claude, which shade-kit integrations install --agent takes. + string AgentId { get; } + + /// + /// Returns a value that indicates whether the agent is detected on this computer. + /// + /// + /// if the CLI of the agent is found; otherwise, . + /// + bool IsAvailable(); + + /// + /// Throws the exception of the agent for a missing CLI if the agent is not detected on this computer. + /// + /// + /// Lets a caller report a named agent that is missing before it does anything else, for example before a network + /// call. + /// + /// + /// The CLI of the agent is not found, for example a . + /// + void EnsureAvailable(); + + /// + /// Reads the SHADE kit integration that is installed in the agent for the user. + /// + /// The token to monitor for cancellation requests. + /// + /// A task that represents the asynchronous operation. The task result contains the installed integration, or + /// if none is installed for the user. + /// + /// The agent CLI is missing, cannot be started, or fails. + /// + /// was canceled; a started process is killed. + /// + Task GetInstalledAsync(CancellationToken cancellationToken = default); + + /// + /// Installs the SHADE kit integration from the specified source for the user, or updates it if it is installed. + /// + /// The marketplace source to install from. + /// The token to monitor for cancellation requests. + /// + /// A task that represents the asynchronous operation. The task result contains what was done. + /// + /// is . + /// + /// The agent knows the marketplace of SHADE kit with a different source; nothing was changed. + /// + /// + /// An agent command failed after the marketplace was switched to another branch or tag. + /// + /// + /// was canceled while the marketplace was switched to another branch or tag. + /// + /// The agent CLI is missing, cannot be started, or fails. + /// + /// was canceled; a started process is killed. + /// + Task InstallAsync(MarketplaceSource source, CancellationToken cancellationToken = default); + + /// + /// Updates the SHADE kit integration if it is installed for the user, from the source that the specified function + /// returns. + /// + /// + /// is called once, and only if the integration is installed, before anything is + /// changed; so a run in which nothing is installed resolves no source. + /// + /// + /// The function that returns the marketplace source to update from; it receives + /// . + /// + /// The token to monitor for cancellation requests. + /// + /// A task that represents the asynchronous operation. The task result contains what was done, or + /// if the integration is not installed for the user, in which case nothing was changed. + /// + /// + /// is or returns . + /// + /// + /// The agent knows the marketplace of SHADE kit with a different source; nothing was changed. + /// + /// + /// An agent command failed after the marketplace was switched to another branch or tag. + /// + /// + /// was canceled while the marketplace was switched to another branch or tag. + /// + /// The agent CLI is missing, cannot be started, or fails. + /// + /// was canceled; a started process is killed. Any exception that + /// throws escapes unchanged. + /// + Task UpdateAsync(Func> getSource, + CancellationToken cancellationToken = default); +} diff --git a/src/CreativeCoders.ShadeKit.Core/Integrations/IIntegrationService.cs b/src/CreativeCoders.ShadeKit.Core/Integrations/IIntegrationService.cs new file mode 100644 index 0000000..4de56a3 --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Core/Integrations/IIntegrationService.cs @@ -0,0 +1,125 @@ +using CreativeCoders.ShadeKit.Core.Integrations.Exceptions; +using CreativeCoders.ShadeKit.Core.Processes.Exceptions; + +namespace CreativeCoders.ShadeKit.Core.Integrations; + +/// +/// Installs, updates, and reads the SHADE kit integrations of all supported agents from the marketplace source that +/// fits the running engine. +/// +/// +/// A release engine x.y.z targets CreativeCodersTeam/shade-kit#vx.y.z if that tag exists or cannot be +/// checked, and CreativeCodersTeam/shade-kit#main with an +/// if it does not exist; a prerelease engine targets +/// CreativeCodersTeam/shade-kit#main with an . The +/// environment variable replaces the whole source, as +/// described for . Nothing is written into a repository. +/// +public interface IIntegrationService +{ + /// + /// Gets the ids of the supported agents. + /// + /// The agent ids in the order in which the agents are registered, for example claude. + IReadOnlyList AgentIds { get; } + + /// + /// Installs the SHADE kit integration for the specified agents, or for every detected agent, and updates it where + /// it is installed. + /// + /// + /// The ids of the agents to install for, compared case-insensitively; or an empty + /// collection installs for every agent that is detected on this computer. + /// + /// The token to monitor for cancellation requests. + /// + /// A task that represents the asynchronous operation. The task result contains the targeted source, the result of + /// each agent, and the warnings. + /// + /// contains an id that is not supported. + /// + /// The environment variable cannot be used. + /// + /// No agent was named and none is detected. + /// + /// An agent knows the marketplace of SHADE kit with a different source; nothing was changed for that agent. + /// + /// + /// An agent command failed after the marketplace was switched to another branch or tag. + /// + /// + /// An agent failed after other agents were already done; the exception keeps their results, and its + /// is the failure of the agent. + /// + /// + /// was canceled while the marketplace of an agent was switched to another + /// branch or tag. + /// + /// + /// The CLI of an agent is missing, cannot be started, or fails, for example a + /// for a named agent that is not detected; a named agent that is not + /// detected fails before the release tag is checked. + /// + /// + /// was canceled; a started process is killed. + /// + Task InstallAsync(IReadOnlyCollection? agentIds, + CancellationToken cancellationToken = default); + + /// + /// Updates the SHADE kit integration of every detected agent in which it is installed for the user. + /// + /// + /// Each agent reads its installed integration once; the source is resolved (and the release tag checked) once, + /// when the first agent with an installed integration needs it. + /// + /// The token to monitor for cancellation requests. + /// + /// A task that represents the asynchronous operation. The task result contains the targeted source, the result of + /// each updated agent, and the warnings. If no integration is installed, the source is , + /// the list is empty, and there are no warnings: the source is resolved (and the release tag checked) only for an + /// installed integration. + /// + /// + /// An integration is installed and the environment variable + /// cannot be used. + /// + /// No agent is detected. + /// + /// An agent knows the marketplace of SHADE kit with a different source; nothing was changed for that agent. + /// + /// + /// An agent command failed after the marketplace was switched to another branch or tag. + /// + /// + /// An agent failed after other agents were already done; the exception keeps their results, and its + /// is the failure of the agent. + /// + /// + /// was canceled while the marketplace of an agent was switched to another + /// branch or tag. + /// + /// The CLI of an agent cannot be started or fails. + /// + /// was canceled; a started process is killed. + /// + Task UpdateAsync(CancellationToken cancellationToken = default); + + /// + /// Reads the SHADE kit integrations that are installed in the agents for the user. + /// + /// + /// Only agents whose CLI is detected are asked; an agent whose CLI is not detected is left out without a warning. + /// An agent whose CLI is detected but cannot be started or fails is left out with an + /// , so this method fails only on cancellation. + /// + /// The token to monitor for cancellation requests. + /// + /// A task that represents the asynchronous operation. The task result contains the installed integrations and the + /// warnings. + /// + /// + /// was canceled; a started process is killed. + /// + Task GetInstalledAsync(CancellationToken cancellationToken = default); +} diff --git a/src/CreativeCoders.ShadeKit.Core/Integrations/InstalledIntegration.cs b/src/CreativeCoders.ShadeKit.Core/Integrations/InstalledIntegration.cs new file mode 100644 index 0000000..0a83348 --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Core/Integrations/InstalledIntegration.cs @@ -0,0 +1,27 @@ +namespace CreativeCoders.ShadeKit.Core.Integrations; + +/// +/// Represents the SHADE kit integration that is installed in an agent for the user. +/// +/// The id of the agent, for example claude. +/// +/// The id of the integration in the agent, for example shade-kit@creativecoders-shade-kit. +/// +/// +/// The installed kit version, taken from the v<SemVer> ref of the marketplace, or +/// if the ref is no such tag, the marketplace is a local directory, or the agent no longer +/// knows the marketplace. +/// +/// +/// The branch or tag of the marketplace, or for a local directory, the default branch, or a +/// marketplace that the agent no longer knows. +/// +/// +/// if the integration is enabled in the agent; otherwise, . +/// +public sealed record InstalledIntegration( + string AgentId, + string PluginId, + string? KitVersion, + string? Ref, + bool Enabled); diff --git a/src/CreativeCoders.ShadeKit.Core/Integrations/InstalledIntegrationsResult.cs b/src/CreativeCoders.ShadeKit.Core/Integrations/InstalledIntegrationsResult.cs new file mode 100644 index 0000000..73808a9 --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Core/Integrations/InstalledIntegrationsResult.cs @@ -0,0 +1,18 @@ +using CreativeCoders.ShadeKit.Core.Warnings; + +namespace CreativeCoders.ShadeKit.Core.Integrations; + +/// +/// Represents the SHADE kit integrations that are installed in the agents for the user. +/// +/// +/// The installed integrations in the order in which the agents are registered; an empty list if none is installed or +/// no agent could be asked. +/// +/// +/// The warnings, for example an for each agent whose CLI is missing or +/// fails; an empty list if there were none. +/// +public sealed record InstalledIntegrationsResult( + IReadOnlyList Integrations, + IReadOnlyList Warnings); diff --git a/src/CreativeCoders.ShadeKit.Core/Integrations/IntegrationOutcome.cs b/src/CreativeCoders.ShadeKit.Core/Integrations/IntegrationOutcome.cs new file mode 100644 index 0000000..2a1969b --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Core/Integrations/IntegrationOutcome.cs @@ -0,0 +1,22 @@ +namespace CreativeCoders.ShadeKit.Core.Integrations; + +/// +/// Specifies what an install or update did with the SHADE kit integration of an agent. +/// +public enum IntegrationOutcome +{ + /// + /// The integration was not installed before and is installed now. + /// + Installed, + + /// + /// The integration was installed before and was updated or installed again from the targeted source. + /// + Updated, + + /// + /// The integration was installed from the targeted source already and had the latest version; nothing was changed. + /// + Current +} diff --git a/src/CreativeCoders.ShadeKit.Core/Integrations/IntegrationResult.cs b/src/CreativeCoders.ShadeKit.Core/Integrations/IntegrationResult.cs new file mode 100644 index 0000000..820d586 --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Core/Integrations/IntegrationResult.cs @@ -0,0 +1,33 @@ +namespace CreativeCoders.ShadeKit.Core.Integrations; + +/// +/// Represents the result of a successful install or update of the SHADE kit integration of one agent. +/// +/// The id of the agent, for example claude. +/// +/// The id of the integration in the agent, for example shade-kit@creativecoders-shade-kit. +/// +/// One of the enumeration values that specifies what was done. +/// +/// The kit version that was installed before, taken from the v<SemVer> ref of the marketplace before the +/// change, or if the integration was not installed or its ref is no such tag. +/// +/// +/// The kit version that is installed now, taken from the v<SemVer> ref of the source, or +/// if the ref is no such tag or the source is a local directory. +/// +/// +/// The branch or tag that is installed now, or for a local directory or the default branch. +/// +/// +/// if the integration is enabled in the agent; otherwise, . An update +/// does not enable a disabled integration. +/// +public sealed record IntegrationResult( + string AgentId, + string PluginId, + IntegrationOutcome Outcome, + string? PreviousKitVersion, + string? KitVersion, + string? Ref, + bool Enabled); diff --git a/src/CreativeCoders.ShadeKit.Core/Integrations/IntegrationRunResult.cs b/src/CreativeCoders.ShadeKit.Core/Integrations/IntegrationRunResult.cs new file mode 100644 index 0000000..b14bc8d --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Core/Integrations/IntegrationRunResult.cs @@ -0,0 +1,23 @@ +using CreativeCoders.ShadeKit.Core.Warnings; + +namespace CreativeCoders.ShadeKit.Core.Integrations; + +/// +/// Represents the result of a successful shade-kit integrations install or update over all agents. +/// +/// +/// The marketplace source that the engine targets, or if an update found no installed +/// integration and therefore resolved no source. +/// +/// +/// The result of each agent that was installed or updated, in the order in which the agents are registered; an empty +/// list if an update found no installed integration. +/// +/// +/// The warnings of the run, for example an ; an empty list if +/// there were none. +/// +public sealed record IntegrationRunResult( + MarketplaceSource? Source, + IReadOnlyList Integrations, + IReadOnlyList Warnings); diff --git a/src/CreativeCoders.ShadeKit.Core/Integrations/IntegrationService.cs b/src/CreativeCoders.ShadeKit.Core/Integrations/IntegrationService.cs new file mode 100644 index 0000000..d5d8504 --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Core/Integrations/IntegrationService.cs @@ -0,0 +1,337 @@ +using System.Diagnostics.CodeAnalysis; +using CreativeCoders.Core; +using CreativeCoders.ShadeKit.Core.Engine; +using CreativeCoders.ShadeKit.Core.Git; +using CreativeCoders.ShadeKit.Core.Integrations.Exceptions; +using CreativeCoders.ShadeKit.Core.Integrations.Warnings; +using CreativeCoders.ShadeKit.Core.Processes.Exceptions; +using CreativeCoders.ShadeKit.Core.Versions; +using CreativeCoders.ShadeKit.Core.Warnings; + +namespace CreativeCoders.ShadeKit.Core.Integrations; + +/// +/// Installs, updates, and reads the SHADE kit integrations of the registered s from +/// the marketplace source that fits the engine version of an . +/// +/// +/// +/// For a release engine without the environment variable , the +/// checks that the release tag exists in . +/// A missing tag gives with an ; if the +/// check cannot be made (no git, no network), the tag is used unchecked without a warning, so an agent CLI that +/// cannot find it reports the failure. +/// +/// +/// The agents run one after the other. If an agent fails after other agents were already installed or updated, the +/// failure is reported as an that keeps their results; a cancellation +/// and a failure of the first agent escape unchanged. +/// +/// +[SuppressMessage("Minor Code Smell", "S1075:URIs should not be hardcoded", + Justification = "The marketplace repository of SHADE kit is fixed by design; the environment variable " + + "SHADE_KIT_MARKETPLACE_SOURCE replaces the source for developers.")] +public sealed class IntegrationService : IIntegrationService +{ + /// + /// Represents the name of the environment variable that replaces the marketplace source, a developer option for + /// example to install from the working tree of the SHADE kit repository. + /// + public const string MarketplaceSourceVariableName = "SHADE_KIT_MARKETPLACE_SOURCE"; + + /// + /// Represents the GitHub repository that is the plugin marketplace of SHADE kit. + /// + public const string MarketplaceRepo = "CreativeCodersTeam/shade-kit"; + + /// + /// Represents the https:// URL of the git repository of , in which the release + /// tags are checked. + /// + public const string MarketplaceRepositoryUrl = "https://github.com/" + MarketplaceRepo + ".git"; + + /// + /// Represents the branch that a prerelease engine, and a release engine whose release tag does not exist, installs + /// from. + /// + public const string FallbackRef = "main"; + + private readonly IReadOnlyList _agentIntegrations; + + private readonly IEngineVersionProvider _engineVersionProvider; + + private readonly IGitRemoteTagChecker _gitRemoteTagChecker; + + private readonly Func _getEnvironmentVariable; + + private readonly Func _getCurrentDirectory; + + /// + /// Initializes a new instance of the class that reads the environment variables + /// and the current directory of the current process. + /// + /// The integrations of the supported agents. + /// The provider of the running engine version. + /// The checker that finds out whether the release tag exists. + /// + /// , , or + /// is . + /// + /// + /// Two of have the same agent id, compared case-insensitively. + /// + public IntegrationService(IEnumerable agentIntegrations, + IEngineVersionProvider engineVersionProvider, IGitRemoteTagChecker gitRemoteTagChecker) + : this(agentIntegrations, engineVersionProvider, gitRemoteTagChecker, Environment.GetEnvironmentVariable, + Directory.GetCurrentDirectory) + { + } + + /// + /// Initializes a new instance of the class with the specified sources for the + /// environment variables and the current directory. + /// + /// The integrations of the supported agents. + /// The provider of the running engine version. + /// The checker that finds out whether the release tag exists. + /// + /// The function that returns the value of an environment variable, or if it is not set. + /// + /// The function that returns the absolute current directory. + /// An argument is . + /// + /// Two of have the same agent id, compared case-insensitively. + /// + internal IntegrationService(IEnumerable agentIntegrations, + IEngineVersionProvider engineVersionProvider, IGitRemoteTagChecker gitRemoteTagChecker, + Func getEnvironmentVariable, Func getCurrentDirectory) + { + _agentIntegrations = [.. Ensure.NotNull(agentIntegrations)]; + _engineVersionProvider = Ensure.NotNull(engineVersionProvider); + _gitRemoteTagChecker = Ensure.NotNull(gitRemoteTagChecker); + _getEnvironmentVariable = Ensure.NotNull(getEnvironmentVariable); + _getCurrentDirectory = Ensure.NotNull(getCurrentDirectory); + + AgentIds = [.. _agentIntegrations.Select(x => x.AgentId)]; + + if (AgentIds.Distinct(StringComparer.OrdinalIgnoreCase).Count() != AgentIds.Count) + { + throw new ArgumentException("Two agent integrations have the same agent id.", nameof(agentIntegrations)); + } + } + + /// + public IReadOnlyList AgentIds { get; } + + /// + public async Task InstallAsync(IReadOnlyCollection? agentIds, + CancellationToken cancellationToken = default) + { + var selectedAgents = agentIds is null or { Count: 0 } ? null : SelectAgents(agentIds); + + // The local part of the source is resolved before the detection, so an invalid override is reported first; + // the release tag is checked only when there is an agent to install for. + var uncheckedSource = ResolveUncheckedSource(); + + var agents = selectedAgents ?? DetectAgents(); + + // A named agent that is missing fails before the network call of the tag check. + foreach (var agent in agents) + { + agent.EnsureAvailable(); + } + + var (source, warnings) = await CheckReleaseTagAsync(uncheckedSource, cancellationToken).ConfigureAwait(false); + + var results = new List(agents.Count); + + foreach (var agent in agents) + { + try + { + results.Add(await agent.InstallAsync(source, cancellationToken).ConfigureAwait(false)); + } + catch (Exception exception) when (results.Count > 0 && IsAgentFailure(exception)) + { + throw new IntegrationRunFailedException(agent.AgentId, source, results, exception); + } + } + + return new IntegrationRunResult(source, results, warnings); + } + + /// + public async Task UpdateAsync(CancellationToken cancellationToken = default) + { + var agents = DetectAgents(); + + // The source is resolved once, by the first agent that has the integration installed, before that agent + // changes anything; without an installed integration neither the tag check nor its warnings happen. + (MarketplaceSource Source, IReadOnlyList Warnings)? resolved = null; + + async Task GetSourceAsync(CancellationToken token) + { + resolved ??= await ResolveSourceAsync(token).ConfigureAwait(false); + + return resolved.Value.Source; + } + + var results = new List(agents.Count); + + foreach (var agent in agents) + { + try + { + if (await agent.UpdateAsync(GetSourceAsync, cancellationToken).ConfigureAwait(false) is { } result) + { + results.Add(result); + } + } + catch (Exception exception) when (results.Count > 0 && resolved is not null && IsAgentFailure(exception)) + { + throw new IntegrationRunFailedException(agent.AgentId, resolved.Value.Source, results, exception); + } + } + + return resolved is { } run + ? new IntegrationRunResult(run.Source, results, run.Warnings) + : new IntegrationRunResult(null, [], []); + } + + /// + public async Task GetInstalledAsync(CancellationToken cancellationToken = default) + { + var integrations = new List(); + var warnings = new List(); + + foreach (var agent in _agentIntegrations.Where(x => x.IsAvailable())) + { + try + { + if (await agent.GetInstalledAsync(cancellationToken).ConfigureAwait(false) is { } integration) + { + integrations.Add(integration); + } + } + catch (ExternalToolUnavailableException exception) + { + warnings.Add(new AgentUnavailableWarning(agent.AgentId, exception.Message)); + } + } + + return new InstalledIntegrationsResult(integrations, warnings); + } + + /// + /// Returns the marketplace source that the running engine targets. + /// + /// The token to monitor for cancellation requests. + /// + /// A task that represents the asynchronous operation. The task result contains the source and its warnings: the + /// value of if it is set; otherwise + /// with the tag v<engine version> for a release engine whose tag exists or cannot be checked, with + /// and an for a release engine whose + /// tag does not exist, or with and an for + /// a prerelease engine. Only a release engine without the environment variable checks the tag. + /// + /// The environment variable cannot be used. + /// The engine version is not a valid SemVer 2.0.0 version. + /// + /// was canceled; a started process is killed. + /// + internal async Task<(MarketplaceSource Source, IReadOnlyList Warnings)> ResolveSourceAsync( + CancellationToken cancellationToken) + { + return await CheckReleaseTagAsync(ResolveUncheckedSource(), cancellationToken).ConfigureAwait(false); + } + + // Everything that needs neither git nor the network: the override, or the source that the engine version names. + private UncheckedSource ResolveUncheckedSource() + { + if (_getEnvironmentVariable(MarketplaceSourceVariableName) is { } overrideValue) + { + return new UncheckedSource(MarketplaceSource.Parse(overrideValue, _getCurrentDirectory()), [], null); + } + + var engineVersionText = _engineVersionProvider.Version; + + if (!SemanticVersion.TryParse(engineVersionText, out var engineVersion)) + { + throw new InvalidOperationException( + $"The engine version '{engineVersionText}' is not a valid SemVer 2.0.0 version, so the marketplace " + + "source cannot be chosen. The engine build is defective."); + } + + if (engineVersion.IsPrerelease) + { + return new UncheckedSource(MarketplaceSource.ForGitHub(MarketplaceRepo, FallbackRef), + [new IntegrationPrereleaseRefWarning(engineVersionText, FallbackRef)], null); + } + + return new UncheckedSource(MarketplaceSource.ForGitHub(MarketplaceRepo, $"v{engineVersion}"), [], + engineVersionText); + } + + private async Task<(MarketplaceSource Source, IReadOnlyList Warnings)> CheckReleaseTagAsync( + UncheckedSource uncheckedSource, CancellationToken cancellationToken) + { + if (uncheckedSource is not { ReleaseEngineVersion: { } engineVersion, Source.Ref: { } releaseTag }) + { + return (uncheckedSource.Source, uncheckedSource.Warnings); + } + + var tagState = await _gitRemoteTagChecker + .CheckTagAsync(MarketplaceRepositoryUrl, releaseTag, cancellationToken) + .ConfigureAwait(false); + + // A tag that cannot be checked (no git, no network) is used unchecked; the agent CLI reports a missing one. + return tagState == GitRemoteTagState.Missing + ? (MarketplaceSource.ForGitHub(MarketplaceRepo, FallbackRef), + [new IntegrationReleaseTagMissingWarning(engineVersion, releaseTag, FallbackRef)]) + : (uncheckedSource.Source, uncheckedSource.Warnings); + } + + // The documented failures of an agent; anything else is a defect, and a cancellation stays a cancellation. + private static bool IsAgentFailure(Exception exception) + { + return exception is ExternalToolUnavailableException or IntegrationConflictException + or IntegrationIncompleteException; + } + + private List SelectAgents(IReadOnlyCollection agentIds) + { + var agents = new List(); + + foreach (var agentId in agentIds) + { + var agent = _agentIntegrations.FirstOrDefault(x => + string.Equals(x.AgentId, agentId, StringComparison.OrdinalIgnoreCase)) + ?? throw new ArgumentException( + $"The agent '{agentId}' is not supported. Supported agents: {string.Join(", ", AgentIds)}.", + nameof(agentIds)); + + if (!agents.Contains(agent)) + { + agents.Add(agent); + } + } + + return agents; + } + + private List DetectAgents() + { + var agents = _agentIntegrations.Where(x => x.IsAvailable()).ToList(); + + return agents.Count == 0 + ? throw new NoAgentFoundException(AgentIds) + : agents; + } + + // The source before the release tag check; ReleaseEngineVersion is set only for the release tag of a release + // engine, the one source that is checked. + private sealed record UncheckedSource( + MarketplaceSource Source, + IReadOnlyList Warnings, + string? ReleaseEngineVersion); +} diff --git a/src/CreativeCoders.ShadeKit.Core/Integrations/MarketplaceSource.cs b/src/CreativeCoders.ShadeKit.Core/Integrations/MarketplaceSource.cs new file mode 100644 index 0000000..a4a4aea --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Core/Integrations/MarketplaceSource.cs @@ -0,0 +1,266 @@ +using System.Text.RegularExpressions; +using CreativeCoders.Core; +using CreativeCoders.ShadeKit.Core.Integrations.Exceptions; +using CreativeCoders.ShadeKit.Core.Versions; + +namespace CreativeCoders.ShadeKit.Core.Integrations; + +/// +/// Represents the source of the plugin marketplace from which an agent installs the SHADE kit integration: a GitHub +/// repository with an optional branch or tag, or a local directory. +/// +/// +/// Exactly one of and is set. Create instances with +/// or . +/// +public sealed partial record MarketplaceSource +{ + private MarketplaceSource(string text, string? repo, string? @ref, string? path) + { + Text = text; + Repo = repo; + Ref = @ref; + Path = path; + } + + /// + /// Gets the source as an agent CLI takes it, for example in claude plugin marketplace add <source>. + /// + /// + /// owner/repo#ref or owner/repo for a GitHub repository, or the absolute path of a local directory. + /// + public string Text { get; } + + /// + /// Gets the GitHub repository of the source. + /// + /// + /// The repository in the form owner/repo, or if the source is a local directory. + /// + public string? Repo { get; } + + /// + /// Gets the branch or tag of the GitHub repository. + /// + /// + /// The branch or tag, for example v0.8.0 or main, or if the source is a + /// local directory or names no branch or tag, which means the default branch of the repository. + /// + public string? Ref { get; } + + /// + /// Gets the absolute path of the local directory of the source. + /// + /// + /// The absolute path without a trailing directory separator, or if the source is a GitHub + /// repository. + /// + public string? Path { get; } + + /// + /// Gets the kit version that the source provides. + /// + /// + /// The SemVer version of a of the form v<SemVer> without the v, for example + /// 0.8.0 for v0.8.0, or for any other ref and for a local directory. + /// + public string? KitVersion => GetKitVersion(Ref); + + /// + /// Creates the source of a GitHub repository with an optional branch or tag. + /// + /// The repository in the form owner/repo, for example CreativeCodersTeam/shade-kit. + /// + /// The branch or tag, for example v0.8.0, or for the default branch. + /// + /// The source with the owner/repo#ref, or owner/repo without a ref. + /// is . + /// + /// is not of the form owner/repo, or is empty or contains + /// whitespace or #. + /// + public static MarketplaceSource ForGitHub(string repo, string? @ref = null) + { + Ensure.NotNull(repo); + + if (!GitHubRepoRegex().IsMatch(repo)) + { + throw new ArgumentException($"'{repo}' is not a GitHub repository of the form owner/repo.", nameof(repo)); + } + + if (@ref is not null && !GitHubRefRegex().IsMatch(@ref)) + { + throw new ArgumentException($"'{@ref}' is not a branch or tag: it is empty or contains whitespace or '#'.", + nameof(@ref)); + } + + return new MarketplaceSource(@ref is null ? repo : $"{repo}#{@ref}", repo, @ref, null); + } + + /// + /// Creates the source of a local directory. + /// + /// The absolute path of the directory. + /// The source with the normalized absolute path as and . + /// is . + /// is not an absolute path. + public static MarketplaceSource ForDirectory(string path) + { + Ensure.NotNull(path); + + if (!System.IO.Path.IsPathFullyQualified(path)) + { + throw new ArgumentException($"'{path}' is not an absolute path.", nameof(path)); + } + + var fullPath = NormalizeDirectoryPath(path); + + return new MarketplaceSource(fullPath, null, null, fullPath); + } + + /// + /// Parses a marketplace source that a developer set, for example in the environment variable + /// . + /// + /// + /// + /// A URL is refused: a value that starts with a scheme of at least two characters and ://, for example + /// https://, ssh://, or file://, and an scp-like git URL such as + /// git@github.com:owner/repo, whose first : follows at least two characters without / or + /// \. A Windows drive path such as C:\kit, C:/kit, or C://kit has a single letter + /// before the : and is no URL; on Windows it is a fully qualified path. + /// + /// + /// A value whose part before the first # is no fully qualified path, does not start with . or + /// ~, and contains exactly one / and no \ is a GitHub repository, owner/repo#ref or + /// owner/repo; the ref may contain /, for example feature/x. Every other value + /// is the path of a local directory; a relative path is made absolute against + /// , so a relative directory with one / is written as + /// ./dir/sub. A ~ is not expanded. + /// + /// + /// The value to parse. + /// The absolute directory against which a relative path is resolved. + /// The parsed source. + /// + /// is empty or whitespace, starts with -, is a URL, or looks like a GitHub + /// repository but is not of the form owner/repo#ref or owner/repo. + /// + internal static MarketplaceSource Parse(string value, string currentDirectory) + { + Ensure.NotNull(value); + Ensure.NotNull(currentDirectory); + + if (string.IsNullOrWhiteSpace(value)) + { + throw new InvalidMarketplaceSourceException(value, "The value is empty."); + } + + if (value.StartsWith('-')) + { + throw new InvalidMarketplaceSourceException(value, + "The value starts with '-', so the agent CLI would read it as an option."); + } + + if (UrlWithSchemeRegex().IsMatch(value)) + { + throw new InvalidMarketplaceSourceException(value, + "It is a URL, and SHADE kit takes no URL as a marketplace source; a GitHub repository is written " + + "as owner/repo#ref or owner/repo."); + } + + if (ScpLikeGitUrlRegex().IsMatch(value)) + { + throw new InvalidMarketplaceSourceException(value, + "It is an scp-like git URL (user@host:path), and SHADE kit takes no URL as a marketplace source; a " + + "GitHub repository is written as owner/repo#ref or owner/repo."); + } + + if (IsGitHubForm(value)) + { + return ParseGitHub(value); + } + + var path = System.IO.Path.IsPathFullyQualified(value) + ? value + : System.IO.Path.GetFullPath(value, currentDirectory); + + return ForDirectory(path); + } + + /// + /// Returns the kit version that the specified branch or tag provides. + /// + /// The branch or tag, or . + /// + /// The text after the v of a ref of the form v<SemVer>, for example 0.8.0; otherwise, + /// . + /// + internal static string? GetKitVersion(string? @ref) + { + return @ref is ['v', .. var version] && SemanticVersion.TryParse(version, out _) + ? version + : null; + } + + /// + /// Returns the specified absolute path in the normalized form of . + /// + /// Symbolic links are not resolved; see for the comparison. + /// The absolute path. + /// The full path without a trailing directory separator. + internal static string NormalizeDirectoryPath(string path) + { + return System.IO.Path.TrimEndingDirectorySeparator(System.IO.Path.GetFullPath(path)); + } + + // Only the part before '#' decides, because a branch such as feature/x may contain '/'. + private static bool IsGitHubForm(string value) + { + var repoPart = value.Split('#', 2)[0]; + + return !System.IO.Path.IsPathFullyQualified(repoPart) + && !repoPart.StartsWith('.') + && !repoPart.StartsWith('~') + && !repoPart.Contains('\\', StringComparison.Ordinal) + && repoPart.Count(x => x == '/') == 1; + } + + private static MarketplaceSource ParseGitHub(string value) + { + var parts = value.Split('#', 2); + var repo = parts[0]; + var @ref = parts.Length == 2 ? parts[1] : null; + + if (!GitHubRepoRegex().IsMatch(repo)) + { + throw new InvalidMarketplaceSourceException(value, + $"'{repo}' is not a GitHub repository of the form owner/repo."); + } + + if (@ref is not null && !GitHubRefRegex().IsMatch(@ref)) + { + throw new InvalidMarketplaceSourceException(value, + "The branch or tag after '#' is empty or contains whitespace or '#'."); + } + + return ForGitHub(repo, @ref); + } + + // GitHub owners consist of letters, digits, and hyphens; repository names also allow '.' and '_' but are not + // '.' or '..'. + [GeneratedRegex(@"\A[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?/(?!\.\.?\z)[A-Za-z0-9._-]+\z")] + private static partial Regex GitHubRepoRegex(); + + [GeneratedRegex(@"\A[^\s#]+\z")] + private static partial Regex GitHubRefRegex(); + + // A scheme in the syntax of RFC 3986, but of at least two characters, so that the drive path C://kit is no URL. + [GeneratedRegex(@"\A[A-Za-z][A-Za-z0-9+.-]+://")] + private static partial Regex UrlWithSchemeRegex(); + + // git's rule: a ':' before the first '/' makes a value an scp-like URL; '\\' counts as a separator too, and a + // single letter before the ':' is a Windows drive. + [GeneratedRegex(@"\A[^/\\:]{2,}:")] + private static partial Regex ScpLikeGitUrlRegex(); +} diff --git a/src/CreativeCoders.ShadeKit.Core/Integrations/Warnings/AgentUnavailableWarning.cs b/src/CreativeCoders.ShadeKit.Core/Integrations/Warnings/AgentUnavailableWarning.cs new file mode 100644 index 0000000..fdc6871 --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Core/Integrations/Warnings/AgentUnavailableWarning.cs @@ -0,0 +1,13 @@ +using CreativeCoders.ShadeKit.Core.Warnings; + +namespace CreativeCoders.ShadeKit.Core.Integrations.Warnings; + +/// +/// Represents a warning that the integration of an agent cannot be read because the agent CLI is detected but cannot +/// be started or fails, so the agent is left out of the installed integrations. +/// +/// The id of the agent, for example claude. +/// +/// A sentence that describes why the agent CLI cannot be used, for example the message of the failed command. +/// +public sealed record AgentUnavailableWarning(string AgentId, string Reason) : KitWarning; diff --git a/src/CreativeCoders.ShadeKit.Core/Integrations/Warnings/IntegrationPrereleaseRefWarning.cs b/src/CreativeCoders.ShadeKit.Core/Integrations/Warnings/IntegrationPrereleaseRefWarning.cs new file mode 100644 index 0000000..a0c2a0e --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Core/Integrations/Warnings/IntegrationPrereleaseRefWarning.cs @@ -0,0 +1,11 @@ +using CreativeCoders.ShadeKit.Core.Warnings; + +namespace CreativeCoders.ShadeKit.Core.Integrations.Warnings; + +/// +/// Represents a warning that the engine is a prerelease, so the integrations are installed from a branch instead of +/// the release tag of the engine version. +/// +/// The version of the running engine, for example 0.8.0-beta.1. +/// The branch from which the integrations are installed, for example main. +public sealed record IntegrationPrereleaseRefWarning(string EngineVersion, string Ref) : KitWarning; diff --git a/src/CreativeCoders.ShadeKit.Core/Integrations/Warnings/IntegrationReleaseTagMissingWarning.cs b/src/CreativeCoders.ShadeKit.Core/Integrations/Warnings/IntegrationReleaseTagMissingWarning.cs new file mode 100644 index 0000000..d7ceb45 --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Core/Integrations/Warnings/IntegrationReleaseTagMissingWarning.cs @@ -0,0 +1,15 @@ +using CreativeCoders.ShadeKit.Core.Warnings; + +namespace CreativeCoders.ShadeKit.Core.Integrations.Warnings; + +/// +/// Represents a warning that the release tag of the engine version does not exist in the marketplace repository, so +/// the integrations are installed from a branch instead, which may not fit the engine. +/// +/// +/// A build of an untagged commit, for example of main, has a release version whose tag does not exist yet. +/// +/// The version of the running engine, for example 0.8.1. +/// The release tag that does not exist, for example v0.8.1. +/// The branch from which the integrations are installed, for example main. +public sealed record IntegrationReleaseTagMissingWarning(string EngineVersion, string Tag, string Ref) : KitWarning; diff --git a/src/CreativeCoders.ShadeKit.Core/Processes/ExternalTool.cs b/src/CreativeCoders.ShadeKit.Core/Processes/ExternalTool.cs index 15519ec..e2df418 100644 --- a/src/CreativeCoders.ShadeKit.Core/Processes/ExternalTool.cs +++ b/src/CreativeCoders.ShadeKit.Core/Processes/ExternalTool.cs @@ -25,4 +25,16 @@ internal sealed record ExternalTool( string DisplayName, IReadOnlyDictionary? EnvironmentVariables, Func, string, ExternalToolUnavailableException> CreateNotFoundException, - Func, string, Exception?, ExternalToolUnavailableException> CreateUnavailableException); + Func, string, Exception?, ExternalToolUnavailableException> CreateUnavailableException) +{ + /// + /// Gets the reason that is passed to when the executable of the tool is not + /// found. + /// + /// + /// The sentence that the executable was not found in any absolute directory of the PATH environment + /// variable, starting with . + /// + public string NotFoundReason => + $"{DisplayName} was not found in any absolute directory of the PATH environment variable."; +} diff --git a/src/CreativeCoders.ShadeKit.Core/Processes/ExternalToolRunner.cs b/src/CreativeCoders.ShadeKit.Core/Processes/ExternalToolRunner.cs index a17094a..39fef91 100644 --- a/src/CreativeCoders.ShadeKit.Core/Processes/ExternalToolRunner.cs +++ b/src/CreativeCoders.ShadeKit.Core/Processes/ExternalToolRunner.cs @@ -53,8 +53,7 @@ public static async Task RunAsync(ExternalTool tool, Func if (string.IsNullOrEmpty(executablePath)) { - throw tool.CreateNotFoundException(arguments, - $"{tool.DisplayName} was not found in any absolute directory of the PATH environment variable."); + throw tool.CreateNotFoundException(arguments, tool.NotFoundReason); } if (!Path.IsPathFullyQualified(executablePath)) diff --git a/src/CreativeCoders.ShadeKit.Core/Processes/UserWorkingDirectory.cs b/src/CreativeCoders.ShadeKit.Core/Processes/UserWorkingDirectory.cs new file mode 100644 index 0000000..2549741 --- /dev/null +++ b/src/CreativeCoders.ShadeKit.Core/Processes/UserWorkingDirectory.cs @@ -0,0 +1,36 @@ +namespace CreativeCoders.ShadeKit.Core.Processes; + +/// +/// Provides the directory outside any repository in which external tools run that act for the user, not for the +/// current repository, such as claude or git ls-remote. +/// +internal static class UserWorkingDirectory +{ + /// + /// Returns the home directory of the user, or the temporary directory if the home directory is not known or does + /// not exist. + /// + /// The absolute path of the home directory or of the temporary directory. + public static string Get() + { + return Get(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), Directory.Exists); + } + + /// + /// Returns the specified home directory if it exists, or the temporary directory otherwise. + /// + /// The home directory of the user, or an empty string if it is not known. + /// + /// The function that returns if the specified directory exists. + /// + /// + /// if it is not empty or whitespace and exists; otherwise, the temporary + /// directory. + /// + public static string Get(string? homeDirectory, Func directoryExists) + { + return !string.IsNullOrWhiteSpace(homeDirectory) && directoryExists(homeDirectory) + ? homeDirectory + : Path.GetTempPath(); + } +} diff --git a/src/CreativeCoders.ShadeKit.Core/ShadeKitCoreServiceCollectionExtensions.cs b/src/CreativeCoders.ShadeKit.Core/ShadeKitCoreServiceCollectionExtensions.cs index 74114fc..c1d367a 100644 --- a/src/CreativeCoders.ShadeKit.Core/ShadeKitCoreServiceCollectionExtensions.cs +++ b/src/CreativeCoders.ShadeKit.Core/ShadeKitCoreServiceCollectionExtensions.cs @@ -6,6 +6,8 @@ using CreativeCoders.ShadeKit.Core.Gates; using CreativeCoders.ShadeKit.Core.Git; using CreativeCoders.ShadeKit.Core.Init; +using CreativeCoders.ShadeKit.Core.Integrations; +using CreativeCoders.ShadeKit.Core.Integrations.Claude; using CreativeCoders.ShadeKit.Core.Store; using CreativeCoders.ShadeKit.Core.Templates; using CreativeCoders.ShadeKit.Core.Trackers; @@ -30,8 +32,10 @@ public static class ShadeKitCoreServiceCollectionExtensions /// /// /// All services are singletons. Existing registrations are kept, so a registration made before the call replaces - /// the default. The call also registers the and the named client - /// with a timeout of + /// the default. is an enumerable registration: the Claude Code integration is + /// added once, next to the integrations of other agents. The call also registers the + /// and the named client with a + /// timeout of /// and the User-Agent /// shade-kit/<engine version> from the . The client keeps the /// default primary handler, which follows redirects. The configuration of the named client does not follow the @@ -58,6 +62,7 @@ public static IServiceCollection AddShadeKitCore(this IServiceCollection service services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); + services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); @@ -89,6 +94,11 @@ public static IServiceCollection AddShadeKitCore(this IServiceCollection service services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddEnumerable(ServiceDescriptor.Singleton()); + services.TryAddSingleton(); return services; } diff --git a/tests/CreativeCoders.ShadeKit.Cli.Tests/Commands/CliEndToEndHarness.cs b/tests/CreativeCoders.ShadeKit.Cli.Tests/Commands/CliEndToEndHarness.cs index c2e5487..70356b3 100644 --- a/tests/CreativeCoders.ShadeKit.Cli.Tests/Commands/CliEndToEndHarness.cs +++ b/tests/CreativeCoders.ShadeKit.Cli.Tests/Commands/CliEndToEndHarness.cs @@ -2,6 +2,8 @@ using System.Text.RegularExpressions; using AwesomeAssertions; using CreativeCoders.ShadeKit.Core.Git; +using CreativeCoders.ShadeKit.Core.Integrations.Claude; +using CreativeCoders.ShadeKit.Core.Integrations.Exceptions; using CreativeCoders.ShadeKit.Core.Processes; using CreativeCoders.ShadeKit.Core.Trackers; using CreativeCoders.ShadeKit.Tests.Shared; @@ -17,9 +19,12 @@ namespace CreativeCoders.ShadeKit.Cli.Tests.Commands; /// /// /// git is answered by a fake (the current branch is , the -/// identity is and , every other call fails), and the tracker issue -/// reader is a fake that returns the issue , so no test starts git or gh. The -/// current directory is restored on disposal; a test class that uses the harness must be in the +/// identity is and , git ls-remote --tags lists the +/// if they are set, every other call fails), and the tracker issue +/// reader is a fake that returns the issue , so no test starts git or gh. Claude +/// Code is answered by a fake and a fake ; +/// by default claude is not on the PATH, so no test starts claude either. The current directory is +/// restored on disposal; a test class that uses the harness must be in the /// collection. /// internal sealed partial class CliEndToEndHarness : IDisposable @@ -50,6 +55,14 @@ public CliEndToEndHarness(string tempDirectoryPrefix) A.CallTo(() => TrackerIssueReader.ReadIssueAsync(A._, A._, A._)) .Returns(new TrackerIssue("Login with SSO", "Users sign in with the company account.", [])); + + A.CallTo(() => ClaudeExecutableLocator.FindClaudeExecutable()) + .Returns((string?)null); + + A.CallTo(() => ClaudeCommandRunner.RunAsync(A._, A>._, A._)) + .ReturnsLazily((string _, IReadOnlyList arguments, CancellationToken _) => + Task.FromException(new ClaudeNotFoundException(arguments, + "The Claude Code CLI claude was not found in any absolute directory of the PATH."))); } public TempKitDirectory TempDirectory { get; } @@ -58,19 +71,35 @@ public CliEndToEndHarness(string tempDirectoryPrefix) public ITrackerIssueReader TrackerIssueReader { get; } = A.Fake(); + /// + /// Gets the fake locator of claude; by default it finds none, so Claude Code is not detected. + /// + public IClaudeExecutableLocator ClaudeExecutableLocator { get; } = A.Fake(); + + /// + /// Gets the fake runner of claude; by default every call fails with a . + /// + public IClaudeCommandRunner ClaudeCommandRunner { get; } = A.Fake(); + /// /// Gets or sets the current branch that the fake git reports; for a detached HEAD. /// public string? Branch { get; set; } = "main"; + /// + /// Gets or sets the tags that git ls-remote --tags finds in every remote repository; + /// (the default) makes the call fail, as without network, so a release tag stays unchecked. + /// + public IReadOnlyCollection? RemoteTags { get; set; } + /// /// Gets or sets an action that sees the arguments of every git call before it is answered. /// public Action>? OnGitCall { get; set; } /// - /// Gets or sets an action that registers further services of a run, after the fake git runner and the fake - /// tracker issue reader. + /// Gets or sets an action that registers further services of a run, after the fake git runner, the fake tracker + /// issue reader, and the fake claude locator and runner. /// public Action? ConfigureServices { get; set; } @@ -125,7 +154,9 @@ public async Task RunAllOkAsync(params string[][] commands) var exitCode = await Program.RunAsync(args, output, error, x => { x.AddSingleton(GitCommandRunner) - .AddSingleton(TrackerIssueReader); + .AddSingleton(TrackerIssueReader) + .AddSingleton(ClaudeExecutableLocator) + .AddSingleton(ClaudeCommandRunner); ConfigureServices?.Invoke(x); }); @@ -209,9 +240,18 @@ private ExternalProcessResult AnswerGit(IReadOnlyList arguments) return arguments switch { + [.., "ls-remote", "--tags", _, var tagRef] when RemoteTags is { } remoteTags => + AnswerLsRemote(remoteTags, tagRef), ["config", "user.name"] => new ExternalProcessResult(0, UserName + "\n", string.Empty), ["config", "user.email"] => new ExternalProcessResult(0, UserEmail + "\n", string.Empty), _ => new ExternalProcessResult(128, string.Empty, $"unexpected git call: {string.Join(' ', arguments)}") }; } + + private static ExternalProcessResult AnswerLsRemote(IReadOnlyCollection remoteTags, string tagRef) + { + var isListed = remoteTags.Any(x => $"refs/tags/{x}" == tagRef); + + return new ExternalProcessResult(0, isListed ? $"4a1b2c3d4e5f\t{tagRef}\n" : string.Empty, string.Empty); + } } diff --git a/tests/CreativeCoders.ShadeKit.Cli.Tests/Commands/Integrations/FakeClaudeCode.cs b/tests/CreativeCoders.ShadeKit.Cli.Tests/Commands/Integrations/FakeClaudeCode.cs new file mode 100644 index 0000000..fde68da --- /dev/null +++ b/tests/CreativeCoders.ShadeKit.Cli.Tests/Commands/Integrations/FakeClaudeCode.cs @@ -0,0 +1,319 @@ +using System.Text.Json; +using System.Text.Json.Nodes; +using CreativeCoders.ShadeKit.Core.Processes; +using FakeItEasy; + +namespace CreativeCoders.ShadeKit.Cli.Tests.Commands.Integrations; + +/// +/// Simulates the plugin commands of the Claude Code CLI claude behind the fake claude runner and locator of a +/// , so the end-to-end tests run the real integration service without starting +/// claude. +/// +/// +/// The answers follow the output of Claude Code 2.1.323: removing a marketplace also uninstalls its plugins, a plugin +/// without a version is listed with the commit SHA as its version, and a plugin update sees new commits of the +/// marketplace source () only after the marketplace was added or refreshed with +/// claude plugin marketplace update. The simulator knows one other marketplace +/// and one other plugin, which the integration must leave alone. +/// +internal sealed class FakeClaudeCode +{ + public const string ExecutablePath = "/usr/local/bin/claude"; + + public const string MarketplaceName = "creativecoders-shade-kit"; + + public const string PluginId = "shade-kit@" + MarketplaceName; + + public const string Repo = "CreativeCodersTeam/shade-kit"; + + private string? _installedRef; + + private int _marketplaceRevision; + + private int _installedRevision; + + /// + /// Gets or sets the revision of the marketplace source, which a new commit on a branch raises. + /// + public int RemoteRevision { get; set; } + + /// + /// Gets or sets the marketplace , or if claude does not know + /// it. + /// + public FakeClaudeMarketplace? Marketplace { get; set; } + + /// + /// Gets or sets a value that indicates whether the plugin is installed with the scope + /// user. + /// + public bool IsPluginInstalled { get; set; } + + /// + /// Gets or sets a value that indicates whether the installed plugin is enabled. + /// + public bool IsPluginEnabled { get; set; } = true; + + /// + /// Gets or sets a function that returns the failed result of a call, or to answer it. + /// + public Func, ExternalProcessResult?>? Fail { get; set; } + + /// + /// Gets the arguments of every call, in the order of the calls. + /// + public List Calls { get; } = []; + + /// + /// Gets the working directory of every call. + /// + public List WorkingDirectories { get; } = []; + + /// + /// Makes the fake locator of the harness find claude and the fake runner answer with this simulator. + /// + public FakeClaudeCode AttachTo(CliEndToEndHarness harness) + { + A.CallTo(() => harness.ClaudeExecutableLocator.FindClaudeExecutable()) + .Returns(ExecutablePath); + + A.CallTo(() => harness.ClaudeCommandRunner.RunAsync(A._, A>._, + A._)) + .ReturnsLazily((string workingDirectory, IReadOnlyList arguments, CancellationToken _) => + Task.FromResult(Answer(workingDirectory, arguments))); + + return this; + } + + /// + /// Sets the state after an install of the plugin from the SHADE kit repository with the specified ref. + /// + public FakeClaudeCode WithInstalledPlugin(string? @ref, bool enabled = true) + { + Marketplace = FakeClaudeMarketplace.ForGitHub(Repo, @ref); + IsPluginInstalled = true; + IsPluginEnabled = enabled; + _installedRef = @ref; + _marketplaceRevision = RemoteRevision; + _installedRevision = RemoteRevision; + + return this; + } + + private ExternalProcessResult Answer(string workingDirectory, IReadOnlyList arguments) + { + Calls.Add(string.Join(' ', arguments)); + WorkingDirectories.Add(workingDirectory); + + if (Fail?.Invoke(arguments) is { } failure) + { + return failure; + } + + return arguments switch + { + ["plugin", "marketplace", "list", "--json"] => Ok(ListMarketplaces()), + ["plugin", "marketplace", "add", var source, "--scope", "user", "--json"] => AddMarketplace(source), + ["plugin", "marketplace", "remove", MarketplaceName, "--json"] => RemoveMarketplace(), + ["plugin", "marketplace", "update", MarketplaceName, "--json"] => UpdateMarketplace(), + ["plugin", "list", "--json"] => Ok(ListPlugins()), + ["plugin", "install", PluginId, "--scope", "user", "--json"] => InstallPlugin(), + ["plugin", "update", PluginId, "--scope", "user", "--json"] => UpdatePlugin(), + _ => new ExternalProcessResult(1, string.Empty, $"unexpected claude call: {string.Join(' ', arguments)}") + }; + } + + private string ListMarketplaces() + { + var marketplaces = new JsonArray(new JsonObject + { + ["name"] = "creativecoders-ai-store", + ["source"] = "github", + ["repo"] = "CreativeCodersTeam/ai-store", + ["ref"] = "main", + ["installLocation"] = "/home/me/.claude/plugins/marketplaces/creativecoders-ai-store" + }); + + if (Marketplace is { } marketplace) + { + var entry = new JsonObject { ["name"] = MarketplaceName, ["source"] = marketplace.SourceKind }; + + if (marketplace.Repo is not null) + { + entry["repo"] = marketplace.Repo; + } + + if (marketplace.Ref is not null) + { + entry["ref"] = marketplace.Ref; + } + + if (marketplace.Path is not null) + { + entry["path"] = marketplace.Path; + } + + entry["installLocation"] = marketplace.Path ?? $"/home/me/.claude/plugins/marketplaces/{MarketplaceName}"; + marketplaces.Add(entry); + } + + return marketplaces.ToJsonString(); + } + + private string ListPlugins() + { + var plugins = new JsonArray(new JsonObject + { + ["id"] = "cc-ai-dotnet@creativecoders-ai-store", + ["version"] = "4972bfa14908", + ["scope"] = "user", + ["enabled"] = true + }); + + if (IsPluginInstalled) + { + plugins.Add(new JsonObject + { + ["id"] = PluginId, + ["version"] = "1a2b3c4d5e6f", + ["scope"] = "user", + ["enabled"] = IsPluginEnabled, + ["installPath"] = $"/home/me/.claude/plugins/cache/{MarketplaceName}/shade-kit/1a2b3c4d5e6f", + ["projectEnabled"] = false + }); + } + + return plugins.ToJsonString(); + } + + private ExternalProcessResult AddMarketplace(string source) + { + Marketplace = FakeClaudeMarketplace.Parse(source); + _marketplaceRevision = RemoteRevision; + + return Ok(Line(new JsonObject + { + ["command"] = "marketplace-add", + ["outcome"] = "ok", + ["marketplace"] = MarketplaceName, + ["message"] = $"Successfully added marketplace: {MarketplaceName}" + })); + } + + private ExternalProcessResult RemoveMarketplace() + { + Marketplace = null; + IsPluginInstalled = false; + _installedRef = null; + + return Ok(Line(new JsonObject + { + ["command"] = "marketplace-remove", + ["outcome"] = "ok", + ["marketplace"] = MarketplaceName, + ["message"] = $"Successfully removed marketplace: {MarketplaceName}. Also uninstalled 1 plugin." + })); + } + + private ExternalProcessResult UpdateMarketplace() + { + if (Marketplace is null) + { + return new ExternalProcessResult(1, Line(new JsonObject + { + ["command"] = "marketplace-update", + ["marketplace"] = MarketplaceName, + ["outcome"] = "failed", + ["message"] = $"Marketplace '{MarketplaceName}' not found.", + ["failureCode"] = "not_configured" + }), "✘ Failed to update marketplace(s)\n"); + } + + _marketplaceRevision = RemoteRevision; + + return Ok(Line(new JsonObject + { + ["command"] = "marketplace-update", + ["outcome"] = "ok", + ["marketplace"] = MarketplaceName, + ["message"] = $"Successfully updated marketplace: {MarketplaceName}" + })); + } + + private ExternalProcessResult InstallPlugin() + { + IsPluginInstalled = true; + IsPluginEnabled = true; + _installedRef = Marketplace?.Ref; + _installedRevision = _marketplaceRevision; + + return Ok(Line(new JsonObject + { + ["command"] = "install", + ["outcome"] = "ok", + ["plugin"] = PluginId, + ["pluginId"] = PluginId, + ["scope"] = "user", + ["message"] = $"Successfully installed plugin: {PluginId} (scope: user)" + })); + } + + private ExternalProcessResult UpdatePlugin() + { + var isUpToDate = _installedRef == Marketplace?.Ref && _installedRevision == _marketplaceRevision; + _installedRef = Marketplace?.Ref; + _installedRevision = _marketplaceRevision; + + var result = new JsonObject + { + ["command"] = "update", + ["outcome"] = "ok", + ["plugin"] = PluginId, + ["pluginId"] = PluginId, + ["scope"] = "user", + ["updateOutcome"] = isUpToDate ? "up_to_date" : "updated" + }; + + if (!isUpToDate) + { + result["oldVersion"] = "0a1b2c3d4e5f"; + result["newVersion"] = "1a2b3c4d5e6f"; + } + + return Ok(Line(result)); + } + + private static string Line(JsonObject result) + { + return result.ToJsonString(new JsonSerializerOptions { WriteIndented = false }) + "\n"; + } + + private static ExternalProcessResult Ok(string output) + { + return new ExternalProcessResult(0, output, string.Empty); + } +} + +/// +/// Represents the marketplace as the simulator stores it. +/// +internal sealed record FakeClaudeMarketplace(string SourceKind, string? Repo, string? Ref, string? Path) +{ + public static FakeClaudeMarketplace ForGitHub(string repo, string? @ref) + { + return new FakeClaudeMarketplace("github", repo, @ref, null); + } + + public static FakeClaudeMarketplace Parse(string source) + { + if (System.IO.Path.IsPathFullyQualified(source)) + { + return new FakeClaudeMarketplace("directory", null, null, source); + } + + var parts = source.Split('#', 2); + + return ForGitHub(parts[0], parts.Length == 2 ? parts[1] : null); + } +} diff --git a/tests/CreativeCoders.ShadeKit.Cli.Tests/Commands/Integrations/Install/AgentOptionConverterTests.cs b/tests/CreativeCoders.ShadeKit.Cli.Tests/Commands/Integrations/Install/AgentOptionConverterTests.cs new file mode 100644 index 0000000..8f5612f --- /dev/null +++ b/tests/CreativeCoders.ShadeKit.Cli.Tests/Commands/Integrations/Install/AgentOptionConverterTests.cs @@ -0,0 +1,82 @@ +using AwesomeAssertions; +using CreativeCoders.ShadeKit.Cli.Commands.Integrations.Install; +using CreativeCoders.ShadeKit.Core; +using CreativeCoders.ShadeKit.Core.Integrations; +using CreativeCoders.SysConsole.Cli.Parsing; +using Microsoft.Extensions.DependencyInjection; + +namespace CreativeCoders.ShadeKit.Cli.Tests.Commands.Integrations.Install; + +public class AgentOptionConverterTests +{ + private static readonly OptionParameterAttribute AgentAttribute = new OptionParameterAttribute("agent"); + + [Theory] + [InlineData("claude")] + [InlineData("Claude")] + [InlineData("CLAUDE")] + public void Convert_SupportedIdInAnyCase_ReturnsIdOfSupportedAgent(string value) + { + // Arrange + var converter = new AgentOptionConverter(); + + // Act + var result = converter.Convert(value, typeof(string), AgentAttribute); + + // Assert + result + .Should().Be("claude"); + } + + [Theory] + [InlineData("copilot")] + [InlineData("")] + [InlineData(" claude")] + public void Convert_UnknownId_ThrowsInvalidAgentOptionExceptionWithValueAndSupportedAgents(string value) + { + // Arrange + var converter = new AgentOptionConverter(); + + // Act + var act = () => converter.Convert(value, typeof(string), AgentAttribute); + + // Assert + var exception = act.Should().Throw().Which; + + exception.Value + .Should().Be(value); + + exception.SupportedAgentIds + .Should().Equal("claude"); + } + + [Fact] + public void Convert_NullValue_ThrowsInvalidAgentOptionExceptionWithoutValue() + { + // Arrange + var converter = new AgentOptionConverter(); + + // Act + var act = () => converter.Convert(null, typeof(string), AgentAttribute); + + // Assert + act.Should().Throw() + .Which.Value.Should().BeNull(); + } + + [Fact] + public void SupportedAgentIds_ComparedWithRegisteredIntegrationService_AreEqual() + { + // Arrange + using var serviceProvider = new ServiceCollection() + .AddShadeKitCore() + .BuildServiceProvider(); + + // Act + var agentIds = serviceProvider.GetRequiredService().AgentIds; + + // Assert + AgentOptionConverter.SupportedAgentIds + .Should().Equal(agentIds); + } +} diff --git a/tests/CreativeCoders.ShadeKit.Cli.Tests/Commands/Integrations/Install/IntegrationsInstallCommandOptionsTests.cs b/tests/CreativeCoders.ShadeKit.Cli.Tests/Commands/Integrations/Install/IntegrationsInstallCommandOptionsTests.cs new file mode 100644 index 0000000..7de69e0 --- /dev/null +++ b/tests/CreativeCoders.ShadeKit.Cli.Tests/Commands/Integrations/Install/IntegrationsInstallCommandOptionsTests.cs @@ -0,0 +1,54 @@ +using AwesomeAssertions; +using CreativeCoders.ShadeKit.Cli.Commands.Integrations.Install; +using CreativeCoders.SysConsole.Cli.Parsing; + +namespace CreativeCoders.ShadeKit.Cli.Tests.Commands.Integrations.Install; + +public class IntegrationsInstallCommandOptionsTests +{ + [Theory] + [InlineData("claude", "claude")] + [InlineData("CLAUDE", "claude")] + public void Parse_AgentWithSupportedId_SetsAgentToSupportedId(string value, string expectedAgent) + { + // Act + var options = (IntegrationsInstallCommandOptions)new OptionParser(typeof(IntegrationsInstallCommandOptions)) + .Parse(["--agent", value, "--json"]); + + // Assert + options.Agent + .Should().Be(expectedAgent); + + options.Json + .Should().BeTrue(); + } + + [Fact] + public void Parse_NoAgent_LeavesAgentNull() + { + // Act + var options = (IntegrationsInstallCommandOptions)new OptionParser(typeof(IntegrationsInstallCommandOptions)) + .Parse(["--json"]); + + // Assert + options.Agent + .Should().BeNull(); + } + + [Theory] + [InlineData("--agent", "copilot")] + [InlineData("--agent")] + [InlineData("--agent", "--json")] + public void Parse_AgentWithUnknownIdOrWithoutValue_ThrowsInvalidAgentOptionException(params string[] args) + { + // Arrange + var parser = new OptionParser(typeof(IntegrationsInstallCommandOptions)); + + // Act + var act = () => parser.Parse(args); + + // Assert + act + .Should().Throw(); + } +} diff --git a/tests/CreativeCoders.ShadeKit.Cli.Tests/Commands/Integrations/Install/IntegrationsInstallCommandTests.cs b/tests/CreativeCoders.ShadeKit.Cli.Tests/Commands/Integrations/Install/IntegrationsInstallCommandTests.cs new file mode 100644 index 0000000..a0eb065 --- /dev/null +++ b/tests/CreativeCoders.ShadeKit.Cli.Tests/Commands/Integrations/Install/IntegrationsInstallCommandTests.cs @@ -0,0 +1,393 @@ +using System.Reflection; +using System.Text.Json; +using AwesomeAssertions; +using CreativeCoders.Cli.Core; +using CreativeCoders.Cli.Hosting.Exceptions; +using CreativeCoders.ShadeKit.Cli.Commands; +using CreativeCoders.ShadeKit.Cli.Commands.Integrations.Install; +using CreativeCoders.ShadeKit.Cli.Tests.Output; +using CreativeCoders.ShadeKit.Core.Integrations; +using CreativeCoders.ShadeKit.Core.Integrations.Exceptions; +using CreativeCoders.ShadeKit.Core.Integrations.Warnings; +using FakeItEasy; +using Spectre.Console.Testing; +using static CreativeCoders.ShadeKit.Cli.Tests.Commands.Integrations.IntegrationsCommandTestData; + +namespace CreativeCoders.ShadeKit.Cli.Tests.Commands.Integrations.Install; + +public sealed class IntegrationsInstallCommandTests : IDisposable +{ + private static readonly string[] ClaudeAgentIds = ["claude"]; + + private readonly CancellationTokenSource _cancellationSource = new CancellationTokenSource(); + + private readonly TestConsole _console = new TestConsole().Width(1000); + + private readonly IIntegrationService _integrationService = A.Fake(); + + private readonly StringWriter _jsonOutput = new StringWriter(); + + public IntegrationsInstallCommandTests() + { + A.CallTo(() => _integrationService.InstallAsync(A?>._, A._)) + .Returns(CreateRun(CreateResult(IntegrationOutcome.Installed))); + } + + [Fact] + [Trait("Requirement", "FP07-AC2")] + public async Task ExecuteAsync_JsonMode_WritesEnvelopeWithTargetedSourceAndResultOfEachAgent() + { + // Arrange + var command = CreateCommand(); + + // Act + var result = await command.ExecuteAsync(new IntegrationsInstallCommandOptions { Json = true }); + + // Assert + result.ExitCode + .Should().Be(0); + + _jsonOutput.ToString() + .Should().Be( + """ + { + "ok": true, + "data": { + "ref": "v0.8.0", + "source": "CreativeCodersTeam/shade-kit#v0.8.0", + "integrations": [ + { + "agent": "claude", + "pluginId": "shade-kit@creativecoders-shade-kit", + "outcome": "installed", + "previousKitVersion": null, + "kitVersion": "0.8.0", + "ref": "v0.8.0", + "enabled": true + } + ] + }, + "warnings": [], + "error": null + } + """.ReplaceLineEndings("\n") + "\n"); + + _console.Output + .Should().BeEmpty(); + } + + [Fact] + public async Task ExecuteAsync_JsonModeWithPrereleaseWarning_WritesWarningIntoEnvelope() + { + // Arrange + A.CallTo(() => _integrationService.InstallAsync(A?>._, A._)) + .Returns(CreateRun([CreateResult(IntegrationOutcome.Installed)], + [new IntegrationPrereleaseRefWarning("0.9.0-beta.1", "main")], + MarketplaceSource.ForGitHub("CreativeCodersTeam/shade-kit", "main"))); + + var command = CreateCommand(); + + // Act + await command.ExecuteAsync(new IntegrationsInstallCommandOptions { Json = true }); + + // Assert + using var document = JsonDocument.Parse(_jsonOutput.ToString()); + + document.RootElement.GetProperty("warnings").EnumerateArray().Select(x => x.GetProperty("code").GetString()) + .Should().Equal(ShadeKitCliWarningCodes.IntegrationPrereleaseRef); + + document.RootElement.GetProperty("data").GetProperty("ref").GetString() + .Should().Be("main"); + } + + [Fact] + public async Task ExecuteAsync_PlainMode_WritesOneLinePerAgentAndRestartHint() + { + // Arrange + var command = CreateCommand(); + + // Act + await command.ExecuteAsync(new IntegrationsInstallCommandOptions()); + + // Assert + _console.Lines + .Should().Equal( + "claude: installed shade-kit@creativecoders-shade-kit 0.8.0 (v0.8.0)", + "Restart Claude Code to load the skills."); + + _jsonOutput.ToString() + .Should().BeEmpty(); + } + + [Fact] + public async Task ExecuteAsync_PlainModeWithWarning_WritesWarningBeforeResultLines() + { + // Arrange + A.CallTo(() => _integrationService.InstallAsync(A?>._, A._)) + .Returns(CreateRun([CreateResult(IntegrationOutcome.Current)], + [new IntegrationPrereleaseRefWarning("0.9.0-beta.1", "main")])); + + var command = CreateCommand(); + + // Act + await command.ExecuteAsync(new IntegrationsInstallCommandOptions()); + + // Assert + _console.Lines + .Should().HaveCount(2); + + _console.Lines[0] + .Should().StartWith("Warning: The engine 0.9.0-beta.1 is a prerelease"); + + _console.Lines[1] + .Should().Be("claude: already current shade-kit@creativecoders-shade-kit 0.8.0 (v0.8.0)"); + } + + [Fact] + public async Task ExecuteAsync_WithAgent_InstallsForThatAgentWithCancellationTokenOfRun() + { + // Arrange + var command = CreateCommand(); + + // Act + await command.ExecuteAsync(new IntegrationsInstallCommandOptions { Agent = "claude" }); + + // Assert + A.CallTo(() => _integrationService.InstallAsync( + A?>.That.Matches(x => x != null && x.SequenceEqual(ClaudeAgentIds)), + _cancellationSource.Token)) + .MustHaveHappenedOnceExactly(); + } + + [Fact] + public async Task ExecuteAsync_WithoutAgent_InstallsForEveryDetectedAgent() + { + // Arrange + var command = CreateCommand(); + + // Act + await command.ExecuteAsync(new IntegrationsInstallCommandOptions()); + + // Assert + A.CallTo(() => _integrationService.InstallAsync(null, A._)) + .MustHaveHappenedOnceExactly(); + } + + [Fact] + public async Task ExecuteAsync_JsonModeNoAgentFound_WritesFailureEnvelopeAndAbortsWith51() + { + // Arrange + A.CallTo(() => _integrationService.InstallAsync(A?>._, A._)) + .ThrowsAsync(new NoAgentFoundException(["claude"])); + + var command = CreateCommand(); + + // Act + var act = () => command.ExecuteAsync(new IntegrationsInstallCommandOptions { Json = true }); + + // Assert + var exception = (await act.Should().ThrowAsync()).Which; + + exception.ExitCode + .Should().Be(ShadeKitCliExitCodes.AgentNotFound); + + exception.PrintMessage + .Should().BeFalse(); + + using var document = JsonDocument.Parse(_jsonOutput.ToString()); + + document.RootElement.GetProperty("ok").GetBoolean() + .Should().BeFalse(); + + document.RootElement.GetProperty("error").GetProperty("code").GetString() + .Should().Be(ShadeKitCliErrorCodes.AgentNotFound); + } + + [Fact] + public async Task ExecuteAsync_PlainModeIntegrationConflict_AbortsWith53AndMessageWithoutOutput() + { + // Arrange + A.CallTo(() => _integrationService.InstallAsync(A?>._, A._)) + .ThrowsAsync(new IntegrationConflictException("claude", "creativecoders-shade-kit", "someone/fork", + "CreativeCodersTeam/shade-kit#v0.8.0", "claude plugin marketplace remove creativecoders-shade-kit")); + + var command = CreateCommand(); + + // Act + var act = () => command.ExecuteAsync(new IntegrationsInstallCommandOptions()); + + // Assert + var exception = (await act.Should().ThrowAsync()).Which; + + exception.ExitCode + .Should().Be(ShadeKitCliExitCodes.IntegrationConflict); + + exception.PrintMessage + .Should().BeTrue(); + + _console.Output + .Should().BeEmpty(); + } + + [Fact] + public async Task ExecuteAsync_JsonModeCanceledDuringMarketplaceSwitch_WritesCanceledEnvelopeWithRepairHint() + { + // Arrange + await _cancellationSource.CancelAsync(); + A.CallTo(() => _integrationService.InstallAsync(A?>._, A._)) + .ThrowsAsync(new IntegrationSwitchCanceledException("claude", + new OperationCanceledException(_cancellationSource.Token))); + + var command = CreateCommand(); + + // Act + var act = () => command.ExecuteAsync(new IntegrationsInstallCommandOptions { Json = true }); + + // Assert + var exception = (await act.Should().ThrowAsync()).Which; + + exception.ExitCode + .Should().Be(ShadeKitCliExitCodes.Canceled); + + using var document = JsonDocument.Parse(_jsonOutput.ToString()); + + document.RootElement.GetProperty("error").GetProperty("code").GetString() + .Should().Be(ShadeKitCliErrorCodes.Canceled); + + document.RootElement.GetProperty("error").GetProperty("message").GetString() + .Should().StartWith("The command was canceled") + .And.EndWith("'shade-kit integrations install' repairs it."); + } + + [Fact] + public async Task ExecuteAsync_PlainModeCanceledDuringMarketplaceSwitch_AbortsWith130AndRepairHint() + { + // Arrange + A.CallTo(() => _integrationService.InstallAsync(A?>._, A._)) + .ThrowsAsync(new IntegrationSwitchCanceledException("claude", new OperationCanceledException())); + + var command = CreateCommand(); + + // Act + var act = () => command.ExecuteAsync(new IntegrationsInstallCommandOptions()); + + // Assert + var exception = (await act.Should().ThrowAsync()).Which; + + exception.ExitCode + .Should().Be(ShadeKitCliExitCodes.Canceled); + + exception.PrintMessage + .Should().BeTrue(); + + exception.Message + .Should().Contain("'shade-kit integrations install' repairs it."); + } + + [Fact] + public async Task ExecuteAsync_JsonModeSecondAgentFailed_WritesFailureEnvelopeNamingCompletedAgents() + { + // Arrange + A.CallTo(() => _integrationService.InstallAsync(A?>._, A._)) + .ThrowsAsync(new IntegrationRunFailedException("copilot", ReleaseSource, + [CreateResult(IntegrationOutcome.Installed)], + new ClaudeCommandFailedException(["plugin", "install"], 1, "claude failed."))); + + var command = CreateCommand(); + + // Act + var act = () => command.ExecuteAsync(new IntegrationsInstallCommandOptions { Json = true }); + + // Assert + var exception = (await act.Should().ThrowAsync()).Which; + + exception.ExitCode + .Should().Be(ShadeKitCliExitCodes.AgentCommandFailed); + + using var document = JsonDocument.Parse(_jsonOutput.ToString()); + + document.RootElement.GetProperty("data").ValueKind + .Should().Be(JsonValueKind.Null, "the failure envelope keeps its contract"); + + var error = document.RootElement.GetProperty("error"); + + error.EnumerateObject().Select(x => x.Name) + .Should().Equal("code", "message"); + + error.GetProperty("code").GetString() + .Should().Be(ShadeKitCliErrorCodes.AgentCommandFailed); + + error.GetProperty("message").GetString() + .Should().EndWith("Before the agent 'copilot' failed, these integrations were done: claude: installed " + + "shade-kit@creativecoders-shade-kit 0.8.0 (v0.8.0)."); + } + + [Fact] + public async Task ExecuteAsync_NullOptions_ThrowsArgumentNullException() + { + // Arrange + var command = CreateCommand(); + + // Act + var act = () => command.ExecuteAsync(null!); + + // Assert + (await act.Should().ThrowAsync()) + .WithParameterName("options"); + } + + [Fact] + public void Ctor_NullContext_ThrowsArgumentNullException() + { + // Act + var act = () => new IntegrationsInstallCommand(null!, _integrationService); + + // Assert + act.Should().Throw() + .WithParameterName("context"); + } + + [Fact] + public void Ctor_NullIntegrationService_ThrowsArgumentNullException() + { + // Act + var act = () => new IntegrationsInstallCommand(TestShadeKitCommandContext.Create(_console), null!); + + // Assert + act.Should().Throw() + .WithParameterName("integrationService"); + } + + [Fact] + public void IntegrationsInstallCommand_CliCommandAttribute_IsRegisteredInIntegrationsGroup() + { + // Act + var attribute = typeof(IntegrationsInstallCommand).GetCustomAttribute(); + + // Assert + attribute!.Commands + .Should().Equal("integrations", "install"); + } + + [Fact] + public void IntegrationsInstallCommandOptions_Type_DerivesFromJsonCommandOptions() + { + // Assert + typeof(IntegrationsInstallCommandOptions) + .Should().BeDerivedFrom(); + } + + public void Dispose() + { + _cancellationSource.Dispose(); + _jsonOutput.Dispose(); + } + + private IntegrationsInstallCommand CreateCommand() + { + return new IntegrationsInstallCommand( + TestShadeKitCommandContext.Create(_console, jsonOutput: _jsonOutput, + cancellation: new TestCliCancellation(_cancellationSource.Token)), + _integrationService); + } +} diff --git a/tests/CreativeCoders.ShadeKit.Cli.Tests/Commands/Integrations/IntegrationRunDataTests.cs b/tests/CreativeCoders.ShadeKit.Cli.Tests/Commands/Integrations/IntegrationRunDataTests.cs new file mode 100644 index 0000000..8829f2e --- /dev/null +++ b/tests/CreativeCoders.ShadeKit.Cli.Tests/Commands/Integrations/IntegrationRunDataTests.cs @@ -0,0 +1,56 @@ +using AwesomeAssertions; +using CreativeCoders.ShadeKit.Cli.Commands.Integrations; +using CreativeCoders.ShadeKit.Core.Integrations; +using static CreativeCoders.ShadeKit.Cli.Tests.Commands.Integrations.IntegrationsCommandTestData; + +namespace CreativeCoders.ShadeKit.Cli.Tests.Commands.Integrations; + +public class IntegrationRunDataTests +{ + [Fact] + public void From_NothingInstalledWithoutSource_ReturnsNullRefAndSourceAndEmptyIntegrations() + { + // Act + var data = IntegrationRunData.From(CreateNothingInstalledRun()); + + // Assert + data + .Should().BeEquivalentTo(new IntegrationRunData(null, null, [])); + } + + [Fact] + public void From_SourceWithoutResults_ReturnsRefAndSourceAndEmptyIntegrations() + { + // Act + var data = IntegrationRunData.From(CreateRun()); + + // Assert + data + .Should().BeEquivalentTo(new IntegrationRunData("v0.8.0", "CreativeCodersTeam/shade-kit#v0.8.0", [])); + } + + [Fact] + public void From_GitHubSourceWithoutRef_ReturnsNullRefAndRepositoryAsSource() + { + // Act + var data = IntegrationRunData.From(CreateRun([], [], MarketplaceSource.ForGitHub("owner/fork"))); + + // Assert + data.Ref + .Should().BeNull(); + + data.Source + .Should().Be("owner/fork"); + } + + [Fact] + public void From_NullResult_ThrowsArgumentNullException() + { + // Act + var act = () => IntegrationRunData.From(null!); + + // Assert + act.Should().Throw() + .WithParameterName("result"); + } +} diff --git a/tests/CreativeCoders.ShadeKit.Cli.Tests/Commands/Integrations/IntegrationsCommandTestData.cs b/tests/CreativeCoders.ShadeKit.Cli.Tests/Commands/Integrations/IntegrationsCommandTestData.cs new file mode 100644 index 0000000..47e02e2 --- /dev/null +++ b/tests/CreativeCoders.ShadeKit.Cli.Tests/Commands/Integrations/IntegrationsCommandTestData.cs @@ -0,0 +1,40 @@ +using CreativeCoders.ShadeKit.Core.Integrations; +using CreativeCoders.ShadeKit.Core.Warnings; + +namespace CreativeCoders.ShadeKit.Cli.Tests.Commands.Integrations; + +/// +/// Creates the results of the integration service for the tests of the shade-kit integrations commands. +/// +internal static class IntegrationsCommandTestData +{ + public const string PluginId = "shade-kit@creativecoders-shade-kit"; + + public static readonly MarketplaceSource ReleaseSource = + MarketplaceSource.ForGitHub("CreativeCodersTeam/shade-kit", "v0.8.0"); + + public static IntegrationResult CreateResult(IntegrationOutcome outcome, string? previousKitVersion = null, + bool enabled = true) + { + return new IntegrationResult("claude", PluginId, outcome, previousKitVersion, "0.8.0", "v0.8.0", enabled); + } + + /// + /// Creates the result of an update that found no installed integration, so it resolved no source. + /// + public static IntegrationRunResult CreateNothingInstalledRun() + { + return new IntegrationRunResult(null, [], []); + } + + public static IntegrationRunResult CreateRun(params IntegrationResult[] results) + { + return CreateRun(results, []); + } + + public static IntegrationRunResult CreateRun(IReadOnlyList results, + IReadOnlyList warnings, MarketplaceSource? source = null) + { + return new IntegrationRunResult(source ?? ReleaseSource, results, warnings); + } +} diff --git a/tests/CreativeCoders.ShadeKit.Cli.Tests/Commands/Integrations/IntegrationsCommandsEndToEndTests.cs b/tests/CreativeCoders.ShadeKit.Cli.Tests/Commands/Integrations/IntegrationsCommandsEndToEndTests.cs new file mode 100644 index 0000000..1d02422 --- /dev/null +++ b/tests/CreativeCoders.ShadeKit.Cli.Tests/Commands/Integrations/IntegrationsCommandsEndToEndTests.cs @@ -0,0 +1,1009 @@ +using System.Text.Json; +using AwesomeAssertions; +using CreativeCoders.ShadeKit.Cli.Tests.Commands.Phase; +using CreativeCoders.ShadeKit.Core.Engine; +using CreativeCoders.ShadeKit.Core.Integrations; +using CreativeCoders.ShadeKit.Core.Processes; +using FakeItEasy; +using Microsoft.Extensions.DependencyInjection; +using static CreativeCoders.ShadeKit.Cli.Tests.Commands.CliEndToEndHarness; + +namespace CreativeCoders.ShadeKit.Cli.Tests.Commands.Integrations; + +/// +/// Runs shade-kit integrations install, shade-kit integrations update, and shade-kit version +/// through the with the real integration service; claude is answered by the +/// simulator, so no test starts claude. +/// +[Collection(CurrentDirectoryCollectionDefinition.Name)] +public sealed class IntegrationsCommandsEndToEndTests : IDisposable +{ + private readonly CliEndToEndHarness _harness = new CliEndToEndHarness("shade-kit-integrations-tests-"); + + private readonly FakeClaudeCode _claude = new FakeClaudeCode(); + + private string _engineVersion = "0.8.0"; + + public IntegrationsCommandsEndToEndTests() + { + var engineVersionProvider = A.Fake(); + A.CallTo(() => engineVersionProvider.Version).ReturnsLazily(() => _engineVersion); + + _harness.ConfigureServices = x => x.AddSingleton(engineVersionProvider); + } + + [Fact] + [Trait("Requirement", "FP07-AC1")] + [Trait("Requirement", "FP07-AC2")] + public async Task IntegrationsInstall_ClaudeWithoutIntegration_InstallsPluginFromReleaseTagOfEngine() + { + // Arrange + _claude.AttachTo(_harness); + + // Act + var run = await _harness.RunJsonAsync("integrations", "install", "--agent", "claude", "--json"); + + // Assert + run.ExitCode + .Should().Be(0); + + run.Root.GetProperty("ok").GetBoolean() + .Should().BeTrue(); + + run.Root.GetProperty("warnings").GetArrayLength() + .Should().Be(0); + + run.Root.GetProperty("data").ShouldBeJson( + """ + { + "ref": "v0.8.0", "source": "CreativeCodersTeam/shade-kit#v0.8.0", + "integrations": [ + { "agent": "claude", "pluginId": "shade-kit@creativecoders-shade-kit", "outcome": "installed", + "previousKitVersion": null, "kitVersion": "0.8.0", "ref": "v0.8.0", "enabled": true } + ] + } + """); + + _claude.Calls + .Should().Contain([ + "plugin marketplace add CreativeCodersTeam/shade-kit#v0.8.0 --scope user --json", + "plugin install shade-kit@creativecoders-shade-kit --scope user --json" + ]); + + _claude.Marketplace + .Should().Be(FakeClaudeMarketplace.ForGitHub(FakeClaudeCode.Repo, "v0.8.0")); + } + + [Fact] + public async Task IntegrationsInstall_PlainModeWithoutAgent_InstallsForDetectedClaudeAndAsksForRestart() + { + // Arrange + _claude.AttachTo(_harness); + + // Act + var (exitCode, output, error) = await _harness.RunAsync("integrations", "install"); + + // Assert + exitCode + .Should().Be(0); + + GetLines(output.TrimEnd()) + .Should().Equal( + "claude: installed shade-kit@creativecoders-shade-kit 0.8.0 (v0.8.0)", + "Restart Claude Code to load the skills."); + + error + .Should().BeEmpty(); + } + + [Theory] + [InlineData("CLAUDE")] + [InlineData("Claude")] + public async Task IntegrationsInstall_AgentInOtherCase_InstallsForClaude(string agent) + { + // Arrange + _claude.AttachTo(_harness); + + // Act + var run = await _harness.RunJsonAsync("integrations", "install", "--agent", agent, "--json"); + + // Assert + run.ExitCode + .Should().Be(0); + + run.Root.GetProperty("data").GetProperty("integrations")[0].GetProperty("agent").GetString() + .Should().Be("claude"); + } + + [Theory] + [InlineData("copilot")] + [InlineData("")] + public async Task IntegrationsInstall_UnknownAgent_WritesInvalidArgumentsEnvelopeAndExits2(string agent) + { + // Arrange + _claude.AttachTo(_harness); + + // Act + var run = await _harness.RunJsonAsync("integrations", "install", "--agent", agent, "--json"); + + // Assert + AssertError(run, ShadeKitCliExitCodes.InvalidArguments, ShadeKitCliErrorCodes.InvalidArguments); + + run.Root.GetProperty("error").GetProperty("message").GetString() + .Should().Be($"Invalid arguments: '{agent}' is not a supported agent for --agent (supported: claude). " + + "Run 'shade-kit integrations install --help' for usage."); + + _claude.Calls + .Should().BeEmpty(); + } + + [Theory] + [InlineData("integrations", "install", "--agent", "--json")] + [InlineData("integrations", "install", "--json", "--agent")] + public async Task IntegrationsInstall_AgentWithoutValue_WritesInvalidArgumentsEnvelopeAndExits2( + params string[] args) + { + // Arrange + _claude.AttachTo(_harness); + + // Act + var run = await _harness.RunJsonAsync(args); + + // Assert + AssertError(run, ShadeKitCliExitCodes.InvalidArguments, ShadeKitCliErrorCodes.InvalidArguments); + + run.Root.GetProperty("error").GetProperty("message").GetString() + .Should().Be("Invalid arguments: --agent needs the id of a supported agent (claude), but got none. Run " + + "'shade-kit integrations install --help' for usage."); + + _claude.Calls + .Should().BeEmpty(); + } + + [Fact] + public async Task IntegrationsInstall_PlainModeUnknownAgent_WritesMessageToStandardErrorAndExits2() + { + // Act + var (exitCode, output, error) = await _harness.RunAsync("integrations", "install", "--agent", "copilot"); + + // Assert + exitCode + .Should().Be(ShadeKitCliExitCodes.InvalidArguments); + + output + .Should().BeEmpty(); + + error + .Should().Contain("'copilot' is not a supported agent for --agent (supported: claude)"); + } + + [Fact] + public async Task IntegrationsInstall_NoAgentDetected_WritesAgentNotFoundEnvelopeAndExits51() + { + // Act + var run = await _harness.RunJsonAsync("integrations", "install", "--json"); + + // Assert + AssertError(run, ShadeKitCliExitCodes.AgentNotFound, ShadeKitCliErrorCodes.AgentNotFound); + + run.Root.GetProperty("error").GetProperty("message").GetString() + .Should().StartWith("No supported agent was found (supported: claude)."); + } + + [Fact] + public async Task IntegrationsInstall_NamedClaudeNotOnPath_WritesAgentNotFoundEnvelopeAndExits51() + { + // Act + var run = await _harness.RunJsonAsync("integrations", "install", "--agent", "claude", "--json"); + + // Assert + AssertError(run, ShadeKitCliExitCodes.AgentNotFound, ShadeKitCliErrorCodes.AgentNotFound); + + run.Root.GetProperty("error").GetProperty("message").GetString() + .Should().StartWith("Claude Code is needed, but its CLI 'claude' was not found."); + } + + [Fact] + public async Task IntegrationsInstall_NamedClaudeNotOnPath_FailsWithoutReleaseTagCheck() + { + // Arrange + _harness.RemoteTags = ["v0.8.0"]; + var gitCalls = new List(); + _harness.OnGitCall = x => gitCalls.Add(string.Join(' ', x)); + + // Act + var run = await _harness.RunJsonAsync("integrations", "install", "--agent", "claude", "--json"); + + // Assert + AssertError(run, ShadeKitCliExitCodes.AgentNotFound, ShadeKitCliErrorCodes.AgentNotFound); + + gitCalls + .Should().BeEmpty("a missing named agent fails before the network call"); + } + + [Fact] + public async Task IntegrationsInstall_PluginInstallFails_WritesAgentCommandFailedEnvelopeAndExits52() + { + // Arrange + _claude.AttachTo(_harness).Fail = arguments => arguments is ["plugin", "install", ..] + ? new ExternalProcessResult(1, + """{"command":"install","outcome":"failed","plugin":"shade-kit@creativecoders-shade-kit","message":"Network error","failureCode":"network"}""" + + "\n", "✘ Network error\n") + : null; + + // Act + var run = await _harness.RunJsonAsync("integrations", "install", "--json"); + + // Assert + AssertError(run, ShadeKitCliExitCodes.AgentCommandFailed, ShadeKitCliErrorCodes.AgentCommandFailed); + + run.Root.GetProperty("error").GetProperty("message").GetString() + .Should().StartWith("'claude plugin install shade-kit@creativecoders-shade-kit --scope user --json' failed:") + .And.Contain("Network error"); + } + + [Fact] + public async Task IntegrationsInstall_MarketplaceWithOtherRepo_WritesIntegrationConflictEnvelopeAndChangesNothing() + { + // Arrange + _claude.AttachTo(_harness).Marketplace = FakeClaudeMarketplace.ForGitHub("someone/fork", "v0.8.0"); + + // Act + var run = await _harness.RunJsonAsync("integrations", "install", "--json"); + + // Assert + AssertError(run, ShadeKitCliExitCodes.IntegrationConflict, ShadeKitCliErrorCodes.IntegrationConflict); + + run.Root.GetProperty("error").GetProperty("message").GetString() + .Should().Contain("claude plugin marketplace remove creativecoders-shade-kit"); + + _claude.Calls + .Should().OnlyContain(x => x.EndsWith("list --json", StringComparison.Ordinal)); + + _claude.Marketplace + .Should().Be(FakeClaudeMarketplace.ForGitHub("someone/fork", "v0.8.0")); + } + + [Fact] + public async Task IntegrationsInstall_FailureAfterMarketplaceSwitch_NamesInstallAsRepair() + { + // Arrange + _claude.AttachTo(_harness).WithInstalledPlugin("v0.7.0").Fail = arguments => + arguments is ["plugin", "marketplace", "add", ..] + ? new ExternalProcessResult(1, string.Empty, "✘ Remote branch v0.8.0 not found\n") + : null; + + // Act + var run = await _harness.RunJsonAsync("integrations", "install", "--json"); + + // Assert + AssertError(run, ShadeKitCliExitCodes.AgentCommandFailed, ShadeKitCliErrorCodes.AgentCommandFailed); + + run.Root.GetProperty("error").GetProperty("message").GetString() + .Should().EndWith("'shade-kit integrations install' repairs it."); + } + + [Fact] + public async Task IntegrationsInstall_PrereleaseEngine_InstallsFromMainWithPrereleaseWarning() + { + // Arrange + _engineVersion = "0.9.0-beta.1"; + _claude.AttachTo(_harness); + + // Act + var run = await _harness.RunJsonAsync("integrations", "install", "--json"); + + // Assert + run.ExitCode + .Should().Be(0); + + run.Root.GetProperty("warnings").EnumerateArray().Select(x => x.GetProperty("code").GetString()) + .Should().Equal(ShadeKitCliWarningCodes.IntegrationPrereleaseRef); + + run.Root.GetProperty("data").ShouldBeJson( + """ + { + "ref": "main", "source": "CreativeCodersTeam/shade-kit#main", + "integrations": [ + { "agent": "claude", "pluginId": "shade-kit@creativecoders-shade-kit", "outcome": "installed", + "previousKitVersion": null, "kitVersion": null, "ref": "main", "enabled": true } + ] + } + """); + } + + [Fact] + public async Task IntegrationsInstall_ReleaseTagExists_ChecksTagAndInstallsFromIt() + { + // Arrange + _claude.AttachTo(_harness); + _harness.RemoteTags = ["v0.7.0", "v0.8.0"]; + var gitCalls = new List(); + _harness.OnGitCall = x => gitCalls.Add(string.Join(' ', x)); + + // Act + var run = await _harness.RunJsonAsync("integrations", "install", "--json"); + + // Assert + run.ExitCode + .Should().Be(0); + + run.Root.GetProperty("warnings").GetArrayLength() + .Should().Be(0); + + run.Root.GetProperty("data").GetProperty("source").GetString() + .Should().Be("CreativeCodersTeam/shade-kit#v0.8.0"); + + gitCalls + .Should().Equal("-c credential.helper= -c protocol.allow=never -c protocol.https.allow=always " + + "ls-remote --tags https://github.com/CreativeCodersTeam/shade-kit.git refs/tags/v0.8.0"); + } + + [Fact] + public async Task IntegrationsInstall_ReleaseTagMissing_InstallsFromMainWithReleaseTagMissingWarning() + { + // Arrange + _engineVersion = "0.8.1"; + _claude.AttachTo(_harness); + _harness.RemoteTags = ["v0.8.0"]; + + // Act + var run = await _harness.RunJsonAsync("integrations", "install", "--json"); + + // Assert + run.ExitCode + .Should().Be(0); + + run.Root.GetProperty("warnings").ShouldBeJson( + """ + [ { "code": "integration-release-tag-missing", + "message": "The release tag 'v0.8.1' of the engine 0.8.1 does not exist in CreativeCodersTeam/shade-kit, so the integrations come from the branch 'main' instead; they may not fit this engine." } ] + """); + + run.Root.GetProperty("data").ShouldBeJson( + """ + { + "ref": "main", "source": "CreativeCodersTeam/shade-kit#main", + "integrations": [ + { "agent": "claude", "pluginId": "shade-kit@creativecoders-shade-kit", "outcome": "installed", + "previousKitVersion": null, "kitVersion": null, "ref": "main", "enabled": true } + ] + } + """); + + _claude.Calls + .Should().Contain("plugin marketplace add CreativeCodersTeam/shade-kit#main --scope user --json"); + } + + [Fact] + public async Task IntegrationsUpdate_PlainModeReleaseTagMissing_WritesWarningAndUpdatesFromMain() + { + // Arrange + _engineVersion = "0.8.1"; + _claude.AttachTo(_harness).WithInstalledPlugin("v0.8.0"); + _harness.RemoteTags = ["v0.8.0"]; + + // Act + var (exitCode, output, _) = await _harness.RunAsync("integrations", "update"); + + // Assert + exitCode + .Should().Be(0); + + FoldWhitespace(output) + .Should().Contain("Warning: The release tag 'v0.8.1' of the engine 0.8.1 does not exist in " + + "CreativeCodersTeam/shade-kit, so the integrations come from the branch 'main' " + + "instead; they may not fit this engine.") + .And.Contain("claude: updated shade-kit@creativecoders-shade-kit 0.8.0 -> (main)"); + } + + [Fact] + public async Task IntegrationsInstall_ReleaseTagCannotBeChecked_InstallsFromTagWithoutWarning() + { + // Arrange + _claude.AttachTo(_harness); + + // Act + var run = await _harness.RunJsonAsync("integrations", "install", "--json"); + + // Assert + run.ExitCode + .Should().Be(0); + + run.Root.GetProperty("warnings").GetArrayLength() + .Should().Be(0); + + run.Root.GetProperty("data").GetProperty("ref").GetString() + .Should().Be("v0.8.0"); + } + + [Fact] + public async Task IntegrationsInstall_DirectoryOverride_InstallsFromDirectoryAndReportsItsPath() + { + // Arrange + _claude.AttachTo(_harness); + var sourcePath = _harness.TempDirectory.CreateDirectory("kit"); + var previousValue = Environment.GetEnvironmentVariable(IntegrationService.MarketplaceSourceVariableName); + + (int ExitCode, JsonElement Root) run; + (int ExitCode, string Output, string Error) plainRun; + + // Act + Environment.SetEnvironmentVariable(IntegrationService.MarketplaceSourceVariableName, sourcePath); + + try + { + run = await _harness.RunJsonAsync("integrations", "install", "--json"); + plainRun = await _harness.RunAsync("integrations", "install"); + } + finally + { + Environment.SetEnvironmentVariable(IntegrationService.MarketplaceSourceVariableName, previousValue); + } + + // Assert + run.ExitCode + .Should().Be(0); + + run.Root.GetProperty("data").GetProperty("ref").ValueKind + .Should().Be(JsonValueKind.Null); + + run.Root.GetProperty("data").GetProperty("source").GetString() + .Should().Be(sourcePath); + + run.Root.GetProperty("data").GetProperty("integrations")[0].GetProperty("kitVersion").ValueKind + .Should().Be(JsonValueKind.Null); + + // The console wraps long lines at spaces and splits words that are longer than a line, such as the path. + FoldWhitespace(plainRun.Output) + .Should().StartWith("claude: already current shade-kit@creativecoders-shade-kit from "); + + RemoveWhitespace(plainRun.Output) + .Should().Contain(RemoveWhitespace(sourcePath)); + } + + [Theory] + [InlineData("integrations", "install", "--json")] + [InlineData("integrations", "update", "--json")] + public async Task IntegrationsCommand_InvalidMarketplaceSourceOverride_WritesInvalidArgumentsEnvelopeAndExits2( + params string[] args) + { + // Arrange + _claude.AttachTo(_harness).WithInstalledPlugin("v0.8.0"); + var previousValue = Environment.GetEnvironmentVariable(IntegrationService.MarketplaceSourceVariableName); + + (int ExitCode, JsonElement Root) run; + + // Act + Environment.SetEnvironmentVariable(IntegrationService.MarketplaceSourceVariableName, "owner/repo#"); + + try + { + run = await _harness.RunJsonAsync(args); + } + finally + { + Environment.SetEnvironmentVariable(IntegrationService.MarketplaceSourceVariableName, previousValue); + } + + // Assert + AssertError(run, ShadeKitCliExitCodes.InvalidArguments, ShadeKitCliErrorCodes.InvalidArguments); + + run.Root.GetProperty("error").GetProperty("message").GetString() + .Should().StartWith($"The environment variable {IntegrationService.MarketplaceSourceVariableName} is " + + "set to 'owner/repo#'"); + + _claude.Calls + .Should().NotContain(x => x.Contains(" add ", StringComparison.Ordinal) || + x.Contains(" remove ", StringComparison.Ordinal) || + x.Contains(" install ", StringComparison.Ordinal) || + x.Contains(" update ", StringComparison.Ordinal)); + } + + [Theory] + [InlineData("https://github.com/CreativeCodersTeam/shade-kit.git", "It is a URL")] + [InlineData("git@github.com:CreativeCodersTeam/shade-kit.git", "It is an scp-like git URL")] + public async Task IntegrationsInstall_UrlAsMarketplaceSourceOverride_Exits2NamingAllowedFormsWithoutClaudeCall( + string value, string expectedReasonStart) + { + // Arrange + _claude.AttachTo(_harness); + var previousValue = Environment.GetEnvironmentVariable(IntegrationService.MarketplaceSourceVariableName); + + (int ExitCode, JsonElement Root) run; + + // Act + Environment.SetEnvironmentVariable(IntegrationService.MarketplaceSourceVariableName, value); + + try + { + run = await _harness.RunJsonAsync("integrations", "install", "--json"); + } + finally + { + Environment.SetEnvironmentVariable(IntegrationService.MarketplaceSourceVariableName, previousValue); + } + + // Assert + AssertError(run, ShadeKitCliExitCodes.InvalidArguments, ShadeKitCliErrorCodes.InvalidArguments); + + run.Root.GetProperty("error").GetProperty("message").GetString() + .Should().StartWith($"The environment variable {IntegrationService.MarketplaceSourceVariableName} is " + + $"set to '{value}', which is not a marketplace source: {expectedReasonStart}") + .And.Contain("a GitHub repository is written as owner/repo#ref or owner/repo.") + .And.EndWith("Set it to owner/repo#ref, owner/repo, or the path of a local directory, or remove it, " + + "then run the command again."); + + _claude.Calls + .Should().BeEmpty(); + } + + [Fact] + [Trait("Requirement", "FP07-AC3")] + public async Task IntegrationsUpdate_AfterEngineUpdate_SwitchesToNewTagAndReportsOldAndNewVersion() + { + // Arrange + _claude.AttachTo(_harness).WithInstalledPlugin("v0.7.0"); + + // Act + var run = await _harness.RunJsonAsync("integrations", "update", "--json"); + + // Assert + run.ExitCode + .Should().Be(0); + + run.Root.GetProperty("data").ShouldBeJson( + """ + { + "ref": "v0.8.0", "source": "CreativeCodersTeam/shade-kit#v0.8.0", + "integrations": [ + { "agent": "claude", "pluginId": "shade-kit@creativecoders-shade-kit", "outcome": "updated", + "previousKitVersion": "0.7.0", "kitVersion": "0.8.0", "ref": "v0.8.0", "enabled": true } + ] + } + """); + + _claude.Calls + .Should().ContainInOrder( + "plugin marketplace remove creativecoders-shade-kit --json", + "plugin marketplace add CreativeCodersTeam/shade-kit#v0.8.0 --scope user --json", + "plugin install shade-kit@creativecoders-shade-kit --scope user --json"); + + _claude.Marketplace + .Should().Be(FakeClaudeMarketplace.ForGitHub(FakeClaudeCode.Repo, "v0.8.0")); + } + + [Fact] + [Trait("Requirement", "FP07-AC3")] + public async Task IntegrationsUpdate_PlainModeAfterEngineUpdate_WritesOldAndNewVersionAndAsksForRestart() + { + // Arrange + _claude.AttachTo(_harness).WithInstalledPlugin("v0.7.0"); + + // Act + var (exitCode, output, _) = await _harness.RunAsync("integrations", "update"); + + // Assert + exitCode + .Should().Be(0); + + GetLines(output.TrimEnd()) + .Should().Equal( + "claude: updated shade-kit@creativecoders-shade-kit 0.7.0 -> 0.8.0 (v0.8.0)", + "Restart Claude Code to load the skills."); + } + + [Fact] + public async Task IntegrationsUpdate_IntegrationOfEngineVersion_ReportsCurrentWithoutRestartHint() + { + // Arrange + _claude.AttachTo(_harness).WithInstalledPlugin("v0.8.0"); + + // Act + var run = await _harness.RunJsonAsync("integrations", "update", "--json"); + var (exitCode, output, _) = await _harness.RunAsync("integrations", "update"); + + // Assert + run.Root.GetProperty("data").GetProperty("integrations")[0].GetProperty("outcome").GetString() + .Should().Be("current"); + + _claude.Calls + .Should().NotContain(x => x.StartsWith("plugin marketplace add", StringComparison.Ordinal) || + x.StartsWith("plugin marketplace remove", StringComparison.Ordinal)); + + exitCode + .Should().Be(0); + + GetLines(output.TrimEnd()) + .Should().Equal("claude: already current shade-kit@creativecoders-shade-kit 0.8.0 (v0.8.0)"); + } + + [Fact] + public async Task IntegrationsUpdate_KeptMarketplace_ReadsPluginsAndMarketplacesOnceAndRefreshesMarketplace() + { + // Arrange + _claude.AttachTo(_harness).WithInstalledPlugin("v0.8.0"); + + // Act + var run = await _harness.RunJsonAsync("integrations", "update", "--json"); + + // Assert + run.ExitCode + .Should().Be(0); + + _claude.Calls + .Should().Equal( + "plugin list --json", + "plugin marketplace list --json", + "plugin marketplace update creativecoders-shade-kit --json", + "plugin update shade-kit@creativecoders-shade-kit --scope user --json"); + } + + [Fact] + public async Task IntegrationsUpdate_BranchMarketplaceWithNewCommits_RefreshesMarketplaceAndReportsUpdated() + { + // Arrange + _engineVersion = "0.9.0-alpha.1"; + _claude.AttachTo(_harness).WithInstalledPlugin("main"); + _claude.RemoteRevision++; + + // Act + var run = await _harness.RunJsonAsync("integrations", "update", "--json"); + + // Assert + run.ExitCode + .Should().Be(0); + + run.Root.GetProperty("data").GetProperty("integrations")[0].GetProperty("outcome").GetString() + .Should().Be("updated", "the new commits of the branch must reach the plugin"); + + _claude.Calls + .Should().ContainInOrder( + "plugin marketplace update creativecoders-shade-kit --json", + "plugin update shade-kit@creativecoders-shade-kit --scope user --json"); + } + + [Fact] + public async Task IntegrationsUpdate_BranchMarketplaceWithoutNewCommits_ReportsCurrent() + { + // Arrange + _engineVersion = "0.9.0-alpha.1"; + _claude.AttachTo(_harness).WithInstalledPlugin("main"); + + // Act + var run = await _harness.RunJsonAsync("integrations", "update", "--json"); + + // Assert + run.Root.GetProperty("data").GetProperty("integrations")[0].GetProperty("outcome").GetString() + .Should().Be("current"); + } + + [Fact] + public async Task IntegrationsUpdate_MarketplaceRefreshFails_WritesAgentCommandFailedEnvelopeAndExits52() + { + // Arrange + _claude.AttachTo(_harness).WithInstalledPlugin("v0.8.0").Fail = arguments => + arguments is ["plugin", "marketplace", "update", ..] + ? new ExternalProcessResult(1, + """{"command":"marketplace-update","outcome":"failed","marketplace":"creativecoders-shade-kit","message":"Clone failed"}""" + + "\n", "✘ Clone failed\n") + : null; + + // Act + var run = await _harness.RunJsonAsync("integrations", "update", "--json"); + + // Assert + AssertError(run, ShadeKitCliExitCodes.AgentCommandFailed, ShadeKitCliErrorCodes.AgentCommandFailed); + + run.Root.GetProperty("error").GetProperty("message").GetString() + .Should().StartWith("'claude plugin marketplace update creativecoders-shade-kit --json' failed:") + .And.Contain("Clone failed"); + + _claude.Calls + .Should().NotContain(x => x.StartsWith("plugin update", StringComparison.Ordinal)); + } + + [Fact] + public async Task IntegrationsUpdate_DisabledPlugin_KeepsItDisabledAndSaysHowToEnableIt() + { + // Arrange + _claude.AttachTo(_harness).WithInstalledPlugin("v0.8.0", enabled: false); + + // Act + var run = await _harness.RunJsonAsync("integrations", "update", "--json"); + var (_, output, _) = await _harness.RunAsync("integrations", "update"); + + // Assert + run.Root.GetProperty("data").GetProperty("integrations")[0].GetProperty("enabled").GetBoolean() + .Should().BeFalse(); + + _claude.IsPluginEnabled + .Should().BeFalse(); + + FoldWhitespace(output) + .Should().Be("claude: already current shade-kit@creativecoders-shade-kit 0.8.0 (v0.8.0) The plugin is " + + "disabled in Claude Code. Run 'claude plugin enable shade-kit@creativecoders-shade-kit' to " + + "enable it. "); + } + + [Fact] + [Trait("Requirement", "FP07-AC6")] + public async Task IntegrationsUpdate_NothingInstalled_WritesEmptyIntegrationsAndExits0() + { + // Arrange + _claude.AttachTo(_harness); + + // Act + var run = await _harness.RunJsonAsync("integrations", "update", "--json"); + + // Assert + run.ExitCode + .Should().Be(0); + + run.Root.GetProperty("ok").GetBoolean() + .Should().BeTrue(); + + run.Root.GetProperty("data").ShouldBeJson( + """ + { "ref": null, "source": null, "integrations": [] } + """); + + run.Root.GetProperty("warnings").GetArrayLength() + .Should().Be(0); + + _claude.Calls + .Should().Equal("plugin list --json"); + } + + [Theory] + [InlineData("0.8.0")] + [InlineData("0.9.0-beta.1")] + public async Task IntegrationsUpdate_NothingInstalled_ChecksNoTagAndWritesNoSourceWarning(string engineVersion) + { + // Arrange + _engineVersion = engineVersion; + _claude.AttachTo(_harness); + _harness.RemoteTags = []; + var gitCalls = new List(); + _harness.OnGitCall = x => gitCalls.Add(string.Join(' ', x)); + + // Act + var run = await _harness.RunJsonAsync("integrations", "update", "--json"); + + // Assert + run.ExitCode + .Should().Be(0); + + run.Root.GetProperty("warnings").GetArrayLength() + .Should().Be(0); + + gitCalls + .Should().NotContain(x => x.Contains("ls-remote", StringComparison.Ordinal)); + } + + [Fact] + [Trait("Requirement", "FP07-AC6")] + public async Task IntegrationsUpdate_PlainModeNothingInstalled_SaysNothingIsInstalledAndExits0() + { + // Arrange + _claude.AttachTo(_harness); + + // Act + var (exitCode, output, error) = await _harness.RunAsync("integrations", "update"); + + // Assert + exitCode + .Should().Be(0); + + GetLines(output.TrimEnd()) + .Should().Equal( + "No SHADE kit integration is installed.", + "Run 'shade-kit integrations install' to install it."); + + error + .Should().BeEmpty(); + } + + [Fact] + public async Task IntegrationsUpdate_ClaudeNotOnPath_WritesAgentNotFoundEnvelopeAndExits51() + { + // Act + var run = await _harness.RunJsonAsync("integrations", "update", "--json"); + + // Assert + AssertError(run, ShadeKitCliExitCodes.AgentNotFound, ShadeKitCliErrorCodes.AgentNotFound); + } + + [Fact] + public async Task IntegrationsUpdate_PluginListFails_WritesAgentCommandFailedEnvelopeAndExits52() + { + // Arrange + _claude.AttachTo(_harness).Fail = _ => new ExternalProcessResult(0, "not json\n", string.Empty); + + // Act + var run = await _harness.RunJsonAsync("integrations", "update", "--json"); + + // Assert + AssertError(run, ShadeKitCliExitCodes.AgentCommandFailed, ShadeKitCliErrorCodes.AgentCommandFailed); + } + + [Fact] + public async Task IntegrationsUpdate_MarketplaceWithDirectorySource_WritesIntegrationConflictEnvelopeAndExits53() + { + // Arrange + _claude.AttachTo(_harness).WithInstalledPlugin("v0.8.0").Marketplace = + new FakeClaudeMarketplace("directory", null, null, "/src/shade-kit"); + + // Act + var run = await _harness.RunJsonAsync("integrations", "update", "--json"); + + // Assert + AssertError(run, ShadeKitCliExitCodes.IntegrationConflict, ShadeKitCliErrorCodes.IntegrationConflict); + + _claude.IsPluginInstalled + .Should().BeTrue(); + } + + [Fact] + [Trait("Requirement", "FP07-AC5")] + public async Task IntegrationsInstallAndUpdate_InGitRepository_CreateOrChangeNoFileInIt() + { + // Arrange + await _harness.InitAsync(); + await _harness.CreateIssueFeatureAsync(); + _claude.AttachTo(_harness).WithInstalledPlugin("v0.7.0"); + var snapshot = _harness.TempDirectory.TakeSnapshot(); + + // Act + await _harness.RunAllOkAsync(["integrations", "update"], ["integrations", "install"], + ["integrations", "install", "--agent", "claude"]); + + _engineVersion = "0.9.0"; + + (await _harness.RunAsync("integrations", "update")).ExitCode + .Should().Be(0); + + (await _harness.RunAsync("integrations", "install")).ExitCode + .Should().Be(0); + + // Assert + _harness.TempDirectory.TakeSnapshot() + .Should().BeEquivalentTo(snapshot); + + _claude.Calls + .Should().Contain("plugin marketplace add CreativeCodersTeam/shade-kit#v0.9.0 --scope user --json"); + + _claude.WorkingDirectories + .Should().NotBeEmpty() + .And.OnlyContain(x => !x.StartsWith(_harness.TempDirectory.RootPath, StringComparison.Ordinal)); + } + + [Fact] + [Trait("Requirement", "FP07-AC4")] + public async Task Version_JsonModeWithInstalledClaudeIntegration_ListsItWithKitVersion() + { + // Arrange + _claude.AttachTo(_harness).WithInstalledPlugin("v0.8.0"); + + // Act + var run = await _harness.RunJsonAsync("version", "--json"); + + // Assert + run.ExitCode + .Should().Be(0); + + run.Root.GetProperty("warnings").GetArrayLength() + .Should().Be(0); + + run.Root.GetProperty("data").GetProperty("integrations").ShouldBeJson( + """ + [ { "agent": "claude", "pluginId": "shade-kit@creativecoders-shade-kit", "kitVersion": "0.8.0", + "ref": "v0.8.0", "enabled": true } ] + """); + } + + [Fact] + [Trait("Requirement", "FP07-AC4")] + public async Task Version_AfterInstall_ListsIntegrationOfEngineVersionInPlainMode() + { + // Arrange + _claude.AttachTo(_harness); + await _harness.RunAllOkAsync(["integrations", "install"]); + + // Act + var (exitCode, output, _) = await _harness.RunAsync("version"); + + // Assert + exitCode + .Should().Be(0); + + GetLines(output.TrimEnd()) + .Should().Equal("shade-kit 0.8.0", "claude: shade-kit@creativecoders-shade-kit 0.8.0 (v0.8.0)"); + } + + [Fact] + public async Task Version_ClaudeNotOnPath_SucceedsWithEmptyIntegrationsAndNoWarning() + { + // Act + var run = await _harness.RunJsonAsync("version", "--json", "--expect", "0.8.0"); + + // Assert + run.ExitCode + .Should().Be(0); + + run.Root.GetProperty("ok").GetBoolean() + .Should().BeTrue(); + + run.Root.GetProperty("data").GetProperty("expectedVersion").GetString() + .Should().Be("0.8.0"); + + run.Root.GetProperty("data").GetProperty("integrations").GetArrayLength() + .Should().Be(0); + + run.Root.GetProperty("warnings").GetArrayLength() + .Should().Be(0); + + A.CallTo(_harness.ClaudeCommandRunner) + .MustNotHaveHappened(); + } + + [Fact] + public async Task Version_ClaudeOnPathFails_SucceedsWithEmptyIntegrationsAndAgentUnavailableWarning() + { + // Arrange + _claude.AttachTo(_harness).Fail = _ => new ExternalProcessResult(1, string.Empty, "claude crashed"); + + // Act + var run = await _harness.RunJsonAsync("version", "--json"); + + // Assert + run.ExitCode + .Should().Be(0); + + run.Root.GetProperty("data").GetProperty("integrations").GetArrayLength() + .Should().Be(0); + + run.Root.GetProperty("warnings").EnumerateArray().Select(x => x.GetProperty("code").GetString()) + .Should().Equal(ShadeKitCliWarningCodes.AgentUnavailable); + } + + [Fact] + public async Task Version_ExpectMismatchWithInstalledIntegration_StillExits50() + { + // Arrange + _claude.AttachTo(_harness).WithInstalledPlugin("v0.8.0"); + + // Act + var run = await _harness.RunJsonAsync("version", "--json", "--expect", "0.9.0"); + + // Assert + AssertError(run, ShadeKitCliExitCodes.VersionMismatch, ShadeKitCliErrorCodes.VersionMismatch); + + _claude.Calls + .Should().BeEmpty(); + } + + [Fact] + public async Task IntegrationsHelp_PlainMode_ListsInstallAndUpdate() + { + // Act + var (exitCode, output, _) = await _harness.RunAsync("integrations", "--help"); + + // Assert + exitCode + .Should().Be(0); + + output + .Should().Contain("install").And.Contain("update"); + } + + public void Dispose() + { + _harness.Dispose(); + } + + private static string RemoveWhitespace(string text) + { + return string.Concat(text.Where(x => !char.IsWhiteSpace(x))); + } +} diff --git a/tests/CreativeCoders.ShadeKit.Cli.Tests/Commands/Integrations/IntegrationsTextFormatTests.cs b/tests/CreativeCoders.ShadeKit.Cli.Tests/Commands/Integrations/IntegrationsTextFormatTests.cs new file mode 100644 index 0000000..0afa251 --- /dev/null +++ b/tests/CreativeCoders.ShadeKit.Cli.Tests/Commands/Integrations/IntegrationsTextFormatTests.cs @@ -0,0 +1,347 @@ +using AwesomeAssertions; +using CreativeCoders.ShadeKit.Cli.Commands.Integrations; +using CreativeCoders.ShadeKit.Core.Integrations; +using Spectre.Console; +using Spectre.Console.Testing; +using static CreativeCoders.ShadeKit.Cli.Tests.Commands.Integrations.IntegrationsCommandTestData; + +namespace CreativeCoders.ShadeKit.Cli.Tests.Commands.Integrations; + +public class IntegrationsTextFormatTests +{ + [Fact] + public void FormatResult_UpdatedWithoutPreviousKitVersion_WritesOnlyNewVersion() + { + // Arrange + var result = CreateResult(IntegrationOutcome.Updated); + + // Act + var markup = IntegrationsTextFormat.FormatResult(result, ReleaseSource); + + // Assert + ToPlainText(markup) + .Should().Be("claude: updated shade-kit@creativecoders-shade-kit 0.8.0 (v0.8.0)"); + } + + [Fact] + public void FormatResult_BranchWithoutKitVersion_WritesOnlyRef() + { + // Arrange + var result = new IntegrationResult("claude", PluginId, IntegrationOutcome.Installed, null, null, "main", true); + + // Act + var markup = IntegrationsTextFormat.FormatResult(result, + MarketplaceSource.ForGitHub("CreativeCodersTeam/shade-kit", "main")); + + // Assert + ToPlainText(markup) + .Should().Be("claude: installed shade-kit@creativecoders-shade-kit (main)"); + } + + [Fact] + public void FormatResult_DefaultBranchOfGitHubSource_WritesDefaultBranch() + { + // Arrange + var result = new IntegrationResult("claude", PluginId, IntegrationOutcome.Installed, null, null, null, true); + + // Act + var markup = IntegrationsTextFormat.FormatResult(result, + MarketplaceSource.ForGitHub("CreativeCodersTeam/shade-kit")); + + // Assert + ToPlainText(markup) + .Should().Be("claude: installed shade-kit@creativecoders-shade-kit (default branch)"); + } + + [Fact] + public void FormatResult_UpdatedToDefaultBranchOfGitHubSource_WritesPreviousVersionAndDefaultBranch() + { + // Arrange + var result = new IntegrationResult("claude", PluginId, IntegrationOutcome.Updated, "0.7.0", null, null, true); + + // Act + var markup = IntegrationsTextFormat.FormatResult(result, + MarketplaceSource.ForGitHub("CreativeCodersTeam/shade-kit")); + + // Assert + ToPlainText(markup) + .Should().Be("claude: updated shade-kit@creativecoders-shade-kit 0.7.0 -> (default branch)"); + } + + [Theory] + [InlineData(IntegrationOutcome.Installed, "installed")] + [InlineData(IntegrationOutcome.Current, "already current")] + public void FormatResult_NotUpdatedWithPreviousKitVersion_WritesNoArrow(IntegrationOutcome outcome, + string outcomeText) + { + // Arrange + var result = CreateResult(outcome, "0.7.0"); + + // Act + var markup = IntegrationsTextFormat.FormatResult(result, ReleaseSource); + + // Assert + ToPlainText(markup) + .Should().Be($"claude: {outcomeText} shade-kit@creativecoders-shade-kit 0.8.0 (v0.8.0)"); + } + + [Fact] + public void FormatResult_DirectoryPathWithMarkupCharacters_EscapesPath() + { + // Arrange + var source = MarketplaceSource.ForDirectory(Path.Combine(Path.GetTempPath(), "[kit]")); + var result = new IntegrationResult("claude", PluginId, IntegrationOutcome.Installed, null, null, null, true); + + // Act + var markup = IntegrationsTextFormat.FormatResult(result, source); + + // Assert + ToPlainText(markup) + .Should().Be($"claude: installed shade-kit@creativecoders-shade-kit from {source.Path}"); + } + + [Fact] + public void FormatResult_NullResult_ThrowsArgumentNullException() + { + // Act + var act = () => IntegrationsTextFormat.FormatResult(null!, ReleaseSource); + + // Assert + act.Should().Throw() + .WithParameterName("result"); + } + + [Fact] + public void FormatResult_NullSource_ThrowsArgumentNullException() + { + // Act + var act = () => IntegrationsTextFormat.FormatResult(CreateResult(IntegrationOutcome.Installed), null!); + + // Assert + act.Should().Throw() + .WithParameterName("source"); + } + + [Fact] + public void FormatResult_DirectorySource_WritesPathOfDirectory() + { + // Arrange + var path = Path.Combine(Path.GetTempPath(), "shade-kit"); + var source = MarketplaceSource.ForDirectory(path); + var result = new IntegrationResult("claude", PluginId, IntegrationOutcome.Updated, "0.7.0", null, null, true); + + // Act + var markup = IntegrationsTextFormat.FormatResult(result, source); + + // Assert + ToPlainText(markup) + .Should().Be($"claude: updated shade-kit@creativecoders-shade-kit 0.7.0 -> from {source.Path}"); + } + + [Fact] + public void FormatResult_ValuesWithMarkupCharacters_EscapesThem() + { + // Arrange + var result = new IntegrationResult("claude", "[x]@y", IntegrationOutcome.Updated, "[old]", "[new]", "[ref]", + true); + + // Act + var markup = IntegrationsTextFormat.FormatResult(result, ReleaseSource); + + // Assert + ToPlainText(markup) + .Should().Be("claude: updated [x]@y [old] -> [new] ([ref])"); + } + + [Fact] + public void FormatInstalled_EnabledIntegration_WritesAgentPluginIdAndVersion() + { + // Act + var markup = IntegrationsTextFormat.FormatInstalled( + new InstalledIntegration("claude", PluginId, "0.8.0", "v0.8.0", true)); + + // Assert + ToPlainText(markup) + .Should().Be("claude: shade-kit@creativecoders-shade-kit 0.8.0 (v0.8.0)"); + } + + [Fact] + public void FormatInstalled_DisabledIntegrationWithoutRef_WritesDisabledMark() + { + // Act + var markup = IntegrationsTextFormat.FormatInstalled( + new InstalledIntegration("claude", PluginId, null, null, false)); + + // Assert + ToPlainText(markup) + .Should().Be("claude: shade-kit@creativecoders-shade-kit (disabled)"); + } + + [Fact] + public void FormatInstalled_ValuesWithMarkupCharacters_EscapesThem() + { + // Act + var markup = IntegrationsTextFormat.FormatInstalled( + new InstalledIntegration("claude", "[x]@y", "[1]", "[ref]", true)); + + // Assert + ToPlainText(markup) + .Should().Be("claude: [x]@y [1] ([ref])"); + } + + [Fact] + public void FormatInstalled_NullIntegration_ThrowsArgumentNullException() + { + // Act + var act = () => IntegrationsTextFormat.FormatInstalled(null!); + + // Assert + act.Should().Throw() + .WithParameterName("integration"); + } + + [Fact] + public void FormatDisabledNote_IdsWithMarkupCharacters_EscapesThem() + { + // Act + var claudeNote = IntegrationsTextFormat.FormatDisabledNote("claude", "[x]@y"); + var otherNote = IntegrationsTextFormat.FormatDisabledNote("[other]", "kit@market"); + + // Assert + ToPlainText(claudeNote) + .Should().Be("The plugin is disabled in Claude Code. Run 'claude plugin enable [x]@y' to enable it."); + + ToPlainText(otherNote) + .Should().Be("The integration is disabled in the agent '[other]'; enable it there."); + } + + [Fact] + public void FormatDisabledNote_OtherAgent_SaysToEnableItInTheAgent() + { + // Act + var markup = IntegrationsTextFormat.FormatDisabledNote("other", "kit@market"); + + // Assert + ToPlainText(markup) + .Should().Be("The integration is disabled in the agent 'other'; enable it there."); + } + + [Fact] + public void WriteRun_OnlyOtherAgentChanged_WritesNoRestartHintForClaude() + { + // Arrange + var console = new TestConsole().Width(1000); + var run = CreateRun(new IntegrationResult("other", "kit@market", IntegrationOutcome.Installed, null, "0.8.0", + "v0.8.0", true)); + + // Act + IntegrationsTextFormat.WriteRun(console, run); + + // Assert + console.Lines + .Should().Equal("other: installed kit@market 0.8.0 (v0.8.0)"); + } + + [Fact] + public void WriteRun_ClaudeCurrentAndOtherAgentInstalled_WritesNoRestartHint() + { + // Arrange + var console = new TestConsole().Width(1000); + var run = CreateRun(CreateResult(IntegrationOutcome.Current), + new IntegrationResult("other", "kit@market", IntegrationOutcome.Installed, null, "0.8.0", "v0.8.0", true)); + + // Act + IntegrationsTextFormat.WriteRun(console, run); + + // Assert + console.Lines + .Should().Equal( + "claude: already current shade-kit@creativecoders-shade-kit 0.8.0 (v0.8.0)", + "other: installed kit@market 0.8.0 (v0.8.0)"); + } + + [Fact] + public void WriteRun_SeveralAgentsWithDisabledOnes_WritesEachNoteAfterItsLineAndOneRestartHintAtTheEnd() + { + // Arrange + var console = new TestConsole().Width(1000); + var run = CreateRun(CreateResult(IntegrationOutcome.Installed, enabled: false), + new IntegrationResult("other", "kit@market", IntegrationOutcome.Updated, "0.7.0", "0.8.0", "v0.8.0", + false)); + + // Act + IntegrationsTextFormat.WriteRun(console, run); + + // Assert + console.Lines + .Should().Equal( + "claude: installed shade-kit@creativecoders-shade-kit 0.8.0 (v0.8.0)", + " The plugin is disabled in Claude Code. Run 'claude plugin enable " + + "shade-kit@creativecoders-shade-kit' to enable it.", + "other: updated kit@market 0.7.0 -> 0.8.0 (v0.8.0)", + " The integration is disabled in the agent 'other'; enable it there.", + "Restart Claude Code to load the skills."); + } + + [Fact] + public void WriteRun_NothingInstalledWithoutSource_SaysNothingIsInstalledAndHowToInstall() + { + // Arrange + var console = new TestConsole().Width(1000); + + // Act + IntegrationsTextFormat.WriteRun(console, CreateNothingInstalledRun()); + + // Assert + console.Lines + .Should().Equal( + "No SHADE kit integration is installed.", + "Run 'shade-kit integrations install' to install it."); + } + + [Fact] + public void WriteRun_SourceWithoutResults_SaysNothingIsInstalledAndHowToInstall() + { + // Arrange + var console = new TestConsole().Width(1000); + + // Act + IntegrationsTextFormat.WriteRun(console, CreateRun()); + + // Assert + console.Lines + .Should().Equal( + "No SHADE kit integration is installed.", + "Run 'shade-kit integrations install' to install it."); + } + + [Fact] + public void WriteRun_NullConsole_ThrowsArgumentNullException() + { + // Act + var act = () => IntegrationsTextFormat.WriteRun(null!, CreateRun()); + + // Assert + act.Should().Throw() + .WithParameterName("console"); + } + + [Fact] + public void WriteRun_NullResult_ThrowsArgumentNullException() + { + // Act + var act = () => IntegrationsTextFormat.WriteRun(new TestConsole(), null!); + + // Assert + act.Should().Throw() + .WithParameterName("result"); + } + + private static string ToPlainText(string markup) + { + var console = new TestConsole().Width(1000); + console.MarkupLine(markup); + + return console.Lines.Single(); + } +} diff --git a/tests/CreativeCoders.ShadeKit.Cli.Tests/Commands/Integrations/Update/IntegrationsUpdateCommandTests.cs b/tests/CreativeCoders.ShadeKit.Cli.Tests/Commands/Integrations/Update/IntegrationsUpdateCommandTests.cs new file mode 100644 index 0000000..617c163 --- /dev/null +++ b/tests/CreativeCoders.ShadeKit.Cli.Tests/Commands/Integrations/Update/IntegrationsUpdateCommandTests.cs @@ -0,0 +1,311 @@ +using System.Reflection; +using System.Text.Json; +using AwesomeAssertions; +using CreativeCoders.Cli.Core; +using CreativeCoders.Cli.Hosting.Exceptions; +using CreativeCoders.ShadeKit.Cli.Commands; +using CreativeCoders.ShadeKit.Cli.Commands.Integrations.Update; +using CreativeCoders.ShadeKit.Cli.Tests.Commands.Phase; +using CreativeCoders.ShadeKit.Cli.Tests.Output; +using CreativeCoders.ShadeKit.Core.Integrations; +using CreativeCoders.ShadeKit.Core.Integrations.Exceptions; +using FakeItEasy; +using Spectre.Console.Testing; +using static CreativeCoders.ShadeKit.Cli.Tests.Commands.Integrations.IntegrationsCommandTestData; + +namespace CreativeCoders.ShadeKit.Cli.Tests.Commands.Integrations.Update; + +public sealed class IntegrationsUpdateCommandTests : IDisposable +{ + private readonly CancellationTokenSource _cancellationSource = new CancellationTokenSource(); + + private readonly TestConsole _console = new TestConsole().Width(1000); + + private readonly IIntegrationService _integrationService = A.Fake(); + + private readonly StringWriter _jsonOutput = new StringWriter(); + + [Fact] + [Trait("Requirement", "FP07-AC3")] + public async Task ExecuteAsync_JsonModeUpdated_WritesEnvelopeWithPreviousAndNewKitVersion() + { + // Arrange + ReturnRun(CreateRun(CreateResult(IntegrationOutcome.Updated, "0.7.0"))); + var command = CreateCommand(); + + // Act + var result = await command.ExecuteAsync(new IntegrationsUpdateCommandOptions { Json = true }); + + // Assert + result.ExitCode + .Should().Be(0); + + using var document = JsonDocument.Parse(_jsonOutput.ToString()); + + JsonSerializer.Serialize(document.RootElement.GetProperty("data")) + .Should().Be( + "{\"ref\":\"v0.8.0\",\"source\":\"CreativeCodersTeam/shade-kit#v0.8.0\",\"integrations\":[" + + "{\"agent\":\"claude\",\"pluginId\":\"shade-kit@creativecoders-shade-kit\",\"outcome\":\"updated\"," + + "\"previousKitVersion\":\"0.7.0\",\"kitVersion\":\"0.8.0\",\"ref\":\"v0.8.0\",\"enabled\":true}]}"); + + _console.Output + .Should().BeEmpty(); + } + + [Fact] + [Trait("Requirement", "FP07-AC3")] + public async Task ExecuteAsync_PlainModeUpdated_WritesOldAndNewVersionAndRestartHint() + { + // Arrange + ReturnRun(CreateRun(CreateResult(IntegrationOutcome.Updated, "0.7.0"))); + var command = CreateCommand(); + + // Act + await command.ExecuteAsync(new IntegrationsUpdateCommandOptions()); + + // Assert + _console.Lines + .Should().Equal( + "claude: updated shade-kit@creativecoders-shade-kit 0.7.0 -> 0.8.0 (v0.8.0)", + "Restart Claude Code to load the skills."); + } + + [Fact] + public async Task ExecuteAsync_PlainModeCurrentAndDisabled_WritesDisabledNoteWithoutRestartHint() + { + // Arrange + ReturnRun(CreateRun(CreateResult(IntegrationOutcome.Current, "0.8.0", enabled: false))); + var command = CreateCommand(); + + // Act + await command.ExecuteAsync(new IntegrationsUpdateCommandOptions()); + + // Assert + _console.Lines + .Should().Equal( + "claude: already current shade-kit@creativecoders-shade-kit 0.8.0 (v0.8.0)", + " The plugin is disabled in Claude Code. Run 'claude plugin enable " + + "shade-kit@creativecoders-shade-kit' to enable it."); + } + + [Fact] + [Trait("Requirement", "FP07-AC6")] + public async Task ExecuteAsync_JsonModeNothingInstalled_WritesSuccessEnvelopeWithEmptyIntegrations() + { + // Arrange + ReturnRun(CreateNothingInstalledRun()); + var command = CreateCommand(); + + // Act + var result = await command.ExecuteAsync(new IntegrationsUpdateCommandOptions { Json = true }); + + // Assert + result.ExitCode + .Should().Be(0); + + using var document = JsonDocument.Parse(_jsonOutput.ToString()); + + document.RootElement.GetProperty("ok").GetBoolean() + .Should().BeTrue(); + + document.RootElement.GetProperty("data").ShouldBeJson( + """ + { "ref": null, "source": null, "integrations": [] } + """); + + document.RootElement.GetProperty("warnings").GetArrayLength() + .Should().Be(0); + } + + [Fact] + [Trait("Requirement", "FP07-AC6")] + public async Task ExecuteAsync_PlainModeNothingInstalled_SaysNothingIsInstalledAndHowToInstall() + { + // Arrange + ReturnRun(CreateNothingInstalledRun()); + var command = CreateCommand(); + + // Act + var result = await command.ExecuteAsync(new IntegrationsUpdateCommandOptions()); + + // Assert + result.ExitCode + .Should().Be(0); + + _console.Lines + .Should().Equal( + "No SHADE kit integration is installed.", + "Run 'shade-kit integrations install' to install it."); + } + + [Fact] + public async Task ExecuteAsync_AnyMode_UpdatesWithCancellationTokenOfRun() + { + // Arrange + ReturnRun(CreateRun()); + var command = CreateCommand(); + + // Act + await command.ExecuteAsync(new IntegrationsUpdateCommandOptions { Json = true }); + + // Assert + A.CallTo(() => _integrationService.UpdateAsync(_cancellationSource.Token)) + .MustHaveHappenedOnceExactly(); + } + + [Fact] + public async Task ExecuteAsync_JsonModeAgentCommandFailed_WritesFailureEnvelopeAndAbortsWith52() + { + // Arrange + A.CallTo(() => _integrationService.UpdateAsync(A._)) + .ThrowsAsync(new ClaudeCommandFailedException(["plugin", "list", "--json"], 1, "claude exited with 1.")); + + var command = CreateCommand(); + + // Act + var act = () => command.ExecuteAsync(new IntegrationsUpdateCommandOptions { Json = true }); + + // Assert + var exception = (await act.Should().ThrowAsync()).Which; + + exception.ExitCode + .Should().Be(ShadeKitCliExitCodes.AgentCommandFailed); + + using var document = JsonDocument.Parse(_jsonOutput.ToString()); + + document.RootElement.GetProperty("error").GetProperty("code").GetString() + .Should().Be(ShadeKitCliErrorCodes.AgentCommandFailed); + } + + [Fact] + public async Task ExecuteAsync_PlainModeSecondAgentFailedAfterSwitch_AbortsWithRepairHintAndCompletedAgents() + { + // Arrange + A.CallTo(() => _integrationService.UpdateAsync(A._)) + .ThrowsAsync(new IntegrationRunFailedException("copilot", ReleaseSource, + [CreateResult(IntegrationOutcome.Updated, "0.7.0")], + new IntegrationIncompleteException("copilot", + new ClaudeCommandFailedException(["plugin", "install"], 1, "claude failed.")))); + + var command = CreateCommand(); + + // Act + var act = () => command.ExecuteAsync(new IntegrationsUpdateCommandOptions()); + + // Assert + var exception = (await act.Should().ThrowAsync()).Which; + + exception.ExitCode + .Should().Be(ShadeKitCliExitCodes.AgentCommandFailed); + + exception.Message + .Should().Contain("'shade-kit integrations install' repairs it.") + .And.EndWith("Before the agent 'copilot' failed, these integrations were done: claude: updated " + + "shade-kit@creativecoders-shade-kit 0.7.0 -> 0.8.0 (v0.8.0)."); + + _console.Output + .Should().BeEmpty(); + } + + [Fact] + public async Task ExecuteAsync_JsonModeCanceledDuringMarketplaceSwitch_WritesCanceledEnvelopeWithRepairHint() + { + // Arrange + A.CallTo(() => _integrationService.UpdateAsync(A._)) + .ThrowsAsync(new IntegrationSwitchCanceledException("claude", new OperationCanceledException())); + + var command = CreateCommand(); + + // Act + var act = () => command.ExecuteAsync(new IntegrationsUpdateCommandOptions { Json = true }); + + // Assert + var exception = (await act.Should().ThrowAsync()).Which; + + exception.ExitCode + .Should().Be(ShadeKitCliExitCodes.Canceled); + + using var document = JsonDocument.Parse(_jsonOutput.ToString()); + + document.RootElement.GetProperty("error").GetProperty("code").GetString() + .Should().Be(ShadeKitCliErrorCodes.Canceled); + + document.RootElement.GetProperty("error").GetProperty("message").GetString() + .Should().EndWith("'shade-kit integrations install' repairs it."); + } + + [Fact] + public async Task ExecuteAsync_NullOptions_ThrowsArgumentNullException() + { + // Arrange + var command = CreateCommand(); + + // Act + var act = () => command.ExecuteAsync(null!); + + // Assert + (await act.Should().ThrowAsync()) + .WithParameterName("options"); + } + + [Fact] + public void Ctor_NullContext_ThrowsArgumentNullException() + { + // Act + var act = () => new IntegrationsUpdateCommand(null!, _integrationService); + + // Assert + act.Should().Throw() + .WithParameterName("context"); + } + + [Fact] + public void Ctor_NullIntegrationService_ThrowsArgumentNullException() + { + // Act + var act = () => new IntegrationsUpdateCommand(TestShadeKitCommandContext.Create(_console), null!); + + // Assert + act.Should().Throw() + .WithParameterName("integrationService"); + } + + [Fact] + public void IntegrationsUpdateCommand_CliCommandAttribute_IsRegisteredInIntegrationsGroup() + { + // Act + var attribute = typeof(IntegrationsUpdateCommand).GetCustomAttribute(); + + // Assert + attribute!.Commands + .Should().Equal("integrations", "update"); + } + + [Fact] + public void IntegrationsUpdateCommandOptions_Type_DerivesFromJsonCommandOptions() + { + // Assert + typeof(IntegrationsUpdateCommandOptions) + .Should().BeDerivedFrom(); + } + + public void Dispose() + { + _cancellationSource.Dispose(); + _jsonOutput.Dispose(); + } + + private void ReturnRun(IntegrationRunResult result) + { + A.CallTo(() => _integrationService.UpdateAsync(A._)) + .Returns(result); + } + + private IntegrationsUpdateCommand CreateCommand() + { + return new IntegrationsUpdateCommand( + TestShadeKitCommandContext.Create(_console, jsonOutput: _jsonOutput, + cancellation: new TestCliCancellation(_cancellationSource.Token)), + _integrationService); + } +} diff --git a/tests/CreativeCoders.ShadeKit.Cli.Tests/Commands/Version/VersionCommandTests.cs b/tests/CreativeCoders.ShadeKit.Cli.Tests/Commands/Version/VersionCommandTests.cs index 6ee09fd..22a7a04 100644 --- a/tests/CreativeCoders.ShadeKit.Cli.Tests/Commands/Version/VersionCommandTests.cs +++ b/tests/CreativeCoders.ShadeKit.Cli.Tests/Commands/Version/VersionCommandTests.cs @@ -8,6 +8,8 @@ using CreativeCoders.ShadeKit.Cli.Tests.Output; using CreativeCoders.ShadeKit.Core.Engine; using CreativeCoders.ShadeKit.Core.Formats; +using CreativeCoders.ShadeKit.Core.Integrations; +using CreativeCoders.ShadeKit.Core.Integrations.Warnings; using CreativeCoders.ShadeKit.Core.Versions; using FakeItEasy; using Spectre.Console; @@ -23,12 +25,17 @@ public class VersionCommandTests private const string NewerEngineMessage = "The SHADE kit engine 1.2.3 does not fit the kit skills 1.1.0: the major and minor versions must be equal. " + - "Update the SHADE kit skills to 1.2 by hand, then run the skill again."; + "Run 'shade-kit integrations install' to install the SHADE kit skills 1.2, then run the skill again."; + + private const string PluginId = "shade-kit@creativecoders-shade-kit"; private const string PrereleaseWarningMessage = "The prerelease engine 1.2.3-beta.1 does not fit the kit skills 1.3.0 (the major and minor versions differ); " + "it is used anyway because it is a prerelease."; + private static readonly InstalledIntegration ClaudeIntegration = + new InstalledIntegration("claude", PluginId, "0.8.0", "v0.8.0", true); + [Fact] [Trait("Requirement", "FP06-1-AC6")] public async Task ExecuteAsync_PlainMode_WritesToolNameAndEngineVersion() @@ -85,8 +92,7 @@ public async Task ExecuteAsync_JsonMode_WritesEnvelopeWithEngineVersionAndOneFor ("gates", 1), ("feature", 1), ("current-feature", 1), - ("templates-lock", 1), - ("integrations", 1)); + ("templates-lock", 1)); root.GetProperty("warnings").GetArrayLength() .Should().Be(0); @@ -122,9 +128,9 @@ public async Task ExecuteAsync_JsonModeWithoutExpect_WritesEnvelopeWithoutExpect "gates": 1, "feature": 1, "current-feature": 1, - "templates-lock": 1, - "integrations": 1 - } + "templates-lock": 1 + }, + "integrations": [] }, "warnings": [], "error": null @@ -141,7 +147,7 @@ public async Task ExecuteAsync_WithoutExpect_DoesNotCheckEngineVersion(bool json // Arrange var checker = A.Fake(); var command = new VersionCommand(TestShadeKitCommandContext.Create(new TestConsole()), - CreateEngineVersionProvider("1.2.3"), FormatRegistry.CreateDefault(), checker); + CreateEngineVersionProvider("1.2.3"), FormatRegistry.CreateDefault(), checker, CreateIntegrationService()); // Act var result = await command.ExecuteAsync(new VersionCommandOptions { Json = json }); @@ -183,7 +189,7 @@ public async Task ExecuteAsync_JsonModeExpectWithEqualMajorAndMinor_WritesSucces .Should().BeTrue(); root.GetProperty("data").EnumerateObject().Select(x => x.Name) - .Should().Equal("engineVersion", "formats", "expectedVersion"); + .Should().Equal("engineVersion", "formats", "expectedVersion", "integrations"); root.GetProperty("data").GetProperty("engineVersion").GetString() .Should().Be("1.2.3"); @@ -562,12 +568,220 @@ public void VersionCommandOptions_Type_DerivesFromJsonCommandOptions() .Should().BeDerivedFrom(); } + [Fact] + [Trait("Requirement", "FP07-AC4")] + public async Task ExecuteAsync_JsonModeWithInstalledIntegration_ListsIntegrationWithKitVersion() + { + // Arrange + using var jsonOutput = new StringWriter(); + var command = CreateCommand(new TestConsole(), jsonOutput, "0.8.0", + integrationService: CreateIntegrationService(ClaudeIntegration)); + + // Act + await command.ExecuteAsync(new VersionCommandOptions { Json = true }); + + // Assert + using var document = JsonDocument.Parse(jsonOutput.ToString()); + var root = document.RootElement; + + JsonSerializer.Serialize(root.GetProperty("data").GetProperty("integrations")) + .Should().Be( + "[{\"agent\":\"claude\",\"pluginId\":\"shade-kit@creativecoders-shade-kit\",\"kitVersion\":\"0.8.0\"," + + "\"ref\":\"v0.8.0\",\"enabled\":true}]"); + + root.GetProperty("warnings").GetArrayLength() + .Should().Be(0); + } + + [Fact] + [Trait("Requirement", "FP07-AC4")] + public async Task ExecuteAsync_JsonModeWithIntegrationOfUnknownVersion_WritesNullKitVersionAndRef() + { + // Arrange + using var jsonOutput = new StringWriter(); + var command = CreateCommand(new TestConsole(), jsonOutput, "0.8.0", + integrationService: CreateIntegrationService( + new InstalledIntegration("claude", PluginId, null, null, false))); + + // Act + await command.ExecuteAsync(new VersionCommandOptions { Json = true }); + + // Assert + using var document = JsonDocument.Parse(jsonOutput.ToString()); + + JsonSerializer.Serialize(document.RootElement.GetProperty("data").GetProperty("integrations")) + .Should().Be( + "[{\"agent\":\"claude\",\"pluginId\":\"shade-kit@creativecoders-shade-kit\",\"kitVersion\":null," + + "\"ref\":null,\"enabled\":false}]"); + } + + [Fact] + [Trait("Requirement", "FP07-AC4")] + public async Task ExecuteAsync_PlainModeWithInstalledIntegrations_WritesOneLinePerIntegrationAfterVersionLine() + { + // Arrange + var console = new TestConsole().Width(1000); + var command = CreateCommand(console, TextWriter.Null, "0.8.0", + integrationService: CreateIntegrationService(ClaudeIntegration, + new InstalledIntegration("claude", PluginId, null, "main", false))); + + // Act + await command.ExecuteAsync(new VersionCommandOptions()); + + // Assert + console.Lines + .Should().Equal( + "shade-kit 0.8.0", + "claude: shade-kit@creativecoders-shade-kit 0.8.0 (v0.8.0)", + "claude: shade-kit@creativecoders-shade-kit (main) (disabled)"); + } + + [Fact] + public async Task ExecuteAsync_JsonModeAgentUnavailable_WritesSuccessWithEmptyIntegrationsAndWarning() + { + // Arrange + using var jsonOutput = new StringWriter(); + var command = CreateCommand(new TestConsole(), jsonOutput, "0.8.0", + integrationService: CreateIntegrationService(new InstalledIntegrationsResult([], + [new AgentUnavailableWarning("claude", "claude was not found on the PATH.")]))); + + // Act + var result = await command.ExecuteAsync(new VersionCommandOptions { Json = true }); + + // Assert + result.ExitCode + .Should().Be(0); + + using var document = JsonDocument.Parse(jsonOutput.ToString()); + var root = document.RootElement; + + root.GetProperty("ok").GetBoolean() + .Should().BeTrue(); + + root.GetProperty("data").GetProperty("integrations").GetArrayLength() + .Should().Be(0); + + root.GetProperty("warnings").EnumerateArray() + .Select(x => (x.GetProperty("code").GetString(), x.GetProperty("message").GetString())) + .Should().Equal((ShadeKitCliWarningCodes.AgentUnavailable, + "The SHADE kit integration of the agent 'claude' cannot be read, so it is not listed: claude was not " + + "found on the PATH.")); + } + + [Fact] + public async Task ExecuteAsync_PlainModeAgentUnavailable_WritesWarningBeforeVersionLine() + { + // Arrange + var console = new TestConsole().Width(1000); + var command = CreateCommand(console, TextWriter.Null, "0.8.0", + integrationService: CreateIntegrationService(new InstalledIntegrationsResult([], + [new AgentUnavailableWarning("claude", "claude was not found on the PATH.")]))); + + // Act + await command.ExecuteAsync(new VersionCommandOptions()); + + // Assert + console.Lines + .Should().Equal( + "Warning: The SHADE kit integration of the agent 'claude' cannot be read, so it is not listed: " + + "claude was not found on the PATH.", + "shade-kit 0.8.0"); + } + + [Fact] + [Trait("Requirement", "FP06-1-AC4")] + public async Task ExecuteAsync_PrereleaseMismatchAndAgentUnavailable_WritesCheckWarningBeforeAgentWarning() + { + // Arrange + using var jsonOutput = new StringWriter(); + var command = CreateCommand(new TestConsole(), jsonOutput, "1.2.3-beta.1", + integrationService: CreateIntegrationService(new InstalledIntegrationsResult([ClaudeIntegration], + [new AgentUnavailableWarning("other", "It fails.")]))); + + // Act + await command.ExecuteAsync(new VersionCommandOptions { Json = true, Expect = "1.3.0" }); + + // Assert + using var document = JsonDocument.Parse(jsonOutput.ToString()); + var root = document.RootElement; + + root.GetProperty("warnings").EnumerateArray().Select(x => x.GetProperty("code").GetString()) + .Should().Equal(ShadeKitCliWarningCodes.EnginePrereleaseVersionMismatch, + ShadeKitCliWarningCodes.AgentUnavailable); + + root.GetProperty("data").EnumerateObject().Select(x => x.Name) + .Should().Equal("engineVersion", "formats", "expectedVersion", "integrations"); + + root.GetProperty("data").GetProperty("integrations").GetArrayLength() + .Should().Be(1); + } + + [Fact] + [Trait("Requirement", "FP06-1-AC1")] + public async Task ExecuteAsync_ReleaseEngineMismatch_DoesNotReadIntegrations() + { + // Arrange + var integrationService = CreateIntegrationService(ClaudeIntegration); + var command = CreateCommand(new TestConsole(), TextWriter.Null, "1.2.3", + integrationService: integrationService); + + // Act + var act = () => command.ExecuteAsync(new VersionCommandOptions { Json = true, Expect = "1.3.0" }); + + // Assert + await act.Should().ThrowAsync(); + + A.CallTo(() => integrationService.GetInstalledAsync(A._)) + .MustNotHaveHappened(); + } + + [Fact] + [Trait("Requirement", "FP06-1-AC5")] + public async Task ExecuteAsync_InvalidExpect_DoesNotReadIntegrations() + { + // Arrange + var integrationService = CreateIntegrationService(ClaudeIntegration); + var command = CreateCommand(new TestConsole(), TextWriter.Null, "1.2.3", + integrationService: integrationService); + + // Act + var act = () => command.ExecuteAsync(new VersionCommandOptions { Json = true, Expect = "abc" }); + + // Assert + (await act.Should().ThrowAsync()) + .Which.ExitCode.Should().Be(ShadeKitCliExitCodes.InvalidArguments); + + A.CallTo(() => integrationService.GetInstalledAsync(A._)) + .MustNotHaveHappened(); + } + + [Fact] + public async Task ExecuteAsync_AnyMode_PassesCancellationTokenOfRunToIntegrationService() + { + // Arrange + using var cancellationTokenSource = new CancellationTokenSource(); + var integrationService = CreateIntegrationService(); + var engineVersionProvider = CreateEngineVersionProvider("1.2.3"); + var command = new VersionCommand( + TestShadeKitCommandContext.Create(new TestConsole(), + cancellation: new TestCliCancellation(cancellationTokenSource.Token)), + engineVersionProvider, FormatRegistry.CreateDefault(), new EngineVersionChecker(engineVersionProvider), + integrationService); + + // Act + await command.ExecuteAsync(new VersionCommandOptions { Json = true }); + + // Assert + A.CallTo(() => integrationService.GetInstalledAsync(cancellationTokenSource.Token)) + .MustHaveHappenedOnceExactly(); + } + [Fact] public void Ctor_NullContext_ThrowsArgumentNullException() { // Act var act = () => new VersionCommand(null!, CreateEngineVersionProvider("1.0.0"), FormatRegistry.CreateDefault(), - A.Fake()); + A.Fake(), CreateIntegrationService()); // Assert act.Should().Throw() @@ -579,7 +793,7 @@ public void Ctor_NullEngineVersionProvider_ThrowsArgumentNullException() { // Act var act = () => new VersionCommand(TestShadeKitCommandContext.Create(new TestConsole()), null!, - FormatRegistry.CreateDefault(), A.Fake()); + FormatRegistry.CreateDefault(), A.Fake(), CreateIntegrationService()); // Assert act.Should().Throw() @@ -591,7 +805,7 @@ public void Ctor_NullFormatRegistry_ThrowsArgumentNullException() { // Act var act = () => new VersionCommand(TestShadeKitCommandContext.Create(new TestConsole()), - CreateEngineVersionProvider("1.0.0"), null!, A.Fake()); + CreateEngineVersionProvider("1.0.0"), null!, A.Fake(), CreateIntegrationService()); // Assert act.Should().Throw() @@ -603,13 +817,26 @@ public void Ctor_NullEngineVersionChecker_ThrowsArgumentNullException() { // Act var act = () => new VersionCommand(TestShadeKitCommandContext.Create(new TestConsole()), - CreateEngineVersionProvider("1.0.0"), FormatRegistry.CreateDefault(), null!); + CreateEngineVersionProvider("1.0.0"), FormatRegistry.CreateDefault(), null!, CreateIntegrationService()); // Assert act.Should().Throw() .WithParameterName("engineVersionChecker"); } + [Fact] + public void Ctor_NullIntegrationService_ThrowsArgumentNullException() + { + // Act + var act = () => new VersionCommand(TestShadeKitCommandContext.Create(new TestConsole()), + CreateEngineVersionProvider("1.0.0"), FormatRegistry.CreateDefault(), A.Fake(), + null!); + + // Assert + act.Should().Throw() + .WithParameterName("integrationService"); + } + [Fact] public void VersionCommand_CliCommandAttribute_IsRegisteredAsTopLevelVersionCommand() { @@ -625,13 +852,26 @@ public void VersionCommand_CliCommandAttribute_IsRegisteredAsTopLevelVersionComm } private static VersionCommand CreateCommand(IAnsiConsole console, TextWriter jsonOutput, string engineVersion, - IFormatRegistry? formatRegistry = null) + IFormatRegistry? formatRegistry = null, IIntegrationService? integrationService = null) { var engineVersionProvider = CreateEngineVersionProvider(engineVersion); return new VersionCommand(TestShadeKitCommandContext.Create(console, jsonOutput: jsonOutput), engineVersionProvider, formatRegistry ?? FormatRegistry.CreateDefault(), - new EngineVersionChecker(engineVersionProvider)); + new EngineVersionChecker(engineVersionProvider), integrationService ?? CreateIntegrationService()); + } + + private static IIntegrationService CreateIntegrationService(params InstalledIntegration[] integrations) + { + return CreateIntegrationService(new InstalledIntegrationsResult(integrations, [])); + } + + private static IIntegrationService CreateIntegrationService(InstalledIntegrationsResult result) + { + var integrationService = A.Fake(); + A.CallTo(() => integrationService.GetInstalledAsync(A._)).Returns(result); + + return integrationService; } private static IEngineVersionProvider CreateEngineVersionProvider(string version) diff --git a/tests/CreativeCoders.ShadeKit.Cli.Tests/Output/CliErrorMapperTests.cs b/tests/CreativeCoders.ShadeKit.Cli.Tests/Output/CliErrorMapperTests.cs index 9929a73..395bcd4 100644 --- a/tests/CreativeCoders.ShadeKit.Cli.Tests/Output/CliErrorMapperTests.cs +++ b/tests/CreativeCoders.ShadeKit.Cli.Tests/Output/CliErrorMapperTests.cs @@ -3,6 +3,7 @@ using AwesomeAssertions; using CreativeCoders.ShadeKit.Cli.Commands.Feature.New; using CreativeCoders.ShadeKit.Cli.Commands.Feature.Show; +using CreativeCoders.ShadeKit.Cli.Commands.Integrations.Install; using CreativeCoders.ShadeKit.Cli.Commands.Version; using CreativeCoders.ShadeKit.Cli.Output; using CreativeCoders.ShadeKit.Core.Engine; @@ -17,6 +18,9 @@ using CreativeCoders.ShadeKit.Core.Git.Exceptions; using CreativeCoders.ShadeKit.Core.Git.Warnings; using CreativeCoders.ShadeKit.Core.Init.Exceptions; +using CreativeCoders.ShadeKit.Core.Integrations; +using CreativeCoders.ShadeKit.Core.Integrations.Exceptions; +using CreativeCoders.ShadeKit.Core.Integrations.Warnings; using CreativeCoders.ShadeKit.Core.Store.Exceptions; using CreativeCoders.ShadeKit.Core.Trackers.Exceptions; using CreativeCoders.ShadeKit.Core.Versions; @@ -841,12 +845,14 @@ public void Map_EngineVersionMismatchWithNewerEngine_ReturnsExitCode50NamingVers error .Should().Be(new CliError(ShadeKitCliExitCodes.VersionMismatch, ShadeKitCliErrorCodes.VersionMismatch, "The SHADE kit engine 2.1.4 does not fit the kit skills 1.9.0+build.2: the major and minor versions " + - "must be equal. Update the SHADE kit skills to 2.1 by hand, then run the skill again.")); + "must be equal. Run 'shade-kit integrations install' to install the SHADE kit skills 2.1, then run " + + "the skill again.")); } [Theory] [InlineData(EngineVersionMismatchDirection.EngineOlder, "Update the engine to 1.x, then")] - [InlineData(EngineVersionMismatchDirection.EngineNewer, "Update the SHADE kit skills to engine by hand, then")] + [InlineData(EngineVersionMismatchDirection.EngineNewer, + "Run 'shade-kit integrations install' to install the SHADE kit skills engine, then")] public void Map_EngineVersionMismatchWithVersionsThatAreNotSemVer_NamesVersionsWhole( EngineVersionMismatchDirection direction, string expectedRemedy) { @@ -974,6 +980,378 @@ public void Map_FileAlreadyExists_ReturnsExitCode17NamingFileAndFix() "or remove the file, then run the command again.")); } + [Fact] + public void Map_ClaudeNotFound_ReturnsExitCode51NamingReasonInstallHintAndWindowsHint() + { + // Arrange + var mapper = CreateMapper(); + + // Act + var error = mapper.Map(new ClaudeNotFoundException(["plugin", "list", "--json"], + "The Claude Code CLI claude was not found in any absolute directory of the PATH environment variable.")); + + // Assert + error + .Should().Be(new CliError(ShadeKitCliExitCodes.AgentNotFound, ShadeKitCliErrorCodes.AgentNotFound, + "Claude Code is needed, but its CLI 'claude' was not found. The Claude Code CLI claude was not found " + + "in any absolute directory of the PATH environment variable. Install Claude Code and make sure " + + "'claude' is in an absolute directory of the PATH, then run the command again. On Windows only the " + + "'claude.exe' of the native installer is found; the 'claude.cmd' of an npm installation is not.")); + } + + [Fact] + public void Map_ClaudeUnavailable_ReturnsExitCode52NamingCommandReasonAndFix() + { + // Arrange + var mapper = CreateMapper(); + + // Act + var error = mapper.Map(new ClaudeUnavailableException(["plugin", "list", "--json"], + "The claude executable '/usr/local/bin/claude' could not be started: Permission denied.")); + + // Assert + error + .Should().Be(new CliError(ShadeKitCliExitCodes.AgentCommandFailed, + ShadeKitCliErrorCodes.AgentCommandFailed, + "'claude plugin list --json' cannot be run: The claude executable '/usr/local/bin/claude' could not " + + "be started: Permission denied. Make sure Claude Code is installed correctly and 'claude --version' " + + "works, then run the command again.")); + } + + [Fact] + public void Map_ClaudeCommandFailed_ReturnsExitCode52NamingCommandClaudeMessageAndFailureCode() + { + // Arrange + var mapper = CreateMapper(); + + // Act + var error = mapper.Map(new ClaudeCommandFailedException( + ["plugin", "update", "nope@creativecoders-shade-kit", "--scope", "user", "--json"], 1, + "claude exited with the exit code 1 and reported the outcome 'failed': Plugin \"nope\" not found " + + "(failure code 'not_found').", "Plugin \"nope\" not found", "not_found")); + + // Assert + error + .Should().Be(new CliError(ShadeKitCliExitCodes.AgentCommandFailed, + ShadeKitCliErrorCodes.AgentCommandFailed, + "'claude plugin update nope@creativecoders-shade-kit --scope user --json' failed: claude exited with " + + "the exit code 1 and reported the outcome 'failed': Plugin \"nope\" not found (failure code " + + "'not_found'). Fix the cause that claude names, make sure Claude Code is up to date ('claude " + + "update'), then run the command again.")); + } + + [Fact] + public void Map_NoAgentFound_ReturnsExitCode51NamingSupportedAgentsAndInstallHint() + { + // Arrange + var mapper = CreateMapper(); + + // Act + var error = mapper.Map(new NoAgentFoundException(["claude"])); + + // Assert + error + .Should().Be(new CliError(ShadeKitCliExitCodes.AgentNotFound, ShadeKitCliErrorCodes.AgentNotFound, + "No supported agent was found (supported: claude). SHADE kit detects Claude Code by its CLI " + + "'claude' in an absolute directory of the PATH. Install a supported agent, then run the command " + + "again. On Windows only the 'claude.exe' of the native installer of Claude Code is found; the " + + "'claude.cmd' of an npm installation is not.")); + } + + [Theory] + [InlineData(new string[0], "none")] + [InlineData(new[] { "claude", "codex" }, "claude, codex")] + public void Map_NoAgentFoundWithOtherAgentLists_NamesSupportedAgents(string[] agentIds, string expectedText) + { + // Arrange + var mapper = CreateMapper(); + + // Act + var error = mapper.Map(new NoAgentFoundException(agentIds)); + + // Assert + error!.Message + .Should().StartWith($"No supported agent was found (supported: {expectedText})."); + } + + [Fact] + public void Map_IntegrationIncompleteWithClaudeUnavailable_KeepsExitCode52AndAddsRepairHint() + { + // Arrange + var mapper = CreateMapper(); + + // Act + var error = mapper.Map(new IntegrationIncompleteException("claude", + new ClaudeUnavailableException(["plugin", "update"], "Cannot start."))); + + // Assert + error!.ExitCode + .Should().Be(ShadeKitCliExitCodes.AgentCommandFailed); + + error.Message + .Should().StartWith("'claude plugin update' cannot be run: Cannot start.") + .And.EndWith("'shade-kit integrations install' repairs it."); + } + + [Fact] + public void Map_IntegrationConflict_ReturnsExitCode53NamingSourcesAndRemoveCommand() + { + // Arrange + var mapper = CreateMapper(); + + // Act + var error = mapper.Map(new IntegrationConflictException("claude", "creativecoders-shade-kit", + "other/shade-kit#main", "CreativeCodersTeam/shade-kit#v0.8.0", + "claude plugin marketplace remove creativecoders-shade-kit")); + + // Assert + error + .Should().Be(new CliError(ShadeKitCliExitCodes.IntegrationConflict, + ShadeKitCliErrorCodes.IntegrationConflict, + "The plugin marketplace 'creativecoders-shade-kit' of the agent 'claude' already exists with the " + + "source 'other/shade-kit#main', but SHADE kit needs 'CreativeCodersTeam/shade-kit#v0.8.0'. Nothing " + + "was changed. Run 'claude plugin marketplace remove creativecoders-shade-kit' to remove it, then " + + "run the command again.")); + } + + [Fact] + public void Map_IntegrationIncompleteWithCommandFailure_KeepsExitCode52AndAddsRepairHint() + { + // Arrange + var mapper = CreateMapper(); + var failure = new ClaudeCommandFailedException( + ["plugin", "marketplace", "add", "CreativeCodersTeam/shade-kit#v0.8.0", "--scope", "user", "--json"], 1, + "claude exited with the exit code 1."); + + // Act + var error = mapper.Map(new IntegrationIncompleteException("claude", failure)); + + // Assert + error + .Should().Be(new CliError(ShadeKitCliExitCodes.AgentCommandFailed, + ShadeKitCliErrorCodes.AgentCommandFailed, + "'claude plugin marketplace add CreativeCodersTeam/shade-kit#v0.8.0 --scope user --json' failed: " + + "claude exited with the exit code 1. Fix the cause that claude names, make sure Claude Code is up " + + "to date ('claude update'), then run the command again. The plugin marketplace of SHADE kit was " + + "already switched, so the integration may be incomplete; 'shade-kit integrations install' repairs " + + "it.")); + } + + [Fact] + public void Map_IntegrationIncompleteWithClaudeNotFound_KeepsExitCode51() + { + // Arrange + var mapper = CreateMapper(); + + // Act + var error = mapper.Map(new IntegrationIncompleteException("claude", + new ClaudeNotFoundException(["plugin", "list", "--json"], "Not on the PATH."))); + + // Assert + error!.ExitCode + .Should().Be(ShadeKitCliExitCodes.AgentNotFound); + + error.Message + .Should().EndWith("'shade-kit integrations install' repairs it."); + } + + [Fact] + public void Map_IntegrationIncompleteWithUnmappedCause_ReturnsExitCode52NamingCauseAndRepairHint() + { + // Arrange + var mapper = CreateMapper(); + + // Act + var error = mapper.Map(new IntegrationIncompleteException("claude", new IOException("Disk full"))); + + // Assert + error + .Should().Be(new CliError(ShadeKitCliExitCodes.AgentCommandFailed, + ShadeKitCliErrorCodes.AgentCommandFailed, + "The SHADE kit integration of the agent 'claude' failed: Disk full. The plugin marketplace of SHADE " + + "kit was already switched, so the integration may be incomplete; 'shade-kit integrations install' " + + "repairs it.")); + } + + [Fact] + public void Map_IntegrationSwitchCanceled_ReturnsExitCode130WithRepairHint() + { + // Arrange + var mapper = CreateMapper(); + + // Act + var error = mapper.Map(new IntegrationSwitchCanceledException("claude", + new OperationCanceledException(new CancellationToken(true)))); + + // Assert + error + .Should().Be(new CliError(ShadeKitCliExitCodes.Canceled, ShadeKitCliErrorCodes.Canceled, + "The command was canceled while the plugin marketplace of SHADE kit was switched for the agent " + + "'claude', so the integration may be incomplete; 'shade-kit integrations install' repairs it.")); + } + + [Fact] + public void Map_IntegrationRunFailedWithCommandFailure_KeepsExitCodeAndMessageAndNamesCompletedAgents() + { + // Arrange + var mapper = CreateMapper(); + var failure = new ClaudeCommandFailedException(["plugin", "install", "--json"], 1, "claude failed."); + IntegrationResult[] completed = + [ + new IntegrationResult("claude", "shade-kit@creativecoders-shade-kit", IntegrationOutcome.Updated, "0.7.0", + "0.8.0", "v0.8.0", true), + new IntegrationResult("codex", "shade-kit", IntegrationOutcome.Current, null, "0.8.0", "v0.8.0", true) + ]; + + // Act + var error = mapper.Map(new IntegrationRunFailedException("copilot", + MarketplaceSource.ForGitHub("CreativeCodersTeam/shade-kit", "v0.8.0"), completed, failure)); + + // Assert + error + .Should().Be(new CliError(ShadeKitCliExitCodes.AgentCommandFailed, + ShadeKitCliErrorCodes.AgentCommandFailed, + $"{mapper.Map(failure)!.Message} Before the agent 'copilot' failed, these integrations were done: " + + "claude: updated shade-kit@creativecoders-shade-kit 0.7.0 -> 0.8.0 (v0.8.0); codex: already current " + + "shade-kit 0.8.0 (v0.8.0).")); + } + + [Fact] + public void Map_IntegrationRunFailedWithConflict_KeepsExitCode53() + { + // Arrange + var mapper = CreateMapper(); + + // Act + var error = mapper.Map(new IntegrationRunFailedException("copilot", + MarketplaceSource.ForGitHub("CreativeCodersTeam/shade-kit", "v0.8.0"), + [new IntegrationResult("claude", "p", IntegrationOutcome.Installed, null, "0.8.0", "v0.8.0", true)], + new IntegrationConflictException("copilot", "m", "a", "b", "c"))); + + // Assert + error!.ExitCode + .Should().Be(ShadeKitCliExitCodes.IntegrationConflict); + + error.Code + .Should().Be(ShadeKitCliErrorCodes.IntegrationConflict); + } + + [Fact] + public void Map_IntegrationRunFailedWithDirectorySourceAndBrackets_NamesPathAsPlainText() + { + // Arrange + var mapper = CreateMapper(); + var path = Path.Combine(Path.GetTempPath(), "[kit]"); + + // Act + var error = mapper.Map(new IntegrationRunFailedException("copilot", MarketplaceSource.ForDirectory(path), + [new IntegrationResult("claude", "p", IntegrationOutcome.Installed, null, null, null, true)], + new ClaudeCommandFailedException(["plugin"], 1, "failed."))); + + // Assert + error!.Message + .Should().EndWith($"these integrations were done: claude: installed p from {path}.", + "the message is plain text; markup is added only when it is printed"); + } + + [Fact] + public void Map_IntegrationRunFailedWithIncompleteSwitch_AddsRepairHintBeforeCompletedAgents() + { + // Arrange + var mapper = CreateMapper(); + + // Act + var error = mapper.Map(new IntegrationRunFailedException("copilot", + MarketplaceSource.ForGitHub("CreativeCodersTeam/shade-kit", "v0.8.0"), + [new IntegrationResult("claude", "p", IntegrationOutcome.Installed, null, "0.8.0", "v0.8.0", true)], + new IntegrationIncompleteException("copilot", + new ClaudeNotFoundException(["plugin", "list", "--json"], "Not on the PATH.")))); + + // Assert + error!.ExitCode + .Should().Be(ShadeKitCliExitCodes.AgentNotFound); + + error.Message + .Should().EndWith("'shade-kit integrations install' repairs it. Before the agent 'copilot' failed, " + + "these integrations were done: claude: installed p 0.8.0 (v0.8.0)."); + } + + [Fact] + public void Map_IntegrationRunFailedWithoutCompletedAgents_ReturnsInnerErrorUnchanged() + { + // Arrange + var mapper = CreateMapper(); + var failure = new ClaudeCommandFailedException(["plugin"], 1, "failed."); + + // Act + var error = mapper.Map(new IntegrationRunFailedException("copilot", + MarketplaceSource.ForGitHub("CreativeCodersTeam/shade-kit", "v0.8.0"), [], failure)); + + // Assert + error + .Should().Be(mapper.Map(failure)); + } + + [Fact] + public void Map_IntegrationRunFailedWithoutInnerException_ReturnsExitCode52() + { + // Arrange + var mapper = CreateMapper(); + + // Act + var error = mapper.Map(new IntegrationRunFailedException("copilot", + MarketplaceSource.ForGitHub("CreativeCodersTeam/shade-kit", "v0.8.0"), + [new IntegrationResult("claude", "p", IntegrationOutcome.Installed, null, "0.8.0", "v0.8.0", true)], + null!)); + + // Assert + error!.ExitCode + .Should().Be(ShadeKitCliExitCodes.AgentCommandFailed); + + error.Message + .Should().StartWith("The SHADE kit integration of the agent 'copilot' failed: ") + .And.EndWith("these integrations were done: claude: installed p 0.8.0 (v0.8.0)."); + } + + [Fact] + public void Map_IntegrationRunFailedWithUnmappedCause_ReturnsExitCode52NamingCauseAndCompletedAgents() + { + // Arrange + var mapper = CreateMapper(); + + // Act + var error = mapper.Map(new IntegrationRunFailedException("copilot", + MarketplaceSource.ForGitHub("CreativeCodersTeam/shade-kit", "v0.8.0"), + [new IntegrationResult("claude", "p", IntegrationOutcome.Installed, null, "0.8.0", "v0.8.0", true)], + new IOException("Disk full"))); + + // Assert + error + .Should().Be(new CliError(ShadeKitCliExitCodes.AgentCommandFailed, + ShadeKitCliErrorCodes.AgentCommandFailed, + "The SHADE kit integration of the agent 'copilot' failed: Disk full. Before the agent 'copilot' " + + "failed, these integrations were done: claude: installed p 0.8.0 (v0.8.0).")); + } + + [Fact] + public void Map_InvalidMarketplaceSource_ReturnsExitCode2NamingVariableAndAllowedForms() + { + // Arrange + var mapper = CreateMapper(); + + // Act + var error = mapper.Map(new InvalidMarketplaceSourceException("-x", + "The value starts with '-', so the agent CLI would read it as an option.")); + + // Assert + error + .Should().Be(new CliError(ShadeKitCliExitCodes.InvalidArguments, ShadeKitCliErrorCodes.InvalidArguments, + "The environment variable SHADE_KIT_MARKETPLACE_SOURCE is set to '-x', which is not a marketplace " + + "source: The value starts with '-', so the agent CLI would read it as an option. Set it to " + + "owner/repo#ref, owner/repo, or the path of a local directory, or remove it, then run the command " + + "again.")); + } + [Fact] public void Map_UnexpectedException_ReturnsNull() { @@ -1518,6 +1896,57 @@ public void MapWarning_EnginePrereleaseVersionMismatch_ReturnsPrereleaseWarningN "differ); it is used anyway because it is a prerelease.")); } + [Fact] + public void MapWarning_IntegrationPrereleaseRef_ReturnsWarningNamingEngineAndBranch() + { + // Act + var warning = CliErrorMapper.MapWarning(new IntegrationPrereleaseRefWarning("0.8.0-beta.1", "main")); + + // Assert + warning + .Should().Be(new CliJsonMessage(ShadeKitCliWarningCodes.IntegrationPrereleaseRef, + "The engine 0.8.0-beta.1 is a prerelease, so the integrations come from the branch 'main' of " + + "CreativeCodersTeam/shade-kit instead of a release tag; they may not fit this engine.")); + } + + [Fact] + public void MapWarning_IntegrationReleaseTagMissing_ReturnsWarningNamingEngineTagAndBranch() + { + // Act + var warning = CliErrorMapper.MapWarning(new IntegrationReleaseTagMissingWarning("0.8.1", "v0.8.1", "main")); + + // Assert + warning + .Should().Be(new CliJsonMessage(ShadeKitCliWarningCodes.IntegrationReleaseTagMissing, + "The release tag 'v0.8.1' of the engine 0.8.1 does not exist in CreativeCodersTeam/shade-kit, so " + + "the integrations come from the branch 'main' instead; they may not fit this engine.")); + } + + [Fact] + public void MapWarning_AgentUnavailable_ReturnsWarningNamingAgentAndReason() + { + // Act + var warning = CliErrorMapper.MapWarning(new AgentUnavailableWarning("claude", + "The claude command 'claude plugin list --json' cannot be run: Not on the PATH.")); + + // Assert + warning + .Should().Be(new CliJsonMessage(ShadeKitCliWarningCodes.AgentUnavailable, + "The SHADE kit integration of the agent 'claude' cannot be read, so it is not listed: The claude " + + "command 'claude plugin list --json' cannot be run: Not on the PATH.")); + } + + [Fact] + public void MapWarning_AgentUnavailableWithReasonWithoutPeriod_EndsWithPeriod() + { + // Act + var warning = CliErrorMapper.MapWarning(new AgentUnavailableWarning("claude", "Not on the PATH")); + + // Assert + warning.Message + .Should().EndWith("so it is not listed: Not on the PATH."); + } + [Fact] public void MapWarning_EveryConcreteCoreWarning_ReturnsCodeAndEveryWarningCodeOnce() { @@ -1791,6 +2220,52 @@ public void MapArgumentError_ExpectedVersionMissing_ReturnsInvalidArgumentsWithG "Run 'shade-kit version --help' for usage.")); } + [Fact] + public void MapArgumentError_InvalidAgentOptionWithUnknownId_ReturnsInvalidArgumentsNamingSupportedAgents() + { + // Arrange + var exception = new InvalidAgentOptionException("copilot", ["claude"]); + + // Act + var error = CliErrorMapper.MapArgumentError(exception, ["integrations", "install", "--agent", "copilot"]); + + // Assert + error + .Should().Be(new CliError(ShadeKitCliExitCodes.InvalidArguments, ShadeKitCliErrorCodes.InvalidArguments, + "Invalid arguments: 'copilot' is not a supported agent for --agent (supported: claude). Run " + + "'shade-kit integrations install --help' for usage.")); + } + + [Fact] + public void MapArgumentError_InvalidAgentOptionWithSeveralSupportedAgents_JoinsTheirIds() + { + // Arrange + var exception = new InvalidAgentOptionException("x", ["claude", "codex"]); + + // Act + var error = CliErrorMapper.MapArgumentError(exception, ["integrations", "install", "--agent", "x"]); + + // Assert + error!.Message + .Should().StartWith("Invalid arguments: 'x' is not a supported agent for --agent (supported: claude, codex)."); + } + + [Fact] + public void MapArgumentError_InvalidAgentOptionWithoutValue_ReturnsInvalidArgumentsWithGotNone() + { + // Arrange + var exception = new InvalidAgentOptionException(null, ["claude"]); + + // Act + var error = CliErrorMapper.MapArgumentError(exception, ["integrations", "install", "--agent"]); + + // Assert + error + .Should().Be(new CliError(ShadeKitCliExitCodes.InvalidArguments, ShadeKitCliErrorCodes.InvalidArguments, + "Invalid arguments: --agent needs the id of a supported agent (claude), but got none. Run " + + "'shade-kit integrations install --help' for usage.")); + } + [Fact] public void MapArgumentError_NoArgumentListedAsNotMatching_ReturnsGenericText() { diff --git a/tests/CreativeCoders.ShadeKit.Cli.Tests/ProgramTests.cs b/tests/CreativeCoders.ShadeKit.Cli.Tests/ProgramTests.cs index d83110c..c8e10db 100644 --- a/tests/CreativeCoders.ShadeKit.Cli.Tests/ProgramTests.cs +++ b/tests/CreativeCoders.ShadeKit.Cli.Tests/ProgramTests.cs @@ -2,11 +2,13 @@ using System.Runtime.Versioning; using System.Text; using System.Text.Json; +using System.Text.RegularExpressions; using AwesomeAssertions; using CreativeCoders.ShadeKit.Cli.Commands.Feature.Show; using CreativeCoders.ShadeKit.Cli.Output; using CreativeCoders.ShadeKit.Core.Engine; using CreativeCoders.ShadeKit.Core.Git; +using CreativeCoders.ShadeKit.Core.Integrations; using CreativeCoders.ShadeKit.Tests.Shared; using CreativeCoders.SysConsole.Cli.Parsing; using CreativeCoders.SysConsole.Cli.Parsing.Exceptions; @@ -43,7 +45,7 @@ public async Task RunAsync_VersionJson_WritesOnlyOneEnvelopeToStandardOutput() using var error = new StringWriter(); // Act - var exitCode = await Program.RunAsync(["version", "--json"], output, error); + var exitCode = await RunProgramAsync(["version", "--json"], output, error); // Assert exitCode @@ -55,7 +57,7 @@ public async Task RunAsync_VersionJson_WritesOnlyOneEnvelopeToStandardOutput() .Should().BeTrue(); document.RootElement.GetProperty("data").GetProperty("formats").EnumerateObject().Select(x => x.Name) - .Should().Equal("config", "gates", "feature", "current-feature", "templates-lock", "integrations"); + .Should().Equal("config", "gates", "feature", "current-feature", "templates-lock"); error.ToString() .Should().BeNullOrWhiteSpace("the host writes only its empty footer line to standard error"); @@ -69,7 +71,7 @@ public async Task RunAsync_VersionPlain_WritesToolNameAndVersion() using var error = new StringWriter(); // Act - var exitCode = await Program.RunAsync(["version"], output, error); + var exitCode = await RunProgramAsync(["version"], output, error); // Assert exitCode @@ -89,7 +91,7 @@ public async Task RunAsync_VersionJsonExpectMismatchWithReleaseEngine_WritesOnly using var error = new StringWriter(); // Act - var exitCode = await Program.RunAsync(["version", "--json", "--expect", "1.3.0"], output, error, + var exitCode = await RunProgramAsync(["version", "--json", "--expect", "1.3.0"], output, error, x => x.AddSingleton(CreateEngineVersionProvider("1.2.3"))); // Assert @@ -128,7 +130,7 @@ public async Task RunAsync_VersionPlainExpectMismatchWithReleaseEngine_WritesOnl using var error = new StringWriter(); // Act - var exitCode = await Program.RunAsync(["version", "--expect", "1.1.0"], output, error, + var exitCode = await RunProgramAsync(["version", "--expect", "1.1.0"], output, error, x => x.AddSingleton(CreateEngineVersionProvider("1.2.3"))); // Assert @@ -136,10 +138,11 @@ public async Task RunAsync_VersionPlainExpectMismatchWithReleaseEngine_WritesOnl .Should().Be(ShadeKitCliExitCodes.VersionMismatch); // In plain mode the host prints the abort message to the console of the run, which writes to standard output - // and wraps long lines; removing the line ends joins the wrapped lines again. - output.ToString().ReplaceLineEndings(string.Empty) + // and wraps long lines at spaces; folding the whitespace joins the wrapped lines again. + Regex.Replace(output.ToString(), @"\s+", " ").TrimEnd() .Should().Be("The SHADE kit engine 1.2.3 does not fit the kit skills 1.1.0: the major and minor versions " + - "must be equal. Update the SHADE kit skills to 1.2 by hand, then run the skill again."); + "must be equal. Run 'shade-kit integrations install' to install the SHADE kit skills 1.2, " + + "then run the skill again."); output.ToString() .Should().NotContain("shade-kit 1.2.3"); @@ -157,7 +160,7 @@ public async Task RunAsync_VersionJsonExpectMismatchWithPrereleaseEngine_WritesS using var error = new StringWriter(); // Act - var exitCode = await Program.RunAsync(["version", "--json", "--expect", "99.0.0"], output, error, + var exitCode = await RunProgramAsync(["version", "--json", "--expect", "99.0.0"], output, error, x => x.AddSingleton(CreateEngineVersionProvider("1.2.3-beta.1"))); // Assert @@ -188,7 +191,7 @@ public async Task RunAsync_VersionJsonExpectNotSemVer_WritesOnlyInvalidArguments using var error = new StringWriter(); // Act - var exitCode = await Program.RunAsync(["version", "--json", "--expect", expect], output, error); + var exitCode = await RunProgramAsync(["version", "--json", "--expect", expect], output, error); // Assert exitCode @@ -213,7 +216,7 @@ public async Task RunAsync_VersionJsonExpectWithoutValue_WritesOnlyInvalidArgume using var error = new StringWriter(); // Act - var exitCode = await Program.RunAsync(args, output, error, + var exitCode = await RunProgramAsync(args, output, error, x => x.AddSingleton(CreateEngineVersionProvider("1.2.3"))); // Assert @@ -240,7 +243,7 @@ public async Task RunAsync_VersionPlainExpectWithoutValue_WritesMessageToStandar using var error = new StringWriter(); // Act - var exitCode = await Program.RunAsync(["version", "--expect"], output, error, + var exitCode = await RunProgramAsync(["version", "--expect"], output, error, x => x.AddSingleton(CreateEngineVersionProvider("1.2.3"))); // Assert @@ -263,7 +266,7 @@ public async Task RunAsync_VersionJsonExpectMatchingVersion_WritesSuccessEnvelop using var error = new StringWriter(); // Act - var exitCode = await Program.RunAsync(["version", "--json", "--expect", "1.2.0"], output, error, + var exitCode = await RunProgramAsync(["version", "--json", "--expect", "1.2.0"], output, error, x => x.AddSingleton(CreateEngineVersionProvider("1.2.3"))); // Assert @@ -375,7 +378,7 @@ public async Task RunAsync_ServiceRegisteredByHook_ReplacesDefaultService() using var error = new StringWriter(); // Act - var exitCode = await Program.RunAsync(["version", "--json"], output, error, + var exitCode = await RunProgramAsync(["version", "--json"], output, error, x => x.AddSingleton(engineVersionProvider)); // Assert @@ -397,7 +400,7 @@ public async Task RunAsync_HookWithoutRegistrations_UsesDefaultServices() var hookCalls = 0; // Act - var exitCode = await Program.RunAsync(["version", "--json"], output, error, _ => hookCalls++); + var exitCode = await RunProgramAsync(["version", "--json"], output, error, _ => hookCalls++); // Assert exitCode @@ -421,7 +424,7 @@ public async Task RunAsync_HookRegistersConsole_KeepsConsoleOfTheRun() using var error = new StringWriter(); // Act - var exitCode = await Program.RunAsync(["version"], output, error, + var exitCode = await RunProgramAsync(["version"], output, error, x => x.AddSingleton(hookConsole)); // Assert @@ -445,7 +448,7 @@ public async Task RunAsync_HookRegistersJsonWriter_KeepsJsonWriterOfTheRunAndWri using var error = new StringWriter(); // Act - var exitCode = await Program.RunAsync(["version", "--json"], output, error, + var exitCode = await RunProgramAsync(["version", "--json"], output, error, x => x.AddSingleton(hookJsonWriter)); // Assert @@ -470,7 +473,7 @@ public async Task RunAsync_HookThrowsInJsonMode_WritesHostErrorEnvelopeAndDetail using var error = new StringWriter(); // Act - var exitCode = await Program.RunAsync(["version", "--json"], output, error, + var exitCode = await RunProgramAsync(["version", "--json"], output, error, _ => throw new InvalidOperationException("hook failed")); // Assert @@ -496,7 +499,7 @@ public async Task RunAsync_UnknownCommandJson_WritesHostErrorEnvelopeAndReturns2 using var error = new StringWriter(); // Act - var exitCode = await Program.RunAsync(["unknown-command", "--json"], output, error); + var exitCode = await RunProgramAsync(["unknown-command", "--json"], output, error); // Assert exitCode @@ -533,7 +536,7 @@ public async Task RunAsync_JsonSwitchWithValueTheParserReadsAsFalse_UsesPlainMod using var error = new StringWriter(); // Act - var exitCode = await Program.RunAsync(["version", .. jsonArgs], output, error); + var exitCode = await RunProgramAsync(["version", .. jsonArgs], output, error); // Assert exitCode @@ -552,7 +555,7 @@ public async Task RunAsync_JsonSwitchBeforeCommand_TakesCommandAsSwitchValueAndR using var error = new StringWriter(); // Act - var exitCode = await Program.RunAsync(["--json", "version"], output, error); + var exitCode = await RunProgramAsync(["--json", "version"], output, error); // Assert exitCode @@ -572,7 +575,7 @@ public async Task RunAsync_JsonSwitchWithExtraLeadingDash_UsesJsonModeLikeThePar using var error = new StringWriter(); // Act - var exitCode = await Program.RunAsync(["version", "---json"], output, error); + var exitCode = await RunProgramAsync(["version", "---json"], output, error); // Assert exitCode @@ -596,7 +599,7 @@ public async Task RunAsync_JsonAssignmentTheParserDoesNotRead_WritesHostErrorEnv using var error = new StringWriter(); // Act - var exitCode = await Program.RunAsync(args, output, error); + var exitCode = await RunProgramAsync(args, output, error); // Assert exitCode @@ -617,7 +620,7 @@ public async Task RunAsync_FalseAssignmentBeforeBareJsonSwitch_FollowsBareSwitch using var error = new StringWriter(); // Act - var exitCode = await Program.RunAsync(["version", "--json=false", "--json"], output, error); + var exitCode = await RunProgramAsync(["version", "--json=false", "--json"], output, error); // Assert exitCode @@ -642,7 +645,7 @@ public async Task RunAsync_JsonSwitchTwice_WritesSuccessEnvelope() using var error = new StringWriter(); // Act - var exitCode = await Program.RunAsync(["version", "--json", "--json"], output, error); + var exitCode = await RunProgramAsync(["version", "--json", "--json"], output, error); // Assert exitCode @@ -663,7 +666,7 @@ public async Task RunAsync_JsonSwitchWithTrueValue_UsesJsonMode() using var error = new StringWriter(); // Act - var exitCode = await Program.RunAsync(["version", "--json", "true"], output, error); + var exitCode = await RunProgramAsync(["version", "--json", "true"], output, error); // Assert exitCode @@ -696,7 +699,7 @@ public async Task RunAsync_UnexpectedExceptionJson_WritesHostErrorEnvelopeAndDet try { // Act - var exitCode = await Program.RunAsync(["feature", "list", "--json"], output, error); + var exitCode = await RunProgramAsync(["feature", "list", "--json"], output, error); // Assert exitCode @@ -728,7 +731,7 @@ public async Task RunAsync_UnknownCommandPlain_ReturnsHostErrorWithoutJson() using var error = new StringWriter(); // Act - var exitCode = await Program.RunAsync(["unknown-command"], output, error); + var exitCode = await RunProgramAsync(["unknown-command"], output, error); // Assert exitCode @@ -752,7 +755,7 @@ public async Task RunAsync_FeatureListJsonInRepositoryWithoutKitRoot_WritesKitRo using var error = new StringWriter(); // Act - var exitCode = await Program.RunAsync(["feature", "list", "--json"], output, error); + var exitCode = await RunProgramAsync(["feature", "list", "--json"], output, error); // Assert exitCode @@ -784,7 +787,7 @@ public async Task RunAsync_FeatureListJsonInSubdirectoryOfInitialisedRepository_ using var error = new StringWriter(); // Act - var exitCode = await Program.RunAsync(["feature", "list", "--json"], output, error); + var exitCode = await RunProgramAsync(["feature", "list", "--json"], output, error); // Assert exitCode @@ -809,7 +812,7 @@ public async Task RunAsync_FeatureListPlainInRepositoryWithoutKitRoot_PrintsInit using var error = new StringWriter(); // Act - var exitCode = await Program.RunAsync(["feature", "list"], output, error); + var exitCode = await RunProgramAsync(["feature", "list"], output, error); // Assert exitCode @@ -830,7 +833,7 @@ public async Task RunAsync_HelpInJsonMode_WritesHostErrorEnvelopeAndHelpToStanda using var error = new StringWriter(); // Act - var exitCode = await Program.RunAsync(args, output, error); + var exitCode = await RunProgramAsync(args, output, error); // Assert exitCode @@ -854,7 +857,7 @@ public async Task RunAsync_JsonSwitchWithoutCommand_WritesHostErrorEnvelope() using var error = new StringWriter(); // Act - var exitCode = await Program.RunAsync(["--json"], output, error); + var exitCode = await RunProgramAsync(["--json"], output, error); // Assert exitCode @@ -874,7 +877,7 @@ public async Task RunAsync_JsonWithUnknownOption_IgnoresOptionAndWritesSuccessEn using var error = new StringWriter(); // Act - var exitCode = await Program.RunAsync(["version", "--json", "--bogus"], output, error); + var exitCode = await RunProgramAsync(["version", "--json", "--bogus"], output, error); // Assert exitCode @@ -895,7 +898,7 @@ public async Task RunAsync_VersionJson_WritesExactlyOneDocumentFollowedByOneLine using var error = new StringWriter(); // Act - await Program.RunAsync(["version", "--json"], output, error); + await RunProgramAsync(["version", "--json"], output, error); // Assert var text = output.ToString(); @@ -916,7 +919,7 @@ public async Task RunAsync_FeatureListJsonWithoutFeaturesDirectory_WritesEmptyFe using var error = new StringWriter(); // Act - var exitCode = await Program.RunAsync(["feature", "list", "--json"], output, error); + var exitCode = await RunProgramAsync(["feature", "list", "--json"], output, error); // Assert exitCode @@ -946,7 +949,7 @@ public async Task RunAsync_FeatureListPlainWithoutFeaturesDirectory_PrintsNoFeat using var error = new StringWriter(); // Act - var exitCode = await Program.RunAsync(["feature", "list"], output, error); + var exitCode = await RunProgramAsync(["feature", "list"], output, error); // Assert exitCode @@ -972,7 +975,7 @@ public async Task RunAsync_FeatureListPlainInInitialisedRepository_PrintsFeature using var error = new StringWriter(); // Act - var exitCode = await Program.RunAsync(["feature", "list"], output, error); + var exitCode = await RunProgramAsync(["feature", "list"], output, error); // Assert exitCode @@ -1012,7 +1015,7 @@ public async Task RunAsync_UnexpectedExceptionPlain_ReturnsHostErrorWithDetailsO try { // Act - var exitCode = await Program.RunAsync(["feature", "list"], output, error); + var exitCode = await RunProgramAsync(["feature", "list"], output, error); // Assert exitCode @@ -1041,7 +1044,7 @@ public async Task RunAsync_JsonModeWithBrokenStandardOutput_ReturnsHostErrorWith using var error = new StringWriter(); // Act - var exitCode = await Program.RunAsync(["version", "--json"], output, error); + var exitCode = await RunProgramAsync(["version", "--json"], output, error); // Assert exitCode @@ -1061,7 +1064,7 @@ public async Task RunAsync_JsonModeFailingAfterSuccessEnvelope_ReturnsZeroToMatc await using var error = new BrokenTextWriter(); // Act - var exitCode = await Program.RunAsync(["version", "--json"], output, error); + var exitCode = await RunProgramAsync(["version", "--json"], output, error); // Assert exitCode @@ -1081,7 +1084,7 @@ public async Task RunAsync_PlainModeWithBrokenStandardOutputAndError_ReturnsHost await using var error = new BrokenTextWriter(); // Act - var exitCode = await Program.RunAsync(["version"], output, error); + var exitCode = await RunProgramAsync(["version"], output, error); // Assert exitCode @@ -1096,7 +1099,7 @@ public async Task RunAsync_FeatureShowWithoutIdPlain_WritesOneUsageLineToStandar using var error = new StringWriter(); // Act - var exitCode = await Program.RunAsync(["feature", "show"], output, error); + var exitCode = await RunProgramAsync(["feature", "show"], output, error); // Assert exitCode @@ -1119,7 +1122,7 @@ public async Task RunAsync_FeatureShowWithoutIdJson_WritesOneInvalidArgumentsEnv using var error = new StringWriter(); // Act - var exitCode = await Program.RunAsync(["feature", "show", "--json"], output, error); + var exitCode = await RunProgramAsync(["feature", "show", "--json"], output, error); // Assert exitCode @@ -1144,7 +1147,7 @@ public async Task RunAsync_FeatureNewWithoutSourcePlain_WritesOneUsageLineToStan using var error = new StringWriter(); // Act - var exitCode = await Program.RunAsync(["feature", "new", ..extraArgs], output, error, + var exitCode = await RunProgramAsync(["feature", "new", ..extraArgs], output, error, x => x.AddSingleton(gitCommandRunner)); // Assert @@ -1173,7 +1176,7 @@ public async Task RunAsync_FeatureNewWithoutSourceJson_WritesOneInvalidArguments using var error = new StringWriter(); // Act - var exitCode = await Program.RunAsync(["feature", "new", "--title", "Login", "--json"], output, error, + var exitCode = await RunProgramAsync(["feature", "new", "--title", "Login", "--json"], output, error, x => x.AddSingleton(gitCommandRunner)); // Assert @@ -1200,7 +1203,7 @@ public async Task RunAsync_ArgumentsMatchNoOptionJson_WritesOneInvalidArgumentsE using var error = new StringWriter(); // Act - var exitCode = await Program.RunAsync(["feature", "list", "--bogus", "--json"], output, error, + var exitCode = await RunProgramAsync(["feature", "list", "--bogus", "--json"], output, error, _ => throw new NotAllArgumentsMatchException( [new OptionArgument { Kind = OptionArgumentKind.LongName, OptionName = "bogus" }])); @@ -1222,7 +1225,7 @@ public async Task RunAsync_ArgumentsMatchNoOptionPlain_WritesOneUsageLineToStand using var error = new StringWriter(); // Act - var exitCode = await Program.RunAsync(["feature", "list", "extra"], output, error, + var exitCode = await RunProgramAsync(["feature", "list", "extra"], output, error, _ => throw new NotAllArgumentsMatchException( [new OptionArgument { Kind = OptionArgumentKind.Value, Value = "extra" }])); @@ -1250,7 +1253,7 @@ public async Task RunAsync_ParserExceptionWrappedInTargetInvocationPlain_WritesU using var error = new StringWriter(); // Act - var exitCode = await Program.RunAsync(["feature", "show"], output, error, + var exitCode = await RunProgramAsync(["feature", "show"], output, error, _ => throw new TargetInvocationException(parserException)); // Assert @@ -1274,7 +1277,7 @@ public async Task RunAsync_ArgumentErrorWithJsonSwitchValue_WritesOneInvalidArgu using var error = new StringWriter(); // Act - var exitCode = await Program.RunAsync(["feature", "show", ..jsonArgs], output, error); + var exitCode = await RunProgramAsync(["feature", "show", ..jsonArgs], output, error); // Assert exitCode @@ -1291,7 +1294,7 @@ public async Task RunAsync_ArgumentErrorWithJsonSwitchFalse_WritesUsageLineToSta using var error = new StringWriter(); // Act - var exitCode = await Program.RunAsync(["feature", "show", "--json", "false"], output, error); + var exitCode = await RunProgramAsync(["feature", "show", "--json", "false"], output, error); // Assert exitCode @@ -1314,7 +1317,7 @@ public async Task RunAsync_ArgumentErrorJsonWithBrokenStandardOutput_ReturnsHost using var error = new StringWriter(); // Act - var exitCode = await Program.RunAsync(["feature", "show", "--json"], output, error); + var exitCode = await RunProgramAsync(["feature", "show", "--json"], output, error); // Assert exitCode @@ -1332,7 +1335,7 @@ public async Task RunAsync_ArgumentErrorPlainWithBrokenStandardError_StillReturn await using var error = new BrokenTextWriter(); // Act - var exitCode = await Program.RunAsync(["feature", "show"], output, error); + var exitCode = await RunProgramAsync(["feature", "show"], output, error); // Assert exitCode @@ -1347,7 +1350,7 @@ public async Task RunAsync_OptionCreationFailedJson_StaysHostErrorWithDetailsOnS using var error = new StringWriter(); // Act - var exitCode = await Program.RunAsync(["feature", "show", "--json"], output, error, + var exitCode = await RunProgramAsync(["feature", "show", "--json"], output, error, _ => throw new OptionCreationFailedException(typeof(FeatureShowCommandOptions))); // Assert @@ -1369,6 +1372,28 @@ public void Dispose() _tempDirectory.Dispose(); } + // Runs the CLI like Program.RunAsync, but registers a fake integration service first: version reads the installed + // integrations, and the fake keeps every test from starting claude. Overrides of configureServices still win. + private static Task RunProgramAsync(string[] args, TextWriter output, TextWriter error, + Action? configureServices = null) + { + return Program.RunAsync(args, output, error, x => + { + x.AddSingleton(CreateIntegrationService()); + + configureServices?.Invoke(x); + }); + } + + private static IIntegrationService CreateIntegrationService() + { + var integrationService = A.Fake(); + A.CallTo(() => integrationService.GetInstalledAsync(A._)) + .Returns(new InstalledIntegrationsResult([], [])); + + return integrationService; + } + private static IEngineVersionProvider CreateEngineVersionProvider(string version) { var engineVersionProvider = A.Fake(); diff --git a/tests/CreativeCoders.ShadeKit.Cli.Tests/ShadeKitCliErrorCodesTests.cs b/tests/CreativeCoders.ShadeKit.Cli.Tests/ShadeKitCliErrorCodesTests.cs index fe2acfc..c72582c 100644 --- a/tests/CreativeCoders.ShadeKit.Cli.Tests/ShadeKitCliErrorCodesTests.cs +++ b/tests/CreativeCoders.ShadeKit.Cli.Tests/ShadeKitCliErrorCodesTests.cs @@ -36,6 +36,9 @@ public partial class ShadeKitCliErrorCodesTests [InlineData(ShadeKitCliErrorCodes.PhaseStateInvalid, "phase-state-invalid")] [InlineData(ShadeKitCliErrorCodes.ChecklistTemplateNotFound, "checklist-template-not-found")] [InlineData(ShadeKitCliErrorCodes.VersionMismatch, "version-mismatch")] + [InlineData(ShadeKitCliErrorCodes.AgentNotFound, "agent-not-found")] + [InlineData(ShadeKitCliErrorCodes.AgentCommandFailed, "agent-command-failed")] + [InlineData(ShadeKitCliErrorCodes.IntegrationConflict, "integration-conflict")] [InlineData(ShadeKitCliErrorCodes.Canceled, "canceled")] [InlineData(ShadeKitCliErrorCodes.HostError, "host-error")] public void ErrorCodes_Contract_HaveStableValues(string errorCode, string expectedErrorCode) @@ -79,7 +82,7 @@ public void ForExitCode_EveryExitCodeConstant_ReturnsErrorCodeWithSameName() [InlineData(1)] [InlineData(11)] [InlineData(49)] - [InlineData(51)] + [InlineData(58)] [InlineData(59)] [InlineData(256)] [InlineData(-1)] diff --git a/tests/CreativeCoders.ShadeKit.Cli.Tests/ShadeKitCliExitCodesTests.cs b/tests/CreativeCoders.ShadeKit.Cli.Tests/ShadeKitCliExitCodesTests.cs index 4be5640..a82f85a 100644 --- a/tests/CreativeCoders.ShadeKit.Cli.Tests/ShadeKitCliExitCodesTests.cs +++ b/tests/CreativeCoders.ShadeKit.Cli.Tests/ShadeKitCliExitCodesTests.cs @@ -56,6 +56,9 @@ public void ToProcessExitCode_NegativeHostExitCode_ReturnsHostError(int exitCode [InlineData(ShadeKitCliExitCodes.PhaseStateInvalid)] [InlineData(ShadeKitCliExitCodes.ChecklistTemplateNotFound)] [InlineData(ShadeKitCliExitCodes.VersionMismatch)] + [InlineData(ShadeKitCliExitCodes.AgentNotFound)] + [InlineData(ShadeKitCliExitCodes.AgentCommandFailed)] + [InlineData(ShadeKitCliExitCodes.IntegrationConflict)] [InlineData(ShadeKitCliExitCodes.Canceled)] [InlineData(ShadeKitCliExitCodes.HostError)] public void ToProcessExitCode_NonNegativeExitCode_ReturnsExitCodeUnchanged(int exitCode) @@ -99,6 +102,9 @@ public void ToProcessExitCode_NonNegativeExitCode_ReturnsExitCodeUnchanged(int e [InlineData(ShadeKitCliExitCodes.PhaseStateInvalid, 46)] [InlineData(ShadeKitCliExitCodes.ChecklistTemplateNotFound, 47)] [InlineData(ShadeKitCliExitCodes.VersionMismatch, 50)] + [InlineData(ShadeKitCliExitCodes.AgentNotFound, 51)] + [InlineData(ShadeKitCliExitCodes.AgentCommandFailed, 52)] + [InlineData(ShadeKitCliExitCodes.IntegrationConflict, 53)] [InlineData(ShadeKitCliExitCodes.Canceled, 130)] [InlineData(ShadeKitCliExitCodes.HostError, 255)] public void ExitCodes_Contract_HaveStableValues(int exitCode, int expectedExitCode) diff --git a/tests/CreativeCoders.ShadeKit.Cli.Tests/ShadeKitCliWarningCodesTests.cs b/tests/CreativeCoders.ShadeKit.Cli.Tests/ShadeKitCliWarningCodesTests.cs index b8dd40a..8fd9d72 100644 --- a/tests/CreativeCoders.ShadeKit.Cli.Tests/ShadeKitCliWarningCodesTests.cs +++ b/tests/CreativeCoders.ShadeKit.Cli.Tests/ShadeKitCliWarningCodesTests.cs @@ -16,6 +16,9 @@ public partial class ShadeKitCliWarningCodesTests [InlineData(ShadeKitCliWarningCodes.EditorConfigInvalid, "editorconfig-invalid")] [InlineData(ShadeKitCliWarningCodes.GitAttributesUnavailable, "git-attributes-unavailable")] [InlineData(ShadeKitCliWarningCodes.EnginePrereleaseVersionMismatch, "engine-prerelease-version-mismatch")] + [InlineData(ShadeKitCliWarningCodes.IntegrationPrereleaseRef, "integration-prerelease-ref")] + [InlineData(ShadeKitCliWarningCodes.IntegrationReleaseTagMissing, "integration-release-tag-missing")] + [InlineData(ShadeKitCliWarningCodes.AgentUnavailable, "agent-unavailable")] public void WarningCodes_Contract_HaveStableValues(string warningCode, string expectedWarningCode) { // Assert diff --git a/tests/CreativeCoders.ShadeKit.Core.Tests/Formats/FormatRegistryTests.cs b/tests/CreativeCoders.ShadeKit.Core.Tests/Formats/FormatRegistryTests.cs index f57d250..c3cf725 100644 --- a/tests/CreativeCoders.ShadeKit.Core.Tests/Formats/FormatRegistryTests.cs +++ b/tests/CreativeCoders.ShadeKit.Core.Tests/Formats/FormatRegistryTests.cs @@ -19,8 +19,7 @@ public void CreateDefault_Called_RegistersEveryFileTypeAtVersionOneInContractOrd (FormatIds.Gates, 1), (FormatIds.Feature, 1), (FormatIds.CurrentFeature, 1), - (FormatIds.TemplatesLock, 1), - (FormatIds.Integrations, 1)); + (FormatIds.TemplatesLock, 1)); } [Fact] @@ -42,7 +41,7 @@ public void CreateDefault_Called_UsesContractSpellingOfFormatIds() var ids = FormatRegistry.CreateDefault().Formats.Select(x => x.Id); // Assert - ids.Should().Equal("config", "gates", "feature", "current-feature", "templates-lock", "integrations"); + ids.Should().Equal("config", "gates", "feature", "current-feature", "templates-lock"); } [Fact] @@ -63,6 +62,7 @@ public void GetFormat_RegisteredId_ReturnsDefinition() [InlineData("unknown")] [InlineData("Config")] [InlineData("")] + [InlineData("integrations")] public void GetFormat_UnregisteredId_ThrowsArgumentException(string id) { // Arrange diff --git a/tests/CreativeCoders.ShadeKit.Core.Tests/Git/GitCommandRunnerTests.cs b/tests/CreativeCoders.ShadeKit.Core.Tests/Git/GitCommandRunnerTests.cs index 089815d..2d19f18 100644 --- a/tests/CreativeCoders.ShadeKit.Core.Tests/Git/GitCommandRunnerTests.cs +++ b/tests/CreativeCoders.ShadeKit.Core.Tests/Git/GitCommandRunnerTests.cs @@ -26,6 +26,35 @@ public void Constructor_NullGitExecutableLocator_ThrowsArgumentNullException() .WithParameterName("gitExecutableLocator"); } + [Fact] + public void EnvironmentVariables_Always_DisableTerminalAndAskpassPrompts() + { + // Act + var environmentVariables = GitCommandRunner.EnvironmentVariables; + + // Assert + environmentVariables + .Should().BeEquivalentTo(new Dictionary + { + ["GIT_TERMINAL_PROMPT"] = "0", + ["GIT_ASKPASS"] = string.Empty + }); + } + + [Fact] + public void Tool_Always_UsesGitNameAndEnvironmentVariables() + { + // Act + var tool = GitCommandRunner.Tool; + + // Assert + tool.Name + .Should().Be("git"); + + tool.EnvironmentVariables + .Should().BeSameAs(GitCommandRunner.EnvironmentVariables); + } + [Fact] public async Task RunAsync_GitNotFound_ThrowsGitUnavailableException() { diff --git a/tests/CreativeCoders.ShadeKit.Core.Tests/Git/GitRemoteTagCheckerTests.cs b/tests/CreativeCoders.ShadeKit.Core.Tests/Git/GitRemoteTagCheckerTests.cs new file mode 100644 index 0000000..268f753 --- /dev/null +++ b/tests/CreativeCoders.ShadeKit.Core.Tests/Git/GitRemoteTagCheckerTests.cs @@ -0,0 +1,302 @@ +using AwesomeAssertions; +using CreativeCoders.ShadeKit.Core.Git; +using CreativeCoders.ShadeKit.Core.Git.Exceptions; +using CreativeCoders.ShadeKit.Core.Processes; +using FakeItEasy; + +namespace CreativeCoders.ShadeKit.Core.Tests.Git; + +// The git runner is faked, so these tests never start git or reach the network. +public class GitRemoteTagCheckerTests +{ + private const string WorkingDirectory = "/home/me"; + + private const string RemoteUrl = "https://github.com/CreativeCodersTeam/shade-kit.git"; + + private static readonly string[] LsRemoteArguments = + [ + "-c", "credential.helper=", "-c", "protocol.allow=never", "-c", "protocol.https.allow=always", + "ls-remote", "--tags", RemoteUrl, "refs/tags/v0.8.0" + ]; + + private readonly IGitCommandRunner _gitCommandRunner = A.Fake(); + + [Fact] + public void Constructor_NullGitCommandRunner_ThrowsArgumentNullException() + { + // Act + var act = () => new GitRemoteTagChecker(null!); + + // Assert + act.Should().Throw() + .WithParameterName("gitCommandRunner"); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public void Constructor_InvalidWorkingDirectory_ThrowsArgumentException(string? workingDirectory) + { + // Act + var act = () => new GitRemoteTagChecker(_gitCommandRunner, workingDirectory!); + + // Assert + act.Should().Throw() + .WithParameterName(nameof(workingDirectory)); + } + + [Fact] + public void Constructor_DefaultWorkingDirectory_UsesExistingHomeOrTemporaryDirectory() + { + // Act + var sut = new GitRemoteTagChecker(_gitCommandRunner); + + // Assert + sut.WorkingDirectory + .Should().BeOneOf(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), Path.GetTempPath()); + } + + [Fact] + public async Task CheckTagAsync_Always_RunsLsRemoteWithoutCredentialHelpersAndOnlyHttpsInWorkingDirectory() + { + // Arrange + using var cancellationTokenSource = new CancellationTokenSource(); + _gitCommandRunner.SetUpResult(LsRemoteArguments, new ExternalProcessResult(0, string.Empty, string.Empty)); + var sut = CreateSut(); + + // Act + await sut.CheckTagAsync(RemoteUrl, "v0.8.0", cancellationTokenSource.Token); + + // Assert + A.CallTo(() => _gitCommandRunner.RunAsync(WorkingDirectory, + A>.That.IsSameSequenceAs(LsRemoteArguments), cancellationTokenSource.Token)) + .MustHaveHappenedOnceExactly(); + } + + [Theory] + [InlineData("4a1b2c3d\trefs/tags/v0.8.0\n")] + [InlineData("4a1b2c3d\trefs/tags/v0.8.0\r\n")] + [InlineData("4a1b2c3d\trefs/tags/v0.8.0\n9f8e7d6c\trefs/tags/v0.8.0^{}\n")] + [InlineData("9f8e7d6c\trefs/tags/v0.8.0^{}")] + public async Task CheckTagAsync_GitListsTag_ReturnsFound(string standardOutput) + { + // Arrange + _gitCommandRunner.SetUpResult(LsRemoteArguments, new ExternalProcessResult(0, standardOutput, string.Empty)); + var sut = CreateSut(); + + // Act + var state = await sut.CheckTagAsync(RemoteUrl, "v0.8.0", TestContext.Current.CancellationToken); + + // Assert + state + .Should().Be(GitRemoteTagState.Found); + } + + [Theory] + [InlineData("")] + [InlineData("\n")] + [InlineData("4a1b2c3d\trefs/tags/v0.8.0-beta.1\n")] + [InlineData("4a1b2c3d\trefs/heads/refs/tags/v0.8.0\n")] + [InlineData("4a1b2c3d refs/tags/v0.8.0\n")] + public async Task CheckTagAsync_GitListsNoMatchingTag_ReturnsMissing(string standardOutput) + { + // Arrange + _gitCommandRunner.SetUpResult(LsRemoteArguments, new ExternalProcessResult(0, standardOutput, string.Empty)); + var sut = CreateSut(); + + // Act + var state = await sut.CheckTagAsync(RemoteUrl, "v0.8.0", TestContext.Current.CancellationToken); + + // Assert + state + .Should().Be(GitRemoteTagState.Missing); + } + + [Theory] + [InlineData(1)] + [InlineData(2)] + [InlineData(128)] + [InlineData(-1)] + public async Task CheckTagAsync_GitFails_ReturnsUnknown(int exitCode) + { + // Arrange + _gitCommandRunner.SetUpResult(LsRemoteArguments, new ExternalProcessResult(exitCode, + "4a1b2c3d\trefs/tags/v0.8.0\n", "fatal: unable to access the repository")); + var sut = CreateSut(); + + // Act + var state = await sut.CheckTagAsync(RemoteUrl, "v0.8.0", TestContext.Current.CancellationToken); + + // Assert + state + .Should().Be(GitRemoteTagState.Unknown); + } + + [Fact] + public async Task CheckTagAsync_GitNotFound_ReturnsUnknown() + { + // Arrange + A.CallTo(() => _gitCommandRunner.RunAsync(A._, A>._, A._)) + .ThrowsAsync(new GitNotFoundException(LsRemoteArguments, "git was not found.")); + var sut = CreateSut(); + + // Act + var state = await sut.CheckTagAsync(RemoteUrl, "v0.8.0", TestContext.Current.CancellationToken); + + // Assert + state + .Should().Be(GitRemoteTagState.Unknown); + } + + [Fact] + public async Task CheckTagAsync_GitCannotBeStarted_ReturnsUnknown() + { + // Arrange + A.CallTo(() => _gitCommandRunner.RunAsync(A._, A>._, A._)) + .ThrowsAsync(new GitUnavailableException(LsRemoteArguments, "git could not be started.")); + var sut = CreateSut(); + + // Act + var state = await sut.CheckTagAsync(RemoteUrl, "v0.8.0", TestContext.Current.CancellationToken); + + // Assert + state + .Should().Be(GitRemoteTagState.Unknown); + } + + [Fact] + public async Task CheckTagAsync_CanceledWhileGitRuns_PropagatesCancellationInsteadOfUnknown() + { + // Arrange + using var cancellationTokenSource = new CancellationTokenSource(); + A.CallTo(() => _gitCommandRunner.RunAsync(A._, A>._, A._)) + .ReturnsLazily(async (string _, IReadOnlyList _, CancellationToken token) => + { + await Task.Delay(Timeout.Infinite, token); + + return new ExternalProcessResult(0, string.Empty, string.Empty); + }); + var sut = CreateSut(); + + // Act + var task = sut.CheckTagAsync(RemoteUrl, "v0.8.0", cancellationTokenSource.Token); + await cancellationTokenSource.CancelAsync(); + + // Assert + await task.Awaiting(x => x) + .Should().ThrowAsync(); + } + + [Fact] + public async Task CheckTagAsync_Canceled_PropagatesCancellation() + { + // Arrange + A.CallTo(() => _gitCommandRunner.RunAsync(A._, A>._, A._)) + .ThrowsAsync(new OperationCanceledException()); + var sut = CreateSut(); + + // Act + var act = () => sut.CheckTagAsync(RemoteUrl, "v0.8.0", TestContext.Current.CancellationToken); + + // Assert + await act.Should().ThrowAsync(); + } + + [Fact] + public async Task CheckTagAsync_UnexpectedFailure_PropagatesFailure() + { + // Arrange + A.CallTo(() => _gitCommandRunner.RunAsync(A._, A>._, A._)) + .ThrowsAsync(new IOException("Disk")); + var sut = CreateSut(); + + // Act + var act = () => sut.CheckTagAsync(RemoteUrl, "v0.8.0", TestContext.Current.CancellationToken); + + // Assert + await act.Should().ThrowAsync(); + } + + [Fact] + public async Task CheckTagAsync_NullRemoteUrl_ThrowsArgumentNullException() + { + // Arrange + var sut = CreateSut(); + + // Act + var act = () => sut.CheckTagAsync(null!, "v0.8.0", TestContext.Current.CancellationToken); + + // Assert + await act.Should().ThrowAsync() + .WithParameterName("remoteUrl"); + } + + [Fact] + public async Task CheckTagAsync_NullTagName_ThrowsArgumentNullException() + { + // Arrange + var sut = CreateSut(); + + // Act + var act = () => sut.CheckTagAsync(RemoteUrl, null!, TestContext.Current.CancellationToken); + + // Assert + await act.Should().ThrowAsync() + .WithParameterName("tagName"); + } + + [Theory] + [InlineData("")] + [InlineData("github.com/CreativeCodersTeam/shade-kit.git")] + [InlineData("http://github.com/CreativeCodersTeam/shade-kit.git")] + [InlineData("git@github.com:CreativeCodersTeam/shade-kit.git")] + [InlineData("--upload-pack=x")] + public async Task CheckTagAsync_RemoteUrlNotHttps_ThrowsArgumentExceptionWithoutRunningGit(string remoteUrl) + { + // Arrange + var sut = CreateSut(); + + // Act + var act = () => sut.CheckTagAsync(remoteUrl, "v0.8.0", TestContext.Current.CancellationToken); + + // Assert + await act.Should().ThrowAsync() + .WithParameterName(nameof(remoteUrl)); + + A.CallTo(_gitCommandRunner) + .MustNotHaveHappened(); + } + + [Theory] + [InlineData("")] + [InlineData("-v0.8.0")] + [InlineData("v0.8 .0")] + [InlineData("v0.*")] + [InlineData("v0.8.?")] + [InlineData("v[0]")] + [InlineData("v0\\8")] + [InlineData("v0.8.0^{}")] + [InlineData("v0.8.0~1")] + [InlineData("v0:8")] + public async Task CheckTagAsync_InvalidTagName_ThrowsArgumentExceptionWithoutRunningGit(string tagName) + { + // Arrange + var sut = CreateSut(); + + // Act + var act = () => sut.CheckTagAsync(RemoteUrl, tagName, TestContext.Current.CancellationToken); + + // Assert + await act.Should().ThrowAsync() + .WithParameterName(nameof(tagName)); + + A.CallTo(_gitCommandRunner) + .MustNotHaveHappened(); + } + + private GitRemoteTagChecker CreateSut() + { + return new GitRemoteTagChecker(_gitCommandRunner, WorkingDirectory); + } +} diff --git a/tests/CreativeCoders.ShadeKit.Core.Tests/Integrations/Claude/ClaudeCodeIntegrationTests.cs b/tests/CreativeCoders.ShadeKit.Core.Tests/Integrations/Claude/ClaudeCodeIntegrationTests.cs new file mode 100644 index 0000000..25246ee --- /dev/null +++ b/tests/CreativeCoders.ShadeKit.Core.Tests/Integrations/Claude/ClaudeCodeIntegrationTests.cs @@ -0,0 +1,1817 @@ +using AwesomeAssertions; +using CreativeCoders.ShadeKit.Core.Integrations; +using CreativeCoders.ShadeKit.Core.Integrations.Claude; +using CreativeCoders.ShadeKit.Core.Integrations.Exceptions; +using CreativeCoders.ShadeKit.Tests.Shared; +using FakeItEasy; + +namespace CreativeCoders.ShadeKit.Core.Tests.Integrations.Claude; + +// The plugin CLI is faked, so these tests never start claude. +public class ClaudeCodeIntegrationTests +{ + private const string PluginId = "shade-kit@creativecoders-shade-kit"; + + private const string MarketplaceName = "creativecoders-shade-kit"; + + private const string Repo = "CreativeCodersTeam/shade-kit"; + + // Replaced by an absolute path of the current operating system. + private const string OtherPath = ""; + + private static readonly MarketplaceSource ReleaseSource = MarketplaceSource.ForGitHub(Repo, "v0.8.0"); + + private static readonly ClaudeInstalledPlugin UserPlugin = new(PluginId, "0.7.0", "user", true); + + private readonly IClaudePluginCli _claudePluginCli = A.Fake(); + + private readonly IClaudeExecutableLocator _claudeExecutableLocator = A.Fake(); + + private readonly ClaudeCodeIntegration _integration; + + public ClaudeCodeIntegrationTests() + { + _integration = new ClaudeCodeIntegration(_claudePluginCli, _claudeExecutableLocator); + } + + [Fact] + public void Constructor_NullClaudePluginCli_ThrowsArgumentNullException() + { + // Act + var act = () => new ClaudeCodeIntegration(null!, _claudeExecutableLocator); + + // Assert + act.Should().Throw() + .WithParameterName("claudePluginCli"); + } + + [Fact] + public void Constructor_NullClaudeExecutableLocator_ThrowsArgumentNullException() + { + // Act + var act = () => new ClaudeCodeIntegration(_claudePluginCli, null!); + + // Assert + act.Should().Throw() + .WithParameterName("claudeExecutableLocator"); + } + + [Fact] + public void AgentId_Always_IsClaude() + { + // Assert + _integration.AgentId + .Should().Be("claude"); + + ClaudeCodeIntegration.PluginId + .Should().Be(PluginId); + + ClaudeCodeIntegration.MarketplaceName + .Should().Be(MarketplaceName); + } + + [Theory] + [InlineData("/usr/local/bin/claude", true)] + [InlineData(null, false)] + public void IsAvailable_ClaudeOnPathOrNot_ReturnsWhetherClaudeIsFound(string? executablePath, bool expected) + { + // Arrange + A.CallTo(() => _claudeExecutableLocator.FindClaudeExecutable()).Returns(executablePath); + + // Act + var isAvailable = _integration.IsAvailable(); + + // Assert + isAvailable + .Should().Be(expected); + } + + [Fact] + public async Task InstallAsync_NullSource_ThrowsArgumentNullException() + { + // Act + var act = () => _integration.InstallAsync(null!, TestContext.Current.CancellationToken); + + // Assert + await act.Should().ThrowAsync() + .WithParameterName("source"); + } + + [Fact] + public async Task UpdateAsync_NullGetSource_ThrowsArgumentNullException() + { + // Act + var act = () => _integration.UpdateAsync(null!, TestContext.Current.CancellationToken); + + // Assert + await act.Should().ThrowAsync() + .WithParameterName("getSource"); + } + + [Fact] + public void EnsureAvailable_ClaudeOnPath_DoesNotThrow() + { + // Arrange + A.CallTo(() => _claudeExecutableLocator.FindClaudeExecutable()).Returns("/usr/local/bin/claude"); + + // Act + var act = () => _integration.EnsureAvailable(); + + // Assert + act.Should().NotThrow(); + + A.CallTo(_claudePluginCli).MustNotHaveHappened(); + } + + [Fact] + public void EnsureAvailable_ClaudeNotOnPath_ThrowsClaudeNotFoundNamingFirstCommand() + { + // Arrange + A.CallTo(() => _claudeExecutableLocator.FindClaudeExecutable()).Returns(null); + + // Act + var act = () => _integration.EnsureAvailable(); + + // Assert + var exception = act.Should().Throw().Which; + + exception.CommandText + .Should().Be("claude plugin list --json"); + + exception.Reason + .Should().Be("The Claude Code CLI claude was not found in any absolute directory of the PATH " + + "environment variable."); + + A.CallTo(_claudePluginCli).MustNotHaveHappened(); + } + + [Fact] + public async Task InstallAsync_MarketplaceAndPluginMissing_AddsMarketplaceInstallsPluginAndReturnsInstalled() + { + // Arrange + SetUpMarketplaces([new ClaudeMarketplace("other", "github", "other/repo", "main", null)]); + SetUpPluginLists([], [], [new ClaudeInstalledPlugin(PluginId, "0.8.0", "user", true)]); + + // Act + var result = await _integration.InstallAsync(ReleaseSource, TestContext.Current.CancellationToken); + + // Assert + result + .Should().Be(new IntegrationResult("claude", PluginId, IntegrationOutcome.Installed, null, "0.8.0", + "v0.8.0", true)); + + A.CallTo(() => _claudePluginCli.AddMarketplaceAsync("CreativeCodersTeam/shade-kit#v0.8.0", + A._)) + .MustHaveHappenedOnceExactly() + .Then(A.CallTo(() => _claudePluginCli.InstallPluginAsync(PluginId, A._)) + .MustHaveHappenedOnceExactly()); + + A.CallTo(() => _claudePluginCli.RemoveMarketplaceAsync(A._, A._)) + .MustNotHaveHappened(); + + A.CallTo(() => _claudePluginCli.UpdatePluginAsync(A._, A._)) + .MustNotHaveHappened(); + } + + [Fact] + public async Task InstallAsync_SameSourceAndPluginMissing_InstallsWithoutMarketplaceChange() + { + // Arrange + SetUpMarketplaces([CreateGitHubMarketplace(Repo, "v0.8.0")]); + SetUpPluginLists([], [new ClaudeInstalledPlugin(PluginId, "0.8.0", "user", false)]); + + // Act + var result = await _integration.InstallAsync(ReleaseSource, TestContext.Current.CancellationToken); + + // Assert + result + .Should().Be(new IntegrationResult("claude", PluginId, IntegrationOutcome.Installed, null, "0.8.0", + "v0.8.0", false)); + + A.CallTo(() => _claudePluginCli.AddMarketplaceAsync(A._, A._)) + .MustNotHaveHappened(); + + A.CallTo(() => _claudePluginCli.RemoveMarketplaceAsync(A._, A._)) + .MustNotHaveHappened(); + } + + [Fact] + public async Task InstallAsync_PluginInstalledOnlyWithProjectScope_InstallsForUser() + { + // Arrange + SetUpMarketplaces([CreateGitHubMarketplace(Repo, "v0.8.0")]); + SetUpPluginLists( + [new ClaudeInstalledPlugin(PluginId, "0.8.0", "project", true)], + [ + new ClaudeInstalledPlugin(PluginId, "0.8.0", "project", true), + new ClaudeInstalledPlugin(PluginId, "0.8.0", "user", true) + ]); + + // Act + var result = await _integration.InstallAsync(ReleaseSource, TestContext.Current.CancellationToken); + + // Assert + result.Outcome + .Should().Be(IntegrationOutcome.Installed); + + A.CallTo(() => _claudePluginCli.InstallPluginAsync(PluginId, A._)) + .MustHaveHappenedOnceExactly(); + } + + [Fact] + public async Task InstallAsync_SameSourceAndPluginUpToDate_RefreshesMarketplaceAndReturnsCurrent() + { + // Arrange + SetUpMarketplaces([CreateGitHubMarketplace(Repo, "v0.8.0")]); + SetUpPluginLists([UserPlugin]); + SetUpUpdate(ClaudePluginUpdateResult.UpToDateOutcome); + + // Act + var result = await _integration.InstallAsync(ReleaseSource, TestContext.Current.CancellationToken); + + // Assert + result + .Should().Be(new IntegrationResult("claude", PluginId, IntegrationOutcome.Current, "0.8.0", "0.8.0", + "v0.8.0", true)); + + A.CallTo(() => _claudePluginCli.AddMarketplaceAsync(A._, A._)) + .MustNotHaveHappened(); + + A.CallTo(() => _claudePluginCli.RemoveMarketplaceAsync(A._, A._)) + .MustNotHaveHappened(); + + A.CallTo(() => _claudePluginCli.InstallPluginAsync(A._, A._)) + .MustNotHaveHappened(); + + A.CallTo(() => _claudePluginCli.ListPluginsAsync(A._)) + .MustHaveHappenedOnceExactly(); + + A.CallTo(() => _claudePluginCli.UpdateMarketplaceAsync(MarketplaceName, A._)) + .MustHaveHappenedOnceExactly() + .Then(A.CallTo(() => _claudePluginCli.UpdatePluginAsync(PluginId, A._)) + .MustHaveHappenedOnceExactly()); + } + + [Fact] + public async Task InstallAsync_KeptBranchMarketplace_RefreshesMarketplaceBeforePluginUpdate() + { + // Arrange + var mainSource = MarketplaceSource.ForGitHub(Repo, "main"); + SetUpMarketplaces([CreateGitHubMarketplace(Repo, "main")]); + SetUpPluginLists([UserPlugin]); + SetUpUpdate(ClaudePluginUpdateResult.UpdatedOutcome); + + // Act + var result = await _integration.InstallAsync(mainSource, TestContext.Current.CancellationToken); + + // Assert + result + .Should().Be(new IntegrationResult("claude", PluginId, IntegrationOutcome.Updated, null, null, "main", + true)); + + A.CallTo(() => _claudePluginCli.ListMarketplacesAsync(A._)) + .MustHaveHappenedOnceExactly() + .Then(A.CallTo(() => _claudePluginCli.UpdateMarketplaceAsync(MarketplaceName, A._)) + .MustHaveHappenedOnceExactly()) + .Then(A.CallTo(() => _claudePluginCli.UpdatePluginAsync(PluginId, A._)) + .MustHaveHappenedOnceExactly()); + + A.CallTo(() => _claudePluginCli.AddMarketplaceAsync(A._, A._)) + .MustNotHaveHappened(); + + A.CallTo(() => _claudePluginCli.RemoveMarketplaceAsync(A._, A._)) + .MustNotHaveHappened(); + } + + [Fact] + public async Task InstallAsync_KeptMarketplaceAndPluginMissing_RefreshesMarketplaceBeforeInstall() + { + // Arrange + SetUpMarketplaces([CreateGitHubMarketplace(Repo, "v0.8.0")]); + SetUpPluginLists([], [new ClaudeInstalledPlugin(PluginId, "0.8.0", "user", true)]); + + // Act + var result = await _integration.InstallAsync(ReleaseSource, TestContext.Current.CancellationToken); + + // Assert + result.Outcome + .Should().Be(IntegrationOutcome.Installed); + + A.CallTo(() => _claudePluginCli.UpdateMarketplaceAsync(MarketplaceName, A._)) + .MustHaveHappenedOnceExactly() + .Then(A.CallTo(() => _claudePluginCli.InstallPluginAsync(PluginId, A._)) + .MustHaveHappenedOnceExactly()); + } + + [Theory] + [InlineData("v0.7.0")] + [InlineData(null)] + public async Task InstallAsync_MarketplaceSwitchedOrAdded_DoesNotRefreshMarketplace(string? existingRef) + { + // Arrange + SetUpMarketplaces(existingRef is null ? [] : [CreateGitHubMarketplace(Repo, existingRef)]); + SetUpPluginLists([UserPlugin], [UserPlugin]); + SetUpUpdate(ClaudePluginUpdateResult.UpdatedOutcome); + + // Act + await _integration.InstallAsync(ReleaseSource, TestContext.Current.CancellationToken); + + // Assert + A.CallTo(() => _claudePluginCli.AddMarketplaceAsync(A._, A._)) + .MustHaveHappenedOnceExactly(); + + A.CallTo(() => _claudePluginCli.UpdateMarketplaceAsync(A._, A._)) + .MustNotHaveHappened(); + } + + [Fact] + public async Task InstallAsync_MarketplaceRefreshFails_ThrowsCauseUnwrappedWithoutPluginChange() + { + // Arrange + var failure = CreateFailure("marketplace", "update"); + SetUpMarketplaces([CreateGitHubMarketplace(Repo, "v0.8.0")]); + SetUpPluginLists([UserPlugin]); + A.CallTo(() => _claudePluginCli.UpdateMarketplaceAsync(A._, A._)) + .Throws(failure); + + // Act + var act = () => _integration.InstallAsync(ReleaseSource, TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()) + .Which.Should().BeSameAs(failure); + + A.CallTo(() => _claudePluginCli.InstallPluginAsync(A._, A._)) + .MustNotHaveHappened(); + A.CallTo(() => _claudePluginCli.UpdatePluginAsync(A._, A._)) + .MustNotHaveHappened(); + } + + [Fact] + public async Task InstallAsync_KeptDirectoryMarketplace_RefreshesMarketplaceBeforePluginUpdate() + { + // Arrange + var path = Path.Combine(Path.GetTempPath(), "shade-kit"); + SetUpMarketplaces([new ClaudeMarketplace(MarketplaceName, "directory", null, null, path)]); + SetUpPluginLists([UserPlugin]); + SetUpUpdate(ClaudePluginUpdateResult.UpToDateOutcome); + + // Act + await _integration.InstallAsync(MarketplaceSource.ForDirectory(path), TestContext.Current.CancellationToken); + + // Assert + A.CallTo(() => _claudePluginCli.UpdateMarketplaceAsync(MarketplaceName, A._)) + .MustHaveHappenedOnceExactly() + .Then(A.CallTo(() => _claudePluginCli.UpdatePluginAsync(PluginId, A._)) + .MustHaveHappenedOnceExactly()); + } + + [Fact] + public async Task InstallAsync_MarketplaceRefreshCannotStartClaude_ThrowsCauseUnwrappedWithoutPluginChange() + { + // Arrange + var failure = new ClaudeUnavailableException(["plugin", "marketplace", "update"], "Cannot start."); + SetUpMarketplaces([CreateGitHubMarketplace(Repo, "v0.8.0")]); + SetUpPluginLists([UserPlugin]); + A.CallTo(() => _claudePluginCli.UpdateMarketplaceAsync(A._, A._)) + .Throws(failure); + + // Act + var act = () => _integration.InstallAsync(ReleaseSource, TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()) + .Which.Should().BeSameAs(failure); + + A.CallTo(() => _claudePluginCli.UpdatePluginAsync(A._, A._)) + .MustNotHaveHappened(); + } + + [Fact] + public async Task InstallAsync_CanceledWhileKeptMarketplaceIsRefreshed_PropagatesCancellationUnwrapped() + { + // Arrange + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; + SetUpMarketplaces([CreateGitHubMarketplace(Repo, "v0.8.0")]); + SetUpPluginLists([UserPlugin]); + A.CallTo(() => _claudePluginCli.UpdateMarketplaceAsync(A._, A._)) + .Invokes(() => cancellationTokenSource.Cancel()) + .Throws(new OperationCanceledException(cancellationToken)); + + // Act + var act = () => _integration.InstallAsync(ReleaseSource, cancellationToken); + + // Assert + (await act.Should().ThrowAsync()) + .Which.Should().NotBeOfType( + "a kept marketplace was not removed, so nothing needs a repair"); + } + + [Fact] + public async Task InstallAsync_SameSourceAndPluginUpdated_ReturnsUpdated() + { + // Arrange + SetUpMarketplaces([CreateGitHubMarketplace(Repo, "v0.8.0")]); + SetUpPluginLists([UserPlugin]); + SetUpUpdate(ClaudePluginUpdateResult.UpdatedOutcome); + + // Act + var result = await _integration.InstallAsync(ReleaseSource, TestContext.Current.CancellationToken); + + // Assert + result.Outcome + .Should().Be(IntegrationOutcome.Updated); + } + + [Fact] + public async Task InstallAsync_SameRepoOtherRef_RemovesAndAddsMarketplaceThenUpdates() + { + // Arrange + SetUpMarketplaces([CreateGitHubMarketplace(Repo, "v0.7.0")]); + SetUpPluginLists([UserPlugin], [UserPlugin]); + SetUpUpdate(ClaudePluginUpdateResult.UpToDateOutcome); + + // Act + var result = await _integration.InstallAsync(ReleaseSource, TestContext.Current.CancellationToken); + + // Assert + result + .Should().Be(new IntegrationResult("claude", PluginId, IntegrationOutcome.Updated, "0.7.0", "0.8.0", + "v0.8.0", true), "an up-to-date plugin after a changed ref still counts as updated"); + + A.CallTo(() => _claudePluginCli.RemoveMarketplaceAsync(MarketplaceName, A._)) + .MustHaveHappenedOnceExactly() + .Then(A.CallTo(() => _claudePluginCli.AddMarketplaceAsync("CreativeCodersTeam/shade-kit#v0.8.0", + A._)) + .MustHaveHappenedOnceExactly()) + .Then(A.CallTo(() => _claudePluginCli.UpdatePluginAsync(PluginId, A._)) + .MustHaveHappenedOnceExactly()); + } + + [Fact] + public async Task InstallAsync_SameRepoInOtherCase_TreatsRepoAsSame() + { + // Arrange + SetUpMarketplaces([CreateGitHubMarketplace("creativecodersteam/SHADE-KIT", "v0.8.0")]); + SetUpPluginLists([UserPlugin]); + SetUpUpdate(ClaudePluginUpdateResult.UpToDateOutcome); + + // Act + var result = await _integration.InstallAsync(ReleaseSource, TestContext.Current.CancellationToken); + + // Assert + result.Outcome + .Should().Be(IntegrationOutcome.Current); + } + + [Fact] + public async Task InstallAsync_RefInOtherCase_SwitchesMarketplace() + { + // Arrange + SetUpMarketplaces([CreateGitHubMarketplace(Repo, "V0.8.0")]); + SetUpPluginLists([UserPlugin], [UserPlugin]); + SetUpUpdate(ClaudePluginUpdateResult.UpToDateOutcome); + + // Act + var result = await _integration.InstallAsync(ReleaseSource, TestContext.Current.CancellationToken); + + // Assert + result.Outcome + .Should().Be(IntegrationOutcome.Updated); + + A.CallTo(() => _claudePluginCli.RemoveMarketplaceAsync(MarketplaceName, A._)) + .MustHaveHappenedOnceExactly(); + } + + [Fact] + public async Task InstallAsync_GitHubMarketplaceWithoutRef_SwitchesToExplicitRef() + { + // Arrange + SetUpMarketplaces([CreateGitHubMarketplace(Repo, null)]); + SetUpPluginLists([UserPlugin], [UserPlugin]); + SetUpUpdate(ClaudePluginUpdateResult.UpdatedOutcome); + + // Act + var result = await _integration.InstallAsync(ReleaseSource, TestContext.Current.CancellationToken); + + // Assert + result + .Should().Be(new IntegrationResult("claude", PluginId, IntegrationOutcome.Updated, null, "0.8.0", + "v0.8.0", true)); + + A.CallTo(() => _claudePluginCli.RemoveMarketplaceAsync(MarketplaceName, A._)) + .MustHaveHappenedOnceExactly(); + } + + [Fact] + public async Task InstallAsync_SourceWithoutRefAndMarketplaceWithoutRef_KeepsMarketplace() + { + // Arrange + SetUpMarketplaces([CreateGitHubMarketplace(Repo, null)]); + SetUpPluginLists([UserPlugin]); + SetUpUpdate(ClaudePluginUpdateResult.UpToDateOutcome); + + // Act + var result = await _integration.InstallAsync(MarketplaceSource.ForGitHub(Repo), + TestContext.Current.CancellationToken); + + // Assert + result + .Should().Be(new IntegrationResult("claude", PluginId, IntegrationOutcome.Current, null, null, null, + true)); + } + + [Fact] + public async Task InstallAsync_PluginRemovedWithOldMarketplace_InstallsAgainAndReturnsUpdated() + { + // Arrange + SetUpMarketplaces([CreateGitHubMarketplace(Repo, "v0.7.0")]); + SetUpPluginLists([UserPlugin], [], [new ClaudeInstalledPlugin(PluginId, "0.8.0", "user", true)]); + + // Act + var result = await _integration.InstallAsync(ReleaseSource, TestContext.Current.CancellationToken); + + // Assert + result + .Should().Be(new IntegrationResult("claude", PluginId, IntegrationOutcome.Updated, "0.7.0", "0.8.0", + "v0.8.0", true)); + + A.CallTo(() => _claudePluginCli.InstallPluginAsync(PluginId, A._)) + .MustHaveHappenedOnceExactly(); + + A.CallTo(() => _claudePluginCli.UpdatePluginAsync(A._, A._)) + .MustNotHaveHappened(); + } + + [Fact] + public async Task InstallAsync_PreviousRefIsBranch_ReturnsNullPreviousKitVersion() + { + // Arrange + SetUpMarketplaces([CreateGitHubMarketplace(Repo, "main")]); + SetUpPluginLists([UserPlugin], [UserPlugin]); + SetUpUpdate(ClaudePluginUpdateResult.UpdatedOutcome); + + // Act + var result = await _integration.InstallAsync(ReleaseSource, TestContext.Current.CancellationToken); + + // Assert + result.PreviousKitVersion + .Should().BeNull(); + } + + [Fact] + public async Task InstallAsync_TargetRefIsBranch_ReturnsNullKitVersionAndBranchRef() + { + // Arrange + SetUpMarketplaces([CreateGitHubMarketplace(Repo, "v0.7.0")]); + SetUpPluginLists([UserPlugin], [UserPlugin]); + SetUpUpdate(ClaudePluginUpdateResult.UpdatedOutcome); + + // Act + var result = await _integration.InstallAsync(MarketplaceSource.ForGitHub(Repo, "main"), + TestContext.Current.CancellationToken); + + // Assert + result + .Should().Be(new IntegrationResult("claude", PluginId, IntegrationOutcome.Updated, "0.7.0", null, "main", + true)); + } + + [Fact] + public async Task InstallAsync_DisabledPlugin_UpdatesAndReportsDisabled() + { + // Arrange + SetUpMarketplaces([CreateGitHubMarketplace(Repo, "v0.8.0")]); + SetUpPluginLists([UserPlugin with { Enabled = false }]); + SetUpUpdate(ClaudePluginUpdateResult.UpdatedOutcome); + + // Act + var result = await _integration.InstallAsync(ReleaseSource, TestContext.Current.CancellationToken); + + // Assert + result.Enabled + .Should().BeFalse(); + + A.CallTo(() => _claudePluginCli.UpdatePluginAsync(PluginId, A._)) + .MustHaveHappenedOnceExactly(); + } + + [Fact] + public async Task InstallAsync_SameDirectory_KeepsMarketplace() + { + // Arrange + var path = Path.Combine(Path.GetTempPath(), "shade-kit"); + SetUpMarketplaces([new ClaudeMarketplace(MarketplaceName, "directory", null, null, + path + Path.DirectorySeparatorChar)]); + SetUpPluginLists([UserPlugin]); + SetUpUpdate(ClaudePluginUpdateResult.UpToDateOutcome); + + // Act + var result = await _integration.InstallAsync(MarketplaceSource.ForDirectory(path), + TestContext.Current.CancellationToken); + + // Assert + result + .Should().Be(new IntegrationResult("claude", PluginId, IntegrationOutcome.Current, null, null, null, + true)); + } + + [Fact] + public async Task InstallAsync_DirectorySourceAndMarketplaceMissing_AddsAbsolutePath() + { + // Arrange + var path = Path.Combine(Path.GetTempPath(), "shade-kit"); + SetUpMarketplaces([]); + SetUpPluginLists([], [], [UserPlugin]); + + // Act + await _integration.InstallAsync(MarketplaceSource.ForDirectory(path), TestContext.Current.CancellationToken); + + // Assert + A.CallTo(() => _claudePluginCli.AddMarketplaceAsync(Path.TrimEndingDirectorySeparator(path), + A._)) + .MustHaveHappenedOnceExactly(); + } + + [Theory] + [InlineData("github", "other/shade-kit", "v0.8.0", null, "github", "other/shade-kit#v0.8.0")] + [InlineData("github", "other/shade-kit", null, null, "github", "other/shade-kit")] + [InlineData("directory", null, null, OtherPath, "github", OtherPath)] + [InlineData("git", null, null, null, "github", "a source of the kind 'git'")] + [InlineData(null, null, null, null, "github", "a source of unknown kind")] + [InlineData("github", null, "v0.8.0", null, "github", "a source of the kind 'github'")] + [InlineData("github", Repo, "v0.8.0", null, "directory", "CreativeCodersTeam/shade-kit#v0.8.0")] + [InlineData("directory", null, null, OtherPath, "directory", OtherPath)] + [InlineData("directory", null, null, null, "directory", "a source of the kind 'directory'")] + public async Task InstallAsync_MarketplaceWithOtherSource_ThrowsConflictWithoutChanges(string? sourceKind, + string? repo, string? @ref, string? path, string targetKind, string expectedExistingSource) + { + // Arrange + var otherPath = Path.Combine(Path.GetTempPath(), "other"); + var source = targetKind == "directory" + ? MarketplaceSource.ForDirectory(Path.Combine(Path.GetTempPath(), "shade-kit")) + : ReleaseSource; + SetUpMarketplaces([new ClaudeMarketplace(MarketplaceName, sourceKind, repo, @ref, + path == OtherPath ? otherPath : path)]); + SetUpPluginLists([UserPlugin]); + + // Act + var act = () => _integration.InstallAsync(source, TestContext.Current.CancellationToken); + + // Assert + var exception = (await act.Should().ThrowAsync()).Which; + + exception.AgentId + .Should().Be("claude"); + + exception.MarketplaceName + .Should().Be(MarketplaceName); + + exception.ExistingSource + .Should().Be(expectedExistingSource == OtherPath ? otherPath : expectedExistingSource); + + exception.RequestedSource + .Should().Be(source.Text); + + exception.ResolveCommand + .Should().Be("claude plugin marketplace remove creativecoders-shade-kit"); + + AssertNoChange(); + } + + [Fact] + public async Task InstallAsync_AddFailsAfterRemove_ThrowsIntegrationIncompleteWithCause() + { + // Arrange + var failure = CreateFailure("marketplace", "add"); + SetUpMarketplaces([CreateGitHubMarketplace(Repo, "v0.7.0")]); + SetUpPluginLists([UserPlugin]); + A.CallTo(() => _claudePluginCli.AddMarketplaceAsync(A._, A._)).Throws(failure); + + // Act + var act = () => _integration.InstallAsync(ReleaseSource, TestContext.Current.CancellationToken); + + // Assert + var exception = (await act.Should().ThrowAsync()).Which; + + exception.AgentId + .Should().Be("claude"); + + exception.InnerException + .Should().BeSameAs(failure); + } + + [Fact] + public async Task InstallAsync_UpdateFailsAfterSwitch_ThrowsIntegrationIncomplete() + { + // Arrange + var failure = CreateFailure("update"); + SetUpMarketplaces([CreateGitHubMarketplace(Repo, "v0.7.0")]); + SetUpPluginLists([UserPlugin], [UserPlugin]); + A.CallTo(() => _claudePluginCli.UpdatePluginAsync(A._, A._)).Throws(failure); + + // Act + var act = () => _integration.InstallAsync(ReleaseSource, TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()) + .WithInnerException(); + } + + [Fact] + public async Task InstallAsync_InstallFailsAfterSwitch_ThrowsIntegrationIncomplete() + { + // Arrange + var failure = CreateFailure("install"); + SetUpMarketplaces([CreateGitHubMarketplace(Repo, "v0.7.0")]); + SetUpPluginLists([UserPlugin], []); + A.CallTo(() => _claudePluginCli.InstallPluginAsync(A._, A._)).Throws(failure); + + // Act + var act = () => _integration.InstallAsync(ReleaseSource, TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()) + .Which.InnerException.Should().BeSameAs(failure); + } + + [Fact] + public async Task InstallAsync_PluginNotListedAfterInstallAfterSwitch_ThrowsIntegrationIncomplete() + { + // Arrange + SetUpMarketplaces([CreateGitHubMarketplace(Repo, "v0.7.0")]); + SetUpPluginLists([UserPlugin], [], []); + + // Act + var act = () => _integration.InstallAsync(ReleaseSource, TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()) + .WithInnerException(); + } + + [Fact] + public async Task InstallAsync_OperationCanceledAfterSwitchWithoutCanceledRunToken_PropagatesUnwrapped() + { + // Arrange + var canceled = new OperationCanceledException(); + SetUpMarketplaces([CreateGitHubMarketplace(Repo, "v0.7.0")]); + SetUpPluginLists([UserPlugin]); + A.CallTo(() => _claudePluginCli.AddMarketplaceAsync(A._, A._)) + .Throws(canceled); + + // Act + var act = () => _integration.InstallAsync(ReleaseSource, TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()) + .Which.Should().BeSameAs(canceled, "only a cancellation of the run itself gets the repair hint"); + } + + [Fact] + public async Task InstallAsync_CanceledAfterRemove_ThrowsSwitchCanceledWithRunToken() + { + // Arrange + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; + var canceled = new OperationCanceledException(cancellationToken); + SetUpMarketplaces([CreateGitHubMarketplace(Repo, "v0.7.0")]); + SetUpPluginLists([UserPlugin]); + A.CallTo(() => _claudePluginCli.AddMarketplaceAsync(A._, A._)) + .Invokes(() => cancellationTokenSource.Cancel()) + .Throws(canceled); + + // Act + var act = () => _integration.InstallAsync(ReleaseSource, cancellationToken); + + // Assert + var exception = (await act.Should().ThrowAsync()).Which; + + exception.AgentId + .Should().Be("claude"); + + exception.InnerException + .Should().BeSameAs(canceled); + + exception.CancellationToken + .Should().Be(cancellationToken); + + exception + .Should().BeAssignableTo("the run still ends as canceled"); + } + + [Fact] + public async Task InstallAsync_CanceledWhileMarketplaceIsRemoved_ThrowsSwitchCanceled() + { + // Arrange + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; + SetUpMarketplaces([CreateGitHubMarketplace(Repo, "v0.7.0")]); + SetUpPluginLists([UserPlugin]); + A.CallTo(() => _claudePluginCli.RemoveMarketplaceAsync(A._, A._)) + .Invokes(() => cancellationTokenSource.Cancel()) + .Throws(new OperationCanceledException(cancellationToken)); + + // Act + var act = () => _integration.InstallAsync(ReleaseSource, cancellationToken); + + // Assert + await act.Should().ThrowAsync( + "the killed claude may already have removed the marketplace and its plugin"); + + A.CallTo(() => _claudePluginCli.AddMarketplaceAsync(A._, A._)) + .MustNotHaveHappened(); + } + + [Fact] + public async Task InstallAsync_CanceledWhilePluginIsUpdatedAfterSwitch_ThrowsSwitchCanceled() + { + // Arrange + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; + SetUpMarketplaces([CreateGitHubMarketplace(Repo, "v0.7.0")]); + SetUpPluginLists([UserPlugin], [UserPlugin]); + A.CallTo(() => _claudePluginCli.UpdatePluginAsync(A._, A._)) + .Invokes(() => cancellationTokenSource.Cancel()) + .Throws(new OperationCanceledException(cancellationToken)); + + // Act + var act = () => _integration.InstallAsync(ReleaseSource, cancellationToken); + + // Assert + await act.Should().ThrowAsync(); + } + + [Fact] + public async Task InstallAsync_CanceledWhileMissingMarketplaceIsAdded_PropagatesCancellationUnwrapped() + { + // Arrange + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; + var canceled = new OperationCanceledException(cancellationToken); + SetUpMarketplaces([]); + SetUpPluginLists([]); + A.CallTo(() => _claudePluginCli.AddMarketplaceAsync(A._, A._)) + .Invokes(() => cancellationTokenSource.Cancel()) + .Throws(canceled); + + // Act + var act = () => _integration.InstallAsync(ReleaseSource, cancellationToken); + + // Assert + (await act.Should().ThrowAsync()) + .Which.Should().BeSameAs(canceled, "no marketplace was removed, so nothing needs a repair"); + } + + [Fact] + public async Task InstallAsync_CanceledWhilePluginsAreListedAfterSwitch_ThrowsSwitchCanceled() + { + // Arrange + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; + SetUpMarketplaces([CreateGitHubMarketplace(Repo, "v0.7.0")]); + var listCalls = 0; + A.CallTo(() => _claudePluginCli.ListPluginsAsync(A._)) + .ReturnsLazily(() => + { + if (++listCalls == 1) + { + return Task.FromResult>([UserPlugin]); + } + + cancellationTokenSource.Cancel(); + + return Task.FromCanceled>(cancellationToken); + }); + + // Act + var act = () => _integration.InstallAsync(ReleaseSource, cancellationToken); + + // Assert + await act.Should().ThrowAsync(); + } + + [Fact] + public async Task InstallAsync_CanceledWhilePluginIsInstalledAfterSwitch_ThrowsSwitchCanceled() + { + // Arrange + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; + SetUpMarketplaces([CreateGitHubMarketplace(Repo, "v0.7.0")]); + SetUpPluginLists([UserPlugin], []); + A.CallTo(() => _claudePluginCli.InstallPluginAsync(A._, A._)) + .Invokes(() => cancellationTokenSource.Cancel()) + .Throws(new OperationCanceledException(cancellationToken)); + + // Act + var act = () => _integration.InstallAsync(ReleaseSource, cancellationToken); + + // Assert + await act.Should().ThrowAsync(); + } + + [Fact] + public async Task InstallAsync_CanceledWhilePluginIsUpdatedWithKeptMarketplace_PropagatesCancellationUnwrapped() + { + // Arrange + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; + var canceled = new OperationCanceledException(cancellationToken); + SetUpMarketplaces([CreateGitHubMarketplace(Repo, "v0.8.0")]); + SetUpPluginLists([UserPlugin]); + A.CallTo(() => _claudePluginCli.UpdatePluginAsync(A._, A._)) + .Invokes(() => cancellationTokenSource.Cancel()) + .Throws(canceled); + + // Act + var act = () => _integration.InstallAsync(ReleaseSource, cancellationToken); + + // Assert + (await act.Should().ThrowAsync()) + .Which.Should().BeSameAs(canceled); + } + + [Fact] + public async Task InstallAsync_OperationCanceledFromRemoveWithoutCanceledRunToken_PropagatesUnwrapped() + { + // Arrange + var canceled = new OperationCanceledException(); + SetUpMarketplaces([CreateGitHubMarketplace(Repo, "v0.7.0")]); + SetUpPluginLists([UserPlugin]); + A.CallTo(() => _claudePluginCli.RemoveMarketplaceAsync(A._, A._)) + .Throws(canceled); + + // Act + var act = () => _integration.InstallAsync(ReleaseSource, TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()) + .Which.Should().BeSameAs(canceled); + } + + [Fact] + public async Task InstallAsync_CanceledWhileMarketplacesAreListed_PropagatesCancellationUnwrapped() + { + // Arrange + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; + SetUpPluginLists([UserPlugin]); + A.CallTo(() => _claudePluginCli.ListMarketplacesAsync(A._)) + .Invokes(() => cancellationTokenSource.Cancel()) + .Throws(new OperationCanceledException(cancellationToken)); + + // Act + var act = () => _integration.InstallAsync(ReleaseSource, cancellationToken); + + // Assert + (await act.Should().ThrowAsync()) + .Which.Should().NotBeOfType("nothing was changed yet"); + } + + [Fact] + public async Task InstallAsync_PluginInstalledButMarketplaceMissing_AddsMarketplaceAndUpdates() + { + // Arrange + SetUpMarketplaces([]); + SetUpPluginLists([UserPlugin], [UserPlugin]); + SetUpUpdate(ClaudePluginUpdateResult.UpToDateOutcome); + + // Act + var result = await _integration.InstallAsync(ReleaseSource, TestContext.Current.CancellationToken); + + // Assert + result + .Should().Be(new IntegrationResult("claude", PluginId, IntegrationOutcome.Updated, null, "0.8.0", + "v0.8.0", true)); + + A.CallTo(() => _claudePluginCli.AddMarketplaceAsync("CreativeCodersTeam/shade-kit#v0.8.0", + A._)) + .MustHaveHappenedOnceExactly() + .Then(A.CallTo(() => _claudePluginCli.UpdatePluginAsync(PluginId, A._)) + .MustHaveHappenedOnceExactly()); + + A.CallTo(() => _claudePluginCli.RemoveMarketplaceAsync(A._, A._)) + .MustNotHaveHappened(); + } + + [Fact] + public async Task InstallAsync_SwitchWithPluginNotInstalled_InstallsAndReturnsInstalled() + { + // Arrange + SetUpMarketplaces([CreateGitHubMarketplace(Repo, "v0.7.0")]); + SetUpPluginLists([], [], [UserPlugin]); + + // Act + var result = await _integration.InstallAsync(ReleaseSource, TestContext.Current.CancellationToken); + + // Assert + result + .Should().Be(new IntegrationResult("claude", PluginId, IntegrationOutcome.Installed, null, "0.8.0", + "v0.8.0", true)); + + A.CallTo(() => _claudePluginCli.RemoveMarketplaceAsync(MarketplaceName, A._)) + .MustHaveHappenedOnceExactly() + .Then(A.CallTo(() => _claudePluginCli.InstallPluginAsync(PluginId, A._)) + .MustHaveHappenedOnceExactly()); + } + + [Fact] + public async Task InstallAsync_PluginAppearsAfterMarketplaceAdd_UpdatesAndReturnsInstalled() + { + // Arrange + SetUpMarketplaces([]); + SetUpPluginLists([], [UserPlugin]); + SetUpUpdate(ClaudePluginUpdateResult.UpToDateOutcome); + + // Act + var result = await _integration.InstallAsync(ReleaseSource, TestContext.Current.CancellationToken); + + // Assert + result.Outcome + .Should().Be(IntegrationOutcome.Installed, "the plugin was not installed before the run"); + + A.CallTo(() => _claudePluginCli.InstallPluginAsync(A._, A._)) + .MustNotHaveHappened(); + } + + [Fact] + public async Task InstallAsync_SourceWithoutRefAndMarketplaceWithRef_SwitchesMarketplace() + { + // Arrange + SetUpMarketplaces([CreateGitHubMarketplace(Repo, "v0.7.0")]); + SetUpPluginLists([UserPlugin], [UserPlugin]); + SetUpUpdate(ClaudePluginUpdateResult.UpdatedOutcome); + + // Act + await _integration.InstallAsync(MarketplaceSource.ForGitHub(Repo), TestContext.Current.CancellationToken); + + // Assert + A.CallTo(() => _claudePluginCli.RemoveMarketplaceAsync(MarketplaceName, A._)) + .MustHaveHappenedOnceExactly() + .Then(A.CallTo(() => _claudePluginCli.AddMarketplaceAsync(Repo, A._)) + .MustHaveHappenedOnceExactly()); + } + + [Fact] + public async Task InstallAsync_DirectoryInOtherCaseAndCaseSensitiveComparer_ThrowsConflict() + { + // Arrange + var integration = new ClaudeCodeIntegration(_claudePluginCli, _claudeExecutableLocator, + new DirectoryPathComparer(StringComparison.Ordinal)); + var path = Path.Combine(Path.GetTempPath(), "shade-kit"); + SetUpMarketplaces([new ClaudeMarketplace(MarketplaceName, "directory", null, null, + Path.Combine(Path.GetTempPath(), "SHADE-KIT"))]); + SetUpPluginLists([UserPlugin]); + + // Act + var act = () => integration.InstallAsync(MarketplaceSource.ForDirectory(path), + TestContext.Current.CancellationToken); + + // Assert + await act.Should().ThrowAsync("Linux compares directories case-sensitively"); + + AssertNoChange(); + } + + [Fact] + public async Task InstallAsync_DirectoryInOtherCaseAndCaseInsensitiveComparer_KeepsMarketplace() + { + // Arrange + var integration = new ClaudeCodeIntegration(_claudePluginCli, _claudeExecutableLocator, + new DirectoryPathComparer(StringComparison.OrdinalIgnoreCase)); + var path = Path.Combine(Path.GetTempPath(), "shade-kit"); + SetUpMarketplaces([new ClaudeMarketplace(MarketplaceName, "directory", null, null, + Path.Combine(Path.GetTempPath(), "SHADE-KIT"))]); + SetUpPluginLists([UserPlugin]); + SetUpUpdate(ClaudePluginUpdateResult.UpToDateOutcome); + + // Act + var result = await integration.InstallAsync(MarketplaceSource.ForDirectory(path), + TestContext.Current.CancellationToken); + + // Assert + result.Outcome + .Should().Be(IntegrationOutcome.Current, "Windows and macOS compare directories case-insensitively"); + + A.CallTo(() => _claudePluginCli.RemoveMarketplaceAsync(A._, A._)) + .MustNotHaveHappened(); + A.CallTo(() => _claudePluginCli.AddMarketplaceAsync(A._, A._)) + .MustNotHaveHappened(); + } + + [Fact] + public async Task InstallAsync_DirectoryInOtherCaseOnCurrentOperatingSystem_FollowsItsCaseSensitivity() + { + // Arrange + var path = Path.Combine(Path.GetTempPath(), "shade-kit"); + SetUpMarketplaces([new ClaudeMarketplace(MarketplaceName, "directory", null, null, + Path.Combine(Path.GetTempPath(), "SHADE-KIT"))]); + SetUpPluginLists([UserPlugin]); + SetUpUpdate(ClaudePluginUpdateResult.UpToDateOutcome); + + // Act + var act = () => _integration.InstallAsync(MarketplaceSource.ForDirectory(path), + TestContext.Current.CancellationToken); + + // Assert + if (OperatingSystem.IsWindows() || OperatingSystem.IsMacOS()) + { + (await act.Should().NotThrowAsync()).Subject.Outcome + .Should().Be(IntegrationOutcome.Current); + } + else + { + await act.Should().ThrowAsync(); + + AssertNoChange(); + } + } + + [Fact] + public async Task InstallAsync_DirectoryMarketplaceThroughSymbolicLink_KeepsMarketplace() + { + // Arrange + using var tempDirectory = new TempKitDirectory(); + var target = tempDirectory.CreateDirectory("shade-kit"); + var link = tempDirectory.CreateDirectorySymbolicLinkOrSkip(target, "shade-kit-link"); + SetUpMarketplaces([new ClaudeMarketplace(MarketplaceName, "directory", null, null, link)]); + SetUpPluginLists([UserPlugin]); + SetUpUpdate(ClaudePluginUpdateResult.UpToDateOutcome); + + // Act + var result = await _integration.InstallAsync(MarketplaceSource.ForDirectory(target), + TestContext.Current.CancellationToken); + + // Assert + result.Outcome + .Should().Be(IntegrationOutcome.Current); + + A.CallTo(() => _claudePluginCli.RemoveMarketplaceAsync(A._, A._)) + .MustNotHaveHappened(); + A.CallTo(() => _claudePluginCli.UpdateMarketplaceAsync(MarketplaceName, A._)) + .MustHaveHappenedOnceExactly(); + } + + [Fact] + public async Task InstallAsync_SourceThroughSymbolicLinkInParentDirectory_KeepsMarketplace() + { + // Arrange + using var tempDirectory = new TempKitDirectory(); + var target = tempDirectory.CreateDirectory("work", "shade-kit"); + var parentLink = tempDirectory.CreateDirectorySymbolicLinkOrSkip(Path.GetDirectoryName(target)!, + "work-link"); + SetUpMarketplaces([new ClaudeMarketplace(MarketplaceName, "directory", null, null, + target + Path.DirectorySeparatorChar)]); + SetUpPluginLists([UserPlugin]); + SetUpUpdate(ClaudePluginUpdateResult.UpToDateOutcome); + + // Act + var result = await _integration.InstallAsync( + MarketplaceSource.ForDirectory(Path.Combine(parentLink, "shade-kit")), + TestContext.Current.CancellationToken); + + // Assert + result.Outcome + .Should().Be(IntegrationOutcome.Current); + } + + [Fact] + public async Task InstallAsync_SymbolicLinkToOtherDirectory_ThrowsConflict() + { + // Arrange + using var tempDirectory = new TempKitDirectory(); + var target = tempDirectory.CreateDirectory("shade-kit"); + var other = tempDirectory.CreateDirectory("other"); + var link = tempDirectory.CreateDirectorySymbolicLinkOrSkip(other, "shade-kit-link"); + SetUpMarketplaces([new ClaudeMarketplace(MarketplaceName, "directory", null, null, link)]); + SetUpPluginLists([UserPlugin]); + + // Act + var act = () => _integration.InstallAsync(MarketplaceSource.ForDirectory(target), + TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()) + .Which.ExistingSource.Should().Be(link); + + AssertNoChange(); + } + + [Fact] + public void Constructor_NullDirectoryPathComparer_ThrowsArgumentNullException() + { + // Act + var act = () => new ClaudeCodeIntegration(_claudePluginCli, _claudeExecutableLocator, null!); + + // Assert + act.Should().Throw() + .WithParameterName("directoryPathComparer"); + } + + [Fact] + public async Task InstallAsync_DirectoryMarketplaceWithRelativePath_ThrowsConflictNamingPath() + { + // Arrange + SetUpMarketplaces([new ClaudeMarketplace(MarketplaceName, "directory", null, null, "shade-kit")]); + SetUpPluginLists([UserPlugin]); + + // Act + var act = () => _integration.InstallAsync( + MarketplaceSource.ForDirectory(Path.Combine(Path.GetTempPath(), "shade-kit")), + TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()) + .Which.ExistingSource.Should().Be("shade-kit"); + } + + [Fact] + public async Task InstallAsync_MarketplaceNotFirstInList_UsesMarketplaceByName() + { + // Arrange + SetUpMarketplaces( + [ + new ClaudeMarketplace("other", "github", "other/repo", "main", null), + CreateGitHubMarketplace(Repo, "v0.8.0") + ]); + SetUpPluginLists([UserPlugin]); + SetUpUpdate(ClaudePluginUpdateResult.UpToDateOutcome); + + // Act + var result = await _integration.InstallAsync(ReleaseSource, TestContext.Current.CancellationToken); + + // Assert + result.Outcome + .Should().Be(IntegrationOutcome.Current); + } + + [Fact] + public async Task InstallAsync_RemoveFails_ThrowsCauseUnwrapped() + { + // Arrange + var failure = CreateFailure("marketplace", "remove"); + SetUpMarketplaces([CreateGitHubMarketplace(Repo, "v0.7.0")]); + SetUpPluginLists([UserPlugin]); + A.CallTo(() => _claudePluginCli.RemoveMarketplaceAsync(A._, A._)) + .Throws(failure); + + // Act + var act = () => _integration.InstallAsync(ReleaseSource, TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()) + .Which.Should().BeSameAs(failure); + } + + [Fact] + public async Task InstallAsync_AddFailsForMissingMarketplace_ThrowsCauseUnwrapped() + { + // Arrange + var failure = CreateFailure("marketplace", "add"); + SetUpMarketplaces([]); + SetUpPluginLists([]); + A.CallTo(() => _claudePluginCli.AddMarketplaceAsync(A._, A._)).Throws(failure); + + // Act + var act = () => _integration.InstallAsync(ReleaseSource, TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()) + .Which.Should().BeSameAs(failure); + } + + [Fact] + public async Task InstallAsync_UpdateFailsWithKeptMarketplace_ThrowsCauseUnwrapped() + { + // Arrange + var failure = CreateFailure("update"); + SetUpMarketplaces([CreateGitHubMarketplace(Repo, "v0.8.0")]); + SetUpPluginLists([UserPlugin]); + A.CallTo(() => _claudePluginCli.UpdatePluginAsync(A._, A._)).Throws(failure); + + // Act + var act = () => _integration.InstallAsync(ReleaseSource, TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()) + .Which.Should().BeSameAs(failure); + } + + [Fact] + public async Task InstallAsync_PluginNotListedAfterInstall_ThrowsClaudeCommandFailed() + { + // Arrange + SetUpMarketplaces([CreateGitHubMarketplace(Repo, "v0.8.0")]); + SetUpPluginLists([], []); + + // Act + var act = () => _integration.InstallAsync(ReleaseSource, TestContext.Current.CancellationToken); + + // Assert + var exception = (await act.Should().ThrowAsync()).Which; + + exception.CommandText + .Should().Be("claude plugin list --json"); + + exception.Reason + .Should().Be("claude does not list the plugin 'shade-kit@creativecoders-shade-kit' with the scope " + + "'user' after it was installed."); + } + + [Fact] + public async Task InstallAsync_ClaudeNotFound_PropagatesClaudeNotFoundException() + { + // Arrange + A.CallTo(() => _claudePluginCli.ListPluginsAsync(A._)) + .Throws(new ClaudeNotFoundException(["plugin", "list", "--json"], "Not on the PATH.")); + + // Act + var act = () => _integration.InstallAsync(ReleaseSource, TestContext.Current.CancellationToken); + + // Assert + await act.Should().ThrowAsync(); + } + + [Fact] + public async Task InstallAsync_Canceled_PassesTokenToEveryCommand() + { + // Arrange + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; + SetUpMarketplaces([CreateGitHubMarketplace(Repo, "v0.7.0")]); + SetUpPluginLists([UserPlugin], [UserPlugin]); + SetUpUpdate(ClaudePluginUpdateResult.UpdatedOutcome); + + // Act + await _integration.InstallAsync(ReleaseSource, cancellationToken); + + // Assert + A.CallTo(() => _claudePluginCli.ListMarketplacesAsync(cancellationToken)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _claudePluginCli.ListPluginsAsync(cancellationToken)).MustHaveHappenedTwiceExactly(); + A.CallTo(() => _claudePluginCli.RemoveMarketplaceAsync(MarketplaceName, cancellationToken)) + .MustHaveHappenedOnceExactly(); + A.CallTo(() => _claudePluginCli.AddMarketplaceAsync(A._, cancellationToken)) + .MustHaveHappenedOnceExactly(); + A.CallTo(() => _claudePluginCli.UpdatePluginAsync(PluginId, cancellationToken)).MustHaveHappenedOnceExactly(); + } + + [Fact] + public async Task InstallAsync_KeptMarketplace_PassesTokenToMarketplaceRefresh() + { + // Arrange + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; + SetUpMarketplaces([CreateGitHubMarketplace(Repo, "v0.8.0")]); + SetUpPluginLists([UserPlugin]); + SetUpUpdate(ClaudePluginUpdateResult.UpToDateOutcome); + + // Act + await _integration.InstallAsync(ReleaseSource, cancellationToken); + + // Assert + A.CallTo(() => _claudePluginCli.UpdateMarketplaceAsync(MarketplaceName, cancellationToken)) + .MustHaveHappenedOnceExactly(); + } + + [Fact] + public async Task UpdateAsync_PluginNotInstalled_ReturnsNullWithoutChanges() + { + // Arrange + SetUpPluginLists([new ClaudeInstalledPlugin("other@market", "1.0.0", "user", true)]); + + // Act + var result = await _integration.UpdateAsync(GetReleaseSourceAsync, TestContext.Current.CancellationToken); + + // Assert + result + .Should().BeNull(); + + A.CallTo(() => _claudePluginCli.ListMarketplacesAsync(A._)) + .MustNotHaveHappened(); + + AssertNoChange(); + } + + [Fact] + public async Task UpdateAsync_PluginNotInstalled_DoesNotResolveSource() + { + // Arrange + var getSource = A.Fake>>(); + SetUpPluginLists([]); + + // Act + var result = await _integration.UpdateAsync(getSource, TestContext.Current.CancellationToken); + + // Assert + result + .Should().BeNull(); + + A.CallTo(getSource).MustNotHaveHappened(); + } + + [Fact] + public async Task UpdateAsync_PluginInstalled_ResolvesSourceOnceWithTokenBeforeMarketplaceIsRead() + { + // Arrange + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; + var getSource = A.Fake>>(); + A.CallTo(() => getSource(A._)).Returns(ReleaseSource); + SetUpMarketplaces([CreateGitHubMarketplace(Repo, "v0.8.0")]); + SetUpPluginLists([UserPlugin]); + SetUpUpdate(ClaudePluginUpdateResult.UpToDateOutcome); + + // Act + await _integration.UpdateAsync(getSource, cancellationToken); + + // Assert + A.CallTo(() => _claudePluginCli.ListPluginsAsync(cancellationToken)) + .MustHaveHappenedOnceExactly() + .Then(A.CallTo(() => getSource(cancellationToken)).MustHaveHappenedOnceExactly()) + .Then(A.CallTo(() => _claudePluginCli.ListMarketplacesAsync(cancellationToken)) + .MustHaveHappenedOnceExactly()); + } + + [Fact] + public async Task UpdateAsync_KeptMarketplace_ListsPluginsAndMarketplacesOnceEach() + { + // Arrange + SetUpMarketplaces([CreateGitHubMarketplace(Repo, "main")]); + SetUpPluginLists([UserPlugin]); + SetUpUpdate(ClaudePluginUpdateResult.UpToDateOutcome); + + // Act + var result = await _integration.UpdateAsync( + _ => Task.FromResult(MarketplaceSource.ForGitHub(Repo, "main")), TestContext.Current.CancellationToken); + + // Assert + result + .Should().Be(new IntegrationResult("claude", PluginId, IntegrationOutcome.Current, null, null, "main", + true)); + + A.CallTo(() => _claudePluginCli.ListPluginsAsync(A._)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _claudePluginCli.ListMarketplacesAsync(A._)) + .MustHaveHappenedOnceExactly(); + A.CallTo(() => _claudePluginCli.UpdateMarketplaceAsync(MarketplaceName, A._)) + .MustHaveHappenedOnceExactly() + .Then(A.CallTo(() => _claudePluginCli.UpdatePluginAsync(PluginId, A._)) + .MustHaveHappenedOnceExactly()); + } + + [Fact] + public async Task UpdateAsync_GetSourceFails_PropagatesFailureWithoutChanges() + { + // Arrange + var failure = new InvalidMarketplaceSourceException("-x", "It starts with '-'."); + SetUpPluginLists([UserPlugin]); + + // Act + var act = () => _integration.UpdateAsync(_ => Task.FromException(failure), + TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()) + .Which.Should().BeSameAs(failure); + + A.CallTo(() => _claudePluginCli.ListMarketplacesAsync(A._)) + .MustNotHaveHappened(); + + AssertNoChange(); + } + + [Fact] + public async Task UpdateAsync_GetSourceCanceled_PropagatesCancellationUnwrappedWithoutChanges() + { + // Arrange + var canceled = new OperationCanceledException(new CancellationToken(true)); + SetUpPluginLists([UserPlugin]); + + // Act + var act = () => _integration.UpdateAsync(_ => Task.FromException(canceled), + TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()) + .Which.Should().BeSameAs(canceled); + + A.CallTo(() => _claudePluginCli.ListMarketplacesAsync(A._)) + .MustNotHaveHappened(); + + AssertNoChange(); + } + + [Fact] + public async Task UpdateAsync_PluginInstalledWithOtherRef_ListsPluginsTwiceAndMarketplacesOnceWithoutRefresh() + { + // Arrange + SetUpMarketplaces([CreateGitHubMarketplace(Repo, "v0.7.0")]); + SetUpPluginLists([UserPlugin], [UserPlugin]); + SetUpUpdate(ClaudePluginUpdateResult.UpdatedOutcome); + + // Act + await _integration.UpdateAsync(GetReleaseSourceAsync, TestContext.Current.CancellationToken); + + // Assert + A.CallTo(() => _claudePluginCli.ListPluginsAsync(A._)).MustHaveHappenedTwiceExactly(); + A.CallTo(() => _claudePluginCli.ListMarketplacesAsync(A._)) + .MustHaveHappenedOnceExactly(); + A.CallTo(() => _claudePluginCli.UpdateMarketplaceAsync(A._, A._)) + .MustNotHaveHappened(); + } + + [Fact] + public async Task UpdateAsync_CanceledDuringMarketplaceSwitch_ThrowsSwitchCanceled() + { + // Arrange + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; + SetUpMarketplaces([CreateGitHubMarketplace(Repo, "v0.7.0")]); + SetUpPluginLists([UserPlugin]); + A.CallTo(() => _claudePluginCli.AddMarketplaceAsync(A._, A._)) + .Invokes(() => cancellationTokenSource.Cancel()) + .Throws(new OperationCanceledException(cancellationToken)); + + // Act + var act = () => _integration.UpdateAsync(GetReleaseSourceAsync, cancellationToken); + + // Assert + await act.Should().ThrowAsync(); + } + + [Fact] + public async Task UpdateAsync_GetSourceReturnsNull_ThrowsArgumentNullExceptionWithoutChanges() + { + // Arrange + SetUpPluginLists([UserPlugin]); + + // Act + var act = () => _integration.UpdateAsync(_ => Task.FromResult(null!), + TestContext.Current.CancellationToken); + + // Assert + await act.Should().ThrowAsync(); + + AssertNoChange(); + } + + [Fact] + public async Task UpdateAsync_PluginInstalledOnlyWithProjectScope_ReturnsNull() + { + // Arrange + SetUpPluginLists([new ClaudeInstalledPlugin(PluginId, "0.8.0", "project", true)]); + + // Act + var result = await _integration.UpdateAsync(GetReleaseSourceAsync, TestContext.Current.CancellationToken); + + // Assert + result + .Should().BeNull(); + + AssertNoChange(); + } + + [Fact] + public async Task UpdateAsync_PluginInstalledWithOtherRef_SwitchesMarketplaceAndUpdates() + { + // Arrange + SetUpMarketplaces([CreateGitHubMarketplace(Repo, "v0.7.0")]); + SetUpPluginLists([UserPlugin], [UserPlugin]); + SetUpUpdate(ClaudePluginUpdateResult.UpdatedOutcome); + + // Act + var result = await _integration.UpdateAsync(GetReleaseSourceAsync, TestContext.Current.CancellationToken); + + // Assert + result + .Should().Be(new IntegrationResult("claude", PluginId, IntegrationOutcome.Updated, "0.7.0", "0.8.0", + "v0.8.0", true)); + } + + [Fact] + public async Task UpdateAsync_PluginInstalledButMarketplaceMissing_AddsMarketplaceAndUpdates() + { + // Arrange + SetUpMarketplaces([]); + SetUpPluginLists([UserPlugin], [UserPlugin]); + SetUpUpdate(ClaudePluginUpdateResult.UpdatedOutcome); + + // Act + var result = await _integration.UpdateAsync(GetReleaseSourceAsync, TestContext.Current.CancellationToken); + + // Assert + result!.Outcome + .Should().Be(IntegrationOutcome.Updated); + + A.CallTo(() => _claudePluginCli.AddMarketplaceAsync(A._, A._)) + .MustHaveHappenedOnceExactly(); + } + + [Fact] + public async Task UpdateAsync_PluginCurrent_ReturnsCurrent() + { + // Arrange + SetUpMarketplaces([CreateGitHubMarketplace(Repo, "v0.8.0")]); + SetUpPluginLists([UserPlugin]); + SetUpUpdate(ClaudePluginUpdateResult.UpToDateOutcome); + + // Act + var result = await _integration.UpdateAsync(GetReleaseSourceAsync, TestContext.Current.CancellationToken); + + // Assert + result!.Outcome + .Should().Be(IntegrationOutcome.Current); + } + + [Fact] + public async Task UpdateAsync_MarketplaceWithOtherRepo_ThrowsConflictWithoutChanges() + { + // Arrange + SetUpMarketplaces([CreateGitHubMarketplace("other/repo", "v0.8.0")]); + SetUpPluginLists([UserPlugin]); + + // Act + var act = () => _integration.UpdateAsync(GetReleaseSourceAsync, TestContext.Current.CancellationToken); + + // Assert + await act.Should().ThrowAsync(); + + AssertNoChange(); + } + + [Fact] + public async Task GetInstalledAsync_PluginNotInstalledForUser_ReturnsNull() + { + // Arrange + SetUpPluginLists([new ClaudeInstalledPlugin(PluginId, "0.8.0", "project", true)]); + + // Act + var installed = await _integration.GetInstalledAsync(TestContext.Current.CancellationToken); + + // Assert + installed + .Should().BeNull(); + + A.CallTo(() => _claudePluginCli.ListMarketplacesAsync(A._)) + .MustNotHaveHappened(); + } + + [Theory] + [InlineData("v0.8.0", "0.8.0", true)] + [InlineData("main", null, false)] + [InlineData(null, null, true)] + public async Task GetInstalledAsync_PluginInstalledWithGitHubMarketplace_ReturnsRefKitVersionAndEnabled( + string? @ref, string? expectedKitVersion, bool enabled) + { + // Arrange + SetUpPluginLists([UserPlugin with { Enabled = enabled }]); + SetUpMarketplaces([CreateGitHubMarketplace(Repo, @ref)]); + + // Act + var installed = await _integration.GetInstalledAsync(TestContext.Current.CancellationToken); + + // Assert + installed + .Should().Be(new InstalledIntegration("claude", PluginId, expectedKitVersion, @ref, enabled)); + } + + [Fact] + public async Task GetInstalledAsync_DirectoryMarketplace_ReturnsNullRefAndKitVersion() + { + // Arrange + SetUpPluginLists([UserPlugin]); + SetUpMarketplaces([new ClaudeMarketplace(MarketplaceName, "directory", null, null, "/src/shade-kit")]); + + // Act + var installed = await _integration.GetInstalledAsync(TestContext.Current.CancellationToken); + + // Assert + installed + .Should().Be(new InstalledIntegration("claude", PluginId, null, null, true)); + } + + [Fact] + public async Task GetInstalledAsync_MarketplaceMissing_ReturnsNullRefAndKitVersion() + { + // Arrange + SetUpPluginLists([UserPlugin]); + SetUpMarketplaces([CreateGitHubMarketplace(Repo, "v0.8.0") with { Name = "other" }]); + + // Act + var installed = await _integration.GetInstalledAsync(TestContext.Current.CancellationToken); + + // Assert + installed + .Should().Be(new InstalledIntegration("claude", PluginId, null, null, true)); + } + + [Fact] + public async Task GetInstalledAsync_MarketplaceOfOtherKindWithRef_ReturnsNullRefAndKitVersion() + { + // Arrange + SetUpPluginLists([UserPlugin]); + SetUpMarketplaces([new ClaudeMarketplace(MarketplaceName, "git", null, "v0.8.0", null)]); + + // Act + var installed = await _integration.GetInstalledAsync(TestContext.Current.CancellationToken); + + // Assert + installed + .Should().Be(new InstalledIntegration("claude", PluginId, null, null, true)); + } + + [Theory] + [InlineData(null)] + [InlineData("User")] + public async Task GetInstalledAsync_PluginWithOtherScope_ReturnsNull(string? scope) + { + // Arrange + SetUpPluginLists([UserPlugin with { Scope = scope }]); + + // Act + var installed = await _integration.GetInstalledAsync(TestContext.Current.CancellationToken); + + // Assert + installed + .Should().BeNull(); + } + + [Fact] + public async Task GetInstalledAsync_MarketplaceListFails_PropagatesFailure() + { + // Arrange + SetUpPluginLists([UserPlugin]); + A.CallTo(() => _claudePluginCli.ListMarketplacesAsync(A._)) + .Throws(CreateFailure("marketplace", "list")); + + // Act + var act = () => _integration.GetInstalledAsync(TestContext.Current.CancellationToken); + + // Assert + await act.Should().ThrowAsync(); + } + + [Fact] + public async Task GetInstalledAsync_ListFails_PropagatesFailure() + { + // Arrange + A.CallTo(() => _claudePluginCli.ListPluginsAsync(A._)).Throws(CreateFailure("list")); + + // Act + var act = () => _integration.GetInstalledAsync(TestContext.Current.CancellationToken); + + // Assert + await act.Should().ThrowAsync(); + } + + private static Task GetReleaseSourceAsync(CancellationToken cancellationToken) + { + return Task.FromResult(ReleaseSource); + } + + private static ClaudeMarketplace CreateGitHubMarketplace(string repo, string? @ref) + { + return new ClaudeMarketplace(MarketplaceName, "github", repo, @ref, null); + } + + private static ClaudeCommandFailedException CreateFailure(params string[] command) + { + return new ClaudeCommandFailedException(["plugin", .. command, "--json"], 1, "claude failed."); + } + + private void SetUpMarketplaces(IReadOnlyList marketplaces) + { + A.CallTo(() => _claudePluginCli.ListMarketplacesAsync(A._)).Returns(marketplaces); + } + + // Each call of ListPluginsAsync returns the next list. + private void SetUpPluginLists(IReadOnlyList first, + IReadOnlyList? second = null, IReadOnlyList? third = null) + { + IReadOnlyList[] pluginLists = + [.. new[] { first, second, third }.OfType>()]; + + A.CallTo(() => _claudePluginCli.ListPluginsAsync(A._)) + .ReturnsNextFromSequence(pluginLists); + } + + private void SetUpUpdate(string updateOutcome) + { + A.CallTo(() => _claudePluginCli.UpdatePluginAsync(A._, A._)) + .Returns(new ClaudePluginUpdateResult(updateOutcome, "0.7.0", "0.8.0")); + } + + private void AssertNoChange() + { + A.CallTo(() => _claudePluginCli.AddMarketplaceAsync(A._, A._)) + .MustNotHaveHappened(); + A.CallTo(() => _claudePluginCli.RemoveMarketplaceAsync(A._, A._)) + .MustNotHaveHappened(); + A.CallTo(() => _claudePluginCli.UpdateMarketplaceAsync(A._, A._)) + .MustNotHaveHappened(); + A.CallTo(() => _claudePluginCli.InstallPluginAsync(A._, A._)) + .MustNotHaveHappened(); + A.CallTo(() => _claudePluginCli.UpdatePluginAsync(A._, A._)) + .MustNotHaveHappened(); + } +} diff --git a/tests/CreativeCoders.ShadeKit.Core.Tests/Integrations/Claude/ClaudeCommandRunnerTests.cs b/tests/CreativeCoders.ShadeKit.Core.Tests/Integrations/Claude/ClaudeCommandRunnerTests.cs new file mode 100644 index 0000000..f6db30d --- /dev/null +++ b/tests/CreativeCoders.ShadeKit.Core.Tests/Integrations/Claude/ClaudeCommandRunnerTests.cs @@ -0,0 +1,209 @@ +using System.ComponentModel; +using AwesomeAssertions; +using CreativeCoders.ShadeKit.Core.Integrations.Claude; +using CreativeCoders.ShadeKit.Core.Integrations.Exceptions; +using CreativeCoders.ShadeKit.Tests.Shared; +using FakeItEasy; + +namespace CreativeCoders.ShadeKit.Core.Tests.Integrations.Claude; + +// These tests never start the real claude: the locator is faked, and the only start attempt targets a file that does +// not exist. +public class ClaudeCommandRunnerTests +{ + private const string NotFoundReason = + "The Claude Code CLI claude was not found in any absolute directory of the PATH environment variable."; + + private static readonly string[] ListArguments = ["plugin", "list", "--json"]; + + private readonly IClaudeExecutableLocator _claudeExecutableLocator = A.Fake(); + + [Fact] + public void Constructor_NullClaudeExecutableLocator_ThrowsArgumentNullException() + { + // Act + var act = () => new ClaudeCommandRunner(null!); + + // Assert + act.Should().Throw() + .WithParameterName("claudeExecutableLocator"); + } + + [Fact] + public void EnvironmentVariables_Always_DisableColors() + { + // Act + var environmentVariables = ClaudeCommandRunner.EnvironmentVariables; + + // Assert + environmentVariables + .Should().BeEquivalentTo(new Dictionary { ["NO_COLOR"] = "1" }); + } + + [Fact] + public void Tool_Always_UsesClaudeNameAndEnvironmentVariables() + { + // Act + var tool = ClaudeCommandRunner.Tool; + + // Assert + tool.Name + .Should().Be("claude"); + + tool.EnvironmentVariables + .Should().BeSameAs(ClaudeCommandRunner.EnvironmentVariables); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + public async Task RunAsync_ClaudeNotFound_ThrowsClaudeNotFoundException(string? claudeExecutablePath) + { + // Arrange + A.CallTo(() => _claudeExecutableLocator.FindClaudeExecutable()).Returns(claudeExecutablePath); + var sut = new ClaudeCommandRunner(_claudeExecutableLocator); + + // Act + var act = () => sut.RunAsync(Path.GetTempPath(), ListArguments, TestContext.Current.CancellationToken); + + // Assert + var exception = (await act.Should().ThrowAsync()).Which; + + exception.Arguments + .Should().Equal(ListArguments); + + exception.Reason + .Should().Be(NotFoundReason); + + exception.InnerException + .Should().BeNull(); + } + + [Theory] + [InlineData("claude")] + [InlineData("./claude")] + [InlineData("bin/claude")] + [InlineData(" ")] + [InlineData(@"C:claude.exe")] + [InlineData(@"\claude.exe")] + public async Task RunAsync_ClaudeLocatorReturnsRelativePath_ThrowsClaudeUnavailableExceptionWithoutStarting( + string relativePath) + { + // Arrange + A.CallTo(() => _claudeExecutableLocator.FindClaudeExecutable()).Returns(relativePath); + var sut = new ClaudeCommandRunner(_claudeExecutableLocator); + + // Act + var act = () => sut.RunAsync(Path.GetTempPath(), ListArguments, TestContext.Current.CancellationToken); + + // Assert + var exception = (await act.Should().ThrowExactlyAsync()).Which; + + exception.Reason + .Should().Be($"The claude executable path '{relativePath}' is not absolute, so it is not started."); + + exception.InnerException + .Should().BeNull(); + } + + [Fact] + public async Task RunAsync_ExecutableCannotBeStarted_ThrowsClaudeUnavailableExceptionWithStartFailure() + { + // Arrange + using var tempDirectory = new TempKitDirectory(); + var missingExecutablePath = Path.Combine(tempDirectory.RootPath, "missing", "claude"); + + A.CallTo(() => _claudeExecutableLocator.FindClaudeExecutable()).Returns(missingExecutablePath); + var sut = new ClaudeCommandRunner(_claudeExecutableLocator); + + // Act + var act = () => sut.RunAsync(tempDirectory.RootPath, ListArguments, TestContext.Current.CancellationToken); + + // Assert + var exception = (await act.Should().ThrowExactlyAsync()).Which; + + exception.Arguments + .Should().Equal(ListArguments); + + exception.Reason + .Should().StartWith($"The claude executable '{missingExecutablePath}' could not be started: ") + .And.EndWith("."); + + exception.InnerException + .Should().BeOfType(); + } + + [Fact] + public async Task RunAsync_CalledTwice_LocatesClaudeOnEveryRun() + { + // Arrange + A.CallTo(() => _claudeExecutableLocator.FindClaudeExecutable()).Returns(null); + var sut = new ClaudeCommandRunner(_claudeExecutableLocator); + + // Act + var firstAct = () => sut.RunAsync(Path.GetTempPath(), ListArguments, TestContext.Current.CancellationToken); + var secondAct = () => sut.RunAsync(Path.GetTempPath(), ListArguments, TestContext.Current.CancellationToken); + + // Assert + await firstAct.Should().ThrowAsync(); + await secondAct.Should().ThrowAsync(); + + A.CallTo(() => _claudeExecutableLocator.FindClaudeExecutable()) + .MustHaveHappenedTwiceExactly(); + } + + [Fact] + public async Task RunAsync_CanceledToken_ThrowsOperationCanceledExceptionWithoutLocatingClaude() + { + // Arrange + using var cancellationTokenSource = new CancellationTokenSource(); + await cancellationTokenSource.CancelAsync(); + + var sut = new ClaudeCommandRunner(_claudeExecutableLocator); + + // Act + var act = () => sut.RunAsync(Path.GetTempPath(), ListArguments, cancellationTokenSource.Token); + + // Assert + await act.Should().ThrowAsync(); + + A.CallTo(() => _claudeExecutableLocator.FindClaudeExecutable()) + .MustNotHaveHappened(); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public async Task RunAsync_InvalidWorkingDirectory_ThrowsArgumentException(string? workingDirectory) + { + // Arrange + var sut = new ClaudeCommandRunner(_claudeExecutableLocator); + + // Act + var act = () => sut.RunAsync(workingDirectory!, ListArguments, TestContext.Current.CancellationToken); + + // Assert + await act.Should().ThrowAsync(); + + A.CallTo(() => _claudeExecutableLocator.FindClaudeExecutable()) + .MustNotHaveHappened(); + } + + [Fact] + public async Task RunAsync_NullArguments_ThrowsArgumentNullException() + { + // Arrange + var sut = new ClaudeCommandRunner(_claudeExecutableLocator); + + // Act + var act = () => sut.RunAsync(Path.GetTempPath(), null!, TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()) + .WithParameterName("arguments"); + + A.CallTo(() => _claudeExecutableLocator.FindClaudeExecutable()) + .MustNotHaveHappened(); + } +} diff --git a/tests/CreativeCoders.ShadeKit.Core.Tests/Integrations/Claude/ClaudeExecutableLocatorTests.cs b/tests/CreativeCoders.ShadeKit.Core.Tests/Integrations/Claude/ClaudeExecutableLocatorTests.cs new file mode 100644 index 0000000..673af7c --- /dev/null +++ b/tests/CreativeCoders.ShadeKit.Core.Tests/Integrations/Claude/ClaudeExecutableLocatorTests.cs @@ -0,0 +1,105 @@ +using AwesomeAssertions; +using CreativeCoders.ShadeKit.Core.Integrations.Claude; +using CreativeCoders.ShadeKit.Core.Processes; + +namespace CreativeCoders.ShadeKit.Core.Tests.Integrations.Claude; + +// The PATH rules are covered by PathExecutableSearchTests and the caching of the shared base class by +// GitExecutableLocatorTests; these tests cover the claude names. +public class ClaudeExecutableLocatorTests +{ + private static readonly Func AllExecutable = static _ => true; + + [Theory] + [InlineData("/opt/none:/usr/local/bin:/usr/bin", "/usr/local/bin/claude")] + [InlineData("/opt/homebrew/bin/", "/opt/homebrew/bin/claude")] + public void FindClaudeExecutable_UnixPathContainsClaude_ReturnsAbsoluteClaudePath(string pathVariable, + string expected) + { + // Arrange + var sut = new ClaudeExecutableLocator(() => pathVariable, false, x => x == expected, AllExecutable); + + // Act + var result = sut.FindClaudeExecutable(); + + // Assert + result + .Should().Be(expected); + } + + [Theory] + [InlineData(@"C:\Windows;C:\Users\me\.local\bin", @"C:\Users\me\.local\bin\claude.exe")] + [InlineData(@"""C:\Users\me\.local\bin\""", @"C:\Users\me\.local\bin\claude.exe")] + public void FindClaudeExecutable_WindowsPathContainsClaudeExe_ReturnsAbsoluteClaudeExePath(string pathVariable, + string expected) + { + // Arrange + var sut = new ClaudeExecutableLocator(() => pathVariable, true, x => x == expected, AllExecutable); + + // Act + var result = sut.FindClaudeExecutable(); + + // Assert + result + .Should().Be(expected); + } + + [Fact] + public void FindClaudeExecutable_WindowsPathContainsOnlyNpmShims_ReturnsNull() + { + // Arrange + string[] existingFiles = [@"C:\npm\claude.cmd", @"C:\npm\claude.ps1", @"C:\npm\claude"]; + var sut = new ClaudeExecutableLocator(() => @"C:\npm", true, existingFiles.Contains, AllExecutable); + + // Act + var result = sut.FindClaudeExecutable(); + + // Assert + result + .Should().BeNull(); + } + + [Fact] + public void FindClaudeExecutable_UnixPathContainsOnlyClaudeExe_ReturnsNull() + { + // Arrange + var sut = new ClaudeExecutableLocator(() => "/opt/bin", false, static x => x == "/opt/bin/claude.exe", + AllExecutable); + + // Act + var result = sut.FindClaudeExecutable(); + + // Assert + result + .Should().BeNull(); + } + + [Fact] + public void FindClaudeExecutable_UnixPathWithoutClaude_ReturnsNull() + { + // Arrange + var sut = new ClaudeExecutableLocator(() => "/usr/bin:/bin", false, static _ => false, AllExecutable); + + // Act + var result = sut.FindClaudeExecutable(); + + // Assert + result + .Should().BeNull(); + } + + [Fact] + public void FindClaudeExecutable_DefaultConstructor_ReturnsNullOrFullyQualifiedExistingExecutableFile() + { + // Arrange + var sut = new ClaudeExecutableLocator(); + + // Act + var result = sut.FindClaudeExecutable(); + + // Assert + result + .Should().Match(x => x == null || (Path.IsPathFullyQualified(x) && File.Exists(x) + && PathExecutableSearch.HasUnixExecuteBit(x))); + } +} diff --git a/tests/CreativeCoders.ShadeKit.Core.Tests/Integrations/Claude/ClaudePluginCliTests.cs b/tests/CreativeCoders.ShadeKit.Core.Tests/Integrations/Claude/ClaudePluginCliTests.cs new file mode 100644 index 0000000..bcea80d --- /dev/null +++ b/tests/CreativeCoders.ShadeKit.Core.Tests/Integrations/Claude/ClaudePluginCliTests.cs @@ -0,0 +1,1137 @@ +using AwesomeAssertions; +using CreativeCoders.ShadeKit.Core.Integrations.Claude; +using CreativeCoders.ShadeKit.Core.Integrations.Exceptions; +using CreativeCoders.ShadeKit.Core.Processes; +using FakeItEasy; + +namespace CreativeCoders.ShadeKit.Core.Tests.Integrations.Claude; + +// The runner is faked with the output of Claude Code 2.1.323, so these tests never start claude. +public class ClaudePluginCliTests +{ + private const string WorkingDirectory = "/home/me"; + + private const string PluginId = "shade-kit@creativecoders-shade-kit"; + + private const string GitHubSource = "CreativeCodersTeam/shade-kit#v0.8.0"; + + private const string MarketplaceListOutput = + """ + [ + { + "name": "creativecoders-ai-store", + "source": "github", + "repo": "CreativeCodersTeam/ai-store", + "ref": "main", + "installLocation": "/home/me/.claude/plugins/marketplaces/creativecoders-ai-store" + }, + { + "name": "anthropic-agent-skills", + "source": "github", + "repo": "anthropics/skills", + "installLocation": "/home/me/.claude/plugins/marketplaces/anthropic-agent-skills" + }, + { + "name": "creativecoders-shade-kit", + "source": "directory", + "path": "/src/shade-kit", + "installLocation": "/src/shade-kit" + } + ] + """; + + private const string PluginListOutput = + """ + [ + { + "id": "shade-kit@creativecoders-shade-kit", + "version": "0.8.0", + "scope": "user", + "enabled": true, + "installPath": "/home/me/.claude/plugins/cache/creativecoders-shade-kit/shade-kit/0.8.0", + "installedAt": "2026-11-13T20:01:57.417Z", + "lastUpdated": "2026-11-13T20:01:57.417Z", + "projectEnabled": false + }, + { + "id": "cc-ai-dotnet@creativecoders-ai-store", + "version": "4972bfa14908", + "scope": "project", + "enabled": false + } + ] + """; + + private const string UpdateNotFoundOutput = + """{"command":"update","outcome":"failed","plugin":"nope@creativecoders-shade-kit","pluginId":"nope@creativecoders-shade-kit","scope":"user","message":"Plugin \"nope\" not found","failureCode":"not_found"}"""; + + private readonly IClaudeCommandRunner _claudeCommandRunner = A.Fake(); + + private string? _actualWorkingDirectory; + + private IReadOnlyList? _actualArguments; + + [Fact] + public void Constructor_NullClaudeCommandRunner_ThrowsArgumentNullException() + { + // Act + var act = () => new ClaudePluginCli(null!); + + // Assert + act.Should().Throw() + .WithParameterName("claudeCommandRunner"); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public void Constructor_InvalidWorkingDirectory_ThrowsArgumentException(string? workingDirectory) + { + // Act + var act = () => new ClaudePluginCli(_claudeCommandRunner, workingDirectory!); + + // Assert + act.Should().Throw() + .WithParameterName(nameof(workingDirectory)); + } + + [Fact] + public void Constructor_DefaultWorkingDirectory_UsesExistingHomeOrTemporaryDirectory() + { + // Act + var sut = new ClaudePluginCli(_claudeCommandRunner); + + // Assert + sut.WorkingDirectory + .Should().BeOneOf(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), Path.GetTempPath()); + + Directory.Exists(sut.WorkingDirectory) + .Should().BeTrue(); + } + + [Fact] + public async Task ListMarketplacesAsync_ClaudeListsMarketplaces_ReturnsMarketplacesInOrderAndIgnoresUnknownFields() + { + // Arrange + SetUpRun(0, MarketplaceListOutput); + var sut = CreateSut(); + + // Act + var marketplaces = await sut.ListMarketplacesAsync(TestContext.Current.CancellationToken); + + // Assert + marketplaces + .Should().Equal( + new ClaudeMarketplace("creativecoders-ai-store", ClaudeMarketplace.GitHubSourceKind, + "CreativeCodersTeam/ai-store", "main", null), + new ClaudeMarketplace("anthropic-agent-skills", ClaudeMarketplace.GitHubSourceKind, + "anthropics/skills", null, null), + new ClaudeMarketplace("creativecoders-shade-kit", ClaudeMarketplace.DirectorySourceKind, null, null, + "/src/shade-kit")); + + AssertRun("plugin", "marketplace", "list", "--json"); + } + + [Fact] + public async Task ListMarketplacesAsync_EmptyArray_ReturnsEmptyList() + { + // Arrange + SetUpRun(0, "[]\n"); + var sut = CreateSut(); + + // Act + var marketplaces = await sut.ListMarketplacesAsync(TestContext.Current.CancellationToken); + + // Assert + marketplaces + .Should().BeEmpty(); + } + + [Fact] + public async Task ListMarketplacesAsync_NullOptionalFields_ReturnsNullValues() + { + // Arrange + SetUpRun(0, """[{"name":"x","source":null,"repo":null,"ref":null,"path":null}]"""); + var sut = CreateSut(); + + // Act + var marketplaces = await sut.ListMarketplacesAsync(TestContext.Current.CancellationToken); + + // Assert + marketplaces + .Should().Equal(new ClaudeMarketplace("x", null, null, null, null)); + } + + [Theory] + [InlineData("""{"name":"x"}""", "The output of claude is not a JSON array.")] + [InlineData("""[{"name":"x"}, 3]""", "The entry 2 of the claude output is not a JSON object.")] + [InlineData("""[{"source":"github"}]""", "The entry 1 of the claude output has no non-empty 'name' string.")] + [InlineData("""[{"name":null}]""", "The entry 1 of the claude output has no non-empty 'name' string.")] + [InlineData("""[{"name":""}]""", "The entry 1 of the claude output has no non-empty 'name' string.")] + [InlineData("""[{"name":" "}]""", "The entry 1 of the claude output has no non-empty 'name' string.")] + [InlineData("""[{"name":42}]""", "The field 'name' of the entry 1 of the claude output is not a string.")] + [InlineData("""[{"name":"x","source":1}]""", + "The field 'source' of the entry 1 of the claude output is not a string.")] + [InlineData("""[{"name":"x","ref":["main"]}]""", + "The field 'ref' of the entry 1 of the claude output is not a string.")] + [InlineData("""[{"name":"x","repo":42}]""", + "The field 'repo' of the entry 1 of the claude output is not a string.")] + [InlineData("""[{"name":"x","path":{"abs":"/src"}}]""", + "The field 'path' of the entry 1 of the claude output is not a string.")] + public async Task ListMarketplacesAsync_UnexpectedShape_ThrowsClaudeCommandFailedExceptionNamingProblem( + string output, string expectedReason) + { + // Arrange + SetUpRun(0, output); + var sut = CreateSut(); + + // Act + var act = () => sut.ListMarketplacesAsync(TestContext.Current.CancellationToken); + + // Assert + var exception = (await act.Should().ThrowAsync()).Which; + + exception.Reason + .Should().Be(expectedReason); + + exception.ExitCode + .Should().Be(0); + + exception.Arguments + .Should().Equal("plugin", "marketplace", "list", "--json"); + } + + [Theory] + [InlineData("")] + [InlineData("Usage: claude plugin marketplace list")] + [InlineData("[{\"name\":")] + public async Task ListMarketplacesAsync_OutputIsNotJson_ThrowsClaudeCommandFailedExceptionWithJsonError( + string output) + { + // Arrange + SetUpRun(0, output); + var sut = CreateSut(); + + // Act + var act = () => sut.ListMarketplacesAsync(TestContext.Current.CancellationToken); + + // Assert + var exception = (await act.Should().ThrowAsync()).Which; + + exception.Reason + .Should().StartWith("The output of claude is not valid JSON: ") + .And.EndWith("."); + + exception.InnerException + .Should().BeAssignableTo(); + } + + [Fact] + public async Task ListMarketplacesAsync_NonZeroExitCodeWithFailureLine_ThrowsClaudeCommandFailedExceptionWithDetails() + { + // Arrange + SetUpRun(1, """{"command":"marketplace-list","outcome":"failed","message":"Broken settings.","failureCode":"invalid_settings"}"""); + var sut = CreateSut(); + + // Act + var act = () => sut.ListMarketplacesAsync(TestContext.Current.CancellationToken); + + // Assert + var exception = (await act.Should().ThrowAsync()).Which; + + exception.Reason + .Should().Be("claude exited with the exit code 1 and reported the outcome 'failed': Broken settings " + + "(failure code 'invalid_settings')."); + + exception.ExitCode + .Should().Be(1); + + exception.ClaudeMessage + .Should().Be("Broken settings."); + + exception.FailureCode + .Should().Be("invalid_settings"); + } + + [Fact] + public async Task ListMarketplacesAsync_NonZeroExitCodeWithValidArray_ThrowsClaudeCommandFailedException() + { + // Arrange + SetUpRun(2, MarketplaceListOutput); + var sut = CreateSut(); + + // Act + var act = () => sut.ListMarketplacesAsync(TestContext.Current.CancellationToken); + + // Assert + var exception = (await act.Should().ThrowAsync()).Which; + + exception.Reason + .Should().Be("claude exited with the exit code 2 and printed no JSON object on standard output."); + + exception.ExitCode + .Should().Be(2); + } + + [Fact] + public async Task ListPluginsAsync_ClaudeListsPlugins_ReturnsPluginsInOrderAndIgnoresUnknownFields() + { + // Arrange + SetUpRun(0, PluginListOutput); + var sut = CreateSut(); + + // Act + var plugins = await sut.ListPluginsAsync(TestContext.Current.CancellationToken); + + // Assert + plugins + .Should().Equal( + new ClaudeInstalledPlugin(PluginId, "0.8.0", ClaudeInstalledPlugin.UserScope, true), + new ClaudeInstalledPlugin("cc-ai-dotnet@creativecoders-ai-store", "4972bfa14908", "project", false)); + + AssertRun("plugin", "list", "--json"); + } + + [Fact] + public async Task ListPluginsAsync_MissingVersionAndScope_ReturnsNullValues() + { + // Arrange + SetUpRun(0, """[{"id":"x@y","enabled":false}]"""); + var sut = CreateSut(); + + // Act + var plugins = await sut.ListPluginsAsync(TestContext.Current.CancellationToken); + + // Assert + plugins + .Should().Equal(new ClaudeInstalledPlugin("x@y", null, null, false)); + } + + [Theory] + [InlineData("""[{"version":"1.0.0","enabled":true}]""", "The entry 1 of the claude output has no non-empty 'id' string.")] + [InlineData("""[{"id":"","enabled":true}]""", "The entry 1 of the claude output has no non-empty 'id' string.")] + [InlineData("""[{"id":"x@y"}]""", "The entry 1 of the claude output has no 'enabled' Boolean.")] + [InlineData("""[{"id":"x@y","enabled":null}]""", "The entry 1 of the claude output has no 'enabled' Boolean.")] + [InlineData("""[{"id":"x@y","enabled":true,"version":1.2}]""", + "The field 'version' of the entry 1 of the claude output is not a string.")] + [InlineData("""[{"id":"x@y","enabled":"true"}]""", "The entry 1 of the claude output has no 'enabled' Boolean.")] + [InlineData("""[{"id":"x@y","enabled":true,"scope":1}]""", + "The field 'scope' of the entry 1 of the claude output is not a string.")] + [InlineData("""["x@y"]""", "The entry 1 of the claude output is not a JSON object.")] + public async Task ListPluginsAsync_UnexpectedShape_ThrowsClaudeCommandFailedExceptionNamingProblem(string output, + string expectedReason) + { + // Arrange + SetUpRun(0, output); + var sut = CreateSut(); + + // Act + var act = () => sut.ListPluginsAsync(TestContext.Current.CancellationToken); + + // Assert + var exception = (await act.Should().ThrowAsync()).Which; + + exception.Reason + .Should().Be(expectedReason); + } + + [Fact] + public async Task AddMarketplaceAsync_ClaudeReportsOk_RunsAddWithUserScope() + { + // Arrange + SetUpRun(0, """{"command":"marketplace-add","outcome":"ok","marketplace":"creativecoders-shade-kit","message":"Successfully added marketplace: creativecoders-shade-kit (declared in user settings)"}""" + "\n"); + var sut = CreateSut(); + + // Act + var act = () => sut.AddMarketplaceAsync(GitHubSource, TestContext.Current.CancellationToken); + + // Assert + await act.Should().NotThrowAsync(); + + AssertRun("plugin", "marketplace", "add", GitHubSource, "--scope", "user", "--json"); + } + + [Fact] + public async Task AddMarketplaceAsync_LocalDirectorySource_PassesPathAsOneArgument() + { + // Arrange + const string source = "/Users/me/src/shade kit"; + SetUpRun(0, """{"command":"marketplace-add","outcome":"ok","message":"Marketplace is already on disk."}"""); + var sut = CreateSut(); + + // Act + await sut.AddMarketplaceAsync(source, TestContext.Current.CancellationToken); + + // Assert + AssertRun("plugin", "marketplace", "add", source, "--scope", "user", "--json"); + } + + [Fact] + public async Task AddMarketplaceAsync_ClaudeRejectsRef_ThrowsClaudeCommandFailedExceptionWithClaudeMessage() + { + // Arrange + SetUpRun(1, """{"command":"marketplace-add","outcome":"failed","message":"Remote branch 0123abc not found"}""", + "✘ Failed to add marketplace: Remote branch 0123abc not found\n"); + var sut = CreateSut(); + + // Act + var act = () => sut.AddMarketplaceAsync("owner/repo#0123abc", TestContext.Current.CancellationToken); + + // Assert + var exception = (await act.Should().ThrowAsync()).Which; + + exception.Reason + .Should().Be("claude exited with the exit code 1 and reported the outcome 'failed': Remote branch " + + "0123abc not found."); + + exception.ClaudeMessage + .Should().Be("Remote branch 0123abc not found"); + + exception.FailureCode + .Should().BeNull(); + + exception.CommandText + .Should().Be("claude plugin marketplace add owner/repo#0123abc --scope user --json"); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + [InlineData("--scope")] + [InlineData("-h")] + public async Task AddMarketplaceAsync_InvalidSource_ThrowsArgumentExceptionWithoutRunningClaude(string? source) + { + // Arrange + var sut = CreateSut(); + + // Act + var act = () => sut.AddMarketplaceAsync(source!, TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()) + .WithParameterName(nameof(source)); + + AssertNoRun(); + } + + [Fact] + public async Task RemoveMarketplaceAsync_ClaudeReportsOk_RunsRemoveWithoutScope() + { + // Arrange + SetUpRun(0, """{"command":"marketplace-remove","outcome":"ok","marketplace":"creativecoders-shade-kit","message":"Successfully removed marketplace: creativecoders-shade-kit"}"""); + var sut = CreateSut(); + + // Act + await sut.RemoveMarketplaceAsync("creativecoders-shade-kit", TestContext.Current.CancellationToken); + + // Assert + AssertRun("plugin", "marketplace", "remove", "creativecoders-shade-kit", "--json"); + } + + [Fact] + public async Task RemoveMarketplaceAsync_UnknownMarketplace_ThrowsClaudeCommandFailedExceptionWithFailureCode() + { + // Arrange + SetUpRun(1, """{"command":"marketplace-remove","marketplace":"nope","outcome":"failed","message":"Marketplace 'nope' not found","failureCode":"not_configured"}""", + "✘ Failed to remove marketplace: Marketplace 'nope' not found\n"); + var sut = CreateSut(); + + // Act + var act = () => sut.RemoveMarketplaceAsync("nope", TestContext.Current.CancellationToken); + + // Assert + var exception = (await act.Should().ThrowAsync()).Which; + + exception.Reason + .Should().Be("claude exited with the exit code 1 and reported the outcome 'failed': Marketplace 'nope' " + + "not found (failure code 'not_configured')."); + + exception.FailureCode + .Should().Be("not_configured"); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("-x")] + public async Task RemoveMarketplaceAsync_InvalidName_ThrowsArgumentExceptionWithoutRunningClaude(string? name) + { + // Arrange + var sut = CreateSut(); + + // Act + var act = () => sut.RemoveMarketplaceAsync(name!, TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()) + .WithParameterName(nameof(name)); + + AssertNoRun(); + } + + [Fact] + public async Task UpdateMarketplaceAsync_ClaudeReportsOk_RunsMarketplaceUpdateWithName() + { + // Arrange (output of Claude Code 2.1.323 for a git marketplace that follows a branch) + SetUpRun(0, """{"command":"marketplace-update","outcome":"ok","marketplace":"creativecoders-shade-kit","message":"Refreshing marketplace cache (timeout: 120s)…\nCloning repository (timeout: 120s): https://github.com/CreativeCodersTeam/shade-kit.git (ref: main)\nReplacing the existing marketplace clone…\nClone complete, validating marketplace…\nSuccessfully updated marketplace: creativecoders-shade-kit"}"""); + var sut = CreateSut(); + + // Act + await sut.UpdateMarketplaceAsync("creativecoders-shade-kit", TestContext.Current.CancellationToken); + + // Assert + AssertRun("plugin", "marketplace", "update", "creativecoders-shade-kit", "--json"); + } + + [Fact] + public async Task UpdateMarketplaceAsync_UnknownMarketplace_ThrowsClaudeCommandFailedExceptionWithFailureCode() + { + // Arrange (output of Claude Code 2.1.323) + SetUpRun(1, """{"command":"marketplace-update","marketplace":"nope","outcome":"failed","message":"Marketplace 'nope' not found. Available marketplaces: creativecoders-shade-kit","failureCode":"not_configured"}""", + "✘ Failed to update marketplace(s): Marketplace 'nope' not found.\n"); + var sut = CreateSut(); + + // Act + var act = () => sut.UpdateMarketplaceAsync("nope", TestContext.Current.CancellationToken); + + // Assert + var exception = (await act.Should().ThrowAsync()).Which; + + exception.CommandText + .Should().Be("claude plugin marketplace update nope --json"); + + exception.FailureCode + .Should().Be("not_configured"); + } + + [Fact] + public async Task UpdateMarketplaceAsync_FailedOutcomeWithExitCodeZero_ThrowsClaudeCommandFailedException() + { + // Arrange + SetUpRun(0, """{"command":"marketplace-update","outcome":"failed","message":"Clone failed."}"""); + var sut = CreateSut(); + + // Act + var act = () => sut.UpdateMarketplaceAsync("creativecoders-shade-kit", TestContext.Current.CancellationToken); + + // Assert + await act.Should().ThrowAsync(); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + [InlineData("-x")] + public async Task UpdateMarketplaceAsync_InvalidName_ThrowsArgumentExceptionWithoutRunningClaude(string? name) + { + // Arrange + var sut = CreateSut(); + + // Act + var act = () => sut.UpdateMarketplaceAsync(name!, TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()) + .WithParameterName(nameof(name)); + + AssertNoRun(); + } + + [Fact] + public async Task InstallPluginAsync_NewPlugin_RunsInstallWithUserScopeAndReturnsNoVersions() + { + // Arrange + SetUpRun(0, """{"command":"install","outcome":"ok","plugin":"shade-kit@creativecoders-shade-kit","pluginId":"shade-kit@creativecoders-shade-kit","scope":"user","message":"Successfully installed plugin: shade-kit@creativecoders-shade-kit (scope: user)"}"""); + var sut = CreateSut(); + + // Act + var result = await sut.InstallPluginAsync(PluginId, TestContext.Current.CancellationToken); + + // Assert + result + .Should().Be(new ClaudePluginInstallResult(null, null)); + + AssertRun("plugin", "install", PluginId, "--scope", "user", "--json"); + } + + [Fact] + public async Task InstallPluginAsync_PluginAlreadyInstalled_ReturnsInstalledAndAvailableVersion() + { + // Arrange + SetUpRun(0, """{"command":"install","outcome":"ok","pluginId":"shade-kit@creativecoders-shade-kit","scope":"user","message":"Already installed.","installedVersion":"0.8.0","availableVersion":"0.9.0"}"""); + var sut = CreateSut(); + + // Act + var result = await sut.InstallPluginAsync(PluginId, TestContext.Current.CancellationToken); + + // Assert + result + .Should().Be(new ClaudePluginInstallResult("0.8.0", "0.9.0")); + } + + [Fact] + public async Task InstallPluginAsync_VersionIsNotString_ThrowsClaudeCommandFailedException() + { + // Arrange + SetUpRun(0, """{"command":"install","outcome":"ok","installedVersion":8}"""); + var sut = CreateSut(); + + // Act + var act = () => sut.InstallPluginAsync(PluginId, TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()).Which.Reason + .Should().Be("The field 'installedVersion' of the result of the claude output is not a string."); + } + + [Theory] + [InlineData(null)] + [InlineData(" ")] + [InlineData("--force")] + public async Task InstallPluginAsync_InvalidPluginId_ThrowsArgumentExceptionWithoutRunningClaude( + string? pluginId) + { + // Arrange + var sut = CreateSut(); + + // Act + var act = () => sut.InstallPluginAsync(pluginId!, TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()) + .WithParameterName(nameof(pluginId)); + + AssertNoRun(); + } + + [Fact] + public async Task UpdatePluginAsync_PluginUpdated_RunsUpdateWithUserScopeAndReturnsVersions() + { + // Arrange + SetUpRun(0, """{"command":"update","outcome":"ok","plugin":"shade-kit@creativecoders-shade-kit","pluginId":"shade-kit@creativecoders-shade-kit","scope":"user","message":"Updated.","updateOutcome":"updated","oldVersion":"0.8.0","newVersion":"0.9.0"}"""); + var sut = CreateSut(); + + // Act + var result = await sut.UpdatePluginAsync(PluginId, TestContext.Current.CancellationToken); + + // Assert + result + .Should().Be(new ClaudePluginUpdateResult(ClaudePluginUpdateResult.UpdatedOutcome, "0.8.0", "0.9.0")); + + result.IsUpToDate + .Should().BeFalse(); + + AssertRun("plugin", "update", PluginId, "--scope", "user", "--json"); + } + + [Fact] + public async Task UpdatePluginAsync_PluginUpToDate_ReturnsUpToDateResult() + { + // Arrange + SetUpRun(0, """{"command":"update","outcome":"ok","pluginId":"shade-kit@creativecoders-shade-kit","scope":"user","message":"shade-kit is already at the latest version (f35fdf204ffd).","updateOutcome":"up_to_date","oldVersion":"f35fdf204ffd","newVersion":"f35fdf204ffd"}"""); + var sut = CreateSut(); + + // Act + var result = await sut.UpdatePluginAsync(PluginId, TestContext.Current.CancellationToken); + + // Assert + result + .Should().Be(new ClaudePluginUpdateResult(ClaudePluginUpdateResult.UpToDateOutcome, "f35fdf204ffd", + "f35fdf204ffd")); + + result.IsUpToDate + .Should().BeTrue(); + } + + [Fact] + public async Task UpdatePluginAsync_NoUpdateOutcome_ReturnsResultThatIsNotUpToDate() + { + // Arrange + SetUpRun(0, """{"command":"update","outcome":"ok"}"""); + var sut = CreateSut(); + + // Act + var result = await sut.UpdatePluginAsync(PluginId, TestContext.Current.CancellationToken); + + // Assert + result + .Should().Be(new ClaudePluginUpdateResult(null, null, null)); + + result.IsUpToDate + .Should().BeFalse(); + } + + [Fact] + public async Task UpdatePluginAsync_PluginNotFound_ThrowsClaudeCommandFailedExceptionWithMessageAndFailureCode() + { + // Arrange + SetUpRun(1, UpdateNotFoundOutput + "\n", + "✘ Failed to update plugin \"nope@creativecoders-shade-kit\": Plugin \"nope\" not found\n"); + var sut = CreateSut(); + + // Act + var act = () => sut.UpdatePluginAsync("nope@creativecoders-shade-kit", TestContext.Current.CancellationToken); + + // Assert + var exception = (await act.Should().ThrowAsync()).Which; + + exception.Message + .Should().Be("The claude command 'claude plugin update nope@creativecoders-shade-kit --scope user " + + "--json' failed: claude exited with the exit code 1 and reported the outcome 'failed': " + + "Plugin \"nope\" not found (failure code 'not_found')."); + + exception.ExitCode + .Should().Be(1); + + exception.ClaudeMessage + .Should().Be("Plugin \"nope\" not found"); + + exception.FailureCode + .Should().Be("not_found"); + } + + [Fact] + public async Task UpdatePluginAsync_FailedOutcomeWithExitCodeZero_ThrowsClaudeCommandFailedException() + { + // Arrange + SetUpRun(0, UpdateNotFoundOutput); + var sut = CreateSut(); + + // Act + var act = () => sut.UpdatePluginAsync(PluginId, TestContext.Current.CancellationToken); + + // Assert + var exception = (await act.Should().ThrowAsync()).Which; + + exception.Reason + .Should().Be("claude reported the outcome 'failed': Plugin \"nope\" not found (failure code " + + "'not_found')."); + + exception.ExitCode + .Should().Be(0); + } + + [Theory] + [InlineData("""{"command":"update"}""")] + [InlineData("""{"command":"update","outcome":null}""")] + [InlineData("""{"command":"update","outcome":true}""")] + public async Task UpdatePluginAsync_NoOutcome_ThrowsClaudeCommandFailedException(string output) + { + // Arrange + SetUpRun(0, output); + var sut = CreateSut(); + + // Act + var act = () => sut.UpdatePluginAsync(PluginId, TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()).Which.Reason + .Should().Be("claude reported no outcome."); + } + + [Fact] + public async Task UpdatePluginAsync_OtherLinesAroundResult_ReadsLastJsonObjectLine() + { + // Arrange + var output = "Checking marketplace...\r\n" + + """{"command":"progress","outcome":"failed"}""" + "\r\n" + + """{"command":"update","outcome":"ok","updateOutcome":"updated","oldVersion":"1","newVersion":"2"}""" + + "\r\n{not json\r\n[1,2]\r\n\r\n"; + SetUpRun(0, output); + var sut = CreateSut(); + + // Act + var result = await sut.UpdatePluginAsync(PluginId, TestContext.Current.CancellationToken); + + // Assert + result + .Should().Be(new ClaudePluginUpdateResult(ClaudePluginUpdateResult.UpdatedOutcome, "1", "2")); + } + + [Theory] + [InlineData("")] + [InlineData("Updated.\n")] + [InlineData("[{\"outcome\":\"ok\"}]")] + [InlineData("{\"outcome\":")] + public async Task UpdatePluginAsync_NoJsonObjectLine_ThrowsClaudeCommandFailedException(string output) + { + // Arrange + SetUpRun(0, output); + var sut = CreateSut(); + + // Act + var act = () => sut.UpdatePluginAsync(PluginId, TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()).Which.Reason + .Should().Be("claude printed no JSON object on standard output."); + } + + [Fact] + public async Task UpdatePluginAsync_NonZeroExitCodeWithoutJson_ThrowsClaudeCommandFailedExceptionWithStandardError() + { + // Arrange + SetUpRun(1, string.Empty, "error: unknown option '--json'\n"); + var sut = CreateSut(); + + // Act + var act = () => sut.UpdatePluginAsync(PluginId, TestContext.Current.CancellationToken); + + // Assert + var exception = (await act.Should().ThrowAsync()).Which; + + exception.Reason + .Should().Be("claude exited with the exit code 1 and printed no JSON object on standard output: error: " + + "unknown option '--json'."); + + exception.ClaudeMessage + .Should().BeNull(); + + exception.FailureCode + .Should().BeNull(); + } + + [Fact] + public async Task UpdatePluginAsync_NonZeroExitCodeWithOkLineWithoutMessage_ThrowsClaudeCommandFailedException() + { + // Arrange + SetUpRun(3, """{"command":"update","outcome":"ok"}"""); + var sut = CreateSut(); + + // Act + var act = () => sut.UpdatePluginAsync(PluginId, TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()).Which.Reason + .Should().Be("claude exited with the exit code 3 and reported the outcome 'ok'."); + } + + [Fact] + public async Task UpdatePluginAsync_NonZeroExitCodeWithFailureCodeOnly_NamesExitCodeAndFailureCode() + { + // Arrange + SetUpRun(1, """{"failureCode":"timeout","message":" "}"""); + var sut = CreateSut(); + + // Act + var act = () => sut.UpdatePluginAsync(PluginId, TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()).Which.Reason + .Should().Be("claude exited with the exit code 1 (failure code 'timeout')."); + } + + [Fact] + public async Task UpdatePluginAsync_ClaudeNotFound_PropagatesClaudeNotFoundException() + { + // Arrange + A.CallTo(() => _claudeCommandRunner.RunAsync(A._, A>._, + A._)) + .ThrowsAsync(new ClaudeNotFoundException(["plugin"], "Not found.")); + var sut = CreateSut(); + + // Act + var act = () => sut.UpdatePluginAsync(PluginId, TestContext.Current.CancellationToken); + + // Assert + await act.Should().ThrowExactlyAsync(); + } + + [Fact] + public async Task ListPluginsAsync_Token_PassesTokenToRunner() + { + // Arrange + using var cancellationTokenSource = new CancellationTokenSource(); + SetUpRun(0, "[]"); + var sut = CreateSut(); + + // Act + await sut.ListPluginsAsync(cancellationTokenSource.Token); + + // Assert + A.CallTo(() => _claudeCommandRunner.RunAsync(WorkingDirectory, A>._, + cancellationTokenSource.Token)) + .MustHaveHappenedOnceExactly(); + } + + [Fact] + public async Task ListMarketplacesAsync_TextLineBeforeArray_ThrowsClaudeCommandFailedException() + { + // Arrange + SetUpRun(0, "Update available.\n[]"); + var sut = CreateSut(); + + // Act + var act = () => sut.ListMarketplacesAsync(TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()).Which.Reason + .Should().StartWith("The output of claude is not valid JSON: "); + } + + [Fact] + public async Task ListPluginsAsync_EmptyArray_ReturnsEmptyList() + { + // Arrange + SetUpRun(0, "[]"); + var sut = CreateSut(); + + // Act + var plugins = await sut.ListPluginsAsync(TestContext.Current.CancellationToken); + + // Assert + plugins + .Should().BeEmpty(); + } + + [Fact] + public async Task ListPluginsAsync_NonZeroExitCodeWithFailureLine_ThrowsClaudeCommandFailedExceptionWithDetails() + { + // Arrange + SetUpRun(1, """{"command":"list","outcome":"failed","message":"Cannot read plugins","failureCode":"io"}"""); + var sut = CreateSut(); + + // Act + var act = () => sut.ListPluginsAsync(TestContext.Current.CancellationToken); + + // Assert + var exception = (await act.Should().ThrowAsync()).Which; + + exception.Reason + .Should().Be("claude exited with the exit code 1 and reported the outcome 'failed': Cannot read plugins " + + "(failure code 'io')."); + + exception.CommandText + .Should().Be("claude plugin list --json"); + } + + [Fact] + public async Task InstallPluginAsync_FailedOutcome_ThrowsClaudeCommandFailedExceptionWithDetails() + { + // Arrange + SetUpRun(1, """{"command":"install","outcome":"failed","message":"Plugin \"shade-kit\" not found in marketplace","failureCode":"not_found"}"""); + var sut = CreateSut(); + + // Act + var act = () => sut.InstallPluginAsync(PluginId, TestContext.Current.CancellationToken); + + // Assert + var exception = (await act.Should().ThrowAsync()).Which; + + exception.FailureCode + .Should().Be("not_found"); + + exception.CommandText + .Should().Be("claude plugin install shade-kit@creativecoders-shade-kit --scope user --json"); + } + + [Theory] + [InlineData("""{"outcome":"ok","availableVersion":false}""", "availableVersion")] + public async Task InstallPluginAsync_AvailableVersionIsNotString_ThrowsClaudeCommandFailedException( + string output, string field) + { + // Arrange + SetUpRun(0, output); + var sut = CreateSut(); + + // Act + var act = () => sut.InstallPluginAsync(PluginId, TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()).Which.Reason + .Should().Be($"The field '{field}' of the result of the claude output is not a string."); + } + + [Theory] + [InlineData("""{"outcome":"ok","updateOutcome":1}""", "updateOutcome")] + [InlineData("""{"outcome":"ok","oldVersion":{}}""", "oldVersion")] + [InlineData("""{"outcome":"ok","newVersion":[]}""", "newVersion")] + public async Task UpdatePluginAsync_ResultFieldIsNotString_ThrowsClaudeCommandFailedException(string output, + string field) + { + // Arrange + SetUpRun(0, output); + var sut = CreateSut(); + + // Act + var act = () => sut.UpdatePluginAsync(PluginId, TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()).Which.Reason + .Should().Be($"The field '{field}' of the result of the claude output is not a string."); + } + + [Fact] + public async Task UpdatePluginAsync_OutcomeInOtherCase_ThrowsClaudeCommandFailedException() + { + // Arrange + SetUpRun(0, """{"command":"update","outcome":"OK"}"""); + var sut = CreateSut(); + + // Act + var act = () => sut.UpdatePluginAsync(PluginId, TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()).Which.Reason + .Should().Be("claude reported the outcome 'OK'."); + } + + [Fact] + public async Task UpdatePluginAsync_ExitCodeZeroWithoutJsonButWithStandardError_NamesStandardError() + { + // Arrange + SetUpRun(0, "Done\n", " warning: settings are read-only \n"); + var sut = CreateSut(); + + // Act + var act = () => sut.UpdatePluginAsync(PluginId, TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()).Which.Reason + .Should().Be("claude printed no JSON object on standard output: warning: settings are read-only."); + } + + [Fact] + public async Task UpdatePluginAsync_PrettyPrintedResultObject_ThrowsClaudeCommandFailedException() + { + // Arrange + SetUpRun(0, "{\n \"command\": \"update\",\n \"outcome\": \"ok\"\n}\n"); + var sut = CreateSut(); + + // Act + var act = () => sut.UpdatePluginAsync(PluginId, TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()).Which.Reason + .Should().Be("claude printed no JSON object on standard output."); + } + + [Fact] + public async Task UpdatePluginAsync_NegativeExitCode_NamesExitCodeWithSign() + { + // Arrange + SetUpRun(-1073741510, string.Empty); + var sut = CreateSut(); + + // Act + var act = () => sut.UpdatePluginAsync(PluginId, TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()).Which.Reason + .Should().Be("claude exited with the exit code -1073741510 and printed no JSON object on standard " + + "output."); + } + + [Fact] + public async Task UpdatePluginAsync_MessageWithWhitespaceAndDotsAndWhitespaceFailureCode_NamesTrimmedMessageOnly() + { + // Arrange + SetUpRun(1, """{"outcome":"failed","message":" Network down... ","failureCode":" "}"""); + var sut = CreateSut(); + + // Act + var act = () => sut.UpdatePluginAsync(PluginId, TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()).Which.Reason + .Should().Be("claude exited with the exit code 1 and reported the outcome 'failed': Network down."); + } + + [Fact] + public async Task ListMarketplacesAsync_ClaudeUnavailable_PropagatesClaudeUnavailableException() + { + // Arrange + A.CallTo(() => _claudeCommandRunner.RunAsync(A._, A>._, + A._)) + .ThrowsAsync(new ClaudeUnavailableException(["plugin"], "Cannot start.")); + var sut = CreateSut(); + + // Act + var act = () => sut.ListMarketplacesAsync(TestContext.Current.CancellationToken); + + // Assert + await act.Should().ThrowExactlyAsync(); + } + + [Fact] + public async Task AddMarketplaceAsync_RunnerCanceled_PropagatesOperationCanceledException() + { + // Arrange + A.CallTo(() => _claudeCommandRunner.RunAsync(A._, A>._, + A._)) + .ThrowsAsync(new OperationCanceledException()); + var sut = CreateSut(); + + // Act + var act = () => sut.AddMarketplaceAsync(GitHubSource, TestContext.Current.CancellationToken); + + // Assert + await act.Should().ThrowExactlyAsync(); + } + + public static TheoryData CommandNames => + ["list-marketplaces", "add", "remove", "update-marketplace", "install", "update"]; + + [Theory] + [MemberData(nameof(CommandNames))] + public async Task EveryCommand_Token_PassesTokenToRunner(string commandName) + { + // Arrange + using var cancellationTokenSource = new CancellationTokenSource(); + var output = commandName == "list-marketplaces" ? "[]" : """{"outcome":"ok"}"""; + SetUpRun(0, output); + var sut = CreateSut(); + var token = cancellationTokenSource.Token; + + // Act + Task task = commandName switch + { + "list-marketplaces" => sut.ListMarketplacesAsync(token), + "add" => sut.AddMarketplaceAsync(GitHubSource, token), + "remove" => sut.RemoveMarketplaceAsync("creativecoders-shade-kit", token), + "update-marketplace" => sut.UpdateMarketplaceAsync("creativecoders-shade-kit", token), + "install" => sut.InstallPluginAsync(PluginId, token), + _ => sut.UpdatePluginAsync(PluginId, token) + }; + await task; + + // Assert + A.CallTo(() => _claudeCommandRunner.RunAsync(WorkingDirectory, A>._, token)) + .MustHaveHappenedOnceExactly(); + } + + private ClaudePluginCli CreateSut() + { + return new ClaudePluginCli(_claudeCommandRunner, WorkingDirectory); + } + + private void SetUpRun(int exitCode, string standardOutput, string standardError = "") + { + A.CallTo(() => _claudeCommandRunner.RunAsync(A._, A>._, + A._)) + .Invokes((string workingDirectory, IReadOnlyList arguments, CancellationToken _) => + { + _actualWorkingDirectory = workingDirectory; + _actualArguments = arguments; + }) + .Returns(new ExternalProcessResult(exitCode, standardOutput, standardError)); + } + + private void AssertRun(params string[] expectedArguments) + { + _actualWorkingDirectory + .Should().Be(WorkingDirectory); + + _actualArguments + .Should().Equal(expectedArguments); + } + + private void AssertNoRun() + { + A.CallTo(_claudeCommandRunner) + .MustNotHaveHappened(); + } +} diff --git a/tests/CreativeCoders.ShadeKit.Core.Tests/Integrations/DirectoryPathComparerTests.cs b/tests/CreativeCoders.ShadeKit.Core.Tests/Integrations/DirectoryPathComparerTests.cs new file mode 100644 index 0000000..f3506b9 --- /dev/null +++ b/tests/CreativeCoders.ShadeKit.Core.Tests/Integrations/DirectoryPathComparerTests.cs @@ -0,0 +1,457 @@ +using AwesomeAssertions; +using CreativeCoders.ShadeKit.Core.Integrations; +using CreativeCoders.ShadeKit.Tests.Shared; + +namespace CreativeCoders.ShadeKit.Core.Tests.Integrations; + +public class DirectoryPathComparerTests +{ + // A path below the temporary directory that no test creates. + private static readonly string MissingPath = + Path.Combine(Path.GetTempPath(), "shade-kit-tests-missing-" + Guid.NewGuid().ToString("N"), "Kit"); + + private static readonly DirectoryPathComparer CaseSensitiveComparer = new(StringComparison.Ordinal); + + private static readonly DirectoryPathComparer CaseInsensitiveComparer = new(StringComparison.OrdinalIgnoreCase); + + [Theory] + [InlineData(true, false, StringComparison.OrdinalIgnoreCase)] + [InlineData(false, true, StringComparison.OrdinalIgnoreCase)] + [InlineData(false, false, StringComparison.Ordinal)] + public void GetComparison_OperatingSystem_IgnoresCaseOnlyOnWindowsAndMacOS(bool isWindows, bool isMacOS, + StringComparison expected) + { + // Act + var comparison = DirectoryPathComparer.GetComparison(isWindows, isMacOS); + + // Assert + comparison + .Should().Be(expected); + } + + [Fact] + public void ForCurrentOperatingSystem_Always_UsesComparisonOfCurrentOperatingSystem() + { + // Act + var comparer = DirectoryPathComparer.ForCurrentOperatingSystem(); + + // Assert + comparer.Comparison + .Should().Be(OperatingSystem.IsWindows() || OperatingSystem.IsMacOS() + ? StringComparison.OrdinalIgnoreCase + : StringComparison.Ordinal); + } + + [Fact] + public void AreSameDirectory_SameExistingDirectory_ReturnsTrue() + { + // Arrange + using var tempDirectory = new TempKitDirectory(); + var path = tempDirectory.CreateDirectory("kit"); + + // Act + var isSame = CaseSensitiveComparer.AreSameDirectory(path, path); + + // Assert + isSame + .Should().BeTrue(); + } + + [Fact] + public void AreSameDirectory_ExistingDirectoryWithTrailingSeparators_ReturnsTrue() + { + // Arrange + using var tempDirectory = new TempKitDirectory(); + var path = tempDirectory.CreateDirectory("kit"); + + // Act + var isSame = CaseSensitiveComparer.AreSameDirectory( + path + Path.DirectorySeparatorChar + Path.DirectorySeparatorChar, path); + + // Assert + isSame + .Should().BeTrue(); + } + + [Fact] + public void AreSameDirectory_MissingDirectoryWithTrailingSeparatorAndDotSegments_ReturnsTrue() + { + // Arrange + var otherForm = Path.Combine(MissingPath, "sub", "..", ".") + Path.DirectorySeparatorChar; + + // Act + var isSame = CaseSensitiveComparer.AreSameDirectory(otherForm, MissingPath); + + // Assert + isSame + .Should().BeTrue(); + } + + [Fact] + public void AreSameDirectory_OtherDirectory_ReturnsFalse() + { + // Arrange + using var tempDirectory = new TempKitDirectory(); + var first = tempDirectory.CreateDirectory("first"); + var second = tempDirectory.CreateDirectory("second"); + + // Act + var isSame = CaseInsensitiveComparer.AreSameDirectory(first, second); + + // Assert + isSame + .Should().BeFalse(); + } + + [Fact] + public void AreSameDirectory_CaseOnlyDifferenceAndCaseInsensitiveComparer_ReturnsTrue() + { + // Act + var isSame = CaseInsensitiveComparer.AreSameDirectory(MissingPath, MissingPath.ToUpperInvariant()); + + // Assert + isSame + .Should().BeTrue(); + } + + [Fact] + public void AreSameDirectory_CaseOnlyDifferenceAndCaseSensitiveComparer_ReturnsFalse() + { + // Act + var isSame = CaseSensitiveComparer.AreSameDirectory(MissingPath, MissingPath.ToUpperInvariant()); + + // Assert + isSame + .Should().BeFalse(); + } + + [Fact] + public void AreSameDirectory_ExistingDirectoryInOtherCaseThroughSymbolicLink_FollowsComparer() + { + // Arrange + using var tempDirectory = new TempKitDirectory(); + var target = tempDirectory.CreateDirectory("kit"); + var link = tempDirectory.CreateDirectorySymbolicLinkOrSkip(target, "kit-link"); + var otherCase = Path.Combine(tempDirectory.RootPath, "KIT"); + + // Act + var isSameIgnoringCase = CaseInsensitiveComparer.AreSameDirectory(otherCase, link); + var isSameWithCase = CaseSensitiveComparer.AreSameDirectory(otherCase, link); + + // Assert + isSameIgnoringCase + .Should().BeTrue(); + + isSameWithCase + .Should().BeFalse(); + } + + [Fact] + public void AreSameDirectory_SymbolicLinkToDirectory_ReturnsTrue() + { + // Arrange + using var tempDirectory = new TempKitDirectory(); + var target = tempDirectory.CreateDirectory("kit"); + var link = tempDirectory.CreateDirectorySymbolicLinkOrSkip(target, "kit-link"); + + // Act + var isSame = CaseSensitiveComparer.AreSameDirectory(link, target); + + // Assert + isSame + .Should().BeTrue(); + } + + [Fact] + public void AreSameDirectory_SymbolicLinkInParentDirectory_ReturnsTrue() + { + // Arrange + using var tempDirectory = new TempKitDirectory(); + var target = tempDirectory.CreateDirectory("work", "kit"); + var link = tempDirectory.CreateDirectorySymbolicLinkOrSkip(Path.GetDirectoryName(target)!, "work-link"); + + // Act + var isSame = CaseSensitiveComparer.AreSameDirectory(Path.Combine(link, "kit"), target); + + // Assert + isSame + .Should().BeTrue(); + } + + [Fact] + public void AreSameDirectory_RelativeSymbolicLinkWithParentSegment_ReturnsTrue() + { + // Arrange + using var tempDirectory = new TempKitDirectory(); + var target = tempDirectory.CreateDirectory("kit"); + tempDirectory.CreateDirectory("links"); + var link = tempDirectory.CreateDirectorySymbolicLinkOrSkip( + Path.Combine("..", "kit"), "links", "kit-link"); + + // Act + var isSame = CaseSensitiveComparer.AreSameDirectory(link, target); + + // Assert + isSame + .Should().BeTrue(); + } + + [Fact] + public void AreSameDirectory_RelativeLinkTargetLeavingLinkedParentDirectory_CombinesWithResolvedParent() + { + // Arrange: alias -> deep/real, and alias/kit-link -> ../../kit leaves deep/real, not alias. + using var tempDirectory = new TempKitDirectory(); + var target = tempDirectory.CreateDirectory("kit"); + var real = tempDirectory.CreateDirectory("deep", "real"); + var alias = tempDirectory.CreateDirectorySymbolicLinkOrSkip(real, "alias"); + var link = tempDirectory.CreateDirectorySymbolicLinkOrSkip(Path.Combine("..", "..", "kit"), "deep", "real", + "kit-link"); + + // Act + var isSame = CaseSensitiveComparer.AreSameDirectory(Path.Combine(alias, "kit-link"), target); + + // Assert + Directory.Exists(link) + .Should().BeTrue(); + + isSame + .Should().BeTrue(); + } + + [Fact] + public void AreSameDirectory_LinkTargetWithDotSegmentAndTrailingSeparator_ReturnsTrue() + { + // Arrange + using var tempDirectory = new TempKitDirectory(); + var target = tempDirectory.CreateDirectory("kit"); + var link = tempDirectory.CreateDirectorySymbolicLinkOrSkip( + "." + Path.DirectorySeparatorChar + "kit" + Path.DirectorySeparatorChar, "kit-link"); + + // Act + var isSame = CaseSensitiveComparer.AreSameDirectory(link, target); + + // Assert + isSame + .Should().BeTrue(); + } + + [Fact] + public void AreSameDirectory_ParentSegmentAfterSymbolicLink_IsRemovedBeforeLinkResolution() + { + // Arrange: link -> work/kit; link/../other means /other, as Path.GetFullPath reads it, not work/other. + using var tempDirectory = new TempKitDirectory(); + var linkTarget = tempDirectory.CreateDirectory("work", "kit"); + tempDirectory.CreateDirectory("work", "other"); + var rootOther = tempDirectory.CreateDirectory("other"); + var link = tempDirectory.CreateDirectorySymbolicLinkOrSkip(linkTarget, "kit-link"); + + // Act + var isSame = CaseSensitiveComparer.AreSameDirectory(Path.Combine(link, "..", "other"), rootOther); + + // Assert + isSame + .Should().BeTrue(); + } + + [Fact] + public void AreSameDirectory_ChainOfSymbolicLinks_ReturnsTrue() + { + // Arrange + using var tempDirectory = new TempKitDirectory(); + var target = tempDirectory.CreateDirectory("kit"); + var firstLink = tempDirectory.CreateDirectorySymbolicLinkOrSkip(target, "link-1"); + var secondLink = tempDirectory.CreateDirectorySymbolicLinkOrSkip(firstLink, "link-2"); + + // Act + var isSame = CaseSensitiveComparer.AreSameDirectory(target, secondLink); + + // Assert + isSame + .Should().BeTrue(); + } + + [Fact] + public void AreSameDirectory_LinkTargetThatContainsSymbolicLink_ReturnsTrue() + { + // Arrange + using var tempDirectory = new TempKitDirectory(); + var target = tempDirectory.CreateDirectory("work", "kit"); + var parentLink = tempDirectory.CreateDirectorySymbolicLinkOrSkip(Path.GetDirectoryName(target)!, + "work-link"); + var link = tempDirectory.CreateDirectorySymbolicLinkOrSkip(Path.Combine(parentLink, "kit"), "kit-link"); + + // Act + var isSame = CaseSensitiveComparer.AreSameDirectory(link, target); + + // Assert + isSame + .Should().BeTrue(); + } + + [Fact] + public void AreSameDirectory_MissingDirectoryBelowSymbolicLink_ComparesWithoutLinkResolution() + { + // Arrange + using var tempDirectory = new TempKitDirectory(); + var target = tempDirectory.CreateDirectory("kit"); + var link = tempDirectory.CreateDirectorySymbolicLinkOrSkip(target, "kit-link"); + + // Act + var isSame = CaseSensitiveComparer.AreSameDirectory(Path.Combine(link, "missing"), + Path.Combine(target, "missing")); + + // Assert + isSame + .Should().BeFalse("a path that does not exist is only normalized"); + } + + [Fact] + public void AreSameDirectory_SymbolicLinkLoop_ComparesWithoutLinkResolution() + { + // Arrange + using var tempDirectory = new TempKitDirectory(); + var firstLink = tempDirectory.CreateDirectorySymbolicLinkOrSkip( + Path.Combine(tempDirectory.RootPath, "loop-2"), "loop-1"); + tempDirectory.CreateDirectorySymbolicLinkOrSkip(firstLink, "loop-2"); + + // Act + var isSame = CaseSensitiveComparer.AreSameDirectory(firstLink + Path.DirectorySeparatorChar, firstLink); + + // Assert + isSame + .Should().BeTrue(); + } + + [Fact] + public void AreSameDirectory_NullFirstPath_ThrowsArgumentNullException() + { + // Act + var act = () => CaseSensitiveComparer.AreSameDirectory(null!, MissingPath); + + // Assert + act.Should().Throw() + .WithParameterName("path"); + } + + [Fact] + public void AreSameDirectory_NullSecondPath_ThrowsArgumentNullException() + { + // Act + var act = () => CaseSensitiveComparer.AreSameDirectory(MissingPath, null!); + + // Assert + act.Should().Throw() + .WithParameterName("path"); + } + + [Theory] + [InlineData("")] + [InlineData("kit")] + [InlineData("./kit")] + public void AreSameDirectory_RelativePath_ThrowsArgumentException(string relativePath) + { + // Act + var act = () => CaseSensitiveComparer.AreSameDirectory(relativePath, MissingPath); + + // Assert + act.Should().Throw() + .WithParameterName("path"); + } + + [Fact] + public void ResolvePath_SymbolicLinkWithTrailingSeparator_ReturnsResolvedTargetWithoutLinks() + { + // Arrange + using var tempDirectory = new TempKitDirectory(); + var target = tempDirectory.CreateDirectory("kit"); + var link = tempDirectory.CreateDirectorySymbolicLinkOrSkip(target, "kit-link"); + var resolvedTarget = DirectoryPathComparer.ResolvePath(target); + + // Act + var resolved = DirectoryPathComparer.ResolvePath(link + Path.DirectorySeparatorChar); + + // Assert + resolved + .Should().Be(resolvedTarget); + + new DirectoryInfo(resolved).LinkTarget + .Should().BeNull(); + } + + [Theory] + [InlineData("/tmp", "/private/tmp")] + [InlineData("/var", "/private/var")] + [InlineData("/tmp/", "/private/tmp")] + public void ResolvePath_MacOSRootLink_ReturnsPrivateDirectory(string path, string expected) + { + // Arrange + Assert.SkipUnless(OperatingSystem.IsMacOS(), "Only macOS links /tmp and /var to /private."); + Assert.SkipWhen(new DirectoryInfo(Path.TrimEndingDirectorySeparator(path)).LinkTarget is null, + $"'{path}' is no symbolic link here."); + + // Act + var resolved = DirectoryPathComparer.ResolvePath(path); + + // Assert + resolved + .Should().Be(expected); + } + + [Fact] + public void ResolvePath_MacOSTempDirectoryBelowVar_ReturnsPathBelowPrivateVar() + { + // Arrange + Assert.SkipUnless(OperatingSystem.IsMacOS(), "Only macOS links /var to /private/var."); + using var tempDirectory = new TempKitDirectory(); + Assert.SkipUnless(tempDirectory.RootPath.StartsWith("/var/", StringComparison.Ordinal), + $"The temporary directory '{tempDirectory.RootPath}' is not below /var."); + + // Act + var resolved = DirectoryPathComparer.ResolvePath(tempDirectory.RootPath); + + // Assert + resolved + .Should().Be("/private" + tempDirectory.RootPath); + } + + [Fact] + public void AreSameDirectory_ForwardSlashesOnWindows_ReturnsTrue() + { + // Arrange + Assert.SkipUnless(OperatingSystem.IsWindows(), "Only Windows reads '/' as a directory separator besides '\\'."); + using var tempDirectory = new TempKitDirectory(); + var path = tempDirectory.CreateDirectory("work", "kit"); + + // Act + var isSame = CaseSensitiveComparer.AreSameDirectory(path.Replace('\\', '/'), path); + + // Assert + isSame + .Should().BeTrue(); + } + + [Fact] + public void ResolvePath_RootDirectory_KeepsItsSeparator() + { + // Arrange + var root = Path.GetPathRoot(Path.GetTempPath())!; + + // Act + var resolved = DirectoryPathComparer.ResolvePath(root); + + // Assert + resolved + .Should().Be(root); + } + + [Fact] + public void ResolvePath_MissingPath_ReturnsNormalizedPath() + { + // Act + var resolved = DirectoryPathComparer.ResolvePath(MissingPath + Path.DirectorySeparatorChar); + + // Assert + resolved + .Should().Be(MissingPath); + } +} diff --git a/tests/CreativeCoders.ShadeKit.Core.Tests/Integrations/Exceptions/ClaudeExceptionTests.cs b/tests/CreativeCoders.ShadeKit.Core.Tests/Integrations/Exceptions/ClaudeExceptionTests.cs new file mode 100644 index 0000000..8e4fdba --- /dev/null +++ b/tests/CreativeCoders.ShadeKit.Core.Tests/Integrations/Exceptions/ClaudeExceptionTests.cs @@ -0,0 +1,106 @@ +using System.ComponentModel; +using System.Text.Json; +using AwesomeAssertions; +using CreativeCoders.ShadeKit.Core.Integrations.Exceptions; + +namespace CreativeCoders.ShadeKit.Core.Tests.Integrations.Exceptions; + +// The command text rules of the shared base class are covered by GitUnavailableExceptionTests. +public class ClaudeExceptionTests +{ + [Fact] + public void ClaudeUnavailableException_ArgumentsReasonAndInnerException_MessageNamesCommandAndReason() + { + // Arrange + var innerException = new Win32Exception("Permission denied"); + + // Act + var exception = new ClaudeUnavailableException(["plugin", "list", "--json"], + "The claude executable '/usr/bin/claude' could not be started: Permission denied.", innerException); + + // Assert + exception.Message + .Should().Be("The claude command 'claude plugin list --json' cannot be run: The claude executable " + + "'/usr/bin/claude' could not be started: Permission denied."); + + exception.CommandText + .Should().Be("claude plugin list --json"); + + exception.InnerException + .Should().BeSameAs(innerException); + } + + [Fact] + public void ClaudeNotFoundException_ArgumentsAndReason_IsClaudeUnavailableExceptionWithoutInnerException() + { + // Act + var exception = new ClaudeNotFoundException(["plugin", "list", "--json"], + "The Claude Code CLI claude was not found in any absolute directory of the PATH environment variable."); + + // Assert + exception + .Should().BeAssignableTo(); + + exception.Message + .Should().Be("The claude command 'claude plugin list --json' cannot be run: The Claude Code CLI claude " + + "was not found in any absolute directory of the PATH environment variable."); + + exception.Arguments + .Should().Equal("plugin", "list", "--json"); + + exception.InnerException + .Should().BeNull(); + } + + [Fact] + public void ClaudeCommandFailedException_AllValues_MessageNamesCommandAndReasonAndKeepsClaudeDetails() + { + // Arrange + var innerException = new JsonException("inner"); + + // Act + var exception = new ClaudeCommandFailedException( + ["plugin", "update", "nope@creativecoders-shade-kit", "--scope", "user", "--json"], 1, + "claude exited with the exit code 1 and reported the outcome 'failed': Plugin \"nope\" not found " + + "(failure code 'not_found').", "Plugin \"nope\" not found", "not_found", innerException); + + // Assert + exception.Message + .Should().Be("The claude command 'claude plugin update nope@creativecoders-shade-kit --scope user " + + "--json' failed: claude exited with the exit code 1 and reported the outcome 'failed': " + + "Plugin \"nope\" not found (failure code 'not_found')."); + + exception.ExitCode + .Should().Be(1); + + exception.ClaudeMessage + .Should().Be("Plugin \"nope\" not found"); + + exception.FailureCode + .Should().Be("not_found"); + + exception.InnerException + .Should().BeSameAs(innerException); + } + + [Fact] + public void ClaudeCommandFailedException_WithoutClaudeDetails_HasNullMessageFailureCodeAndInnerException() + { + // Act + var exception = new ClaudeCommandFailedException(["plugin", "list", "--json"], 0, + "The output of claude is not a JSON array."); + + // Assert + exception + .Should().NotBeAssignableTo(); + + exception.ClaudeMessage + .Should().BeNull(); + + exception.FailureCode + .Should().BeNull(); + + exception.InnerException + .Should().BeNull(); + } +} diff --git a/tests/CreativeCoders.ShadeKit.Core.Tests/Integrations/Exceptions/IntegrationExceptionTests.cs b/tests/CreativeCoders.ShadeKit.Core.Tests/Integrations/Exceptions/IntegrationExceptionTests.cs new file mode 100644 index 0000000..98bbca5 --- /dev/null +++ b/tests/CreativeCoders.ShadeKit.Core.Tests/Integrations/Exceptions/IntegrationExceptionTests.cs @@ -0,0 +1,106 @@ +using AwesomeAssertions; +using CreativeCoders.ShadeKit.Core.Integrations; +using CreativeCoders.ShadeKit.Core.Integrations.Exceptions; + +namespace CreativeCoders.ShadeKit.Core.Tests.Integrations.Exceptions; + +public class IntegrationExceptionTests +{ + private static readonly MarketplaceSource ReleaseSource = + MarketplaceSource.ForGitHub("CreativeCodersTeam/shade-kit", "v0.8.0"); + + [Fact] + public void IntegrationSwitchCanceledException_CanceledInnerException_TakesTokenAndNamesAgent() + { + // Arrange + var token = new CancellationToken(true); + var innerException = new OperationCanceledException(token); + + // Act + var exception = new IntegrationSwitchCanceledException("claude", innerException); + + // Assert + exception.AgentId + .Should().Be("claude"); + + exception.CancellationToken + .Should().Be(token); + + exception.InnerException + .Should().BeSameAs(innerException); + + exception.Message + .Should().Be("The SHADE kit integration of the agent 'claude' was canceled while its plugin marketplace " + + "was switched, so it may be incomplete."); + } + + [Fact] + public void IntegrationSwitchCanceledException_NullInnerException_UsesNoneToken() + { + // Act + var exception = new IntegrationSwitchCanceledException("claude", null!); + + // Assert + exception.CancellationToken + .Should().Be(CancellationToken.None); + } + + [Fact] + public void IntegrationRunFailedException_CompletedAgents_MessageNamesFailedAndCompletedAgentsAndCause() + { + // Arrange + var innerException = new InvalidOperationException("claude failed."); + + // Act + var exception = new IntegrationRunFailedException("copilot", ReleaseSource, + [CreateResult("claude"), CreateResult("codex")], innerException); + + // Assert + exception.Message + .Should().Be("The SHADE kit integration of the agent 'copilot' failed after the integrations of " + + "'claude', 'codex' were done: claude failed."); + + exception.FailedAgentId + .Should().Be("copilot"); + + exception.MarketplaceSource + .Should().Be(ReleaseSource); + + exception.InnerException + .Should().BeSameAs(innerException); + } + + [Fact] + public void IntegrationRunFailedException_CallerChangesListAfterwards_KeepsCopy() + { + // Arrange + var completed = new List { CreateResult("claude") }; + + // Act + var exception = new IntegrationRunFailedException("copilot", ReleaseSource, completed, + new InvalidOperationException("failed.")); + completed.Add(CreateResult("codex")); + + // Assert + exception.CompletedIntegrations + .Should().Equal(CreateResult("claude")); + } + + [Fact] + public void IntegrationRunFailedException_NullList_KeepsEmptyList() + { + // Act + var exception = new IntegrationRunFailedException("copilot", ReleaseSource, null!, + new InvalidOperationException("failed.")); + + // Assert + exception.CompletedIntegrations + .Should().BeEmpty(); + } + + private static IntegrationResult CreateResult(string agentId) + { + return new IntegrationResult(agentId, "shade-kit", IntegrationOutcome.Installed, null, "0.8.0", "v0.8.0", + true); + } +} diff --git a/tests/CreativeCoders.ShadeKit.Core.Tests/Integrations/IntegrationServiceTests.cs b/tests/CreativeCoders.ShadeKit.Core.Tests/Integrations/IntegrationServiceTests.cs new file mode 100644 index 0000000..03f11b9 --- /dev/null +++ b/tests/CreativeCoders.ShadeKit.Core.Tests/Integrations/IntegrationServiceTests.cs @@ -0,0 +1,1535 @@ +using AwesomeAssertions; +using CreativeCoders.ShadeKit.Core.Engine; +using CreativeCoders.ShadeKit.Core.Git; +using CreativeCoders.ShadeKit.Core.Integrations; +using CreativeCoders.ShadeKit.Core.Integrations.Exceptions; +using CreativeCoders.ShadeKit.Core.Integrations.Warnings; +using FakeItEasy; + +namespace CreativeCoders.ShadeKit.Core.Tests.Integrations; + +// The agents and the release tag checker are faked and the environment variables come from a dictionary, so these +// tests neither start an agent CLI or git nor read the real environment. +public class IntegrationServiceTests +{ + private static readonly string CurrentDirectory = Path.Combine(Path.GetTempPath(), "shade-kit-tests", "cwd"); + + private static readonly MarketplaceSource ReleaseSource = + MarketplaceSource.ForGitHub("CreativeCodersTeam/shade-kit", "v0.8.0"); + + private static readonly MarketplaceSource MainSource = MarketplaceSource.ForGitHub("CreativeCodersTeam/shade-kit", + "main"); + + private readonly IEngineVersionProvider _engineVersionProvider = A.Fake(); + + private readonly IGitRemoteTagChecker _gitRemoteTagChecker = A.Fake(); + + private readonly Dictionary _environment = new(StringComparer.Ordinal); + + // The source that each agent received in UpdateAsync, in the order of the calls. + private readonly List<(string AgentId, MarketplaceSource Source)> _updateSources = []; + + private readonly IAgentIntegration _claude; + + private readonly IAgentIntegration _other; + + public IntegrationServiceTests() + { + _claude = CreateAgent("claude", isAvailable: true); + _other = CreateAgent("other", isAvailable: false); + + A.CallTo(() => _engineVersionProvider.Version).Returns("0.8.0"); + A.CallTo(() => _gitRemoteTagChecker.CheckTagAsync(A._, A._, A._)) + .Returns(GitRemoteTagState.Found); + } + + [Fact] + public void Constructor_NullAgentIntegrations_ThrowsArgumentNullException() + { + // Act + var act = () => new IntegrationService(null!, _engineVersionProvider, _gitRemoteTagChecker); + + // Assert + act.Should().Throw() + .WithParameterName("agentIntegrations"); + } + + [Fact] + public void Constructor_NullEngineVersionProvider_ThrowsArgumentNullException() + { + // Act + var act = () => new IntegrationService([_claude], null!, _gitRemoteTagChecker); + + // Assert + act.Should().Throw() + .WithParameterName("engineVersionProvider"); + } + + [Fact] + public void Constructor_NullGitRemoteTagChecker_ThrowsArgumentNullException() + { + // Act + var act = () => new IntegrationService([_claude], _engineVersionProvider, null!); + + // Assert + act.Should().Throw() + .WithParameterName("gitRemoteTagChecker"); + } + + [Fact] + public void Constructor_DuplicateAgentIds_ThrowsArgumentException() + { + // Act + var act = () => new IntegrationService([_claude, CreateAgent("CLAUDE", isAvailable: true)], + _engineVersionProvider, _gitRemoteTagChecker); + + // Assert + act.Should().Throw() + .WithParameterName("agentIntegrations"); + } + + [Fact] + public void AgentIds_RegisteredAgents_ReturnsIdsInRegistrationOrder() + { + // Arrange + var service = CreateService(); + + // Act + var agentIds = service.AgentIds; + + // Assert + agentIds + .Should().Equal("claude", "other"); + } + + [Theory] + [InlineData("0.8.0", "CreativeCodersTeam/shade-kit#v0.8.0")] + [InlineData("1.12.3", "CreativeCodersTeam/shade-kit#v1.12.3")] + [InlineData("0.8.0+build.5", "CreativeCodersTeam/shade-kit#v0.8.0")] + public async Task ResolveSourceAsync_ReleaseEngine_ReturnsReleaseTagWithoutWarnings(string engineVersion, + string expectedSource) + { + // Arrange + A.CallTo(() => _engineVersionProvider.Version).Returns(engineVersion); + var service = CreateService(); + + // Act + var (source, warnings) = await service.ResolveSourceAsync(TestContext.Current.CancellationToken); + + // Assert + source.Text + .Should().Be(expectedSource); + + warnings + .Should().BeEmpty(); + } + + [Fact] + public async Task ResolveSourceAsync_PrereleaseEngine_ReturnsMainWithPrereleaseRefWarning() + { + // Arrange + A.CallTo(() => _engineVersionProvider.Version).Returns("0.8.0-beta.3"); + var service = CreateService(); + + // Act + var (source, warnings) = await service.ResolveSourceAsync(TestContext.Current.CancellationToken); + + // Assert + source + .Should().Be(MarketplaceSource.ForGitHub("CreativeCodersTeam/shade-kit", "main")); + + warnings + .Should().Equal(new IntegrationPrereleaseRefWarning("0.8.0-beta.3", "main")); + } + + [Fact] + public async Task ResolveSourceAsync_InvalidEngineVersion_ThrowsInvalidOperationException() + { + // Arrange + A.CallTo(() => _engineVersionProvider.Version).Returns("1.0"); + var service = CreateService(); + + // Act + var act = () => service.ResolveSourceAsync(TestContext.Current.CancellationToken); + + // Assert + await act.Should().ThrowAsync() + .WithMessage("*'1.0'*"); + } + + [Theory] + [InlineData("owner/fork#feature/x", "owner/fork", "feature/x")] + [InlineData("owner/fork", "owner/fork", null)] + public async Task ResolveSourceAsync_GitHubOverride_ReturnsOverrideWithoutWarnings(string value, string expectedRepo, + string? expectedRef) + { + // Arrange + A.CallTo(() => _engineVersionProvider.Version).Returns("0.8.0-beta.1"); + _environment[IntegrationService.MarketplaceSourceVariableName] = value; + var service = CreateService(); + + // Act + var (source, warnings) = await service.ResolveSourceAsync(TestContext.Current.CancellationToken); + + // Assert + source + .Should().Be(MarketplaceSource.ForGitHub(expectedRepo, expectedRef)); + + warnings + .Should().BeEmpty("the override replaces the whole source, also the prerelease branch"); + } + + [Fact] + public async Task ResolveSourceAsync_RelativePathOverride_ReturnsPathResolvedAgainstCurrentDirectory() + { + // Arrange + _environment[IntegrationService.MarketplaceSourceVariableName] = "./shade-kit"; + var service = CreateService(); + + // Act + var (source, _) = await service.ResolveSourceAsync(TestContext.Current.CancellationToken); + + // Assert + source.Path + .Should().Be(Path.Combine(CurrentDirectory, "shade-kit")); + } + + [Theory] + [InlineData("")] + [InlineData("--help")] + [InlineData("owner/repo#")] + public async Task ResolveSourceAsync_InvalidOverride_ThrowsInvalidMarketplaceSourceException(string value) + { + // Arrange + _environment[IntegrationService.MarketplaceSourceVariableName] = value; + var service = CreateService(); + + // Act + var act = () => service.ResolveSourceAsync(TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()) + .Which.Value.Should().Be(value); + } + + [Fact] + public async Task ResolveSourceAsync_OverrideAndInvalidEngineVersion_ReturnsOverride() + { + // Arrange + A.CallTo(() => _engineVersionProvider.Version).Returns("not a version"); + _environment[IntegrationService.MarketplaceSourceVariableName] = "owner/fork#main"; + var service = CreateService(); + + // Act + var (source, _) = await service.ResolveSourceAsync(TestContext.Current.CancellationToken); + + // Assert + source + .Should().Be(MarketplaceSource.ForGitHub("owner/fork", "main")); + } + + [Fact] + public async Task ResolveSourceAsync_EmptyEngineVersion_ThrowsInvalidOperationException() + { + // Arrange + A.CallTo(() => _engineVersionProvider.Version).Returns(string.Empty); + var service = CreateService(); + + // Act + var act = () => service.ResolveSourceAsync(TestContext.Current.CancellationToken); + + // Assert + await act.Should().ThrowAsync(); + } + + [Fact] + public async Task ResolveSourceAsync_AbsolutePathOverride_ReturnsDirectorySource() + { + // Arrange + var path = Path.Combine(Path.GetTempPath(), "shade-kit"); + _environment[IntegrationService.MarketplaceSourceVariableName] = path; + var service = CreateService(); + + // Act + var (source, _) = await service.ResolveSourceAsync(TestContext.Current.CancellationToken); + + // Assert + source + .Should().Be(MarketplaceSource.ForDirectory(path)); + } + + [Fact] + public async Task ResolveSourceAsync_ReleaseEngine_ChecksReleaseTagInMarketplaceRepository() + { + // Arrange + using var cancellationTokenSource = new CancellationTokenSource(); + var service = CreateService(); + + // Act + await service.ResolveSourceAsync(cancellationTokenSource.Token); + + // Assert + A.CallTo(() => _gitRemoteTagChecker.CheckTagAsync("https://github.com/CreativeCodersTeam/shade-kit.git", + "v0.8.0", cancellationTokenSource.Token)) + .MustHaveHappenedOnceExactly(); + } + + [Fact] + public async Task ResolveSourceAsync_ReleaseTagMissing_ReturnsMainWithReleaseTagMissingWarning() + { + // Arrange + A.CallTo(() => _engineVersionProvider.Version).Returns("0.8.1+build.7"); + A.CallTo(() => _gitRemoteTagChecker.CheckTagAsync(A._, "v0.8.1", A._)) + .Returns(GitRemoteTagState.Missing); + var service = CreateService(); + + // Act + var (source, warnings) = await service.ResolveSourceAsync(TestContext.Current.CancellationToken); + + // Assert + source + .Should().Be(MainSource); + + warnings + .Should().Equal(new IntegrationReleaseTagMissingWarning("0.8.1+build.7", "v0.8.1", "main")); + } + + [Fact] + public async Task ResolveSourceAsync_ReleaseTagCannotBeChecked_ReturnsReleaseTagUncheckedWithoutWarnings() + { + // Arrange + A.CallTo(() => _gitRemoteTagChecker.CheckTagAsync(A._, A._, A._)) + .Returns(GitRemoteTagState.Unknown); + var service = CreateService(); + + // Act + var (source, warnings) = await service.ResolveSourceAsync(TestContext.Current.CancellationToken); + + // Assert + source + .Should().Be(ReleaseSource); + + warnings + .Should().BeEmpty(); + } + + [Fact] + public async Task ResolveSourceAsync_TagCheckCanceled_PropagatesCancellation() + { + // Arrange + A.CallTo(() => _gitRemoteTagChecker.CheckTagAsync(A._, A._, A._)) + .ThrowsAsync(new OperationCanceledException()); + var service = CreateService(); + + // Act + var act = () => service.ResolveSourceAsync(TestContext.Current.CancellationToken); + + // Assert + await act.Should().ThrowAsync(); + } + + [Fact] + public async Task ResolveSourceAsync_PrereleaseEngine_DoesNotCheckAnyTag() + { + // Arrange + A.CallTo(() => _engineVersionProvider.Version).Returns("0.8.0-beta.3"); + var service = CreateService(); + + // Act + await service.ResolveSourceAsync(TestContext.Current.CancellationToken); + + // Assert + A.CallTo(() => _gitRemoteTagChecker.CheckTagAsync(A._, A._, A._)) + .MustNotHaveHappened(); + } + + [Theory] + [InlineData("owner/fork#v0.8.0")] + [InlineData("CreativeCodersTeam/shade-kit#v0.8.0")] + [InlineData("./shade-kit")] + public async Task ResolveSourceAsync_OverrideOfReleaseEngine_DoesNotCheckAnyTag(string value) + { + // Arrange + _environment[IntegrationService.MarketplaceSourceVariableName] = value; + A.CallTo(() => _gitRemoteTagChecker.CheckTagAsync(A._, A._, A._)) + .Returns(GitRemoteTagState.Missing); + var service = CreateService(); + + // Act + var (_, warnings) = await service.ResolveSourceAsync(TestContext.Current.CancellationToken); + + // Assert + warnings + .Should().BeEmpty(); + + A.CallTo(() => _gitRemoteTagChecker.CheckTagAsync(A._, A._, A._)) + .MustNotHaveHappened(); + } + + [Fact] + public async Task InstallAsync_ReleaseTagMissing_InstallsFromMainWithReleaseTagMissingWarning() + { + // Arrange + A.CallTo(() => _gitRemoteTagChecker.CheckTagAsync(A._, A._, A._)) + .Returns(GitRemoteTagState.Missing); + var service = CreateService(); + + // Act + var result = await service.InstallAsync(null, TestContext.Current.CancellationToken); + + // Assert + result.Source + .Should().Be(MainSource); + + result.Warnings + .Should().Equal(new IntegrationReleaseTagMissingWarning("0.8.0", "v0.8.0", "main")); + + A.CallTo(() => _claude.InstallAsync(MainSource, A._)) + .MustHaveHappenedOnceExactly(); + } + + [Fact] + public async Task InstallAsync_ExplicitAgentAndReleaseTagMissing_InstallsFromMain() + { + // Arrange + A.CallTo(() => _gitRemoteTagChecker.CheckTagAsync(A._, A._, A._)) + .Returns(GitRemoteTagState.Missing); + var service = CreateService(); + + // Act + var result = await service.InstallAsync(["other"], TestContext.Current.CancellationToken); + + // Assert + result.Warnings + .Should().Equal(new IntegrationReleaseTagMissingWarning("0.8.0", "v0.8.0", "main")); + + A.CallTo(() => _other.InstallAsync(MainSource, A._)) + .MustHaveHappenedOnceExactly(); + } + + [Fact] + public async Task InstallAsync_SecondAgentFails_ThrowsRunFailedWithResultOfFirstAgent() + { + // Arrange + var failure = new ClaudeCommandFailedException(["plugin", "install"], 1, "failed."); + A.CallTo(() => _other.IsAvailable()).Returns(true); + A.CallTo(() => _other.InstallAsync(A._, A._)).ThrowsAsync(failure); + var service = CreateService(); + + // Act + var act = () => service.InstallAsync(null, TestContext.Current.CancellationToken); + + // Assert + var exception = (await act.Should().ThrowAsync()).Which; + + exception.FailedAgentId + .Should().Be("other"); + + exception.CompletedIntegrations + .Should().Equal(CreateResult("claude")); + + exception.MarketplaceSource + .Should().Be(ReleaseSource); + + exception.InnerException + .Should().BeSameAs(failure); + } + + [Theory] + [MemberData(nameof(AgentFailures))] + public async Task InstallAsync_SecondAgentFailsWithAgentFailure_KeepsFailureAsInnerException( + Exception failure) + { + // Arrange + A.CallTo(() => _other.IsAvailable()).Returns(true); + A.CallTo(() => _other.InstallAsync(A._, A._)).ThrowsAsync(failure); + var service = CreateService(); + + // Act + var act = () => service.InstallAsync(null, TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()) + .Which.InnerException.Should().BeSameAs(failure); + } + + [Fact] + public async Task InstallAsync_SecondAgentFailsWithReleaseTagMissing_KeepsFallbackSource() + { + // Arrange + A.CallTo(() => _gitRemoteTagChecker.CheckTagAsync(A._, A._, A._)) + .Returns(GitRemoteTagState.Missing); + A.CallTo(() => _other.IsAvailable()).Returns(true); + A.CallTo(() => _other.InstallAsync(A._, A._)) + .ThrowsAsync(new ClaudeCommandFailedException(["plugin", "install"], 1, "failed.")); + var service = CreateService(); + + // Act + var act = () => service.InstallAsync(null, TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()) + .Which.MarketplaceSource.Should().Be(MainSource); + } + + [Fact] + public async Task InstallAsync_SecondAgentSwitchCanceled_PropagatesSameInstance() + { + // Arrange + var canceled = new IntegrationSwitchCanceledException("other", new OperationCanceledException()); + A.CallTo(() => _other.IsAvailable()).Returns(true); + A.CallTo(() => _other.InstallAsync(A._, A._)).ThrowsAsync(canceled); + var service = CreateService(); + + // Act + var act = () => service.InstallAsync(null, TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()) + .Which.Should().BeSameAs(canceled); + } + + [Fact] + public async Task InstallAsync_SecondDetectedAgentMissing_ChecksNoTagAndInstallsForNoAgent() + { + // Arrange + A.CallTo(() => _other.IsAvailable()).Returns(true); + A.CallTo(() => _other.EnsureAvailable()) + .Throws(new ClaudeNotFoundException(["plugin", "list", "--json"], "Not on the PATH.")); + var service = CreateService(); + + // Act + var act = () => service.InstallAsync(null, TestContext.Current.CancellationToken); + + // Assert + await act.Should().ThrowAsync(); + + A.CallTo(() => _gitRemoteTagChecker.CheckTagAsync(A._, A._, A._)) + .MustNotHaveHappened(); + + A.CallTo(() => _claude.InstallAsync(A._, A._)) + .MustNotHaveHappened(); + } + + [Fact] + public async Task InstallAsync_TagCheckCanceled_InstallsForNoAgent() + { + // Arrange + A.CallTo(() => _gitRemoteTagChecker.CheckTagAsync(A._, A._, A._)) + .ThrowsAsync(new OperationCanceledException()); + var service = CreateService(); + + // Act + var act = () => service.InstallAsync(null, TestContext.Current.CancellationToken); + + // Assert + await act.Should().ThrowAsync(); + + A.CallTo(() => _claude.InstallAsync(A._, A._)) + .MustNotHaveHappened(); + } + + [Fact] + public async Task InstallAsync_ThirdAgentFails_KeepsResultsOfFirstTwoAgentsInOrder() + { + // Arrange + var third = CreateAgent("third", isAvailable: true); + A.CallTo(() => _other.IsAvailable()).Returns(true); + A.CallTo(() => third.InstallAsync(A._, A._)) + .ThrowsAsync(new ClaudeCommandFailedException(["plugin", "install"], 1, "failed.")); + var service = new IntegrationService([_claude, _other, third], _engineVersionProvider, _gitRemoteTagChecker, + name => _environment.GetValueOrDefault(name), () => CurrentDirectory); + + // Act + var act = () => service.InstallAsync(null, TestContext.Current.CancellationToken); + + // Assert + var exception = (await act.Should().ThrowAsync()).Which; + + exception.FailedAgentId + .Should().Be("third"); + + exception.CompletedIntegrations.Select(x => x.AgentId) + .Should().Equal("claude", "other"); + } + + [Fact] + public async Task InstallAsync_SecondAgentCanceled_PropagatesCancellationUnwrapped() + { + // Arrange + var canceled = new OperationCanceledException(); + A.CallTo(() => _other.IsAvailable()).Returns(true); + A.CallTo(() => _other.InstallAsync(A._, A._)).ThrowsAsync(canceled); + var service = CreateService(); + + // Act + var act = () => service.InstallAsync(null, TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()) + .Which.Should().BeSameAs(canceled); + } + + [Fact] + public async Task InstallAsync_SecondAgentThrowsUnexpectedException_PropagatesUnwrapped() + { + // Arrange + var failure = new InvalidOperationException("Defect."); + A.CallTo(() => _other.IsAvailable()).Returns(true); + A.CallTo(() => _other.InstallAsync(A._, A._)).ThrowsAsync(failure); + var service = CreateService(); + + // Act + var act = () => service.InstallAsync(null, TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()) + .Which.Should().BeSameAs(failure); + } + + [Fact] + public async Task InstallAsync_ExplicitAgentMissing_ThrowsItsNotFoundErrorBeforeReleaseTagCheck() + { + // Arrange + var notFound = new ClaudeNotFoundException(["plugin", "list", "--json"], "Not on the PATH."); + A.CallTo(() => _claude.EnsureAvailable()).Throws(notFound); + var service = CreateService(); + + // Act + var act = () => service.InstallAsync(["claude"], TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()) + .Which.Should().BeSameAs(notFound); + + A.CallTo(() => _gitRemoteTagChecker.CheckTagAsync(A._, A._, A._)) + .MustNotHaveHappened(); + + A.CallTo(() => _claude.InstallAsync(A._, A._)) + .MustNotHaveHappened(); + } + + [Fact] + public async Task InstallAsync_SecondExplicitAgentMissing_InstallsForNoAgent() + { + // Arrange + A.CallTo(() => _other.EnsureAvailable()) + .Throws(new ClaudeNotFoundException(["plugin", "list", "--json"], "Not on the PATH.")); + var service = CreateService(); + + // Act + var act = () => service.InstallAsync(["claude", "other"], TestContext.Current.CancellationToken); + + // Assert + await act.Should().ThrowAsync(); + + A.CallTo(() => _claude.InstallAsync(A._, A._)) + .MustNotHaveHappened(); + } + + [Fact] + public async Task InstallAsync_AvailableAgents_EnsuresAvailabilityBeforeTagCheckAndInstall() + { + // Arrange + var service = CreateService(); + + // Act + await service.InstallAsync(null, TestContext.Current.CancellationToken); + + // Assert + A.CallTo(() => _claude.EnsureAvailable()) + .MustHaveHappenedOnceExactly() + .Then(A.CallTo(() => _gitRemoteTagChecker.CheckTagAsync(A._, A._, + A._)) + .MustHaveHappenedOnceExactly()) + .Then(A.CallTo(() => _claude.InstallAsync(ReleaseSource, A._)) + .MustHaveHappenedOnceExactly()); + } + + [Fact] + public async Task InstallAsync_NoAgentAvailable_DoesNotCheckReleaseTag() + { + // Arrange + A.CallTo(() => _claude.IsAvailable()).Returns(false); + var service = CreateService(); + + // Act + var act = () => service.InstallAsync(null, TestContext.Current.CancellationToken); + + // Assert + await act.Should().ThrowAsync(); + + A.CallTo(() => _gitRemoteTagChecker.CheckTagAsync(A._, A._, A._)) + .MustNotHaveHappened(); + } + + [Fact] + public async Task InstallAsync_SeveralAvailableAgents_InstallsAllInRegistrationOrder() + { + // Arrange + A.CallTo(() => _other.IsAvailable()).Returns(true); + var service = CreateService(); + + // Act + var result = await service.InstallAsync(null, TestContext.Current.CancellationToken); + + // Assert + result.Integrations.Select(x => x.AgentId) + .Should().Equal("claude", "other"); + } + + [Fact] + public async Task InstallAsync_ExplicitAgentIdsInOtherOrder_InstallsInRequestedOrder() + { + // Arrange + var service = CreateService(); + + // Act + var result = await service.InstallAsync(["other", "claude"], TestContext.Current.CancellationToken); + + // Assert + result.Integrations.Select(x => x.AgentId) + .Should().Equal("other", "claude"); + } + + [Fact] + public async Task InstallAsync_FirstAgentFails_PropagatesFailureWithoutAskingLaterAgents() + { + // Arrange + A.CallTo(() => _other.IsAvailable()).Returns(true); + A.CallTo(() => _claude.InstallAsync(A._, A._)) + .ThrowsAsync(new IntegrationConflictException("claude", "m", "a", "b", "c")); + var service = CreateService(); + + // Act + var act = () => service.InstallAsync(null, TestContext.Current.CancellationToken); + + // Assert + await act.Should().ThrowAsync(); + + A.CallTo(() => _other.InstallAsync(A._, A._)) + .MustNotHaveHappened(); + } + + [Fact] + public async Task InstallAsync_UnknownAgentIdAndInvalidOverride_ThrowsArgumentException() + { + // Arrange + _environment[IntegrationService.MarketplaceSourceVariableName] = "-x"; + var service = CreateService(); + + // Act + var act = () => service.InstallAsync(["nope"], TestContext.Current.CancellationToken); + + // Assert + await act.Should().ThrowAsync() + .WithParameterName("agentIds"); + } + + [Fact] + public async Task InstallAsync_NoAgentsRegistered_ThrowsNoAgentFoundExceptionWithEmptyList() + { + // Arrange + var service = new IntegrationService([], _engineVersionProvider, _gitRemoteTagChecker, _ => null, + () => CurrentDirectory); + + // Act + var act = () => service.InstallAsync(null, TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()) + .Which.SupportedAgentIds.Should().BeEmpty(); + } + + [Fact] + public async Task InstallAsync_NoAgentIds_InstallsForEveryAvailableAgent() + { + // Arrange + var expected = CreateResult("claude"); + A.CallTo(() => _claude.InstallAsync(ReleaseSource, A._)).Returns(expected); + var service = CreateService(); + + // Act + var result = await service.InstallAsync(null, TestContext.Current.CancellationToken); + + // Assert + result + .Should().BeEquivalentTo(new IntegrationRunResult(ReleaseSource, [expected], [])); + + A.CallTo(() => _other.InstallAsync(A._, A._)) + .MustNotHaveHappened(); + } + + [Fact] + public async Task InstallAsync_EmptyAgentIds_InstallsForEveryAvailableAgent() + { + // Arrange + var service = CreateService(); + + // Act + await service.InstallAsync([], TestContext.Current.CancellationToken); + + // Assert + A.CallTo(() => _claude.InstallAsync(ReleaseSource, A._)).MustHaveHappenedOnceExactly(); + } + + [Fact] + public async Task InstallAsync_PrereleaseEngine_ReturnsPrereleaseRefWarning() + { + // Arrange + A.CallTo(() => _engineVersionProvider.Version).Returns("0.9.0-alpha.1"); + var service = CreateService(); + + // Act + var result = await service.InstallAsync(null, TestContext.Current.CancellationToken); + + // Assert + result.Source + .Should().Be(MainSource); + + result.Warnings + .Should().Equal(new IntegrationPrereleaseRefWarning("0.9.0-alpha.1", "main")); + + A.CallTo(() => _gitRemoteTagChecker.CheckTagAsync(A._, A._, A._)) + .MustNotHaveHappened(); + } + + [Fact] + public async Task InstallAsync_NoAgentAvailable_ThrowsNoAgentFoundException() + { + // Arrange + A.CallTo(() => _claude.IsAvailable()).Returns(false); + var service = CreateService(); + + // Act + var act = () => service.InstallAsync(null, TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()) + .Which.SupportedAgentIds.Should().Equal("claude", "other"); + } + + [Fact] + public async Task InstallAsync_ExplicitAgentIdInOtherCase_InstallsOnlyThatAgentWithoutDetection() + { + // Arrange + var service = CreateService(); + + // Act + await service.InstallAsync(["OTHER", "other"], TestContext.Current.CancellationToken); + + // Assert + A.CallTo(() => _other.InstallAsync(ReleaseSource, A._)).MustHaveHappenedOnceExactly(); + + A.CallTo(() => _claude.InstallAsync(A._, A._)) + .MustNotHaveHappened(); + + A.CallTo(() => _other.IsAvailable()) + .MustNotHaveHappened(); + } + + [Fact] + public async Task InstallAsync_ExplicitAgentNotFound_PropagatesAgentFailure() + { + // Arrange + A.CallTo(() => _claude.InstallAsync(A._, A._)) + .ThrowsAsync(new ClaudeNotFoundException(["plugin", "list", "--json"], "Not on the PATH.")); + var service = CreateService(); + + // Act + var act = () => service.InstallAsync(["claude"], TestContext.Current.CancellationToken); + + // Assert + await act.Should().ThrowAsync(); + } + + [Fact] + public async Task InstallAsync_UnknownAgentId_ThrowsArgumentExceptionWithoutAgentCalls() + { + // Arrange + var service = CreateService(); + + // Act + var act = () => service.InstallAsync(["claude", "nope"], TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()) + .WithParameterName("agentIds") + .WithMessage("*'nope'*claude, other*"); + + A.CallTo(() => _claude.InstallAsync(A._, A._)) + .MustNotHaveHappened(); + + A.CallTo(() => _gitRemoteTagChecker.CheckTagAsync(A._, A._, A._)) + .MustNotHaveHappened(); + } + + [Fact] + public async Task InstallAsync_InvalidOverride_ThrowsBeforeAnyAgentIsAsked() + { + // Arrange + _environment[IntegrationService.MarketplaceSourceVariableName] = "-x"; + A.CallTo(() => _claude.IsAvailable()).Returns(false); + var service = CreateService(); + + // Act + var act = () => service.InstallAsync(null, TestContext.Current.CancellationToken); + + // Assert + await act.Should().ThrowAsync(); + } + + [Fact] + public async Task InstallAsync_CancellationToken_IsPassedToAgent() + { + // Arrange + using var cancellationTokenSource = new CancellationTokenSource(); + var service = CreateService(); + + // Act + await service.InstallAsync(null, cancellationTokenSource.Token); + + // Assert + A.CallTo(() => _claude.InstallAsync(ReleaseSource, cancellationTokenSource.Token)) + .MustHaveHappenedOnceExactly(); + } + + [Fact] + public async Task UpdateAsync_InstalledAgent_ReturnsItsResult() + { + // Arrange + var service = CreateService(); + + // Act + var result = await service.UpdateAsync(TestContext.Current.CancellationToken); + + // Assert + result + .Should().BeEquivalentTo(new IntegrationRunResult(ReleaseSource, [CreateResult("claude")], [])); + + _updateSources + .Should().Equal(("claude", ReleaseSource)); + + A.CallTo(() => _other.UpdateAsync(A>>._, + A._)) + .MustNotHaveHappened(); + } + + [Fact] + public async Task UpdateAsync_InstalledAgents_DoesNotReadInstalledIntegrationsSeparately() + { + // Arrange + A.CallTo(() => _other.IsAvailable()).Returns(true); + var service = CreateService(); + + // Act + await service.UpdateAsync(TestContext.Current.CancellationToken); + + // Assert + A.CallTo(() => _claude.GetInstalledAsync(A._)).MustNotHaveHappened(); + A.CallTo(() => _other.GetInstalledAsync(A._)).MustNotHaveHappened(); + } + + [Fact] + public async Task UpdateAsync_NothingInstalled_ReturnsEmptyResultWithoutSourceAndWarnings() + { + // Arrange + SetUpNotInstalled(_claude); + var service = CreateService(); + + // Act + var result = await service.UpdateAsync(TestContext.Current.CancellationToken); + + // Assert + result + .Should().BeEquivalentTo(new IntegrationRunResult(null, [], [])); + + _updateSources + .Should().BeEmpty(); + } + + [Theory] + [InlineData("0.8.0")] + [InlineData("0.9.0-alpha.1")] + public async Task UpdateAsync_NothingInstalled_DoesNotCheckReleaseTag(string engineVersion) + { + // Arrange + A.CallTo(() => _engineVersionProvider.Version).Returns(engineVersion); + SetUpNotInstalled(_claude); + var service = CreateService(); + + // Act + var result = await service.UpdateAsync(TestContext.Current.CancellationToken); + + // Assert + result.Warnings + .Should().BeEmpty(); + + A.CallTo(() => _gitRemoteTagChecker.CheckTagAsync(A._, A._, A._)) + .MustNotHaveHappened(); + } + + [Fact] + public async Task UpdateAsync_NothingInstalledAndInvalidOverride_ReturnsEmptyResult() + { + // Arrange + _environment[IntegrationService.MarketplaceSourceVariableName] = "-x"; + SetUpNotInstalled(_claude); + var service = CreateService(); + + // Act + var result = await service.UpdateAsync(TestContext.Current.CancellationToken); + + // Assert + result.Integrations + .Should().BeEmpty(); + } + + [Fact] + public async Task UpdateAsync_InstalledAndReleaseTagMissing_UpdatesFromMainWithReleaseTagMissingWarning() + { + // Arrange + A.CallTo(() => _gitRemoteTagChecker.CheckTagAsync(A._, A._, A._)) + .Returns(GitRemoteTagState.Missing); + var service = CreateService(); + + // Act + var result = await service.UpdateAsync(TestContext.Current.CancellationToken); + + // Assert + result + .Should().BeEquivalentTo(new IntegrationRunResult(MainSource, [CreateResult("claude")], + [new IntegrationReleaseTagMissingWarning("0.8.0", "v0.8.0", "main")])); + + _updateSources + .Should().Equal(("claude", MainSource)); + } + + [Fact] + public async Task UpdateAsync_AgentResolvesSourceButReturnsNoResult_ReturnsSourceWithEmptyList() + { + // Arrange + A.CallTo(() => _claude.UpdateAsync(A>>._, + A._)) + .ReturnsLazily(async (Func> getSource, + CancellationToken cancellationToken) => + { + await getSource(cancellationToken); + + return (IntegrationResult?)null; + }); + var service = CreateService(); + + // Act + var result = await service.UpdateAsync(TestContext.Current.CancellationToken); + + // Assert + result.Integrations + .Should().BeEmpty(); + + result.Source + .Should().Be(ReleaseSource); + } + + [Fact] + public async Task UpdateAsync_SeveralInstalledAgents_UpdatesAllFromSourceResolvedOnceInRegistrationOrder() + { + // Arrange + A.CallTo(() => _other.IsAvailable()).Returns(true); + var service = CreateService(); + + // Act + var result = await service.UpdateAsync(TestContext.Current.CancellationToken); + + // Assert + result.Integrations.Select(x => x.AgentId) + .Should().Equal("claude", "other"); + + _updateSources + .Should().Equal(("claude", ReleaseSource), ("other", ReleaseSource)); + + A.CallTo(() => _gitRemoteTagChecker.CheckTagAsync(A._, A._, A._)) + .MustHaveHappenedOnceExactly(); + } + + [Fact] + public async Task UpdateAsync_FirstAgentNotInstalled_ResolvesSourceForSecondAgent() + { + // Arrange + A.CallTo(() => _other.IsAvailable()).Returns(true); + SetUpNotInstalled(_claude); + var service = CreateService(); + + // Act + var result = await service.UpdateAsync(TestContext.Current.CancellationToken); + + // Assert + result + .Should().BeEquivalentTo(new IntegrationRunResult(ReleaseSource, [CreateResult("other")], [])); + } + + [Fact] + public async Task UpdateAsync_SecondAgentUpdateFails_ThrowsRunFailedWithResultOfFirstAgent() + { + // Arrange + var failure = new ClaudeCommandFailedException(["plugin", "update"], 1, "failed."); + A.CallTo(() => _other.IsAvailable()).Returns(true); + A.CallTo(() => _other.UpdateAsync(A>>._, + A._)) + .ThrowsAsync(failure); + var service = CreateService(); + + // Act + var act = () => service.UpdateAsync(TestContext.Current.CancellationToken); + + // Assert + var exception = (await act.Should().ThrowAsync()).Which; + + exception.FailedAgentId + .Should().Be("other"); + + exception.CompletedIntegrations + .Should().Equal(CreateResult("claude")); + + exception.MarketplaceSource + .Should().Be(ReleaseSource); + + exception.InnerException + .Should().BeSameAs(failure); + } + + [Theory] + [MemberData(nameof(AgentFailures))] + public async Task UpdateAsync_SecondAgentFailsWithAgentFailure_ThrowsRunFailedKeepingFailure(Exception failure) + { + // Arrange + A.CallTo(() => _other.IsAvailable()).Returns(true); + A.CallTo(() => _other.UpdateAsync(A>>._, + A._)) + .ThrowsAsync(failure); + var service = CreateService(); + + // Act + var act = () => service.UpdateAsync(TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()) + .Which.InnerException.Should().BeSameAs(failure); + } + + [Fact] + public async Task UpdateAsync_FirstAgentReturnsNoResultSecondFails_PropagatesFailureUnwrapped() + { + // Arrange + var failure = new ClaudeCommandFailedException(["plugin", "update"], 1, "failed."); + A.CallTo(() => _other.IsAvailable()).Returns(true); + A.CallTo(() => _claude.UpdateAsync(A>>._, + A._)) + .ReturnsLazily(async (Func> getSource, + CancellationToken cancellationToken) => + { + await getSource(cancellationToken); + + return (IntegrationResult?)null; + }); + A.CallTo(() => _other.UpdateAsync(A>>._, + A._)) + .ThrowsAsync(failure); + var service = CreateService(); + + // Act + var act = () => service.UpdateAsync(TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()) + .Which.Should().BeSameAs(failure); + } + + [Fact] + public async Task UpdateAsync_FirstAgentNotInstalledSecondFails_PropagatesFailureUnwrapped() + { + // Arrange + var failure = new ClaudeCommandFailedException(["plugin", "update"], 1, "failed."); + A.CallTo(() => _other.IsAvailable()).Returns(true); + SetUpNotInstalled(_claude); + A.CallTo(() => _other.UpdateAsync(A>>._, + A._)) + .ThrowsAsync(failure); + var service = CreateService(); + + // Act + var act = () => service.UpdateAsync(TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()) + .Which.Should().BeSameAs(failure, "no other agent was done, so there is nothing to keep"); + } + + [Fact] + public async Task UpdateAsync_SecondAgentCanceled_PropagatesCancellationUnwrapped() + { + // Arrange + var canceled = new IntegrationSwitchCanceledException("other", new OperationCanceledException()); + A.CallTo(() => _other.IsAvailable()).Returns(true); + A.CallTo(() => _other.UpdateAsync(A>>._, + A._)) + .ThrowsAsync(canceled); + var service = CreateService(); + + // Act + var act = () => service.UpdateAsync(TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()) + .Which.Should().BeSameAs(canceled); + } + + [Fact] + public async Task UpdateAsync_SecondAgentThrowsUnexpectedException_PropagatesUnwrapped() + { + // Arrange + var failure = new IOException("Disk"); + A.CallTo(() => _other.IsAvailable()).Returns(true); + A.CallTo(() => _other.UpdateAsync(A>>._, + A._)) + .ThrowsAsync(failure); + var service = CreateService(); + + // Act + var act = () => service.UpdateAsync(TestContext.Current.CancellationToken); + + // Assert + (await act.Should().ThrowAsync()) + .Which.Should().BeSameAs(failure, "a defect is not an agent failure"); + } + + [Fact] + public async Task UpdateAsync_FirstAgentCannotBeStarted_PropagatesFailureWithoutAskingLaterAgents() + { + // Arrange + A.CallTo(() => _other.IsAvailable()).Returns(true); + A.CallTo(() => _claude.UpdateAsync(A>>._, + A._)) + .ThrowsAsync(new ClaudeUnavailableException(["plugin", "list", "--json"], "Cannot start.")); + var service = CreateService(); + + // Act + var act = () => service.UpdateAsync(TestContext.Current.CancellationToken); + + // Assert + await act.Should().ThrowAsync("update reports an agent failure as an error, " + + "unlike the read for 'version'"); + + A.CallTo(() => _other.UpdateAsync(A>>._, + A._)) + .MustNotHaveHappened(); + + A.CallTo(() => _gitRemoteTagChecker.CheckTagAsync(A._, A._, A._)) + .MustNotHaveHappened(); + } + + [Fact] + public async Task UpdateAsync_CancellationToken_IsPassedToAgentAndTagChecker() + { + // Arrange + using var cancellationTokenSource = new CancellationTokenSource(); + var service = CreateService(); + + // Act + await service.UpdateAsync(cancellationTokenSource.Token); + + // Assert + A.CallTo(() => _claude.UpdateAsync(A>>._, + cancellationTokenSource.Token)) + .MustHaveHappenedOnceExactly(); + + A.CallTo(() => _gitRemoteTagChecker.CheckTagAsync(A._, A._, cancellationTokenSource.Token)) + .MustHaveHappenedOnceExactly(); + } + + [Fact] + public async Task UpdateAsync_AgentFails_PropagatesFailure() + { + // Arrange + A.CallTo(() => _claude.UpdateAsync(A>>._, + A._)) + .ThrowsAsync(new ClaudeCommandFailedException(["plugin", "update"], 1, "claude failed.")); + var service = CreateService(); + + // Act + var act = () => service.UpdateAsync(TestContext.Current.CancellationToken); + + // Assert + await act.Should().ThrowAsync(); + } + + [Fact] + public async Task UpdateAsync_InstalledAndInvalidOverride_ThrowsFromSourceResolution() + { + // Arrange + _environment[IntegrationService.MarketplaceSourceVariableName] = ""; + A.CallTo(() => _other.IsAvailable()).Returns(true); + var service = CreateService(); + + // Act + var act = () => service.UpdateAsync(TestContext.Current.CancellationToken); + + // Assert + await act.Should().ThrowAsync(); + + _updateSources + .Should().BeEmpty("the first installed agent resolves the source before it changes anything"); + + A.CallTo(() => _other.UpdateAsync(A>>._, + A._)) + .MustNotHaveHappened(); + } + + [Fact] + public async Task UpdateAsync_NoAgentAvailable_ThrowsNoAgentFoundException() + { + // Arrange + A.CallTo(() => _claude.IsAvailable()).Returns(false); + var service = CreateService(); + + // Act + var act = () => service.UpdateAsync(TestContext.Current.CancellationToken); + + // Assert + await act.Should().ThrowAsync(); + } + + [Fact] + public async Task UpdateAsync_PrereleaseEngine_ReturnsPrereleaseRefWarning() + { + // Arrange + A.CallTo(() => _engineVersionProvider.Version).Returns("0.9.0-alpha.1"); + var service = CreateService(); + + // Act + var result = await service.UpdateAsync(TestContext.Current.CancellationToken); + + // Assert + result.Warnings + .Should().Equal(new IntegrationPrereleaseRefWarning("0.9.0-alpha.1", "main")); + } + + [Fact] + public async Task GetInstalledAsync_InstalledAndNotInstalledAgents_ReturnsInstalledOnly() + { + // Arrange + var installed = new InstalledIntegration("claude", "shade-kit@creativecoders-shade-kit", "0.8.0", "v0.8.0", + true); + A.CallTo(() => _other.IsAvailable()).Returns(true); + A.CallTo(() => _claude.GetInstalledAsync(A._)).Returns(installed); + A.CallTo(() => _other.GetInstalledAsync(A._)).Returns((InstalledIntegration?)null); + var service = CreateService(); + + // Act + var result = await service.GetInstalledAsync(TestContext.Current.CancellationToken); + + // Assert + result.Integrations + .Should().Equal(installed); + + result.Warnings + .Should().BeEmpty(); + } + + [Fact] + public async Task GetInstalledAsync_AgentNotAvailable_DoesNotAskItAndReturnsNoWarning() + { + // Arrange + A.CallTo(() => _claude.IsAvailable()).Returns(false); + var service = CreateService(); + + // Act + var result = await service.GetInstalledAsync(TestContext.Current.CancellationToken); + + // Assert + result + .Should().BeEquivalentTo(new InstalledIntegrationsResult([], [])); + + A.CallTo(() => _claude.GetInstalledAsync(A._)) + .MustNotHaveHappened(); + + A.CallTo(() => _other.GetInstalledAsync(A._)) + .MustNotHaveHappened(); + } + + [Fact] + public async Task GetInstalledAsync_AvailableAgentNotFoundWhenCalled_ReturnsAgentUnavailableWarning() + { + // Arrange + var failure = new ClaudeNotFoundException(["plugin", "list", "--json"], "Not on the PATH."); + A.CallTo(() => _claude.GetInstalledAsync(A._)).ThrowsAsync(failure); + A.CallTo(() => _other.GetInstalledAsync(A._)).Returns((InstalledIntegration?)null); + var service = CreateService(); + + // Act + var result = await service.GetInstalledAsync(TestContext.Current.CancellationToken); + + // Assert + result.Integrations + .Should().BeEmpty(); + + result.Warnings + .Should().Equal(new AgentUnavailableWarning("claude", failure.Message)); + } + + [Fact] + public async Task GetInstalledAsync_AgentCommandFails_ReturnsWarningAndOtherAgents() + { + // Arrange + var failure = new ClaudeCommandFailedException(["plugin", "list", "--json"], 1, "claude failed."); + var installed = new InstalledIntegration("other", "kit", null, null, true); + A.CallTo(() => _other.IsAvailable()).Returns(true); + A.CallTo(() => _claude.GetInstalledAsync(A._)).ThrowsAsync(failure); + A.CallTo(() => _other.GetInstalledAsync(A._)).Returns(installed); + var service = CreateService(); + + // Act + var result = await service.GetInstalledAsync(TestContext.Current.CancellationToken); + + // Assert + result.Integrations + .Should().Equal(installed); + + result.Warnings + .Should().Equal(new AgentUnavailableWarning("claude", failure.Message)); + } + + [Fact] + public async Task GetInstalledAsync_UnexpectedFailure_PropagatesFailure() + { + // Arrange + A.CallTo(() => _claude.GetInstalledAsync(A._)).ThrowsAsync(new IOException("Disk")); + var service = CreateService(); + + // Act + var act = () => service.GetInstalledAsync(TestContext.Current.CancellationToken); + + // Assert + await act.Should().ThrowAsync(); + } + + [Fact] + public async Task GetInstalledAsync_AllAgentsFail_ReturnsOneWarningPerAgentInOrder() + { + // Arrange + A.CallTo(() => _other.IsAvailable()).Returns(true); + A.CallTo(() => _claude.GetInstalledAsync(A._)) + .ThrowsAsync(new ClaudeNotFoundException(["plugin", "list", "--json"], "Not on the PATH.")); + A.CallTo(() => _other.GetInstalledAsync(A._)) + .ThrowsAsync(new ClaudeUnavailableException(["plugin", "list", "--json"], "Cannot start.")); + var service = CreateService(); + + // Act + var result = await service.GetInstalledAsync(TestContext.Current.CancellationToken); + + // Assert + result.Warnings.OfType().Select(x => x.AgentId) + .Should().Equal("claude", "other"); + } + + [Fact] + public async Task GetInstalledAsync_Canceled_PropagatesCancellation() + { + // Arrange + A.CallTo(() => _claude.GetInstalledAsync(A._)) + .ThrowsAsync(new OperationCanceledException()); + var service = CreateService(); + + // Act + var act = () => service.GetInstalledAsync(TestContext.Current.CancellationToken); + + // Assert + await act.Should().ThrowAsync(); + } + + [Fact] + public async Task GetInstalledAsync_CancellationToken_IsPassedToAgent() + { + // Arrange + using var cancellationTokenSource = new CancellationTokenSource(); + var service = CreateService(); + + // Act + await service.GetInstalledAsync(cancellationTokenSource.Token); + + // Assert + A.CallTo(() => _claude.GetInstalledAsync(cancellationTokenSource.Token)) + .MustHaveHappenedOnceExactly(); + } + + [Fact] + public async Task GetInstalledAsync_InvalidOverride_IgnoresOverride() + { + // Arrange + _environment[IntegrationService.MarketplaceSourceVariableName] = "-x"; + A.CallTo(() => _claude.GetInstalledAsync(A._)).Returns((InstalledIntegration?)null); + A.CallTo(() => _other.GetInstalledAsync(A._)).Returns((InstalledIntegration?)null); + var service = CreateService(); + + // Act + var result = await service.GetInstalledAsync(TestContext.Current.CancellationToken); + + // Assert + result.Warnings + .Should().BeEmpty(); + } + + // An update of the fake behaves like an installed integration: it resolves the source with the token it got, + // records the source, and returns its result. + private IAgentIntegration CreateAgent(string agentId, bool isAvailable) + { + var agent = A.Fake(); + A.CallTo(() => agent.AgentId).Returns(agentId); + A.CallTo(() => agent.IsAvailable()).Returns(isAvailable); + A.CallTo(() => agent.InstallAsync(A._, A._)) + .Returns(CreateResult(agentId)); + A.CallTo(() => agent.GetInstalledAsync(A._)) + .Returns(new InstalledIntegration(agentId, "shade-kit@creativecoders-shade-kit", "0.7.0", "v0.7.0", true)); + A.CallTo(() => agent.UpdateAsync(A>>._, + A._)) + .ReturnsLazily(async (Func> getSource, + CancellationToken cancellationToken) => + { + _updateSources.Add((agentId, await getSource(cancellationToken))); + + return (IntegrationResult?)CreateResult(agentId); + }); + + return agent; + } + + // An update of the fake behaves like a missing integration: it resolves no source and returns null. + private static void SetUpNotInstalled(IAgentIntegration agent) + { + A.CallTo(() => agent.UpdateAsync(A>>._, + A._)) + .Returns((IntegrationResult?)null); + } + + public static TheoryData AgentFailures() + { + return + [ + new ClaudeUnavailableException(["plugin", "list", "--json"], "Cannot start."), + new IntegrationConflictException("other", "m", "a", "b", "c"), + new IntegrationIncompleteException("other", new ClaudeCommandFailedException(["x"], 1, "failed.")) + ]; + } + + private static IntegrationResult CreateResult(string agentId) + { + return new IntegrationResult(agentId, "shade-kit@creativecoders-shade-kit", IntegrationOutcome.Installed, + null, "0.8.0", "v0.8.0", true); + } + + private IntegrationService CreateService() + { + return new IntegrationService([_claude, _other], _engineVersionProvider, _gitRemoteTagChecker, + name => _environment.GetValueOrDefault(name), () => CurrentDirectory); + } +} diff --git a/tests/CreativeCoders.ShadeKit.Core.Tests/Integrations/MarketplaceSourceTests.cs b/tests/CreativeCoders.ShadeKit.Core.Tests/Integrations/MarketplaceSourceTests.cs new file mode 100644 index 0000000..e52b841 --- /dev/null +++ b/tests/CreativeCoders.ShadeKit.Core.Tests/Integrations/MarketplaceSourceTests.cs @@ -0,0 +1,380 @@ +using AwesomeAssertions; +using CreativeCoders.ShadeKit.Core.Integrations; +using CreativeCoders.ShadeKit.Core.Integrations.Exceptions; + +namespace CreativeCoders.ShadeKit.Core.Tests.Integrations; + +public class MarketplaceSourceTests +{ + private static readonly string CurrentDirectory = + Path.TrimEndingDirectorySeparator(Path.Combine(Path.GetTempPath(), "shade-kit-tests", "cwd")); + + [Theory] + [InlineData("CreativeCodersTeam/shade-kit#v0.8.0", "CreativeCodersTeam/shade-kit", "v0.8.0")] + [InlineData("owner/repo#main", "owner/repo", "main")] + [InlineData("owner/repo#feature/login-sso", "owner/repo", "feature/login-sso")] + [InlineData("my-org/my.repo_name#v1.0.0-beta.1", "my-org/my.repo_name", "v1.0.0-beta.1")] + public void Parse_GitHubRepoWithRef_ReturnsGitHubSourceWithRef(string value, string expectedRepo, + string expectedRef) + { + // Act + var source = MarketplaceSource.Parse(value, CurrentDirectory); + + // Assert + source.Text + .Should().Be(value); + + source.Repo + .Should().Be(expectedRepo); + + source.Ref + .Should().Be(expectedRef); + + source.Path + .Should().BeNull(); + } + + [Fact] + public void Parse_GitHubRepoWithoutRef_ReturnsGitHubSourceWithoutRef() + { + // Act + var source = MarketplaceSource.Parse("owner/repo", CurrentDirectory); + + // Assert + source + .Should().Be(MarketplaceSource.ForGitHub("owner/repo")); + + source.Text + .Should().Be("owner/repo"); + + source.Ref + .Should().BeNull(); + } + + [Fact] + public void Parse_AbsolutePath_ReturnsDirectorySourceWithNormalizedPath() + { + // Arrange + var path = Path.Combine(Path.GetTempPath(), "shade-kit-tests", "kit") + Path.DirectorySeparatorChar; + var expectedPath = Path.TrimEndingDirectorySeparator(path); + + // Act + var source = MarketplaceSource.Parse(path, CurrentDirectory); + + // Assert + source.Text + .Should().Be(expectedPath); + + source.Path + .Should().Be(expectedPath); + + source.Repo + .Should().BeNull(); + + source.Ref + .Should().BeNull(); + } + + [Theory] + [InlineData("./kit")] + [InlineData("kit")] + [InlineData("./dir/kit")] + [InlineData("dir/sub/kit")] + [InlineData("../cwd/kit")] + public void Parse_RelativePath_ReturnsDirectorySourceResolvedAgainstCurrentDirectory(string value) + { + // Arrange + var expectedPath = Path.GetFullPath(value, CurrentDirectory); + + // Act + var source = MarketplaceSource.Parse(value, CurrentDirectory); + + // Assert + source.Path + .Should().Be(expectedPath); + + source.Text + .Should().Be(expectedPath); + } + + [Theory] + [InlineData("~/kit")] + [InlineData("dir\\kit")] + [InlineData("owner\\repo")] + [InlineData("./dir#x/kit")] + [InlineData("./mirror/https://example.com/repo")] + [InlineData("./git@host:repo")] + [InlineData("dir/sub/git@host:repo")] + public void Parse_ValueThatIsNoGitHubForm_ReturnsDirectorySource(string value) + { + // Act + var source = MarketplaceSource.Parse(value, CurrentDirectory); + + // Assert + source.Path + .Should().Be(Path.TrimEndingDirectorySeparator(Path.GetFullPath(value, CurrentDirectory))); + + source.Repo + .Should().BeNull(); + } + + [Theory] + [InlineData("/kit")] + [InlineData("/kit#x")] + [InlineData("/srv/git@host:repo")] + [InlineData("/mirror/https://example.com/repo")] + public void Parse_AbsoluteUnixPath_ReturnsDirectorySource(string value) + { + // Arrange + Assert.SkipWhen(OperatingSystem.IsWindows(), "On Windows a path that starts with '/' is not fully qualified."); + + // Act + var source = MarketplaceSource.Parse(value, CurrentDirectory); + + // Assert + source.Path + .Should().Be(Path.GetFullPath(value)); + + source.Repo + .Should().BeNull(); + } + + [Fact] + public void Parse_AbsolutePathWithHash_KeepsHashInPath() + { + // Arrange + var path = Path.Combine(Path.GetTempPath(), "a#b"); + + // Act + var source = MarketplaceSource.Parse(path, CurrentDirectory); + + // Assert + source.Path + .Should().Be(Path.GetFullPath(path)); + } + + [Theory] + [InlineData("a/b")] + [InlineData("owner/.github")] + public void Parse_ShortOrDotLeadingRepo_ReturnsGitHubSource(string value) + { + // Act + var source = MarketplaceSource.Parse(value, CurrentDirectory); + + // Assert + source.Repo + .Should().Be(value); + } + + [Fact] + public void Parse_NullValue_ThrowsArgumentNullException() + { + // Act + var act = () => MarketplaceSource.Parse(null!, CurrentDirectory); + + // Assert + act.Should().Throw(); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData("-x")] + [InlineData("--scope")] + [InlineData("owner/repo#")] + [InlineData("owner/repo#with space")] + [InlineData("owner/repo#a#b")] + [InlineData("owner/")] + [InlineData("-owner/repo")] + [InlineData("owner/..")] + [InlineData("owner/.")] + [InlineData("owner-/repo")] + [InlineData(" owner/repo")] + public void Parse_InvalidValue_ThrowsInvalidMarketplaceSourceException(string value) + { + // Act + var act = () => MarketplaceSource.Parse(value, CurrentDirectory); + + // Assert + act.Should().Throw() + .Which.Value.Should().Be(value); + } + + [Theory] + [InlineData("https://github.com/CreativeCodersTeam/shade-kit.git")] + [InlineData("https://github.com/owner/repo#main")] + [InlineData("http://example.com/owner/repo")] + [InlineData("HTTPS://GITHUB.COM/OWNER/REPO")] + [InlineData("ssh://git@github.com/owner/repo.git")] + [InlineData("git://github.com/owner/repo")] + [InlineData("git+ssh://git@github.com/owner/repo")] + [InlineData("file:///Users/dev/shade-kit")] + [InlineData("file://C:/work/shade-kit")] + [InlineData("ab://x")] + public void Parse_UrlWithScheme_ThrowsInvalidMarketplaceSourceExceptionNamingGitHubForm(string value) + { + // Act + var act = () => MarketplaceSource.Parse(value, CurrentDirectory); + + // Assert + var exception = act.Should().Throw().Which; + + exception.Value + .Should().Be(value); + + exception.Reason + .Should().Be("It is a URL, and SHADE kit takes no URL as a marketplace source; a GitHub repository is " + + "written as owner/repo#ref or owner/repo."); + } + + [Theory] + [InlineData("git@github.com:owner/repo")] + [InlineData("git@github.com:CreativeCodersTeam/shade-kit.git")] + [InlineData("git@github.com:owner/repo#main")] + [InlineData("user@host.example:path/to/repo")] + [InlineData("github.com:owner/repo")] + [InlineData("ab:c")] + public void Parse_ScpLikeGitUrl_ThrowsInvalidMarketplaceSourceExceptionNamingGitHubForm(string value) + { + // Act + var act = () => MarketplaceSource.Parse(value, CurrentDirectory); + + // Assert + var exception = act.Should().Throw().Which; + + exception.Value + .Should().Be(value); + + exception.Reason + .Should().Be("It is an scp-like git URL (user@host:path), and SHADE kit takes no URL as a marketplace " + + "source; a GitHub repository is written as owner/repo#ref or owner/repo."); + } + + [Theory] + [InlineData("C:\\work\\shade-kit")] + [InlineData("C:/work/shade-kit")] + [InlineData("c:\\work\\shade-kit")] + [InlineData("C://work/shade-kit")] + [InlineData("D:\\")] + [InlineData("C:\\work\\git@host:x")] + public void Parse_WindowsDrivePathOnWindows_ReturnsDirectorySource(string value) + { + // Arrange + Assert.SkipUnless(OperatingSystem.IsWindows(), "Only Windows reads a drive path as a fully qualified path."); + + // Act + var source = MarketplaceSource.Parse(value, CurrentDirectory); + + // Assert + source.Path + .Should().Be(Path.TrimEndingDirectorySeparator(Path.GetFullPath(value))); + + source.Repo + .Should().BeNull(); + } + + [Theory] + [InlineData("C:\\work\\shade-kit")] + [InlineData("C:/work/shade-kit")] + [InlineData("c:\\work\\shade-kit")] + [InlineData("C://work/shade-kit")] + [InlineData("D:\\")] + public void Parse_WindowsDrivePath_IsNotRefusedAsUrl(string value) + { + // Act + var exception = Record.Exception(() => MarketplaceSource.Parse(value, CurrentDirectory)); + + // Assert: on Windows every value is a path; elsewhere C:/work/shade-kit looks like a GitHub repository and is + // refused as one, but no value is refused as a URL. + if (exception is InvalidMarketplaceSourceException invalidSource) + { + invalidSource.Reason + .Should().NotContain("URL"); + } + else + { + exception + .Should().BeNull(); + } + } + + [Theory] + [InlineData("v0.8.0", "0.8.0")] + [InlineData("v1.2.3-beta.1", "1.2.3-beta.1")] + [InlineData("main", null)] + [InlineData("0.8.0", null)] + [InlineData("V0.8.0", null)] + [InlineData("v0.8", null)] + [InlineData("v", null)] + [InlineData(null, null)] + public void GetKitVersion_Ref_ReturnsSemVerOfVTagOrNull(string? @ref, string? expectedKitVersion) + { + // Act + var kitVersion = MarketplaceSource.GetKitVersion(@ref); + + // Assert + kitVersion + .Should().Be(expectedKitVersion); + } + + [Fact] + public void KitVersion_GitHubSourceWithVTag_ReturnsVersionWithoutV() + { + // Act + var source = MarketplaceSource.ForGitHub("CreativeCodersTeam/shade-kit", "v0.8.0"); + + // Assert + source.KitVersion + .Should().Be("0.8.0"); + } + + [Fact] + public void KitVersion_DirectorySource_ReturnsNull() + { + // Act + var source = MarketplaceSource.ForDirectory(CurrentDirectory); + + // Assert + source.KitVersion + .Should().BeNull(); + } + + [Theory] + [InlineData("repo")] + [InlineData("owner/repo/extra")] + [InlineData("owner/repo#v1")] + public void ForGitHub_InvalidRepo_ThrowsArgumentException(string value) + { + // Act + var act = () => MarketplaceSource.ForGitHub(value); + + // Assert + act.Should().Throw() + .WithParameterName("repo"); + } + + [Theory] + [InlineData("")] + [InlineData("a b")] + [InlineData("a#b")] + public void ForGitHub_InvalidRef_ThrowsArgumentException(string value) + { + // Act + var act = () => MarketplaceSource.ForGitHub("owner/repo", value); + + // Assert + act.Should().Throw() + .WithParameterName("ref"); + } + + [Fact] + public void ForDirectory_RelativePath_ThrowsArgumentException() + { + // Act + var act = () => MarketplaceSource.ForDirectory("kit"); + + // Assert + act.Should().Throw() + .WithParameterName("path"); + } +} diff --git a/tests/CreativeCoders.ShadeKit.Core.Tests/Processes/ExternalToolRunnerTests.cs b/tests/CreativeCoders.ShadeKit.Core.Tests/Processes/ExternalToolRunnerTests.cs new file mode 100644 index 0000000..e357492 --- /dev/null +++ b/tests/CreativeCoders.ShadeKit.Core.Tests/Processes/ExternalToolRunnerTests.cs @@ -0,0 +1,31 @@ +using AwesomeAssertions; +using CreativeCoders.ShadeKit.Core.Git.Exceptions; +using CreativeCoders.ShadeKit.Core.Processes; + +namespace CreativeCoders.ShadeKit.Core.Tests.Processes; + +public class ExternalToolRunnerTests +{ + [Fact] + public async Task RunAsync_ExecutableNotFound_PassesNotFoundReasonToTheToolException() + { + // Arrange + var tool = new ExternalTool("tool", "The Example CLI tool", null, + static (arguments, reason) => new GitNotFoundException(arguments, reason), + static (_, _, _) => throw new NotSupportedException()); + + // Act + var act = () => ExternalToolRunner.RunAsync(tool, static () => null, Path.GetTempPath(), ["x"], + TestContext.Current.CancellationToken); + + // Assert + var exception = (await act + .Should().ThrowExactlyAsync()).Which; + + exception.Reason + .Should().Be(tool.NotFoundReason); + + exception.Arguments + .Should().Equal("x"); + } +} diff --git a/tests/CreativeCoders.ShadeKit.Core.Tests/Processes/ExternalToolTests.cs b/tests/CreativeCoders.ShadeKit.Core.Tests/Processes/ExternalToolTests.cs new file mode 100644 index 0000000..b07eb43 --- /dev/null +++ b/tests/CreativeCoders.ShadeKit.Core.Tests/Processes/ExternalToolTests.cs @@ -0,0 +1,24 @@ +using AwesomeAssertions; +using CreativeCoders.ShadeKit.Core.Processes; + +namespace CreativeCoders.ShadeKit.Core.Tests.Processes; + +public class ExternalToolTests +{ + [Fact] + public void NotFoundReason_NameDiffersFromDisplayName_StartsWithDisplayName() + { + // Arrange + var tool = new ExternalTool("tool", "The Example CLI tool", null, + static (_, _) => throw new NotSupportedException(), + static (_, _, _) => throw new NotSupportedException()); + + // Act + var reason = tool.NotFoundReason; + + // Assert + reason + .Should().Be( + "The Example CLI tool was not found in any absolute directory of the PATH environment variable."); + } +} diff --git a/tests/CreativeCoders.ShadeKit.Core.Tests/Processes/UserWorkingDirectoryTests.cs b/tests/CreativeCoders.ShadeKit.Core.Tests/Processes/UserWorkingDirectoryTests.cs new file mode 100644 index 0000000..6e0a9ab --- /dev/null +++ b/tests/CreativeCoders.ShadeKit.Core.Tests/Processes/UserWorkingDirectoryTests.cs @@ -0,0 +1,59 @@ +using AwesomeAssertions; +using CreativeCoders.ShadeKit.Core.Processes; + +namespace CreativeCoders.ShadeKit.Core.Tests.Processes; + +public class UserWorkingDirectoryTests +{ + private const string HomeDirectory = "/home/me"; + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public void Get_HomeDirectoryNotKnown_ReturnsTemporaryDirectory(string? homeDirectory) + { + // Act + var workingDirectory = UserWorkingDirectory.Get(homeDirectory, static _ => true); + + // Assert + workingDirectory + .Should().Be(Path.GetTempPath()); + } + + [Fact] + public void Get_HomeDirectoryDoesNotExist_ReturnsTemporaryDirectory() + { + // Act + var workingDirectory = UserWorkingDirectory.Get(HomeDirectory, static _ => false); + + // Assert + workingDirectory + .Should().Be(Path.GetTempPath()); + } + + [Fact] + public void Get_HomeDirectoryExists_ReturnsHomeDirectory() + { + // Act + var workingDirectory = UserWorkingDirectory.Get(HomeDirectory, static x => x == HomeDirectory); + + // Assert + workingDirectory + .Should().Be(HomeDirectory); + } + + [Fact] + public void Get_CurrentProcess_ReturnsExistingHomeOrTemporaryDirectory() + { + // Act + var workingDirectory = UserWorkingDirectory.Get(); + + // Assert + workingDirectory + .Should().BeOneOf(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), Path.GetTempPath()); + + Directory.Exists(workingDirectory) + .Should().BeTrue(); + } +} diff --git a/tests/CreativeCoders.ShadeKit.Core.Tests/ShadeKitCoreServiceCollectionExtensionsTests.cs b/tests/CreativeCoders.ShadeKit.Core.Tests/ShadeKitCoreServiceCollectionExtensionsTests.cs index a680a89..e9a2aa3 100644 --- a/tests/CreativeCoders.ShadeKit.Core.Tests/ShadeKitCoreServiceCollectionExtensionsTests.cs +++ b/tests/CreativeCoders.ShadeKit.Core.Tests/ShadeKitCoreServiceCollectionExtensionsTests.cs @@ -8,6 +8,8 @@ using CreativeCoders.ShadeKit.Core.Git; using CreativeCoders.ShadeKit.Core.Git.Exceptions; using CreativeCoders.ShadeKit.Core.Init; +using CreativeCoders.ShadeKit.Core.Integrations; +using CreativeCoders.ShadeKit.Core.Integrations.Claude; using CreativeCoders.ShadeKit.Core.Processes; using CreativeCoders.ShadeKit.Core.Store; using CreativeCoders.ShadeKit.Core.Store.Exceptions; @@ -93,6 +95,11 @@ public void AddShadeKitCore_ServiceCollection_RegistersKitStoreFactoryAsSingleto [InlineData(typeof(IGhExecutableLocator), typeof(GhExecutableLocator))] [InlineData(typeof(IGhCommandRunner), typeof(GhCommandRunner))] [InlineData(typeof(ITrackerIssueReader), typeof(GitHubCliIssueReader))] + [InlineData(typeof(IGitRemoteTagChecker), typeof(GitRemoteTagChecker))] + [InlineData(typeof(IClaudeExecutableLocator), typeof(ClaudeExecutableLocator))] + [InlineData(typeof(IClaudeCommandRunner), typeof(ClaudeCommandRunner))] + [InlineData(typeof(IClaudePluginCli), typeof(ClaudePluginCli))] + [InlineData(typeof(IIntegrationService), typeof(IntegrationService))] public void AddShadeKitCore_ServiceCollection_RegistersServiceAsSingleton(Type serviceType, Type implementationType) { // Arrange @@ -111,6 +118,49 @@ public void AddShadeKitCore_ServiceCollection_RegistersServiceAsSingleton(Type s secondInstance.Should().BeSameAs(firstInstance); } + [Fact] + public void AddShadeKitCore_CalledTwice_RegistersClaudeCodeIntegrationOnceAsSingleton() + { + // Arrange + var services = new ServiceCollection(); + + // Act + services.AddShadeKitCore(); + services.AddShadeKitCore(); + + // Assert + using var serviceProvider = services.BuildServiceProvider(); + + var agentIntegrations = serviceProvider.GetServices().ToArray(); + + agentIntegrations + .Should().ContainSingle() + .Which.Should().BeOfType() + .And.BeSameAs(serviceProvider.GetServices().Single()); + + serviceProvider.GetRequiredService().AgentIds + .Should().Equal(ClaudeCodeIntegration.ClaudeAgentId); + } + + [Fact] + public void AddShadeKitCore_OtherAgentIntegrationRegistered_KeepsBothIntegrations() + { + // Arrange + var services = new ServiceCollection(); + var otherIntegration = A.Fake(); + A.CallTo(() => otherIntegration.AgentId).Returns("other"); + services.AddSingleton(otherIntegration); + + // Act + services.AddShadeKitCore(); + + // Assert + using var serviceProvider = services.BuildServiceProvider(); + + serviceProvider.GetRequiredService().AgentIds + .Should().Equal("other", ClaudeCodeIntegration.ClaudeAgentId); + } + [Fact] public void AddShadeKitCore_ServiceCollection_RegistersFormatRegistryWithAllFileTypes() { @@ -125,7 +175,7 @@ public void AddShadeKitCore_ServiceCollection_RegistersFormatRegistryWithAllFile serviceProvider.GetRequiredService().Formats.Select(x => x.Id) .Should().Equal(FormatIds.Config, FormatIds.Gates, FormatIds.Feature, FormatIds.CurrentFeature, - FormatIds.TemplatesLock, FormatIds.Integrations); + FormatIds.TemplatesLock); } [Fact] @@ -198,6 +248,11 @@ public void AddShadeKitCore_ExistingFormatRegistryRegistration_SerializerUsesExi [InlineData(typeof(IGhExecutableLocator))] [InlineData(typeof(IGhCommandRunner))] [InlineData(typeof(ITrackerIssueReader))] + [InlineData(typeof(IGitRemoteTagChecker))] + [InlineData(typeof(IClaudeExecutableLocator))] + [InlineData(typeof(IClaudeCommandRunner))] + [InlineData(typeof(IClaudePluginCli))] + [InlineData(typeof(IIntegrationService))] [InlineData(typeof(IHttpClientFactory))] [InlineData(typeof(TimeProvider))] public void AddShadeKitCore_ExistingServiceRegistration_KeepsExistingRegistration(Type serviceType) @@ -247,6 +302,11 @@ public void AddShadeKitCore_ExistingServiceRegistration_KeepsExistingRegistratio [InlineData(typeof(IGhExecutableLocator))] [InlineData(typeof(IGhCommandRunner))] [InlineData(typeof(ITrackerIssueReader))] + [InlineData(typeof(IGitRemoteTagChecker))] + [InlineData(typeof(IClaudeExecutableLocator))] + [InlineData(typeof(IClaudeCommandRunner))] + [InlineData(typeof(IClaudePluginCli))] + [InlineData(typeof(IIntegrationService))] [InlineData(typeof(IHttpClientFactory))] [InlineData(typeof(TimeProvider))] public void AddShadeKitCore_CalledTwice_RegistersServiceOnlyOnce(Type serviceType) @@ -412,6 +472,30 @@ public async Task AddShadeKitCore_ExistingGitRepositoryInfoRegistration_CurrentF .Should().Be("login"); } + [Fact] + public async Task AddShadeKitCore_ExistingGitCommandRunnerRegistration_GitRemoteTagCheckerUsesExistingRunner() + { + // Arrange + var existingRunner = A.Fake(); + A.CallTo(() => existingRunner.RunAsync(A._, A>._, A._)) + .Returns(new ExternalProcessResult(0, "4a1b2c3d\trefs/tags/v0.8.0\n", "")); + + var services = new ServiceCollection(); + services.AddSingleton(existingRunner); + + // Act + services.AddShadeKitCore(); + + // Assert + await using var serviceProvider = services.BuildServiceProvider(); + + var state = await serviceProvider.GetRequiredService() + .CheckTagAsync("https://example.com/repo.git", "v0.8.0", TestContext.Current.CancellationToken); + + state + .Should().Be(GitRemoteTagState.Found); + } + [Fact] public async Task AddShadeKitCore_ExistingGitCommandRunnerRegistration_GitLineEndingResolverUsesExistingRunner() { diff --git a/tests/CreativeCoders.ShadeKit.Core.Tests/Skills/ShippedSkillFiles.cs b/tests/CreativeCoders.ShadeKit.Core.Tests/Skills/ShippedSkillFiles.cs new file mode 100644 index 0000000..86ca424 --- /dev/null +++ b/tests/CreativeCoders.ShadeKit.Core.Tests/Skills/ShippedSkillFiles.cs @@ -0,0 +1,102 @@ +using System.Text; + +namespace CreativeCoders.ShadeKit.Core.Tests.Skills; + +/// +/// Finds the shipped skill files of a repository for the guard tests of the skills. +/// +internal static class ShippedSkillFiles +{ + public const string SkillsDirectoryName = "skills"; + + public const string SkillFileName = "SKILL.md"; + + private const string SolutionFileName = "ShadeKit.slnx"; + + // git treats a file as binary when its first 8000 bytes contain a NUL byte; the guards use the same rule. + private const int BinaryProbeLength = 8000; + + private static readonly UTF8Encoding StrictUtf8 = new(encoderShouldEmitUTF8Identifier: false, + throwOnInvalidBytes: true); + + public static string FindRepositoryRoot() + { + for (var directory = new DirectoryInfo(AppContext.BaseDirectory); directory != null; + directory = directory.Parent) + { + if (File.Exists(Path.Combine(directory.FullName, SolutionFileName))) + { + return directory.FullName; + } + } + + throw new DirectoryNotFoundException( + $"No directory containing {SolutionFileName} found above {AppContext.BaseDirectory}."); + } + + /// + /// Returns the SKILL.md files under skills/, in ordinal order of their paths. The file name is + /// compared case-sensitively on every operating system. + /// + public static string[] EnumerateSkillFiles(string repositoryRoot) + { + return Directory + .EnumerateFiles(Path.Combine(repositoryRoot, SkillsDirectoryName), SkillFileName, + SearchOption.AllDirectories) + .Where(file => string.Equals(Path.GetFileName(file), SkillFileName, StringComparison.Ordinal)) + .Order(StringComparer.Ordinal) + .ToArray(); + } + + /// + /// Returns every text file under skills/ with its text (a leading byte order mark removed) and its lines, in + /// ordinal order of the paths. A file whose first 8000 bytes contain a NUL byte is binary and left out; every other + /// file must be UTF-8. + /// + /// A file that is not binary is not valid UTF-8. + public static (string File, string Text, string[] Lines)[] ReadTextFiles(string repositoryRoot) + { + return Directory + .EnumerateFiles(Path.Combine(repositoryRoot, SkillsDirectoryName), "*", SearchOption.AllDirectories) + .Order(StringComparer.Ordinal) + .Select(file => (File: file, Content: File.ReadAllBytes(file))) + .Where(x => !IsBinary(x.Content)) + .Select(x => (x.File, Text: Decode(x.File, x.Content))) + .Select(x => (x.File, x.Text, Lines: SplitLines(x.Text))) + .ToArray(); + } + + /// + /// Returns the lines of the specified text file; a leading byte order mark is removed. + /// + /// The file is not valid UTF-8. + public static string[] ReadLines(string file) + { + return SplitLines(Decode(file, File.ReadAllBytes(file))); + } + + private static bool IsBinary(byte[] content) + { + return content.AsSpan(0, Math.Min(content.Length, BinaryProbeLength)).Contains((byte)0); + } + + private static string Decode(string file, byte[] content) + { + try + { + return StrictUtf8.GetString(content).TrimStart(''); + } + catch (DecoderFallbackException ex) + { + throw new InvalidDataException($"The file '{file}' under skills/ is not valid UTF-8.", ex); + } + } + + /// + /// Splits the specified text into lines at CRLF, LF, and a lone CR. + /// + public static string[] SplitLines(string text) + { + return text.Split(["\r\n", "\n", "\r"], StringSplitOptions.None); + } +} diff --git a/tests/CreativeCoders.ShadeKit.Core.Tests/Skills/ShippedSkillsTests.cs b/tests/CreativeCoders.ShadeKit.Core.Tests/Skills/ShippedSkillsTests.cs new file mode 100644 index 0000000..e88b1d0 --- /dev/null +++ b/tests/CreativeCoders.ShadeKit.Core.Tests/Skills/ShippedSkillsTests.cs @@ -0,0 +1,212 @@ +using System.Text.RegularExpressions; +using AwesomeAssertions; +using CreativeCoders.ShadeKit.Tests.Shared; + +namespace CreativeCoders.ShadeKit.Core.Tests.Skills; + +public partial class ShippedSkillsTests +{ + private const string SkillFileName = ShippedSkillFiles.SkillFileName; + + [Fact] + [Trait("Requirement", "FP07-AC7")] + public void SkillFiles_ShippedSkills_ContainNoPathReferenceIntoDocsOrResearch() + { + // Arrange + var repositoryRoot = ShippedSkillFiles.FindRepositoryRoot(); + + // Act + var skillFiles = ShippedSkillFiles.EnumerateSkillFiles(repositoryRoot); + var violations = FindDocsOrResearchReferences(repositoryRoot); + + // Assert + skillFiles + .Should().NotBeEmpty("the repository ships its skills under skills/"); + + violations + .Should().BeEmpty("no shipped file under skills/ may reference a path under docs/ or research/"); + } + + [Fact] + [Trait("Requirement", "FP07-AC7")] + public void FindDocsOrResearchReferences_NestedSkillsWithReferences_ReportsFileAndLineOfEachReference() + { + // Arrange + using var root = new TempKitDirectory(); + root.WriteFile("See docs/specs/x.md.\nClean line.\nAlso research/notes.md", "skills", "a", SkillFileName); + root.WriteFile("Clean line.\n", "skills", "b", SkillFileName); + root.WriteFile("Text\n\nPath ../docs/plans/y.md", "skills", "group", "c", SkillFileName); + + // Act + var violations = FindDocsOrResearchReferences(root.RootPath); + + // Assert + violations + .Should().Equal( + $"{Path.Combine("skills", "a", SkillFileName)}:1: See docs/specs/x.md.", + $"{Path.Combine("skills", "a", SkillFileName)}:3: Also research/notes.md", + $"{Path.Combine("skills", "group", "c", SkillFileName)}:3: Path ../docs/plans/y.md"); + } + + [Fact] + [Trait("Requirement", "FP07-AC7")] + public void FindDocsOrResearchReferences_BundledFilesBesideSkillFiles_ReportsReferencesInEveryTextFile() + { + // Arrange + using var root = new TempKitDirectory(); + root.WriteFile("Clean line.\n", "skills", "a", SkillFileName); + root.WriteFile("Intro\r\nSee research/notes.md", "skills", "a", "references", "guide.md"); + root.WriteFile("{ \"path\": \"docs/x.md\" }", "skills", "a", "assets", "config.json"); + root.WriteFile("first\rdocs/y.txt", "skills", "b", "notes"); + root.WriteFile("docs/ at the skills root", "skills", "README.txt"); + + // Act + var violations = FindDocsOrResearchReferences(root.RootPath); + + // Assert + violations + .Should().Equal( + $"{Path.Combine("skills", "README.txt")}:1: docs/ at the skills root", + $"{Path.Combine("skills", "a", "assets", "config.json")}:1: {{ \"path\": \"docs/x.md\" }}", + $"{Path.Combine("skills", "a", "references", "guide.md")}:2: See research/notes.md", + $"{Path.Combine("skills", "b", "notes")}:2: docs/y.txt"); + } + + [Fact] + public void FindDocsOrResearchReferences_BinaryFileWithReference_IsNotScanned() + { + // Arrange + using var root = new TempKitDirectory(); + root.WriteFile("Clean line.\n", "skills", "a", SkillFileName); + root.WriteFileBytes([.. "docs/x.md"u8, 0, .. "research/y.md"u8], "skills", "a", "assets", "image.png"); + + // Act + var violations = FindDocsOrResearchReferences(root.RootPath); + + // Assert + violations + .Should().BeEmpty(); + } + + [Theory] + [InlineData(7999, false)] + [InlineData(8000, true)] + public void FindDocsOrResearchReferences_NulByteAtProbeBoundary_ScansOnlyFilesWithoutNulInFirst8000Bytes( + int nulIndex, bool reported) + { + // Arrange + using var root = new TempKitDirectory(); + var content = Enumerable.Repeat((byte)'x', 9000).ToArray(); + content[nulIndex] = 0; + "\ndocs/x.md"u8.CopyTo(content.AsSpan(8500)); + root.WriteFileBytes(content, "skills", "a", "asset.bin"); + + // Act + var violations = FindDocsOrResearchReferences(root.RootPath); + + // Assert + violations + .Should().HaveCount(reported ? 1 : 0); + } + + [Fact] + public void FindDocsOrResearchReferences_TextFileThatIsNotUtf8_ThrowsInvalidDataException() + { + // Arrange + using var root = new TempKitDirectory(); + root.WriteFileBytes([0x64, 0x6F, 0x63, 0xFC], "skills", "a", "latin1.txt"); + + // Act + var act = () => FindDocsOrResearchReferences(root.RootPath); + + // Assert + act + .Should().Throw() + .WithMessage($"*{Path.Combine("skills", "a", "latin1.txt")}*not valid UTF-8*"); + } + + [Fact] + public void FindDocsOrResearchReferences_LineWithSeveralReferences_ReportsLineOnce() + { + // Arrange + using var root = new TempKitDirectory(); + root.WriteFile("docs/a.md and research/b.md", "skills", "a", SkillFileName); + + // Act + var violations = FindDocsOrResearchReferences(root.RootPath); + + // Assert + violations + .Should().Equal($"{Path.Combine("skills", "a", SkillFileName)}:1: docs/a.md and research/b.md"); + } + + [Theory] + [InlineData("")] + [InlineData("See research/shade-kit-skills.md.")] + [InlineData("Read `docs/specs/x.md` first.")] + [InlineData("Path ../../docs/plans/x.md")] + [InlineData("./research/notes.md")] + [InlineData("docs/")] + [InlineData("[spec](docs/specs/x.md)")] + [InlineData("\"research/x.md\"")] + [InlineData("")] + [InlineData(@"docs\specs\x.md")] + [InlineData(@"..\..\research\notes.md")] + [InlineData("Docs/specs/x.md")] + [InlineData("RESEARCH/notes.md")] + [InlineData(".shadekit/research/x.md")] + [InlineData("https://example.com/docs/x")] + public void ContainsDocsOrResearchReference_LineWithDocsOrResearchPathSegment_ReturnsTrue(string line) + { + // Act + var result = ContainsDocsOrResearchReference(line); + + // Assert + result + .Should().BeTrue(); + } + + [Theory] + [InlineData("")] + [InlineData("Load `shade-kit-research` for the research step.")] + [InlineData("skills/shade-kit-research/SKILL.md")] + [InlineData("Write the docs and the research notes.")] + [InlineData("mydocs/readme.md")] + [InlineData("my_docs/readme.md")] + [InlineData(".docs/readme.md")] + [InlineData("researches.md")] + [InlineData("docs.md")] + [InlineData("research-notes/x.md")] + [InlineData("docsets/x.md")] + public void ContainsDocsOrResearchReference_LineWithoutDocsOrResearchPathSegment_ReturnsFalse(string line) + { + // Act + var result = ContainsDocsOrResearchReference(line); + + // Assert + result + .Should().BeFalse(); + } + + private static string[] FindDocsOrResearchReferences(string repositoryRoot) + { + return ShippedSkillFiles.ReadTextFiles(repositoryRoot) + .SelectMany(file => file.Lines + .Select((line, index) => (Line: line, Number: index + 1)) + .Where(x => ContainsDocsOrResearchReference(x.Line)) + .Select(x => $"{Path.GetRelativePath(repositoryRoot, file.File)}:{x.Number}: {x.Line}")) + .ToArray(); + } + + private static bool ContainsDocsOrResearchReference(string line) + { + return DocsOrResearchPathRegex().IsMatch(line); + } + + // A path segment "docs" or "research" in any letter case, followed by a slash or backslash. It must not be + // preceded by a name character, so that "shade-kit-research/", "mydocs/", or ".docs/" do not match. A nested + // segment (".shadekit/research/") matches on purpose: the guard errs on the side of flagging. + [GeneratedRegex(@"(?`."); + + // Act + var violations = FindKitVersionViolations(root.RootPath, DefaultEngineVersion); + + // Assert + violations + .Should().Equal($"{SkillPath("a")}:8: expected --expect 0.8.0, found --expect "); + } + + [Fact] + public void FindKitVersionViolations_LongBundledLineWithoutWhitespace_FinishesWithoutRegexTimeout() + { + // Arrange + using var root = new TempKitDirectory(); + WriteSkill(root, "0.8.0", "a", "Body"); + root.WriteFile(new string('a', 200_000) + " is the kit version of this skill", "skills", "a", "asset.svg"); + + // Act + var violations = FindKitVersionViolations(root.RootPath, DefaultEngineVersion); + + // Assert + violations + .Should().ContainSingle() + .Which.Should().StartWith($"{Path.Combine("skills", "a", "asset.svg")}:1: expected '0.8.0 is the kit"); + } + + [Fact] + public void FindKitVersionViolations_SkillWithOtherVersionAndOtherMajorMinor_ReportsBothForTheSkill() + { + // Arrange + using var root = new TempKitDirectory(); + WriteSkill(root, "0.8.0", "a", "Body"); + WriteSkill(root, "0.9.0", "b", "Body"); + + // Act + var violations = FindKitVersionViolations(root.RootPath, DefaultEngineVersion); + + // Assert + violations + .Should().Equal( + $"{SkillPath("b")}:5: expected metadata.version 0.8.0 (the kit version of {SkillPath("a")}), " + + "found 0.9.0", + $"{SkillPath("b")}:5: expected the major.minor 0.8 of the engine version 0.8.3, found 0.9.0"); + } + + [Fact] + public void FindKitVersionViolations_OutlierFirstInPathOrder_ReportsOnlyTheOutlier() + { + // Arrange + using var root = new TempKitDirectory(); + WriteSkill(root, "0.8.1", "a", "Body"); + WriteSkill(root, "0.8.0", "b", "Run `shade-kit version --json --expect 0.8.0`."); + WriteSkill(root, "0.8.0", "c", "Body"); + + // Act + var violations = FindKitVersionViolations(root.RootPath, DefaultEngineVersion); + + // Assert + violations + .Should().Equal( + $"{SkillPath("a")}:5: expected metadata.version 0.8.0 (the kit version of {SkillPath("b")}), " + + "found 0.8.1"); + } + + [Fact] + public void FindKitVersionViolations_MoreFrequentVersionWithOtherMajorMinor_IsTheKitVersion() + { + // Arrange + using var root = new TempKitDirectory(); + WriteSkill(root, "0.8.0", "a", "Body"); + WriteSkill(root, "0.9.0", "b", "Body"); + WriteSkill(root, "0.9.0", "c", "Body"); + + // Act + var violations = FindKitVersionViolations(root.RootPath, DefaultEngineVersion); + + // Assert + violations + .Should().Equal( + $"{SkillPath("a")}:5: expected metadata.version 0.9.0 (the kit version of {SkillPath("b")}), " + + "found 0.8.0", + $"{SkillPath("b")}:5: expected the major.minor 0.8 of the engine version 0.8.3, found 0.9.0", + $"{SkillPath("c")}:5: expected the major.minor 0.8 of the engine version 0.8.3, found 0.9.0"); + } + + [Fact] + public void FindKitVersionViolations_TieWithOneVersionMatchingEngineMajorMinor_TakesThatVersion() + { + // Arrange + using var root = new TempKitDirectory(); + WriteSkill(root, "0.9.0", "a", "Body"); + WriteSkill(root, "0.9.0", "b", "Body"); + WriteSkill(root, "0.8.0", "c", "Run `shade-kit version --json --expect 0.8.0`."); + WriteSkill(root, "0.8.0", "d", "Body"); + + // Act + var violations = FindKitVersionViolations(root.RootPath, DefaultEngineVersion); + + // Assert + violations + .Should().Equal( + $"{SkillPath("a")}:5: expected metadata.version 0.8.0 (the kit version of {SkillPath("c")}), " + + "found 0.9.0", + $"{SkillPath("a")}:5: expected the major.minor 0.8 of the engine version 0.8.3, found 0.9.0", + $"{SkillPath("b")}:5: expected metadata.version 0.8.0 (the kit version of {SkillPath("c")}), " + + "found 0.9.0", + $"{SkillPath("b")}:5: expected the major.minor 0.8 of the engine version 0.8.3, found 0.9.0"); + } + + [Fact] + public void FindKitVersionViolations_TieOfInterleavedVersionsWithSameMajorMinor_TakesTheVersionOfTheFirstSkill() + { + // Arrange + using var root = new TempKitDirectory(); + WriteSkill(root, "0.8.1", "a", "Body"); + WriteSkill(root, "0.8.0", "b", "Body"); + WriteSkill(root, "0.8.1", "c", "Body"); + WriteSkill(root, "0.8.0", "d", "Body"); + + // Act + var violations = FindKitVersionViolations(root.RootPath, DefaultEngineVersion); + + // Assert + violations + .Should().Equal( + $"{SkillPath("b")}:5: expected metadata.version 0.8.1 (the kit version of {SkillPath("a")}), " + + "found 0.8.0", + $"{SkillPath("d")}:5: expected metadata.version 0.8.1 (the kit version of {SkillPath("a")}), " + + "found 0.8.0"); + } + + [Fact] + public void FindKitVersionViolations_TieOfSingleSkillsWithEngineMatchLastInPathOrder_TakesTheMatchingVersion() + { + // Arrange + using var root = new TempKitDirectory(); + WriteSkill(root, "0.9.0", "a", "Body"); + WriteSkill(root, "0.7.0", "b", "Body"); + WriteSkill(root, "0.8.0", "c", "Body"); + + // Act + var violations = FindKitVersionViolations(root.RootPath, SemanticVersion.Parse("0.8.3-feature.2")); + + // Assert + violations + .Where(x => x.Contains(": expected metadata.version ", StringComparison.Ordinal)) + .Should().Equal( + $"{SkillPath("a")}:5: expected metadata.version 0.8.0 (the kit version of {SkillPath("c")}), " + + "found 0.9.0", + $"{SkillPath("b")}:5: expected metadata.version 0.8.0 (the kit version of {SkillPath("c")}), " + + "found 0.7.0"); + } + + [Fact] + public void FindKitVersionViolations_SeveralInvalidVersionsAndOneValid_TakesTheValidVersion() + { + // Arrange + using var root = new TempKitDirectory(); + WriteSkill(root, "0.8", "a", "Body"); + WriteSkill(root, "0.8", "b", "Body"); + WriteSkill(root, "0.8.0", "c", "Run `shade-kit version --json --expect 0.8.0`."); + + // Act + var violations = FindKitVersionViolations(root.RootPath, DefaultEngineVersion); + + // Assert + violations + .Should().Equal( + $"{SkillPath("a")}:5: expected metadata.version as a plain x.y.z version, found '0.8'", + $"{SkillPath("b")}:5: expected metadata.version as a plain x.y.z version, found '0.8'"); + } + + [Theory] + [InlineData("0.8.1", "0.8.0")] + [InlineData("0.9.0", "0.7.0")] + public void FindKitVersionViolations_TieWithEqualEngineMatch_TakesTheVersionOfTheFirstSkillInPathOrder( + string firstVersion, string secondVersion) + { + // Arrange + using var root = new TempKitDirectory(); + WriteSkill(root, firstVersion, "a", "Body"); + WriteSkill(root, secondVersion, "b", "Body"); + + // Act + var violations = FindKitVersionViolations(root.RootPath, DefaultEngineVersion); + + // Assert + violations + .Where(x => x.Contains(": expected metadata.version ", StringComparison.Ordinal)) + .Should().Equal( + $"{SkillPath("b")}:5: expected metadata.version {firstVersion} " + + $"(the kit version of {SkillPath("a")}), found {secondVersion}"); + } + + [Theory] + [InlineData("0.7.0")] + [InlineData("0.9.0")] + [InlineData("1.8.0")] + public void FindKitVersionViolations_KitVersionWithOtherMajorMinorThanEngine_ReportsEverySkill( + string kitVersion) + { + // Arrange + using var root = new TempKitDirectory(); + WriteSkill(root, kitVersion, "a", "Body"); + WriteSkill(root, kitVersion, "b", "Body"); + + // Act + var violations = FindKitVersionViolations(root.RootPath, SemanticVersion.Parse("0.8.3-feature.2")); + + // Assert + violations + .Should().Equal( + $"{SkillPath("a")}:5: expected the major.minor 0.8 of the engine version 0.8.3-feature.2, " + + $"found {kitVersion}", + $"{SkillPath("b")}:5: expected the major.minor 0.8 of the engine version 0.8.3-feature.2, " + + $"found {kitVersion}"); + } + + [Theory] + [InlineData("0.8.7")] + [InlineData("0.8.0")] + public void FindKitVersionViolations_KitPatchDiffersFromEnginePatch_ReturnsNoViolation(string kitVersion) + { + // Arrange + using var root = new TempKitDirectory(); + WriteSkill(root, kitVersion, "a", "Body"); + + // Act + var violations = FindKitVersionViolations(root.RootPath, DefaultEngineVersion); + + // Assert + violations + .Should().BeEmpty(); + } + + [Theory] + [InlineData("0.8.0-beta.1")] + [InlineData("0.8.0+build.5")] + [InlineData("\"0.8.0\"")] + [InlineData("'0.8.0'")] + [InlineData("0.8")] + [InlineData("v0.8.0")] + [InlineData("08.0.0")] + [InlineData("0.8.0 # kit version")] + [InlineData("")] + public void FindKitVersionViolations_VersionThatIsNotPlainSemVer_ReportsFileLineAndFoundValue( + string version) + { + // Arrange + using var root = new TempKitDirectory(); + WriteSkill(root, version, "a", "Body"); + + // Act + var violations = FindKitVersionViolations(root.RootPath, DefaultEngineVersion); + + // Assert + violations + .Should().Equal( + $"{SkillPath("a")}:5: expected metadata.version as a plain x.y.z version, found '{version}'"); + } + + [Fact] + public void FindKitVersionViolations_InvalidVersionInFirstSkill_TakesKitVersionFromNextValidSkill() + { + // Arrange + using var root = new TempKitDirectory(); + WriteSkill(root, "0.8", "a", "Run `shade-kit version --json --expect 0.8.0`."); + WriteSkill(root, "0.8.0", "b", "Body"); + + // Act + var violations = FindKitVersionViolations(root.RootPath, DefaultEngineVersion); + + // Assert + violations + .Should().Equal($"{SkillPath("a")}:5: expected metadata.version as a plain x.y.z version, found '0.8'"); + } + + [Theory] + [InlineData("")] + [InlineData("---")] + [InlineData(" ---\nname: a\n---\nBody")] + [InlineData("# shade-kit-a\n\nBody")] + [InlineData("\n---\nname: a\n---\nBody")] + [InlineData("---\nname: a\nmetadata:\n version: 0.8.0\n")] + public void FindKitVersionViolations_SkillWithoutFrontmatter_ReportsMissingFrontmatter(string content) + { + // Arrange + using var root = new TempKitDirectory(); + root.WriteFile(content, "skills", "a", SkillFileName); + + // Act + var violations = FindKitVersionViolations(root.RootPath, DefaultEngineVersion); + + // Assert + violations + .Should().Equal( + $"{SkillPath("a")}:1: expected a frontmatter between a first line '---' and a second line '---', " + + "found none"); + } + + [Theory] + [InlineData("---\nname: a\n---\nmetadata:\n version: 0.8.0\n", 3)] + [InlineData("---\nname: a\nversion: 0.8.0\n---\nBody", 4)] + [InlineData("---\nname: a\nmetadata:\n author: x\nversion: 0.8.0\n---\nBody", 6)] + [InlineData("---\nname: a\nmetadata:\n other:\n version: 0.8.0\n---\nBody", 6)] + [InlineData("---\nname: a\nmetadata: {version: 0.8.0}\n---\nBody", 4)] + [InlineData("---\nname: a\nmetadata:\n version:0.8.0\n---\nBody", 5)] + [InlineData("---\nname: a\nmetadata:\n---\nBody", 4)] + [InlineData("---\n---\nBody", 2)] + [InlineData("--- \nname: a\n---\t\nBody", 3)] + public void FindKitVersionViolations_FrontmatterWithoutMetadataVersion_ReportsClosingDelimiterLine( + string content, int closingLine) + { + // Arrange + using var root = new TempKitDirectory(); + root.WriteFile(content, "skills", "a", SkillFileName); + + // Act + var violations = FindKitVersionViolations(root.RootPath, DefaultEngineVersion); + + // Assert + violations + .Should().Equal( + $"{SkillPath("a")}:{closingLine}: expected metadata.version in the frontmatter, found none"); + } + + [Fact] + public void FindKitVersionViolations_FrontmatterWithBomCrLfAndOtherMetadata_ReadsVersion() + { + // Arrange + using var root = new TempKitDirectory(); + root.WriteFileBytes( + [ + 0xEF, 0xBB, 0xBF, + .. "---\r\nname: a\r\nmetadata:\r\n author: x\r\n\r\n version: 0.8.0 \r\n---\r\nBody\r\n"u8 + ], + "skills", "a", SkillFileName); + + // Act + var violations = FindKitVersionViolations(root.RootPath, DefaultEngineVersion); + + // Assert + violations + .Should().BeEmpty(); + } + + [Fact] + public void FindKitVersionViolations_VersionOutsideFrontmatter_IsNotTakenAsKitVersion() + { + // Arrange + using var root = new TempKitDirectory(); + root.WriteFile("---\nname: a\n---\nmetadata:\n version: 0.8.0\n---\n", "skills", "a", SkillFileName); + + // Act + var violations = FindKitVersionViolations(root.RootPath, DefaultEngineVersion); + + // Assert + violations + .Should().Equal($"{SkillPath("a")}:3: expected metadata.version in the frontmatter, found none"); + } + + [Fact] + public void FindKitVersionViolations_SkillFileThatIsNotUtf8_ThrowsInvalidDataException() + { + // Arrange + using var root = new TempKitDirectory(); + root.WriteFileBytes([.. "---\nname: a\n---\n"u8, 0xFC], "skills", "a", SkillFileName); + + // Act + var act = () => FindKitVersionViolations(root.RootPath, DefaultEngineVersion); + + // Assert + act + .Should().Throw() + .WithMessage($"*{SkillPath("a")}*not valid UTF-8*"); + } + + [Fact] + public void FindKitVersionViolations_BundledFileWithBom_ReportsTheVersionWithoutTheBom() + { + // Arrange + using var root = new TempKitDirectory(); + WriteSkill(root, "0.8.0", "a", "Body"); + root.WriteFileBytes([0xEF, 0xBB, 0xBF, .. "0.7.0 is the kit version of this skill"u8], + "skills", "a", "notes.md"); + + // Act + var violations = FindKitVersionViolations(root.RootPath, DefaultEngineVersion); + + // Assert + violations + .Should().Equal( + $"{Path.Combine("skills", "a", "notes.md")}:1: expected '0.8.0 is the kit version of this skill', " + + "found '0.7.0 is the kit version of this skill'"); + } + + [Fact] + public void FindKitVersionViolations_LowercaseSkillFileName_IsNotASkillFile() + { + // Arrange + using var root = new TempKitDirectory(); + root.WriteFile("---\nname: a\nmetadata:\n version: 0.8.0\n---\n", "skills", "a", "skill.md"); + + // Act + var violations = FindKitVersionViolations(root.RootPath, DefaultEngineVersion); + + // Assert + violations + .Should().Equal($"skills: expected at least one {SkillFileName}, found none"); + } + + [Fact] + public void FindKitVersionViolations_NoSkillFiles_ReportsMissingSkills() + { + // Arrange + using var root = new TempKitDirectory(); + root.WriteFile("Run `shade-kit version --json --expect 0.7.0`.", "skills", "a", "notes.md"); + + // Act + var violations = FindKitVersionViolations(root.RootPath, DefaultEngineVersion); + + // Assert + violations + .Should().Equal($"skills: expected at least one {SkillFileName}, found none"); + } + + [Fact] + public void FindKitVersionViolations_NoValidKitVersion_ReportsOnlyTheInvalidVersions() + { + // Arrange + using var root = new TempKitDirectory(); + WriteSkill(root, "0.8.0-beta.1", "a", "Run `shade-kit version --json --expect 0.7.0`."); + + // Act + var violations = FindKitVersionViolations(root.RootPath, DefaultEngineVersion); + + // Assert + violations + .Should().Equal( + $"{SkillPath("a")}:5: expected metadata.version as a plain x.y.z version, found '0.8.0-beta.1'"); + } + + private static void WriteSkill(TempKitDirectory root, string version, string name, string body) + { + root.WriteFile( + $"---\nname: shade-kit-{name}\ndescription: Test skill {name}.\nmetadata:\n version: {version}\n---\n\n" + + $"{body}\n", + "skills", name, SkillFileName); + } + + private static string SkillPath(string name) + { + return Path.Combine("skills", name, SkillFileName); + } + + /// + /// Checks the kit version of the skills under skills/: every SKILL.md has a frontmatter + /// metadata.version as a plain x.y.z version; all skills carry the same value (the kit version, + /// chosen by ); its major.minor is the major.minor of the engine; every + /// --expect <v> and every "<v> is the kit version of this skill" in any text file under + /// skills/ names the kit version. + /// + /// One line per violation: the path relative to the repository, the line, and expected vs. found. + private static string[] FindKitVersionViolations(string repositoryRoot, SemanticVersion engineVersion) + { + var skills = ShippedSkillFiles.EnumerateSkillFiles(repositoryRoot) + .Select(file => ReadFrontmatterVersion(Path.GetRelativePath(repositoryRoot, file), + ShippedSkillFiles.ReadLines(file))) + .ToArray(); + + if (skills.Length == 0) + { + return [$"{ShippedSkillFiles.SkillsDirectoryName}: expected at least one {SkillFileName}, found none"]; + } + + var violations = new List(); + var kitSkill = SelectKitSkill(skills, engineVersion); + + foreach (var skill in skills) + { + if (skill.Version is null) + { + violations.Add($"{skill.File}:{skill.Line}: {skill.Error}"); + continue; + } + + if (skill.Version != kitSkill?.Version) + { + violations.Add($"{skill.File}:{skill.Line}: expected metadata.version {kitSkill?.Version} " + + $"(the kit version of {kitSkill?.File}), found {skill.Version}"); + } + + if (skill.Version.Major != engineVersion.Major || skill.Version.Minor != engineVersion.Minor) + { + violations.Add($"{skill.File}:{skill.Line}: expected the major.minor " + + $"{engineVersion.Major}.{engineVersion.Minor} of the engine version {engineVersion}, " + + $"found {skill.Version}"); + } + } + + if (kitSkill?.Version is not null) + { + violations.AddRange(FindHandshakeViolations(repositoryRoot, kitSkill.Version.ToString())); + } + + return violations.ToArray(); + } + + /// + /// Selects the skill whose version is the kit version, so that a single skill with another version is the one + /// that is reported. + /// + /// + /// The kit version is the most frequent valid version. On a tie, a version with the major.minor of the engine wins, + /// then the version of the skill that comes first in ordinal path order. + /// + /// + /// The first skill in ordinal path order that carries the kit version, or if no skill has a + /// valid version. + /// + private static SkillVersion? SelectKitSkill(SkillVersion[] skills, SemanticVersion engineVersion) + { + // GroupBy keeps the groups in the order of their first skill and the skills of a group in path order, and the + // sort is stable, so the remaining ties keep the path order. + return skills + .Where(x => x.Version is not null) + .GroupBy(x => x.Version!) + .OrderByDescending(group => group.Count()) + .ThenByDescending(group => + group.Key.Major == engineVersion.Major && group.Key.Minor == engineVersion.Minor) + .Select(group => group.First()) + .FirstOrDefault(); + } + + // The texts are matched as a whole, so that a handshake wrapped across lines is found too; the line of a violation + // is the line where the match starts. + private static IEnumerable FindHandshakeViolations(string repositoryRoot, string kitVersion) + { + var expectedSentence = $"{kitVersion} is the kit version of this skill"; + + return ShippedSkillFiles.ReadTextFiles(repositoryRoot) + .SelectMany(file => + { + var path = Path.GetRelativePath(repositoryRoot, file.File); + + return ExpectOptionRegex().Matches(file.Text) + .Select(match => (match.Index, Version: match.Groups["version"].Value.TrimEnd('.', ':'), + Found: (string?)null)) + .Concat(KitVersionSentenceRegex().Matches(file.Text) + .Select(match => (match.Index, Version: match.Groups["version"].Value, + Found: (string?)match.Value))) + .Where(x => x.Version != kitVersion) + .OrderBy(x => x.Index) + .Select(x => + { + var location = $"{path}:{ShippedSkillFiles.SplitLines(file.Text[..x.Index]).Length}"; + + return x.Found is null + ? $"{location}: expected --expect {kitVersion}, found --expect {x.Version}" + : $"{location}: expected '{expectedSentence}', found '{x.Found}'"; + }); + }); + } + + private static SkillVersion ReadFrontmatterVersion(string file, string[] lines) + { + var closingIndex = lines.Length > 0 && lines[0].TrimEnd() == FrontmatterDelimiter + ? Array.FindIndex(lines, 1, line => line.TrimEnd() == FrontmatterDelimiter) + : -1; + + if (closingIndex < 0) + { + return new SkillVersion(file, 1, null, + $"expected a frontmatter between a first line '{FrontmatterDelimiter}' and a second line " + + $"'{FrontmatterDelimiter}', found none"); + } + + var versionIndex = FindMetadataVersionIndex(lines, closingIndex); + + if (versionIndex >= 0) + { + var value = MetadataVersionRegex().Match(lines[versionIndex]).Groups["value"].Value; + + return IsPlainVersion(value, out var version) + ? new SkillVersion(file, versionIndex + 1, version, null) + : new SkillVersion(file, versionIndex + 1, null, + $"expected metadata.version as a plain x.y.z version, found '{value}'"); + } + + return new SkillVersion(file, closingIndex + 1, null, + "expected metadata.version in the frontmatter, found none"); + } + + // The index of the line " version: ..." among the entries of "metadata:" in the frontmatter (lines 1 to + // closingIndex - 1), or -1. The entries are the indented or blank lines that follow "metadata:". + private static int FindMetadataVersionIndex(string[] lines, int closingIndex) + { + var metadataIndex = Array.FindIndex(lines, 1, closingIndex - 1, line => MetadataKeyRegex().IsMatch(line)); + + if (metadataIndex < 0) + { + return -1; + } + + for (var index = metadataIndex + 1; index < closingIndex; index++) + { + var line = lines[index]; + + if (line.Length > 0 && !char.IsWhiteSpace(line[0])) + { + return -1; + } + + if (MetadataVersionRegex().IsMatch(line)) + { + return index; + } + } + + return -1; + } + + private static bool IsPlainVersion(string value, out SemanticVersion? version) + { + return SemanticVersion.TryParse(value, out version) && !version.IsPrerelease && version.ToString() == value; + } + + private sealed record SkillVersion(string File, int Line, SemanticVersion? Version, string? Error); + + [GeneratedRegex(@"^metadata:[ \t]*$", RegexOptions.CultureInvariant, matchTimeoutMilliseconds: 1000)] + private static partial Regex MetadataKeyRegex(); + + // A direct child "version:" of the metadata map: exactly two spaces, the indentation the skills use. YAML needs a + // space after the colon ("version:0.8.0" is no key), so the value follows only after a blank. + [GeneratedRegex(@"^ version:(?:[ \t]+(?.*?))?[ \t]*$", RegexOptions.CultureInvariant, + matchTimeoutMilliseconds: 1000)] + private static partial Regex MetadataVersionRegex(); + + // The value after "--expect" (a blank, a line break, or "="; optionally quoted); a trailing "." or ":" of the + // sentence is cut off in code. + [GeneratedRegex(@"--expect(?:\s+|=)[""'`]?(?[^\s`'"";,)]+)", RegexOptions.CultureInvariant, + matchTimeoutMilliseconds: 1000)] + private static partial Regex ExpectOptionRegex(); + + // The version token before the sentence, which may be wrapped across lines. The lookbehind starts a match only at + // the start of a token and the atomic group gives up a token without backtracking, so a long line without + // whitespace takes linear time. Quotes, parentheses, and Markdown emphasis are not part of the token. + [GeneratedRegex( + @"(?(?>[^\s`'""(*_]+))[*_`'""]*\s+is\s+the\s+kit\s+version\s+of\s+this\s+skill", + RegexOptions.CultureInvariant, matchTimeoutMilliseconds: 1000)] + private static partial Regex KitVersionSentenceRegex(); +}