convert-rs 0.2.0

Extensible file conversion library with graph routing and optional native tools
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
//! Adapter registry, route execution, and per-step output validation.
//!
//! Every step receives a private output directory, and every artifact an adapter
//! returns is checked: regular file, inside its step directory, declared
//! format matches the step target, and total bytes respect the budget. A step
//! that fails validation abandons the route and the engine tries the next.
//! The workspace is a file ownership boundary, not an execution sandbox.

use std::collections::BTreeMap;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use tempfile::TempDir;

use crate::{
    Adapter, Artifact, BackendStatus, ConversionKind, Error, Format, Graph, Limits, Plan, Policy,
    Result, StepRequest,
};

use crate::builtin::{BuiltinAdapter, detect};

#[cfg(feature = "archives")]
use crate::archives::ArchivesAdapter;
#[cfg(feature = "media")]
use crate::media::MediaAdapter;

/// Per-conversion identification and route-selection choices.
///
/// Defaults use file identification and normal planning without a backend filter.
/// These options do not select codecs, bitrates, or encoder quality settings.
/// Resource budgets are configured separately through [`Converter::limits`].
#[derive(Clone, Debug, Default)]
pub struct ConversionOptions {
    /// Override format identification for every input (a format ID or extension).
    ///
    /// Skips content identification, including its empty-file rejection. Staging
    /// still requires regular files within the per-file input budget. This is a
    /// caller assertion, not a content validation request.
    pub from: Option<String>,
    /// Require every executed step to use this backend.
    ///
    /// Normal planning first finds a bounded set of routes, then filters it; a
    /// matching route outside that set is not searched for. Identity plans have
    /// no steps and pass any backend filter. Forced plans are checked step by step.
    pub backend: Option<String>,
    /// Skip route search and attempt only this caller-supplied plan.
    ///
    /// Prefer a plan obtained from [`Converter::plan`]. Steps must have concrete
    /// format IDs. Execution checks kind gates, the `external` flag against
    /// [`Policy::allow_external`], backend filtering, format continuity, and
    /// returned artifacts. It does not verify edge membership in the graph,
    /// recompute cost, enforce search budgets or decode-only gates, or apply
    /// [`Policy::allow_external_packaging`]. Metadata is trusted: forced plans
    /// are not a safe boundary for untrusted callers.
    pub forced_plan: Option<Plan>,
}

/// An informational warning derived from an executed step's declared kind.
///
/// The engine emits one warning for each non-lossless step of the successful
/// route, including packaging and extraction. It does not measure actual loss
/// or collect every adapter diagnostic. Failed attempts' warnings are discarded.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Warning {
    /// Zero-based index into the successful report's plan, not an artifact index.
    pub step: usize,
    /// Adapter that executed the step.
    pub backend: String,
    /// Adapter operation ID.
    pub operation: String,
    /// Adapter-declared semantic classification of the step.
    pub kind: ConversionKind,
    /// Explanation suitable for logs or a user interface.
    pub message: String,
}

/// A resolved conversion: the accepted route, its warnings, and the artifacts.
///
/// Artifacts live in a private directory owned by this report. Dropping the
/// report deletes them, so copy final files out before the report is dropped.
/// Moving or cloning artifact paths does not transfer workspace ownership.
/// Reports include only the successful attempt; earlier route failures and
/// adapter stderr are not exposed as a structured attempt log.
#[derive(Debug)]
pub struct ConversionReport {
    workspace: TempDir,
    /// Route selected and executed by the converter, or the supplied forced plan.
    pub plan: Plan,
    /// Final artifacts, in adapter output order, or input order for identity copies.
    ///
    /// Format labels were checked against the target, not independently decoded.
    /// The engine currently permits an adapter to return an empty vector.
    pub artifacts: Vec<Artifact>,
    /// One warning per non-lossless step in this report's plan.
    ///
    /// An empty list is not a guarantee of complete quality or metadata preservation.
    pub warnings: Vec<Warning>,
}

impl ConversionReport {
    /// The workspace directory holding this report's artifacts.
    ///
    /// It also contains staged inputs and intermediate outputs. The returned
    /// path is valid only while this report's temporary directory exists; this
    /// method does not persist or transfer ownership of that directory.
    #[must_use]
    pub fn directory(&self) -> &Path {
        self.workspace.path()
    }
}

/// A resolved input format with the evidence used to determine it.
///
/// Identification is a heuristic label, not proof that a decoder accepts the file.
/// [`Converter::identify`] never returns [`IdentificationMethod::Override`]; that
/// variant represents a source override applied internally during conversion.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Identification {
    /// Resolved format ID.
    pub format: String,
    /// Evidence used to identify the input.
    pub method: IdentificationMethod,
}

/// Evidence source used by [`Converter::identify`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum IdentificationMethod {
    /// Caller supplied the format override.
    Override,
    /// A single filename suffix matched a registered ID or extension alias.
    Extension,
    /// Up to the first 1,024 bytes matched a known signature for a registered format.
    Magic,
    /// No known signature or extension matched; the input is treated as binary.
    Unknown,
}

/// Adapter registry, routing configuration, and file conversion entry point.
///
/// [`Self::new`] and [`Default`] register compiled-in pure-Rust adapters with
/// default [`Policy`] and [`Limits`]. Native tools require explicit discovery
/// (with the `external` feature) and policy opt-in. Execution requires a Tokio
/// runtime; registration, lookup, and planning do not.
///
/// Plans describe format-level operations, not codec selection. A route can
/// fail because of input contents or adapter limitations despite valid metadata.
pub struct Converter {
    graph: Graph,
    adapters: BTreeMap<String, Arc<dyn Adapter>>,
    order: Vec<String>,
    policy: Policy,
    limits: Limits,
}

impl std::fmt::Debug for Converter {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("Converter")
            .field("adapters", &self.order)
            .field("formats", &self.graph.formats().count())
            .finish()
    }
}

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

impl Converter {
    /// Construct a converter with every compiled-in pure-Rust adapter.
    ///
    /// Always includes byte/text operations. Optional `data`, `media`, and
    /// `archives` features add their operations. Does not probe native tools.
    #[must_use]
    pub fn new() -> Self {
        let mut converter = Self {
            graph: Graph::new(),
            adapters: BTreeMap::new(),
            order: Vec::new(),
            policy: Policy::default(),
            limits: Limits::default(),
        };
        let _ = converter.register(Arc::new(BuiltinAdapter));
        #[cfg(feature = "media")]
        {
            let _ = converter.register(Arc::new(MediaAdapter));
        }
        #[cfg(feature = "archives")]
        {
            let _ = converter.register(Arc::new(ArchivesAdapter));
        }
        converter
    }

    /// Construct a converter and register native-tool adapters whose probes succeed.
    ///
    /// Available only with the `external` feature. Starts from [`Self::new`];
    /// unavailable tools are omitted rather than returned as errors. Probes do
    /// not establish that every advertised format or codec works for a file.
    /// Native tools are invoked per operation, not kept running by discovery.
    ///
    /// The default policy still disallows external routes. Set
    /// [`Policy::allow_external`] to use them. The library does not sandbox native
    /// tools; use operating-system isolation for hostile inputs.
    #[cfg(feature = "external")]
    pub async fn discover() -> Self {
        let mut converter = Self::new();
        let adapters = crate::external::discover().await;
        for adapter in adapters {
            if adapter.status().available {
                let _ = converter.register(adapter);
            }
        }
        converter
    }

    /// Add an adapter. Registration by name is idempotent; re-registering the
    /// same name replaces the previous adapter and rebuilds the graph.
    ///
    /// Formats from all adapters are registered before edges, allowing references
    /// to other adapters' formats. No availability probe is required. Metadata
    /// must remain stable across calls. Failed registration leaves the current
    /// registry and graph unchanged.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Invalid`] for an empty name, a name longer than 64 bytes,
    /// no format declarations, more than 8,192 formats, or more than 1,000,000
    /// conversions from the incoming adapter. Returns [`Error::Plan`] if the
    /// rebuilt graph rejects format or edge metadata. Backend names in edges
    /// are not checked against the adapter's registration name.
    pub fn register(&mut self, adapter: Arc<dyn Adapter>) -> Result<()> {
        let name = adapter.name().to_owned();
        if name.is_empty() || name.len() > 64 {
            return Err(Error::Invalid("invalid adapter name".into()));
        }
        let formats = adapter.formats();
        let conversions = adapter.conversions();
        if formats.is_empty() || formats.len() > 8192 || conversions.len() > 1_000_000 {
            return Err(Error::Invalid("adapter registration rejected".into()));
        }
        // Rebuild from every registered adapter so a replacement never leaves
        // edges whose backend no longer exists, and so a rejected registration
        // cannot leave a converter with an emptied registry.
        let mut previous = self.adapters.clone();
        let mut ordered = self.order.clone();
        ordered.retain(|existing| existing != &name);
        ordered.push(name.clone());
        previous.insert(name.clone(), Arc::clone(&adapter));
        let mut graph = Graph::new();
        for key in &ordered {
            for format in previous[key].formats() {
                graph.add_format(format).map_err(Error::Plan)?;
            }
        }
        for key in &ordered {
            for conversion in previous[key].conversions() {
                graph.add_conversion(conversion).map_err(Error::Plan)?;
            }
        }
        self.graph = graph;
        self.adapters = previous;
        self.order = ordered;
        Ok(())
    }

    #[must_use]
    /// Replace resource limits using builder-style ownership.
    ///
    /// Does not validate the values. See [`Limits`] for adapter-dependent checks
    /// and the distinction between budgets and hard resource isolation.
    pub fn limits(mut self, limits: Limits) -> Self {
        self.limits = limits;
        self
    }

    #[must_use]
    /// Replace the routing and execution policy using builder-style ownership.
    ///
    /// The policy is not validated here; invalid search settings fail at planning.
    pub fn with_policy(mut self, policy: Policy) -> Self {
        self.policy = policy;
        self
    }

    /// Replace the routing policy at runtime.
    ///
    /// Affects later conversions, including kind checks on forced plans. It does
    /// not alter previously returned plans or validate the new policy immediately.
    pub fn set_policy(&mut self, policy: Policy) {
        self.policy = policy;
    }

    #[must_use]
    /// Return the immutable route graph used by this converter.
    ///
    /// Use [`Self::register`] to contribute formats and conversions.
    pub fn graph(&self) -> &Graph {
        &self.graph
    }

    #[must_use]
    /// Return the current routing policy.
    pub fn policy(&self) -> &Policy {
        &self.policy
    }

    #[must_use]
    /// Clone all registered formats in ascending format-ID order.
    ///
    /// Includes custom registrations, not just compiled-in or discovered adapters.
    /// Presence does not imply a permitted route or a working encoder.
    pub fn formats(&self) -> Vec<Format> {
        self.graph.formats().cloned().collect()
    }

    /// Return registered adapters' status reports in ascending backend-name order.
    ///
    /// Calls [`Adapter::status`], which may return cached probe results. Tools
    /// omitted during discovery are not listed; status does not re-plan routes.
    #[must_use]
    pub fn backends(&self) -> Vec<BackendStatus> {
        self.adapters
            .values()
            .map(|adapter| adapter.status())
            .collect()
    }

    #[must_use]
    /// Resolve a format ID or extension alias without inspecting a file.
    ///
    /// Trims whitespace, folds ASCII case, and accepts leading dots. IDs take
    /// precedence over aliases; ambiguous aliases choose the smallest format ID.
    /// Returns `None` for unknown values. Does not parse paths or MIME types.
    pub fn resolve(&self, value: &str) -> Option<&Format> {
        self.graph.resolve(value)
    }

    /// Identify one nonempty regular input file by extension, then signature.
    ///
    /// A single suffix after the filename's first dot is considered; multi-dot
    /// names do not use extension lookup. A recognized suffix wins without
    /// opening or validating the contents. Otherwise, up to 1,024 bytes are read
    /// for magic detection. Unknown content becomes `bin`; built-in conversion
    /// from `bin` to text requires reinterpretation opt-in, but identity does not.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Invalid`] when metadata cannot be inspected or a needed
    /// header read fails. Returns [`Error::Security`] for nonregular paths
    /// (including symlinks) and empty files. Input byte budgets are checked later
    /// during staging, not by this method.
    pub fn identify(&self, path: &Path) -> Result<Identification> {
        let metadata = std::fs::symlink_metadata(path)
            .map_err(|_| Error::Invalid(format!("cannot inspect {}", path.display())))?;
        if !metadata.file_type().is_file() {
            return Err(Error::Security("input is not a regular file".into()));
        }
        if metadata.len() == 0 {
            return Err(Error::Security("input is empty".into()));
        }
        if let Some(id) = extension_of(path).and_then(|value| self.graph.resolve(&value)) {
            return Ok(Identification {
                format: id.id.clone(),
                method: IdentificationMethod::Extension,
            });
        }
        let mut header = [0u8; 1024];
        let mut file =
            std::fs::File::open(path).map_err(|_| Error::Invalid("input is unreadable".into()))?;
        let count = file
            .read(&mut header)
            .map_err(|_| Error::Invalid("input is unreadable".into()))?;
        if let Some(id) = detect(&header[..count]).and_then(|name| self.graph.resolve(name)) {
            return Ok(Identification {
                format: id.id.clone(),
                method: IdentificationMethod::Magic,
            });
        }
        Ok(Identification {
            format: "bin".into(),
            method: IdentificationMethod::Unknown,
        })
    }

    /// Enumerate policy-filtered routes between two formats.
    ///
    /// Uses the supplied policy, not necessarily [`Self::policy`]. Does not inspect
    /// files or filter by backend availability. See [`Graph::routes`] for ordering,
    /// bounded search, and partial-result behavior.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use convert_rs::{ConversionKind, Converter, Policy};
    /// let converter = Converter::new();
    /// let plans = converter.plan("txt", "bin", converter.policy())?;
    /// assert_eq!(plans[0].steps[0].kind, ConversionKind::Lossless);
    /// assert!(converter.plan("bin", "txt", converter.policy()).is_err());
    /// let policy = Policy { allow_reinterpret: true, ..Policy::default() };
    /// let plans = converter.plan("bin", "txt", &policy)?;
    /// assert_eq!(plans[0].steps[0].operation, "decode-text");
    /// # Ok::<(), convert_rs::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`Error::Plan`] for unknown formats, invalid search settings, no
    /// route, or an exhausted search budget before any route is found.
    pub fn plan(&self, from: &str, to: &str, policy: &Policy) -> Result<Vec<Plan>> {
        Ok(self.graph.routes(from, to, policy)?)
    }

    /// Convert files through the first successful route in the planned set.
    ///
    /// All inputs must resolve to one format. Routes are attempted in cost
    /// order, and every attempt re-stages fresh copies of inputs that adapters
    /// must not mutate. Search is bounded, so not every graph route is attempted.
    /// Backend filtering occurs after this bounded search. A forced plan bypasses
    /// search and is attempted once; see [`ConversionOptions::forced_plan`].
    ///
    /// With normal planning, same-format requests produce staged copies with an
    /// empty plan and no warnings. They do not validate content, re-encode, or
    /// choose codecs. File extensions and overrides are declarations, not decoder validation.
    /// Successful outputs remain temporary until copied out of the report.
    ///
    /// # Execute a reviewed plan
    ///
    /// ```rust
    /// use convert_rs::{ConversionKind, ConversionOptions, Converter, Policy};
    /// # #[tokio::main(flavor = "current_thread")]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let policy = Policy { allow_reinterpret: true, ..Policy::default() };
    /// let converter = Converter::new().with_policy(policy);
    /// let plans = converter.plan("bin", "txt", converter.policy())?;
    /// let chosen = plans.into_iter().next().ok_or("no plan")?;
    /// assert_eq!(chosen.steps[0].kind, ConversionKind::Reinterpret);
    /// let options = ConversionOptions {
    ///     from: Some("bin".into()),
    ///     backend: Some("builtin".into()),
    ///     forced_plan: Some(chosen),
    /// };
    /// let inputs = tempfile::tempdir()?;
    /// let source = inputs.path().join("payload");
    /// std::fs::write(&source, "valid UTF-8")?;
    /// let report = converter.convert(&[source], "txt", &options).await?;
    /// assert_eq!(std::fs::read_to_string(&report.artifacts[0].path)?, "valid UTF-8");
    /// assert_eq!(report.warnings[0].kind, ConversionKind::Reinterpret);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`Error::Invalid`] for empty input lists, unknown overrides or
    /// targets, mixed identified formats, or no route remaining after backend
    /// filtering; [`Error::Limit`] for too many inputs; and identification or
    /// planning errors before execution. Staging, adapter, execution-policy,
    /// and output-validation failures are accumulated into [`Error::RoutesFailed`]
    /// if all attempted routes fail. A successful fallback omits earlier errors.
    pub async fn convert(
        &self,
        paths: &[PathBuf],
        to: &str,
        options: &ConversionOptions,
    ) -> Result<ConversionReport> {
        if paths.is_empty() {
            return Err(Error::Invalid("no input files given".into()));
        }
        if paths.len() > self.limits.max_artifacts {
            return Err(Error::Limit("input file count".into()));
        }
        let target = self
            .graph
            .resolve(to)
            .ok_or_else(|| Error::Invalid(format!("unknown target format: {to}")))?
            .id
            .clone();

        let identification = match &options.from {
            Some(value) => {
                let format = self
                    .graph
                    .resolve(value)
                    .ok_or_else(|| Error::Invalid(format!("unknown source format: {value}")))?
                    .id
                    .clone();
                Identification {
                    format,
                    method: IdentificationMethod::Override,
                }
            }
            None => self.identify(&paths[0])?,
        };
        if options.from.is_none() {
            for path in &paths[1..] {
                let other = self.identify(path)?;
                if other.format != identification.format {
                    return Err(Error::Invalid(format!(
                        "inputs have different formats: {} and {}",
                        identification.format, other.format
                    )));
                }
            }
        }
        let source = identification.format;

        let plans = match &options.forced_plan {
            Some(plan) => vec![plan.clone()],
            None => {
                let mut plans = self.graph.routes(&source, &target, &self.policy)?;
                if let Some(backend) = &options.backend {
                    plans.retain(|plan| {
                        plan.steps.is_empty()
                            || plan.steps.iter().all(|step| &step.backend == backend)
                    });
                    if plans.is_empty() {
                        return Err(Error::Invalid(format!(
                            "no route from {source} to {target} uses only backend {backend}"
                        )));
                    }
                }
                plans
            }
        };

        let mut failures = Vec::new();
        for plan in plans {
            let attempt = self
                .execute(&plan, &source, &target, paths, &options.backend)
                .await;
            match attempt {
                Ok(report) => return Ok(report),
                Err(error) => {
                    let rendered = if plan.steps.is_empty() {
                        "identity".to_owned()
                    } else {
                        plan.steps
                            .iter()
                            .map(|step| format!("{}→{} via {}", step.from, step.to, step.backend))
                            .collect::<Vec<_>>()
                            .join(" | ")
                    };
                    failures.push(format!("{rendered}: {error}"));
                }
            }
        }
        Err(Error::RoutesFailed(failures.join("; ")))
    }

    async fn execute(
        &self,
        plan: &Plan,
        source: &str,
        target: &str,
        paths: &[PathBuf],
        pinned: &Option<String>,
    ) -> Result<ConversionReport> {
        let workspace = TempDir::new()?;
        let mut artifacts = Vec::with_capacity(paths.len());
        for (index, path) in paths.iter().enumerate() {
            artifacts.push(stage_input(
                path,
                workspace.path(),
                index,
                source,
                &self.limits,
            )?);
        }

        let mut warnings = Vec::new();
        for (index, step) in plan.steps.iter().enumerate() {
            if !self.policy.allows(step.kind) {
                return Err(Error::Security(format!(
                    "{:?} steps are disabled",
                    step.kind
                )));
            }
            if step.external && !self.policy.allow_external {
                return Err(Error::Security(format!(
                    "{} uses a native external tool; enable Policy::allow_external",
                    step.backend
                )));
            }
            if pinned
                .as_ref()
                .is_some_and(|backend| &step.backend != backend)
            {
                return Err(Error::Invalid("plan uses a disallowed backend".into()));
            }
            if artifacts
                .iter()
                .any(|artifact| artifact.format != step.from)
            {
                return Err(Error::Conversion(format!(
                    "step {index} expected {} inputs",
                    step.from
                )));
            }
            let adapter = self.adapters.get(&step.backend).ok_or_else(|| {
                Error::Conversion(format!("backend {} is not registered", step.backend))
            })?;
            let step_dir = workspace.path().join(step_dir_name(index)?);
            tokio::fs::create_dir_all(&step_dir).await?;
            let request = StepRequest {
                inputs: artifacts.clone(),
                output_dir: step_dir.clone(),
                from: step.from.clone(),
                to: step.to.clone(),
                operation: step.operation.clone(),
                limits: self.limits.clone(),
            };
            match adapter.convert(&request).await {
                Ok(produced) => {
                    artifacts = validate_artifacts(produced, &step_dir, step, &self.limits)?
                }
                Err(error) => {
                    let _ = tokio::fs::remove_dir_all(&step_dir).await;
                    return Err(error);
                }
            }
            if let Some(warning) = warning_for(index, step) {
                warnings.push(warning);
            }
        }
        if artifacts.iter().any(|artifact| artifact.format != *target) {
            return Err(Error::Conversion(
                "final artifacts do not match the target".into(),
            ));
        }
        Ok(ConversionReport {
            workspace,
            plan: plan.clone(),
            artifacts,
            warnings,
        })
    }
}

fn step_dir_name(index: usize) -> Result<String> {
    Ok(format!("step-{index:04}"))
}

fn warning_for(index: usize, step: &crate::Conversion) -> Option<Warning> {
    let message = match step.kind {
        ConversionKind::Lossless => return None,
        ConversionKind::Lossy => format!(
            "{} re-encoded through {}; expect quality or metadata loss",
            step.to, step.operation
        ),
        ConversionKind::Bridge => format!(
            "{} bridged through {}; the result expresses {} differently",
            step.from, step.operation, step.to
        ),
        ConversionKind::Reinterpret => format!(
            "bytes were reinterpreted as {} by {}",
            step.to, step.backend
        ),
        ConversionKind::Package => "files were packaged; contents were not converted".into(),
        ConversionKind::Extract => "archive members were extracted as separate files".into(),
    };
    Some(Warning {
        step: index,
        backend: step.backend.clone(),
        operation: step.operation.clone(),
        kind: step.kind,
        message,
    })
}

fn extension_of(path: &Path) -> Option<String> {
    let name = path.file_name()?.to_str()?;
    let (_, suffix) = name.split_once('.')?;
    let suffix = suffix.to_ascii_lowercase();
    (!suffix.is_empty() && !suffix.contains('.')).then_some(suffix)
}

fn stage_input(
    path: &Path,
    dir: &Path,
    index: usize,
    format: &str,
    limits: &Limits,
) -> Result<Artifact> {
    let metadata = std::fs::symlink_metadata(path)?;
    if !metadata.file_type().is_file() {
        return Err(Error::Security("input is not a regular file".into()));
    }
    if metadata.len() > limits.max_input_bytes {
        return Err(Error::Limit("input bytes exceed budget".into()));
    }
    let destination = dir.join(format!("input-{index}"));
    std::fs::copy(path, &destination)?;
    let staged = std::fs::symlink_metadata(&destination)?;
    if !staged.file_type().is_file() || staged.len() != metadata.len() {
        return Err(Error::Security("staged input changed during copy".into()));
    }
    Ok(Artifact {
        path: destination,
        format: format.to_owned(),
    })
}

/// Ensure an adapter produced only bounded regular files inside its own step
/// directory and that no intermediate directory contains path-traversal names.
fn validate_artifacts(
    produced: Vec<Artifact>,
    step_dir: &Path,
    step: &crate::Conversion,
    limits: &Limits,
) -> Result<Vec<Artifact>> {
    if produced.len() > limits.max_artifacts {
        return Err(Error::Limit("adapter produced too many artifacts".into()));
    }
    let root = step_dir
        .canonicalize()
        .map_err(|_| Error::Security("step directory disappeared".into()))?;
    let mut artifacts = Vec::with_capacity(produced.len());
    let mut total = 0u64;
    for artifact in produced {
        if artifact.format != step.to {
            return Err(Error::Conversion(format!(
                "{} returned a {} artifact for a {} step",
                step.backend, artifact.format, step.to
            )));
        }
        let metadata = std::fs::symlink_metadata(&artifact.path)
            .map_err(|_| Error::Security("adapter artifact does not exist".into()))?;
        if !metadata.file_type().is_file() {
            return Err(Error::Security(
                "adapter returned a non-regular file".into(),
            ));
        }
        let canonical = artifact.path.canonicalize().map_err(|_| {
            Error::Security("adapter returned a path that cannot be resolved".into())
        })?;
        if !canonical.starts_with(&root) {
            return Err(Error::Security(
                "adapter wrote outside its step directory".into(),
            ));
        }
        total = total
            .checked_add(metadata.len())
            .ok_or_else(|| Error::Limit("artifact byte overflow".into()))?;
        if total > limits.max_output_bytes {
            return Err(Error::Limit("artifact bytes exceed budget".into()));
        }
        artifacts.push(Artifact {
            path: canonical,
            format: artifact.format,
        });
    }
    Ok(artifacts)
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;

    fn graph_backend_converter() -> Converter {
        Converter::new()
    }

    #[test]
    fn registration_is_idempotent_by_name() {
        let converter = graph_backend_converter();
        assert_eq!(
            converter
                .order
                .iter()
                .filter(|name| name.as_str() == "builtin")
                .count(),
            1
        );
    }

    #[test]
    #[cfg(feature = "media")]
    fn extension_detection_wins_and_magic_is_fallback() {
        let converter = graph_backend_converter();
        let dir = TempDir::new().unwrap();
        std::fs::write(dir.path().join("note.txt"), b"plain text").unwrap();
        assert_eq!(
            converter
                .identify(&dir.path().join("note.txt"))
                .unwrap()
                .method,
            IdentificationMethod::Extension
        );
        std::fs::write(dir.path().join("payload.dat"), b"\x89PNG\r\n\x1a\nxx").unwrap();
        let found = converter.identify(&dir.path().join("payload.dat")).unwrap();
        assert_eq!(found.format, "png");
        assert_eq!(found.method, IdentificationMethod::Magic);
        std::fs::write(dir.path().join("random"), [1, 2, 3, 250, 7]).unwrap();
        let found = converter.identify(&dir.path().join("random")).unwrap();
        assert_eq!(found.format, "bin");
        assert_eq!(found.method, IdentificationMethod::Unknown);
    }

    #[test]
    fn identify_rejects_nonregular_and_empty() {
        let converter = graph_backend_converter();
        let dir = TempDir::new().unwrap();
        std::fs::create_dir(dir.path().join("adir")).unwrap();
        assert!(matches!(
            converter.identify(&dir.path().join("adir")),
            Err(Error::Security(_))
        ));
        std::fs::write(dir.path().join("empty.txt"), b"").unwrap();
        assert!(matches!(
            converter.identify(&dir.path().join("empty.txt")),
            Err(Error::Security(_))
        ));
    }

    #[tokio::test]
    async fn unknown_files_require_reinterpretation_opt_in() {
        let converter = graph_backend_converter();
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("mystery");
        std::fs::write(&path, [7u8; 40]).unwrap();
        let default = converter
            .convert(
                std::slice::from_ref(&path),
                "txt",
                &ConversionOptions::default(),
            )
            .await;
        assert!(matches!(default, Err(Error::Plan(_))), "{default:?}");
        let policy = Policy {
            allow_reinterpret: true,
            ..Policy::default()
        };
        let report = Converter::default()
            .with_policy(policy)
            .convert(&[path], "txt", &ConversionOptions::default())
            .await
            .unwrap();
        assert_eq!(report.plan.steps.len(), 1);
        assert!(
            report
                .warnings
                .iter()
                .any(|warning| warning.kind == ConversionKind::Reinterpret)
        );
    }

    #[tokio::test]
    async fn same_format_requests_stage_a_copy() {
        let converter = graph_backend_converter();
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("data.txt");
        std::fs::write(&path, b"unchanged").unwrap();
        let report = converter
            .convert(&[path], "txt", &ConversionOptions::default())
            .await
            .unwrap();
        assert!(report.plan.steps.is_empty());
        assert_eq!(
            std::fs::read_to_string(&report.artifacts[0].path).unwrap(),
            "unchanged"
        );
    }

    #[tokio::test]
    async fn mixed_format_inputs_are_rejected() {
        let converter = graph_backend_converter();
        let dir = TempDir::new().unwrap();
        std::fs::write(dir.path().join("a.txt"), b"a").unwrap();
        std::fs::write(dir.path().join("b.gz"), b"\x1f\x8brest").unwrap();
        let error = converter
            .convert(
                &[dir.path().join("a.txt"), dir.path().join("b.gz")],
                "tar",
                &ConversionOptions::default(),
            )
            .await
            .err();
        assert!(matches!(error, Some(Error::Invalid(_))));
    }

    #[test]
    fn validating_artifacts_rejects_escapes_and_mismatch() {
        let dir = TempDir::new().unwrap();
        let step_dir = dir.path().join("step");
        std::fs::create_dir(&step_dir).unwrap();
        let step = crate::Conversion::new(
            "a",
            "png",
            "backend",
            "convert",
            ConversionKind::Lossless,
            1,
        );
        let limits = Limits::default();

        std::fs::write(dir.path().join("escape.png"), b"x").unwrap();
        let escape = Artifact {
            path: dir.path().join("escape.png"),
            format: "png".into(),
        };
        assert!(matches!(
            validate_artifacts(vec![escape], &step_dir, &step, &limits),
            Err(Error::Security(_))
        ));

        let directory = Artifact {
            path: step_dir.clone(),
            format: "png".into(),
        };
        assert!(matches!(
            validate_artifacts(vec![directory], &step_dir, &step, &limits),
            Err(Error::Security(_))
        ));

        let wrong = Artifact {
            path: step_dir.join("wrong.jpg"),
            format: "jpeg".into(),
        };
        std::fs::write(&wrong.path, b"x").unwrap();
        assert!(matches!(
            validate_artifacts(vec![wrong], &step_dir, &step, &limits),
            Err(Error::Conversion(_))
        ));

        std::fs::write(step_dir.join("real.png"), b"x").unwrap();
        let good = Artifact {
            path: step_dir.join("real.png"),
            format: "png".into(),
        };
        assert_eq!(
            validate_artifacts(vec![good], &step_dir, &step, &limits)
                .unwrap()
                .len(),
            1
        );
    }

    #[test]
    fn stage_input_rejects_nonregular_and_oversize() {
        let limits = Limits {
            max_input_bytes: 4,
            ..Limits::default()
        };
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("in");
        std::fs::write(&path, b"payload").unwrap();
        assert!(matches!(
            stage_input(&path, dir.path(), 0, "bin", &limits),
            Err(Error::Limit(_))
        ));
        std::fs::create_dir(dir.path().join("adir")).unwrap();
        assert!(matches!(
            stage_input(
                &dir.path().join("adir"),
                dir.path(),
                1,
                "bin",
                &Limits::default()
            ),
            Err(Error::Security(_))
        ));
    }

    #[tokio::test]
    async fn backend_constraint_selects_or_rejects_routes() {
        let converter = graph_backend_converter();
        let dir = TempDir::new().unwrap();
        std::fs::write(dir.path().join("data.txt"), b"[1, 2, 3]").unwrap();
        let options = ConversionOptions {
            from: Some("txt".into()),
            backend: Some("builtin".into()),
            forced_plan: None,
        };
        let report = converter
            .convert(&[dir.path().join("data.txt")], "csv", &options)
            .await
            .err();
        assert!(report.is_some(),);
    }

    #[test]
    #[cfg(feature = "media")]
    fn graph_routes_honor_policy() {
        let converter = graph_backend_converter();
        let strict = converter
            .plan("bin", "png", &Policy::default())
            .unwrap_err();
        assert!(matches!(
            strict,
            Error::Plan(convert_rs_core::PlanError::NoRoute { .. })
        ));
    }
}