Skip to content

Commit 337756a

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. Signed-off-by: Felix Kästner <felix.kaestner@sap.com>
1 parent 7452de0 commit 337756a

2 files changed

Lines changed: 214 additions & 0 deletions

File tree

‎AGENTS.md‎

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

0 commit comments

Comments
 (0)