@telorun/analyzer 0.11.0 → 1.2.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 (56) hide show
  1. package/LICENSE +2 -2
  2. package/README.md +3 -3
  3. package/dist/analysis-registry.d.ts +7 -0
  4. package/dist/analysis-registry.d.ts.map +1 -1
  5. package/dist/analysis-registry.js +38 -0
  6. package/dist/analyzer.d.ts.map +1 -1
  7. package/dist/analyzer.js +53 -9
  8. package/dist/builtins.d.ts.map +1 -1
  9. package/dist/builtins.js +44 -1
  10. package/dist/index.d.ts +1 -0
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +1 -0
  13. package/dist/kernel-globals.d.ts.map +1 -1
  14. package/dist/kernel-globals.js +9 -11
  15. package/dist/manifest-loader.d.ts +23 -1
  16. package/dist/manifest-loader.d.ts.map +1 -1
  17. package/dist/manifest-loader.js +66 -3
  18. package/dist/normalize-inline-resources.d.ts.map +1 -1
  19. package/dist/normalize-inline-resources.js +26 -14
  20. package/dist/position-metadata.d.ts +5 -1
  21. package/dist/position-metadata.d.ts.map +1 -1
  22. package/dist/position-metadata.js +8 -1
  23. package/dist/reference-field-map.d.ts +21 -4
  24. package/dist/reference-field-map.d.ts.map +1 -1
  25. package/dist/reference-field-map.js +35 -19
  26. package/dist/residual-schema.d.ts +23 -0
  27. package/dist/residual-schema.d.ts.map +1 -0
  28. package/dist/residual-schema.js +45 -0
  29. package/dist/rewrite-synthetic-origins.d.ts +10 -0
  30. package/dist/rewrite-synthetic-origins.d.ts.map +1 -0
  31. package/dist/rewrite-synthetic-origins.js +55 -0
  32. package/dist/types.d.ts +12 -0
  33. package/dist/types.d.ts.map +1 -1
  34. package/dist/validate-cel-context.d.ts +5 -0
  35. package/dist/validate-cel-context.d.ts.map +1 -1
  36. package/dist/validate-cel-context.js +27 -15
  37. package/dist/validate-provider-coherence.d.ts +23 -0
  38. package/dist/validate-provider-coherence.d.ts.map +1 -0
  39. package/dist/validate-provider-coherence.js +148 -0
  40. package/dist/validate-references.js +24 -24
  41. package/package.json +7 -4
  42. package/src/analysis-registry.ts +37 -0
  43. package/src/analyzer.ts +55 -11
  44. package/src/builtins.ts +44 -1
  45. package/src/index.ts +1 -0
  46. package/src/kernel-globals.ts +9 -11
  47. package/src/manifest-loader.ts +69 -4
  48. package/src/normalize-inline-resources.ts +48 -13
  49. package/src/position-metadata.ts +8 -1
  50. package/src/reference-field-map.ts +46 -18
  51. package/src/residual-schema.ts +49 -0
  52. package/src/rewrite-synthetic-origins.ts +75 -0
  53. package/src/types.ts +12 -0
  54. package/src/validate-cel-context.ts +28 -15
  55. package/src/validate-provider-coherence.ts +166 -0
  56. package/src/validate-references.ts +24 -24
@@ -82,7 +82,14 @@ export function normalizeInlineResources(
82
82
  );
83
83
 
84
84
  const invocationContext = isRefEntry(entry) ? entry.context : undefined;
85
- const extracted = extractInlinesAtPath(resource, fieldPath, parentName, parentModule, invocationContext);
85
+ const extracted = extractInlinesAtPath(
86
+ resource,
87
+ fieldPath,
88
+ parentName,
89
+ resource.kind,
90
+ parentModule,
91
+ invocationContext,
92
+ );
86
93
  for (const manifest of extracted) {
87
94
  result.push(manifest);
88
95
  queue.push(manifest as ResourceManifest & { metadata: { name: string } });
@@ -99,18 +106,42 @@ export function normalizeInlineResources(
99
106
  * Walks `resource` following `fieldPath` (dot notation, `[]` = array traversal).
100
107
  * Mutates the resource in-place: replaces each inline value with `{kind, name}`.
101
108
  * Returns the extracted manifests.
109
+ *
110
+ * Each extracted manifest carries `metadata.xTeloOrigin` so downstream
111
+ * diagnostics can be rerouted back to the parent doc's YAML position:
112
+ * - `parentKind` / `parentName` — the resource that owned the inline slot
113
+ * - `pathFromParent` — concrete dotted path with `[N]` indices, matching
114
+ * `buildPositionIndex` keys (e.g. `routes[0].handler`)
102
115
  */
103
116
  function extractInlinesAtPath(
104
117
  resource: ResourceManifest,
105
118
  fieldPath: string,
106
119
  parentName: string,
120
+ parentKind: string,
107
121
  parentModule: string | undefined,
108
122
  invocationContext?: Record<string, any>,
109
123
  ): ResourceManifest[] {
110
124
  const extracted: ResourceManifest[] = [];
111
125
  const parts = fieldPath.split(".");
112
126
 
113
- function traverse(obj: unknown, partsLeft: string[], nameParts: string[]): void {
127
+ function emit(
128
+ inline: Record<string, unknown>,
129
+ nameSegments: string[],
130
+ concretePath: string,
131
+ ): string {
132
+ const name = sanitizeName([parentName, ...nameSegments].join("_"));
133
+ extracted.push(
134
+ buildManifest(inline, name, parentKind, parentName, concretePath, parentModule, invocationContext),
135
+ );
136
+ return name;
137
+ }
138
+
139
+ function traverse(
140
+ obj: unknown,
141
+ partsLeft: string[],
142
+ nameParts: string[],
143
+ pathSoFar: string,
144
+ ): void {
114
145
  if (!obj || typeof obj !== "object" || partsLeft.length === 0) return;
115
146
 
116
147
  const [head, ...rest] = partsLeft;
@@ -123,15 +154,15 @@ function extractInlinesAtPath(
123
154
  const elem = container[mapKey];
124
155
  if (!elem || typeof elem !== "object") continue;
125
156
  const sanitizedKey = sanitizeName(mapKey);
157
+ const childPath = pathSoFar ? `${pathSoFar}.${mapKey}` : mapKey;
126
158
 
127
159
  if (rest.length === 0) {
128
160
  if (isInlineResource(elem as Record<string, unknown>)) {
129
- const name = sanitizeName([parentName, ...nameParts, sanitizedKey].join("_"));
130
- extracted.push(buildManifest(elem as Record<string, unknown>, name, parentModule, invocationContext));
161
+ const name = emit(elem as Record<string, unknown>, [...nameParts, sanitizedKey], childPath);
131
162
  container[mapKey] = { kind: (elem as Record<string, unknown>).kind, name };
132
163
  }
133
164
  } else {
134
- traverse(elem, rest, [...nameParts, sanitizedKey]);
165
+ traverse(elem, rest, [...nameParts, sanitizedKey], childPath);
135
166
  }
136
167
  }
137
168
  return;
@@ -142,6 +173,7 @@ function extractInlinesAtPath(
142
173
  const container = obj as Record<string, unknown>;
143
174
  const val = container[key];
144
175
  if (val == null) return;
176
+ const keyPath = pathSoFar ? `${pathSoFar}.${key}` : key;
145
177
 
146
178
  if (isArr) {
147
179
  if (!Array.isArray(val)) return;
@@ -152,39 +184,41 @@ function extractInlinesAtPath(
152
184
  typeof (elem as Record<string, unknown>).name === "string"
153
185
  ? ((elem as Record<string, unknown>).name as string)
154
186
  : String(idx);
187
+ const childPath = `${keyPath}[${idx}]`;
155
188
 
156
189
  if (rest.length === 0) {
157
190
  // Array element itself is the ref slot
158
191
  if (isInlineResource(elem as Record<string, unknown>)) {
159
- const name = sanitizeName([parentName, ...nameParts, key, elemId].join("_"));
160
- extracted.push(buildManifest(elem as Record<string, unknown>, name, parentModule, invocationContext));
192
+ const name = emit(elem as Record<string, unknown>, [...nameParts, key, elemId], childPath);
161
193
  val[idx] = { kind: (elem as Record<string, unknown>).kind, name };
162
194
  }
163
195
  } else {
164
- traverse(elem, rest, [...nameParts, key, elemId]);
196
+ traverse(elem, rest, [...nameParts, key, elemId], childPath);
165
197
  }
166
198
  }
167
199
  } else {
168
200
  if (rest.length === 0) {
169
201
  // val is the ref slot
170
202
  if (val && typeof val === "object" && !Array.isArray(val) && isInlineResource(val as Record<string, unknown>)) {
171
- const name = sanitizeName([parentName, ...nameParts, key].join("_"));
172
- extracted.push(buildManifest(val as Record<string, unknown>, name, parentModule, invocationContext));
203
+ const name = emit(val as Record<string, unknown>, [...nameParts, key], keyPath);
173
204
  container[key] = { kind: (val as Record<string, unknown>).kind, name };
174
205
  }
175
206
  } else {
176
- traverse(val, rest, [...nameParts, key]);
207
+ traverse(val, rest, [...nameParts, key], keyPath);
177
208
  }
178
209
  }
179
210
  }
180
211
 
181
- traverse(resource, parts, []);
212
+ traverse(resource, parts, [], "");
182
213
  return extracted;
183
214
  }
184
215
 
185
216
  function buildManifest(
186
217
  inline: Record<string, unknown>,
187
218
  name: string,
219
+ parentKind: string,
220
+ parentName: string,
221
+ pathFromParent: string,
188
222
  parentModule: string | undefined,
189
223
  invocationContext?: Record<string, any>,
190
224
  ): ResourceManifest {
@@ -200,6 +234,7 @@ function buildManifest(
200
234
  // Inherit parent module only if the inline doesn't already declare one
201
235
  ...(parentModule && !existingMeta.module ? { module: parentModule } : {}),
202
236
  ...(invocationContext ? { xTeloInvocationContext: invocationContext } : {}),
237
+ xTeloOrigin: { parentKind, parentName, pathFromParent },
203
238
  },
204
- } as ResourceManifest;
239
+ } as unknown as ResourceManifest;
205
240
  }
@@ -63,7 +63,11 @@ function offsetToPosition(offset: number, lineOffsets: number[]): Position {
63
63
  }
64
64
 
65
65
  /** Walks the YAML AST and records source ranges for every field value, keyed
66
- * by dotted path (e.g. "kind", "config.handler", "config.routes[0].path"). */
66
+ * by dotted path (e.g. "kind", "config.handler", "config.routes[0].path").
67
+ * Map keys are also recorded under the `@key:<path>` namespace so diagnostic
68
+ * resolvers can squiggle just the key identifier instead of the full value
69
+ * block — used when a diagnostic targets a missing child property and the
70
+ * resolver has to fall back to the parent. */
67
71
  export function buildPositionIndex(doc: Document, lineOffsets: number[]): PositionIndex {
68
72
  const index: PositionIndex = new Map();
69
73
 
@@ -83,6 +87,9 @@ export function buildPositionIndex(doc: Document, lineOffsets: number[]): Positi
83
87
  const key = isScalar(pair.key) ? String(pair.key.value) : null;
84
88
  if (key == null) continue;
85
89
  const childPath = path ? `${path}.${key}` : key;
90
+ if (pair.key && (pair.key as any).range) {
91
+ recordNode(pair.key, `@key:${childPath}`);
92
+ }
86
93
  if (pair.value != null) {
87
94
  recordNode(pair.value, childPath);
88
95
  walk(pair.value, childPath);
@@ -63,23 +63,39 @@ export function isInlineResource(val: Record<string, unknown>): boolean {
63
63
  return true;
64
64
  }
65
65
 
66
- /** Resolves all values at a field map path in a resource config.
67
- * Path-segment markers:
68
- * - `[]` iterate array values at this key
66
+ /** A value found at a field-map path, paired with the concrete path that
67
+ * produced it. `path` has every `[]` substituted with `[N]` and every `{}`
68
+ * substituted with the actual map key, matching the format produced by
69
+ * `buildPositionIndex`. Used so diagnostics emitted against a specific
70
+ * array element / map entry can be resolved back to a YAML range. */
71
+ export interface ResolvedFieldEntry {
72
+ value: unknown;
73
+ path: string;
74
+ }
75
+
76
+ /** Resolves all `{value, path}` entries at a field map path in a resource
77
+ * config. The returned `path` is the concrete dotted path produced by the
78
+ * substitutions below, matching the format `buildPositionIndex` keys on.
79
+ * Path-segment markers accepted in the input `path`:
80
+ * - `[]` iterate array values at this key, substituting `[N]` per item
81
+ * (e.g. `routes[]` → `routes[0]`, `routes[1]`, …).
69
82
  * - `{}` iterate map values (every value in an `additionalProperties`-typed
70
83
  * object — used for fields like `content[mime]` whose schema declares
71
- * a key-as-MIME map). The path is `<key>.{}.<rest>`. */
72
- export function resolveFieldValues(obj: unknown, path: string): unknown[] {
84
+ * a key-as-MIME map). Substituted with the literal map key joined by
85
+ * a dot, so the input `content.{}.encoder` yields concrete paths
86
+ * like `content.application/json.encoder`. */
87
+ export function resolveFieldEntries(obj: unknown, path: string): ResolvedFieldEntry[] {
73
88
  const parts = path.split(".");
74
- let current: unknown[] = [obj];
89
+ let current: ResolvedFieldEntry[] = [{ value: obj, path: "" }];
75
90
  for (const part of parts) {
76
91
  if (part === "{}") {
77
- // Iterate the values of every map currently in `current`.
78
- const next: unknown[] = [];
79
- for (const item of current) {
80
- if (!item || typeof item !== "object") continue;
81
- for (const v of Object.values(item as Record<string, unknown>)) {
82
- if (v != null) next.push(v);
92
+ const next: ResolvedFieldEntry[] = [];
93
+ for (const entry of current) {
94
+ if (!entry.value || typeof entry.value !== "object") continue;
95
+ for (const [k, v] of Object.entries(entry.value as Record<string, unknown>)) {
96
+ if (v != null) {
97
+ next.push({ value: v, path: entry.path ? `${entry.path}.${k}` : k });
98
+ }
83
99
  }
84
100
  }
85
101
  current = next;
@@ -87,19 +103,31 @@ export function resolveFieldValues(obj: unknown, path: string): unknown[] {
87
103
  }
88
104
  const isArray = part.endsWith("[]");
89
105
  const key = isArray ? part.slice(0, -2) : part;
90
- const next: unknown[] = [];
91
- for (const item of current) {
92
- if (!item || typeof item !== "object") continue;
93
- const val = (item as Record<string, unknown>)[key];
106
+ const next: ResolvedFieldEntry[] = [];
107
+ for (const entry of current) {
108
+ if (!entry.value || typeof entry.value !== "object") continue;
109
+ const val = (entry.value as Record<string, unknown>)[key];
94
110
  if (val == null) continue;
95
- if (isArray && Array.isArray(val)) next.push(...val);
96
- else if (!isArray) next.push(val);
111
+ const basePath = entry.path ? `${entry.path}.${key}` : key;
112
+ if (isArray && Array.isArray(val)) {
113
+ for (let i = 0; i < val.length; i++) {
114
+ if (val[i] != null) next.push({ value: val[i], path: `${basePath}[${i}]` });
115
+ }
116
+ } else if (!isArray) {
117
+ next.push({ value: val, path: basePath });
118
+ }
97
119
  }
98
120
  current = next;
99
121
  }
100
122
  return current;
101
123
  }
102
124
 
125
+ /** Backwards-compat wrapper that drops the concrete path. Prefer
126
+ * `resolveFieldEntries` for new code that wants positions. */
127
+ export function resolveFieldValues(obj: unknown, path: string): unknown[] {
128
+ return resolveFieldEntries(obj, path).map((e) => e.value);
129
+ }
130
+
103
131
  /**
104
132
  * Traverses a definition's JSON Schema once and returns a field map recording every
105
133
  * x-telo-ref slot and every x-telo-scope slot.
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Build the residual JSON Schema for a `variables` / `secrets` entry.
3
+ *
4
+ * For Telo.Application env-binding entries (those with an `env:` key), strips
5
+ * the kernel-specific wrapper keys `env` and `default` — `default` here is
6
+ * the *fallback host value* the kernel coerces when the env var is unset, not
7
+ * a JSON Schema annotation, so it must not leak into the validator.
8
+ *
9
+ * For Telo.Library entries (no `env:`), passes the entry through unchanged.
10
+ * Library `default:` is a standard JSON Schema annotation and stays.
11
+ *
12
+ * Single source of truth for "residual schema" referenced by both the
13
+ * analyzer's CEL globals normalization and the kernel's runtime env-var
14
+ * resolver — keeping them aligned prevents the two surfaces from drifting.
15
+ */
16
+ export function residualEntrySchema(
17
+ entry: Record<string, unknown> | null | undefined,
18
+ ): Record<string, unknown> {
19
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
20
+ return { type: "object", additionalProperties: true };
21
+ }
22
+ const isAppEnvBinding = "env" in entry;
23
+ const out: Record<string, unknown> = {};
24
+ for (const [key, value] of Object.entries(entry)) {
25
+ if (isAppEnvBinding && (key === "env" || key === "default")) continue;
26
+ out[key] = value;
27
+ }
28
+ return out;
29
+ }
30
+
31
+ /**
32
+ * Apply `residualEntrySchema` to every entry in a `variables` / `secrets` map.
33
+ * Returns a property-map suitable for use as the inner schema of CEL's
34
+ * `variables` / `secrets` namespaces.
35
+ */
36
+ export function residualEntrySchemaMap(
37
+ entries: Record<string, unknown> | null | undefined,
38
+ ): Record<string, Record<string, unknown>> {
39
+ const out: Record<string, Record<string, unknown>> = {};
40
+ if (!entries || typeof entries !== "object" || Array.isArray(entries)) {
41
+ return out;
42
+ }
43
+ for (const [name, value] of Object.entries(entries)) {
44
+ if (value !== null && typeof value === "object" && !Array.isArray(value)) {
45
+ out[name] = residualEntrySchema(value as Record<string, unknown>);
46
+ }
47
+ }
48
+ return out;
49
+ }
@@ -0,0 +1,75 @@
1
+ import type { ResourceManifest } from "@telorun/sdk";
2
+ import type { AnalysisDiagnostic } from "./types.js";
3
+
4
+ interface XTeloOrigin {
5
+ parentKind: string;
6
+ parentName: string;
7
+ pathFromParent: string;
8
+ }
9
+
10
+ function readOrigin(manifest: ResourceManifest | undefined): XTeloOrigin | undefined {
11
+ if (!manifest) return undefined;
12
+ const origin = (manifest.metadata as { xTeloOrigin?: XTeloOrigin } | undefined)?.xTeloOrigin;
13
+ if (
14
+ !origin ||
15
+ typeof origin.parentKind !== "string" ||
16
+ typeof origin.parentName !== "string" ||
17
+ typeof origin.pathFromParent !== "string"
18
+ ) {
19
+ return undefined;
20
+ }
21
+ return origin;
22
+ }
23
+
24
+ /** Diagnostics emitted on synthetic manifests (resources extracted by
25
+ * `normalizeInlineResources`) carry the synthetic's identity in
26
+ * `data.resource`, which has no YAML source. Rewrite each such diagnostic
27
+ * back to the chain root: walk up `metadata.xTeloOrigin` until a manifest
28
+ * with no origin is reached, and prepend each hop's `pathFromParent` to
29
+ * `data.path` so position-index lookups against the root doc resolve. */
30
+ export function rewriteSyntheticOrigins(
31
+ diagnostics: AnalysisDiagnostic[],
32
+ manifests: ResourceManifest[],
33
+ ): AnalysisDiagnostic[] {
34
+ const byName = new Map<string, ResourceManifest>();
35
+ for (const m of manifests) {
36
+ const name = m.metadata?.name;
37
+ if (typeof name === "string") byName.set(name, m);
38
+ }
39
+
40
+ return diagnostics.map((d) => {
41
+ const data = d.data as
42
+ | { resource?: { kind?: string; name?: string }; path?: string; filePath?: string }
43
+ | undefined;
44
+ if (!data?.resource?.name) return d;
45
+
46
+ let current = byName.get(data.resource.name);
47
+ let origin = readOrigin(current);
48
+ if (!origin) return d;
49
+
50
+ let accumPath = typeof data.path === "string" ? data.path : "";
51
+ let rootKind: string = origin.parentKind;
52
+ let rootName: string = origin.parentName;
53
+
54
+ while (origin) {
55
+ accumPath = accumPath ? `${origin.pathFromParent}.${accumPath}` : origin.pathFromParent;
56
+ rootKind = origin.parentKind;
57
+ rootName = origin.parentName;
58
+ current = byName.get(origin.parentName);
59
+ origin = readOrigin(current);
60
+ }
61
+
62
+ const rootFilePath =
63
+ (current?.metadata as { source?: string } | undefined)?.source ?? data.filePath;
64
+
65
+ return {
66
+ ...d,
67
+ data: {
68
+ ...data,
69
+ resource: { kind: rootKind, name: rootName },
70
+ filePath: rootFilePath,
71
+ path: accumPath,
72
+ },
73
+ };
74
+ });
75
+ }
package/src/types.ts CHANGED
@@ -81,6 +81,18 @@ export interface LoaderInitOptions {
81
81
 
82
82
  export interface AnalysisOptions {
83
83
  strictContexts?: boolean;
84
+ /** When true, `analyze()` runs the state-mutating setup (module identity /
85
+ * alias / definition registration plus `normalizeInlineResources`) but
86
+ * skips every diagnostic-producing pass — per-resource validation, the
87
+ * Library `env:` check, `validateExtends`, `validateProviderCoherence`,
88
+ * and `validateThrowsCoverage`. Used by the kernel when a previous load
89
+ * has already stamped the manifest set as valid (by content hash), so
90
+ * the registry still gets populated without paying the validation walk
91
+ * on every cold start. The caller takes responsibility for the
92
+ * correctness guarantee — pass this only when something durable
93
+ * (on-disk stamp) attests that the manifests passed a real analyze
94
+ * pass at the same analyzer / kernel version. */
95
+ skipValidation?: boolean;
84
96
  }
85
97
 
86
98
  /** Pre-seeded state for incremental analysis. Passed to StaticAnalyzer.analyze() so it does
@@ -119,6 +119,11 @@ export function pathMatchesScope(exprPath: string, scope: string): boolean {
119
119
  * `manifestRoot.provide.kind` as a kind name, looks up the kind's Telo.Definition,
120
120
  * and returns the `outputType` schema.
121
121
  *
122
+ * Accepts either a single string or an array of strings. With an array, paths
123
+ * are tried in order and the first one that resolves to a usable schema wins —
124
+ * used by `result:` to find its dispatch target under whichever entry-point
125
+ * field (`provide:` or `invoke:`) the definition declares.
126
+ *
122
127
  * - `x-telo-context-ref-from`: existing form — reads `{kind, name}` object from
123
128
  * `manifestItem.<path>`, looks up the named manifest, returns its `<subpath>` field.
124
129
  *
@@ -153,8 +158,16 @@ export function resolveContextAnnotations(
153
158
  }
154
159
 
155
160
  const fromRoot = schema["x-telo-context-from-root"] as string | undefined;
156
- const fromRefKind = schema["x-telo-context-from-ref-kind"] as string | undefined;
157
- if (fromRoot || fromRefKind) {
161
+ const fromRefKindRaw = schema["x-telo-context-from-ref-kind"] as
162
+ | string
163
+ | string[]
164
+ | undefined;
165
+ const fromRefKinds = fromRefKindRaw == null
166
+ ? []
167
+ : Array.isArray(fromRefKindRaw)
168
+ ? fromRefKindRaw
169
+ : [fromRefKindRaw];
170
+ if (fromRoot || fromRefKinds.length > 0) {
158
171
  if (fromRoot) {
159
172
  const resolved = navigatePath(manifestRoot, fromRoot.split("/")) as
160
173
  | Record<string, any>
@@ -163,22 +176,22 @@ export function resolveContextAnnotations(
163
176
  return resolved;
164
177
  }
165
178
  }
166
- if (fromRefKind && defs) {
167
- const hashIdx = fromRefKind.indexOf("#");
168
- if (hashIdx > 0) {
179
+ if (defs) {
180
+ for (const fromRefKind of fromRefKinds) {
181
+ const hashIdx = fromRefKind.indexOf("#");
182
+ if (hashIdx <= 0) continue;
169
183
  const refPath = fromRefKind.slice(0, hashIdx);
170
184
  const field = fromRefKind.slice(hashIdx + 1);
171
185
  const kindValue = navigatePath(manifestRoot, refPath.split("/"));
172
- if (typeof kindValue === "string" && kindValue.length > 0) {
173
- const canonical = aliases?.resolveKind(kindValue) ?? kindValue;
174
- const def = defs.resolve(canonical);
175
- const typeField = def
176
- ? (def as Record<string, unknown>)[field]
177
- : undefined;
178
- const resolved = resolveTypeFieldToSchema(typeField, allManifests ?? []);
179
- if (resolved && typeof resolved === "object") {
180
- return resolved;
181
- }
186
+ if (typeof kindValue !== "string" || kindValue.length === 0) continue;
187
+ const canonical = aliases?.resolveKind(kindValue) ?? kindValue;
188
+ const def = defs.resolve(canonical);
189
+ const typeField = def
190
+ ? (def as Record<string, unknown>)[field]
191
+ : undefined;
192
+ const resolved = resolveTypeFieldToSchema(typeField, allManifests ?? []);
193
+ if (resolved && typeof resolved === "object") {
194
+ return resolved;
182
195
  }
183
196
  }
184
197
  }
@@ -0,0 +1,166 @@
1
+ import type { ResourceManifest } from "@telorun/sdk";
2
+ import type { AliasResolver } from "./alias-resolver.js";
3
+ import type { DefinitionRegistry } from "./definition-registry.js";
4
+ import { DiagnosticSeverity, type AnalysisDiagnostic } from "./types.js";
5
+
6
+ const SOURCE = "telo-analyzer";
7
+
8
+ /**
9
+ * Validates coherence rules for `Telo.Definition` documents that use the `provide:`
10
+ * template target, plus the implementation-presence rule on `Telo.Provider`
11
+ * definitions.
12
+ *
13
+ * Diagnostics:
14
+ * - PROVIDE_ON_NON_PROVIDER: `provide:` declared on a definition whose
15
+ * `capability` is not `Telo.Provider`.
16
+ * - PROVIDE_DISPATCHER_CONFLICT: `provide:` co-exists with `invoke:` or `run:`
17
+ * on the same definition.
18
+ * - PROVIDE_TARGET_UNKNOWN: `provide.name` does not resolve to an entry in
19
+ * `resources:`.
20
+ * - PROVIDE_TARGET_NOT_INVOCABLE: `provide.name` resolves to a resource whose
21
+ * kind is registered but not a `Telo.Invocable`.
22
+ * - PROVIDER_MISSING_IMPLEMENTATION: definition with `capability: Telo.Provider`
23
+ * declares neither `controllers:` (TS-backed) nor `provide:` (template-backed).
24
+ */
25
+ export function validateProviderCoherence(
26
+ manifests: ResourceManifest[],
27
+ registry: DefinitionRegistry,
28
+ aliases: AliasResolver,
29
+ ): AnalysisDiagnostic[] {
30
+ const diagnostics: AnalysisDiagnostic[] = [];
31
+
32
+ const importedModules = new Set<string>();
33
+ for (const m of manifests) {
34
+ if (m.kind !== "Telo.Import") continue;
35
+ const resolved = (m.metadata as { resolvedModuleName?: string } | undefined)
36
+ ?.resolvedModuleName;
37
+ if (resolved) importedModules.add(resolved);
38
+ }
39
+
40
+ for (const m of manifests) {
41
+ if (m.kind !== "Telo.Definition") continue;
42
+ const name = m.metadata?.name as string | undefined;
43
+ if (!name) continue;
44
+ const ownModule = (m.metadata as { module?: string } | undefined)?.module;
45
+ if (ownModule && importedModules.has(ownModule)) continue;
46
+ const filePath = (m.metadata as { source?: string } | undefined)?.source;
47
+ const resource = { kind: m.kind, name };
48
+ const label = `${m.kind}/${name}`;
49
+
50
+ const md = m as Record<string, unknown>;
51
+ const capability = typeof md.capability === "string" ? md.capability : undefined;
52
+ const provide = md.provide;
53
+ const invoke = md.invoke;
54
+ const run = md.run;
55
+ const controllers = md.controllers;
56
+ const resources = md.resources;
57
+
58
+ const hasProvide = provide !== undefined && provide !== null;
59
+ const hasInvoke = invoke !== undefined && invoke !== null;
60
+ const hasRun = run !== undefined && run !== null;
61
+ const hasControllers = Array.isArray(controllers) && controllers.length > 0;
62
+
63
+ if (hasProvide && capability !== "Telo.Provider") {
64
+ diagnostics.push({
65
+ severity: DiagnosticSeverity.Error,
66
+ code: "PROVIDE_ON_NON_PROVIDER",
67
+ source: SOURCE,
68
+ message:
69
+ `${label}: 'provide:' is only valid on definitions with 'capability: Telo.Provider' ` +
70
+ `(found '${capability ?? "<unset>"}'). Use 'invoke:' or 'run:' for other capabilities.`,
71
+ data: { resource, filePath, path: "provide" },
72
+ });
73
+ }
74
+
75
+ if (hasProvide && (hasInvoke || hasRun)) {
76
+ const conflict = hasInvoke ? "invoke" : "run";
77
+ diagnostics.push({
78
+ severity: DiagnosticSeverity.Error,
79
+ code: "PROVIDE_DISPATCHER_CONFLICT",
80
+ source: SOURCE,
81
+ message:
82
+ `${label}: 'provide:' cannot co-exist with '${conflict}:'. ` +
83
+ `A definition declares exactly one dispatch entry-point.`,
84
+ data: { resource, filePath, path: "provide" },
85
+ });
86
+ }
87
+
88
+ if (hasProvide && typeof provide === "object" && !Array.isArray(provide)) {
89
+ const provideObj = provide as { kind?: unknown; name?: unknown };
90
+ const providedName = typeof provideObj.name === "string" ? provideObj.name : undefined;
91
+ const providedKind = typeof provideObj.kind === "string" ? provideObj.kind : undefined;
92
+ if (providedName && Array.isArray(resources)) {
93
+ const match = resources.find((r) => {
94
+ const meta = (r as { metadata?: { name?: unknown } })?.metadata;
95
+ return typeof meta?.name === "string" && meta.name === providedName;
96
+ }) as { kind?: unknown } | undefined;
97
+ if (!match) {
98
+ diagnostics.push({
99
+ severity: DiagnosticSeverity.Error,
100
+ code: "PROVIDE_TARGET_UNKNOWN",
101
+ source: SOURCE,
102
+ message:
103
+ `${label}: 'provide.name: ${providedName}' does not match any entry's ` +
104
+ `metadata.name in 'resources:'.`,
105
+ data: { resource, filePath, path: "provide.name" },
106
+ });
107
+ } else if (typeof match.kind === "string") {
108
+ // `provide.kind` is the type contract the analyzer uses to type
109
+ // `result` CEL against the target's `outputType`. The runtime
110
+ // dispatches on `provide.name` and ignores `provide.kind`, so a
111
+ // mismatch silently degrades `result` typing to an open schema
112
+ // (and at runtime quietly invokes the actually-matched resource).
113
+ // Flag the divergence so result-typing never lies.
114
+ if (providedKind) {
115
+ const providedCanonical = aliases.resolveKind(providedKind) ?? providedKind;
116
+ const matchCanonical = aliases.resolveKind(match.kind) ?? match.kind;
117
+ if (providedCanonical !== matchCanonical) {
118
+ diagnostics.push({
119
+ severity: DiagnosticSeverity.Error,
120
+ code: "PROVIDE_KIND_MISMATCH",
121
+ source: SOURCE,
122
+ message:
123
+ `${label}: 'provide.kind: ${providedKind}' disagrees with the matched ` +
124
+ `'resources:' entry's kind '${match.kind}' (matched by metadata.name ` +
125
+ `'${providedName}'). The runtime dispatches by name, so 'provide.kind' ` +
126
+ `is decorative — but the analyzer types 'result:' against it, and a ` +
127
+ `mismatch silently turns off that typing.`,
128
+ data: { resource, filePath, path: "provide.kind" },
129
+ });
130
+ }
131
+ }
132
+ const resolvedKind = aliases.resolveKind(match.kind) ?? match.kind;
133
+ const targetDef = registry.resolve(resolvedKind) ?? registry.resolve(match.kind);
134
+ if (targetDef && targetDef.kind === "Telo.Definition") {
135
+ const targetCap = (targetDef as { capability?: unknown }).capability;
136
+ if (typeof targetCap === "string" && targetCap !== "Telo.Invocable") {
137
+ diagnostics.push({
138
+ severity: DiagnosticSeverity.Error,
139
+ code: "PROVIDE_TARGET_NOT_INVOCABLE",
140
+ source: SOURCE,
141
+ message:
142
+ `${label}: 'provide.name: ${providedName}' resolves to a ${match.kind} ` +
143
+ `(capability '${targetCap}'); 'provide:' requires a Telo.Invocable target.`,
144
+ data: { resource, filePath, path: "provide.name" },
145
+ });
146
+ }
147
+ }
148
+ }
149
+ }
150
+ }
151
+
152
+ if (capability === "Telo.Provider" && !hasControllers && !hasProvide) {
153
+ diagnostics.push({
154
+ severity: DiagnosticSeverity.Error,
155
+ code: "PROVIDER_MISSING_IMPLEMENTATION",
156
+ source: SOURCE,
157
+ message:
158
+ `${label}: 'capability: Telo.Provider' requires either 'controllers:' ` +
159
+ `(TS-backed) or 'provide:' (template-backed) to declare an implementation.`,
160
+ data: { resource, filePath, path: "capability" },
161
+ });
162
+ }
163
+ }
164
+
165
+ return diagnostics;
166
+ }