Skip to content

feat(operator): KapeAgentServer CRD, renderer, reconcile loop, chart clean cut (#263) - #268

Merged
dzungtr merged 3 commits into
mainfrom
pi-subagents/worker-Implement-GitHub-issue-https-github.com-dzungtr-kape-issues-263-autobot-slice-of-9de6a1e2-c2b7a6e-0ce3-s0-t0
Oct 19, 2026
Merged

dzungtr merged 3 commits into
mainfrom
pi-subagents/worker-Implement-GitHub-issue-https-github.com-dzungtr-kape-issues-263-autobot-slice-of-9de6a1e2-c2b7a6e-0ce3-s0-t0

Conversation

@dzungtr

@dzungtr dzungtr commented Oct 19, 2026 •

Copy link
Copy Markdown
Owner

Closes #263

Slice of epic #261 (spec). Full vertical of the declarative serving path, credentials excluded by design (schema ships complete, behaviour arrives in #265).

What changed

M1 — KapeAgentServer API types + CRD (operator/infra/api/v1alpha1/kapeagentserver_types.go, crds/kape.io_kapeagentservers.yaml)

  • Complete v0 schema in one CRD version: description, controller (image, resources), sandbox (image, model, cpu/mem), modelGateway (url), credentials[] ({name, secretRef{name}, providerType, hostPatterns[]}), network (ingress host/TLS, egressPolicyRefs).
  • Status: Ready + observedGeneration + per-credential conditions (status.credentials[].conditions) — present now, written by Operator credential automation: registry → OpenShell providers → env, rotation, degrade-loud #265, so no later CRD revision.
  • CEL at admission: host-pattern syntax (OpenShell host[:port] globs), unique credential names, same-namespace secretRef.

M2 — pure renderer (operator/domain/agentserver/render.go + golden tests)

  • Render(CR, resolvedSecrets) → DesiredState{DeploymentEnv, NetworkResources, OpenShellRecords}; no client calls, deterministic.
  • Env contract: sandbox.image→KAPE_DEFAULT_IMAGE, sandbox.model→KAPE_DEFAULT_MODEL, sandbox.resources→KAPE_DEFAULT_RESOURCES, modelGateway.url→KAPE_MODEL_GATEWAY_URL, description→KAPE_SERVER_DESCRIPTION, KAPE_CREDENTIAL_BINDINGS = [].
  • Also owns the OpenShell record naming convention kape-<ns>-<cr>-<cred> (Operator credential automation: registry → OpenShell providers → env, rotation, degrade-loud #265 handoff H2) and degrade-loud filtering of unresolved credentials.

M5 — apply loop (operator/controller/reconcile/agentserver.go, operator/infra/k8s/agentserver.go)

  • Converges the controller Deployment, its ServiceAccount, the kape-controller-sandbox-reader RoleBinding, the Service, and an optional Ingress in the CR's namespace; prunes rendered objects the CR no longer declares; never adopts an object without this CR's ownership labels (ErrNotOwned → Ready=False/OwnershipConflict).
  • Ready reflects the outcome: Deployed / Progressing / WiringIncomplete / OwnershipConflict / ApplyFailed, with observedGeneration.

M7 — MCP instructions (controller/mcpapi.go, controller/config.go)

  • KAPE_SERVER_DESCRIPTION is served as the initialize handshake's instructions. The tool contract is byte-identical (the existing TestMCPToolListMatchesRESTContract gate still passes); KAPE_DEFAULT_MODEL becomes the default model for create_agent.

M8 — chart clean cut (charts/kape)

  • Installs the CRD, the operator wiring, and a default KapeAgentServer CR; keeps the cluster-scoped kape-controller-sandbox-reader ClusterRole (the operator renders the per-CR RoleBinding).
  • Deletes templates/controller/deployment.yaml, serviceaccount.yaml, networkpolicy.yaml. No legacyController.enabled or equivalent toggle.

Decision recorded: A vs B vs C for non-CR controller env

The renderer env table is a strict subset of a runnable controller's env. Option A was chosen (supervisor-approved) and is implemented here:

  • Render emits only the six contract vars (golden-tested with exactly six).
  • The apply layer merges operator-level cluster wiring — KAPE_GATEWAY_ADDR, KAPE_CREDS_DIR (+ read-only creds Secret mount at that path), KAPE_DEFAULT_PROVIDER, KAPE_TRANSPORT, KAPE_EVENT_STORE — sourced from the operator Deployment's own env (KAPE_OPERATOR_CONTROLLER_*, chart value block controllerWiring). These are cluster plumbing, not CR intent (D5), and the CRD is untouched (no rev).
  • Chart-owned optional feature wiring (controller.monitor.*, controller.revive.*, the monitor API key) rides a generic passthrough (controllerWiring.extraEnv / extraEnvFrom → KAPE_OPERATOR_CONTROLLER_EXTRA_ENV / _EXTRA_ENV_FROM), so the operator knows no KAPE_MONITOR_* / KAPE_REVIVE_* names and no capability was lost in the cut.
  • Guard (tested): a wiring/passthrough entry named KAPE_DEFAULT_*, KAPE_MODEL_GATEWAY_URL, KAPE_SERVER_DESCRIPTION or KAPE_CREDENTIAL_BINDINGS is dropped — the CR contract can never be shadowed.
  • An unset wiring value is not defaulted: Ready=False, reason=WiringIncomplete names the missing keys and no controller is materialised.

Handoff H4 (default CR values for the smoke)

Field Value
CR kape-system/default (kubectl get kas -n kape-system)
controller.image ghcr.io/dzungtr/kape-controller:0.1.0
sandbox.image ghcr.io/dzungtr/pi-openshell:openrouter
sandbox.model "" (image's own selection)
sandbox.resources cpu: 1, memory: 2Gi
modelGateway.url http://model-gateway-http.aperture.svc.cluster.local/v1
description kape default agent server: sandbox agents for this cluster
rendered objects kape-controller-default Deployment/Service/SA/RoleBinding (+ Ingress when enabled), Service 80 → container 8081 http
wiring gatewayAddr=openshell.openshell.svc.cluster.local:8080, credsDir=/var/run/kape-controller/creds, credsSecret=kape-controller-creds, defaultProvider=openrouter, transport=pull, eventStore=/var/lib/kape-controller/controller-events.db

Note for the live smoke: the cluster's current kape-controller (ns openshell, ArgoCD-managed from the homelab repo) is not chart-managed; after the chart install there will be two controllers unless that ArgoCD app is removed. Cut-over is a post-merge, human step.

Verification

Verified locally (this sandbox)

  • go build ./..., go vet ./... — operator (CGO off) and controller (own module): pass.
  • go test ./... — controller: all pass (56s). Operator: all pass except 4 pre-existing TestToolReconciler_* cases that connect to httptest servers on loopback; this sandbox denies loopback (connect: permission denied), so they cannot pass here. They are unrelated to this change and touch no file in the diff except the duplicate-helper removal.
  • New unit tests (all pass): renderer golden + env-contract + naming + degrade-filter + purity; k8s apply adapter (create/converge/update/never-adopt/prune/status/contract-shadowing guard/volume mounts); reconciler (wiring gate, Progressing, Ready, ownership conflict, deleted CR, missing-var names); cmd wiring JSON parse; controller config env + MCP initialize instructions.
  • helm lint + helm template + charts/kape/tests/render-test.sh (rewritten for the cut-over): pass — CRD in the install hook, default CR rendered, operator wiring env rendered, no legacy controller Deployment/NetworkPolicy, ingress/TLS/extraEnv cases.
  • golangci-lint on the touched packages: clean (remaining findings are pre-existing in untouched files).

Verified live against microk8s (CRD + reconcile loop; cluster left as found — CRD, namespace and CR all removed afterwards)

  • CRD installs on a real API server (kubectl apply, and --dry-run=server, accepted).
  • CEL admission, all three rejections reproduced:
    • hostPatterns entries must be host[:port] globs in OpenShell NetworkEndpoint syntax …
    • credentials[].name must be unique within a KapeAgentServer
    • secretRef must be same-namespace: omit namespace …
    • same manifest with valid patterns/unique names/no namespace → accepted.
  • Scenario 2 (re-run on the fixed binary, commit 7a54fe9; namespace k263-verify, CR k263-sre, credentials: [] explicit — see the admission caveat below): kubectl apply of a KapeAgentServer (scratch ns) with the reconciler running → deployment/kape-controller-sre, service/kape-controller-sre (80/TCP), ingress/kape-controller-sre (host + TLS), serviceaccount/kape-controller-sre, rolebinding/kape-controller-sre → ClusterRole/kape-controller-sandbox-reader; status Ready=False/Progressing, observedGeneration=1; container env exactly the 6 contract vars + 5 wiring vars; creds Secret mounted read-only at KAPE_CREDS_DIR, emptyDir at the event-store dir.
  • Scenario 6: kubectl delete deploy kape-controller-sre → recreated by the operator within seconds.
  • Deleting the CR garbage-collected every rendered object (owner references).

NOT verified — CI-only or blocked (marked, not claimed)

  • envtest (scenario 5 in-process, reconcile convergence in envtest): cases authored, never executed in operator/test/integration/agentserver_envtest_test.go (round-trip of the complete schema incl. credential status, the three CEL rejections, CR→Deployment/Service/Ingress convergence, delete-Deployment recreation, Ready transition). envtest needs loopback, which this sandbox denies; CI cannot run them (below). The same assertions were exercised live against microk8s instead (above).
  • Scenario 1 admission defect — FIXED in round 2 (commit 2f1b73c). A KapeAgentServer that omits spec.credentials used to be rejected with no such key: credentials evaluating rule: credentials[].name must be unique, and the chart's own default CR omits that list, so a fresh helm install failed admission. Now: the unique-name CEL rule is guarded with !has(self.credentials), the sandbox.model pattern admits "" (^([A-Za-z0-9._:/-]+)?$, matching controller/config.go, which only validates a non-empty model), and the chart renders credentials: [] explicitly. Proven live on microk8s: the freshly rendered default CR is accepted with a Ready condition, a CR with credentials omitted entirely is accepted, model: "" is accepted, and the three CEL negatives plus bad model! still reject — evidence in the round-2 comment below.
  • Scenario 1 (fresh helm install): admission of the exact object the chart renders is now proven live (scenario 1's failure mode). A full helm install into the shared microk8s cluster was still not executed — it would collide with the existing nats/postgres/task-service/dashboard release and the ArgoCD-managed openshell/kape-controller. helm lint / helm template / charts/kape/tests/render-test.sh also pass.
  • Scenario 3 (MCP initialize against a served endpoint): the instructions handshake is unit-verified in-process (fake gateway, in-memory transport); no CR-managed controller pod is running live (no image with this code pushed) so no endpoint-level check.
  • Scenario 4 (create_agent/prompt_agent through the CR-managed controller): blocked twice — no controller image containing this change is published, and Proto re-pin to OpenShell v0.1.0 + workspace_scope fix (cluster upgrade done) #262 (proto re-pin / workspace_scope) has not landed, so the current controller image is broken against gateway v0.1.0 regardless.

Local gate (executed in the worktree; real output)

operator/  $ CGO_ENABLED=0 go build ./...
OK
operator/  $ CGO_ENABLED=0 go vet ./...
OK
operator/  $ CGO_ENABLED=0 go test ./...
ok   github.com/kape-io/kape/operator/cmd
ok   github.com/kape-io/kape/operator/controller
FAIL github.com/kape-io/kape/operator/controller/reconcile   (4 pre-existing TestToolReconciler_* probe tests)
ok   github.com/kape-io/kape/operator/domain/agentserver
ok   github.com/kape-io/kape/operator/domain/config
ok   github.com/kape-io/kape/operator/infra/k8s
FAIL github.com/kape-io/kape/operator/infra/qdrant                (4 pre-existing httptest tests)
ok   github.com/kape-io/kape/operator/infra/toml

controller/ $ GOWORK=off CGO_ENABLED=0 go build ./...   -> OK
controller/ $ GOWORK=off CGO_ENABLED=0 go vet ./...     -> OK
controller/ $ GOWORK=off CGO_ENABLED=0 go test ./...    -> ok  github.com/dzungtr/kape/controller (56.6s)

charts/    $ helm lint charts/kape                       -> 1 chart(s) linted, 0 failed
charts/    $ helm template t charts/kape                 -> clean render
charts/    $ charts/kape/tests/render-test.sh            -> OK: all chart render assertions passed

The 8 failing tests (both pre-existing suites) all fail the same way and touch nothing in this diff:
dial tcp 127.0.0.1:<port>: connect: permission denied — this sandbox denies loopback, so their
httptest servers are unreachable. Confirmed environmental: a bare socket.connect(("127.0.0.1", n))
is refused here, and the same suites are green in a normal environment.

Targeted new tests, run explicitly: go test ./domain/... ./infra/k8s/ ./cmd/ all ok;
go test ./controller/reconcile/ -run 'TestAgentServer|TestControllerWiring' → 6/6 PASS.

CI status

CI unavailable — the repo has no registered Actions runners
(repos/dzungtr/kape/actions/runners is empty); run 39285106342 for this PR never dispatched its job
(queued forever, last successful integration-test run 2026-07-19). Recent merges (e.g. #259) landed with
zero checks. The envtest cases authored here have never been executed anywhere — they cannot run in
this sandbox (envtest needs loopback; etcd … dial 127.0.0.1: permission denied) and CI cannot run them.
Local gate evidence above; the live microk8s runs below cover the same assertions at admission/apply level.

Live-cluster footprint (shared microk8s)

  • Left installed, intentionally: CRD kapeagentservers.kape.io (re-applied at 16:32Z from this branch). It is additive, is what the chart install produces anyway, and unblocks the sibling slices. Delete with kubectl delete crd kapeagentservers.kape.io when no longer wanted (that deletes any remaining KapeAgentServer CRs).
  • Nothing else left behind: verification ran in its own namespace kape-as-263 with CR sre; both were deleted, and the CR's rendered objects were garbage-collected via owner references. No Deployments, Services, Ingresses, providers or port-forwards remain.
  • No sibling objects were touched: k264-* / k262-* objects and providers openrouter / openrouter-spike were never read-modified (and the live check created no sandboxes).

Out-of-brief fixes (test floor only)

  1. operator/controller/reconcile/tool_test.go — removed duplicated findCondition / fakeConfigLoader (copies live in testhelpers_test.go). Reason: the package did not compile on main, so no operator unit test could run.
  2. operator/test/integration/suite_test.go — NewToolReconciler was called with a stale argument list (StatefulSet adapter + config loader instead of QdrantClusterPort + event recorder). Reason: the envtest suite did not compile on main; CI only runs ./test/integration/..., so neither breakage was surfaced.
  3. crds/kape.io_kapetools.yaml — regenerated by make generate; the only delta is one stale field description (source comment was updated earlier without regenerating).

Review notes

…hart clean cut (#263)

Implements the declarative serving-environment slice of epic #261:

- KapeAgentServer API types carrying the complete v0 schema (controller,
  sandbox, modelGateway, credentials[], network, description) plus the
  Ready condition and the per-credential status conditions #265 will write.
  CEL rejects bad host patterns, duplicate credential names and
  cross-namespace secretRefs at admission.
- domain/agentserver.Render: pure CR -> DesiredState renderer emitting the
  six-var env contract (KAPE_DEFAULT_IMAGE / _MODEL / _RESOURCES,
  KAPE_MODEL_GATEWAY_URL, KAPE_SERVER_DESCRIPTION, and
  KAPE_CREDENTIAL_BINDINGS rendered empty), the Service/Ingress, and the
  OpenShell record naming convention (#265's handoff H2). Golden-tested.
- AgentServerReconciler + controller-runtime apply loop: converges the
  controller Deployment, its ServiceAccount, the sandbox-reader RoleBinding,
  the Service and an optional Ingress in the CR's namespace; prunes what the
  CR no longer declares, never adopts an object it did not render, and
  reports Ready (Deployed / Progressing / WiringIncomplete /
  OwnershipConflict / ApplyFailed).
- Operator cluster wiring (D5): KAPE_GATEWAY_ADDR, KAPE_CREDS_DIR (+ creds
  Secret mount), KAPE_DEFAULT_PROVIDER, KAPE_TRANSPORT, KAPE_EVENT_STORE and
  chart-owned passthrough env ride the operator's own config into every
  rendered controller; contract env always wins on a name clash.
- Controller: KAPE_SERVER_DESCRIPTION is served as the MCP initialize
  handshake's server `instructions`; KAPE_DEFAULT_MODEL becomes the default
  model for created sandboxes. The tool contract is unchanged.
- Chart: installs the CRD + a default KapeAgentServer CR, keeps the
  cluster-scoped sandbox-reader ClusterRole, and deletes the hand-wired
  controller Deployment/ServiceAccount/NetworkPolicy templates. No legacy
  toggle.

Out-of-brief fixes (test floor only):
- operator/controller/reconcile/tool_test.go: duplicated findCondition /
  fakeConfigLoader made the package fail to compile on main; kept the
  testhelpers_test.go copies.
- operator/test/integration/suite_test.go: stale NewToolReconciler argument
  list broke the envtest suite build; now passes a noop QdrantClusterPort
  and an event recorder.
…nciler runs

SetupKapeProxyReconciler built its controller with Watches() only, which
controller-runtime rejects ("one of For() or Named() must be called").
main.go exits 1 on that error, so SetupAgentServerReconciler never ran and
the shipped operator never registered the KapeAgentServer reconciler.

Named("kapeproxy") gives the controller its name without declaring a For()
primary resource, so the existing label-filtered Pod watch stays the only
event source (For(&corev1.Pod{}) would also enqueue unlabelled Pods).
@dzungtr

dzungtr commented Oct 19, 2026

Copy link
Copy Markdown
Owner Author

Fix round 1 — P0 kapeproxy controller registration

Change (1 line + comment), operator/controller/kapeproxy.go

 	return ctrl.NewControllerManagedBy(mgr).
+		Named("kapeproxy").
 		Watches(&corev1.Pod{}, handler.EnqueueRequestsFromMapFunc(mapHandlerPods)).

Named("kapeproxy") rather than For(&corev1.Pod{}): For would install an unfiltered Pod watch (enqueue every Pod in the cluster, doubling enqueues for labelled ones), while the reconciler's event contract is "Pods carrying kape.io/handler". Named satisfies controller-runtime's For-or-Named requirement and leaves the event set exactly as before. No other behaviour touched. Commit 7a54fe9.

Baseline reproduction (unfixed build, microk8s context microk8s)

$ CGO_ENABLED=0 go build -o /tmp/kape-operator-268-baseline ./cmd/   # kapeproxy.go at 2e18756
$ /tmp/kape-operator-268-baseline --leader-elect=false --metrics-bind-address=0 --health-probe-bind-address=0
exit=1
ERROR	main	setting up KapeProxy controller	{"error": "one of For() or Named() must be called"}
	/dzungtr/kape/operator/cmd/main.go:211

Deterministic exit 1 before SetupAgentServerReconciler (main.go:226) — the reported P0, reproduced.

Startup proof (fixed build)

$ CGO_ENABLED=0 go build -o /tmp/kape-operator-268 ./cmd/
$ /tmp/kape-operator-268 --leader-elect=false --metrics-bind-address=0 --health-probe-bind-address=0 \
    --controller-gateway-addr=openshell.openshell.svc.cluster.local:8080 \
    --controller-creds-dir=/var/run/kape-controller/creds --controller-creds-secret=kape-controller-creds \
    --controller-default-provider=openrouter --controller-transport=pull \
    --controller-event-store=/var/lib/kape-controller/controller-events.db
INFO	Starting EventSource	{"controller": "kapeproxy", "source": "kind source: *v1.Pod"}
INFO	Starting Controller	{"controller": "kapeproxy"}
INFO	Starting EventSource	{"controller": "kapeagentserver", "controllerGroup": "kape.io", "controllerKind": "KapeAgentServer", "source": "kind source: *v1alpha1.KapeAgentServer"}
INFO	Starting EventSource	{"controller": "kapeagentserver", ... "source": "kind source: *v1.Deployment"}
INFO	Starting EventSource	{"controller": "kapeagentserver", ... "source": "kind source: *v1.Service"}
INFO	Starting EventSource	{"controller": "kapeagentserver", ... "source": "kind source: *v1.ServiceAccount"}
INFO	Starting EventSource	{"controller": "kapeagentserver", ... "source": "kind source: *v1.RoleBinding"}
INFO	Starting EventSource	{"controller": "kapeagentserver", ... "source": "kind source: *v1.Ingress"}
INFO	Starting Controller	{"controller": "kapeagentserver", "controllerGroup": "kape.io", "controllerKind": "KapeAgentServer"}
INFO	Starting workers	{"controller": "kapeproxy", "worker count": 3}
INFO	Starting workers	{"controller": "kapeagentserver", "controllerGroup": "kape.io", "controllerKind": "KapeAgentServer", "worker count": 3}

No os.Exit(1); the agent-server reconciler registers and its workers start. (The other four kape.io CRDs had to be installed from crds/ for the manager's informers to sync — they were absent from the cluster. Deleted again afterwards.)

Scenario 2 re-run with this binary — reproducible

Namespace k263-verify, CR k263-sre (credentials: [] explicitly, see caveat below):

$ kubectl -n k263-verify get deploy,svc,sa,rolebinding,ingress
deployment.apps/kape-controller-k263-sre        0/1   1   0   10s
service/kape-controller-k263-sre                ClusterIP   10.152.183.166   80/TCP
serviceaccount/kape-controller-k263-sre
rolebinding.rbac.authorization.k8s.io/kape-controller-k263-sre   ClusterRole/kape-controller-sandbox-reader
ingress.networking.k8s.io/kape-controller-k263-sre   k263-sre.example.test   80

$ kubectl -n k263-verify get kas k263-sre -o jsonpath='{.status}'
{"conditions":[{"type":"Ready","status":"False","reason":"Progressing","message":"controller Deployment k263-verify/kape-controller-k263-sre is not available yet","observedGeneration":1}],"observedGeneration":1}

Env contract on the rendered Deployment (6 CR-derived + 5 wiring):

KAPE_CREDENTIAL_BINDINGS=[]
KAPE_DEFAULT_IMAGE=ghcr.io/dzungtr/pi-openshell:openrouter
KAPE_DEFAULT_MODEL=
KAPE_DEFAULT_RESOURCES={"cpu":"1","memory":"2Gi"}
KAPE_MODEL_GATEWAY_URL=http://model-gateway-http.aperture.svc.cluster.local/v1
KAPE_SERVER_DESCRIPTION=k263 scenario-2 verification server
KAPE_GATEWAY_ADDR=openshell.openshell.svc.cluster.local:8080
KAPE_CREDS_DIR=/var/run/kape-controller/creds
KAPE_DEFAULT_PROVIDER=openrouter
KAPE_TRANSPORT=pull
KAPE_EVENT_STORE=/var/lib/kape-controller/controller-events.db

Ready=False/Progressing is the expected terminal state here: the rendered image pulls but the pod does not become available in this cluster, and Deployed needs an available Deployment.

Cleanup: CR + namespace deleted (no k263 namespaces, no k263 objects), operator stopped, CRDs installed for the run deleted again. Pre-existing kapeagentservers.kape.io left installed as found.

New defect found while running Scenario 2 — not fixed in this round (out of the approved scope)

A KapeAgentServer that omits spec.credentials is rejected at admission: the list-map CEL rule dereferences a missing key.

$ kubectl apply --dry-run=server -f <chart's rendered default CR>
The KapeAgentServer "k263-chart-default" is invalid: spec: Invalid value: "object":
no such key: credentials evaluating rule: credentials[].name must be unique within a KapeAgentServer

This hits the chart's own default CR (charts/kape/templates/controller/agentserver.yaml omits credentials and network when unset), so fresh helm install (scenario 1) would fail admission for the default CR. Two independent fixes are possible — make the rule !has(self.credentials) || self.credentials.all(...), or always render credentials: [] in the chart. spec.sandbox.model: "" is likewise rejected by its pattern while the H4 table documents "" as "image's own selection". Needs its own decision/ticket; it is not part of the startup P0 and this commit does not change it.

Gates (local — CI has no registered runners here)

operator/  $ CGO_ENABLED=0 go build ./...          -> OK
operator/  $ CGO_ENABLED=0 go vet ./...            -> OK
operator/  $ CGO_ENABLED=0 go test ./controller/ ./cmd/ ./domain/... ./infra/k8s/
ok  .../controller   ok  .../cmd   ok  .../domain/agentserver   ok  .../domain/config   ok  .../infra/k8s

Not runnable in this sandbox: envtest (./test/integration/..., needs loopback bind/connect, denied) and the pre-existing httptest suites (.../controller/reconcile TestToolReconciler_*, .../infra/qdrant) — unchanged from the base PR's note. No unit test guards the For-or-Named requirement itself: a manager cannot be constructed here without an API server, so the live startup run above is the regression evidence.

The CEL rule that enforces unique credential names indexed into
spec.credentials unconditionally, so a KapeAgentServer that omits the
optional list was rejected at admission with `no such key: credentials`.
The chart's own default CR omits it, so a fresh `helm install` failed
(issue #263 scenario 1).

- Guard the rule with `!has(self.credentials)`; a present list with
  duplicate names still rejects, as do the host-pattern and
  same-namespace secretRef rules.
- Relax the sandbox.model pattern to admit the empty string, which
  controller/config.go and the field comment both read as "keep the
  sandbox image's own selection"; non-empty ids keep the same charset.
- Render `credentials: []` explicitly in the chart's default CR, and pin
  the rendered contract in charts/kape/tests/render-test.sh.
- Pin both behaviours in TestKapeAgentServerOptionalFields (envtest,
  CI-only: this sandbox denies loopback): credentials omitted/empty and
  model omitted/empty/valid are admitted, `bad model!` and the three CEL
  negatives still reject.

Verified live on microk8s: the rendered default CR is accepted with a
Ready condition, and all three negatives still reject.
@dzungtr

dzungtr commented Oct 19, 2026

Copy link
Copy Markdown
Owner Author

Round 2 — admission defect fixed (commit 2f1b73c)

Defect: a KapeAgentServer omitting the optional spec.credentials list was rejected with no such key: credentials evaluating rule: credentials[].name must be unique. The chart's default CR omits it, so a fresh helm install failed (scenario 1). sandbox.model: "" was likewise rejected by its pattern although the field documents empty as valid.

What changed

File Change
operator/infra/api/v1alpha1/kapeagentserver_types.go unique-name CEL rule guarded with !has(self.credentials); sandbox.model pattern → ^([A-Za-z0-9._:/-]+)?$ (admits "", same charset otherwise)
crds/, charts/kape/files/crds/ regenerated with controller-gen (never hand-edited); only these two lines moved
charts/kape/templates/controller/agentserver.yaml credentials: now always rendered ([] when empty)
charts/kape/tests/render-test.sh pins credentials: [] in the rendered default CR and "no model: key when the value is empty"
operator/test/integration/agentserver_envtest_test.go new TestKapeAgentServerOptionalFields (unstructured, so an omitted key is distinguishable from model: "")

Why the model pattern instead of a non-empty chart default: controller/config.go validates the model only when non-empty (if p.Model != "" && !modelRe.MatchString) and the field comment says empty keeps the image's own selection, so rejecting "" was a schema lie. Pinning a concrete model id in values.yaml would set KAPE_DEFAULT_MODEL cluster-wide for every sandbox — a runtime decision outside #263 (supervisor-approved: schema fix + omit key, no model pin).

Live proof — microk8s, CRD re-applied from this branch, namespace k263-r2 (deleted afterwards)

Admission of the freshly rendered default CR (helm template t charts/kape --namespace k263-r2 --set namespace=k263-r2 --show-only templates/controller/agentserver.yaml), reconciler running:

kapeagentserver.kape.io/default created          # exit=0  ACCEPTED
NAME      READY   IMAGE
default   False   ghcr.io/dzungtr/kape-controller:0.1.0
status: observedGeneration=1
  Ready=False reason=Progressing msg=controller Deployment k263-r2/kape-controller-default is not available yet
rendered: deployment/kape-controller-default, service/kape-controller-default (80/TCP),
          serviceaccount/kape-controller-default, rolebinding/kape-controller-default -> ClusterRole/kape-controller-sandbox-reader

(Progressing, not Deployed: no pullable image in this cluster — the Ready condition is present and reflects the outcome.)

The exact original defect — spec.credentials key omitted entirely: kapeagentserver.kape.io/k263-omitted created (exit 0), Ready=False/Progressing. model: "": kapeagentserver.kape.io/k263-model-empty created (exit 0), Ready=False/Progressing.

Three negatives still reject:

k263-neg-host: The KapeAgentServer "k263-neg-host" is invalid: spec.credentials[0]: Invalid value:
  hostPatterns entries must be host[:port] globs in OpenShell NetworkEndpoint syntax (…)
k263-neg-dup:  The KapeAgentServer "k263-neg-dup" is invalid: spec:
  Invalid value: credentials[].name must be unique within a KapeAgentServer
k263-neg-ns:   The KapeAgentServer "k263-neg-ns" is invalid: spec.credentials[0]: Invalid value:
  secretRef must be same-namespace: omit namespace (credential Secrets are read from the KapeAgentServer namespace only)
k263-model-invalid: The KapeAgentServer "k263-model-invalid" is invalid: spec.sandbox.model:
  Invalid value: "bad model!": spec.sandbox.model in body should match '^([A-Za-z0-9._:/-]+)?$'

Gate (executed here)

operator/  CGO_ENABLED=0 go build ./...                     -> OK
operator/  CGO_ENABLED=0 go vet ./...                       -> OK
operator/  CGO_ENABLED=0 go vet -tags envtest ./test/integration/ -> OK
operator/  CGO_ENABLED=0 go test ./...                      -> same 8 pre-existing failures as documented above
                                                               (TestToolReconciler_* + infra/qdrant: 127.0.0.1 connect: permission denied,
                                                                loopback denied by the sandbox; no file in this commit is in either package)
charts/    helm lint charts/kape                            -> 1 chart(s) linted, 0 failed
charts/    helm template t charts/kape                      -> clean render (2239 lines)
charts/    charts/kape/tests/render-test.sh                 -> OK: all chart render assertions passed

TestKapeAgentServerOptionalFields is authored, never executed: envtest needs loopback, which the authoring sandbox denies, and CI has no runners. The same assertions are covered live above.

Scenario status after round 2

  • Scenario 1 (fresh helm install): the blocker is gone — the default CR rendered by the chart is now admissible live (proof above). A full helm install into the shared cluster was still not executed (it would collide with the existing nats/postgres/task-service/dashboard release and the ArgoCD-managed openshell/kape-controller); admission of exactly that rendered object is now proven instead of merely linted.
  • Scenario 2 (CR → materialisation): unchanged from round 1, re-confirmed here for the default CR (Ready condition + all four rendered objects + RoleBinding).
  • Scenarios 3/4 remain blocked as documented in the PR body (no published image carrying this code; Proto re-pin to OpenShell v0.1.0 + workspace_scope fix (cluster upgrade done) #262 dependency).

@dzungtr
dzungtr merged commit c4319fe into main Oct 19, 2026
1 check failed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

KapeAgentServer CRD + reconcile skeleton + chart clean cut

1 participant