@telorun/analyzer 0.12.1 → 0.13.0

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.
Files changed (45) hide show
  1. package/dist/analysis-registry.d.ts +12 -0
  2. package/dist/analysis-registry.d.ts.map +1 -1
  3. package/dist/analysis-registry.js +15 -0
  4. package/dist/analyzer.d.ts.map +1 -1
  5. package/dist/analyzer.js +64 -84
  6. package/dist/builtins.d.ts.map +1 -1
  7. package/dist/builtins.js +25 -0
  8. package/dist/cel-environment.d.ts +1 -1
  9. package/dist/cel-environment.d.ts.map +1 -1
  10. package/dist/cel-environment.js +40 -2
  11. package/dist/dependency-graph.d.ts.map +1 -1
  12. package/dist/dependency-graph.js +41 -62
  13. package/dist/index.d.ts +2 -0
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +1 -0
  16. package/dist/kernel-globals.d.ts +1 -1
  17. package/dist/kernel-globals.d.ts.map +1 -1
  18. package/dist/kernel-globals.js +19 -1
  19. package/dist/manifest-visitor.d.ts +109 -0
  20. package/dist/manifest-visitor.d.ts.map +1 -0
  21. package/dist/manifest-visitor.js +110 -0
  22. package/dist/schema-compat.d.ts +10 -0
  23. package/dist/schema-compat.d.ts.map +1 -1
  24. package/dist/schema-compat.js +32 -0
  25. package/dist/validate-cel-context.d.ts +14 -0
  26. package/dist/validate-cel-context.d.ts.map +1 -1
  27. package/dist/validate-cel-context.js +38 -0
  28. package/dist/validate-references.d.ts.map +1 -1
  29. package/dist/validate-references.js +117 -160
  30. package/dist/validate-unused-declarations.d.ts +25 -0
  31. package/dist/validate-unused-declarations.d.ts.map +1 -0
  32. package/dist/validate-unused-declarations.js +91 -0
  33. package/package.json +2 -2
  34. package/src/analysis-registry.ts +20 -0
  35. package/src/analyzer.ts +157 -169
  36. package/src/builtins.ts +25 -0
  37. package/src/cel-environment.ts +42 -1
  38. package/src/dependency-graph.ts +37 -52
  39. package/src/index.ts +11 -0
  40. package/src/kernel-globals.ts +22 -1
  41. package/src/manifest-visitor.ts +251 -0
  42. package/src/schema-compat.ts +32 -0
  43. package/src/validate-cel-context.ts +50 -0
  44. package/src/validate-references.ts +168 -211
  45. package/src/validate-unused-declarations.ts +95 -0
@@ -1,6 +1,7 @@
1
1
  import type { ResourceManifest } from "@telorun/sdk";
2
2
  import { isRefSentinel } from "@telorun/templating";
3
- import { isRefEntry, isScopeEntry, isSchemaFromEntry, isInlineResource, resolveFieldEntries, resolveFieldValues, type RefFieldEntry } from "./reference-field-map.js";
3
+ import { visitManifest } from "./manifest-visitor.js";
4
+ import { isInlineResource, resolveFieldEntries, resolveFieldValues, type RefFieldEntry } from "./reference-field-map.js";
4
5
  import { navigateJsonPointer } from "./schema-compat.js";
5
6
  import { REF_VALIDATION_SKIP_KINDS as SYSTEM_KINDS } from "./system-kinds.js";
6
7
  import { DiagnosticSeverity, type AnalysisDiagnostic, type AnalysisContext } from "./types.js";
@@ -155,66 +156,20 @@ export function validateReferences(
155
156
  const byName = new Map<string, ResourceManifest>();
156
157
  for (const [name, list] of byNameAll) byName.set(name, list[0]);
157
158
 
158
- for (const r of resources) {
159
- if (!r.metadata?.name || !r.kind || SYSTEM_KINDS.has(r.kind)) continue;
160
-
161
- // Use the expanded map so refs nested behind x-telo-schema-from get the
162
- // same kind-check / unresolved-name validation as locally-declared refs.
163
- // Falls back to the base map when aliasesByModule isn't supplied.
164
- const fieldMap = aliasesByModule
165
- ? registry.expandedFieldMapForResource(r, aliases, aliasesByModule)
166
- : registry.getFieldMapForKind(r.kind, aliases);
167
- if (!fieldMap) continue;
168
-
169
- const resourceLabel = `${r.kind}/${r.metadata.name as string}`;
170
- const resourceData = { kind: r.kind, name: r.metadata.name as string };
171
- const filePath = (r.metadata as { source?: string } | undefined)?.source;
172
-
173
- // Collect scope visibility prefixes (JSON Pointer → dot prefix) and their manifests.
174
- // scope field path → flat array of ResourceManifest declared in that scope.
175
- const scopeManifestsByPointer = new Map<string, ResourceManifest[]>();
176
- for (const [fieldPath, entry] of fieldMap) {
177
- if (!isScopeEntry(entry)) continue;
178
- const raw = resolveFieldValues(r, fieldPath)
179
- .flatMap((v) => (Array.isArray(v) ? v : [v]))
180
- .filter((v): v is ResourceManifest => !!v && typeof v === "object");
181
- const pointers = Array.isArray(entry.scope) ? entry.scope : [entry.scope];
182
- for (const pointer of pointers) {
183
- scopeManifestsByPointer.set(pointer, raw);
184
- }
185
- }
186
-
187
- const scopePrefixes = Array.from(scopeManifestsByPointer.keys()).map((p) =>
188
- p.replace(/^\//, "").replace(/\//g, "."),
189
- );
190
-
191
- for (const [fieldPath, entry] of fieldMap) {
192
- if (!isRefEntry(entry)) continue;
193
-
194
- const inScope = scopePrefixes.some(
195
- (prefix) =>
196
- fieldPath === prefix ||
197
- fieldPath.startsWith(prefix + ".") ||
198
- fieldPath.startsWith(prefix + "["),
199
- );
200
-
201
- // Scope manifests visible to this ref path.
202
- const visibleScopeManifests: ResourceManifest[] = [];
203
- if (inScope) {
204
- for (const [pointer, manifests] of scopeManifestsByPointer) {
205
- const prefix = pointer.replace(/^\//, "").replace(/\//g, ".");
206
- if (
207
- fieldPath === prefix ||
208
- fieldPath.startsWith(prefix + ".") ||
209
- fieldPath.startsWith(prefix + "[")
210
- ) {
211
- visibleScopeManifests.push(...manifests);
212
- }
213
- }
214
- }
215
-
216
- for (const { value: val, path: concretePath } of resolveFieldEntries(r, fieldPath)) {
217
- if (!val) continue;
159
+ // Phase 3 per-ref validation. The walker supplies each ref site already
160
+ // resolved against the schema-from-expanded field map, with its source
161
+ // enclosure (`inScope`) and the scope manifests visible to it — so this
162
+ // handler only validates, it does not re-walk.
163
+ visitManifest(
164
+ resources,
165
+ registry,
166
+ {
167
+ onRef: (e) => {
168
+ const r = e.source;
169
+ const resourceLabel = `${r.kind}/${r.metadata!.name as string}`;
170
+ const resourceData = { kind: r.kind, name: r.metadata!.name as string };
171
+ const filePath = (r.metadata as { source?: string } | undefined)?.source;
172
+ const { value: val, concretePath, entry, visibleScopeManifests } = e;
218
173
 
219
174
  // `!ref <name>` sentinel — bare resource name marked at parse time as a
220
175
  // reference. Look it up against the slot's x-telo-ref constraint exactly
@@ -233,7 +188,7 @@ export function validateReferences(
233
188
  message: `${resourceLabel}: reference at '${concretePath}' → resource '${refName}' not found`,
234
189
  data: { resource: resourceData, filePath, path: concretePath },
235
190
  });
236
- continue;
191
+ return;
237
192
  }
238
193
  const kindErrors = checkKind(target.kind as string, entry, registry, aliases);
239
194
  if (kindErrors.length > 0) {
@@ -245,7 +200,7 @@ export function validateReferences(
245
200
  data: { resource: resourceData, filePath, path: concretePath },
246
201
  });
247
202
  }
248
- continue;
203
+ return;
249
204
  }
250
205
 
251
206
  // Name-only reference (plain string) — look up by name to validate.
@@ -263,7 +218,7 @@ export function validateReferences(
263
218
  // Multi-dot prefixes like "Alias.Kind.Name" are local resources with qualified
264
219
  // kinds — those must be validated.
265
220
  if (refKindPrefix && !refKindPrefix.includes(".") && aliases.hasAlias(refKindPrefix)) {
266
- continue;
221
+ return;
267
222
  }
268
223
  diagnostics.push({
269
224
  severity: DiagnosticSeverity.Error,
@@ -272,7 +227,7 @@ export function validateReferences(
272
227
  message: `${resourceLabel}: reference at '${concretePath}' → resource '${val}' not found`,
273
228
  data: { resource: resourceData, filePath, path: concretePath },
274
229
  });
275
- continue;
230
+ return;
276
231
  }
277
232
  const kindErrors = checkKind(target.kind as string, entry, registry, aliases);
278
233
  if (kindErrors.length > 0) {
@@ -284,14 +239,14 @@ export function validateReferences(
284
239
  data: { resource: resourceData, filePath, path: concretePath },
285
240
  });
286
241
  }
287
- continue;
242
+ return;
288
243
  }
289
244
 
290
- if (typeof val !== "object") continue;
245
+ if (typeof val !== "object") return;
291
246
  const refVal = val as Record<string, unknown>;
292
247
 
293
248
  // Skip inline resources — Phase 2 normalization hasn't run yet.
294
- if (isInlineResource(refVal)) continue;
249
+ if (isInlineResource(refVal)) return;
295
250
 
296
251
  // 1. Structural check
297
252
  if (typeof refVal.kind !== "string" || typeof refVal.name !== "string") {
@@ -302,7 +257,7 @@ export function validateReferences(
302
257
  message: `${resourceLabel}: reference at '${concretePath}' must have string 'kind' and 'name' fields`,
303
258
  data: { resource: resourceData, filePath, path: concretePath },
304
259
  });
305
- continue;
260
+ return;
306
261
  }
307
262
 
308
263
  // 2. Kind check
@@ -330,177 +285,179 @@ export function validateReferences(
330
285
  data: { resource: resourceData, filePath, path: concretePath },
331
286
  });
332
287
  }
333
- }
334
- }
335
- }
288
+ },
289
+ },
290
+ { aliases, aliasesByModule, skipKinds: SYSTEM_KINDS, expand: true },
291
+ );
336
292
 
337
293
  // Phase 3b — x-telo-schema-from validation.
338
294
  // For each field with a schemaFrom path expression, resolve the anchor ref to get the
339
295
  // concrete kind, navigate the JSON Pointer into that kind's definition schema, and
340
- // validate the field value against the resulting sub-schema.
341
- for (const r of resources) {
342
- if (!r.metadata?.name || !r.kind || SYSTEM_KINDS.has(r.kind)) continue;
343
-
344
- const fieldMap = registry.getFieldMapForKind(r.kind, aliases);
345
- if (!fieldMap) continue;
346
-
347
- const resourceLabel = `${r.kind}/${r.metadata.name as string}`;
348
- const resourceData = { kind: r.kind, name: r.metadata.name as string };
349
- const filePath = (r.metadata as { source?: string } | undefined)?.source;
350
-
351
- for (const [fieldPath, entry] of fieldMap) {
352
- if (!isSchemaFromEntry(entry)) continue;
353
-
354
- const { schemaFrom } = entry;
355
- const isAbsolute = schemaFrom.startsWith("/");
356
- const expr = isAbsolute ? schemaFrom.slice(1) : schemaFrom;
357
- const slashIdx = expr.indexOf("/");
358
- if (slashIdx === -1) {
359
- diagnostics.push({
360
- severity: DiagnosticSeverity.Error,
361
- code: "INVALID_SCHEMA_FROM",
362
- source: SOURCE,
363
- message: `${resourceLabel}: x-telo-schema-from "${schemaFrom}" must contain at least one "/" to separate anchor from JSON Pointer`,
364
- data: { resource: resourceData, filePath, path: fieldPath },
365
- });
366
- continue;
367
- }
368
-
369
- const anchorName = expr.slice(0, slashIdx);
370
- const jsonPointer = "/" + expr.slice(slashIdx + 1);
371
-
372
- // Aliased absolute kind path — first segment carries a dot, e.g.
373
- // "HttpDispatch.Outcomes/$defs/Returns". Resolves the alias through the
374
- // *kind owner's* scope (not the consumer's), navigates the JSON Pointer
375
- // into the resolved definition's schema, and validates each field value.
376
- //
377
- // Relative anchors are property names that cannot contain a dot
378
- // (CEL-style identifiers), so a dot in anchorName is unambiguous.
379
- if (!isAbsolute && anchorName.includes(".")) {
380
- const resolvedResourceKind = aliases.resolveKind(r.kind) ?? r.kind;
381
- const resourceDef =
382
- registry.resolve(r.kind) ?? registry.resolve(resolvedResourceKind);
383
- const owningModule = (resourceDef?.metadata as { module?: string } | undefined)?.module;
384
- const ownerScope =
385
- (owningModule ? aliasesByModule?.get(owningModule) : undefined) ?? aliases;
386
-
387
- const targetKind = ownerScope.resolveKind(anchorName);
388
- if (!targetKind) {
296
+ // validate the field value against the resulting sub-schema. Driven off the base map
297
+ // (un-expanded) so each schema-from slot is seen as its own site.
298
+ visitManifest(
299
+ resources,
300
+ registry,
301
+ {
302
+ onSchemaFrom: (e) => {
303
+ const r = e.source;
304
+ const fieldPath = e.fieldPath;
305
+ const resourceLabel = `${r.kind}/${r.metadata!.name as string}`;
306
+ const resourceData = { kind: r.kind, name: r.metadata!.name as string };
307
+ const filePath = (r.metadata as { source?: string } | undefined)?.source;
308
+
309
+ const { schemaFrom } = e.entry;
310
+ const isAbsolute = schemaFrom.startsWith("/");
311
+ const expr = isAbsolute ? schemaFrom.slice(1) : schemaFrom;
312
+ const slashIdx = expr.indexOf("/");
313
+ if (slashIdx === -1) {
389
314
  diagnostics.push({
390
315
  severity: DiagnosticSeverity.Error,
391
- code: "SCHEMA_FROM_MISSING_PATH",
316
+ code: "INVALID_SCHEMA_FROM",
392
317
  source: SOURCE,
393
- message: `${resourceLabel}: x-telo-schema-from at '${fieldPath}' cannot resolve alias '${anchorName}'`,
318
+ message: `${resourceLabel}: x-telo-schema-from "${schemaFrom}" must contain at least one "/" to separate anchor from JSON Pointer`,
394
319
  data: { resource: resourceData, filePath, path: fieldPath },
395
320
  });
396
- continue;
321
+ return;
397
322
  }
398
323
 
399
- const targetDef = registry.resolve(targetKind);
400
- if (!targetDef?.schema) {
401
- diagnostics.push({
402
- severity: DiagnosticSeverity.Error,
403
- code: "SCHEMA_FROM_MISSING_PATH",
404
- source: SOURCE,
405
- message: `${resourceLabel}: x-telo-schema-from at '${fieldPath}' kind '${targetKind}' has no schema`,
406
- data: { resource: resourceData, filePath, path: fieldPath },
407
- });
408
- continue;
409
- }
324
+ const anchorName = expr.slice(0, slashIdx);
325
+ const jsonPointer = "/" + expr.slice(slashIdx + 1);
326
+
327
+ // Aliased absolute kind path — first segment carries a dot, e.g.
328
+ // "HttpDispatch.Outcomes/$defs/Returns". Resolves the alias through the
329
+ // *kind owner's* scope (not the consumer's), navigates the JSON Pointer
330
+ // into the resolved definition's schema, and validates each field value.
331
+ //
332
+ // Relative anchors are property names that cannot contain a dot
333
+ // (CEL-style identifiers), so a dot in anchorName is unambiguous.
334
+ if (!isAbsolute && anchorName.includes(".")) {
335
+ const resolvedResourceKind = aliases.resolveKind(r.kind) ?? r.kind;
336
+ const resourceDef =
337
+ registry.resolve(r.kind) ?? registry.resolve(resolvedResourceKind);
338
+ const owningModule = (resourceDef?.metadata as { module?: string } | undefined)?.module;
339
+ const ownerScope =
340
+ (owningModule ? aliasesByModule?.get(owningModule) : undefined) ?? aliases;
341
+
342
+ const targetKind = ownerScope.resolveKind(anchorName);
343
+ if (!targetKind) {
344
+ diagnostics.push({
345
+ severity: DiagnosticSeverity.Error,
346
+ code: "SCHEMA_FROM_MISSING_PATH",
347
+ source: SOURCE,
348
+ message: `${resourceLabel}: x-telo-schema-from at '${fieldPath}' → cannot resolve alias '${anchorName}'`,
349
+ data: { resource: resourceData, filePath, path: fieldPath },
350
+ });
351
+ return;
352
+ }
410
353
 
411
- const subSchema = navigateJsonPointer(targetDef.schema, jsonPointer);
412
- if (subSchema === undefined) {
413
- diagnostics.push({
414
- severity: DiagnosticSeverity.Error,
415
- code: "SCHEMA_FROM_MISSING_PATH",
416
- source: SOURCE,
417
- message: `${resourceLabel}: x-telo-schema-from at '${fieldPath}' → kind '${targetKind}' has no schema path '${jsonPointer}'`,
418
- data: { resource: resourceData, filePath, path: fieldPath },
419
- });
420
- continue;
421
- }
354
+ const targetDef = registry.resolve(targetKind);
355
+ if (!targetDef?.schema) {
356
+ diagnostics.push({
357
+ severity: DiagnosticSeverity.Error,
358
+ code: "SCHEMA_FROM_MISSING_PATH",
359
+ source: SOURCE,
360
+ message: `${resourceLabel}: x-telo-schema-from at '${fieldPath}' → kind '${targetKind}' has no schema`,
361
+ data: { resource: resourceData, filePath, path: fieldPath },
362
+ });
363
+ return;
364
+ }
422
365
 
423
- for (const { value: fieldValue, path: concretePath } of resolveFieldEntries(r, fieldPath)) {
424
- if (fieldValue == null) continue;
425
- const issues = registry.validateWithRefs(fieldValue, subSchema as Record<string, any>);
426
- for (const issue of issues) {
366
+ const subSchema = navigateJsonPointer(targetDef.schema, jsonPointer);
367
+ if (subSchema === undefined) {
427
368
  diagnostics.push({
428
369
  severity: DiagnosticSeverity.Error,
429
- code: "DEPENDENT_SCHEMA_MISMATCH",
370
+ code: "SCHEMA_FROM_MISSING_PATH",
430
371
  source: SOURCE,
431
- message: `${resourceLabel}: '${concretePath}' does not match schema from '${anchorName}${jsonPointer}': ${issue}`,
432
- data: { resource: resourceData, filePath, path: concretePath },
372
+ message: `${resourceLabel}: x-telo-schema-from at '${fieldPath}' kind '${targetKind}' has no schema path '${jsonPointer}'`,
373
+ data: { resource: resourceData, filePath, path: fieldPath },
433
374
  });
375
+ return;
434
376
  }
377
+
378
+ for (const { value: fieldValue, path: concretePath } of resolveFieldEntries(r, fieldPath)) {
379
+ if (fieldValue == null) continue;
380
+ const issues = registry.validateWithRefs(fieldValue, subSchema as Record<string, any>);
381
+ for (const issue of issues) {
382
+ diagnostics.push({
383
+ severity: DiagnosticSeverity.Error,
384
+ code: "DEPENDENT_SCHEMA_MISMATCH",
385
+ source: SOURCE,
386
+ message: `${resourceLabel}: '${concretePath}' does not match schema from '${anchorName}${jsonPointer}': ${issue}`,
387
+ data: { resource: resourceData, filePath, path: concretePath },
388
+ });
389
+ }
390
+ }
391
+ return;
435
392
  }
436
- continue;
437
- }
438
393
 
439
- // Derive the anchor path in the resource config.
440
- let anchorPath: string;
441
- if (isAbsolute) {
442
- anchorPath = anchorName;
443
- } else {
444
- // Relative: replace the last dot-segment of fieldPath with anchorName.
445
- // e.g. "nodes[].options" → "nodes[].backend"
446
- const lastDot = fieldPath.lastIndexOf(".");
447
- anchorPath = lastDot === -1 ? anchorName : fieldPath.slice(0, lastDot + 1) + anchorName;
448
- }
394
+ // Derive the anchor path in the resource config.
395
+ let anchorPath: string;
396
+ if (isAbsolute) {
397
+ anchorPath = anchorName;
398
+ } else {
399
+ // Relative: replace the last dot-segment of fieldPath with anchorName.
400
+ // e.g. "nodes[].options" → "nodes[].backend"
401
+ const lastDot = fieldPath.lastIndexOf(".");
402
+ anchorPath = lastDot === -1 ? anchorName : fieldPath.slice(0, lastDot + 1) + anchorName;
403
+ }
449
404
 
450
- const anchorValues = resolveFieldValues(r, anchorPath);
451
- if (anchorValues.length === 0) continue; // anchor field not set — nothing to validate
405
+ const anchorValues = resolveFieldValues(r, anchorPath);
406
+ if (anchorValues.length === 0) return; // anchor field not set — nothing to validate
452
407
 
453
- const fieldEntries = resolveFieldEntries(r, fieldPath);
408
+ const fieldEntries = resolveFieldEntries(r, fieldPath);
454
409
 
455
- for (let i = 0; i < fieldEntries.length; i++) {
456
- const { value: fieldValue, path: concretePath } = fieldEntries[i];
457
- if (fieldValue == null) continue;
410
+ for (let i = 0; i < fieldEntries.length; i++) {
411
+ const { value: fieldValue, path: concretePath } = fieldEntries[i];
412
+ if (fieldValue == null) continue;
458
413
 
459
- // For absolute paths, the single anchor applies to all field values.
460
- const anchorVal = isAbsolute ? anchorValues[0] : anchorValues[i];
461
- if (!anchorVal || typeof anchorVal !== "object") continue;
414
+ // For absolute paths, the single anchor applies to all field values.
415
+ const anchorVal = isAbsolute ? anchorValues[0] : anchorValues[i];
416
+ if (!anchorVal || typeof anchorVal !== "object") continue;
462
417
 
463
- const refVal = anchorVal as Record<string, unknown>;
464
- if (typeof refVal.kind !== "string") continue;
418
+ const refVal = anchorVal as Record<string, unknown>;
419
+ if (typeof refVal.kind !== "string") continue;
465
420
 
466
- const refResolvedKind = aliases.resolveKind(refVal.kind) ?? refVal.kind;
467
- const refDef = registry.resolve(refVal.kind) ?? registry.resolve(refResolvedKind);
468
- if (!refDef?.schema) {
469
- diagnostics.push({
470
- severity: DiagnosticSeverity.Error,
471
- code: "SCHEMA_FROM_MISSING_PATH",
472
- source: SOURCE,
473
- message: `${resourceLabel}: x-telo-schema-from at '${concretePath}' → kind '${refVal.kind}' has no schema`,
474
- data: { resource: resourceData, filePath, path: concretePath },
475
- });
476
- continue;
477
- }
421
+ const refResolvedKind = aliases.resolveKind(refVal.kind) ?? refVal.kind;
422
+ const refDef = registry.resolve(refVal.kind) ?? registry.resolve(refResolvedKind);
423
+ if (!refDef?.schema) {
424
+ diagnostics.push({
425
+ severity: DiagnosticSeverity.Error,
426
+ code: "SCHEMA_FROM_MISSING_PATH",
427
+ source: SOURCE,
428
+ message: `${resourceLabel}: x-telo-schema-from at '${concretePath}' → kind '${refVal.kind}' has no schema`,
429
+ data: { resource: resourceData, filePath, path: concretePath },
430
+ });
431
+ continue;
432
+ }
478
433
 
479
- const subSchema = navigateJsonPointer(refDef.schema, jsonPointer);
480
- if (subSchema === undefined) {
481
- diagnostics.push({
482
- severity: DiagnosticSeverity.Error,
483
- code: "SCHEMA_FROM_MISSING_PATH",
484
- source: SOURCE,
485
- message: `${resourceLabel}: x-telo-schema-from at '${concretePath}' → kind '${refVal.kind}' has no schema path '${jsonPointer}'`,
486
- data: { resource: resourceData, filePath, path: concretePath },
487
- });
488
- continue;
489
- }
434
+ const subSchema = navigateJsonPointer(refDef.schema, jsonPointer);
435
+ if (subSchema === undefined) {
436
+ diagnostics.push({
437
+ severity: DiagnosticSeverity.Error,
438
+ code: "SCHEMA_FROM_MISSING_PATH",
439
+ source: SOURCE,
440
+ message: `${resourceLabel}: x-telo-schema-from at '${concretePath}' → kind '${refVal.kind}' has no schema path '${jsonPointer}'`,
441
+ data: { resource: resourceData, filePath, path: concretePath },
442
+ });
443
+ continue;
444
+ }
490
445
 
491
- const issues = registry.validateWithRefs(fieldValue, subSchema as Record<string, any>);
492
- for (const issue of issues) {
493
- diagnostics.push({
494
- severity: DiagnosticSeverity.Error,
495
- code: "DEPENDENT_SCHEMA_MISMATCH",
496
- source: SOURCE,
497
- message: `${resourceLabel}: '${concretePath}' does not match schema from '${refVal.kind}${jsonPointer}': ${issue}`,
498
- data: { resource: resourceData, filePath, path: concretePath },
499
- });
446
+ const issues = registry.validateWithRefs(fieldValue, subSchema as Record<string, any>);
447
+ for (const issue of issues) {
448
+ diagnostics.push({
449
+ severity: DiagnosticSeverity.Error,
450
+ code: "DEPENDENT_SCHEMA_MISMATCH",
451
+ source: SOURCE,
452
+ message: `${resourceLabel}: '${concretePath}' does not match schema from '${refVal.kind}${jsonPointer}': ${issue}`,
453
+ data: { resource: resourceData, filePath, path: concretePath },
454
+ });
455
+ }
500
456
  }
501
- }
502
- }
503
- }
457
+ },
458
+ },
459
+ { aliases, aliasesByModule, skipKinds: SYSTEM_KINDS, expand: false },
460
+ );
504
461
 
505
462
  return diagnostics;
506
463
  }
@@ -0,0 +1,95 @@
1
+ import type { Environment } from "@marcbachmann/cel-js";
2
+ import type { ResourceManifest } from "@telorun/sdk";
3
+ import { extractAccessChains, INDEX_SEGMENT, walkCelExpressions } from "@telorun/templating";
4
+ import { type AnalysisDiagnostic, DiagnosticSeverity } from "./types.js";
5
+
6
+ const SOURCE = "telo-analyzer";
7
+
8
+ /** Module-doc namespaces whose entries are consumed via `<ns>.<name>` CEL
9
+ * access. One table drives the whole check — adding a namespace is an entry,
10
+ * not a branch. */
11
+ const NAMESPACES = ["variables", "secrets", "ports"] as const;
12
+
13
+ /**
14
+ * Warn about declared `variables` / `secrets` / `ports` entries that no CEL
15
+ * expression references. A declared-but-unconsumed entry is dead weight at
16
+ * best and misleading at worst (an unbound `ports` entry makes a runner
17
+ * advertise a port the app never listens on).
18
+ *
19
+ * Generic across all three namespaces. References are collected from every CEL
20
+ * expression (both `${{ … }}` and `!cel`, via `walkCelExpressions`) by
21
+ * extracting member-access chains: a `<ns>.<name>` chain marks `<name>` used.
22
+ * Dynamic access (`<ns>[expr]`, or the namespace passed whole, e.g.
23
+ * `keys(variables)`) yields a chain that stops at the namespace root — that
24
+ * can't be attributed to a name, so the whole namespace is conservatively
25
+ * suppressed to avoid false positives.
26
+ *
27
+ * Application-only: an Application's `variables` / `secrets` / `ports` flow
28
+ * exclusively through CEL (into resource fields, or into `Telo.Import` inputs),
29
+ * so unreferenced means dead. A `Telo.Library`'s `variables` / `secrets` are a
30
+ * public input contract consumed by its controllers — invisible to CEL
31
+ * analysis — so they are deliberately not flagged.
32
+ */
33
+ export function validateUnusedDeclarations(
34
+ manifests: ResourceManifest[],
35
+ celEnv: Environment,
36
+ ): AnalysisDiagnostic[] {
37
+ const moduleManifest = manifests.find((m) => m.kind === "Telo.Application") as
38
+ | Record<string, any>
39
+ | undefined;
40
+ if (!moduleManifest) return [];
41
+
42
+ const declared = new Map<string, string[]>();
43
+ for (const ns of NAMESPACES) {
44
+ const block = moduleManifest[ns];
45
+ if (block && typeof block === "object" && !Array.isArray(block)) {
46
+ const names = Object.keys(block);
47
+ if (names.length > 0) declared.set(ns, names);
48
+ }
49
+ }
50
+ if (declared.size === 0) return [];
51
+
52
+ const used = new Map<string, Set<string>>(NAMESPACES.map((ns) => [ns, new Set<string>()]));
53
+ const suppressed = new Set<string>();
54
+
55
+ for (const m of manifests) {
56
+ walkCelExpressions(m, "", (expr, _path, engineName) => {
57
+ if (engineName !== "cel") return;
58
+ let ast: unknown;
59
+ try {
60
+ ast = celEnv.parse(expr).ast;
61
+ } catch {
62
+ return; // syntax errors are reported by the CEL engine pass
63
+ }
64
+ for (const chain of extractAccessChains(ast as Parameters<typeof extractAccessChains>[0])) {
65
+ const ns = chain[0];
66
+ if (!used.has(ns)) continue;
67
+ const member = chain[1];
68
+ // No static member after the namespace root — either the namespace is
69
+ // used whole (`keys(ports)` → ["ports"]) or accessed dynamically
70
+ // (`ports[x]` → ["ports", "[*]"]). Neither can be attributed to a
71
+ // declared name, so suppress the namespace rather than false-positive.
72
+ if (member === undefined || member === INDEX_SEGMENT) suppressed.add(ns);
73
+ else used.get(ns)!.add(member);
74
+ }
75
+ });
76
+ }
77
+
78
+ const diagnostics: AnalysisDiagnostic[] = [];
79
+ const filePath = (moduleManifest.metadata as { source?: string } | undefined)?.source;
80
+ for (const [ns, names] of declared) {
81
+ if (suppressed.has(ns)) continue;
82
+ const seen = used.get(ns)!;
83
+ for (const name of names) {
84
+ if (seen.has(name)) continue;
85
+ diagnostics.push({
86
+ severity: DiagnosticSeverity.Warning,
87
+ code: "UNUSED_DECLARATION",
88
+ source: SOURCE,
89
+ message: `${ns}.${name} is declared but never referenced in any CEL expression.`,
90
+ data: { filePath, path: `${ns}.${name}` },
91
+ });
92
+ }
93
+ }
94
+ return diagnostics;
95
+ }