xbp 10.26.1

XBP is a zero-config build pack that can also interact with proxies, kafka, sockets, synthetic monitors.
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
//! config command module
//!
//! locates and prints project config from yaml/json files
//! when debug is enabled prints resolution details and raw config
//! displays configuration in a simple aligned table format
use crate::cli::auto_commit::{commit_paths, print_skip, AutoCommitRequest, AutoCommitResult};
use crate::commands::linear::{fetch_available_initiatives, LinearInitiativeSummary};
use crate::commands::ssh_helpers::prompt_for_password;
use crate::config::{global_xbp_paths, resolve_linear_api_key, SecretProvider, SshConfig};
use crate::logging::{get_prefix, log_info};
use crate::strategies::project_detector::{
    infer_project_name as shared_infer_project_name, infer_target as shared_infer_target,
    DeploymentRecommendations,
};
use crate::strategies::{ProjectDetector, ProjectType, XbpConfig};
use crate::utils::{
    collapse_project_path, default_project_yaml_config_path, find_xbp_config_upwards,
    maybe_auto_convert_legacy_xbp_json_to_yaml, parse_config_with_auto_heal, FoundXbpConfig,
};
use crate::utils::{open_path_with_editor, open_with_default_handler};
use dialoguer::{theme::ColorfulTheme, FuzzySelect};
use serde_json::{Map, Value};
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use tracing::{debug, error, info};

const GITHUB_CLASSIC_PAT_URL: &str = "https://github.com/settings/tokens";

/// Execute the `config` command.
///
/// Prints discovered configuration keys and values in a simple aligned table.
/// Returns `Ok(())` even when no config is found to keep UX friendly.
pub async fn run_config(debug: bool) -> Result<(), String> {
    let current_dir: PathBuf =
        env::current_dir().map_err(|e| format!("Failed to get current directory: {}", e))?;
    let found = find_xbp_config_upwards(&current_dir);
    let project_root = found
        .as_ref()
        .map(|f| f.project_root.clone())
        .unwrap_or_else(|| current_dir.clone());

    let xbp_yaml_path_dotfolder: PathBuf = project_root.join(".xbp/xbp.yaml");
    let xbp_yml_path_dotfolder: PathBuf = project_root.join(".xbp/xbp.yml");
    let xbp_json_path_dotfolder: PathBuf = project_root.join(".xbp/xbp.json");

    let xbp_yaml_path_root: PathBuf = project_root.join("xbp.yaml");
    let xbp_yml_path_root: PathBuf = project_root.join("xbp.yml");
    let xbp_json_path_root: PathBuf = project_root.join("xbp.json");

    if debug {
        debug!("Current dir: {}", current_dir.display());
        debug!("Project root: {}", project_root.display());
        debug!("Checking for: {}", xbp_yaml_path_dotfolder.display());
        debug!("Checking for: {}", xbp_yml_path_dotfolder.display());
        debug!("Checking for: {}", xbp_json_path_dotfolder.display());
        debug!("Checking for: {}", xbp_yaml_path_root.display());
        debug!("Checking for: {}", xbp_yml_path_root.display());
        debug!("Checking for: {}", xbp_json_path_root.display());
    }

    let (mut found_path, mut found_location, mut kind): (Option<PathBuf>, Option<String>, &str) =
        if let Some(f) = &found {
            (
                Some(f.config_path.clone()),
                Some(f.location.clone()),
                f.kind,
            )
        } else if xbp_yaml_path_dotfolder.exists() {
            (
                Some(xbp_yaml_path_dotfolder.clone()),
                Some(".xbp/xbp.yaml".to_string()),
                "yaml",
            )
        } else if xbp_yml_path_dotfolder.exists() {
            (
                Some(xbp_yml_path_dotfolder.clone()),
                Some(".xbp/xbp.yml".to_string()),
                "yaml",
            )
        } else if xbp_json_path_dotfolder.exists() {
            (
                Some(xbp_json_path_dotfolder.clone()),
                Some(".xbp/xbp.json".to_string()),
                "json",
            )
        } else if xbp_yaml_path_root.exists() {
            (
                Some(xbp_yaml_path_root.clone()),
                Some("xbp.yaml".to_string()),
                "yaml",
            )
        } else if xbp_yml_path_root.exists() {
            (
                Some(xbp_yml_path_root.clone()),
                Some("xbp.yml".to_string()),
                "yaml",
            )
        } else if xbp_json_path_root.exists() {
            (
                Some(xbp_json_path_root.clone()),
                Some("xbp.json".to_string()),
                "json",
            )
        } else {
            (None, None, "unknown")
        };

    if kind == "json" {
        if let Some(path) = &found_path {
            if let Ok(Some(yaml_path)) =
                maybe_auto_convert_legacy_xbp_json_to_yaml(&project_root, path)
            {
                let yaml_location = yaml_path
                    .strip_prefix(&project_root)
                    .ok()
                    .map(|p| p.to_string_lossy().replace('\\', "/"))
                    .unwrap_or_else(|| yaml_path.to_string_lossy().replace('\\', "/"));
                found_path = Some(yaml_path);
                found_location = Some(yaml_location);
                kind = "yaml";
            }
        }
    }

    if found_path.is_none() {
        let detected: Option<ProjectType> = ProjectDetector::detect_project_type(&current_dir)
            .await
            .ok();
        let recommendations: Option<DeploymentRecommendations> =
            detected.as_ref().map(|detected| {
                ProjectDetector::get_deployment_recommendations(&current_dir, detected)
            });

        let default_port: u16 = recommendations
            .as_ref()
            .map(|r| r.default_port)
            .unwrap_or(8080);

        let target = detected.as_ref().and_then(shared_infer_target);

        let baseline: XbpConfig = XbpConfig {
            project_name: match (detected.as_ref(), recommendations.as_ref()) {
                (Some(detected), Some(recommendations)) => {
                    shared_infer_project_name(&current_dir, detected, recommendations)
                }
                _ => current_dir
                    .file_name()
                    .and_then(|n| n.to_str())
                    .unwrap_or("app")
                    .to_string(),
            },
            version: "0.1.0".to_string(),
            port: default_port,
            build_dir: collapse_project_path(&current_dir, current_dir.to_string_lossy().as_ref()),
            app_type: target.clone(),
            build_command: recommendations
                .as_ref()
                .and_then(|r| r.build_command.clone()),
            start_command: recommendations
                .as_ref()
                .and_then(|r| r.start_command.clone()),
            install_command: recommendations
                .as_ref()
                .and_then(|r| r.install_command.clone()),
            environment: None,
            services: None,
            systemd_service_name: None,
            systemd: None,
            kafka_brokers: None,
            kafka_topic: None,
            kafka_public_url: None,
            log_files: None,
            monitor_url: None,
            monitor_method: None,
            monitor_expected_code: None,
            monitor_interval: None,
            database: None,
            target,
            branch: Some("main".to_string()),
            crate_name: None,
            npm_script: None,
            port_storybook: None,
            url: None,
            url_storybook: None,
            linear: None,
        };

        if let Err(e) = fs::create_dir_all(current_dir.join(".xbp")) {
            let msg: String = format!("Failed to create .xbp directory: {}", e);
            error!("{}", msg);
            eprintln!("{}", msg);
        } else {
            let out_yaml = current_dir.join(".xbp/xbp.yaml");
            if let Ok(yaml) = serde_yaml::to_string(&baseline) {
                if fs::write(&out_yaml, yaml).is_ok() {
                    found_path = Some(out_yaml);
                    found_location = Some(".xbp/xbp.yaml".to_string());
                    kind = "yaml";
                    println!("Generated .xbp/xbp.yaml from detected manifests.");
                }
            }
        }
    }

    if let (Some(path), Some(location)) = (found_path, found_location) {
        let _ = log_info(
            "config",
            &format!("Found config at: {}", path.display()),
            None,
        )
        .await;
        println!("Found config at: {}", path.display());

        match fs::read_to_string(&path) {
            Ok(contents) => {
                if debug {
                    debug!("config contents: {}", contents);
                }
                let data = if kind == "yaml" {
                    serde_yaml::from_str::<serde_yaml::Value>(&contents)
                        .ok()
                        .and_then(|v| serde_json::to_value(v).ok())
                } else {
                    serde_json::from_str::<serde_json::Value>(&contents).ok()
                };

                if let Some(json_data) = data {
                    let prefix = get_prefix();
                    println!("\nConfiguration:");
                    println!("{}", "─".repeat(50));
                    for (key, value) in json_data.as_object().unwrap() {
                        let value_str: String = value.to_string().replace("\"", "");
                        println!("{:<15} |   {}", key, value_str);
                        info!("{}{:<15} |   {}", prefix, key, value_str);
                    }
                    println!("{}", "─".repeat(50));
                } else {
                    let msg = format!("Failed to parse {} contents.", location);
                    error!("{}", msg);
                    eprintln!("{}", msg);
                }
            }
            Err(e) => {
                let msg = format!("Failed to read {}: {}", location, e);
                error!("{}", msg);
                eprintln!("{}", msg);
            }
        }
    } else {
        let msg =
            "No .xbp/xbp.yaml|.yml|.json or xbp.yaml|.yml|.json found in the current directory.";
        error!("{}", msg);
        eprintln!("{}", msg);
    }

    Ok(())
}

pub async fn open_global_config(no_open: bool) -> Result<(), String> {
    let paths = global_xbp_paths()?;

    println!("Global XBP directory: {}", paths.root_dir.display());
    println!("Config file: {}", paths.config_file.display());
    println!("SSH directory: {}", paths.ssh_dir.display());
    println!("Cache directory: {}", paths.cache_dir.display());
    println!("Logs directory: {}", paths.logs_dir.display());

    if no_open {
        return Ok(());
    }

    let _ = open_with_default_handler(&paths.root_dir.display().to_string());
    let _ = open_path_with_editor(&paths.config_file);

    Ok(())
}

pub async fn run_config_secret_set(provider_key: &str, key: Option<String>) -> Result<(), String> {
    let provider = SecretProvider::from_key(provider_key).ok_or_else(|| {
        format!(
            "Unsupported provider `{}`. Use `openrouter`, `github`, or `linear`.",
            provider_key
        )
    })?;

    let mut config = SshConfig::load()?;
    let resolved_key = match key {
        Some(value) => value.trim().to_string(),
        None => prompt_for_password(&format!("Enter {} key/token: ", provider.as_key()))?,
    };

    if resolved_key.trim().is_empty() {
        if provider == SecretProvider::Github {
            let _ = open_with_default_handler(GITHUB_CLASSIC_PAT_URL);
            println!(
                "No GitHub key/token provided.\nOpened: {}\nCreate a Personal Access Token (classic), copy it, then run `xbp config github set-key` again.",
                GITHUB_CLASSIC_PAT_URL
            );
            return Ok(());
        }
        return Err("Refusing to store an empty key/token.".to_string());
    }

    config.set_secret(provider, Some(resolved_key.clone()));
    config.save()?;

    println!(
        "Saved {} in global config field `{}`: {}",
        provider.as_key(),
        provider.config_field(),
        mask_secret(&resolved_key)
    );
    Ok(())
}

pub async fn run_config_secret_delete(provider_key: &str) -> Result<(), String> {
    let provider = SecretProvider::from_key(provider_key).ok_or_else(|| {
        format!(
            "Unsupported provider `{}`. Use `openrouter`, `github`, or `linear`.",
            provider_key
        )
    })?;

    let mut config = SshConfig::load()?;
    if config.get_secret(provider).is_none() {
        println!("No {} key/token is currently set.", provider.as_key());
        return Ok(());
    }

    config.set_secret(provider, None);
    config.save()?;
    println!(
        "Deleted {} key/token from global config.",
        provider.as_key()
    );
    Ok(())
}

pub async fn run_config_secret_show(provider_key: &str, raw: bool) -> Result<(), String> {
    let provider = SecretProvider::from_key(provider_key).ok_or_else(|| {
        format!(
            "Unsupported provider `{}`. Use `openrouter`, `github`, or `linear`.",
            provider_key
        )
    })?;

    let config = SshConfig::load()?;
    if let Some(secret) = config.get_secret(provider) {
        let display = if raw {
            secret.to_string()
        } else {
            mask_secret(secret)
        };
        println!(
            "{} key/token is set in `{}`: {}",
            provider.as_key(),
            provider.config_field(),
            display
        );
    } else {
        println!(
            "{} key/token is not configured in `{}`.",
            provider.as_key(),
            provider.config_field()
        );
    }

    Ok(())
}

pub async fn run_config_linear_select_initiative() -> Result<(), String> {
    let current_dir =
        env::current_dir().map_err(|e| format!("Failed to get current directory: {}", e))?;
    let found = find_xbp_config_upwards(&current_dir).ok_or_else(|| {
        "No XBP project config found in the current directory tree. Run this inside a repo with `.xbp/xbp.yaml` or `xbp.yaml`.".to_string()
    })?;

    let linear_api_key = resolve_linear_api_key().ok_or_else(|| {
        "No Linear API key found. Configure one first with `xbp config linear set-key`.".to_string()
    })?;

    let initiatives = fetch_available_initiatives(&linear_api_key).await?;
    if initiatives.is_empty() {
        println!("No accessible Linear initiatives were found for the configured API key.");
        return Ok(());
    }

    let labels = initiatives
        .iter()
        .map(format_linear_initiative_label)
        .collect::<Vec<_>>();

    let selection = FuzzySelect::with_theme(&ColorfulTheme::default())
        .with_prompt("Select a Linear initiative for this repo")
        .default(0)
        .items(&labels)
        .interact_opt()
        .map_err(|e| format!("Failed to run initiative picker: {}", e))?;

    let Some(selection) = selection else {
        println!("No initiative selected. Repo config was not changed.");
        return Ok(());
    };

    let selected = initiatives
        .get(selection)
        .ok_or_else(|| "Selected initiative index was out of range.".to_string())?;
    let saved_path = save_repo_linear_initiative(&found, selected)?;

    println!(
        "Saved Linear initiative `{}` ({}) to {}",
        selected.name,
        selected.id,
        saved_path.display()
    );

    match commit_paths(AutoCommitRequest {
        project_root: &found.project_root,
        paths: vec![saved_path],
        message: format!("chore(config): set Linear initiative to {}", selected.id),
        action_label: "xbp config linear select-initiative",
    })
    .await
    {
        Ok(AutoCommitResult::Committed(_)) => {}
        Ok(AutoCommitResult::Skipped(reason)) => {
            print_skip("xbp config linear select-initiative", &reason)
        }
        Err(e) => print_skip("xbp config linear select-initiative", &e),
    }

    Ok(())
}

fn mask_secret(secret: &str) -> String {
    let chars: Vec<char> = secret.chars().collect();
    if chars.is_empty() {
        return "(empty)".to_string();
    }

    if chars.len() <= 8 {
        return "*".repeat(chars.len());
    }

    let prefix: String = chars.iter().take(4).collect();
    let suffix: String = chars.iter().skip(chars.len() - 4).collect();
    format!("{}...{}", prefix, suffix)
}

fn format_linear_initiative_label(initiative: &LinearInitiativeSummary) -> String {
    let mut parts = vec![initiative.name.trim().to_string()];

    if let Some(status) = non_empty_text(initiative.status.as_deref()) {
        parts.push(format!("[{}]", status));
    }

    if let Some(owner) = non_empty_text(initiative.owner_name.as_deref()) {
        parts.push(owner.to_string());
    }

    if let Some(target_date) = non_empty_text(initiative.target_date.as_deref()) {
        parts.push(target_date.to_string());
    }

    parts.join("  ")
}

fn save_repo_linear_initiative(
    found: &FoundXbpConfig,
    initiative: &LinearInitiativeSummary,
) -> Result<PathBuf, String> {
    let (mut config, output_path) = load_project_config_for_repo_linear_update(found)?;
    set_repo_linear_release_initiative(&mut config, initiative.id.clone())?;
    write_project_yaml_config(&output_path, &config)?;
    Ok(output_path)
}

fn load_project_config_for_repo_linear_update(
    found: &FoundXbpConfig,
) -> Result<(Value, PathBuf), String> {
    let source_path = if found.kind == "json" {
        maybe_auto_convert_legacy_xbp_json_to_yaml(&found.project_root, &found.config_path)?
            .unwrap_or_else(|| default_project_yaml_config_path(&found.project_root))
    } else {
        found.config_path.clone()
    };

    let kind = if source_path
        .extension()
        .and_then(|ext| ext.to_str())
        .map(|ext| ext.eq_ignore_ascii_case("yaml") || ext.eq_ignore_ascii_case("yml"))
        .unwrap_or(false)
    {
        "yaml"
    } else {
        "json"
    };

    let content = fs::read_to_string(&source_path)
        .map_err(|e| format!("Failed to read config {}: {}", source_path.display(), e))?;
    let (config, _healed_content) = parse_config_with_auto_heal::<Value>(&content, kind)
        .map_err(|e| format!("Failed to parse project config: {}", e))?;

    Ok((
        config,
        default_project_yaml_config_path(&found.project_root),
    ))
}

fn set_repo_linear_release_initiative(
    config: &mut Value,
    initiative_id: String,
) -> Result<(), String> {
    let root = config
        .as_object_mut()
        .ok_or_else(|| "Project config root must be an object.".to_string())?;

    let linear = root
        .entry("linear".to_string())
        .or_insert_with(|| Value::Object(Map::new()));
    if linear.is_null() {
        *linear = Value::Object(Map::new());
    }
    let linear = linear
        .as_object_mut()
        .ok_or_else(|| "Project config `linear` field must be an object if present.".to_string())?;

    let release = linear
        .entry("release".to_string())
        .or_insert_with(|| Value::Object(Map::new()));
    if release.is_null() {
        *release = Value::Object(Map::new());
    }
    let release = release.as_object_mut().ok_or_else(|| {
        "Project config `linear.release` field must be an object if present.".to_string()
    })?;

    release.insert(
        "initiative_ids".to_string(),
        Value::Array(vec![Value::String(initiative_id)]),
    );

    Ok(())
}

fn write_project_yaml_config(path: &Path, config: &Value) -> Result<(), String> {
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).map_err(|e| {
            format!(
                "Failed to create config directory {}: {}",
                parent.display(),
                e
            )
        })?;
    }

    let content = serde_yaml::to_string(config)
        .map_err(|e| format!("Failed to serialize project config: {}", e))?;
    fs::write(path, content)
        .map_err(|e| format!("Failed to write project config {}: {}", path.display(), e))
}

fn non_empty_text(value: Option<&str>) -> Option<&str> {
    value.map(str::trim).filter(|value| !value.is_empty())
}

#[cfg(test)]
mod tests {
    use super::{
        format_linear_initiative_label, load_project_config_for_repo_linear_update,
        save_repo_linear_initiative, set_repo_linear_release_initiative,
    };
    use crate::commands::linear::LinearInitiativeSummary;
    use crate::utils::FoundXbpConfig;
    use serde_json::{json, Value};
    use std::env;
    use std::fs;
    use std::path::PathBuf;
    use std::time::{SystemTime, UNIX_EPOCH};

    #[test]
    fn creates_linear_release_block_when_missing() {
        let mut config = sample_xbp_config();

        set_repo_linear_release_initiative(&mut config, "initiative-1".to_string())
            .expect("set initiative");

        let release = config
            .get("linear")
            .and_then(|linear| linear.get("release"))
            .expect("release config");
        assert_eq!(
            release.get("initiative_ids"),
            Some(&json!(["initiative-1"]))
        );
        assert!(release.get("enabled").is_none());
        assert!(release.get("health").is_none());
    }

    #[test]
    fn replaces_repo_linear_initiatives_and_preserves_enabled_and_health() {
        let mut config = json!({
            "project_name": "XBP",
            "version": "10.22.0",
            "port": 3398,
            "build_dir": "./",
            "linear": {
                "release": {
                    "enabled": false,
                    "initiative_ids": ["old-1", "old-2"],
                    "health": "at_risk"
                }
            }
        });

        set_repo_linear_release_initiative(&mut config, "new-initiative".to_string())
            .expect("set initiative");

        let release = config
            .get("linear")
            .and_then(|linear| linear.get("release"))
            .expect("release config");
        assert_eq!(
            release.get("initiative_ids"),
            Some(&json!(["new-initiative"]))
        );
        assert_eq!(release.get("enabled"), Some(&json!(false)));
        assert_eq!(release.get("health"), Some(&json!("at_risk")));
    }

    #[test]
    fn formats_initiative_labels_when_optional_fields_are_missing() {
        let label = format_linear_initiative_label(&LinearInitiativeSummary {
            id: "initiative-1".to_string(),
            name: "Formations live".to_string(),
            status: Some("Active".to_string()),
            health: None,
            archived_at: None,
            target_date: None,
            owner_name: None,
        });

        assert_eq!(label, "Formations live  [Active]");
    }

    #[test]
    fn converts_json_only_repo_config_and_writes_selected_initiative_to_yaml() {
        let temp_dir = create_temp_dir("linear-select-json");
        let dot_xbp = temp_dir.join(".xbp");
        fs::create_dir_all(&dot_xbp).expect("create .xbp");
        let json_path = dot_xbp.join("xbp.json");
        fs::write(
            &json_path,
            r#"{
  "project_name": "XBP",
  "version": "10.22.0",
  "port": 3398,
  "build_dir": "./",
  "linear": {
    "release": {
      "enabled": true,
      "health": "off_track",
      "initiative_ids": ["legacy-id"]
    }
  }
}"#,
        )
        .expect("write json config");

        let found = FoundXbpConfig {
            project_root: temp_dir.clone(),
            config_path: json_path,
            kind: "json",
            location: ".xbp/xbp.json".to_string(),
        };
        let selected = LinearInitiativeSummary {
            id: "new-id".to_string(),
            name: "Changelog".to_string(),
            status: Some("Active".to_string()),
            health: Some("onTrack".to_string()),
            archived_at: None,
            target_date: None,
            owner_name: Some("floris".to_string()),
        };

        let saved_path = save_repo_linear_initiative(&found, &selected).expect("save config");
        let rendered = fs::read_to_string(&saved_path).expect("read yaml config");

        assert_eq!(saved_path, temp_dir.join(".xbp").join("xbp.yaml"));
        assert!(rendered.contains("initiative_ids:"));
        assert!(rendered.contains("- new-id"));
        assert!(rendered.contains("enabled: true"));
        assert!(rendered.contains("health: off_track"));

        let _ = fs::remove_dir_all(temp_dir);
    }

    #[test]
    fn loads_existing_yaml_config_for_repo_linear_update() {
        let temp_dir = create_temp_dir("linear-select-yaml");
        let dot_xbp = temp_dir.join(".xbp");
        fs::create_dir_all(&dot_xbp).expect("create .xbp");
        let yaml_path = dot_xbp.join("xbp.yaml");
        fs::write(
            &yaml_path,
            r#"project_name: XBP
version: 10.22.0
port: 3398
build_dir: ./
"#,
        )
        .expect("write yaml config");

        let found = FoundXbpConfig {
            project_root: temp_dir.clone(),
            config_path: yaml_path.clone(),
            kind: "yaml",
            location: ".xbp/xbp.yaml".to_string(),
        };

        let (_, output_path) =
            load_project_config_for_repo_linear_update(&found).expect("load config");
        assert_eq!(output_path, yaml_path);

        let _ = fs::remove_dir_all(temp_dir);
    }

    #[test]
    fn saves_initiative_for_repo_config_missing_top_level_port() {
        let temp_dir = create_temp_dir("linear-select-missing-port");
        let dot_xbp = temp_dir.join(".xbp");
        fs::create_dir_all(&dot_xbp).expect("create .xbp");
        let yaml_path = dot_xbp.join("xbp.yaml");
        fs::write(
            &yaml_path,
            r#"project_name: XBP
build_dir: ./
services:
  - name: web
    target: nextjs
    branch: main
    port: 3000
"#,
        )
        .expect("write yaml config");

        let found = FoundXbpConfig {
            project_root: temp_dir.clone(),
            config_path: yaml_path,
            kind: "yaml",
            location: ".xbp/xbp.yaml".to_string(),
        };
        let selected = LinearInitiativeSummary {
            id: "initiative-1".to_string(),
            name: "Changelog".to_string(),
            status: Some("Active".to_string()),
            health: None,
            archived_at: None,
            target_date: None,
            owner_name: None,
        };

        let saved_path = save_repo_linear_initiative(&found, &selected).expect("save config");
        let rendered = fs::read_to_string(saved_path).expect("read yaml config");

        assert!(rendered.contains("initiative_ids:"));
        assert!(rendered.contains("- initiative-1"));
        assert!(rendered.contains("services:"));

        let _ = fs::remove_dir_all(temp_dir);
    }

    fn sample_xbp_config() -> Value {
        json!({
            "project_name": "XBP",
            "version": "10.22.0",
            "port": 3398,
            "build_dir": "./"
        })
    }

    fn create_temp_dir(name: &str) -> PathBuf {
        let unique = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("time")
            .as_nanos();
        let dir = env::temp_dir().join(format!("xbp-{}-{}", name, unique));
        fs::create_dir_all(&dir).expect("create temp dir");
        dir
    }
}