@contractspec/lib.evolution 1.57.0 → 1.59.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.
- package/dist/analyzer/posthog-telemetry-reader.d.ts +20 -0
- package/dist/analyzer/posthog-telemetry-reader.d.ts.map +1 -0
- package/dist/analyzer/spec-analyzer.d.ts +31 -0
- package/dist/analyzer/spec-analyzer.d.ts.map +1 -0
- package/dist/approval/integration.d.ts +39 -0
- package/dist/approval/integration.d.ts.map +1 -0
- package/dist/generator/ai-spec-generator.d.ts +51 -0
- package/dist/generator/ai-spec-generator.d.ts.map +1 -0
- package/dist/generator/spec-generator.d.ts +42 -0
- package/dist/generator/spec-generator.d.ts.map +1 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1069 -0
- package/dist/node/index.js +1068 -0
- package/dist/types.d.ts +128 -0
- package/dist/types.d.ts.map +1 -0
- package/package.json +23 -19
- package/dist/analyzer/posthog-telemetry-reader.d.mts +0 -24
- package/dist/analyzer/posthog-telemetry-reader.d.mts.map +0 -1
- package/dist/analyzer/posthog-telemetry-reader.mjs +0 -225
- package/dist/analyzer/posthog-telemetry-reader.mjs.map +0 -1
- package/dist/analyzer/spec-analyzer.d.mts +0 -35
- package/dist/analyzer/spec-analyzer.d.mts.map +0 -1
- package/dist/analyzer/spec-analyzer.mjs +0 -305
- package/dist/analyzer/spec-analyzer.mjs.map +0 -1
- package/dist/approval/integration.d.mts +0 -43
- package/dist/approval/integration.d.mts.map +0 -1
- package/dist/approval/integration.mjs +0 -126
- package/dist/approval/integration.mjs.map +0 -1
- package/dist/generator/ai-spec-generator.d.mts +0 -55
- package/dist/generator/ai-spec-generator.d.mts.map +0 -1
- package/dist/generator/ai-spec-generator.mjs +0 -186
- package/dist/generator/ai-spec-generator.mjs.map +0 -1
- package/dist/generator/spec-generator.d.mts +0 -46
- package/dist/generator/spec-generator.d.mts.map +0 -1
- package/dist/generator/spec-generator.mjs +0 -121
- package/dist/generator/spec-generator.mjs.map +0 -1
- package/dist/index.d.mts +0 -7
- package/dist/index.mjs +0 -7
- package/dist/types.d.mts +0 -132
- package/dist/types.d.mts.map +0 -1
|
@@ -0,0 +1,1068 @@
|
|
|
1
|
+
// src/analyzer/spec-analyzer.ts
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { LifecycleStage } from "@contractspec/lib.lifecycle";
|
|
4
|
+
var DEFAULT_OPTIONS = {
|
|
5
|
+
minSampleSize: 50,
|
|
6
|
+
errorRateThreshold: 0.05,
|
|
7
|
+
latencyP99ThresholdMs: 750
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
class SpecAnalyzer {
|
|
11
|
+
logger;
|
|
12
|
+
minSampleSize;
|
|
13
|
+
errorRateThreshold;
|
|
14
|
+
latencyP99ThresholdMs;
|
|
15
|
+
throughputDropThreshold;
|
|
16
|
+
constructor(options = {}) {
|
|
17
|
+
this.logger = options.logger;
|
|
18
|
+
this.minSampleSize = options.minSampleSize ?? DEFAULT_OPTIONS.minSampleSize;
|
|
19
|
+
this.errorRateThreshold = options.errorRateThreshold ?? DEFAULT_OPTIONS.errorRateThreshold;
|
|
20
|
+
this.latencyP99ThresholdMs = options.latencyP99ThresholdMs ?? DEFAULT_OPTIONS.latencyP99ThresholdMs;
|
|
21
|
+
this.throughputDropThreshold = options.throughputDropThreshold ?? 0.2;
|
|
22
|
+
}
|
|
23
|
+
analyzeSpecUsage(samples) {
|
|
24
|
+
if (!samples.length) {
|
|
25
|
+
this.logger?.debug("SpecAnalyzer.analyzeSpecUsage.skip", {
|
|
26
|
+
reason: "no-samples"
|
|
27
|
+
});
|
|
28
|
+
return [];
|
|
29
|
+
}
|
|
30
|
+
const groups = new Map;
|
|
31
|
+
for (const sample of samples) {
|
|
32
|
+
const key = this.operationKey(sample);
|
|
33
|
+
const arr = groups.get(key) ?? [];
|
|
34
|
+
arr.push(sample);
|
|
35
|
+
groups.set(key, arr);
|
|
36
|
+
}
|
|
37
|
+
const entries = [...groups.values()];
|
|
38
|
+
const usable = entries.filter((samplesForOp) => {
|
|
39
|
+
const valid = samplesForOp.length >= this.minSampleSize;
|
|
40
|
+
if (!valid) {
|
|
41
|
+
this.logger?.debug("SpecAnalyzer.analyzeSpecUsage.skipOperation", {
|
|
42
|
+
operation: this.operationKey(samplesForOp[0]),
|
|
43
|
+
sampleSize: samplesForOp.length,
|
|
44
|
+
minSampleSize: this.minSampleSize
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
return valid;
|
|
48
|
+
});
|
|
49
|
+
return usable.map((operationSamples) => this.buildUsageStats(operationSamples));
|
|
50
|
+
}
|
|
51
|
+
detectAnomalies(stats, baseline) {
|
|
52
|
+
const anomalies = [];
|
|
53
|
+
if (!stats.length) {
|
|
54
|
+
this.logger?.debug("SpecAnalyzer.detectAnomalies.skip", {
|
|
55
|
+
reason: "no-stats"
|
|
56
|
+
});
|
|
57
|
+
return anomalies;
|
|
58
|
+
}
|
|
59
|
+
const baselineByOp = new Map((baseline ?? []).map((item) => [this.operationKey(item.operation), item]));
|
|
60
|
+
for (const stat of stats) {
|
|
61
|
+
const evidence = [];
|
|
62
|
+
if (stat.errorRate >= this.errorRateThreshold) {
|
|
63
|
+
evidence.push({
|
|
64
|
+
type: "telemetry",
|
|
65
|
+
description: `Error rate ${stat.errorRate.toFixed(2)} exceeded threshold ${this.errorRateThreshold}`,
|
|
66
|
+
data: { errorRate: stat.errorRate }
|
|
67
|
+
});
|
|
68
|
+
anomalies.push({
|
|
69
|
+
operation: stat.operation,
|
|
70
|
+
severity: this.toSeverity(stat.errorRate / this.errorRateThreshold),
|
|
71
|
+
metric: "error-rate",
|
|
72
|
+
description: "Error rate spike",
|
|
73
|
+
detectedAt: new Date,
|
|
74
|
+
threshold: this.errorRateThreshold,
|
|
75
|
+
observedValue: stat.errorRate,
|
|
76
|
+
evidence
|
|
77
|
+
});
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
if (stat.p99LatencyMs >= this.latencyP99ThresholdMs) {
|
|
81
|
+
evidence.push({
|
|
82
|
+
type: "telemetry",
|
|
83
|
+
description: `P99 latency ${stat.p99LatencyMs}ms exceeded threshold ${this.latencyP99ThresholdMs}ms`,
|
|
84
|
+
data: { p99LatencyMs: stat.p99LatencyMs }
|
|
85
|
+
});
|
|
86
|
+
anomalies.push({
|
|
87
|
+
operation: stat.operation,
|
|
88
|
+
severity: this.toSeverity(stat.p99LatencyMs / this.latencyP99ThresholdMs),
|
|
89
|
+
metric: "latency",
|
|
90
|
+
description: "Latency regression detected",
|
|
91
|
+
detectedAt: new Date,
|
|
92
|
+
threshold: this.latencyP99ThresholdMs,
|
|
93
|
+
observedValue: stat.p99LatencyMs,
|
|
94
|
+
evidence
|
|
95
|
+
});
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
const baselineStat = baselineByOp.get(this.operationKey(stat.operation));
|
|
99
|
+
if (baselineStat) {
|
|
100
|
+
const drop = (baselineStat.totalCalls - stat.totalCalls) / baselineStat.totalCalls;
|
|
101
|
+
if (drop >= this.throughputDropThreshold) {
|
|
102
|
+
evidence.push({
|
|
103
|
+
type: "telemetry",
|
|
104
|
+
description: `Throughput dropped by ${(drop * 100).toFixed(1)}% compared to baseline`,
|
|
105
|
+
data: {
|
|
106
|
+
baselineCalls: baselineStat.totalCalls,
|
|
107
|
+
currentCalls: stat.totalCalls
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
anomalies.push({
|
|
111
|
+
operation: stat.operation,
|
|
112
|
+
severity: this.toSeverity(drop / this.throughputDropThreshold),
|
|
113
|
+
metric: "throughput",
|
|
114
|
+
description: "Usage drop detected",
|
|
115
|
+
detectedAt: new Date,
|
|
116
|
+
threshold: this.throughputDropThreshold,
|
|
117
|
+
observedValue: drop,
|
|
118
|
+
evidence
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return anomalies;
|
|
124
|
+
}
|
|
125
|
+
toIntentPatterns(anomalies, stats) {
|
|
126
|
+
const statsByOp = new Map(stats.map((item) => [this.operationKey(item.operation), item]));
|
|
127
|
+
return anomalies.map((anomaly) => {
|
|
128
|
+
const stat = statsByOp.get(this.operationKey(anomaly.operation));
|
|
129
|
+
const confidence = {
|
|
130
|
+
score: Math.min(1, (anomaly.observedValue ?? 0) / (anomaly.threshold ?? 1)),
|
|
131
|
+
sampleSize: stat?.totalCalls ?? 0,
|
|
132
|
+
pValue: undefined
|
|
133
|
+
};
|
|
134
|
+
return {
|
|
135
|
+
id: randomUUID(),
|
|
136
|
+
type: this.mapMetricToIntent(anomaly.metric),
|
|
137
|
+
description: anomaly.description,
|
|
138
|
+
operation: anomaly.operation,
|
|
139
|
+
confidence,
|
|
140
|
+
metadata: {
|
|
141
|
+
observedValue: anomaly.observedValue,
|
|
142
|
+
threshold: anomaly.threshold
|
|
143
|
+
},
|
|
144
|
+
evidence: anomaly.evidence
|
|
145
|
+
};
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
suggestOptimizations(stats, anomalies, lifecycleContext) {
|
|
149
|
+
const anomaliesByOp = new Map(this.groupByOperation(anomalies));
|
|
150
|
+
const hints = [];
|
|
151
|
+
for (const stat of stats) {
|
|
152
|
+
const opKey = this.operationKey(stat.operation);
|
|
153
|
+
const opAnomalies = anomaliesByOp.get(opKey) ?? [];
|
|
154
|
+
for (const anomaly of opAnomalies) {
|
|
155
|
+
if (anomaly.metric === "latency") {
|
|
156
|
+
hints.push(this.applyLifecycleContext({
|
|
157
|
+
operation: stat.operation,
|
|
158
|
+
category: "performance",
|
|
159
|
+
summary: "Latency regression detected",
|
|
160
|
+
justification: `P99 latency at ${stat.p99LatencyMs}ms`,
|
|
161
|
+
recommendedActions: [
|
|
162
|
+
"Add batching or caching layer",
|
|
163
|
+
"Replay golden tests to capture slow inputs"
|
|
164
|
+
]
|
|
165
|
+
}, lifecycleContext?.stage));
|
|
166
|
+
} else if (anomaly.metric === "error-rate") {
|
|
167
|
+
const topError = Object.entries(stat.topErrors).sort((a, b) => b[1] - a[1])[0]?.[0];
|
|
168
|
+
hints.push(this.applyLifecycleContext({
|
|
169
|
+
operation: stat.operation,
|
|
170
|
+
category: "error-handling",
|
|
171
|
+
summary: "Error spike detected",
|
|
172
|
+
justification: topError ? `Dominant error code ${topError}` : "Increase in failures",
|
|
173
|
+
recommendedActions: [
|
|
174
|
+
"Generate regression spec from failing payloads",
|
|
175
|
+
"Add policy guardrails before rollout"
|
|
176
|
+
]
|
|
177
|
+
}, lifecycleContext?.stage));
|
|
178
|
+
} else if (anomaly.metric === "throughput") {
|
|
179
|
+
hints.push(this.applyLifecycleContext({
|
|
180
|
+
operation: stat.operation,
|
|
181
|
+
category: "performance",
|
|
182
|
+
summary: "Throughput drop detected",
|
|
183
|
+
justification: "Significant traffic reduction relative to baseline",
|
|
184
|
+
recommendedActions: [
|
|
185
|
+
"Validate routing + feature flag bucketing",
|
|
186
|
+
"Backfill spec variant to rehydrate demand"
|
|
187
|
+
]
|
|
188
|
+
}, lifecycleContext?.stage));
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
return hints;
|
|
193
|
+
}
|
|
194
|
+
operationKey(op) {
|
|
195
|
+
const coordinate = "operation" in op ? op.operation : op;
|
|
196
|
+
return `${coordinate.key}.v${coordinate.version}${coordinate.tenantId ? `@${coordinate.tenantId}` : ""}`;
|
|
197
|
+
}
|
|
198
|
+
buildUsageStats(samples) {
|
|
199
|
+
const durations = samples.map((s) => s.durationMs).sort((a, b) => a - b);
|
|
200
|
+
const errors = samples.filter((s) => !s.success);
|
|
201
|
+
const totalCalls = samples.length;
|
|
202
|
+
const successRate = (totalCalls - errors.length) / totalCalls;
|
|
203
|
+
const errorRate = errors.length / totalCalls;
|
|
204
|
+
const averageLatencyMs = durations.reduce((sum, value) => sum + value, 0) / totalCalls;
|
|
205
|
+
const topErrors = errors.reduce((acc, sample) => {
|
|
206
|
+
if (!sample.errorCode)
|
|
207
|
+
return acc;
|
|
208
|
+
acc[sample.errorCode] = (acc[sample.errorCode] ?? 0) + 1;
|
|
209
|
+
return acc;
|
|
210
|
+
}, {});
|
|
211
|
+
const timestamps = samples.map((s) => s.timestamp.getTime());
|
|
212
|
+
const windowStart = new Date(Math.min(...timestamps));
|
|
213
|
+
const windowEnd = new Date(Math.max(...timestamps));
|
|
214
|
+
return {
|
|
215
|
+
operation: samples[0].operation,
|
|
216
|
+
totalCalls,
|
|
217
|
+
successRate,
|
|
218
|
+
errorRate,
|
|
219
|
+
averageLatencyMs,
|
|
220
|
+
p95LatencyMs: percentile(durations, 0.95),
|
|
221
|
+
p99LatencyMs: percentile(durations, 0.99),
|
|
222
|
+
maxLatencyMs: Math.max(...durations),
|
|
223
|
+
lastSeenAt: windowEnd,
|
|
224
|
+
windowStart,
|
|
225
|
+
windowEnd,
|
|
226
|
+
topErrors
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
toSeverity(ratio) {
|
|
230
|
+
if (ratio >= 2)
|
|
231
|
+
return "high";
|
|
232
|
+
if (ratio >= 1.3)
|
|
233
|
+
return "medium";
|
|
234
|
+
return "low";
|
|
235
|
+
}
|
|
236
|
+
mapMetricToIntent(metric) {
|
|
237
|
+
switch (metric) {
|
|
238
|
+
case "error-rate":
|
|
239
|
+
return "error-spike";
|
|
240
|
+
case "latency":
|
|
241
|
+
return "latency-regression";
|
|
242
|
+
case "throughput":
|
|
243
|
+
return "throughput-drop";
|
|
244
|
+
default:
|
|
245
|
+
return "schema-mismatch";
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
groupByOperation(items) {
|
|
249
|
+
const map = new Map;
|
|
250
|
+
for (const item of items) {
|
|
251
|
+
const key = this.operationKey(item.operation);
|
|
252
|
+
const arr = map.get(key) ?? [];
|
|
253
|
+
arr.push(item);
|
|
254
|
+
map.set(key, arr);
|
|
255
|
+
}
|
|
256
|
+
return map;
|
|
257
|
+
}
|
|
258
|
+
applyLifecycleContext(hint, stage) {
|
|
259
|
+
if (stage === undefined)
|
|
260
|
+
return hint;
|
|
261
|
+
const band = mapStageBand(stage);
|
|
262
|
+
const advice = LIFECYCLE_HINTS[band]?.[hint.category];
|
|
263
|
+
if (!advice) {
|
|
264
|
+
return { ...hint, lifecycleStage: stage };
|
|
265
|
+
}
|
|
266
|
+
return {
|
|
267
|
+
...hint,
|
|
268
|
+
lifecycleStage: stage,
|
|
269
|
+
lifecycleNotes: advice.message,
|
|
270
|
+
recommendedActions: dedupeActions([
|
|
271
|
+
...hint.recommendedActions,
|
|
272
|
+
...advice.supplementalActions
|
|
273
|
+
])
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
function percentile(values, p) {
|
|
278
|
+
if (!values.length)
|
|
279
|
+
return 0;
|
|
280
|
+
if (values.length === 1)
|
|
281
|
+
return values[0];
|
|
282
|
+
const idx = Math.min(values.length - 1, Math.floor(p * values.length));
|
|
283
|
+
return values[idx];
|
|
284
|
+
}
|
|
285
|
+
var mapStageBand = (stage) => {
|
|
286
|
+
if (stage <= 2)
|
|
287
|
+
return "early";
|
|
288
|
+
if (stage === LifecycleStage.ProductMarketFit)
|
|
289
|
+
return "pmf";
|
|
290
|
+
if (stage === LifecycleStage.GrowthScaleUp || stage === LifecycleStage.ExpansionPlatform) {
|
|
291
|
+
return "scale";
|
|
292
|
+
}
|
|
293
|
+
return "mature";
|
|
294
|
+
};
|
|
295
|
+
var LIFECYCLE_HINTS = {
|
|
296
|
+
early: {
|
|
297
|
+
performance: {
|
|
298
|
+
message: "Favor guardrails that protect learning velocity before heavy rewrites.",
|
|
299
|
+
supplementalActions: [
|
|
300
|
+
"Wrap risky changes behind progressive delivery flags"
|
|
301
|
+
]
|
|
302
|
+
},
|
|
303
|
+
"error-handling": {
|
|
304
|
+
message: "Make failures loud and recoverable so you can learn faster.",
|
|
305
|
+
supplementalActions: ["Add auto-rollbacks or manual kill switches"]
|
|
306
|
+
}
|
|
307
|
+
},
|
|
308
|
+
pmf: {
|
|
309
|
+
performance: {
|
|
310
|
+
message: "Stabilize the core use case to avoid regressions while demand grows.",
|
|
311
|
+
supplementalActions: ["Instrument regression tests on critical specs"]
|
|
312
|
+
}
|
|
313
|
+
},
|
|
314
|
+
scale: {
|
|
315
|
+
performance: {
|
|
316
|
+
message: "Prioritize resilience and multi-tenant safety as volumes expand.",
|
|
317
|
+
supplementalActions: [
|
|
318
|
+
"Introduce workload partitioning or isolation per tenant"
|
|
319
|
+
]
|
|
320
|
+
},
|
|
321
|
+
"error-handling": {
|
|
322
|
+
message: "Contain blast radius with policy fallbacks and circuit breakers.",
|
|
323
|
+
supplementalActions: ["Add circuit breakers to high-risk operations"]
|
|
324
|
+
}
|
|
325
|
+
},
|
|
326
|
+
mature: {
|
|
327
|
+
performance: {
|
|
328
|
+
message: "Optimize for margins and predictable SLAs.",
|
|
329
|
+
supplementalActions: [
|
|
330
|
+
"Capture unit-cost impacts alongside latency fixes"
|
|
331
|
+
]
|
|
332
|
+
},
|
|
333
|
+
"error-handling": {
|
|
334
|
+
message: "Prevent regressions with automated regression specs before deploy.",
|
|
335
|
+
supplementalActions: [
|
|
336
|
+
"Run auto-evolution simulations on renewal scenarios"
|
|
337
|
+
]
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
};
|
|
341
|
+
var dedupeActions = (actions) => {
|
|
342
|
+
const seen = new Set;
|
|
343
|
+
const ordered = [];
|
|
344
|
+
for (const action of actions) {
|
|
345
|
+
if (seen.has(action))
|
|
346
|
+
continue;
|
|
347
|
+
seen.add(action);
|
|
348
|
+
ordered.push(action);
|
|
349
|
+
}
|
|
350
|
+
return ordered;
|
|
351
|
+
};
|
|
352
|
+
// src/analyzer/posthog-telemetry-reader.ts
|
|
353
|
+
class PosthogTelemetryReader {
|
|
354
|
+
reader;
|
|
355
|
+
eventPrefix;
|
|
356
|
+
constructor(reader, options = {}) {
|
|
357
|
+
this.reader = reader;
|
|
358
|
+
this.eventPrefix = options.eventPrefix ?? "observability";
|
|
359
|
+
}
|
|
360
|
+
async readOperationSamples(input) {
|
|
361
|
+
const result = await this.queryHogQL({
|
|
362
|
+
query: [
|
|
363
|
+
"select",
|
|
364
|
+
" properties.operation as operationKey,",
|
|
365
|
+
" properties.version as version,",
|
|
366
|
+
" properties.durationMs as durationMs,",
|
|
367
|
+
" properties.success as success,",
|
|
368
|
+
" properties.errorCode as errorCode,",
|
|
369
|
+
" properties.tenantId as tenantId,",
|
|
370
|
+
" properties.traceId as traceId,",
|
|
371
|
+
" properties.metadata as metadata,",
|
|
372
|
+
" timestamp as timestamp",
|
|
373
|
+
"from events",
|
|
374
|
+
`where ${buildOperationWhereClause(this.eventPrefix, input)}`,
|
|
375
|
+
"order by timestamp desc",
|
|
376
|
+
`limit ${input.limit ?? 1000}`
|
|
377
|
+
].join(`
|
|
378
|
+
`),
|
|
379
|
+
values: buildOperationValues(input)
|
|
380
|
+
});
|
|
381
|
+
return mapOperationSamples(result);
|
|
382
|
+
}
|
|
383
|
+
async readAnomalyBaseline(operation, windowDays = 7) {
|
|
384
|
+
const dateRange = buildWindowRange(windowDays);
|
|
385
|
+
const baseResult = await this.queryHogQL({
|
|
386
|
+
query: [
|
|
387
|
+
"select",
|
|
388
|
+
" count() as totalCalls,",
|
|
389
|
+
" avg(properties.durationMs) as averageLatencyMs,",
|
|
390
|
+
" quantile(0.95)(properties.durationMs) as p95LatencyMs,",
|
|
391
|
+
" quantile(0.99)(properties.durationMs) as p99LatencyMs,",
|
|
392
|
+
" max(properties.durationMs) as maxLatencyMs,",
|
|
393
|
+
" sum(if(properties.success = 1, 1, 0)) as successCount,",
|
|
394
|
+
" sum(if(properties.success = 0, 1, 0)) as errorCount",
|
|
395
|
+
"from events",
|
|
396
|
+
`where ${buildOperationWhereClause(this.eventPrefix, {
|
|
397
|
+
operations: [operation],
|
|
398
|
+
dateRange
|
|
399
|
+
})}`
|
|
400
|
+
].join(`
|
|
401
|
+
`),
|
|
402
|
+
values: buildOperationValues({
|
|
403
|
+
operations: [operation],
|
|
404
|
+
dateRange
|
|
405
|
+
})
|
|
406
|
+
});
|
|
407
|
+
const stats = mapBaselineStats(baseResult, operation, dateRange);
|
|
408
|
+
if (!stats)
|
|
409
|
+
return null;
|
|
410
|
+
const topErrors = await this.readTopErrors(operation, dateRange);
|
|
411
|
+
return {
|
|
412
|
+
...stats,
|
|
413
|
+
topErrors
|
|
414
|
+
};
|
|
415
|
+
}
|
|
416
|
+
async readTopErrors(operation, dateRange) {
|
|
417
|
+
const result = await this.queryHogQL({
|
|
418
|
+
query: [
|
|
419
|
+
"select",
|
|
420
|
+
" properties.errorCode as errorCode,",
|
|
421
|
+
" count() as errorCount",
|
|
422
|
+
"from events",
|
|
423
|
+
`where ${buildOperationWhereClause(this.eventPrefix, {
|
|
424
|
+
operations: [operation],
|
|
425
|
+
dateRange
|
|
426
|
+
})} and properties.success = 0`,
|
|
427
|
+
"group by errorCode",
|
|
428
|
+
"order by errorCount desc",
|
|
429
|
+
"limit 5"
|
|
430
|
+
].join(`
|
|
431
|
+
`),
|
|
432
|
+
values: buildOperationValues({
|
|
433
|
+
operations: [operation],
|
|
434
|
+
dateRange
|
|
435
|
+
})
|
|
436
|
+
});
|
|
437
|
+
const rows = mapRows(result);
|
|
438
|
+
return rows.reduce((acc, row) => {
|
|
439
|
+
const code = asString(row.errorCode);
|
|
440
|
+
if (!code)
|
|
441
|
+
return acc;
|
|
442
|
+
acc[code] = asNumber(row.errorCount);
|
|
443
|
+
return acc;
|
|
444
|
+
}, {});
|
|
445
|
+
}
|
|
446
|
+
async queryHogQL(input) {
|
|
447
|
+
if (!this.reader.queryHogQL) {
|
|
448
|
+
throw new Error("Analytics reader does not support HogQL queries.");
|
|
449
|
+
}
|
|
450
|
+
return this.reader.queryHogQL(input);
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
function buildOperationWhereClause(eventPrefix, input) {
|
|
454
|
+
const clauses = [`event = '${eventPrefix}.operation'`];
|
|
455
|
+
if (input.operations?.length) {
|
|
456
|
+
clauses.push(`(${buildOperationFilters(input.operations)})`);
|
|
457
|
+
}
|
|
458
|
+
if (input.dateRange?.from) {
|
|
459
|
+
clauses.push("timestamp >= {dateFrom}");
|
|
460
|
+
}
|
|
461
|
+
if (input.dateRange?.to) {
|
|
462
|
+
clauses.push("timestamp < {dateTo}");
|
|
463
|
+
}
|
|
464
|
+
return clauses.join(" and ");
|
|
465
|
+
}
|
|
466
|
+
function buildOperationValues(input) {
|
|
467
|
+
const values = {
|
|
468
|
+
dateFrom: toIsoString(input.dateRange?.from),
|
|
469
|
+
dateTo: toIsoString(input.dateRange?.to)
|
|
470
|
+
};
|
|
471
|
+
input.operations?.forEach((op, index) => {
|
|
472
|
+
values[`operationKey${index}`] = op.key;
|
|
473
|
+
values[`operationVersion${index}`] = op.version;
|
|
474
|
+
if (op.tenantId) {
|
|
475
|
+
values[`operationTenant${index}`] = op.tenantId;
|
|
476
|
+
}
|
|
477
|
+
});
|
|
478
|
+
return values;
|
|
479
|
+
}
|
|
480
|
+
function buildOperationFilters(operations) {
|
|
481
|
+
return operations.map((op, index) => {
|
|
482
|
+
const clauses = [
|
|
483
|
+
`properties.operation = {operationKey${index}}`,
|
|
484
|
+
`properties.version = {operationVersion${index}}`
|
|
485
|
+
];
|
|
486
|
+
if (op.tenantId) {
|
|
487
|
+
clauses.push(`properties.tenantId = {operationTenant${index}}`);
|
|
488
|
+
}
|
|
489
|
+
return `(${clauses.join(" and ")})`;
|
|
490
|
+
}).join(" or ");
|
|
491
|
+
}
|
|
492
|
+
function mapOperationSamples(result) {
|
|
493
|
+
const rows = mapRows(result);
|
|
494
|
+
return rows.flatMap((row) => {
|
|
495
|
+
const operationKey = asString(row.operationKey);
|
|
496
|
+
const version = asString(row.version);
|
|
497
|
+
const timestamp = asDate(row.timestamp);
|
|
498
|
+
if (!operationKey || !version || !timestamp) {
|
|
499
|
+
return [];
|
|
500
|
+
}
|
|
501
|
+
return [
|
|
502
|
+
{
|
|
503
|
+
operation: {
|
|
504
|
+
key: operationKey,
|
|
505
|
+
version,
|
|
506
|
+
tenantId: asOptionalString(row.tenantId) ?? undefined
|
|
507
|
+
},
|
|
508
|
+
durationMs: asNumber(row.durationMs),
|
|
509
|
+
success: asBoolean(row.success),
|
|
510
|
+
timestamp,
|
|
511
|
+
errorCode: asOptionalString(row.errorCode) ?? undefined,
|
|
512
|
+
traceId: asOptionalString(row.traceId) ?? undefined,
|
|
513
|
+
metadata: isRecord(row.metadata) ? row.metadata : undefined
|
|
514
|
+
}
|
|
515
|
+
];
|
|
516
|
+
});
|
|
517
|
+
}
|
|
518
|
+
function mapBaselineStats(result, operation, dateRange) {
|
|
519
|
+
const rows = mapRows(result);
|
|
520
|
+
const row = rows[0];
|
|
521
|
+
if (!row)
|
|
522
|
+
return null;
|
|
523
|
+
const totalCalls = asNumber(row.totalCalls);
|
|
524
|
+
if (!totalCalls)
|
|
525
|
+
return null;
|
|
526
|
+
const successCount = asNumber(row.successCount);
|
|
527
|
+
const errorCount = asNumber(row.errorCount);
|
|
528
|
+
return {
|
|
529
|
+
operation,
|
|
530
|
+
totalCalls,
|
|
531
|
+
successRate: totalCalls ? successCount / totalCalls : 0,
|
|
532
|
+
errorRate: totalCalls ? errorCount / totalCalls : 0,
|
|
533
|
+
averageLatencyMs: asNumber(row.averageLatencyMs),
|
|
534
|
+
p95LatencyMs: asNumber(row.p95LatencyMs),
|
|
535
|
+
p99LatencyMs: asNumber(row.p99LatencyMs),
|
|
536
|
+
maxLatencyMs: asNumber(row.maxLatencyMs),
|
|
537
|
+
lastSeenAt: new Date,
|
|
538
|
+
windowStart: toDate(dateRange.from) ?? new Date,
|
|
539
|
+
windowEnd: toDate(dateRange.to) ?? new Date,
|
|
540
|
+
topErrors: {}
|
|
541
|
+
};
|
|
542
|
+
}
|
|
543
|
+
function mapRows(result) {
|
|
544
|
+
if (!Array.isArray(result.results) || !Array.isArray(result.columns)) {
|
|
545
|
+
return [];
|
|
546
|
+
}
|
|
547
|
+
const columns = result.columns;
|
|
548
|
+
return result.results.flatMap((row) => {
|
|
549
|
+
if (!Array.isArray(row))
|
|
550
|
+
return [];
|
|
551
|
+
const record = {};
|
|
552
|
+
columns.forEach((column, index) => {
|
|
553
|
+
record[column] = row[index];
|
|
554
|
+
});
|
|
555
|
+
return [record];
|
|
556
|
+
});
|
|
557
|
+
}
|
|
558
|
+
function buildWindowRange(windowDays) {
|
|
559
|
+
const windowEnd = new Date;
|
|
560
|
+
const windowStart = new Date(windowEnd.getTime() - windowDays * 24 * 60 * 60 * 1000);
|
|
561
|
+
return {
|
|
562
|
+
from: windowStart,
|
|
563
|
+
to: windowEnd
|
|
564
|
+
};
|
|
565
|
+
}
|
|
566
|
+
function asString(value) {
|
|
567
|
+
if (typeof value === "string" && value.trim())
|
|
568
|
+
return value;
|
|
569
|
+
if (typeof value === "number")
|
|
570
|
+
return String(value);
|
|
571
|
+
return null;
|
|
572
|
+
}
|
|
573
|
+
function asOptionalString(value) {
|
|
574
|
+
if (typeof value === "string")
|
|
575
|
+
return value;
|
|
576
|
+
if (typeof value === "number")
|
|
577
|
+
return String(value);
|
|
578
|
+
return null;
|
|
579
|
+
}
|
|
580
|
+
function asNumber(value) {
|
|
581
|
+
if (typeof value === "number" && Number.isFinite(value))
|
|
582
|
+
return value;
|
|
583
|
+
if (typeof value === "string" && value.trim()) {
|
|
584
|
+
const parsed = Number(value);
|
|
585
|
+
if (Number.isFinite(parsed))
|
|
586
|
+
return parsed;
|
|
587
|
+
}
|
|
588
|
+
return 0;
|
|
589
|
+
}
|
|
590
|
+
function asBoolean(value) {
|
|
591
|
+
if (typeof value === "boolean")
|
|
592
|
+
return value;
|
|
593
|
+
if (typeof value === "number")
|
|
594
|
+
return value !== 0;
|
|
595
|
+
if (typeof value === "string")
|
|
596
|
+
return value.toLowerCase() === "true";
|
|
597
|
+
return false;
|
|
598
|
+
}
|
|
599
|
+
function asDate(value) {
|
|
600
|
+
if (value instanceof Date)
|
|
601
|
+
return value;
|
|
602
|
+
if (typeof value === "string" || typeof value === "number") {
|
|
603
|
+
const date = new Date(value);
|
|
604
|
+
if (!Number.isNaN(date.getTime()))
|
|
605
|
+
return date;
|
|
606
|
+
}
|
|
607
|
+
return null;
|
|
608
|
+
}
|
|
609
|
+
function toIsoString(value) {
|
|
610
|
+
if (!value)
|
|
611
|
+
return;
|
|
612
|
+
return typeof value === "string" ? value : value.toISOString();
|
|
613
|
+
}
|
|
614
|
+
function toDate(value) {
|
|
615
|
+
if (!value)
|
|
616
|
+
return null;
|
|
617
|
+
return value instanceof Date ? value : new Date(value);
|
|
618
|
+
}
|
|
619
|
+
function isRecord(value) {
|
|
620
|
+
return typeof value === "object" && value !== null;
|
|
621
|
+
}
|
|
622
|
+
// src/generator/spec-generator.ts
|
|
623
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
624
|
+
|
|
625
|
+
class SpecGenerator {
|
|
626
|
+
config;
|
|
627
|
+
logger;
|
|
628
|
+
clock;
|
|
629
|
+
getSpec;
|
|
630
|
+
constructor(options = {}) {
|
|
631
|
+
this.config = options.config ?? {};
|
|
632
|
+
this.logger = options.logger;
|
|
633
|
+
this.clock = options.clock ?? (() => new Date);
|
|
634
|
+
this.getSpec = options.getSpec;
|
|
635
|
+
}
|
|
636
|
+
generateFromIntent(intent, options = {}) {
|
|
637
|
+
const now = this.clock();
|
|
638
|
+
const summary = options.summary ?? `${this.intentToVerb(intent.type)} ${intent.operation?.key ?? "operation"}`;
|
|
639
|
+
const rationale = options.rationale ?? [
|
|
640
|
+
intent.description,
|
|
641
|
+
intent.metadata?.observedValue ? `Observed ${intent.metadata.observedValue}` : undefined
|
|
642
|
+
].filter(Boolean).join(" — ");
|
|
643
|
+
const suggestion = {
|
|
644
|
+
id: randomUUID2(),
|
|
645
|
+
intent,
|
|
646
|
+
target: intent.operation,
|
|
647
|
+
proposal: {
|
|
648
|
+
summary,
|
|
649
|
+
rationale,
|
|
650
|
+
changeType: options.changeType ?? this.inferChangeType(intent),
|
|
651
|
+
kind: options.kind,
|
|
652
|
+
spec: options.spec,
|
|
653
|
+
diff: options.diff,
|
|
654
|
+
metadata: options.metadata
|
|
655
|
+
},
|
|
656
|
+
confidence: intent.confidence.score,
|
|
657
|
+
priority: this.intentToPriority(intent),
|
|
658
|
+
createdAt: now,
|
|
659
|
+
createdBy: options.createdBy ?? "auto-evolution",
|
|
660
|
+
status: options.status ?? "pending",
|
|
661
|
+
evidence: intent.evidence,
|
|
662
|
+
tags: options.tags
|
|
663
|
+
};
|
|
664
|
+
return suggestion;
|
|
665
|
+
}
|
|
666
|
+
generateVariant(operation, patch, intent, options = {}) {
|
|
667
|
+
if (!this.getSpec) {
|
|
668
|
+
throw new Error("SpecGenerator requires getSpec() to generate variants");
|
|
669
|
+
}
|
|
670
|
+
const base = this.getSpec(operation.key, operation.version);
|
|
671
|
+
if (!base) {
|
|
672
|
+
throw new Error(`Cannot generate variant; spec ${operation.key}.v${operation.version} not found`);
|
|
673
|
+
}
|
|
674
|
+
const merged = mergeContract(base, patch);
|
|
675
|
+
return this.generateFromIntent(intent, { ...options, spec: merged });
|
|
676
|
+
}
|
|
677
|
+
validateSuggestion(suggestion, config = this.config) {
|
|
678
|
+
const reasons = [];
|
|
679
|
+
if (config.minConfidence != null && suggestion.confidence < config.minConfidence) {
|
|
680
|
+
reasons.push(`Confidence ${suggestion.confidence.toFixed(2)} below minimum ${config.minConfidence}`);
|
|
681
|
+
}
|
|
682
|
+
if (config.requireApproval && suggestion.status === "approved") {
|
|
683
|
+
reasons.push("Suggestion cannot be auto-approved when approval is required");
|
|
684
|
+
}
|
|
685
|
+
if (suggestion.proposal.spec && !suggestion.proposal.spec.meta?.key) {
|
|
686
|
+
reasons.push("Proposal spec must include meta.key");
|
|
687
|
+
}
|
|
688
|
+
if (!suggestion.proposal.summary) {
|
|
689
|
+
reasons.push("Proposal summary is required");
|
|
690
|
+
}
|
|
691
|
+
const ok = reasons.length === 0;
|
|
692
|
+
if (!ok) {
|
|
693
|
+
this.logger?.warn("SpecGenerator.validateSuggestion.failed", {
|
|
694
|
+
suggestionId: suggestion.id,
|
|
695
|
+
reasons
|
|
696
|
+
});
|
|
697
|
+
}
|
|
698
|
+
return { ok, reasons };
|
|
699
|
+
}
|
|
700
|
+
intentToVerb(intent) {
|
|
701
|
+
switch (intent) {
|
|
702
|
+
case "error-spike":
|
|
703
|
+
return "Stabilize";
|
|
704
|
+
case "latency-regression":
|
|
705
|
+
return "Optimize";
|
|
706
|
+
case "missing-operation":
|
|
707
|
+
return "Introduce";
|
|
708
|
+
case "throughput-drop":
|
|
709
|
+
return "Rebalance";
|
|
710
|
+
default:
|
|
711
|
+
return "Adjust";
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
intentToPriority(intent) {
|
|
715
|
+
const severity = intent.confidence.score;
|
|
716
|
+
if (intent.type === "error-spike" || severity >= 0.8)
|
|
717
|
+
return "high";
|
|
718
|
+
if (severity >= 0.5)
|
|
719
|
+
return "medium";
|
|
720
|
+
return "low";
|
|
721
|
+
}
|
|
722
|
+
inferChangeType(intent) {
|
|
723
|
+
switch (intent.type) {
|
|
724
|
+
case "missing-operation":
|
|
725
|
+
return "new-spec";
|
|
726
|
+
case "schema-mismatch":
|
|
727
|
+
return "schema-update";
|
|
728
|
+
case "error-spike":
|
|
729
|
+
return "policy-update";
|
|
730
|
+
default:
|
|
731
|
+
return "revision";
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
function mergeContract(base, patch) {
|
|
736
|
+
return {
|
|
737
|
+
...base,
|
|
738
|
+
...patch,
|
|
739
|
+
meta: { ...base.meta, ...patch.meta },
|
|
740
|
+
io: {
|
|
741
|
+
...base.io,
|
|
742
|
+
...patch.io
|
|
743
|
+
},
|
|
744
|
+
policy: {
|
|
745
|
+
...base.policy,
|
|
746
|
+
...patch.policy
|
|
747
|
+
},
|
|
748
|
+
telemetry: {
|
|
749
|
+
...base.telemetry,
|
|
750
|
+
...patch.telemetry
|
|
751
|
+
},
|
|
752
|
+
sideEffects: {
|
|
753
|
+
...base.sideEffects,
|
|
754
|
+
...patch.sideEffects
|
|
755
|
+
}
|
|
756
|
+
};
|
|
757
|
+
}
|
|
758
|
+
// src/generator/ai-spec-generator.ts
|
|
759
|
+
import { generateText, Output } from "ai";
|
|
760
|
+
import * as z from "zod";
|
|
761
|
+
import { randomUUID as randomUUID3 } from "node:crypto";
|
|
762
|
+
var SpecSuggestionProposalSchema = z.object({
|
|
763
|
+
summary: z.string().describe("Brief summary of the proposed change"),
|
|
764
|
+
rationale: z.string().describe("Detailed explanation of why this change is needed"),
|
|
765
|
+
changeType: z.enum(["new-spec", "revision", "policy-update", "schema-update"]).describe("Type of change being proposed"),
|
|
766
|
+
recommendedActions: z.array(z.string()).describe("List of specific actions to implement the change"),
|
|
767
|
+
estimatedImpact: z.enum(["low", "medium", "high"]).describe("Estimated impact of implementing this change"),
|
|
768
|
+
riskLevel: z.enum(["low", "medium", "high"]).describe("Risk level associated with this change"),
|
|
769
|
+
diff: z.string().optional().describe("Optional diff or code snippet showing the change")
|
|
770
|
+
});
|
|
771
|
+
|
|
772
|
+
class AISpecGenerator {
|
|
773
|
+
model;
|
|
774
|
+
config;
|
|
775
|
+
systemPrompt;
|
|
776
|
+
constructor(options) {
|
|
777
|
+
this.model = options.model;
|
|
778
|
+
this.config = options.evolutionConfig ?? {};
|
|
779
|
+
this.systemPrompt = options.systemPrompt ?? `You are a ContractSpec evolution expert. Your role is to analyze telemetry data, anomalies, and usage patterns to suggest improvements to API contracts and specifications.
|
|
780
|
+
|
|
781
|
+
When generating suggestions:
|
|
782
|
+
1. Be specific and actionable
|
|
783
|
+
2. Consider backwards compatibility
|
|
784
|
+
3. Prioritize stability and reliability
|
|
785
|
+
4. Explain the rationale clearly
|
|
786
|
+
5. Estimate impact and risk accurately`;
|
|
787
|
+
}
|
|
788
|
+
async generateFromIntent(intent, options = {}) {
|
|
789
|
+
const prompt = this.buildPrompt(intent, options);
|
|
790
|
+
const { output } = await generateText({
|
|
791
|
+
model: this.model,
|
|
792
|
+
system: this.systemPrompt,
|
|
793
|
+
prompt,
|
|
794
|
+
output: Output.object({
|
|
795
|
+
schema: SpecSuggestionProposalSchema
|
|
796
|
+
})
|
|
797
|
+
});
|
|
798
|
+
return this.buildSuggestion(intent, output);
|
|
799
|
+
}
|
|
800
|
+
async generateBatch(intents, options = {}) {
|
|
801
|
+
const maxConcurrent = options.maxConcurrent ?? 3;
|
|
802
|
+
const results = [];
|
|
803
|
+
for (let i = 0;i < intents.length; i += maxConcurrent) {
|
|
804
|
+
const batch = intents.slice(i, i + maxConcurrent);
|
|
805
|
+
const batchResults = await Promise.all(batch.map((intent) => this.generateFromIntent(intent)));
|
|
806
|
+
results.push(...batchResults);
|
|
807
|
+
}
|
|
808
|
+
return results;
|
|
809
|
+
}
|
|
810
|
+
async enhanceSuggestion(suggestion) {
|
|
811
|
+
const prompt = `Review and enhance this spec suggestion:
|
|
812
|
+
|
|
813
|
+
Intent: ${suggestion.intent.type} - ${suggestion.intent.description}
|
|
814
|
+
Current Summary: ${suggestion.proposal.summary}
|
|
815
|
+
Current Rationale: ${suggestion.proposal.rationale}
|
|
816
|
+
|
|
817
|
+
Evidence:
|
|
818
|
+
${suggestion.evidence.map((e) => `- ${e.type}: ${e.description}`).join(`
|
|
819
|
+
`)}
|
|
820
|
+
|
|
821
|
+
Please provide an improved version with more specific recommendations.`;
|
|
822
|
+
const { output } = await generateText({
|
|
823
|
+
model: this.model,
|
|
824
|
+
system: this.systemPrompt,
|
|
825
|
+
prompt,
|
|
826
|
+
output: Output.object({
|
|
827
|
+
schema: SpecSuggestionProposalSchema
|
|
828
|
+
})
|
|
829
|
+
});
|
|
830
|
+
return {
|
|
831
|
+
...suggestion,
|
|
832
|
+
proposal: {
|
|
833
|
+
...suggestion.proposal,
|
|
834
|
+
summary: output.summary,
|
|
835
|
+
rationale: output.rationale,
|
|
836
|
+
changeType: output.changeType,
|
|
837
|
+
diff: output.diff,
|
|
838
|
+
metadata: {
|
|
839
|
+
...suggestion.proposal.metadata,
|
|
840
|
+
aiEnhanced: true,
|
|
841
|
+
recommendedActions: output.recommendedActions,
|
|
842
|
+
estimatedImpact: output.estimatedImpact,
|
|
843
|
+
riskLevel: output.riskLevel
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
};
|
|
847
|
+
}
|
|
848
|
+
buildPrompt(intent, options) {
|
|
849
|
+
const parts = [
|
|
850
|
+
`Analyze this intent pattern and generate a spec suggestion:`,
|
|
851
|
+
``,
|
|
852
|
+
`Intent Type: ${intent.type}`,
|
|
853
|
+
`Description: ${intent.description}`,
|
|
854
|
+
`Confidence: ${(intent.confidence.score * 100).toFixed(0)}% (sample size: ${intent.confidence.sampleSize})`
|
|
855
|
+
];
|
|
856
|
+
if (intent.operation) {
|
|
857
|
+
parts.push(`Operation: ${intent.operation.key} v${intent.operation.version}`);
|
|
858
|
+
}
|
|
859
|
+
if (intent.evidence.length > 0) {
|
|
860
|
+
parts.push(``, `Evidence:`);
|
|
861
|
+
for (const evidence of intent.evidence) {
|
|
862
|
+
parts.push(`- [${evidence.type}] ${evidence.description}`);
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
if (intent.metadata) {
|
|
866
|
+
parts.push(``, `Metadata: ${JSON.stringify(intent.metadata, null, 2)}`);
|
|
867
|
+
}
|
|
868
|
+
if (options.existingSpec) {
|
|
869
|
+
parts.push(``, `Existing Spec:`, "```json", JSON.stringify(options.existingSpec, null, 2), "```");
|
|
870
|
+
}
|
|
871
|
+
if (options.additionalContext) {
|
|
872
|
+
parts.push(``, `Additional Context:`, options.additionalContext);
|
|
873
|
+
}
|
|
874
|
+
return parts.join(`
|
|
875
|
+
`);
|
|
876
|
+
}
|
|
877
|
+
buildSuggestion(intent, aiOutput) {
|
|
878
|
+
const now = new Date;
|
|
879
|
+
const proposal = {
|
|
880
|
+
summary: aiOutput.summary,
|
|
881
|
+
rationale: aiOutput.rationale,
|
|
882
|
+
changeType: aiOutput.changeType,
|
|
883
|
+
diff: aiOutput.diff,
|
|
884
|
+
metadata: {
|
|
885
|
+
aiGenerated: true,
|
|
886
|
+
recommendedActions: aiOutput.recommendedActions,
|
|
887
|
+
estimatedImpact: aiOutput.estimatedImpact,
|
|
888
|
+
riskLevel: aiOutput.riskLevel
|
|
889
|
+
}
|
|
890
|
+
};
|
|
891
|
+
return {
|
|
892
|
+
id: randomUUID3(),
|
|
893
|
+
intent,
|
|
894
|
+
target: intent.operation,
|
|
895
|
+
proposal,
|
|
896
|
+
confidence: intent.confidence.score,
|
|
897
|
+
priority: this.calculatePriority(intent, aiOutput),
|
|
898
|
+
createdAt: now,
|
|
899
|
+
createdBy: "ai-spec-generator",
|
|
900
|
+
status: this.determineInitialStatus(intent),
|
|
901
|
+
evidence: intent.evidence,
|
|
902
|
+
tags: ["ai-generated", intent.type]
|
|
903
|
+
};
|
|
904
|
+
}
|
|
905
|
+
calculatePriority(intent, aiOutput) {
|
|
906
|
+
const impactScore = aiOutput.estimatedImpact === "high" ? 1 : aiOutput.estimatedImpact === "medium" ? 0.5 : 0.25;
|
|
907
|
+
const intentScore = intent.confidence.score;
|
|
908
|
+
const urgency = intent.type === "error-spike" ? 0.3 : intent.type === "latency-regression" ? 0.2 : 0;
|
|
909
|
+
const combined = impactScore * 0.4 + intentScore * 0.4 + urgency;
|
|
910
|
+
if (combined >= 0.7)
|
|
911
|
+
return "high";
|
|
912
|
+
if (combined >= 0.4)
|
|
913
|
+
return "medium";
|
|
914
|
+
return "low";
|
|
915
|
+
}
|
|
916
|
+
determineInitialStatus(intent) {
|
|
917
|
+
if (this.config.autoApproveThreshold && intent.confidence.score >= this.config.autoApproveThreshold && !this.config.requireApproval) {
|
|
918
|
+
return "approved";
|
|
919
|
+
}
|
|
920
|
+
return "pending";
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
function createAISpecGenerator(config) {
|
|
924
|
+
return new AISpecGenerator(config);
|
|
925
|
+
}
|
|
926
|
+
// src/approval/integration.ts
|
|
927
|
+
import { mkdir, writeFile } from "node:fs/promises";
|
|
928
|
+
import { join } from "node:path";
|
|
929
|
+
|
|
930
|
+
class SpecSuggestionOrchestrator {
|
|
931
|
+
options;
|
|
932
|
+
constructor(options) {
|
|
933
|
+
this.options = options;
|
|
934
|
+
}
|
|
935
|
+
async submit(suggestion, session, approvalReason) {
|
|
936
|
+
await this.options.repository.create(suggestion);
|
|
937
|
+
if (session && this.options.approval) {
|
|
938
|
+
await this.options.approval.requestApproval({
|
|
939
|
+
sessionId: session.sessionId,
|
|
940
|
+
agentId: session.agentId,
|
|
941
|
+
tenantId: session.tenantId,
|
|
942
|
+
toolName: "evolution.apply_suggestion",
|
|
943
|
+
toolCallId: suggestion.id,
|
|
944
|
+
toolArgs: { suggestionId: suggestion.id },
|
|
945
|
+
reason: approvalReason ?? suggestion.proposal.summary,
|
|
946
|
+
payload: { suggestionId: suggestion.id }
|
|
947
|
+
});
|
|
948
|
+
}
|
|
949
|
+
return suggestion;
|
|
950
|
+
}
|
|
951
|
+
async approve(id, reviewer, notes) {
|
|
952
|
+
const suggestion = await this.ensureSuggestion(id);
|
|
953
|
+
await this.options.repository.updateStatus(id, "approved", {
|
|
954
|
+
reviewer,
|
|
955
|
+
notes,
|
|
956
|
+
decidedAt: new Date
|
|
957
|
+
});
|
|
958
|
+
if (this.options.writer) {
|
|
959
|
+
await this.options.writer.write({
|
|
960
|
+
...suggestion,
|
|
961
|
+
status: "approved",
|
|
962
|
+
approvals: {
|
|
963
|
+
reviewer,
|
|
964
|
+
notes,
|
|
965
|
+
decidedAt: new Date,
|
|
966
|
+
status: "approved"
|
|
967
|
+
}
|
|
968
|
+
});
|
|
969
|
+
}
|
|
970
|
+
}
|
|
971
|
+
async reject(id, reviewer, notes) {
|
|
972
|
+
await this.options.repository.updateStatus(id, "rejected", {
|
|
973
|
+
reviewer,
|
|
974
|
+
notes,
|
|
975
|
+
decidedAt: new Date
|
|
976
|
+
});
|
|
977
|
+
}
|
|
978
|
+
list(filters) {
|
|
979
|
+
return this.options.repository.list(filters);
|
|
980
|
+
}
|
|
981
|
+
async ensureSuggestion(id) {
|
|
982
|
+
const suggestion = await this.options.repository.getById(id);
|
|
983
|
+
if (!suggestion)
|
|
984
|
+
throw new Error(`Spec suggestion ${id} not found`);
|
|
985
|
+
return suggestion;
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
class FileSystemSuggestionWriter {
|
|
990
|
+
outputDir;
|
|
991
|
+
filenameTemplate;
|
|
992
|
+
constructor(options = {}) {
|
|
993
|
+
this.outputDir = options.outputDir ?? join(process.cwd(), "packages/libs/contracts/src/generated");
|
|
994
|
+
this.filenameTemplate = options.filenameTemplate ?? ((suggestion) => `${suggestion.target?.key ?? suggestion.intent.id}.v${suggestion.target?.version ?? "next"}.suggestion.json`);
|
|
995
|
+
}
|
|
996
|
+
async write(suggestion) {
|
|
997
|
+
await mkdir(this.outputDir, { recursive: true });
|
|
998
|
+
const filename = this.filenameTemplate(suggestion);
|
|
999
|
+
const filepath = join(this.outputDir, filename);
|
|
1000
|
+
const payload = serializeSuggestion(suggestion);
|
|
1001
|
+
await writeFile(filepath, JSON.stringify(payload, null, 2));
|
|
1002
|
+
return filepath;
|
|
1003
|
+
}
|
|
1004
|
+
}
|
|
1005
|
+
|
|
1006
|
+
class InMemorySpecSuggestionRepository {
|
|
1007
|
+
items = new Map;
|
|
1008
|
+
async create(suggestion) {
|
|
1009
|
+
this.items.set(suggestion.id, suggestion);
|
|
1010
|
+
}
|
|
1011
|
+
async getById(id) {
|
|
1012
|
+
return this.items.get(id);
|
|
1013
|
+
}
|
|
1014
|
+
async updateStatus(id, status, metadata) {
|
|
1015
|
+
const suggestion = await this.getById(id);
|
|
1016
|
+
if (!suggestion)
|
|
1017
|
+
return;
|
|
1018
|
+
this.items.set(id, {
|
|
1019
|
+
...suggestion,
|
|
1020
|
+
status,
|
|
1021
|
+
approvals: {
|
|
1022
|
+
reviewer: metadata?.reviewer,
|
|
1023
|
+
notes: metadata?.notes,
|
|
1024
|
+
decidedAt: metadata?.decidedAt,
|
|
1025
|
+
status
|
|
1026
|
+
}
|
|
1027
|
+
});
|
|
1028
|
+
}
|
|
1029
|
+
async list(filters) {
|
|
1030
|
+
const values = [...this.items.values()];
|
|
1031
|
+
if (!filters)
|
|
1032
|
+
return values;
|
|
1033
|
+
return values.filter((item) => {
|
|
1034
|
+
if (filters.status && item.status !== filters.status)
|
|
1035
|
+
return false;
|
|
1036
|
+
if (filters.operationKey && item.target?.key !== filters.operationKey)
|
|
1037
|
+
return false;
|
|
1038
|
+
return true;
|
|
1039
|
+
});
|
|
1040
|
+
}
|
|
1041
|
+
}
|
|
1042
|
+
function serializeSuggestion(suggestion) {
|
|
1043
|
+
const { proposal, ...rest } = suggestion;
|
|
1044
|
+
const { spec, ...proposalRest } = proposal;
|
|
1045
|
+
return {
|
|
1046
|
+
...rest,
|
|
1047
|
+
proposal: {
|
|
1048
|
+
...proposalRest,
|
|
1049
|
+
specMeta: spec?.meta
|
|
1050
|
+
},
|
|
1051
|
+
createdAt: suggestion.createdAt.toISOString(),
|
|
1052
|
+
intent: {
|
|
1053
|
+
...suggestion.intent,
|
|
1054
|
+
confidence: { ...suggestion.intent.confidence },
|
|
1055
|
+
evidence: suggestion.intent.evidence
|
|
1056
|
+
}
|
|
1057
|
+
};
|
|
1058
|
+
}
|
|
1059
|
+
export {
|
|
1060
|
+
createAISpecGenerator,
|
|
1061
|
+
SpecSuggestionOrchestrator,
|
|
1062
|
+
SpecGenerator,
|
|
1063
|
+
SpecAnalyzer,
|
|
1064
|
+
PosthogTelemetryReader,
|
|
1065
|
+
InMemorySpecSuggestionRepository,
|
|
1066
|
+
FileSystemSuggestionWriter,
|
|
1067
|
+
AISpecGenerator
|
|
1068
|
+
};
|