ggen-core 26.5.19

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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
//! μ₃: Emission Pass
//!
//! Performs bindings → files transformation using Tera templates.
//! Renders extracted data into source code files.
//!
//! ## CONSTRUCT Guarantees
//!
//! - **Determinism checks**: Verify template rendering is deterministic (no timestamps, randomness)
//! - **Stop-the-line**: Any non-deterministic output halts the pipeline
//! - **Receipt integration**: All generated files are hashed and recorded

use crate::marketplace::ownership::{OwnershipMap, OwnershipTarget};
use crate::pipeline_engine::guard::{GuardAction, GuardSet, GuardViolation};
use crate::pipeline_engine::pass::{Pass, PassContext, PassResult, PassType};
use crate::resolver::TemplateResolver;
use crate::utils::error::{Error, Result};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::path::PathBuf;
use std::time::Instant;

/// An emission rule that produces files from templates
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EmissionRule {
    /// Rule name for auditing
    pub name: String,

    /// Path to Tera template file (relative to base_path)
    pub template_path: PathBuf,

    /// When set, use this content instead of reading `template_path` from disk.
    #[serde(default)]
    pub inline_template: Option<String>,

    /// Output file pattern (supports Tera syntax for dynamic paths)
    pub output_pattern: String,

    /// Binding key to use as context (from extraction)
    pub binding_key: String,

    /// Whether to iterate over binding array items
    pub iterate: bool,

    /// Skip if binding is empty
    pub skip_empty: bool,

    /// Description for documentation
    pub description: Option<String>,
}

/// Emission receipt for auditing
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EmissionReceipt {
    /// Files generated with hashes
    pub files: Vec<EmittedFile>,

    /// Total rendering duration in milliseconds
    pub duration_ms: u64,

    /// Determinism checks passed
    pub determinism_verified: bool,

    /// Idempotence checks passed
    pub idempotence_verified: bool,
}

/// Record of an emitted file
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EmittedFile {
    /// Output path
    pub path: PathBuf,

    /// SHA-256 hash of content
    pub hash: String,

    /// File size in bytes
    pub size: usize,

    /// Rule that generated this file
    pub rule_name: String,
}

/// μ₃: Emission pass implementation
#[derive(Debug, Clone)]
pub struct EmissionPass {
    /// Rules to execute
    rules: Vec<EmissionRule>,

    /// Guards to apply to outputs
    guards: GuardSet,

    /// Whether to enable determinism verification
    enable_determinism_check: bool,

    /// Emission receipt for current execution
    receipt: Option<EmissionReceipt>,

    /// Ownership map for conflict detection (from μ₀ pack resolution)
    ownership_map: Option<OwnershipMap>,
}

impl EmissionPass {
    /// Create a new emission pass
    pub fn new() -> Self {
        Self {
            rules: Vec::new(),
            guards: GuardSet::default_v26(),
            enable_determinism_check: true,
            receipt: None,
            ownership_map: None,
        }
    }

    /// Get the emission receipt from last execution
    pub fn receipt(&self) -> Option<&EmissionReceipt> {
        self.receipt.as_ref()
    }

    /// Add an emission rule
    pub fn add_rule(&mut self, rule: EmissionRule) {
        self.rules.push(rule);
    }

    /// Create with a set of rules
    pub fn with_rules(mut self, rules: Vec<EmissionRule>) -> Self {
        self.rules = rules;
        self
    }

    /// Extend with pack-contributed templates.
    ///
    /// Creates emission rules from pack templates. Each template becomes a rule
    /// with the template content as inline_template, ensuring pack templates are
    /// included in the build output without requiring external files.
    ///
    /// See `docs/marketplace/PACK_QUERY_CONTRACT.md`.
    pub fn extend_with_pack_templates(
        &mut self, templates: &[crate::pack_resolver::TemplateDef],
    ) -> Result<()> {
        for template in templates {
            // Extract rule name from template path (e.g., "test-pack-integration/templates/test_entity.rs.tera")
            // -> "pack:test-pack-integration::test_entity"
            let path_str = template.path.display().to_string();
            let parts: Vec<&str> = path_str.split('/').collect();

            // Expected format: <pack-id>/templates/<template-name>.tera
            let pack_id = parts.first().unwrap_or(&"unknown");
            let template_name = parts
                .get(2)
                .and_then(|s| s.strip_suffix(".tera"))
                .unwrap_or("unknown");

            let rule_name = format!("pack:{}::{}", pack_id, template_name);

            // Create binding key from template name (e.g., "test_entity" -> "test_entities")
            let binding_key = format!(
                "{}{}",
                template_name,
                if template_name.ends_with('y') {
                    "ies"
                } else {
                    "s"
                }
            );

            // Create output pattern from template name (e.g., "test_entity.rs.tera" -> "{{ name | lower }}.rs")
            let output_pattern = if template_name.contains('.') {
                // Already has extension in name
                "{% if name %}{{ name | lower }}{% endif %}".to_string()
            } else {
                // Use template stem
                "{% if name %}{{ name | lower }}{% endif %}".to_string()
            };

            self.rules.push(EmissionRule {
                name: rule_name,
                template_path: PathBuf::from(&template.path),
                inline_template: Some(template.content.clone()),
                output_pattern,
                binding_key,
                iterate: true,
                skip_empty: true,
                description: Some(format!("Pack-contributed template from {}", path_str)),
            });
        }
        Ok(())
    }

    /// Set custom guards
    pub fn with_guards(mut self, guards: GuardSet) -> Self {
        self.guards = guards;
        self
    }

    /// Enable or disable determinism checking
    pub fn with_determinism_check(mut self, enabled: bool) -> Self {
        self.enable_determinism_check = enabled;
        self
    }

    /// Set the ownership map for conflict detection (from μ₀ pack resolution).
    ///
    /// When set, each file emission is checked against ownership declarations.
    /// Packs claiming exclusive or forbidden-overlap ownership of a path will
    /// cause emission from other packs to fail with a descriptive error.
    pub fn with_ownership_map(mut self, map: OwnershipMap) -> Self {
        self.ownership_map = Some(map);
        self
    }

    /// Check if emitting to a path would violate ownership declarations.
    ///
    /// This gate runs before any file is written. If the `ownership_map` is set
    /// and contains declarations for the target path, the emitting pack must be
    /// the declared owner for exclusive/forbidden-overlap classes.
    ///
    /// For mergeable/overlay classes, overlap is allowed (merge strategy is
    /// handled upstream by the three-way merger).
    fn check_ownership_conflict(
        &self, artifact_path: &std::path::Path, emitting_pack: &str,
    ) -> Result<()> {
        let ownership_map = match &self.ownership_map {
            Some(map) => map,
            None => return Ok(()), // No ownership map — skip check
        };

        let target = OwnershipTarget::FilePath(artifact_path.to_path_buf());
        let declarations = match ownership_map.get_declarations(&target) {
            Some(decls) => decls,
            None => return Ok(()), // No declarations for this path
        };

        for declaration in declarations {
            if declaration.owner_pack != emitting_pack {
                match declaration.class {
                    crate::marketplace::ownership::OwnershipClass::Exclusive => {
                        return Err(Error::new(&format!(
                            "Ownership conflict: '{}' claims exclusive ownership of '{}', but '{}' is attempting to emit to it",
                            declaration.owner_pack,
                            artifact_path.display(),
                            emitting_pack,
                        )));
                    }
                    crate::marketplace::ownership::OwnershipClass::ForbiddenOverlap => {
                        return Err(Error::new(&format!(
                            "Forbidden overlap: '{}' and '{}' both target '{}'",
                            declaration.owner_pack,
                            emitting_pack,
                            artifact_path.display(),
                        )));
                    }
                    crate::marketplace::ownership::OwnershipClass::Mergeable
                    | crate::marketplace::ownership::OwnershipClass::Overlay => {
                        // Allowed — merge strategy or overlay transfer handled upstream
                    }
                }
            }
        }

        Ok(())
    }

    /// Extract the pack ID from an emission rule name.
    ///
    /// Pack-contributed rules use the format `"pack:<pack-id>::<template-name>"`.
    /// Non-pack rules return `"core"`.
    fn extract_pack_id(rule_name: &str) -> &str {
        if let Some(rest) = rule_name.strip_prefix("pack:") {
            // rest is "<pack-id>::<template-name>"
            rest.split("::").next().unwrap_or("core")
        } else {
            "core"
        }
    }

    /// Verify template rendering is deterministic
    fn verify_determinism(
        &self, _ctx: &PassContext<'_>, path: &std::path::Path, content: &str,
    ) -> Result<()> {
        if !self.enable_determinism_check {
            return Ok(());
        }

        // Check for common non-deterministic patterns
        let non_deterministic_patterns = [
            (
                "timestamp",
                vec![
                    "now()",
                    "Utc::now()",
                    "Local::now()",
                    "SystemTime::now()",
                    "chrono::Utc::now",
                    "std::time::SystemTime::now",
                    "Instant::now()",
                    "OffsetDateTime::now",
                    "current_time()",
                    "get_timestamp()",
                ],
            ),
            (
                "random",
                vec![
                    "rand()",
                    "random()",
                    "uuid()",
                    "Uuid::new_v4()",
                    "thread_rng()",
                    "rand::random",
                    "OsRng",
                    "RandomNumberGenerator",
                    "rand::thread_rng",
                ],
            ),
            (
                "process",
                vec![
                    "pid()",
                    "getpid()",
                    "thread_id()",
                    "std::process::id()",
                    "ThreadId::current()",
                    "current_thread_id()",
                ],
            ),
            (
                "network",
                vec![
                    "reqwest::",
                    "hyper::",
                    "tokio::net::",
                    "std::net::TcpStream",
                    "UdpSocket",
                    "fetch(",
                    "http_get(",
                    "download(",
                ],
            ),
            (
                "filesystem_metadata",
                vec![
                    ".metadata()",
                    "fs::metadata",
                    "DirEntry",
                    "modified()",
                    "accessed()",
                    "created()",
                    "file_modified_time",
                ],
            ),
            (
                "ordering",
                vec![
                    "HashMap::",
                    "std::collections::HashMap",
                    "use std::collections::HashMap",
                    "HashSet::",
                    "use std::collections::HashSet",
                ],
            ),
            (
                "grouping",
                vec![
                    ".group_by(",
                    "GROUP BY",
                    "groupBy",
                    "aggregate(",
                    "AGGREGATE",
                ],
            ),
            (
                "joins",
                vec![
                    ".join(",
                    "JOIN ",
                    "INNER JOIN",
                    "LEFT JOIN",
                    "OUTER JOIN",
                    "RIGHT JOIN",
                    "CROSS JOIN",
                ],
            ),
        ];

        for (category, patterns) in &non_deterministic_patterns {
            for pattern in patterns {
                if content.contains(pattern) {
                    return Err(Error::new(&format!(
                        "🚨 Non-Deterministic Pattern Detected in μ₃:emission\n\n\
                         μ₃:emission STOPPED THE LINE (Andon Protocol)\n\n\
                         File '{}' contains non-deterministic {} pattern: '{}'\n\n\
                         μ₃ output must be deterministic for reproducible builds.\n\n\
                         Fix: Remove {} pattern or use deterministic alternative.\n\n\
                         For ordering: Use BTreeMap/BTreeSet instead of HashMap/HashSet.\n\
                         For timestamps: Use fixed epoch or SOURCE_DATE_EPOCH.\n\
                         For random: Use fixed seed with StdRng::seed_from_u64.\n\
                         For grouping/joins: Use pure SELECT extraction in μ₂.",
                        path.display(),
                        category,
                        pattern,
                        pattern
                    )));
                }
            }
        }

        Ok(())
    }

    /// Verify template rendering is idempotent (double-render check)
    fn verify_idempotence(
        &self, ctx: &PassContext<'_>, rule: &EmissionRule, template_content: &str,
        item_context: &serde_json::Value,
    ) -> Result<()> {
        if !self.enable_determinism_check {
            return Ok(());
        }

        // Render twice with identical inputs
        let (_, content1) = self.render_file(ctx, rule, template_content, item_context)?;
        let (_, content2) = self.render_file(ctx, rule, template_content, item_context)?;

        if content1 != content2 {
            return Err(Error::new(&format!(
                "🚨 Non-Idempotent Rendering Detected in μ₃:emission\n\n\
                 μ₃:emission STOPPED THE LINE (Andon Protocol)\n\n\
                 Rule '{}' produced different outputs on subsequent renders.\n\n\
                 μ₃ must be idempotent: μ∘μ = μ\n\n\
                 Fix: Remove stateful operations from template or filter.",
                rule.name
            )));
        }

        Ok(())
    }

    /// Verify ordered iteration over bindings (BTreeMap guarantees)
    fn verify_ordered_iteration(&self, _ctx: &PassContext<'_>) -> Result<()> {
        // PassContext uses BTreeMap for bindings, which guarantees ordered iteration
        // This is a static verification that the type system enforces
        // No runtime check needed - compile-time guarantee
        Ok(())
    }

    /// Verify file hash for determinism (same input = same output)
    fn record_file_hash(&self, _path: &PathBuf, content: &str) -> String {
        format!("{:x}", Sha256::digest(content.as_bytes()))
    }

    /// Render a single file from template and context
    fn render_file(
        &self, ctx: &PassContext<'_>, rule: &EmissionRule, template_content: &str,
        item_context: &serde_json::Value,
    ) -> Result<(PathBuf, String)> {
        // Create Tera instance
        let mut tera = tera::Tera::default();
        tera.add_raw_template("template", template_content)
            .map_err(|e| Error::new(&format!("Template parse error in '{}': {}", rule.name, e)))?;

        // Build context
        let mut context = tera::Context::new();

        // Add project metadata
        context.insert("project_name", &ctx.project_name);
        context.insert("project_version", &ctx.project_version);

        // Add all bindings
        for (key, value) in &ctx.bindings {
            context.insert(key, value);
        }

        // Add current item if iterating
        if rule.iterate {
            context.insert("item", item_context);

            // Also flatten item properties to top level for convenience
            if let Some(obj) = item_context.as_object() {
                for (key, value) in obj {
                    context.insert(key, value);
                }
            }
        }

        // Render template
        let content = tera
            .render("template", &context)
            .map_err(|e| Error::new(&format!("Template render error in '{}': {}", rule.name, e)))?;

        // Render output path
        let output_path_str = tera
            .render_str(&rule.output_pattern, &context)
            .map_err(|e| {
                Error::new(&format!(
                    "Output path template error in '{}': {}",
                    rule.name, e
                ))
            })?;

        let output_path = PathBuf::from(output_path_str.trim());

        Ok((output_path, content))
    }

    /// Execute a single emission rule
    fn execute_rule(
        &self, ctx: &mut PassContext<'_>, rule: &EmissionRule, emitted_files: &mut Vec<EmittedFile>,
    ) -> Result<Vec<PathBuf>> {
        let mut generated_files = Vec::new();

        // Load template content (inline wins over filesystem, pack templates resolved from cache)
        let template_content = if let Some(ref inline) = rule.inline_template {
            inline.clone()
        } else {
            // Check if template_path uses pack_id:template_path syntax
            let template_path_str = rule.template_path.to_string_lossy();
            if TemplateResolver::is_pack_reference(&template_path_str) {
                // Resolve from pack cache
                tracing::info!("Loading template from pack cache: {}", template_path_str);
                let resolver = TemplateResolver::new()?;
                let template_source = resolver.resolve(&template_path_str)?;
                tracing::info!(
                    "Loaded template from pack cache: {} -> {}",
                    template_path_str,
                    template_source.full_path.display()
                );
                template_source.content
            } else {
                // Load from filesystem
                let template_path = ctx.base_path.join(&rule.template_path);
                std::fs::read_to_string(&template_path).map_err(|e| {
                    Error::new(&format!(
                        "Failed to read template '{}': {}",
                        template_path.display(),
                        e
                    ))
                })?
            }
        };

        // Get binding value
        let binding = ctx.bindings.get(&rule.binding_key).cloned();

        if rule.iterate {
            // Iterate over array items
            if let Some(serde_json::Value::Array(items)) = &binding {
                if items.is_empty() && rule.skip_empty {
                    return Ok(generated_files);
                }

                for item in items {
                    // GATE 0: Verify idempotence (double render check)
                    self.verify_idempotence(ctx, rule, &template_content, item)?;

                    let (output_path, content) =
                        self.render_file(ctx, rule, &template_content, item)?;

                    // GATE 1: Determinism check
                    self.verify_determinism(ctx, &output_path, &content)?;

                    // GATE 2: Apply guards
                    let violations = self.guards.check(&output_path, &content);
                    self.handle_violations(&violations)?;

                    // GATE 3: Ownership conflict check
                    let emitting_pack = Self::extract_pack_id(&rule.name);
                    self.check_ownership_conflict(&output_path, emitting_pack)?;

                    // Record hash for receipt
                    let hash = self.record_file_hash(&output_path, &content);
                    emitted_files.push(EmittedFile {
                        path: output_path.clone(),
                        hash,
                        size: content.len(),
                        rule_name: rule.name.clone(),
                    });

                    // Write file
                    let full_output_path = ctx.output_dir.join(&output_path);
                    self.write_output(&full_output_path, &content)?;

                    generated_files.push(output_path);
                }
            }
        } else {
            // Single file from entire binding
            let context_value = binding.unwrap_or(serde_json::Value::Null);

            if context_value.is_null() && rule.skip_empty {
                return Ok(generated_files);
            }

            // GATE 0: Verify idempotence (double render check)
            self.verify_idempotence(ctx, rule, &template_content, &context_value)?;

            let (output_path, content) =
                self.render_file(ctx, rule, &template_content, &context_value)?;

            // GATE 1: Determinism check
            self.verify_determinism(ctx, &output_path, &content)?;

            // GATE 2: Apply guards
            let violations = self.guards.check(&output_path, &content);
            self.handle_violations(&violations)?;

            // GATE 3: Ownership conflict check
            let emitting_pack = Self::extract_pack_id(&rule.name);
            self.check_ownership_conflict(&output_path, emitting_pack)?;

            // Record hash for receipt
            let hash = self.record_file_hash(&output_path, &content);
            emitted_files.push(EmittedFile {
                path: output_path.clone(),
                hash,
                size: content.len(),
                rule_name: rule.name.clone(),
            });

            // Write file
            let full_output_path = ctx.output_dir.join(&output_path);
            self.write_output(&full_output_path, &content)?;

            generated_files.push(output_path);
        }

        Ok(generated_files)
    }

    /// Handle guard violations
    fn handle_violations(&self, violations: &[GuardViolation]) -> Result<()> {
        for violation in violations {
            match violation.action {
                GuardAction::Reject => {
                    return Err(Error::new(&format!(
                        "Guard '{}' violation: {}",
                        violation.guard_name, violation.message
                    )));
                }
                GuardAction::Warn => {
                    eprintln!("WARNING [{}]: {}", violation.guard_name, violation.message);
                }
                GuardAction::RequireApproval => {
                    return Err(Error::new(&format!(
                        "Guard '{}' requires approval: {}",
                        violation.guard_name, violation.message
                    )));
                }
            }
        }
        Ok(())
    }

    /// Write output file with parent directory creation
    fn write_output(&self, path: &std::path::Path, content: &str) -> Result<()> {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).map_err(|e| {
                Error::new(&format!(
                    "Failed to create directory '{}': {}",
                    parent.display(),
                    e
                ))
            })?;
        }

        std::fs::write(path, content)
            .map_err(|e| Error::new(&format!("Failed to write file '{}': {}", path.display(), e)))
    }
}

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

impl Pass for EmissionPass {
    fn pass_type(&self) -> PassType {
        PassType::Emission
    }

    fn name(&self) -> &str {
        "μ₃:emission"
    }

    fn execute(&self, ctx: &mut PassContext<'_>) -> Result<PassResult> {
        let start = Instant::now();
        let mut all_generated = Vec::new();
        let mut emitted_files = Vec::new();

        // GATE: Verify ordered iteration is enforced by type system
        self.verify_ordered_iteration(ctx)?;

        for rule in &self.rules {
            let generated = self.execute_rule(ctx, rule, &mut emitted_files)?;
            all_generated.extend(generated);
        }

        // Update context with generated files
        ctx.generated_files.extend(all_generated.clone());

        let duration = start.elapsed();

        // Create emission receipt
        let _receipt = EmissionReceipt {
            files: emitted_files,
            duration_ms: duration.as_millis() as u64,
            determinism_verified: self.enable_determinism_check,
            idempotence_verified: self.enable_determinism_check,
        };

        // Store receipt (need mutable self, so we'll return it in result for now)
        // In production, receipt would be stored in pipeline context

        Ok(PassResult::success()
            .with_files(all_generated)
            .with_duration(duration))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::graph::Graph;
    use crate::marketplace::ownership::{OwnershipClass, OwnershipDeclaration};
    use tempfile::TempDir;

    #[test]
    fn test_emission_pass_empty() {
        let graph = Graph::new().unwrap();
        let pass = EmissionPass::new();

        let temp_dir = TempDir::new().unwrap();
        let mut ctx = PassContext::new(
            &graph,
            temp_dir.path().to_path_buf(),
            temp_dir.path().join("output"),
        );

        let result = pass.execute(&mut ctx).unwrap();
        assert!(result.success);
    }

    #[test]
    fn test_emission_single_file() {
        let graph = Graph::new().unwrap();
        let temp_dir = TempDir::new().unwrap();

        // Create template file
        let template_dir = temp_dir.path().join("templates");
        std::fs::create_dir_all(&template_dir).unwrap();
        std::fs::write(
            template_dir.join("domain.ttl.tera"),
            "@prefix ex: <http://example.org/> .\n# Generated for {{ project_name }}\n",
        )
        .unwrap();

        // Create output dir (use generated subdirectory to pass guards)
        let output_dir = temp_dir.path().join("ontology").join("output");
        std::fs::create_dir_all(&output_dir).unwrap();

        let mut pass = EmissionPass::new();
        // Disable guards for testing
        pass.guards = GuardSet::new();

        pass.add_rule(EmissionRule {
            inline_template: None,
            name: "generate-ontology".to_string(),
            template_path: PathBuf::from("templates/domain.ttl.tera"),
            output_pattern: "domain.ttl".to_string(),
            binding_key: "data".to_string(),
            iterate: false,
            skip_empty: false,
            description: None,
        });

        let mut ctx = PassContext::new(&graph, temp_dir.path().to_path_buf(), output_dir.clone())
            .with_project("TestProject".to_string(), "1.0.0".to_string());

        let result = pass.execute(&mut ctx).unwrap();

        assert!(result.success);
        assert_eq!(result.files_generated.len(), 1);
        assert!(output_dir.join("domain.ttl").exists());
    }

    #[test]
    fn test_emission_with_iteration() {
        let graph = Graph::new().unwrap();
        let temp_dir = TempDir::new().unwrap();

        // Create template
        let template_dir = temp_dir.path().join("templates");
        std::fs::create_dir_all(&template_dir).unwrap();
        std::fs::write(
            template_dir.join("entity.rs.tera"),
            "pub struct {{ name }} {}",
        )
        .unwrap();

        let output_dir = temp_dir.path().join("output");

        let mut pass = EmissionPass::new();
        pass.guards = GuardSet::new(); // Disable guards for testing

        pass.add_rule(EmissionRule {
            name: "generate-entities".to_string(),
            template_path: PathBuf::from("templates/entity.rs.tera"),
            output_pattern: "{{ name | lower }}.rs".to_string(),
            binding_key: "entities".to_string(),
            inline_template: None,
            iterate: true,
            skip_empty: true,
            description: None,
        });

        let mut ctx = PassContext::new(&graph, temp_dir.path().to_path_buf(), output_dir.clone());

        // Add bindings
        ctx.bindings.insert(
            "entities".to_string(),
            serde_json::json!([
                {"name": "User"},
                {"name": "Order"}
            ]),
        );

        let result = pass.execute(&mut ctx).unwrap();

        assert!(result.success);
        assert_eq!(result.files_generated.len(), 2);
    }

    // --- Ownership conflict tests ---

    #[test]
    fn test_extract_pack_id_pack_rule() {
        assert_eq!(
            EmissionPass::extract_pack_id("pack:serde-utils::serialize"),
            "serde-utils"
        );
    }

    #[test]
    fn test_extract_pack_id_non_pack_rule() {
        assert_eq!(EmissionPass::extract_pack_id("generate-ontology"), "core");
    }

    #[test]
    fn test_ownership_conflict_no_map() {
        // No ownership map set — check should pass
        let pass = EmissionPass::new();
        let path = std::path::Path::new("src/main.rs");
        assert!(pass.check_ownership_conflict(path, "pack-a").is_ok());
    }

    #[test]
    fn test_ownership_conflict_exclusive_owner_allowed() {
        // Exclusive owner emitting to its own path — should pass
        let mut map = OwnershipMap::new();
        map.add(OwnershipDeclaration::exclusive(
            OwnershipTarget::FilePath(PathBuf::from("src/main.rs")),
            "pack-a".to_string(),
        ))
        .unwrap();

        let pass = EmissionPass::new().with_ownership_map(map);
        assert!(pass
            .check_ownership_conflict(std::path::Path::new("src/main.rs"), "pack-a")
            .is_ok());
    }

    #[test]
    fn test_ownership_conflict_exclusive_blocked() {
        // Different pack emitting to exclusive path — should fail
        let mut map = OwnershipMap::new();
        map.add(OwnershipDeclaration::exclusive(
            OwnershipTarget::FilePath(PathBuf::from("src/main.rs")),
            "pack-a".to_string(),
        ))
        .unwrap();

        let pass = EmissionPass::new().with_ownership_map(map);
        let result = pass.check_ownership_conflict(std::path::Path::new("src/main.rs"), "pack-b");
        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(err_msg.contains("exclusive ownership"));
        assert!(err_msg.contains("pack-a"));
        assert!(err_msg.contains("pack-b"));
    }

    #[test]
    fn test_ownership_conflict_forbidden_overlap_blocked() {
        let mut map = OwnershipMap::new();
        map.add(OwnershipDeclaration::new(
            OwnershipTarget::FilePath(PathBuf::from("src/config.rs")),
            OwnershipClass::ForbiddenOverlap,
            "pack-a".to_string(),
        ))
        .unwrap();

        let pass = EmissionPass::new().with_ownership_map(map);
        let result = pass.check_ownership_conflict(std::path::Path::new("src/config.rs"), "pack-b");
        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(err_msg.contains("Forbidden overlap"));
    }

    #[test]
    fn test_ownership_conflict_mergeable_allowed() {
        // Mergeable allows overlap
        use crate::marketplace::ownership::MergeStrategy;

        let mut map = OwnershipMap::new();
        map.add(OwnershipDeclaration::mergeable(
            OwnershipTarget::FilePath(PathBuf::from("src/config.rs")),
            "pack-a".to_string(),
            MergeStrategy::Concat,
        ))
        .unwrap();

        let pass = EmissionPass::new().with_ownership_map(map);
        assert!(pass
            .check_ownership_conflict(std::path::Path::new("src/config.rs"), "pack-b")
            .is_ok());
    }

    #[test]
    fn test_ownership_conflict_undeclared_path() {
        // Path with no declarations — should pass
        let map = OwnershipMap::new();
        let pass = EmissionPass::new().with_ownership_map(map);
        assert!(pass
            .check_ownership_conflict(std::path::Path::new("src/undeclared.rs"), "pack-a")
            .is_ok());
    }
}