@telorun/analyzer 0.11.0 → 0.12.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 (92) hide show
  1. package/LICENSE +2 -2
  2. package/README.md +3 -3
  3. package/dist/adapters/http-adapter.d.ts +10 -0
  4. package/dist/adapters/http-adapter.d.ts.map +1 -0
  5. package/dist/adapters/http-adapter.js +18 -0
  6. package/dist/adapters/node-adapter.d.ts +17 -0
  7. package/dist/adapters/node-adapter.d.ts.map +1 -0
  8. package/dist/adapters/node-adapter.js +71 -0
  9. package/dist/adapters/registry-adapter.d.ts +15 -0
  10. package/dist/adapters/registry-adapter.d.ts.map +1 -0
  11. package/dist/adapters/registry-adapter.js +53 -0
  12. package/dist/analysis-registry.d.ts +7 -0
  13. package/dist/analysis-registry.d.ts.map +1 -1
  14. package/dist/analysis-registry.js +38 -0
  15. package/dist/analyzer.d.ts +15 -0
  16. package/dist/analyzer.d.ts.map +1 -1
  17. package/dist/analyzer.js +114 -10
  18. package/dist/builtins.d.ts.map +1 -1
  19. package/dist/builtins.js +58 -1
  20. package/dist/definition-registry.d.ts.map +1 -1
  21. package/dist/definition-registry.js +16 -0
  22. package/dist/dependency-graph.d.ts.map +1 -1
  23. package/dist/dependency-graph.js +27 -13
  24. package/dist/index.d.ts +2 -0
  25. package/dist/index.d.ts.map +1 -1
  26. package/dist/index.js +2 -0
  27. package/dist/kernel-globals.d.ts.map +1 -1
  28. package/dist/kernel-globals.js +9 -11
  29. package/dist/manifest-loader.d.ts +23 -1
  30. package/dist/manifest-loader.d.ts.map +1 -1
  31. package/dist/manifest-loader.js +66 -3
  32. package/dist/normalize-inline-resources.d.ts.map +1 -1
  33. package/dist/normalize-inline-resources.js +26 -14
  34. package/dist/position-metadata.d.ts +11 -2
  35. package/dist/position-metadata.d.ts.map +1 -1
  36. package/dist/position-metadata.js +18 -3
  37. package/dist/precompile.d.ts.map +1 -1
  38. package/dist/precompile.js +9 -1
  39. package/dist/reference-field-map.d.ts +21 -4
  40. package/dist/reference-field-map.d.ts.map +1 -1
  41. package/dist/reference-field-map.js +93 -25
  42. package/dist/residual-schema.d.ts +23 -0
  43. package/dist/residual-schema.d.ts.map +1 -0
  44. package/dist/residual-schema.js +45 -0
  45. package/dist/resolve-ref-sentinels.d.ts +27 -0
  46. package/dist/resolve-ref-sentinels.d.ts.map +1 -0
  47. package/dist/resolve-ref-sentinels.js +114 -0
  48. package/dist/rewrite-synthetic-origins.d.ts +10 -0
  49. package/dist/rewrite-synthetic-origins.d.ts.map +1 -0
  50. package/dist/rewrite-synthetic-origins.js +55 -0
  51. package/dist/schema-compat.d.ts +7 -1
  52. package/dist/schema-compat.d.ts.map +1 -1
  53. package/dist/schema-compat.js +19 -2
  54. package/dist/system-kinds.d.ts +25 -0
  55. package/dist/system-kinds.d.ts.map +1 -0
  56. package/dist/system-kinds.js +34 -0
  57. package/dist/types.d.ts +12 -0
  58. package/dist/types.d.ts.map +1 -1
  59. package/dist/validate-cel-context.d.ts +5 -0
  60. package/dist/validate-cel-context.d.ts.map +1 -1
  61. package/dist/validate-cel-context.js +27 -15
  62. package/dist/validate-provider-coherence.d.ts +23 -0
  63. package/dist/validate-provider-coherence.d.ts.map +1 -0
  64. package/dist/validate-provider-coherence.js +148 -0
  65. package/dist/validate-references.d.ts.map +1 -1
  66. package/dist/validate-references.js +141 -36
  67. package/dist/with-synthetic-positions.d.ts +28 -0
  68. package/dist/with-synthetic-positions.d.ts.map +1 -0
  69. package/dist/with-synthetic-positions.js +45 -0
  70. package/package.json +7 -4
  71. package/src/analysis-registry.ts +37 -0
  72. package/src/analyzer.ts +118 -12
  73. package/src/builtins.ts +58 -1
  74. package/src/definition-registry.ts +15 -0
  75. package/src/dependency-graph.ts +27 -14
  76. package/src/index.ts +2 -0
  77. package/src/kernel-globals.ts +9 -11
  78. package/src/manifest-loader.ts +69 -4
  79. package/src/normalize-inline-resources.ts +48 -13
  80. package/src/position-metadata.ts +18 -3
  81. package/src/precompile.ts +8 -1
  82. package/src/reference-field-map.ts +129 -24
  83. package/src/residual-schema.ts +49 -0
  84. package/src/resolve-ref-sentinels.ts +127 -0
  85. package/src/rewrite-synthetic-origins.ts +75 -0
  86. package/src/schema-compat.ts +19 -2
  87. package/src/system-kinds.ts +37 -0
  88. package/src/types.ts +12 -0
  89. package/src/validate-cel-context.ts +28 -15
  90. package/src/validate-provider-coherence.ts +166 -0
  91. package/src/validate-references.ts +138 -35
  92. package/src/with-synthetic-positions.ts +48 -0
@@ -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
  }
@@ -29,13 +29,21 @@ export function buildDocumentPositions(
29
29
 
30
30
  /** Line numbers (0-indexed) where each YAML document in a multi-doc file
31
31
  * starts. The first document is always at line 0; subsequent entries point
32
- * to the line after each `---` directive. */
32
+ * to the line after each `---` separator.
33
+ *
34
+ * A `---` at line 0 is the doc-start marker for doc 0 (the parser still
35
+ * emits a single document), not a separator before an empty doc — skipping
36
+ * it keeps `offsets.length === parsedDocs.length` so diagnostics for doc N
37
+ * don't land inside doc N-1's text. */
33
38
  export function documentLineOffsets(text: string): number[] {
34
39
  const offsets = [0];
35
40
  const lines = text.split("\n");
36
41
  for (let i = 0; i < lines.length; i++) {
37
42
  const t = lines[i].trimEnd();
38
- if (t === "---" || t.startsWith("--- ")) offsets.push(i + 1);
43
+ if (t === "---" || t.startsWith("--- ")) {
44
+ if (i === 0) continue;
45
+ offsets.push(i + 1);
46
+ }
39
47
  }
40
48
  return offsets;
41
49
  }
@@ -63,7 +71,11 @@ function offsetToPosition(offset: number, lineOffsets: number[]): Position {
63
71
  }
64
72
 
65
73
  /** 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"). */
74
+ * by dotted path (e.g. "kind", "config.handler", "config.routes[0].path").
75
+ * Map keys are also recorded under the `@key:<path>` namespace so diagnostic
76
+ * resolvers can squiggle just the key identifier instead of the full value
77
+ * block — used when a diagnostic targets a missing child property and the
78
+ * resolver has to fall back to the parent. */
67
79
  export function buildPositionIndex(doc: Document, lineOffsets: number[]): PositionIndex {
68
80
  const index: PositionIndex = new Map();
69
81
 
@@ -83,6 +95,9 @@ export function buildPositionIndex(doc: Document, lineOffsets: number[]): Positi
83
95
  const key = isScalar(pair.key) ? String(pair.key.value) : null;
84
96
  if (key == null) continue;
85
97
  const childPath = path ? `${path}.${key}` : key;
98
+ if (pair.key && (pair.key as any).range) {
99
+ recordNode(pair.key, `@key:${childPath}`);
100
+ }
86
101
  if (pair.value != null) {
87
102
  recordNode(pair.value, childPath);
88
103
  walk(pair.value, childPath);
package/src/precompile.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { Environment } from "@marcbachmann/cel-js";
2
2
  import { isCompiledValue } from "@telorun/sdk";
3
- import { compileString, defaultRegistry, isTaggedSentinel } from "@telorun/templating";
3
+ import { compileString, defaultRegistry, isRefSentinel, isTaggedSentinel } from "@telorun/templating";
4
4
 
5
5
  /**
6
6
  * Walks a raw YAML document and replaces all `${{ expr }}` strings (and
@@ -21,6 +21,13 @@ export function precompileDoc(doc: unknown, env: Environment): unknown {
21
21
  // analyzer's diagnostic walk can identify it on compiled trees too;
22
22
  // engines returning plain values (e.g. `literal` → a string) pass through
23
23
  // verbatim — the runtime contract is "any scalar value is fine."
24
+ // `!ref` sentinels are identity markers, not templating values. They must
25
+ // survive precompile intact so the analyzer's `resolveRefSentinels` pass
26
+ // can substitute them with `{kind, name}` objects against the resolved
27
+ // resource manifest. Running the engine's `compile` here would prematurely
28
+ // collapse the sentinel into its source string and the ref slot would
29
+ // arrive at the controller as a bare name with no kind.
30
+ if (isRefSentinel(doc)) return doc;
24
31
  if (isTaggedSentinel(doc)) {
25
32
  const engine = defaultRegistry().get(doc.engine);
26
33
  if (!engine) {
@@ -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.
@@ -114,7 +142,7 @@ export function buildReferenceFieldMap(schema: Record<string, any>): ReferenceFi
114
142
  const map: ReferenceFieldMap = new Map();
115
143
  if (schema.properties) {
116
144
  for (const [key, propSchema] of Object.entries(schema.properties)) {
117
- traverseNode(propSchema as Record<string, any>, key, map);
145
+ traverseNode(propSchema as Record<string, any>, key, map, schema);
118
146
  }
119
147
  }
120
148
  return map;
@@ -144,11 +172,29 @@ export function buildFieldMapAtPath(
144
172
  pathPrefix: string,
145
173
  ): ReferenceFieldMap {
146
174
  const map: ReferenceFieldMap = new Map();
147
- traverseNode(schema, pathPrefix, map);
175
+ traverseNode(schema, pathPrefix, map, schema);
148
176
  return map;
149
177
  }
150
178
 
151
- function traverseNode(node: Record<string, any>, path: string, map: ReferenceFieldMap): void {
179
+ function traverseNode(
180
+ node: Record<string, any>,
181
+ path: string,
182
+ map: ReferenceFieldMap,
183
+ root?: Record<string, any>,
184
+ visitedRefs: Set<string> = new Set(),
185
+ ): void {
186
+ // Local `$ref` is intentionally NOT followed. Descending into shared
187
+ // `$defs` (notably `Run.Sequence`'s `step` definition) would surface
188
+ // ref slots like `steps[].invoke` that Phase 5 then injects live
189
+ // instances into; today's `Run.Sequence` controller calls
190
+ // `instance.invoke()` directly when handed an instance, bypassing
191
+ // the kernel's `runInvoke` emit-Invoked path. The walker fix and the
192
+ // dispatcher fix need to land together — see the follow-up in
193
+ // [kernel/nodejs/plans/reference-syntax-unification.md] and the
194
+ // stopgap in `resource-context.ts:resolveChildren`. `visitedRefs`
195
+ // stays as a parameter so the recursive calls below thread the right
196
+ // signature; turning the descent back on is a single-branch change.
197
+ if (typeof node?.$ref === "string") return;
152
198
  // Scope slot — record and stop; do not recurse into scope contents
153
199
  if ("x-telo-scope" in node) {
154
200
  map.set(path, { scope: node["x-telo-scope"] });
@@ -172,13 +218,32 @@ function traverseNode(node: Record<string, any>, path: string, map: ReferenceFie
172
218
 
173
219
  // Array — recurse into items
174
220
  if (node.type === "array" && node.items) {
175
- traverseNode(node.items as Record<string, any>, path + "[]", map);
221
+ traverseNode(node.items as Record<string, any>, path + "[]", map, root, visitedRefs);
176
222
  }
177
223
 
178
224
  // Object — recurse into properties
179
225
  if (node.properties) {
180
226
  for (const [key, propSchema] of Object.entries(node.properties)) {
181
- traverseNode(propSchema as Record<string, any>, `${path}.${key}`, map);
227
+ traverseNode(propSchema as Record<string, any>, `${path}.${key}`, map, root, visitedRefs);
228
+ }
229
+ }
230
+
231
+ // Variant branches — descend into every alternative's properties / items.
232
+ // Schemas that discriminate on shape (Run.Sequence's step kinds:
233
+ // `oneOf: [{properties: {invoke}}, {properties: {try}}, ...]`) hide ref
234
+ // slots inside the branch. Walking each branch surfaces those slots into
235
+ // the field map so downstream passes (ref validation, sentinel
236
+ // resolution, dependency graph) cover them without a runtime fallback.
237
+ // The same field path may be added by multiple branches; the later
238
+ // assignment wins, which is fine — branches with the same field path
239
+ // share the same ref/context configuration (any divergence is already
240
+ // a schema bug).
241
+ for (const variantKey of ["oneOf", "anyOf", "allOf"] as const) {
242
+ const variants = node[variantKey];
243
+ if (!Array.isArray(variants)) continue;
244
+ for (const variant of variants) {
245
+ if (!variant || typeof variant !== "object") continue;
246
+ traverseVariant(variant as Record<string, any>, path, map, root, visitedRefs);
182
247
  }
183
248
  }
184
249
 
@@ -190,6 +255,46 @@ function traverseNode(node: Record<string, any>, path: string, map: ReferenceFie
190
255
  typeof node.additionalProperties === "object" &&
191
256
  !Array.isArray(node.additionalProperties)
192
257
  ) {
193
- traverseNode(node.additionalProperties as Record<string, any>, `${path}.{}`, map);
258
+ traverseNode(
259
+ node.additionalProperties as Record<string, any>,
260
+ `${path}.{}`,
261
+ map,
262
+ root,
263
+ visitedRefs,
264
+ );
265
+ }
266
+ }
267
+
268
+ /** Walk a single variant of a `oneOf` / `anyOf` / `allOf` branch. Only
269
+ * the properties / items / map slots are followed — collectRefs at the
270
+ * variant root is handled by the parent's `collectRefs(node)` already
271
+ * (anyOf of x-telo-ref branches is the canonical multi-ref shape). */
272
+ function traverseVariant(
273
+ variant: Record<string, any>,
274
+ path: string,
275
+ map: ReferenceFieldMap,
276
+ root?: Record<string, any>,
277
+ visitedRefs: Set<string> = new Set(),
278
+ ): void {
279
+ if (variant.properties) {
280
+ for (const [key, propSchema] of Object.entries(variant.properties)) {
281
+ traverseNode(propSchema as Record<string, any>, `${path}.${key}`, map, root, visitedRefs);
282
+ }
283
+ }
284
+ if (variant.type === "array" && variant.items) {
285
+ traverseNode(variant.items as Record<string, any>, path + "[]", map, root, visitedRefs);
286
+ }
287
+ if (
288
+ variant.additionalProperties &&
289
+ typeof variant.additionalProperties === "object" &&
290
+ !Array.isArray(variant.additionalProperties)
291
+ ) {
292
+ traverseNode(
293
+ variant.additionalProperties as Record<string, any>,
294
+ `${path}.{}`,
295
+ map,
296
+ root,
297
+ visitedRefs,
298
+ );
194
299
  }
195
300
  }
@@ -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,127 @@
1
+ import type { ResourceManifest } from "@telorun/sdk";
2
+ import { isRefSentinel } from "@telorun/templating";
3
+ import type { AliasResolver } from "./alias-resolver.js";
4
+ import type { DefinitionRegistry } from "./definition-registry.js";
5
+ import { isRefEntry } from "./reference-field-map.js";
6
+ import { REF_RESOLUTION_SKIP_KINDS as SYSTEM_KINDS } from "./system-kinds.js";
7
+
8
+ /**
9
+ * Walks every `x-telo-ref` slot in every non-system resource and rewrites
10
+ * `!ref <name>` sentinels in-place to `{kind: <resolved-kind>, name}`.
11
+ *
12
+ * The downstream pipeline (inline normalization, dependency graph, kernel
13
+ * controllers) expects every ref-slot value to be either a `{kind, name}`
14
+ * object, an inline-definition object, or a legacy bare string — resolving
15
+ * sentinels here keeps that contract intact so each consumer doesn't need
16
+ * its own sentinel branch.
17
+ *
18
+ * The walker assigns `kind` by name lookup (resource names are unique
19
+ * within a manifest scope). When the name doesn't resolve in the local
20
+ * `byName` map, the sentinel is left in place so `validateReferences`
21
+ * can emit the `UNRESOLVED_REFERENCE` diagnostic with full context.
22
+ *
23
+ * Mutation strategy: the field-path walker descends the resource tree
24
+ * directly and replaces the sentinel on its parent container. Re-parsing
25
+ * a string-encoded concrete path (the earlier shape) coupled the writer
26
+ * to the path-encoding rules of `resolveFieldEntries` — any new path
27
+ * marker would silently break this writer. Descending directly avoids
28
+ * that coupling.
29
+ */
30
+ export function resolveRefSentinels(
31
+ resources: ResourceManifest[],
32
+ registry: DefinitionRegistry,
33
+ aliases?: AliasResolver,
34
+ aliasesByModule?: Map<string, AliasResolver>,
35
+ ): void {
36
+ const byName = new Map<string, ResourceManifest>();
37
+ for (const r of resources) {
38
+ if (r.metadata?.name && !SYSTEM_KINDS.has(r.kind)) {
39
+ byName.set(r.metadata.name as string, r);
40
+ }
41
+ }
42
+
43
+ for (const r of resources) {
44
+ if (!r.metadata?.name || !r.kind || SYSTEM_KINDS.has(r.kind)) continue;
45
+
46
+ const fieldMap =
47
+ aliases && aliasesByModule
48
+ ? registry.expandedFieldMapForResource(r, aliases, aliasesByModule)
49
+ : registry.getFieldMapForKind(r.kind, aliases);
50
+ if (!fieldMap) continue;
51
+
52
+ for (const [fieldPath, entry] of fieldMap) {
53
+ if (!isRefEntry(entry)) continue;
54
+ replaceSentinelsAtPath(r as Record<string, unknown>, fieldPath, byName);
55
+ }
56
+ }
57
+ }
58
+
59
+ /** Walks `obj` along `fieldPath` (dot notation with `[]` for arrays and
60
+ * `{}` for additionalProperties-typed maps) and replaces any `!ref`
61
+ * sentinel value at the terminal slot with `{kind, name}` looked up
62
+ * via `byName`. Mutates the parent container in place; no string-path
63
+ * round-trip. */
64
+ function replaceSentinelsAtPath(
65
+ obj: Record<string, unknown>,
66
+ fieldPath: string,
67
+ byName: Map<string, ResourceManifest>,
68
+ ): void {
69
+ const parts = fieldPath.split(".");
70
+ descend(obj, parts, byName);
71
+ }
72
+
73
+ function descend(
74
+ obj: unknown,
75
+ parts: string[],
76
+ byName: Map<string, ResourceManifest>,
77
+ ): void {
78
+ if (obj == null || typeof obj !== "object" || parts.length === 0) return;
79
+ const [head, ...rest] = parts;
80
+
81
+ // Map iteration: descend into every value of the current object.
82
+ if (head === "{}") {
83
+ const container = obj as Record<string, unknown>;
84
+ for (const key of Object.keys(container)) {
85
+ const child = container[key];
86
+ if (rest.length === 0) {
87
+ if (isRefSentinel(child)) {
88
+ const target = byName.get(child.source);
89
+ if (target) container[key] = { kind: target.kind as string, name: child.source };
90
+ }
91
+ } else {
92
+ descend(child, rest, byName);
93
+ }
94
+ }
95
+ return;
96
+ }
97
+
98
+ const isArr = head.endsWith("[]");
99
+ const key = isArr ? head.slice(0, -2) : head;
100
+ const container = obj as Record<string, unknown>;
101
+ const val = container[key];
102
+ if (val == null) return;
103
+
104
+ if (isArr) {
105
+ if (!Array.isArray(val)) return;
106
+ for (let i = 0; i < val.length; i++) {
107
+ if (rest.length === 0) {
108
+ const elem = val[i];
109
+ if (isRefSentinel(elem)) {
110
+ const target = byName.get(elem.source);
111
+ if (target) val[i] = { kind: target.kind as string, name: elem.source };
112
+ }
113
+ } else {
114
+ descend(val[i], rest, byName);
115
+ }
116
+ }
117
+ } else {
118
+ if (rest.length === 0) {
119
+ if (isRefSentinel(val)) {
120
+ const target = byName.get(val.source);
121
+ if (target) container[key] = { kind: target.kind as string, name: val.source };
122
+ }
123
+ } else {
124
+ descend(val, rest, byName);
125
+ }
126
+ }
127
+ }
@@ -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
+ }