xbp 10.57.0

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
//! Deploy history helpers for non-engine entrypoints (cloudflare / workers)
//! and operator UX (repeated-failure warnings).

use std::path::Path;

use colored::Colorize;
use xbp_deploy::{
    classify_deploy_error, record_from_plan_with_version, DeployHistoryStore, DeployPlan,
    DeployTarget, K8sPlanView, OciPlan, ServiceDeployPlan, ServicePlan,
};

/// Paths under `.xbp/` that should not block publish (local deploy/release ledger noise).
pub fn is_xbp_ledger_noise_path(path: &str) -> bool {
    let p = path.replace('\\', "/").trim().trim_start_matches("./").to_string();
    let lower = p.to_ascii_lowercase();
    if lower.contains("/.xbp/deployments/")
        || lower.starts_with(".xbp/deployments/")
        || lower.contains("/.xbp/releases/")
        || lower.starts_with(".xbp/releases/")
    {
        return true;
    }
    if lower.ends_with("/.xbp/last-version-scope")
        || lower == ".xbp/last-version-scope"
        || lower.ends_with("/.xbp/deploy.lock")
        || lower == ".xbp/deploy.lock"
        || lower.ends_with("/.xbp/opennext-deploy.log")
        || lower.ends_with("opennext-deploy.log")
    {
        return true;
    }
    // Nested package ledgers: packages/foo/.xbp/deployments/...
    if lower.contains("/.xbp/")
        && (lower.contains("deployments/")
            || lower.contains("releases/")
            || lower.ends_with("last-version-scope")
            || lower.ends_with("deploy.lock")
            || lower.ends_with("opennext-deploy.log"))
    {
        return true;
    }
    false
}

/// Extract path from a `git status --porcelain` line and test ledger noise.
pub fn porcelain_line_is_xbp_ledger_noise(line: &str) -> bool {
    let path = porcelain_path(line);
    !path.is_empty() && is_xbp_ledger_noise_path(&path)
}

fn porcelain_path(line: &str) -> String {
    // XY PATH or XY PATH -> PATH2 or "quoted path"
    let rest = if line.len() >= 3 { &line[3..] } else { line.trim() };
    let rest = rest.trim();
    if let Some((left, _)) = rest.split_once(" -> ") {
        return unquote(left.trim());
    }
    unquote(rest)
}

fn unquote(s: &str) -> String {
    let s = s.trim();
    if s.starts_with('"') && s.ends_with('"') && s.len() >= 2 {
        s[1..s.len() - 1].replace("\\\"", "\"").replace("\\\\", "\\")
    } else {
        s.to_string()
    }
}

/// Record a Cloudflare / OpenNext deploy attempt under project `.xbp/deployments/`.
pub fn record_cloudflare_cli_deploy(
    project_root: &Path,
    app_name: &str,
    provider: &str,
    ok: bool,
    summary: &str,
    error: Option<&str>,
) {
    let history_dir = project_root.join(".xbp").join("deployments");
    let plan = minimal_cf_plan(project_root, app_name, provider);
    let xbp_version = Some(env!("CARGO_PKG_VERSION").to_string());
    let err = error.map(str::to_string);
    let sanitized = record_from_plan_with_version(
        &plan,
        ok,
        summary.to_string(),
        err,
        None,
        xbp_version,
    );
    let store = DeployHistoryStore::new(&history_dir);
    match store.write_record(&sanitized.record) {
        Ok(path) => {
            println!(
                "{} deploy history {}{}",
                "·".dimmed(),
                sanitized.record.id.bright_cyan(),
                path.display().to_string().dimmed()
            );
        }
        Err(e) => {
            eprintln!(
                "{} could not write deploy history: {e}",
                "!".bright_yellow()
            );
        }
    }
}

fn minimal_cf_plan(project_root: &Path, app_name: &str, provider: &str) -> DeployPlan {
    let project = project_root
        .file_name()
        .and_then(|s| s.to_str())
        .unwrap_or("project")
        .to_string();
    DeployPlan {
        target: DeployTarget::Service(app_name.to_string()),
        env: "production".into(),
        project,
        project_version: env!("CARGO_PKG_VERSION").into(),
        git_sha: None,
        services: vec![ServicePlan {
            name: app_name.to_string(),
            provider: provider.to_string(),
            destination: Some("cloudflare".into()),
            root_directory: None,
            version: env!("CARGO_PKG_VERSION").into(),
            image: None,
            image_ref: None,
            digest: None,
            dockerfile: None,
            build_context: None,
            platforms: vec![],
            worker_app: Some(app_name.to_string()),
            rollout: None,
            runtime_env: Default::default(),
            container_port: None,
            config_mounts: vec![],
            expose: None,
            deploy: ServiceDeployPlan {
                namespace: None,
                workload: None,
                service: None,
                health: vec![],
                manifest_paths: vec![],
                crds_path: None,
                install_path: None,
                selector: None,
                actions: vec!["cloudflare cli deploy".into()],
            },
        }],
        order: vec![format!("{app_name}@cloudflare")],
        oci_plan: OciPlan::default(),
        k8s_plan: K8sPlanView {
            context: None,
            default_namespace: None,
            services: vec![],
        },
        hash: "cli-cf".into(),
    }
}

/// Built-in operator check: repair history, print stats, optionally scan sibling repos.
///
/// Replaces external verify scripts — use:
///   `xbp deploy --engine-check`
///   `xbp deploy --engine-check --scan`
pub fn run_engine_check(
    project_root: &Path,
    project_name: &str,
    history_dir: &Path,
    env: &str,
    history_limit: usize,
    scan_siblings: bool,
    json: bool,
) -> Result<(), String> {
    let limit = history_limit.max(1);
    let mut reports: Vec<EngineCheckReport> = Vec::new();

    reports.push(check_one_project(project_root, project_name, history_dir, env, limit)?);

    if scan_siblings {
        for (root, name, hdir) in discover_sibling_history_projects(project_root) {
            if root == project_root {
                continue;
            }
            match check_one_project(&root, &name, &hdir, env, limit) {
                Ok(r) => reports.push(r),
                Err(e) => {
                    eprintln!(
                        "{} skip {}: {e}",
                        "!".bright_yellow(),
                        root.display()
                    );
                }
            }
        }
    }

    if json {
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::json!({
                "engine_check": true,
                "projects": reports.iter().map(|r| serde_json::json!({
                    "project": r.project_name,
                    "root": r.root,
                    "history_dir": r.history_dir,
                    "entries": r.entries,
                    "success": r.success,
                    "failed": r.failed,
                    "by_error_code": r.by_error_code,
                    "repaired": r.repaired,
                })).collect::<Vec<_>>(),
            }))
            .map_err(|e| e.to_string())?
        );
        return Ok(());
    }

    println!();
    println!(
        "{} xbp deploy engine-check",
        "".bright_magenta().bold()
    );
    println!(
        "{}",
        "repair history · classify failures · multi-repo scan (optional)".dimmed()
    );
    println!("{}", "".repeat(72).bright_black());

    for r in &reports {
        println!();
        println!(
            "{} {}  {}",
            "".bright_cyan().bold(),
            r.project_name.bright_white().bold(),
            r.root.dimmed()
        );
        println!(
            "  {} {} entries  ok={}  fail={}",
            "history:".bright_black(),
            r.entries,
            r.success.to_string().bright_green(),
            r.failed.to_string().bright_red()
        );
        if r.repaired {
            println!(
                "  {} rebuilt index.json from attempt files",
                "repaired:".bright_green()
            );
        }
        if !r.by_error_code.is_empty() {
            println!("  {}", "by code:".bright_black());
            let mut codes: Vec<_> = r.by_error_code.iter().collect();
            codes.sort_by(|a, b| b.1.cmp(a.1).then_with(|| a.0.cmp(b.0)));
            for (code, n) in codes.into_iter().take(10) {
                println!(
                    "    {}  {}",
                    format!("{n:>3}").bright_white(),
                    code.bright_magenta()
                );
            }
        }
        if let Some(ref top) = r.latest_target {
            println!(
                "  {} {} ({})",
                "latest:".bright_black(),
                top.bright_white(),
                r.latest_status.as_deref().unwrap_or("?")
            );
        }
    }

    println!();
    println!("{}", "".repeat(72).bright_black());
    println!("{}", "Engine policy (built-in):".bright_black());
    println!(
        "  {} CF/OpenNext never GHCR-push; containers allow unchanged image by default",
        "·".dimmed()
    );
    println!(
        "  {} OpenNext stages: install→build→entry_assert→wrangler  (log: .xbp/opennext-deploy.log)",
        "·".dimmed()
    );
    println!(
        "  {} strict container image: --require-new-container-image",
        "·".dimmed()
    );
    println!(
        "  {} history: xbp deploy --history  ·  repair only: --repair-history",
        "·".dimmed()
    );
    println!();
    Ok(())
}

#[derive(Debug, Clone)]
struct EngineCheckReport {
    project_name: String,
    root: String,
    history_dir: String,
    entries: usize,
    success: usize,
    failed: usize,
    by_error_code: std::collections::BTreeMap<String, usize>,
    repaired: bool,
    latest_target: Option<String>,
    latest_status: Option<String>,
}

fn check_one_project(
    project_root: &Path,
    project_name: &str,
    history_dir: &Path,
    env: &str,
    limit: usize,
) -> Result<EngineCheckReport, String> {
    let store = DeployHistoryStore::new(history_dir);
    // Always rebuild index from attempt files (idempotent; fixes merge conflicts).
    let index = store
        .rebuild_index_from_records()
        .map_err(|e| e.to_string())?;
    let stats = store
        .stats("all", env, limit.max(index.entries.len().max(1)))
        .map_err(|e| e.to_string())?;
    let latest = index.entries.first();
    Ok(EngineCheckReport {
        project_name: project_name.to_string(),
        root: project_root.display().to_string(),
        history_dir: history_dir.display().to_string(),
        entries: stats.total,
        success: stats.success,
        failed: stats.failed,
        by_error_code: stats.by_error_code,
        repaired: true,
        latest_target: latest.map(|e| e.target.clone()),
        latest_status: latest.map(|e| e.status.clone()),
    })
}

/// Sibling repos under the same parent (e.g. Documents/GitHub/*) that have `.xbp/deployments`.
fn discover_sibling_history_projects(project_root: &Path) -> Vec<(std::path::PathBuf, String, std::path::PathBuf)> {
    let mut out = Vec::new();
    let Some(parent) = project_root.parent() else {
        return out;
    };
    let Ok(rd) = std::fs::read_dir(parent) else {
        return out;
    };
    for ent in rd.flatten() {
        let path = ent.path();
        if !path.is_dir() {
            continue;
        }
        let deployments = path.join(".xbp").join("deployments");
        if !deployments.is_dir() {
            continue;
        }
        // Only if there is at least one attempt json or we care about empty dirs too.
        let name = path
            .file_name()
            .and_then(|s| s.to_str())
            .unwrap_or("project")
            .to_string();
        out.push((path, name, deployments));
    }
    out.sort_by(|a, b| a.1.cmp(&b.1));
    out
}

/// Warn when the last N deploys of `target` failed with the same error_code.
pub fn warn_repeated_deploy_failures(history_dir: &Path, target: &str, env: &str, min_streak: usize) {
    let store = DeployHistoryStore::new(history_dir);
    let Ok(entries) = store.list(target, env, min_streak.max(3)) else {
        return;
    };
    if entries.len() < min_streak {
        return;
    }

    let mut codes: Vec<String> = Vec::new();
    for entry in &entries {
        if entry.status == "success" {
            break;
        }
        let code = entry
            .error_code
            .clone()
            .or_else(|| {
                store.load_record(entry).ok().flatten().and_then(|r| {
                    r.error_code.or_else(|| {
                        let c = classify_deploy_error(r.error.as_deref(), &r.summary, false);
                        Some(c.error_code.as_str().into())
                    })
                })
            })
            .unwrap_or_else(|| "unknown".into());
        codes.push(code);
    }

    if codes.len() < min_streak {
        return;
    }
    let first = &codes[0];
    if !codes.iter().take(min_streak).all(|c| c == first) {
        return;
    }

    println!();
    println!(
        "{} Last {} deploys of `{}` failed with the same code `{}`.",
        "!".bright_yellow().bold(),
        min_streak,
        target.bright_white(),
        first.bright_magenta()
    );
    println!(
        "  {} fix the root cause before retrying (doctor / logs / history).",
        "".bright_cyan()
    );
    println!(
        "  {} xbp deploy --history   ·   xbp cloudflare doctor --app {}",
        "·".dimmed(),
        target.dimmed()
    );
    println!(
        "  {} OpenNext log: <worker>/.xbp/opennext-deploy.log",
        "·".dimmed()
    );
    println!();
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn detects_ledger_noise() {
        assert!(is_xbp_ledger_noise_path(".xbp/deployments/foo.json"));
        assert!(is_xbp_ledger_noise_path(
            "C:/Users/x/repo/.xbp/deployments/2026.json"
        ));
        assert!(is_xbp_ledger_noise_path(".xbp/last-version-scope"));
        assert!(is_xbp_ledger_noise_path(
            "packages/app/.xbp/opennext-deploy.log"
        ));
        assert!(!is_xbp_ledger_noise_path("crates/cli/src/main.rs"));
        assert!(!is_xbp_ledger_noise_path(".xbp/xbp.toml"));
    }

    #[test]
    fn porcelain_noise_lines() {
        assert!(porcelain_line_is_xbp_ledger_noise(
            " M .xbp/deployments/x.json"
        ));
        assert!(porcelain_line_is_xbp_ledger_noise(
            "?? .xbp/releases/service-x/1.0.0.yaml"
        ));
        assert!(!porcelain_line_is_xbp_ledger_noise(" M Cargo.toml"));
    }
}