@telorun/analyzer 0.48.0 → 0.49.1

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 (50) hide show
  1. package/dist/analysis-registry.d.ts +22 -11
  2. package/dist/analysis-registry.d.ts.map +1 -1
  3. package/dist/analysis-registry.js +36 -39
  4. package/dist/analyzer.d.ts +38 -1
  5. package/dist/analyzer.d.ts.map +1 -1
  6. package/dist/analyzer.js +115 -83
  7. package/dist/builtins.d.ts.map +1 -1
  8. package/dist/builtins.js +72 -1
  9. package/dist/extends-resolution.d.ts +41 -0
  10. package/dist/extends-resolution.d.ts.map +1 -1
  11. package/dist/extends-resolution.js +68 -0
  12. package/dist/index.d.ts +4 -2
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +2 -1
  15. package/dist/invocation-contract.d.ts +100 -0
  16. package/dist/invocation-contract.d.ts.map +1 -0
  17. package/dist/invocation-contract.js +208 -0
  18. package/dist/manifest-loader.d.ts +11 -0
  19. package/dist/manifest-loader.d.ts.map +1 -1
  20. package/dist/manifest-loader.js +20 -0
  21. package/dist/schema-compat.d.ts +12 -4
  22. package/dist/schema-compat.d.ts.map +1 -1
  23. package/dist/schema-compat.js +185 -9
  24. package/dist/validate-base-mapping.js +11 -1
  25. package/dist/validate-cel-context.d.ts +0 -6
  26. package/dist/validate-cel-context.d.ts.map +1 -1
  27. package/dist/validate-cel-context.js +51 -4
  28. package/dist/validate-invocation-contract.d.ts +30 -0
  29. package/dist/validate-invocation-contract.d.ts.map +1 -0
  30. package/dist/validate-invocation-contract.js +394 -0
  31. package/dist/validate-step-inputs.d.ts +24 -0
  32. package/dist/validate-step-inputs.d.ts.map +1 -0
  33. package/dist/validate-step-inputs.js +87 -0
  34. package/dist/validate-throws-coverage.d.ts +1 -1
  35. package/dist/validate-throws-coverage.d.ts.map +1 -1
  36. package/dist/validate-throws-coverage.js +9 -1
  37. package/package.json +3 -3
  38. package/src/analysis-registry.ts +44 -34
  39. package/src/analyzer.ts +171 -100
  40. package/src/builtins.ts +74 -1
  41. package/src/extends-resolution.ts +86 -0
  42. package/src/index.ts +13 -1
  43. package/src/invocation-contract.ts +275 -0
  44. package/src/manifest-loader.ts +20 -0
  45. package/src/schema-compat.ts +191 -8
  46. package/src/validate-base-mapping.ts +14 -1
  47. package/src/validate-cel-context.ts +49 -4
  48. package/src/validate-invocation-contract.ts +450 -0
  49. package/src/validate-step-inputs.ts +117 -0
  50. package/src/validate-throws-coverage.ts +12 -2
@@ -0,0 +1,450 @@
1
+ import type { ResourceDefinition, ResourceManifest } from "@telorun/sdk";
2
+ import type { AliasResolver } from "./alias-resolver.js";
3
+ import type { DefinitionRegistry } from "./definition-registry.js";
4
+ import {
5
+ type ContractDirection,
6
+ type DefResolver,
7
+ effectiveContractField,
8
+ mappingFieldFor,
9
+ needsContractMapping,
10
+ } from "./extends-resolution.js";
11
+ import { buildReferenceFieldMap, isRefEntry } from "./reference-field-map.js";
12
+ import { DiagnosticSeverity, type AnalysisDiagnostic } from "./types.js";
13
+
14
+ const SOURCE = "telo-analyzer";
15
+
16
+ /**
17
+ * Phase 3 — static checks on declared invocation contracts.
18
+ *
19
+ * The runtime binds a contract to every instance and enforces it at dispatch;
20
+ * these are the failures worth catching before anything runs, and the ones the
21
+ * runtime cannot see at all (a declaration that is inert, an input nobody can
22
+ * supply).
23
+ *
24
+ * Diagnostics:
25
+ * - CONTRACT_MISSING_MAPPING: a definition that inherits its controller declares
26
+ * its own `inputType` / `outputType` without the `inputs:` / `result:` mapping
27
+ * that bridges it back to the inherited controller.
28
+ * - CONTRACT_INPUTS_SCHEMA_FORM: a leftover `inputs:` property map on a kind
29
+ * whose input contract is now `inputType:`.
30
+ * - CONTRACT_TYPE_NOT_FOUND: a contract names a type that is not declared in
31
+ * scope, so every call through it would fail at dispatch.
32
+ *
33
+ * Deliberately NOT diagnosed: an input that is neither `required:` nor
34
+ * defaulted. It is indistinguishable from a genuinely optional one — `Ai.Text`
35
+ * takes `prompt` OR `messages`, and `system` is optional on purpose — so the
36
+ * check fired ~40 times across the standard library on correct manifests with no
37
+ * way for an author to record the intent. A warning that cannot be silenced on
38
+ * correct code teaches people to ignore warnings.
39
+ */
40
+ export function validateInvocationContract(
41
+ manifests: ResourceManifest[],
42
+ registry: DefinitionRegistry,
43
+ aliases: AliasResolver,
44
+ aliasesByModule: Map<string, AliasResolver> = new Map(),
45
+ ): AnalysisDiagnostic[] {
46
+ const diagnostics: AnalysisDiagnostic[] = [];
47
+ const resolveDef: DefResolver = (kind, from) => {
48
+ const module = (from?.metadata as { module?: string } | undefined)?.module;
49
+ const scope = (module ? aliasesByModule.get(module) : undefined) ?? aliases;
50
+ return registry.resolve(kind) ?? registry.resolve(scope.resolveKind(kind) ?? kind);
51
+ };
52
+
53
+ // A published dependency's declarations are not the consumer's to fix.
54
+ const importedModules = new Set<string>();
55
+ for (const m of manifests) {
56
+ if (m.kind !== "Telo.Import") continue;
57
+ const resolved = (m.metadata as { resolvedModuleName?: string } | undefined)?.resolvedModuleName;
58
+ if (resolved) importedModules.add(resolved);
59
+ }
60
+ const isOwn = (m: ResourceManifest): boolean => {
61
+ const ownModule = (m.metadata as { module?: string } | undefined)?.module;
62
+ return !ownModule || !importedModules.has(ownModule);
63
+ };
64
+
65
+ for (const m of manifests) {
66
+ if (!isOwn(m)) continue;
67
+ const name = m.metadata?.name as string | undefined;
68
+ if (!name) continue;
69
+ const filePath = (m.metadata as { source?: string } | undefined)?.source;
70
+ const resource = { kind: m.kind, name };
71
+ const md = m as unknown as Record<string, unknown>;
72
+
73
+ if (m.kind === "Telo.Definition" || m.kind === "Telo.Abstract") {
74
+ checkMappingRequired(m, resource, filePath, resolveDef, diagnostics);
75
+ checkContractResolves(m, md, manifests, resource, filePath, diagnostics);
76
+ continue;
77
+ }
78
+
79
+ // A RESOURCE (an instance of some kind) — a leftover `inputs:` map is only
80
+ // meaningful against a kind whose schema no longer declares one.
81
+ const definition = resolveDef(m.kind, m as unknown as ResourceDefinition);
82
+ if (!definition) continue;
83
+ checkContractResolves(m, md, manifests, resource, filePath, diagnostics);
84
+ checkLeftoverInputsSchema(m, definition, md, resource, filePath, diagnostics);
85
+ checkRefSlotWiring(m, definition, manifests, resolveDef, resource, filePath, diagnostics);
86
+ }
87
+
88
+ return diagnostics;
89
+ }
90
+
91
+ /**
92
+ * The wiring rule: whether a ref slot may hold a resource whose input contract
93
+ * differs from the slot's declared kind.
94
+ *
95
+ * `extends` decides which resources a slot ACCEPTS; it never carried the
96
+ * dispatch contract. What matters per slot is whether the caller can supply the
97
+ * target's arguments at all:
98
+ *
99
+ * - the slot's declared kind declares no `inputType` and is not a run site →
100
+ * nothing to violate, accept;
101
+ * - the wiring site takes a paired author `inputs:` → the author supplies the
102
+ * arguments and can see both sides, so the call site check covers it;
103
+ * - the consumer's controller builds the arguments and knows only the slot's
104
+ * kind → the wired resource must not require anything that kind does not
105
+ * declare, because nothing could ever supply it.
106
+ *
107
+ * The run-site case is the same rule with an empty argument set: a `run()`
108
+ * dispatch passes nothing at all, so a target requiring any input can never be
109
+ * satisfied there. Both are keyed on declared capability and declared contracts,
110
+ * never on a kind's name.
111
+ */
112
+ function checkRefSlotWiring(
113
+ m: ResourceManifest,
114
+ definition: ResourceDefinition,
115
+ manifests: ResourceManifest[],
116
+ resolveDef: DefResolver,
117
+ resource: { kind: string; name: string },
118
+ filePath: string | undefined,
119
+ diagnostics: AnalysisDiagnostic[],
120
+ ): void {
121
+ const schema = definition.schema as Record<string, any> | undefined;
122
+ if (!schema) return;
123
+
124
+ for (const [path, entry] of buildReferenceFieldMap(schema)) {
125
+ if (!isRefEntry(entry)) continue;
126
+ // A slot that takes a paired `inputs:` is the author's to fill; its values
127
+ // are checked at the call site instead, against the target's own contract.
128
+ if (slotTakesPairedInputs(schema, path)) continue;
129
+
130
+ const slotDeclares = slotDeclaredInputs(entry.refs, resolveDef, manifests);
131
+ const runSite = isRunOnlySlot(entry.refs, resolveDef);
132
+ if (!runSite && slotDeclares === undefined) continue;
133
+
134
+ const ownModule = (m.metadata as { module?: string } | undefined)?.module;
135
+ for (const name of refValuesAt(m as Record<string, any>, path)) {
136
+ // Scoped to the declaring module: a resource of the same name in another
137
+ // module is a different resource, and checking against its contract would
138
+ // report on something the author never wired.
139
+ const target = findInModule(manifests, name, ownModule);
140
+ if (!target) continue;
141
+ const targetDef = resolveDef(target.kind, target as unknown as ResourceDefinition);
142
+ const targetRequired = requiredInputsOf(
143
+ contractSchemaFor(target, targetDef, resolveDef, manifests),
144
+ );
145
+ if (!targetRequired || targetRequired.length === 0) continue;
146
+
147
+ const unsatisfiable = runSite
148
+ ? targetRequired
149
+ : targetRequired.filter((key) => !(slotDeclares ?? []).includes(key));
150
+ if (unsatisfiable.length === 0) continue;
151
+
152
+ diagnostics.push({
153
+ severity: DiagnosticSeverity.Error,
154
+ code: runSite ? "CONTRACT_INPUTS_AT_RUN_SITE" : "CONTRACT_SLOT_INPUTS_UNSATISFIABLE",
155
+ source: SOURCE,
156
+ message: runSite
157
+ ? `${m.kind}/${resource.name}: '${name}' is wired at '${path}', which starts it with \`run()\` — ` +
158
+ `a dispatch that passes no arguments — but its contract requires ${list(unsatisfiable)}. ` +
159
+ `Nothing can supply them there. Invoke it from a step instead, or drop the requirement.`
160
+ : `${m.kind}/${resource.name}: '${name}' is wired at '${path}', where the consumer builds the ` +
161
+ `arguments from the slot's declared kind alone, but its contract requires ${list(unsatisfiable)} ` +
162
+ `which that kind does not declare. Nothing could supply them.`,
163
+ data: { resource, filePath, path },
164
+ });
165
+ }
166
+ }
167
+ }
168
+
169
+ const list = (keys: string[]): string => keys.map((k) => `'${k}'`).join(", ");
170
+
171
+ /** The inputs a consumer can supply knowing only the slot — the UNION of every
172
+ * accepted kind's declared inputs.
173
+ *
174
+ * Union rather than the first match: a slot accepting several kinds may see any
175
+ * of them, and a name any accepted kind declares is one a consumer could
176
+ * plausibly supply. Taking the first kind's contract would make the check
177
+ * depend on the order `anyOf` branches happen to be written in. Undefined when
178
+ * no accepted kind declares a contract at all — the "nothing to violate" case. */
179
+ function slotDeclaredInputs(
180
+ refs: string[],
181
+ resolveDef: DefResolver,
182
+ manifests: ResourceManifest[],
183
+ ): string[] | undefined {
184
+ let seen: Set<string> | undefined;
185
+ for (const ref of refs) {
186
+ const def = resolveDef(ref);
187
+ if (!def) continue;
188
+ const schema = contractSchemaFor(undefined, def, resolveDef, manifests);
189
+ if (!schema) continue;
190
+ seen ??= new Set<string>();
191
+ for (const key of Object.keys((schema.properties ?? {}) as Record<string, unknown>)) {
192
+ seen.add(key);
193
+ }
194
+ }
195
+ return seen ? [...seen] : undefined;
196
+ }
197
+
198
+ /** True when every kind a slot accepts is started rather than invoked — the
199
+ * capabilities whose dispatch verb is `run()`, which passes no arguments.
200
+ * Keyed on the declared capability, so a user-defined abstract resolves the
201
+ * same way a built-in does. */
202
+ function isRunOnlySlot(refs: string[], resolveDef: DefResolver): boolean {
203
+ if (refs.length === 0) return false;
204
+ return refs.every((ref) => {
205
+ const def = resolveDef(ref);
206
+ const capability = def?.capability ?? ref;
207
+ return capability === "Telo.Runnable" || capability === "Telo.Service";
208
+ });
209
+ }
210
+
211
+ /** The resolved contract schema for a target: its own declaration first, then
212
+ * the nearest along `extends`. Inline schemas only — a named reference resolves
213
+ * through machinery this pass does not carry, and half-resolving would be worse
214
+ * than not reporting. */
215
+ function contractSchemaFor(
216
+ manifest: ResourceManifest | undefined,
217
+ definition: ResourceDefinition | undefined,
218
+ resolveDef: DefResolver,
219
+ manifests: ResourceManifest[],
220
+ direction: ContractDirection = "inputType",
221
+ ): Record<string, any> | undefined {
222
+ const declaringModule = ((manifest ?? definition)?.metadata as { module?: string } | undefined)
223
+ ?.module;
224
+ const own = manifest ? (manifest as unknown as Record<string, unknown>)[direction] : undefined;
225
+ const declared =
226
+ own !== undefined && own !== null
227
+ ? own
228
+ : effectiveContractField(definition, resolveDef, direction);
229
+ const inline = inlineSchemaOf(declared);
230
+ if (inline) return inline;
231
+ // A `!ref` / bare name: resolve it to the named type resource in scope.
232
+ const named =
233
+ typeof declared === "string"
234
+ ? declared
235
+ : declared && typeof declared === "object" && typeof (declared as any).name === "string"
236
+ ? (declared as any).name
237
+ : undefined;
238
+ if (!named) return undefined;
239
+ const typeManifest = findInModule(manifests, named, declaringModule);
240
+ return typeManifest ? inlineSchemaOf(typeManifest) : undefined;
241
+ }
242
+
243
+ /** The input names a contract makes mandatory. Undefined means "no contract
244
+ * declared" — distinct from an empty list, which means "declared, requires
245
+ * nothing". */
246
+ function requiredInputsOf(schema: Record<string, any> | undefined): string[] | undefined {
247
+ if (!schema) return undefined;
248
+ return Array.isArray(schema.required) ? (schema.required as string[]) : [];
249
+ }
250
+
251
+ /** Whether the object containing this ref slot also declares an inputs field —
252
+ * the `invoke`/`inputs` pairing, recognised through the topology role rather
253
+ * than a field name, so a composer spelling it differently still counts. */
254
+ function slotTakesPairedInputs(schema: Record<string, any>, path: string): boolean {
255
+ const parentPath = path.slice(0, Math.max(0, path.lastIndexOf(".")));
256
+ const parent = parentPath ? navigateSchema(schema, parentPath) : schema;
257
+ const properties = (parent?.properties ?? {}) as Record<string, Record<string, any>>;
258
+ return Object.values(properties).some((p) => p?.["x-telo-topology-role"] === "inputs");
259
+ }
260
+
261
+ /** Follow a field-map path (`a.b[].c`) through a schema's properties/items. */
262
+ function navigateSchema(
263
+ schema: Record<string, any>,
264
+ path: string,
265
+ ): Record<string, any> | undefined {
266
+ let node: Record<string, any> | undefined = schema;
267
+ for (const raw of path.split(".")) {
268
+ if (!node) return undefined;
269
+ const key = raw.replace(/\[\]|\{\}/g, "");
270
+ let next = (node.properties ?? {})[key] as Record<string, any> | undefined;
271
+ if (!next) return undefined;
272
+ if (raw.includes("[]")) next = (next.items ?? {}) as Record<string, any>;
273
+ node = next;
274
+ }
275
+ return node;
276
+ }
277
+
278
+ /** The `{kind, name}` references actually written at a field-map path. */
279
+ function refValuesAt(manifest: Record<string, any>, path: string): string[] {
280
+ const out: string[] = [];
281
+ const walk = (node: unknown, segments: string[]): void => {
282
+ if (node == null) return;
283
+ if (segments.length === 0) {
284
+ const items = Array.isArray(node) ? node : [node];
285
+ for (const item of items) {
286
+ // A reference is `{kind, name}` — BOTH fields. Requiring only `name`
287
+ // would read an inline invoke step (`{ name, invoke, inputs }`) as a
288
+ // reference to a resource called after the step, which it is not: that
289
+ // `name` labels the step, and the step is an invoke site anyway.
290
+ if (
291
+ item &&
292
+ typeof item === "object" &&
293
+ typeof (item as any).name === "string" &&
294
+ typeof (item as any).kind === "string"
295
+ ) {
296
+ out.push((item as any).name);
297
+ }
298
+ }
299
+ return;
300
+ }
301
+ const [head, ...rest] = segments;
302
+ const key = head!.replace(/\[\]|\{\}/g, "");
303
+ const value = (node as Record<string, any>)[key];
304
+ if (head!.includes("[]") && Array.isArray(value)) {
305
+ for (const item of value) walk(item, rest);
306
+ } else if (head!.includes("{}") && value && typeof value === "object") {
307
+ for (const item of Object.values(value)) walk(item, rest);
308
+ } else {
309
+ walk(value, rest);
310
+ }
311
+ };
312
+ walk(manifest, path.split("."));
313
+ return out;
314
+ }
315
+
316
+ /**
317
+ * A named contract must name a type that exists.
318
+ *
319
+ * The runtime raises `ERR_CONTRACT_UNRESOLVABLE` on the first dispatch through
320
+ * an unresolvable contract, which is exactly the failure a checker should have
321
+ * caught: nothing about it depends on runtime values. Instance-level slots were
322
+ * already covered, because a module kind declares its `inputType` property with
323
+ * `x-telo-ref: Telo.Type`; the KIND-level fields are on `Telo.Definition`, which
324
+ * is deliberately excluded from reference validation, so they had no check at
325
+ * all and the same typo behaved differently depending on where it was written.
326
+ */
327
+ function checkContractResolves(
328
+ m: ResourceManifest,
329
+ md: Record<string, unknown>,
330
+ manifests: ResourceManifest[],
331
+ resource: { kind: string; name: string },
332
+ filePath: string | undefined,
333
+ diagnostics: AnalysisDiagnostic[],
334
+ ): void {
335
+ const declaringModule = (m.metadata as { module?: string } | undefined)?.module;
336
+ for (const direction of ["inputType", "outputType"] as ContractDirection[]) {
337
+ const named = namedTypeReference(md[direction]);
338
+ if (!named) continue;
339
+ if (findInModule(manifests, named, declaringModule)) continue;
340
+ diagnostics.push({
341
+ severity: DiagnosticSeverity.Error,
342
+ code: "CONTRACT_TYPE_NOT_FOUND",
343
+ source: SOURCE,
344
+ message:
345
+ `${m.kind}/${resource.name}: \`${direction}\` names the type '${named}', which is not declared ` +
346
+ `in scope. The contract cannot be enforced, so every call through it would fail at dispatch. ` +
347
+ `Declare a \`Telo.JsonSchema\` with that name, or inline the shape.`,
348
+ data: { resource, filePath, path: direction },
349
+ });
350
+ }
351
+ }
352
+
353
+ /** The name a contract field references, when it is a reference at all. An
354
+ * inline shape or a raw schema names nothing and resolves on its own. */
355
+ function namedTypeReference(value: unknown): string | undefined {
356
+ if (typeof value === "string") return value;
357
+ if (!value || typeof value !== "object") return undefined;
358
+ const ref = value as Record<string, unknown>;
359
+ if (ref.schema && typeof ref.schema === "object") return undefined;
360
+ return typeof ref.name === "string" ? ref.name : undefined;
361
+ }
362
+
363
+ /** A child that inherits its controller and REPLACES a contract must bridge it:
364
+ * contracts resolve to the nearest declaration and never merge, so the
365
+ * inherited controller only understands its own shape. Without the mapping the
366
+ * declaration is inert — precisely the silent no-op this rule exists to end. */
367
+ function checkMappingRequired(
368
+ m: ResourceManifest,
369
+ resource: { kind: string; name: string },
370
+ filePath: string | undefined,
371
+ resolveDef: DefResolver,
372
+ diagnostics: AnalysisDiagnostic[],
373
+ ): void {
374
+ const def = m as unknown as ResourceDefinition;
375
+ const body = m as unknown as Record<string, unknown>;
376
+ for (const direction of ["inputType", "outputType"] as ContractDirection[]) {
377
+ if (!needsContractMapping(def, resolveDef, direction)) continue;
378
+ const mappingField = mappingFieldFor(direction);
379
+ if (body[mappingField] != null) continue;
380
+ diagnostics.push({
381
+ severity: DiagnosticSeverity.Error,
382
+ code: "CONTRACT_MISSING_MAPPING",
383
+ source: SOURCE,
384
+ message:
385
+ `${m.kind}/${resource.name}: declares its own \`${direction}\` but inherits its controller, ` +
386
+ `and no \`${mappingField}:\` mapping bridges the two. The inherited controller only understands ` +
387
+ `the kind it came from, so without a mapping the declaration would never be applied. Add a ` +
388
+ `\`${mappingField}:\` mapping, or drop \`${direction}\` to inherit the contract unchanged.`,
389
+ data: { resource, filePath, path: direction },
390
+ });
391
+ }
392
+ }
393
+
394
+ /** `inputs:` on a resource once meant "a JSON Schema property map" on the run
395
+ * kinds. It is values everywhere else, and now means values everywhere — so a
396
+ * leftover map against a kind that declares no `inputs` property is a migration
397
+ * the author has not finished, not an unknown field. */
398
+ function checkLeftoverInputsSchema(
399
+ m: ResourceManifest,
400
+ definition: ResourceDefinition,
401
+ md: Record<string, unknown>,
402
+ resource: { kind: string; name: string },
403
+ filePath: string | undefined,
404
+ diagnostics: AnalysisDiagnostic[],
405
+ ): void {
406
+ const value = md.inputs;
407
+ if (!value || typeof value !== "object" || Array.isArray(value)) return;
408
+ const properties = (definition.schema?.properties ?? {}) as Record<string, unknown>;
409
+ if ("inputs" in properties) return;
410
+ if (!("inputType" in properties)) return;
411
+ diagnostics.push({
412
+ severity: DiagnosticSeverity.Error,
413
+ code: "CONTRACT_INPUTS_SCHEMA_FORM",
414
+ source: SOURCE,
415
+ message:
416
+ `${m.kind}/${resource.name}: \`inputs:\` no longer declares an input contract — it always means ` +
417
+ `values now. Move the property map to \`inputType:\` (a \`Telo.JsonSchema\` shape, a named type ` +
418
+ `reference, or an inline schema).`,
419
+ data: { resource, filePath, path: "inputs" },
420
+ });
421
+ }
422
+
423
+ /** The schema behind an INLINE type declaration, which is all this pass can read
424
+ * without a manifest lookup. A named reference resolves elsewhere; skipping it
425
+ * here keeps the check total rather than half-informed. */
426
+ function inlineSchemaOf(value: unknown): Record<string, any> | undefined {
427
+ if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
428
+ const obj = value as Record<string, any>;
429
+ if (obj.schema && typeof obj.schema === "object") return obj.schema;
430
+ if (obj.properties && typeof obj.properties === "object") return obj;
431
+ return undefined;
432
+ }
433
+
434
+ /** Find a manifest by name within a module, falling back to a unique global
435
+ * match. Names are unique per module, not per flattened graph, so an unscoped
436
+ * `find` can silently return another module's resource; an ambiguous global
437
+ * match resolves to nothing rather than to a guess. */
438
+ function findInModule(
439
+ manifests: ResourceManifest[],
440
+ name: string,
441
+ module: string | undefined,
442
+ ): ResourceManifest | undefined {
443
+ const byName = manifests.filter((t) => (t.metadata as any)?.name === name);
444
+ if (byName.length === 0) return undefined;
445
+ const scoped = byName.filter(
446
+ (t) => (t.metadata as { module?: string } | undefined)?.module === module,
447
+ );
448
+ if (scoped.length === 1) return scoped[0];
449
+ return byName.length === 1 ? byName[0] : undefined;
450
+ }
@@ -0,0 +1,117 @@
1
+ import type { AliasResolver, ModuleScopes } from "./alias-resolver.js";
2
+ import type { DefinitionRegistry } from "./definition-registry.js";
3
+ import type { ContractDirection } from "./extends-resolution.js";
4
+ import { resolveContract } from "./invocation-contract.js";
5
+ import { substituteCelFields, validateAgainstSchema } from "./schema-compat.js";
6
+ import {
7
+ analyzerContractScope,
8
+ containerOf,
9
+ gatherPropertySchemas,
10
+ missingRequired,
11
+ resolveLocalRef,
12
+ walkStepArray,
13
+ } from "./analyzer.js";
14
+
15
+ export interface StepInputIssue {
16
+ path: string;
17
+ targetLabel: string;
18
+ message: string;
19
+ }
20
+
21
+ /**
22
+ * Validate every step's `inputs:` against the invoked target's declared input
23
+ * contract — the static half of what the kernel enforces at dispatch.
24
+ *
25
+ * Worth doing statically because a call site is where the mistake is made and
26
+ * where the author can see both sides: a misspelled key or a wrong-shaped value
27
+ * would otherwise surface at runtime inside the callee, several steps from its
28
+ * cause, naming a resource the author may not have written.
29
+ *
30
+ * CEL leaves are replaced by schema-shaped placeholders first (`substituteCelFields`),
31
+ * so an expression is never a false positive — only structural disagreement is
32
+ * reported. Nothing is hardcoded about `Run.Sequence`: the invoke field comes
33
+ * from `x-telo-step-context`, and the paired inputs field from whichever sibling
34
+ * property carries `x-telo-topology-role: inputs`.
35
+ */
36
+ export function collectStepInputIssues(
37
+ manifest: Record<string, any>,
38
+ defSchema: Record<string, any>,
39
+ allManifests: Record<string, any>[],
40
+ defs: DefinitionRegistry,
41
+ aliases: AliasResolver,
42
+ scopes: ModuleScopes,
43
+ ): StepInputIssue[] {
44
+ const out: StepInputIssue[] = [];
45
+ const props = defSchema.properties as Record<string, any> | undefined;
46
+ if (!props) return out;
47
+
48
+ const contractScope = analyzerContractScope(defs, aliases, scopes, allManifests);
49
+ const readingModule = (manifest.metadata as { module?: string } | undefined)?.module;
50
+
51
+ for (const [fieldName, fieldSchema] of Object.entries(props)) {
52
+ const stepCtx = fieldSchema["x-telo-step-context"] as Record<string, string> | undefined;
53
+ if (!stepCtx?.invoke) continue;
54
+ const steps = manifest[fieldName];
55
+ if (!Array.isArray(steps)) continue;
56
+
57
+ const stepItemSchema = resolveLocalRef(
58
+ fieldSchema.items as Record<string, any> | undefined,
59
+ defSchema,
60
+ );
61
+ if (!stepItemSchema) continue;
62
+
63
+ // The inputs field is whichever sibling declares the role — never the literal
64
+ // name, so a composer that spells it differently still gets checked.
65
+ let inputsField: string | undefined;
66
+ for (const [key, sub] of gatherPropertySchemas(stepItemSchema)) {
67
+ if (sub?.["x-telo-topology-role"] === "inputs") inputsField = key;
68
+ }
69
+ if (!inputsField) continue;
70
+
71
+ walkStepArray(steps, stepItemSchema, defSchema, fieldName, (step, stepPath) => {
72
+ const invoke = step[stepCtx.invoke] as Record<string, any> | undefined;
73
+ const values = step[inputsField!];
74
+ if (!invoke || typeof invoke !== "object") return;
75
+ if (!values || typeof values !== "object" || Array.isArray(values)) return;
76
+
77
+ const invokedKind = invoke.kind as string | undefined;
78
+ const invokedName = invoke.name as string | undefined;
79
+ const invokedManifest = invokedName
80
+ ? (allManifests.find(
81
+ (m) =>
82
+ (m.metadata as any)?.name === invokedName && (!invokedKind || m.kind === invokedKind),
83
+ ) as Record<string, any> | undefined)
84
+ : (invoke as Record<string, any>);
85
+ const invokedDef = invokedKind
86
+ ? contractScope.resolveIn(invokedKind, readingModule)
87
+ : undefined;
88
+ const contract = resolveContract("inputType", invokedManifest, invokedDef, contractScope);
89
+ if (!contract) return;
90
+
91
+ // Findings AT a substituted path are about a placeholder, not about
92
+ // anything the author wrote — a `pattern`-constrained string or a `oneOf`
93
+ // of unrelated shapes cannot be satisfied by any stand-in. Structural
94
+ // findings (missing required, unknown property) are located at the
95
+ // container and survive the filter.
96
+ const celPaths = new Set<string>();
97
+ const substituted = substituteCelFields(values, contract.schema, undefined, (p) =>
98
+ celPaths.add(p),
99
+ );
100
+ for (const issue of validateAgainstSchema(substituted, contract.schema)) {
101
+ if (celPaths.has(issue.path)) continue;
102
+ // A missing-required issue names the property that ISN'T there, so
103
+ // anchoring on it finds no node and the diagnostic degrades to 1:1 —
104
+ // losing the location of the most common contract mistake. Anchor on the
105
+ // container that should have held it, which does exist.
106
+ const anchor = missingRequired(issue) ? containerOf(issue.path) : issue.path;
107
+ out.push({
108
+ path: anchor ? `${stepPath}.${inputsField}.${anchor}` : `${stepPath}.${inputsField}`,
109
+ targetLabel: invokedName ?? invokedKind ?? "the invoked resource",
110
+ message: issue.message,
111
+ });
112
+ }
113
+ });
114
+ }
115
+ return out;
116
+ }
117
+
@@ -1,6 +1,10 @@
1
1
  import type { ASTNode, Environment } from "@marcbachmann/cel-js";
2
2
  import { isTaggedSentinel } from "@telorun/templating";
3
- import type { ResourceManifest } from "@telorun/sdk";
3
+ import {
4
+ AMBIENT_CONTRACT_ERROR_CODES,
5
+ isAmbientContractErrorCode,
6
+ type ResourceManifest,
7
+ } from "@telorun/sdk";
4
8
  import { scopeResolverForModule, type AliasResolver } from "./alias-resolver.js";
5
9
  import type { DefinitionRegistry } from "./definition-registry.js";
6
10
  import {
@@ -250,12 +254,18 @@ function checkCatchesCoverage(
250
254
  const { proven, codes } = extractCoveredCodes(e.when, env);
251
255
  if (proven) {
252
256
  for (const c of codes) {
257
+ // An ambient kernel code (contract violations) is raised by the kernel,
258
+ // not declared by the kind, so naming it is legal and still typo-checked
259
+ // — but it is NOT part of the declared union, so it never counts toward
260
+ // coverage. Folding these into every union would make every bounded
261
+ // catches: block in the standard library incomplete overnight.
262
+ if (isAmbientContractErrorCode(c)) continue;
253
263
  if (!declaredCodes.has(c)) {
254
264
  diagnostics.push({
255
265
  severity: DiagnosticSeverity.Error,
256
266
  code: "UNDECLARED_THROW_CODE",
257
267
  source: SOURCE,
258
- message: `catches[${i}] references code '${c}' which is not in the handler's declared throw union {${[...declaredCodes].sort().join(", ") || "∅"}}${union.unbounded ? " (union is unbounded a catch-all is required)" : ""}.`,
268
+ message: `catches[${i}] references code '${c}' which is not in the handler's declared throw union {${[...declaredCodes].sort().join(", ") || "∅"}} (ambient kernel codes ${AMBIENT_CONTRACT_ERROR_CODES.join(", ")} may also be named)${union.unbounded ? "; the union is unbounded, so a catch-all is required" : ""}.`,
259
269
  data: { resource, filePath, path: `${arrayPath}[${i}].when` },
260
270
  });
261
271
  } else {