-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBlueprintValidator.php
More file actions
255 lines (216 loc) · 7.14 KB
/
BlueprintValidator.php
File metadata and controls
255 lines (216 loc) · 7.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
<?php
namespace NORP\PHP;
use NORP\PHP\DTOs\ValidationResult;
/**
* BlueprintValidator - NORP-001 and NORP-004 Reference Implementation
*
* Implements:
* - NORP-001: Pre-Execution Validation Pipeline (Structural Validation stage)
* - NORP-004: Cycle Detection (DFS algorithm O(V+E))
* - NORP-007: Cost Estimation
*
* @license MIT
* @copyright 2026 NeuraScope CONVERWAY
*/
class BlueprintValidator
{
/**
* Validate complete workflow
*
* @param array $workflow - Workflow definition with 'nodes' array
* @param callable|null $resourceValidator - Optional callback to validate resource existence
* @return ValidationResult
*/
public function validate(array $workflow, ?callable $resourceValidator = null): ValidationResult
{
$errors = [];
$warnings = [];
// 1. Structural validation
if (empty($workflow['nodes'])) {
$errors[] = 'At least one node required in workflow';
return new ValidationResult(false, $errors, $warnings);
}
// 2. Cycle detection (NORP-004)
if ($this->detectCycles($workflow['nodes'])) {
$errors[] = 'Cycle detected in execution graph';
}
// 3. Validate node dependencies
foreach ($workflow['nodes'] as $node) {
$nodeId = $node['id'] ?? 'unknown';
if (!empty($node['depends_on'])) {
foreach ($node['depends_on'] as $depId) {
if (!$this->nodeExists($workflow['nodes'], $depId)) {
$errors[] = "Node '{$nodeId}' depends on non-existent node '{$depId}'";
}
}
}
}
// 4. Validate resources (if validator provided)
if ($resourceValidator !== null) {
foreach ($workflow['nodes'] as $node) {
$resourceErrors = $resourceValidator($node);
$errors = array_merge($errors, $resourceErrors);
}
}
// 5. Estimate cost (NORP-007)
$estimatedCost = $this->estimateCost($workflow['nodes']);
if ($estimatedCost > 100) {
$warnings[] = "High estimated cost: \${$estimatedCost} (based on 1K executions/month)";
}
return new ValidationResult(
valid: empty($errors),
errors: $errors,
warnings: $warnings,
estimated_cost: $estimatedCost
);
}
/**
* Detect cycles in graph using DFS (NORP-004)
*
* Complexity: O(V + E)
*
* @param array $nodes
* @return bool - True if cycle detected
*/
private function detectCycles(array $nodes): bool
{
$graph = $this->buildGraph($nodes);
$visited = [];
$recStack = [];
foreach (array_keys($graph) as $nodeId) {
if ($this->isCyclicUtil($nodeId, $graph, $visited, $recStack)) {
return true;
}
}
return false;
}
/**
* DFS recursive cycle detection
*
* @param string $nodeId
* @param array $graph
* @param array $visited - Fully explored nodes
* @param array $recStack - Recursion stack (detects back-edge)
* @return bool
*/
private function isCyclicUtil(string $nodeId, array $graph, array &$visited, array &$recStack): bool
{
// Back-edge detected → CYCLE
if (isset($recStack[$nodeId])) {
return true;
}
// Already fully explored
if (isset($visited[$nodeId])) {
return false;
}
// Mark as visiting
$visited[$nodeId] = true;
$recStack[$nodeId] = true;
// Explore neighbors
foreach ($graph[$nodeId] ?? [] as $neighbor) {
if ($this->isCyclicUtil($neighbor, $graph, $visited, $recStack)) {
return true;
}
}
// Backtrack (remove from recursion stack)
unset($recStack[$nodeId]);
return false;
}
/**
* Build dependency graph
*
* @param array $nodes
* @return array - ['node_id' => ['dependent_node_1', 'dependent_node_2']]
*/
private function buildGraph(array $nodes): array
{
$graph = [];
// Initialize all nodes
foreach ($nodes as $node) {
$nodeId = $node['id'] ?? uniqid('node_');
$graph[$nodeId] = [];
}
// Add edges (inverted for DFS)
foreach ($nodes as $node) {
$nodeId = $node['id'] ?? uniqid('node_');
$dependencies = $node['depends_on'] ?? [];
foreach ($dependencies as $depId) {
if (!isset($graph[$depId])) {
$graph[$depId] = [];
}
$graph[$depId][] = $nodeId;
}
}
return $graph;
}
/**
* Check if node exists
*
* @param array $nodes
* @param string $nodeId
* @return bool
*/
private function nodeExists(array $nodes, string $nodeId): bool
{
foreach ($nodes as $node) {
if (($node['id'] ?? null) === $nodeId) {
return true;
}
}
return false;
}
/**
* Estimate workflow cost (NORP-007)
*
* @param array $nodes
* @return float - Estimated cost in USD
*/
private function estimateCost(array $nodes): float
{
$totalCost = 0;
$executionsPerMonth = 1000;
foreach ($nodes as $node) {
if (($node['type'] ?? null) === 'llm_call') {
$maxTokens = $node['config']['max_tokens'] ?? 1000;
$model = $node['config']['model'] ?? 'gpt-3.5-turbo';
$pricing = $this->getModelPricing($model);
// Estimate input tokens (average prompt)
$inputTokens = 500;
$costPerExecution =
($inputTokens / 1000 * $pricing['input']) +
($maxTokens / 1000 * $pricing['output']);
$totalCost += $costPerExecution * $executionsPerMonth;
}
}
return round($totalCost, 2);
}
/**
* Get model pricing (NORP-007)
*
* @param string $model
* @return array - ['input' => float, 'output' => float] ($/1K tokens)
*/
private function getModelPricing(string $model): array
{
$pricingMap = [
// Anthropic
'claude-3-5-sonnet' => ['input' => 0.003, 'output' => 0.015],
'claude-3-haiku' => ['input' => 0.00025, 'output' => 0.00125],
// OpenAI
'gpt-4-turbo' => ['input' => 0.010, 'output' => 0.030],
'gpt-3.5-turbo' => ['input' => 0.0005, 'output' => 0.0015],
// Mistral
'mistral-large' => ['input' => 0.004, 'output' => 0.012],
// Local (free)
'llama' => ['input' => 0.000, 'output' => 0.000],
];
// Partial match (e.g., "mistral-7b" matches "mistral")
foreach ($pricingMap as $modelKey => $pricing) {
if (str_contains(strtolower($model), strtolower($modelKey))) {
return $pricing;
}
}
// Default: average pricing
return ['input' => 0.010, 'output' => 0.030];
}
}