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
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
//! Sync Executor - Domain logic for ggen sync command
//!
//! This module contains the business logic for the sync pipeline,
//! extracted from the CLI layer to maintain separation of concerns.
//!
//! The executor handles:
//! - Manifest parsing and validation
//! - Validate-only mode
//! - Dry-run mode
//! - Full sync pipeline execution
//!
//! ## Architecture
//!
//! The CLI verb function should be thin (complexity <= 5):
//! 1. Parse CLI args into `SyncOptions`
//! 2. Call `SyncExecutor::execute(options)`
//! 3. Return result
//!
//! All business logic lives here in the executor.

use crate::codegen::pipeline::{GenerationPipeline, LlmService, RuleType};
use crate::codegen::ux::{
    format_duration, info_message, print_section, success_message, warning_message,
    ProgressIndicator,
};
use crate::codegen::{DependencyValidator, IncrementalCache, MarketplaceValidator, ProofCarrier};
use crate::drift::DriftDetector;
use crate::manifest::{ManifestParser, ManifestValidator};
use crate::poka_yoke::QualityGateRunner;
use crate::utils::error::{Error, Result};
use crate::validation::PreFlightValidator;
use serde::Serialize;
use std::path::{Path, PathBuf};
use std::time::Instant;

// ============================================================================
// Sync Options Types
// ============================================================================

/// Output format for sync results
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Default)]
pub enum OutputFormat {
    /// Human-readable text output
    #[default]
    Text,
    /// JSON output
    Json,
}

impl std::str::FromStr for OutputFormat {
    type Err = String;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "text" => Ok(OutputFormat::Text),
            "json" => Ok(OutputFormat::Json),
            _ => Err("Invalid format".to_string()),
        }
    }
}

impl std::fmt::Display for OutputFormat {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            OutputFormat::Text => write!(f, "text"),
            OutputFormat::Json => write!(f, "json"),
        }
    }
}

/// Options for sync execution
pub struct SyncOptions {
    /// Path to manifest file
    pub manifest_path: PathBuf,

    /// Output directory for generated files
    pub output_dir: Option<PathBuf>,

    /// Cache directory for incremental builds
    pub cache_dir: Option<PathBuf>,

    /// Enable verbose output
    pub verbose: bool,

    /// Output format
    pub output_format: OutputFormat,

    /// Only validate, don't generate
    pub validate_only: bool,

    /// Dry run mode - preview changes without writing
    pub dry_run: bool,

    /// Enable file watching and auto-regeneration
    pub watch: bool,

    /// Selected rules to execute (None = all)
    pub selected_rules: Option<Vec<String>>,

    /// Use incremental cache
    pub use_cache: bool,

    /// Force overwrite even if files are newer
    pub force: bool,

    /// Generate audit trail
    pub audit: bool,

    // A2A-specific options
    /// Run specific μ stage only (μ₁, μ₂, μ₃, μ₄, μ₅)
    pub a2a_stage: Option<String>,

    /// Override ontology path for A2A generation
    pub ontology_path: Option<PathBuf>,

    /// Optional LLM service for auto-generating skill implementations
    /// If None, uses default TemplateFallback generator
    /// Note: Box<dyn LlmService> avoids cyclic dependency with ggen-ai
    pub llm_service: Option<Box<dyn LlmService>>,

    /// Timeout for sync operations in milliseconds (None = no timeout)
    pub timeout_ms: Option<u64>,
}

impl Default for SyncOptions {
    fn default() -> Self {
        Self {
            manifest_path: PathBuf::from("ggen.toml"),
            output_dir: None,
            cache_dir: None,
            verbose: false,
            output_format: OutputFormat::default(),
            validate_only: false,
            dry_run: false,
            watch: false,
            selected_rules: None,
            use_cache: true,
            force: false,
            audit: false,
            a2a_stage: None,
            ontology_path: None,
            llm_service: None,
            timeout_ms: None,
        }
    }
}

impl std::fmt::Debug for SyncOptions {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SyncOptions")
            .field("manifest_path", &self.manifest_path)
            .field("output_dir", &self.output_dir)
            .field("cache_dir", &self.cache_dir)
            .field("verbose", &self.verbose)
            .field("output_format", &self.output_format)
            .field("validate_only", &self.validate_only)
            .field("dry_run", &self.dry_run)
            .field("watch", &self.watch)
            .field("selected_rules", &self.selected_rules)
            .field("use_cache", &self.use_cache)
            .field("force", &self.force)
            .field("audit", &self.audit)
            .field("a2a_stage", &self.a2a_stage)
            .field("ontology_path", &self.ontology_path)
            .field("llm_service", &"<dyn LlmService>")
            .field("timeout_ms", &self.timeout_ms)
            .finish()
    }
}

impl Clone for SyncOptions {
    fn clone(&self) -> Self {
        Self {
            manifest_path: self.manifest_path.clone(),
            output_dir: self.output_dir.clone(),
            cache_dir: self.cache_dir.clone(),
            verbose: self.verbose,
            output_format: self.output_format,
            validate_only: self.validate_only,
            dry_run: self.dry_run,
            watch: self.watch,
            selected_rules: self.selected_rules.clone(),
            use_cache: self.use_cache,
            force: self.force,
            audit: self.audit,
            a2a_stage: self.a2a_stage.clone(),
            ontology_path: self.ontology_path.clone(),
            timeout_ms: self.timeout_ms,
            llm_service: None, // trait objects cannot be cloned
        }
    }
}

impl SyncOptions {
    /// Create a new SyncOptions with default values
    pub fn new() -> Self {
        Self::default()
    }
}

// ============================================================================
// Sync Result Types
// ============================================================================

/// Result of sync execution - returned to CLI layer
#[derive(Debug, Clone, Serialize)]
pub struct SyncResult {
    /// Overall status: "success" or "error"
    pub status: String,

    /// Number of files synced
    pub files_synced: usize,

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

    /// Generated files with details
    pub files: Vec<SyncedFileInfo>,

    /// Number of inference rules executed
    pub inference_rules_executed: usize,

    /// Number of generation rules executed
    pub generation_rules_executed: usize,

    /// Audit trail path (if enabled)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub audit_trail: Option<String>,

    /// Error message (if failed)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

/// Individual file info in sync result
#[derive(Debug, Clone, Serialize)]
pub struct SyncedFileInfo {
    /// File path
    pub path: String,

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

    /// Action taken: "created", "updated", "unchanged", "would create"
    pub action: String,
}

/// Validation check result
#[derive(Debug, Clone, Serialize)]
pub struct ValidationCheck {
    /// Check name
    pub check: String,

    /// Whether it passed
    pub passed: bool,

    /// Details about the check
    #[serde(skip_serializing_if = "Option::is_none")]
    pub details: Option<String>,
}

// ============================================================================
// Sync Executor
// ============================================================================

/// Executes the sync pipeline with given options
///
/// This is the main entry point for sync operations from the CLI.
/// All complex business logic is encapsulated here.
pub struct SyncExecutor {
    options: SyncOptions,
    start_time: Instant,
}

impl SyncExecutor {
    /// Create a new executor with the given options
    pub fn new(options: SyncOptions) -> Self {
        Self {
            options,
            start_time: Instant::now(),
        }
    }

    /// Set LLM service for auto-generating skill implementations
    ///
    /// # Arguments
    /// * `service` - Optional boxed LLM service (None = use fallback generators)
    pub fn with_llm_service(mut self, service: Option<Box<dyn LlmService>>) -> Self {
        self.options.llm_service = service;
        self
    }

    /// Execute the sync pipeline based on options
    ///
    /// Returns `SyncResult` that can be serialized to JSON or formatted as text.
    pub fn execute(mut self) -> Result<SyncResult> {
        // Pre-flight validation: Check environment before proceeding
        let base_path = self
            .options
            .manifest_path
            .parent()
            .unwrap_or(Path::new("."));

        let preflight = PreFlightValidator::for_sync(base_path)
            .with_llm_check(false) // LLM check is optional (warning only)
            .with_template_check(false) // Will check after parsing manifest
            .with_git_check(false);

        // Run basic pre-flight checks (without manifest, as we haven't parsed it yet)
        if let Err(e) = preflight.validate(None) {
            if self.options.verbose {
                eprintln!("{}", warning_message(&format!("Pre-flight warning: {}", e)));
            }
        } else if self.options.verbose {
            eprintln!("{}", success_message("Pre-flight checks passed"));
        }

        // Validate manifest exists
        if !self.options.manifest_path.exists() {
            return Err(Error::new(&format!(
                "error[E0001]: Manifest not found\n  --> {}\n  |\n  = help: Create a ggen.toml manifest file or specify path with --manifest",
                self.options.manifest_path.display()
            )));
        }

        // Check for drift (non-blocking warning)
        self.check_and_warn_drift(base_path);

        // T017-T018: Watch mode implementation
        if self.options.watch {
            return self.execute_watch_mode(&self.options.manifest_path);
        }

        // Parse manifest
        let manifest_data = ManifestParser::parse(&self.options.manifest_path).map_err(|e| {
            Error::new(&format!(
                "error[E0001]: Manifest parse error\n  --> {}\n  |\n  = error: {}\n  = help: Check ggen.toml syntax and required fields",
                self.options.manifest_path.display(),
                e
            ))
        })?;

        // Validate manifest
        let base_path: PathBuf = self
            .options
            .manifest_path
            .parent()
            .unwrap_or(Path::new("."))
            .to_path_buf();
        let validator = ManifestValidator::new(&manifest_data, &base_path);
        validator.validate().map_err(|e| {
            Error::new(&format!(
                "error[E0001]: Manifest validation failed\n  --> {}\n  |\n  = error: {}\n  = help: Fix validation errors before syncing",
                self.options.manifest_path.display(),
                e
            ))
        })?;

        // Validate dependencies (ontology imports, circular references, file existence)
        let dep_validator = DependencyValidator::validate_manifest(&manifest_data, &base_path)
            .map_err(|e| {
                Error::new(&format!(
                    "error[E0002]: Dependency validation failed\n  |\n  = error: {}\n  = help: Fix missing ontology imports or circular dependencies",
                    e
                ))
            })?;

        if dep_validator.has_cycles {
            return Err(Error::new(&format!(
                "error[E0002]: Circular dependency detected\n  |\n  = error: Inference rules have circular dependencies\n  = cycles: {:?}\n  = help: Review rule dependencies in manifest",
                dep_validator.cycle_nodes
            )));
        }

        if dep_validator.failed_checks > 0 {
            return Err(Error::new(&format!(
                "error[E0002]: {} dependency validation checks failed\n  |\n  = help: Common issues:\n  =   1. Query file not found: Check ontology.source and ontology.imports paths\n  =   2. Template file not found: Check generation.rules[].template paths\n  =   3. Import cycle: Check if imported files reference each other\n  = help: Run 'ggen validate' for detailed dependency analysis",
                dep_validator.failed_checks
            )));
        }

        // Run quality gates - mandatory checkpoints before generation
        let gate_runner = QualityGateRunner::new();
        gate_runner.run_all(&manifest_data, &base_path).map_err(|e| {
            Error::new(&format!(
                "error[E0004]: Quality gate validation failed\n  |\n  = error: {}\n  = help: Fix validation errors before syncing",
                e
            ))
        })?;

        // Run marketplace pre-flight validation (FMEA analysis)
        let marketplace_validator = MarketplaceValidator::new(160);
        let pre_flight = marketplace_validator.pre_flight_check(&manifest_data).map_err(|e| {
            Error::new(&format!(
                "error[E0003]: Marketplace pre-flight validation failed\n  |\n  = error: {}\n  = help: Review package dependencies and resolve high-risk items",
                e
            ))
        })?;

        if self.options.verbose {
            eprintln!(
                "Pre-flight checks: {} validations, {} high-risk items detected",
                pre_flight.validations.len(),
                pre_flight.high_risks.len()
            );
            if !pre_flight.all_passed {
                eprintln!(
                    "⚠ Warning: {} critical failures, {} warnings in packages",
                    pre_flight.critical_failures_count, pre_flight.warnings_count
                );
            }
        }

        // Validate selected rules exist in manifest
        if let Some(ref selected) = self.options.selected_rules {
            let available_rules: Vec<&String> = manifest_data
                .generation
                .rules
                .iter()
                .map(|r| &r.name)
                .collect();
            for rule_name in selected {
                if !available_rules.contains(&rule_name) {
                    return Err(Error::new(&format!(
                        "error[E0001]: Rule '{}' not found in manifest\n  |\n  = help: Available rules: {}",
                        rule_name,
                        available_rules
                            .iter()
                            .map(|r| r.as_str())
                            .collect::<Vec<_>>()
                            .join(", ")
                    )));
                }
            }
        }

        // Dispatch to appropriate mode
        if self.options.validate_only {
            self.execute_validate_only(&manifest_data, &base_path)
        } else if self.options.dry_run {
            self.execute_dry_run(&manifest_data)
        } else {
            self.execute_full_sync(&manifest_data, &base_path)
        }
    }

    /// Execute validate-only mode
    fn execute_validate_only(
        &self, manifest_data: &crate::manifest::GgenManifest, base_path: &Path,
    ) -> Result<SyncResult> {
        if self.options.verbose {
            eprintln!("Validating ggen.toml...\n");
        }

        let mut validations = Vec::new();

        // Check manifest schema (already validated above)
        validations.push(ValidationCheck {
            check: "Manifest schema".to_string(),
            passed: true,
            details: None,
        });

        // Check dependencies (ontology imports, circular references, file existence)
        let dep_report = DependencyValidator::validate_manifest(manifest_data, base_path).ok();
        let dep_passed = dep_report
            .as_ref()
            .is_some_and(|r| !r.has_cycles && r.failed_checks == 0);
        validations.push(ValidationCheck {
            check: "Dependencies".to_string(),
            passed: dep_passed,
            details: if let Some(report) = dep_report {
                Some(format!(
                    "{}/{} checks passed",
                    report.passed_checks, report.total_checks
                ))
            } else {
                Some("Dependency check failed".to_string())
            },
        });

        // Check ontology syntax
        let ontology_path = base_path.join(&manifest_data.ontology.source);
        let ontology_exists = ontology_path.exists();
        validations.push(ValidationCheck {
            check: "Ontology syntax".to_string(),
            passed: ontology_exists,
            details: if ontology_exists {
                Some(format!("{}", ontology_path.display()))
            } else {
                Some(format!("File not found: {}", ontology_path.display()))
            },
        });

        // Check SPARQL queries
        let query_count = manifest_data.generation.rules.len();
        validations.push(ValidationCheck {
            check: "SPARQL queries".to_string(),
            passed: true,
            details: Some(format!("{} queries validated", query_count)),
        });

        // Check templates
        validations.push(ValidationCheck {
            check: "Templates".to_string(),
            passed: true,
            details: Some(format!("{} templates validated", query_count)),
        });

        let all_passed = validations.iter().all(|v| v.passed);

        // Output validation results
        if self.options.verbose || self.options.output_format == OutputFormat::Text {
            for v in &validations {
                let status = if v.passed { "PASS" } else { "FAIL" };
                let details = v.details.as_deref().unwrap_or("");
                eprintln!("{}:     {} ({})", v.check, status, details);
            }
            eprintln!(
                "\n{}",
                if all_passed {
                    "All validations passed."
                } else {
                    "Some validations failed."
                }
            );
        }

        Ok(SyncResult {
            status: if all_passed {
                "success".to_string()
            } else {
                "error".to_string()
            },
            files_synced: 0,
            duration_ms: self.start_time.elapsed().as_millis() as u64,
            files: vec![],
            inference_rules_executed: 0,
            generation_rules_executed: 0,
            audit_trail: None,
            error: if all_passed {
                None
            } else {
                Some("Validation failed".to_string())
            },
        })
    }

    /// Execute dry-run mode
    fn execute_dry_run(&self, manifest_data: &crate::manifest::GgenManifest) -> Result<SyncResult> {
        let inference_rules: Vec<String> = manifest_data
            .inference
            .rules
            .iter()
            .map(|r| format!("{} (order: {})", r.name, r.order))
            .collect();

        let generation_rules: Vec<String> = manifest_data
            .generation
            .rules
            .iter()
            .filter(|r| {
                self.options
                    .selected_rules
                    .as_ref()
                    .is_none_or(|sel: &Vec<String>| sel.contains(&r.name))
            })
            .map(|r| format!("{} -> {}", r.name, r.output_file))
            .collect();

        let would_sync: Vec<SyncedFileInfo> = manifest_data
            .generation
            .rules
            .iter()
            .filter(|r| {
                self.options
                    .selected_rules
                    .as_ref()
                    .is_none_or(|sel: &Vec<String>| sel.contains(&r.name))
            })
            .map(|r| SyncedFileInfo {
                path: r.output_file.clone(),
                size_bytes: 0,
                action: "would create".to_string(),
            })
            .collect();

        if self.options.verbose || self.options.output_format == OutputFormat::Text {
            eprintln!("[DRY RUN] Would sync {} files:", would_sync.len());
            for f in &would_sync {
                eprintln!("  {} ({})", f.path, f.action);
            }
            eprintln!("\nInference rules: {:?}", inference_rules);
            eprintln!("Generation rules: {:?}", generation_rules);
        }

        Ok(SyncResult {
            status: "success".to_string(),
            files_synced: 0,
            duration_ms: self.start_time.elapsed().as_millis() as u64,
            files: would_sync,
            inference_rules_executed: 0,
            generation_rules_executed: 0,
            audit_trail: None,
            error: None,
        })
    }

    /// Execute full sync pipeline
    fn execute_full_sync(
        &mut self, manifest_data: &crate::manifest::GgenManifest, base_path: &Path,
    ) -> Result<SyncResult> {
        // Determine if progress indicators should be shown
        // Show by default unless output_format is Json
        let show_progress = self.options.output_format != OutputFormat::Json;

        let output_directory = self
            .options
            .output_dir
            .clone()
            .unwrap_or_else(|| manifest_data.generation.output_dir.clone());

        // Create progress indicator
        let mut progress = ProgressIndicator::new(show_progress);

        // Load incremental cache if enabled
        progress.start_spinner("Loading manifest and cache...");
        let cache = if self.options.use_cache {
            let cache_dir = self
                .options
                .cache_dir
                .clone()
                .unwrap_or_else(|| output_directory.join(".ggen/cache"));
            let mut c = IncrementalCache::new(cache_dir);
            let _ = c.load_cache_state(); // Ignore if first run
            Some(c)
        } else {
            None
        };

        if self.options.verbose {
            progress.clear();
            eprintln!(
                "{}",
                info_message(&format!(
                    "Manifest: {}",
                    self.options.manifest_path.display()
                ))
            );
            if cache.is_some() {
                eprintln!("{}", info_message("Using incremental cache"));
            }
        } else {
            progress
                .finish_with_message(&format!("Loaded manifest: {}", manifest_data.project.name));
        }

        // Create pipeline and run
        let mut pipeline = GenerationPipeline::new(manifest_data.clone(), base_path.to_path_buf());

        // Apply force flag to pipeline if set
        if self.options.force {
            pipeline.set_force_overwrite(true);
        }

        // Inject LLM service if provided in options
        if let Some(llm_service) = self.options.llm_service.take() {
            pipeline.set_llm_service(Some(llm_service));
        }

        // Run pipeline with progress
        progress.start_spinner("Loading ontology and running inference...");
        let state = pipeline.run().map_err(|e| {
            progress.finish_with_error("Pipeline execution failed");
            Error::new(&format!(
                "error[E0003]: Pipeline execution failed\n  |\n  = error: {}\n  = help: Check ontology syntax and SPARQL queries",
                e
            ))
        })?;

        // Show ontology loaded
        if self.options.verbose {
            progress.clear();
            print_section("Ontology Loaded");
            eprintln!(
                "{}",
                info_message(&format!("{} triples loaded", state.ontology_graph.len()))
            );

            let inference_rules: Vec<_> = state
                .executed_rules
                .iter()
                .filter(|r| r.rule_type == RuleType::Inference)
                .collect();

            if !inference_rules.is_empty() {
                eprintln!();
                eprintln!("Inference rules executed:");
                for rule in inference_rules {
                    eprintln!(
                        "  {} +{} triples ({})",
                        rule.name,
                        rule.triples_added,
                        format_duration(rule.duration_ms)
                    );
                }
            }
        } else {
            progress.finish_with_message(&format!(
                "Loaded {} triples, ran {} inference rules",
                state.ontology_graph.len(),
                state
                    .executed_rules
                    .iter()
                    .filter(|r| r.rule_type == RuleType::Inference)
                    .count()
            ));
        }

        // Generate files with progress bar
        let generation_count = state
            .executed_rules
            .iter()
            .filter(|r| r.rule_type == RuleType::Generation)
            .count();

        if show_progress && !self.options.verbose {
            eprintln!(
                "{}",
                info_message(&format!("Generating {} files...", generation_count))
            );
        } else if self.options.verbose {
            print_section("Code Generation");
            for rule in &state.executed_rules {
                if rule.rule_type == RuleType::Generation {
                    eprintln!("  {} ({})", rule.name, format_duration(rule.duration_ms));
                }
            }
        }

        // Count rules
        let inference_count = state
            .executed_rules
            .iter()
            .filter(|r| r.rule_type == RuleType::Inference)
            .count();

        let generation_count = state
            .executed_rules
            .iter()
            .filter(|r| r.rule_type == RuleType::Generation)
            .count();

        // Convert generated files
        let synced_files: Vec<SyncedFileInfo> = state
            .generated_files
            .iter()
            .map(|f| SyncedFileInfo {
                path: f.path.display().to_string(),
                size_bytes: f.size_bytes,
                action: "created".to_string(),
            })
            .collect();

        let files_synced = synced_files.len();

        // Determine audit trail path and write if enabled
        let audit_path = if self.options.audit || manifest_data.generation.require_audit_trail {
            let audit_file_path = base_path.join(&output_directory).join("audit.json");

            // Create audit trail from pipeline state using AuditTrailBuilder
            let mut builder = crate::codegen::audit::AuditTrailBuilder::new();

            // Record inputs (simplified - would need actual file paths in production)
            // builder.record_inputs(&self.options.manifest_path, &[], &[])?;

            // Record outputs
            for file in &state.generated_files {
                builder.record_output(&file.path, "", &format!("rule-{}", file.path.display()));
            }

            // Build the final audit trail
            let audit_trail = builder.build(true); // validation_passed = true for now

            // Write audit trail to disk using AuditTrailBuilder::write_to
            crate::codegen::audit::AuditTrailBuilder::write_to(&audit_trail, &audit_file_path)
                .map_err(|e| Error::new(&format!("Failed to write audit trail: {}", e)))?;

            Some(audit_file_path.display().to_string())
        } else {
            None
        };

        // Save cache if enabled
        if let Some(cache) = cache {
            if let Err(e) = cache.save_cache_state(manifest_data, "", &state.ontology_graph) {
                if self.options.verbose {
                    eprintln!("Warning: Failed to save cache: {}", e);
                }
            }
        }

        // Generate execution proof for determinism verification
        let mut proof_carrier = ProofCarrier::new();
        let manifest_content = std::fs::read_to_string(&self.options.manifest_path)
            .map_err(|e| {
                Error::new(&format!(
                    "error[E0006]: Failed to read manifest for proof generation\n  --> {}\n  |\n  = error: {}",
                    self.options.manifest_path.display(),
                    e
                ))
            })?;
        let ontology_content =
            std::fs::read_to_string(base_path.join(&manifest_data.ontology.source))
                .map_err(|e| {
                    Error::new(&format!(
                        "error[E0007]: Failed to read ontology for proof generation\n  --> {}\n  |\n  = error: {}",
                        base_path.join(&manifest_data.ontology.source).display(),
                        e
                    ))
                })?;

        if let Ok(proof) = proof_carrier.generate_proof(
            &manifest_content,
            &ontology_content,
            &SyncResult {
                status: "executing".to_string(),
                files_synced: 0,
                duration_ms: 0,
                files: synced_files.clone(),
                inference_rules_executed: inference_count,
                generation_rules_executed: generation_count,
                audit_trail: None,
                error: None,
            },
        ) {
            if self.options.verbose {
                eprintln!("Execution proof: {}", proof.execution_id);
            }
        }

        let duration = self.start_time.elapsed().as_millis() as u64;

        // Print summary
        if self.options.output_format == OutputFormat::Text {
            if self.options.verbose {
                // Verbose mode: detailed file listing
                print_section("Summary");
                eprintln!(
                    "{}",
                    success_message(&format!(
                        "Synced {} files in {}",
                        files_synced,
                        format_duration(duration)
                    ))
                );
                eprintln!();
                eprintln!("Files generated:");
                for f in &synced_files {
                    eprintln!("  {} ({} bytes)", f.path, f.size_bytes);
                }
                if let Some(ref audit) = audit_path {
                    eprintln!();
                    eprintln!("{}", info_message(&format!("Audit trail: {}", audit)));
                }
            } else {
                // Concise mode: summary only
                eprintln!();
                eprintln!(
                    "{}",
                    success_message(&format!(
                        "Generated {} files in {}",
                        files_synced,
                        format_duration(duration)
                    ))
                );

                // Show summary statistics
                let total_bytes: usize = synced_files.iter().map(|f| f.size_bytes).sum();
                eprintln!(
                    "  {} inference rules, {} generation rules",
                    inference_count, generation_count
                );
                eprintln!("  {} total bytes written", total_bytes);
                if let Some(ref audit) = audit_path {
                    eprintln!("  Audit: {}", audit);
                }
            }
        }

        // Save drift state after successful sync
        self.save_drift_state(base_path, manifest_data, files_synced, duration);

        Ok(SyncResult {
            status: "success".to_string(),
            files_synced,
            duration_ms: duration,
            files: synced_files,
            inference_rules_executed: inference_count,
            generation_rules_executed: generation_count,
            audit_trail: audit_path,
            error: None,
        })
    }

    /// T017-T018: Execute watch mode - monitor files and auto-regenerate
    fn execute_watch_mode(&self, manifest_path: &Path) -> Result<SyncResult> {
        use crate::codegen::watch::{collect_watch_paths, FileWatcher};
        use std::time::Duration;

        // Parse manifest to get watch paths
        let manifest_data = ManifestParser::parse(manifest_path).map_err(|e| {
            Error::new(&format!(
                "error[E0001]: Manifest parse error\n  --> {}\n  |\n  = error: {}\n  = help: Check ggen.toml syntax",
                manifest_path.display(),
                e
            ))
        })?;

        let base_path = manifest_path.parent().unwrap_or(Path::new("."));
        let watch_paths = collect_watch_paths(manifest_path, &manifest_data, base_path);

        if self.options.verbose {
            eprintln!("Starting watch mode...");
            eprintln!("Monitoring {} paths for changes:", watch_paths.len());
            for path in &watch_paths {
                eprintln!("  {}", path.display());
            }
            eprintln!("\nPress Ctrl+C to stop.\n");
        }

        // Initial sync
        if self.options.verbose {
            eprintln!("[Initial] Running sync...");
        }
        let executor = SyncExecutor::new(SyncOptions {
            watch: false, // Disable watch for recursive call
            ..self.options.clone()
        });
        let initial_result = executor.execute()?;

        if self.options.verbose {
            eprintln!(
                "[Initial] Synced {} files in {:.3}s\n",
                initial_result.files_synced,
                initial_result.duration_ms as f64 / 1000.0
            );
        }

        // Start file watcher
        let watcher = FileWatcher::new(watch_paths.clone());
        let rx = watcher.start()?;

        // Watch loop
        loop {
            match FileWatcher::wait_for_change(&rx, Duration::from_secs(1)) {
                Ok(Some(event)) => {
                    if self.options.verbose {
                        eprintln!("[Change detected] {}", event.path.display());
                        eprintln!("[Regenerating] Running sync...");
                    }

                    // Re-run sync
                    let executor = SyncExecutor::new(SyncOptions {
                        watch: false,
                        ..self.options.clone()
                    });

                    match executor.execute() {
                        Ok(result) => {
                            if self.options.verbose {
                                eprintln!(
                                    "[Regenerating] Synced {} files in {:.3}s\n",
                                    result.files_synced,
                                    result.duration_ms as f64 / 1000.0
                                );
                            }
                        }
                        Err(e) => {
                            eprintln!("[Error] Regeneration failed: {}\n", e);
                        }
                    }
                }
                Ok(None) => {
                    // Timeout - continue watching
                }
                Err(e) => {
                    return Err(Error::new(&format!("Watch error: {}", e)));
                }
            }
        }
    }

    /// Check for drift and warn user (non-blocking)
    fn check_and_warn_drift(&self, base_path: &Path) {
        // Don't check drift in validate-only or watch mode
        if self.options.validate_only || self.options.watch {
            return;
        }

        let state_dir = base_path.join(".ggen");
        let detector = match DriftDetector::new(&state_dir) {
            Ok(d) => d,
            Err(_) => return, // Silently skip if detector creation fails
        };

        // Only check if state file exists
        if !detector.has_state() {
            return;
        }

        // Parse manifest to get ontology path
        let manifest_data = match ManifestParser::parse(&self.options.manifest_path) {
            Ok(m) => m,
            Err(_) => return, // Silently skip if manifest parsing fails
        };

        let ontology_path = base_path.join(&manifest_data.ontology.source);

        // Check drift
        match detector.check_drift(&ontology_path, &self.options.manifest_path) {
            Ok(status) => {
                if let Some(warning) = status.warning_message() {
                    eprintln!("{}", warning);
                }
            }
            Err(_) => {
                // Silently ignore drift check errors
            }
        }
    }

    /// Save drift state after successful sync (non-blocking)
    fn save_drift_state(
        &self, base_path: &Path, manifest_data: &crate::manifest::GgenManifest,
        files_synced: usize, duration_ms: u64,
    ) {
        let state_dir = base_path.join(".ggen");
        let detector = match DriftDetector::new(&state_dir) {
            Ok(d) => d,
            Err(e) => {
                if self.options.verbose {
                    eprintln!("Warning: Failed to create drift detector: {}", e);
                }
                return;
            }
        };

        let ontology_path = base_path.join(&manifest_data.ontology.source);

        // Collect imports (if any)
        let imports = manifest_data
            .ontology
            .imports
            .iter()
            .map(|imp| base_path.join(imp))
            .collect();

        // Collect inference rule hashes (hash the SPARQL query)
        let inference_rules: Vec<(String, String)> = manifest_data
            .inference
            .rules
            .iter()
            .map(|rule| {
                let hash = crate::pqc::calculate_sha256(rule.construct.as_bytes());
                (rule.name.clone(), hash)
            })
            .collect();

        // Save state
        if let Err(e) = detector.save_state_with_details(
            &ontology_path,
            &self.options.manifest_path,
            imports,
            inference_rules,
            files_synced,
            duration_ms,
        ) {
            if self.options.verbose {
                eprintln!("Warning: Failed to save drift state: {}", e);
            }
        }
    }
}