Architecture
Caproni is a general-purpose CLI for orchestrating local Kubernetes development environments.
It is a deployment orchestrator, not a configuration generator: it points Helm at charts,
passes values files through, and sequences the workflow. Helm is the sole source of truth for
application configuration. Caproni knows nothing about GitLab, webservice, gitaly, or any other
specific application.
Goal: close the gap between local development and production Kubernetes by composing
open, standard cloud-native tools (Helm, Kubernetes, mirrord, Skaffold, k3d, Colima) rather
than inventing proprietary abstractions. The plugin registry pattern means new tools and
workflows can be added without changing the core.
Lesson from
GDK:
tight coupling to a single application turns a developer tool into a
maintenance burden for every feature team. Caproni deliberately avoids that path — every
design decision is evaluated against whether it would work for a team unrelated to GitLab.
Test question for every feature: “Could the Switchboard team use this feature without modification?”
If no, redesign.
Related documentation
| File | Covers |
|---|
AGENTS.md | Development conventions, mock generation, commit rules |
docs/design/*.md | Per-feature design documents |
docs/configuration.md | Full configuration reference |
.gitlab/duo/mr-review-instructions.yaml | Code review standards |
Non-negotiable design rules
Application-agnostic. No hardcoded resource names, namespaces, or secrets. All
application-specific knowledge lives in caproni.yaml.
Config in caproni.yaml, not env vars. os.Getenv() is never used for application
config. Env vars bypass schema validation, discovery, and caproni config migrate.
Exception: meta-config that controls which config file to load.
Helm-first. Caproni must not become a fourth configuration system alongside Omnibus,
Helm Charts, and GDK. It does not generate manifests, template application config, or
translate between formats.
No business logic in cmd/. cmd/ packages wire CLI flags to internal/ calls.
Logic that belongs in cmd/ is untestable without the CLI framework.
No global state. Dependencies flow through constructors. Constructors panic on nil
dependencies (fail-fast, not silent NPE later).
What caproni up does
1. Generate per-profile dev CA (internal/pki)
2. Verify create-time settings (cluster.Verify over the driver's Checks(), NeedProfile)
3. Start the local cluster (internal/cluster + driver)
4. Wait for the cluster API (kubectl.WithReadiness polls /readyz)
5. Verify every setting, apply fixes (cluster.Verify at NeedAPI, then up's policy)
6. Clone git repos for edit-mode (internal/update)
7. Reload config (picks up caproni-project.yaml from freshly-cloned repos)
8. Run edit_mode_prepare hooks (internal/lifecyclehooks)
9. Deploy all deployers (internal/deploy Orchestrator, topological sort on `needs`)
caproni run follows with the reloaders (mirrord, Skaffold).
Cluster verification. Start creates or resumes the cluster; it never compares settings. A
driver declares the settings it can compare as cluster.Check values, each with what applying the
configured value costs (Remedy: in place, restart, recreate) and what the observation needs
(Need: the profile, a running cluster, the API). cluster.Verify runs the checks a caller can
satisfy and hands back plain Mismatch data. The policy lives in cmd/up: before Start it runs
the profile-level checks, skipping restart-class ones on a stopped cluster; after the readiness wait
it runs everything, applies the in-place fixes drivers provide, warns about log-only differences,
and fails on the rest with the hint for their remedy. See internal/cluster/README.md.
Cluster verification in doctor. caproni doctor runs the cluster driver’s checks
(cluster.Verify over Checks(), see internal/cluster/README.md) in any cluster state and only
reports: one warning per difference with what applies the configured value, one per setting it
could not read. It never runs a fix.
Directory map
cmd/ CLI commands — flag parsing, context extraction, delegation only
factory.go Wiring: before/after hooks, anonymous imports that trigger init()
internal/
backends/{git,helm,kubectl,hosts,docker,kustomize}/
Stateless wrappers around CLI tools; each has interface.go + client.go + mocks/
deployer/ Manager interface + registry; implementations: helm/, kustomize/, namespace/
reloader/ Manager interface + registry; implementations: mirror/ (mirrord), skaffold/
cluster/ Manager interface + registry; drivers: k3d/, colima/, auto/, external/, vcluster/
deploy/ Orchestrator: sequences deployers via topological sort on `needs` graph
diagnostics/ Automated diagnostics for self-serve troubleshooting
config/ Two-level config system (see below)
executor/ CommandRunner interface — the single CLI execution abstraction
kubeconfig/ Materializes kubeconfig YAML into a temp file for injection
pki/ Per-profile dev CA generation and loading
update/ Git repository update strategies (clone-only, pull)
lifecyclehooks/ edit_mode_prepare / edit_mode_start / edit_mode_stop
variables/ Variable resolver: expands ${VAR} across the config tree
infra/assets/ Embedded Kustomize overlays: builtin:dev-ca, builtin:traefik-tlsstore
naming/ Profile name resolution (static hash, directory name)
registrycache/ Local zot OCI registry cache
schema/config.v2.schema.json JSON schema for caproni.yaml (validated at config load time)
examples/ Educational only — not production configs
Core patterns
1. Stateless backends + stateful managers
Backends are thin, stateless wrappers around external tools. Managers orchestrate workflows
and hold state; they never call CLI tools directly.
internal/backends/{tool}/
├── interface.go Backend interface
├── client.go Implementation
└── mocks/ mockery-generated mocks + for_testing_only.go guard
This is the architectural boundary that makes unit testing possible: inject a mock backend,
test the manager’s logic without running real CLI commands.
Never let a manager import a concrete backend type — only the interface.
2. Plugin registries + init() bootstrap
All three domains (deployer, reloader, cluster) use the same registry shape: a
map[string]FactoryFunc with Register, NewManager, and ListTypes.
Implementations register in init():
// internal/deployer/helm/manager.go
func init() {
deployer.Register("helm", func(kubeconfig string) deployer.Manager {
exec := executor.NewClient()
return NewManager(helm.NewClient(exec), kubeconfig)
})
}
cmd/factory.go triggers all registrations with blank imports:
_ "gitlab.com/.../internal/deployer/helm"
_ "gitlab.com/.../internal/deployer/kustomize"
_ "gitlab.com/.../internal/reloader/mirror"
_ "gitlab.com/.../internal/cluster/auto" // auto also imports colima and k3d
3. Conditionals behind the interface (Strategy pattern)
Platform selection belongs inside an implementation, not in callers:
// internal/cluster/auto — the only place runtime.GOOS appears
func init() {
cluster.Register("auto", func(cfg types.ClusterConfig, profileName string) cluster.Manager {
if runtime.GOOS == "linux" {
return k3d.NewDriver(cfg, profileName)
}
return colima.NewDriver(cfg, profileName)
})
}
Callers use cluster.NewManager(cfg, profileName) with cfg.Driver = "auto" and never
branch on OS themselves.
4. Virtual kubeconfig
Caproni never reads from ~/.kube/config. The internal/kubeconfig/ package materializes
a kubeconfig YAML string (from the cluster driver’s GetKubeconfig) into a short-lived
temp file:
kc, _ := kubeconfig.Create(kubeconfigYAML)
defer kc.Close()
// kc.Environ() returns KUBECONFIG=<tempfile>, KUBECACHEDIR=...
All backends (helm, kubectl) and lifecycle hooks receive kc.Environ(). This isolates
Caproni’s clusters from the user’s global kubeconfig and makes concurrent operations safe.
No cluster driver may write to ~/.kube/config either, which is why the colima driver
passes --activate=false and the k3d driver --kubeconfig-update-default=false.
The one sanctioned exception is caproni set-kube-context, which merges the cluster into
the user’s kubeconfig under a profile-derived context name. It is a command the user runs
deliberately, never something a Caproni workflow does on their behalf.
5. Executor abstraction
Every shell invocation goes through executor.CommandRunner. This makes backends mockable
without shelling out, and enables the mise decorator (wraps commands through mise exec
for tool version pinning). No backend calls exec.Command directly.
Backends and drivers get the runner from the context with executor.FromContext(ctx) instead of
holding it in a field. FromContext panics if no runner is on the context, so tests must attach
the mock first with ctx = executor.WithContext(ctx, mockExec).
6. Infrastructure services as ordinary deployers
Cluster-wide services (cert-manager, ingress controller, the dev CA) are declared by the
rig as regular deployers — not composed by Caproni. Caproni embeds two Kustomize overlays
reachable via builtin: paths:
builtin:dev-ca — dev CA Secret, ClusterIssuer, trust Bundle, wildcard Certificatebuiltin:traefik-tlsstore — makes the dev cert Traefik’s default TLS store
Both need an explicit deployer declaration to be installed. caproni config print shows
exactly what will be installed and in what order.
Do not add new builtin overlays unless they directly enable Caproni’s own functionality.
The dev CA and Traefik TLS store exist because HTTPS is a prerequisite for production-like
local development — that is Caproni’s core job. Everything else (Postgres operators,
cert-manager, ingress controllers) belongs in the rig’s deployer declarations, not in
the Caproni binary.
Configuration system
Two levels
| Level | Type | Stored in | Retrieved with |
|---|
| Global | config.GlobalConfig | context | config.MustFromContext(ctx) |
| Application | latest.CaproniConfig | loaded per command | config.LoadCaproniConfig(globalCfg) |
Load pipeline (11 steps)
- Read
caproni.yaml - Resolve
extends: — recursively merge remote HTTPS fragments (TTL-cached) - Merge
caproni.local.yaml on top - Detect
version: field - Apply
caproni-project.yaml from cloned edit-mode repos - Seed variable resolver from decoded (pre-default) config
- Resolve
ProfileName via naming strategy (static or directory) - Expand
${VAR} across the entire YAML tree (skipping mirrord regex fields and cluster driver fields) - Validate against
schema/config.v2.schema.json (compiled once, embedded in binary) - Unmarshal into
latest.CaproniConfig, apply defaults, run upgrade chain - Semantic validation; inject embedded CI tool versions
Schema change checklist
When changing the configuration schema:
schema/config.v2.schema.json — update the schemainternal/config/v2/config.go — update Go typesexamples/ — add or update an example; run caproni config validate against itdocs/configuration.md — update the reference if user-visible behavior changes
Only mark fields required if they truly have no sensible default.
Testing
Managers are unit-tested by injecting mock backends. Mocks are generated by
mockery (run ./scripts/generate.sh), configured in
.mockery.yaml. Every mocks/ directory has a for_testing_only.go guard:
func init() {
if !testing.Testing() {
panic("package helm/mocks must only be used in tests")
}
}
Mocks use regular .go files (not _test.go) to allow cross-package import in tests.
Variadic args in mock expectations — the generated mock packs variadic args into a slice
before calling _mock.Called. Pass them as a single slice to EXPECT():
// Correct
mockExec.EXPECT().ReadStdout(ctx, "k3d", []string{"cluster", "list", "-o", "json"}).Return(...)
// Wrong — individual args do not match the recorded []string
mockExec.EXPECT().ReadStdout(ctx, "k3d", "cluster", "list", "-o", "json").Return(...)
internal/cluster.Manager uses a hand-written mock in internal/cluster/mock/ registered
programmatically in tests, rather than mockery.
Anti-patterns
| Anti-pattern | Why it breaks things |
|---|
| Hardcoded resource/secret names | Couples CLI to one application |
| Generating manifests or config templates | Caproni becomes a fourth config system |
Business logic in cmd/ | Untestable without the CLI framework |
| Global state / singletons | Hidden dependencies, testing hell |
os.Getenv() for application config | Bypasses validation, discovery, migration |
| Conditionals in front of an interface | Should live inside an implementation |
| Raw command output from backends | Backends must return structured data |
| Capability flags on registries | Use configuration instead (see cluster.<driver>.k3s.disable) |
| New builtin infrastructure overlays | Ship as rig deployers unless they enable Caproni’s own functionality |