diff --git a/plugins/gitops/.apm/skills/flux-diagnose/SKILL.md b/plugins/gitops/.apm/skills/flux-diagnose/SKILL.md new file mode 100644 index 0000000..68a520f --- /dev/null +++ b/plugins/gitops/.apm/skills/flux-diagnose/SKILL.md @@ -0,0 +1,78 @@ +--- +name: flux-diagnose +description: > + Use when checking live Flux reconcile state, whether a commit is applied, or why a Flux + object fails. Not Flux concepts or YAML -> `gitops-knowledge`. Not repo files -> + `gitops-repo-audit`. Not pods -> `k8s-diagnose`. Not app code bugs -> `diagnose`. +compatibility: Requires the flux and kubectl CLIs and a kubeconfig from the session or the caller + with read access to Flux resources (the built-in view ClusterRole plus Flux's flux-view + aggregation). +allowed-tools: Bash Read +metadata: + category: gitops + version: "0.1.0" + source_keys: + - adr-0032-action-tiers + - delivery-guard-flux-allowlist +--- + +## Gotchas + +- A Kustomization that applied a HelmRelease object has not upgraded the release. The Helm + upgrade is a separate, later reconcile by helm-controller. +- Never pick credentials yourself: no `--kubeconfig`, `--context` or `--server` flag, no + `kubectl config use-context`, no reading `~/.kube` or a repo's credential paths. + +## Step 1 — Cluster access gate + +Run every command in the caller's environment. Given a kubeconfig path, prefix each command +with `KUBECONFIG=`, since each shell call starts fresh; command forms below omit it. + +Run `flux get kustomizations -A` with no connection flags. Then: + +- No kubeconfig, connection refused, timeout, `Unauthorized`, or a TLS error → return + `no cluster access: ` and stop. +- `forbidden` on Flux kinds → return `no Flux read access: ` and stop. +- Kind not found (`no matches for kind`) → return `Flux not installed on this cluster` and stop. +- Rows print → keep them; every flow starts from this read. + +## Step 2 — Tiers + +Run only the Read rows, even when a fix is one command away: `flux reconcile`, `suspend` and +`resume` look harmless but change what the cluster does. Anything else, listed or not, goes back +to the caller as a recommendation. + +| Command | Tier | Use | +|---|---|---| +| `flux get [name] [-A] [--status-selector ready=false] [--show-source]` | Read | status of sources, Kustomizations, HelmReleases | +| `flux events --for / -n [--types warning]` | Read | recent controller events | +| `flux logs --kind --name -n --level error --since ` | Read | controller errors for one object | +| `flux tree kustomization -n [--compact]` | Read | what a Kustomization manages | +| `flux trace -n ` | Read | which Flux object and revision owns a workload | +| `flux stats -A` | Read | cluster-wide counts of failing and suspended objects | +| `flux check` | Read | controller health; not `--pre` | +| `kubectl get -n -o jsonpath=…` | Read | exact status fields | +| `kubectl wait / -n --for=jsonpath=… --timeout=60s` | Read | the bounded pause between polls | +| `kubectl config current-context` | Read | the context name for the report; never switch it | +| `flux build kustomization --path --kustomization-file --dry-run` | Read | offline build-failure repro | +| `rtk git fetch`; `rtk git merge-base --is-ancestor` | Read | revision ancestry | +| none | Propose, Apply-by-merge | fixes go back to the caller as findings | +| `flux reconcile` | Odd job | not used by this skill; name it as a human's option | +| `flux suspend/resume/create/delete/install/bootstrap`, live `flux diff`, `flux export --with-credentials`, `flux debug --show-values/--show-vars`, any Secret read | Never | — | + +## Step 3 — Dispatch + +| Condition | Flow | Reference | +|---|---|---| +| Caller wants the state of Flux objects, cluster-wide or named | Status | `references/status.md` | +| Caller gives a Kustomization and a commit SHA and asks whether it is applied | Applied check | `references/applied-check.md` | +| Caller names a failing object or symptom and asks why | Diagnose | `references/diagnose.md` | + +Read only the matching reference; each is self-contained with its own output format. + +## Step 4 — Hand off + +When the chain ends at a workload (a stuck Deployment, failing pods, a failed Helm test, a health +check naming a workload), stop walking. Return the Flux finding with the +workload's kind, namespace and name, and route the rest to `k8s-diagnose`. Never chase pod logs or +node state from this skill. diff --git a/plugins/gitops/.apm/skills/flux-diagnose/references/applied-check.md b/plugins/gitops/.apm/skills/flux-diagnose/references/applied-check.md new file mode 100644 index 0000000..aef6ee7 --- /dev/null +++ b/plugins/gitops/.apm/skills/flux-diagnose/references/applied-check.md @@ -0,0 +1,134 @@ +--- +source_keys: + - adr-0032-action-tiers + - delivery-guard-flux-allowlist +--- + +# Applied check flow + +Answer one question: has this Kustomization applied this commit? Read tier only; every command +here is in the `SKILL.md` tier table. + +## Inputs + +- Kustomization name and namespace. No namespace given → `flux-system`, and say so in the output. +- Target commit: a full 40-character SHA. Given a short SHA or a branch name, return + `unverifiable: need a full commit SHA` and stop; do not resolve it yourself. +- Wait cap: the caller passes a cap in minutes. It counts 60-second pauses, not wall-clock + time, so a cap of N allows at most N pauses. No cap given → read once and + return; never invent a wait. +- HelmReleases, optional: a list of `/`. Given → check only those. Not given → check + only the HelmReleases this Kustomization applies itself (step 3). +- Kubeconfig path, optional: given → prefix every command below with `KUBECONFIG=`. + +## 1 — Read the Kustomization + +Run exactly, substituting name and namespace, behind the `KUBECONFIG=` prefix when given: + +```bash +kubectl get kustomization -n -o jsonpath='{.spec.suspend}{"|"}{.spec.sourceRef.kind}{"|"}{.spec.sourceRef.namespace}{"|"}{.spec.sourceRef.name}{"|"}{.status.lastAppliedRevision}{"|"}{.status.lastAttemptedRevision}{"|"}{.status.conditions[?(@.type=="Ready")].status}{"|"}{.status.conditions[?(@.type=="Ready")].reason}{"\n"}' +``` + +An empty source namespace means the Kustomization's own namespace. + +Gates, in order: + +- `suspend` is `true` → verdict `suspended`. Stop; never resume it. +- Source kind is not `GitRepository` → verdict `unverifiable: source is ; its revision + carries no commit SHA`. Stop. + +## 2 — Extract SHAs + +A Git revision reads `@sha1:`, or `sha1:` when the source pins a commit. +Flux before 2.0 wrote `/`. Take the 40-hex SHA after `sha1:`, or after the last `/` +for the legacy form. Compare full SHAs only. + +## 3 — Classify + +"At or past the target" means the SHA equals the target, or the target is its ancestor. Test +ancestry in the repo checkout with `rtk git merge-base --is-ancestor `; the exit +code is the answer. Exit 0 → at or past; exit 1 → not. Exit 128 (unknown +commit) → `rtk git fetch` once and retry; still 128 → `unknown: not in local history`. + +First match wins: + +1. Applied SHA at or past the target → `applied`, whatever Ready says now. Applied SHA past the + target → note `superseded by `. Attempted SHA differs from the applied one and + Ready is `False` → note `later revision failing`; that failure belongs to the + later revision, never to this target. +2. Attempted SHA at or past the target, Ready `False` → `failed`: the target is not applied and + the attempt carrying it fails. Record the Ready reason and the failing HelmReleases (below), + then read `references/diagnose.md` and follow it from its step 3 for this Kustomization. +3. Attempted SHA at or past the target, Ready `Unknown` → `pending: reconciling`. +4. Ready reason `DependencyNotReady` → `pending: waiting on dependency`; name the `dependsOn` + objects from `flux get ks -n `'s message. +5. Read the source with `flux get sources git -n `. Source revision not + at or past the target and READY `False` → `failed` at the source, since the target cannot + arrive; diagnose as in rule 2. Source revision not at or past the target → `pending: source has + not fetched the commit`. Otherwise → `pending: queued for the next reconcile`. + +On `applied`, check the HelmReleases: the caller's list, or else the HelmRelease entries of this +Kustomization's own inventory, read with +`kubectl get kustomization -n -o jsonpath='{.status.inventory.entries[*].id}'` +(an id reads `_
_helm.toolkit.fluxcd.io_HelmRelease`). Never widen to `flux tree` of a +root Kustomization: it spans the whole cluster, and an unrelated failing release would block a +commit that never touched it. For each release read +`kubectl get helmrelease
-n -o jsonpath='{.metadata.generation}{"|"}{.status.observedGeneration}{"|"}{.status.conditions[?(@.type=="Ready")].status}{"|"}{.status.conditions[?(@.type=="Ready")].reason}{"\n"}'`. +Observed generation behind generation, or Ready `Unknown` → verdict becomes +`pending: helm upgrade in progress`. Ready `False` at the current generation → verdict becomes `failed`, naming the release. +A release failing since before this commit is still reported; attributing it is the caller's job. + +On `failed` by rule 2, read the same releases and name each Ready `False` on the HelmReleases +line. A Kustomization with `wait: true` or `healthChecks` whose health check on a release fails is +believed, not confirmed, to keep the applied revision at the previous commit, so that release is +the failure's likely cause. + +## 4 — Poll, only with a cap and a `pending` verdict + +Each round makes exactly one pause, and every pause counts toward the cap, even one that returns +early. Pause on the object the verdict waits for. + +Kustomization pending: + +```bash +kubectl wait kustomization/ -n --for=jsonpath='{.status.lastAppliedRevision}'= --timeout=60s +``` + +`` is the target in the form of the current revision: `@sha1:`, where `` is +the text before `@` in the attempted revision, or `sha1:` for a source pinned to a commit. + +HelmRelease pending, observed generation behind the `metadata.generation` read this round: + +```bash +kubectl wait helmrelease/
-n --for=jsonpath='{.status.observedGeneration}'= --timeout=60s +``` + +HelmRelease pending, observed generation already equal and Ready `Unknown`: + +```bash +kubectl wait helmrelease/
-n --for=jsonpath='{.status.conditions[?(@.type=="Ready")].status}'=True --timeout=60s +``` + +Waiting on the generation there would return at once and spend a pause without waiting. Never +pause with `--for=condition=Ready` while the generation is behind: a release still Ready at its +old generation satisfies it before helm-controller has seen the new spec. + +A non-zero exit on timeout is the normal end of a pause, not an error. After every pause, repeat +steps 1–3. + +Stop polling on any verdict other than `pending`, or once the pause count reaches the cap. At the +cap, return the last `pending` verdict as it stands. Never extend the cap, and never +`flux reconcile` to hurry it; that is an odd job for a human. + +## Output + +```text +Kustomization: / Target: Verdict: +Applied: Attempted: Ready: +Source: / at , Ready +HelmReleases: , … | none +Pauses: of | not polled +Note: failing, defaulted namespace, or empty> +``` + +On `failed`, append the diagnosis output from `references/diagnose.md` below these lines. diff --git a/plugins/gitops/.apm/skills/flux-diagnose/references/diagnose.md b/plugins/gitops/.apm/skills/flux-diagnose/references/diagnose.md new file mode 100644 index 0000000..7812262 --- /dev/null +++ b/plugins/gitops/.apm/skills/flux-diagnose/references/diagnose.md @@ -0,0 +1,78 @@ +--- +source_keys: + - adr-0032-action-tiers + - delivery-guard-flux-allowlist +--- + +# Diagnose flow + +Find why a Flux object is failing, walking the dependency chain from source to Kustomization to +HelmRelease. Read tier only; every command here is in the `SKILL.md` tier table. + +## 1 — Find the object + +- Given a Flux object (source, Kustomization, HelmRelease) → start from it. +- Given a workload or other Kubernetes object → `flux trace -n ` names the + Kustomization or HelmRelease that owns it and the source revision; start from that owner. Not + Flux-managed → say so and stop. +- Given only a symptom ("Flux is stuck") → `flux get all -A --status-selector ready=false`; take + every failing object as a candidate. + +## 2 — Rule out the controllers + +Run `flux stats -A`. When most objects are failing, or nothing has reconciled for longer than its +interval, run `flux check`. A controller reported not ready ends the walk: the finding is the +controller, handed off as a workload in `flux-system`. If `flux check` itself returns `forbidden`, +report controller health as unknown and continue. + +## 3 — Walk upstream first + +The chain is: source (`GitRepository`, `OCIRepository`, `HelmRepository`, `HelmChart`, `Bucket`) → +`Kustomization` → `HelmRelease`, plus every `dependsOn` edge. Downstream objects fail as a symptom +of an upstream one (`ArtifactFailed`, `DependencyNotReady`), so diagnose the most upstream failing +object and treat the rest as consequences. + +For each object on the path, read in this order and stop once the cause is clear: + +1. `flux get -n ` — Ready, revision and message. +2. `flux events --for / -n --types warning`. +3. `flux logs --kind --name -n --level error --since 1h`. + +A `HelmRelease`'s upstream is its chart: the `HelmChart` (from a `HelmRepository`) or the +`OCIRepository` named in `spec.chartRef`. + +## 4 — Read the reason + +| Kind | Ready reason or message | Meaning | Next | +|---|---|---|---| +| source | authentication or `secretRef` error | credentials rejected or missing | name the `secretRef` only, never read it; human fixes the Secret | +| source | fetch, clone or timeout error | remote unreachable or ref missing | check the ref exists in the repo; report | +| Kustomization | `ArtifactFailed` | source artifact unavailable | walk to the source | +| Kustomization | `DependencyNotReady` | a `dependsOn` object is not Ready | walk to that object | +| Kustomization | `BuildFailed` | kustomize build failed on the repo content | repo fix by PR; reproduce offline with `flux build kustomization --path --kustomization-file --dry-run` | +| Kustomization | `ReconciliationFailed` | apply rejected: schema, immutable field, missing CRD or namespace, decryption | repo fix by PR, or a human for an immutable field | +| Kustomization | `HealthCheckFailed` | applied, but a workload never became ready | hand the named workload to `k8s-diagnose` | +| Kustomization | `PruneFailed` | garbage collection was refused | report the object named in the message | +| HelmRelease | `ArtifactFailed`, chart not ready | chart unavailable | walk to the chart source | +| HelmRelease | `InstallFailed`, `UpgradeFailed` | Helm action failed or timed out waiting | read the message; workload not ready → `k8s-diagnose` | +| HelmRelease | `TestFailed` | a Helm test pod failed | hand the test pod to `k8s-diagnose` | +| HelmRelease | `RollbackSucceeded` and others after remediation | the upgrade failed and was undone | report the original failure from events | +| HelmRelease | Stalled, retries exhausted | the controller stopped retrying | a fixing commit or a human odd job resumes it | + +A message this table does not cover: quote its first line and the events that match it, and say +the cause is unclassified. Do not guess. + +## 5 — Return + +Output format: + +```text +Root cause: / — : +| Step | Kind | Namespace/Name | Ready | Reason | Finding | +Next: () | k8s-diagnose on / +``` + +One row per object walked, upstream first. `Next` names one action and its tier from the +`SKILL.md` table: a repo change is Apply-by-merge, `flux reconcile` is an odd job for a human, and +a workload fault routes to `k8s-diagnose`. Never paste Secret data, Helm values or full log text; +quote one line. diff --git a/plugins/gitops/.apm/skills/flux-diagnose/references/sources.md b/plugins/gitops/.apm/skills/flux-diagnose/references/sources.md new file mode 100644 index 0000000..8aa4cd9 --- /dev/null +++ b/plugins/gitops/.apm/skills/flux-diagnose/references/sources.md @@ -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 access gate, 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/applied-check.md, references/diagnose.md, references/status.md +- **Status:** `extracted` + +## delivery-guard-flux-allowlist + +- **URL:** (repo code — not a plugin research corpus entry) +- **Description:** The delivery guard hook's `flux` read-verb allowlist and its denials (`flux debug --show-values/--show-vars`, `flux export --with-credentials`, live `flux diff`, every mutating verb), its `ask` on `flux reconcile`, and the `kubectl` read verbs including `wait`. 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/applied-check.md, references/diagnose.md +- **Status:** `extracted` diff --git a/plugins/gitops/.apm/skills/flux-diagnose/references/status.md b/plugins/gitops/.apm/skills/flux-diagnose/references/status.md new file mode 100644 index 0000000..3135963 --- /dev/null +++ b/plugins/gitops/.apm/skills/flux-diagnose/references/status.md @@ -0,0 +1,51 @@ +--- +source_keys: + - adr-0032-action-tiers +--- + +# Status flow + +Report the reconcile state of Flux objects. Read tier only; every command here is in the +`SKILL.md` tier table. + +## 1 — Read + +Every `flux` command defaults to the `flux-system` namespace. Pass `-A` for a cluster-wide read, +or `-n ` for a named object; never trust the default. + +- Cluster-wide: `flux get sources all -A`, then `flux get kustomizations -A` (already read by the + access gate), then `flux get helmreleases -A`. Add `flux stats -A` for the totals line. +- Named objects: `flux get -n `, for example `flux get ks apps -n flux-system`. +- Failing only, when the caller asks "what's broken": add `--status-selector ready=false` to each + `flux get`. + +## 2 — Classify each object + +| State | Rule | +|---|---| +| `ready` | READY `True` | +| `failing` | READY `False` | +| `progressing` | READY `Unknown`, or the message says reconciliation is in progress | +| `suspended` | SUSPENDED `True`, whatever READY says; its status is frozen and stale | +| `stale` | READY `True`, but a Kustomization's revision is behind its source's revision | + +`stale` needs both rows: compare the Kustomization's REVISION with its source's REVISION (the +source is shown by `flux get ks -n --show-source`). A gap that persists past the +Kustomization's interval means it is waiting on a `dependsOn` object or is not being reconciled. + +## 3 — Return + +Output format: + +```text +Cluster: Ready: Failing: Suspended: Stale: +| Kind | Namespace/Name | State | Revision | Message | +``` + +One row per object; for a cluster-wide read, list only rows not `ready` and give `ready` as a +count. `Message` is the controller's message cut to one line; never paste events or logs here. +Get the context name with `kubectl config current-context`, which reads the name only. + +A `failing` or `stale` row is a finding, not a diagnosis. Say which object is most upstream (a +source before the Kustomizations that use it) and stop; the caller re-invokes the skill to +diagnose it. diff --git a/plugins/gitops/apm.yml b/plugins/gitops/apm.yml index afcc8b9..923856a 100644 --- a/plugins/gitops/apm.yml +++ b/plugins/gitops/apm.yml @@ -1,6 +1,6 @@ name: gitops -version: 0.1.0 -description: Skills for authoring, auditing and diagnosing a Flux GitOps repository, including the secrets sealed into it. +version: 0.2.0 +description: Skills for authoring, auditing and diagnosing a Flux GitOps repository, including the secrets sealed into it, and for reading live Flux reconcile state on a cluster. author: name: Mortis url: https://git.rkdr.net/Mortis/