@contractspec/lib.example-shared-ui 1.11.0 → 1.13.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 (121) hide show
  1. package/.turbo/turbo-build.log +86 -11
  2. package/.turbo/turbo-prebuild.log +1 -0
  3. package/CHANGELOG.md +27 -0
  4. package/dist/EvolutionDashboard.d.ts +11 -0
  5. package/dist/EvolutionDashboard.d.ts.map +1 -0
  6. package/dist/EvolutionDashboard.js +804 -0
  7. package/dist/EvolutionSidebar.d.ts +19 -0
  8. package/dist/EvolutionSidebar.d.ts.map +1 -0
  9. package/dist/EvolutionSidebar.js +532 -0
  10. package/dist/LocalDataIndicator.d.ts +2 -0
  11. package/dist/LocalDataIndicator.d.ts.map +1 -0
  12. package/dist/LocalDataIndicator.js +63 -0
  13. package/dist/MarkdownView.d.ts +20 -0
  14. package/dist/MarkdownView.d.ts.map +1 -0
  15. package/dist/MarkdownView.js +304 -0
  16. package/dist/OverlayContextProvider.d.ts +79 -0
  17. package/dist/OverlayContextProvider.d.ts.map +1 -0
  18. package/dist/OverlayContextProvider.js +203 -0
  19. package/dist/PersonalizationInsights.d.ts +14 -0
  20. package/dist/PersonalizationInsights.d.ts.map +1 -0
  21. package/dist/PersonalizationInsights.js +456 -0
  22. package/dist/SaveToStudioButton.d.ts +8 -0
  23. package/dist/SaveToStudioButton.d.ts.map +1 -0
  24. package/dist/SaveToStudioButton.js +74 -0
  25. package/dist/SpecEditorPanel.d.ts +23 -0
  26. package/dist/SpecEditorPanel.d.ts.map +1 -0
  27. package/dist/SpecEditorPanel.js +720 -0
  28. package/dist/TemplateShell.d.ts +13 -0
  29. package/dist/TemplateShell.d.ts.map +1 -0
  30. package/dist/TemplateShell.js +190 -0
  31. package/dist/browser/EvolutionDashboard.js +803 -0
  32. package/dist/browser/EvolutionSidebar.js +531 -0
  33. package/dist/browser/LocalDataIndicator.js +62 -0
  34. package/dist/browser/MarkdownView.js +303 -0
  35. package/dist/browser/OverlayContextProvider.js +202 -0
  36. package/dist/browser/PersonalizationInsights.js +455 -0
  37. package/dist/browser/SaveToStudioButton.js +73 -0
  38. package/dist/browser/SpecEditorPanel.js +719 -0
  39. package/dist/browser/TemplateShell.js +189 -0
  40. package/dist/browser/hooks/index.js +1516 -0
  41. package/dist/browser/hooks/useBehaviorTracking.js +157 -0
  42. package/dist/browser/hooks/useEvolution.js +260 -0
  43. package/dist/browser/hooks/useRegistryTemplates.js +31 -0
  44. package/dist/browser/hooks/useSpecContent.js +579 -0
  45. package/dist/browser/hooks/useWorkflowComposer.js +493 -0
  46. package/dist/browser/index.js +3497 -0
  47. package/dist/browser/lib/component-registry.js +42 -0
  48. package/dist/browser/lib/runtime-context.js +15 -0
  49. package/dist/browser/lib/types.js +0 -0
  50. package/dist/browser/overlay-types.js +0 -0
  51. package/dist/browser/utils/fetchPresentationData.js +15 -0
  52. package/dist/browser/utils/generateSpecFromTemplate.js +423 -0
  53. package/dist/browser/utils/index.js +437 -0
  54. package/dist/hooks/index.d.ts +6 -0
  55. package/dist/hooks/index.d.ts.map +1 -0
  56. package/dist/hooks/index.js +1517 -0
  57. package/dist/hooks/useBehaviorTracking.d.ts +56 -0
  58. package/dist/hooks/useBehaviorTracking.d.ts.map +1 -0
  59. package/dist/hooks/useBehaviorTracking.js +158 -0
  60. package/dist/hooks/useEvolution.d.ts +111 -0
  61. package/dist/hooks/useEvolution.d.ts.map +1 -0
  62. package/dist/hooks/useEvolution.js +261 -0
  63. package/dist/hooks/useRegistryTemplates.d.ts +10 -0
  64. package/dist/hooks/useRegistryTemplates.d.ts.map +1 -0
  65. package/dist/hooks/useRegistryTemplates.js +32 -0
  66. package/dist/hooks/useSpecContent.d.ts +41 -0
  67. package/dist/hooks/useSpecContent.d.ts.map +1 -0
  68. package/dist/hooks/useSpecContent.js +580 -0
  69. package/dist/hooks/useWorkflowComposer.d.ts +94 -0
  70. package/dist/hooks/useWorkflowComposer.d.ts.map +1 -0
  71. package/dist/hooks/useWorkflowComposer.js +494 -0
  72. package/dist/index.d.ts +16 -0
  73. package/dist/index.d.ts.map +1 -0
  74. package/dist/index.js +3498 -0
  75. package/dist/lib/component-registry.d.ts +18 -0
  76. package/dist/lib/component-registry.d.ts.map +1 -0
  77. package/dist/lib/component-registry.js +43 -0
  78. package/dist/lib/runtime-context.d.ts +29 -0
  79. package/dist/lib/runtime-context.d.ts.map +1 -0
  80. package/dist/lib/runtime-context.js +16 -0
  81. package/dist/lib/types.d.ts +69 -0
  82. package/dist/lib/types.d.ts.map +1 -0
  83. package/dist/lib/types.js +1 -0
  84. package/dist/node/EvolutionDashboard.js +803 -0
  85. package/dist/node/EvolutionSidebar.js +531 -0
  86. package/dist/node/LocalDataIndicator.js +62 -0
  87. package/dist/node/MarkdownView.js +303 -0
  88. package/dist/node/OverlayContextProvider.js +202 -0
  89. package/dist/node/PersonalizationInsights.js +455 -0
  90. package/dist/node/SaveToStudioButton.js +73 -0
  91. package/dist/node/SpecEditorPanel.js +719 -0
  92. package/dist/node/TemplateShell.js +189 -0
  93. package/dist/node/hooks/index.js +1516 -0
  94. package/dist/node/hooks/useBehaviorTracking.js +157 -0
  95. package/dist/node/hooks/useEvolution.js +260 -0
  96. package/dist/node/hooks/useRegistryTemplates.js +31 -0
  97. package/dist/node/hooks/useSpecContent.js +579 -0
  98. package/dist/node/hooks/useWorkflowComposer.js +493 -0
  99. package/dist/node/index.js +3497 -0
  100. package/dist/node/lib/component-registry.js +42 -0
  101. package/dist/node/lib/runtime-context.js +15 -0
  102. package/dist/node/lib/types.js +0 -0
  103. package/dist/node/overlay-types.js +0 -0
  104. package/dist/node/utils/fetchPresentationData.js +15 -0
  105. package/dist/node/utils/generateSpecFromTemplate.js +423 -0
  106. package/dist/node/utils/index.js +437 -0
  107. package/dist/overlay-types.d.ts +41 -0
  108. package/dist/overlay-types.d.ts.map +1 -0
  109. package/dist/overlay-types.js +1 -0
  110. package/dist/utils/fetchPresentationData.d.ts +34 -0
  111. package/dist/utils/fetchPresentationData.d.ts.map +1 -0
  112. package/dist/utils/fetchPresentationData.js +16 -0
  113. package/dist/utils/generateSpecFromTemplate.d.ts +7 -0
  114. package/dist/utils/generateSpecFromTemplate.d.ts.map +1 -0
  115. package/dist/utils/generateSpecFromTemplate.js +424 -0
  116. package/dist/utils/index.d.ts +3 -0
  117. package/dist/utils/index.d.ts.map +1 -0
  118. package/dist/utils/index.js +438 -0
  119. package/package.json +219 -14
  120. package/.turbo/turbo-build$colon$bundle.log +0 -9
  121. package/dist/index.mjs +0 -3121
@@ -0,0 +1,1517 @@
1
+ // @bun
2
+ // src/hooks/useEvolution.ts
3
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
4
+ "use client";
5
+ var EVOLUTION_STORAGE_KEY = "contractspec-evolution-data";
6
+ function useEvolution(templateId) {
7
+ const [usageStats, setUsageStats] = useState([]);
8
+ const [anomalies, setAnomalies] = useState([]);
9
+ const [suggestions, setSuggestions] = useState([]);
10
+ const [hints, setHints] = useState([]);
11
+ const [loading, setLoading] = useState(false);
12
+ const metricsRef = useRef([]);
13
+ const [operationCount, setOperationCount] = useState(0);
14
+ useEffect(() => {
15
+ try {
16
+ const stored = localStorage.getItem(`${EVOLUTION_STORAGE_KEY}-${templateId}`);
17
+ if (stored) {
18
+ const data = JSON.parse(stored);
19
+ setSuggestions(data.suggestions.map((s) => ({
20
+ ...s,
21
+ createdAt: new Date(s.createdAt)
22
+ })));
23
+ }
24
+ } catch {}
25
+ }, [templateId]);
26
+ useEffect(() => {
27
+ try {
28
+ localStorage.setItem(`${EVOLUTION_STORAGE_KEY}-${templateId}`, JSON.stringify({ suggestions }));
29
+ } catch {}
30
+ }, [suggestions, templateId]);
31
+ const trackOperation = useCallback((operationName, durationMs, success, errorCode) => {
32
+ const sample = {
33
+ operation: {
34
+ name: operationName,
35
+ version: "1.0.0",
36
+ tenantId: "sandbox"
37
+ },
38
+ durationMs,
39
+ success,
40
+ timestamp: new Date,
41
+ errorCode
42
+ };
43
+ metricsRef.current.push(sample);
44
+ setOperationCount((prev) => prev + 1);
45
+ }, []);
46
+ const analyzeUsage = useCallback(() => {
47
+ const samples = metricsRef.current;
48
+ if (samples.length < 5)
49
+ return;
50
+ const groups = new Map;
51
+ for (const sample of samples) {
52
+ const key = `${sample.operation.name}.v${sample.operation.version}`;
53
+ const arr = groups.get(key) ?? [];
54
+ arr.push(sample);
55
+ groups.set(key, arr);
56
+ }
57
+ const stats = [];
58
+ const detectedAnomalies = [];
59
+ groups.forEach((opSamples) => {
60
+ if (opSamples.length < 3)
61
+ return;
62
+ const durations = opSamples.map((s) => s.durationMs).sort((a, b) => a - b);
63
+ const errors = opSamples.filter((s) => !s.success);
64
+ const totalCalls = opSamples.length;
65
+ const errorRate = errors.length / totalCalls;
66
+ const averageLatencyMs = durations.reduce((sum, value) => sum + value, 0) / totalCalls;
67
+ const timestamps = opSamples.map((s) => s.timestamp.getTime());
68
+ const firstSample = opSamples[0];
69
+ if (!firstSample)
70
+ return;
71
+ const stat = {
72
+ operation: firstSample.operation,
73
+ totalCalls,
74
+ successRate: 1 - errorRate,
75
+ errorRate,
76
+ averageLatencyMs,
77
+ p95LatencyMs: percentile(durations, 0.95),
78
+ p99LatencyMs: percentile(durations, 0.99),
79
+ maxLatencyMs: Math.max(...durations),
80
+ lastSeenAt: new Date(Math.max(...timestamps)),
81
+ windowStart: new Date(Math.min(...timestamps)),
82
+ windowEnd: new Date(Math.max(...timestamps)),
83
+ topErrors: errors.reduce((acc, s) => {
84
+ if (s.errorCode) {
85
+ acc[s.errorCode] = (acc[s.errorCode] ?? 0) + 1;
86
+ }
87
+ return acc;
88
+ }, {})
89
+ };
90
+ stats.push(stat);
91
+ if (errorRate > 0.1) {
92
+ detectedAnomalies.push({
93
+ operation: stat.operation,
94
+ severity: errorRate > 0.3 ? "high" : errorRate > 0.2 ? "medium" : "low",
95
+ metric: "error-rate",
96
+ description: `Error rate ${(errorRate * 100).toFixed(1)}% exceeds threshold`,
97
+ detectedAt: new Date,
98
+ threshold: 0.1,
99
+ observedValue: errorRate
100
+ });
101
+ }
102
+ if (stat.p99LatencyMs > 500) {
103
+ detectedAnomalies.push({
104
+ operation: stat.operation,
105
+ severity: stat.p99LatencyMs > 1000 ? "high" : stat.p99LatencyMs > 750 ? "medium" : "low",
106
+ metric: "latency",
107
+ description: `P99 latency ${stat.p99LatencyMs.toFixed(0)}ms exceeds threshold`,
108
+ detectedAt: new Date,
109
+ threshold: 500,
110
+ observedValue: stat.p99LatencyMs
111
+ });
112
+ }
113
+ });
114
+ setUsageStats(stats);
115
+ setAnomalies(detectedAnomalies);
116
+ const newHints = detectedAnomalies.map((anomaly) => ({
117
+ operation: anomaly.operation,
118
+ category: anomaly.metric === "latency" ? "performance" : "error-handling",
119
+ summary: anomaly.metric === "latency" ? "Latency regression detected" : "Error spike detected",
120
+ justification: anomaly.description,
121
+ recommendedActions: anomaly.metric === "latency" ? [
122
+ "Add caching layer",
123
+ "Optimize database queries",
124
+ "Consider pagination"
125
+ ] : [
126
+ "Add retry logic",
127
+ "Improve error handling",
128
+ "Add circuit breaker"
129
+ ]
130
+ }));
131
+ setHints(newHints);
132
+ }, []);
133
+ const generateSuggestions = useCallback(async () => {
134
+ if (anomalies.length === 0)
135
+ return;
136
+ setLoading(true);
137
+ await new Promise((resolve) => setTimeout(resolve, 800));
138
+ const newSuggestions = anomalies.map((anomaly) => ({
139
+ id: `suggestion-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
140
+ intent: {
141
+ id: `intent-${anomaly.operation.name}`,
142
+ type: anomaly.metric === "latency" ? "latency-regression" : anomaly.metric === "error-rate" ? "error-spike" : "throughput-drop",
143
+ description: anomaly.description,
144
+ operation: anomaly.operation,
145
+ confidence: {
146
+ score: anomaly.severity === "high" ? 0.9 : anomaly.severity === "medium" ? 0.7 : 0.5,
147
+ sampleSize: usageStats.find((s) => s.operation.name === anomaly.operation.name)?.totalCalls ?? 0
148
+ }
149
+ },
150
+ target: anomaly.operation,
151
+ proposal: {
152
+ summary: generateSuggestionSummary(anomaly),
153
+ rationale: generateSuggestionRationale(anomaly),
154
+ changeType: anomaly.metric === "error-rate" ? "policy-update" : "revision",
155
+ recommendedActions: generateRecommendedActions(anomaly)
156
+ },
157
+ confidence: anomaly.severity === "high" ? 0.85 : anomaly.severity === "medium" ? 0.7 : 0.55,
158
+ createdAt: new Date,
159
+ createdBy: "ai-evolution-agent",
160
+ status: "pending",
161
+ priority: anomaly.severity
162
+ }));
163
+ setSuggestions((prev) => [...prev, ...newSuggestions]);
164
+ setLoading(false);
165
+ }, [anomalies, usageStats]);
166
+ const approveSuggestion = useCallback((id, _notes) => {
167
+ setSuggestions((prev) => prev.map((s) => s.id === id ? { ...s, status: "approved" } : s));
168
+ }, []);
169
+ const rejectSuggestion = useCallback((id, _notes) => {
170
+ setSuggestions((prev) => prev.map((s) => s.id === id ? { ...s, status: "rejected" } : s));
171
+ }, []);
172
+ const clear = useCallback(() => {
173
+ metricsRef.current = [];
174
+ setOperationCount(0);
175
+ setUsageStats([]);
176
+ setAnomalies([]);
177
+ setSuggestions([]);
178
+ setHints([]);
179
+ localStorage.removeItem(`${EVOLUTION_STORAGE_KEY}-${templateId}`);
180
+ }, [templateId]);
181
+ return useMemo(() => ({
182
+ usageStats,
183
+ anomalies,
184
+ suggestions,
185
+ hints,
186
+ loading,
187
+ trackOperation,
188
+ analyzeUsage,
189
+ generateSuggestions,
190
+ approveSuggestion,
191
+ rejectSuggestion,
192
+ clear,
193
+ operationCount
194
+ }), [
195
+ usageStats,
196
+ anomalies,
197
+ suggestions,
198
+ hints,
199
+ loading,
200
+ trackOperation,
201
+ analyzeUsage,
202
+ generateSuggestions,
203
+ approveSuggestion,
204
+ rejectSuggestion,
205
+ clear,
206
+ operationCount
207
+ ]);
208
+ }
209
+ function percentile(values, p) {
210
+ if (!values.length)
211
+ return 0;
212
+ if (values.length === 1)
213
+ return values[0] ?? 0;
214
+ const idx = Math.min(values.length - 1, Math.floor(p * values.length));
215
+ return values[idx] ?? 0;
216
+ }
217
+ function generateSuggestionSummary(anomaly) {
218
+ if (anomaly.metric === "latency") {
219
+ return `Add caching and pagination to ${anomaly.operation.name} to reduce latency`;
220
+ }
221
+ if (anomaly.metric === "error-rate") {
222
+ return `Add retry policy and circuit breaker to ${anomaly.operation.name}`;
223
+ }
224
+ return `Optimize ${anomaly.operation.name} for improved throughput`;
225
+ }
226
+ function generateSuggestionRationale(anomaly) {
227
+ if (anomaly.metric === "latency") {
228
+ 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.`;
229
+ }
230
+ if (anomaly.metric === "error-rate") {
231
+ 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.`;
232
+ }
233
+ return `Throughput for ${anomaly.operation.name} has dropped significantly, suggesting potential bottlenecks or reduced demand that should be investigated.`;
234
+ }
235
+ function generateRecommendedActions(anomaly) {
236
+ if (anomaly.metric === "latency") {
237
+ return [
238
+ "Add response caching for frequently accessed data",
239
+ "Implement pagination for large result sets",
240
+ "Optimize database queries with proper indexing",
241
+ "Consider adding a GraphQL DataLoader for batching"
242
+ ];
243
+ }
244
+ if (anomaly.metric === "error-rate") {
245
+ return [
246
+ "Add input validation at the contract level",
247
+ "Implement retry policy with exponential backoff",
248
+ "Add circuit breaker for external dependencies",
249
+ "Enhance error logging for better debugging"
250
+ ];
251
+ }
252
+ return [
253
+ "Review resource allocation and scaling policies",
254
+ "Check for upstream routing or load balancer issues",
255
+ "Validate feature flag configurations",
256
+ "Monitor dependency health metrics"
257
+ ];
258
+ }
259
+
260
+ // src/lib/runtime-context.tsx
261
+ import { createContext, useContext } from "react";
262
+ "use client";
263
+ var TemplateRuntimeContext = createContext(null);
264
+ function useTemplateRuntime() {
265
+ const context = useContext(TemplateRuntimeContext);
266
+ if (!context) {
267
+ throw new Error("useTemplateRuntime must be used within a TemplateRuntimeProvider");
268
+ }
269
+ return context;
270
+ }
271
+
272
+ // src/hooks/useBehaviorTracking.ts
273
+ import { useCallback as useCallback2, useEffect as useEffect2, useMemo as useMemo2, useRef as useRef2, useState as useState2 } from "react";
274
+ "use client";
275
+ var BEHAVIOR_STORAGE_KEY = "contractspec-behavior-data";
276
+ var ALL_FEATURES = [
277
+ "playground",
278
+ "specs",
279
+ "builder",
280
+ "markdown",
281
+ "evolution",
282
+ "canvas_add",
283
+ "canvas_delete",
284
+ "spec_save",
285
+ "spec_validate",
286
+ "ai_suggestions"
287
+ ];
288
+ function useBehaviorTracking(templateId) {
289
+ const [events, setEvents] = useState2([]);
290
+ const sessionStartRef = useRef2(new Date);
291
+ const [eventCount, setEventCount] = useState2(0);
292
+ useEffect2(() => {
293
+ try {
294
+ const stored = localStorage.getItem(BEHAVIOR_STORAGE_KEY);
295
+ if (stored) {
296
+ const data = JSON.parse(stored);
297
+ setEvents(data.events.map((e) => ({
298
+ ...e,
299
+ timestamp: new Date(e.timestamp)
300
+ })));
301
+ sessionStartRef.current = new Date(data.sessionStart);
302
+ }
303
+ } catch {}
304
+ }, []);
305
+ useEffect2(() => {
306
+ if (events.length > 0) {
307
+ try {
308
+ localStorage.setItem(BEHAVIOR_STORAGE_KEY, JSON.stringify({
309
+ events: events.map((e) => ({
310
+ ...e,
311
+ timestamp: e.timestamp.toISOString()
312
+ })),
313
+ sessionStart: sessionStartRef.current.toISOString()
314
+ }));
315
+ } catch {}
316
+ }
317
+ }, [events]);
318
+ const trackEvent = useCallback2((type, metadata) => {
319
+ const event = {
320
+ type,
321
+ timestamp: new Date,
322
+ templateId,
323
+ metadata
324
+ };
325
+ setEvents((prev) => [...prev, event]);
326
+ setEventCount((prev) => prev + 1);
327
+ }, [templateId]);
328
+ const getEventsByType = useCallback2((type) => {
329
+ return events.filter((e) => e.type === type);
330
+ }, [events]);
331
+ const getSummary = useCallback2(() => {
332
+ const now = new Date;
333
+ const sessionDuration = now.getTime() - sessionStartRef.current.getTime();
334
+ const templateCounts = new Map;
335
+ for (const event of events) {
336
+ const count = templateCounts.get(event.templateId) ?? 0;
337
+ templateCounts.set(event.templateId, count + 1);
338
+ }
339
+ const mostUsedTemplates = Array.from(templateCounts.entries()).map(([templateId2, count]) => ({ templateId: templateId2, count })).sort((a, b) => b.count - a.count).slice(0, 3);
340
+ const modeCounts = new Map;
341
+ for (const event of events) {
342
+ if (event.type === "mode_change" && event.metadata?.mode) {
343
+ const mode = event.metadata.mode;
344
+ const count = modeCounts.get(mode) ?? 0;
345
+ modeCounts.set(mode, count + 1);
346
+ }
347
+ }
348
+ const mostUsedModes = Array.from(modeCounts.entries()).map(([mode, count]) => ({ mode, count })).sort((a, b) => b.count - a.count);
349
+ const featuresUsed = new Set;
350
+ for (const event of events) {
351
+ if (event.type === "mode_change" && event.metadata?.mode) {
352
+ featuresUsed.add(event.metadata.mode);
353
+ }
354
+ if (event.type === "feature_usage" && event.metadata?.feature) {
355
+ featuresUsed.add(event.metadata.feature);
356
+ }
357
+ if (event.type === "canvas_interaction") {
358
+ const action = event.metadata?.action;
359
+ if (action === "add")
360
+ featuresUsed.add("canvas_add");
361
+ if (action === "delete")
362
+ featuresUsed.add("canvas_delete");
363
+ }
364
+ if (event.type === "spec_edit") {
365
+ const action = event.metadata?.action;
366
+ if (action === "save")
367
+ featuresUsed.add("spec_save");
368
+ if (action === "validate")
369
+ featuresUsed.add("spec_validate");
370
+ }
371
+ }
372
+ const unusedFeatures = ALL_FEATURES.filter((f) => !featuresUsed.has(f));
373
+ const errorCount = events.filter((e) => e.type === "error").length;
374
+ const recommendations = generateRecommendations(Array.from(featuresUsed), unusedFeatures, mostUsedModes, events.length);
375
+ return {
376
+ totalEvents: events.length,
377
+ sessionDuration,
378
+ mostUsedTemplates,
379
+ mostUsedModes,
380
+ featuresUsed: Array.from(featuresUsed),
381
+ unusedFeatures,
382
+ errorCount,
383
+ recommendations
384
+ };
385
+ }, [events]);
386
+ const clear = useCallback2(() => {
387
+ setEvents([]);
388
+ setEventCount(0);
389
+ sessionStartRef.current = new Date;
390
+ localStorage.removeItem(BEHAVIOR_STORAGE_KEY);
391
+ }, []);
392
+ return useMemo2(() => ({
393
+ trackEvent,
394
+ getSummary,
395
+ getEventsByType,
396
+ eventCount,
397
+ sessionStart: sessionStartRef.current,
398
+ clear
399
+ }), [trackEvent, getSummary, getEventsByType, eventCount, clear]);
400
+ }
401
+ function generateRecommendations(featuresUsed, unusedFeatures, mostUsedModes, totalEvents) {
402
+ const recommendations = [];
403
+ if (unusedFeatures.includes("evolution")) {
404
+ recommendations.push("Try the AI Evolution mode to get automated improvement suggestions");
405
+ }
406
+ if (unusedFeatures.includes("markdown")) {
407
+ recommendations.push("Use Markdown preview to see documentation for your specs");
408
+ }
409
+ if (unusedFeatures.includes("builder")) {
410
+ recommendations.push("Explore the Visual Builder to design your UI components");
411
+ }
412
+ if (!featuresUsed.includes("spec_validate") && featuresUsed.includes("specs")) {
413
+ recommendations.push("Don't forget to validate your specs before saving");
414
+ }
415
+ if (featuresUsed.includes("evolution") && !featuresUsed.includes("ai_suggestions")) {
416
+ recommendations.push("Generate AI suggestions to get actionable improvement recommendations");
417
+ }
418
+ if (totalEvents > 50) {
419
+ recommendations.push("Great engagement! Consider saving your work regularly");
420
+ }
421
+ if (mostUsedModes.length === 1) {
422
+ recommendations.push("Try different modes to explore all sandbox capabilities");
423
+ }
424
+ return recommendations;
425
+ }
426
+
427
+ // src/utils/generateSpecFromTemplate.ts
428
+ function generateSpecFromTemplate(template) {
429
+ const templateId = template?.id ?? "unknown";
430
+ if (!template) {
431
+ return generateDefaultSpec(templateId);
432
+ }
433
+ switch (templateId) {
434
+ case "crm-pipeline":
435
+ return generateCrmPipelineSpec(template.schema.contracts);
436
+ case "saas-boilerplate":
437
+ return generateSaasBoilerplateSpec(template.schema.contracts);
438
+ case "agent-console":
439
+ return generateAgentConsoleSpec(template.schema.contracts);
440
+ case "todos-app":
441
+ return generateTodosSpec(template.schema.contracts);
442
+ case "messaging-app":
443
+ return generateMessagingSpec(template.schema.contracts);
444
+ case "recipe-app-i18n":
445
+ return generateRecipeSpec(template.schema.contracts);
446
+ default:
447
+ return generateDefaultSpec(templateId);
448
+ }
449
+ }
450
+ function generateCrmPipelineSpec(contracts) {
451
+ return `// CRM Pipeline Specs
452
+ // Contracts: ${contracts.join(", ")}
453
+
454
+ contractSpec("crm.deal.updateStage.v1", {
455
+ goal: "Move a deal to a different pipeline stage",
456
+ transport: { gql: { mutation: "updateDealStage" } },
457
+ io: {
458
+ input: {
459
+ dealId: "string",
460
+ stageId: "string",
461
+ notes: "string?"
462
+ },
463
+ output: {
464
+ deal: {
465
+ id: "string",
466
+ stage: "string",
467
+ probability: "number",
468
+ value: "number"
469
+ }
470
+ }
471
+ },
472
+ events: ["deal.stage.changed"],
473
+ policy: { auth: "user", rbac: "org:sales" }
474
+ });
475
+
476
+ contractSpec("crm.deal.create.v1", {
477
+ goal: "Create a new deal in the pipeline",
478
+ transport: { gql: { mutation: "createDeal" } },
479
+ io: {
480
+ input: {
481
+ title: "string",
482
+ value: "number",
483
+ contactId: "string",
484
+ stageId: "string",
485
+ ownerId: "string?"
486
+ },
487
+ output: {
488
+ deal: {
489
+ id: "string",
490
+ title: "string",
491
+ value: "number",
492
+ stage: "string",
493
+ createdAt: "ISO8601"
494
+ }
495
+ }
496
+ },
497
+ events: ["deal.created"]
498
+ });
499
+
500
+ contractSpec("crm.contact.list.v1", {
501
+ goal: "List contacts with filtering and pagination",
502
+ transport: { gql: { query: "listContacts" } },
503
+ io: {
504
+ input: {
505
+ filter: {
506
+ search: "string?",
507
+ companyId: "string?",
508
+ tags: "string[]?"
509
+ },
510
+ pagination: {
511
+ page: "number",
512
+ limit: "number"
513
+ }
514
+ },
515
+ output: {
516
+ contacts: "array<Contact>",
517
+ total: "number",
518
+ hasMore: "boolean"
519
+ }
520
+ }
521
+ });`;
522
+ }
523
+ function generateSaasBoilerplateSpec(contracts) {
524
+ return `// SaaS Boilerplate Specs
525
+ // Contracts: ${contracts.join(", ")}
526
+
527
+ contractSpec("saas.project.create.v1", {
528
+ goal: "Create a new project in an organization",
529
+ transport: { gql: { mutation: "createProject" } },
530
+ io: {
531
+ input: {
532
+ orgId: "string",
533
+ name: "string",
534
+ description: "string?"
535
+ },
536
+ output: {
537
+ project: {
538
+ id: "string",
539
+ name: "string",
540
+ description: "string?",
541
+ createdAt: "ISO8601"
542
+ }
543
+ }
544
+ },
545
+ policy: { auth: "user", rbac: "org:member" }
546
+ });
547
+
548
+ contractSpec("saas.billing.recordUsage.v1", {
549
+ goal: "Record usage for billing purposes",
550
+ transport: { gql: { mutation: "recordUsage" } },
551
+ io: {
552
+ input: {
553
+ orgId: "string",
554
+ metric: "enum<'api_calls'|'storage_gb'|'seats'>",
555
+ quantity: "number",
556
+ timestamp: "ISO8601?"
557
+ },
558
+ output: {
559
+ usage: {
560
+ id: "string",
561
+ metric: "string",
562
+ quantity: "number",
563
+ recordedAt: "ISO8601"
564
+ }
565
+ }
566
+ },
567
+ events: ["billing.usage.recorded"]
568
+ });
569
+
570
+ contractSpec("saas.settings.update.v1", {
571
+ goal: "Update organization or user settings",
572
+ transport: { gql: { mutation: "updateSettings" } },
573
+ io: {
574
+ input: {
575
+ scope: "enum<'org'|'user'>",
576
+ targetId: "string",
577
+ settings: "Record<string, unknown>"
578
+ },
579
+ output: {
580
+ settings: {
581
+ scope: "string",
582
+ values: "Record<string, unknown>",
583
+ updatedAt: "ISO8601"
584
+ }
585
+ }
586
+ },
587
+ events: ["settings.updated"]
588
+ });`;
589
+ }
590
+ function generateAgentConsoleSpec(contracts) {
591
+ return `// Agent Console Specs
592
+ // Contracts: ${contracts.join(", ")}
593
+
594
+ contractSpec("agent.run.execute.v1", {
595
+ goal: "Execute an agent run with specified tools",
596
+ transport: { gql: { mutation: "executeAgentRun" } },
597
+ io: {
598
+ input: {
599
+ agentId: "string",
600
+ input: "string",
601
+ tools: "string[]?",
602
+ maxSteps: "number?"
603
+ },
604
+ output: {
605
+ runId: "string",
606
+ status: "enum<'running'|'completed'|'failed'>",
607
+ steps: "number"
608
+ }
609
+ },
610
+ events: ["run.started", "run.completed", "run.failed"]
611
+ });
612
+
613
+ contractSpec("agent.tool.create.v1", {
614
+ goal: "Register a new tool in the tool registry",
615
+ transport: { gql: { mutation: "createTool" } },
616
+ io: {
617
+ input: {
618
+ name: "string",
619
+ description: "string",
620
+ category: "enum<'code'|'data'|'api'|'file'|'custom'>",
621
+ schema: "JSONSchema",
622
+ handler: "string"
623
+ },
624
+ output: {
625
+ tool: {
626
+ id: "string",
627
+ name: "string",
628
+ category: "string",
629
+ createdAt: "ISO8601"
630
+ }
631
+ }
632
+ },
633
+ events: ["tool.created"]
634
+ });
635
+
636
+ contractSpec("agent.agent.create.v1", {
637
+ goal: "Create a new AI agent configuration",
638
+ transport: { gql: { mutation: "createAgent" } },
639
+ io: {
640
+ input: {
641
+ name: "string",
642
+ description: "string",
643
+ model: "string",
644
+ systemPrompt: "string?",
645
+ tools: "string[]?"
646
+ },
647
+ output: {
648
+ agent: {
649
+ id: "string",
650
+ name: "string",
651
+ model: "string",
652
+ toolCount: "number",
653
+ createdAt: "ISO8601"
654
+ }
655
+ }
656
+ },
657
+ events: ["agent.created"]
658
+ });`;
659
+ }
660
+ function generateTodosSpec(contracts) {
661
+ return `// To-dos App Specs
662
+ // Contracts: ${contracts.join(", ")}
663
+
664
+ contractSpec("tasks.board.v1", {
665
+ goal: "Assign and approve craft work",
666
+ transport: { gql: { field: "tasksBoard" } },
667
+ io: {
668
+ input: {
669
+ tenantId: "string",
670
+ assignee: "string?",
671
+ status: "enum<'pending'|'in_progress'|'completed'>?"
672
+ },
673
+ output: {
674
+ tasks: "array<Task>",
675
+ summary: {
676
+ total: "number",
677
+ completed: "number",
678
+ overdue: "number"
679
+ }
680
+ }
681
+ }
682
+ });
683
+
684
+ contractSpec("tasks.create.v1", {
685
+ goal: "Create a new task",
686
+ transport: { gql: { mutation: "createTask" } },
687
+ io: {
688
+ input: {
689
+ title: "string",
690
+ description: "string?",
691
+ assignee: "string?",
692
+ priority: "enum<'low'|'medium'|'high'>",
693
+ dueDate: "ISO8601?"
694
+ },
695
+ output: {
696
+ task: {
697
+ id: "string",
698
+ title: "string",
699
+ status: "string",
700
+ createdAt: "ISO8601"
701
+ }
702
+ }
703
+ },
704
+ events: ["task.created"]
705
+ });
706
+
707
+ contractSpec("tasks.complete.v1", {
708
+ goal: "Mark a task as completed",
709
+ transport: { gql: { mutation: "completeTask" } },
710
+ io: {
711
+ input: { taskId: "string" },
712
+ output: {
713
+ task: {
714
+ id: "string",
715
+ status: "string",
716
+ completedAt: "ISO8601"
717
+ }
718
+ }
719
+ },
720
+ events: ["task.completed"]
721
+ });`;
722
+ }
723
+ function generateMessagingSpec(contracts) {
724
+ return `// Messaging App Specs
725
+ // Contracts: ${contracts.join(", ")}
726
+
727
+ contractSpec("messaging.send.v1", {
728
+ goal: "Deliver intent-rich updates",
729
+ io: {
730
+ input: {
731
+ conversationId: "string",
732
+ body: "richtext",
733
+ attachments: "array<Attachment>?"
734
+ },
735
+ output: {
736
+ messageId: "string",
737
+ deliveredAt: "ISO8601"
738
+ }
739
+ },
740
+ events: ["message.sent", "message.delivered"]
741
+ });
742
+
743
+ contractSpec("messaging.conversation.create.v1", {
744
+ goal: "Start a new conversation",
745
+ transport: { gql: { mutation: "createConversation" } },
746
+ io: {
747
+ input: {
748
+ participants: "string[]",
749
+ title: "string?",
750
+ type: "enum<'direct'|'group'>"
751
+ },
752
+ output: {
753
+ conversation: {
754
+ id: "string",
755
+ title: "string?",
756
+ participantCount: "number",
757
+ createdAt: "ISO8601"
758
+ }
759
+ }
760
+ },
761
+ events: ["conversation.created"]
762
+ });
763
+
764
+ contractSpec("messaging.read.v1", {
765
+ goal: "Mark messages as read",
766
+ transport: { gql: { mutation: "markRead" } },
767
+ io: {
768
+ input: {
769
+ conversationId: "string",
770
+ messageIds: "string[]"
771
+ },
772
+ output: {
773
+ readCount: "number",
774
+ readAt: "ISO8601"
775
+ }
776
+ },
777
+ events: ["message.read"]
778
+ });`;
779
+ }
780
+ function generateRecipeSpec(contracts) {
781
+ return `// Recipe App (i18n) Specs
782
+ // Contracts: ${contracts.join(", ")}
783
+
784
+ contractSpec("recipes.lookup.v1", {
785
+ goal: "Serve bilingual rituals",
786
+ io: {
787
+ input: {
788
+ locale: "enum<'EN'|'FR'>",
789
+ slug: "string"
790
+ },
791
+ output: {
792
+ title: "string",
793
+ content: "markdown",
794
+ ingredients: "array<Ingredient>",
795
+ instructions: "array<Instruction>"
796
+ }
797
+ }
798
+ });
799
+
800
+ contractSpec("recipes.list.v1", {
801
+ goal: "Browse recipes with filtering",
802
+ transport: { gql: { query: "listRecipes" } },
803
+ io: {
804
+ input: {
805
+ locale: "enum<'EN'|'FR'>",
806
+ category: "string?",
807
+ search: "string?",
808
+ favorites: "boolean?"
809
+ },
810
+ output: {
811
+ recipes: "array<RecipeSummary>",
812
+ categories: "array<Category>",
813
+ total: "number"
814
+ }
815
+ }
816
+ });
817
+
818
+ contractSpec("recipes.favorite.toggle.v1", {
819
+ goal: "Toggle recipe favorite status",
820
+ transport: { gql: { mutation: "toggleFavorite" } },
821
+ io: {
822
+ input: { recipeId: "string" },
823
+ output: {
824
+ isFavorite: "boolean",
825
+ totalFavorites: "number"
826
+ }
827
+ },
828
+ events: ["recipe.favorited", "recipe.unfavorited"]
829
+ });`;
830
+ }
831
+ function generateDefaultSpec(templateId) {
832
+ return `// ${templateId} Specs
833
+
834
+ contractSpec("${templateId}.main.v1", {
835
+ goal: "Main operation for ${templateId}",
836
+ transport: { gql: { query: "main" } },
837
+ io: {
838
+ input: {
839
+ id: "string"
840
+ },
841
+ output: {
842
+ result: "unknown"
843
+ }
844
+ }
845
+ });`;
846
+ }
847
+
848
+ // src/hooks/useSpecContent.ts
849
+ import { useCallback as useCallback3, useEffect as useEffect3, useState as useState3 } from "react";
850
+ "use client";
851
+ var SPEC_STORAGE_KEY = "contractspec-spec-content";
852
+ function useSpecContent(templateId) {
853
+ const { template } = useTemplateRuntime();
854
+ const [content, setContentState] = useState3("");
855
+ const [savedContent, setSavedContent] = useState3("");
856
+ const [loading, setLoading] = useState3(true);
857
+ const [validation, setValidation] = useState3(null);
858
+ const [lastSaved, setLastSaved] = useState3(null);
859
+ useEffect3(() => {
860
+ setLoading(true);
861
+ try {
862
+ const stored = localStorage.getItem(`${SPEC_STORAGE_KEY}-${templateId}`);
863
+ if (stored) {
864
+ const parsed = JSON.parse(stored);
865
+ if (parsed.content) {
866
+ setContentState(parsed.content);
867
+ setSavedContent(parsed.content);
868
+ setLastSaved(parsed.savedAt);
869
+ } else {
870
+ const generated = generateSpecFromTemplate(template);
871
+ setContentState(generated);
872
+ setSavedContent(generated);
873
+ }
874
+ } else {
875
+ const generated = generateSpecFromTemplate(template);
876
+ setContentState(generated);
877
+ setSavedContent(generated);
878
+ }
879
+ } catch {
880
+ const generated = generateSpecFromTemplate(template);
881
+ setContentState(generated);
882
+ setSavedContent(generated);
883
+ }
884
+ setLoading(false);
885
+ }, [templateId]);
886
+ const setContent = useCallback3((newContent) => {
887
+ setContentState(newContent);
888
+ setValidation(null);
889
+ }, []);
890
+ const save = useCallback3(() => {
891
+ try {
892
+ const savedAt = new Date().toISOString();
893
+ localStorage.setItem(`${SPEC_STORAGE_KEY}-${templateId}`, JSON.stringify({
894
+ content,
895
+ savedAt
896
+ }));
897
+ setSavedContent(content);
898
+ setLastSaved(savedAt);
899
+ } catch {}
900
+ }, [content, templateId]);
901
+ const validate = useCallback3(() => {
902
+ const errors = [];
903
+ const lines = content.split(`
904
+ `);
905
+ if (!content.includes("contractSpec(")) {
906
+ errors.push({
907
+ line: 1,
908
+ message: "Spec must contain a contractSpec() definition",
909
+ severity: "error"
910
+ });
911
+ }
912
+ if (!content.includes("goal:")) {
913
+ errors.push({
914
+ line: 1,
915
+ message: "Spec should have a goal field",
916
+ severity: "warning"
917
+ });
918
+ }
919
+ if (!content.includes("io:")) {
920
+ errors.push({
921
+ line: 1,
922
+ message: "Spec should define io (input/output)",
923
+ severity: "warning"
924
+ });
925
+ }
926
+ const openBraces = (content.match(/{/g) ?? []).length;
927
+ const closeBraces = (content.match(/}/g) ?? []).length;
928
+ if (openBraces !== closeBraces) {
929
+ errors.push({
930
+ line: lines.length,
931
+ message: `Unbalanced braces: ${openBraces} opening, ${closeBraces} closing`,
932
+ severity: "error"
933
+ });
934
+ }
935
+ const openParens = (content.match(/\(/g) ?? []).length;
936
+ const closeParens = (content.match(/\)/g) ?? []).length;
937
+ if (openParens !== closeParens) {
938
+ errors.push({
939
+ line: lines.length,
940
+ message: `Unbalanced parentheses: ${openParens} opening, ${closeParens} closing`,
941
+ severity: "error"
942
+ });
943
+ }
944
+ lines.forEach((line, index) => {
945
+ const singleQuotes = (line.match(/'/g) ?? []).length;
946
+ const doubleQuotes = (line.match(/"/g) ?? []).length;
947
+ if (singleQuotes % 2 !== 0) {
948
+ errors.push({
949
+ line: index + 1,
950
+ message: "Unclosed single quote",
951
+ severity: "error"
952
+ });
953
+ }
954
+ if (doubleQuotes % 2 !== 0) {
955
+ errors.push({
956
+ line: index + 1,
957
+ message: "Unclosed double quote",
958
+ severity: "error"
959
+ });
960
+ }
961
+ });
962
+ const result = {
963
+ valid: errors.filter((e) => e.severity === "error").length === 0,
964
+ errors
965
+ };
966
+ setValidation(result);
967
+ return result;
968
+ }, [content]);
969
+ const reset = useCallback3(() => {
970
+ const generated = generateSpecFromTemplate(template);
971
+ setContentState(generated);
972
+ setSavedContent(generated);
973
+ setValidation(null);
974
+ setLastSaved(null);
975
+ try {
976
+ localStorage.removeItem(`${SPEC_STORAGE_KEY}-${templateId}`);
977
+ } catch {}
978
+ }, [templateId]);
979
+ return {
980
+ content,
981
+ loading,
982
+ isDirty: content !== savedContent,
983
+ validation,
984
+ setContent,
985
+ save,
986
+ validate,
987
+ reset,
988
+ lastSaved
989
+ };
990
+ }
991
+
992
+ // src/hooks/useWorkflowComposer.ts
993
+ import { useCallback as useCallback4, useEffect as useEffect4, useMemo as useMemo3, useState as useState4 } from "react";
994
+ "use client";
995
+ function useWorkflowComposer(templateId) {
996
+ const [selectedWorkflow, setSelectedWorkflow] = useState4(null);
997
+ const [extensions, setExtensions] = useState4([]);
998
+ const [loading, _setLoading] = useState4(false);
999
+ const [error, _setError] = useState4(null);
1000
+ const baseWorkflows = useMemo3(() => getTemplateWorkflows(templateId), [templateId]);
1001
+ useEffect4(() => {
1002
+ const firstWorkflow = baseWorkflows[0];
1003
+ if (baseWorkflows.length > 0 && !selectedWorkflow && firstWorkflow) {
1004
+ setSelectedWorkflow(firstWorkflow.meta.key);
1005
+ }
1006
+ }, [baseWorkflows, selectedWorkflow]);
1007
+ const currentBase = useMemo3(() => {
1008
+ return baseWorkflows.find((w) => w.meta.key === selectedWorkflow) ?? null;
1009
+ }, [baseWorkflows, selectedWorkflow]);
1010
+ const compose = useCallback4((scope) => {
1011
+ if (!currentBase)
1012
+ return null;
1013
+ const applicableExtensions = extensions.filter((ext) => ext.workflow === currentBase.meta.key).filter((ext) => matchesScope(ext, scope)).sort((a, b) => (a.priority ?? 0) - (b.priority ?? 0));
1014
+ if (applicableExtensions.length === 0) {
1015
+ return currentBase;
1016
+ }
1017
+ let composedWorkflow = { ...currentBase, steps: [...currentBase.steps] };
1018
+ for (const extension of applicableExtensions) {
1019
+ composedWorkflow = applyExtension(composedWorkflow, extension);
1020
+ }
1021
+ return composedWorkflow;
1022
+ }, [currentBase, extensions]);
1023
+ const workflow = useMemo3(() => compose(), [compose]);
1024
+ const selectWorkflow = useCallback4((workflowName) => {
1025
+ setSelectedWorkflow(workflowName);
1026
+ }, []);
1027
+ const addExtension = useCallback4((extension) => {
1028
+ setExtensions((prev) => [...prev, extension]);
1029
+ }, []);
1030
+ const removeExtension = useCallback4((workflowName, index) => {
1031
+ setExtensions((prev) => {
1032
+ const forWorkflow = prev.filter((e) => e.workflow === workflowName);
1033
+ const others = prev.filter((e) => e.workflow !== workflowName);
1034
+ forWorkflow.splice(index, 1);
1035
+ return [...others, ...forWorkflow];
1036
+ });
1037
+ }, []);
1038
+ const generateSpecCode = useCallback4(() => {
1039
+ const composed = workflow;
1040
+ if (!composed) {
1041
+ return "// No workflow selected";
1042
+ }
1043
+ const stepsCode = composed.steps.map((step) => ` {
1044
+ id: '${step.id}',
1045
+ name: '${step.name}',
1046
+ type: '${step.type}',${step.description ? `
1047
+ description: '${step.description}',` : ""}${step.next ? `
1048
+ next: ${JSON.stringify(step.next)},` : ""}${step.condition ? `
1049
+ condition: '${step.condition}',` : ""}${step.timeout ? `
1050
+ timeout: ${step.timeout},` : ""}${step.retries ? `
1051
+ retries: ${step.retries},` : ""}${step.onError ? `
1052
+ onError: '${step.onError}',` : ""}
1053
+ }`).join(`,
1054
+ `);
1055
+ const extensionsCode = extensions.length > 0 ? `
1056
+
1057
+ // Extensions applied:
1058
+ ${extensions.map((ext) => `// - ${ext.workflow} (priority: ${ext.priority ?? 0})${ext.customSteps?.length ? ` +${ext.customSteps.length} steps` : ""}${ext.hiddenSteps?.length ? ` -${ext.hiddenSteps.length} hidden` : ""}`).join(`
1059
+ `)}` : "";
1060
+ return `// Workflow Spec: ${composed.meta.key} v${composed.meta.version}
1061
+ // Generated from ${templateId} template
1062
+ ${extensionsCode}
1063
+
1064
+ import { workflowSpec } from '@contractspec/lib.contracts/workflow';
1065
+
1066
+ export const ${toCamelCase(composed.meta.key)}Workflow = workflowSpec({
1067
+ meta: {
1068
+ key: '${composed.meta.key}',
1069
+ version: ${composed.meta.version},${composed.meta.description ? `
1070
+ description: '${composed.meta.description}',` : ""}
1071
+ },
1072
+ start: '${composed.start}',
1073
+ steps: [
1074
+ ${stepsCode}
1075
+ ],${composed.context ? `
1076
+ context: ${JSON.stringify(composed.context, null, 2)},` : ""}
1077
+ });
1078
+ `;
1079
+ }, [workflow, extensions, templateId]);
1080
+ return {
1081
+ workflow,
1082
+ baseWorkflows,
1083
+ extensions,
1084
+ selectWorkflow,
1085
+ addExtension,
1086
+ removeExtension,
1087
+ compose,
1088
+ generateSpecCode,
1089
+ loading,
1090
+ error
1091
+ };
1092
+ }
1093
+ function matchesScope(extension, scope) {
1094
+ if (!scope)
1095
+ return true;
1096
+ if (extension.tenantId && extension.tenantId !== scope.tenantId) {
1097
+ return false;
1098
+ }
1099
+ if (extension.role && extension.role !== scope.role) {
1100
+ return false;
1101
+ }
1102
+ if (extension.device && extension.device !== scope.device) {
1103
+ return false;
1104
+ }
1105
+ return true;
1106
+ }
1107
+ function applyExtension(workflow, extension) {
1108
+ let steps = [...workflow.steps];
1109
+ if (extension.hiddenSteps) {
1110
+ steps = steps.filter((s) => !extension.hiddenSteps?.includes(s.id));
1111
+ }
1112
+ if (extension.customSteps) {
1113
+ for (const injection of extension.customSteps) {
1114
+ const stepToInject = {
1115
+ ...injection.inject,
1116
+ id: injection.id ?? injection.inject.id
1117
+ };
1118
+ if (injection.after) {
1119
+ const afterIndex = steps.findIndex((s) => s.id === injection.after);
1120
+ if (afterIndex !== -1) {
1121
+ steps.splice(afterIndex + 1, 0, stepToInject);
1122
+ }
1123
+ } else if (injection.before) {
1124
+ const beforeIndex = steps.findIndex((s) => s.id === injection.before);
1125
+ if (beforeIndex !== -1) {
1126
+ steps.splice(beforeIndex, 0, stepToInject);
1127
+ }
1128
+ } else {
1129
+ steps.push(stepToInject);
1130
+ }
1131
+ }
1132
+ }
1133
+ return { ...workflow, steps };
1134
+ }
1135
+ function toCamelCase(str) {
1136
+ return str.replace(/[^a-zA-Z0-9]+(.)/g, (_, c) => c.toUpperCase()).replace(/^./, (c) => c.toLowerCase());
1137
+ }
1138
+ function getTemplateWorkflows(templateId) {
1139
+ const templateWorkflows = {
1140
+ "crm-pipeline": [
1141
+ {
1142
+ meta: {
1143
+ key: "deal.qualification",
1144
+ version: "1.0.0",
1145
+ description: "Deal qualification workflow"
1146
+ },
1147
+ start: "lead-received",
1148
+ steps: [
1149
+ {
1150
+ id: "lead-received",
1151
+ name: "Lead Received",
1152
+ type: "action",
1153
+ description: "New lead enters the pipeline",
1154
+ next: "qualify-lead"
1155
+ },
1156
+ {
1157
+ id: "qualify-lead",
1158
+ name: "Qualify Lead",
1159
+ type: "decision",
1160
+ description: "Determine if lead meets qualification criteria",
1161
+ next: ["qualified", "disqualified"],
1162
+ condition: "lead.score >= threshold"
1163
+ },
1164
+ {
1165
+ id: "qualified",
1166
+ name: "Lead Qualified",
1167
+ type: "action",
1168
+ next: "assign-rep"
1169
+ },
1170
+ {
1171
+ id: "disqualified",
1172
+ name: "Lead Disqualified",
1173
+ type: "end"
1174
+ },
1175
+ {
1176
+ id: "assign-rep",
1177
+ name: "Assign Sales Rep",
1178
+ type: "action",
1179
+ next: "complete"
1180
+ },
1181
+ {
1182
+ id: "complete",
1183
+ name: "Workflow Complete",
1184
+ type: "end"
1185
+ }
1186
+ ]
1187
+ },
1188
+ {
1189
+ meta: {
1190
+ key: "deal.closing",
1191
+ version: "1.0.0",
1192
+ description: "Deal closing workflow"
1193
+ },
1194
+ start: "proposal-sent",
1195
+ steps: [
1196
+ {
1197
+ id: "proposal-sent",
1198
+ name: "Proposal Sent",
1199
+ type: "action",
1200
+ next: "wait-response"
1201
+ },
1202
+ {
1203
+ id: "wait-response",
1204
+ name: "Wait for Response",
1205
+ type: "wait",
1206
+ timeout: 604800000,
1207
+ next: "negotiate",
1208
+ onError: "follow-up"
1209
+ },
1210
+ {
1211
+ id: "follow-up",
1212
+ name: "Follow Up",
1213
+ type: "action",
1214
+ next: "wait-response",
1215
+ retries: 3
1216
+ },
1217
+ {
1218
+ id: "negotiate",
1219
+ name: "Negotiation",
1220
+ type: "action",
1221
+ next: "finalize"
1222
+ },
1223
+ {
1224
+ id: "finalize",
1225
+ name: "Finalize Deal",
1226
+ type: "decision",
1227
+ next: ["won", "lost"],
1228
+ condition: "deal.accepted"
1229
+ },
1230
+ {
1231
+ id: "won",
1232
+ name: "Deal Won",
1233
+ type: "end"
1234
+ },
1235
+ {
1236
+ id: "lost",
1237
+ name: "Deal Lost",
1238
+ type: "end"
1239
+ }
1240
+ ]
1241
+ }
1242
+ ],
1243
+ "saas-boilerplate": [
1244
+ {
1245
+ meta: {
1246
+ key: "user.onboarding",
1247
+ version: "1.0.0",
1248
+ description: "User onboarding workflow"
1249
+ },
1250
+ start: "signup",
1251
+ steps: [
1252
+ {
1253
+ id: "signup",
1254
+ name: "User Signup",
1255
+ type: "action",
1256
+ next: "verify-email"
1257
+ },
1258
+ {
1259
+ id: "verify-email",
1260
+ name: "Verify Email",
1261
+ type: "wait",
1262
+ timeout: 86400000,
1263
+ next: "profile-setup",
1264
+ onError: "resend-verification"
1265
+ },
1266
+ {
1267
+ id: "resend-verification",
1268
+ name: "Resend Verification",
1269
+ type: "action",
1270
+ next: "verify-email",
1271
+ retries: 2
1272
+ },
1273
+ {
1274
+ id: "profile-setup",
1275
+ name: "Setup Profile",
1276
+ type: "action",
1277
+ next: "onboarding-tour"
1278
+ },
1279
+ {
1280
+ id: "onboarding-tour",
1281
+ name: "Onboarding Tour",
1282
+ type: "action",
1283
+ next: "complete"
1284
+ },
1285
+ {
1286
+ id: "complete",
1287
+ name: "Onboarding Complete",
1288
+ type: "end"
1289
+ }
1290
+ ]
1291
+ }
1292
+ ],
1293
+ "agent-console": [
1294
+ {
1295
+ meta: {
1296
+ key: "agent.execution",
1297
+ version: "1.0.0",
1298
+ description: "Agent execution workflow"
1299
+ },
1300
+ start: "receive-task",
1301
+ steps: [
1302
+ {
1303
+ id: "receive-task",
1304
+ name: "Receive Task",
1305
+ type: "action",
1306
+ next: "plan-execution"
1307
+ },
1308
+ {
1309
+ id: "plan-execution",
1310
+ name: "Plan Execution",
1311
+ type: "action",
1312
+ next: "execute-steps"
1313
+ },
1314
+ {
1315
+ id: "execute-steps",
1316
+ name: "Execute Steps",
1317
+ type: "parallel",
1318
+ next: ["tool-call", "observe", "reason"]
1319
+ },
1320
+ {
1321
+ id: "tool-call",
1322
+ name: "Tool Call",
1323
+ type: "action",
1324
+ next: "evaluate"
1325
+ },
1326
+ {
1327
+ id: "observe",
1328
+ name: "Observe",
1329
+ type: "action",
1330
+ next: "evaluate"
1331
+ },
1332
+ {
1333
+ id: "reason",
1334
+ name: "Reason",
1335
+ type: "action",
1336
+ next: "evaluate"
1337
+ },
1338
+ {
1339
+ id: "evaluate",
1340
+ name: "Evaluate Result",
1341
+ type: "decision",
1342
+ condition: "task.isComplete",
1343
+ next: ["complete", "execute-steps"]
1344
+ },
1345
+ {
1346
+ id: "complete",
1347
+ name: "Task Complete",
1348
+ type: "end"
1349
+ }
1350
+ ]
1351
+ }
1352
+ ],
1353
+ "todos-app": [
1354
+ {
1355
+ meta: {
1356
+ key: "task.lifecycle",
1357
+ version: "1.0.0",
1358
+ description: "Task lifecycle workflow"
1359
+ },
1360
+ start: "created",
1361
+ steps: [
1362
+ {
1363
+ id: "created",
1364
+ name: "Task Created",
1365
+ type: "action",
1366
+ next: "in-progress"
1367
+ },
1368
+ {
1369
+ id: "in-progress",
1370
+ name: "In Progress",
1371
+ type: "action",
1372
+ next: "review"
1373
+ },
1374
+ {
1375
+ id: "review",
1376
+ name: "Review",
1377
+ type: "decision",
1378
+ condition: "task.approved",
1379
+ next: ["done", "in-progress"]
1380
+ },
1381
+ {
1382
+ id: "done",
1383
+ name: "Done",
1384
+ type: "end"
1385
+ }
1386
+ ]
1387
+ }
1388
+ ],
1389
+ "messaging-app": [
1390
+ {
1391
+ meta: {
1392
+ key: "message.delivery",
1393
+ version: "1.0.0",
1394
+ description: "Message delivery workflow"
1395
+ },
1396
+ start: "compose",
1397
+ steps: [
1398
+ {
1399
+ id: "compose",
1400
+ name: "Compose Message",
1401
+ type: "action",
1402
+ next: "send"
1403
+ },
1404
+ {
1405
+ id: "send",
1406
+ name: "Send Message",
1407
+ type: "action",
1408
+ next: "deliver"
1409
+ },
1410
+ {
1411
+ id: "deliver",
1412
+ name: "Deliver",
1413
+ type: "decision",
1414
+ condition: "recipient.online",
1415
+ next: ["delivered", "queue"]
1416
+ },
1417
+ {
1418
+ id: "queue",
1419
+ name: "Queue for Delivery",
1420
+ type: "wait",
1421
+ next: "deliver"
1422
+ },
1423
+ {
1424
+ id: "delivered",
1425
+ name: "Message Delivered",
1426
+ type: "action",
1427
+ next: "read"
1428
+ },
1429
+ {
1430
+ id: "read",
1431
+ name: "Message Read",
1432
+ type: "end"
1433
+ }
1434
+ ]
1435
+ }
1436
+ ],
1437
+ "recipe-app-i18n": [
1438
+ {
1439
+ meta: {
1440
+ key: "recipe.creation",
1441
+ version: "1.0.0",
1442
+ description: "Recipe creation workflow"
1443
+ },
1444
+ start: "draft",
1445
+ steps: [
1446
+ {
1447
+ id: "draft",
1448
+ name: "Draft Recipe",
1449
+ type: "action",
1450
+ next: "add-ingredients"
1451
+ },
1452
+ {
1453
+ id: "add-ingredients",
1454
+ name: "Add Ingredients",
1455
+ type: "action",
1456
+ next: "add-steps"
1457
+ },
1458
+ {
1459
+ id: "add-steps",
1460
+ name: "Add Steps",
1461
+ type: "action",
1462
+ next: "review"
1463
+ },
1464
+ {
1465
+ id: "review",
1466
+ name: "Review Recipe",
1467
+ type: "decision",
1468
+ condition: "recipe.isComplete",
1469
+ next: ["publish", "draft"]
1470
+ },
1471
+ {
1472
+ id: "publish",
1473
+ name: "Publish Recipe",
1474
+ type: "end"
1475
+ }
1476
+ ]
1477
+ }
1478
+ ]
1479
+ };
1480
+ return templateWorkflows[templateId] ?? [];
1481
+ }
1482
+
1483
+ // src/hooks/useRegistryTemplates.ts
1484
+ import { useQuery } from "@tanstack/react-query";
1485
+ function useRegistryTemplates() {
1486
+ return useQuery({
1487
+ queryKey: ["registryTemplates"],
1488
+ queryFn: async () => {
1489
+ const registryUrl = process.env.NEXT_PUBLIC_CONTRACTSPEC_REGISTRY_URL ?? "";
1490
+ if (!registryUrl)
1491
+ return [];
1492
+ const res = await fetch(`${registryUrl.replace(/\/$/, "")}/r/contractspec.json`, {
1493
+ method: "GET",
1494
+ headers: { Accept: "application/json" }
1495
+ });
1496
+ if (!res.ok)
1497
+ return [];
1498
+ const json = await res.json();
1499
+ const items = json.items ?? [];
1500
+ return items.filter((i) => i.type === "contractspec:template").map((i) => ({
1501
+ id: i.name,
1502
+ name: i.title ?? i.name,
1503
+ description: i.description,
1504
+ tags: i.meta?.tags ?? [],
1505
+ source: "registry",
1506
+ registryUrl
1507
+ }));
1508
+ }
1509
+ });
1510
+ }
1511
+ export {
1512
+ useWorkflowComposer,
1513
+ useSpecContent,
1514
+ useRegistryTemplates,
1515
+ useEvolution,
1516
+ useBehaviorTracking
1517
+ };