gugen 0.1.0

Explainable materials synthesis and process planning
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
use crate::composition::Element;
use crate::config::PlanningConfig;
use crate::error::Result;
use crate::evidence::{EvidenceKind, EvidenceScope, EvidenceStrength, PlanningEvidence};
use crate::precursor::{PrecursorId, PrecursorSelection, search_precursor_sets};
use crate::process::conventional_solid_state_template;
use crate::provenance::PlanningProvenance;
use crate::provider::{PrecursorCatalog, ProcessEvidenceProvider, ThermodynamicProvider};
use crate::reaction::{BalancedReaction, ThermodynamicConditions};
use crate::rejection::{RejectedCandidate, RejectionCode};
use crate::report::{
    ApplicabilityAssessment, ApplicabilityLevel, PlanId, PlanningWarning, SCHEMA_VERSION,
    SynthesisPlan, SynthesisPlanningReport, TargetSummary, UnresolvedRequirement, WarningSeverity,
};
use crate::score::{ranking_weights_digest, score_plan};
use crate::target::TargetSpecification;

/// Orchestrates every subsystem built in Phases 2-5 into the single public
/// entry point AGENTS.md §18 illustrates: catalog lookup, bounded precursor
/// search, process templating, and scoring, assembled into one
/// [`SynthesisPlanningReport`].
///
/// `thermodynamic_provider` and `process_evidence_provider` are optional
/// (AGENTS.md §18's `Planner::offline_minimal`); `catalog` is not, since
/// there is nothing to plan from without it. A failure from either optional
/// provider degrades to a `PlanningWarning` on the affected plan rather
/// than failing the whole report (AGENTS.md §21.5); a catalog failure
/// propagates, since planning cannot proceed without one at all.
pub struct Planner {
    catalog: Box<dyn PrecursorCatalog>,
    thermodynamic_provider: Option<Box<dyn ThermodynamicProvider>>,
    process_evidence_provider: Option<Box<dyn ProcessEvidenceProvider>>,
    config: PlanningConfig,
}

impl Planner {
    /// Full configuration: a catalog plus both optional providers.
    pub fn new(
        catalog: impl PrecursorCatalog + 'static,
        process_evidence_provider: impl ProcessEvidenceProvider + 'static,
        thermodynamic_provider: impl ThermodynamicProvider + 'static,
        config: PlanningConfig,
    ) -> Self {
        Self {
            catalog: Box::new(catalog),
            thermodynamic_provider: Some(Box::new(thermodynamic_provider)),
            process_evidence_provider: Some(Box::new(process_evidence_provider)),
            config,
        }
    }

    /// Catalog only -- no thermodynamic or process-evidence provider.
    /// AGENTS.md §18: "providerがなくても最低限のstoichiometric planningを
    /// 実行できる構成" -- but conditions are still never fabricated to make
    /// up for the missing providers; they stay unresolved instead.
    pub fn offline_minimal(
        catalog: impl PrecursorCatalog + 'static,
        config: PlanningConfig,
    ) -> Self {
        Self {
            catalog: Box::new(catalog),
            thermodynamic_provider: None,
            process_evidence_provider: None,
            config,
        }
    }

    /// Plans for `target`, returning a complete report -- never a partial
    /// or panicking result for well-formed input (AGENTS.md §25).
    ///
    /// `execution_timestamp` is a parameter, not read from the system
    /// clock internally: `PlanningProvenance.execution_timestamp` is
    /// documented as caller-supplied precisely so the deterministic core
    /// never touches wall-clock time (AGENTS.md §25). This is one
    /// deliberate deviation from AGENTS.md §18's illustrative
    /// single-argument `plan(&target)` signature -- an unset provenance
    /// field would fail §29's "provenanceがある" completion criterion for
    /// every report the crate produces.
    pub fn plan(
        &self,
        target: &TargetSpecification,
        execution_timestamp: &str,
    ) -> Result<SynthesisPlanningReport> {
        let composition = &target.composition;
        let provenance = self.provenance(execution_timestamp);

        let contradictory = contradictory_elements(target);
        if !contradictory.is_empty() {
            return Ok(abstain(target, &contradictory, provenance));
        }

        let applicability = assess_applicability(target);
        let candidates = self
            .catalog
            .candidates_for(composition, &target.constraints)?;

        let mut warnings = Vec::new();
        if candidates.is_empty() {
            warnings.push(PlanningWarning {
                message: "the precursor catalog returned no candidates sharing any \
                    element with the target"
                    .to_string(),
                severity: WarningSeverity::Caution,
            });
        }

        let outcome = search_precursor_sets(
            composition,
            &candidates,
            &target.constraints,
            &self.config.search_budget,
        )?;

        let mut plans: Vec<SynthesisPlan> = Vec::with_capacity(outcome.accepted.len());
        for accepted in &outcome.accepted {
            let template = conventional_solid_state_template(composition, accepted);
            let mut evidence = template.evidence;
            let mut provider_warnings = Vec::new();

            if let Some(provider) = &self.thermodynamic_provider {
                match provider
                    .reaction_energy(&accepted.reaction, &ThermodynamicConditions::default())
                {
                    Ok(Some(energy)) => evidence.push(PlanningEvidence {
                        kind: EvidenceKind::ThermodynamicData,
                        source_id: None,
                        statement: format!(
                            "reaction energy {:.4} eV/atom from the configured \
                            ThermodynamicProvider",
                            energy.value_ev_per_atom()
                        ),
                        strength: EvidenceStrength::Moderate,
                        applicable_to: EvidenceScope::ExactTarget,
                        limitations: vec![
                            "a raw reaction energy is not converted into a favorability \
                                judgment: thermodynamic favorability is not experimental \
                                likelihood (AGENTS.md §4.3)"
                                .to_string(),
                        ],
                    }),
                    Ok(None) => {}
                    Err(err) => provider_warnings.push(PlanningWarning {
                        message: format!(
                            "thermodynamic provider failed for this candidate, \
                            continuing without its data: {err}"
                        ),
                        severity: WarningSeverity::Info,
                    }),
                }
            }

            let precursors: Vec<PrecursorSelection> = accepted
                .precursors
                .iter()
                .zip(&accepted.reaction.reactants)
                .map(|(id, species)| PrecursorSelection {
                    precursor: id.clone(),
                    formula_units: species.coefficient,
                })
                .collect();

            if let Some(provider) = &self.process_evidence_provider {
                match provider.precedents(target, &precursors) {
                    Ok(precedents) => {
                        for precedent in precedents {
                            evidence.push(PlanningEvidence {
                                kind: EvidenceKind::UserProvidedPrecedent,
                                source_id: None,
                                statement: precedent.description,
                                strength: EvidenceStrength::Weak,
                                applicable_to: EvidenceScope::SimilarMaterial,
                                limitations: vec![
                                    "ProcessPrecedent has no structured method/condition \
                                        detail yet"
                                        .to_string(),
                                ],
                            });
                        }
                    }
                    Err(err) => provider_warnings.push(PlanningWarning {
                        message: format!(
                            "process evidence provider failed for this candidate, \
                            continuing without its data: {err}"
                        ),
                        severity: WarningSeverity::Info,
                    }),
                }
            }

            let assessment = score_plan(
                composition,
                &applicability,
                Some(&accepted.reaction),
                &template.steps,
                &evidence,
                &self.config.ranking_weights,
            );

            let mut plan_warnings = template.warnings;
            plan_warnings.extend(assessment.warnings);
            plan_warnings.extend(provider_warnings);

            plans.push(SynthesisPlan {
                plan_id: derive_plan_id(&accepted.precursors, &accepted.reaction),
                route_family: template.route_family,
                precursors,
                balanced_reaction: Some(accepted.reaction.clone()),
                steps: template.steps,
                score: assessment.score,
                confidence: assessment.confidence,
                applicability: assessment.applicability,
                evidence,
                warnings: plan_warnings,
                assumptions: assessment.assumptions,
                unresolved: assessment.unresolved,
                manual_review_required: assessment.manual_review_required,
            });
        }

        // Deterministic descending rank; ties break on plan_id so ordering
        // never depends on catalog/accepted-set iteration order (AGENTS.md
        // §21.4).
        plans.sort_by(|a, b| {
            b.score
                .total_ranking_score
                .value()
                .partial_cmp(&a.score.total_ranking_score.value())
                .unwrap_or(std::cmp::Ordering::Equal)
                .then_with(|| a.plan_id.0.cmp(&b.plan_id.0))
        });

        let max_plans = self.config.search_budget.max_plans_returned;
        let mut rejected_candidates = outcome.rejected;
        let overflow = plans.len().saturating_sub(max_plans);
        if overflow > 0 {
            rejected_candidates.push(RejectedCandidate {
                precursors: vec![],
                reason_codes: vec![RejectionCode::SearchBudgetExhausted],
                explanation: format!(
                    "{overflow} additional valid plan(s) were found but are not \
                    included: only the top {max_plans} by total_ranking_score are \
                    returned (SearchBudget::max_plans_returned)"
                ),
            });
        }
        plans.truncate(max_plans);

        Ok(SynthesisPlanningReport {
            schema_version: SCHEMA_VERSION,
            target: TargetSummary {
                composition: composition.clone(),
                structure_present: target.structure.is_some(),
                desired_phase: target.desired_phase.as_ref().map(|p| p.phase_name.clone()),
            },
            applicability,
            plans,
            rejected_candidates,
            unresolved: vec![],
            warnings,
            provenance,
        })
    }

    fn provenance(&self, execution_timestamp: &str) -> PlanningProvenance {
        PlanningProvenance {
            gugen_version: PlanningProvenance::gugen_version().to_string(),
            build_identifier: None,
            schema_version: SCHEMA_VERSION,
            chematic_crystal_version: None,
            mikiwame_version: None,
            precursor_catalog_version: None,
            thermodynamic_provider_version: None,
            process_template_version: None,
            ranking_config_digest: Some(ranking_weights_digest(&self.config.ranking_weights)),
            execution_timestamp: execution_timestamp.to_string(),
            deterministic_seed: self.config.deterministic_seed,
            enabled_features: enabled_features(),
        }
    }
}

fn enabled_features() -> Vec<String> {
    let mut features = Vec::new();
    if cfg!(feature = "serde") {
        features.push("serde".to_string());
    }
    if cfg!(feature = "clap") {
        features.push("clap".to_string());
    }
    if cfg!(feature = "mikiwame") {
        features.push("mikiwame".to_string());
    }
    features
}

/// Target elements that `constraints.forbidden_elements` also forbids --
/// self-contradictory input no plan can ever satisfy (AGENTS.md §26 Phase
/// 6 "invalid target handling"). Distinct from "no candidates cover the
/// target," which is a catalog-coverage outcome, not a domain judgment.
fn contradictory_elements(target: &TargetSpecification) -> Vec<Element> {
    target
        .composition
        .elements()
        .filter(|e| target.constraints.forbidden_elements.contains(e))
        .collect()
}

fn abstain(
    target: &TargetSpecification,
    contradictory: &[Element],
    provenance: PlanningProvenance,
) -> SynthesisPlanningReport {
    let symbols = contradictory
        .iter()
        .map(Element::symbol)
        .collect::<Vec<_>>()
        .join(", ");
    SynthesisPlanningReport {
        schema_version: SCHEMA_VERSION,
        target: TargetSummary {
            composition: target.composition.clone(),
            structure_present: target.structure.is_some(),
            desired_phase: target.desired_phase.as_ref().map(|p| p.phase_name.clone()),
        },
        applicability: ApplicabilityAssessment {
            level: ApplicabilityLevel::OutOfDomain,
            rationale: vec![format!(
                "target composition requires element(s) {symbols} that \
                PlanningConstraints.forbidden_elements also forbids -- no plan can \
                ever satisfy both"
            )],
        },
        plans: vec![],
        rejected_candidates: vec![],
        unresolved: vec![UnresolvedRequirement {
            description: "planning".to_string(),
            reason: format!(
                "target and constraints are self-contradictory over element(s) {symbols}"
            ),
        }],
        warnings: vec![],
        provenance,
    }
}

/// Content-derived, not position-derived (AGENTS.md §20: "plan IDを決定的
/// にする"): the same precursor set and reaction always get the same id
/// regardless of where it lands in ranked order or catalog insertion order.
fn derive_plan_id(precursors: &[PrecursorId], reaction: &BalancedReaction) -> PlanId {
    use std::hash::{Hash, Hasher};
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    let mut ids: Vec<&str> = precursors.iter().map(|p| p.0.as_str()).collect();
    ids.sort_unstable();
    for id in &ids {
        id.hash(&mut hasher);
    }
    for species in reaction.reactants.iter().chain(&reaction.products) {
        for (element, amount) in species.composition.iter() {
            element.symbol().hash(&mut hasher);
            amount.to_bits().hash(&mut hasher);
        }
        species.coefficient.hash(&mut hasher);
    }
    PlanId(format!("plan-{:016x}", hasher.finish()))
}

/// AGENTS.md §16 lists `InDomain` for "bulk inorganic solid-state" but
/// `OutOfDomain` for MOF/thin-film -- and gugen cannot currently tell those
/// apart. `TargetStructure { description: String }` is free text with no
/// classification; a structure gugen can't classify is not evidence of
/// being in-domain, so this stays `PartiallyInDomain` regardless of
/// whether structure is present. Only a real classifier (mikiwame, once
/// wired with actual structure data -- see the `mikiwame` adapter) or a
/// published `chematic-crystal` could justify `InDomain` here.
fn assess_applicability(target: &TargetSpecification) -> ApplicabilityAssessment {
    let rationale = if target.structure.is_some() {
        "structure provided, but gugen has no structural classifier wired in \
        to confirm it's in the validated bulk-inorganic domain (AGENTS.md §16 \
        lists both in-domain and out-of-domain examples with structure present)"
            .to_string()
    } else {
        "formula-only target, no structure provided (AGENTS.md §16's own \
        example for this level)"
            .to_string()
    };
    ApplicabilityAssessment {
        level: ApplicabilityLevel::PartiallyInDomain,
        rationale: vec![rationale],
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::composition::Composition;
    use crate::config::SearchBudget;
    use crate::error::ProviderError;
    use crate::precursor::{AvailabilityMetadata, InMemoryPrecursorCatalog, PrecursorCandidate};
    use crate::process::ProcessPrecedent;
    use crate::reaction::ReactionEnergy;
    use crate::target::PlanningConstraints;

    fn element(symbol: &str) -> Element {
        Element::new(symbol).unwrap()
    }

    fn composition(pairs: &[(&str, f64)]) -> Composition {
        Composition::new(pairs.iter().map(|&(sym, amt)| (element(sym), amt))).unwrap()
    }

    fn candidate(id: &str, pairs: &[(&str, f64)]) -> PrecursorCandidate {
        PrecursorCandidate {
            id: PrecursorId(id.to_string()),
            composition: composition(pairs),
            availability: None,
        }
    }

    fn barium_titanate_catalog() -> InMemoryPrecursorCatalog {
        InMemoryPrecursorCatalog::new(vec![
            candidate("BaCO3", &[("Ba", 1.0), ("C", 1.0), ("O", 3.0)]),
            candidate("BaO", &[("Ba", 1.0), ("O", 1.0)]),
            candidate("TiO2", &[("Ti", 1.0), ("O", 2.0)]),
        ])
    }

    fn barium_titanate_target() -> TargetSpecification {
        TargetSpecification {
            composition: composition(&[("Ba", 1.0), ("Ti", 1.0), ("O", 3.0)]),
            structure: None,
            desired_phase: None,
            constraints: PlanningConstraints::default(),
        }
    }

    fn generous_config() -> PlanningConfig {
        PlanningConfig {
            search_budget: SearchBudget {
                max_precursor_sets: 10_000,
                max_precursors_per_plan: 3,
                max_plans_returned: 20,
            },
            ..PlanningConfig::default()
        }
    }

    #[test]
    fn offline_minimal_produces_ranked_plans_from_a_catalog_alone() {
        let planner = Planner::offline_minimal(barium_titanate_catalog(), generous_config());
        let report = planner
            .plan(&barium_titanate_target(), "2026-08-14T00:00:00Z")
            .unwrap();

        assert!(!report.plans.is_empty(), "expected at least one plan");
        assert!(
            report
                .plans
                .iter()
                .all(|p| p.balanced_reaction.is_some() && p.manual_review_required),
        );
        assert_eq!(
            report.provenance.execution_timestamp,
            "2026-08-14T00:00:00Z"
        );
        assert!(report.provenance.ranking_config_digest.is_some());
        // Descending order by total_ranking_score.
        for window in report.plans.windows(2) {
            assert!(
                window[0].score.total_ranking_score.value()
                    >= window[1].score.total_ranking_score.value()
            );
        }
        // plan_id must uniquely identify a plan within a report -- this is
        // the assertion that would have caught the search_precursor_sets
        // duplicate-acceptance bug automatically instead of by manually
        // inspecting `gugen plan` CLI output (see precursor.rs's
        // `a_redundant_larger_combination_is_rejected_as_a_duplicate_not_double_accepted`).
        let ids: std::collections::BTreeSet<&str> =
            report.plans.iter().map(|p| p.plan_id.0.as_str()).collect();
        assert_eq!(
            ids.len(),
            report.plans.len(),
            "plan_id must be unique across the report's plans: {:?}",
            report
                .plans
                .iter()
                .map(|p| &p.plan_id.0)
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn self_contradictory_target_abstains_with_no_plans() {
        let mut target = barium_titanate_target();
        target.constraints.forbidden_elements.insert(element("Ba"));
        let planner = Planner::offline_minimal(barium_titanate_catalog(), generous_config());

        let report = planner.plan(&target, "2026-08-14T00:00:00Z").unwrap();

        assert!(report.plans.is_empty());
        assert_eq!(
            report.applicability.level,
            crate::report::ApplicabilityLevel::OutOfDomain
        );
    }

    #[test]
    fn empty_catalog_result_produces_a_warning_not_a_panic() {
        let empty = InMemoryPrecursorCatalog::new(vec![]);
        let planner = Planner::offline_minimal(empty, generous_config());

        let report = planner
            .plan(&barium_titanate_target(), "2026-08-14T00:00:00Z")
            .unwrap();

        assert!(report.plans.is_empty());
        assert!(
            report
                .warnings
                .iter()
                .any(|w| w.message.contains("no candidates"))
        );
    }

    struct FailingThermodynamicProvider;
    impl ThermodynamicProvider for FailingThermodynamicProvider {
        fn reaction_energy(
            &self,
            _reaction: &BalancedReaction,
            _conditions: &ThermodynamicConditions,
        ) -> std::result::Result<Option<ReactionEnergy>, ProviderError> {
            Err(ProviderError::Unavailable("simulated outage".to_string()))
        }
    }
    struct FailingProcessEvidenceProvider;
    impl ProcessEvidenceProvider for FailingProcessEvidenceProvider {
        fn precedents(
            &self,
            _target: &TargetSpecification,
            _precursors: &[PrecursorSelection],
        ) -> std::result::Result<Vec<ProcessPrecedent>, ProviderError> {
            Err(ProviderError::Unavailable("simulated outage".to_string()))
        }
    }

    /// AGENTS.md §21.5: one provider failing must not fail the whole plan.
    #[test]
    fn a_failing_optional_provider_degrades_to_a_warning_not_a_failure() {
        let planner = Planner::new(
            barium_titanate_catalog(),
            FailingProcessEvidenceProvider,
            FailingThermodynamicProvider,
            generous_config(),
        );

        let report = planner
            .plan(&barium_titanate_target(), "2026-08-14T00:00:00Z")
            .unwrap();

        assert!(!report.plans.is_empty());
        for plan in &report.plans {
            assert!(
                plan.warnings
                    .iter()
                    .filter(|w| w.message.contains("continuing without"))
                    .count()
                    >= 2,
                "expected both provider failures reflected as warnings: {:?}",
                plan.warnings
            );
        }
    }

    #[test]
    fn overflow_beyond_max_plans_returned_is_explained_not_silently_dropped() {
        let tight_config = PlanningConfig {
            search_budget: SearchBudget {
                max_plans_returned: 1,
                ..generous_config().search_budget
            },
            ..generous_config()
        };
        let planner = Planner::offline_minimal(barium_titanate_catalog(), tight_config);

        let report = planner
            .plan(&barium_titanate_target(), "2026-08-14T00:00:00Z")
            .unwrap();

        assert_eq!(report.plans.len(), 1);
        assert!(report.rejected_candidates.iter().any(|r| {
            r.reason_codes
                .contains(&RejectionCode::SearchBudgetExhausted)
                && r.explanation.contains("additional valid plan")
        }));
    }

    /// `plan_id` must be derived from a plan's own content, not its
    /// position: adding an unrelated candidate to the catalog (which
    /// changes generation order and ranked position for everything after
    /// it) must not change the id of a plan that doesn't use it.
    #[test]
    fn plan_id_is_stable_when_an_unrelated_candidate_is_added_to_the_catalog() {
        let target = barium_titanate_target();
        let baseline = Planner::offline_minimal(barium_titanate_catalog(), generous_config())
            .plan(&target, "2026-08-14T00:00:00Z")
            .unwrap();

        let mut with_extra = vec![
            candidate("BaCO3", &[("Ba", 1.0), ("C", 1.0), ("O", 3.0)]),
            candidate("BaO", &[("Ba", 1.0), ("O", 1.0)]),
            candidate("TiO2", &[("Ti", 1.0), ("O", 2.0)]),
            // Shares no element with the target -- irrelevant to every
            // accepted plan, but changes catalog size/order.
            candidate("NaCl", &[("Na", 1.0), ("Cl", 1.0)]),
        ];
        with_extra.reverse();
        let augmented =
            Planner::offline_minimal(InMemoryPrecursorCatalog::new(with_extra), generous_config())
                .plan(&target, "2026-08-14T00:00:00Z")
                .unwrap();

        let plan_key = |plan: &SynthesisPlan| {
            let mut ids: Vec<String> = plan
                .precursors
                .iter()
                .map(|s| s.precursor.0.clone())
                .collect();
            ids.sort();
            ids
        };
        let baseline_by_precursors: std::collections::BTreeMap<Vec<String>, &str> = baseline
            .plans
            .iter()
            .map(|p| (plan_key(p), p.plan_id.0.as_str()))
            .collect();
        assert!(!baseline_by_precursors.is_empty());

        for plan in &augmented.plans {
            if let Some(&expected_id) = baseline_by_precursors.get(&plan_key(plan)) {
                assert_eq!(
                    plan.plan_id.0.as_str(),
                    expected_id,
                    "plan_id for precursor set {:?} changed after an unrelated catalog addition",
                    plan_key(plan)
                );
            }
        }
    }

    #[test]
    fn missing_availability_metadata_still_flows_through_planning() {
        let with_metadata = InMemoryPrecursorCatalog::new(vec![PrecursorCandidate {
            id: PrecursorId("BaO".to_string()),
            composition: composition(&[("Ba", 1.0), ("O", 1.0)]),
            availability: Some(AvailabilityMetadata {
                source: "curated_fixture".to_string(),
            }),
        }]);
        let target = TargetSpecification {
            composition: composition(&[("Ba", 1.0), ("O", 1.0)]),
            structure: None,
            desired_phase: None,
            constraints: PlanningConstraints::default(),
        };
        let report = Planner::offline_minimal(with_metadata, generous_config())
            .plan(&target, "2026-08-14T00:00:00Z")
            .unwrap();
        assert!(!report.plans.is_empty());
    }
}