@contractspec/lib.observability 1.57.0 → 1.58.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 (77) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/anomaly/alert-manager.d.ts +17 -0
  3. package/dist/anomaly/alert-manager.js +24 -0
  4. package/dist/anomaly/anomaly-detector.d.ts +22 -0
  5. package/dist/anomaly/anomaly-detector.js +102 -0
  6. package/dist/anomaly/baseline-calculator.d.ts +23 -0
  7. package/dist/anomaly/baseline-calculator.js +40 -0
  8. package/dist/anomaly/root-cause-analyzer.d.ts +19 -0
  9. package/dist/anomaly/root-cause-analyzer.js +32 -0
  10. package/dist/index.d.ts +16 -0
  11. package/dist/index.js +1078 -0
  12. package/dist/intent/aggregator.d.ts +57 -0
  13. package/dist/intent/aggregator.js +110 -0
  14. package/dist/intent/detector.d.ts +28 -0
  15. package/dist/intent/detector.js +133 -0
  16. package/dist/logging/index.d.ts +17 -0
  17. package/dist/logging/index.js +42 -0
  18. package/dist/metrics/index.d.ts +12 -0
  19. package/dist/metrics/index.js +31 -0
  20. package/dist/node/anomaly/alert-manager.js +23 -0
  21. package/dist/node/anomaly/anomaly-detector.js +101 -0
  22. package/dist/node/anomaly/baseline-calculator.js +39 -0
  23. package/dist/node/anomaly/root-cause-analyzer.js +31 -0
  24. package/dist/node/index.js +1077 -0
  25. package/dist/node/intent/aggregator.js +109 -0
  26. package/dist/node/intent/detector.js +132 -0
  27. package/dist/node/logging/index.js +41 -0
  28. package/dist/node/metrics/index.js +30 -0
  29. package/dist/node/pipeline/evolution-pipeline.js +299 -0
  30. package/dist/node/pipeline/lifecycle-pipeline.js +85 -0
  31. package/dist/node/telemetry/posthog-baseline-reader.js +308 -0
  32. package/dist/node/telemetry/posthog-telemetry.js +60 -0
  33. package/dist/node/tracing/index.js +52 -0
  34. package/dist/node/tracing/middleware.js +150 -0
  35. package/dist/pipeline/evolution-pipeline.d.ts +36 -0
  36. package/dist/pipeline/evolution-pipeline.js +300 -0
  37. package/dist/pipeline/lifecycle-pipeline.d.ts +40 -0
  38. package/dist/pipeline/lifecycle-pipeline.js +86 -0
  39. package/dist/telemetry/posthog-baseline-reader.d.ts +27 -0
  40. package/dist/telemetry/posthog-baseline-reader.js +309 -0
  41. package/dist/telemetry/posthog-telemetry.d.ts +15 -0
  42. package/dist/telemetry/posthog-telemetry.js +61 -0
  43. package/dist/tracing/index.d.ts +5 -0
  44. package/dist/tracing/index.js +53 -0
  45. package/dist/tracing/middleware.d.ts +15 -0
  46. package/dist/tracing/middleware.js +151 -0
  47. package/package.json +140 -43
  48. package/dist/anomaly/alert-manager.d.mts +0 -21
  49. package/dist/anomaly/alert-manager.mjs +0 -23
  50. package/dist/anomaly/anomaly-detector.d.mts +0 -26
  51. package/dist/anomaly/anomaly-detector.mjs +0 -58
  52. package/dist/anomaly/baseline-calculator.d.mts +0 -26
  53. package/dist/anomaly/baseline-calculator.mjs +0 -37
  54. package/dist/anomaly/root-cause-analyzer.d.mts +0 -23
  55. package/dist/anomaly/root-cause-analyzer.mjs +0 -27
  56. package/dist/index.d.mts +0 -15
  57. package/dist/index.mjs +0 -16
  58. package/dist/intent/aggregator.d.mts +0 -60
  59. package/dist/intent/aggregator.mjs +0 -98
  60. package/dist/intent/detector.d.mts +0 -32
  61. package/dist/intent/detector.mjs +0 -122
  62. package/dist/logging/index.d.mts +0 -20
  63. package/dist/logging/index.mjs +0 -40
  64. package/dist/metrics/index.d.mts +0 -17
  65. package/dist/metrics/index.mjs +0 -26
  66. package/dist/pipeline/evolution-pipeline.d.mts +0 -40
  67. package/dist/pipeline/evolution-pipeline.mjs +0 -66
  68. package/dist/pipeline/lifecycle-pipeline.d.mts +0 -44
  69. package/dist/pipeline/lifecycle-pipeline.mjs +0 -73
  70. package/dist/telemetry/posthog-baseline-reader.d.mts +0 -31
  71. package/dist/telemetry/posthog-baseline-reader.mjs +0 -266
  72. package/dist/telemetry/posthog-telemetry.d.mts +0 -19
  73. package/dist/telemetry/posthog-telemetry.mjs +0 -61
  74. package/dist/tracing/index.d.mts +0 -9
  75. package/dist/tracing/index.mjs +0 -47
  76. package/dist/tracing/middleware.d.mts +0 -19
  77. package/dist/tracing/middleware.mjs +0 -80
@@ -0,0 +1,300 @@
1
+ // @bun
2
+ // src/intent/aggregator.ts
3
+ var DEFAULT_WINDOW_MS = 15 * 60 * 1000;
4
+
5
+ class IntentAggregator {
6
+ windowMs;
7
+ sequenceSampleSize;
8
+ samples = [];
9
+ constructor(options = {}) {
10
+ this.windowMs = options.windowMs ?? DEFAULT_WINDOW_MS;
11
+ this.sequenceSampleSize = options.sequenceSampleSize ?? 1000;
12
+ }
13
+ add(sample) {
14
+ this.samples.push(sample);
15
+ }
16
+ flush(now = new Date) {
17
+ const minTimestamp = now.getTime() - this.windowMs;
18
+ const windowSamples = this.samples.filter((sample) => sample.timestamp.getTime() >= minTimestamp);
19
+ this.samples.length = 0;
20
+ const metrics = this.aggregateMetrics(windowSamples);
21
+ const sequences = this.buildSequences(windowSamples);
22
+ const timestamps = windowSamples.map((sample) => sample.timestamp.getTime());
23
+ return {
24
+ metrics,
25
+ sequences,
26
+ sampleCount: windowSamples.length,
27
+ windowStart: timestamps.length ? new Date(Math.min(...timestamps)) : undefined,
28
+ windowEnd: timestamps.length ? new Date(Math.max(...timestamps)) : undefined
29
+ };
30
+ }
31
+ aggregateMetrics(samples) {
32
+ if (!samples.length)
33
+ return [];
34
+ const groups = new Map;
35
+ for (const sample of samples) {
36
+ const key = `${sample.operation.name}.v${sample.operation.version}`;
37
+ const arr = groups.get(key) ?? [];
38
+ arr.push(sample);
39
+ groups.set(key, arr);
40
+ }
41
+ return [...groups.values()].map((group) => {
42
+ const first = group[0];
43
+ if (!first)
44
+ throw new Error("Empty group in aggregation");
45
+ const durations = group.map((s) => s.durationMs).sort((a, b) => a - b);
46
+ const errors = group.filter((s) => !s.success);
47
+ const totalCalls = group.length;
48
+ const topErrors = errors.reduce((acc, sample) => {
49
+ if (!sample.errorCode)
50
+ return acc;
51
+ acc[sample.errorCode] = (acc[sample.errorCode] ?? 0) + 1;
52
+ return acc;
53
+ }, {});
54
+ const timestamps = group.map((s) => s.timestamp.getTime());
55
+ return {
56
+ operation: first.operation,
57
+ totalCalls,
58
+ successRate: (totalCalls - errors.length) / totalCalls,
59
+ errorRate: errors.length / totalCalls,
60
+ averageLatencyMs: durations.reduce((sum, value) => sum + value, 0) / totalCalls,
61
+ p95LatencyMs: percentile(durations, 0.95),
62
+ p99LatencyMs: percentile(durations, 0.99),
63
+ maxLatencyMs: Math.max(...durations),
64
+ windowStart: new Date(Math.min(...timestamps)),
65
+ windowEnd: new Date(Math.max(...timestamps)),
66
+ topErrors
67
+ };
68
+ });
69
+ }
70
+ buildSequences(samples) {
71
+ const byTrace = new Map;
72
+ for (const sample of samples.slice(-this.sequenceSampleSize)) {
73
+ if (!sample.traceId)
74
+ continue;
75
+ const arr = byTrace.get(sample.traceId) ?? [];
76
+ arr.push(sample);
77
+ byTrace.set(sample.traceId, arr);
78
+ }
79
+ const sequences = {};
80
+ for (const events of byTrace.values()) {
81
+ const ordered = events.sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime());
82
+ const steps = ordered.map((event) => event.operation.name);
83
+ if (steps.length < 2)
84
+ continue;
85
+ const key = `${steps.join(">")}@${ordered[0]?.tenantId ?? "global"}`;
86
+ const existing = sequences[key];
87
+ if (existing) {
88
+ existing.count += 1;
89
+ } else {
90
+ sequences[key] = {
91
+ steps,
92
+ tenantId: ordered[0]?.tenantId,
93
+ count: 1
94
+ };
95
+ }
96
+ }
97
+ return Object.values(sequences).sort((a, b) => b.count - a.count);
98
+ }
99
+ }
100
+ function percentile(values, ratio) {
101
+ if (!values.length)
102
+ return 0;
103
+ if (values.length === 1)
104
+ return values[0] ?? 0;
105
+ const index = Math.min(values.length - 1, Math.floor(ratio * values.length));
106
+ return values[index] ?? 0;
107
+ }
108
+
109
+ // src/intent/detector.ts
110
+ import { randomUUID } from "crypto";
111
+ var DEFAULTS = {
112
+ errorRateThreshold: 0.05,
113
+ latencyP99ThresholdMs: 750,
114
+ throughputDropThreshold: 0.3,
115
+ minSequenceLength: 3
116
+ };
117
+
118
+ class IntentDetector {
119
+ options;
120
+ constructor(options = {}) {
121
+ this.options = {
122
+ errorRateThreshold: options.errorRateThreshold ?? DEFAULTS.errorRateThreshold,
123
+ latencyP99ThresholdMs: options.latencyP99ThresholdMs ?? DEFAULTS.latencyP99ThresholdMs,
124
+ throughputDropThreshold: options.throughputDropThreshold ?? DEFAULTS.throughputDropThreshold,
125
+ minSequenceLength: options.minSequenceLength ?? DEFAULTS.minSequenceLength
126
+ };
127
+ }
128
+ detectFromMetrics(current, previous) {
129
+ const signals = [];
130
+ const baseline = new Map((previous ?? []).map((metric) => [
131
+ `${metric.operation.name}.v${metric.operation.version}`,
132
+ metric
133
+ ]));
134
+ for (const metric of current) {
135
+ if (metric.errorRate >= this.options.errorRateThreshold) {
136
+ signals.push({
137
+ id: randomUUID(),
138
+ type: "error-spike",
139
+ operation: metric.operation,
140
+ confidence: Math.min(1, metric.errorRate / this.options.errorRateThreshold),
141
+ description: `Error rate ${metric.errorRate.toFixed(2)} exceeded threshold`,
142
+ metadata: {
143
+ errorRate: metric.errorRate,
144
+ topErrors: metric.topErrors
145
+ },
146
+ evidence: [
147
+ {
148
+ type: "metric",
149
+ description: "error-rate",
150
+ data: {
151
+ errorRate: metric.errorRate,
152
+ threshold: this.options.errorRateThreshold
153
+ }
154
+ }
155
+ ]
156
+ });
157
+ continue;
158
+ }
159
+ if (metric.p99LatencyMs >= this.options.latencyP99ThresholdMs) {
160
+ signals.push({
161
+ id: randomUUID(),
162
+ type: "latency-regression",
163
+ operation: metric.operation,
164
+ confidence: Math.min(1, metric.p99LatencyMs / this.options.latencyP99ThresholdMs),
165
+ description: `P99 latency ${metric.p99LatencyMs}ms exceeded threshold`,
166
+ metadata: { p99LatencyMs: metric.p99LatencyMs },
167
+ evidence: [
168
+ {
169
+ type: "metric",
170
+ description: "p99-latency",
171
+ data: {
172
+ p99LatencyMs: metric.p99LatencyMs,
173
+ threshold: this.options.latencyP99ThresholdMs
174
+ }
175
+ }
176
+ ]
177
+ });
178
+ continue;
179
+ }
180
+ const base = baseline.get(`${metric.operation.name}.v${metric.operation.version}`);
181
+ if (base) {
182
+ const drop = (base.totalCalls - metric.totalCalls) / Math.max(base.totalCalls, 1);
183
+ if (drop >= this.options.throughputDropThreshold) {
184
+ signals.push({
185
+ id: randomUUID(),
186
+ type: "throughput-drop",
187
+ operation: metric.operation,
188
+ confidence: Math.min(1, drop / this.options.throughputDropThreshold),
189
+ description: `Throughput dropped ${(drop * 100).toFixed(1)}% vs baseline`,
190
+ metadata: {
191
+ baselineCalls: base.totalCalls,
192
+ currentCalls: metric.totalCalls
193
+ },
194
+ evidence: [
195
+ {
196
+ type: "metric",
197
+ description: "throughput-drop",
198
+ data: {
199
+ baselineCalls: base.totalCalls,
200
+ currentCalls: metric.totalCalls
201
+ }
202
+ }
203
+ ]
204
+ });
205
+ }
206
+ }
207
+ }
208
+ return signals;
209
+ }
210
+ detectSequentialIntents(sequences) {
211
+ const signals = [];
212
+ for (const sequence of sequences) {
213
+ if (sequence.steps.length < this.options.minSequenceLength)
214
+ continue;
215
+ const description = sequence.steps.join(" \u2192 ");
216
+ signals.push({
217
+ id: randomUUID(),
218
+ type: "missing-workflow-step",
219
+ confidence: 0.6,
220
+ description: `Repeated workflow detected: ${description}`,
221
+ metadata: {
222
+ steps: sequence.steps,
223
+ tenantId: sequence.tenantId,
224
+ occurrences: sequence.count
225
+ },
226
+ evidence: [
227
+ {
228
+ type: "sequence",
229
+ description: "sequential-calls",
230
+ data: { steps: sequence.steps, count: sequence.count }
231
+ }
232
+ ]
233
+ });
234
+ }
235
+ return signals;
236
+ }
237
+ }
238
+
239
+ // src/pipeline/evolution-pipeline.ts
240
+ import { EventEmitter } from "events";
241
+ class EvolutionPipeline {
242
+ detector;
243
+ aggregator;
244
+ emitter;
245
+ onIntent;
246
+ onSnapshot;
247
+ timer;
248
+ previousMetrics;
249
+ constructor(options = {}) {
250
+ this.detector = options.detector ?? new IntentDetector;
251
+ this.aggregator = options.aggregator ?? new IntentAggregator;
252
+ this.emitter = options.emitter ?? new EventEmitter;
253
+ this.onIntent = options.onIntent;
254
+ this.onSnapshot = options.onSnapshot;
255
+ }
256
+ ingest(sample) {
257
+ this.aggregator.add(sample);
258
+ }
259
+ on(listener) {
260
+ this.emitter.on("event", listener);
261
+ }
262
+ start(intervalMs = 5 * 60 * 1000) {
263
+ this.stop();
264
+ this.timer = setInterval(() => {
265
+ this.run();
266
+ }, intervalMs);
267
+ }
268
+ stop() {
269
+ if (this.timer) {
270
+ clearInterval(this.timer);
271
+ this.timer = undefined;
272
+ }
273
+ }
274
+ async run() {
275
+ const snapshot = this.aggregator.flush();
276
+ this.emit({
277
+ type: "telemetry.window",
278
+ payload: { sampleCount: snapshot.sampleCount }
279
+ });
280
+ if (this.onSnapshot)
281
+ await this.onSnapshot(snapshot);
282
+ if (!snapshot.sampleCount)
283
+ return;
284
+ const metricSignals = this.detector.detectFromMetrics(snapshot.metrics, this.previousMetrics);
285
+ const sequenceSignals = this.detector.detectSequentialIntents(snapshot.sequences);
286
+ this.previousMetrics = snapshot.metrics;
287
+ const signals = [...metricSignals, ...sequenceSignals];
288
+ for (const signal of signals) {
289
+ if (this.onIntent)
290
+ await this.onIntent(signal);
291
+ this.emit({ type: "intent.detected", payload: signal });
292
+ }
293
+ }
294
+ emit(event) {
295
+ this.emitter.emit("event", event);
296
+ }
297
+ }
298
+ export {
299
+ EvolutionPipeline
300
+ };
@@ -0,0 +1,40 @@
1
+ import { EventEmitter } from 'node:events';
2
+ import type { LifecycleAssessment, LifecycleStage } from '@contractspec/lib.lifecycle';
3
+ export type LifecyclePipelineEvent = {
4
+ type: 'assessment.recorded';
5
+ payload: {
6
+ tenantId?: string;
7
+ stage: LifecycleStage;
8
+ };
9
+ } | {
10
+ type: 'stage.changed';
11
+ payload: {
12
+ tenantId?: string;
13
+ previousStage?: LifecycleStage;
14
+ nextStage: LifecycleStage;
15
+ };
16
+ } | {
17
+ type: 'confidence.low';
18
+ payload: {
19
+ tenantId?: string;
20
+ confidence: number;
21
+ };
22
+ };
23
+ export interface LifecycleKpiPipelineOptions {
24
+ meterName?: string;
25
+ emitter?: EventEmitter;
26
+ lowConfidenceThreshold?: number;
27
+ }
28
+ export declare class LifecycleKpiPipeline {
29
+ private readonly assessmentCounter;
30
+ private readonly confidenceHistogram;
31
+ private readonly stageUpDownCounter;
32
+ private readonly emitter;
33
+ private readonly lowConfidenceThreshold;
34
+ private readonly currentStageByTenant;
35
+ constructor(options?: LifecycleKpiPipelineOptions);
36
+ recordAssessment(assessment: LifecycleAssessment, tenantId?: string): void;
37
+ on(listener: (event: LifecyclePipelineEvent) => void): void;
38
+ private ensureStageCounters;
39
+ }
40
+ //# sourceMappingURL=lifecycle-pipeline.d.ts.map
@@ -0,0 +1,86 @@
1
+ // @bun
2
+ // src/metrics/index.ts
3
+ import {
4
+ metrics
5
+ } from "@opentelemetry/api";
6
+ var DEFAULT_METER_NAME = "@contractspec/lib.observability";
7
+ function getMeter(name = DEFAULT_METER_NAME) {
8
+ return metrics.getMeter(name);
9
+ }
10
+ function createCounter(name, description, meterName) {
11
+ return getMeter(meterName).createCounter(name, { description });
12
+ }
13
+ function createUpDownCounter(name, description, meterName) {
14
+ return getMeter(meterName).createUpDownCounter(name, { description });
15
+ }
16
+ function createHistogram(name, description, meterName) {
17
+ return getMeter(meterName).createHistogram(name, { description });
18
+ }
19
+ var standardMetrics = {
20
+ httpRequests: createCounter("http_requests_total", "Total HTTP requests"),
21
+ httpDuration: createHistogram("http_request_duration_seconds", "HTTP request duration"),
22
+ operationErrors: createCounter("operation_errors_total", "Total operation errors"),
23
+ workflowDuration: createHistogram("workflow_duration_seconds", "Workflow execution duration")
24
+ };
25
+
26
+ // src/pipeline/lifecycle-pipeline.ts
27
+ import { EventEmitter } from "events";
28
+ import { getStageLabel } from "@contractspec/lib.lifecycle";
29
+ class LifecycleKpiPipeline {
30
+ assessmentCounter;
31
+ confidenceHistogram;
32
+ stageUpDownCounter;
33
+ emitter;
34
+ lowConfidenceThreshold;
35
+ currentStageByTenant = new Map;
36
+ constructor(options = {}) {
37
+ const meterName = options.meterName ?? "@contractspec/lib.lifecycle-kpi";
38
+ this.assessmentCounter = createCounter("lifecycle_assessments_total", "Total lifecycle assessments", meterName);
39
+ this.confidenceHistogram = createHistogram("lifecycle_assessment_confidence", "Lifecycle assessment confidence distribution", meterName);
40
+ this.stageUpDownCounter = createUpDownCounter("lifecycle_stage_tenants", "Current tenants per lifecycle stage", meterName);
41
+ this.emitter = options.emitter ?? new EventEmitter;
42
+ this.lowConfidenceThreshold = options.lowConfidenceThreshold ?? 0.4;
43
+ }
44
+ recordAssessment(assessment, tenantId) {
45
+ const stageLabel = getStageLabel(assessment.stage);
46
+ const attributes = { stage: stageLabel, tenantId };
47
+ this.assessmentCounter.add(1, attributes);
48
+ this.confidenceHistogram.record(assessment.confidence, attributes);
49
+ this.ensureStageCounters(assessment.stage, tenantId);
50
+ this.emitter.emit("event", {
51
+ type: "assessment.recorded",
52
+ payload: { tenantId, stage: assessment.stage }
53
+ });
54
+ if (assessment.confidence < this.lowConfidenceThreshold) {
55
+ this.emitter.emit("event", {
56
+ type: "confidence.low",
57
+ payload: { tenantId, confidence: assessment.confidence }
58
+ });
59
+ }
60
+ }
61
+ on(listener) {
62
+ this.emitter.on("event", listener);
63
+ }
64
+ ensureStageCounters(stage, tenantId) {
65
+ if (!tenantId)
66
+ return;
67
+ const previous = this.currentStageByTenant.get(tenantId);
68
+ if (previous === stage)
69
+ return;
70
+ if (previous !== undefined) {
71
+ this.stageUpDownCounter.add(-1, {
72
+ stage: getStageLabel(previous),
73
+ tenantId
74
+ });
75
+ }
76
+ this.stageUpDownCounter.add(1, { stage: getStageLabel(stage), tenantId });
77
+ this.currentStageByTenant.set(tenantId, stage);
78
+ this.emitter.emit("event", {
79
+ type: "stage.changed",
80
+ payload: { tenantId, previousStage: previous, nextStage: stage }
81
+ });
82
+ }
83
+ }
84
+ export {
85
+ LifecycleKpiPipeline
86
+ };
@@ -0,0 +1,27 @@
1
+ import type { AnalyticsReader, DateRangeInput } from '@contractspec/lib.contracts/integrations/providers/analytics';
2
+ import type { AggregatedOperationMetrics, OperationSequence, TelemetrySample } from '../intent/aggregator';
3
+ export interface ReadTelemetrySamplesInput {
4
+ operations?: {
5
+ name: string;
6
+ version: string;
7
+ }[];
8
+ dateRange?: DateRangeInput;
9
+ limit?: number;
10
+ }
11
+ export interface PosthogBaselineReaderOptions {
12
+ eventPrefix?: string;
13
+ }
14
+ export declare class PosthogBaselineReader {
15
+ private readonly reader;
16
+ private readonly eventPrefix;
17
+ constructor(reader: AnalyticsReader, options?: PosthogBaselineReaderOptions);
18
+ readSamples(input: ReadTelemetrySamplesInput): Promise<TelemetrySample[]>;
19
+ readAggregatedMetrics(operation: {
20
+ name: string;
21
+ version: string;
22
+ }, windowDays?: number): Promise<AggregatedOperationMetrics | null>;
23
+ readOperationSequences(dateRange?: DateRangeInput): Promise<OperationSequence[]>;
24
+ private readTopErrors;
25
+ private queryHogQL;
26
+ }
27
+ //# sourceMappingURL=posthog-baseline-reader.d.ts.map