xbp-deploy 10.57.0

Service-centric declarative deploy engine for XBP.
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
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

use crate::compose::env_key_looks_secret;
use crate::error::{DeployError, Result};
use crate::failure::{classify_deploy_error, ClassifiedDeployOutcome, DeployFailureClass};
use crate::types::DeployPlan;

/// Prefix for redacted runtime_env placeholders written to disk.
/// Format: `xbp:deploy:{deployment_id}:{SECRET_NAME}:{hash12}`
pub const DEPLOY_SECRET_PLACEHOLDER_PREFIX: &str = "xbp:deploy:";

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HistoryEntry {
    pub id: String,
    pub status: String,
    pub path: String,
    pub timestamp: DateTime<Utc>,
    pub env: String,
    pub target: String,
    /// Stable failure/success code when known (optional for older index rows).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error_code: Option<String>,
    /// Deploy phase when failure was recorded.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub phase: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct DeployHistoryIndex {
    pub entries: Vec<HistoryEntry>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeployHistoryRecord {
    pub id: String,
    pub timestamp: DateTime<Utc>,
    pub env: String,
    pub target: String,
    pub target_kind: String,
    pub status: String,
    pub services: Vec<String>,
    pub git_sha: Option<String>,
    pub project_version: Option<String>,
    /// XBP CLI version that produced this record (semver string).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub xbp_version: Option<String>,
    /// When true, `plan.services[].runtime_env` values that looked secret were
    /// replaced with `xbp:deploy:{id}:{NAME}:{hash}` placeholders; plaintexts
    /// live in xbp.app D1 (`cli_deploy_secret`) when the operator was logged in.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub runtime_env_redacted: Option<bool>,
    pub digests: BTreeMap<String, String>,
    pub kubernetes_context: Option<String>,
    pub namespace: Option<String>,
    pub summary: String,
    pub error: Option<String>,
    /// Stable machine-readable failure class (e.g. `opennext_wsl_failed`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error_code: Option<String>,
    /// Deploy phase where the attempt stopped (`oci_build`, `cf_deploy`, …).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub phase: Option<String>,
    /// Short operator-facing diagnostics (remediation + first error line).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub diagnostics: Vec<String>,
    /// Primary provider from the first plan step (`kubernetes`, `cloudflare-worker`, …).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provider: Option<String>,
    /// Primary destination (`kubernetes`, `cloudflare`, …).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub destination: Option<String>,
    pub plan: DeployPlan,
}

/// One secret extracted from deploy history before writing redacted JSON.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct DeployHistorySecret {
    pub name: String,
    pub value: String,
    /// First 12 hex chars of sha256(value) — embedded in the on-disk placeholder.
    pub hash: String,
    /// Service plan step name that owned this env key (`athena` or `athena@kubernetes`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub service: Option<String>,
}

/// Result of building a history record with secrets stripped for disk.
#[derive(Debug, Clone)]
pub struct SanitizedHistoryRecord {
    pub record: DeployHistoryRecord,
    pub secrets: Vec<DeployHistorySecret>,
}

pub struct DeployHistoryStore {
    pub dir: PathBuf,
}

impl DeployHistoryStore {
    pub fn new(dir: impl Into<PathBuf>) -> Self {
        Self { dir: dir.into() }
    }

    pub fn index_path(&self) -> PathBuf {
        self.dir.join("index.json")
    }

    pub fn load_index(&self) -> Result<DeployHistoryIndex> {
        let path = self.index_path();
        if !path.exists() {
            return Ok(DeployHistoryIndex::default());
        }
        let raw = std::fs::read_to_string(&path).map_err(|e| DeployError::Io(e.to_string()))?;
        // Merge-conflict markers are never trustworthy — rebuild from attempt files.
        if raw.contains("<<<<<<<") || raw.contains(">>>>>>>") {
            return self.rebuild_index_from_records();
        }
        match parse_index_raw(&raw) {
            Ok(index) => Ok(index),
            Err(_) => {
                // Corrupt / partial index — salvage from attempt files.
                self.rebuild_index_from_records()
            }
        }
    }

    /// Rebuild `index.json` solely from `*.json` attempt records on disk.
    pub fn rebuild_index_from_records(&self) -> Result<DeployHistoryIndex> {
        let mut entries = self.scan_record_entries()?;
        // Newest first
        entries.sort_by(|a, b| b.timestamp.cmp(&a.timestamp));
        entries.truncate(200);
        let index = DeployHistoryIndex { entries };
        self.write_index_atomic(&index)?;
        Ok(index)
    }

    /// Scan deployment attempt files (excludes `index.json` and revitalized sidecars).
    pub fn scan_record_entries(&self) -> Result<Vec<HistoryEntry>> {
        if !self.dir.is_dir() {
            return Ok(Vec::new());
        }
        let mut entries = Vec::new();
        let rd = std::fs::read_dir(&self.dir).map_err(|e| DeployError::Io(e.to_string()))?;
        for ent in rd {
            let ent = ent.map_err(|e| DeployError::Io(e.to_string()))?;
            let path = ent.path();
            let name = match path.file_name().and_then(|n| n.to_str()) {
                Some(n) => n.to_string(),
                None => continue,
            };
            if name == "index.json" || !name.ends_with(".json") {
                continue;
            }
            if name.contains(".revitalized.") {
                continue;
            }
            let raw = match std::fs::read_to_string(&path) {
                Ok(r) => r,
                Err(_) => continue,
            };
            let record: DeployHistoryRecord = match serde_json::from_str(&raw) {
                Ok(r) => r,
                Err(_) => continue,
            };
            entries.push(history_entry_from_record(&record, &name));
        }
        Ok(entries)
    }

    fn write_index_atomic(&self, index: &DeployHistoryIndex) -> Result<()> {
        std::fs::create_dir_all(&self.dir).map_err(|e| DeployError::Io(e.to_string()))?;
        let index_body =
            serde_json::to_string_pretty(index).map_err(|e| DeployError::Io(e.to_string()))?;
        let final_path = self.index_path();
        let tmp_path = self.dir.join("index.json.tmp");
        std::fs::write(&tmp_path, index_body).map_err(|e| DeployError::Io(e.to_string()))?;
        // On Windows, rename over existing may fail — remove first.
        if final_path.exists() {
            let _ = std::fs::remove_file(&final_path);
        }
        std::fs::rename(&tmp_path, &final_path).map_err(|e| DeployError::Io(e.to_string()))?;
        Ok(())
    }

    pub fn write_record(&self, record: &DeployHistoryRecord) -> Result<PathBuf> {
        std::fs::create_dir_all(&self.dir).map_err(|e| DeployError::Io(e.to_string()))?;
        let file_name = format!("{}.json", record.id);
        let path = self.dir.join(&file_name);
        let body =
            serde_json::to_string_pretty(record).map_err(|e| DeployError::Io(e.to_string()))?;
        // Atomic-ish: write temp then rename.
        let tmp = self.dir.join(format!("{}.json.tmp", record.id));
        std::fs::write(&tmp, &body).map_err(|e| DeployError::Io(e.to_string()))?;
        if path.exists() {
            let _ = std::fs::remove_file(&path);
        }
        std::fs::rename(&tmp, &path).map_err(|e| DeployError::Io(e.to_string()))?;

        let mut index = self.load_index().unwrap_or_default();
        index.entries.retain(|e| e.id != record.id);
        index
            .entries
            .insert(0, history_entry_from_record(record, &file_name));
        // Cap index size
        index.entries.truncate(200);
        self.write_index_atomic(&index)?;
        Ok(path)
    }

    /// Aggregate counts by `error_code` (falls back to classifying free-text for older records).
    pub fn stats(&self, target: &str, env: &str, limit: usize) -> Result<DeployHistoryStats> {
        let entries = self.list(target, env, limit.max(1))?;
        let mut by_code: BTreeMap<String, usize> = BTreeMap::new();
        let mut by_target: BTreeMap<String, usize> = BTreeMap::new();
        let mut success = 0usize;
        let mut failed = 0usize;
        for entry in &entries {
            *by_target.entry(entry.target.clone()).or_default() += 1;
            if entry.status == "success" {
                success += 1;
                *by_code
                    .entry(DeployFailureClass::Success.as_str().into())
                    .or_default() += 1;
                continue;
            }
            failed += 1;
            let code = if let Some(c) = &entry.error_code {
                c.clone()
            } else if let Ok(Some(rec)) = self.load_record(entry) {
                rec.error_code
                    .or_else(|| {
                        let c = classify_deploy_error(
                            rec.error.as_deref(),
                            &rec.summary,
                            false,
                        );
                        Some(c.error_code.as_str().into())
                    })
                    .unwrap_or_else(|| DeployFailureClass::Unknown.as_str().into())
            } else {
                DeployFailureClass::Unknown.as_str().into()
            };
            *by_code.entry(code).or_default() += 1;
        }
        Ok(DeployHistoryStats {
            total: entries.len(),
            success,
            failed,
            by_error_code: by_code,
            by_target,
        })
    }

    pub fn latest_status(&self, target: &str, env: &str) -> Result<Option<HistoryEntry>> {
        let index = self.load_index()?;
        Ok(index
            .entries
            .into_iter()
            .find(|e| (target == "all" || e.target == target) && (env.is_empty() || e.env == env)))
    }

    pub fn list(&self, target: &str, env: &str, limit: usize) -> Result<Vec<HistoryEntry>> {
        let index = self.load_index()?;
        Ok(index
            .entries
            .into_iter()
            .filter(|e| (target == "all" || e.target == target) && (env.is_empty() || e.env == env))
            .take(limit)
            .collect())
    }

    /// Load a full history JSON record by index entry (relative `path` or id).
    pub fn load_record(&self, entry: &HistoryEntry) -> Result<Option<DeployHistoryRecord>> {
        let candidates = [
            self.dir.join(&entry.path),
            self.dir.join(format!("{}.json", entry.id)),
        ];
        for path in candidates {
            if !path.is_file() {
                continue;
            }
            let raw =
                std::fs::read_to_string(&path).map_err(|e| DeployError::Io(e.to_string()))?;
            let record: DeployHistoryRecord =
                serde_json::from_str(&raw).map_err(|e| DeployError::Io(e.to_string()))?;
            return Ok(Some(record));
        }
        Ok(None)
    }

    /// Load by deployment id (filename without `.json` or full id).
    pub fn load_record_by_id(&self, id: &str) -> Result<Option<DeployHistoryRecord>> {
        let id = id.trim().trim_end_matches(".json");
        if id.is_empty() {
            return Ok(None);
        }
        let path = self.dir.join(format!("{id}.json"));
        if !path.is_file() {
            return Ok(None);
        }
        let raw = std::fs::read_to_string(&path).map_err(|e| DeployError::Io(e.to_string()))?;
        let record: DeployHistoryRecord =
            serde_json::from_str(&raw).map_err(|e| DeployError::Io(e.to_string()))?;
        Ok(Some(record))
    }

    pub fn record_path(&self, id: &str) -> PathBuf {
        let id = id.trim().trim_end_matches(".json");
        self.dir.join(format!("{id}.json"))
    }
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct DeployHistoryStats {
    pub total: usize,
    pub success: usize,
    pub failed: usize,
    pub by_error_code: BTreeMap<String, usize>,
    pub by_target: BTreeMap<String, usize>,
}

fn history_entry_from_record(record: &DeployHistoryRecord, file_name: &str) -> HistoryEntry {
    HistoryEntry {
        id: record.id.clone(),
        status: record.status.clone(),
        path: file_name.to_string(),
        timestamp: record.timestamp,
        env: record.env.clone(),
        target: record.target.clone(),
        error_code: record.error_code.clone(),
        phase: record.phase.clone(),
    }
}

/// Parse index JSON; strip common merge-conflict noise when possible.
pub fn parse_index_raw(raw: &str) -> Result<DeployHistoryIndex> {
    if raw.contains("<<<<<<<") || raw.contains(">>>>>>>") || raw.contains("=======") {
        // Try salvage: drop conflict marker lines and parse remaining JSON.
        let cleaned: String = raw
            .lines()
            .filter(|line| {
                let t = line.trim_start();
                !(t.starts_with("<<<<<<<")
                    || t.starts_with(">>>>>>>")
                    || t.starts_with("======="))
            })
            .collect::<Vec<_>>()
            .join("\n");
        if let Ok(index) = serde_json::from_str::<DeployHistoryIndex>(&cleaned) {
            return Ok(index);
        }
        return Err(DeployError::Io(
            "deploy history index.json contains merge conflict markers".into(),
        ));
    }
    serde_json::from_str(raw).map_err(|e| DeployError::Io(e.to_string()))
}

pub fn make_record_id(env: &str, target: &str, ts: DateTime<Utc>) -> String {
    let safe_target: String = target
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
                c
            } else {
                '_'
            }
        })
        .collect();
    format!("{}-{}-{}", ts.format("%Y%m%dT%H%M%SZ"), env, safe_target)
}

/// sha256 hex truncated to 12 chars for short integrity stubs in placeholders.
pub fn secret_value_hash(value: &str) -> String {
    let digest = Sha256::digest(value.as_bytes());
    digest
        .iter()
        .flat_map(|b| [nibble(b >> 4), nibble(b & 0x0f)])
        .take(12)
        .collect()
}

fn nibble(n: u8) -> char {
    match n {
        0..=9 => (b'0' + n) as char,
        10..=15 => (b'a' + (n - 10)) as char,
        _ => '0',
    }
}

/// Build on-disk placeholder for a secret.
/// Example: `xbp:deploy:20260722T052353Z-production-athena:ATHENA_DB_URL:a1b2c3d4e5f6`
pub fn deploy_secret_placeholder(deployment_id: &str, name: &str, hash: &str) -> String {
    format!("{DEPLOY_SECRET_PLACEHOLDER_PREFIX}{deployment_id}:{name}:{hash}")
}

/// Parse `xbp:deploy:{id}:{NAME}:{hash}` placeholders.
pub fn parse_deploy_secret_placeholder(value: &str) -> Option<(&str, &str, &str)> {
    let rest = value.strip_prefix(DEPLOY_SECRET_PLACEHOLDER_PREFIX)?;
    // deployment_id may contain hyphens/underscores but not colons in practice;
    // name is SCREAMING_SNAKE; hash is 12 hex. Split from the right.
    let (left, hash) = rest.rsplit_once(':')?;
    let (deployment_id, name) = left.rsplit_once(':')?;
    if deployment_id.is_empty() || name.is_empty() || hash.is_empty() {
        return None;
    }
    Some((deployment_id, name, hash))
}

/// Whether this env entry should leave the on-disk history file.
pub fn runtime_env_value_should_redact(key: &str, value: &str) -> bool {
    if value.is_empty() {
        return false;
    }
    if value.starts_with(DEPLOY_SECRET_PLACEHOLDER_PREFIX) {
        return false; // already redacted
    }
    if env_key_looks_secret(key) {
        return true;
    }
    // Connection strings / tokens that slip past key heuristics.
    let v = value.trim();
    if v.contains("://") && v.contains('@') {
        return true; // e.g. postgres://user:pass@host
    }
    // Discord (and similar) webhook endpoints: https://discord.com/api/webhooks/…
    if v.contains("://") && v.to_ascii_lowercase().contains("/webhooks/") {
        return true;
    }
    if v.len() >= 24
        && v.chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '/' | '=' | '_' | '-' | '.'))
    {
        // long opaque tokens
        return true;
    }
    false
}

/// Replace secret runtime_env values on a plan with placeholders; return extracted secrets.
pub fn redact_plan_runtime_env(
    plan: &mut DeployPlan,
    deployment_id: &str,
) -> Vec<DeployHistorySecret> {
    let mut secrets: Vec<DeployHistorySecret> = Vec::new();
    let mut seen: BTreeMap<String, String> = BTreeMap::new(); // name -> hash (dedupe)

    for svc in &mut plan.services {
        let mut next_env = BTreeMap::new();
        for (key, value) in std::mem::take(&mut svc.runtime_env) {
            if runtime_env_value_should_redact(&key, &value) {
                let hash = secret_value_hash(&value);
                let placeholder = deploy_secret_placeholder(deployment_id, &key, &hash);
                if let Some(prev_hash) = seen.get(&key) {
                    if prev_hash != &hash {
                        // Same key, different values across services — namespace by service.
                        let scoped = format!("{}__{}", svc.name.replace('@', "_"), key);
                        let hash2 = secret_value_hash(&value);
                        let ph = deploy_secret_placeholder(deployment_id, &scoped, &hash2);
                        secrets.push(DeployHistorySecret {
                            name: scoped,
                            value: value.clone(),
                            hash: hash2,
                            service: Some(svc.name.clone()),
                        });
                        next_env.insert(key, ph);
                        continue;
                    }
                } else {
                    seen.insert(key.clone(), hash.clone());
                    secrets.push(DeployHistorySecret {
                        name: key.clone(),
                        value: value.clone(),
                        hash: hash.clone(),
                        service: Some(svc.name.clone()),
                    });
                }
                next_env.insert(key, placeholder);
            } else {
                next_env.insert(key, value);
            }
        }
        svc.runtime_env = next_env;
    }
    secrets
}

/// Restore placeholders in a history record using a name→plaintext map from D1.
/// Returns how many placeholders were filled.
pub fn revitalize_record_runtime_env(
    record: &mut DeployHistoryRecord,
    secrets: &BTreeMap<String, String>,
) -> usize {
    let mut filled = 0usize;
    for svc in &mut record.plan.services {
        for (_key, value) in svc.runtime_env.iter_mut() {
            if let Some((dep_id, name, hash)) = parse_deploy_secret_placeholder(value) {
                if dep_id != record.id {
                    continue;
                }
                if let Some(plain) = secrets.get(name) {
                    let actual = secret_value_hash(plain);
                    if actual == hash || hash.is_empty() {
                        *value = plain.clone();
                        filled += 1;
                    }
                }
            }
        }
    }
    if filled > 0 {
        record.runtime_env_redacted = Some(false);
    }
    filled
}

pub fn record_from_plan(
    plan: &DeployPlan,
    ok: bool,
    summary: String,
    error: Option<String>,
    kube_context: Option<String>,
) -> SanitizedHistoryRecord {
    record_from_plan_with_version(plan, ok, summary, error, kube_context, None)
}

pub fn record_from_plan_with_version(
    plan: &DeployPlan,
    ok: bool,
    summary: String,
    error: Option<String>,
    kube_context: Option<String>,
    xbp_version: Option<String>,
) -> SanitizedHistoryRecord {
    let classified = classify_deploy_error(error.as_deref(), &summary, ok);
    record_from_plan_with_classification(
        plan,
        ok,
        summary,
        error,
        kube_context,
        xbp_version,
        classified,
    )
}

pub fn record_from_plan_with_classification(
    plan: &DeployPlan,
    ok: bool,
    summary: String,
    error: Option<String>,
    kube_context: Option<String>,
    xbp_version: Option<String>,
    classified: ClassifiedDeployOutcome,
) -> SanitizedHistoryRecord {
    let ts = Utc::now();
    let id = make_record_id(&plan.env, &plan.target.label(), ts);
    let mut digests = BTreeMap::new();
    for svc in &plan.services {
        if let Some(d) = &svc.digest {
            digests.insert(svc.name.clone(), d.clone());
        }
    }

    let mut plan_for_disk = plan.clone();
    let secrets = redact_plan_runtime_env(&mut plan_for_disk, &id);
    let redacted = !secrets.is_empty();

    let primary = plan.services.first();
    let provider = primary.map(|s| s.provider.clone());
    let destination = primary.and_then(|s| s.destination.clone());

    let (error_code, phase, diagnostics) = if ok {
        (
            Some(DeployFailureClass::Success.as_str().to_string()),
            None,
            Vec::new(),
        )
    } else {
        (
            Some(classified.error_code.as_str().to_string()),
            Some(classified.phase.as_str().to_string()),
            classified.diagnostics,
        )
    };

    let record = DeployHistoryRecord {
        id,
        timestamp: ts,
        env: plan.env.clone(),
        target: plan.target.label(),
        target_kind: plan.target.kind_str().into(),
        status: if ok {
            "success".into()
        } else {
            "failed".into()
        },
        services: plan.order.clone(),
        git_sha: plan.git_sha.clone(),
        project_version: Some(plan.project_version.clone()),
        xbp_version,
        runtime_env_redacted: if redacted { Some(true) } else { None },
        digests,
        kubernetes_context: kube_context,
        namespace: plan
            .services
            .first()
            .and_then(|s| s.deploy.namespace.clone()),
        summary,
        error,
        error_code,
        phase,
        diagnostics,
        provider,
        destination,
        plan: plan_for_disk,
    };

    SanitizedHistoryRecord { record, secrets }
}
/// Path helper for tests.
#[allow(dead_code)]
pub fn history_dir(root: &Path, rel: &Path) -> PathBuf {
    root.join(rel)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::{
        DeployTarget, K8sPlanView, OciPlan, ServiceDeployPlan, ServicePlan,
    };
    use std::collections::BTreeMap;

    fn sample_plan_with_secret() -> DeployPlan {
        let mut env = BTreeMap::new();
        env.insert("PORT".into(), "5052".into());
        env.insert("ATHENA_DEBUG_JWT_SECRET".into(), "super-secret-token-value".into());
        env.insert(
            "DATABASE_URL".into(),
            "postgresql://user:pass@host:5432/db".into(),
        );
        DeployPlan {
            target: DeployTarget::Service("athena".into()),
            env: "production".into(),
            project: "athena".into(),
            project_version: "4.1.0".into(),
            git_sha: Some("abc".into()),
            services: vec![ServicePlan {
                name: "athena".into(),
                provider: "kubernetes".into(),
                destination: Some("kubernetes".into()),
                root_directory: None,
                version: "4.1.0".into(),
                image: None,
                image_ref: None,
                digest: None,
                dockerfile: None,
                build_context: None,
                platforms: vec![],
                worker_app: None,
                rollout: None,
                runtime_env: env,
                container_port: Some(5052),
                config_mounts: vec![],
                expose: None,
                deploy: ServiceDeployPlan {
                    namespace: Some("athena".into()),
                    workload: None,
                    service: None,
                    health: vec![],
                    manifest_paths: vec![],
                    crds_path: None,
                    install_path: None,
                    selector: None,
                    actions: vec![],
                },
            }],
            order: vec!["athena@kubernetes".into()],
            oci_plan: OciPlan::default(),
            k8s_plan: K8sPlanView {
                context: None,
                default_namespace: Some("athena".into()),
                services: vec![],
            },
            hash: "h".into(),
        }
    }

    #[test]
    fn redacts_discord_webhook_urls_even_without_secret_key_suffix() {
        // Live Discord webhook URLs must never land in on-disk history.
        assert!(runtime_env_value_should_redact(
            "DISCORD_WEBHOOK_URL",
            "https://discord.com/api/webhooks/1234567890/abcdefghijklmnopqrstuvwxyz",
        ));
        assert!(runtime_env_value_should_redact(
            "NOTIFY_HOOK",
            "https://discordapp.com/api/webhooks/1/token-here",
        ));
        // Already redacted placeholders stay as-is.
        assert!(!runtime_env_value_should_redact(
            "DISCORD_WEBHOOK_URL",
            "xbp:deploy:id:DISCORD_WEBHOOK_URL:abcdef012345",
        ));
    }

    #[test]
    fn redacts_secrets_and_revitalizes() {
        let plan = sample_plan_with_secret();
        let sanitized = record_from_plan_with_version(
            &plan,
            true,
            "ok".into(),
            None,
            None,
            Some("10.51.1".into()),
        );
        assert_eq!(sanitized.record.xbp_version.as_deref(), Some("10.51.1"));
        assert_eq!(sanitized.record.runtime_env_redacted, Some(true));
        assert!(sanitized.secrets.len() >= 2);

        let env = &sanitized.record.plan.services[0].runtime_env;
        assert_eq!(env.get("PORT").map(String::as_str), Some("5052"));
        let secret_ph = env.get("ATHENA_DEBUG_JWT_SECRET").unwrap();
        assert!(secret_ph.starts_with("xbp:deploy:"));
        assert!(parse_deploy_secret_placeholder(secret_ph).is_some());

        let mut secrets_map = BTreeMap::new();
        for s in &sanitized.secrets {
            secrets_map.insert(s.name.clone(), s.value.clone());
        }
        let mut restored = sanitized.record.clone();
        let n = revitalize_record_runtime_env(&mut restored, &secrets_map);
        assert!(n >= 2);
        assert_eq!(
            restored.plan.services[0]
                .runtime_env
                .get("ATHENA_DEBUG_JWT_SECRET")
                .map(String::as_str),
            Some("super-secret-token-value")
        );
    }

    #[test]
    fn placeholder_roundtrip() {
        let ph = deploy_secret_placeholder("20260722T052353Z-production-athena", "FOO", "abc123def456");
        let (id, name, hash) = parse_deploy_secret_placeholder(&ph).unwrap();
        assert_eq!(id, "20260722T052353Z-production-athena");
        assert_eq!(name, "FOO");
        assert_eq!(hash, "abc123def456");
    }

    #[test]
    fn classifies_on_record_write_path() {
        let plan = sample_plan_with_secret();
        let sanitized = record_from_plan_with_version(
            &plan,
            false,
            "failed".into(),
            Some("OpenNext WSL deploy failed with status exit code: 1.".into()),
            None,
            Some("10.54.0".into()),
        );
        assert_eq!(
            sanitized.record.error_code.as_deref(),
            Some("opennext_wsl_failed")
        );
        assert_eq!(sanitized.record.phase.as_deref(), Some("opennext"));
        assert_eq!(sanitized.record.provider.as_deref(), Some("kubernetes"));
        assert!(!sanitized.record.diagnostics.is_empty());
    }

    #[test]
    fn index_salvages_merge_conflict_markers() {
        let dir = std::env::temp_dir().join(format!(
            "xbp-deploy-history-test-{}",
            std::process::id()
        ));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let store = DeployHistoryStore::new(&dir);

        let plan = sample_plan_with_secret();
        let sanitized = record_from_plan(&plan, true, "deploy succeeded".into(), None, None);
        store.write_record(&sanitized.record).unwrap();

        // Corrupt index with merge conflict markers (as seen on athena).
        let corrupt = r#"{
  "entries": [
<<<<<<< Updated upstream
=======
    {
      "id": "stale",
      "status": "failed",
      "path": "stale.json",
      "timestamp": "2026-07-22T13:45:02.303897600Z",
      "env": "production",
      "target": "next-heroui-example"
    },
>>>>>>> Stashed changes
    {
      "id": "keep-me",
      "status": "success",
      "path": "keep-me.json",
      "timestamp": "2026-07-22T05:23:53.154691300Z",
      "env": "production",
      "target": "athena"
    }
  ]
}
"#;
        std::fs::write(dir.join("index.json"), corrupt).unwrap();

        // load_index should rebuild from on-disk attempt records.
        let index = store.load_index().unwrap();
        assert!(
            index.entries.iter().any(|e| e.id == sanitized.record.id),
            "rebuilt index should include written record"
        );
        assert!(
            !index.entries.iter().any(|e| e.id == "stale"),
            "stale conflict-only entry without a file should not appear after rebuild"
        );

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn parse_index_strips_conflict_markers_when_json_salvageable() {
        let raw = r#"{
  "entries": [
<<<<<<< Updated upstream
=======
    {
      "id": "a",
      "status": "failed",
      "path": "a.json",
      "timestamp": "2026-07-22T13:45:02.303897600Z",
      "env": "production",
      "target": "x"
    }
>>>>>>> Stashed changes
  ]
}
"#;
        // After stripping markers, JSON is valid with one entry.
        let index = parse_index_raw(raw).unwrap();
        assert_eq!(index.entries.len(), 1);
        assert_eq!(index.entries[0].id, "a");
    }
}