# Command Surface

This file maps each top-level command family to source files and required update points.

## auth

- Source: `internal/cmd/auth.go`
- Help metadata: `internal/cmd/auth.go` (Cobra command builders and per-subcommand flag registration)
- Typical tests: `internal/cmd/auth_env_test.go`
- Note: `auth set-key` reads API keys from an interactive terminal prompt with hidden input (password-style); `--api-key` flag input is intentionally unsupported.

## version

- Source: `internal/cmd/version.go`
- Help metadata: `internal/cmd/version.go` (Cobra command builder)
- Typical tests: `internal/cmd/version_test.go`, `internal/cmd/root_test.go`
- Note: `version` is intentionally a standalone root command and does not load runtime env/profile/config state.

## env

- Source: `internal/cmd/env.go`
- Help metadata: `internal/cmd/env.go` (Cobra command builders)
- Typical tests: `internal/cmd/auth_env_test.go`, `internal/cmd/root_test.go`

## switch

- Source: `internal/cmd/switch.go`
- Help metadata: `internal/cmd/switch.go` (Cobra command builder)
- Typical tests: `internal/cmd/auth_env_test.go`, `internal/cmd/help_test.go`
- Note: `switch <env>` behaves like `env use <env>` and only changes `active_env`.
- Note: `switch <env> <profile>` validates the profile in that target env first, then persists both `active_env` and that env's `active_profile`.

## profile

- Source: `internal/cmd/profile.go`
- Help metadata: `internal/cmd/profile.go` (Cobra command builders and registered flags)
- Typical tests: `internal/cmd/profile_test.go`, `internal/cmd/help_test.go`
- Note: profiles are env-scoped only; the `profile cluster` subtree was removed.
- Note: `profile set current ...` is a reserved alias that targets the active profile in the selected env.
- Note: `profile open [<name>]` opens the selected profile `clinic_url` in the default browser without changing `active_profile`.

## completion

- Source: `internal/cmd/completion.go`
- Help metadata: `internal/cmd/completion.go` (Cobra command builder)
- Typical tests: `internal/cmd/completion_test.go`
- Note: `clinic completion <shell>` emits shell completion scripts and completion callbacks resolve env/profile names from local config.

## cluster

- Source: `internal/cmd/cluster.go`
- Help metadata: `internal/cmd/cluster.go` (Cobra command builders and registered flags)
- Typical tests: `internal/cmd/cluster_test.go`
- Note: `cluster search` requires at least one of `--query` or `--deploy-type`.
- Note: `cluster search --deploy-type` supports shell completion (`configureClusterCommandCompletion` in `internal/cmd/completion.go`) and lists known `deploy_type_v2` values in help (`knownDeployTypeV2Values` in `internal/cmd/cluster.go`). Update the list in both places when the dashboard gains a deploy type.
- Note: `cluster search` and `cluster search-id` always send `show_deleted=true|false` (default `false`, so deleted clusters are excluded unless `--show-deleted` is set).
- Note: `cluster topology` supports dedicated detail payloads, premium/byoc tenant pools via `parent_id`, and resource-pool deploy types (for example `premium resource pool`) via the cluster ID itself.
- Note: `cluster search-id` can auto-create an env-local profile on first exact cluster-ID match and does not switch `active_profile`.

## data

- Source: `internal/cmd/data.go`
- Help metadata: `internal/cmd/data.go` (Cobra command builders and registered flags)
- Typical tests: `internal/cmd/data_test.go`

## metrics

- Source: `internal/cmd/metrics.go`
- Help metadata: `internal/cmd/metrics.go` (Cobra command builders, aliases, and registered flags)
- Typical tests: `internal/cmd/metrics_test.go`, `internal/cmd/time_parse_test.go`
- Note: `metrics query`, `metrics range`, and `metrics series` retry `504 Gateway Timeout` responses up to 3 times (4 attempts total) before returning the error.
- Note: `metrics {query|range|series} --pool` (or `-p`) is only valid for premium clusters with `parent_id`; it routes metric requests through the parent resource pool ID.
- Note: `metrics range` keeps the existing default data-proxy path (`/data-proxy/metrics/<target-id>/api/v1/query_range`) unless `--data-server`/`--ds` is set. `<target-id>` is the cluster ID by default, or `parent_id` when `--pool` is set for eligible premium clusters.
- Note: `metrics range --data-server`/`--ds` is opt-in only for this command; use it for node-level metric families (for example `node_*`). It sends `GET /clinic/api/v1/data/metrics` with `query/start/end/step` and optional `timeout` query params plus `X-OrgType`, `X-OrgID`, and `X-ClusterID` headers. `metrics query` and `metrics series` remain unchanged.
- Note: `metrics range --data-server` is incompatible with `--pool`; do not extend that flag combination without an explicit routing design.
- Note: `metrics range` defaults to `echarts` output (`go-echarts` HTML report, auto-open attempt in browser). `--output json`/`-o json` forces JSON, and `--output tui`/`-o tui` forces the terminal TUI and requires a terminal.
- Note: In `metrics range` ECharts output, the header shows `cluster id`, `cluster name`, `deploy type`, and the request `query`, and the displayed range/time labels use the local timezone.
- Note: In `metrics range` ECharts legend interactions, all series render by default; plain legend click focuses one series, clicking that same legend again restores all series, and Cmd/Ctrl + click allows additive multi-series selection.

## loki

- Source: `internal/cmd/loki.go`, with Starter/Essential route selection and datasource-catalog validation in `internal/cmd/loki_route.go`
- Help metadata: `internal/cmd/loki.go` (Cobra command builders and registered flags)
- Typical tests: `internal/cmd/loki_test.go`, `internal/cmd/time_parse_test.go`
- Note: `loki query` retries `504 Gateway Timeout` responses up to 3 times (4 attempts total) before returning the error.
- Note: `loki query` auto-injects missing `cluster_env` and `namespace` label matchers for selector-style queries, including `{}` content searches. Use `--skip-namespace-injection` to inject only `cluster_env`. Explicit scope labels warn by default and `--allow-explicit-scope` suppresses that warning for intentional raw/cross-profile or cross-namespace investigations.
- Note: Exact normalized `starter` and `essential` `loki query` requests refresh Dashboard metadata, require exactly one selector with a non-empty equality `cluster="..."` matcher, case-insensitively select exactly one provider/region system-log datasource, and use its regional `/logs/query-range` route. They inject `namespace="tidb-serverless"` unless namespace injection is skipped. Validation and catalog errors fail closed without logical-route fallback.
- Note: Essential V2, Essential V2 resource pool, Premium, BYOC, Dedicated, and all other deploy types retain the logical-cluster query route and selector behavior. `loki instance-map`, `loki labels`, `loki label-values`, and `diagnose` do not use the regional route.
- Note: Use `component` label filtering to separate shared-vs-unique resources instead of a Loki `--pool` flag.
- Note: `loki instance-map` reuses the same Loki request/retry path as `loki query` and returns deterministic rows mapping `node`→`loki_instance` with derived `ip`; output supports table (default) and JSON (`-o/--output` with `table|json`).

## diagnose

- Source: `internal/cmd/diagnose.go` plus focused helpers in `internal/cmd/diagnose_*.go`
- Help metadata: `internal/cmd/diagnose.go` (Cobra command builder and registered flags)
- Typical tests: `internal/cmd/diagnose_test.go`
- Note: `diagnose` is stateless evidence correlation only. It does not infer root cause, persist investigations, or register stateful subcommands in the MVP.
- Note: all `diagnose` output formats include the profile timezone plus the resolved query window in both local time and UTC.
- Note: output is built from the `diagnose.v2` bundle schema. `-o json` emits the full bundle (`schema_version`, `scope`, `query_plan`, `seed_matches`, `related_logs`, `events`, `topology`, `groups`, `timelines`, `summaries`, `warnings`).
- Note: default table output is a compact bundle summary (scope, seed/related totals, warning types, and group rows with kind/keyspace/cluster/components/counts/first-seen/last-seen) and omits raw log lines.
- Note: expansion controls are user-facing diagnose flags: `--no-expand`, `--max-seed-expand`, `--max-related-logs`.
- Note: if the seed Loki query fails after its retry policy, `diagnose` still collects independent topology and events sources where possible, writes a partial bundle with a failed `query_plan` entry and `query_error` warning, then returns the original seed-query error.

## events

- Source: `internal/cmd/events.go`
- Help metadata: `internal/cmd/events.go` (Cobra command builder and registered flags)
- Typical tests: `internal/cmd/events_test.go`
- Note: `events list` resolves the fallback range through `resolveRequiredRangeWithFallback` with a 7-day window (`defaultEventsRangeFallbackWindow`) instead of the 5-minute default used by `metrics range` and `loki query`; cluster activity events are low-frequency, so `--start now-7d --end now` is the default when both are unresolved from flag/env/profile.

## raw

- Source: `internal/cmd/raw.go`
- Help metadata: `internal/cmd/raw.go` (Cobra command builder and registered flags)
- Typical tests: `internal/cmd/raw_test.go`, `internal/cmd/json_format_test.go`

## Shared Command Infrastructure

- Root command graph: `internal/cmd/root.go` (Cobra persistent flags for `--env`, `--profile`, and `--verbose`)
- Shell completion wiring: `internal/cmd/completion.go` (script generation + dynamic completion for subcommands, env, and profile names)
- Cobra adapters, the shared help template, and error normalization: `internal/cmd/cobra_helpers.go`
- Shared time parser: `internal/cmd/time_parse.go` (datetime/epoch parsing) + `internal/timeexpr/timeexpr.go` (`now` and `now-<duration>` parsing, including `d` as a 24-hour day)
- Shared legend-label extraction: `internal/legendlabels/legendlabels.go` (remove common labels across all series and keep only differing label parts)
- JSON formatting and terminal color behavior:
  - `internal/cmd/json_format.go`
  - `internal/cmd/gojq_color_encoder.go`
- Runtime diagnostics and request tracing helpers:
  - `internal/cmd/diagnostics.go`
  - `internal/cmd/flag_env.go` (cluster/range source tracing)

## Update Checklist For Any Command Change

1. update command handler code,
2. update corresponding help metadata and registered flags,
3. add/adjust tests,
4. update README examples if user-facing behavior changed,
5. run `make verify`.
