ggen-core 26.7.2

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
#![allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    clippy::needless_raw_string_hashes,
    clippy::duration_suboptimal_units,
    clippy::branches_sharing_code,
    clippy::used_underscore_binding,
    clippy::single_char_pattern,
    clippy::ignore_without_reason,
    clippy::cloned_ref_to_slice_refs,
    clippy::doc_overindented_list_items,
    clippy::match_wildcard_for_single_variants,
    clippy::ignored_unit_patterns,
    clippy::needless_collect,
    clippy::unnecessary_map_or,
    clippy::manual_flatten,
    clippy::manual_strip,
    clippy::future_not_send,
    clippy::unnested_or_patterns,
    clippy::no_effect_underscore_binding,
    clippy::literal_string_with_formatting_args
)]
#![allow(
    dead_code,
    unused_imports,
    unused_variables,
    deprecated,
    clippy::all,
    unused_mut
)]
/// Syntax validation tests for MCP/A2A .tera, .rq, and .ttl files.
///
/// These tests ensure that:
/// 1. Critical MCP/A2A Tera template files parse without syntax errors
/// 2. All SPARQL query files parse without syntax errors (via oxigraph)
/// 3. All Turtle ontology files load without syntax errors (via oxigraph)
/// 4. Files that should use RDF 1.2 triple terms actually do
/// 5. MCP/A2A templates use consistent variable names
use tera::Tera;
use walkdir::WalkDir;

fn workspace_root() -> std::path::PathBuf {
    let mut p = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    p.pop(); // crates/ggen-core -> crates
    p.pop(); // crates -> ggen root
    p
}

// ---------------------------------------------------------------------------
// 1. Critical MCP/A2A Tera template syntax validation
// ---------------------------------------------------------------------------

/// MCP/A2A templates that MUST parse without error.
/// These are actively used in the ggen.toml pipeline.
const CRITICAL_TERA_TEMPLATES: &[&str] = &[
    // Root templates (used by ggen.toml rules)
    "templates/mcp-rust.tera",
    "templates/mcp-typescript.tera",
    "templates/mcp-go.tera",
    "templates/mcp-elixir.tera",
    "templates/mcp-java.tera",
    "templates/a2a-rust.tera",
    "templates/a2a-typescript.tera",
    "templates/a2a-go.tera",
    "templates/a2a-elixir.tera",
    "templates/a2a-java.tera",
    // Adapter templates (used by ggen.toml rules)
    // NOTE: templates using {% extends %} or {% import %} need parent templates
    // loaded first and are tested separately
    "crates/ggen-core/templates/mcp/server.rs.tera",
    "crates/ggen-core/templates/a2a/agent.ex.tera",
    "crates/ggen-core/templates/bridge/bridges.rs.tera",
];

#[test]
fn test_critical_mcp_a2a_templates_parse() {
    let mut tera = Tera::default();
    ggen_core::register::register_all(&mut tera);

    let root = workspace_root();
    let mut errors = Vec::new();

    for rel in CRITICAL_TERA_TEMPLATES {
        let path = root.join(rel);
        if !path.exists() {
            continue;
        }

        let content = std::fs::read_to_string(&path)
            .unwrap_or_else(|e| panic!("Cannot read {}: {}", path.display(), e));

        // Use a unique name per file to avoid collisions
        let template_name = rel.replace('/', "__");

        if let Err(e) = tera.add_raw_template(&template_name, &content) {
            errors.push(format!("ERROR in {}: {}", rel, e));
        }
    }

    if !errors.is_empty() {
        panic!(
            "Critical MCP/A2A template syntax errors:\n{}",
            errors.join("\n")
        );
    }
}

// ---------------------------------------------------------------------------
// 2. SPARQL query syntax validation
// ---------------------------------------------------------------------------

/// MCP/A2A SPARQL queries that MUST parse (used in ggen.toml pipeline).
const CRITICAL_RQ_FILES: &[&str] = &[
    "crates/ggen-core/queries/mcp/extract-mcp-full.rq",
    "crates/ggen-core/queries/mcp/extract-mcp-params.rq",
    "crates/ggen-core/queries/mcp/extract-mcp-server.rq",
    "crates/ggen-core/queries/mcp/extract-mcp-tools.rq",
    "crates/ggen-core/queries/mcp/extract-mcp-tools-params.rq",
    "crates/ggen-core/queries/a2a/extract-a2a-full.rq",
    "crates/ggen-core/queries/a2a/extract-a2a-agent.rq",
    "crates/ggen-core/queries/a2a/extract-a2a-skills.rq",
    "crates/ggen-core/queries/a2a/extract-agents-skills-params.rq",
    "crates/ggen-core/queries/bridge/extract-bridges.rq",
];

#[test]
fn test_critical_sparql_queries_parse() {
    let root = workspace_root();
    let mut errors = Vec::new();

    for rel in CRITICAL_RQ_FILES {
        let path = root.join(rel);
        if !path.exists() {
            continue;
        }
        let content = std::fs::read_to_string(&path)
            .unwrap_or_else(|e| panic!("Cannot read {}: {}", path.display(), e));

        let store = oxigraph::store::Store::new().unwrap();
        if let Err(e) = store.query(&content) {
            errors.push(format!("SPARQL ERROR in {}: {}", rel, e));
        }
    }

    if !errors.is_empty() {
        panic!(
            "Critical SPARQL query syntax errors:\n{}",
            errors.join("\n")
        );
    }
}

#[test]
fn test_all_rq_files_parse_without_error() {
    let root = workspace_root();
    let rq_dirs = [
        root.join("crates/ggen-core/queries"),
        root.join(".specify/queries"),
    ];

    let mut count = 0u32;
    let mut errors = Vec::new();
    let mut non_critical = Vec::new();

    for dir in &rq_dirs {
        if !dir.exists() {
            continue;
        }
        for entry in WalkDir::new(dir)
            .into_iter()
            .filter_map(|e| e.ok())
            .filter(|e| e.path().extension().is_some_and(|ext| ext == "rq"))
        {
            let content = match std::fs::read_to_string(entry.path()) {
                Ok(c) => c,
                Err(e) => {
                    errors.push(format!("READ ERROR {}: {}", entry.path().display(), e));
                    count += 1;
                    continue;
                }
            };

            // oxigraph store.query() validates SPARQL syntax
            let store = oxigraph::store::Store::new().unwrap();
            if let Err(e) = store.query(&content) {
                let path_str = entry.path().display().to_string();
                // Check if this is a critical query (used in ggen.toml pipeline)
                let is_critical = CRITICAL_RQ_FILES.iter().any(|f| path_str.ends_with(f));

                if is_critical {
                    errors.push(format!(
                        "SPARQL PARSE ERROR in {}: {}",
                        entry.path().display(),
                        e
                    ));
                } else {
                    non_critical.push(format!(
                        "SPARQL WARNING (non-blocking) in {}: {}",
                        entry.path().display(),
                        e
                    ));
                }
            }
            count += 1;
        }
    }

    assert!(
        count > 0,
        "Should find .rq files in crates/ggen-core/queries/ or specify/queries/"
    );

    // Non-critical errors are reported but don't fail the test
    // (these are pre-existing issues in older query files)
    for w in &non_critical {
        eprintln!("[WARN] {}", w);
    }

    if !errors.is_empty() {
        panic!(
            "Critical SPARQL syntax errors ({} of {} files):\n{}",
            errors.len(),
            count,
            errors.join("\n")
        );
    }
}

// ---------------------------------------------------------------------------
// 3. Turtle ontology syntax validation
// ---------------------------------------------------------------------------

/// MCP/A2A Turtle files that MUST parse (loaded by ggen.toml pipeline).
const CRITICAL_TTL_FILES: &[&str] = &[
    ".specify/mcp-a2a-protocol.ttl",
    ".specify/mcp-a2a-protocol-example.ttl",
];

#[test]
fn test_critical_ttl_files_parse() {
    let root = workspace_root();
    let mut errors = Vec::new();

    for rel in CRITICAL_TTL_FILES {
        let path = root.join(rel);
        if !path.exists() {
            continue;
        }
        let content = std::fs::read_to_string(&path)
            .unwrap_or_else(|e| panic!("Cannot read {}: {}", path.display(), e));

        let cursor = std::io::Cursor::new(content.as_bytes());
        let store = oxigraph::store::Store::new().unwrap();

        if let Err(e) = store.load_from_reader(oxigraph::io::RdfFormat::Turtle, cursor) {
            errors.push(format!("TURTLE ERROR in {}: {}", rel, e));
        }
    }

    if !errors.is_empty() {
        panic!(
            "Critical Turtle ontology syntax errors:\n{}",
            errors.join("\n")
        );
    }
}

#[test]
fn test_all_ttl_files_parse_without_error() {
    let root = workspace_root();
    let ttl_dirs = [root.join(".specify")];

    let mut count = 0u32;
    let mut errors = Vec::new();
    let mut non_critical = Vec::new();

    for dir in &ttl_dirs {
        if !dir.exists() {
            continue;
        }
        for entry in WalkDir::new(dir)
            .into_iter()
            .filter_map(|e| e.ok())
            .filter(|e| e.path().extension().is_some_and(|ext| ext == "ttl"))
        {
            let content = match std::fs::read_to_string(entry.path()) {
                Ok(c) => c,
                Err(e) => {
                    errors.push(format!("READ ERROR {}: {}", entry.path().display(), e));
                    count += 1;
                    continue;
                }
            };

            let cursor = std::io::Cursor::new(content.as_bytes());
            let store = oxigraph::store::Store::new().unwrap();

            if let Err(e) = store.load_from_reader(oxigraph::io::RdfFormat::Turtle, cursor) {
                let path_str = entry.path().display().to_string();
                let is_critical = CRITICAL_TTL_FILES.iter().any(|f| path_str.ends_with(f));

                if is_critical {
                    errors.push(format!(
                        "TURTLE PARSE ERROR in {}: {}",
                        entry.path().display(),
                        e
                    ));
                } else {
                    non_critical.push(format!(
                        "TURTLE WARNING (non-blocking) in {}: {}",
                        entry.path().display(),
                        e
                    ));
                }
            }
            count += 1;
        }
    }

    assert!(count > 0, "Should find .ttl files in .specify/");

    // Non-critical errors are reported but don't fail the test
    // (pre-existing issues in older ontology files, e.g. RDF 1.2 triple terms)
    for w in &non_critical {
        eprintln!("[WARN] {}", w);
    }

    if !errors.is_empty() {
        panic!(
            "Critical Turtle syntax errors ({} of {} files):\n{}",
            errors.len(),
            count,
            errors.join("\n")
        );
    }
}

// ---------------------------------------------------------------------------
// 4. Triple-term usage verification
// ---------------------------------------------------------------------------

/// Files that deliberately don't use RDF 1.2 triple terms.
const NON_TRIPLE_TERM_FILES: &[&str] = &[
    ".specify/dod-ontology.ttl",
    ".specify/dod-example.ttl",
    ".specify/dod-compliance-mining.ttl",
    ".specify/onboarding-conventions.ttl",
    ".specify/merge-gate-workflow.ttl",
    ".specify/queries/dod-extract.rq",
];

#[test]
fn test_non_triple_term_files_are_clean() {
    let root = workspace_root();

    for file in NON_TRIPLE_TERM_FILES {
        let path = root.join(file);
        if !path.exists() {
            continue;
        }
        let content = std::fs::read_to_string(&path)
            .unwrap_or_else(|e| panic!("Cannot read {}: {}", path.display(), e));
        assert!(
            !content.contains("<<"),
            "Expected {} to NOT use triple terms (<<...>>), but it does",
            file
        );
    }
}

/// Files that MUST use RDF 1.2 triple terms (<<...>>).
const TRIPLE_TERM_FILES: &[&str] = &[
    ".specify/codegen-annotations-example.ttl",
    ".specify/codegen-annotations.ttl",
    ".specify/conflict-detection-example.ttl",
    ".specify/conflict-detection.ttl",
    ".specify/mcp-a2a-protocol-example.ttl",
    ".specify/mcp-a2a-protocol.ttl",
    ".specify/ontology-diff-example.ttl",
    ".specify/ontology-diff.ttl",
    ".specify/ontology-explorer-example.ttl",
    ".specify/ontology-explorer.ttl",
    ".specify/provenance-chain-example.ttl",
    ".specify/provenance-chain.ttl",
    ".specify/review-rules.ttl",
    ".specify/tdd-axiom-links.ttl",
    ".specify/type-registry-example.ttl",
    ".specify/type-registry.ttl",
    ".specify/queries/axiom-linked-tdd-extract.rq",
    ".specify/queries/codegen-annotations-extract.rq",
    ".specify/queries/conflict-detect-extract.rq",
    ".specify/queries/mcp-a2a-extract.rq",
    ".specify/queries/ontology-diff-extract.rq",
    ".specify/queries/ontology-explorer-extract.rq",
    ".specify/queries/openapi-typegen-extract.rq",
    ".specify/queries/provenance-chain-extract.rq",
    ".specify/queries/review-rules-extract.rq",
    ".specify/queries/type-registry-extract.rq",
    ".specify/folk-calculus-definitions.ttl",
    ".specify/folk-calculus-dictionary.ttl",
    ".specify/ggen-cli-integration-kgc.ttl",
    ".specify/holographic-orchestration-kgc.ttl",
    ".specify/specs/013-ga-production-release/feature.ttl",
    ".specify/specs/013-ga-production-release/plan.ttl",
];

#[test]
fn test_triple_term_files_do_use_triple_terms() {
    let root = workspace_root();

    let mut checked = 0u32;
    let mut missing = Vec::new();

    for file in TRIPLE_TERM_FILES {
        let path = root.join(file);
        if !path.exists() {
            continue;
        }

        let content = std::fs::read_to_string(&path)
            .unwrap_or_else(|e| panic!("Cannot read {}: {}", path.display(), e));

        if !content.contains("<<") {
            missing.push(path.display().to_string());
        }
        checked += 1;
    }

    if !missing.is_empty() {
        panic!(
            "These files should use RDF 1.2 triple terms (<<...>>) but don't:\n{}",
            missing.join("\n")
        );
    }

    assert!(
        checked > 0,
        "Should check at least some files for triple terms"
    );
}

// ---------------------------------------------------------------------------
// 5. Cross-template variable name consistency
// ---------------------------------------------------------------------------

#[test]
fn test_mcp_templates_use_consistent_variable_names() {
    let root = workspace_root();
    let mcp_templates = [
        "templates/mcp-rust.tera",
        "templates/mcp-typescript.tera",
        "templates/mcp-go.tera",
        "templates/mcp-elixir.tera",
        "templates/mcp-java.tera",
    ];

    let required_vars = [
        "server_name",
        "server_version",
        "server_description",
        "transport_type",
    ];

    for tmpl_rel in &mcp_templates {
        let path = root.join(tmpl_rel);
        if !path.exists() {
            continue;
        }
        let content = std::fs::read_to_string(&path)
            .unwrap_or_else(|e| panic!("Cannot read {}: {}", path.display(), e));
        for var in &required_vars {
            assert!(
                content.contains(var),
                "MCP template {} missing variable: {}",
                tmpl_rel,
                var
            );
        }
    }
}

#[test]
fn test_a2a_templates_use_consistent_variable_names() {
    let root = workspace_root();
    let a2a_templates = [
        "templates/a2a-rust.tera",
        "templates/a2a-typescript.tera",
        "templates/a2a-go.tera",
        "templates/a2a-elixir.tera",
        "templates/a2a-java.tera",
    ];

    let required_vars = [
        "agent_name",
        "agent_version",
        "agent_description",
        "agent_url",
        "provider_name",
    ];

    for tmpl_rel in &a2a_templates {
        let path = root.join(tmpl_rel);
        if !path.exists() {
            continue;
        }
        let content = std::fs::read_to_string(&path)
            .unwrap_or_else(|e| panic!("Cannot read {}: {}", path.display(), e));
        for var in &required_vars {
            assert!(
                content.contains(var),
                "A2A template {} missing variable: {}",
                tmpl_rel,
                var
            );
        }
    }
}