Repository navigation
Conversation
…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).
Fix round 1 — P0
|
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.
Round 2 — admission defect fixed (commit
|
| 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 fullhelm installinto the shared cluster was still not executed (it would collide with the existing nats/postgres/task-service/dashboard release and the ArgoCD-managedopenshell/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 (
Readycondition + 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).
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 —
KapeAgentServerAPI types + CRD (operator/infra/api/v1alpha1/kapeagentserver_types.go,crds/kape.io_kapeagentservers.yaml)description,controller(image, resources),sandbox(image, model, cpu/mem),modelGateway(url),credentials[]({name, secretRef{name}, providerType, hostPatterns[]}),network(ingress host/TLS,egressPolicyRefs).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.host[:port]globs), unique credential names, same-namespacesecretRef.M2 — pure renderer (
operator/domain/agentserver/render.go+ golden tests)Render(CR, resolvedSecrets) → DesiredState{DeploymentEnv, NetworkResources, OpenShellRecords}; no client calls, deterministic.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=[].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)kape-controller-sandbox-readerRoleBinding, 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).Readyreflects the outcome:Deployed/Progressing/WiringIncomplete/OwnershipConflict/ApplyFailed, withobservedGeneration.M7 — MCP instructions (
controller/mcpapi.go,controller/config.go)KAPE_SERVER_DESCRIPTIONis served as the initialize handshake'sinstructions. The tool contract is byte-identical (the existingTestMCPToolListMatchesRESTContractgate still passes);KAPE_DEFAULT_MODELbecomes the default model forcreate_agent.M8 — chart clean cut (
charts/kape)KapeAgentServerCR; keeps the cluster-scopedkape-controller-sandbox-readerClusterRole (the operator renders the per-CR RoleBinding).templates/controller/deployment.yaml,serviceaccount.yaml,networkpolicy.yaml. NolegacyController.enabledor 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:
Renderemits only the six contract vars (golden-tested with exactly six).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 blockcontrollerWiring). These are cluster plumbing, not CR intent (D5), and the CRD is untouched (no rev).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 noKAPE_MONITOR_*/KAPE_REVIVE_*names and no capability was lost in the cut.KAPE_DEFAULT_*,KAPE_MODEL_GATEWAY_URL,KAPE_SERVER_DESCRIPTIONorKAPE_CREDENTIAL_BINDINGSis dropped — the CR contract can never be shadowed.Ready=False, reason=WiringIncompletenames the missing keys and no controller is materialised.Handoff H4 (default CR values for the smoke)
kape-system/default(kubectl get kas -n kape-system)controller.imageghcr.io/dzungtr/kape-controller:0.1.0sandbox.imageghcr.io/dzungtr/pi-openshell:openroutersandbox.model""(image's own selection)sandbox.resourcescpu: 1,memory: 2GimodelGateway.urlhttp://model-gateway-http.aperture.svc.cluster.local/v1descriptionkape default agent server: sandbox agents for this clusterkape-controller-defaultDeployment/Service/SA/RoleBinding (+ Ingress when enabled), Service 80 → container 8081httpgatewayAddr=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.dbNote for the live smoke: the cluster's current
kape-controller(nsopenshell, 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-existingTestToolReconciler_*cases that connect tohttptestservers 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.cmdwiring 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-linton 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)
kubectl apply, and--dry-run=server, accepted).hostPatterns entries must be host[:port] globs in OpenShell NetworkEndpoint syntax …credentials[].name must be unique within a KapeAgentServersecretRef must be same-namespace: omit namespace …7a54fe9; namespacek263-verify, CRk263-sre,credentials: []explicit — see the admission caveat below):kubectl applyof aKapeAgentServer(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; statusReady=False/Progressing,observedGeneration=1; container env exactly the 6 contract vars + 5 wiring vars; creds Secret mounted read-only atKAPE_CREDS_DIR, emptyDir at the event-store dir.kubectl delete deploy kape-controller-sre→ recreated by the operator within seconds.NOT verified — CI-only or blocked (marked, not claimed)
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,Readytransition). envtest needs loopback, which this sandbox denies; CI cannot run them (below). The same assertions were exercised live against microk8s instead (above).2f1b73c). AKapeAgentServerthat omitsspec.credentialsused to be rejected withno such key: credentials evaluating rule: credentials[].name must be unique, and the chart's own default CR omits that list, so a freshhelm installfailed admission. Now: the unique-name CEL rule is guarded with!has(self.credentials), thesandbox.modelpattern admits""(^([A-Za-z0-9._:/-]+)?$, matchingcontroller/config.go, which only validates a non-empty model), and the chart renderscredentials: []explicitly. Proven live on microk8s: the freshly rendered default CR is accepted with aReadycondition, a CR withcredentialsomitted entirely is accepted,model: ""is accepted, and the three CEL negatives plusbad model!still reject — evidence in the round-2 comment below.helm install): admission of the exact object the chart renders is now proven live (scenario 1's failure mode). A fullhelm installinto the shared microk8s cluster was still not executed — it would collide with the existing nats/postgres/task-service/dashboard release and the ArgoCD-managedopenshell/kape-controller.helm lint/helm template/charts/kape/tests/render-test.shalso pass.create_agent/prompt_agentthrough 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)
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 theirhttptestservers are unreachable. Confirmed environmental: a baresocket.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/allok;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/runnersis empty); run39285106342for 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)
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 withkubectl delete crd kapeagentservers.kape.iowhen no longer wanted (that deletes any remaining KapeAgentServer CRs).kape-as-263with CRsre; both were deleted, and the CR's rendered objects were garbage-collected via owner references. No Deployments, Services, Ingresses, providers or port-forwards remain.k264-*/k262-*objects and providersopenrouter/openrouter-spikewere never read-modified (and the live check created no sandboxes).Out-of-brief fixes (test floor only)
operator/controller/reconcile/tool_test.go— removed duplicatedfindCondition/fakeConfigLoader(copies live intesthelpers_test.go). Reason: the package did not compile onmain, so no operator unit test could run.operator/test/integration/suite_test.go—NewToolReconcilerwas called with a stale argument list (StatefulSet adapter + config loader instead ofQdrantClusterPort+ event recorder). Reason: the envtest suite did not compile onmain; CI only runs./test/integration/..., so neither breakage was surfaced.crds/kape.io_kapetools.yaml— regenerated bymake generate; the only delta is one stale field description (source comment was updated earlier without regenerating).Review notes
status.credentials[]andnetwork.egressPolicyRefsare schema-only in this slice (documented on the types); they are consumed by Credential-injection mechanism proof: controller binding merge + profile-backed manual provider #264/Operator credential automation: registry → OpenShell providers → env, rotation, degrade-loud #265.