diff --git a/CHANGELOG.md b/CHANGELOG.md index 6780d89..1bcaa3f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,8 @@ All notable changes to cloudpin are listed here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow [Semantic Versioning](https://semver.org/). -Versions 0.1.0 to 0.4.2 (2026-10-08 to 2026-10-10) are in [docs/changelog-0.x.md](docs/changelog-0.x.md). +Versions 1.0.0 to 1.1.2 are in [docs/changelog-1.0-1.1.md](docs/changelog-1.0-1.1.md), and 0.1.0 to 0.4.2 in +[docs/changelog-0.x.md](docs/changelog-0.x.md). ## [Unreleased] @@ -20,10 +21,10 @@ Versions 0.1.0 to 0.4.2 (2026-10-08 to 2026-10-10) are in [docs/changelog-0.x.md - winget manifests for `paureis.cloudpin` (#96) in `packaging/winget/`: a portable zip installing `cloudpin.exe` as the `cloudpin` command. `node scripts/bump-installers.mjs X.Y.Z --winget ` renders them for a release, after checking the exe zip against `SHA256SUMS`, and `docs/winget.md` lists the maintainer's steps to submit them. -- MCP: a third read-only tool, `cloudpin_doctor` (#112): the same report as `cloudpin doctor --json` (cloudpin on - PATH, shell wrappers, agent hooks, on Windows the PowerShell execution policy, the pin file and each CLI's account, - each with its fix), so an agent can tell you why cloudpin isn't guarding. Account IDs are shortened, and it skips - the identity cache check, which writes a file. +- MCP: two more read-only tools (#112). `cloudpin_doctor`: `cloudpin doctor --json`'s report, so an agent can tell you + why cloudpin isn't guarding (IDs shortened; it skips the cache check, which writes a file). `cloudpin_switch_plan`: the + plan `cloudpin switch --json` prints without `--yes`, for you to run, pinned IDs in full; nothing is run. The plugin's + skill names both. - Docs: [Guard a Claude Agent SDK app](docs/agent-sdk.md) (#142). An app that loads project settings needs no code; for one that loads none, there is a Python and a TypeScript `PreToolUse` callback that denies on every error. - `cloudpin switch [--yes] [--json] [--only ]` (#14) switches each pinned CLI to its pinned account. It shows a @@ -44,6 +45,8 @@ Versions 0.1.0 to 0.4.2 (2026-10-08 to 2026-10-10) are in [docs/changelog-0.x.md ### Security +- An agent's `cloudpin exec -- bash -c 'gh ...'` or `cloudpin exec -- npx gh ...` was read as an unguarded `bash` or `npx`, + so it could run on the wrong account. What `cloudpin exec` starts is now read as a call of its own (#14). - `cloudpin explain` (text and `--json`) and the MCP `cloudpin_check` tool no longer repeat a token or password from the command line (#134): `--token`, kubectl's `--token` and `--password`, helm's `--kube-token` and the other credential flags are masked, as in cloudpin's own block messages, also inside `cmd /c`, `powershell -Command` and @@ -211,64 +214,3 @@ Wrangler account checks. one (#125). A group's value also no longer passes for the command: `vercel -dT whoami deploy` isn't exempt. - Vercel: `--scope` beats `--team` whatever their order, and with neither, the `scope` in `vercel.json` (or the `-A` file) picks the team, as in Vercel; a local config that can't be read stops the command (#127). - -## [1.1.2] - 2026-10-19 - -Completes the 1.1.1 security fix for Windows. Please upgrade. - -### Security - -- Windows: CLIs installed by npm (vercel, wrangler, ...) no longer start a `node` found in the current folder. npm's - `.cmd` shims run `node` by name when no node.exe sits beside them, and Windows looked for it in the current folder - first. cloudpin now tells Windows not to search the current folder for any process it starts, including the command - `cloudpin exec` runs, as PowerShell and Git Bash already do - ([GHSA-3cf7-5v5w-q5vr](https://github.com/paureis/cloudpin/security/advisories/GHSA-3cf7-5v5w-q5vr)). - -## [1.1.1] - 2026-10-18 - -A security fix for Windows. Please upgrade. - -### Security - -- Windows: cloudpin now runs each CLI it asks about (az, gh, vercel, aws, gcloud, kubectl, helm, supabase, - wrangler), and the command `cloudpin exec` runs, by its full path from PATH, skipping empty and relative PATH - entries. Before, Windows' own lookup checked the current folder first, so a file named like one of those CLIs - inside a repository could run in its place when cloudpin checked a command there - ([GHSA-3cf7-5v5w-q5vr](https://github.com/paureis/cloudpin/security/advisories/GHSA-3cf7-5v5w-q5vr)). - -## [1.1.0] - 2026-10-16 - -Claude Code gets a one-step plugin, and any MCP agent can ask cloudpin before it acts. - -### Added - -- A Claude Code plugin (#15): `claude plugin install cloudpin --marketplace paureis/cloudpin` installs the hook, a - read-only MCP server and a skill that tells the agent to check first and stop on a block. With the plugin enabled, - `install-hook claude` declines and `doctor` warns if a settings hook would also run. -- `cloudpin mcp` (#15): a read-only MCP server (stdio) with `cloudpin_status` and `cloudpin_check`, for any agent that - supports MCP. No new dependency. - -## [1.0.0] - 2026-10-15 - -The first stable release: the `.cloudpin.yml` format is stable from here on (later versions only add sections and -keys), and every agent hook except Gemini CLI's is tested inside the real agent. - -### Fixed - -- Variables an agent sets earlier in its command line now count (#86). `export AWS_PROFILE=other; aws ...` and - PowerShell `$env:AWS_PROFILE = 'other'; aws ...` were checked against the default account and ran on another; and - `GH_TOKEN=$(cat other.token) gh ...` read the token as empty. cloudpin now follows `export`, `unset` and `$env:` - through the line, and stops a command whose account depends on a value only known when it runs, saying why. Found - in the threat-model review. -- Cursor: a command on your Cursor allowlist runs again when the account matches (#2). cloudpin answered `ask`, which - stopped even allowlisted commands; it now answers `allow`, which Cursor treats exactly like having no hook (measured - in Cursor CLI 2026.10.01: commands not on the allowlist still need your approval). Wrong accounts are still blocked. - -### Added - -- Antigravity hooks (#80): `cloudpin install-hook antigravity` guards Antigravity CLI, the IDE and Antigravity 2.0 - (`.agents/hooks.json`, or `~/.gemini/config/hooks.json` with `--user`). Google replaced Gemini CLI with Antigravity - CLI for free and consumer accounts on 2026-06-18. The hook checks `run_command` and text typed into a running - terminal; it asks rather than allows when nothing is wrong, so Antigravity's own approvals still apply. -- The Copilot CLI and Antigravity CLI hooks are tested inside the real agents (#3): a wrong pin blocks the command, a - right one lets it run, and Antigravity's own approval still applies to commands you haven't allowed. diff --git a/README.md b/README.md index 937da1d..6759886 100644 --- a/README.md +++ b/README.md @@ -332,7 +332,7 @@ older than 2.1.47. ### Claude Code plugin -One install gives Claude Code the hook, three read-only tools it can call before acting, and a short skill telling it to +One install gives Claude Code the hook, four read-only tools it can call before acting, and a short skill telling it to check first and to stop and ask you when cloudpin blocks a command. cloudpin itself must be installed first: ```sh @@ -345,14 +345,14 @@ The plugin replaces `cloudpin install-hook claude`: with the plugin enabled, `in ### MCP server -`cloudpin mcp` is an MCP server (stdio) for any agent; the Claude Code plugin starts it for you. Its three tools, -`cloudpin_status`, `cloudpin_check` and `cloudpin_doctor`, report the accounts in use, if a command would be allowed, -and why cloudpin may not be guarding. None runs, switches or changes anything: an agent that could switch accounts -could switch to the wrong one. -[docs/mcp.md](docs/mcp.md) adds it to Codex, Cursor, VS Code and more. It gives advice, not enforcement: where the +`cloudpin mcp` is an MCP server (stdio) for any agent; the Claude Code plugin starts it. Its four tools, +`cloudpin_status`, `cloudpin_check`, `cloudpin_doctor` and `cloudpin_switch_plan`, report the accounts in use, if a +command would be allowed, why cloudpin may not guard, and what you'd run to switch. None runs or changes +anything: an agent that could switch accounts could switch to the wrong one. +[docs/mcp.md](docs/mcp.md) adds it to Codex, Cursor, VS Code and more. It is advice, not enforcement: where the agent has a hook, install that too. -Building your own agent with the Claude Agent SDK? [docs/agent-sdk.md](docs/agent-sdk.md) shows how to guard it. +On the Claude Agent SDK? [docs/agent-sdk.md](docs/agent-sdk.md) shows how to guard it. ## Configuration diff --git a/ROADMAP.md b/ROADMAP.md index 045934e..346f0b1 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -30,9 +30,8 @@ issues it ships. Open an [issue](https://github.com/paureis/cloudpin/issues) to - **Threat model** ([#84](https://github.com/paureis/cloudpin/issues/84)): done. What cloudpin protects against and what it doesn't, in THREAT_MODEL.md. - **MCP: `cloudpin_switch_plan` and `cloudpin_doctor` tools** ([#112](https://github.com/paureis/cloudpin/issues/112)): - two more read-only tools: the commands you would run to move each CLI to the pinned account (from `cloudpin + done. Two more read-only tools: the commands you would run to move each CLI to the pinned account (from `cloudpin switch`, nothing run), and `cloudpin doctor`'s report, so an agent can say why the hook isn't guarding. - `cloudpin_doctor` is done; `cloudpin_switch_plan` follows `cloudpin switch` (#14). - **Write-up** ([#114](https://github.com/paureis/cloudpin/issues/114)): why AI agents need an account guardrail, and how cloudpin does it, with numbers from the test suite. - **Short flags joined with `=`** ([#118](https://github.com/paureis/cloudpin/issues/118)): read `-e=production` diff --git a/SECURITY.md b/SECURITY.md index 6d12697..3474105 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -34,8 +34,8 @@ What cloudpin protects against, what it trusts and what is out of scope: [THREAT For Vercel it checks whether a login file exists, without reading it. - It stores successful identity answers for up to five minutes in a cache file in your user cache folder. Keys are salted hashes, so tokens and command arguments are never written in clear. -- `cloudpin mcp`, the MCP server for agents, is read-only: its three tools report status, what cloudpin would decide and why it may not be guarding - for a command; they never run that command, log in, switch accounts or write anything. +- `cloudpin mcp`, the MCP server for agents, is read-only: its four tools report status, what cloudpin would decide for a command, why it may not be + guarding and what a person would run to switch; they never run any of those commands, log in, switch accounts or write anything. - It has no telemetry and sends nothing about you or your accounts. Its one request of its own asks registry.npmjs.org for the latest cloudpin version (public data; the request names only the package), at most once a day, and only from cloudpin's own commands run in a terminal: never from the shell wrappers, `cloudpin exec` or the diff --git a/THREAT_MODEL.md b/THREAT_MODEL.md index cd1e055..7fbb482 100644 --- a/THREAT_MODEL.md +++ b/THREAT_MODEL.md @@ -88,6 +88,10 @@ These are real limits, stated so nobody relies on cloudpin for them: - **Which resource inside the account.** cloudpin checks the identity a command acts as and the account or project it lands in, not which repository, Vercel project, region or resource group it targets. `gh repo delete other/repo` passes if you are logged in as the pinned user. (A pinned Kubernetes namespace is the exception.) +- **An agent that runs a CLI's own switch command.** `gh auth switch` or `az account set` is exempt, so a person is never + locked out of fixing a mismatch, and that holds for an agent too. `cloudpin switch` asks; those don't. +- **A name Cursor's hook filter can't see.** Cursor runs the hook only when its text matcher finds a guarded name on the + line, so `"cloud"pin` or `-EncodedCommand ` never reach cloudpin there. Other agents have no such filter. - **A command cloudpin doesn't guard.** Only the CLIs above are checked. A cloud SDK called from a program, `curl` to a cloud API, a Terraform run, or an agent's MCP tools for a cloud provider (which never go through the shell hook) act on whatever credentials they find. diff --git a/docs/agent-sdk.md b/docs/agent-sdk.md index 1acc0ee..fd3c23b 100644 --- a/docs/agent-sdk.md +++ b/docs/agent-sdk.md @@ -185,8 +185,9 @@ your `can_use_tool` (`canUseTool`) callback. According to the SDK's types, an ap ## The MCP server: advice, not enforcement -`cloudpin mcp` gives the agent three read-only tools: which account each CLI uses here, whether cloudpin would allow -a command, and why cloudpin may not be guarding (see [cloudpin's MCP server](mcp.md)). An SDK app adds it like any stdio server: +`cloudpin mcp` gives the agent four read-only tools: which account each CLI uses here, whether cloudpin would allow +a command, why cloudpin may not be guarding, and what a person would run to switch (see +[cloudpin's MCP server](mcp.md)). An SDK app adds it like any stdio server: ```python options = ClaudeAgentOptions(mcp_servers={"cloudpin": {"type": "stdio", "command": "cloudpin", "args": ["mcp"]}}) diff --git a/docs/changelog-1.0-1.1.md b/docs/changelog-1.0-1.1.md new file mode 100644 index 0000000..576f7ce --- /dev/null +++ b/docs/changelog-1.0-1.1.md @@ -0,0 +1,65 @@ +# Changelog: 1.0 and 1.1 + +cloudpin's 1.0 and 1.1 releases, moved here from [CHANGELOG.md](../CHANGELOG.md) on 2026-11-04 to keep that file +short. Newer versions are listed there, and older ones in [changelog-0.x.md](changelog-0.x.md). + +## [1.1.2] - 2026-10-19 + +Completes the 1.1.1 security fix for Windows. Please upgrade. + +### Security + +- Windows: CLIs installed by npm (vercel, wrangler, ...) no longer start a `node` found in the current folder. npm's + `.cmd` shims run `node` by name when no node.exe sits beside them, and Windows looked for it in the current folder + first. cloudpin now tells Windows not to search the current folder for any process it starts, including the command + `cloudpin exec` runs, as PowerShell and Git Bash already do + ([GHSA-3cf7-5v5w-q5vr](https://github.com/paureis/cloudpin/security/advisories/GHSA-3cf7-5v5w-q5vr)). + +## [1.1.1] - 2026-10-18 + +A security fix for Windows. Please upgrade. + +### Security + +- Windows: cloudpin now runs each CLI it asks about (az, gh, vercel, aws, gcloud, kubectl, helm, supabase, + wrangler), and the command `cloudpin exec` runs, by its full path from PATH, skipping empty and relative PATH + entries. Before, Windows' own lookup checked the current folder first, so a file named like one of those CLIs + inside a repository could run in its place when cloudpin checked a command there + ([GHSA-3cf7-5v5w-q5vr](https://github.com/paureis/cloudpin/security/advisories/GHSA-3cf7-5v5w-q5vr)). + +## [1.1.0] - 2026-10-16 + +Claude Code gets a one-step plugin, and any MCP agent can ask cloudpin before it acts. + +### Added + +- A Claude Code plugin (#15): `claude plugin install cloudpin --marketplace paureis/cloudpin` installs the hook, a + read-only MCP server and a skill that tells the agent to check first and stop on a block. With the plugin enabled, + `install-hook claude` declines and `doctor` warns if a settings hook would also run. +- `cloudpin mcp` (#15): a read-only MCP server (stdio) with `cloudpin_status` and `cloudpin_check`, for any agent that + supports MCP. No new dependency. + +## [1.0.0] - 2026-10-15 + +The first stable release: the `.cloudpin.yml` format is stable from here on (later versions only add sections and +keys), and every agent hook except Gemini CLI's is tested inside the real agent. + +### Fixed + +- Variables an agent sets earlier in its command line now count (#86). `export AWS_PROFILE=other; aws ...` and + PowerShell `$env:AWS_PROFILE = 'other'; aws ...` were checked against the default account and ran on another; and + `GH_TOKEN=$(cat other.token) gh ...` read the token as empty. cloudpin now follows `export`, `unset` and `$env:` + through the line, and stops a command whose account depends on a value only known when it runs, saying why. Found + in the threat-model review. +- Cursor: a command on your Cursor allowlist runs again when the account matches (#2). cloudpin answered `ask`, which + stopped even allowlisted commands; it now answers `allow`, which Cursor treats exactly like having no hook (measured + in Cursor CLI 2026.10.01: commands not on the allowlist still need your approval). Wrong accounts are still blocked. + +### Added + +- Antigravity hooks (#80): `cloudpin install-hook antigravity` guards Antigravity CLI, the IDE and Antigravity 2.0 + (`.agents/hooks.json`, or `~/.gemini/config/hooks.json` with `--user`). Google replaced Gemini CLI with Antigravity + CLI for free and consumer accounts on 2026-06-18. The hook checks `run_command` and text typed into a running + terminal; it asks rather than allows when nothing is wrong, so Antigravity's own approvals still apply. +- The Copilot CLI and Antigravity CLI hooks are tested inside the real agents (#3): a wrong pin blocks the command, a + right one lets it run, and Antigravity's own approval still applies to commands you haven't allowed. diff --git a/docs/mcp.md b/docs/mcp.md index 00a106c..e69d5b4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1,13 +1,14 @@ # cloudpin's MCP server `cloudpin mcp` is an MCP server (stdio) for any agent that supports MCP. The -[Claude Code plugin](../README.md#claude-code-plugin) starts it for you. It has three tools: +[Claude Code plugin](../README.md#claude-code-plugin) starts it for you. It has four tools: | Tool | Answers | |---|---| | `cloudpin_status` | which account each CLI is using here, what the project pins, which environment applies, which hooks are installed (the same as `cloudpin status --json`) | | `cloudpin_check` | would cloudpin allow this command line, as an agent's: each call, the account it would use and why, and the verdict with its reason and fix (the same as `cloudpin explain --agent --json`). The line is read as bash; pass `shell: "powershell"` for a PowerShell command (`--powershell` for `explain`) | | `cloudpin_doctor` | why cloudpin may not be guarding here: cloudpin on PATH, shell wrappers, agent hooks missing or out of date, on Windows the PowerShell execution policy and PATH, the pin file and each CLI's account, each with its fix (the same as `cloudpin doctor --json`, account IDs shortened; it skips the identity cache check, which writes a file, and says so) | +| `cloudpin_switch_plan` | on a mismatch, what you would run to move each CLI to its pinned account: the commands, what to do by hand, and any candidates to pick from (the same as `cloudpin switch --json` without `--yes`, plus a `note` saying who the plan is for). Nothing is run | No tool runs, switches or changes anything, by design: an agent that could switch accounts could switch to the wrong one, and only you know which account the work is for. @@ -15,6 +16,17 @@ wrong one, and only you know which account the work is for. When an agent connects, the server also hands it a few lines of instructions: check first, and on a block stop and tell you the reason and the fix, never work around it. +### A switch plan is for you to run + +`cloudpin_switch_plan` tells the agent to show you the plan and never run its commands itself. That is advice: a CLI's +own switch command (`gh auth switch`, `az account set`) is never blocked, so that you can always switch, which means +neither the hook nor `cloudpin_check` stops an agent that runs one anyway. The plan adds no new way to do that; a +blocked command's fix already names the switch command. + +A plan's commands hold the IDs from your pin file in full, because they have to run, plus the names they need from your +setup: the Vercel team's slug, a kube context, an AWS profile. Account IDs the active login reported are shortened, as +in `cloudpin_doctor`. A variable is named, never its value. + ## Add it to your agent Install cloudpin first (`npm install --global cloudpin`). Any MCP client that starts stdio servers takes the same diff --git a/plugin/skills/cloudpin/SKILL.md b/plugin/skills/cloudpin/SKILL.md index 30a4620..07f9fbd 100644 --- a/plugin/skills/cloudpin/SKILL.md +++ b/plugin/skills/cloudpin/SKILL.md @@ -6,7 +6,7 @@ description: Use before running cloud CLIs (az, aws, gcloud, vercel, gh, kubectl # cloudpin This project pins the cloud accounts it uses in `.cloudpin.yml`. cloudpin stops any cloud CLI command that would run -on a different account. Three read-only tools let you check first; none runs, switches or changes anything. +on a different account. Four read-only tools let you check first; none runs, switches or changes anything. ## Before cloud work @@ -25,6 +25,13 @@ the command another way, never set `CLOUDPIN_SKIP` or `CLOUDPIN_CONFIRM`, never switch accounts yourself. Switching is the user's call, because only they know which account the work is for: you may suggest they run `cloudpin switch`, which shows its plan and asks them before switching anything. +On a mismatch, show the user the plan from `cloudpin_switch_plan`. Its commands are for them to run: never run them +yourself, even when nothing stops you. + +## If cloudpin seems not to be guarding + +Call `cloudpin_doctor` and tell the user what it finds and its fix. + ## If the tools are missing The plugin runs the `cloudpin` command. If its tools or hook fail with "command not found", tell the user to run diff --git a/scripts/demo-folder.mjs b/scripts/demo-folder.mjs index 60289e9..072c854 100644 --- a/scripts/demo-folder.mjs +++ b/scripts/demo-folder.mjs @@ -146,7 +146,7 @@ export function readme() { "5. If Cursor asks whether you trust the authors of the files in this folder, answer that you trust them:", " Cursor runs a project's hooks only in a trusted workspace.", "6. Open Cursor Settings > MCP (called \"Tools & MCP\" or \"Tools & Integrations\" in some versions): `cloudpin`", - " is listed with its toggle on and two tools, `cloudpin_status` and `cloudpin_check`. If it shows an error, see", + " is listed with its toggle on and four tools, among them `cloudpin_status` and `cloudpin_check`. If it shows an error, see", " Troubleshooting.", "7. Open Cursor Settings > Hooks: `beforeShellExecution` lists `cloudpin hook cursor`.", "8. Rehearse in a new agent chat: type `Call cloudpin_status for this project.` It reports environment", diff --git a/src/cli.ts b/src/cli.ts index b787a82..97eb6ea 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -57,7 +57,7 @@ Usage: (one quoted argument is read as a full shell line, bash unless --powershell; --agent: as an agent hook) cloudpin mcp Read-only MCP server for agents (stdio): cloudpin_status, cloudpin_check, - cloudpin_doctor + cloudpin_doctor, cloudpin_switch_plan cloudpin doctor [--json] Check the whole setup (PATH, shell, hooks, pins, CLIs) and say what to fix (--json is safe to paste in a bug report) cloudpin use [ | --clear] diff --git a/src/doctor.ts b/src/doctor.ts index bff494a..2f05543 100644 --- a/src/doctor.ts +++ b/src/doctor.ts @@ -378,6 +378,18 @@ export function formatDoctor(checks: Check[], env: NodeJS.ProcessEnv): string[] /** Shortens an account ID or name to its last four characters. */ const shorten = (value: string) => `…${value.length > 4 ? value.slice(-4) : ""}`; +/** + * `text` with these values shortened, as --json does, for text that must keep other values whole (a pinned ID the + * user needs in full): only a whole value counts, not one inside a longer ID, name or address. + */ +export function shortenWhole(text: string, values: string[]): string { + const longestFirst = [...new Set(values)].filter((v) => v && !PUBLIC_VALUES.has(v)).sort((a, b) => b.length - a.length); + return longestFirst.reduce((t, v) => { + const literal = v.replace(/[.*+?^${}()|[\]\\]/g, (c) => `\\${c}`); + return t.replace(new RegExp(`(? shorten(v)); + }, text); +} + /** * The checks as JSON for a bug report, safe to paste in a public issue: * account IDs and names shortened to their last four characters, the home diff --git a/src/mcp-tools.ts b/src/mcp-tools.ts index de8b195..86f94a0 100644 --- a/src/mcp-tools.ts +++ b/src/mcp-tools.ts @@ -1,11 +1,12 @@ import { resolve } from "node:path"; -import { doctorJson, runDoctor, type Check, type DoctorDeps } from "./doctor.js"; +import { doctorJson, runDoctor, shortenWhole, type Check, type DoctorDeps } from "./doctor.js"; import { explain } from "./explain.js"; import type { GuardDeps } from "./guard.js"; import { installedHooks } from "./install.js"; import { createHandler, type McpTool } from "./mcp.js"; import { cacheDir } from "./paths.js"; import { collectStatus } from "./status.js"; +import { planJson, planSwitch, switchJson } from "./switch.js"; /** What doctor needs to know about this cloudpin and machine, apart from the folder, environment and files. */ export type DoctorHost = Pick; @@ -37,6 +38,27 @@ async function readOnlyDoctor(deps: GuardDeps, ctx: ToolContext, cwd: string) { return doctorJson(checks, d); } +/** + * A plan's lines speak to the person at a terminal ("run it yourself"), and a CLI's own switch command passes the hook + * and cloudpin_check, since a person must always be able to switch. So the answer says who a plan is for (#15). + */ +export const SWITCH_PLAN_NOTE = + 'Nothing was run. This plan is addressed to the user, including any line that says "yourself": show it to them, to run in their own terminal. ' + + "Do not run its commands yourself, even where no hook or cloudpin_check would stop you: which account the work is for is the user's call."; + +/** + * What `cloudpin switch --json` prints without `--yes`, with the note. The commands and the pinned IDs stay whole: they + * come from the pin file and have to run. What the active login said is shortened, as in cloudpin_doctor. + */ +async function switchPlan(deps: GuardDeps, ctx: ToolContext, cwd: string) { + const { report, steps } = await planSwitch(cwd, ctx.env, deps, {}); + const plan = steps.map((step) => { + const line = planJson(step); + return line.reason === undefined ? line : { ...line, reason: shortenWhole(line.reason, step.loginValues ?? []) }; + }); + return { note: SWITCH_PLAN_NOTE, ...switchJson(report, plan, [], null) }; +} + function folder(ctx: ToolContext, value: unknown): string { if (value === undefined) return ctx.cwd; if (typeof value !== "string") throw new Error("cwd must be a string"); @@ -58,7 +80,7 @@ export const CLOUDPIN_INSTRUCTIONS = [ "Never work around a block (another account, CLOUDPIN_SKIP, an environment variable, a script file).", "This server never runs or switches anything.", ].join(" ") + - "\n\nSwitching accounts and editing .cloudpin.yml are the user's call. If this server may not be running in the project folder, pass it as cwd."; + "\n\nSwitching accounts and editing .cloudpin.yml are the user's call. On a mismatch, cloudpin_switch_plan gives the commands for the user to run: show them, and never run them yourself. If this server may not be running in the project folder, pass it as cwd."; /** The handler `cloudpin mcp` serves: its tools, and the instructions at initialize. */ export function cloudpinHandler(deps: GuardDeps, ctx: ToolContext, version: string): (line: string) => Promise { @@ -120,5 +142,15 @@ export function cloudpinTools(deps: GuardDeps, ctx: ToolContext): McpTool[] { }, call: async (args) => readOnlyDoctor(deps, ctx, folder(ctx, args.cwd)), }, + { + name: "cloudpin_switch_plan", + description: + "On a mismatch with .cloudpin.yml: the exact commands that move each CLI to its pinned account, or what to do by hand, for the user to run. The same plan as cloudpin switch --json without --yes. Pinned IDs in full, those of the active login shortened. Nothing is run. Show the commands to the user and never run them yourself: switching accounts is the user's call.", + inputSchema: { + type: "object", + properties: { cwd: { type: "string", description: "Project folder; defaults to the current one." } }, + }, + call: async (args) => switchPlan(deps, ctx, folder(ctx, args.cwd)), + }, ]; } diff --git a/src/switch-plan.ts b/src/switch-plan.ts index bf1966c..4acaa80 100644 --- a/src/switch-plan.ts +++ b/src/switch-plan.ts @@ -36,6 +36,8 @@ export interface Step { notes: string[]; /** What cloudpin will not or cannot do, naming the exact command or variable. */ manual: string[]; + /** Account IDs and names the active login gave and the pin doesn't hold; cloudpin_switch_plan shortens them in its text. */ + loginValues?: string[]; } export interface PlanInput { @@ -83,6 +85,9 @@ export async function planProvider(input: PlanInput): Promise { const candidates = plan.candidates ?? []; const status: StepStatus = commands.length > 0 || plan.awsProfile !== undefined ? "run" : candidates.length > 1 ? "choose" : "manual"; + const pinned = new Set(Object.values(input.pin)); + const identity = input.resolution?.kind === "identity" ? Object.values(input.resolution.identity) : []; + const loginValues = [...identity, ...(plan.loginValues ?? [])].filter((v) => v && !pinned.has(v)); return { ...base, status, @@ -93,5 +98,6 @@ export async function planProvider(input: PlanInput): Promise { ...(plan.listed && plan.listed.length > 0 ? { listed: plan.listed } : {}), notes: plan.notes ?? [], manual: plan.manual ?? [], + ...(loginValues.length > 0 ? { loginValues } : {}), }; } diff --git a/src/switch-planners.ts b/src/switch-planners.ts index feb7d56..5657a86 100644 --- a/src/switch-planners.ts +++ b/src/switch-planners.ts @@ -36,6 +36,8 @@ export interface Plan { listed?: string[]; notes?: string[]; manual?: string[]; + /** Account IDs in these lines that the login's listings gave, not the pin. */ + loginValues?: string[]; } /** The line for a provider whose account cloudpin could not determine. */ @@ -74,7 +76,10 @@ export async function planAzure({ pin, entry, env, exec }: PlanInput): Promise

0 ? parts.join("; ") : undefined; } -function planJson(step: Step): PlanJson { +export function planJson(step: Step): PlanJson { const reason = reasonOf(step); const candidates = step.candidates?.map((c) => c.name) ?? step.listed; return { @@ -145,6 +145,19 @@ function describe(c: Candidate): string { return parts.length > 0 ? `: ${parts.join(", then ")}` : ""; } +/** The object `--json` prints; with no `ran` and no `after`, the plan alone (and cloudpin_switch_plan's answer). */ +export function switchJson(report: CheckReport, plan: PlanJson[], ran: RanJson[], after: CheckReport | null): SwitchJson { + return { + result: (after ?? report).result, + path: report.path, + environment: report.environment, + ...(report.error !== undefined ? { error: report.error } : {}), + plan, + ran, + after, + }; +} + /** * What `cloudpin switch` would do, running no switch command and writing nothing: the check it starts from and one * step per provider, using only the CLIs' read-only listings. On Windows the environment comes back with its names @@ -194,16 +207,7 @@ export async function runSwitch(cwd: string, typed: NodeJS.ProcessEnv, deps: Gua const only = opts.only ? { only: opts.only } : {}; const { report, steps, env } = await planSwitch(cwd, typed, deps, only); const emit = (plan: PlanJson[], ran: RanJson[], after: CheckReport | null) => { - const json: SwitchJson = { - result: (after ?? report).result, - path: report.path, - environment: report.environment, - ...(report.error !== undefined ? { error: report.error } : {}), - plan, - ran, - after, - }; - io.out(JSON.stringify(json, null, 2)); + io.out(JSON.stringify(switchJson(report, plan, ran, after), null, 2)); }; if (report.error !== undefined || report.path === null) { diff --git a/test/mcp-switch-plan.test.ts b/test/mcp-switch-plan.test.ts new file mode 100644 index 0000000..e5cc568 --- /dev/null +++ b/test/mcp-switch-plan.test.ts @@ -0,0 +1,379 @@ +import { readdirSync, statSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { findConfig } from "../src/config.js"; +import type { GuardDeps } from "../src/guard.js"; +import { CLOUDPIN_INSTRUCTIONS, cloudpinHandler, cloudpinTools, type ToolContext } from "../src/mcp-tools.js"; +import { providers } from "../src/providers/index.js"; +import { runSwitch, type SwitchIO } from "../src/switch.js"; +import type { Exec, ProviderDef } from "../src/types.js"; +import { fakeDoctorHost } from "./fake-doctor-host.js"; +import { tempDir } from "./tmp.js"; + +// #112: the plan `cloudpin switch --json` prints without --yes, as an MCP tool. Every ID and name here is made up. + +const SUB = "11111111-1111-4111-8111-111111111111"; +const OTHER_SUB = "22222222-2222-4222-8222-222222222222"; +const TENANT = "33333333-3333-4333-8333-333333333333"; +const OTHER_TENANT = "44444444-4444-4444-8444-444444444444"; +const SERVER = "https://kube.example.test"; +/** What a credential variable holds in these tests; it must never reach an answer. */ +const FAKE_VALUE = "example-value-of-a-variable"; + +/** Every command `cloudpin switch` may run. The fake CLIs answer them, so a tool that ran one is seen. */ +const SWITCHES = /auth switch|teams switch|config set|account set|use-context|set-context/; +/** The identity and listing reads a plan may use. */ +const READS = /^(gh api user|gh auth status|az account (show|list)|aws sts get-caller-identity|gcloud config list|gcloud auth list)\b/; + +interface Logins { + ghUser?: string; + ghAccounts?: unknown; + azSub?: string; + azTenant?: string; + azList?: { id: string; tenantId: string }[]; + gcloudLogins?: string[]; +} + +/** Fake CLIs that record every call. */ +function machine(logins: Logins = {}) { + const calls: string[] = []; + const exec: Exec = async (bin, args) => { + const line = [bin, ...args].join(" "); + calls.push(line); + const ok = (value: unknown) => ({ code: 0, stdout: typeof value === "string" ? value : JSON.stringify(value), stderr: "" }); + if (SWITCHES.test(line)) return ok(""); + if (line.startsWith("gh api user")) return ok(`${logins.ghUser ?? "someone-else"}\n`); + if (line.startsWith("gh auth status")) return ok(logins.ghAccounts ?? []); + if (line.startsWith("az account show")) return ok({ id: logins.azSub ?? OTHER_SUB, tenantId: logins.azTenant ?? TENANT, name: "Other Subscription" }); + if (line.startsWith("az account list")) return ok(logins.azList ?? []); + if (line.startsWith("gcloud config list")) return ok({ core: { account: "other@example.test", project: "other-project" } }); + if (line.startsWith("gcloud auth list")) return ok((logins.gcloudLogins ?? []).map((account) => ({ account }))); + if (line.startsWith("aws sts")) return ok({ Account: "999999999999", Arn: "arn:aws:iam::999999999999:user/x" }); + throw new Error(`unscripted: ${line}`); + }; + return { calls, exec }; +} + +interface Line { + provider: string; + status: string; + commands?: string[][]; + candidates?: string[]; + reason?: string; +} +interface Answer { + note: string; + result: string; + path: string | null; + environment: unknown; + error?: string; + plan: Line[]; + ran: unknown[]; + after: unknown; +} + +/** A real folder with this pin file, the real providers and config reader, and fake CLIs. */ +function project(pinFile: string | null, logins: Logins = {}, extraEnv: NodeJS.ProcessEnv = {}, platform: NodeJS.Platform = "linux", list = providers) { + const dir = tempDir("cloudpin-mcp-plan-"); + if (pinFile !== null) writeFileSync(join(dir, ".cloudpin.yml"), pinFile); + const env: NodeJS.ProcessEnv = { HOME: dir, USERPROFILE: dir, ...extraEnv }; + const m = machine(logins); + const deps: GuardDeps = { providers: list, exec: m.exec, platform, findConfig }; + const ctx: ToolContext = { + cwd: dir, + env, + read: () => null, + isDir: (p) => statSync(p, { throwIfNoEntry: false })?.isDirectory() ?? false, + doctor: fakeDoctorHost, + }; + const tool = cloudpinTools(deps, ctx).find((t) => t.name === "cloudpin_switch_plan"); + const call = async (args: Record = {}) => (await tool!.call(args)) as Answer; + /** What `cloudpin switch --json` prints in this project, with or without --yes. */ + const terminal = async (yes: boolean) => { + const out: string[] = []; + const io: SwitchIO = { isTTY: false, ask: async () => "", out: (l) => out.push(l), err: (l) => out.push(l) }; + await runSwitch(dir, env, deps, { yes, json: true }, io); + return JSON.parse(out[0]!) as Omit; + }; + return { dir, env, deps, ctx, tool, call, terminal, calls: m.calls }; +} + +const GH_PIN = "github: { user: me }\n"; +const AZ_PIN = `azure: { subscription: ${SUB}, tenant: ${TENANT} }\n`; +const AWS_PIN = 'aws: { account: "111111111111" }\n'; +const ME_LOGGED_IN = [{ host: "github.com", login: "me", active: false }]; +const SUB_KNOWN = [{ id: SUB, tenantId: TENANT }]; +const line = (a: Answer, provider: string) => a.plan.find((l) => l.provider === provider)!; + +function awsConfig() { + const dir = tempDir("cloudpin-mcp-plan-aws-"); + const file = join(dir, "config"); + writeFileSync(file, "[profile dev]\nsso_account_id = 111111111111\n"); + return { dir, file }; +} + +/** A kubeconfig on context `other` (namespace `right`), with these contexts on the pinned server. */ +function kubeconfig(names: string[]) { + const file = join(tempDir("cloudpin-mcp-plan-kube-"), "config"); + const contexts = names.map((name) => `- name: ${name}\n context: { cluster: c1 }\n`).join(""); + writeFileSync( + file, + `current-context: other\ncontexts:\n- name: other\n context: { cluster: c2, namespace: right }\n${contexts}clusters:\n- name: c1\n cluster: { server: ${SERVER} }\n- name: c2\n cluster: { server: https://other.example.test }\n`, + ); + return file; +} + +describe("cloudpin_switch_plan: the tool", () => { + it("is listed as read-only, with only an optional cwd", async () => { + const { deps, ctx } = project(GH_PIN); + const handle = cloudpinHandler(deps, ctx, "9.9.9"); + const list = JSON.parse((await handle(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" })))!); + const tool = list.result.tools.find((t: { name: string }) => t.name === "cloudpin_switch_plan"); + expect(tool).toBeDefined(); + expect(tool.annotations).toEqual({ readOnlyHint: true }); + expect(Object.keys(tool.inputSchema.properties)).toEqual(["cwd"]); + expect(tool.inputSchema.required).toBeUndefined(); + }); + + it("answers over tools/call with the JSON as text and as structured content", async () => { + const { deps, ctx } = project(GH_PIN, { ghAccounts: ME_LOGGED_IN }); + const handle = cloudpinHandler(deps, ctx, "9.9.9"); + const call = { jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "cloudpin_switch_plan", arguments: {} } }; + const res = JSON.parse((await handle(JSON.stringify(call)))!).result; + expect(res.isError).toBeUndefined(); + expect(JSON.parse(res.content[0].text)).toEqual(res.structuredContent); + expect(res.structuredContent.plan[0].status).toBe("run"); + }); + + it("refuses a folder that doesn't exist, and a cwd that isn't a string", async () => { + const { tool, dir } = project(GH_PIN); + await expect(tool!.call({ cwd: join(dir, "nope") })).rejects.toThrow(/folder not found/); + await expect(tool!.call({ cwd: 7 })).rejects.toThrow(/cwd must be a string/); + }); +}); + +describe("cloudpin_switch_plan: what it answers", () => { + it("every pin matches: nothing to do", async () => { + const a = await project(GH_PIN, { ghUser: "me" }).call(); + expect(a.result).toBe("match"); + expect(a.plan).toEqual([{ provider: "github", status: "ok" }]); + }); + + it("a mismatch: run lines, the same as `cloudpin switch --json` without --yes, plus the note", async () => { + const { call, terminal } = project(AZ_PIN + GH_PIN, { ghAccounts: ME_LOGGED_IN, azList: SUB_KNOWN }); + const { note, ...rest } = await call(); + expect(typeof note).toBe("string"); + expect(rest).toEqual(await terminal(false)); + expect(rest.result).toBe("mismatch"); + expect(rest.plan).toEqual([ + { provider: "azure", status: "run", commands: [["az", "account", "set", "--subscription", SUB]] }, + { provider: "github", status: "run", commands: [["gh", "auth", "switch", "--hostname", "github.com", "--user", "me"]] }, + ]); + expect(rest.ran).toEqual([]); + expect(rest.after).toBeNull(); + }); + + it("a missing login: a manual line with the login command, and no command to run", async () => { + const gh = line(await project(GH_PIN, { ghAccounts: [] }).call(), "github"); + expect(gh.status).toBe("manual"); + expect(gh.commands).toBeUndefined(); + expect(gh.reason).toContain("gh auth login --hostname github.com"); + }); + + it("a subscription this login doesn't know: a manual line naming the full pinned IDs", async () => { + const az = line(await project(AZ_PIN, { azList: [] }).call(), "azure"); + expect(az.status).toBe("manual"); + expect(az.reason).toContain(SUB); + expect(az.reason).toContain(`az login --tenant ${TENANT}`); + }); + + it("an override in the environment: the manual line names the variable, never its value", async () => { + const a = await project(GH_PIN, { ghAccounts: ME_LOGGED_IN }, { GH_TOKEN: FAKE_VALUE }).call(); + expect(line(a, "github").status).toBe("manual"); + expect(line(a, "github").reason).toContain("unset GH_TOKEN"); + expect(JSON.stringify(a)).not.toContain(FAKE_VALUE); + }); + + it("no variable's value reaches the answer, for any provider's override line", async () => { + const names = ["GH_TOKEN", "GITHUB_TOKEN", "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN", "VERCEL_TOKEN", "SUPABASE_ACCESS_TOKEN", "CLOUDFLARE_API_TOKEN", "CLOUDSDK_CORE_PROJECT", "CLOUDSDK_CORE_ACCOUNT"]; + const env = Object.fromEntries(names.map((n) => [n, FAKE_VALUE])); + const pins = `${AZ_PIN}${AWS_PIN}gcloud: { account: me@example.test, project: mine }\n${GH_PIN}`; + const a = await project(pins, { ghAccounts: ME_LOGGED_IN, azList: SUB_KNOWN }, env).call(); + expect(line(a, "github").reason).toContain("unset GH_TOKEN and GITHUB_TOKEN"); + expect(line(a, "aws").reason).toContain("unset AWS_ACCESS_KEY_ID"); + expect(line(a, "gcloud").reason).toContain("unset CLOUDSDK_CORE_PROJECT"); + expect(JSON.stringify(a)).not.toContain(FAKE_VALUE); + }); + + it("a gcloud configuration whose name cloudpin won't pass on: named by its variable, not its value", async () => { + const pin = "gcloud: { project: mine }\n"; + const a = await project(pin, {}, { CLOUDSDK_ACTIVE_CONFIG_NAME: "example value!" }).call(); + expect(line(a, "gcloud").status).toBe("manual"); + expect(line(a, "gcloud").reason).toContain("CLOUDSDK_ACTIVE_CONFIG_NAME"); + expect(JSON.stringify(a)).not.toContain("example value!"); + }); + + it("AWS: no command exists, so the line says what to set by hand, with the profile's name", async () => { + const aws = line(await project(AWS_PIN, {}, { AWS_CONFIG_FILE: awsConfig().file }).call(), "aws"); + expect(aws.status).toBe("manual"); + expect(aws.reason).toContain("export AWS_PROFILE=dev"); + }); + + it("several matching kube contexts: a choose line with the candidates, and how to pick", async () => { + const { call, terminal } = project(`kubernetes: { server: ${SERVER} }\n`, {}, { KUBECONFIG: kubeconfig(["one", "two"]) }); + const { note: _note, ...rest } = await call(); + expect(rest).toEqual(await terminal(false)); + const kube = rest.plan[0]!; + expect(kube.status).toBe("choose"); + expect(kube.candidates).toEqual(["one", "two"]); + expect(kube.commands).toBeUndefined(); + expect(kube.reason).toContain("cloudpin switch in a terminal"); + }); + + it("no pin file: nothing is pinned, and the plan is empty", async () => { + const a = await project(null).call(); + expect(a).toMatchObject({ result: "unpinned", path: null, environment: null, plan: [], ran: [], after: null }); + expect(a.note).toMatch(/nothing was run/i); + }); + + it("a broken pin file: the error in the answer, as `cloudpin switch --json` gives it", async () => { + const { call, terminal } = project("github: [not, a, mapping]\n"); + const { note: _note, ...rest } = await call(); + expect(rest.result).toBe("error"); + expect(rest.error).toMatch(/invalid config/); + expect(rest).toEqual(await terminal(false)); + }); + + it("uses the active environment of the pin file", async () => { + const a = await project("environments:\n staging:\n github: { user: stage-bot }\n", { ghAccounts: [{ host: "github.com", login: "stage-bot", active: false }] }).call(); + expect(a.environment).toMatchObject({ name: "staging" }); + expect(line(a, "github").commands).toEqual([["gh", "auth", "switch", "--hostname", "github.com", "--user", "stage-bot"]]); + }); +}); + +describe("cloudpin_switch_plan: Windows, where a variable's name has no case (#119, #136)", () => { + it("gh_token is the override there, and its value stays out; control: another variable elsewhere", async () => { + const win = await project(GH_PIN, { ghAccounts: ME_LOGGED_IN }, { gh_token: FAKE_VALUE }, "win32").call(); + expect(line(win, "github").status).toBe("manual"); + expect(line(win, "github").reason).toContain("unset GH_TOKEN"); + expect(JSON.stringify(win)).not.toContain(FAKE_VALUE); + + const linux = await project(GH_PIN, { ghAccounts: ME_LOGGED_IN }, { gh_token: FAKE_VALUE }, "linux").call(); + expect(line(linux, "github").status).toBe("run"); + }); + + it("a lowercase cloudpin_env picks the environment there", async () => { + const pins = "environments:\n staging:\n github: { user: stage-bot }\n production:\n github: { user: me }\n"; + const a = await project(pins, { ghAccounts: ME_LOGGED_IN }, { cloudpin_env: "production" }, "win32").call(); + expect(a.environment).toMatchObject({ name: "production" }); + }); +}); + +describe("cloudpin_switch_plan: nothing runs (#15: no tool will ever switch accounts)", () => { + const PINS = `${AZ_PIN}gcloud: { account: me@example.test, project: mine }\n${GH_PIN}`; + const LOGINS: Logins = { ghAccounts: ME_LOGGED_IN, azList: SUB_KNOWN, gcloudLogins: ["me@example.test"] }; + + it("control: `cloudpin switch --yes` runs each switch command through these fake CLIs, and the pattern sees them", async () => { + const { calls, terminal } = project(PINS, LOGINS); + const json = await terminal(true); + expect(json.ran).toHaveLength(4); + expect(calls.filter((c) => SWITCHES.test(c))).toHaveLength(4); + }); + + it("the plan has those same commands, and the fake CLIs saw only identity reads", async () => { + const { calls, call } = project(PINS, LOGINS); + const a = await call(); + expect(a.plan.flatMap((l) => l.commands ?? [])).toHaveLength(4); + expect(calls.length).toBeGreaterThan(0); + expect(calls.filter((c) => SWITCHES.test(c))).toEqual([]); + expect(calls.filter((c) => !READS.test(c))).toEqual([]); + expect(a.ran).toEqual([]); + expect(a.after).toBeNull(); + }); + + it("writes nothing: no file in the folder, and nothing to CLOUDPIN_ENV_FILE for AWS", async () => { + const { dir: aws, file } = awsConfig(); + const { call, dir } = project(AWS_PIN, {}, { AWS_CONFIG_FILE: file, CLOUDPIN_ENV_FILE: join(aws, "side") }); + const before = readdirSync(dir, { recursive: true, encoding: "utf8" }).sort(); + await call(); + expect(readdirSync(dir, { recursive: true, encoding: "utf8" }).sort()).toEqual(before); + expect(readdirSync(aws)).toEqual(["config"]); + }); +}); + +describe("cloudpin_switch_plan: account IDs", () => { + /** gh lists the pinned login as active, but the API answers as another: the plan repeats guard's mismatch. */ + const stillOther = { ghUser: "someone-else", ghAccounts: [{ host: "github.com", login: "me", active: true }] }; + + it("shortens what the active login said, keeps the pin whole; control: the terminal's --json has it in full", async () => { + const { call, terminal } = project(GH_PIN, stillOther); + const reason = line(await call(), "github").reason!; + expect(reason).toContain('expected "me"'); + expect(reason).toContain("…else"); + expect(reason).not.toContain("someone-else"); + expect((await terminal(false)).plan[0]!.reason).toContain("someone-else"); + }); + + it("a subscription in another tenant: the login's tenant shortened, the pinned IDs whole", async () => { + const { call, terminal } = project(AZ_PIN, { azList: [{ id: SUB, tenantId: OTHER_TENANT }] }); + const reason = line(await call(), "azure").reason!; + expect(reason).toContain(SUB); + expect(reason).toContain(TENANT); + expect(reason).not.toContain(OTHER_TENANT); + expect(reason).toContain("…4444"); + expect((await terminal(false)).plan[0]!.reason).toContain(OTHER_TENANT); + }); + + /** The real GitHub provider, comparing with the words given. */ + const github = (compare: string[]): ProviderDef[] => [{ ...providers.find((p) => p.name === "github")!, compare: () => compare } as ProviderDef]; + + it("keeps a value that identifies nobody (github.com), as doctor does", async () => { + const list = github(['host: active is "github.com"']); + const reason = line(await project(GH_PIN, stillOther, {}, "linux", list).call(), "github").reason!; + expect(reason).toBe('host: active is "github.com"'); + }); + + it("shortens only the whole value: a pinned ID that contains the active one stays runnable", async () => { + const list = github(['user: expected "me-and-others", active is "me"; me again, and me.']); + const accounts = [{ host: "github.com", login: "me-and-others", active: true }]; + const reason = line(await project("github: { user: me-and-others }\n", { ghUser: "me", ghAccounts: accounts }, {}, "linux", list).call(), "github").reason!; + expect(reason).toBe('user: expected "me-and-others", active is "…"; … again, and ….'); + }); + + it("never shortens a command, even one that holds a value the active login also has", async () => { + // The active context's namespace is `right`, the name of the context to move to. + const pin = `kubernetes: { server: ${SERVER} }\n`; + const a = await project(pin, {}, { KUBECONFIG: kubeconfig(["right"]) }).call(); + expect(line(a, "kubernetes").commands).toEqual([["kubectl", "config", "use-context", "right"]]); + }); +}); + +describe("cloudpin_switch_plan: a plan is for the user to run", () => { + it("the description says nothing runs, the user runs them, and not to run them", () => { + const { description } = project(GH_PIN).tool!; + expect(description).toMatch(/nothing is run/i); + expect(description).toMatch(/for the user to run/i); + expect(description).toMatch(/never run them yourself/i); + }); + + it("the answer says so too, also for a command neither a hook nor cloudpin_check would stop", async () => { + const { note } = await project(GH_PIN, { ghAccounts: ME_LOGGED_IN }).call(); + expect(note).toMatch(/nothing was run/i); + expect(note).toMatch(/show it to them/i); + expect(note).toMatch(/do not run its commands yourself/i); + expect(note).toContain("cloudpin_check"); + expect(note).toMatch(/hook/i); + }); + + it("the answer says that a line saying 'yourself' speaks to the user, not the agent", async () => { + const a = await project(GH_PIN, { ghAccounts: "not a list" }).call(); + expect(line(a, "github").reason).toContain("switch yourself"); + expect(a.note).toMatch(/addressed to the user/i); + }); + + it("the server's instructions say to show a plan and never run it, leaving the first 512 characters as they were", () => { + expect(CLOUDPIN_INSTRUCTIONS).toMatch(/cloudpin_switch_plan[^.]*for the user to run/i); + expect(CLOUDPIN_INSTRUCTIONS).toMatch(/show them, and never run them yourself/i); + expect(CLOUDPIN_INSTRUCTIONS.slice(0, 512)).toMatch(/never runs or switches anything/i); + }); +}); diff --git a/test/mcp-tools.test.ts b/test/mcp-tools.test.ts index 1102e73..e27295f 100644 --- a/test/mcp-tools.test.ts +++ b/test/mcp-tools.test.ts @@ -106,7 +106,7 @@ describe("server instructions", () => { expect(init.result.instructions).toBe(CLOUDPIN_INSTRUCTIONS); expect(init.result.serverInfo).toEqual({ name: "cloudpin", version: "9.9.9" }); const list = JSON.parse((await handle(JSON.stringify({ jsonrpc: "2.0", id: 2, method: "tools/list" })))!); - expect(list.result.tools.map((t: { name: string }) => t.name)).toEqual(["cloudpin_status", "cloudpin_check", "cloudpin_doctor"]); + expect(list.result.tools.map((t: { name: string }) => t.name)).toEqual(["cloudpin_status", "cloudpin_check", "cloudpin_doctor", "cloudpin_switch_plan"]); }); it("name every CLI the tools describe, as the skill does", () => { diff --git a/test/plugin.test.ts b/test/plugin.test.ts index bb03277..ae690f6 100644 --- a/test/plugin.test.ts +++ b/test/plugin.test.ts @@ -29,11 +29,19 @@ describe("the Claude Code plugin", () => { expect(market.plugins).toEqual([expect.objectContaining({ name: "cloudpin", source: "./plugin" })]); }); - it("ships a skill that names both tools and says to stop on a block", () => { + it("ships a skill that names every tool and says to stop on a block", () => { const skill = read("plugin/skills/cloudpin/SKILL.md"); expect(skill).toMatch(/^---\nname: cloudpin\ndescription: .+\n---\n/); expect(skill).toContain("cloudpin_status"); expect(skill).toContain("cloudpin_check"); + expect(skill).toContain("cloudpin_doctor"); + expect(skill).toContain("cloudpin_switch_plan"); expect(skill).toMatch(/never .*CLOUDPIN_SKIP/i); }); + + it("has the skill say a switch plan is for the user to run, never the agent", () => { + const skill = read("plugin/skills/cloudpin/SKILL.md").replace(/\s+/g, " "); + expect(skill).toMatch(/show the user the plan from `cloudpin_switch_plan`/); + expect(skill).toMatch(/for them to run: never run them yourself/); + }); });