autotel-schema 5.0.0 → 7.0.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 (41) hide show
  1. package/dist/cli.cjs +1 -2
  2. package/dist/cli.d.cts +1 -2
  3. package/dist/cli.d.ts +1 -2
  4. package/dist/cli.js +1 -2
  5. package/dist/contract-Ymh_Q37N.d.cts +1 -2
  6. package/dist/contract-Ymh_Q37N.d.ts +1 -2
  7. package/dist/diff-CAIC04O4.d.ts +1 -2
  8. package/dist/diff-CfvhW7ux.d.cts +1 -2
  9. package/dist/diff.cjs +1 -2
  10. package/dist/diff.js +1 -2
  11. package/dist/index.cjs +98 -2
  12. package/dist/index.d.cts +32 -2
  13. package/dist/index.d.ts +32 -2
  14. package/dist/index.js +95 -2
  15. package/dist/processor-BPp_DewZ.js +1 -2
  16. package/dist/processor-DVcsS6Rz.d.cts +1 -2
  17. package/dist/processor-Gu8Yl_dS.cjs +1 -2
  18. package/dist/processor-TpuacLr5.d.ts +1 -2
  19. package/dist/snapshot-CyWGJaJT.cjs +1 -2
  20. package/dist/snapshot-h8pb_Up_.js +1 -2
  21. package/package.json +4 -4
  22. package/dist/cli.cjs.map +0 -1
  23. package/dist/cli.d.cts.map +0 -1
  24. package/dist/cli.d.ts.map +0 -1
  25. package/dist/cli.js.map +0 -1
  26. package/dist/contract-Ymh_Q37N.d.cts.map +0 -1
  27. package/dist/contract-Ymh_Q37N.d.ts.map +0 -1
  28. package/dist/diff-CAIC04O4.d.ts.map +0 -1
  29. package/dist/diff-CfvhW7ux.d.cts.map +0 -1
  30. package/dist/diff.cjs.map +0 -1
  31. package/dist/diff.js.map +0 -1
  32. package/dist/index.cjs.map +0 -1
  33. package/dist/index.d.cts.map +0 -1
  34. package/dist/index.d.ts.map +0 -1
  35. package/dist/index.js.map +0 -1
  36. package/dist/processor-BPp_DewZ.js.map +0 -1
  37. package/dist/processor-DVcsS6Rz.d.cts.map +0 -1
  38. package/dist/processor-Gu8Yl_dS.cjs.map +0 -1
  39. package/dist/processor-TpuacLr5.d.ts.map +0 -1
  40. package/dist/snapshot-CyWGJaJT.cjs.map +0 -1
  41. package/dist/snapshot-h8pb_Up_.js.map +0 -1
package/dist/cli.cjs CHANGED
@@ -107,5 +107,4 @@ const entry = process.argv[1] ? node_path.default.basename(process.argv[1]) : ""
107
107
  if (entry === "autotel-schema" || entry === "cli.js" || entry === "cli.cjs") process.exit(run(process.argv.slice(2)));
108
108
 
109
109
  //#endregion
110
- exports.run = run;
111
- //# sourceMappingURL=cli.cjs.map
110
+ exports.run = run;
package/dist/cli.d.cts CHANGED
@@ -10,5 +10,4 @@
10
10
  */
11
11
  declare function run(argv: string[]): number;
12
12
  //#endregion
13
- export { run };
14
- //# sourceMappingURL=cli.d.cts.map
13
+ export { run };
package/dist/cli.d.ts CHANGED
@@ -10,5 +10,4 @@
10
10
  */
11
11
  declare function run(argv: string[]): number;
12
12
  //#endregion
13
- export { run };
14
- //# sourceMappingURL=cli.d.ts.map
13
+ export { run };
package/dist/cli.js CHANGED
@@ -78,5 +78,4 @@ const entry = process.argv[1] ? path.basename(process.argv[1]) : "";
78
78
  if (entry === "autotel-schema" || entry === "cli.js" || entry === "cli.cjs") process.exit(run(process.argv.slice(2)));
79
79
 
80
80
  //#endregion
81
- export { run };
82
- //# sourceMappingURL=cli.js.map
81
+ export { run };
@@ -301,5 +301,4 @@ declare function resolveAttributeSpec(contract: TelemetryContract, spanName: str
301
301
  /** Whether attributes outside the declared set are tolerated for a span. */
302
302
  declare function allowsAdditionalAttributes(contract: TelemetryContract, spanName: string): boolean;
303
303
  //#endregion
304
- export { validateScenarioSpec as A, ScenarioViolationCode as C, isScenarioClosed as D, formatScenarioResult as E, parseCardinality as O, ScenarioViolation as S, evaluateScenario as T, ScenarioOutcome as _, SpanSpec as a, ScenarioSpan as b, allowsAdditionalAttributes as c, Cardinality as d, CheckScenarioOptions as f, ScenarioEventSpec as g, ScenarioAddition as h, STABILITIES as i, proposeScenario as k, defineContract as l, EvaluateScenarioOptions as m, AttributeSpec as n, Stability as o, CompletionBoundary as p, AttributeType as r, TelemetryContract as s, ATTRIBUTE_TYPES as t, resolveAttributeSpec as u, ScenarioProposal as v, checkScenario as w, ScenarioSpec as x, ScenarioResult as y };
305
- //# sourceMappingURL=contract-Ymh_Q37N.d.cts.map
304
+ export { validateScenarioSpec as A, ScenarioViolationCode as C, isScenarioClosed as D, formatScenarioResult as E, parseCardinality as O, ScenarioViolation as S, evaluateScenario as T, ScenarioOutcome as _, SpanSpec as a, ScenarioSpan as b, allowsAdditionalAttributes as c, Cardinality as d, CheckScenarioOptions as f, ScenarioEventSpec as g, ScenarioAddition as h, STABILITIES as i, proposeScenario as k, defineContract as l, EvaluateScenarioOptions as m, AttributeSpec as n, Stability as o, CompletionBoundary as p, AttributeType as r, TelemetryContract as s, ATTRIBUTE_TYPES as t, resolveAttributeSpec as u, ScenarioProposal as v, checkScenario as w, ScenarioSpec as x, ScenarioResult as y };
@@ -301,5 +301,4 @@ declare function resolveAttributeSpec(contract: TelemetryContract, spanName: str
301
301
  /** Whether attributes outside the declared set are tolerated for a span. */
302
302
  declare function allowsAdditionalAttributes(contract: TelemetryContract, spanName: string): boolean;
303
303
  //#endregion
304
- export { validateScenarioSpec as A, ScenarioViolationCode as C, isScenarioClosed as D, formatScenarioResult as E, parseCardinality as O, ScenarioViolation as S, evaluateScenario as T, ScenarioOutcome as _, SpanSpec as a, ScenarioSpan as b, allowsAdditionalAttributes as c, Cardinality as d, CheckScenarioOptions as f, ScenarioEventSpec as g, ScenarioAddition as h, STABILITIES as i, proposeScenario as k, defineContract as l, EvaluateScenarioOptions as m, AttributeSpec as n, Stability as o, CompletionBoundary as p, AttributeType as r, TelemetryContract as s, ATTRIBUTE_TYPES as t, resolveAttributeSpec as u, ScenarioProposal as v, checkScenario as w, ScenarioSpec as x, ScenarioResult as y };
305
- //# sourceMappingURL=contract-Ymh_Q37N.d.ts.map
304
+ export { validateScenarioSpec as A, ScenarioViolationCode as C, isScenarioClosed as D, formatScenarioResult as E, parseCardinality as O, ScenarioViolation as S, evaluateScenario as T, ScenarioOutcome as _, SpanSpec as a, ScenarioSpan as b, allowsAdditionalAttributes as c, Cardinality as d, CheckScenarioOptions as f, ScenarioEventSpec as g, ScenarioAddition as h, STABILITIES as i, proposeScenario as k, defineContract as l, EvaluateScenarioOptions as m, AttributeSpec as n, Stability as o, CompletionBoundary as p, AttributeType as r, TelemetryContract as s, ATTRIBUTE_TYPES as t, resolveAttributeSpec as u, ScenarioProposal as v, checkScenario as w, ScenarioSpec as x, ScenarioResult as y };
@@ -86,5 +86,4 @@ declare function hasBreakingChanges(diff: SnapshotDiff): boolean;
86
86
  /** Markdown rendering of a diff — for CI logs and PR comments. */
87
87
  declare function formatDiff(diff: SnapshotDiff): string;
88
88
  //#endregion
89
- export { diffSnapshots as a, ContractSnapshot as c, contractToSnapshot as d, parseSnapshot as f, SchemaAttributeKey as g, SNAPSHOT_SPEC as h, SnapshotDiff as i, SnapshotAttribute as l, SCHEMA_ATTRS as m, ChangeType as n, formatDiff as o, serializeSnapshot as p, SnapshotChange as r, hasBreakingChanges as s, ChangeKind as t, SnapshotSpan as u };
90
- //# sourceMappingURL=diff-CAIC04O4.d.ts.map
89
+ export { diffSnapshots as a, ContractSnapshot as c, contractToSnapshot as d, parseSnapshot as f, SchemaAttributeKey as g, SNAPSHOT_SPEC as h, SnapshotDiff as i, SnapshotAttribute as l, SCHEMA_ATTRS as m, ChangeType as n, formatDiff as o, serializeSnapshot as p, SnapshotChange as r, hasBreakingChanges as s, ChangeKind as t, SnapshotSpan as u };
@@ -86,5 +86,4 @@ declare function hasBreakingChanges(diff: SnapshotDiff): boolean;
86
86
  /** Markdown rendering of a diff — for CI logs and PR comments. */
87
87
  declare function formatDiff(diff: SnapshotDiff): string;
88
88
  //#endregion
89
- export { diffSnapshots as a, ContractSnapshot as c, contractToSnapshot as d, parseSnapshot as f, SchemaAttributeKey as g, SNAPSHOT_SPEC as h, SnapshotDiff as i, SnapshotAttribute as l, SCHEMA_ATTRS as m, ChangeType as n, formatDiff as o, serializeSnapshot as p, SnapshotChange as r, hasBreakingChanges as s, ChangeKind as t, SnapshotSpan as u };
90
- //# sourceMappingURL=diff-CfvhW7ux.d.cts.map
89
+ export { diffSnapshots as a, ContractSnapshot as c, contractToSnapshot as d, parseSnapshot as f, SchemaAttributeKey as g, SNAPSHOT_SPEC as h, SnapshotDiff as i, SnapshotAttribute as l, SCHEMA_ATTRS as m, ChangeType as n, formatDiff as o, serializeSnapshot as p, SnapshotChange as r, hasBreakingChanges as s, ChangeKind as t, SnapshotSpan as u };
package/dist/diff.cjs CHANGED
@@ -181,5 +181,4 @@ function formatDiff(diff) {
181
181
  //#endregion
182
182
  exports.diffSnapshots = diffSnapshots;
183
183
  exports.formatDiff = formatDiff;
184
- exports.hasBreakingChanges = hasBreakingChanges;
185
- //# sourceMappingURL=diff.cjs.map
184
+ exports.hasBreakingChanges = hasBreakingChanges;
package/dist/diff.js CHANGED
@@ -177,5 +177,4 @@ function formatDiff(diff) {
177
177
  }
178
178
 
179
179
  //#endregion
180
- export { diffSnapshots, formatDiff, hasBreakingChanges };
181
- //# sourceMappingURL=diff.js.map
180
+ export { diffSnapshots, formatDiff, hasBreakingChanges };
package/dist/index.cjs CHANGED
@@ -3,6 +3,100 @@ const require_snapshot = require('./snapshot-CyWGJaJT.cjs');
3
3
  const require_processor = require('./processor-Gu8Yl_dS.cjs');
4
4
  const require_diff = require('./diff.cjs');
5
5
 
6
+ //#region src/completeness.ts
7
+ /** The ten fields a GenAI trace is scored on. */
8
+ const GENAI_COMPLETENESS_FIELDS = [
9
+ "llm_input",
10
+ "llm_output",
11
+ "model_name",
12
+ "token_usage",
13
+ "cost_usd",
14
+ "latency_per_span",
15
+ "tool_call_args",
16
+ "tool_call_results",
17
+ "span_tree",
18
+ "span_count"
19
+ ];
20
+ /** A value counts as present only if it is non-null and not an empty string/array. */
21
+ function isNonEmpty(value) {
22
+ if (value === null || value === void 0) return false;
23
+ if (typeof value === "string") return value.trim() !== "";
24
+ if (Array.isArray(value)) return value.length > 0;
25
+ return true;
26
+ }
27
+ function anySpanHas(spans, key) {
28
+ return spans.some((s) => isNonEmpty(s.attributes?.[key]));
29
+ }
30
+ function countSpansWith(spans, key) {
31
+ return spans.filter((s) => isNonEmpty(s.attributes?.[key])).length;
32
+ }
33
+ function score(field, points, detail) {
34
+ return {
35
+ field,
36
+ points,
37
+ detail
38
+ };
39
+ }
40
+ /**
41
+ * Score a single trace's spans against the ten-field checklist.
42
+ *
43
+ * Pass every span of one trace — the tree and count checks are meaningless on a
44
+ * partial slice.
45
+ */
46
+ function scoreGenAiCompleteness(spans) {
47
+ const fields = [];
48
+ fields.push(anySpanHas(spans, "gen_ai.input.messages") ? score("llm_input", 1, "gen_ai.input.messages present") : score("llm_input", 0, "no span carries gen_ai.input.messages"));
49
+ fields.push(anySpanHas(spans, "gen_ai.output.messages") ? score("llm_output", 1, "gen_ai.output.messages present") : score("llm_output", 0, "no span carries gen_ai.output.messages"));
50
+ const hasResponseModel = anySpanHas(spans, "gen_ai.response.model");
51
+ const hasRequestModel = anySpanHas(spans, "gen_ai.request.model");
52
+ fields.push(hasResponseModel || hasRequestModel ? score("model_name", 1, hasResponseModel ? "gen_ai.response.model present" : "gen_ai.request.model present (no response model)") : score("model_name", 0, "neither request nor response model recorded"));
53
+ const hasInputTokens = anySpanHas(spans, "gen_ai.usage.input_tokens");
54
+ const hasOutputTokens = anySpanHas(spans, "gen_ai.usage.output_tokens");
55
+ if (hasInputTokens && hasOutputTokens) fields.push(score("token_usage", 1, "input and output tokens recorded"));
56
+ else if (hasInputTokens || hasOutputTokens) fields.push(score("token_usage", .5, `only ${hasInputTokens ? "input" : "output"} tokens recorded`));
57
+ else fields.push(score("token_usage", 0, "no token usage recorded"));
58
+ fields.push(anySpanHas(spans, "gen_ai.usage.cost.usd") ? score("cost_usd", 1, "gen_ai.usage.cost.usd present") : score("cost_usd", 0, "no span carries gen_ai.usage.cost.usd"));
59
+ const timed = spans.filter((s) => typeof s.durationMs === "number" && s.durationMs >= 0).length;
60
+ if (spans.length > 0 && timed === spans.length) fields.push(score("latency_per_span", 1, `all ${timed} spans timed`));
61
+ else if (timed > 0) fields.push(score("latency_per_span", .5, `${timed} of ${spans.length} spans carry a duration`));
62
+ else fields.push(score("latency_per_span", 0, "no span carries a duration"));
63
+ const toolCallSpans = spans.filter((span) => isNonEmpty(span.attributes?.["gen_ai.tool.name"]) || isNonEmpty(span.attributes?.["gen_ai.tool.call.id"]) || isNonEmpty(span.attributes?.["gen_ai.tool.call.arguments"]) || isNonEmpty(span.attributes?.["gen_ai.tool.call.result"]));
64
+ const toolSpans = toolCallSpans.length;
65
+ const argCount = countSpansWith(toolCallSpans, "gen_ai.tool.call.arguments");
66
+ const resultCount = countSpansWith(toolCallSpans, "gen_ai.tool.call.result");
67
+ if (toolSpans === 0) fields.push(score("tool_call_args", 0, "no tool calls in this trace"));
68
+ else if (argCount === toolSpans) fields.push(score("tool_call_args", 1, `all ${toolSpans} tool call(s) carry arguments`));
69
+ else if (argCount > 0) fields.push(score("tool_call_args", .5, `${argCount} of ${toolSpans} tool call(s) carry arguments`));
70
+ else fields.push(score("tool_call_args", 0, `${toolSpans} tool span(s) but none carry gen_ai.tool.call.arguments`));
71
+ if (toolSpans > 0 && resultCount === toolSpans) fields.push(score("tool_call_results", 1, `all ${toolSpans} tool call(s) carry results`));
72
+ else if (resultCount > 0) fields.push(score("tool_call_results", .5, `${resultCount} of ${toolSpans} tool call(s) carry a result`));
73
+ else if (toolSpans > 0) fields.push(score("tool_call_results", .5, `${toolSpans} tool call(s) recorded but no result landed`));
74
+ else fields.push(score("tool_call_results", 0, "no tool calls in this trace"));
75
+ const ids = new Set(spans.map((s) => s.spanId));
76
+ const linked = spans.filter((s) => s.parentSpanId !== void 0 && ids.has(s.parentSpanId)).length;
77
+ const dangling = spans.filter((s) => s.parentSpanId !== void 0 && !ids.has(s.parentSpanId)).length;
78
+ if (linked > 0) fields.push(score("span_tree", 1, `${linked} parent/child link(s) resolve`));
79
+ else if (dangling > 0) fields.push(score("span_tree", .5, `${dangling} parent id(s) resolve to no span`));
80
+ else fields.push(score("span_tree", 0, "trace is flat — no parent/child links"));
81
+ if (spans.length >= 2) fields.push(score("span_count", 1, `${spans.length} spans`));
82
+ else if (spans.length === 1) fields.push(score("span_count", .5, "single-span trace"));
83
+ else fields.push(score("span_count", 0, "no spans"));
84
+ return {
85
+ score: fields.reduce((sum, f) => sum + f.points, 0),
86
+ max: GENAI_COMPLETENESS_FIELDS.length,
87
+ fields,
88
+ missing: fields.filter((f) => f.points === 0).map((f) => f.field),
89
+ partial: fields.filter((f) => f.points === .5).map((f) => f.field)
90
+ };
91
+ }
92
+ /** One line per field, for a CLI or a failed assertion. */
93
+ function formatCompleteness(result) {
94
+ return [`GenAI trace completeness: ${result.score}/${result.max}`, ...result.fields.map((f) => {
95
+ return ` ${f.points === 1 ? "✓" : f.points === .5 ? "~" : "✗"} ${f.field} — ${f.detail}`;
96
+ })].join("\n");
97
+ }
98
+
99
+ //#endregion
6
100
  //#region src/redaction.ts
7
101
  /**
8
102
  * Every attribute key in the contract flagged `highCardinality: true`, across
@@ -180,6 +274,7 @@ const AGENT_SECURITY_TELEMETRY_CONTRACT = require_processor.defineContract({
180
274
  //#endregion
181
275
  exports.AGENT_SECURITY_TELEMETRY_CONTRACT = AGENT_SECURITY_TELEMETRY_CONTRACT;
182
276
  exports.ATTRIBUTE_TYPES = require_processor.ATTRIBUTE_TYPES;
277
+ exports.GENAI_COMPLETENESS_FIELDS = GENAI_COMPLETENESS_FIELDS;
183
278
  exports.SCHEMA_ATTRS = require_snapshot.SCHEMA_ATTRS;
184
279
  exports.SNAPSHOT_SPEC = require_snapshot.SNAPSHOT_SPEC;
185
280
  exports.STABILITIES = require_processor.STABILITIES;
@@ -191,6 +286,7 @@ exports.createSchemaValidationProcessor = require_processor.createSchemaValidati
191
286
  exports.defineContract = require_processor.defineContract;
192
287
  exports.diffSnapshots = require_diff.diffSnapshots;
193
288
  exports.evaluateScenario = require_processor.evaluateScenario;
289
+ exports.formatCompleteness = formatCompleteness;
194
290
  exports.formatDiff = require_diff.formatDiff;
195
291
  exports.formatScenarioResult = require_processor.formatScenarioResult;
196
292
  exports.formatViolation = require_processor.formatViolation;
@@ -203,7 +299,7 @@ exports.parseCardinality = require_processor.parseCardinality;
203
299
  exports.parseSnapshot = require_snapshot.parseSnapshot;
204
300
  exports.proposeScenario = require_processor.proposeScenario;
205
301
  exports.resolveAttributeSpec = require_processor.resolveAttributeSpec;
302
+ exports.scoreGenAiCompleteness = scoreGenAiCompleteness;
206
303
  exports.serializeSnapshot = require_snapshot.serializeSnapshot;
207
304
  exports.validateScenarioSpec = require_processor.validateScenarioSpec;
208
- exports.validateSpan = require_processor.validateSpan;
209
- //# sourceMappingURL=index.cjs.map
305
+ exports.validateSpan = require_processor.validateSpan;
package/dist/index.d.cts CHANGED
@@ -1,6 +1,37 @@
1
1
  import { a as diffSnapshots, c as ContractSnapshot, d as contractToSnapshot, f as parseSnapshot, g as SchemaAttributeKey, h as SNAPSHOT_SPEC, i as SnapshotDiff, l as SnapshotAttribute, m as SCHEMA_ATTRS, n as ChangeType, o as formatDiff, p as serializeSnapshot, r as SnapshotChange, s as hasBreakingChanges, t as ChangeKind, u as SnapshotSpan } from "./diff-CfvhW7ux.cjs";
2
2
  import { A as validateScenarioSpec, C as ScenarioViolationCode, D as isScenarioClosed, E as formatScenarioResult, O as parseCardinality, S as ScenarioViolation, T as evaluateScenario, _ as ScenarioOutcome, a as SpanSpec, b as ScenarioSpan, c as allowsAdditionalAttributes, d as Cardinality, f as CheckScenarioOptions, g as ScenarioEventSpec, h as ScenarioAddition, i as STABILITIES, k as proposeScenario, l as defineContract, m as EvaluateScenarioOptions, n as AttributeSpec, o as Stability, p as CompletionBoundary, r as AttributeType, s as TelemetryContract, t as ATTRIBUTE_TYPES, u as resolveAttributeSpec, v as ScenarioProposal, w as checkScenario, x as ScenarioSpec, y as ScenarioResult } from "./contract-Ymh_Q37N.cjs";
3
3
  import { a as SchemaValidationSpanProcessor, c as createSchemaValidationProcessor, d as ValidateOptions, f as ViolationCode, g as validateSpan, h as hasErrors, i as SchemaValidationProcessorOptions, l as SchemaViolation, m as formatViolation, n as ReadableSpanLike, o as SpanLike, p as ViolationSeverity, r as SchemaProcessorMode, s as SpanProcessorLike, t as OtelContext, u as SpanShape } from "./processor-DVcsS6Rz.cjs";
4
+ //#region src/completeness.d.ts
5
+ /** The ten fields a GenAI trace is scored on. */
6
+ declare const GENAI_COMPLETENESS_FIELDS: readonly ["llm_input", "llm_output", "model_name", "token_usage", "cost_usd", "latency_per_span", "tool_call_args", "tool_call_results", "span_tree", "span_count"];
7
+ type GenAiCompletenessField = (typeof GENAI_COMPLETENESS_FIELDS)[number];
8
+ /** Per-field outcome: 1 present, 0.5 partial, 0 absent. */
9
+ interface FieldScore {
10
+ field: GenAiCompletenessField;
11
+ points: 0 | 0.5 | 1;
12
+ /** Why the field scored what it did — shown to whoever has to fix it. */
13
+ detail: string;
14
+ }
15
+ interface CompletenessResult {
16
+ /** Total points, 0–10. */
17
+ score: number;
18
+ max: number;
19
+ fields: FieldScore[];
20
+ /** Fields that scored 0. */
21
+ missing: GenAiCompletenessField[];
22
+ /** Fields that scored 0.5. */
23
+ partial: GenAiCompletenessField[];
24
+ }
25
+ /**
26
+ * Score a single trace's spans against the ten-field checklist.
27
+ *
28
+ * Pass every span of one trace — the tree and count checks are meaningless on a
29
+ * partial slice.
30
+ */
31
+ declare function scoreGenAiCompleteness(spans: ScenarioSpan[]): CompletenessResult;
32
+ /** One line per field, for a CLI or a failed assertion. */
33
+ declare function formatCompleteness(result: CompletenessResult): string;
34
+ //#endregion
4
35
  //#region src/redaction.d.ts
5
36
  /**
6
37
  * Every attribute key in the contract flagged `highCardinality: true`, across
@@ -35,5 +66,4 @@ declare function isHighCardinalityKey(contract: TelemetryContract, key: string):
35
66
  */
36
67
  declare const AGENT_SECURITY_TELEMETRY_CONTRACT: TelemetryContract;
37
68
  //#endregion
38
- export { AGENT_SECURITY_TELEMETRY_CONTRACT, ATTRIBUTE_TYPES, type AttributeSpec, type AttributeType, type Cardinality, type ChangeKind, type ChangeType, type CheckScenarioOptions, type CompletionBoundary, type ContractSnapshot, type EvaluateScenarioOptions, type OtelContext, type ReadableSpanLike, SCHEMA_ATTRS, SNAPSHOT_SPEC, STABILITIES, type ScenarioAddition, type ScenarioEventSpec, type ScenarioOutcome, type ScenarioProposal, type ScenarioResult, type ScenarioSpan, type ScenarioSpec, type ScenarioViolation, type ScenarioViolationCode, type SchemaAttributeKey, type SchemaProcessorMode, type SchemaValidationProcessorOptions, SchemaValidationSpanProcessor, type SchemaViolation, type SnapshotAttribute, type SnapshotChange, type SnapshotDiff, type SnapshotSpan, type SpanLike, type SpanProcessorLike, type SpanShape, type SpanSpec, type Stability, type TelemetryContract, type ValidateOptions, type ViolationCode, type ViolationSeverity, allowsAdditionalAttributes, checkScenario, contractToSnapshot, createSchemaValidationProcessor, defineContract, diffSnapshots, evaluateScenario, formatDiff, formatScenarioResult, formatViolation, hasBreakingChanges, hasErrors, highCardinalityKeys, isHighCardinalityKey, isScenarioClosed, parseCardinality, parseSnapshot, proposeScenario, resolveAttributeSpec, serializeSnapshot, validateScenarioSpec, validateSpan };
39
- //# sourceMappingURL=index.d.cts.map
69
+ export { AGENT_SECURITY_TELEMETRY_CONTRACT, ATTRIBUTE_TYPES, type AttributeSpec, type AttributeType, type Cardinality, type ChangeKind, type ChangeType, type CheckScenarioOptions, type CompletenessResult, type CompletionBoundary, type ContractSnapshot, type EvaluateScenarioOptions, type FieldScore, GENAI_COMPLETENESS_FIELDS, type GenAiCompletenessField, type OtelContext, type ReadableSpanLike, SCHEMA_ATTRS, SNAPSHOT_SPEC, STABILITIES, type ScenarioAddition, type ScenarioEventSpec, type ScenarioOutcome, type ScenarioProposal, type ScenarioResult, type ScenarioSpan, type ScenarioSpec, type ScenarioViolation, type ScenarioViolationCode, type SchemaAttributeKey, type SchemaProcessorMode, type SchemaValidationProcessorOptions, SchemaValidationSpanProcessor, type SchemaViolation, type SnapshotAttribute, type SnapshotChange, type SnapshotDiff, type SnapshotSpan, type SpanLike, type SpanProcessorLike, type SpanShape, type SpanSpec, type Stability, type TelemetryContract, type ValidateOptions, type ViolationCode, type ViolationSeverity, allowsAdditionalAttributes, checkScenario, contractToSnapshot, createSchemaValidationProcessor, defineContract, diffSnapshots, evaluateScenario, formatCompleteness, formatDiff, formatScenarioResult, formatViolation, hasBreakingChanges, hasErrors, highCardinalityKeys, isHighCardinalityKey, isScenarioClosed, parseCardinality, parseSnapshot, proposeScenario, resolveAttributeSpec, scoreGenAiCompleteness, serializeSnapshot, validateScenarioSpec, validateSpan };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,37 @@
1
1
  import { a as diffSnapshots, c as ContractSnapshot, d as contractToSnapshot, f as parseSnapshot, g as SchemaAttributeKey, h as SNAPSHOT_SPEC, i as SnapshotDiff, l as SnapshotAttribute, m as SCHEMA_ATTRS, n as ChangeType, o as formatDiff, p as serializeSnapshot, r as SnapshotChange, s as hasBreakingChanges, t as ChangeKind, u as SnapshotSpan } from "./diff-CAIC04O4.js";
2
2
  import { A as validateScenarioSpec, C as ScenarioViolationCode, D as isScenarioClosed, E as formatScenarioResult, O as parseCardinality, S as ScenarioViolation, T as evaluateScenario, _ as ScenarioOutcome, a as SpanSpec, b as ScenarioSpan, c as allowsAdditionalAttributes, d as Cardinality, f as CheckScenarioOptions, g as ScenarioEventSpec, h as ScenarioAddition, i as STABILITIES, k as proposeScenario, l as defineContract, m as EvaluateScenarioOptions, n as AttributeSpec, o as Stability, p as CompletionBoundary, r as AttributeType, s as TelemetryContract, t as ATTRIBUTE_TYPES, u as resolveAttributeSpec, v as ScenarioProposal, w as checkScenario, x as ScenarioSpec, y as ScenarioResult } from "./contract-Ymh_Q37N.js";
3
3
  import { a as SchemaValidationSpanProcessor, c as createSchemaValidationProcessor, d as ValidateOptions, f as ViolationCode, g as validateSpan, h as hasErrors, i as SchemaValidationProcessorOptions, l as SchemaViolation, m as formatViolation, n as ReadableSpanLike, o as SpanLike, p as ViolationSeverity, r as SchemaProcessorMode, s as SpanProcessorLike, t as OtelContext, u as SpanShape } from "./processor-TpuacLr5.js";
4
+ //#region src/completeness.d.ts
5
+ /** The ten fields a GenAI trace is scored on. */
6
+ declare const GENAI_COMPLETENESS_FIELDS: readonly ["llm_input", "llm_output", "model_name", "token_usage", "cost_usd", "latency_per_span", "tool_call_args", "tool_call_results", "span_tree", "span_count"];
7
+ type GenAiCompletenessField = (typeof GENAI_COMPLETENESS_FIELDS)[number];
8
+ /** Per-field outcome: 1 present, 0.5 partial, 0 absent. */
9
+ interface FieldScore {
10
+ field: GenAiCompletenessField;
11
+ points: 0 | 0.5 | 1;
12
+ /** Why the field scored what it did — shown to whoever has to fix it. */
13
+ detail: string;
14
+ }
15
+ interface CompletenessResult {
16
+ /** Total points, 0–10. */
17
+ score: number;
18
+ max: number;
19
+ fields: FieldScore[];
20
+ /** Fields that scored 0. */
21
+ missing: GenAiCompletenessField[];
22
+ /** Fields that scored 0.5. */
23
+ partial: GenAiCompletenessField[];
24
+ }
25
+ /**
26
+ * Score a single trace's spans against the ten-field checklist.
27
+ *
28
+ * Pass every span of one trace — the tree and count checks are meaningless on a
29
+ * partial slice.
30
+ */
31
+ declare function scoreGenAiCompleteness(spans: ScenarioSpan[]): CompletenessResult;
32
+ /** One line per field, for a CLI or a failed assertion. */
33
+ declare function formatCompleteness(result: CompletenessResult): string;
34
+ //#endregion
4
35
  //#region src/redaction.d.ts
5
36
  /**
6
37
  * Every attribute key in the contract flagged `highCardinality: true`, across
@@ -35,5 +66,4 @@ declare function isHighCardinalityKey(contract: TelemetryContract, key: string):
35
66
  */
36
67
  declare const AGENT_SECURITY_TELEMETRY_CONTRACT: TelemetryContract;
37
68
  //#endregion
38
- export { AGENT_SECURITY_TELEMETRY_CONTRACT, ATTRIBUTE_TYPES, type AttributeSpec, type AttributeType, type Cardinality, type ChangeKind, type ChangeType, type CheckScenarioOptions, type CompletionBoundary, type ContractSnapshot, type EvaluateScenarioOptions, type OtelContext, type ReadableSpanLike, SCHEMA_ATTRS, SNAPSHOT_SPEC, STABILITIES, type ScenarioAddition, type ScenarioEventSpec, type ScenarioOutcome, type ScenarioProposal, type ScenarioResult, type ScenarioSpan, type ScenarioSpec, type ScenarioViolation, type ScenarioViolationCode, type SchemaAttributeKey, type SchemaProcessorMode, type SchemaValidationProcessorOptions, SchemaValidationSpanProcessor, type SchemaViolation, type SnapshotAttribute, type SnapshotChange, type SnapshotDiff, type SnapshotSpan, type SpanLike, type SpanProcessorLike, type SpanShape, type SpanSpec, type Stability, type TelemetryContract, type ValidateOptions, type ViolationCode, type ViolationSeverity, allowsAdditionalAttributes, checkScenario, contractToSnapshot, createSchemaValidationProcessor, defineContract, diffSnapshots, evaluateScenario, formatDiff, formatScenarioResult, formatViolation, hasBreakingChanges, hasErrors, highCardinalityKeys, isHighCardinalityKey, isScenarioClosed, parseCardinality, parseSnapshot, proposeScenario, resolveAttributeSpec, serializeSnapshot, validateScenarioSpec, validateSpan };
39
- //# sourceMappingURL=index.d.ts.map
69
+ export { AGENT_SECURITY_TELEMETRY_CONTRACT, ATTRIBUTE_TYPES, type AttributeSpec, type AttributeType, type Cardinality, type ChangeKind, type ChangeType, type CheckScenarioOptions, type CompletenessResult, type CompletionBoundary, type ContractSnapshot, type EvaluateScenarioOptions, type FieldScore, GENAI_COMPLETENESS_FIELDS, type GenAiCompletenessField, type OtelContext, type ReadableSpanLike, SCHEMA_ATTRS, SNAPSHOT_SPEC, STABILITIES, type ScenarioAddition, type ScenarioEventSpec, type ScenarioOutcome, type ScenarioProposal, type ScenarioResult, type ScenarioSpan, type ScenarioSpec, type ScenarioViolation, type ScenarioViolationCode, type SchemaAttributeKey, type SchemaProcessorMode, type SchemaValidationProcessorOptions, SchemaValidationSpanProcessor, type SchemaViolation, type SnapshotAttribute, type SnapshotChange, type SnapshotDiff, type SnapshotSpan, type SpanLike, type SpanProcessorLike, type SpanShape, type SpanSpec, type Stability, type TelemetryContract, type ValidateOptions, type ViolationCode, type ViolationSeverity, allowsAdditionalAttributes, checkScenario, contractToSnapshot, createSchemaValidationProcessor, defineContract, diffSnapshots, evaluateScenario, formatCompleteness, formatDiff, formatScenarioResult, formatViolation, hasBreakingChanges, hasErrors, highCardinalityKeys, isHighCardinalityKey, isScenarioClosed, parseCardinality, parseSnapshot, proposeScenario, resolveAttributeSpec, scoreGenAiCompleteness, serializeSnapshot, validateScenarioSpec, validateSpan };
package/dist/index.js CHANGED
@@ -2,6 +2,100 @@ import { a as SNAPSHOT_SPEC, i as SCHEMA_ATTRS, n as parseSnapshot, r as seriali
2
2
  import { _ as validateScenarioSpec, a as validateSpan, c as allowsAdditionalAttributes, d as checkScenario, f as evaluateScenario, g as proposeScenario, h as parseCardinality, i as hasErrors, l as defineContract, m as isScenarioClosed, n as createSchemaValidationProcessor, o as ATTRIBUTE_TYPES, p as formatScenarioResult, r as formatViolation, s as STABILITIES, t as SchemaValidationSpanProcessor, u as resolveAttributeSpec } from "./processor-BPp_DewZ.js";
3
3
  import { diffSnapshots, formatDiff, hasBreakingChanges } from "./diff.js";
4
4
 
5
+ //#region src/completeness.ts
6
+ /** The ten fields a GenAI trace is scored on. */
7
+ const GENAI_COMPLETENESS_FIELDS = [
8
+ "llm_input",
9
+ "llm_output",
10
+ "model_name",
11
+ "token_usage",
12
+ "cost_usd",
13
+ "latency_per_span",
14
+ "tool_call_args",
15
+ "tool_call_results",
16
+ "span_tree",
17
+ "span_count"
18
+ ];
19
+ /** A value counts as present only if it is non-null and not an empty string/array. */
20
+ function isNonEmpty(value) {
21
+ if (value === null || value === void 0) return false;
22
+ if (typeof value === "string") return value.trim() !== "";
23
+ if (Array.isArray(value)) return value.length > 0;
24
+ return true;
25
+ }
26
+ function anySpanHas(spans, key) {
27
+ return spans.some((s) => isNonEmpty(s.attributes?.[key]));
28
+ }
29
+ function countSpansWith(spans, key) {
30
+ return spans.filter((s) => isNonEmpty(s.attributes?.[key])).length;
31
+ }
32
+ function score(field, points, detail) {
33
+ return {
34
+ field,
35
+ points,
36
+ detail
37
+ };
38
+ }
39
+ /**
40
+ * Score a single trace's spans against the ten-field checklist.
41
+ *
42
+ * Pass every span of one trace — the tree and count checks are meaningless on a
43
+ * partial slice.
44
+ */
45
+ function scoreGenAiCompleteness(spans) {
46
+ const fields = [];
47
+ fields.push(anySpanHas(spans, "gen_ai.input.messages") ? score("llm_input", 1, "gen_ai.input.messages present") : score("llm_input", 0, "no span carries gen_ai.input.messages"));
48
+ fields.push(anySpanHas(spans, "gen_ai.output.messages") ? score("llm_output", 1, "gen_ai.output.messages present") : score("llm_output", 0, "no span carries gen_ai.output.messages"));
49
+ const hasResponseModel = anySpanHas(spans, "gen_ai.response.model");
50
+ const hasRequestModel = anySpanHas(spans, "gen_ai.request.model");
51
+ fields.push(hasResponseModel || hasRequestModel ? score("model_name", 1, hasResponseModel ? "gen_ai.response.model present" : "gen_ai.request.model present (no response model)") : score("model_name", 0, "neither request nor response model recorded"));
52
+ const hasInputTokens = anySpanHas(spans, "gen_ai.usage.input_tokens");
53
+ const hasOutputTokens = anySpanHas(spans, "gen_ai.usage.output_tokens");
54
+ if (hasInputTokens && hasOutputTokens) fields.push(score("token_usage", 1, "input and output tokens recorded"));
55
+ else if (hasInputTokens || hasOutputTokens) fields.push(score("token_usage", .5, `only ${hasInputTokens ? "input" : "output"} tokens recorded`));
56
+ else fields.push(score("token_usage", 0, "no token usage recorded"));
57
+ fields.push(anySpanHas(spans, "gen_ai.usage.cost.usd") ? score("cost_usd", 1, "gen_ai.usage.cost.usd present") : score("cost_usd", 0, "no span carries gen_ai.usage.cost.usd"));
58
+ const timed = spans.filter((s) => typeof s.durationMs === "number" && s.durationMs >= 0).length;
59
+ if (spans.length > 0 && timed === spans.length) fields.push(score("latency_per_span", 1, `all ${timed} spans timed`));
60
+ else if (timed > 0) fields.push(score("latency_per_span", .5, `${timed} of ${spans.length} spans carry a duration`));
61
+ else fields.push(score("latency_per_span", 0, "no span carries a duration"));
62
+ const toolCallSpans = spans.filter((span) => isNonEmpty(span.attributes?.["gen_ai.tool.name"]) || isNonEmpty(span.attributes?.["gen_ai.tool.call.id"]) || isNonEmpty(span.attributes?.["gen_ai.tool.call.arguments"]) || isNonEmpty(span.attributes?.["gen_ai.tool.call.result"]));
63
+ const toolSpans = toolCallSpans.length;
64
+ const argCount = countSpansWith(toolCallSpans, "gen_ai.tool.call.arguments");
65
+ const resultCount = countSpansWith(toolCallSpans, "gen_ai.tool.call.result");
66
+ if (toolSpans === 0) fields.push(score("tool_call_args", 0, "no tool calls in this trace"));
67
+ else if (argCount === toolSpans) fields.push(score("tool_call_args", 1, `all ${toolSpans} tool call(s) carry arguments`));
68
+ else if (argCount > 0) fields.push(score("tool_call_args", .5, `${argCount} of ${toolSpans} tool call(s) carry arguments`));
69
+ else fields.push(score("tool_call_args", 0, `${toolSpans} tool span(s) but none carry gen_ai.tool.call.arguments`));
70
+ if (toolSpans > 0 && resultCount === toolSpans) fields.push(score("tool_call_results", 1, `all ${toolSpans} tool call(s) carry results`));
71
+ else if (resultCount > 0) fields.push(score("tool_call_results", .5, `${resultCount} of ${toolSpans} tool call(s) carry a result`));
72
+ else if (toolSpans > 0) fields.push(score("tool_call_results", .5, `${toolSpans} tool call(s) recorded but no result landed`));
73
+ else fields.push(score("tool_call_results", 0, "no tool calls in this trace"));
74
+ const ids = new Set(spans.map((s) => s.spanId));
75
+ const linked = spans.filter((s) => s.parentSpanId !== void 0 && ids.has(s.parentSpanId)).length;
76
+ const dangling = spans.filter((s) => s.parentSpanId !== void 0 && !ids.has(s.parentSpanId)).length;
77
+ if (linked > 0) fields.push(score("span_tree", 1, `${linked} parent/child link(s) resolve`));
78
+ else if (dangling > 0) fields.push(score("span_tree", .5, `${dangling} parent id(s) resolve to no span`));
79
+ else fields.push(score("span_tree", 0, "trace is flat — no parent/child links"));
80
+ if (spans.length >= 2) fields.push(score("span_count", 1, `${spans.length} spans`));
81
+ else if (spans.length === 1) fields.push(score("span_count", .5, "single-span trace"));
82
+ else fields.push(score("span_count", 0, "no spans"));
83
+ return {
84
+ score: fields.reduce((sum, f) => sum + f.points, 0),
85
+ max: GENAI_COMPLETENESS_FIELDS.length,
86
+ fields,
87
+ missing: fields.filter((f) => f.points === 0).map((f) => f.field),
88
+ partial: fields.filter((f) => f.points === .5).map((f) => f.field)
89
+ };
90
+ }
91
+ /** One line per field, for a CLI or a failed assertion. */
92
+ function formatCompleteness(result) {
93
+ return [`GenAI trace completeness: ${result.score}/${result.max}`, ...result.fields.map((f) => {
94
+ return ` ${f.points === 1 ? "✓" : f.points === .5 ? "~" : "✗"} ${f.field} — ${f.detail}`;
95
+ })].join("\n");
96
+ }
97
+
98
+ //#endregion
5
99
  //#region src/redaction.ts
6
100
  /**
7
101
  * Every attribute key in the contract flagged `highCardinality: true`, across
@@ -177,5 +271,4 @@ const AGENT_SECURITY_TELEMETRY_CONTRACT = defineContract({
177
271
  });
178
272
 
179
273
  //#endregion
180
- export { AGENT_SECURITY_TELEMETRY_CONTRACT, ATTRIBUTE_TYPES, SCHEMA_ATTRS, SNAPSHOT_SPEC, STABILITIES, SchemaValidationSpanProcessor, allowsAdditionalAttributes, checkScenario, contractToSnapshot, createSchemaValidationProcessor, defineContract, diffSnapshots, evaluateScenario, formatDiff, formatScenarioResult, formatViolation, hasBreakingChanges, hasErrors, highCardinalityKeys, isHighCardinalityKey, isScenarioClosed, parseCardinality, parseSnapshot, proposeScenario, resolveAttributeSpec, serializeSnapshot, validateScenarioSpec, validateSpan };
181
- //# sourceMappingURL=index.js.map
274
+ export { AGENT_SECURITY_TELEMETRY_CONTRACT, ATTRIBUTE_TYPES, GENAI_COMPLETENESS_FIELDS, SCHEMA_ATTRS, SNAPSHOT_SPEC, STABILITIES, SchemaValidationSpanProcessor, allowsAdditionalAttributes, checkScenario, contractToSnapshot, createSchemaValidationProcessor, defineContract, diffSnapshots, evaluateScenario, formatCompleteness, formatDiff, formatScenarioResult, formatViolation, hasBreakingChanges, hasErrors, highCardinalityKeys, isHighCardinalityKey, isScenarioClosed, parseCardinality, parseSnapshot, proposeScenario, resolveAttributeSpec, scoreGenAiCompleteness, serializeSnapshot, validateScenarioSpec, validateSpan };
@@ -631,5 +631,4 @@ function createSchemaValidationProcessor(opts) {
631
631
  }
632
632
 
633
633
  //#endregion
634
- export { validateScenarioSpec as _, validateSpan as a, allowsAdditionalAttributes as c, checkScenario as d, evaluateScenario as f, proposeScenario as g, parseCardinality as h, hasErrors as i, defineContract as l, isScenarioClosed as m, createSchemaValidationProcessor as n, ATTRIBUTE_TYPES as o, formatScenarioResult as p, formatViolation as r, STABILITIES as s, SchemaValidationSpanProcessor as t, resolveAttributeSpec as u };
635
- //# sourceMappingURL=processor-BPp_DewZ.js.map
634
+ export { validateScenarioSpec as _, validateSpan as a, allowsAdditionalAttributes as c, checkScenario as d, evaluateScenario as f, proposeScenario as g, parseCardinality as h, hasErrors as i, defineContract as l, isScenarioClosed as m, createSchemaValidationProcessor as n, ATTRIBUTE_TYPES as o, formatScenarioResult as p, formatViolation as r, STABILITIES as s, SchemaValidationSpanProcessor as t, resolveAttributeSpec as u };
@@ -95,5 +95,4 @@ declare class SchemaValidationSpanProcessor implements SpanProcessorLike {
95
95
  }
96
96
  declare function createSchemaValidationProcessor(opts: SchemaValidationProcessorOptions): SchemaValidationSpanProcessor;
97
97
  //#endregion
98
- export { SchemaValidationSpanProcessor as a, createSchemaValidationProcessor as c, ValidateOptions as d, ViolationCode as f, validateSpan as g, hasErrors as h, SchemaValidationProcessorOptions as i, SchemaViolation as l, formatViolation as m, ReadableSpanLike as n, SpanLike as o, ViolationSeverity as p, SchemaProcessorMode as r, SpanProcessorLike as s, OtelContext as t, SpanShape as u };
99
- //# sourceMappingURL=processor-DVcsS6Rz.d.cts.map
98
+ export { SchemaValidationSpanProcessor as a, createSchemaValidationProcessor as c, ValidateOptions as d, ViolationCode as f, validateSpan as g, hasErrors as h, SchemaValidationProcessorOptions as i, SchemaViolation as l, formatViolation as m, ReadableSpanLike as n, SpanLike as o, ViolationSeverity as p, SchemaProcessorMode as r, SpanProcessorLike as s, OtelContext as t, SpanShape as u };
@@ -733,5 +733,4 @@ Object.defineProperty(exports, 'validateSpan', {
733
733
  get: function () {
734
734
  return validateSpan;
735
735
  }
736
- });
737
- //# sourceMappingURL=processor-Gu8Yl_dS.cjs.map
736
+ });
@@ -95,5 +95,4 @@ declare class SchemaValidationSpanProcessor implements SpanProcessorLike {
95
95
  }
96
96
  declare function createSchemaValidationProcessor(opts: SchemaValidationProcessorOptions): SchemaValidationSpanProcessor;
97
97
  //#endregion
98
- export { SchemaValidationSpanProcessor as a, createSchemaValidationProcessor as c, ValidateOptions as d, ViolationCode as f, validateSpan as g, hasErrors as h, SchemaValidationProcessorOptions as i, SchemaViolation as l, formatViolation as m, ReadableSpanLike as n, SpanLike as o, ViolationSeverity as p, SchemaProcessorMode as r, SpanProcessorLike as s, OtelContext as t, SpanShape as u };
99
- //# sourceMappingURL=processor-TpuacLr5.d.ts.map
98
+ export { SchemaValidationSpanProcessor as a, createSchemaValidationProcessor as c, ValidateOptions as d, ViolationCode as f, validateSpan as g, hasErrors as h, SchemaValidationProcessorOptions as i, SchemaViolation as l, formatViolation as m, ReadableSpanLike as n, SpanLike as o, ViolationSeverity as p, SchemaProcessorMode as r, SpanProcessorLike as s, OtelContext as t, SpanShape as u };
@@ -115,5 +115,4 @@ Object.defineProperty(exports, 'serializeSnapshot', {
115
115
  get: function () {
116
116
  return serializeSnapshot;
117
117
  }
118
- });
119
- //# sourceMappingURL=snapshot-CyWGJaJT.cjs.map
118
+ });
@@ -85,5 +85,4 @@ function parseSnapshot(json) {
85
85
  }
86
86
 
87
87
  //#endregion
88
- export { SNAPSHOT_SPEC as a, SCHEMA_ATTRS as i, parseSnapshot as n, serializeSnapshot as r, contractToSnapshot as t };
89
- //# sourceMappingURL=snapshot-h8pb_Up_.js.map
88
+ export { SNAPSHOT_SPEC as a, SCHEMA_ATTRS as i, parseSnapshot as n, serializeSnapshot as r, contractToSnapshot as t };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "autotel-schema",
3
- "version": "5.0.0",
3
+ "version": "7.0.0",
4
4
  "description": "Your telemetry surface as a typed, versioned contract — declare the spans and attributes your service emits, validate live spans against them, and diff the surface across commits to catch breaking trace changes before they ship.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -44,7 +44,7 @@
44
44
  "author": "Jag Reehal <jag@jagreehal.com> (https://jagreehal.com)",
45
45
  "license": "Apache-2.0",
46
46
  "peerDependencies": {
47
- "autotel": "6.0.0"
47
+ "autotel": "6.2.0"
48
48
  },
49
49
  "peerDependenciesMeta": {
50
50
  "autotel": {
@@ -52,9 +52,9 @@
52
52
  }
53
53
  },
54
54
  "devDependencies": {
55
- "@types/node": "^26.1.1",
55
+ "@types/node": "^26.1.2",
56
56
  "rimraf": "^6.1.3",
57
- "tsdown": "^0.22.12",
57
+ "tsdown": "^0.22.14",
58
58
  "typescript": "^6.0.3",
59
59
  "vitest": "^4.1.10"
60
60
  },
package/dist/cli.cjs.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"cli.cjs","names":["diffSnapshots","parseSnapshot","formatDiff","hasBreakingChanges","path"],"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * autotel-schema CLI — the CI gate for your telemetry's public API.\n *\n * autotel-schema diff <baseline.json> <current.json> # classify changes\n * autotel-schema check <baseline.json> <current.json> # exit 1 on breaking\n *\n * Both operate on snapshot JSON produced by `serializeSnapshot(contractToSnapshot(contract))`.\n * Commit the baseline; regenerate `current` in CI; gate the merge on `check`.\n */\n\nimport { readFileSync } from 'node:fs';\nimport path from 'node:path';\nimport { parseSnapshot } from './snapshot.js';\nimport {\n diffSnapshots,\n formatDiff,\n hasBreakingChanges,\n type SnapshotDiff,\n} from './diff.js';\n\ninterface Parsed {\n command: string | undefined;\n baseline: string | undefined;\n current: string | undefined;\n json: boolean;\n}\n\nfunction parseArgs(argv: string[]): Parsed {\n const positional: string[] = [];\n let json = false;\n for (const arg of argv) {\n if (arg === '--json') json = true;\n else if (arg === '-h' || arg === '--help') positional.unshift('help');\n else positional.push(arg);\n }\n return {\n command: positional[0],\n baseline: positional[1],\n current: positional[2],\n json,\n };\n}\n\nconst USAGE = `autotel-schema — treat your trace surface like a versioned public API\n\nUsage:\n autotel-schema diff <baseline.json> <current.json> [--json]\n autotel-schema check <baseline.json> <current.json> [--json]\n\nCommands:\n diff Print every change (breaking / additive / neutral). Always exits 0.\n check Like diff, but exits 1 if any breaking change is found (CI gate).\n\nSnapshots are produced with serializeSnapshot(contractToSnapshot(contract)).`;\n\nfunction loadDiff(baseline: string, current: string): SnapshotDiff {\n const prev = parseSnapshot(readFileSync(baseline, 'utf8'));\n const next = parseSnapshot(readFileSync(current, 'utf8'));\n return diffSnapshots(prev, next);\n}\n\nfunction emit(diff: SnapshotDiff, json: boolean): void {\n if (json) {\n console.log(JSON.stringify(diff, null, 2));\n } else {\n console.log(formatDiff(diff));\n }\n}\n\nexport function run(argv: string[]): number {\n const { command, baseline, current, json } = parseArgs(argv);\n\n if (!command || command === 'help') {\n console.log(USAGE);\n return command ? 0 : 1;\n }\n\n if (command !== 'diff' && command !== 'check') {\n console.error(`autotel-schema: unknown command \"${command}\"\\n\\n${USAGE}`);\n return 1;\n }\n\n if (!baseline || !current) {\n console.error(\n 'autotel-schema: both <baseline.json> and <current.json> are required\\n',\n );\n console.error(USAGE);\n return 1;\n }\n\n let diff: SnapshotDiff;\n try {\n diff = loadDiff(baseline, current);\n } catch (error) {\n console.error(\n `autotel-schema: ${error instanceof Error ? error.message : String(error)}`,\n );\n return 1;\n }\n\n emit(diff, json);\n\n if (command === 'check' && hasBreakingChanges(diff)) {\n console.error(\n `\\nautotel-schema: ${diff.breaking.length} breaking change(s) to the telemetry contract. ` +\n `Bump the contract major version and update the committed snapshot.`,\n );\n return 1;\n }\n return 0;\n}\n\n// Only auto-run when invoked directly as the binary, not when imported in tests.\n// Match the basename so a repo path containing \"autotel-schema\" can't trigger it.\nconst entry = process.argv[1] ? path.basename(process.argv[1]) : '';\nif (entry === 'autotel-schema' || entry === 'cli.js' || entry === 'cli.cjs') {\n process.exit(run(process.argv.slice(2)));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,SAAS,UAAU,MAAwB;CACzC,MAAM,aAAuB,CAAC;CAC9B,IAAI,OAAO;CACX,KAAK,MAAM,OAAO,MAChB,IAAI,QAAQ,UAAU,OAAO;MACxB,IAAI,QAAQ,QAAQ,QAAQ,UAAU,WAAW,QAAQ,MAAM;MAC/D,WAAW,KAAK,GAAG;CAE1B,OAAO;EACL,SAAS,WAAW;EACpB,UAAU,WAAW;EACrB,SAAS,WAAW;EACpB;CACF;AACF;AAEA,MAAM,QAAQ;;;;;;;;;;;AAYd,SAAS,SAAS,UAAkB,SAA+B;CAGjE,OAAOA,2BAFMC,yDAA2B,UAAU,MAAM,CAEhC,GADXA,yDAA2B,SAAS,MAAM,CACzB,CAAC;AACjC;AAEA,SAAS,KAAK,MAAoB,MAAqB;CACrD,IAAI,MACF,QAAQ,IAAI,KAAK,UAAU,MAAM,MAAM,CAAC,CAAC;MAEzC,QAAQ,IAAIC,wBAAW,IAAI,CAAC;AAEhC;AAEA,SAAgB,IAAI,MAAwB;CAC1C,MAAM,EAAE,SAAS,UAAU,SAAS,SAAS,UAAU,IAAI;CAE3D,IAAI,CAAC,WAAW,YAAY,QAAQ;EAClC,QAAQ,IAAI,KAAK;EACjB,OAAO,UAAU,IAAI;CACvB;CAEA,IAAI,YAAY,UAAU,YAAY,SAAS;EAC7C,QAAQ,MAAM,oCAAoC,QAAQ,OAAO,OAAO;EACxE,OAAO;CACT;CAEA,IAAI,CAAC,YAAY,CAAC,SAAS;EACzB,QAAQ,MACN,wEACF;EACA,QAAQ,MAAM,KAAK;EACnB,OAAO;CACT;CAEA,IAAI;CACJ,IAAI;EACF,OAAO,SAAS,UAAU,OAAO;CACnC,SAAS,OAAO;EACd,QAAQ,MACN,mBAAmB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAC1E;EACA,OAAO;CACT;CAEA,KAAK,MAAM,IAAI;CAEf,IAAI,YAAY,WAAWC,gCAAmB,IAAI,GAAG;EACnD,QAAQ,MACN,qBAAqB,KAAK,SAAS,OAAO,kHAE5C;EACA,OAAO;CACT;CACA,OAAO;AACT;AAIA,MAAM,QAAQ,QAAQ,KAAK,KAAKC,kBAAK,SAAS,QAAQ,KAAK,EAAE,IAAI;AACjE,IAAI,UAAU,oBAAoB,UAAU,YAAY,UAAU,WAChE,QAAQ,KAAK,IAAI,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"cli.d.cts","names":[],"sources":["../src/cli.ts"],"mappings":";;;;;;;;;;iBAsEgB,IAAI"}
package/dist/cli.d.ts.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"cli.d.ts","names":[],"sources":["../src/cli.ts"],"mappings":";;;;;;;;;;iBAsEgB,IAAI"}
package/dist/cli.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * autotel-schema CLI — the CI gate for your telemetry's public API.\n *\n * autotel-schema diff <baseline.json> <current.json> # classify changes\n * autotel-schema check <baseline.json> <current.json> # exit 1 on breaking\n *\n * Both operate on snapshot JSON produced by `serializeSnapshot(contractToSnapshot(contract))`.\n * Commit the baseline; regenerate `current` in CI; gate the merge on `check`.\n */\n\nimport { readFileSync } from 'node:fs';\nimport path from 'node:path';\nimport { parseSnapshot } from './snapshot.js';\nimport {\n diffSnapshots,\n formatDiff,\n hasBreakingChanges,\n type SnapshotDiff,\n} from './diff.js';\n\ninterface Parsed {\n command: string | undefined;\n baseline: string | undefined;\n current: string | undefined;\n json: boolean;\n}\n\nfunction parseArgs(argv: string[]): Parsed {\n const positional: string[] = [];\n let json = false;\n for (const arg of argv) {\n if (arg === '--json') json = true;\n else if (arg === '-h' || arg === '--help') positional.unshift('help');\n else positional.push(arg);\n }\n return {\n command: positional[0],\n baseline: positional[1],\n current: positional[2],\n json,\n };\n}\n\nconst USAGE = `autotel-schema — treat your trace surface like a versioned public API\n\nUsage:\n autotel-schema diff <baseline.json> <current.json> [--json]\n autotel-schema check <baseline.json> <current.json> [--json]\n\nCommands:\n diff Print every change (breaking / additive / neutral). Always exits 0.\n check Like diff, but exits 1 if any breaking change is found (CI gate).\n\nSnapshots are produced with serializeSnapshot(contractToSnapshot(contract)).`;\n\nfunction loadDiff(baseline: string, current: string): SnapshotDiff {\n const prev = parseSnapshot(readFileSync(baseline, 'utf8'));\n const next = parseSnapshot(readFileSync(current, 'utf8'));\n return diffSnapshots(prev, next);\n}\n\nfunction emit(diff: SnapshotDiff, json: boolean): void {\n if (json) {\n console.log(JSON.stringify(diff, null, 2));\n } else {\n console.log(formatDiff(diff));\n }\n}\n\nexport function run(argv: string[]): number {\n const { command, baseline, current, json } = parseArgs(argv);\n\n if (!command || command === 'help') {\n console.log(USAGE);\n return command ? 0 : 1;\n }\n\n if (command !== 'diff' && command !== 'check') {\n console.error(`autotel-schema: unknown command \"${command}\"\\n\\n${USAGE}`);\n return 1;\n }\n\n if (!baseline || !current) {\n console.error(\n 'autotel-schema: both <baseline.json> and <current.json> are required\\n',\n );\n console.error(USAGE);\n return 1;\n }\n\n let diff: SnapshotDiff;\n try {\n diff = loadDiff(baseline, current);\n } catch (error) {\n console.error(\n `autotel-schema: ${error instanceof Error ? error.message : String(error)}`,\n );\n return 1;\n }\n\n emit(diff, json);\n\n if (command === 'check' && hasBreakingChanges(diff)) {\n console.error(\n `\\nautotel-schema: ${diff.breaking.length} breaking change(s) to the telemetry contract. ` +\n `Bump the contract major version and update the committed snapshot.`,\n );\n return 1;\n }\n return 0;\n}\n\n// Only auto-run when invoked directly as the binary, not when imported in tests.\n// Match the basename so a repo path containing \"autotel-schema\" can't trigger it.\nconst entry = process.argv[1] ? path.basename(process.argv[1]) : '';\nif (entry === 'autotel-schema' || entry === 'cli.js' || entry === 'cli.cjs') {\n process.exit(run(process.argv.slice(2)));\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA4BA,SAAS,UAAU,MAAwB;CACzC,MAAM,aAAuB,CAAC;CAC9B,IAAI,OAAO;CACX,KAAK,MAAM,OAAO,MAChB,IAAI,QAAQ,UAAU,OAAO;MACxB,IAAI,QAAQ,QAAQ,QAAQ,UAAU,WAAW,QAAQ,MAAM;MAC/D,WAAW,KAAK,GAAG;CAE1B,OAAO;EACL,SAAS,WAAW;EACpB,UAAU,WAAW;EACrB,SAAS,WAAW;EACpB;CACF;AACF;AAEA,MAAM,QAAQ;;;;;;;;;;;AAYd,SAAS,SAAS,UAAkB,SAA+B;CAGjE,OAAO,cAFM,cAAc,aAAa,UAAU,MAAM,CAEhC,GADX,cAAc,aAAa,SAAS,MAAM,CACzB,CAAC;AACjC;AAEA,SAAS,KAAK,MAAoB,MAAqB;CACrD,IAAI,MACF,QAAQ,IAAI,KAAK,UAAU,MAAM,MAAM,CAAC,CAAC;MAEzC,QAAQ,IAAI,WAAW,IAAI,CAAC;AAEhC;AAEA,SAAgB,IAAI,MAAwB;CAC1C,MAAM,EAAE,SAAS,UAAU,SAAS,SAAS,UAAU,IAAI;CAE3D,IAAI,CAAC,WAAW,YAAY,QAAQ;EAClC,QAAQ,IAAI,KAAK;EACjB,OAAO,UAAU,IAAI;CACvB;CAEA,IAAI,YAAY,UAAU,YAAY,SAAS;EAC7C,QAAQ,MAAM,oCAAoC,QAAQ,OAAO,OAAO;EACxE,OAAO;CACT;CAEA,IAAI,CAAC,YAAY,CAAC,SAAS;EACzB,QAAQ,MACN,wEACF;EACA,QAAQ,MAAM,KAAK;EACnB,OAAO;CACT;CAEA,IAAI;CACJ,IAA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c,eAAe;;;KC/FjC;KAEA;UAeK;EACf,MAAM;EACN,MAAM;;EAEN;EACA;EACA;;UAGe;EACf;EACA;EACA;EACA,UAAU;EACV,UAAU;EACV,SAAS;;;;;;iBAuKK,cACd,UAAU,kBACV,MAAM,mBACL;;iBA6Ca,mBAAmB,MAAM;;iBAKzB,WAAW,MAAM"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"diff-CfvhW7ux.d.cts","names":[],"sources":["../src/attrs.ts","../src/snapshot.ts","../src/diff.ts"],"mappings":";;;;;;;;;;;;;cAYa;;WAAA;;WAAA;;KAOD,6BACF,2BAA2B;;cAGxB;;;;UCPI;EACf,MAAM;EACN,WAAW;EACX;EACA;EACA;EACA;EACA;;UAGe;EACf,WAAW;EACX;EACA;EACA,YAAY,eAAe;;;UAIZ;EACf,aAAa;EACb;EACA;EACA,kBAAkB,eAAe;EACjC,OAAO,eAAe;;;;;;;iBA6BR,mBACd,UAAU,oBACT;;iBAgCa,kBAAkB,UAAU;;iBAK5B,cAAc,eAAe;;;KC/FjC;KAEA;UAeK;EACf,MAAM;EACN,MAAM;;EAEN;EACA;EACA;;UAGe;EACf;EACA;EACA;EACA,UAAU;EACV,UAAU;EACV,SAAS;;;;;;iBAuKK,cACd,UAAU,kBACV,MAAM,mBACL;;iBA6Ca,mBAAmB,MAAM;;iBAKzB,WAAW,MAAM"}
package/dist/diff.cjs.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"diff.cjs","names":[],"sources":["../src/diff.ts"],"sourcesContent":["/**\n * Snapshot diffing — the CI gate that catches breaking changes to your trace\n * surface before they ship.\n *\n * \"If you wouldn't ship a rename to your public API without a changelog, don't\n * do it to your traces.\" This module is what makes that enforceable: classify\n * every change between two snapshots as breaking, additive, or neutral, and let\n * CI fail on the breaking ones.\n */\n\nimport type { ContractSnapshot, SnapshotAttribute } from './snapshot.js';\n\nexport type ChangeKind = 'breaking' | 'additive' | 'neutral';\n\nexport type ChangeType =\n | 'span_removed'\n | 'span_added'\n | 'attribute_removed'\n | 'attribute_added'\n | 'type_changed'\n | 'required_added'\n | 'required_removed'\n | 'enum_value_removed'\n | 'enum_value_added'\n | 'stability_downgraded'\n | 'stability_advanced'\n | 'deprecated'\n | 'replacement_documented';\n\nexport interface SnapshotChange {\n kind: ChangeKind;\n type: ChangeType;\n /** Span the change applies to (`*` = common attributes / contract-wide). */\n span: string;\n attribute?: string;\n message: string;\n}\n\nexport interface SnapshotDiff {\n service: string;\n previousVersion: string;\n nextVersion: string;\n breaking: SnapshotChange[];\n additive: SnapshotChange[];\n neutral: SnapshotChange[];\n}\n\n/**\n * How every cross-stability transition is classified. Keyed `prev->next` so all\n * six transitions are explicit and auditable — no silent fall-through. Same-\n * stability transitions are absent (no change to report).\n */\nconst STABILITY_TRANSITIONS: Record<\n string,\n { kind: ChangeKind; type: ChangeType }\n> = {\n 'stable->experimental': { kind: 'breaking', type: 'stability_downgraded' },\n 'stable->deprecated': { kind: 'additive', type: 'deprecated' },\n 'experimental->stable': { kind: 'neutral', type: 'stability_advanced' },\n 'experimental->deprecated': { kind: 'additive', type: 'deprecated' },\n 'deprecated->stable': { kind: 'neutral', type: 'stability_advanced' },\n 'deprecated->experimental': {\n kind: 'breaking',\n type: 'stability_downgraded',\n },\n};\n\nfunction stabilityMessage(\n type: ChangeType,\n attribute: string,\n prev: SnapshotAttribute,\n next: SnapshotAttribute,\n): string {\n if (type === 'deprecated') {\n return `attribute \"${attribute}\" was deprecated${next.replacedBy ? ` (use \"${next.replacedBy}\")` : ''}`;\n }\n if (type === 'stability_downgraded') {\n return `attribute \"${attribute}\" stability downgraded ${prev.stability} → ${next.stability}`;\n }\n return `attribute \"${attribute}\" promoted ${prev.stability} → ${next.stability}`;\n}\n\nfunction push(diff: SnapshotDiff, change: SnapshotChange): void {\n if (change.kind === 'breaking') diff.breaking.push(change);\n else if (change.kind === 'additive') diff.additive.push(change);\n else diff.neutral.push(change);\n}\n\nfunction diffAttribute(\n diff: SnapshotDiff,\n span: string,\n attribute: string,\n prev: SnapshotAttribute,\n next: SnapshotAttribute,\n): void {\n if (prev.type !== next.type) {\n push(diff, {\n kind: 'breaking',\n type: 'type_changed',\n span,\n attribute,\n message: `attribute \"${attribute}\" changed type ${prev.type} → ${next.type}`,\n });\n }\n\n if (!prev.required && next.required) {\n push(diff, {\n kind: 'breaking',\n type: 'required_added',\n span,\n attribute,\n message: `attribute \"${attribute}\" became required`,\n });\n } else if (prev.required && !next.required) {\n push(diff, {\n kind: 'additive',\n type: 'required_removed',\n span,\n attribute,\n message: `attribute \"${attribute}\" is no longer required`,\n });\n }\n\n // Enum: removing a permitted value can break a producer that still emits it.\n if (prev.enum && next.enum) {\n const nextSet = new Set(next.enum);\n const removed = prev.enum.filter((v) => !nextSet.has(v));\n const prevSet = new Set(prev.enum);\n const added = next.enum.filter((v) => !prevSet.has(v));\n if (removed.length > 0) {\n push(diff, {\n kind: 'breaking',\n type: 'enum_value_removed',\n span,\n attribute,\n message: `attribute \"${attribute}\" dropped enum value(s) ${JSON.stringify(removed)}`,\n });\n }\n if (added.length > 0) {\n push(diff, {\n kind: 'additive',\n type: 'enum_value_added',\n span,\n attribute,\n message: `attribute \"${attribute}\" added enum value(s) ${JSON.stringify(added)}`,\n });\n }\n }\n\n if (prev.stability !== next.stability) {\n const transition =\n STABILITY_TRANSITIONS[`${prev.stability}->${next.stability}`];\n if (transition) {\n push(diff, {\n ...transition,\n span,\n attribute,\n message: stabilityMessage(transition.type, attribute, prev, next),\n });\n }\n }\n}\n\nfunction diffAttributeMaps(\n diff: SnapshotDiff,\n span: string,\n prev: Record<string, SnapshotAttribute>,\n next: Record<string, SnapshotAttribute>,\n): void {\n for (const [key, prevAttr] of Object.entries(prev)) {\n const nextAttr = next[key];\n if (!nextAttr) {\n // A removed attribute whose replacement is named is a documented\n // migration (still breaking — but reported as such with the pointer).\n push(diff, {\n kind: 'breaking',\n type: prevAttr.replacedBy\n ? 'replacement_documented'\n : 'attribute_removed',\n span,\n attribute: key,\n message: prevAttr.replacedBy\n ? `attribute \"${key}\" removed — replaced by \"${prevAttr.replacedBy}\"`\n : `attribute \"${key}\" was removed`,\n });\n continue;\n }\n diffAttribute(diff, span, key, prevAttr, nextAttr);\n }\n for (const key of Object.keys(next)) {\n if (!prev[key]) {\n const added = next[key];\n // Always `attribute_added` (the event is \"new attribute\"); severity rides\n // on `kind` — a new *required* attribute breaks existing producers.\n push(diff, {\n kind: added.required ? 'breaking' : 'additive',\n type: 'attribute_added',\n span,\n attribute: key,\n message: added.required\n ? `new required attribute \"${key}\" added`\n : `new attribute \"${key}\" added`,\n });\n }\n }\n}\n\n/**\n * Diff two snapshots, classifying every change. The `breaking` array is what a\n * CI gate keys off; `hasBreakingChanges()` is the convenience predicate.\n */\nexport function diffSnapshots(\n previous: ContractSnapshot,\n next: ContractSnapshot,\n): SnapshotDiff {\n const diff: SnapshotDiff = {\n service: next.service,\n previousVersion: previous.version,\n nextVersion: next.version,\n breaking: [],\n additive: [],\n neutral: [],\n };\n\n diffAttributeMaps(\n diff,\n '*',\n previous.commonAttributes,\n next.commonAttributes,\n );\n\n for (const [name, prevSpan] of Object.entries(previous.spans)) {\n const nextSpan = next.spans[name];\n if (!nextSpan) {\n push(diff, {\n kind: 'breaking',\n type: 'span_removed',\n span: name,\n message: `span \"${name}\" was removed`,\n });\n continue;\n }\n diffAttributeMaps(diff, name, prevSpan.attributes, nextSpan.attributes);\n }\n for (const name of Object.keys(next.spans)) {\n if (!previous.spans[name]) {\n push(diff, {\n kind: 'additive',\n type: 'span_added',\n span: name,\n message: `new span \"${name}\" added`,\n });\n }\n }\n\n return diff;\n}\n\n/** `true` when the diff contains at least one breaking change. */\nexport function hasBreakingChanges(diff: SnapshotDiff): boolean {\n return diff.breaking.length > 0;\n}\n\n/** Markdown rendering of a diff — for CI logs and PR comments. */\nexport function formatDiff(diff: SnapshotDiff): string {\n const lines: string[] = [\n `# Telemetry contract diff: ${diff.service} ${diff.previousVersion} → ${diff.nextVersion}`,\n '',\n ];\n const section = (title: string, changes: SnapshotChange[]) => {\n if (changes.length === 0) return;\n lines.push(`## ${title} (${changes.length})`, '');\n for (const c of changes) {\n const where = c.attribute\n ? `\\`${c.span}.${c.attribute}\\``\n : `\\`${c.span}\\``;\n lines.push(`- ${where}: ${c.message}`);\n }\n lines.push('');\n };\n section('💥 Breaking', diff.breaking);\n section('➕ Additive', diff.additive);\n section('• Neutral', diff.neutral);\n if (\n diff.breaking.length === 0 &&\n diff.additive.length === 0 &&\n diff.neutral.length === 0\n ) {\n lines.push('No changes to the telemetry contract.', '');\n }\n return lines.join('\\n');\n}\n"],"mappings":";;;;;;;;AAoDA,MAAM,wBAGF;CACF,wBAAwB;EAAE,MAAM;EAAY,MAAM;CAAuB;CACzE,sBAAsB;EAAE,MAAM;EAAY,MAAM;CAAa;CAC7D,wBAAwB;EAAE,MAAM;EAAW,MAAM;CAAqB;CACtE,4BAA4B;EAAE,MAAM;EAAY,MAAM;CAAa;CACnE,sBAAsB;EAAE,MAAM;EAAW,MAAM;CAAqB;CACpE,4BAA4B;EAC1B,MAAM;EACN,MAAM;CACR;AACF;AAEA,SAAS,iBACP,MACA,WACA,MACA,MACQ;CACR,IAAI,SAAS,cACX,OAAO,cAAc,UAAU,kBAAkB,KAAK,aAAa,UAAU,KAAK,WAAW,MAAM;CAErG,IAAI,SAAS,wBACX,OAAO,cAAc,UAAU,yBAAyB,KAAK,UAAU,KAAK,KAAK;CAEnF,OAAO,cAAc,UAAU,aAAa,KAAK,UAAU,KAAK,KAAK;AACvE;AAEA,SAAS,KAAK,MAAoB,QAA8B;CAC9D,IAAI,OAAO,SAAS,YAAY,KAAK,SAAS,KAAK,MAAM;MACpD,IAAI,OAAO,SAAS,YAAY,KAAK,SAAS,KAAK,MAAM;MACzD,KAAK,QAAQ,KAAK,MAAM;AAC/B;AAEA,SAAS,cACP,MACA,MACA,WACA,MACA,MACM;CACN,IAAI,KAAK,SAAS,KAAK,MACrB,KAAK,MAAM;EACT,MAAM;EACN,MAAM;EACN;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QAAkB,CACtB,8BAA8B,KAAK,QAAQ,GAAG,KAAK,gBAAgB,KAAK,KAAK,eAC7E,EACF;CACA,MAAM,WAAW,OAAe,YAA8B;EAC5D,IAAI,QAAQ,WAAW,GAAG;EAC1B,MAAM,KAAK,MAAM,MAAM,IAAI,QAAQ,OAAO,IAAI,EAAE;EAChD,KAAK,MAAM,KAAK,SAAS;GACvB,MAAM,QAAQ,EAAE,YACZ,KAAK,EAAE,KAAK,GAAG,EAAE,UAAU,MAC3B,KAAK,EAAE,KAAK;GAChB,MAAM,KAAK,KAAK,MAAM,IAAI,EAAE,SAAS;EACvC;EACA,MAAM,KAAK,EAAE;CACf;CACA,QAAQ,eAAe,KAAK,QAAQ;CACpC,QAAQ,cAAc,KAAK,QAAQ;CACnC,QAAQ,aAAa,KAAK,OAAO;CACjC,IACE,KAAK,SAAS,WAAW,KACzB,KAAK,SAAS,WAAW,KACzB,KAAK,QAAQ,WAAW,GAExB,MAAM,KAAK,yCAAyC,EAAE;CAExD,OAAO,MAAM,KAAK,IAAI;AACxB"}
package/dist/diff.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"diff.js","names":[],"sources":["../src/diff.ts"],"sourcesContent":["/**\n * Snapshot diffing — the CI gate that catches breaking changes to your trace\n * surface before they ship.\n *\n * \"If you wouldn't ship a rename to your public API without a changelog, don't\n * do it to your traces.\" This module is what makes that enforceable: classify\n * every change between two snapshots as breaking, additive, or neutral, and let\n * CI fail on the breaking ones.\n */\n\nimport type { ContractSnapshot, SnapshotAttribute } from './snapshot.js';\n\nexport type ChangeKind = 'breaking' | 'additive' | 'neutral';\n\nexport type ChangeType =\n | 'span_removed'\n | 'span_added'\n | 'attribute_removed'\n | 'attribute_added'\n | 'type_changed'\n | 'required_added'\n | 'required_removed'\n | 'enum_value_removed'\n | 'enum_value_added'\n | 'stability_downgraded'\n | 'stability_advanced'\n | 'deprecated'\n | 'replacement_documented';\n\nexport interface SnapshotChange {\n kind: ChangeKind;\n type: ChangeType;\n /** Span the change applies to (`*` = common attributes / contract-wide). */\n span: string;\n attribute?: string;\n message: string;\n}\n\nexport interface SnapshotDiff {\n service: string;\n previousVersion: string;\n nextVersion: string;\n breaking: SnapshotChange[];\n additive: SnapshotChange[];\n neutral: SnapshotChange[];\n}\n\n/**\n * How every cross-stability transition is classified. Keyed `prev->next` so all\n * six transitions are explicit and auditable — no silent fall-through. Same-\n * stability transitions are absent (no change to report).\n */\nconst STABILITY_TRANSITIONS: Record<\n string,\n { kind: ChangeKind; type: ChangeType }\n> = {\n 'stable->experimental': { kind: 'breaking', type: 'stability_downgraded' },\n 'stable->deprecated': { kind: 'additive', type: 'deprecated' },\n 'experimental->stable': { kind: 'neutral', type: 'stability_advanced' },\n 'experimental->deprecated': { kind: 'additive', type: 'deprecated' },\n 'deprecated->stable': { kind: 'neutral', type: 'stability_advanced' },\n 'deprecated->experimental': {\n kind: 'breaking',\n type: 'stability_downgraded',\n },\n};\n\nfunction stabilityMessage(\n type: ChangeType,\n attribute: string,\n prev: SnapshotAttribute,\n next: SnapshotAttribute,\n): string {\n if (type === 'deprecated') {\n return `attribute \"${attribute}\" was deprecated${next.replacedBy ? ` (use \"${next.replacedBy}\")` : ''}`;\n }\n if (type === 'stability_downgraded') {\n return `attribute \"${attribute}\" stability downgraded ${prev.stability} → ${next.stability}`;\n }\n return `attribute \"${attribute}\" promoted ${prev.stability} → ${next.stability}`;\n}\n\nfunction push(diff: SnapshotDiff, change: SnapshotChange): void {\n if (change.kind === 'breaking') diff.breaking.push(change);\n else if (change.kind === 'additive') diff.additive.push(change);\n else diff.neutral.push(change);\n}\n\nfunction diffAttribute(\n diff: SnapshotDiff,\n span: string,\n attribute: string,\n prev: SnapshotAttribute,\n next: SnapshotAttribute,\n): void {\n if (prev.type !== next.type) {\n push(diff, {\n kind: 'breaking',\n type: 'type_changed',\n span,\n attribute,\n message: `attribute \"${attribute}\" changed type ${prev.type} → ${next.type}`,\n });\n }\n\n if (!prev.required && next.required) {\n push(diff, {\n kind: 'breaking',\n type: 'required_added',\n span,\n attribute,\n message: `attribute \"${attribute}\" became required`,\n });\n } else if (prev.required && !next.required) {\n push(diff, {\n kind: 'additive',\n type: 'required_removed',\n span,\n attribute,\n message: `attribute \"${attribute}\" is no longer required`,\n });\n }\n\n // Enum: removing a permitted value can break a producer that still emits it.\n if (prev.enum && next.enum) {\n const nextSet = new Set(next.enum);\n const removed = prev.enum.filter((v) => !nextSet.has(v));\n const prevSet = new Set(prev.enum);\n const added = next.enum.filter((v) => !prevSet.has(v));\n if (removed.length > 0) {\n push(diff, {\n kind: 'breaking',\n type: 'enum_value_removed',\n span,\n attribute,\n message: `attribute \"${attribute}\" dropped enum value(s) ${JSON.stringify(removed)}`,\n });\n }\n if (added.length > 0) {\n push(diff, {\n kind: 'additive',\n type: 'enum_value_added',\n span,\n attribute,\n message: `attribute \"${attribute}\" added enum value(s) ${JSON.stringify(added)}`,\n });\n }\n }\n\n if (prev.stability !== next.stability) {\n const transition =\n STABILITY_TRANSITIONS[`${prev.stability}->${next.stability}`];\n if (transition) {\n push(diff, {\n ...transition,\n span,\n attribute,\n message: stabilityMessage(transition.type, attribute, prev, next),\n });\n }\n }\n}\n\nfunction diffAttributeMaps(\n diff: SnapshotDiff,\n span: string,\n prev: Record<string, SnapshotAttribute>,\n next: Record<string, SnapshotAttribute>,\n): void {\n for (const [key, prevAttr] of Object.entries(prev)) {\n const nextAttr = next[key];\n if (!nextAttr) {\n // A removed attribute whose replacement is named is a documented\n // migration (still breaking — but reported as such with the pointer).\n push(diff, {\n kind: 'breaking',\n type: prevAttr.replacedBy\n ? 'replacement_documented'\n : 'attribute_removed',\n span,\n attribute: key,\n message: prevAttr.replacedBy\n ? `attribute \"${key}\" removed — replaced by \"${prevAttr.replacedBy}\"`\n : `attribute \"${key}\" was removed`,\n });\n continue;\n }\n diffAttribute(diff, span, key, prevAttr, nextAttr);\n }\n for (const key of Object.keys(next)) {\n if (!prev[key]) {\n const added = next[key];\n // Always `attribute_added` (the event is \"new attribute\"); severity rides\n // on `kind` — a new *required* attribute breaks existing producers.\n push(diff, {\n kind: added.required ? 'breaking' : 'additive',\n type: 'attribute_added',\n span,\n attribute: key,\n message: added.required\n ? `new required attribute \"${key}\" added`\n : `new attribute \"${key}\" added`,\n });\n }\n }\n}\n\n/**\n * Diff two snapshots, classifying every change. The `breaking` array is what a\n * CI gate keys off; `hasBreakingChanges()` is the convenience predicate.\n */\nexport function diffSnapshots(\n previous: ContractSnapshot,\n next: ContractSnapshot,\n): SnapshotDiff {\n const diff: SnapshotDiff = {\n service: next.service,\n previousVersion: previous.version,\n nextVersion: next.version,\n breaking: [],\n additive: [],\n neutral: [],\n };\n\n diffAttributeMaps(\n diff,\n '*',\n previous.commonAttributes,\n next.commonAttributes,\n );\n\n for (const [name, prevSpan] of Object.entries(previous.spans)) {\n const nextSpan = next.spans[name];\n if (!nextSpan) {\n push(diff, {\n kind: 'breaking',\n type: 'span_removed',\n span: name,\n message: `span \"${name}\" was removed`,\n });\n continue;\n }\n diffAttributeMaps(diff, name, prevSpan.attributes, nextSpan.attributes);\n }\n for (const name of Object.keys(next.spans)) {\n if (!previous.spans[name]) {\n push(diff, {\n kind: 'additive',\n type: 'span_added',\n span: name,\n message: `new span \"${name}\" added`,\n });\n }\n }\n\n return diff;\n}\n\n/** `true` when the diff contains at least one breaking change. */\nexport function hasBreakingChanges(diff: SnapshotDiff): boolean {\n return diff.breaking.length > 0;\n}\n\n/** Markdown rendering of a diff — for CI logs and PR comments. */\nexport function formatDiff(diff: SnapshotDiff): string {\n const lines: string[] = [\n `# Telemetry contract diff: ${diff.service} ${diff.previousVersion} → ${diff.nextVersion}`,\n '',\n ];\n const section = (title: string, changes: SnapshotChange[]) => {\n if (changes.length === 0) return;\n lines.push(`## ${title} (${changes.length})`, '');\n for (const c of changes) {\n const where = c.attribute\n ? `\\`${c.span}.${c.attribute}\\``\n : `\\`${c.span}\\``;\n lines.push(`- ${where}: ${c.message}`);\n }\n lines.push('');\n };\n section('💥 Breaking', diff.breaking);\n section('➕ Additive', diff.additive);\n section('• Neutral', diff.neutral);\n if (\n diff.breaking.length === 0 &&\n diff.additive.length === 0 &&\n diff.neutral.length === 0\n ) {\n lines.push('No changes to the telemetry contract.', '');\n }\n return lines.join('\\n');\n}\n"],"mappings":";;;;;;AAoDA,MAAM,wBAGF;CACF,wBAAwB;EAAE,MAAM;EAAY,MAAM;CAAuB;CACzE,sBAAsB;EAAE,MAAM;EAAY,MAAM;CAAa;CAC7D,wBAAwB;EAAE,MAAM;EAAW,MAAM;CAAqB;CACtE,4BAA4B;EAAE,MAAM;EAAY,MAAM;CAAa;CACnE,sBAAsB;EAAE,MAAM;EAAW,MAAM;CAAqB;CACpE,4BAA4B;EAC1B,MAAM;EACN,MAAM;CACR;AACF;AAEA,SAAS,iBACP,MACA,WACA,MACA,MACQ;CACR,IAAI,SAAS,cACX,OAAO,cAAc,UAAU,kBAAkB,KAAK,aAAa,UAAU,KAAK,WAAW,MAAM;CAErG,IAAI,SAAS,wBACX,OAAO,cAAc,UAAU,yBAAyB,KAAK,UAAU,KAAK,KAAK;CAEnF,OAAO,cAAc,UAAU,aAAa,KAAK,UAAU,KAAK,KAAK;AACvE;AAEA,SAAS,KAAK,MAAoB,QAA8B;CAC9D,IAAI,OAAO,SAAS,YAAY,KAAK,SAAS,KAAK,MAAM;MACpD,IAAI,OAAO,SAAS,YAAY,KAAK,SAAS,KAAK,MAAM;MACzD,KAAK,QAAQ,KAAK,MAAM;AAC/B;AAEA,SAAS,cACP,MACA,MACA,WACA,MACA,MACM;CACN,IAAI,KAAK,SAAS,KAAK,MACrB,KAAK,MAAM;EACT,MAAM;EACN,MAAM;EACN;EACA;EACA,SAAS,cAAc,UAAU,iBAAiB,KAAK,KAAK,KAAK,KAAK;CACxE,CAAC;CAGH,IAAI,CAAC,KAAK,YAAY,KAAK,UACzB,KAAK,MAAM;EACT,MAAM;EACN,MAAM;EACN;EACA;EACA,SAAS,cAAc,UAAU;CACnC,CAAC;MACI,I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EAAE;EAChD,KAAK,MAAM,KAAK,SAAS;GACvB,MAAM,QAAQ,EAAE,YACZ,KAAK,EAAE,KAAK,GAAG,EAAE,UAAU,MAC3B,KAAK,EAAE,KAAK;GAChB,MAAM,KAAK,KAAK,MAAM,IAAI,EAAE,SAAS;EACvC;EACA,MAAM,KAAK,EAAE;CACf;CACA,QAAQ,eAAe,KAAK,QAAQ;CACpC,QAAQ,cAAc,KAAK,QAAQ;CACnC,QAAQ,aAAa,KAAK,OAAO;CACjC,IACE,KAAK,SAAS,WAAW,KACzB,KAAK,SAAS,WAAW,KACzB,KAAK,QAAQ,WAAW,GAExB,MAAM,KAAK,yCAAyC,EAAE;CAExD,OAAO,MAAM,KAAK,IAAI;AACxB"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.cjs","names":["defineContract"],"sources":["../src/redaction.ts","../src/contracts/agent-security.ts"],"sourcesContent":["/**\n * Cardinality posture helpers.\n *\n * The old cardinality rule — \"keep unique-value counts down\" — was a constraint\n * invented because dashboards have pixels and a graph with 10k series is\n * unreadable to a human. An agent does not look at the graph; it reads the\n * spans. A high-cardinality field (the user id, the sender domain, the request\n * id) is then the single most useful attribute on a trace when the agent is\n * chasing one specific failure.\n *\n * So the contract lets you mark attributes `highCardinality: true` as a\n * deliberate signal, and this module turns that into a *protect list*: the keys\n * a redactor or span-name normalizer must NOT strip, even when an aggressive\n * default would otherwise drop them.\n */\n\nimport type { TelemetryContract } from './contract.js';\n\n/**\n * Every attribute key in the contract flagged `highCardinality: true`, across\n * both common and per-span attributes. Feed this into a redaction/normalization\n * allow-list so the fields most useful to an agent reader survive.\n *\n * @example\n * ```ts\n * import { init } from 'autotel';\n * import { highCardinalityKeys } from 'autotel-schema';\n * import { contract } from './telemetry.contract';\n *\n * init({\n * service: 'checkout',\n * // keep user.id / request.id intact even under the strict redactor\n * attributeRedactor: { allowKeys: highCardinalityKeys(contract), preset: 'strict' },\n * });\n * ```\n */\nexport function highCardinalityKeys(contract: TelemetryContract): string[] {\n const keys = new Set<string>();\n for (const [key, spec] of Object.entries(contract.commonAttributes ?? {})) {\n if (spec.highCardinality) keys.add(key);\n }\n for (const spanSpec of Object.values(contract.spans)) {\n for (const [key, spec] of Object.entries(spanSpec.attributes ?? {})) {\n if (spec.highCardinality) keys.add(key);\n }\n }\n return [...keys].toSorted();\n}\n\n/**\n * Predicate form of {@link highCardinalityKeys} — `true` when `key` is declared\n * high-cardinality anywhere in the contract. Useful inside a custom\n * `spanNameNormalizer` or redactor callback.\n */\nexport function isHighCardinalityKey(\n contract: TelemetryContract,\n key: string,\n): boolean {\n if (contract.commonAttributes?.[key]?.highCardinality) return true;\n for (const spanSpec of Object.values(contract.spans)) {\n if (spanSpec.attributes?.[key]?.highCardinality) return true;\n }\n return false;\n}\n","import { defineContract } from '../contract.js';\n\nconst stringAttr = { type: 'string' as const };\nconst boolAttr = { type: 'boolean' as const };\nconst numberAttr = { type: 'number' as const };\nconst stringArrayAttr = { type: 'string[]' as const };\n\n/**\n * Published telemetry contract for Google SAIF-aligned agent security observability.\n * Span names are illustrative — attributes are the stable surface under validation.\n */\nexport const AGENT_SECURITY_TELEMETRY_CONTRACT = defineContract({\n service: 'autotel-agent-security',\n version: '1.0.0',\n commonAttributes: {\n 'autotel.agent': {\n ...boolAttr,\n required: false,\n description: 'Agent audit marker',\n },\n 'agent.controller.id': {\n ...stringAttr,\n highCardinality: true,\n description: 'Hashed controlling human user id',\n },\n 'agent.input.provenance': {\n ...stringAttr,\n enum: [\n 'user_direct',\n 'user_voice',\n 'rag',\n 'memory',\n 'tool_result',\n 'external_untrusted',\n ],\n },\n 'agent.action.risk_class': {\n ...stringAttr,\n enum: [\n 'read',\n 'write',\n 'destructive',\n 'financial',\n 'exfiltration_capable',\n ],\n },\n 'agent.consent.required': { ...boolAttr },\n 'agent.consent.outcome': {\n ...stringAttr,\n enum: ['approved', 'denied', 'timeout', 'revoked'],\n },\n 'agent.scope.active': { ...stringArrayAttr },\n 'agent.memory.operation': {\n ...stringAttr,\n enum: ['read', 'write', 'delete', 'search'],\n },\n 'agent.memory.isolation_key': { ...stringAttr, highCardinality: true },\n 'agent.plan.step_index': { ...numberAttr },\n 'agent.plan.tool_intents': { ...stringArrayAttr },\n 'agent.plan.risk.verdict': {\n ...stringAttr,\n enum: ['low', 'medium', 'high', 'critical'],\n },\n 'agent.plan.risk.score': { ...numberAttr },\n 'agent.plan.risk.categories': { ...stringArrayAttr },\n 'policy.decision': {\n ...stringAttr,\n enum: ['permit', 'deny', 'challenge', 'observe', 'error'],\n },\n 'tool.input_hash': { ...stringAttr },\n 'tool.output_hash': { ...stringAttr },\n 'mcp.tool.destructive': { ...boolAttr },\n 'mcp.tool.untrusted_content': { ...boolAttr },\n 'mcp.security.injection.verdict': {\n ...stringAttr,\n enum: ['clean', 'suspicious', 'malicious'],\n },\n 'security.event': { ...stringAttr },\n 'security.category': { ...stringAttr },\n 'security.outcome': { ...stringAttr },\n 'security.severity': {\n ...stringAttr,\n enum: ['info', 'warning', 'error', 'critical'],\n },\n },\n spans: {\n 'agent.action': {\n description: 'Scoped agent action or tool call with audit metadata',\n attributes: {\n 'agent.id': { ...stringAttr, required: true },\n 'tool.name': { ...stringAttr },\n },\n },\n 'tools/call': {\n description: 'MCP tool invocation with boundary security signals',\n attributes: {\n 'mcp.tool.name': { ...stringAttr, required: true },\n },\n },\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAoCA,SAAgB,oBAAoB,UAAuC;CACzE,MAAM,uBAAO,IAAI,IAAY;CAC7B,KAAK,MAAM,CAAC,KAAK,SAAS,OAAO,QAAQ,SAAS,oBAAoB,CAAC,CAAC,GACtE,IAAI,KAAK,iBAAiB,KAAK,IAAI,GAAG;CAExC,KAAK,MAAM,YAAY,OAAO,OAAO,SAAS,KAAK,GACjD,KAAK,MAAM,CAAC,KAAK,SAAS,OAAO,QAAQ,SAAS,cAAc,CAAC,CAAC,GAChE,IAAI,KAAK,iBAAiB,KAAK,IAAI,GAAG;CAG1C,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GAAG;GACH,MAAM;IAAC;IAAU;IAAQ;IAAa;IAAW;GAAO;EAC1D;EACA,mBAAmB,EAAE,GAAG,WAAW;EACnC,oBAAoB,EAAE,GAAG,WAAW;EACpC,wBAAwB,EAAE,GAAG,SAAS;EACtC,8BAA8B,EAAE,GAAG,SAAS;EAC5C,kCAAkC;GAChC,GAAG;GACH,MAAM;IAAC;IAAS;IAAc;GAAW;EAC3C;EACA,kBAAkB,EAAE,GAAG,WAAW;EAClC,qBAAqB,EAAE,GAAG,WAAW;EACrC,oBAAoB,EAAE,GAAG,WAAW;EACpC,qBAAqB;GACnB,GAAG;GACH,MAAM;IAAC;IAAQ;IAAW;IAAS;GAAU;EAC/C;CACF;CACA,OAAO;EACL,gBAAgB;GACd,aAAa;GACb,YAAY;IACV,YAAY;KAAE,GAAG;KAAY,UAAU;IAAK;IAC5C,aAAa,EAAE,GAAG,WAAW;GAC/B;EACF;EACA,cAAc;GACZ,aAAa;GACb,YAAY,EACV,iBAAiB;IAAE,GAAG;IAAY,UAAU;GAAK,EACnD;EACF;CACF;AACF,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.cts","names":[],"sources":["../src/redaction.ts","../src/contracts/agent-security.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;iBAoCgB,oBAAoB,UAAU;;;;;;iBAkB9B,qBACd,UAAU,mBACV;;;;;;;cC7CW,mCAAA"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/redaction.ts","../src/contracts/agent-security.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;iBAoCgB,oBAAoB,UAAU;;;;;;iBAkB9B,qBACd,UAAU,mBACV;;;;;;;cC7CW,mCAAA"}
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/redaction.ts","../src/contracts/agent-security.ts"],"sourcesContent":["/**\n * Cardinality posture helpers.\n *\n * The old cardinality rule — \"keep unique-value counts down\" — was a constraint\n * invented because dashboards have pixels and a graph with 10k series is\n * unreadable to a human. An agent does not look at the graph; it reads the\n * spans. A high-cardinality field (the user id, the sender domain, the request\n * id) is then the single most useful attribute on a trace when the agent is\n * chasing one specific failure.\n *\n * So the contract lets you mark attributes `highCardinality: true` as a\n * deliberate signal, and this module turns that into a *protect list*: the keys\n * a redactor or span-name normalizer must NOT strip, even when an aggressive\n * default would otherwise drop them.\n */\n\nimport type { TelemetryContract } from './contract.js';\n\n/**\n * Every attribute key in the contract flagged `highCardinality: true`, across\n * both common and per-span attributes. Feed this into a redaction/normalization\n * allow-list so the fields most useful to an agent reader survive.\n *\n * @example\n * ```ts\n * import { init } from 'autotel';\n * import { highCardinalityKeys } from 'autotel-schema';\n * import { contract } from './telemetry.contract';\n *\n * init({\n * service: 'checkout',\n * // keep user.id / request.id intact even under the strict redactor\n * attributeRedactor: { allowKeys: highCardinalityKeys(contract), preset: 'strict' },\n * });\n * ```\n */\nexport function highCardinalityKeys(contract: TelemetryContract): string[] {\n const keys = new Set<string>();\n for (const [key, spec] of Object.entries(contract.commonAttributes ?? {})) {\n if (spec.highCardinality) keys.add(key);\n }\n for (const spanSpec of Object.values(contract.spans)) {\n for (const [key, spec] of Object.entries(spanSpec.attributes ?? {})) {\n if (spec.highCardinality) keys.add(key);\n }\n }\n return [...keys].toSorted();\n}\n\n/**\n * Predicate form of {@link highCardinalityKeys} — `true` when `key` is declared\n * high-cardinality anywhere in the contract. Useful inside a custom\n * `spanNameNormalizer` or redactor callback.\n */\nexport function isHighCardinalityKey(\n contract: TelemetryContract,\n key: string,\n): boolean {\n if (contract.commonAttributes?.[key]?.highCardinality) return true;\n for (const spanSpec of Object.values(contract.spans)) {\n if (spanSpec.attributes?.[key]?.highCardinality) return true;\n }\n return false;\n}\n","import { defineContract } from '../contract.js';\n\nconst stringAttr = { type: 'string' as const };\nconst boolAttr = { type: 'boolean' as const };\nconst numberAttr = { type: 'number' as const };\nconst stringArrayAttr = { type: 'string[]' as const };\n\n/**\n * Published telemetry contract for Google SAIF-aligned agent security observability.\n * Span names are illustrative — attributes are the stable surface under validation.\n */\nexport const AGENT_SECURITY_TELEMETRY_CONTRACT = defineContract({\n service: 'autotel-agent-security',\n version: '1.0.0',\n commonAttributes: {\n 'autotel.agent': {\n ...boolAttr,\n required: false,\n description: 'Agent audit marker',\n },\n 'agent.controller.id': {\n ...stringAttr,\n highCardinality: true,\n description: 'Hashed controlling human user id',\n },\n 'agent.input.provenance': {\n ...stringAttr,\n enum: [\n 'user_direct',\n 'user_voice',\n 'rag',\n 'memory',\n 'tool_result',\n 'external_untrusted',\n ],\n },\n 'agent.action.risk_class': {\n ...stringAttr,\n enum: [\n 'read',\n 'write',\n 'destructive',\n 'financial',\n 'exfiltration_capable',\n ],\n },\n 'agent.consent.required': { ...boolAttr },\n 'agent.consent.outcome': {\n ...stringAttr,\n enum: ['approved', 'denied', 'timeout', 'revoked'],\n },\n 'agent.scope.active': { ...stringArrayAttr },\n 'agent.memory.operation': {\n ...stringAttr,\n enum: ['read', 'write', 'delete', 'search'],\n },\n 'agent.memory.isolation_key': { ...stringAttr, highCardinality: true },\n 'agent.plan.step_index': { ...numberAttr },\n 'agent.plan.tool_intents': { ...stringArrayAttr },\n 'agent.plan.risk.verdict': {\n ...stringAttr,\n enum: ['low', 'medium', 'high', 'critical'],\n },\n 'agent.plan.risk.score': { ...numberAttr },\n 'agent.plan.risk.categories': { ...stringArrayAttr },\n 'policy.decision': {\n ...stringAttr,\n enum: ['permit', 'deny', 'challenge', 'observe', 'error'],\n },\n 'tool.input_hash': { ...stringAttr },\n 'tool.output_hash': { ...stringAttr },\n 'mcp.tool.destructive': { ...boolAttr },\n 'mcp.tool.untrusted_content': { ...boolAttr },\n 'mcp.security.injection.verdict': {\n ...stringAttr,\n enum: ['clean', 'suspicious', 'malicious'],\n },\n 'security.event': { ...stringAttr },\n 'security.category': { ...stringAttr },\n 'security.outcome': { ...stringAttr },\n 'security.severity': {\n ...stringAttr,\n enum: ['info', 'warning', 'error', 'critical'],\n },\n },\n spans: {\n 'agent.action': {\n description: 'Scoped agent action or tool call with audit metadata',\n attributes: {\n 'agent.id': { ...stringAttr, required: true },\n 'tool.name': { ...stringAttr },\n },\n },\n 'tools/call': {\n description: 'MCP tool invocation with boundary security signals',\n attributes: {\n 'mcp.tool.name': { ...stringAttr, required: true },\n },\n },\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAoCA,SAAgB,oBAAoB,UAAuC;CACzE,MAAM,uBAAO,IAAI,IAAY;CAC7B,KAAK,MAAM,CAAC,KAAK,SAAS,OAAO,QAAQ,SAAS,oBAAoB,CAAC,CAAC,GACtE,IAAI,KAAK,iBAAiB,KAAK,IAAI,GAAG;CAExC,KAAK,MAAM,YAAY,OAAO,OAAO,SAAS,KAAK,GACjD,KAAK,MAAM,CAAC,KAAK,SAAS,OAAO,QAAQ,SAAS,cAAc,CAAC,CAAC,GAChE,IAAI,KAAK,iBAAiB,KAAK,IAAI,GAAG;CAG1C,OAAO,CAAC,GAAG,IAAI,CAAC,CAAC,SAAS;AAC5B;;;;;;AAOA,SAAgB,qBACd,UACA,KACS;CACT,IAAI,SAAS,mBAAmB,IAAI,EAAE,iBAAiB,OAAO;CAC9D,KAAK,MAAM,YAAY,OAAO,OAAO,SAAS,KAAK,GACjD,IAAI,SAAS,aAAa,IAAI,EAAE,iBAAiB,OAAO;CAE1D,OAAO;AACT;;;;AC7DA,MAAM,aAAa,EAAE,MAAM,SAAkB;AAC7C,MAAM,WAAW,EAAE,MAAM,UAAmB;AAC5C,MAAM,aAAa,EAAE,MAAM,SAAkB;AAC7C,MAAM,kBAAkB,EAAE,MAAM,WAAoB;;;;;AAMpD,MAAa,oCAAoC,eAAe;CAC9D,SAAS;CACT,SAAS;CACT,kBAAkB;EAChB,iBAAiB;GACf,GAAG;GACH,UAAU;GACV,aAAa;EACf;EACA,uBAAuB;GACrB,GAAG;GACH,iBAAiB;GACjB,aAAa;EACf;EACA,0BAA0B;GACxB,G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IAAE,GAAG;IAAY,UAAU;GAAK,EACnD;EACF;CACF;AACF,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"processor-BPp_DewZ.js","names":["assert"],"sources":["../src/scenario.ts","../src/contract.ts","../src/validate.ts","../src/processor.ts"],"sourcesContent":["/**\n * Scenario conformance — a flow-level contract checked against collected spans.\n *\n * Where {@link ./contract} declares the *surface* of your telemetry (span\n * names + attributes), a scenario declares the *behaviour* of one exercised\n * flow: which events must fire, how many times, in what parent/child\n * topology, and — critically — **when the observation is complete**, because\n * for an async flow a missing event and an event that has not fired *yet* are\n * indistinguishable without a completion boundary.\n *\n * Checking a scenario yields one of three outcomes, not two:\n *\n * - `conformant` — the boundary closed and the signature satisfied the contract\n * - `non-conformant` — required behaviour was missing or invalid (definitive)\n * - `incomplete` — the boundary did not close within the observation budget;\n * infrastructure slowness is *not* reported as behavioural regression\n *\n * Absence is definitive only after closure (closed-world semantics). Excess\n * is definitive immediately: a `max` cardinality violation or an unexpected\n * error span fails the check even while the flow is still open.\n *\n * Undeclared events are **additive**: reported in `result.additions`, never a\n * failure — improving instrumentation must not break CI.\n *\n * The span input shape is structurally compatible with `SerializedSpan` from\n * `autotel/test-span-collector`, so a test can feed a collector's output\n * straight in. Like the rest of this package the module is dependency-free —\n * usable from vitest, a deferred reconciliation job, or a CLI alike.\n *\n * @example\n * ```ts\n * const result = await checkScenario(\n * contract.scenarios!['transfer.accept'],\n * () => collector.peekTrace(traceId),\n * { name: 'transfer.accept' },\n * );\n * if (result.outcome === 'non-conformant') throw new Error(formatScenarioResult(result));\n * ```\n */\n\n/** A finished span/event as the scenario checker sees it. */\nexport interface ScenarioSpan {\n spanId: string;\n parentSpanId?: string;\n name: string;\n status: 'ok' | 'error' | 'unset';\n attributes?: Record<string, unknown>;\n /** Epoch ms. Optional — used by {@link proposeScenario} to suggest budgets. */\n startTimeMs?: number;\n durationMs?: number;\n}\n\n/** Canonical cardinality range. `max` omitted = unbounded. */\nexport interface Cardinality {\n min: number;\n max?: number;\n}\n\n/**\n * Parse a cardinality shorthand: `'exactly 1'`, `'at least 1'`, `'at most 3'`,\n * `'0..1'`, `'2..'`. A canonical {@link Cardinality} passes through.\n */\nexport function parseCardinality(input: string | Cardinality): Cardinality {\n if (typeof input !== 'string') {\n assert(\n Number.isInteger(input.min) && input.min >= 0,\n `cardinality min must be a non-negative integer, got ${input.min}`,\n );\n assert(\n input.max === undefined ||\n (Number.isInteger(input.max) && input.max >= input.min),\n `cardinality max must be >= min, got ${input.max}`,\n );\n return input;\n }\n const exact = /^exactly (\\d+)$/.exec(input);\n if (exact) return { min: Number(exact[1]), max: Number(exact[1]) };\n const atLeast = /^at least (\\d+)$/.exec(input);\n if (atLeast) return { min: Number(atLeast[1]) };\n const atMost = /^at most (\\d+)$/.exec(input);\n if (atMost) return { min: 0, max: Number(atMost[1]) };\n const range = /^(\\d+)\\.\\.(\\d*)$/.exec(input);\n if (range) {\n const min = Number(range[1]);\n const max = range[2] === '' ? undefined : Number(range[2]);\n assert(\n max === undefined || max >= min,\n `cardinality \"${input}\" has max < min`,\n );\n return { min, max };\n }\n throw new Error(\n `autotel-schema: unparseable cardinality \"${input}\" (expected \"exactly N\", \"at least N\", \"at most N\", or \"N..M\")`,\n );\n}\n\n/** Declaration for one event (span name) a scenario expects to observe. */\nexport interface ScenarioEventSpec {\n /** How many occurrences are permitted. Defaults to `'at least 1'`. */\n cardinality?: string | Cardinality;\n /**\n * Expected terminal status. Defaults to non-error: an `error` status on an\n * event not declared `status: 'error'` is a definitive violation.\n */\n status?: 'ok' | 'error';\n description?: string;\n}\n\n/**\n * How the observed phase of a scenario becomes complete. Every async\n * conformance check must declare this — it is what makes absence meaningful.\n *\n * `externally-reconciled` never closes in-process: the phase is verified\n * elsewhere (a deferred reconciliation job keyed by a durable business ID),\n * so an in-process check reports at most definitive violations, never absence.\n */\nexport type CompletionBoundary =\n | { mode: 'root-span-closed'; observationBudgetMs: number }\n | { mode: 'terminal-event'; event: string; observationBudgetMs: number }\n | { mode: 'externally-reconciled'; reconciliationDeadlineMs: number };\n\n/** The flow-level contract for one exercised scenario (or one phase of one). */\nexport interface ScenarioSpec {\n description?: string;\n /** When the observed phase is complete. See {@link CompletionBoundary}. */\n completion: CompletionBoundary;\n /** Events this scenario must (or may) observe, keyed by span name. */\n events: Record<string, ScenarioEventSpec>;\n /**\n * Required ancestor→descendant edges by span name. Ancestor — not immediate\n * parent — so a framework span inserted between the two does not break the\n * contract (canonicalisation: infrastructure spans are not behaviour).\n */\n edges?: ReadonlyArray<readonly [string, string]>;\n /** Edges that may appear but are not required. Documented, never enforced. */\n optionalEdges?: ReadonlyArray<readonly [string, string]>;\n}\n\nexport type ScenarioOutcome = 'conformant' | 'non-conformant' | 'incomplete';\n\nexport type ScenarioViolationCode =\n | 'missing_event'\n | 'cardinality_violation'\n | 'missing_edge'\n | 'unexpected_error';\n\n/** A definitive (breaking) discrepancy between observed spans and the scenario. */\nexport interface ScenarioViolation {\n code: ScenarioViolationCode;\n event?: string;\n edge?: readonly [string, string];\n message: string;\n}\n\n/** An additive observation — reported, never a failure. */\nexport interface ScenarioAddition {\n code: 'undeclared_event';\n event: string;\n count: number;\n message: string;\n}\n\nexport interface ScenarioResult {\n scenario: string;\n outcome: ScenarioOutcome;\n /** Whether the completion boundary closed within the observation window. */\n closed: boolean;\n violations: ScenarioViolation[];\n additions: ScenarioAddition[];\n /** The evaluated snapshot — assert business values on this in your test. */\n spans: ScenarioSpan[];\n}\n\nfunction assert(condition: unknown, message: string): asserts condition {\n if (!condition) {\n throw new Error(`autotel-schema: ${message}`);\n }\n}\n\nconst COMPLETION_MODES = [\n 'root-span-closed',\n 'terminal-event',\n 'externally-reconciled',\n] as const;\n\n/**\n * Structural validation for one scenario declaration. Called by\n * `defineContract()` so a malformed scenario throws at module load.\n */\nexport function validateScenarioSpec(name: string, spec: ScenarioSpec): void {\n const scope = `scenario \"${name}\"`;\n assert(\n spec.completion && typeof spec.completion === 'object',\n `${scope} must declare a completion boundary`,\n );\n assert(\n (COMPLETION_MODES as readonly string[]).includes(spec.completion.mode),\n `${scope} has invalid completion mode \"${(spec.completion as { mode: string }).mode}\"`,\n );\n const budget =\n spec.completion.mode === 'externally-reconciled'\n ? spec.completion.reconciliationDeadlineMs\n : spec.completion.observationBudgetMs;\n assert(\n typeof budget === 'number' && Number.isFinite(budget) && budget > 0,\n `${scope} completion budget must be a positive number of milliseconds`,\n );\n switch (spec.completion.mode) {\n case 'terminal-event':\n assert(\n typeof spec.completion.event === 'string' &&\n spec.completion.event.length > 0,\n `${scope} terminal-event completion must declare a non-empty event`,\n );\n break;\n }\n assert(\n spec.events &&\n typeof spec.events === 'object' &&\n Object.keys(spec.events).length > 0,\n `${scope} must declare at least one event`,\n );\n for (const [event, eventSpec] of Object.entries(spec.events)) {\n if (eventSpec.cardinality !== undefined) {\n try {\n parseCardinality(eventSpec.cardinality);\n } catch (error) {\n throw new Error(\n `autotel-schema: ${scope} event \"${event}\": ${(error as Error).message}`,\n );\n }\n }\n if (eventSpec.status !== undefined) {\n assert(\n eventSpec.status === 'ok' || eventSpec.status === 'error',\n `${scope} event \"${event}\" has invalid status \"${eventSpec.status}\"`,\n );\n }\n }\n for (const [from, to] of [\n ...(spec.edges ?? []),\n ...(spec.optionalEdges ?? []),\n ]) {\n assert(\n from in spec.events && to in spec.events,\n `${scope} edge [\"${from}\", \"${to}\"] references an undeclared event — declare both endpoints in events`,\n );\n }\n}\n\n/** Whether the scenario's completion boundary has closed for these spans. */\nexport function isScenarioClosed(\n spec: ScenarioSpec,\n spans: readonly ScenarioSpan[],\n): boolean {\n const { completion } = spec;\n switch (completion.mode) {\n case 'externally-reconciled':\n return false;\n case 'root-span-closed':\n // Only finished spans reach a collector, so a present root = a closed root.\n return spans.some((s) => !s.parentSpanId);\n case 'terminal-event':\n return spans.some((s) => s.name === completion.event);\n }\n}\n\n/** True when `span` has an ancestor named `ancestorName` within `byId`. */\nfunction hasAncestorNamed(\n span: ScenarioSpan,\n ancestorName: string,\n byId: ReadonlyMap<string, ScenarioSpan>,\n): boolean {\n const seen = new Set<string>();\n let parentId = span.parentSpanId;\n while (parentId && !seen.has(parentId)) {\n seen.add(parentId);\n const parent = byId.get(parentId);\n if (!parent) return false;\n if (parent.name === ancestorName) return true;\n parentId = parent.parentSpanId;\n }\n return false;\n}\n\nexport interface EvaluateScenarioOptions {\n /** Name used in the result/messages. Defaults to `'scenario'`. */\n name?: string;\n /** Override closure detection (e.g. the poller already knows). */\n closed?: boolean;\n}\n\n/**\n * Pure three-state evaluation of collected spans against a scenario.\n *\n * Definitive at any time (no closure needed): an unexpected error status, a\n * `max` cardinality exceeded. Meaningful only after closure: a missing event,\n * a `min` cardinality not reached, a missing required edge.\n */\nexport function evaluateScenario(\n spec: ScenarioSpec,\n spans: readonly ScenarioSpan[],\n options?: EvaluateScenarioOptions,\n): ScenarioResult {\n const name = options?.name ?? 'scenario';\n const closed = options?.closed ?? isScenarioClosed(spec, spans);\n const violations: ScenarioViolation[] = [];\n const additions: ScenarioAddition[] = [];\n\n const countByName = new Map<string, number>();\n for (const span of spans) {\n countByName.set(span.name, (countByName.get(span.name) ?? 0) + 1);\n }\n\n // Unexpected error status — definitive even while the flow is open.\n for (const span of spans) {\n if (span.status === 'error' && spec.events[span.name]?.status !== 'error') {\n violations.push({\n code: 'unexpected_error',\n event: span.name,\n message: `\"${span.name}\" ended with status error, which the scenario does not declare`,\n });\n }\n }\n\n for (const [event, eventSpec] of Object.entries(spec.events)) {\n const { min, max } = parseCardinality(eventSpec.cardinality ?? { min: 1 });\n const count = countByName.get(event) ?? 0;\n\n // Excess is definitive immediately.\n if (max !== undefined && count > max) {\n violations.push({\n code: 'cardinality_violation',\n event,\n message: `\"${event}\" observed ${count}×, contract allows at most ${max}`,\n });\n }\n // Absence is definitive only after closure.\n if (closed && count < min) {\n violations.push({\n code: count === 0 ? 'missing_event' : 'cardinality_violation',\n event,\n message:\n count === 0\n ? `\"${event}\" was not observed and the completion boundary has closed`\n : `\"${event}\" observed ${count}×, contract requires at least ${min}`,\n });\n }\n }\n\n if (closed) {\n const byId = new Map<string, ScenarioSpan>();\n for (const span of spans) byId.set(span.spanId, span);\n for (const [from, to] of spec.edges ?? []) {\n const satisfied = spans.some(\n (s) => s.name === to && hasAncestorNamed(s, from, byId),\n );\n if (!satisfied) {\n violations.push({\n code: 'missing_edge',\n edge: [from, to],\n message: `no \"${to}\" span has ancestor \"${from}\"`,\n });\n }\n }\n }\n\n for (const [event, count] of [...countByName.entries()].toSorted()) {\n if (!(event in spec.events)) {\n additions.push({\n code: 'undeclared_event',\n event,\n count,\n message: `\"${event}\" observed ${count}× but not declared — additive, consider adding it to the scenario`,\n });\n }\n }\n\n return {\n scenario: name,\n outcome:\n violations.length > 0\n ? 'non-conformant'\n : closed\n ? 'conformant'\n : 'incomplete',\n closed,\n violations,\n additions,\n spans: [...spans],\n };\n}\n\nexport interface CheckScenarioOptions {\n /** Name used in the result/messages. Defaults to `'scenario'`. */\n name?: string;\n /** Poll interval while waiting for closure. Default 25ms. */\n pollIntervalMs?: number;\n /** Override the boundary's observation budget (how long the checker waits). */\n budgetMs?: number;\n}\n\n/**\n * Poll `getSpans` until the scenario's completion boundary closes, a\n * definitive violation appears (fail fast), or the observation budget is\n * spent — then evaluate.\n *\n * The observation budget bounds how long *this checker* waits; it is not a\n * statement that the operation is allowed to take that long. Express a\n * business deadline as its own assertion on the returned spans.\n *\n * An `externally-reconciled` boundary never closes in-process: the check\n * evaluates the current snapshot once and reports `incomplete` unless a\n * definitive violation is already present.\n */\nexport async function checkScenario(\n spec: ScenarioSpec,\n getSpans: () => readonly ScenarioSpan[] | Promise<readonly ScenarioSpan[]>,\n options?: CheckScenarioOptions,\n): Promise<ScenarioResult> {\n const name = options?.name;\n if (spec.completion.mode === 'externally-reconciled') {\n return evaluateScenario(spec, await getSpans(), { name });\n }\n const budgetMs = options?.budgetMs ?? spec.completion.observationBudgetMs;\n const pollIntervalMs = options?.pollIntervalMs ?? 25;\n assert(\n Number.isFinite(budgetMs) && budgetMs > 0,\n 'checkScenario budgetMs must be a positive number of milliseconds',\n );\n assert(\n Number.isFinite(pollIntervalMs) && pollIntervalMs >= 0,\n 'checkScenario pollIntervalMs must be a non-negative number of milliseconds',\n );\n const deadline = Date.now() + budgetMs;\n let lastResult = evaluateScenario(spec, [], { name });\n\n for (;;) {\n const remainingMs = deadline - Date.now();\n if (remainingMs <= 0) return lastResult;\n\n let timeout: ReturnType<typeof setTimeout> | undefined;\n let next:\n { kind: 'spans'; spans: readonly ScenarioSpan[] } | { kind: 'timeout' };\n try {\n next = await Promise.race([\n Promise.resolve()\n .then(getSpans)\n .then((spans) => ({ kind: 'spans' as const, spans })),\n new Promise<{ kind: 'timeout' }>((resolve) => {\n timeout = setTimeout(() => resolve({ kind: 'timeout' }), remainingMs);\n }),\n ]);\n } finally {\n if (timeout !== undefined) clearTimeout(timeout);\n }\n if (next.kind === 'timeout') return lastResult;\n\n const { spans } = next;\n const result = evaluateScenario(spec, spans, { name });\n lastResult = result;\n if (result.closed || result.outcome === 'non-conformant') return result;\n const waitMs = Math.min(pollIntervalMs, deadline - Date.now());\n if (waitMs <= 0) return result; // incomplete\n await new Promise((resolve) => setTimeout(resolve, waitMs));\n }\n}\n\n/** Human-readable summary of a scenario result, for assertion messages. */\nexport function formatScenarioResult(result: ScenarioResult): string {\n const lines = [\n `scenario \"${result.scenario}\": ${result.outcome}${result.closed ? '' : ' (completion boundary did not close)'}`,\n ];\n for (const v of result.violations) lines.push(` ✗ ${v.message}`);\n for (const a of result.additions) lines.push(` + ${a.message}`);\n return lines.join('\\n');\n}\n\nexport interface ScenarioProposal {\n scenario: ScenarioSpec;\n /** Review annotations — what was observed and what to double-check. */\n notes: string[];\n}\n\n/**\n * Draft a scenario contract from repeated controlled runs (record → propose →\n * commit). Events stable across every run become required with their observed\n * cardinality; variable ones get a range and a review note. The draft is a\n * starting point for human curation, not a finished contract.\n */\nexport function proposeScenario(\n runs: ReadonlyArray<ReadonlyArray<ScenarioSpan>>,\n options?: { name?: string },\n): ScenarioProposal {\n assert(runs.length > 0, 'proposeScenario needs at least one recorded run');\n for (const [index, run] of runs.entries()) {\n assert(\n run.length > 0,\n `proposeScenario run ${index + 1} has no recorded spans`,\n );\n }\n const name = options?.name ?? 'scenario';\n const notes: string[] = [];\n const total = runs.length;\n\n // Occurrence counts per event name per run (0 when absent).\n const names = new Set<string>();\n const countsPerRun: Array<Map<string, number>> = runs.map((run) => {\n const counts = new Map<string, number>();\n for (const span of run) {\n names.add(span.name);\n counts.set(span.name, (counts.get(span.name) ?? 0) + 1);\n }\n return counts;\n });\n\n const events: Record<string, ScenarioEventSpec> = {};\n for (const event of [...names].toSorted()) {\n const counts = countsPerRun.map((c) => c.get(event) ?? 0);\n const min = Math.min(...counts);\n const max = Math.max(...counts);\n const seenIn = counts.filter((c) => c > 0).length;\n events[event] = {\n cardinality: min === max ? `exactly ${min}` : { min, max },\n };\n notes.push(\n min === max\n ? `${event}: exactly ${min} (${seenIn}/${total} runs)`\n : `${event}: ${min}..${max} (${seenIn}/${total} runs) — review: variable`,\n );\n if (\n runs.some((run) =>\n run.some((s) => s.name === event && s.status === 'error'),\n )\n ) {\n notes.push(`${event}: observed with status error — review: expected?`);\n }\n }\n\n // Immediate parent→child name pairs; present in every run → required edge.\n const edgeRuns = new Map<string, number>();\n for (const run of runs) {\n const byId = new Map(run.map((s) => [s.spanId, s]));\n const pairs = new Set<string>();\n for (const span of run) {\n const parent = span.parentSpanId\n ? byId.get(span.parentSpanId)\n : undefined;\n if (parent) pairs.add(`${parent.name}\u0000${span.name}`);\n }\n for (const pair of pairs) edgeRuns.set(pair, (edgeRuns.get(pair) ?? 0) + 1);\n }\n const edges: Array<readonly [string, string]> = [];\n const optionalEdges: Array<readonly [string, string]> = [];\n for (const [pair, seen] of [...edgeRuns.entries()].toSorted()) {\n const [from, to] = pair.split('\u0000') as [string, string];\n if (seen === total) {\n edges.push([from, to]);\n } else {\n optionalEdges.push([from, to]);\n notes.push(\n `edge ${from} → ${to}: ${seen}/${total} runs — proposed optional`,\n );\n }\n }\n\n // Completion: consistent last-ending span → terminal event; else root closure.\n // Budget: 3× the slowest observed makespan when timing data is present.\n let completion: CompletionBoundary;\n const lastNames = new Set<string>();\n let maxMakespanMs = 0;\n let hasTiming = true;\n for (const run of runs) {\n let last: ScenarioSpan | undefined;\n let start = Number.POSITIVE_INFINITY;\n let end = 0;\n for (const span of run) {\n if (span.startTimeMs === undefined || span.durationMs === undefined) {\n hasTiming = false;\n break;\n }\n const spanEnd = span.startTimeMs + span.durationMs;\n start = Math.min(start, span.startTimeMs);\n if (spanEnd >= end) {\n end = spanEnd;\n last = span;\n }\n }\n if (!hasTiming) break;\n if (last) lastNames.add(last.name);\n maxMakespanMs = Math.max(maxMakespanMs, end - start);\n }\n const observationBudgetMs = hasTiming\n ? Math.max(1000, Math.ceil(maxMakespanMs * 3))\n : 30_000;\n if (hasTiming && lastNames.size === 1) {\n const [event] = [...lastNames] as [string];\n completion = { mode: 'terminal-event', event, observationBudgetMs };\n notes.push(\n `completion: terminal-event \"${event}\" (last to end in all ${total} runs), budget ${observationBudgetMs}ms (3× slowest observed run)`,\n );\n } else {\n completion = { mode: 'root-span-closed', observationBudgetMs };\n notes.push(\n hasTiming\n ? `completion: root-span-closed (last-ending span varies: ${[...lastNames].toSorted().join(', ')}), budget ${observationBudgetMs}ms`\n : `completion: root-span-closed, budget ${observationBudgetMs}ms (default — no timing data recorded)`,\n );\n }\n\n const scenario: ScenarioSpec = {\n description: `Proposed from ${total} recorded run${total === 1 ? '' : 's'} of ${name} — review before committing`,\n completion,\n events,\n ...(edges.length > 0 ? { edges } : {}),\n ...(optionalEdges.length > 0 ? { optionalEdges } : {}),\n };\n validateScenarioSpec(name, scenario);\n return { scenario, notes };\n}\n","/**\n * Telemetry contract model.\n *\n * The premise: when the primary reader of your telemetry is an agent, your\n * span names and attribute keys are a **public API**. Renaming `fast_path_hit`\n * to `fast_path_taken` in a refactor PR silently breaks every prompt that\n * mentions it — there is no compiler to catch it, because to the compiler these\n * are just strings in a JSON blob.\n *\n * `defineContract()` makes that surface explicit, typed, and versionable: you\n * declare which spans your service emits and which attributes live on them,\n * then validate live spans against it ({@link ./validate}) and diff it across\n * commits to catch breaking changes before they ship ({@link ./diff}).\n *\n * This module is dependency-free and side-effect-free by design — safe to\n * import anywhere (browser, edge, CLI) without pulling in the OpenTelemetry SDK.\n */\n\nimport { validateScenarioSpec, type ScenarioSpec } from './scenario.js';\n\n/** Scalar and array attribute types permitted on a span (OTLP value shapes). */\nexport type AttributeType =\n 'string' | 'number' | 'boolean' | 'string[]' | 'number[]' | 'boolean[]';\n\nexport const ATTRIBUTE_TYPES: readonly AttributeType[] = [\n 'string',\n 'number',\n 'boolean',\n 'string[]',\n 'number[]',\n 'boolean[]',\n];\n\n/**\n * Lifecycle of a span or attribute, mirroring how the OpenTelemetry semantic\n * conventions stage their own surface. `stable` is a promise to agent readers\n * that the name will not change without a major contract bump.\n */\nexport type Stability = 'stable' | 'experimental' | 'deprecated';\n\nexport const STABILITIES: readonly Stability[] = [\n 'stable',\n 'experimental',\n 'deprecated',\n];\n\n/** Declaration for a single attribute key on a span. */\nexport interface AttributeSpec {\n /** OTLP value shape. Validated at runtime against the emitted value. */\n type: AttributeType;\n /** Lifecycle stage. Defaults to `stable`. */\n stability?: Stability;\n /** When `true`, the attribute must be present on every matching span. */\n required?: boolean;\n /** Human/agent-facing description of what the attribute means. */\n description?: string;\n /**\n * Marks an attribute as intentionally high-cardinality (user id, sender\n * domain, request id). For an agent reader these are the single most useful\n * fields on a trace, so {@link ./redaction.highCardinalityKeys} surfaces them\n * as a *protect* list — telling redactors/normalizers NOT to strip them.\n */\n highCardinality?: boolean;\n /** Closed set of permitted values. Reported as `enum_violation` if exceeded. */\n enum?: readonly (string | number)[];\n /** Set when `stability: 'deprecated'`; explains what to use instead. */\n replacedBy?: string;\n /** Free-text note shown alongside deprecation warnings. */\n deprecatedReason?: string;\n}\n\n/** Declaration for a single span name your service emits. */\nexport interface SpanSpec {\n /** Human/agent-facing description of when this span is produced. */\n description?: string;\n /** Lifecycle stage. Defaults to `stable`. */\n stability?: Stability;\n /** Attributes specific to this span, keyed by attribute name. */\n attributes?: Record<string, AttributeSpec>;\n /**\n * When `true`, attributes not declared here are allowed without an\n * `unknown_attribute` violation. Defaults to the contract-level setting.\n */\n additionalAttributes?: boolean;\n}\n\n/** The full telemetry contract for one service. */\nexport interface TelemetryContract {\n /** `service.name` this contract describes. */\n service: string;\n /**\n * Semver of the *contract itself* (not the app). Bumped when the trace\n * surface changes; surfaced to readers as the `telemetry.schema.version`\n * resource attribute via {@link ./attrs.SCHEMA_ATTRS}.\n */\n version: string;\n /** Spans this service emits, keyed by span name. */\n spans: Record<string, SpanSpec>;\n /** Attributes permitted on *any* span (e.g. `user.id`, `tenant.id`). */\n commonAttributes?: Record<string, AttributeSpec>;\n /**\n * Default for `SpanSpec.additionalAttributes` when a span does not set it.\n * Defaults to `false` (declared-only — the stricter, agent-friendlier mode).\n */\n additionalAttributes?: boolean;\n /**\n * Flow-level scenario contracts, keyed by scenario name: which events one\n * exercised flow must emit, their cardinality and topology, and when the\n * observation is complete. Checked with `checkScenario` ({@link ./scenario}).\n */\n scenarios?: Record<string, ScenarioSpec>;\n}\n\nconst SEMVER_RE = /^\\d+\\.\\d+\\.\\d+(?:-[\\w.]+)?$/;\n\nfunction assert(condition: unknown, message: string): asserts condition {\n if (!condition) {\n throw new Error(`autotel-schema: ${message}`);\n }\n}\n\nfunction validateAttribute(\n scope: string,\n key: string,\n spec: AttributeSpec,\n): void {\n assert(\n ATTRIBUTE_TYPES.includes(spec.type),\n `${scope} attribute \"${key}\" has invalid type \"${spec.type}\"`,\n );\n if (spec.stability) {\n assert(\n STABILITIES.includes(spec.stability),\n `${scope} attribute \"${key}\" has invalid stability \"${spec.stability}\"`,\n );\n }\n if (spec.stability === 'deprecated') {\n assert(\n spec.replacedBy !== undefined || spec.deprecatedReason !== undefined,\n `${scope} attribute \"${key}\" is deprecated but has no replacedBy or deprecatedReason`,\n );\n }\n if (spec.enum) {\n assert(\n spec.enum.length > 0,\n `${scope} attribute \"${key}\" declares an empty enum`,\n );\n }\n}\n\n/**\n * Validate and freeze a telemetry contract. Throws on structural mistakes\n * (bad semver, unknown attribute type, deprecation with no replacement) so the\n * contract fails loudly at module load, not silently at runtime.\n *\n * @example\n * ```ts\n * export const contract = defineContract({\n * service: 'checkout',\n * version: '1.2.0',\n * commonAttributes: {\n * 'user.id': { type: 'string', highCardinality: true, description: 'Authenticated user' },\n * },\n * spans: {\n * 'checkout.charge': {\n * description: 'Charge a payment method',\n * attributes: {\n * 'payment.provider': { type: 'string', required: true, enum: ['stripe', 'paypal'] },\n * 'payment.amount_cents': { type: 'number', required: true },\n * },\n * },\n * },\n * });\n * ```\n */\nexport function defineContract(contract: TelemetryContract): TelemetryContract {\n assert(\n typeof contract.service === 'string' && contract.service.length > 0,\n 'contract.service must be a non-empty string',\n );\n assert(\n SEMVER_RE.test(contract.version),\n `contract.version \"${contract.version}\" is not valid semver (e.g. \"1.2.0\")`,\n );\n assert(\n contract.spans && typeof contract.spans === 'object',\n 'contract.spans must be an object',\n );\n\n for (const [spanName, spanSpec] of Object.entries(contract.spans)) {\n if (spanSpec.stability) {\n assert(\n STABILITIES.includes(spanSpec.stability),\n `span \"${spanName}\" has invalid stability \"${spanSpec.stability}\"`,\n );\n }\n for (const [key, spec] of Object.entries(spanSpec.attributes ?? {})) {\n validateAttribute(`span \"${spanName}\"`, key, spec);\n }\n }\n for (const [key, spec] of Object.entries(contract.commonAttributes ?? {})) {\n validateAttribute('common', key, spec);\n }\n for (const [name, spec] of Object.entries(contract.scenarios ?? {})) {\n validateScenarioSpec(name, spec);\n }\n\n return Object.freeze(contract);\n}\n\n/**\n * Resolve the effective attribute spec for `key` on `spanName`: span-specific\n * attributes win over common attributes. Returns `undefined` when the key is\n * declared nowhere.\n */\nexport function resolveAttributeSpec(\n contract: TelemetryContract,\n spanName: string,\n key: string,\n): AttributeSpec | undefined {\n return (\n contract.spans[spanName]?.attributes?.[key] ??\n contract.commonAttributes?.[key]\n );\n}\n\n/** Whether attributes outside the declared set are tolerated for a span. */\nexport function allowsAdditionalAttributes(\n contract: TelemetryContract,\n spanName: string,\n): boolean {\n return (\n contract.spans[spanName]?.additionalAttributes ??\n contract.additionalAttributes ??\n false\n );\n}\n","/**\n * Pure span-vs-contract validation. No SDK, no side effects — the same engine\n * the runtime processor ({@link ./processor}) and any test harness can call.\n */\n\nimport {\n allowsAdditionalAttributes,\n resolveAttributeSpec,\n type AttributeSpec,\n type AttributeType,\n type TelemetryContract,\n} from './contract.js';\n\n/** Severity of a contract violation. `error` = a breaking-shaped problem. */\nexport type ViolationSeverity = 'error' | 'warning';\n\nexport type ViolationCode =\n | 'unknown_span'\n | 'unknown_attribute'\n | 'type_mismatch'\n | 'missing_required'\n | 'deprecated_attribute'\n | 'enum_violation';\n\n/** A single discrepancy between an emitted span and the contract. */\nexport interface SchemaViolation {\n code: ViolationCode;\n severity: ViolationSeverity;\n spanName: string;\n /** Attribute key involved, when the violation is attribute-scoped. */\n attribute?: string;\n message: string;\n /** Nearest declared key, for likely typos (`unknown_attribute` only). */\n suggestion?: string;\n}\n\n/** Minimal emitted-span shape — avoids a hard dependency on the OTel SDK. */\nexport interface SpanShape {\n name: string;\n attributes: Record<string, unknown>;\n}\n\nexport interface ValidateOptions {\n /** Report `unknown_span` for span names not in the contract. Default `false`. */\n strictSpanNames?: boolean;\n}\n\n/** `'empty[]'` is a distinct marker: an empty array satisfies any array type. */\nfunction actualType(value: unknown): AttributeType | 'empty[]' | 'unknown' {\n if (typeof value === 'string') return 'string';\n if (typeof value === 'number') return 'number';\n if (typeof value === 'boolean') return 'boolean';\n if (Array.isArray(value)) {\n const first = value.find((v) => v !== null && v !== undefined);\n if (first === undefined) return 'empty[]';\n if (typeof first === 'string') return 'string[]';\n if (typeof first === 'number') return 'number[]';\n if (typeof first === 'boolean') return 'boolean[]';\n }\n return 'unknown';\n}\n\nfunction typeMatches(expected: AttributeType, value: unknown): boolean {\n const actual = actualType(value);\n if (actual === 'unknown') return false;\n if (actual === 'empty[]') return expected.endsWith('[]');\n return actual === expected;\n}\n\n/** Levenshtein distance — small, allocation-light, good enough for key typos. */\nfunction editDistance(a: string, b: string): number {\n const m = a.length;\n const n = b.length;\n if (m === 0) return n;\n if (n === 0) return m;\n let prev = Array.from({ length: n + 1 }, (_, i) => i);\n let curr = Array.from<number>({ length: n + 1 });\n for (let i = 1; i <= m; i++) {\n curr[0] = i;\n for (let j = 1; j <= n; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n curr[j] = Math.min(prev[j] + 1, curr[j - 1] + 1, prev[j - 1] + cost);\n }\n [prev, curr] = [curr, prev];\n }\n return prev[n];\n}\n\n/**\n * Closest declared key to `key`, when one is within a small edit distance.\n * Turns \"you emitted an attribute I don't know\" into \"did you mean `user.id`?\".\n */\nfunction nearestKey(key: string, candidates: string[]): string | undefined {\n let best: string | undefined;\n let bestDistance = Infinity;\n const threshold = Math.max(1, Math.floor(key.length / 4) + 1);\n for (const candidate of candidates) {\n const d = editDistance(key, candidate);\n if (d < bestDistance && d <= threshold) {\n best = candidate;\n bestDistance = d;\n }\n }\n return best;\n}\n\nfunction declaredKeysFor(\n contract: TelemetryContract,\n spanName: string,\n): string[] {\n return [\n ...Object.keys(contract.spans[spanName]?.attributes ?? {}),\n ...Object.keys(contract.commonAttributes ?? {}),\n ];\n}\n\nfunction checkValue(\n spanName: string,\n key: string,\n value: unknown,\n spec: AttributeSpec,\n out: SchemaViolation[],\n): void {\n if (!typeMatches(spec.type, value)) {\n out.push({\n code: 'type_mismatch',\n severity: 'error',\n spanName,\n attribute: key,\n message: `attribute \"${key}\" should be ${spec.type} but got ${actualType(value)}`,\n });\n return; // a wrong type makes enum/deprecation checks noise\n }\n if (\n spec.enum &&\n (typeof value === 'string' || typeof value === 'number') &&\n !spec.enum.includes(value)\n ) {\n out.push({\n code: 'enum_violation',\n severity: 'error',\n spanName,\n attribute: key,\n message: `attribute \"${key}\" value ${JSON.stringify(value)} is not one of ${JSON.stringify(spec.enum)}`,\n });\n }\n if (spec.stability === 'deprecated') {\n const hint = spec.replacedBy\n ? ` — use \"${spec.replacedBy}\" instead`\n : spec.deprecatedReason\n ? ` — ${spec.deprecatedReason}`\n : '';\n out.push({\n code: 'deprecated_attribute',\n severity: 'warning',\n spanName,\n attribute: key,\n message: `attribute \"${key}\" is deprecated${hint}`,\n suggestion: spec.replacedBy,\n });\n }\n}\n\n/**\n * Validate one emitted span against the contract, returning every discrepancy.\n * Order is deterministic: required-but-missing first, then per-attribute checks\n * in attribute insertion order.\n */\nexport function validateSpan(\n span: SpanShape,\n contract: TelemetryContract,\n options: ValidateOptions = {},\n): SchemaViolation[] {\n const out: SchemaViolation[] = [];\n const spanSpec = contract.spans[span.name];\n\n if (!spanSpec) {\n if (options.strictSpanNames) {\n out.push({\n code: 'unknown_span',\n severity: 'warning',\n spanName: span.name,\n message: `span \"${span.name}\" is not declared in the contract`,\n });\n }\n return out; // unknown span → no attribute contract to check against\n }\n\n // Required attributes that never showed up.\n const required = [\n ...Object.entries(spanSpec.attributes ?? {}),\n ...Object.entries(contract.commonAttributes ?? {}),\n ].filter(([, spec]) => spec.required);\n for (const [key] of required) {\n if (!(key in span.attributes)) {\n out.push({\n code: 'missing_required',\n severity: 'error',\n spanName: span.name,\n attribute: key,\n message: `required attribute \"${key}\" is missing`,\n });\n }\n }\n\n const allowExtra = allowsAdditionalAttributes(contract, span.name);\n const declared = allowExtra ? [] : declaredKeysFor(contract, span.name);\n\n for (const [key, value] of Object.entries(span.attributes)) {\n if (value === null || value === undefined) continue;\n const spec = resolveAttributeSpec(contract, span.name, key);\n if (!spec) {\n if (!allowExtra) {\n out.push({\n code: 'unknown_attribute',\n severity: 'warning',\n spanName: span.name,\n attribute: key,\n message: `attribute \"${key}\" is not declared on span \"${span.name}\"`,\n suggestion: nearestKey(key, declared),\n });\n }\n continue;\n }\n checkValue(span.name, key, value, spec, out);\n }\n\n return out;\n}\n\n/** `true` when any violation is `error` severity. */\nexport function hasErrors(violations: SchemaViolation[]): boolean {\n return violations.some((v) => v.severity === 'error');\n}\n\n/** One-line human/agent-readable rendering of a violation. */\nexport function formatViolation(v: SchemaViolation): string {\n const where = v.attribute ? `${v.spanName}.${v.attribute}` : v.spanName;\n const suffix = v.suggestion ? ` (did you mean \"${v.suggestion}\"?)` : '';\n return `[${v.severity}] ${v.code} @ ${where}: ${v.message}${suffix}`;\n}\n","/**\n * Runtime contract enforcement as an OpenTelemetry SpanProcessor.\n *\n * Wire it into `init({ spanProcessors: [...] })` and every span your service\n * emits is validated against the contract as it ends. In development a typo'd\n * or undeclared attribute surfaces immediately instead of silently drifting\n * the public telemetry API out from under the agents reading it.\n *\n * Fail-open by construction: a bug in validation must never break the app or\n * lose a span. Off in production by default (validation belongs in CI and dev),\n * but `enabledInProduction` is there if you want a sampled canary in prod.\n */\n\nimport {\n validateSpan,\n type SchemaViolation,\n type ValidateOptions,\n} from './validate.js';\nimport type { TelemetryContract } from './contract.js';\n\n/** Minimal ReadableSpan shape — matches OTel without a hard SDK dependency. */\nexport interface ReadableSpanLike {\n name: string;\n attributes: Record<string, unknown>;\n}\n\nexport interface SpanLike {\n spanContext(): { traceId: string; spanId: string };\n}\n\n/** Opaque parent context — matches OTel SpanProcessor without importing it. */\nexport type OtelContext = unknown;\n\nexport interface SpanProcessorLike {\n onStart(span: SpanLike, parentContext: OtelContext): void;\n onEnd(span: ReadableSpanLike): void;\n shutdown(): Promise<void>;\n forceFlush(): Promise<void>;\n}\n\n/** How the processor reacts to a contract violation. */\nexport type SchemaProcessorMode = 'warn' | 'throw' | 'silent';\n\nexport interface SchemaValidationProcessorOptions extends ValidateOptions {\n contract: TelemetryContract;\n /**\n * `warn` (default): log each distinct violation once per interval.\n * `throw`: throw on the first error-severity violation — for tests/CI only.\n * `silent`: collect via `onViolation` without logging.\n */\n mode?: SchemaProcessorMode;\n /** Called for every violation, before mode handling. */\n onViolation?: (violation: SchemaViolation, span: ReadableSpanLike) => void;\n /** Override the warn sink (defaults to `console.warn`). */\n onWarn?: (message: string) => void;\n /** Run even when `NODE_ENV === 'production'`. Default `false`. */\n enabledInProduction?: boolean;\n /** Throttle window for repeated identical warnings (ms). Default 60s. */\n warnIntervalMs?: number;\n}\n\nconst DEFAULT_WARN_INTERVAL_MS = 60_000;\n\nfunction isProduction(): boolean {\n return process.env.NODE_ENV === 'production';\n}\n\n/**\n * Validates each ending span against a {@link TelemetryContract}. Bounded,\n * deduplicated warnings; fail-open on any internal error.\n */\nexport class SchemaValidationSpanProcessor implements SpanProcessorLike {\n private readonly opts: SchemaValidationProcessorOptions;\n private readonly enabled: boolean;\n private readonly warnIntervalMs: number;\n private readonly lastWarnAt = new Map<string, number>();\n private violationCount = 0;\n\n constructor(opts: SchemaValidationProcessorOptions) {\n this.opts = opts;\n this.enabled = opts.enabledInProduction === true || !isProduction();\n this.warnIntervalMs = opts.warnIntervalMs ?? DEFAULT_WARN_INTERVAL_MS;\n }\n\n /** Number of violations seen since startup (across all spans). */\n get totalViolations(): number {\n return this.violationCount;\n }\n\n onStart(_span: SpanLike, _parentContext: OtelContext): void {\n // no-op — validation happens once the span is complete\n }\n\n onEnd(span: ReadableSpanLike): void {\n if (!this.enabled) return;\n let violations: SchemaViolation[];\n try {\n // Validation itself is fail-open: a bug here must never break export.\n violations = validateSpan(\n { name: span.name, attributes: span.attributes },\n this.opts.contract,\n { strictSpanNames: this.opts.strictSpanNames },\n );\n } catch {\n return;\n }\n // Mode handling runs outside the fail-open guard so `throw` mode propagates.\n for (const violation of violations) {\n this.violationCount++;\n this.opts.onViolation?.(violation, span);\n this.handle(violation);\n }\n }\n\n private handle(violation: SchemaViolation): void {\n const mode = this.opts.mode ?? 'warn';\n if (mode === 'silent') return;\n if (mode === 'throw' && violation.severity === 'error') {\n throw new Error(\n `autotel-schema: contract violation (${violation.code}) on span \"${violation.spanName}\": ${violation.message}`,\n );\n }\n this.maybeWarn(violation);\n }\n\n private maybeWarn(violation: SchemaViolation): void {\n const key = `${violation.code}:${violation.spanName}:${violation.attribute ?? ''}`;\n const now = Date.now();\n const last = this.lastWarnAt.get(key) ?? 0;\n if (now - last < this.warnIntervalMs) return;\n this.lastWarnAt.set(key, now);\n const suffix = violation.suggestion\n ? ` (did you mean \"${violation.suggestion}\"?)`\n : '';\n const message = `autotel-schema [${violation.severity}] ${violation.code} on \"${violation.spanName}\"${violation.attribute ? `.${violation.attribute}` : ''}: ${violation.message}${suffix}`;\n if (this.opts.onWarn) {\n this.opts.onWarn(message);\n } else {\n console.warn(message);\n }\n }\n\n async forceFlush(): Promise<void> {\n // nothing buffered — validation is synchronous in onEnd\n }\n\n async shutdown(): Promise<void> {\n this.lastWarnAt.clear();\n }\n}\n\nexport function createSchemaValidationProcessor(\n opts: SchemaValidationProcessorOptions,\n): SchemaValidationSpanProcessor {\n return new SchemaValidationSpanProcessor(opts);\n}\n"],"mappings":";;;;;AA8DA,SAAgB,iBAAiB,OAA0C;CACzE,IAAI,OAAO,UAAU,UAAU;EAC7B,SACE,OAAO,UAAU,MAAM,GAAG,KAAK,MAAM,OAAO,GAC5C,uDAAuD,MAAM,KAC/D;EACA,SACE,MAAM,QAAQ,UACX,OAAO,UAAU,MAAM,GAAG,KAAK,MAAM,OAAO,MAAM,KACrD,uCAAuC,MAAM,KAC/C;EACA,OAAO;CACT;CACA,MAAM,QAAQ,kBAAkB,KAAK,KAAK;CAC1C,IAAI,OAAO,OAAO;EAAE,KAAK,OAAO,MAAM,EAAE;EAAG,KAAK,OAAO,MAAM,EAAE;CAAE;CACjE,MAAM,UAAU,mBAAmB,KAAK,KAAK;CAC7C,IAAI,SAAS,OAAO,EAAE,KAAK,OAAO,QAAQ,EAAE,EAAE;CAC9C,MAAM,SAAS,kBAAkB,KAAK,KAAK;CAC3C,IAAI,QAAQ,OAAO;EAAE,KAAK;EAAG,KAAK,OAAO,OAAO,EAAE;CAAE;CACpD,MAAM,QAAQ,mBA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M,WACN,UAAU,mBACV,UAAS,kBACR;;iBA2Da,UAAU,YAAY;;iBAKtB,gBAAgB,GAAG;;;;UCvNlB;EACf;EACA,YAAY;;UAGG;EACf;IAAiB;IAAiB;;;;KAIxB;UAEK;EACf,QAAQ,MAAM,UAAU,eAAe;EACvC,MAAM,MAAM;EACZ,YAAY;EACZ,cAAc;;;KAIJ;UAEK,yCAAyC;EACxD,UAAU;;;;;;EAMV,OAAO;;EAEP,eAAe,WAAW,iBAAiB,MAAM;;EAEjD,UAAU;;EAEV;;EAEA;;;;;;cAaW,yCAAyC;mBACnC;mBACA;mBACA;mBACA;UACT;EAEI,YAAA,MAAM;;MAOd;EAIJ,QAAQ,OAAO,UAAU,gBAAgB;EAIzC,MAAM,MAAM;UAqBJ;UAWA;EAiBF,cAAc;EAId,YAAY;;iBAKJ,gCACd,MAAM,mCACL"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"processor-Gu8Yl_dS.cjs","names":["assert"],"sources":["../src/scenario.ts","../src/contract.ts","../src/validate.ts","../src/processor.ts"],"sourcesContent":["/**\n * Scenario conformance — a flow-level contract checked against collected spans.\n *\n * Where {@link ./contract} declares the *surface* of your telemetry (span\n * names + attributes), a scenario declares the *behaviour* of one exercised\n * flow: which events must fire, how many times, in what parent/child\n * topology, and — critically — **when the observation is complete**, because\n * for an async flow a missing event and an event that has not fired *yet* are\n * indistinguishable without a completion boundary.\n *\n * Checking a scenario yields one of three outcomes, not two:\n *\n * - `conformant` — the boundary closed and the signature satisfied the contract\n * - `non-conformant` — required behaviour was missing or invalid (definitive)\n * - `incomplete` — the boundary did not close within the observation budget;\n * infrastructure slowness is *not* reported as behavioural regression\n *\n * Absence is definitive only after closure (closed-world semantics). Excess\n * is definitive immediately: a `max` cardinality violation or an unexpected\n * error span fails the check even while the flow is still open.\n *\n * Undeclared events are **additive**: reported in `result.additions`, never a\n * failure — improving instrumentation must not break CI.\n *\n * The span input shape is structurally compatible with `SerializedSpan` from\n * `autotel/test-span-collector`, so a test can feed a collector's output\n * straight in. Like the rest of this package the module is dependency-free —\n * usable from vitest, a deferred reconciliation job, or a CLI alike.\n *\n * @example\n * ```ts\n * const result = await checkScenario(\n * contract.scenarios!['transfer.accept'],\n * () => collector.peekTrace(traceId),\n * { name: 'transfer.accept' },\n * );\n * if (result.outcome === 'non-conformant') throw new Error(formatScenarioResult(result));\n * ```\n */\n\n/** A finished span/event as the scenario checker sees it. */\nexport interface ScenarioSpan {\n spanId: string;\n parentSpanId?: string;\n name: string;\n status: 'ok' | 'error' | 'unset';\n attributes?: Record<string, unknown>;\n /** Epoch ms. Optional — used by {@link proposeScenario} to suggest budgets. */\n startTimeMs?: number;\n durationMs?: number;\n}\n\n/** Canonical cardinality range. `max` omitted = unbounded. */\nexport interface Cardinality {\n min: number;\n max?: number;\n}\n\n/**\n * Parse a cardinality shorthand: `'exactly 1'`, `'at least 1'`, `'at most 3'`,\n * `'0..1'`, `'2..'`. A canonical {@link Cardinality} passes through.\n */\nexport function parseCardinality(input: string | Cardinality): Cardinality {\n if (typeof input !== 'string') {\n assert(\n Number.isInteger(input.min) && input.min >= 0,\n `cardinality min must be a non-negative integer, got ${input.min}`,\n );\n assert(\n input.max === undefined ||\n (Number.isInteger(input.max) && input.max >= input.min),\n `cardinality max must be >= min, got ${input.max}`,\n );\n return input;\n }\n const exact = /^exactly (\\d+)$/.exec(input);\n if (exact) return { min: Number(exact[1]), max: Number(exact[1]) };\n const atLeast = /^at least (\\d+)$/.exec(input);\n if (atLeast) return { min: Number(atLeast[1]) };\n const atMost = /^at most (\\d+)$/.exec(input);\n if (atMost) return { min: 0, max: Number(atMost[1]) };\n const range = /^(\\d+)\\.\\.(\\d*)$/.exec(input);\n if (range) {\n const min = Number(range[1]);\n const max = range[2] === '' ? undefined : Number(range[2]);\n assert(\n max === undefined || max >= min,\n `cardinality \"${input}\" has max < min`,\n );\n return { min, max };\n }\n throw new Error(\n `autotel-schema: unparseable cardinality \"${input}\" (expected \"exactly N\", \"at least N\", \"at most N\", or \"N..M\")`,\n );\n}\n\n/** Declaration for one event (span name) a scenario expects to observe. */\nexport interface ScenarioEventSpec {\n /** How many occurrences are permitted. Defaults to `'at least 1'`. */\n cardinality?: string | Cardinality;\n /**\n * Expected terminal status. Defaults to non-error: an `error` status on an\n * event not declared `status: 'error'` is a definitive violation.\n */\n status?: 'ok' | 'error';\n description?: string;\n}\n\n/**\n * How the observed phase of a scenario becomes complete. Every async\n * conformance check must declare this — it is what makes absence meaningful.\n *\n * `externally-reconciled` never closes in-process: the phase is verified\n * elsewhere (a deferred reconciliation job keyed by a durable business ID),\n * so an in-process check reports at most definitive violations, never absence.\n */\nexport type CompletionBoundary =\n | { mode: 'root-span-closed'; observationBudgetMs: number }\n | { mode: 'terminal-event'; event: string; observationBudgetMs: number }\n | { mode: 'externally-reconciled'; reconciliationDeadlineMs: number };\n\n/** The flow-level contract for one exercised scenario (or one phase of one). */\nexport interface ScenarioSpec {\n description?: string;\n /** When the observed phase is complete. See {@link CompletionBoundary}. */\n completion: CompletionBoundary;\n /** Events this scenario must (or may) observe, keyed by span name. */\n events: Record<string, ScenarioEventSpec>;\n /**\n * Required ancestor→descendant edges by span name. Ancestor — not immediate\n * parent — so a framework span inserted between the two does not break the\n * contract (canonicalisation: infrastructure spans are not behaviour).\n */\n edges?: ReadonlyArray<readonly [string, string]>;\n /** Edges that may appear but are not required. Documented, never enforced. */\n optionalEdges?: ReadonlyArray<readonly [string, string]>;\n}\n\nexport type ScenarioOutcome = 'conformant' | 'non-conformant' | 'incomplete';\n\nexport type ScenarioViolationCode =\n | 'missing_event'\n | 'cardinality_violation'\n | 'missing_edge'\n | 'unexpected_error';\n\n/** A definitive (breaking) discrepancy between observed spans and the scenario. */\nexport interface ScenarioViolation {\n code: ScenarioViolationCode;\n event?: string;\n edge?: readonly [string, string];\n message: string;\n}\n\n/** An additive observation — reported, never a failure. */\nexport interface ScenarioAddition {\n code: 'undeclared_event';\n event: string;\n count: number;\n message: string;\n}\n\nexport interface ScenarioResult {\n scenario: string;\n outcome: ScenarioOutcome;\n /** Whether the completion boundary closed within the observation window. */\n closed: boolean;\n violations: ScenarioViolation[];\n additions: ScenarioAddition[];\n /** The evaluated snapshot — assert business values on this in your test. */\n spans: ScenarioSpan[];\n}\n\nfunction assert(condition: unknown, message: string): asserts condition {\n if (!condition) {\n throw new Error(`autotel-schema: ${message}`);\n }\n}\n\nconst COMPLETION_MODES = [\n 'root-span-closed',\n 'terminal-event',\n 'externally-reconciled',\n] as const;\n\n/**\n * Structural validation for one scenario declaration. Called by\n * `defineContract()` so a malformed scenario throws at module load.\n */\nexport function validateScenarioSpec(name: string, spec: ScenarioSpec): void {\n const scope = `scenario \"${name}\"`;\n assert(\n spec.completion && typeof spec.completion === 'object',\n `${scope} must declare a completion boundary`,\n );\n assert(\n (COMPLETION_MODES as readonly string[]).includes(spec.completion.mode),\n `${scope} has invalid completion mode \"${(spec.completion as { mode: string }).mode}\"`,\n );\n const budget =\n spec.completion.mode === 'externally-reconciled'\n ? spec.completion.reconciliationDeadlineMs\n : spec.completion.observationBudgetMs;\n assert(\n typeof budget === 'number' && Number.isFinite(budget) && budget > 0,\n `${scope} completion budget must be a positive number of milliseconds`,\n );\n switch (spec.completion.mode) {\n case 'terminal-event':\n assert(\n typeof spec.completion.event === 'string' &&\n spec.completion.event.length > 0,\n `${scope} terminal-event completion must declare a non-empty event`,\n );\n break;\n }\n assert(\n spec.events &&\n typeof spec.events === 'object' &&\n Object.keys(spec.events).length > 0,\n `${scope} must declare at least one event`,\n );\n for (const [event, eventSpec] of Object.entries(spec.events)) {\n if (eventSpec.cardinality !== undefined) {\n try {\n parseCardinality(eventSpec.cardinality);\n } catch (error) {\n throw new Error(\n `autotel-schema: ${scope} event \"${event}\": ${(error as Error).message}`,\n );\n }\n }\n if (eventSpec.status !== undefined) {\n assert(\n eventSpec.status === 'ok' || eventSpec.status === 'error',\n `${scope} event \"${event}\" has invalid status \"${eventSpec.status}\"`,\n );\n }\n }\n for (const [from, to] of [\n ...(spec.edges ?? []),\n ...(spec.optionalEdges ?? []),\n ]) {\n assert(\n from in spec.events && to in spec.events,\n `${scope} edge [\"${from}\", \"${to}\"] references an undeclared event — declare both endpoints in events`,\n );\n }\n}\n\n/** Whether the scenario's completion boundary has closed for these spans. */\nexport function isScenarioClosed(\n spec: ScenarioSpec,\n spans: readonly ScenarioSpan[],\n): boolean {\n const { completion } = spec;\n switch (completion.mode) {\n case 'externally-reconciled':\n return false;\n case 'root-span-closed':\n // Only finished spans reach a collector, so a present root = a closed root.\n return spans.some((s) => !s.parentSpanId);\n case 'terminal-event':\n return spans.some((s) => s.name === completion.event);\n }\n}\n\n/** True when `span` has an ancestor named `ancestorName` within `byId`. */\nfunction hasAncestorNamed(\n span: ScenarioSpan,\n ancestorName: string,\n byId: ReadonlyMap<string, ScenarioSpan>,\n): boolean {\n const seen = new Set<string>();\n let parentId = span.parentSpanId;\n while (parentId && !seen.has(parentId)) {\n seen.add(parentId);\n const parent = byId.get(parentId);\n if (!parent) return false;\n if (parent.name === ancestorName) return true;\n parentId = parent.parentSpanId;\n }\n return false;\n}\n\nexport interface EvaluateScenarioOptions {\n /** Name used in the result/messages. Defaults to `'scenario'`. */\n name?: string;\n /** Override closure detection (e.g. the poller already knows). */\n closed?: boolean;\n}\n\n/**\n * Pure three-state evaluation of collected spans against a scenario.\n *\n * Definitive at any time (no closure needed): an unexpected error status, a\n * `max` cardinality exceeded. Meaningful only after closure: a missing event,\n * a `min` cardinality not reached, a missing required edge.\n */\nexport function evaluateScenario(\n spec: ScenarioSpec,\n spans: readonly ScenarioSpan[],\n options?: EvaluateScenarioOptions,\n): ScenarioResult {\n const name = options?.name ?? 'scenario';\n const closed = options?.closed ?? isScenarioClosed(spec, spans);\n const violations: ScenarioViolation[] = [];\n const additions: ScenarioAddition[] = [];\n\n const countByName = new Map<string, number>();\n for (const span of spans) {\n countByName.set(span.name, (countByName.get(span.name) ?? 0) + 1);\n }\n\n // Unexpected error status — definitive even while the flow is open.\n for (const span of spans) {\n if (span.status === 'error' && spec.events[span.name]?.status !== 'error') {\n violations.push({\n code: 'unexpected_error',\n event: span.name,\n message: `\"${span.name}\" ended with status error, which the scenario does not declare`,\n });\n }\n }\n\n for (const [event, eventSpec] of Object.entries(spec.events)) {\n const { min, max } = parseCardinality(eventSpec.cardinality ?? { min: 1 });\n const count = countByName.get(event) ?? 0;\n\n // Excess is definitive immediately.\n if (max !== undefined && count > max) {\n violations.push({\n code: 'cardinality_violation',\n event,\n message: `\"${event}\" observed ${count}×, contract allows at most ${max}`,\n });\n }\n // Absence is definitive only after closure.\n if (closed && count < min) {\n violations.push({\n code: count === 0 ? 'missing_event' : 'cardinality_violation',\n event,\n message:\n count === 0\n ? `\"${event}\" was not observed and the completion boundary has closed`\n : `\"${event}\" observed ${count}×, contract requires at least ${min}`,\n });\n }\n }\n\n if (closed) {\n const byId = new Map<string, ScenarioSpan>();\n for (const span of spans) byId.set(span.spanId, span);\n for (const [from, to] of spec.edges ?? []) {\n const satisfied = spans.some(\n (s) => s.name === to && hasAncestorNamed(s, from, byId),\n );\n if (!satisfied) {\n violations.push({\n code: 'missing_edge',\n edge: [from, to],\n message: `no \"${to}\" span has ancestor \"${from}\"`,\n });\n }\n }\n }\n\n for (const [event, count] of [...countByName.entries()].toSorted()) {\n if (!(event in spec.events)) {\n additions.push({\n code: 'undeclared_event',\n event,\n count,\n message: `\"${event}\" observed ${count}× but not declared — additive, consider adding it to the scenario`,\n });\n }\n }\n\n return {\n scenario: name,\n outcome:\n violations.length > 0\n ? 'non-conformant'\n : closed\n ? 'conformant'\n : 'incomplete',\n closed,\n violations,\n additions,\n spans: [...spans],\n };\n}\n\nexport interface CheckScenarioOptions {\n /** Name used in the result/messages. Defaults to `'scenario'`. */\n name?: string;\n /** Poll interval while waiting for closure. Default 25ms. */\n pollIntervalMs?: number;\n /** Override the boundary's observation budget (how long the checker waits). */\n budgetMs?: number;\n}\n\n/**\n * Poll `getSpans` until the scenario's completion boundary closes, a\n * definitive violation appears (fail fast), or the observation budget is\n * spent — then evaluate.\n *\n * The observation budget bounds how long *this checker* waits; it is not a\n * statement that the operation is allowed to take that long. Express a\n * business deadline as its own assertion on the returned spans.\n *\n * An `externally-reconciled` boundary never closes in-process: the check\n * evaluates the current snapshot once and reports `incomplete` unless a\n * definitive violation is already present.\n */\nexport async function checkScenario(\n spec: ScenarioSpec,\n getSpans: () => readonly ScenarioSpan[] | Promise<readonly ScenarioSpan[]>,\n options?: CheckScenarioOptions,\n): Promise<ScenarioResult> {\n const name = options?.name;\n if (spec.completion.mode === 'externally-reconciled') {\n return evaluateScenario(spec, await getSpans(), { name });\n }\n const budgetMs = options?.budgetMs ?? spec.completion.observationBudgetMs;\n const pollIntervalMs = options?.pollIntervalMs ?? 25;\n assert(\n Number.isFinite(budgetMs) && budgetMs > 0,\n 'checkScenario budgetMs must be a positive number of milliseconds',\n );\n assert(\n Number.isFinite(pollIntervalMs) && pollIntervalMs >= 0,\n 'checkScenario pollIntervalMs must be a non-negative number of milliseconds',\n );\n const deadline = Date.now() + budgetMs;\n let lastResult = evaluateScenario(spec, [], { name });\n\n for (;;) {\n const remainingMs = deadline - Date.now();\n if (remainingMs <= 0) return lastResult;\n\n let timeout: ReturnType<typeof setTimeout> | undefined;\n let next:\n { kind: 'spans'; spans: readonly ScenarioSpan[] } | { kind: 'timeout' };\n try {\n next = await Promise.race([\n Promise.resolve()\n .then(getSpans)\n .then((spans) => ({ kind: 'spans' as const, spans })),\n new Promise<{ kind: 'timeout' }>((resolve) => {\n timeout = setTimeout(() => resolve({ kind: 'timeout' }), remainingMs);\n }),\n ]);\n } finally {\n if (timeout !== undefined) clearTimeout(timeout);\n }\n if (next.kind === 'timeout') return lastResult;\n\n const { spans } = next;\n const result = evaluateScenario(spec, spans, { name });\n lastResult = result;\n if (result.closed || result.outcome === 'non-conformant') return result;\n const waitMs = Math.min(pollIntervalMs, deadline - Date.now());\n if (waitMs <= 0) return result; // incomplete\n await new Promise((resolve) => setTimeout(resolve, waitMs));\n }\n}\n\n/** Human-readable summary of a scenario result, for assertion messages. */\nexport function formatScenarioResult(result: ScenarioResult): string {\n const lines = [\n `scenario \"${result.scenario}\": ${result.outcome}${result.closed ? '' : ' (completion boundary did not close)'}`,\n ];\n for (const v of result.violations) lines.push(` ✗ ${v.message}`);\n for (const a of result.additions) lines.push(` + ${a.message}`);\n return lines.join('\\n');\n}\n\nexport interface ScenarioProposal {\n scenario: ScenarioSpec;\n /** Review annotations — what was observed and what to double-check. */\n notes: string[];\n}\n\n/**\n * Draft a scenario contract from repeated controlled runs (record → propose →\n * commit). Events stable across every run become required with their observed\n * cardinality; variable ones get a range and a review note. The draft is a\n * starting point for human curation, not a finished contract.\n */\nexport function proposeScenario(\n runs: ReadonlyArray<ReadonlyArray<ScenarioSpan>>,\n options?: { name?: string },\n): ScenarioProposal {\n assert(runs.length > 0, 'proposeScenario needs at least one recorded run');\n for (const [index, run] of runs.entries()) {\n assert(\n run.length > 0,\n `proposeScenario run ${index + 1} has no recorded spans`,\n );\n }\n const name = options?.name ?? 'scenario';\n const notes: string[] = [];\n const total = runs.length;\n\n // Occurrence counts per event name per run (0 when absent).\n const names = new Set<string>();\n const countsPerRun: Array<Map<string, number>> = runs.map((run) => {\n const counts = new Map<string, number>();\n for (const span of run) {\n names.add(span.name);\n counts.set(span.name, (counts.get(span.name) ?? 0) + 1);\n }\n return counts;\n });\n\n const events: Record<string, ScenarioEventSpec> = {};\n for (const event of [...names].toSorted()) {\n const counts = countsPerRun.map((c) => c.get(event) ?? 0);\n const min = Math.min(...counts);\n const max = Math.max(...counts);\n const seenIn = counts.filter((c) => c > 0).length;\n events[event] = {\n cardinality: min === max ? `exactly ${min}` : { min, max },\n };\n notes.push(\n min === max\n ? `${event}: exactly ${min} (${seenIn}/${total} runs)`\n : `${event}: ${min}..${max} (${seenIn}/${total} runs) — review: variable`,\n );\n if (\n runs.some((run) =>\n run.some((s) => s.name === event && s.status === 'error'),\n )\n ) {\n notes.push(`${event}: observed with status error — review: expected?`);\n }\n }\n\n // Immediate parent→child name pairs; present in every run → required edge.\n const edgeRuns = new Map<string, number>();\n for (const run of runs) {\n const byId = new Map(run.map((s) => [s.spanId, s]));\n const pairs = new Set<string>();\n for (const span of run) {\n const parent = span.parentSpanId\n ? byId.get(span.parentSpanId)\n : undefined;\n if (parent) pairs.add(`${parent.name}\u0000${span.name}`);\n }\n for (const pair of pairs) edgeRuns.set(pair, (edgeRuns.get(pair) ?? 0) + 1);\n }\n const edges: Array<readonly [string, string]> = [];\n const optionalEdges: Array<readonly [string, string]> = [];\n for (const [pair, seen] of [...edgeRuns.entries()].toSorted()) {\n const [from, to] = pair.split('\u0000') as [string, string];\n if (seen === total) {\n edges.push([from, to]);\n } else {\n optionalEdges.push([from, to]);\n notes.push(\n `edge ${from} → ${to}: ${seen}/${total} runs — proposed optional`,\n );\n }\n }\n\n // Completion: consistent last-ending span → terminal event; else root closure.\n // Budget: 3× the slowest observed makespan when timing data is present.\n let completion: CompletionBoundary;\n const lastNames = new Set<string>();\n let maxMakespanMs = 0;\n let hasTiming = true;\n for (const run of runs) {\n let last: ScenarioSpan | undefined;\n let start = Number.POSITIVE_INFINITY;\n let end = 0;\n for (const span of run) {\n if (span.startTimeMs === undefined || span.durationMs === undefined) {\n hasTiming = false;\n break;\n }\n const spanEnd = span.startTimeMs + span.durationMs;\n start = Math.min(start, span.startTimeMs);\n if (spanEnd >= end) {\n end = spanEnd;\n last = span;\n }\n }\n if (!hasTiming) break;\n if (last) lastNames.add(last.name);\n maxMakespanMs = Math.max(maxMakespanMs, end - start);\n }\n const observationBudgetMs = hasTiming\n ? Math.max(1000, Math.ceil(maxMakespanMs * 3))\n : 30_000;\n if (hasTiming && lastNames.size === 1) {\n const [event] = [...lastNames] as [string];\n completion = { mode: 'terminal-event', event, observationBudgetMs };\n notes.push(\n `completion: terminal-event \"${event}\" (last to end in all ${total} runs), budget ${observationBudgetMs}ms (3× slowest observed run)`,\n );\n } else {\n completion = { mode: 'root-span-closed', observationBudgetMs };\n notes.push(\n hasTiming\n ? `completion: root-span-closed (last-ending span varies: ${[...lastNames].toSorted().join(', ')}), budget ${observationBudgetMs}ms`\n : `completion: root-span-closed, budget ${observationBudgetMs}ms (default — no timing data recorded)`,\n );\n }\n\n const scenario: ScenarioSpec = {\n description: `Proposed from ${total} recorded run${total === 1 ? '' : 's'} of ${name} — review before committing`,\n completion,\n events,\n ...(edges.length > 0 ? { edges } : {}),\n ...(optionalEdges.length > 0 ? { optionalEdges } : {}),\n };\n validateScenarioSpec(name, scenario);\n return { scenario, notes };\n}\n","/**\n * Telemetry contract model.\n *\n * The premise: when the primary reader of your telemetry is an agent, your\n * span names and attribute keys are a **public API**. Renaming `fast_path_hit`\n * to `fast_path_taken` in a refactor PR silently breaks every prompt that\n * mentions it — there is no compiler to catch it, because to the compiler these\n * are just strings in a JSON blob.\n *\n * `defineContract()` makes that surface explicit, typed, and versionable: you\n * declare which spans your service emits and which attributes live on them,\n * then validate live spans against it ({@link ./validate}) and diff it across\n * commits to catch breaking changes before they ship ({@link ./diff}).\n *\n * This module is dependency-free and side-effect-free by design — safe to\n * import anywhere (browser, edge, CLI) without pulling in the OpenTelemetry SDK.\n */\n\nimport { validateScenarioSpec, type ScenarioSpec } from './scenario.js';\n\n/** Scalar and array attribute types permitted on a span (OTLP value shapes). */\nexport type AttributeType =\n 'string' | 'number' | 'boolean' | 'string[]' | 'number[]' | 'boolean[]';\n\nexport const ATTRIBUTE_TYPES: readonly AttributeType[] = [\n 'string',\n 'number',\n 'boolean',\n 'string[]',\n 'number[]',\n 'boolean[]',\n];\n\n/**\n * Lifecycle of a span or attribute, mirroring how the OpenTelemetry semantic\n * conventions stage their own surface. `stable` is a promise to agent readers\n * that the name will not change without a major contract bump.\n */\nexport type Stability = 'stable' | 'experimental' | 'deprecated';\n\nexport const STABILITIES: readonly Stability[] = [\n 'stable',\n 'experimental',\n 'deprecated',\n];\n\n/** Declaration for a single attribute key on a span. */\nexport interface AttributeSpec {\n /** OTLP value shape. Validated at runtime against the emitted value. */\n type: AttributeType;\n /** Lifecycle stage. Defaults to `stable`. */\n stability?: Stability;\n /** When `true`, the attribute must be present on every matching span. */\n required?: boolean;\n /** Human/agent-facing description of what the attribute means. */\n description?: string;\n /**\n * Marks an attribute as intentionally high-cardinality (user id, sender\n * domain, request id). For an agent reader these are the single most useful\n * fields on a trace, so {@link ./redaction.highCardinalityKeys} surfaces them\n * as a *protect* list — telling redactors/normalizers NOT to strip them.\n */\n highCardinality?: boolean;\n /** Closed set of permitted values. Reported as `enum_violation` if exceeded. */\n enum?: readonly (string | number)[];\n /** Set when `stability: 'deprecated'`; explains what to use instead. */\n replacedBy?: string;\n /** Free-text note shown alongside deprecation warnings. */\n deprecatedReason?: string;\n}\n\n/** Declaration for a single span name your service emits. */\nexport interface SpanSpec {\n /** Human/agent-facing description of when this span is produced. */\n description?: string;\n /** Lifecycle stage. Defaults to `stable`. */\n stability?: Stability;\n /** Attributes specific to this span, keyed by attribute name. */\n attributes?: Record<string, AttributeSpec>;\n /**\n * When `true`, attributes not declared here are allowed without an\n * `unknown_attribute` violation. Defaults to the contract-level setting.\n */\n additionalAttributes?: boolean;\n}\n\n/** The full telemetry contract for one service. */\nexport interface TelemetryContract {\n /** `service.name` this contract describes. */\n service: string;\n /**\n * Semver of the *contract itself* (not the app). Bumped when the trace\n * surface changes; surfaced to readers as the `telemetry.schema.version`\n * resource attribute via {@link ./attrs.SCHEMA_ATTRS}.\n */\n version: string;\n /** Spans this service emits, keyed by span name. */\n spans: Record<string, SpanSpec>;\n /** Attributes permitted on *any* span (e.g. `user.id`, `tenant.id`). */\n commonAttributes?: Record<string, AttributeSpec>;\n /**\n * Default for `SpanSpec.additionalAttributes` when a span does not set it.\n * Defaults to `false` (declared-only — the stricter, agent-friendlier mode).\n */\n additionalAttributes?: boolean;\n /**\n * Flow-level scenario contracts, keyed by scenario name: which events one\n * exercised flow must emit, their cardinality and topology, and when the\n * observation is complete. Checked with `checkScenario` ({@link ./scenario}).\n */\n scenarios?: Record<string, ScenarioSpec>;\n}\n\nconst SEMVER_RE = /^\\d+\\.\\d+\\.\\d+(?:-[\\w.]+)?$/;\n\nfunction assert(condition: unknown, message: string): asserts condition {\n if (!condition) {\n throw new Error(`autotel-schema: ${message}`);\n }\n}\n\nfunction validateAttribute(\n scope: string,\n key: string,\n spec: AttributeSpec,\n): void {\n assert(\n ATTRIBUTE_TYPES.includes(spec.type),\n `${scope} attribute \"${key}\" has invalid type \"${spec.type}\"`,\n );\n if (spec.stability) {\n assert(\n STABILITIES.includes(spec.stability),\n `${scope} attribute \"${key}\" has invalid stability \"${spec.stability}\"`,\n );\n }\n if (spec.stability === 'deprecated') {\n assert(\n spec.replacedBy !== undefined || spec.deprecatedReason !== undefined,\n `${scope} attribute \"${key}\" is deprecated but has no replacedBy or deprecatedReason`,\n );\n }\n if (spec.enum) {\n assert(\n spec.enum.length > 0,\n `${scope} attribute \"${key}\" declares an empty enum`,\n );\n }\n}\n\n/**\n * Validate and freeze a telemetry contract. Throws on structural mistakes\n * (bad semver, unknown attribute type, deprecation with no replacement) so the\n * contract fails loudly at module load, not silently at runtime.\n *\n * @example\n * ```ts\n * export const contract = defineContract({\n * service: 'checkout',\n * version: '1.2.0',\n * commonAttributes: {\n * 'user.id': { type: 'string', highCardinality: true, description: 'Authenticated user' },\n * },\n * spans: {\n * 'checkout.charge': {\n * description: 'Charge a payment method',\n * attributes: {\n * 'payment.provider': { type: 'string', required: true, enum: ['stripe', 'paypal'] },\n * 'payment.amount_cents': { type: 'number', required: true },\n * },\n * },\n * },\n * });\n * ```\n */\nexport function defineContract(contract: TelemetryContract): TelemetryContract {\n assert(\n typeof contract.service === 'string' && contract.service.length > 0,\n 'contract.service must be a non-empty string',\n );\n assert(\n SEMVER_RE.test(contract.version),\n `contract.version \"${contract.version}\" is not valid semver (e.g. \"1.2.0\")`,\n );\n assert(\n contract.spans && typeof contract.spans === 'object',\n 'contract.spans must be an object',\n );\n\n for (const [spanName, spanSpec] of Object.entries(contract.spans)) {\n if (spanSpec.stability) {\n assert(\n STABILITIES.includes(spanSpec.stability),\n `span \"${spanName}\" has invalid stability \"${spanSpec.stability}\"`,\n );\n }\n for (const [key, spec] of Object.entries(spanSpec.attributes ?? {})) {\n validateAttribute(`span \"${spanName}\"`, key, spec);\n }\n }\n for (const [key, spec] of Object.entries(contract.commonAttributes ?? {})) {\n validateAttribute('common', key, spec);\n }\n for (const [name, spec] of Object.entries(contract.scenarios ?? {})) {\n validateScenarioSpec(name, spec);\n }\n\n return Object.freeze(contract);\n}\n\n/**\n * Resolve the effective attribute spec for `key` on `spanName`: span-specific\n * attributes win over common attributes. Returns `undefined` when the key is\n * declared nowhere.\n */\nexport function resolveAttributeSpec(\n contract: TelemetryContract,\n spanName: string,\n key: string,\n): AttributeSpec | undefined {\n return (\n contract.spans[spanName]?.attributes?.[key] ??\n contract.commonAttributes?.[key]\n );\n}\n\n/** Whether attributes outside the declared set are tolerated for a span. */\nexport function allowsAdditionalAttributes(\n contract: TelemetryContract,\n spanName: string,\n): boolean {\n return (\n contract.spans[spanName]?.additionalAttributes ??\n contract.additionalAttributes ??\n false\n );\n}\n","/**\n * Pure span-vs-contract validation. No SDK, no side effects — the same engine\n * the runtime processor ({@link ./processor}) and any test harness can call.\n */\n\nimport {\n allowsAdditionalAttributes,\n resolveAttributeSpec,\n type AttributeSpec,\n type AttributeType,\n type TelemetryContract,\n} from './contract.js';\n\n/** Severity of a contract violation. `error` = a breaking-shaped problem. */\nexport type ViolationSeverity = 'error' | 'warning';\n\nexport type ViolationCode =\n | 'unknown_span'\n | 'unknown_attribute'\n | 'type_mismatch'\n | 'missing_required'\n | 'deprecated_attribute'\n | 'enum_violation';\n\n/** A single discrepancy between an emitted span and the contract. */\nexport interface SchemaViolation {\n code: ViolationCode;\n severity: ViolationSeverity;\n spanName: string;\n /** Attribute key involved, when the violation is attribute-scoped. */\n attribute?: string;\n message: string;\n /** Nearest declared key, for likely typos (`unknown_attribute` only). */\n suggestion?: string;\n}\n\n/** Minimal emitted-span shape — avoids a hard dependency on the OTel SDK. */\nexport interface SpanShape {\n name: string;\n attributes: Record<string, unknown>;\n}\n\nexport interface ValidateOptions {\n /** Report `unknown_span` for span names not in the contract. Default `false`. */\n strictSpanNames?: boolean;\n}\n\n/** `'empty[]'` is a distinct marker: an empty array satisfies any array type. */\nfunction actualType(value: unknown): AttributeType | 'empty[]' | 'unknown' {\n if (typeof value === 'string') return 'string';\n if (typeof value === 'number') return 'number';\n if (typeof value === 'boolean') return 'boolean';\n if (Array.isArray(value)) {\n const first = value.find((v) => v !== null && v !== undefined);\n if (first === undefined) return 'empty[]';\n if (typeof first === 'string') return 'string[]';\n if (typeof first === 'number') return 'number[]';\n if (typeof first === 'boolean') return 'boolean[]';\n }\n return 'unknown';\n}\n\nfunction typeMatches(expected: AttributeType, value: unknown): boolean {\n const actual = actualType(value);\n if (actual === 'unknown') return false;\n if (actual === 'empty[]') return expected.endsWith('[]');\n return actual === expected;\n}\n\n/** Levenshtein distance — small, allocation-light, good enough for key typos. */\nfunction editDistance(a: string, b: string): number {\n const m = a.length;\n const n = b.length;\n if (m === 0) return n;\n if (n === 0) return m;\n let prev = Array.from({ length: n + 1 }, (_, i) => i);\n let curr = Array.from<number>({ length: n + 1 });\n for (let i = 1; i <= m; i++) {\n curr[0] = i;\n for (let j = 1; j <= n; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n curr[j] = Math.min(prev[j] + 1, curr[j - 1] + 1, prev[j - 1] + cost);\n }\n [prev, curr] = [curr, prev];\n }\n return prev[n];\n}\n\n/**\n * Closest declared key to `key`, when one is within a small edit distance.\n * Turns \"you emitted an attribute I don't know\" into \"did you mean `user.id`?\".\n */\nfunction nearestKey(key: string, candidates: string[]): string | undefined {\n let best: string | undefined;\n let bestDistance = Infinity;\n const threshold = Math.max(1, Math.floor(key.length / 4) + 1);\n for (const candidate of candidates) {\n const d = editDistance(key, candidate);\n if (d < bestDistance && d <= threshold) {\n best = candidate;\n bestDistance = d;\n }\n }\n return best;\n}\n\nfunction declaredKeysFor(\n contract: TelemetryContract,\n spanName: string,\n): string[] {\n return [\n ...Object.keys(contract.spans[spanName]?.attributes ?? {}),\n ...Object.keys(contract.commonAttributes ?? {}),\n ];\n}\n\nfunction checkValue(\n spanName: string,\n key: string,\n value: unknown,\n spec: AttributeSpec,\n out: SchemaViolation[],\n): void {\n if (!typeMatches(spec.type, value)) {\n out.push({\n code: 'type_mismatch',\n severity: 'error',\n spanName,\n attribute: key,\n message: `attribute \"${key}\" should be ${spec.type} but got ${actualType(value)}`,\n });\n return; // a wrong type makes enum/deprecation checks noise\n }\n if (\n spec.enum &&\n (typeof value === 'string' || typeof value === 'number') &&\n !spec.enum.includes(value)\n ) {\n out.push({\n code: 'enum_violation',\n severity: 'error',\n spanName,\n attribute: key,\n message: `attribute \"${key}\" value ${JSON.stringify(value)} is not one of ${JSON.stringify(spec.enum)}`,\n });\n }\n if (spec.stability === 'deprecated') {\n const hint = spec.replacedBy\n ? ` — use \"${spec.replacedBy}\" instead`\n : spec.deprecatedReason\n ? ` — ${spec.deprecatedReason}`\n : '';\n out.push({\n code: 'deprecated_attribute',\n severity: 'warning',\n spanName,\n attribute: key,\n message: `attribute \"${key}\" is deprecated${hint}`,\n suggestion: spec.replacedBy,\n });\n }\n}\n\n/**\n * Validate one emitted span against the contract, returning every discrepancy.\n * Order is deterministic: required-but-missing first, then per-attribute checks\n * in attribute insertion order.\n */\nexport function validateSpan(\n span: SpanShape,\n contract: TelemetryContract,\n options: ValidateOptions = {},\n): SchemaViolation[] {\n const out: SchemaViolation[] = [];\n const spanSpec = contract.spans[span.name];\n\n if (!spanSpec) {\n if (options.strictSpanNames) {\n out.push({\n code: 'unknown_span',\n severity: 'warning',\n spanName: span.name,\n message: `span \"${span.name}\" is not declared in the contract`,\n });\n }\n return out; // unknown span → no attribute contract to check against\n }\n\n // Required attributes that never showed up.\n const required = [\n ...Object.entries(spanSpec.attributes ?? {}),\n ...Object.entries(contract.commonAttributes ?? {}),\n ].filter(([, spec]) => spec.required);\n for (const [key] of required) {\n if (!(key in span.attributes)) {\n out.push({\n code: 'missing_required',\n severity: 'error',\n spanName: span.name,\n attribute: key,\n message: `required attribute \"${key}\" is missing`,\n });\n }\n }\n\n const allowExtra = allowsAdditionalAttributes(contract, span.name);\n const declared = allowExtra ? [] : declaredKeysFor(contract, span.name);\n\n for (const [key, value] of Object.entries(span.attributes)) {\n if (value === null || value === undefined) continue;\n const spec = resolveAttributeSpec(contract, span.name, key);\n if (!spec) {\n if (!allowExtra) {\n out.push({\n code: 'unknown_attribute',\n severity: 'warning',\n spanName: span.name,\n attribute: key,\n message: `attribute \"${key}\" is not declared on span \"${span.name}\"`,\n suggestion: nearestKey(key, declared),\n });\n }\n continue;\n }\n checkValue(span.name, key, value, spec, out);\n }\n\n return out;\n}\n\n/** `true` when any violation is `error` severity. */\nexport function hasErrors(violations: SchemaViolation[]): boolean {\n return violations.some((v) => v.severity === 'error');\n}\n\n/** One-line human/agent-readable rendering of a violation. */\nexport function formatViolation(v: SchemaViolation): string {\n const where = v.attribute ? `${v.spanName}.${v.attribute}` : v.spanName;\n const suffix = v.suggestion ? ` (did you mean \"${v.suggestion}\"?)` : '';\n return `[${v.severity}] ${v.code} @ ${where}: ${v.message}${suffix}`;\n}\n","/**\n * Runtime contract enforcement as an OpenTelemetry SpanProcessor.\n *\n * Wire it into `init({ spanProcessors: [...] })` and every span your service\n * emits is validated against the contract as it ends. In development a typo'd\n * or undeclared attribute surfaces immediately instead of silently drifting\n * the public telemetry API out from under the agents reading it.\n *\n * Fail-open by construction: a bug in validation must never break the app or\n * lose a span. Off in production by default (validation belongs in CI and dev),\n * but `enabledInProduction` is there if you want a sampled canary in prod.\n */\n\nimport {\n validateSpan,\n type SchemaViolation,\n type ValidateOptions,\n} from './validate.js';\nimport type { TelemetryContract } from './contract.js';\n\n/** Minimal ReadableSpan shape — matches OTel without a hard SDK dependency. */\nexport interface ReadableSpanLike {\n name: string;\n attributes: Record<string, unknown>;\n}\n\nexport interface SpanLike {\n spanContext(): { traceId: string; spanId: string };\n}\n\n/** Opaque parent context — matches OTel SpanProcessor without importing it. */\nexport type OtelContext = unknown;\n\nexport interface SpanProcessorLike {\n onStart(span: SpanLike, parentContext: OtelContext): void;\n onEnd(span: ReadableSpanLike): void;\n shutdown(): Promise<void>;\n forceFlush(): Promise<void>;\n}\n\n/** How the processor reacts to a contract violation. */\nexport type SchemaProcessorMode = 'warn' | 'throw' | 'silent';\n\nexport interface SchemaValidationProcessorOptions extends ValidateOptions {\n contract: TelemetryContract;\n /**\n * `warn` (default): log each distinct violation once per interval.\n * `throw`: throw on the first error-severity violation — for tests/CI only.\n * `silent`: collect via `onViolation` without logging.\n */\n mode?: SchemaProcessorMode;\n /** Called for every violation, before mode handling. */\n onViolation?: (violation: SchemaViolation, span: ReadableSpanLike) => void;\n /** Override the warn sink (defaults to `console.warn`). */\n onWarn?: (message: string) => void;\n /** Run even when `NODE_ENV === 'production'`. Default `false`. */\n enabledInProduction?: boolean;\n /** Throttle window for repeated identical warnings (ms). Default 60s. */\n warnIntervalMs?: number;\n}\n\nconst DEFAULT_WARN_INTERVAL_MS = 60_000;\n\nfunction isProduction(): boolean {\n return process.env.NODE_ENV === 'production';\n}\n\n/**\n * Validates each ending span against a {@link TelemetryContract}. Bounded,\n * deduplicated warnings; fail-open on any internal error.\n */\nexport class SchemaValidationSpanProcessor implements SpanProcessorLike {\n private readonly opts: SchemaValidationProcessorOptions;\n private readonly enabled: boolean;\n private readonly warnIntervalMs: number;\n private readonly lastWarnAt = new Map<string, number>();\n private violationCount = 0;\n\n constructor(opts: SchemaValidationProcessorOptions) {\n this.opts = opts;\n this.enabled = opts.enabledInProduction === true || !isProduction();\n this.warnIntervalMs = opts.warnIntervalMs ?? DEFAULT_WARN_INTERVAL_MS;\n }\n\n /** Number of violations seen since startup (across all spans). */\n get totalViolations(): number {\n return this.violationCount;\n }\n\n onStart(_span: SpanLike, _parentContext: OtelContext): void {\n // no-op — validation happens once the span is complete\n }\n\n onEnd(span: ReadableSpanLike): void {\n if (!this.enabled) return;\n let violations: SchemaViolation[];\n try {\n // Validation itself is fail-open: a bug here must never break export.\n violations = validateSpan(\n { name: span.name, attributes: span.attributes },\n this.opts.contract,\n { strictSpanNames: this.opts.strictSpanNames },\n );\n } catch {\n return;\n }\n // Mode handling runs outside the fail-open guard so `throw` mode propagates.\n for (const violation of violations) {\n this.violationCount++;\n this.opts.onViolation?.(violation, span);\n this.handle(violation);\n }\n }\n\n private handle(violation: SchemaViolation): void {\n const mode = this.opts.mode ?? 'warn';\n if (mode === 'silent') return;\n if (mode === 'throw' && violation.severity === 'error') {\n throw new Error(\n `autotel-schema: contract violation (${violation.code}) on span \"${violation.spanName}\": ${violation.message}`,\n );\n }\n this.maybeWarn(violation);\n }\n\n private maybeWarn(violation: SchemaViolation): void {\n const key = `${violation.code}:${violation.spanName}:${violation.attribute ?? ''}`;\n const now = Date.now();\n const last = this.lastWarnAt.get(key) ?? 0;\n if (now - last < this.warnIntervalMs) return;\n this.lastWarnAt.set(key, now);\n const suffix = violation.suggestion\n ? ` (did you mean \"${violation.suggestion}\"?)`\n : '';\n const message = `autotel-schema [${violation.severity}] ${violation.code} on \"${violation.spanName}\"${violation.attribute ? `.${violation.attribute}` : ''}: ${violation.message}${suffix}`;\n if (this.opts.onWarn) {\n this.opts.onWarn(message);\n } else {\n console.warn(message);\n }\n }\n\n async forceFlush(): Promise<void> {\n // nothing buffered — validation is synchronous in onEnd\n }\n\n async shutdown(): Promise<void> {\n this.lastWarnAt.clear();\n }\n}\n\nexport function createSchemaValidationProcessor(\n opts: SchemaValidationProcessorOptions,\n): SchemaValidationSpanProcessor {\n return new SchemaValidationSpanProcessor(opts);\n}\n"],"mappings":";;;;;;AA8DA,SAAgB,iBAAiB,OAA0C;CACzE,IAAI,OAAO,UAAU,UAAU;EAC7B,SACE,OAAO,UAAU,MAAM,GAAG,KAAK,MAAM,OAAO,GAC5C,uDAAuD,MAAM,KAC/D;EACA,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AG,IAAI,UAAU,UAAU;EACnL,IAAI,KAAK,KAAK,QACZ,KAAK,KAAK,OAAO,OAAO;OAExB,QAAQ,KAAK,OAAO;CAExB;CAEA,MAAM,aAA4B,CAElC;CAEA,MAAM,WAA0B;EAC9B,KAAK,WAAW,MAAM;CACxB;AACF;AAEA,SAAgB,gCACd,MAC+B;CAC/B,OAAO,IAAI,8BAA8B,IAAI;AAC/C"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"processor-TpuacLr5.d.ts","names":[],"sources":["../src/validate.ts","../src/processor.ts"],"mappings":";;;KAcY;KAEA;;UASK;EACf,MAAM;EACN,UAAU;EACV;;EAEA;EACA;;EAEA;;;UAIe;EACf;EACA,YAAY;;UAGG;;EAEf;;;;;;;iBA4Hc,aACd,MAAM,WACN,UAAU,mBACV,UAAS,kBACR;;iBA2Da,UAAU,YAAY;;iBAKtB,gBAAgB,GAAG;;;;UCvNlB;EACf;EACA,YAAY;;UAGG;EACf;IAAiB;IAAiB;;;;KAIxB;UAEK;EACf,QAAQ,MAAM,UAAU,eAAe;EACvC,MAAM,MAAM;EACZ,YAAY;EACZ,cAAc;;;KAIJ;UAEK,yCAAyC;EACxD,UAAU;;;;;;EAMV,OAAO;;EAEP,eAAe,WAAW,iBAAiB,MAAM;;EAEjD,UAAU;;EAEV;;EAEA;;;;;;cAaW,yCAAyC;mBACnC;mBACA;mBACA;mBACA;UACT;EAEI,YAAA,MAAM;;MAOd;EAIJ,QAAQ,OAAO,UAAU,gBAAgB;EAIzC,MAAM,MAAM;UAqBJ;UAWA;EAiBF,cAAc;EAId,YAAY;;iBAKJ,gCACd,MAAM,mCACL"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"snapshot-CyWGJaJT.cjs","names":[],"sources":["../src/attrs.ts","../src/snapshot.ts"],"sourcesContent":["/**\n * Wire constants for the schema contract — the keys autotel-schema reads from\n * and stamps onto spans. Dependency-free so CLI, browser, and edge code can\n * share the exact same strings the runtime uses.\n */\n\n/**\n * Resource/span attributes that announce the contract to a reader. Stamping\n * `telemetry.schema.version` means an agent following a trace knows *which*\n * version of your public telemetry API it is looking at — the difference\n * between \"confidently correct\" and \"confidently wrong\" after a rename.\n */\nexport const SCHEMA_ATTRS = {\n /** The service this contract describes (mirrors `service.name`). */\n SERVICE: 'telemetry.schema.service',\n /** Semver of the telemetry contract that produced this span. */\n VERSION: 'telemetry.schema.version',\n} as const;\n\nexport type SchemaAttributeKey =\n (typeof SCHEMA_ATTRS)[keyof typeof SCHEMA_ATTRS];\n\n/** Snapshot file spec marker — bump only on a breaking snapshot format change. */\nexport const SNAPSHOT_SPEC = 'autotel-schema-snapshot/v1' as const;\n","/**\n * Snapshots — the serializable form of a contract that gets committed and\n * diffed across versions. Checking a snapshot into the repo turns \"did this\n * refactor rename a span?\" into a reviewable line in a PR instead of a silent\n * break the agent reader discovers at 3am.\n */\n\nimport { SNAPSHOT_SPEC } from './attrs.js';\nimport type {\n AttributeSpec,\n AttributeType,\n Stability,\n TelemetryContract,\n} from './contract.js';\n\n/** Flattened, fully-resolved attribute record in a snapshot. */\nexport interface SnapshotAttribute {\n type: AttributeType;\n stability: Stability;\n required: boolean;\n highCardinality: boolean;\n enum?: readonly (string | number)[];\n replacedBy?: string;\n description?: string;\n}\n\nexport interface SnapshotSpan {\n stability: Stability;\n additionalAttributes: boolean;\n description?: string;\n attributes: Record<string, SnapshotAttribute>;\n}\n\n/** Canonical, comparable representation of a {@link TelemetryContract}. */\nexport interface ContractSnapshot {\n spec: typeof SNAPSHOT_SPEC;\n service: string;\n version: string;\n commonAttributes: Record<string, SnapshotAttribute>;\n spans: Record<string, SnapshotSpan>;\n}\n\nfunction normalizeAttribute(spec: AttributeSpec): SnapshotAttribute {\n const out: SnapshotAttribute = {\n type: spec.type,\n stability: spec.stability ?? 'stable',\n required: spec.required ?? false,\n highCardinality: spec.highCardinality ?? false,\n };\n if (spec.enum) out.enum = [...spec.enum];\n if (spec.replacedBy) out.replacedBy = spec.replacedBy;\n if (spec.description) out.description = spec.description;\n return out;\n}\n\nfunction sortRecord<T>(record: Record<string, T>): Record<string, T> {\n const out: Record<string, T> = {};\n for (const key of Object.keys(record).toSorted()) {\n out[key] = record[key];\n }\n return out;\n}\n\n/**\n * Produce a deterministic, JSON-serializable snapshot from a contract. Keys are\n * sorted so two snapshots of the same logical contract are byte-identical —\n * important for clean `git diff`s and stable CI comparisons.\n */\nexport function contractToSnapshot(\n contract: TelemetryContract,\n): ContractSnapshot {\n const commonAttributes: Record<string, SnapshotAttribute> = {};\n for (const [key, spec] of Object.entries(contract.commonAttributes ?? {})) {\n commonAttributes[key] = normalizeAttribute(spec);\n }\n\n const spans: Record<string, SnapshotSpan> = {};\n for (const [name, spanSpec] of Object.entries(contract.spans)) {\n const attributes: Record<string, SnapshotAttribute> = {};\n for (const [key, spec] of Object.entries(spanSpec.attributes ?? {})) {\n attributes[key] = normalizeAttribute(spec);\n }\n const span: SnapshotSpan = {\n stability: spanSpec.stability ?? 'stable',\n additionalAttributes:\n spanSpec.additionalAttributes ?? contract.additionalAttributes ?? false,\n attributes: sortRecord(attributes),\n };\n if (spanSpec.description) span.description = spanSpec.description;\n spans[name] = span;\n }\n\n return {\n spec: SNAPSHOT_SPEC,\n service: contract.service,\n version: contract.version,\n commonAttributes: sortRecord(commonAttributes),\n spans: sortRecord(spans),\n };\n}\n\n/** Pretty, deterministic JSON for writing a snapshot to disk. */\nexport function serializeSnapshot(snapshot: ContractSnapshot): string {\n return JSON.stringify(snapshot, null, 2) + '\\n';\n}\n\n/** Parse and structurally validate a snapshot read from disk. */\nexport function parseSnapshot(json: string): ContractSnapshot {\n const data = JSON.parse(json) as ContractSnapshot;\n if (data.spec !== SNAPSHOT_SPEC) {\n throw new Error(\n `autotel-schema: unexpected snapshot spec \"${data.spec}\" (expected \"${SNAPSHOT_SPEC}\")`,\n );\n }\n if (typeof data.service !== 'string' || typeof data.version !== 'string') {\n throw new Error('autotel-schema: snapshot is missing service/version');\n }\n return data;\n}\n"],"mappings":";;;;;;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,OAAO,WAAW,KAAK;CACzB;AACF;;AAGA,SAAgB,kBAAkB,UAAoC;CACpE,OAAO,KAAK,UAAU,UAAU,MAAM,CAAC,IAAI;AAC7C;;AAGA,SAAgB,cAAc,MAAgC;CAC5D,MAAM,OAAO,KAAK,MAAM,IAAI;CAC5B,IAAI,KAAK,uCACP,MAAM,IAAI,MACR,6CAA6C,KAAK,KAAK,eAAe,cAAc,GACtF;CAEF,IAAI,OAAO,KAAK,YAAY,YAAY,OAAO,KAAK,YAAY,UAC9D,MAAM,IAAI,MAAM,qDAAqD;CAEvE,OAAO;AACT"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"snapshot-h8pb_Up_.js","names":[],"sources":["../src/attrs.ts","../src/snapshot.ts"],"sourcesContent":["/**\n * Wire constants for the schema contract — the keys autotel-schema reads from\n * and stamps onto spans. Dependency-free so CLI, browser, and edge code can\n * share the exact same strings the runtime uses.\n */\n\n/**\n * Resource/span attributes that announce the contract to a reader. Stamping\n * `telemetry.schema.version` means an agent following a trace knows *which*\n * version of your public telemetry API it is looking at — the difference\n * between \"confidently correct\" and \"confidently wrong\" after a rename.\n */\nexport const SCHEMA_ATTRS = {\n /** The service this contract describes (mirrors `service.name`). */\n SERVICE: 'telemetry.schema.service',\n /** Semver of the telemetry contract that produced this span. */\n VERSION: 'telemetry.schema.version',\n} as const;\n\nexport type SchemaAttributeKey =\n (typeof SCHEMA_ATTRS)[keyof typeof SCHEMA_ATTRS];\n\n/** Snapshot file spec marker — bump only on a breaking snapshot format change. */\nexport const SNAPSHOT_SPEC = 'autotel-schema-snapshot/v1' as const;\n","/**\n * Snapshots — the serializable form of a contract that gets committed and\n * diffed across versions. Checking a snapshot into the repo turns \"did this\n * refactor rename a span?\" into a reviewable line in a PR instead of a silent\n * break the agent reader discovers at 3am.\n */\n\nimport { SNAPSHOT_SPEC } from './attrs.js';\nimport type {\n AttributeSpec,\n AttributeType,\n Stability,\n TelemetryContract,\n} from './contract.js';\n\n/** Flattened, fully-resolved attribute record in a snapshot. */\nexport interface SnapshotAttribute {\n type: AttributeType;\n stability: Stability;\n required: boolean;\n highCardinality: boolean;\n enum?: readonly (string | number)[];\n replacedBy?: string;\n description?: string;\n}\n\nexport interface SnapshotSpan {\n stability: Stability;\n additionalAttributes: boolean;\n description?: string;\n attributes: Record<string, SnapshotAttribute>;\n}\n\n/** Canonical, comparable representation of a {@link TelemetryContract}. */\nexport interface ContractSnapshot {\n spec: typeof SNAPSHOT_SPEC;\n service: string;\n version: string;\n commonAttributes: Record<string, SnapshotAttribute>;\n spans: Record<string, SnapshotSpan>;\n}\n\nfunction normalizeAttribute(spec: AttributeSpec): SnapshotAttribute {\n const out: SnapshotAttribute = {\n type: spec.type,\n stability: spec.stability ?? 'stable',\n required: spec.required ?? false,\n highCardinality: spec.highCardinality ?? false,\n };\n if (spec.enum) out.enum = [...spec.enum];\n if (spec.replacedBy) out.replacedBy = spec.replacedBy;\n if (spec.description) out.description = spec.description;\n return out;\n}\n\nfunction sortRecord<T>(record: Record<string, T>): Record<string, T> {\n const out: Record<string, T> = {};\n for (const key of Object.keys(record).toSorted()) {\n out[key] = record[key];\n }\n return out;\n}\n\n/**\n * Produce a deterministic, JSON-serializable snapshot from a contract. Keys are\n * sorted so two snapshots of the same logical contract are byte-identical —\n * important for clean `git diff`s and stable CI comparisons.\n */\nexport function contractToSnapshot(\n contract: TelemetryContract,\n): ContractSnapshot {\n const commonAttributes: Record<string, SnapshotAttribute> = {};\n for (const [key, spec] of Object.entries(contract.commonAttributes ?? {})) {\n commonAttributes[key] = normalizeAttribute(spec);\n }\n\n const spans: Record<string, SnapshotSpan> = {};\n for (const [name, spanSpec] of Object.entries(contract.spans)) {\n const attributes: Record<string, SnapshotAttribute> = {};\n for (const [key, spec] of Object.entries(spanSpec.attributes ?? {})) {\n attributes[key] = normalizeAttribute(spec);\n }\n const span: SnapshotSpan = {\n stability: spanSpec.stability ?? 'stable',\n additionalAttributes:\n spanSpec.additionalAttributes ?? contract.additionalAttributes ?? false,\n attributes: sortRecord(attributes),\n };\n if (spanSpec.description) span.description = spanSpec.description;\n spans[name] = span;\n }\n\n return {\n spec: SNAPSHOT_SPEC,\n service: contract.service,\n version: contract.version,\n commonAttributes: sortRecord(commonAttributes),\n spans: sortRecord(spans),\n };\n}\n\n/** Pretty, deterministic JSON for writing a snapshot to disk. */\nexport function serializeSnapshot(snapshot: ContractSnapshot): string {\n return JSON.stringify(snapshot, null, 2) + '\\n';\n}\n\n/** Parse and structurally validate a snapshot read from disk. */\nexport function parseSnapshot(json: string): ContractSnapshot {\n const data = JSON.parse(json) as ContractSnapshot;\n if (data.spec !== SNAPSHOT_SPEC) {\n throw new Error(\n `autotel-schema: unexpected snapshot spec \"${data.spec}\" (expected \"${SNAPSHOT_SPEC}\")`,\n );\n }\n if (typeof data.service !== 'string' || typeof data.version !== 'string') {\n throw new Error('autotel-schema: snapshot is missing service/version');\n }\n return data;\n}\n"],"mappings":";;;;;;;;;;;;AAYA,MAAa,eAAe;;CAE1B,SAAS;;CAET,SAAS;AACX;;AAMA,MAAa,gBAAgB;;;;;;;;;;ACmB7B,SAAS,mBAAmB,MAAwC;CAClE,MAAM,MAAyB;EAC7B,MAAM,KAAK;EACX,WAAW,KAAK,aAAa;EAC7B,UAAU,KAAK,YAAY;EAC3B,iBAAiB,KAAK,mBAAmB;CAC3C;CACA,IAAI,KAAK,MAAM,IAAI,OAAO,CAAC,GAAG,KAAK,IAAI;CACvC,IAAI,KAAK,YAAY,IAAI,aAAa,KAAK;CAC3C,IAAI,KAAK,aAAa,IAAI,cAAc,KAAK;CAC7C,OAAO;AACT;AAEA,SAAS,WAAc,QAA8C;CACnE,MAAM,MAAyB,CAAC;CAChC,KAAK,MAAM,OAAO,OAAO,KAAK,MAAM,CAAC,CAAC,SAAS,GAC7C,IAAI,OAAO,OAAO;CAEpB,OAAO;AACT;;;;;;AAOA,SAAgB,mBACd,UACkB;CAClB,MAAM,mBAAsD,CAAC;CAC7D,KAAK,MAAM,CAAC,KAAK,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