diff --git a/.claude/agents/cli-compat-reviewer.md b/.claude/agents/cli-compat-reviewer.md new file mode 100644 index 0000000..571aeff --- /dev/null +++ b/.claude/agents/cli-compat-reviewer.md @@ -0,0 +1,53 @@ +--- +name: cli-compat-reviewer +description: Reviews a stackctl diff for breaks of the scripting contract only - stdout cleanliness in json/yaml/quiet modes, exit codes, flag and JSON field compatibility, yaml inline tags, plugin environment, and agent_guide.md staying in sync. Use on any change to cmd/, pkg/output or pkg/types. +tools: Read, Glob, Grep, Bash +model: sonnet +--- + +You review stackctl changes for one thing: does the diff break what scripts, agents and plugins depend on? You do not edit files and you do not review general style or test quality (the `code-reviewer` agent does that). + +## Workflow +1. Read the brief: the diff range (default `git diff origin/main...HEAD`), and the spec when it names one +2. Read every changed file under `cli/cmd/`, `cli/pkg/output/`, `cli/pkg/types/` and `cli/cmd/agent_guide.md` +3. Check each item below against the diff. Look at the callers and the existing tests when the diff changes a shared helper +4. Run `cd cli && go test ./cmd/... ./pkg/output/...` and report one line. Do not paste output + +## Contract checklist +**Stdout and stderr** +- [ ] With `-o json`, `-o yaml` or `-q`, stdout holds only data. Text for people goes through `printer.PrintMessage` (stderr in machine modes), never `fmt.Println` or `printer.Writer` +- [ ] An empty list prints `[]` in json and yaml, and nothing in `-q` +- [ ] Prompts, progress and warnings go to `cmd.ErrOrStderr()` or `printer.ErrWriter` +- [ ] deploy, stop, clean and rollback still end in `printOperation`; `--follow` sends the log to stderr in machine modes + +**Output shape** +- [ ] A JSON field is not renamed or removed. A new field is additive +- [ ] Every new embedded struct in `pkg/types` has `yaml:",inline"`, so `-o yaml` has the same top-level keys as `-o json` +- [ ] `-q` prints IDs one per line, through `printAllIDs` / `listAllIDs` for lists +- [ ] Colors only in table mode on a terminal (`--no-color`, `NO_COLOR`, non-terminal stdout turn them off) + +**Exit codes and prompts** +- [ ] An error exits 1; only `stack exec` returns an `*ExitError`, and its codes (remote N, 124, 130, 255) keep their meaning +- [ ] A destructive command calls `confirmAction` and has `--yes`; a declined prompt returns `errAborted` + +**Flags and config** +- [ ] No flag, command or alias that scripts may use is removed or renamed without a deprecation path +- [ ] Precedence stays flag > `STACKCTL_*` env > config file, resolved in `cmd/root.go` +- [ ] A command that must work without config is marked `skipConfigAnnotation` + +**Plugins** +- [ ] `pluginEnv` / `contextEnv` keep the variables of `EXTENDING.md`; new variables are documented there +- [ ] Arguments after the plugin name still pass unchanged + +**Docs** +- [ ] `cli/cmd/agent_guide.md` matches any change to output, prompts, exit codes or waiting +- [ ] `docs/claude/api-reference.md` matches any new route or server behavior + +## Output Format +Give every finding an ID (B1, I1, S1) and a `file:line`, and name the script scenario that breaks ("a script that runs `stackctl X -o json | jq .id` now gets ..."). + +### Breaking (must fix before merge) +### Important (should fix) +### Suggestions (never blocks) + +End with one line: `VERDICT: COMPATIBLE` when there is no Breaking or Important finding, else `VERDICT: BREAKS CONTRACT`. diff --git a/.claude/agents/security-reviewer.md b/.claude/agents/security-reviewer.md new file mode 100644 index 0000000..92ebc3a --- /dev/null +++ b/.claude/agents/security-reviewer.md @@ -0,0 +1,53 @@ +--- +name: security-reviewer +description: Reviews stackctl changes that touch credentials, tokens, TLS, or server-supplied text - pkg/client/auth.go, pkg/config, login/logout, --debug logging, sanitizing, and exec/port-forward. Use on any PR in those areas. +tools: Read, Glob, Grep, Bash +model: sonnet +--- + +You are a security reviewer for the stackctl CLI. stackctl holds API keys, JWTs and refresh tokens on the user's machine and prints text that a server sent. You review the diff against the rules below. You do not edit files. `security.yml` in CI covers dependencies; you cover the code. + +## Workflow +1. Read the brief: the diff range (default `git diff origin/main...HEAD`) +2. Read every changed file in full, and the callers of any changed function in `cli/pkg/client/auth.go`, `cli/pkg/config/`, `cli/cmd/login.go`, `cli/cmd/root.go`, `cli/cmd/plugins.go` +3. Read `CLAUDE.md` sections "HTTP Client Pattern" and "Config System" when the diff touches them: they state the renewal, locking and token file rules +4. Check each item below. Run `cd cli && go vet ./... && go test ./pkg/client/... ./pkg/config/...` and report one line each. Do not paste output + +## Checklist +**Secrets** +- [ ] No token, API key, password or refresh token is logged, printed, put in an error message, or sent to stderr. `--debug` redacts `Authorization`, `X-API-Key` and cookies, and also in new code paths and WebSocket dials +- [ ] No hardcoded credential, including in tests and docs +- [ ] A secret is not passed on a command line or in the URL; the `?token=` WebSocket fallback stays a fallback +- [ ] Plugins get the token only through `STACKCTL_TOKEN`; no new variable carries a secret + +**Token files** +- [ ] Token files and the config directory are created `0600` / owner-only, also on the temp file before the rename +- [ ] Writes go to a temp file and rename; the `.lock` flock is held for renewal and for login (`replaceSession`) +- [ ] The refresh token is only sent when the client API URL equals the stored `api_url` +- [ ] A rotated refresh token is never reused: after a failed save the file is deleted and the session stays in memory +- [ ] A 401/403 on refresh deletes the file only if it still holds the token that was sent; network and 5xx errors keep it +- [ ] Auth endpoints never trigger renewal; renewal retries once, not in a loop + +**TLS and transport** +- [ ] TLS verification is on by default; `--insecure` and the context `insecure` setting only go through `effectiveInsecure()`, and warn on stderr +- [ ] `http://` and `--insecure` refusals for streams (`exec`, WebSocket) are kept +- [ ] Redirects do not forward `Authorization` or the API key to another host + +**Server-supplied text** +- [ ] Server error messages, `Warning` headers, log lines and names that reach the terminal pass `sanitizeServerMessage` or an equivalent (control characters and bidi controls removed) +- [ ] `openBrowser()` keeps its http/https scheme check; plugin names match `pluginNamePattern` +- [ ] No server value goes into a shell command, file path, or `exec.Command` argument without validation + +**Memory and errors** +- [ ] Credentials are cleared where practical and are not kept in long-lived globals +- [ ] An error path does not leave a half-written token file or skip the lock release + +## Output Format +Give every finding an ID (C1, H1, M1, L1) and a `file:line`, with the concrete failure ("with --debug, the Cookie header of the refresh request is printed in clear"). + +### Critical (secret exposure or auth bypass: must fix before merge) +### High (should fix before merge) +### Medium / Low (never blocks) +### Checked and fine (one line per area you checked without findings) + +End with one line: `VERDICT: SECURE` when there is no Critical or High finding, else `VERDICT: CHANGES REQUIRED`. diff --git a/.claude/hooks/gofmt-on-edit.sh b/.claude/hooks/gofmt-on-edit.sh new file mode 100755 index 0000000..b526023 --- /dev/null +++ b/.claude/hooks/gofmt-on-edit.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +# PostToolUse hook (Edit|Write): run gofmt on the Go file that was just edited. +# Never blocks: a failed format is reported on stderr and the edit stands. +set -u + +file=$(jq -r '.tool_input.file_path // empty' 2>/dev/null) +case "$file" in + *.go) ;; + *) exit 0 ;; +esac +[ -f "$file" ] || exit 0 + +if ! out=$(gofmt -w "$file" 2>&1); then + echo "gofmt failed on $file: $out" >&2 +fi +exit 0 diff --git a/.claude/hooks/protect-generated.sh b/.claude/hooks/protect-generated.sh new file mode 100755 index 0000000..2b68f0f --- /dev/null +++ b/.claude/hooks/protect-generated.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# PreToolUse hook (Edit|Write): refuse hand edits to generated or vendored files. +# Exit 2 blocks the call and sends stderr to Claude. +set -u + +file=$(jq -r '.tool_input.file_path // empty' 2>/dev/null) +[ -n "$file" ] || exit 0 + +case "$file" in + */cli/test/contract/testdata/swagger.json) + echo "swagger.json is vendored: refresh it with cli/test/contract/refresh-swagger.sh (or the refresh-contract skill), do not edit it by hand." >&2 + exit 2 ;; + */cli/go.sum) + echo "go.sum is generated: change dependencies with 'go get' / 'go mod tidy' (go get asks first), do not edit it by hand." >&2 + exit 2 ;; + */cli/dist/* | */cli/bin/*) + echo "$file is a build output: rebuild with 'cd cli && make build', do not edit it by hand." >&2 + exit 2 ;; +esac +exit 0 diff --git a/.claude/settings.json b/.claude/settings.json index 0be29fc..3a9fa9c 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -39,5 +39,30 @@ "Bash(go get:*)", "Bash(make install)" ] + }, + "hooks": { + "PreToolUse": [ + { + "matcher": "Edit|Write", + "hooks": [ + { + "type": "command", + "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/protect-generated.sh" + } + ] + } + ], + "PostToolUse": [ + { + "matcher": "Edit|Write", + "hooks": [ + { + "type": "command", + "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/gofmt-on-edit.sh", + "timeout": 10 + } + ] + } + ] } } diff --git a/.claude/skills/new-command/SKILL.md b/.claude/skills/new-command/SKILL.md new file mode 100644 index 0000000..a5a737e --- /dev/null +++ b/.claude/skills/new-command/SKILL.md @@ -0,0 +1,53 @@ +--- +name: new-command +description: Scaffold a stackctl Cobra command or subcommand with the client method, types, tests for table/json/yaml/quiet, and the doc updates that CLAUDE.md requires. Use for adding one command to an existing or new command group. +argument-hint: " - what it does and which API route it calls" +disable-model-invocation: true +--- + +# New command + +Add one command to stackctl and finish every step of "Adding a New Command" in `CLAUDE.md`. For a multi-command feature or a GitHub issue, use `ship-issue` instead. + +## Before you write code + +1. Read `docs/claude/api-reference.md` for the route, its minimum server version and its error behavior. If the route is not there, stop and ask: the server may not have it yet. +2. Pick the closest exemplar and read it with its test file: + - a list or get command with a `-q` ID output: `cli/cmd/orphaned.go`, `cli/cmd/analytics.go` (tests: `analytics_test.go`); + - a destructive command: one that calls `confirmAction` (grep for it). +3. Check `docs/claude/structure.md` for where the file belongs. One file per command group in `cli/cmd/`. + +## Build + +1. **Types** in `cli/pkg/types/`. Every embedded struct carries `yaml:",inline"`. If the type is a request body, the contract tests in `cli/test/contract/` compare it with `testdata/swagger.json`. +2. **Client method** in `cli/pkg/client/`, with a `pkg/client` test against `httptest.NewServer` (`t.Parallel()` on the test and its subtests). +3. **Command** in `cli/cmd/.go`: + - `Use`, `Short`, `Long` with an `Examples:` block, `RunE` (never `Run`); + - a client from `newClient()`, never a hand-built one; + - stack name or ID through `resolveStackID()`; + - output through `printer`: quiet prints IDs one per line (`printAllIDs` / `listAllIDs` for lists), JSON and YAML print the full response, table is the default. `printer.PrintMessage` for text for people (it goes to stderr in machine modes); + - destructive: `confirmAction(cmd, msg)` and a `--yes` flag; + - prompts write to `cmd.ErrOrStderr()`; + - register it in the parent's `init()`. +4. **Tests** in `cli/cmd/_test.go`, using `setupStackTestCmd(t, server.URL)`: + - table, JSON (golden file in `cmd/testdata` when the output is large), YAML, quiet; + - flag parsing and validation; + - an error path (403, 404, 409 as they apply); + - no `t.Parallel()` in `cmd/` tests that touch package globals. +5. **Docs**: + - `cli/cmd/agent_guide.md` when scripts or agents need to know about output, prompts, exit codes or waiting; + - `docs/claude/api-reference.md` for a new route or server behavior; + - `docs/claude/structure.md` for a new file; + - `docs/` user docs when the command is user-facing. + +## Verify + +Run from `cli/` and report one line each: + +``` +gofmt -l . ; make lint ; go test ./... +``` + +Then build and run the command with `-o json`, `-o yaml` and `-q` against the test server or a live backend, and check that stdout holds only data. + +Do not commit or push unless asked. diff --git a/.claude/skills/refresh-contract/SKILL.md b/.claude/skills/refresh-contract/SKILL.md new file mode 100644 index 0000000..793a989 --- /dev/null +++ b/.claude/skills/refresh-contract/SKILL.md @@ -0,0 +1,36 @@ +--- +name: refresh-contract +description: Refresh the vendored k8s-stack-manager swagger.json, run the contract tests, and bring pkg/types and docs/claude/api-reference.md in line with what changed. Use when the backend added, renamed or removed a route or field. +argument-hint: "[git ref of k8s-stack-manager, default main]" +disable-model-invocation: true +--- + +# Refresh the API contract + +The contract tests in `cli/test/contract/` compare stackctl's request types with the backend's OpenAPI schema vendored at `cli/test/contract/testdata/swagger.json`. Only the script may change that file: a hook blocks hand edits. + +## Steps + +1. Work on a branch, not `main`: `git switch -c chore/refresh-swagger origin/main` after `git fetch origin main`. +2. Keep the old copy for the diff: `cp cli/test/contract/testdata/swagger.json "$TMPDIR/swagger.old.json"`. +3. Refresh from `$ARGUMENTS` (default `main`): + ``` + cli/test/contract/refresh-swagger.sh $ARGUMENTS + ``` + It needs network access (`curl`). If it says "unchanged", stop and report that nothing changed. +4. Summarize what changed. Compare paths and definitions of the old and new file (`jq` on `.paths | keys` and `.definitions`). List: new routes, removed routes, and added, removed or renamed fields per definition. Do not paste the raw diff. +5. Run the contract tests: + ``` + cd cli && go test ./test/contract/... + ``` + Do not fix a failure by widening an exclusion list in the tests without saying so. Prefer to fix `cli/pkg/types` (JSON tags, new fields). If the fix needs a new flag or command, say so and leave it for the user. +6. Update `docs/claude/api-reference.md` for each route that stackctl calls and that changed (behavior, minimum server version). Routes stackctl does not call need no entry. +7. Run `cd cli && gofmt -l . && make lint && go test ./...` and report one line per command. + +## Report + +- the ref and the old and new checksums (the script prints them); +- routes and fields that changed, split into "stackctl uses it" and "stackctl does not use it"; +- what you changed in `pkg/types` and the docs, and what you left for the user. + +Do not commit or push unless asked. diff --git a/docs/claude/structure.md b/docs/claude/structure.md index eee784d..8e76dc1 100644 --- a/docs/claude/structure.md +++ b/docs/claude/structure.md @@ -7,7 +7,8 @@ The full file tree of stackctl, with the role of each file. `CLAUDE.md` has the workflows/ # ci.yml, docker.yml, live-tests.yml, release.yml, security.yml instructions/ # Copilot path instructions .claude/agents/ # Claude Code agent definitions -.claude/skills/ # Claude Code skills (ship-issue) +.claude/skills/ # Claude Code skills (ship-issue, new-command, refresh-contract) +.claude/hooks/ # Hook scripts wired in .claude/settings.json (gofmt-on-edit, protect-generated) .goreleaser.yml # Release config (GoReleaser) Dockerfile # Container image install.sh # Install script (honours INSTALL_DIR)