Skip to content

Commit 02c80be

Browse files
Add AGENTS.md
Add AGENTS.md with coding guidelines for AI agents covering project structure, constraints, workflows, API/controller/provider design, logging conventions, testing style, and references. Symlink CLAUDE.md to AGENTS.md as single source of truth. Pin KUBECTL in Makefile to --context kind-$(KIND_CLUSTER_NAME) so deploy targets always use the Kind cluster without mutating the global kubeconfig. Signed-off-by: Felix Kästner <felix.kaestner@sap.com>
1 parent 62dd4b2 commit 02c80be

3 files changed

Lines changed: 217 additions & 1 deletion

File tree

‎AGENTS.md‎

Lines changed: 215 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,215 @@
1+
# AI Agent Guide
2+
3+
## Rules (Quick Reference)
4+
5+
- NEVER edit auto-generated files (see project structure for which ones)
6+
- NEVER delete `// +kubebuilder:scaffold:*` markers — CLI injects code at these
7+
- NEVER move files — the CLI expects files in specific locations
8+
- NEVER create API/webhook files manually — use `kubebuilder create api` / `kubebuilder create webhook`
9+
10+
## Project Structure
11+
12+
```
13+
cmd/main.go Manager entry (registers controllers/webhooks)
14+
api/<group>/<version>/*_types.go CRD schemas by group
15+
api/<group>/<version>/zz_generated.* Auto-generated (DO NOT EDIT)
16+
internal/controller/<group>/* Reconciliation logic
17+
internal/webhook/<group>/<version>/* Validation/defaulting Webhooks
18+
config/crd/bases/* Generated CRDs (DO NOT EDIT)
19+
config/rbac/role.yaml Generated RBAC (DO NOT EDIT)
20+
config/samples/* Example CRs (edit these)
21+
Makefile Build/test/deploy commands
22+
PROJECT Kubebuilder metadata Auto-generated (DO NOT EDIT)
23+
```
24+
25+
## After Making Changes
26+
27+
**After editing `*_types.go` or markers:**
28+
29+
```bash
30+
make manifests # Regenerate CRDs/RBAC from markers
31+
make generate # Regenerate DeepCopy methods
32+
make charts # Regenerate Helm chart manifests
33+
```
34+
35+
**After editing any `*.go` files:**
36+
37+
```bash
38+
make fmt # Format code
39+
make lint # Lint code style
40+
make test # Run unit tests (uses envtest: real K8s API + etcd)
41+
```
42+
43+
Tests use **Ginkgo + Gomega** (BDD style) for controller and webhook tests — check `suite_test.go` in each package for setup.
44+
All other packages use the **standard library `testing` package** with table-driven tests where appropriate.
45+
46+
- Keep test files focused — only necessary cases, no exhaustive permutations
47+
- Test helpers stay in the same file as their tests
48+
49+
**All of `make fmt lint test` must pass before work is considered complete.**
50+
51+
## Commits
52+
53+
- Run `git log` first and match the existing commit style
54+
- Plain imperative mood, no semantic prefixes (no feat:/fix:/chore:)
55+
- Max 72 characters per line
56+
57+
## Development Workflow
58+
59+
Always run against a dedicated [Kind](https://kind.sigs.k8s.io/) cluster, not a real dev/prod cluster.
60+
The Makefile passes `--context kind-$(KIND_CLUSTER_NAME)` to all kubectl calls automatically — no need to switch context globally.
61+
62+
```bash
63+
# 1. Regenerate manifests
64+
make manifests generate
65+
66+
# 2. Create a kind cluster (if not already running)
67+
make kind-create
68+
69+
# 3. Build & Deploy (targets the kind cluster by default)
70+
export IMG=controller:<tag>
71+
make docker-build IMG=$IMG
72+
kind load docker-image $IMG --name network-operator
73+
make deploy IMG=$IMG
74+
75+
# 4. Test
76+
kubectl --context kind-network-operator apply -k config/samples/<resource>
77+
78+
# 5. Debug
79+
kubectl --context kind-network-operator logs -n network-operator-system deployment/network-operator-controller-manager -c manager -f
80+
```
81+
82+
## API Design
83+
84+
**Key markers for** `api/<group>/<version>/*_types.go`:
85+
86+
```go
87+
// +kubebuilder:object:root=true
88+
// +kubebuilder:subresource:status
89+
// +kubebuilder:resource:scope=Namespaced
90+
// +kubebuilder:printcolumn:name="Status",type=string,JSONPath=".status.conditions[?(@.type=='Ready')].status"
91+
92+
// On fields:
93+
// +kubebuilder:validation:Required
94+
// +kubebuilder:validation:Minimum=1
95+
// +kubebuilder:validation:MaxLength=100
96+
// +kubebuilder:validation:Pattern="^[a-z]+$"
97+
// +kubebuilder:default="value"
98+
```
99+
100+
- **Use** `metav1.Condition` for status (not custom string fields)
101+
- **Use predefined types**: `metav1.Time` instead of `string` for dates
102+
- **Follow K8s API conventions**: Standard field names (`spec`, `status`, `metadata`)
103+
104+
## Controller Design
105+
106+
**RBAC markers in** `internal/<group>/controller/*_controller.go`:
107+
108+
```go
109+
// +kubebuilder:rbac:groups=mygroup.example.com,resources=mykinds,verbs=get;list;watch;create;update;patch;delete
110+
// +kubebuilder:rbac:groups=mygroup.example.com,resources=mykinds/status,verbs=get;update;patch
111+
// +kubebuilder:rbac:groups=mygroup.example.com,resources=mykinds/finalizers,verbs=update
112+
// +kubebuilder:rbac:groups=events.k8s.io,resources=events,verbs=create;patch
113+
```
114+
115+
**Implementation rules:**
116+
117+
- **Idempotent reconciliation**: Safe to run multiple times
118+
- **Re-fetch before updates**: `r.Get(ctx, req.NamespacedName, obj)` before `r.Update` to avoid conflicts
119+
- **Structured logging**: `log := log.FromContext(ctx); log.Info("msg", "key", val)`
120+
- **Owner references**: Enable automatic garbage collection (`SetControllerReference`)
121+
- **Watch secondary resources**: Use `.Owns()` or `.Watches()`, not just `RequeueAfter`
122+
- **Finalizers**: Clean up external resources
123+
124+
## Provider Implementation
125+
126+
Provider implementations live in `internal/provider/<platform>/` and realize the API types as actual device configuration. Follow the `internal/provider/openconfig/` package as the reference implementation.
127+
128+
**File structure:**
129+
130+
- One `.go` file per API resource (e.g. `interface.go`, `banner.go`, `device.go`)
131+
- Each file contains: the provider interface implementation for that resource, plus all Go structs and helpers needed to realize it
132+
- Keep it simple — avoid many small few-line functions and abstractions that don't serve a real purpose (YAGNI)
133+
- Use string constants for any value used more than once — no raw string literals scattered across the code
134+
135+
**Idempotency is mandatory:**
136+
137+
A provider's `EnsureX` methods must be safe to call on every reconciliation without causing unnecessary device writes. After initial configuration, repeated calls must result in "configuration is already up to date" — no gNMI Set requests unless an actual drift exists.
138+
139+
The `gnmiext` package already implements a Get-and-Check approach: it diffs current device state against the desired configuration and only performs a gNMI Set when a real change is needed. This makes it safe for periodic reconciliation.
140+
141+
**Platform default values — critical pitfall:**
142+
143+
Optional fields in the API spec that map to optional fields in the provider Go struct require special handling:
144+
145+
1. If a field is unset in the API spec, the provider must adopt the platform's known default value in the struct (not leave it zero/empty)
146+
2. Only overwrite with the API spec value when explicitly set by the user
147+
3. This prevents false diffs: without this, the device returns its default → diff sees `"" != "default"` → unnecessary Set on every reconcile
148+
149+
**The `omitempty`/`omitzero` trap:**
150+
151+
Using `omitempty` or `omitzero` JSON struct tags on gNMI payload structs is dangerous for the same reason. An omitted field means "don't set this" in the gNMI payload, which is correct on first write. But on subsequent reconciles:
152+
153+
1. Device returns platform defaults for those fields in the Get response
154+
2. The desired struct has those fields empty/zero (omitted from serialization)
155+
3. Diff compares device state (with defaults) against desired (without) → mismatch
156+
4. Operator performs a Set on every reconcile — breaking idempotency
157+
158+
**Rule:** After setting configuration once, the provider must produce no gNMI Set calls on subsequent reconciles when no user-facing configuration has changed. Test this explicitly.
159+
160+
## Logging
161+
162+
**Follow Kubernetes logging message style guidelines:**
163+
164+
- Start from a capital letter
165+
- Do not end the message with a period
166+
- Active voice: subject present (`"Deployment could not create Pod"`) or omitted (`"Could not create Pod"`)
167+
- Past tense: `"Could not delete Pod"` not `"Cannot delete Pod"`
168+
- Specify object type: `"Deleted Pod"` not `"Deleted"`
169+
- Balanced key-value pairs
170+
171+
```go
172+
log.Info("Starting reconciliation")
173+
log.Info("Created Deployment", "name", deploy.Name)
174+
log.Error(err, "Failed to create Pod", "name", name)
175+
```
176+
177+
## Coding Philosophy
178+
179+
- **YAGNI** — don't build it until it's needed. No scaffolding "for later"
180+
- **Reuse before writing** — check if the codebase, stdlib, or an existing dependency already solves it
181+
- **No premature abstraction** — no interfaces with one implementation, no factories for a single entities, no config for a value that never changes
182+
- **Deletion over addition** — remove complexity rather than add code
183+
- **Fewest files, shortest diff** — the minimal change that solves the problem wins
184+
- **Fix root causes** — fix bugs where all callers converge, not in each caller
185+
- **Edge-case correctness** — between two approaches of similar size, pick the one correct on edge cases
186+
- **Don't over-comment** — don't document trivial steps; avoid unnecessary empty lines between code segments
187+
188+
## References
189+
190+
### Go Style
191+
192+
- **Effective Go**: https://go.dev/doc/effective_go (idiomatic Go patterns and design)
193+
- **Go Code Review Comments**: https://go.dev/wiki/CodeReviewComments (common review feedback, naming, error handling)
194+
- **Google Go Style Guide**: https://google.github.io/styleguide/go/guide (naming, formatting, conventions)
195+
- **Google Go Best Practices**: https://google.github.io/styleguide/go/best-practices (patterns, error handling, design)
196+
197+
### Essential Reading
198+
199+
- **Kubebuilder Book**: https://book.kubebuilder.io (comprehensive guide)
200+
- **controller-runtime FAQ**: https://github.com/kubernetes-sigs/controller-runtime/blob/main/FAQ.md (common patterns and questions)
201+
- **Good Practices**: https://book.kubebuilder.io/reference/good-practices.html (why reconciliation is idempotent, status conditions, etc.)
202+
- **Logging Conventions**: https://github.com/kubernetes/community/blob/main/contributors/devel/sig-instrumentation/logging.md#message-style-guidelines (message style, verbosity levels)
203+
204+
### API Design & Implementation
205+
206+
- **API Conventions**: https://github.com/kubernetes/community/blob/main/contributors/devel/sig-architecture/api-conventions.md
207+
- **API Changes:** https://github.com/kubernetes/community/blob/main/contributors/devel/sig-architecture/api_changes.md#adding-a-field
208+
- **Operator Pattern**: https://kubernetes.io/docs/concepts/extend-kubernetes/operator/
209+
- **Markers Reference**: https://book.kubebuilder.io/reference/markers.html
210+
211+
### Tools & Libraries
212+
213+
- **controller-runtime**: https://github.com/kubernetes-sigs/controller-runtime
214+
- **controller-tools**: https://github.com/kubernetes-sigs/controller-tools
215+
- **Kubebuilder Repo**: https://github.com/kubernetes-sigs/kubebuilder

‎CLAUDE.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
AGENTS.md

‎Makefile‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -250,7 +250,7 @@ $(LOCALBIN):
250250
CURL_RETRIES=3
251251

252252
## Tool Binaries
253-
KUBECTL ?= kubectl
253+
KUBECTL ?= kubectl --context kind-$(KIND_CLUSTER_NAME)
254254
KIND ?= $(LOCALBIN)/kind
255255
KUSTOMIZE ?= $(LOCALBIN)/kustomize
256256
CONTROLLER_GEN ?= $(LOCALBIN)/controller-gen

0 commit comments

Comments
 (0)