feat(k8s): add k8s-diagnose for read-only workload triage

k8s-diagnose triages pods, probes, scheduling, storage and Service
endpoints under a view-only kubeconfig: one evidence command per
finding and a likely cause, never a fix applied. It stops with
"no cluster access" or the RBAC gap instead of looking for other
credentials, and accepts hand-offs from flux-diagnose.

k8s 0.2.0; the .gitkeep placeholder goes now that a skill exists.

Refs: #194

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_014uGZTNugst7K9Bd2FTR4Mi
This commit is contained in:
Defame1297andClaude Opus 5.5 committed 2026-11-24 20:34:48 +00:00
1 parent 2a6eea3db1
commit 277d6f5826
5 files changed
+172 -1

No files matched your search

View File
Whitespace-only changes.
@@ -0,0 +1,92 @@
---
name: k8s-diagnose
description: >
Use when a Kubernetes workload is unhealthy — pods not Ready, crash-looping or Pending — or
`flux-diagnose` hands over a pod problem. Read-only kubectl triage. Not Flux reconcile or
source status -> `flux-diagnose`. Not app code bugs -> `diagnose`.
compatibility: Requires kubectl and a kubeconfig the caller supplies, exported or as a path,
bound to the built-in view ClusterRole or a wider read-only role.
allowed-tools: Bash Read
metadata:
category: k8s
version: "0.1.0"
source_keys:
- adr-0032-action-tiers
- delivery-guard-kubectl-allowlist
---
## Gotchas
- `The connection to the server localhost:8080 was refused` means kubectl found no kubeconfig,
not that a cluster is down. Never pick credentials yourself: no `--kubeconfig`, `--context`,
`--as` or `--token`, no `kubectl config use-context`, no filesystem search.
- The `view` role reads no Secrets, nodes, PersistentVolumes or StorageClasses. A Forbidden there
is a gap to report, not a reason to retry another way.
- `describe`, `-o yaml` and logs print inline env values and whatever the app logs. Quote only the
lines that prove a finding and redact anything that looks like a credential.
## Command tiers
Run only the Read row. Anything else, listed or not, goes back to the caller as a
recommendation.
| Tier | Commands |
|---|---|
| Read | `kubectl auth can-i`, `api-resources`, `explain`; `get` and `describe` on any kind but Secrets (`-o wide`, `-o jsonpath`); `logs` (`--previous`, `--tail`, `-c`, `--all-containers`); `events --for`; `top pod` when the metrics API is served |
| Propose | None: the caller opens the fix PR |
| Apply-by-merge | The fix itself: a manifest change in the repo, applied by Flux after an approved merge |
| Odd job | None: `flux reconcile` is HITL-only |
| Never | `apply`, `create`, `delete`, `edit`, `patch`, `label`, `annotate`, `scale`, `set`, `rollout restart`, `rollout undo`, `cordon`, `drain`, `taint`, `exec`, `attach`, `port-forward`, `cp`, `debug`, `proxy`, live `diff`; `get secret -o …`, `describe secret`, `get --raw` on Secrets, `config view --raw` |
## Step 1 — Check access
No namespace given → stop and report `need a namespace`, so the caller can supply one; never
sweep `--all-namespaces`.
Run every command in the environment the caller gave. Given a kubeconfig path, prefix each command
with `KUBECONFIG=<path>`: an `export` does not carry between shell calls.
Run `kubectl auth can-i list pods -n <ns>`:
- `yes` → continue.
- `no` → stop and report `rbac gap: cannot list pods in <ns>`.
- Any connection, certificate or `Unauthorized` error, or no kubeconfig → stop and report
`no cluster access: <first line of the error>`.
A later Forbidden does not stop the run; record it under Gaps.
## Step 2 — Resolve the target to pods
- **Pod** → that pod.
- **Workload** (Deployment, StatefulSet, DaemonSet, Job) →
`kubectl describe <kind>/<name> -n <ns>`, then `kubectl get pods -n <ns> -l '<selector>' -o wide`
with `<selector>` copied verbatim from the describe output's `Selector:` line, never rebuilt
from `matchLabels`, which drops `matchExpressions`.
- **Namespace** → `kubectl get pods -n <ns> -o wide` and
`kubectl get deploy,sts,ds,job,pvc,svc -n <ns>`.
A pod is unhealthy when its phase is not `Running` or `Succeeded`, its READY count is short, or
its restart count is climbing. Target not found → a finding; if the repo should create it, Flux
likely never applied it: hand to `flux-diagnose`.
## Step 3 — Triage each unhealthy pod
If any pod is unhealthy, read `references/symptoms.md`: run its baseline commands on each
unhealthy pod, then follow its symptom row.
## Step 4 — Check storage and Services
If the target's scope holds a PVC or a Service, read `references/symptoms.md` Gotchas and
§Storage and Services: a PVC not `Bound` or a Service with no ready endpoints is a finding.
## Step 5 — Report
```text
k8s-diagnose: <target> in <ns> — <healthy|unhealthy|need a namespace|no cluster access|rbac gap>
- <finding> — evidence: `<command>`
Likely cause: <one line, or "undetermined">
Gaps: <Forbidden reads, missing metrics, or none>
```
Never apply a fix; name the manifest change for the caller's PR. When the
cause sits in the Flux layer, end with `hand to flux-diagnose: <Kustomization or HelmRelease>`.
@@ -0,0 +1,19 @@
# Sources
## adr-0032-action-tiers
- **URL:** (repo decision record — not a plugin research corpus entry)
- **Description:** The five action tiers (Read, Propose, Apply-by-merge, Odd job, Never), the `view`-ClusterRole kubeconfig that excludes Secrets, and the rule that every infrastructure change applies by approved merge. Grounds the tier table, the RBAC gaps, and "never apply a fix".
- **Research doc:** none — repo decision record, not a plugin research corpus entry
- **Basis:** docs/adr/0032-credentials-not-hooks-are-the-agent-safety-boundary.md
- **Contributing files:** SKILL.md, references/symptoms.md
- **Status:** `extracted`
## delivery-guard-kubectl-allowlist
- **URL:** (repo code — not a plugin research corpus entry)
- **Description:** The delivery guard hook's `kubectl` read-verb allowlist and its Secret denials (`get secret -o`, `get --raw` on Secrets, `config view --raw`, live `diff`). Every command the skill names stays inside it.
- **Research doc:** none — repo code, not a plugin research corpus entry
- **Basis:** plugins/delivery/.apm/hooks/guard.py
- **Contributing files:** SKILL.md, references/symptoms.md
- **Status:** `extracted`
@@ -0,0 +1,60 @@
---
source_keys:
- adr-0032-action-tiers
- delivery-guard-kubectl-allowlist
---
# Symptoms, evidence and likely causes
Every command here is Read tier. `<p>` is the pod, `<c>` the container, `<ns>` the namespace. Keep
log reads short: `--tail=50` unless the error is further back.
## Gotchas
- On a crash-looping pod, plain `kubectl logs` shows the fresh container, which has often printed
nothing yet. The crash is in `--previous`.
- Events expire (one hour by default), so "no events" does not mean nothing happened. A
container's `lastState` survives and is the durable record.
## Selectors
The `Selector:` line of `kubectl describe` on a workload already renders `matchExpressions` in
set-based form (`tier in (web,api)`, `!canary`). A selector rebuilt from `matchLabels` alone drops
those terms and matches too many pods, so copy the line verbatim.
## Baseline for every unhealthy pod
```bash
kubectl describe pod <p> -n <ns>
kubectl get pod <p> -n <ns> -o jsonpath='{range .status.initContainerStatuses[*]}init/{.name} ready={.ready} restarts={.restartCount} waiting={.state.waiting.reason} last={.lastState.terminated.reason} exit={.lastState.terminated.exitCode}{"\n"}{end}{range .status.containerStatuses[*]}{.name} ready={.ready} restarts={.restartCount} waiting={.state.waiting.reason} last={.lastState.terminated.reason} exit={.lastState.terminated.exitCode}{"\n"}{end}'
kubectl events -n <ns> --for pod/<p>
```
The second prints one status line per container. Its `waiting=` and `last=` reasons, with the
pod's phase and events, give the symptom.
## Pod and container symptoms
| Symptom | Evidence | Likely causes |
|---|---|---|
| `CrashLoopBackOff`, or `last=Error` | `kubectl logs <p> -n <ns> -c <c> --previous --tail=50`; the `exit=` code | exit 1 or 2: the app failed at start (bad config, missing dependency, failed migration). 126/127: command not executable or not found (wrong image or `command:`). 137: killed, see OOMKilled and Liveness kill rows. 143: SIGTERM, a stop the app did not survive |
| `last=OOMKilled` | `kubectl get pod <p> -n <ns> -o jsonpath='{.spec.containers[*].resources}'`; `kubectl top pod <p> -n <ns> --containers` if `kubectl api-resources --api-group=metrics.k8s.io` lists `pods` | Memory limit below the app's working set, or a leak (usage climbs across restarts) |
| Liveness kill: `Unhealthy` events saying `Liveness probe failed`, then restarts with exit 137 | `kubectl get pod <p> -n <ns> -o jsonpath='{.spec.containers[*].livenessProbe}'`; current `kubectl logs <p> -n <ns> -c <c> --tail=50` | Probe path or port does not match the app; `initialDelaySeconds` or `failureThreshold` shorter than the app's start time; app deadlocked |
| `Running` but not Ready: `Readiness probe failed` events | readiness probe spec as above; the container's `ports`; current logs | Probe path or port wrong; a dependency the readiness check calls is down |
| `ImagePullBackOff` or `ErrImagePull` | The `Failed` event's message; `kubectl get pod <p> -n <ns> -o jsonpath='{.spec.imagePullSecrets}'` (names only) | `not found` or `manifest unknown`: wrong image or tag. `unauthorized` or `pull access denied`: missing or wrong pull secret. `i/o timeout` or `dial tcp`: registry unreachable from the node |
| `CreateContainerConfigError` | The `Failed` event names the missing ConfigMap, Secret or key; `kubectl get configmap <name> -n <ns>` for a ConfigMap; `kubectl get sealedsecret <name> -n <ns>` then `kubectl describe sealedsecret <name> -n <ns>` when a SealedSecret should produce the Secret | Object not created yet, wrong name or key, or the SealedSecret failed to unseal (its status says why). Never try to read the Secret itself |
| `Init:…` (`Init:CrashLoopBackOff`, `Init:0/1` stuck) | `kubectl logs <p> -n <ns> -c <init-container> --previous --tail=50`, or without `--previous` while it is still running | The init container's own failure or wait, usually a dependency it polls |
| `Pending` | The `FailedScheduling` event message | `Insufficient cpu` or `memory`: requests exceed free capacity. `didn't match Pod's node affinity/selector`: selector or affinity names no node. `untolerated taint`: missing toleration. `unbound immediate PersistentVolumeClaims`: see Storage below. Node details are Forbidden under `view`; quote the message instead |
| `ContainerCreating` for minutes | `FailedMount`, `FailedAttachVolume` or `FailedCreatePodSandBox` events | Volume not attachable or still held by another node; a referenced ConfigMap or Secret volume missing; CNI fault on the node |
| `Evicted` or `Failed` with a node-pressure reason | `kubectl get pod <p> -n <ns> -o jsonpath='{.status.reason}: {.status.message}'` | Node ran short of memory or disk; the pod's requests are too low to protect it |
| Job failed: `BackoffLimitExceeded` | `kubectl describe job/<name> -n <ns>`; logs of its newest failed pod, with `--previous` if it restarted in place | The job's own error in those logs |
No row fits → report the container status line and the newest `Warning` events as findings, with
likely cause `undetermined`.
## Storage and Services
| Check | Evidence | Likely causes |
|---|---|---|
| PVC not `Bound` | `kubectl get pvc -n <ns>`; `kubectl describe pvc <name> -n <ns>` events | `WaitForFirstConsumer`: normal until a pod using it schedules, so look at that pod. `no persistent volumes available` or `storageclass … not found`: no matching class or volume. `ProvisioningFailed`: the provisioner's message says why. PersistentVolumes and StorageClasses are Forbidden under `view`; report that gap |
| Service with no ready endpoints | `kubectl get svc -n <ns>`; `kubectl get endpointslices -n <ns> -l kubernetes.io/service-name=<svc>`, falling back to `kubectl get endpoints <svc> -n <ns>` if EndpointSlices are Forbidden; `kubectl get svc <svc> -n <ns> -o jsonpath='{.spec.selector}'` against `kubectl get pods -n <ns> --show-labels` | Selector matches no pod labels; matching pods exist but none is Ready (triage those pods); `targetPort` names a port the container does not expose |
+1 -1
View File
@@ -1,5 +1,5 @@
name: k8s
version: 0.1.0
version: 0.2.0
description: Skills for read-only diagnosis of workloads on a Kubernetes cluster.
author:
name: Mortis