# CLUSTER-AGENT KNOWLEDGE BASE

## OVERVIEW
`cluster-agent` runs inside dataplane clusters and exposes a gRPC service plus HTTP gateway for cluster-side operations such as command execution, password reset and `cloud_admin` deletion, audit-log settings, restart flows, topology queries, and resource metrics.

## STRUCTURE
- `cmd/agent/`: entrypoint, config loading, internal gRPC server, and HTTP gateway startup.
- `service/`: API handlers for execution, restart, topology, audit-log, password, and metrics workflows.
- `internal/sqlexec/`: SQL execution abstraction and privileged/direct executors.
- `internal/utils/`: TiDB/pod address resolution helpers.
- `metrics/`: metrics-server client integration for resource metrics APIs.
- `crypto/`: encryption helpers for password-related flows.
- `mocks/`: generated test doubles.

## WHERE TO LOOK
| Task | Location | Notes |
|------|----------|-------|
| API endpoint behavior | `service/*.go` | Request validation and response handling |
| TiDB HTTP API flows | `service/common.go`, `service/reset_password.go`, `service/delete_cloud_admin.go` | V2 HTTP-first logic and fallback boundaries |
| SQL execution behavior | `internal/sqlexec/` | Read-only query interfaces and executor variants |
| Restart behavior | `service/restart*.go`, `service/node*.go`, `service/pod*.go` | K8s object selection and provider-specific restart hooks |
| Metrics/topology behavior | `service/resource_metrics.go`, `service/topology.go`, `metrics/` | metrics-server dependency and component inspection |
| Transport startup | `cmd/agent/grpc.go` and `cmd/agent/main.go` | internal gRPC + gin/gRPC-gateway lifecycle |
| Host/base URL validation | `service/common.go` | strict host/path/query constraints |

## COMMANDS
```bash
make build
make test
make unit
make lint
make lint-fix
make generate
make docker-build
```

## CONVENTIONS (LOCAL)
- `make build` uses `CGO_ENABLED=0` and outputs `bin/cluster-agent`.
- Host and URL validation is strict (`host must not include scheme/port`, base URL must not include path/query/fragment).
- Several write paths are intentionally layered: TiDB HTTP API first where available, then fallback to direct/privileged execution when required. Preserve that ordering unless the API contract changes.
- `internal/sqlexec` intentionally hides raw `*sql.Rows` behind interfaces; preserve that boundary when extending query paths.
- `mocks/kubeclient/rutimeclient.go` and other generated files must be regenerated, not manually edited.

## ANTI-PATTERNS
- Returning `(nil, nil)` TLS configs from executor hooks.
- Bypassing input validation in `service/common.go` for host/base URL parsing.
- Referring to a non-existent local proxy package or adding new behavior to docs without checking the actual module tree.
- Leaking `*sql.Rows` across package boundaries instead of using `sqlexec.Rows` abstractions.
- Editing generated mock files directly.
