@contractspec/lib.example-shared-ui 1.11.0 → 1.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +86 -11
- package/.turbo/turbo-prebuild.log +1 -0
- package/CHANGELOG.md +14 -0
- package/dist/EvolutionDashboard.d.ts +11 -0
- package/dist/EvolutionDashboard.d.ts.map +1 -0
- package/dist/EvolutionDashboard.js +804 -0
- package/dist/EvolutionSidebar.d.ts +19 -0
- package/dist/EvolutionSidebar.d.ts.map +1 -0
- package/dist/EvolutionSidebar.js +532 -0
- package/dist/LocalDataIndicator.d.ts +2 -0
- package/dist/LocalDataIndicator.d.ts.map +1 -0
- package/dist/LocalDataIndicator.js +63 -0
- package/dist/MarkdownView.d.ts +20 -0
- package/dist/MarkdownView.d.ts.map +1 -0
- package/dist/MarkdownView.js +304 -0
- package/dist/OverlayContextProvider.d.ts +79 -0
- package/dist/OverlayContextProvider.d.ts.map +1 -0
- package/dist/OverlayContextProvider.js +203 -0
- package/dist/PersonalizationInsights.d.ts +14 -0
- package/dist/PersonalizationInsights.d.ts.map +1 -0
- package/dist/PersonalizationInsights.js +456 -0
- package/dist/SaveToStudioButton.d.ts +8 -0
- package/dist/SaveToStudioButton.d.ts.map +1 -0
- package/dist/SaveToStudioButton.js +74 -0
- package/dist/SpecEditorPanel.d.ts +23 -0
- package/dist/SpecEditorPanel.d.ts.map +1 -0
- package/dist/SpecEditorPanel.js +720 -0
- package/dist/TemplateShell.d.ts +13 -0
- package/dist/TemplateShell.d.ts.map +1 -0
- package/dist/TemplateShell.js +190 -0
- package/dist/browser/EvolutionDashboard.js +803 -0
- package/dist/browser/EvolutionSidebar.js +531 -0
- package/dist/browser/LocalDataIndicator.js +62 -0
- package/dist/browser/MarkdownView.js +303 -0
- package/dist/browser/OverlayContextProvider.js +202 -0
- package/dist/browser/PersonalizationInsights.js +455 -0
- package/dist/browser/SaveToStudioButton.js +73 -0
- package/dist/browser/SpecEditorPanel.js +719 -0
- package/dist/browser/TemplateShell.js +189 -0
- package/dist/browser/hooks/index.js +1516 -0
- package/dist/browser/hooks/useBehaviorTracking.js +157 -0
- package/dist/browser/hooks/useEvolution.js +260 -0
- package/dist/browser/hooks/useRegistryTemplates.js +31 -0
- package/dist/browser/hooks/useSpecContent.js +579 -0
- package/dist/browser/hooks/useWorkflowComposer.js +493 -0
- package/dist/browser/index.js +3497 -0
- package/dist/browser/lib/component-registry.js +42 -0
- package/dist/browser/lib/runtime-context.js +15 -0
- package/dist/browser/lib/types.js +0 -0
- package/dist/browser/overlay-types.js +0 -0
- package/dist/browser/utils/fetchPresentationData.js +15 -0
- package/dist/browser/utils/generateSpecFromTemplate.js +423 -0
- package/dist/browser/utils/index.js +437 -0
- package/dist/hooks/index.d.ts +6 -0
- package/dist/hooks/index.d.ts.map +1 -0
- package/dist/hooks/index.js +1517 -0
- package/dist/hooks/useBehaviorTracking.d.ts +56 -0
- package/dist/hooks/useBehaviorTracking.d.ts.map +1 -0
- package/dist/hooks/useBehaviorTracking.js +158 -0
- package/dist/hooks/useEvolution.d.ts +111 -0
- package/dist/hooks/useEvolution.d.ts.map +1 -0
- package/dist/hooks/useEvolution.js +261 -0
- package/dist/hooks/useRegistryTemplates.d.ts +10 -0
- package/dist/hooks/useRegistryTemplates.d.ts.map +1 -0
- package/dist/hooks/useRegistryTemplates.js +32 -0
- package/dist/hooks/useSpecContent.d.ts +41 -0
- package/dist/hooks/useSpecContent.d.ts.map +1 -0
- package/dist/hooks/useSpecContent.js +580 -0
- package/dist/hooks/useWorkflowComposer.d.ts +94 -0
- package/dist/hooks/useWorkflowComposer.d.ts.map +1 -0
- package/dist/hooks/useWorkflowComposer.js +494 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3498 -0
- package/dist/lib/component-registry.d.ts +18 -0
- package/dist/lib/component-registry.d.ts.map +1 -0
- package/dist/lib/component-registry.js +43 -0
- package/dist/lib/runtime-context.d.ts +29 -0
- package/dist/lib/runtime-context.d.ts.map +1 -0
- package/dist/lib/runtime-context.js +16 -0
- package/dist/lib/types.d.ts +69 -0
- package/dist/lib/types.d.ts.map +1 -0
- package/dist/lib/types.js +1 -0
- package/dist/node/EvolutionDashboard.js +803 -0
- package/dist/node/EvolutionSidebar.js +531 -0
- package/dist/node/LocalDataIndicator.js +62 -0
- package/dist/node/MarkdownView.js +303 -0
- package/dist/node/OverlayContextProvider.js +202 -0
- package/dist/node/PersonalizationInsights.js +455 -0
- package/dist/node/SaveToStudioButton.js +73 -0
- package/dist/node/SpecEditorPanel.js +719 -0
- package/dist/node/TemplateShell.js +189 -0
- package/dist/node/hooks/index.js +1516 -0
- package/dist/node/hooks/useBehaviorTracking.js +157 -0
- package/dist/node/hooks/useEvolution.js +260 -0
- package/dist/node/hooks/useRegistryTemplates.js +31 -0
- package/dist/node/hooks/useSpecContent.js +579 -0
- package/dist/node/hooks/useWorkflowComposer.js +493 -0
- package/dist/node/index.js +3497 -0
- package/dist/node/lib/component-registry.js +42 -0
- package/dist/node/lib/runtime-context.js +15 -0
- package/dist/node/lib/types.js +0 -0
- package/dist/node/overlay-types.js +0 -0
- package/dist/node/utils/fetchPresentationData.js +15 -0
- package/dist/node/utils/generateSpecFromTemplate.js +423 -0
- package/dist/node/utils/index.js +437 -0
- package/dist/overlay-types.d.ts +41 -0
- package/dist/overlay-types.d.ts.map +1 -0
- package/dist/overlay-types.js +1 -0
- package/dist/utils/fetchPresentationData.d.ts +34 -0
- package/dist/utils/fetchPresentationData.d.ts.map +1 -0
- package/dist/utils/fetchPresentationData.js +16 -0
- package/dist/utils/generateSpecFromTemplate.d.ts +7 -0
- package/dist/utils/generateSpecFromTemplate.d.ts.map +1 -0
- package/dist/utils/generateSpecFromTemplate.js +424 -0
- package/dist/utils/index.d.ts +3 -0
- package/dist/utils/index.d.ts.map +1 -0
- package/dist/utils/index.js +438 -0
- package/package.json +219 -14
- package/.turbo/turbo-build$colon$bundle.log +0 -9
- package/dist/index.mjs +0 -3121
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
// src/hooks/useBehaviorTracking.ts
|
|
2
|
+
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
3
|
+
"use client";
|
|
4
|
+
var BEHAVIOR_STORAGE_KEY = "contractspec-behavior-data";
|
|
5
|
+
var ALL_FEATURES = [
|
|
6
|
+
"playground",
|
|
7
|
+
"specs",
|
|
8
|
+
"builder",
|
|
9
|
+
"markdown",
|
|
10
|
+
"evolution",
|
|
11
|
+
"canvas_add",
|
|
12
|
+
"canvas_delete",
|
|
13
|
+
"spec_save",
|
|
14
|
+
"spec_validate",
|
|
15
|
+
"ai_suggestions"
|
|
16
|
+
];
|
|
17
|
+
function useBehaviorTracking(templateId) {
|
|
18
|
+
const [events, setEvents] = useState([]);
|
|
19
|
+
const sessionStartRef = useRef(new Date);
|
|
20
|
+
const [eventCount, setEventCount] = useState(0);
|
|
21
|
+
useEffect(() => {
|
|
22
|
+
try {
|
|
23
|
+
const stored = localStorage.getItem(BEHAVIOR_STORAGE_KEY);
|
|
24
|
+
if (stored) {
|
|
25
|
+
const data = JSON.parse(stored);
|
|
26
|
+
setEvents(data.events.map((e) => ({
|
|
27
|
+
...e,
|
|
28
|
+
timestamp: new Date(e.timestamp)
|
|
29
|
+
})));
|
|
30
|
+
sessionStartRef.current = new Date(data.sessionStart);
|
|
31
|
+
}
|
|
32
|
+
} catch {}
|
|
33
|
+
}, []);
|
|
34
|
+
useEffect(() => {
|
|
35
|
+
if (events.length > 0) {
|
|
36
|
+
try {
|
|
37
|
+
localStorage.setItem(BEHAVIOR_STORAGE_KEY, JSON.stringify({
|
|
38
|
+
events: events.map((e) => ({
|
|
39
|
+
...e,
|
|
40
|
+
timestamp: e.timestamp.toISOString()
|
|
41
|
+
})),
|
|
42
|
+
sessionStart: sessionStartRef.current.toISOString()
|
|
43
|
+
}));
|
|
44
|
+
} catch {}
|
|
45
|
+
}
|
|
46
|
+
}, [events]);
|
|
47
|
+
const trackEvent = useCallback((type, metadata) => {
|
|
48
|
+
const event = {
|
|
49
|
+
type,
|
|
50
|
+
timestamp: new Date,
|
|
51
|
+
templateId,
|
|
52
|
+
metadata
|
|
53
|
+
};
|
|
54
|
+
setEvents((prev) => [...prev, event]);
|
|
55
|
+
setEventCount((prev) => prev + 1);
|
|
56
|
+
}, [templateId]);
|
|
57
|
+
const getEventsByType = useCallback((type) => {
|
|
58
|
+
return events.filter((e) => e.type === type);
|
|
59
|
+
}, [events]);
|
|
60
|
+
const getSummary = useCallback(() => {
|
|
61
|
+
const now = new Date;
|
|
62
|
+
const sessionDuration = now.getTime() - sessionStartRef.current.getTime();
|
|
63
|
+
const templateCounts = new Map;
|
|
64
|
+
for (const event of events) {
|
|
65
|
+
const count = templateCounts.get(event.templateId) ?? 0;
|
|
66
|
+
templateCounts.set(event.templateId, count + 1);
|
|
67
|
+
}
|
|
68
|
+
const mostUsedTemplates = Array.from(templateCounts.entries()).map(([templateId2, count]) => ({ templateId: templateId2, count })).sort((a, b) => b.count - a.count).slice(0, 3);
|
|
69
|
+
const modeCounts = new Map;
|
|
70
|
+
for (const event of events) {
|
|
71
|
+
if (event.type === "mode_change" && event.metadata?.mode) {
|
|
72
|
+
const mode = event.metadata.mode;
|
|
73
|
+
const count = modeCounts.get(mode) ?? 0;
|
|
74
|
+
modeCounts.set(mode, count + 1);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
const mostUsedModes = Array.from(modeCounts.entries()).map(([mode, count]) => ({ mode, count })).sort((a, b) => b.count - a.count);
|
|
78
|
+
const featuresUsed = new Set;
|
|
79
|
+
for (const event of events) {
|
|
80
|
+
if (event.type === "mode_change" && event.metadata?.mode) {
|
|
81
|
+
featuresUsed.add(event.metadata.mode);
|
|
82
|
+
}
|
|
83
|
+
if (event.type === "feature_usage" && event.metadata?.feature) {
|
|
84
|
+
featuresUsed.add(event.metadata.feature);
|
|
85
|
+
}
|
|
86
|
+
if (event.type === "canvas_interaction") {
|
|
87
|
+
const action = event.metadata?.action;
|
|
88
|
+
if (action === "add")
|
|
89
|
+
featuresUsed.add("canvas_add");
|
|
90
|
+
if (action === "delete")
|
|
91
|
+
featuresUsed.add("canvas_delete");
|
|
92
|
+
}
|
|
93
|
+
if (event.type === "spec_edit") {
|
|
94
|
+
const action = event.metadata?.action;
|
|
95
|
+
if (action === "save")
|
|
96
|
+
featuresUsed.add("spec_save");
|
|
97
|
+
if (action === "validate")
|
|
98
|
+
featuresUsed.add("spec_validate");
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
const unusedFeatures = ALL_FEATURES.filter((f) => !featuresUsed.has(f));
|
|
102
|
+
const errorCount = events.filter((e) => e.type === "error").length;
|
|
103
|
+
const recommendations = generateRecommendations(Array.from(featuresUsed), unusedFeatures, mostUsedModes, events.length);
|
|
104
|
+
return {
|
|
105
|
+
totalEvents: events.length,
|
|
106
|
+
sessionDuration,
|
|
107
|
+
mostUsedTemplates,
|
|
108
|
+
mostUsedModes,
|
|
109
|
+
featuresUsed: Array.from(featuresUsed),
|
|
110
|
+
unusedFeatures,
|
|
111
|
+
errorCount,
|
|
112
|
+
recommendations
|
|
113
|
+
};
|
|
114
|
+
}, [events]);
|
|
115
|
+
const clear = useCallback(() => {
|
|
116
|
+
setEvents([]);
|
|
117
|
+
setEventCount(0);
|
|
118
|
+
sessionStartRef.current = new Date;
|
|
119
|
+
localStorage.removeItem(BEHAVIOR_STORAGE_KEY);
|
|
120
|
+
}, []);
|
|
121
|
+
return useMemo(() => ({
|
|
122
|
+
trackEvent,
|
|
123
|
+
getSummary,
|
|
124
|
+
getEventsByType,
|
|
125
|
+
eventCount,
|
|
126
|
+
sessionStart: sessionStartRef.current,
|
|
127
|
+
clear
|
|
128
|
+
}), [trackEvent, getSummary, getEventsByType, eventCount, clear]);
|
|
129
|
+
}
|
|
130
|
+
function generateRecommendations(featuresUsed, unusedFeatures, mostUsedModes, totalEvents) {
|
|
131
|
+
const recommendations = [];
|
|
132
|
+
if (unusedFeatures.includes("evolution")) {
|
|
133
|
+
recommendations.push("Try the AI Evolution mode to get automated improvement suggestions");
|
|
134
|
+
}
|
|
135
|
+
if (unusedFeatures.includes("markdown")) {
|
|
136
|
+
recommendations.push("Use Markdown preview to see documentation for your specs");
|
|
137
|
+
}
|
|
138
|
+
if (unusedFeatures.includes("builder")) {
|
|
139
|
+
recommendations.push("Explore the Visual Builder to design your UI components");
|
|
140
|
+
}
|
|
141
|
+
if (!featuresUsed.includes("spec_validate") && featuresUsed.includes("specs")) {
|
|
142
|
+
recommendations.push("Don't forget to validate your specs before saving");
|
|
143
|
+
}
|
|
144
|
+
if (featuresUsed.includes("evolution") && !featuresUsed.includes("ai_suggestions")) {
|
|
145
|
+
recommendations.push("Generate AI suggestions to get actionable improvement recommendations");
|
|
146
|
+
}
|
|
147
|
+
if (totalEvents > 50) {
|
|
148
|
+
recommendations.push("Great engagement! Consider saving your work regularly");
|
|
149
|
+
}
|
|
150
|
+
if (mostUsedModes.length === 1) {
|
|
151
|
+
recommendations.push("Try different modes to explore all sandbox capabilities");
|
|
152
|
+
}
|
|
153
|
+
return recommendations;
|
|
154
|
+
}
|
|
155
|
+
export {
|
|
156
|
+
useBehaviorTracking
|
|
157
|
+
};
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
// src/hooks/useEvolution.ts
|
|
2
|
+
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
3
|
+
"use client";
|
|
4
|
+
var EVOLUTION_STORAGE_KEY = "contractspec-evolution-data";
|
|
5
|
+
function useEvolution(templateId) {
|
|
6
|
+
const [usageStats, setUsageStats] = useState([]);
|
|
7
|
+
const [anomalies, setAnomalies] = useState([]);
|
|
8
|
+
const [suggestions, setSuggestions] = useState([]);
|
|
9
|
+
const [hints, setHints] = useState([]);
|
|
10
|
+
const [loading, setLoading] = useState(false);
|
|
11
|
+
const metricsRef = useRef([]);
|
|
12
|
+
const [operationCount, setOperationCount] = useState(0);
|
|
13
|
+
useEffect(() => {
|
|
14
|
+
try {
|
|
15
|
+
const stored = localStorage.getItem(`${EVOLUTION_STORAGE_KEY}-${templateId}`);
|
|
16
|
+
if (stored) {
|
|
17
|
+
const data = JSON.parse(stored);
|
|
18
|
+
setSuggestions(data.suggestions.map((s) => ({
|
|
19
|
+
...s,
|
|
20
|
+
createdAt: new Date(s.createdAt)
|
|
21
|
+
})));
|
|
22
|
+
}
|
|
23
|
+
} catch {}
|
|
24
|
+
}, [templateId]);
|
|
25
|
+
useEffect(() => {
|
|
26
|
+
try {
|
|
27
|
+
localStorage.setItem(`${EVOLUTION_STORAGE_KEY}-${templateId}`, JSON.stringify({ suggestions }));
|
|
28
|
+
} catch {}
|
|
29
|
+
}, [suggestions, templateId]);
|
|
30
|
+
const trackOperation = useCallback((operationName, durationMs, success, errorCode) => {
|
|
31
|
+
const sample = {
|
|
32
|
+
operation: {
|
|
33
|
+
name: operationName,
|
|
34
|
+
version: "1.0.0",
|
|
35
|
+
tenantId: "sandbox"
|
|
36
|
+
},
|
|
37
|
+
durationMs,
|
|
38
|
+
success,
|
|
39
|
+
timestamp: new Date,
|
|
40
|
+
errorCode
|
|
41
|
+
};
|
|
42
|
+
metricsRef.current.push(sample);
|
|
43
|
+
setOperationCount((prev) => prev + 1);
|
|
44
|
+
}, []);
|
|
45
|
+
const analyzeUsage = useCallback(() => {
|
|
46
|
+
const samples = metricsRef.current;
|
|
47
|
+
if (samples.length < 5)
|
|
48
|
+
return;
|
|
49
|
+
const groups = new Map;
|
|
50
|
+
for (const sample of samples) {
|
|
51
|
+
const key = `${sample.operation.name}.v${sample.operation.version}`;
|
|
52
|
+
const arr = groups.get(key) ?? [];
|
|
53
|
+
arr.push(sample);
|
|
54
|
+
groups.set(key, arr);
|
|
55
|
+
}
|
|
56
|
+
const stats = [];
|
|
57
|
+
const detectedAnomalies = [];
|
|
58
|
+
groups.forEach((opSamples) => {
|
|
59
|
+
if (opSamples.length < 3)
|
|
60
|
+
return;
|
|
61
|
+
const durations = opSamples.map((s) => s.durationMs).sort((a, b) => a - b);
|
|
62
|
+
const errors = opSamples.filter((s) => !s.success);
|
|
63
|
+
const totalCalls = opSamples.length;
|
|
64
|
+
const errorRate = errors.length / totalCalls;
|
|
65
|
+
const averageLatencyMs = durations.reduce((sum, value) => sum + value, 0) / totalCalls;
|
|
66
|
+
const timestamps = opSamples.map((s) => s.timestamp.getTime());
|
|
67
|
+
const firstSample = opSamples[0];
|
|
68
|
+
if (!firstSample)
|
|
69
|
+
return;
|
|
70
|
+
const stat = {
|
|
71
|
+
operation: firstSample.operation,
|
|
72
|
+
totalCalls,
|
|
73
|
+
successRate: 1 - errorRate,
|
|
74
|
+
errorRate,
|
|
75
|
+
averageLatencyMs,
|
|
76
|
+
p95LatencyMs: percentile(durations, 0.95),
|
|
77
|
+
p99LatencyMs: percentile(durations, 0.99),
|
|
78
|
+
maxLatencyMs: Math.max(...durations),
|
|
79
|
+
lastSeenAt: new Date(Math.max(...timestamps)),
|
|
80
|
+
windowStart: new Date(Math.min(...timestamps)),
|
|
81
|
+
windowEnd: new Date(Math.max(...timestamps)),
|
|
82
|
+
topErrors: errors.reduce((acc, s) => {
|
|
83
|
+
if (s.errorCode) {
|
|
84
|
+
acc[s.errorCode] = (acc[s.errorCode] ?? 0) + 1;
|
|
85
|
+
}
|
|
86
|
+
return acc;
|
|
87
|
+
}, {})
|
|
88
|
+
};
|
|
89
|
+
stats.push(stat);
|
|
90
|
+
if (errorRate > 0.1) {
|
|
91
|
+
detectedAnomalies.push({
|
|
92
|
+
operation: stat.operation,
|
|
93
|
+
severity: errorRate > 0.3 ? "high" : errorRate > 0.2 ? "medium" : "low",
|
|
94
|
+
metric: "error-rate",
|
|
95
|
+
description: `Error rate ${(errorRate * 100).toFixed(1)}% exceeds threshold`,
|
|
96
|
+
detectedAt: new Date,
|
|
97
|
+
threshold: 0.1,
|
|
98
|
+
observedValue: errorRate
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
if (stat.p99LatencyMs > 500) {
|
|
102
|
+
detectedAnomalies.push({
|
|
103
|
+
operation: stat.operation,
|
|
104
|
+
severity: stat.p99LatencyMs > 1000 ? "high" : stat.p99LatencyMs > 750 ? "medium" : "low",
|
|
105
|
+
metric: "latency",
|
|
106
|
+
description: `P99 latency ${stat.p99LatencyMs.toFixed(0)}ms exceeds threshold`,
|
|
107
|
+
detectedAt: new Date,
|
|
108
|
+
threshold: 500,
|
|
109
|
+
observedValue: stat.p99LatencyMs
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
});
|
|
113
|
+
setUsageStats(stats);
|
|
114
|
+
setAnomalies(detectedAnomalies);
|
|
115
|
+
const newHints = detectedAnomalies.map((anomaly) => ({
|
|
116
|
+
operation: anomaly.operation,
|
|
117
|
+
category: anomaly.metric === "latency" ? "performance" : "error-handling",
|
|
118
|
+
summary: anomaly.metric === "latency" ? "Latency regression detected" : "Error spike detected",
|
|
119
|
+
justification: anomaly.description,
|
|
120
|
+
recommendedActions: anomaly.metric === "latency" ? [
|
|
121
|
+
"Add caching layer",
|
|
122
|
+
"Optimize database queries",
|
|
123
|
+
"Consider pagination"
|
|
124
|
+
] : [
|
|
125
|
+
"Add retry logic",
|
|
126
|
+
"Improve error handling",
|
|
127
|
+
"Add circuit breaker"
|
|
128
|
+
]
|
|
129
|
+
}));
|
|
130
|
+
setHints(newHints);
|
|
131
|
+
}, []);
|
|
132
|
+
const generateSuggestions = useCallback(async () => {
|
|
133
|
+
if (anomalies.length === 0)
|
|
134
|
+
return;
|
|
135
|
+
setLoading(true);
|
|
136
|
+
await new Promise((resolve) => setTimeout(resolve, 800));
|
|
137
|
+
const newSuggestions = anomalies.map((anomaly) => ({
|
|
138
|
+
id: `suggestion-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
|
|
139
|
+
intent: {
|
|
140
|
+
id: `intent-${anomaly.operation.name}`,
|
|
141
|
+
type: anomaly.metric === "latency" ? "latency-regression" : anomaly.metric === "error-rate" ? "error-spike" : "throughput-drop",
|
|
142
|
+
description: anomaly.description,
|
|
143
|
+
operation: anomaly.operation,
|
|
144
|
+
confidence: {
|
|
145
|
+
score: anomaly.severity === "high" ? 0.9 : anomaly.severity === "medium" ? 0.7 : 0.5,
|
|
146
|
+
sampleSize: usageStats.find((s) => s.operation.name === anomaly.operation.name)?.totalCalls ?? 0
|
|
147
|
+
}
|
|
148
|
+
},
|
|
149
|
+
target: anomaly.operation,
|
|
150
|
+
proposal: {
|
|
151
|
+
summary: generateSuggestionSummary(anomaly),
|
|
152
|
+
rationale: generateSuggestionRationale(anomaly),
|
|
153
|
+
changeType: anomaly.metric === "error-rate" ? "policy-update" : "revision",
|
|
154
|
+
recommendedActions: generateRecommendedActions(anomaly)
|
|
155
|
+
},
|
|
156
|
+
confidence: anomaly.severity === "high" ? 0.85 : anomaly.severity === "medium" ? 0.7 : 0.55,
|
|
157
|
+
createdAt: new Date,
|
|
158
|
+
createdBy: "ai-evolution-agent",
|
|
159
|
+
status: "pending",
|
|
160
|
+
priority: anomaly.severity
|
|
161
|
+
}));
|
|
162
|
+
setSuggestions((prev) => [...prev, ...newSuggestions]);
|
|
163
|
+
setLoading(false);
|
|
164
|
+
}, [anomalies, usageStats]);
|
|
165
|
+
const approveSuggestion = useCallback((id, _notes) => {
|
|
166
|
+
setSuggestions((prev) => prev.map((s) => s.id === id ? { ...s, status: "approved" } : s));
|
|
167
|
+
}, []);
|
|
168
|
+
const rejectSuggestion = useCallback((id, _notes) => {
|
|
169
|
+
setSuggestions((prev) => prev.map((s) => s.id === id ? { ...s, status: "rejected" } : s));
|
|
170
|
+
}, []);
|
|
171
|
+
const clear = useCallback(() => {
|
|
172
|
+
metricsRef.current = [];
|
|
173
|
+
setOperationCount(0);
|
|
174
|
+
setUsageStats([]);
|
|
175
|
+
setAnomalies([]);
|
|
176
|
+
setSuggestions([]);
|
|
177
|
+
setHints([]);
|
|
178
|
+
localStorage.removeItem(`${EVOLUTION_STORAGE_KEY}-${templateId}`);
|
|
179
|
+
}, [templateId]);
|
|
180
|
+
return useMemo(() => ({
|
|
181
|
+
usageStats,
|
|
182
|
+
anomalies,
|
|
183
|
+
suggestions,
|
|
184
|
+
hints,
|
|
185
|
+
loading,
|
|
186
|
+
trackOperation,
|
|
187
|
+
analyzeUsage,
|
|
188
|
+
generateSuggestions,
|
|
189
|
+
approveSuggestion,
|
|
190
|
+
rejectSuggestion,
|
|
191
|
+
clear,
|
|
192
|
+
operationCount
|
|
193
|
+
}), [
|
|
194
|
+
usageStats,
|
|
195
|
+
anomalies,
|
|
196
|
+
suggestions,
|
|
197
|
+
hints,
|
|
198
|
+
loading,
|
|
199
|
+
trackOperation,
|
|
200
|
+
analyzeUsage,
|
|
201
|
+
generateSuggestions,
|
|
202
|
+
approveSuggestion,
|
|
203
|
+
rejectSuggestion,
|
|
204
|
+
clear,
|
|
205
|
+
operationCount
|
|
206
|
+
]);
|
|
207
|
+
}
|
|
208
|
+
function percentile(values, p) {
|
|
209
|
+
if (!values.length)
|
|
210
|
+
return 0;
|
|
211
|
+
if (values.length === 1)
|
|
212
|
+
return values[0] ?? 0;
|
|
213
|
+
const idx = Math.min(values.length - 1, Math.floor(p * values.length));
|
|
214
|
+
return values[idx] ?? 0;
|
|
215
|
+
}
|
|
216
|
+
function generateSuggestionSummary(anomaly) {
|
|
217
|
+
if (anomaly.metric === "latency") {
|
|
218
|
+
return `Add caching and pagination to ${anomaly.operation.name} to reduce latency`;
|
|
219
|
+
}
|
|
220
|
+
if (anomaly.metric === "error-rate") {
|
|
221
|
+
return `Add retry policy and circuit breaker to ${anomaly.operation.name}`;
|
|
222
|
+
}
|
|
223
|
+
return `Optimize ${anomaly.operation.name} for improved throughput`;
|
|
224
|
+
}
|
|
225
|
+
function generateSuggestionRationale(anomaly) {
|
|
226
|
+
if (anomaly.metric === "latency") {
|
|
227
|
+
return `The operation ${anomaly.operation.name} is experiencing P99 latency of ${anomaly.observedValue?.toFixed(0)}ms, which is above the recommended threshold of ${anomaly.threshold}ms. This can impact user experience and downstream operations.`;
|
|
228
|
+
}
|
|
229
|
+
if (anomaly.metric === "error-rate") {
|
|
230
|
+
return `The error rate for ${anomaly.operation.name} is ${((anomaly.observedValue ?? 0) * 100).toFixed(1)}%, indicating potential issues with input validation, external dependencies, or resource limits.`;
|
|
231
|
+
}
|
|
232
|
+
return `Throughput for ${anomaly.operation.name} has dropped significantly, suggesting potential bottlenecks or reduced demand that should be investigated.`;
|
|
233
|
+
}
|
|
234
|
+
function generateRecommendedActions(anomaly) {
|
|
235
|
+
if (anomaly.metric === "latency") {
|
|
236
|
+
return [
|
|
237
|
+
"Add response caching for frequently accessed data",
|
|
238
|
+
"Implement pagination for large result sets",
|
|
239
|
+
"Optimize database queries with proper indexing",
|
|
240
|
+
"Consider adding a GraphQL DataLoader for batching"
|
|
241
|
+
];
|
|
242
|
+
}
|
|
243
|
+
if (anomaly.metric === "error-rate") {
|
|
244
|
+
return [
|
|
245
|
+
"Add input validation at the contract level",
|
|
246
|
+
"Implement retry policy with exponential backoff",
|
|
247
|
+
"Add circuit breaker for external dependencies",
|
|
248
|
+
"Enhance error logging for better debugging"
|
|
249
|
+
];
|
|
250
|
+
}
|
|
251
|
+
return [
|
|
252
|
+
"Review resource allocation and scaling policies",
|
|
253
|
+
"Check for upstream routing or load balancer issues",
|
|
254
|
+
"Validate feature flag configurations",
|
|
255
|
+
"Monitor dependency health metrics"
|
|
256
|
+
];
|
|
257
|
+
}
|
|
258
|
+
export {
|
|
259
|
+
useEvolution
|
|
260
|
+
};
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// src/hooks/useRegistryTemplates.ts
|
|
2
|
+
import { useQuery } from "@tanstack/react-query";
|
|
3
|
+
function useRegistryTemplates() {
|
|
4
|
+
return useQuery({
|
|
5
|
+
queryKey: ["registryTemplates"],
|
|
6
|
+
queryFn: async () => {
|
|
7
|
+
const registryUrl = process.env.NEXT_PUBLIC_CONTRACTSPEC_REGISTRY_URL ?? "";
|
|
8
|
+
if (!registryUrl)
|
|
9
|
+
return [];
|
|
10
|
+
const res = await fetch(`${registryUrl.replace(/\/$/, "")}/r/contractspec.json`, {
|
|
11
|
+
method: "GET",
|
|
12
|
+
headers: { Accept: "application/json" }
|
|
13
|
+
});
|
|
14
|
+
if (!res.ok)
|
|
15
|
+
return [];
|
|
16
|
+
const json = await res.json();
|
|
17
|
+
const items = json.items ?? [];
|
|
18
|
+
return items.filter((i) => i.type === "contractspec:template").map((i) => ({
|
|
19
|
+
id: i.name,
|
|
20
|
+
name: i.title ?? i.name,
|
|
21
|
+
description: i.description,
|
|
22
|
+
tags: i.meta?.tags ?? [],
|
|
23
|
+
source: "registry",
|
|
24
|
+
registryUrl
|
|
25
|
+
}));
|
|
26
|
+
}
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
export {
|
|
30
|
+
useRegistryTemplates
|
|
31
|
+
};
|