Imported from mortezakarimi/k8s-mini-explorer (
AGENTS.md). Install upstream withnpx skills add mortezakarimi/k8s-mini-explorer. Copyright stays with the author.
1. System Design & Architectural Patterns
This document defines the architecture, design patterns, and engineering constraints for the Go Kubernetes Mini Explorer service. The application is built as a highly decoupled, lightweight utility designed to inspect resources within a local Minikube cluster.
Hexagonal Architecture (Ports and Adapters)
To ensure testability and compliance with golang-pro standards, the codebase must strictly isolate the HTTP transport layer from the Kubernetes API infrastructure logic.
- Driving Adapters (HTTP Layer): Handlers implemented using the Gin-Gonic (go-gin) framework. They parse HTTP requests, trigger domain behavior, and return structured JSON responses.
- Core Domain (Ports): Go interfaces defining the exact capabilities required by the application (e.g., PodLister, DeploymentInspector). The domain logic knows nothing about Gin or the raw client-go library.
- Driven Adapters (Infrastructure Layer): Concrete implementations of the domain interfaces that communicate directly with the Kubernetes API server using the official Go client.
Declarative API Documentation
- Swagger Annotation: API endpoints must be documented using declarative swag comments directly above the Gin handler functions.
- Dynamic UI Endpoint: The service must serve a compiled Swagger UI asset bundle natively at
/swagger/index.html, ensuring the API documentation updates dynamically based on code compilation.
Swagger Invariants (mandatory for every API change)
Every new or modified Gin handler must satisfy all of the following before the change is considered complete:
-
Annotations — place a swag godoc block directly above the handler function with:
@Summary,@Description,@Tags@Produce json@Routerusing the/api/v1/...path convention@Success 200 {object} models.<ResponseType>for every success response@Failure {code} {object} models.ErrorResponsefor every HTTP error status the handler can return (400,403,404,500, etc.)@Paramfor every path, query, or header parameter
-
Typed models — success and error JSON bodies must use structs from
internal/api/models/. Never returngin.Hor raw maps from handlers. -
Error envelope — all error responses use
models.ErrorResponse(code,message). Never expose raw Kubernetes API errors or stack traces. -
Regenerate docs — after any handler or model change, run
make swagger(orgo generate ./...) and commit the updateddocs/package. -
Route convention — all business and system APIs live under
/api/v1. Swagger UI is served at/swagger/*.
Planned routes and response models
| Route | Handler tag | Success model |
|---|---|---|
GET /api/v1/health |
system |
models.HealthResponse |
GET /api/v1/namespaces/{namespace}/pods |
pods |
[]models.Pod |
GET /api/v1/namespaces/{namespace}/deployments/{name} |
deployments |
models.DeploymentStatus |
GET /api/v1/namespaces/{namespace}/events |
events |
[]models.Event |
GET /api/v1/namespaces/{namespace}/services/{name}/health |
services |
models.ServiceHealth |
Handler annotation template
Copy and adapt this template for every new endpoint:
// <HandlerName> godoc
//
// @Summary Short summary
// @Description Longer description of behavior
// @Tags <pods|deployments|events|services|system>
// @Produce json
// @Param namespace path string true "Kubernetes namespace"
// @Success 200 {object} models.<ResponseType>
// @Failure 400 {object} models.ErrorResponse
// @Failure 403 {object} models.ErrorResponse
// @Failure 404 {object} models.ErrorResponse
// @Failure 500 {object} models.ErrorResponse
// @Router /api/v1/namespaces/{namespace}/pods [get]
func HandlerName(c *gin.Context) { ... }
2. Critical Engineering Concerns & Kubernetes Strategy
A. Minikube Cluster Connectivity & Lifecycle Management
The application must execute reliably against a local Minikube instance:
- Configuration Resolution: The infrastructure layer must dynamically look up the local system's environment. For Minikube execution, it must load configuration from the standard KUBECONFIG environment variable or fall back to the path ~/.kube/config. It must also preserve the fallback option for rest.InClusterConfig() to guarantee infrastructure flexibility.
- Context Propagation: Every Gin handler must extract the request context (c.Request.Context()) and explicitly pass it down through the service layer into the Kubernetes client-go method calls. If a client disconnects or times out, the context cancellation must propagate instantly to terminate the active upstream Kubernetes API server request, preventing memory and socket leakage.
B. Core Capabilities & Invariants
The underlying service implementation must cleanly satisfy the following requirements while transforming raw cluster entities into lean, readable JSON models:
- Pod Inspector: Fetch pods from a specified namespace, transforming raw structural types into a unified object capturing only Name, Status, and Age.
- Deployment Status Tracker: Calculate the state of target deployments, explicitly computing metrics for Total Replicas, Ready Replicas, and Unavailable Replicas.
- Namespace Event Stream: Retrieve the latest lifecycle and warning events from a targeted namespace for debugging execution flows.
- Service Health Check: Assess network routing configurations by identifying backing Endpoints and verifying the current running health status of all target pods associated with that service.
C. Resilient Error Handling
- The system must never return raw Kubernetes API server errors or internal stack traces to the API consumer.
- All infrastructure errors (such as StatusNotFound from missing namespaces or StatusForbidden due to local RBAC restrictions) must be handled gracefully. They must be mapped to explicit internal domain errors before being converted into standardized JSON error payloads accompanied by semantic HTTP status codes.
3. Quality Assurance & Golang Pro TDD Invariants
Test-Driven Development (TDD) Boundaries
The code must be developed using a strict TDD lifecycle—writing tests before implementation code—to achieve 100% test coverage across the business logic.
- Zero Live Cluster Reliance: Unit and integration tests must not connect to the live Minikube cluster.
- Fake Clientset Mocking: Tests must inject the official client-go/kubernetes/fake clientset package. The agent must pre-populate this fake in-memory cluster with mock Deployments, Pods, Services, and Endpoints before running test assertions against the Gin handlers.
- Concurrent Safety Validation: Since Gin handlers execute concurrently, all service dependencies and custom caching layers (if implemented) must be explicitly tested for race conditions using Go’s race detector (go test -race).