Local code intelligence for developers and AI agents. Connect code, docs and infrastructure in a persistent graph, with CBM Lens, MCP tools, agent integrations and change-aware test selection.
C aiderastclaude-codecode-analysiscode-intelligencecodexcursorcypherdeveloper-toolsgemini-cligraph-visualizationkilocodeknowledge-graphmcpmcp-servermodel-context-protocolopencodesqlitetree-sitterwindsurf
feat(k8s): objects link to the objects they name
Martin Vogel3ef74c230770
diff --git a/internal/cbm/cbm.c b/internal/cbm/cbm.cindex b9e3237b2..2f0f9cc1c 100644--- a/internal/cbm/cbm.c+++ b/internal/cbm/cbm.c@@ -262,6 +262,11 @@ void cbm_infrabinding_push(CBMInfraBindingArray *arr, CBMArena *a, CBMInfraBindiarr->items[arr->count++] = ib;}+void cbm_k8sfact_push(CBMK8sFactArray *arr, CBMArena *a, CBMK8sFact f) {+ GROW_ARRAY(arr, a);+ arr->items[arr->count++] = f;+}+void cbm_impltrait_push(CBMImplTraitArray *arr, CBMArena *a, CBMImplTrait it) {GROW_ARRAY(arr, a);arr->items[arr->count++] = it;diff --git a/internal/cbm/cbm.h b/internal/cbm/cbm.hindex 6cc5d4743..0ae684030 100644--- a/internal/cbm/cbm.h+++ b/internal/cbm/cbm.h@@ -600,6 +600,29 @@ typedef struct {int cap;} CBMInfraBindingArray;+/* A fact a Kubernetes manifest states about other objects (extract_k8s.c),+ * resolved by the K8s pass against the objects of the source's bundle.+ * CBM_K8S_FACT_REF: object def_index names a kind/ns/name object at a+ * reference path (via), drawn as edge (USAGE or INFRA_MAPS); ns NULL =+ * the source's own namespace.+ * CBM_K8S_FACT_CRD: the CRD def_index declares kind `kind` in group `name`. */+typedef enum { CBM_K8S_FACT_REF = 0, CBM_K8S_FACT_CRD } CBMK8sFactKind;+typedef struct {+ CBMK8sFactKind fact;+ int def_index;+ const char *kind;+ const char *ns;+ const char *name;+ const char *via;+ const char *edge;+} CBMK8sFact;++typedef struct {+ CBMK8sFact *items;+ int count;+ int cap;+} CBMK8sFactArray;+typedef struct {CBMImplTrait *items;int count;@@ -660,6 +683,7 @@ typedef struct CBMFileResult {CBMResolvedCallArray resolved_calls; // LSP-resolved invocations/references (high confidence)CBMStringRefArray string_refs; // URL/config string literals from ASTCBMInfraBindingArray infra_bindings; // topic→URL pairs from IaC configs+ CBMK8sFactArray k8s_facts; // Kubernetes references and CRD declarationsCBMChannelArray channels; // Socket.IO / EventEmitter pub/sub participationCBMFieldTypeArray field_types; // Python: annotated instance fields (#1277)@@ -1119,6 +1143,7 @@ void cbm_typeassign_push(CBMTypeAssignArray *arr, CBMArena *a, CBMTypeAssign ta)void cbm_fieldtype_push(CBMFieldTypeArray *arr, CBMArena *a, CBMFieldType ft);void cbm_stringref_push(CBMStringRefArray *arr, CBMArena *a, CBMStringRef sr);void cbm_infrabinding_push(CBMInfraBindingArray *arr, CBMArena *a, CBMInfraBinding ib);+void cbm_k8sfact_push(CBMK8sFactArray *arr, CBMArena *a, CBMK8sFact f);void cbm_impltrait_push(CBMImplTraitArray *arr, CBMArena *a, CBMImplTrait it);void cbm_resolvedcall_push(CBMResolvedCallArray *arr, CBMArena *a, CBMResolvedCall rc);void cbm_channels_push(CBMChannelArray *arr, CBMArena *a, CBMChannel ch);diff --git a/internal/cbm/extract_k8s.c b/internal/cbm/extract_k8s.cindex 46937668d..29765d87c 100644--- a/internal/cbm/extract_k8s.c+++ b/internal/cbm/extract_k8s.c@@ -331,6 +331,312 @@ static void extract_k8s_scalars(CBMExtractCtx *ctx, TSNode mapping, k8s_doc_id_t}}+// ---------------------------------------------------------------------------+// Object references (PHASE1.md): facts the K8s pass resolves per bundle+// ---------------------------------------------------------------------------++// A reference held by a scalar at a path, relative to the pod spec, to a+// container, or (kinds) to the whole object.+typedef struct {+ const char *path;+ const char *kind;+ const char *via;+} k8s_leaf_ref_t;++typedef struct {+ const char *kinds; // "|A|B|" of the source kinds+ const char *path;+ const char *kind;+ const char *via;+ const char *edge;+} k8s_object_ref_t;++// A reference held by a mapping's kind/name/namespace fields.+typedef struct {+ const char *kinds; // "|A|B|" of the source kinds+ const char *path; // the mapping's path+ const char *kind; // the target kind; NULL = the mapping's own `kind` field+ const char *allowed; // with kind NULL: "|A|" of the kinds that are objects+ const char *dflt; // with kind NULL: the kind when the field is absent+ const char *via;+ const char *edge;+} k8s_mapping_ref_t;++static const k8s_leaf_ref_t k8s_pod_refs[] = {+ {"serviceAccountName", "ServiceAccount", "serviceAccountName"},+ {"serviceAccount", "ServiceAccount", "serviceAccountName"},+ {"priorityClassName", "PriorityClass", "priorityClassName"},+ {"imagePullSecrets[].name", "Secret", "imagePullSecrets"},+ {"volumes[].configMap.name", "ConfigMap", "volume"},+ {"volumes[].secret.secretName", "Secret", "volume"},+ {"volumes[].persistentVolumeClaim.claimName", "PersistentVolumeClaim", "volume"},+ {"volumes[].projected.sources[].configMap.name", "ConfigMap", "volume"},+ {"volumes[].projected.sources[].secret.name", "Secret", "volume"},+};++static const k8s_leaf_ref_t k8s_container_refs[] = {+ {"env[].valueFrom.configMapKeyRef.name", "ConfigMap", "env"},+ {"env[].valueFrom.secretKeyRef.name", "Secret", "env"},+ {"envFrom[].configMapRef.name", "ConfigMap", "envFrom"},+ {"envFrom[].secretRef.name", "Secret", "envFrom"},+};++static const k8s_object_ref_t k8s_object_refs[] = {+ {"|Ingress|", "spec.rules[].http.paths[].backend.service.name", "Service", "ingress",+ "INFRA_MAPS"},+ {"|Ingress|", "spec.defaultBackend.service.name", "Service", "ingress", "INFRA_MAPS"},+ {"|Ingress|", "spec.tls[].secretName", "Secret", "tls", "USAGE"},+ {"|Ingress|", "spec.ingressClassName", "IngressClass", "ingressClassName", "USAGE"},+ {"|StatefulSet|", "spec.serviceName", "Service", "serviceName", "USAGE"},+ {"|PersistentVolumeClaim|", "spec.storageClassName", "StorageClass", "storageClassName",+ "USAGE"},+};++static const k8s_mapping_ref_t k8s_mapping_refs[] = {+ {"|RoleBinding|ClusterRoleBinding|", "roleRef", NULL, "|Role|ClusterRole|", NULL, "roleRef",+ "USAGE"},+ {"|RoleBinding|ClusterRoleBinding|", "subjects[]", NULL, "|ServiceAccount|", NULL, "subject",+ "USAGE"},+ {"|HorizontalPodAutoscaler|", "spec.scaleTargetRef", NULL, NULL, NULL, "scaleTarget", "USAGE"},+ {"|ValidatingWebhookConfiguration|MutatingWebhookConfiguration|",+ "webhooks[].clientConfig.service", "Service", NULL, NULL, "webhook", "INFRA_MAPS"},+ {"|APIService|", "spec.service", "Service", NULL, NULL, "apiservice", "INFRA_MAPS"},+ {"|HTTPRoute|GRPCRoute|TCPRoute|TLSRoute|UDPRoute|", "spec.rules[].backendRefs[]", NULL, NULL,+ "Service", "route", "INFRA_MAPS"},+ {"|HTTPRoute|GRPCRoute|TCPRoute|TLSRoute|UDPRoute|", "spec.parentRefs[]", NULL, NULL, "Gateway",+ "parentRef", "USAGE"},+};++// Is `kind` one of the "|A|B|" list?+static bool k8s_kind_in(const char *list, const char *kind) {+ if (!list || !kind[0]) {+ return false;+ }+ size_t n = strlen(kind);+ for (const char *p = strstr(list, kind); p; p = strstr(p + SKIP_ONE, kind)) {+ if (p[-SKIP_ONE] == '|' && p[n] == '|') {+ return true;+ }+ }+ return false;+}++// Where a kind keeps its pod spec, "" for none.+static const char *k8s_pod_prefix(const char *kind) {+ if (strcmp(kind, "Pod") == 0) {+ return "spec";+ }+ if (strcmp(kind, "CronJob") == 0) {+ return "spec.jobTemplate.spec.template.spec";+ }+ if (k8s_kind_in("|Deployment|StatefulSet|DaemonSet|ReplicaSet|ReplicationController|Job|",+ kind)) {+ return "spec.template.spec";+ }+ return "";+}++typedef struct {+ CBMExtractCtx *ctx;+ const char *kind; // the document's kind+ int def_index;+ char crd_group[K8S_BUF_SIZE];+ char crd_kind[K8S_BUF_SIZE];+} k8s_walk_t;++static void k8s_emit_ref(k8s_walk_t *w, const char *kind, const char *ns, const char *name,+ const char *via, const char *edge) {+ if (!kind || !kind[0] || !name || !name[0] || strstr(name, "{{") || strstr(kind, "{{")) {+ return;+ }+ CBMArena *a = w->ctx->arena;+ CBMK8sFact f = {.fact = CBM_K8S_FACT_REF,+ .def_index = w->def_index,+ .kind = cbm_arena_strdup(a, kind),+ .ns = ns && ns[0] && !strstr(ns, "{{") ? cbm_arena_strdup(a, ns) : NULL,+ .name = cbm_arena_strdup(a, name),+ .via = via,+ .edge = edge};+ cbm_k8sfact_push(&w->ctx->result->k8s_facts, a, f);+}++// A scalar at `path`: a leaf reference, or a CRD's group / kind.+static void k8s_leaf(k8s_walk_t *w, const char *path, const char *value) {+ const char *pod = k8s_pod_prefix(w->kind);+ size_t pl = strlen(pod);+ if (pl && strncmp(path, pod, pl) == 0 && path[pl] == '.') {+ const char *rel = path + pl + SKIP_ONE;+ for (size_t i = 0; i < sizeof(k8s_pod_refs) / sizeof(k8s_pod_refs[0]); i++) {+ if (strcmp(rel, k8s_pod_refs[i].path) == 0) {+ k8s_emit_ref(w, k8s_pod_refs[i].kind, NULL, value, k8s_pod_refs[i].via, "USAGE");+ }+ }+ static const char *const holders[] = {"containers[].", "initContainers[].",+ "ephemeralContainers[]."};+ for (size_t h = 0; h < sizeof(holders) / sizeof(holders[0]); h++) {+ size_t hl = strlen(holders[h]);+ if (strncmp(rel, holders[h], hl) != 0) {+ continue;+ }+ for (size_t i = 0; i < sizeof(k8s_container_refs) / sizeof(k8s_container_refs[0]);+ i++) {+ if (strcmp(rel + hl, k8s_container_refs[i].path) == 0) {+ k8s_emit_ref(w, k8s_container_refs[i].kind, NULL, value,+ k8s_container_refs[i].via, "USAGE");+ }+ }+ }+ }+ for (size_t i = 0; i < sizeof(k8s_object_refs) / sizeof(k8s_object_refs[0]); i++) {+ const k8s_object_ref_t *r = &k8s_object_refs[i];+ if (k8s_kind_in(r->kinds, w->kind) && strcmp(path, r->path) == 0) {+ k8s_emit_ref(w, r->kind, NULL, value, r->via, r->edge);+ }+ }+ if (strcmp(w->kind, "CustomResourceDefinition") == 0) {+ if (strcmp(path, "spec.group") == 0) {+ snprintf(w->crd_group, sizeof(w->crd_group), "%s", value);+ } else if (strcmp(path, "spec.names.kind") == 0) {+ snprintf(w->crd_kind, sizeof(w->crd_kind), "%s", value);+ }+ }+}++// Through block_node / flow_node wrappers to the content node.+static TSNode k8s_unwrap(TSNode node) {+ for (int i = 0; i < PAIR_LEN && !ts_node_is_null(node); i++) {+ const char *t = ts_node_type(node);+ if (strcmp(t, "block_node") == 0) {+ node = first_content_child(node);+ } else if (strcmp(t, "flow_node") == 0) {+ node = flow_node_value(node);+ } else {+ break;+ }+ }+ return node;+}++static bool k8s_is_mapping(TSNode n) {+ const char *t = ts_node_type(n);+ return strcmp(t, "block_mapping") == 0 || strcmp(t, "flow_mapping") == 0;+}++static bool k8s_is_pair(TSNode n) {+ const char *t = ts_node_type(n);+ return strcmp(t, "block_mapping_pair") == 0 || strcmp(t, "flow_pair") == 0;+}++// The scalar value of `field` in a mapping, or NULL.+static const char *k8s_field(k8s_walk_t *w, TSNode mapping, const char *field) {+ uint32_t n = ts_node_named_child_count(mapping);+ for (uint32_t i = 0; i < n; i++) {+ TSNode pair = ts_node_named_child(mapping, i);+ if (!k8s_is_pair(pair)) {+ continue;+ }+ TSNode key = ts_node_named_child(pair, 0);+ const char *k =+ ts_node_is_null(key) ? NULL : get_scalar_text(w->ctx->arena, key, w->ctx->source);+ if (k && strcmp(k, field) == 0) {+ TSNode v = unwrap_pair_value(pair);+ return ts_node_is_null(v) ? NULL : get_scalar_text(w->ctx->arena, v, w->ctx->source);+ }+ }+ return NULL;+}++// A mapping at `path` that holds a reference in its kind/name/namespace.+static void k8s_mapping(k8s_walk_t *w, const char *path, TSNode mapping) {+ for (size_t i = 0; i < sizeof(k8s_mapping_refs) / sizeof(k8s_mapping_refs[0]); i++) {+ const k8s_mapping_ref_t *r = &k8s_mapping_refs[i];+ if (!k8s_kind_in(r->kinds, w->kind) || strcmp(path, r->path) != 0) {+ continue;+ }+ const char *kind = r->kind;+ if (!kind) {+ kind = k8s_field(w, mapping, "kind");+ kind = kind ? kind : r->dflt;+ if (!kind || (r->allowed && !k8s_kind_in(r->allowed, kind))) {+ continue;+ }+ }+ k8s_emit_ref(w, kind, k8s_field(w, mapping, "namespace"), k8s_field(w, mapping, "name"),+ r->via, r->edge);+ }+}++// Walk `node` (reached at `path`) for references.+static void k8s_walk(k8s_walk_t *w, TSNode node, char *path, size_t len, size_t cap) {+ node = k8s_unwrap(node);+ if (ts_node_is_null(node)) {+ return;+ }+ const char *type = ts_node_type(node);+ if (k8s_is_mapping(node)) {+ k8s_mapping(w, path, node);+ uint32_t n = ts_node_named_child_count(node);+ for (uint32_t i = 0; i < n; i++) {+ TSNode pair = ts_node_named_child(node, i);+ if (!k8s_is_pair(pair)) {+ continue;+ }+ TSNode key = ts_node_named_child(pair, 0);+ const char *k =+ ts_node_is_null(key) ? NULL : get_scalar_text(w->ctx->arena, key, w->ctx->source);+ int add = k ? snprintf(path + len, cap - len, "%s%s", len ? "." : "", k) : -1;+ if (add <= 0 || len + (size_t)add >= cap) {+ path[len] = '\0'; // a path too long for any reference path: not one+ continue;+ }+ TSNode value = unwrap_pair_value(pair);+ TSNode inner = k8s_unwrap(value);+ const char *scalar = ts_node_is_null(inner)+ ? NULL+ : get_scalar_text(w->ctx->arena, inner, w->ctx->source);+ if (scalar) {+ k8s_leaf(w, path, scalar);+ } else if (!ts_node_is_null(value)) {+ k8s_walk(w, value, path, len + (size_t)add, cap);+ }+ path[len] = '\0';+ }+ return;+ }+ if (strcmp(type, "block_sequence") == 0 || strcmp(type, "flow_sequence") == 0) {+ int add = snprintf(path + len, cap - len, "[]");+ if (add <= 0 || len + (size_t)add >= cap) {+ path[len] = '\0';+ return;+ }+ uint32_t n = ts_node_named_child_count(node);+ for (uint32_t i = 0; i < n; i++) {+ TSNode item = ts_node_named_child(node, i);+ if (strcmp(ts_node_type(item), "block_sequence_item") == 0) {+ item = first_content_child(item);+ }+ if (!ts_node_is_null(item) && strcmp(ts_node_type(item), "comment") != 0) {+ k8s_walk(w, item, path, len + (size_t)add, cap);+ }+ }+ path[len] = '\0';+ }+}++// The references and CRD declaration of document def `def_index`.+static void k8s_emit_facts(CBMExtractCtx *ctx, TSNode mapping, const char *kind, int def_index) {+ k8s_walk_t w = {.ctx = ctx, .kind = kind, .def_index = def_index};+ char path[CBM_SZ_512] = "";+ k8s_walk(&w, mapping, path, 0, sizeof(path));+ if (w.crd_group[0] && w.crd_kind[0]) {+ CBMK8sFact f = {.fact = CBM_K8S_FACT_CRD,+ .def_index = def_index,+ .kind = cbm_arena_strdup(ctx->arena, w.crd_kind),+ .name = cbm_arena_strdup(ctx->arena, w.crd_group)};+ cbm_k8sfact_push(&ctx->result->k8s_facts, ctx->arena, f);+ }+}+// "<project>.<rel_path segments>" with the extension kept: the File node's QN// without ".__file__" (IDENTITY.md). Unique per file, unlike the module QN,// which drops the extension (`a.yaml` / `a.yml`, `x/` / `x.yaml`).@@ -420,6 +726,7 @@ static void extract_k8s_manifest(CBMExtractCtx *ctx) {def.start_line = ts_node_start_point(mapping).row + TS_LINE_OFFSET;def.end_line = ts_node_end_point(mapping).row + TS_LINE_OFFSET;cbm_defs_push(&ctx->result->defs, a, def);+ k8s_emit_facts(ctx, mapping, id.kind, ctx->result->defs.count - SKIP_ONE);}}diff --git a/src/pipeline/pass_k8s.c b/src/pipeline/pass_k8s.cindex 818a791d4..f09037b08 100644--- a/src/pipeline/pass_k8s.c+++ b/src/pipeline/pass_k8s.c@@ -1069,6 +1069,265 @@ static void k8s_apply_effective_namespaces(cbm_pipeline_ctx_t *ctx, k8s_bundles_}}+/* ── Object references (PHASE1.md) ───────────────────────────────── */++/* A reference fact of a manifest, kept past its file's extraction. */+typedef struct {+ int64_t src; /* the referencing Resource */+ char *kind; /* target kind */+ char *ns; /* explicit target namespace, NULL = the source's */+ char *name; /* target metadata.name */+ const char *via; /* static: the extractor's table */+ const char *edge; /* static: "USAGE" or "INFRA_MAPS" */+} k8s_ref_t;++/* A CRD and the group/kind it declares. */+typedef struct {+ int64_t node;+ char *group;+ char *kind;+} k8s_crd_t;++typedef struct {+ k8s_ref_t *refs;+ int ref_n;+ int ref_cap;+ k8s_crd_t *crds;+ int crd_n;+ int crd_cap;+} k8s_facts_t;++static void k8s_facts_free(k8s_facts_t *f) {+ for (int i = 0; i < f->ref_n; i++) {+ cbm_free(CBM_MEM_CLASS_OTHER, f->refs[i].kind);+ cbm_free(CBM_MEM_CLASS_OTHER, f->refs[i].ns);+ cbm_free(CBM_MEM_CLASS_OTHER, f->refs[i].name);+ }+ for (int i = 0; i < f->crd_n; i++) {+ cbm_free(CBM_MEM_CLASS_OTHER, f->crds[i].group);+ cbm_free(CBM_MEM_CLASS_OTHER, f->crds[i].kind);+ }+ cbm_free(CBM_MEM_CLASS_OTHER, f->refs);+ cbm_free(CBM_MEM_CLASS_OTHER, f->crds);+ *f = (k8s_facts_t){0};+}++/* Keep a file's facts, its def indices mapped to the Resource nodes. */+static void k8s_facts_keep(k8s_facts_t *f, const CBMFileResult *res, const int64_t *node_of) {+ for (int i = 0; i < res->k8s_facts.count; i++) {+ const CBMK8sFact *x = &res->k8s_facts.items[i];+ if (x->def_index < 0 || x->def_index >= res->defs.count || node_of[x->def_index] <= 0) {+ continue;+ }+ int64_t node = node_of[x->def_index];+ if (x->fact == CBM_K8S_FACT_CRD) {+ if (k8s_grow((void **)&f->crds, &f->crd_cap, f->crd_n, sizeof(*f->crds))) {+ f->crds[f->crd_n++] =+ (k8s_crd_t){node, cbm_mem_strdup(CBM_MEM_CLASS_OTHER, x->name),+ cbm_mem_strdup(CBM_MEM_CLASS_OTHER, x->kind)};+ }+ } else if (k8s_grow((void **)&f->refs, &f->ref_cap, f->ref_n, sizeof(*f->refs))) {+ f->refs[f->ref_n++] =+ (k8s_ref_t){.src = node,+ .kind = cbm_mem_strdup(CBM_MEM_CLASS_OTHER, x->kind),+ .ns = x->ns ? cbm_mem_strdup(CBM_MEM_CLASS_OTHER, x->ns) : NULL,+ .name = cbm_mem_strdup(CBM_MEM_CLASS_OTHER, x->name),+ .via = x->via,+ .edge = x->edge};+ }+ }+}++/* Does the target at `tgt` answer `ref` from `src`: one bundle, and the+ * namespace the reference asks for (explicit, else the source's own there)+ * agrees with the target's there? A cluster-scoped kind has no namespace. */+static bool k8s_ref_meets(k8s_bundles_t *b, const k8s_ref_t *ref, const cbm_gbuf_node_t *src,+ const cbm_gbuf_node_t *tgt) {+ k8s_member_t one_s[SKIP_ONE];+ k8s_member_t one_t[SKIP_ONE];+ k8s_members_t single_s = {.items = one_s, .cap = SKIP_ONE};+ k8s_members_t single_t = {.items = one_t, .cap = SKIP_ONE};+ const k8s_members_t *ms = k8s_bundles_of(b, src->file_path, &single_s);+ const k8s_members_t *mt = k8s_bundles_of(b, tgt->file_path, &single_t);+ char src_ns[K8S_LABEL_LEN];+ char tgt_ns[K8S_LABEL_LEN];+ k8s_declared_ns(src->qualified_name, src_ns, sizeof(src_ns));+ k8s_declared_ns(tgt->qualified_name, tgt_ns, sizeof(tgt_ns));+ bool cluster = k8s_cluster_scoped(ref->kind);+ for (int i = 0; i < ms->count; i++) {+ for (int j = 0; j < mt->count; j++) {+ if (ms->items[i].bundle != mt->items[j].bundle) {+ continue;+ }+ const char *want = ref->ns ? ref->ns : ms->items[i].ns ? ms->items[i].ns : src_ns;+ const char *have = mt->items[j].ns ? mt->items[j].ns : tgt_ns;+ if (cluster || !want[0] || !have[0] || strcmp(want, have) == 0) {+ return true;+ }+ }+ }+ return false;+}++/* Draw every reference to the object(s) it names inside its bundle;+ * an unresolved reference draws nothing. */+static void k8s_resolve_refs(cbm_pipeline_ctx_t *ctx, k8s_bundles_t *b, const k8s_facts_t *f) {+ int edges = 0;+ int unresolved = 0;+ for (int i = 0; i < f->ref_n; i++) {+ const k8s_ref_t *ref = &f->refs[i];+ const cbm_gbuf_node_t *src = cbm_gbuf_find_by_id(ctx->gbuf, ref->src);+ char name[CBM_SZ_1K];+ snprintf(name, sizeof(name), "%s/%s", ref->kind, ref->name);+ const cbm_gbuf_node_t **cands = NULL;+ int n = 0;+ if (!src || !src->file_path || cbm_gbuf_find_by_name(ctx->gbuf, name, &cands, &n) != 0) {+ n = 0;+ }+ char props[CBM_SZ_256];+ snprintf(props, sizeof(props), "{\"%s\":\"%s\"}",+ strcmp(ref->edge, "INFRA_MAPS") == 0 ? "kind" : "ref", ref->via);+ /* A name is one object per kind and namespace, so two declarations+ * of it in one bundle are alternatives (versioned manifests side by+ * side): the declaration in the reference's own file, when there is+ * one, is the one it means. */+ bool own_file = false;+ for (int c = 0; c < n && !own_file; c++) {+ const cbm_gbuf_node_t *t = cands[c];+ own_file = t != src && t->label && strcmp(t->label, "Resource") == 0 && t->file_path &&+ strcmp(t->file_path, src->file_path) == 0 && k8s_ref_meets(b, ref, src, t);+ }+ int hits = 0;+ for (int c = 0; c < n; c++) {+ const cbm_gbuf_node_t *t = cands[c];+ if (t == src || !t->label || strcmp(t->label, "Resource") != 0 || !t->file_path ||+ (own_file && strcmp(t->file_path, src->file_path) != 0) ||+ !k8s_ref_meets(b, ref, src, t)) {+ continue;+ }+ cbm_gbuf_insert_edge(ctx->gbuf, src->id, t->id, ref->edge, props);+ hits++;+ }+ edges += hits;+ unresolved += hits == 0;+ }+ if (f->ref_n > 0) {+ cbm_log_info("pass.k8s.refs", "refs", itoa_k8s(f->ref_n), "edges", itoa_k8s(edges),+ "unresolved", itoa_k8s(unresolved));+ }+}++/* A CRD's group/kind, for grouping the CRDs of one type. */+typedef struct {+ char key[CBM_SZ_512];+ int crd;+} k8s_crd_key_t;++static int k8s_cmp_crd_key(const void *a, const void *b) {+ const k8s_crd_key_t *x = a;+ const k8s_crd_key_t *y = b;+ int c = strcmp(x->key, y->key);+ return c ? c : (x->crd > y->crd) - (x->crd < y->crd);+}++/* Do the files at `a` and `b` share a bundle? */+static bool k8s_same_bundle(k8s_bundles_t *b, const char *a, const char *c) {+ k8s_member_t one_a[SKIP_ONE];+ k8s_member_t one_c[SKIP_ONE];+ k8s_members_t single_a = {.items = one_a, .cap = SKIP_ONE};+ k8s_members_t single_c = {.items = one_c, .cap = SKIP_ONE};+ const k8s_members_t *ma = k8s_bundles_of(b, a, &single_a);+ const k8s_members_t *mc = k8s_bundles_of(b, c, &single_c);+ for (int i = 0; i < ma->count; i++) {+ for (int j = 0; j < mc->count; j++) {+ if (ma->items[i].bundle == mc->items[j].bundle) {+ return true;+ }+ }+ }+ return false;+}++/* A custom resource is an instance of the CRD declaring its group and+ * kind. A CRD vendored in several places: the copy deployed with the+ * resource (one bundle) is the one; with no copy beside it, the resource+ * stands for all of them. */+static void k8s_link_crds(cbm_pipeline_ctx_t *ctx, k8s_bundles_t *b, const k8s_facts_t *f) {+ if (f->crd_n == 0) {+ return;+ }+ /* group/kind -> the run of its CRDs in `order` (sorted by group/kind), so+ * each resource visits only the CRDs of its own type. */+ k8s_crd_key_t *order = cbm_calloc(CBM_MEM_CLASS_OTHER, (size_t)f->crd_n * sizeof(*order));+ CBMHashTable *by_type = cbm_ht_create(0);+ if (!order || !by_type) {+ cbm_free(CBM_MEM_CLASS_OTHER, order);+ if (by_type) {+ cbm_ht_free(by_type);+ }+ return;+ }+ for (int i = 0; i < f->crd_n; i++) {+ snprintf(order[i].key, sizeof(order[i].key), "%s/%s", f->crds[i].group, f->crds[i].kind);+ order[i].crd = i;+ }+ qsort(order, (size_t)f->crd_n, sizeof(*order), k8s_cmp_crd_key);+ for (int i = f->crd_n - SKIP_ONE; i >= 0; i--) {+ cbm_ht_set(by_type, order[i].key, (void *)(intptr_t)(i + SKIP_ONE)); /* first of run */+ }+ const cbm_gbuf_node_t **nodes = NULL;+ int count = 0;+ int edges = 0;+ if (cbm_gbuf_find_by_label(ctx->gbuf, "Resource", &nodes, &count) == 0) {+ for (int i = 0; i < count; i++) {+ const char *key =+ nodes[i]->qualified_name ? strstr(nodes[i]->qualified_name, "::") : NULL;+ if (!key || !nodes[i]->file_path) {+ continue;+ }+ key += K8S_SLEN("::");+ const char *kind_end = strchr(key, '/');+ kind_end = kind_end ? strchr(kind_end + SKIP_ONE, '/') : NULL;+ if (!kind_end) {+ continue;+ }+ char type[CBM_SZ_512];+ snprintf(type, sizeof(type), "%.*s", (int)(kind_end - key), key);+ int first = (int)(intptr_t)cbm_ht_get(by_type, type) - SKIP_ONE;+ if (first < 0) {+ continue;+ }+ int end = first;+ while (end < f->crd_n && strcmp(order[end].key, type) == 0) {+ end++;+ }+ bool beside = false;+ for (int r = first; r < end && !beside; r++) {+ const cbm_gbuf_node_t *crd =+ cbm_gbuf_find_by_id(ctx->gbuf, f->crds[order[r].crd].node);+ beside = crd && crd->file_path &&+ k8s_same_bundle(b, nodes[i]->file_path, crd->file_path);+ }+ for (int r = first; r < end; r++) {+ int64_t crd_id = f->crds[order[r].crd].node;+ const cbm_gbuf_node_t *crd = cbm_gbuf_find_by_id(ctx->gbuf, crd_id);+ if (crd_id == nodes[i]->id ||+ (beside && (!crd || !crd->file_path ||+ !k8s_same_bundle(b, nodes[i]->file_path, crd->file_path)))) {+ continue;+ }+ cbm_gbuf_insert_edge(ctx->gbuf, nodes[i]->id, crd_id, "USAGE", "{\"ref\":\"crd\"}");+ edges++;+ }+ }+ }+ cbm_ht_free(by_type);+ cbm_free(CBM_MEM_CLASS_OTHER, order);+ if (edges > 0) {+ cbm_log_info("pass.k8s.crds", "instances", itoa_k8s(edges));+ }+}+/* Connect each Service to the workloads its selector targets via an INFRA_MAPS* edge (Service Resource → workload Resource), inside a shared bundle. */static void k8s_link_selectors(cbm_pipeline_ctx_t *ctx, const k8s_record_array_t *recs,@@ -1132,7 +1391,8 @@ static void k8s_link_selectors(cbm_pipeline_ctx_t *ctx, const k8s_record_array_t* must free after this call returns). Every Resource's own document is* recorded in `recs` for cross-manifest selector matching. */static void handle_k8s_manifest(cbm_pipeline_ctx_t *ctx, const char *rel_path, const char *source,- const CBMFileResult *res, k8s_record_array_t *recs) {+ const CBMFileResult *res, k8s_record_array_t *recs,+ k8s_facts_t *facts) {int resource_count = 0;if (!res) {@@ -1144,6 +1404,9 @@ static void handle_k8s_manifest(cbm_pipeline_ctx_t *ctx, const char *rel_path, cconst cbm_gbuf_node_t *file_node = file_qn ? cbm_gbuf_find_by_qn(ctx->gbuf, file_qn) : NULL;free(file_qn);+ int64_t *node_of =+ cbm_calloc(CBM_MEM_CLASS_OTHER,+ (size_t)(res->defs.count ? res->defs.count : SKIP_ONE) * sizeof(int64_t));for (int d = 0; d < res->defs.count; d++) {CBMDefinition *def = &res->defs.items[d];if (!def->label || strcmp(def->label, "Resource") != 0) {@@ -1168,9 +1431,16 @@ static void handle_k8s_manifest(cbm_pipeline_ctx_t *ctx, const char *rel_path, cif (node_id > 0 && source) {k8s_record_document(recs, node_id, source, (int)def->start_line, (int)def->end_line);}+ if (node_of) {+ node_of[d] = node_id;+ }resource_count++;}+ if (node_of) {+ k8s_facts_keep(facts, res, node_of);+ cbm_free(CBM_MEM_CLASS_OTHER, node_of);+ }cbm_log_info("pass.k8s.manifest", "file", rel_path, "resources", itoa_k8s(resource_count));}@@ -1580,6 +1850,7 @@ int cbm_pipeline_pass_k8s(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *files,k8s_local_deps_t local_deps = {0};k8s_kusts_t kusts = {0};k8s_bundles_t bundles = {.charts = cbm_ht_create(0)};+ k8s_facts_t facts = {0};k8s_prep_t *prep = cbm_calloc(CBM_MEM_CLASS_OTHER, K8S_CHUNK * sizeof(*prep));if (!prep) {@@ -1596,6 +1867,7 @@ int cbm_pipeline_pass_k8s(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *files,k8s_local_deps_free(&local_deps);k8s_kusts_free(&kusts);k8s_bundles_free(&bundles);+ k8s_facts_free(&facts);return CBM_NOT_FOUND;}memset(prep, 0, (size_t)K8S_CHUNK * sizeof(*prep));@@ -1628,7 +1900,7 @@ int cbm_pipeline_pass_k8s(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *files,k8s_kusts_push(&kusts, rel, k8s_kustomize_namespace(p->source));break;case K8S_MANIFEST:- handle_k8s_manifest(ctx, rel, p->source, p->res, &recs);+ handle_k8s_manifest(ctx, rel, p->source, p->res, &recs, &facts);manifest_count++;break;case K8S_SKIP:@@ -1647,6 +1919,7 @@ int cbm_pipeline_pass_k8s(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *files,k8s_local_deps_free(&local_deps);k8s_kusts_free(&kusts);k8s_bundles_free(&bundles);+ k8s_facts_free(&facts);return CBM_NOT_FOUND;}}@@ -1657,6 +1930,9 @@ int cbm_pipeline_pass_k8s(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *files,k8s_bundles_build(ctx, &kusts, &bundles);k8s_apply_effective_namespaces(ctx, &bundles);k8s_link_selectors(ctx, &recs, &bundles);+ k8s_resolve_refs(ctx, &bundles, &facts);+ k8s_link_crds(ctx, &bundles, &facts);+ k8s_facts_free(&facts);k8s_records_free(&recs);k8s_bundles_free(&bundles);k8s_kusts_free(&kusts);diff --git a/tests/test_grammar_probe_f.c b/tests/test_grammar_probe_f.cindex 7fc7ee08d..391687e23 100644--- a/tests/test_grammar_probe_f.c+++ b/tests/test_grammar_probe_f.c@@ -915,6 +915,193 @@ TEST(probe_tfvars_values_mint_no_route) {PASS();}+/* ── Object references (Phase 1, PHASE1.md) ────────────────────────── */++/* Edges of `type` between two Resources whose properties carry `prop`+ * (e.g. "\"ref\":\"volume\""); -1 when indexing failed. */+static int gpf_resource_edges(const GpfFile *files, int nfiles, const char *type,+ const char *prop) {+ GpfProj lp;+ cbm_store_t *store = gpf_index_files(&lp, files, nfiles);+ int n = -1;+ if (store) {+ sqlite3_stmt *st = NULL;+ const char *sql = "SELECT COUNT(*) FROM edges e JOIN nodes s ON s.id=e.source_id "+ "JOIN nodes t ON t.id=e.target_id WHERE e.project=?1 AND e.type=?2 "+ "AND s.label='Resource' AND t.label='Resource' AND instr(e.properties,?3)";+ if (sqlite3_prepare_v2(cbm_store_get_db(store), sql, -1, &st, NULL) == SQLITE_OK) {+ sqlite3_bind_text(st, 1, lp.project, -1, SQLITE_STATIC);+ sqlite3_bind_text(st, 2, type, -1, SQLITE_STATIC);+ sqlite3_bind_text(st, 3, prop, -1, SQLITE_STATIC);+ n = sqlite3_step(st) == SQLITE_ROW ? sqlite3_column_int(st, 0) : -1;+ }+ sqlite3_finalize(st);+ }+ gpf_cleanup(&lp, store);+ return n;+}++static const char k_pod_refs_app[] =+ "apiVersion: apps/v1\n"+ "kind: Deployment\n"+ "metadata:\n"+ " name: web\n"+ "spec:\n"+ " template:\n"+ " spec:\n"+ " serviceAccountName: web-sa\n"+ " imagePullSecrets:\n"+ " - name: registry-creds\n"+ " volumes:\n"+ " - name: cfg\n"+ " configMap:\n"+ " name: web-config\n"+ " - name: data\n"+ " persistentVolumeClaim:\n"+ " claimName: web-data\n"+ " containers:\n"+ " - name: web\n"+ " env:\n"+ " - name: DB_PASSWORD\n"+ " valueFrom:\n"+ " secretKeyRef:\n"+ " name: web-db\n"+ " key: password\n"+ " envFrom:\n"+ " - configMapRef:\n"+ " name: web-env\n"+ "---\n"+ "apiVersion: v1\nkind: ServiceAccount\nmetadata:\n name: web-sa\n"+ "---\n"+ "apiVersion: v1\nkind: Secret\nmetadata:\n name: registry-creds\n"+ "---\n"+ "apiVersion: v1\nkind: ConfigMap\nmetadata:\n name: web-config\n"+ "---\n"+ "apiVersion: v1\nkind: PersistentVolumeClaim\nmetadata:\n name: web-data\n"+ "---\n"+ "apiVersion: v1\nkind: Secret\nmetadata:\n name: web-db\n"+ "---\n"+ "apiVersion: v1\nkind: ConfigMap\nmetadata:\n name: web-env\n";++/* A workload's pod spec names the objects it runs with: its service+ * account, pull secret, mounted ConfigMap and claim, env sources. */+TEST(probe_k8s_pod_spec_references) {+ static const GpfFile files[] = {{"app.yaml", k_pod_refs_app}};+ ASSERT_EQ(gpf_resource_edges(files, 1, "USAGE", "\"ref\":\"serviceAccountName\""), 1);+ ASSERT_EQ(gpf_resource_edges(files, 1, "USAGE", "\"ref\":\"imagePullSecrets\""), 1);+ ASSERT_EQ(gpf_resource_edges(files, 1, "USAGE", "\"ref\":\"volume\""), 2);+ ASSERT_EQ(gpf_resource_edges(files, 1, "USAGE", "\"ref\":\"env\""), 1);+ ASSERT_EQ(gpf_resource_edges(files, 1, "USAGE", "\"ref\":\"envFrom\""), 1);+ PASS();+}++/* RBAC: a binding uses the role it names and the service accounts it+ * grants; an Ingress routes to its backend Service; an HPA scales its+ * target; a webhook configuration calls its Service. */+TEST(probe_k8s_rbac_ingress_hpa_webhook_references) {+ static const GpfFile files[] = {+ {"rbac.yaml",+ "apiVersion: rbac.authorization.k8s.io/v1\nkind: ClusterRole\nmetadata:\n name: reader\n"+ "---\n"+ "apiVersion: v1\nkind: ServiceAccount\nmetadata:\n name: web-sa\n namespace: prod\n"+ "---\n"+ "apiVersion: rbac.authorization.k8s.io/v1\nkind: ClusterRoleBinding\n"+ "metadata:\n name: web-reader\n"+ "roleRef:\n apiGroup: rbac.authorization.k8s.io\n kind: ClusterRole\n name: reader\n"+ "subjects:\n - kind: ServiceAccount\n name: web-sa\n namespace: prod\n"},+ {"web.yaml",+ "apiVersion: v1\nkind: Service\nmetadata:\n name: web\n namespace: prod\n"+ "---\n"+ "apiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: web\n namespace: prod\n"+ "---\n"+ "apiVersion: networking.k8s.io/v1\nkind: Ingress\nmetadata:\n name: web\n"+ " namespace: prod\nspec:\n rules:\n - host: web.example.com\n http:\n"+ " paths:\n - path: /\n pathType: Prefix\n"+ " backend:\n service:\n name: web\n"+ " port:\n number: 80\n"+ "---\n"+ "apiVersion: autoscaling/v2\nkind: HorizontalPodAutoscaler\nmetadata:\n name: web\n"+ " namespace: prod\nspec:\n scaleTargetRef:\n apiVersion: apps/v1\n"+ " kind: Deployment\n name: web\n"+ "---\n"+ "apiVersion: admissionregistration.k8s.io/v1\nkind: ValidatingWebhookConfiguration\n"+ "metadata:\n name: web-hook\nwebhooks:\n - name: validate.web.example.com\n"+ " clientConfig:\n service:\n name: web\n namespace: prod\n"}};+ ASSERT_EQ(gpf_resource_edges(files, 2, "USAGE", "\"ref\":\"roleRef\""), 1);+ ASSERT_EQ(gpf_resource_edges(files, 2, "USAGE", "\"ref\":\"subject\""), 1);+ ASSERT_EQ(gpf_resource_edges(files, 2, "INFRA_MAPS", "\"kind\":\"ingress\""), 1);+ ASSERT_EQ(gpf_resource_edges(files, 2, "USAGE", "\"ref\":\"scaleTarget\""), 1);+ ASSERT_EQ(gpf_resource_edges(files, 2, "INFRA_MAPS", "\"kind\":\"webhook\""), 1);+ PASS();+}++/* A custom resource is an instance of the CRD that declares its group and+ * kind; a reference to an object that is not in the repo draws nothing. */+TEST(probe_k8s_cr_uses_its_crd_and_unresolved_draws_nothing) {+ static const GpfFile files[] = {+ {"crd.yaml",+ "apiVersion: apiextensions.k8s.io/v1\nkind: CustomResourceDefinition\n"+ "metadata:\n name: widgets.example.com\nspec:\n group: example.com\n"+ " names:\n kind: Widget\n plural: widgets\n scope: Namespaced\n"},+ {"widget.yaml",+ "apiVersion: example.com/v1\nkind: Widget\nmetadata:\n name: w1\n"+ "---\n"+ "apiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: lonely\nspec:\n"+ " template:\n spec:\n serviceAccountName: not-in-repo\n"}};+ ASSERT_EQ(gpf_resource_edges(files, 2, "USAGE", "\"ref\":\"crd\""), 1);+ ASSERT_EQ(gpf_resource_edges(files, 2, "USAGE", "\"ref\":\"serviceAccountName\""), 0);+ PASS();+}++/* References resolve inside the bundle: a ConfigMap of the same name in+ * another directory (another app's copy) is not the one mounted. */+TEST(probe_k8s_reference_stays_in_bundle) {+ static const GpfFile files[] = {+ {"a/app.yaml",+ "apiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: web\nspec:\n template:\n"+ " spec:\n volumes:\n - name: cfg\n configMap:\n"+ " name: web-config\n"+ "---\n"+ "apiVersion: v1\nkind: ConfigMap\nmetadata:\n name: web-config\n"},+ {"b/cm.yaml", "apiVersion: v1\nkind: ConfigMap\nmetadata:\n name: web-config\n"}};+ ASSERT_EQ(gpf_resource_edges(files, 2, "USAGE", "\"ref\":\"volume\""), 1);+ PASS();+}++/* A name is one object per kind and namespace: two declarations of it in+ * one bundle are alternatives (kubermatic keeps canal_v3.21 ... v3.31 side+ * by side; one is applied). A reference means the declaration in its own+ * file when there is one. */+TEST(probe_k8s_reference_prefers_its_own_file) {+ static const char v1[] =+ "apiVersion: apps/v1\nkind: DaemonSet\nmetadata:\n name: canal\nspec:\n template:\n"+ " spec:\n volumes:\n - name: cfg\n configMap:\n"+ " name: canal-config\n"+ "---\n"+ "apiVersion: v1\nkind: ConfigMap\nmetadata:\n name: canal-config\n";+ static const GpfFile files[] = {{"canal/canal_v1.yaml", v1}, {"canal/canal_v2.yaml", v1}};+ ASSERT_EQ(gpf_resource_edges(files, 2, "USAGE", "\"ref\":\"volume\""), 2);+ PASS();+}++/* A CRD vendored twice (gardener: example/seed-crds and a chart): a custom+ * resource is an instance of the copy deployed with it; only when no copy+ * shares its bundle does it stand for all of them. */+TEST(probe_k8s_cr_prefers_the_crd_in_its_bundle) {+ static const char crd[] =+ "apiVersion: apiextensions.k8s.io/v1\nkind: CustomResourceDefinition\n"+ "metadata:\n name: widgets.example.com\nspec:\n group: example.com\n"+ " names:\n kind: Widget\n plural: widgets\n scope: Namespaced\n";+ static const char cr[] = "apiVersion: example.com/v1\nkind: Widget\nmetadata:\n name: w1\n";+ static const GpfFile files[] = {{"app/crd.yaml", crd},+ {"app/widget.yaml", cr},+ {"vendor-chart/crds/crd.yaml", crd},+ {"other/widget.yaml", cr}};+ /* app/widget -> app/crd only; other/widget (no copy beside it) -> both */+ ASSERT_EQ(gpf_resource_edges(files, 4, "USAGE", "\"ref\":\"crd\""), 3);+ PASS();+}+/* ── Bundles: a Service selects inside what is deployed together ───── */#define GPF_DEPLOY(name, label) \@@ -2489,6 +2676,12 @@ SUITE(grammar_probe_f) {RUN_TEST(probe_secret_stringdata_mints_no_route);RUN_TEST(probe_endpoint_url_loses_credentials);RUN_TEST(probe_tfvars_values_mint_no_route);+ RUN_TEST(probe_k8s_pod_spec_references);+ RUN_TEST(probe_k8s_rbac_ingress_hpa_webhook_references);+ RUN_TEST(probe_k8s_cr_uses_its_crd_and_unresolved_draws_nothing);+ RUN_TEST(probe_k8s_reference_stays_in_bundle);+ RUN_TEST(probe_k8s_reference_prefers_its_own_file);+ RUN_TEST(probe_k8s_cr_prefers_the_crd_in_its_bundle);RUN_TEST(probe_k8s_selector_stays_in_its_directory);RUN_TEST(probe_k8s_selector_within_kustomize_build);RUN_TEST(probe_k8s_kustomize_namespace_is_effective);