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): every manifest document is an object with a stable identity
Martin Vogel69ac2846f2ad
diff --git a/internal/cbm/extract_k8s.c b/internal/cbm/extract_k8s.cindex 88f8a46f8..46937668d 100644--- a/internal/cbm/extract_k8s.c+++ b/internal/cbm/extract_k8s.c@@ -4,9 +4,11 @@// matches "resources", "bases", "patches", "components", or// "patchesStrategicMerge", then emits one CBMImport per block_sequence item.//-// For CBM_LANG_K8S: finds apiVersion, kind, and metadata.name scalars in the-// first document's block_mapping and emits one CBMDefinition with label-// "Resource" and name "Kind/metadata-name".+// For CBM_LANG_K8S: reads apiVersion, kind, metadata.name and+// metadata.namespace of EVERY document and emits one CBMDefinition per object:+// label "Resource", name "Kind/metadata-name", QN+// "<file-base>::<group>/<Kind>/<declared namespace or ->/<name>" (identity+// spec: the file base keeps the extension, so it is unique per file).#include "cbm.h"#include "arena.h"@@ -20,24 +22,39 @@/* Local constants. */enum {K8S_BUF_SIZE = 256,- RESULT_BUF_SIZE = 512,};// ---------------------------------------------------------------------------// Internal helpers// ---------------------------------------------------------------------------+// The value inside a flow_node: its first named child that is not an anchor+// (`&name`), a tag (`!!str`) or a comment, all of which precede the value.+static TSNode flow_node_value(TSNode node) {+ uint32_t n = ts_node_named_child_count(node);+ for (uint32_t i = 0; i < n; i++) {+ TSNode child = ts_node_named_child(node, i);+ const char *type = ts_node_type(child);+ if (strcmp(type, "anchor") != 0 && strcmp(type, "tag") != 0 &&+ strcmp(type, "comment") != 0) {+ return child;+ }+ }+ TSNode null_node = {0};+ return null_node;+}+// Return the raw source text for a scalar node (plain, single-quoted, or// double-quoted). Surrounding quote characters are stripped for quoted forms.-// Handles flow_node wrappers transparently by descending into the first named-// child (the tree-sitter YAML grammar often wraps scalars in flow_node).+// Handles flow_node wrappers transparently by descending into the value they+// wrap (the tree-sitter YAML grammar often wraps scalars in flow_node).// Returns NULL for non-scalar node types.static const char *get_scalar_text(CBMArena *a, TSNode node, const char *source) {enum { MAX_UNWRAP = 4 };for (int depth = 0; depth < MAX_UNWRAP; depth++) {const char *type = ts_node_type(node);if (strcmp(type, "flow_node") == 0) {- TSNode inner = ts_node_named_child(node, 0);+ TSNode inner = flow_node_value(node);if (ts_node_is_null(inner)) {return NULL;}@@ -241,9 +258,17 @@ static void extract_kustomize(CBMExtractCtx *ctx) {// K8s manifest extraction// ----------------------------------------------------------------------------// Extract the "name" scalar from a metadata block_mapping.-static void extract_metadata_name(CBMArena *a, TSNode meta_mapping, const char *source,- char *meta_name_buf, size_t meta_sz) {+// The identity scalars of one manifest document.+typedef struct {+ char api_version[K8S_BUF_SIZE];+ char kind[K8S_BUF_SIZE];+ char name[K8S_BUF_SIZE];+ char ns[K8S_BUF_SIZE];+} k8s_doc_id_t;++// Read metadata.name and metadata.namespace from a metadata block_mapping.+static void extract_metadata(CBMArena *a, TSNode meta_mapping, const char *source,+ k8s_doc_id_t *id) {if (ts_node_is_null(meta_mapping) || strcmp(ts_node_type(meta_mapping), "block_mapping") != 0) {return;}@@ -258,28 +283,22 @@ static void extract_metadata_name(CBMArena *a, TSNode meta_mapping, const char *continue;}const char *mkey_text = get_scalar_text(a, mkey, source);- if (!mkey_text || strcmp(mkey_text, "name") != 0) {+ bool is_name = mkey_text && strcmp(mkey_text, "name") == 0;+ bool is_ns = mkey_text && strcmp(mkey_text, "namespace") == 0;+ if (!is_name && !is_ns) {continue;}TSNode mval = unwrap_pair_value(mpair);- if (ts_node_is_null(mval)) {- continue;- }- const char *meta_name = get_scalar_text(a, mval, source);- if (meta_name) {- snprintf(meta_name_buf, meta_sz, "%s", meta_name);+ const char *text = ts_node_is_null(mval) ? NULL : get_scalar_text(a, mval, source);+ if (text) {+ snprintf(is_name ? id->name : id->ns, K8S_BUF_SIZE, "%s", text);}}}-// Descend into the first block_mapping of a document and extract-// kind and metadata.name. Returns void; fills kind_buf and meta_name_buf.-static void extract_k8s_scalars(CBMExtractCtx *ctx, TSNode mapping, char *kind_buf, size_t kind_sz,- char *meta_name_buf, size_t meta_sz) {+// Read apiVersion, kind and metadata from a document's top-level mapping.+static void extract_k8s_scalars(CBMExtractCtx *ctx, TSNode mapping, k8s_doc_id_t *id) {CBMArena *a = ctx->arena;- kind_buf[0] = '\0';- meta_name_buf[0] = '\0';-uint32_t n = ts_node_child_count(mapping);for (uint32_t i = 0; i < n; i++) {TSNode pair = ts_node_child(mapping, i);@@ -294,25 +313,75 @@ static void extract_k8s_scalars(CBMExtractCtx *ctx, TSNode mapping, char *kind_bif (!key) {continue;}-TSNode val_node = unwrap_pair_value(pair);if (ts_node_is_null(val_node)) {continue;}+ if (strcmp(key, "metadata") == 0) {+ extract_metadata(a, val_node, ctx->source, id);+ continue;+ }+ char *dst = strcmp(key, "kind") == 0 ? id->kind+ : strcmp(key, "apiVersion") == 0 ? id->api_version+ : NULL;+ const char *v = dst ? get_scalar_text(a, val_node, ctx->source) : NULL;+ if (v) {+ snprintf(dst, K8S_BUF_SIZE, "%s", v);+ }+ }+}- if (strcmp(key, "kind") == 0) {- const char *v = get_scalar_text(a, val_node, ctx->source);- if (v) {- snprintf(kind_buf, kind_sz, "%s", v);- }- } else if (strcmp(key, "metadata") == 0) {- extract_metadata_name(a, val_node, ctx->source, meta_name_buf, meta_sz);+// "<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`).+static const char *k8s_file_base(CBMArena *a, const char *project, const char *rel_path) {+ project = project ? project : "";+ rel_path = rel_path ? rel_path : "";+ size_t plen = strlen(project);+ char *buf = cbm_arena_alloc(a, plen + strlen(rel_path) + PAIR_LEN);+ if (!buf) {+ return NULL;+ }+ char *o = buf;+ memcpy(o, project, plen);+ o += plen;+ bool seg_start = true;+ for (const char *p = rel_path; *p; p++) {+ char c = *p == '\\' ? '/' : *p;+ if (c == '/') {+ seg_start = true;+ continue;}+ if (seg_start) {+ *o++ = '.';+ seg_start = false;+ }+ *o++ = c;+ }+ *o = '\0';+ return buf;+}++// The API group of an apiVersion: the part before '/', "core" for the core+// group ("v1"), "?" when the document names none. The version is not part of+// an object's identity.+static void k8s_api_group(const char *api_version, char *out, size_t out_sz) {+ const char *slash = strchr(api_version, '/');+ if (slash) {+ snprintf(out, out_sz, "%.*s", (int)(slash - api_version), api_version);+ } else {+ snprintf(out, out_sz, "%s", api_version[0] ? "core" : "?");}}+// One Resource def per document: `Kind/name`, QN+// `<file-base>::<group>/<Kind>/<declared namespace or ->/<name>` (IDENTITY.md).static void extract_k8s_manifest(CBMExtractCtx *ctx) {CBMArena *a = ctx->arena;+ const char *base = k8s_file_base(a, ctx->project, ctx->rel_path);+ if (!base) {+ return;+ }TSNode root = ctx->root;uint32_t root_n = ts_node_child_count(root);@@ -327,22 +396,22 @@ static void extract_k8s_manifest(CBMExtractCtx *ctx) {continue;}- char kind_buf[K8S_BUF_SIZE] = {0};- char meta_name_buf[K8S_BUF_SIZE] = {0};- extract_k8s_scalars(ctx, mapping, kind_buf, sizeof(kind_buf), meta_name_buf,- sizeof(meta_name_buf));+ k8s_doc_id_t id;+ memset(&id, 0, sizeof(id));+ extract_k8s_scalars(ctx, mapping, &id);// Skip malformed manifests (no kind or no metadata.name)- if (kind_buf[0] == '\0' || meta_name_buf[0] == '\0') {+ if (id.kind[0] == '\0' || id.name[0] == '\0') {continue;}- char def_name[RESULT_BUF_SIZE];- snprintf(def_name, sizeof(def_name), "%s/%s", kind_buf, meta_name_buf);+ char group[K8S_BUF_SIZE];+ k8s_api_group(id.api_version, group, sizeof(group));CBMDefinition def = {0};- def.name = cbm_arena_strdup(a, def_name);- def.qualified_name = cbm_arena_sprintf(a, "%s.%s", ctx->module_qn, def_name);+ def.name = cbm_arena_sprintf(a, "%s/%s", id.kind, id.name);+ def.qualified_name = cbm_arena_sprintf(a, "%s::%s/%s/%s/%s", base, group, id.kind,+ id.ns[0] ? id.ns : "-", id.name);// "Resource" is the canonical def label for a K8s resource kind. It is a// valid graph label and is what the K8s pipeline pass (pass_k8s.c) filters// on to upsert Resource nodes and emit INFRA_MAPS edges.@@ -351,8 +420,6 @@ 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);-- break; // Only the first document per file}}diff --git a/src/pipeline/pass_k8s.c b/src/pipeline/pass_k8s.cindex 040cb1688..ea7cdfa6a 100644--- a/src/pipeline/pass_k8s.c+++ b/src/pipeline/pass_k8s.c@@ -284,7 +284,47 @@ static void k8s_parent_path(char *out, size_t out_sz, const char (*keys)[64], in}}-/* Scan a single-document k8s manifest's text for its name, namespace, kind and+/* `key: { a: b, c: d }` — a flow-style map is the same label map written on+ * one line. One the line buffer cut short (no closing brace) is skipped+ * whole: a selector missing pairs would select too much. */+static void k8s_scan_flow_map(k8s_scanned_t *out, const char (*keys)[64], int depth,+ const char *key, const char *val) {+ size_t n = strlen(val);+ if (n < PAIR_LEN || val[0] != '{' || val[n - SKIP_ONE] != '}') {+ return;+ }+ char path[CBM_SZ_512];+ k8s_parent_path(path, sizeof(path), keys, depth);+ size_t w = strlen(path);+ snprintf(path + w, sizeof(path) - w, "%s%s", w ? "." : "", key);+ k8s_pair_block_t block = k8s_pair_block(path);+ if (block == K8S_PAIR_NONE) {+ return;+ }+ char inner[CBM_SZ_512];+ snprintf(inner, sizeof(inner), "%.*s", (int)(n - PAIR_LEN), val + SKIP_ONE);+ for (char *item = inner; item;) {+ char *comma = strchr(item, ',');+ if (comma) {+ *comma = '\0';+ }+ while (*item == ' ') {+ item++;+ }+ char k[64];+ char v[K8S_LABEL_LEN];+ if (k8s_split_kv(item, k, sizeof(k), v, sizeof(v)) && v[0]) {+ size_t kl = strlen(k);+ while (kl > 0 && k[kl - SKIP_ONE] == ' ') {+ k[--kl] = '\0';+ }+ k8s_scanned_push(out, block, k, v);+ }+ item = comma ? comma + SKIP_ONE : NULL;+ }+}++/* Scan ONE manifest document's text for its name, namespace, kind and* label pairs into `rec` / `out`. A small indentation path-stack gives every* leaf its parent path, which tells spec.selector from the pod template's* labels and from the object's own metadata.labels. */@@ -305,7 +345,7 @@ static void k8s_scan_labels(const char *source, k8s_record_t *rec, k8s_scanned_tmemcpy(line, p, cp);line[cp] = '\0';- /* End of first YAML document — stop (one Resource per file). */+ /* End of the document — stop (the caller hands over one document). */const char *trimmed = line;while (*trimmed == ' ') {trimmed++;@@ -329,7 +369,7 @@ static void k8s_scan_labels(const char *source, k8s_record_t *rec, k8s_scanned_tdepth--;}char key[64];- char val[K8S_LABEL_LEN];+ char val[CBM_SZ_512]; /* a whole flow map fits: the line is the limit */if (k8s_split_kv(trimmed, key, sizeof(key), val, sizeof(val))) {if (val[0] == '\0') {/* Block-opening key: push onto the path stack. */@@ -340,6 +380,8 @@ static void k8s_scan_labels(const char *source, k8s_record_t *rec, k8s_scanned_t}} else if (ind == 0 && strcmp(key, "kind") == 0) {rec->kind = k8s_rec_kind(val);+ } else if (val[0] == '{') {+ k8s_scan_flow_map(out, (const char (*)[64])keys, depth, key, val);} else if (depth == 1 && strcmp(keys[0], "metadata") == 0) {if (!got_name && strcmp(key, "name") == 0) {snprintf(rec->name, sizeof(rec->name), "%s", val);@@ -419,6 +461,115 @@ static void k8s_record_manifest(k8s_record_array_t *recs, int64_t node_id, constcbm_free(CBM_MEM_CLASS_OTHER, scanned.items);}+/* Record the document at lines [start_line, end_line] (1-based, inclusive) of+ * a multi-document manifest: every object's selector or pod labels come from+ * its own document. */+static void k8s_record_document(k8s_record_array_t *recs, int64_t node_id, const char *source,+ int start_line, int end_line) {+ const char *begin = source;+ for (int line = 1; begin && line < start_line; line++) {+ begin = strchr(begin, '\n');+ begin = begin ? begin + SKIP_ONE : NULL;+ }+ if (!begin) {+ return;+ }+ const char *end = begin;+ for (int line = start_line; *end && line <= end_line; line++) {+ const char *eol = strchr(end, '\n');+ end = eol ? eol + SKIP_ONE : end + strlen(end);+ }+ size_t n = (size_t)(end - begin);+ char *doc = cbm_alloc(CBM_MEM_CLASS_OTHER, n + SKIP_ONE);+ if (!doc) {+ return;+ }+ memcpy(doc, begin, n);+ doc[n] = '\0';+ k8s_record_manifest(recs, node_id, doc);+ cbm_free(CBM_MEM_CLASS_OTHER, doc);+}++/* Built-in kinds that live outside any namespace (IDENTITY.md). A CRD's own+ * scope (spec.scope) is the curated / generated table's job. */+static bool k8s_cluster_scoped(const char *kind) {+ static const char *const kinds[] = {"Namespace",+ "Node",+ "PersistentVolume",+ "ClusterRole",+ "ClusterRoleBinding",+ "CustomResourceDefinition",+ "StorageClass",+ "PriorityClass",+ "ValidatingWebhookConfiguration",+ "MutatingWebhookConfiguration",+ "APIService",+ "CSIDriver",+ "CSINode",+ "IngressClass",+ "RuntimeClass",+ "VolumeAttachment",+ "ValidatingAdmissionPolicy",+ "ValidatingAdmissionPolicyBinding",+ "ClusterIssuer"};+ for (size_t i = 0; i < sizeof(kinds) / sizeof(kinds[0]); i++) {+ if (strcmp(kind, kinds[i]) == 0) {+ return true;+ }+ }+ return false;+}++/* A Resource's properties from its identity key, the part of its QN after+ * "::": `<group>/<Kind>/<declared namespace or ->/<name>` (IDENTITY.md).+ * `obj_key` is the logical identity: the namespace it lives in, `_` for a+ * cluster-scoped kind, `?` when the deploy decides. NULL for a QN without a+ * well-formed key (the caller keeps the plain source tag). */+static char *k8s_resource_props(const char *qn) {+ enum { K8S_KEY_PARTS = 4, K8S_ESC = 6 * K8S_LABEL_LEN };+ const char *key = qn ? strstr(qn, "::") : NULL;+ if (!key) {+ return NULL;+ }+ key += K8S_SLEN("::");+ char part[K8S_KEY_PARTS][K8S_LABEL_LEN];+ int parts = 0;+ for (const char *p = key; parts < K8S_KEY_PARTS; parts++) {+ const char *slash = parts < K8S_KEY_PARTS - SKIP_ONE ? strchr(p, '/') : NULL;+ size_t len = slash ? (size_t)(slash - p) : strlen(p);+ if (len == 0 || len >= K8S_LABEL_LEN || (!slash && parts < K8S_KEY_PARTS - SKIP_ONE)) {+ return NULL;+ }+ memcpy(part[parts], p, len);+ part[parts][len] = '\0';+ p = slash ? slash + SKIP_ONE : p + len;+ }+ const char *group = part[0];+ const char *kind = part[1];+ const char *ns = strcmp(part[2], "-") == 0 ? "" : part[2];+ const char *name = part[3];+ const char *effective = k8s_cluster_scoped(kind) ? "_" : ns[0] ? ns : "?";+ char esc[K8S_KEY_PARTS + SKIP_ONE][K8S_ESC];+ cbm_json_escape(esc[0], K8S_ESC, group);+ cbm_json_escape(esc[1], K8S_ESC, kind);+ cbm_json_escape(esc[2], K8S_ESC, ns);+ cbm_json_escape(esc[3], K8S_ESC, name);+ cbm_json_escape(esc[4], K8S_ESC, effective);+ size_t n = K8S_KEY_PARTS * K8S_ESC + K8S_ESC + CBM_SZ_256;+ char *props = cbm_alloc(CBM_MEM_CLASS_OTHER, n);+ if (!props) {+ return NULL;+ }+ int w =+ snprintf(props, n, "{\"source\":\"k8s\",\"group\":\"%s\",\"kind\":\"%s\"", esc[0], esc[1]);+ if (ns[0]) {+ w += snprintf(props + w, n - (size_t)w, ",\"namespace\":\"%s\"", esc[2]);+ }+ snprintf(props + w, n - (size_t)w, ",\"obj_key\":\"%s/%s/%s/%s\"}", esc[0], esc[1], esc[4],+ esc[3]);+ return props;+}+static void k8s_records_free(k8s_record_array_t *recs) {for (int i = 0; i < recs->pair_count; i++) {cbm_free(CBM_MEM_CLASS_OTHER, recs->pairs[i]);@@ -541,12 +692,11 @@ static void k8s_link_selectors(cbm_pipeline_ctx_t *ctx, const k8s_record_array_t/* ── K8s manifest handler ────────────────────────────────────────── *//* source/src_len are the already-read file bytes (caller retains ownership and- * must free after this call returns). The first Resource's manifest is+ * 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) {int resource_count = 0;- int64_t first_node_id = 0;if (!res) {return;@@ -566,28 +716,25 @@ static void handle_k8s_manifest(cbm_pipeline_ctx_t *ctx, const char *rel_path, ccontinue;}- int64_t node_id =- cbm_gbuf_upsert_node(ctx->gbuf, "Resource", def->name, def->qualified_name, rel_path,- (int)def->start_line, (int)def->end_line, "{\"source\":\"k8s\"}");+ char *props = k8s_resource_props(def->qualified_name);+ int64_t node_id = cbm_gbuf_upsert_node(+ ctx->gbuf, "Resource", def->name, def->qualified_name, rel_path, (int)def->start_line,+ (int)def->end_line, props ? props : "{\"source\":\"k8s\"}");+ cbm_free(CBM_MEM_CLASS_OTHER, props);/* DEFINES edge: File → Resource */if (file_node && node_id > 0) {cbm_gbuf_insert_edge(ctx->gbuf, file_node->id, node_id, "DEFINES", "{}");}- /* Capture the first Resource for cross-manifest selector matching. */- if (first_node_id <= 0 && node_id > 0) {- first_node_id = node_id;+ /* Record its selector / pod-label pairs for Service → workload linking. */+ if (node_id > 0 && source) {+ k8s_record_document(recs, node_id, source, (int)def->start_line, (int)def->end_line);}resource_count++;}- /* Record selector / pod-label pairs for later Service → workload linking. */- if (first_node_id > 0 && source) {- k8s_record_manifest(recs, first_node_id, source);- }-cbm_log_info("pass.k8s.manifest", "file", rel_path, "resources", itoa_k8s(resource_count));}diff --git a/src/store/store.h b/src/store/store.hindex 8dc67ee48..d64041192 100644--- a/src/store/store.h+++ b/src/store/store.h@@ -24,7 +24,12 @@ typedef struct cbm_store_read_scope cbm_store_read_scope_t;#define CBM_STORE_OK 0#define CBM_STORE_ERR (-1)#define CBM_STORE_NOT_FOUND (-2)-#define CBM_INDEX_FORMAT_VERSION 1+/* Persisted index format. A bump routes every existing index through one full+ * rebuild (pipeline.c, format_change_reindex) that keeps ADR/project metadata.+ * 1 #1108: File-node QNs keep the file extension.+ * 2 Kubernetes objects: one Resource per YAML document, QN+ * <file>::<group>/<Kind>/<declared namespace or ->/<name>. */+#define CBM_INDEX_FORMAT_VERSION 2#define CBM_STORE_CANCELLED (-3)#define CBM_STORE_SCAN_LIMIT (-4)#define CBM_STORE_CALLBACK_ERR (-5)diff --git a/tests/test_grammar_probe_f.c b/tests/test_grammar_probe_f.cindex 37638e192..c3e7e6afd 100644--- a/tests/test_grammar_probe_f.c+++ b/tests/test_grammar_probe_f.c@@ -762,6 +762,204 @@ TEST(probe_k8s_manifest_metadata_after_key_line_comment) {PASS();}+/* ── Identity: every document is an object (IDENTITY.md) ──────────── */++/* The QN and properties of the Resource named `name` after indexing `files`;+ * false when there is no such node or it is not unique. */+static bool gpf_resource(const GpfFile *files, int nfiles, const char *name, char *qn,+ size_t qn_sz, char *props, size_t props_sz) {+ GpfProj lp;+ cbm_store_t *store = gpf_index_files(&lp, files, nfiles);+ bool found = false;+ int hits = 0;+ cbm_node_t *nodes = NULL;+ int count = 0;+ if (store &&+ cbm_store_find_nodes_by_label(store, lp.project, "Resource", &nodes, &count) ==+ CBM_STORE_OK) {+ for (int i = 0; i < count; i++) {+ if (nodes[i].name && strcmp(nodes[i].name, name) == 0) {+ hits++;+ const char *q = nodes[i].qualified_name ? nodes[i].qualified_name : "";+ const char *sep = strstr(q, "::");+ snprintf(qn, qn_sz, "%s", sep ? sep : q); /* the part after the file base */+ snprintf(props, props_sz, "%s",+ nodes[i].properties_json ? nodes[i].properties_json : "{}");+ }+ }+ cbm_store_free_nodes(nodes, count);+ found = hits == 1;+ }+ gpf_cleanup(&lp, store);+ return found;+}++/* A multi-document manifest is a list of objects: kubernetes-sigs and+ * microservices-demo ship a Deployment and its Service in one file, and+ * 3,139 objects of the 17 infra corpora sat behind a file's first `---`. */+TEST(probe_k8s_every_document_is_an_object) {+ GpfMetrics m = gpf_metrics("app.yaml",+ "apiVersion: apps/v1\n"+ "kind: Deployment\n"+ "metadata:\n"+ " name: web\n"+ "---\n"+ "apiVersion: v1\n"+ "kind: Service\n"+ "metadata:\n"+ " name: web\n"+ "---\n"+ "apiVersion: v1\n"+ "kind: ConfigMap\n"+ "metadata:\n"+ " name: web-config\n");+ ASSERT_TRUE(m.ok);+ ASSERT_EQ(m.resources, 3);+ PASS();+}++/* ...and the Service in the second document selects the Deployment in the+ * first. */+TEST(probe_k8s_selector_across_documents) {+ GpfMetrics m = gpf_metrics("app.yaml",+ "apiVersion: apps/v1\n"+ "kind: Deployment\n"+ "metadata:\n"+ " name: web\n"+ "spec:\n"+ " template:\n"+ " metadata:\n"+ " labels:\n"+ " app: web\n"+ "---\n"+ "apiVersion: v1\n"+ "kind: Service\n"+ "metadata:\n"+ " name: web\n"+ "spec:\n"+ " selector:\n"+ " app: web\n");+ ASSERT_TRUE(m.ok);+ ASSERT_EQ(m.resources, 2);+ ASSERT_EQ(m.infra_maps, 1);+ PASS();+}++/* Flow-style label maps (`labels: { app: kdc }`, deckhouse's kerberos demo)+ * are label maps; a selector given that way selects just the same. */+TEST(probe_k8s_selector_flow_mapping) {+ GpfMetrics m = gpf_metrics("kdc.yaml",+ "apiVersion: apps/v1\n"+ "kind: Deployment\n"+ "metadata:\n"+ " name: kdc\n"+ "spec:\n"+ " template:\n"+ " metadata:\n"+ " labels: { app: kdc, tier: \"auth\" }\n"+ "---\n"+ "apiVersion: v1\n"+ "kind: Service\n"+ "metadata:\n"+ " name: kdc\n"+ "spec:\n"+ " selector: { app: kdc }\n"+ "---\n"+ "apiVersion: v1\n"+ "kind: Service\n"+ "metadata:\n"+ " name: other\n"+ "spec:\n"+ " selector: {app: kdc, tier: web}\n");+ ASSERT_TRUE(m.ok);+ ASSERT_EQ(m.resources, 3);+ ASSERT_EQ(m.infra_maps, 1); /* `other` needs tier=web, which kdc lacks */+ PASS();+}++/* An anchored name (`name: &name app`, onedr0p/home-ops reuses it in the+ * chart values) is still the object's name; so is a tagged one. */+TEST(probe_k8s_anchored_and_tagged_names) {+ GpfMetrics m = gpf_metrics("release.yaml",+ "apiVersion: helm.toolkit.fluxcd.io/v2\n"+ "kind: HelmRelease\n"+ "metadata:\n"+ " name: &name actions-runner-controller\n"+ "spec:\n"+ " releaseName: *name\n"+ "---\n"+ "apiVersion: v1\n"+ "kind: ConfigMap\n"+ "metadata:\n"+ " name: !!str settings\n");+ ASSERT_TRUE(m.ok);+ ASSERT_EQ(m.resources, 2);+ PASS();+}++/* One name in two namespaces is two objects. */+TEST(probe_k8s_same_name_two_namespaces) {+ GpfMetrics m = gpf_metrics("app.yaml",+ "apiVersion: apps/v1\n"+ "kind: Deployment\n"+ "metadata:\n"+ " name: web\n"+ " namespace: staging\n"+ "---\n"+ "apiVersion: apps/v1\n"+ "kind: Deployment\n"+ "metadata:\n"+ " name: web\n"+ " namespace: prod\n");+ ASSERT_TRUE(m.ok);+ ASSERT_EQ(m.resources, 2);+ PASS();+}++/* The node QN carries group, kind, declared namespace and name after the+ * file; `obj_key` is the logical identity (effective namespace, `?` when the+ * deploy decides it). */+TEST(probe_k8s_identity_key) {+ static const GpfFile files[] = {{"app.yaml",+ "apiVersion: apps/v1\n"+ "kind: Deployment\n"+ "metadata:\n"+ " name: web\n"}};+ char qn[256];+ char props[512];+ ASSERT_TRUE(gpf_resource(files, 1, "Deployment/web", qn, sizeof(qn), props, sizeof(props)));+ ASSERT_STR_EQ(qn, "::apps/Deployment/-/web");+ ASSERT_NOT_NULL(strstr(props, "\"obj_key\":\"apps/Deployment/?/web\""));+ ASSERT_NOT_NULL(strstr(props, "\"kind\":\"Deployment\""));+ ASSERT_NOT_NULL(strstr(props, "\"group\":\"apps\""));+ PASS();+}++/* Core-group objects say `core`; a declared namespace is part of the QN; a+ * cluster-scoped kind's logical key has no namespace (`_`). */+TEST(probe_k8s_identity_core_namespaced_and_cluster_scoped) {+ static const GpfFile svc[] = {{"svc.yaml",+ "apiVersion: v1\n"+ "kind: Service\n"+ "metadata:\n"+ " name: web\n"+ " namespace: prod\n"}};+ static const GpfFile ns[] = {{"ns.yaml",+ "apiVersion: v1\n"+ "kind: Namespace\n"+ "metadata:\n"+ " name: prod\n"}};+ char qn[256];+ char props[512];+ ASSERT_TRUE(gpf_resource(svc, 1, "Service/web", qn, sizeof(qn), props, sizeof(props)));+ ASSERT_STR_EQ(qn, "::core/Service/prod/web");+ ASSERT_NOT_NULL(strstr(props, "\"obj_key\":\"core/Service/prod/web\""));+ ASSERT_NOT_NULL(strstr(props, "\"namespace\":\"prod\""));+ ASSERT_TRUE(gpf_resource(ns, 1, "Namespace/prod", qn, sizeof(qn), props, sizeof(props)));+ ASSERT_NOT_NULL(strstr(props, "\"obj_key\":\"core/Namespace/_/prod\""));+ PASS();+}+/* The same comment in front of a kustomization hid its resource list:* home-ops resolved 1 of 348 entries. */TEST(probe_kustomize_imports_after_leading_comment) {@@ -2156,6 +2354,13 @@ SUITE(grammar_probe_f) {RUN_TEST(probe_kustomize_entries_after_commented_out_entry);RUN_TEST(probe_kustomize_entries_after_key_line_comment);RUN_TEST(probe_k8s_manifest_metadata_after_key_line_comment);+ RUN_TEST(probe_k8s_every_document_is_an_object);+ RUN_TEST(probe_k8s_selector_across_documents);+ RUN_TEST(probe_k8s_same_name_two_namespaces);+ RUN_TEST(probe_k8s_identity_key);+ RUN_TEST(probe_k8s_identity_core_namespaced_and_cluster_scoped);+ RUN_TEST(probe_k8s_anchored_and_tagged_names);+ RUN_TEST(probe_k8s_selector_flow_mapping);/* Nix */RUN_TEST(probe_nix_attrset_node);diff --git a/tests/test_pipeline.c b/tests/test_pipeline.cindex 0ad711800..f666f993c 100644--- a/tests/test_pipeline.c+++ b/tests/test_pipeline.c@@ -14274,15 +14274,8 @@ TEST(k8s_extract_manifest_no_name) {}TEST(k8s_extract_manifest_multidoc) {- /* Two-document YAML separated by "---".- * extract_k8s_manifest contains a "break" after the first successful push,- * so it processes only the first document that has both kind and- * metadata.name. This test pins that behaviour: the first document's- * resource must be present and no crash must occur.- *- * Note: with some tree-sitter YAML grammar versions the root stream may- * expose both documents as siblings; the break still fires after the first- * successful def push, so defs.count must be exactly 1. */+ /* Two-document YAML separated by "---": every document is an object, with+ * the identity QN <file-base>::<group>/<Kind>/<declared ns or ->/<name>. */const char *src = "apiVersion: apps/v1\n""kind: Deployment\n""metadata:\n"@@ -14296,17 +14289,24 @@ TEST(k8s_extract_manifest_multidoc) {"k8s/multi.yaml", 0, NULL, NULL);ASSERT(r != NULL);ASSERT(!r->has_error);- /* First document's resource must be present */- int found = 0;+ int deploy = 0;+ int svc = 0;for (int i = 0; i < r->defs.count; i++) {- if (r->defs.items[i].label && strcmp(r->defs.items[i].label, "Resource") == 0 &&- r->defs.items[i].name && strcmp(r->defs.items[i].name, "Deployment/my-app") == 0) {- found = 1;+ const CBMDefinition *d = &r->defs.items[i];+ if (!d->label || strcmp(d->label, "Resource") != 0 || !d->name || !d->qualified_name) {+ continue;+ }+ if (strcmp(d->name, "Deployment/my-app") == 0 &&+ strcmp(d->qualified_name, "myproj.k8s.multi.yaml::apps/Deployment/-/my-app") == 0) {+ deploy++;+ }+ if (strcmp(d->name, "Service/my-svc") == 0 &&+ strcmp(d->qualified_name, "myproj.k8s.multi.yaml::core/Service/-/my-svc") == 0) {+ svc++;}}- ASSERT(found);- /* At least one def, no more than one (only first document processed) */- ASSERT(r->defs.count >= 1);+ ASSERT_EQ(deploy, 1);+ ASSERT_EQ(svc, 1);cbm_free_result(r);PASS();}