xchecker-engine 1.2.0

Core orchestration engine for xchecker phase execution
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
//! Orchestrator façade for external consumers.
//!
//! This module provides a clean, stable API for external consumers (CLI, Kiro, MCP tools)
//! to interact with the phase orchestrator without needing to know internal details.
//!
//! **Integration rule**: Outside `src/orchestrator/`, use `OrchestratorHandle`.
//! Direct `PhaseOrchestrator` usage is reserved for tests and orchestrator internals.
//!
//! # Quick Start
//!
//! ```rust,no_run
//! use xchecker_engine::orchestrator::OrchestratorHandle;
//! use xchecker_engine::types::PhaseId;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     // Using environment-based config discovery
//!     let mut handle = OrchestratorHandle::new("my-spec")?;
//!     handle.run_phase(PhaseId::Requirements).await?;
//!     Ok(())
//! }
//! ```

use std::path::PathBuf;

use anyhow::Result;

use crate::config::{CliArgs, Config};
use crate::error::{ConfigError, XCheckerError};
use crate::receipt::ReceiptManager;
use crate::spec_id::sanitize_spec_id;
use crate::status::artifact::ArtifactManager;
use crate::types::{PhaseId, StatusOutput};

use super::{ExecutionResult, OrchestratorConfig, PhaseOrchestrator};

/// The primary public API for embedding xchecker.
///
/// `OrchestratorHandle` provides a stable interface for creating specs and running
/// phases programmatically. It is the canonical way to use xchecker outside of the CLI.
///
/// # Overview
///
/// Use `OrchestratorHandle` to:
/// - Create and manage specs programmatically
/// - Execute individual phases or the full workflow
/// - Query spec status and artifacts
/// - Configure execution options
///
/// # Construction
///
/// There are two ways to create an `OrchestratorHandle`:
///
/// - [`OrchestratorHandle::new`]: Uses environment-based config discovery (same as CLI)
/// - [`OrchestratorHandle::from_config`]: Uses explicit configuration (deterministic)
///
/// # Threading
///
/// `OrchestratorHandle` is **NOT** guaranteed `Send` or `Sync` in 1.x.
/// Treat as single-threaded; concurrent use is undefined behavior.
/// This may be relaxed in future versions.
///
/// # Mutability
///
/// Methods that execute phases take `&mut self` to encode "sequential use only"
/// semantics. This prevents accidental concurrent use at compile time.
///
/// # Sync vs Async
///
/// Public APIs are synchronous and manage their own async runtime internally.
/// Tokio is an implementation detail not exposed to library consumers.
///
/// # Example
///
/// ```rust,no_run
/// use xchecker_engine::orchestrator::OrchestratorHandle;
/// use xchecker_engine::types::PhaseId;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     // Using environment-based config discovery
///     let mut handle = OrchestratorHandle::new("my-spec")?;
///
///     // Run a single phase
///     handle.run_phase(PhaseId::Requirements).await?;
///
///     // Check status
///     let status = handle.status()?;
///     println!("Artifacts: {}", status.artifacts.len());
///
///     // Get the spec ID
///     println!("Spec: {}", handle.spec_id());
///     Ok(())
/// }
/// ```
///
/// # Using Explicit Configuration
///
/// ```rust,no_run
/// use xchecker_engine::config::Config;
/// use xchecker_engine::orchestrator::OrchestratorHandle;
///
/// // Create explicit config programmatically
/// let config = Config::discover(&Default::default())?;
/// let handle = OrchestratorHandle::from_config("my-spec", config)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// # Error Handling
///
/// All methods return `Result` types. Errors are returned as [`XCheckerError`]
/// which provides:
/// - Rich context about what went wrong
/// - Actionable suggestions for resolution
/// - Mapping to CLI exit codes via [`XCheckerError::to_exit_code`]
pub struct OrchestratorHandle {
    orchestrator: PhaseOrchestrator,
    config: OrchestratorConfig,
    spec_id: String,
}

impl OrchestratorHandle {
    /// Create a handle using environment-based config discovery.
    ///
    /// This uses the same discovery logic as the CLI:
    /// - `XCHECKER_HOME` environment variable
    /// - Upward search for `.xchecker/config.toml`
    /// - Built-in defaults
    ///
    /// Acquires an exclusive lock on the spec directory.
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// - Configuration discovery fails
    /// - Orchestrator creation fails
    /// - Lock cannot be acquired
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use xchecker_engine::orchestrator::OrchestratorHandle;
    ///
    /// let handle = OrchestratorHandle::new("my-spec")?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn new(spec_id: &str) -> Result<Self, XCheckerError> {
        // Use environment-based config discovery (same as CLI)
        let config = Config::discover(&CliArgs::default())?;

        Self::from_config_internal(spec_id, config, false)
    }

    /// Create a handle using explicit configuration.
    ///
    /// This does NOT probe the global environment or filesystem for config.
    /// Use this when you need deterministic behavior independent of the
    /// user's environment.
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// - Orchestrator creation fails
    /// - Lock cannot be acquired
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use xchecker_engine::config::Config;
    /// use xchecker_engine::orchestrator::OrchestratorHandle;
    ///
    /// // Create explicit config programmatically
    /// let config = Config::discover(&Default::default())?;
    /// let handle = OrchestratorHandle::from_config("my-spec", config)?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn from_config(spec_id: &str, config: Config) -> Result<Self, XCheckerError> {
        Self::from_config_internal(spec_id, config, false)
    }

    /// Internal constructor that converts Config to OrchestratorConfig
    fn from_config_internal(
        spec_id: &str,
        config: Config,
        force: bool,
    ) -> Result<Self, XCheckerError> {
        // Sanitize spec ID to prevent path traversal and invalid characters
        let sanitized_id = sanitize_spec_id(spec_id).map_err(|e| {
            XCheckerError::Config(ConfigError::InvalidValue {
                key: "spec_id".to_string(),
                value: e.to_string(),
            })
        })?;

        let redactor = crate::redaction::SecretRedactor::from_config(&config).map_err(
            |e: anyhow::Error| {
                XCheckerError::Config(ConfigError::InvalidValue {
                    key: "security".to_string(),
                    value: e.to_string(),
                })
            },
        )?;

        let orchestrator = if force {
            PhaseOrchestrator::new_with_force(&sanitized_id, true)
        } else {
            PhaseOrchestrator::new(&sanitized_id)
        }
        .map_err(|e| {
            XCheckerError::Config(crate::error::ConfigError::DiscoveryFailed {
                reason: e.to_string(),
            })
        })?;

        // Convert Config to OrchestratorConfig
        let mut orch_config = OrchestratorConfig {
            redactor: std::sync::Arc::new(redactor),
            full_config: Some(config.clone()),
            hooks: Some(config.hooks.clone()),
            ..Default::default()
        };

        // Apply config values to orchestrator config
        if let Some(packet_max_bytes) = config.defaults.packet_max_bytes {
            orch_config
                .config
                .insert("packet_max_bytes".to_string(), packet_max_bytes.to_string());
        }
        if let Some(packet_max_lines) = config.defaults.packet_max_lines {
            orch_config
                .config
                .insert("packet_max_lines".to_string(), packet_max_lines.to_string());
        }
        if let Some(max_turns) = config.defaults.max_turns {
            orch_config
                .config
                .insert("max_turns".to_string(), max_turns.to_string());
        }
        if let Some(model) = &config.defaults.model {
            orch_config
                .config
                .insert("model".to_string(), model.clone());
        }
        if let Some(output_format) = &config.defaults.output_format {
            orch_config
                .config
                .insert("output_format".to_string(), output_format.clone());
        }
        if let Some(timeout) = config.defaults.phase_timeout {
            orch_config
                .config
                .insert("phase_timeout".to_string(), timeout.to_string());
        }
        if let Some(stdout_cap_bytes) = config.defaults.stdout_cap_bytes {
            orch_config
                .config
                .insert("stdout_cap_bytes".to_string(), stdout_cap_bytes.to_string());
        }
        if let Some(stderr_cap_bytes) = config.defaults.stderr_cap_bytes {
            orch_config
                .config
                .insert("stderr_cap_bytes".to_string(), stderr_cap_bytes.to_string());
        }
        if let Some(lock_ttl_seconds) = config.defaults.lock_ttl_seconds {
            orch_config
                .config
                .insert("lock_ttl_seconds".to_string(), lock_ttl_seconds.to_string());
        }
        if let Some(debug_packet) = config.defaults.debug_packet
            && debug_packet
        {
            orch_config
                .config
                .insert("debug_packet".to_string(), "true".to_string());
        }
        if let Some(allow_links) = config.defaults.allow_links
            && allow_links
        {
            orch_config
                .config
                .insert("allow_links".to_string(), "true".to_string());
        }
        if let Some(runner_mode) = &config.runner.mode {
            orch_config
                .config
                .insert("runner_mode".to_string(), runner_mode.clone());
        }
        if let Some(runner_distro) = &config.runner.distro {
            orch_config
                .config
                .insert("runner_distro".to_string(), runner_distro.clone());
        }
        if let Some(claude_path) = &config.runner.claude_path {
            orch_config
                .config
                .insert("claude_path".to_string(), claude_path.clone());
        }
        if let Some(provider) = &config.llm.provider {
            orch_config
                .config
                .insert("llm_provider".to_string(), provider.clone());
        }
        if let Some(fallback_provider) = &config.llm.fallback_provider {
            orch_config.config.insert(
                "llm_fallback_provider".to_string(),
                fallback_provider.clone(),
            );
        }
        if let Some(execution_strategy) = &config.llm.execution_strategy {
            orch_config
                .config
                .insert("execution_strategy".to_string(), execution_strategy.clone());
        }
        if let Some(prompt_template) = &config.llm.prompt_template {
            orch_config
                .config
                .insert("prompt_template".to_string(), prompt_template.clone());
        }
        if let Some(claude_config) = &config.llm.claude
            && let Some(binary) = &claude_config.binary
        {
            orch_config
                .config
                .insert("llm_claude_binary".to_string(), binary.clone());
        }
        if let Some(gemini_config) = &config.llm.gemini {
            if let Some(binary) = &gemini_config.binary {
                orch_config
                    .config
                    .insert("llm_gemini_binary".to_string(), binary.clone());
            }
            if let Some(default_model) = &gemini_config.default_model {
                orch_config.config.insert(
                    "llm_gemini_default_model".to_string(),
                    default_model.clone(),
                );
            }
        }
        orch_config.strict_validation = config.strict_validation();

        // Copy selectors
        orch_config.selectors = Some(config.selectors.clone());

        Ok(Self {
            orchestrator,
            config: orch_config,
            spec_id: sanitized_id,
        })
    }

    /// Create a handle with force flag for lock override.
    ///
    /// Use with caution: forcing lock override can lead to race conditions if another
    /// process is actively working on the spec.
    ///
    /// # Errors
    ///
    /// Returns error if orchestrator creation fails.
    pub fn with_force(spec_id: &str, force: bool) -> Result<Self, XCheckerError> {
        let config = Config::discover(&CliArgs::default())?;

        Self::from_config_internal(spec_id, config, force)
    }

    /// Create a handle with custom OrchestratorConfig and force flag.
    ///
    /// This is used by the CLI when it needs to pass specific orchestrator
    /// configuration options.
    ///
    /// # Errors
    ///
    /// Returns error if orchestrator creation fails.
    pub fn with_config_and_force(
        spec_id: &str,
        config: OrchestratorConfig,
        force: bool,
    ) -> Result<Self, XCheckerError> {
        // Sanitize spec ID
        let sanitized_id = sanitize_spec_id(spec_id).map_err(|e| {
            XCheckerError::Config(ConfigError::InvalidValue {
                key: "spec_id".to_string(),
                value: e.to_string(),
            })
        })?;

        let orchestrator = if force {
            PhaseOrchestrator::new_with_force(&sanitized_id, true)
        } else {
            PhaseOrchestrator::new(&sanitized_id)
        }
        .map_err(|e| {
            XCheckerError::Config(crate::error::ConfigError::DiscoveryFailed {
                reason: e.to_string(),
            })
        })?;

        Ok(Self {
            orchestrator,
            config,
            spec_id: sanitized_id,
        })
    }

    /// Create a read-only handle for status inspection.
    ///
    /// Does not acquire locks, allowing inspection while another process
    /// is actively working on the spec.
    ///
    /// # Errors
    ///
    /// Returns error if orchestrator creation fails.
    pub fn readonly(spec_id: &str) -> Result<Self, XCheckerError> {
        // Sanitize spec ID
        let sanitized_id = sanitize_spec_id(spec_id).map_err(|e| {
            XCheckerError::Config(ConfigError::InvalidValue {
                key: "spec_id".to_string(),
                value: e.to_string(),
            })
        })?;

        let orchestrator = PhaseOrchestrator::new_readonly(&sanitized_id).map_err(|e| {
            XCheckerError::Config(crate::error::ConfigError::DiscoveryFailed {
                reason: e.to_string(),
            })
        })?;

        let config = OrchestratorConfig::default();

        Ok(Self {
            orchestrator,
            config,
            spec_id: sanitized_id,
        })
    }

    /// Execute a single phase.
    ///
    /// Behavior matches the CLI `xchecker resume --phase <phase>` command.
    /// Takes `&mut self` to enforce sequential use.
    ///
    /// # Errors
    ///
    /// Returns error if transition is invalid or execution fails.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use xchecker_engine::orchestrator::OrchestratorHandle;
    /// use xchecker_engine::types::PhaseId;
    ///
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut handle = OrchestratorHandle::new("my-spec")?;
    /// handle.run_phase(PhaseId::Requirements).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn run_phase(&mut self, phase: PhaseId) -> Result<ExecutionResult> {
        self.orchestrator
            .resume_from_phase(phase, &self.config)
            .await
    }

    /// Execute all phases in sequence.
    ///
    /// Stops on first failure. Behavior matches the CLI `xchecker spec` command.
    /// Takes `&mut self` to enforce sequential use.
    ///
    /// # Errors
    ///
    /// Returns error if any phase fails.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use xchecker_engine::orchestrator::OrchestratorHandle;
    ///
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut handle = OrchestratorHandle::new("my-spec")?;
    /// handle.run_all().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn run_all(&mut self) -> Result<ExecutionResult> {
        // Execute phases in sequence: Requirements -> Design -> Tasks
        // (Review, Fixup, Final are optional/advanced phases)
        let phases = [PhaseId::Requirements, PhaseId::Design, PhaseId::Tasks];

        let mut last_result = None;
        for phase in phases {
            let result = self
                .orchestrator
                .resume_from_phase(phase, &self.config)
                .await?;

            if !result.success {
                return Ok(result);
            }
            last_result = Some(result);
        }

        // Return the last successful result
        last_result.ok_or_else(|| anyhow::anyhow!("No phases executed"))
    }

    /// Get the current spec status.
    ///
    /// Returns `StatusOutput` which is part of the stable public API.
    ///
    /// # Errors
    ///
    /// Returns error if status generation fails.
    pub fn status(&self) -> Result<StatusOutput, XCheckerError> {
        use std::collections::BTreeMap;

        let mut effective_config: BTreeMap<String, (String, String)> = self
            .config
            .full_config
            .as_ref()
            .map(|config| config.effective_config().into_iter().collect())
            .unwrap_or_default();

        // Merge any programmatic overrides (e.g., set_config) without losing source attribution.
        for (key, value) in &self.config.config {
            let override_needed = match effective_config.get(key) {
                Some((existing_value, _)) => existing_value != value,
                None => true,
            };
            if override_needed {
                effective_config.insert(key.clone(), (value.clone(), "programmatic".to_string()));
            }
        }

        crate::status::status::StatusManager::generate_status_internal(
            self.orchestrator.artifact_manager(),
            self.orchestrator.receipt_manager(),
            effective_config,
            None,
            None,
            Some(&self.config.redactor),
        )
        .map_err(|e| {
            XCheckerError::Config(ConfigError::DiscoveryFailed {
                reason: format!("Failed to generate status: {e}"),
            })
        })
    }

    /// Get the path to the most recent receipt.
    ///
    /// Returns `None` if no receipts have been written.
    #[must_use]
    pub fn last_receipt_path(&self) -> Option<PathBuf> {
        // Check each phase in reverse order to find the most recent receipt
        let phases = [
            PhaseId::Final,
            PhaseId::Fixup,
            PhaseId::Review,
            PhaseId::Tasks,
            PhaseId::Design,
            PhaseId::Requirements,
        ];

        for phase in &phases {
            if let Ok(Some(_receipt)) = self
                .orchestrator
                .receipt_manager()
                .read_latest_receipt(*phase)
            {
                // Construct the receipt path from the receipt manager's base path
                let base_path = self.orchestrator.artifact_manager().base_path();
                let receipts_dir = base_path.join("receipts");

                // Find the most recent receipt file for this phase
                if let Ok(entries) = std::fs::read_dir(&receipts_dir) {
                    let phase_prefix = format!("{}-", phase.as_str());
                    let mut receipt_files: Vec<_> = entries
                        .filter_map(|e| e.ok())
                        .filter(|e| e.file_name().to_string_lossy().starts_with(&phase_prefix))
                        .collect();

                    // Sort by name (timestamp-based) to get the most recent
                    receipt_files.sort_by_key(|b| std::cmp::Reverse(b.file_name()));

                    if let Some(entry) = receipt_files.first() {
                        return Some(entry.path());
                    }
                }
            }
        }

        None
    }

    /// Get the spec ID this handle operates on.
    #[must_use]
    pub fn spec_id(&self) -> &str {
        &self.spec_id
    }

    /// Check if a phase can be run.
    ///
    /// Validates that all dependencies are satisfied and have successful receipts.
    ///
    /// # Returns
    ///
    /// `true` if the phase can be executed, `false` otherwise.
    pub fn can_run_phase(&self, phase: PhaseId) -> Result<bool> {
        self.orchestrator.can_resume_from_phase_public(phase)
    }

    /// Get the current phase state.
    ///
    /// Returns the last successfully completed phase, or `None` if no phases
    /// have been completed.
    pub fn current_phase(&self) -> Result<Option<PhaseId>> {
        self.orchestrator.get_current_phase_state()
    }

    /// Get legal next phases from current state.
    ///
    /// Returns a list of phases that can be validly executed based on
    /// the current workflow state.
    pub fn legal_next_phases(&self) -> Result<Vec<PhaseId>> {
        let current = self.current_phase()?;
        Ok(match current {
            None => vec![PhaseId::Requirements],
            Some(PhaseId::Requirements) => vec![PhaseId::Requirements, PhaseId::Design],
            Some(PhaseId::Design) => vec![PhaseId::Design, PhaseId::Tasks],
            Some(PhaseId::Tasks) => vec![PhaseId::Tasks, PhaseId::Review, PhaseId::Final],
            Some(PhaseId::Review) => vec![PhaseId::Review, PhaseId::Fixup, PhaseId::Final],
            Some(PhaseId::Fixup) => vec![PhaseId::Fixup, PhaseId::Final],
            Some(PhaseId::Final) => vec![PhaseId::Final],
        })
    }

    /// Set a configuration option.
    ///
    /// Common keys include:
    /// - `model`: LLM model to use
    /// - `phase_timeout`: Timeout in seconds
    /// - `apply_fixups`: Whether to apply fixups or preview
    pub fn set_config(&mut self, key: &str, value: &str) {
        self.config
            .config
            .insert(key.to_string(), value.to_string());
    }

    /// Get a configuration option.
    ///
    /// Returns `None` if the key is not set.
    #[must_use]
    pub fn get_config(&self, key: &str) -> Option<&String> {
        self.config.config.get(key)
    }

    /// Enable or disable dry-run mode.
    ///
    /// In dry-run mode, phases are simulated without calling the LLM.
    pub fn set_dry_run(&mut self, dry_run: bool) {
        self.config.dry_run = dry_run;
    }

    /// Get the current orchestrator configuration.
    ///
    /// Returns a reference to the configuration used for phase execution.
    #[must_use]
    pub fn orchestrator_config(&self) -> &OrchestratorConfig {
        &self.config
    }

    /// Access the artifact manager for status queries.
    ///
    /// Use this for read-only operations like checking phase completion,
    /// listing artifacts, or getting the base path.
    #[must_use]
    #[doc(hidden)]
    pub fn artifact_manager(&self) -> &ArtifactManager {
        self.orchestrator.artifact_manager()
    }

    /// Access the receipt manager for status queries.
    ///
    /// Use this for read-only operations like listing receipts or
    /// getting receipt metadata.
    #[must_use]
    #[doc(hidden)]
    pub fn receipt_manager(&self) -> &ReceiptManager {
        self.orchestrator.receipt_manager()
    }

    /// Get a reference to the underlying orchestrator.
    ///
    /// This is primarily for interop with APIs that require `&PhaseOrchestrator`,
    /// such as `StatusManager::generate_status_from_orchestrator`.
    ///
    /// Prefer using the high-level methods on `OrchestratorHandle` when possible.
    #[must_use]
    #[doc(hidden)]
    pub fn as_orchestrator(&self) -> &PhaseOrchestrator {
        &self.orchestrator
    }
}

// Implement SpecDataProvider trait for gate module
impl xchecker_gate::SpecDataProvider for &OrchestratorHandle {
    fn base_path(&self) -> &std::path::Path {
        self.orchestrator
            .artifact_manager()
            .base_path()
            .as_std_path()
    }

    fn spec_id(&self) -> &str {
        &self.spec_id
    }

    fn receipt_manager(&self) -> &xchecker_receipt::ReceiptManager {
        self.orchestrator.receipt_manager()
    }

    fn phase_completed(&self, phase: xchecker_utils::types::PhaseId) -> bool {
        self.orchestrator.artifact_manager().phase_completed(phase)
    }

    fn pending_fixups_result(&self) -> xchecker_gate::PendingFixupsResult {
        use crate::fixup::pending_fixups_result_from_handle;
        pending_fixups_result_from_handle(self)
    }
}