@intentius/chant-lexicon-k8s 0.124.52 → 0.124.55

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../src/plugin.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,KAAK,EAAE,aAAa,EAAqC,MAAM,0BAA0B,CAAC;AAiCjG,eAAO,MAAM,SAAS,EAAE,aA8vBvB,CAAC"}
1
+ {"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../src/plugin.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,KAAK,EAAE,aAAa,EAAqC,MAAM,0BAA0B,CAAC;AAqCjG,eAAO,MAAM,SAAS,EAAE,aA6wBvB,CAAC"}
package/dist/plugin.js CHANGED
@@ -23,6 +23,10 @@ import { k8sHover } from "./lsp/hover.js";
23
23
  import { K8sParser } from "./import/parser.js";
24
24
  import { K8sGenerator } from "./import/generator.js";
25
25
  import { k8sDeepNormalizationHooks } from "./deep-observe-hooks.js";
26
+ import { k8sListedTypes } from "./listed-types.js";
27
+ import { k8sIndexIdentity } from "./index-identity.js";
28
+ import { k8sIndexImport } from "./index-import.js";
29
+ import { k8sReferenceCatalog } from "./reference-catalog.js";
26
30
  import { LABEL_OWNERSHIP_KEYS } from "@intentius/chant/ownership";
27
31
  import { k8sConfigSchema } from "./config-schema.js";
28
32
  import { renderKustomizeRoots } from "./kustomize/root.js";
@@ -754,4 +758,15 @@ const { deployment, service, serviceMonitor, prometheusRule } = MonitoredService
754
758
  return observeResourcesDeepK8s(options);
755
759
  },
756
760
  deepNormalizationHooks: k8sDeepNormalizationHooks,
761
+ // Cloud inventory type names to kinds, for an indexed resource (#4521).
762
+ listedTypes: k8sListedTypes,
763
+ // How its resources reference each other, for chant's catalog pass over an
764
+ // index and a declared graph (#4535; behold#1005 retires behold's matcher on it).
765
+ referenceCatalog: k8sReferenceCatalog,
766
+ // Declared objects matched to indexed ones by apiVersion/kind, namespace and
767
+ // name; the server-assigned uid names a node to the identity edge pass (#4538).
768
+ indexIdentity: k8sIndexIdentity,
769
+ // `chant import --index`: an indexed object as source; a masked Secret as a
770
+ // referenced secret, any other masked value read from the environment (#4538).
771
+ indexImport: k8sIndexImport,
757
772
  };
@@ -0,0 +1,3 @@
1
+ import type { ReferenceCatalog } from "@intentius/chant/graph-refs";
2
+ export declare const k8sReferenceCatalog: ReferenceCatalog;
3
+ //# sourceMappingURL=reference-catalog.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reference-catalog.d.ts","sourceRoot":"","sources":["../src/reference-catalog.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAgB,gBAAgB,EAAW,MAAM,6BAA6B,CAAC;AA4J3F,eAAO,MAAM,mBAAmB,EAAE,gBAAuC,CAAC"}
@@ -0,0 +1,138 @@
1
+ /**
2
+ * Kubernetes reference catalog (#4535): how Kubernetes objects name each
3
+ * other, so chant's catalog pass (`reconstructIndexedEdges`, #4522) draws
4
+ * their edges over an index and over a declared graph, and behold can retire
5
+ * its name matcher (behold#1005).
6
+ *
7
+ * ## Shape and scope
8
+ *
9
+ * The paths are the manifest's own (`metadata`, `spec`), which is the tree a
10
+ * listed object becomes once `apiVersion` and `kind` are dropped
11
+ * (./listed-types.ts `k8sObservedTree`) and the shape the lexicon's declared
12
+ * props have. Every target is identified by `metadata.name`.
13
+ *
14
+ * A name is unique only inside its namespace. Over an index a namespaced
15
+ * object's location is its namespace (behold#1025), so the scoped join key
16
+ * (behold#1023's ruling) keeps a `serviceAccountName: default` inside its own
17
+ * namespace, and a namespaced holder also reaches cluster-scoped objects (a
18
+ * `Namespace`, a `ClusterRole`, a `StorageClass`). A declared graph is one
19
+ * scope, so two `default` service accounts in two namespaces make that
20
+ * reference ambiguous there, and it draws no edge.
21
+ *
22
+ * ## Multi-kind fields
23
+ *
24
+ * A field that can name one of several kinds (`scaleTargetRef`, `roleRef`,
25
+ * a binding's `subjects`, an owner reference) has one rule per kind, each
26
+ * `optional`, so a value that names a node of another kind is not dangling
27
+ * under the rules it does not match.
28
+ *
29
+ * ## Values that may name a cloud resource
30
+ *
31
+ * A container's env var value can be the literal name of a bucket it uses
32
+ * (behold#166's case: `ASSET_BUCKET` set to the bucket's `BucketName`). The
33
+ * env-value rules join such a value to an `AWS::S3::Bucket` of that name, and
34
+ * are `optional`, since most env values name nothing. Over an index the
35
+ * cluster and the AWS account are two scopes, so the join only draws on a
36
+ * declared graph (one scope), which is where behold's matcher drew it.
37
+ *
38
+ * ## What this does not do
39
+ *
40
+ * - Label selectors. A Service selects pods by labels, and the standard keys
41
+ * (`app.kubernetes.io/name`) contain dots, which `readPath` reads as path
42
+ * separators. Only the bare `app` label is matched: a Service's
43
+ * `spec.selector.app` to a workload whose pod template carries the same
44
+ * `app` label. behold's own k8s pass (src/k8s-edges.ts) still joins full
45
+ * selectors on behold's side.
46
+ * - Annotations, for the same reason (`eks.amazonaws.com/role-arn`).
47
+ */
48
+ /** Workload kinds and the path to their pod spec. */
49
+ const POD_SPECS = [
50
+ ["K8s::Core::Pod", "spec"],
51
+ ["K8s::Apps::Deployment", "spec.template.spec"],
52
+ ["K8s::Apps::StatefulSet", "spec.template.spec"],
53
+ ["K8s::Apps::DaemonSet", "spec.template.spec"],
54
+ ["K8s::Apps::ReplicaSet", "spec.template.spec"],
55
+ ["K8s::Batch::Job", "spec.template.spec"],
56
+ ["K8s::Batch::CronJob", "spec.jobTemplate.spec.template.spec"],
57
+ ];
58
+ /** Kinds that sit in a namespace, so `metadata.namespace` places them. */
59
+ const NAMESPACED_KINDS = [
60
+ ...POD_SPECS.map(([kind]) => kind),
61
+ "K8s::Core::Service",
62
+ "K8s::Core::ConfigMap",
63
+ "K8s::Core::Secret",
64
+ "K8s::Core::ServiceAccount",
65
+ "K8s::Core::PersistentVolumeClaim",
66
+ "K8s::Networking::Ingress",
67
+ "K8s::Networking::NetworkPolicy",
68
+ "K8s::Autoscaling::HorizontalPodAutoscaler",
69
+ "K8s::Policy::PodDisruptionBudget",
70
+ "K8s::Rbac::Role",
71
+ "K8s::Rbac::RoleBinding",
72
+ ];
73
+ /** Kinds other objects name by `metadata.name`. */
74
+ const NAMED_KINDS = [
75
+ ...NAMESPACED_KINDS,
76
+ "K8s::Core::Namespace",
77
+ "K8s::Core::PersistentVolume",
78
+ "K8s::Networking::IngressClass",
79
+ "K8s::Storage::StorageClass",
80
+ "K8s::Rbac::ClusterRole",
81
+ ];
82
+ /** Workloads whose pod template a Service's `app` selector can match. */
83
+ const SELECTED_WORKLOADS = ["K8s::Apps::Deployment", "K8s::Apps::StatefulSet", "K8s::Apps::DaemonSet"];
84
+ const identities = NAMED_KINDS.map((kind) => ({
85
+ kind,
86
+ ids: SELECTED_WORKLOADS.includes(kind) ? ["metadata.name", "spec.template.metadata.labels.app"] : ["metadata.name"],
87
+ }));
88
+ const ref = (from, path, targetKind, label, relation = "reference") => ({ from, path, targetKind, relation, label });
89
+ const anyOf = (from, path, targetKinds, label) => targetKinds.map((targetKind) => ({ from, path, targetKind, relation: "reference", label, optional: true }));
90
+ /** What a pod spec names: its service account, mounted config and secrets, claims, pull secrets. */
91
+ function podSpecRules(kind, p) {
92
+ const containers = [`${p}.containers[]`, `${p}.initContainers[]`];
93
+ return [
94
+ ref(kind, `${p}.serviceAccountName`, "K8s::Core::ServiceAccount", "runs as"),
95
+ ref(kind, `${p}.volumes[].configMap.name`, "K8s::Core::ConfigMap", "mounts"),
96
+ ref(kind, `${p}.volumes[].secret.secretName`, "K8s::Core::Secret", "mounts"),
97
+ ref(kind, `${p}.volumes[].persistentVolumeClaim.claimName`, "K8s::Core::PersistentVolumeClaim", "mounts"),
98
+ ref(kind, `${p}.volumes[].projected.sources[].configMap.name`, "K8s::Core::ConfigMap", "mounts"),
99
+ ref(kind, `${p}.volumes[].projected.sources[].secret.name`, "K8s::Core::Secret", "mounts"),
100
+ ref(kind, `${p}.imagePullSecrets[].name`, "K8s::Core::Secret", "pulls with"),
101
+ ...containers.flatMap((c) => [
102
+ ref(kind, `${c}.envFrom[].configMapRef.name`, "K8s::Core::ConfigMap", "env from"),
103
+ ref(kind, `${c}.envFrom[].secretRef.name`, "K8s::Core::Secret", "env from"),
104
+ ref(kind, `${c}.env[].valueFrom.configMapKeyRef.name`, "K8s::Core::ConfigMap", "env from"),
105
+ ref(kind, `${c}.env[].valueFrom.secretKeyRef.name`, "K8s::Core::Secret", "env from"),
106
+ ]),
107
+ // behold#166: an env var whose value is a bucket's literal name.
108
+ { from: kind, path: `${p}.containers[].env[].value`, targetKind: "AWS::S3::Bucket", relation: "reference", label: "uses bucket", optional: true },
109
+ ];
110
+ }
111
+ const refs = [
112
+ // ── containment: the namespace an object is in ──
113
+ ...NAMESPACED_KINDS.map((kind) => ref(kind, "metadata.namespace", "K8s::Core::Namespace", "in namespace", "containment")),
114
+ // ── owner references, by name inside the namespace ──
115
+ ...anyOf("K8s::Core::Pod", "metadata.ownerReferences[].name", ["K8s::Apps::ReplicaSet", "K8s::Apps::StatefulSet", "K8s::Apps::DaemonSet", "K8s::Batch::Job"], "owned by"),
116
+ ...anyOf("K8s::Apps::ReplicaSet", "metadata.ownerReferences[].name", ["K8s::Apps::Deployment"], "owned by"),
117
+ ...anyOf("K8s::Batch::Job", "metadata.ownerReferences[].name", ["K8s::Batch::CronJob"], "owned by"),
118
+ // ── pod specs ──
119
+ ...POD_SPECS.flatMap(([kind, p]) => podSpecRules(kind, p)),
120
+ // ── services and ingress ──
121
+ ...anyOf("K8s::Core::Service", "spec.selector.app", SELECTED_WORKLOADS, "selects"),
122
+ ref("K8s::Networking::Ingress", "spec.rules[].http.paths[].backend.service.name", "K8s::Core::Service", "routes to"),
123
+ ref("K8s::Networking::Ingress", "spec.defaultBackend.service.name", "K8s::Core::Service", "routes to"),
124
+ ref("K8s::Networking::Ingress", "spec.tls[].secretName", "K8s::Core::Secret", "tls"),
125
+ ref("K8s::Networking::Ingress", "spec.ingressClassName", "K8s::Networking::IngressClass", "class"),
126
+ // ── scaling, storage, RBAC ──
127
+ ...anyOf("K8s::Autoscaling::HorizontalPodAutoscaler", "spec.scaleTargetRef.name", ["K8s::Apps::Deployment", "K8s::Apps::StatefulSet", "K8s::Apps::ReplicaSet"], "scales"),
128
+ ref("K8s::Core::PersistentVolumeClaim", "spec.volumeName", "K8s::Core::PersistentVolume", "bound to"),
129
+ ref("K8s::Core::PersistentVolumeClaim", "spec.storageClassName", "K8s::Storage::StorageClass", "class"),
130
+ ref("K8s::Core::PersistentVolume", "spec.storageClassName", "K8s::Storage::StorageClass", "class"),
131
+ ...anyOf("K8s::Rbac::RoleBinding", "roleRef.name", ["K8s::Rbac::Role", "K8s::Rbac::ClusterRole"], "binds"),
132
+ ...anyOf("K8s::Rbac::RoleBinding", "subjects[].name", ["K8s::Core::ServiceAccount"], "grants"),
133
+ ...anyOf("K8s::Rbac::ClusterRoleBinding", "roleRef.name", ["K8s::Rbac::ClusterRole"], "binds"),
134
+ ...anyOf("K8s::Rbac::ClusterRoleBinding", "subjects[].name", ["K8s::Core::ServiceAccount"], "grants"),
135
+ ref("K8s::Core::ServiceAccount", "secrets[].name", "K8s::Core::Secret", "token"),
136
+ ref("K8s::Core::ServiceAccount", "imagePullSecrets[].name", "K8s::Core::Secret", "pulls with"),
137
+ ];
138
+ export const k8sReferenceCatalog = { identities, refs };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@intentius/chant-lexicon-k8s",
3
- "version": "0.124.52",
3
+ "version": "0.124.55",
4
4
  "description": "Kubernetes lexicon for chant — declarative IaC in TypeScript",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://intentius.io/chant",
@@ -74,13 +74,13 @@
74
74
  "build": "../../scripts/tsc7.sh -p tsconfig.build.json --sourceMap false && tsc-alias -p tsconfig.build.json && cp src/generated/index.d.ts dist/generated/index.d.d.ts"
75
75
  },
76
76
  "dependencies": {
77
- "@intentius/chant-lexicon-otel": "^0.124.52",
78
- "@intentius/chant-lexicon-prometheus": "^0.124.52",
77
+ "@intentius/chant-lexicon-otel": "^0.124.55",
78
+ "@intentius/chant-lexicon-prometheus": "^0.124.55",
79
79
  "js-yaml": "^4.3.1",
80
80
  "@types/js-yaml": "^4.0.9"
81
81
  },
82
82
  "optionalDependencies": {
83
- "@intentius/chant-k8s-client": "^0.124.52"
83
+ "@intentius/chant-k8s-client": "^0.124.55"
84
84
  },
85
85
  "devDependencies": {
86
86
  "@intentius/chant": "*",
@@ -88,6 +88,6 @@
88
88
  },
89
89
  "peerDependencies": {
90
90
  "zod": "^4.3.6",
91
- "@intentius/chant": "^0.124.52"
91
+ "@intentius/chant": "^0.124.55"
92
92
  }
93
93
  }
@@ -318,6 +318,32 @@ describe("kubectl-apply plan: a server-side dry-run diff (#3998)", () => {
318
318
  await cap.run({ env: "prod", component: "api", plans: { other: { kind: "kubectl-apply-plan", planDigest: "sha256:x", documents: [] } } }, { manifest: "k8s.yaml", stack: "web" });
319
319
  expect(applied).toEqual([{ manifest: "k8s.yaml", environment: "prod", stack: "web" }]);
320
320
  });
321
+
322
+ test("inputs waiting on another component read nothing and leave a hole (#4467)", async () => {
323
+ const cap = createKubectlApplyCapability(
324
+ noApply,
325
+ () => {
326
+ throw new Error("no read expected");
327
+ },
328
+ async () => {
329
+ throw new Error("no dry run expected");
330
+ },
331
+ async () => {
332
+ throw new Error("no live read expected");
333
+ },
334
+ );
335
+ const ctx = { env: "prod", component: "api", unresolvedInputs: ["network", "cluster"] };
336
+ const input = { manifest: undefined as unknown as string, stack: "web", outputs: { host: { object: "Service/prod/web", field: "spec.clusterIP" } } };
337
+ const planned = await cap.plan!(ctx, input);
338
+ expect(planned.member).toBe("web");
339
+ expect(planned.artifact).toBeUndefined();
340
+ expect(planned.outputs).toBeUndefined();
341
+ expect(planned.changeSet!.entries).toEqual([]);
342
+ expect(planned.changeSet!.member.holes).toEqual([{ address: "web", type: "kubectl-apply", reason: "inputs from cluster, network; re-checked on apply" }]);
343
+ expect(isPlanDigest(planned.planDigest)).toBe(true);
344
+ const other = await cap.plan!({ ...ctx, unresolvedInputs: ["network"] }, input);
345
+ expect(other.planDigest).not.toBe(planned.planDigest);
346
+ });
321
347
  });
322
348
 
323
349
  describe("kubectl-apply outputs: the fields a step names (#3999)", () => {
@@ -259,6 +259,37 @@ function dryRunDigest(
259
259
  });
260
260
  }
261
261
 
262
+ /**
263
+ * The plan of a step whose inputs wait on other components (#4467): one hole
264
+ * naming them, no artifact, and a digest over the environment, the member,
265
+ * the input and the unresolved names.
266
+ */
267
+ function unresolvedPlan(ctx: DeployContext, input: KubectlApplyInput, member: string, unresolved: string[]): CapabilityPlan {
268
+ const planDigest = computePlanDigest("kubectl-apply-plan", {
269
+ env: ctx.env,
270
+ member,
271
+ manifest: input.manifest ?? null,
272
+ context: input.context ?? null,
273
+ delete: input.delete ?? "never",
274
+ unresolved,
275
+ });
276
+ return {
277
+ member,
278
+ planDigest,
279
+ changeSet: {
280
+ member: {
281
+ member,
282
+ lexicon: "k8s",
283
+ planner: "chant",
284
+ status: "planned",
285
+ planDigest,
286
+ holes: [{ address: member, type: "kubectl-apply", reason: `inputs from ${unresolved.join(", ")}; re-checked on apply` }],
287
+ },
288
+ entries: [],
289
+ },
290
+ };
291
+ }
292
+
262
293
  export interface KubectlApplyInput {
263
294
  /** Path to a manifest file, or a directory of them. */
264
295
  manifest: string;
@@ -464,10 +495,16 @@ export function createKubectlApplyCapability(
464
495
  * would apply, release attributes set, server-side applied with
465
496
  * `dryRun=All` as the same field manager, each compared with its live
466
497
  * object. The member is the step's `stack`, or the component.
498
+ *
499
+ * A step whose inputs wait on another component's outputs (#4467) reads
500
+ * nothing and dry-runs nothing: its manifest or context may be one of
501
+ * them, so the member gets one hole and no artifact, as `gcp-apply` does.
467
502
  */
468
503
  async plan(ctx: DeployContext, stepInput: KubectlApplyInput): Promise<CapabilityPlan> {
469
504
  const input = narrowedInput(ctx, stepInput);
470
505
  const member = input.stack ?? ctx.component;
506
+ const unresolved = [...(ctx.unresolvedInputs ?? [])].sort();
507
+ if (unresolved.length > 0) return unresolvedPlan(ctx, input, member, unresolved);
471
508
  const read_ = (read ?? (await activities()).readManifestDocuments)(input.manifest);
472
509
  const targets = ctx.targets && ctx.targets.length > 0 ? ctx.targets : undefined;
473
510
  const documents = targets ? targetedDocuments(member, input.manifest, read_, targets) : read_;
@@ -12,6 +12,8 @@ import {
12
12
  isEmbeddedReference,
13
13
  renderEmbeddedReference,
14
14
  } from "@intentius/chant/import/embedded";
15
+ import { SECRET_DECLARATION_ENTITY_TYPE } from "@intentius/chant/secret-provenance";
16
+ import { isMaskedValueRef } from "../index-import";
15
17
 
16
18
  const IDENT = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
17
19
 
@@ -131,8 +133,13 @@ export class K8sGenerator implements TypeScriptGenerator {
131
133
  /** The imports for embedded content the current `generate()` call references (#2962). */
132
134
  private scope = new EmbeddedImportScope("");
133
135
 
136
+ /** Whether the current `generate()` call wrote a `maskedValue(...)` (chant import --index, #4538). */
137
+ private usesMaskedValue = false;
138
+
134
139
  generate(ir: TemplateIR): GeneratedFile[] {
135
140
  const lines: string[] = [];
141
+ this.usesMaskedValue = false;
142
+ let usesDeclareSecret = false;
136
143
 
137
144
  // Collect which constructors are needed
138
145
  const usedConstructors = new Set<string>();
@@ -161,6 +168,13 @@ export class K8sGenerator implements TypeScriptGenerator {
161
168
 
162
169
  // Emit resources
163
170
  for (const resource of ir.resources) {
171
+ // A Secret `chant import --index` read masked: a referenced secret the user supplies (#4538).
172
+ if (resource.type === SECRET_DECLARATION_ENTITY_TYPE) {
173
+ usesDeclareSecret = true;
174
+ lines.push(`export const ${resource.logicalId} = declareSecret(${this.emitLiteral(resource.properties, 0, resource.type)});`);
175
+ lines.push("");
176
+ continue;
177
+ }
164
178
  const cls = this.resolveClass(resource.type);
165
179
  if (!cls) {
166
180
  lines.push(`// TODO: unsupported type ${resource.type} (${resource.logicalId})`);
@@ -182,11 +196,33 @@ export class K8sGenerator implements TypeScriptGenerator {
182
196
  const code = lines.join("\n").replace(/"(?:[^"\\\n]|\\.)*"/g, '""');
183
197
  for (const m of code.matchAll(/\bnew ([A-Z][A-Za-z0-9_]*)\(/g)) usedConstructors.add(m[1]);
184
198
  const imports = [...usedConstructors].sort().join(", ");
185
- const head = [`import { ${imports} } from "@intentius/chant-lexicon-k8s";`, ...this.scope.lines(), ""];
199
+ const head = [
200
+ ...(usesDeclareSecret ? [`import { declareSecret } from "@intentius/chant";`] : []),
201
+ ...(imports ? [`import { ${imports} } from "@intentius/chant-lexicon-k8s";`] : []),
202
+ ...this.scope.lines(),
203
+ "",
204
+ ];
205
+ if (this.usesMaskedValue) head.push(...this.maskedValueHelper(ir), "");
186
206
 
187
207
  return [{ path: "main.ts", content: [...head, ...lines].join("\n") }];
188
208
  }
189
209
 
210
+ /**
211
+ * The helper a value masked in the index reads its environment variable
212
+ * through, with the parameters it stands for listed above it.
213
+ */
214
+ private maskedValueHelper(ir: TemplateIR): string[] {
215
+ return [
216
+ "// Values the index masked. Set each environment variable before building:",
217
+ ...ir.parameters.map((p) => `// ${p.name}: ${(p.description ?? "").replace(/\r?\n/g, " ")}`),
218
+ "function maskedValue(name: string): any {",
219
+ " const raw = process.env[name];",
220
+ " if (raw === undefined) throw new Error(`${name} is not set: the value was masked in the index`);",
221
+ " return /^\\s*[[{]/.test(raw) ? JSON.parse(raw) : raw;",
222
+ "}",
223
+ ];
224
+ }
225
+
190
226
  /**
191
227
  * Resolve a K8s type name to a constructor class name.
192
228
  * Falls back to extracting the last segment of the type.
@@ -207,7 +243,7 @@ export class K8sGenerator implements TypeScriptGenerator {
207
243
  parentType: string,
208
244
  ): void {
209
245
  for (const [key, value] of Object.entries(props)) {
210
- if (value === undefined || value === null) continue;
246
+ if (value === undefined || value === null || isMaskedValueRef(value)) continue;
211
247
 
212
248
  // Special case: "ports" on Service resources → ServicePort
213
249
  if (key === "ports" && SERVICE_PORT_TYPES.has(parentType)) {
@@ -254,6 +290,7 @@ export class K8sGenerator implements TypeScriptGenerator {
254
290
  private emitValue(key: string, value: unknown, depth: number, parentType: string): string {
255
291
  if (value === null || value === undefined) return "undefined";
256
292
  if (isEmbeddedReference(value)) return renderEmbeddedReference(value, this.scope, depth * 2);
293
+ if (isMaskedValueRef(value)) return this.emitLiteral(value, depth, parentType);
257
294
 
258
295
  // Special case: "ports" on Service → ServicePort constructor
259
296
  if (key === "ports" && SERVICE_PORT_TYPES.has(parentType) && Array.isArray(value)) {
@@ -287,6 +324,7 @@ export class K8sGenerator implements TypeScriptGenerator {
287
324
  const innerIndent = " ".repeat(depth + 1);
288
325
 
289
326
  const emitted = items.map((item) => {
327
+ if (isMaskedValueRef(item)) return this.emitLiteral(item, depth + 1, parentType);
290
328
  if (typeof item === "object" && item !== null && !Array.isArray(item)) {
291
329
  const propsStr = this.emitProps(item as Record<string, unknown>, depth + 1, parentType);
292
330
  return `new ${constructor}(${propsStr})`;
@@ -303,6 +341,10 @@ export class K8sGenerator implements TypeScriptGenerator {
303
341
  private emitLiteral(value: unknown, depth: number, parentType: string): string {
304
342
  if (value === null || value === undefined) return "undefined";
305
343
  if (isEmbeddedReference(value)) return renderEmbeddedReference(value, this.scope, depth * 2);
344
+ if (isMaskedValueRef(value)) {
345
+ this.usesMaskedValue = true;
346
+ return `maskedValue(${JSON.stringify(value.__k8sMaskedValue)})`;
347
+ }
306
348
  if (typeof value === "string") return JSON.stringify(value);
307
349
  if (typeof value === "number" || typeof value === "boolean") return String(value);
308
350
 
@@ -0,0 +1,119 @@
1
+ /**
2
+ * The k8s lexicon's identity rule for indexed objects (#4538, on #4523's
3
+ * matcher, ../../../packages/core/src/lifecycle/identity-match.ts).
4
+ *
5
+ * core's Kubernetes lister (packages/core/src/cloud-lister/kubernetes.ts)
6
+ * writes each object as:
7
+ *
8
+ * - `listedType` `<apiVersion>/<kind>` (`apps/v1/Deployment`, `v1/Secret`);
9
+ * - `location` its namespace, or `cluster` for a cluster-scoped kind;
10
+ * - `nativeId` `<namespace>/<name>`, or `<name>` for a cluster-scoped kind;
11
+ * - one cloud id, `k8s-uid`, the object's `metadata.uid`.
12
+ *
13
+ * apiVersion, kind, namespace and name are all spelled by the user, so a
14
+ * declaration that was never applied still matches its object by value.
15
+ * The uid is assigned by the API server, so no declaration states it. It
16
+ * still names an indexed node to the identity edge pass, where another
17
+ * object's `ownerReferences[].uid` points at its owner.
18
+ *
19
+ * The match is by lexicon kind, not by listed type: discovery lists a
20
+ * group at its preferred version, which need not be the version the
21
+ * lexicon writes, and the kind is the same at any version. Coverage is
22
+ * still read for the declared listed type, so a version the index did not
23
+ * list reads not observed, never absent.
24
+ *
25
+ * What cannot match (`no-binding`):
26
+ * - a name the declaration leaves out, spells with a reference, or asks the
27
+ * API server to generate (`metadata.generateName`);
28
+ * - a namespaced kind with no `metadata.namespace`. The namespace kubectl
29
+ * or a GitOps controller would apply it to is not in the declaration.
30
+ *
31
+ * A type the lexicon has no API address for (`K8s::Sops::EncryptedSecretFile`,
32
+ * a kind outside the generated surface) is `unsupported-kind`.
33
+ */
34
+ import type { DeclaredIdentity, IndexIdentity } from "@intentius/chant/lifecycle/identity-match";
35
+ import type { NodeIdentityValue } from "@intentius/chant/graph-refs";
36
+ import type { IRNode } from "@intentius/chant/graph-ir";
37
+ import { operationFor, operationTable, type K8sOperationDescriptor, type K8sOperationTable } from "./api/operation-surface";
38
+ import { k8sListedTypeFor } from "./listed-types";
39
+
40
+ /** The location core's Kubernetes lister gives a cluster-scoped object. */
41
+ export const K8S_CLUSTER_LOCATION = "cluster";
42
+
43
+ /** The cloud id kind holding an object's `metadata.uid`. */
44
+ export const K8S_UID_CLOUD_ID = "k8s-uid";
45
+
46
+ function isRecord(v: unknown): v is Record<string, unknown> {
47
+ return typeof v === "object" && v !== null && !Array.isArray(v);
48
+ }
49
+
50
+ const nonEmptyString = (v: unknown): v is string => typeof v === "string" && v !== "";
51
+
52
+ /**
53
+ * The descriptor for `entityType` and whether its scope is known: from the
54
+ * generated table when there is one, else derived (and the derived scope is
55
+ * a guess, so it is not trusted for a declaration without a namespace).
56
+ */
57
+ function addressOf(entityType: string, table: K8sOperationTable | undefined): { op: K8sOperationDescriptor; scopeKnown: boolean } | undefined {
58
+ const t = table ?? operationTable();
59
+ if (t[entityType]) return { op: t[entityType], scopeKnown: true };
60
+ // Only the generated table knows CRDs and cluster-scoped kinds. A test table stands alone.
61
+ if (table) return undefined;
62
+ const derived = operationFor(entityType);
63
+ return derived ? { op: derived, scopeKnown: false } : undefined;
64
+ }
65
+
66
+ /**
67
+ * The identifier a k8s declaration spells for the index, or why it spells
68
+ * none. `table` is the generated operation surface; a test passes one.
69
+ */
70
+ export function k8sDeclaredIdentity(entityType: string, props: Record<string, unknown>, table?: K8sOperationTable): DeclaredIdentity {
71
+ const address = addressOf(entityType, table);
72
+ if (!address) {
73
+ return { kind: "unmatchable", reason: "unsupported-kind", detail: `${entityType} has no Kubernetes API address on record` };
74
+ }
75
+ const { op, scopeKnown } = address;
76
+ const metadata = isRecord(props.metadata) ? props.metadata : {};
77
+ if (!nonEmptyString(metadata.name)) {
78
+ const detail = nonEmptyString(metadata.generateName)
79
+ ? `the name of ${entityType} is generated by the API server (metadata.generateName), so no declaration states it`
80
+ : `identity is not in the declaration (${entityType} metadata.name)`;
81
+ return { kind: "unmatchable", reason: "no-binding", detail };
82
+ }
83
+ const name = metadata.name;
84
+ const apiVersion = nonEmptyString(props.apiVersion) ? props.apiVersion : op.apiVersion;
85
+ const listedType = k8sListedTypeFor(apiVersion, op.kind);
86
+ const namespace = nonEmptyString(metadata.namespace) ? metadata.namespace : undefined;
87
+
88
+ if (scopeKnown && op.scope === "Cluster") {
89
+ return { kind: "identifier", listedType, identifier: name, global: true, location: K8S_CLUSTER_LOCATION, entityKind: entityType };
90
+ }
91
+ if (!namespace) {
92
+ return {
93
+ kind: "unmatchable",
94
+ reason: "no-binding",
95
+ detail: scopeKnown
96
+ ? `identity is not in the declaration (${entityType} ${name} names no metadata.namespace)`
97
+ : `${entityType} ${name} names no metadata.namespace, and without a generated surface its scope is not known`,
98
+ };
99
+ }
100
+ return { kind: "identifier", listedType, identifier: `${namespace}/${name}`, global: false, location: namespace, entityKind: entityType };
101
+ }
102
+
103
+ /** The values that name an indexed k8s object: its `<namespace>/<name>` and its uid. */
104
+ export function k8sNodeIdentities(node: IRNode): NodeIdentityValue[] {
105
+ const out: NodeIdentityValue[] = [];
106
+ if (node.nativeId) out.push({ kind: "native-id", value: node.nativeId });
107
+ for (const c of node.facts?.cloudIds ?? []) if (c.kind === K8S_UID_CLOUD_ID) out.push({ kind: c.kind, value: c.value });
108
+ return out;
109
+ }
110
+
111
+ export function createK8sIndexIdentity(table?: K8sOperationTable): IndexIdentity {
112
+ return {
113
+ substrate: "kubernetes",
114
+ declaredIdentity: (entityType, props) => k8sDeclaredIdentity(entityType, props, table),
115
+ nodeIdentities: k8sNodeIdentities,
116
+ };
117
+ }
118
+
119
+ export const k8sIndexIdentity: IndexIdentity = createK8sIndexIdentity();