ggen-core 26.6.11

Core graph-aware code generation engine
Documentation
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
//! Guard: Forbidden output class constraints (H)
//!
//! Guards enforce μ ⊣ H, ensuring that certain classes of outputs
//! are forbidden during projection.

use regex::Regex;
use serde::{Deserialize, Serialize};
use std::path::Path;

/// Action to take when a guard is violated
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum GuardAction {
    /// Reject the output (fail the projection)
    Reject,
    /// Warn but continue
    Warn,
    /// Require explicit approval
    RequireApproval,
}

/// A guard violation detected during projection
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GuardViolation {
    /// Name of the guard that was violated
    pub guard_name: String,

    /// Path or content that violated the guard
    pub violating_content: String,

    /// Human-readable explanation
    pub message: String,

    /// Action that should be taken
    pub action: GuardAction,
}

/// Trait for implementing guards
pub trait Guard: Send + Sync {
    /// Get the guard name
    fn name(&self) -> &str;

    /// Get the guard action
    fn action(&self) -> GuardAction;

    /// Whether this guard is enabled
    fn is_enabled(&self) -> bool;

    /// Check if a path violates this guard
    ///
    /// # Arguments
    /// * `path` - Relative path to check
    ///
    /// # Returns
    /// * `Some(GuardViolation)` if the path violates the guard
    /// * `None` if the path is allowed
    fn check_path(&self, path: &Path) -> Option<GuardViolation>;

    /// Check if content violates this guard
    ///
    /// # Arguments
    /// * `content` - File content to check
    /// * `path` - Path for error messages
    ///
    /// # Returns
    /// * `Some(GuardViolation)` if the content violates the guard
    /// * `None` if the content is allowed
    fn check_content(&self, content: &str, path: &Path) -> Option<GuardViolation>;
}

/// Guard that restricts output paths
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PathGuard {
    /// Guard name
    pub name: String,

    /// Glob pattern for allowed paths
    pub allowed_pattern: String,

    /// Compiled regex (not serialized)
    #[serde(skip)]
    pub pattern_regex: Option<Regex>,

    /// Action when violated
    pub action: GuardAction,

    /// Whether enabled
    pub enabled: bool,
}

impl PathGuard {
    /// Create a new path guard
    pub fn new(name: impl Into<String>, allowed_pattern: impl Into<String>) -> Self {
        let pattern = allowed_pattern.into();
        let regex = Self::glob_to_regex(&pattern);
        Self {
            name: name.into(),
            allowed_pattern: pattern,
            pattern_regex: regex,
            action: GuardAction::Reject,
            enabled: true,
        }
    }

    /// Convert a glob pattern to a regex
    fn glob_to_regex(pattern: &str) -> Option<Regex> {
        let regex_str = pattern
            .replace("**", "DOUBLESTAR")
            .replace('*', "[^/]*")
            .replace("DOUBLESTAR", ".*")
            .replace('?', "[^/]");
        Regex::new(&format!("^{}$", regex_str)).ok()
    }

    /// Set the action
    pub fn with_action(mut self, action: GuardAction) -> Self {
        self.action = action;
        self
    }

    /// Set enabled state
    pub fn with_enabled(mut self, enabled: bool) -> Self {
        self.enabled = enabled;
        self
    }
}

impl Guard for PathGuard {
    fn name(&self) -> &str {
        &self.name
    }

    fn action(&self) -> GuardAction {
        self.action
    }

    fn is_enabled(&self) -> bool {
        self.enabled
    }

    fn check_path(&self, path: &Path) -> Option<GuardViolation> {
        if !self.enabled {
            return None;
        }

        let path_str = path.to_string_lossy();

        // Check if path matches allowed pattern
        let matches = if let Some(ref regex) = self.pattern_regex {
            regex.is_match(&path_str)
        } else {
            // Fallback to simple prefix matching
            path_str.starts_with(&self.allowed_pattern.replace("**", ""))
        };

        if matches {
            None
        } else {
            Some(GuardViolation {
                guard_name: self.name.clone(),
                violating_content: path_str.to_string(),
                message: format!(
                    "Path '{}' is not allowed. Must match pattern '{}'",
                    path_str, self.allowed_pattern
                ),
                action: self.action,
            })
        }
    }

    fn check_content(&self, _content: &str, _path: &Path) -> Option<GuardViolation> {
        None // PathGuard doesn't check content
    }
}

/// Guard that detects secrets in content
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecretGuard {
    /// Guard name
    pub name: String,

    /// Regex pattern to match secrets
    pub pattern: String,

    /// Compiled regex (not serialized)
    #[serde(skip)]
    pub pattern_regex: Option<Regex>,

    /// Action when violated
    pub action: GuardAction,

    /// Whether enabled
    pub enabled: bool,
}

impl SecretGuard {
    /// Create a new secret guard with default patterns
    pub fn new(name: impl Into<String>) -> Self {
        // Pattern to detect potential secrets (password=, secret=, api_key=, etc.)
        let pattern =
            r#"(?i)(password|secret|api[_-]?key|token|private[_-]?key)\s*[:=]\s*["'][^"']+["']"#;
        Self {
            name: name.into(),
            pattern: pattern.to_string(),
            pattern_regex: Regex::new(pattern).ok(),
            action: GuardAction::Reject,
            enabled: true,
        }
    }

    /// Create with a custom pattern
    pub fn with_pattern(mut self, pattern: impl Into<String>) -> Self {
        let p = pattern.into();
        self.pattern_regex = Regex::new(&p).ok();
        self.pattern = p;
        self
    }

    /// Set the action
    pub fn with_action(mut self, action: GuardAction) -> Self {
        self.action = action;
        self
    }

    /// Set enabled state
    pub fn with_enabled(mut self, enabled: bool) -> Self {
        self.enabled = enabled;
        self
    }
}

impl Guard for SecretGuard {
    fn name(&self) -> &str {
        &self.name
    }

    fn action(&self) -> GuardAction {
        self.action
    }

    fn is_enabled(&self) -> bool {
        self.enabled
    }

    fn check_path(&self, path: &Path) -> Option<GuardViolation> {
        if !self.enabled {
            return None;
        }

        let path_str = path.to_string_lossy();

        // Check for sensitive file names
        let sensitive_extensions = [".env", ".credentials", ".secret", ".pem", ".key"];
        for ext in sensitive_extensions {
            if path_str.ends_with(ext) {
                return Some(GuardViolation {
                    guard_name: self.name.clone(),
                    violating_content: path_str.to_string(),
                    message: format!("Cannot emit sensitive file type: '{}'", ext),
                    action: self.action,
                });
            }
        }

        None
    }

    fn check_content(&self, content: &str, path: &Path) -> Option<GuardViolation> {
        if !self.enabled {
            return None;
        }

        if let Some(ref regex) = self.pattern_regex {
            if let Some(m) = regex.find(content) {
                return Some(GuardViolation {
                    guard_name: self.name.clone(),
                    violating_content: m.as_str().to_string(),
                    message: format!(
                        "Potential secret detected in '{}': {}",
                        path.display(),
                        m.as_str()
                    ),
                    action: self.action,
                });
            }
        }

        None
    }
}

/// Guard that detects runtime model-serving dependencies
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelDependencyGuard {
    /// Guard name
    pub name: String,

    /// Regex pattern to match model dependencies
    pub pattern: String,

    /// Compiled regex (not serialized)
    #[serde(skip)]
    pub pattern_regex: Option<Regex>,

    /// Action when violated
    pub action: GuardAction,

    /// Whether enabled
    pub enabled: bool,
}

impl ModelDependencyGuard {
    /// Create a new model dependency guard
    pub fn new(name: impl Into<String>) -> Self {
        // Pattern to detect AI/ML serving frameworks
        let pattern = r"(?i)(tensorflow|onnxruntime|candle-core|tch-rs|pytorch|transformers|huggingface|llm-chain|burn|ort)";
        Self {
            name: name.into(),
            pattern: pattern.to_string(),
            pattern_regex: Regex::new(pattern).ok(),
            action: GuardAction::Reject,
            enabled: true,
        }
    }
}

impl Guard for ModelDependencyGuard {
    fn name(&self) -> &str {
        &self.name
    }

    fn action(&self) -> GuardAction {
        self.action
    }

    fn is_enabled(&self) -> bool {
        self.enabled
    }

    fn check_path(&self, _path: &Path) -> Option<GuardViolation> {
        None
    }

    fn check_content(&self, content: &str, path: &Path) -> Option<GuardViolation> {
        if !self.enabled {
            return None;
        }

        if let Some(ref regex) = self.pattern_regex {
            if let Some(m) = regex.find(content) {
                return Some(GuardViolation {
                    guard_name: self.name.clone(),
                    violating_content: m.as_str().to_string(),
                    message: format!(
                        "Runtime model-serving dependency detected in '{}': {}. Zero Dependency and Compile-Time AutoML doctrines require artifact-resident cognition via branchless deterministic const structures.",
                        path.display(),
                        m.as_str()
                    ),
                    action: self.action,
                });
            }
        }

        None
    }
}

/// Collection of guards to apply during projection
pub struct GuardSet {
    guards: Vec<Box<dyn Guard>>,
}

impl std::fmt::Debug for GuardSet {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("GuardSet")
            .field("guards_count", &self.guards.len())
            .finish()
    }
}

impl Default for GuardSet {
    fn default() -> Self {
        Self::new()
    }
}

impl Clone for GuardSet {
    /// Clone by recreating guards (guards are stateless)
    fn clone(&self) -> Self {
        // Since guards are stateless, we create a new default set
        // This preserves the configured guard behavior
        Self::default_v26()
    }
}

impl GuardSet {
    /// Create a new empty guard set
    pub fn new() -> Self {
        Self { guards: Vec::new() }
    }

    /// Add a guard to the set
    pub fn add_guard(&mut self, guard: impl Guard + 'static) {
        self.guards.push(Box::new(guard));
    }

    /// Check a path against all guards
    pub fn check_path(&self, path: &Path) -> Vec<GuardViolation> {
        self.guards
            .iter()
            .filter_map(|g| g.check_path(path))
            .collect()
    }

    /// Check content against all guards
    pub fn check_content(&self, content: &str, path: &Path) -> Vec<GuardViolation> {
        self.guards
            .iter()
            .filter_map(|g| g.check_content(content, path))
            .collect()
    }

    /// Check both path and content
    pub fn check(&self, path: &Path, content: &str) -> Vec<GuardViolation> {
        let mut violations = self.check_path(path);
        violations.extend(self.check_content(content, path));
        violations
    }

    /// Create a default guard set with standard v26_5_19 guards
    pub fn default_v26() -> Self {
        let mut set = Self::new();
        set.add_guard(PathGuard::new("path-guard", "ontology/**"));
        set.add_guard(SecretGuard::new("secret-guard"));
        set.add_guard(ModelDependencyGuard::new("model-dependency-guard"));
        set
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_path_guard_allowed() {
        let guard = PathGuard::new("test", "ontology/**");
        assert!(guard.check_path(Path::new("ontology/domain.ttl")).is_none());
    }

    #[test]
    fn test_path_guard_rejected() {
        let guard = PathGuard::new("test", "ontology/**");
        let violation = guard.check_path(Path::new("src/core.ttl"));
        assert!(violation.is_some());
        assert_eq!(violation.unwrap().guard_name, "test");
    }

    #[test]
    fn test_secret_guard_clean_content() {
        let guard = SecretGuard::new("secret-guard");
        let content = "fn main() { println!(\"hello\"); }";
        assert!(guard.check_content(content, Path::new("test.rs")).is_none());
    }

    #[test]
    fn test_secret_guard_detects_secret() {
        let guard = SecretGuard::new("secret-guard");
        let content = r#"let api_key = "sk-1234567890";"#;
        let violation = guard.check_content(content, Path::new("config.rs"));
        assert!(violation.is_some());
    }

    #[test]
    fn test_secret_guard_rejects_env_file() {
        let guard = SecretGuard::new("secret-guard");
        let violation = guard.check_path(Path::new(".env"));
        assert!(violation.is_some());
    }

    #[test]
    fn test_model_dependency_guard_clean() {
        let guard = ModelDependencyGuard::new("model");
        let content = "const A: u32 = 42;";
        assert!(guard.check_content(content, Path::new("main.rs")).is_none());
    }

    #[test]
    fn test_model_dependency_guard_detects_tensorflow() {
        let guard = ModelDependencyGuard::new("model");
        let content = "import tensorflow as tf";
        let violation = guard.check_content(content, Path::new("model.py"));
        assert!(violation.is_some());
        assert!(violation
            .unwrap()
            .message
            .contains("Zero Dependency and Compile-Time AutoML doctrines"));
    }

    #[test]
    fn test_guard_set() {
        let mut set = GuardSet::new();
        set.add_guard(PathGuard::new("path", "ontology/**"));
        set.add_guard(SecretGuard::new("secret"));

        // Should pass both guards
        let violations = set.check(
            Path::new("ontology/domain.ttl"),
            "@prefix ex: <http://example.org/> .",
        );
        assert!(violations.is_empty());

        // Should fail path guard
        let violations = set.check(
            Path::new("src/core.ttl"),
            "@prefix ex: <http://example.org/> .",
        );
        assert_eq!(violations.len(), 1);
    }
}