cpa-server 0.4.4

Part of cliproxy: HTTP routes, client auth, credential selection and the management API
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
//! Go's runtime `Config` as `json.Marshal` prints it (the v0 reads): the v8 document
//! flattened back to the legacy layout (`flattenV8`), each field typed and ordered by a
//! shape table generated from Go's structs, absent fields taking Go's load defaults,
//! then Go's post-load normalizers (`LoadConfig`).
use cpa_core::gostr::GoStr;
use std::collections::BTreeMap;
use std::sync::LazyLock;

use serde::Deserialize;
use serde_json::{Map, Value};
use serde_yaml_ng::Value as Yaml;

/// One field of a Go struct (or the element of a slice or map).
#[derive(Clone, Deserialize)]
pub(super) struct Shape {
    #[serde(default)]
    pub json: String,
    #[serde(default)]
    pub yaml: String,
    #[serde(default)]
    pub omit: bool,
    pub kind: String,
    #[serde(default)]
    pub ptr: bool,
    #[serde(default)]
    pub fields: Vec<Shape>,
    pub elem: Option<Box<Shape>>,
}

#[derive(Deserialize)]
struct Shapes {
    config: Shape,
    v8_paths: BTreeMap<String, String>,
}

/// Generated by tests/reference/legacy/shape_fixture_test.go from Go's `Config`.
static SHAPES: LazyLock<Shapes> =
    LazyLock::new(|| serde_json::from_str(include_str!("shape.json")).expect("generated shape"));
/// Go's GET /v0/management/config for a config with nothing but a management key.
static DEFAULTS: LazyLock<Value> =
    LazyLock::new(|| serde_json::from_str(include_str!("defaults.json")).expect("recorded defaults"));

/// Go `v8KeyFamilies`: legacy list name, v8 group name.
pub(super) const KEY_FAMILIES: [(&str, &str); 8] = [
    ("gemini-api-key", "gemini"),
    ("interactions-api-key", "interactions"),
    ("vertex-api-key", "vertex"),
    ("codex-api-key", "codex"),
    ("claude-api-key", "claude"),
    ("xai-api-key", "xai"),
    ("meta-api-key", "meta"),
    ("openai-compatibility", "openai-compatibility"),
];

/// Group fields copied into every key of a v8 group (Go `sharedKeyFields` plus base-url).
pub(super) const SHARED_KEY_FIELDS: [&str; 10] = [
    "base-url",
    "priority",
    "prefix",
    "proxy-url",
    "headers",
    "models",
    "excluded-models",
    "disable-cooling",
    "request-retry",
    "request-scoped-errors",
];

pub(super) fn shape() -> &'static Shape {
    &SHAPES.config
}

/// The shape of a root field by its JSON name.
pub(super) fn field(json: &str) -> &'static Shape {
    SHAPES
        .config
        .fields
        .iter()
        .find(|f| f.json == json)
        .expect("known Config field")
}

/// The shape of a field inside a root list's element (for example a Claude key's `cloak`).
pub(super) fn nested(list: &str, name: &str) -> Option<&'static Shape> {
    field(list).elem.as_deref()?.fields.iter().find(|f| f.json == name)
}

fn get_path<'a>(v: &'a Yaml, path: &str) -> Option<&'a Yaml> {
    path.split('.').try_fold(v, |v, k| v.get(k))
}

fn set_path(v: &mut Yaml, path: &str, value: Yaml) {
    let mut parts = path.split('.').peekable();
    let mut node = v;
    while let Some(key) = parts.next() {
        if !node.is_mapping() {
            *node = Yaml::Mapping(Default::default());
        }
        let map = node.as_mapping_mut().expect("mapping");
        if parts.peek().is_none() {
            map.insert(key.into(), value);
            return;
        }
        node = map.entry(key.into()).or_insert(Yaml::Null);
    }
}

/// Go `expandV8Groups`: each key of a group becomes one legacy entry carrying the
/// group's shared fields; OpenAI compatibility keeps its group with `api-key-entries`.
pub(super) fn expand_groups(groups: &Yaml, family: &str) -> Yaml {
    let mut out = Vec::new();
    for group in groups.as_sequence().into_iter().flatten() {
        let keys = group
            .get("keys")
            .and_then(Yaml::as_sequence)
            .cloned()
            .unwrap_or_default();
        if family == "openai-compatibility" {
            let mut item = group.as_mapping().cloned().unwrap_or_default();
            item.shift_remove("keys");
            item.insert("api-key-entries".into(), Yaml::Sequence(keys));
            out.push(Yaml::Mapping(item));
            continue;
        }
        for key in keys {
            let mut item = serde_yaml_ng::Mapping::new();
            for (k, v) in group.as_mapping().into_iter().flatten() {
                if k.as_str().is_some_and(|k| SHARED_KEY_FIELDS.contains(&k)) {
                    item.insert(k.clone(), v.clone());
                }
            }
            for (k, v) in key.as_mapping().into_iter().flatten() {
                if !v.is_null() {
                    item.insert(k.clone(), v.clone());
                }
            }
            out.push(Yaml::Mapping(item));
        }
    }
    Yaml::Sequence(out)
}

/// Go `flattenV8`: the v8 document in the legacy layout Go's `Config` decodes.
pub(super) fn flatten(doc: &Yaml) -> Yaml {
    let mut root = doc.clone();
    if root.get("api-keys").is_some_and(Yaml::is_mapping)
        && let Some(map) = root.as_mapping_mut()
    {
        map.shift_remove("api-keys");
    }
    for (old, current) in &SHAPES.v8_paths {
        if let Some(value) = get_path(doc, current) {
            set_path(&mut root, old, value.clone());
        }
    }
    for (old, family) in KEY_FAMILIES {
        if let Some(groups) = doc.get("api-keys").and_then(|k| k.get(family)) {
            set_path(&mut root, old, expand_groups(groups, family));
        }
    }
    root
}

/// A YAML scalar as yaml.v3 decodes it into a Go string (null is empty).
pub(super) fn yaml_string(v: &Yaml) -> String {
    match v {
        Yaml::String(s) => s.clone(),
        Yaml::Bool(b) => b.to_string(),
        Yaml::Number(n) => n.to_string(),
        Yaml::Tagged(t) => yaml_string(&t.value),
        _ => String::new(),
    }
}

/// Go `time.ParseDuration` for the values yaml.v3 decodes into `time.Duration`.
fn duration_nanos(v: &Yaml) -> Value {
    match v {
        Yaml::Number(n) => n.as_i64().map_or(Value::from(0), Value::from),
        Yaml::String(s) => Value::from(cpa_core::config::parse_duration(s).unwrap_or(0)),
        _ => Value::from(0),
    }
}

/// A YAML value as Go's `json.Marshal` prints an `any` decoded by yaml.v3: map keys
/// sorted at every level, and a float with no fraction printed as an integer.
/// ponytail: other floats use serde's shortest form, which differs from Go's
/// `strconv` form only for exponents (`1e21` vs `1e+21`, `1e16` vs `10000000000000000`).
fn any_json(v: &Yaml) -> Value {
    fn go(v: Value) -> Value {
        match v {
            Value::Number(n) if n.is_f64() => match n.as_f64() {
                Some(f) if f.fract() == 0.0 && f.abs() < 9.2e18 => Value::from(f as i64),
                _ => Value::Number(n),
            },
            Value::Array(a) => Value::Array(a.into_iter().map(go).collect()),
            Value::Object(o) => {
                let sorted: BTreeMap<String, Value> = o.into_iter().map(|(k, v)| (k, go(v))).collect();
                Value::Object(sorted.into_iter().collect())
            }
            v => v,
        }
    }
    go(serde_json::to_value(cpa_core::config::AsJson(v)).unwrap_or(Value::Null))
}

/// Go's zero value of a shape, as `json.Marshal` prints it.
pub(super) fn zero(shape: &Shape) -> Value {
    if shape.ptr {
        return Value::Null;
    }
    pointee_zero(shape)
}

/// The zero value a pointer field points at once Go allocates it.
pub(super) fn pointee_zero(shape: &Shape) -> Value {
    match shape.kind.as_str() {
        "bool" => Value::Bool(false),
        "int" | "uint" | "float" | "duration" => Value::from(0),
        "string" => Value::from(""),
        "struct" => object(shape, None, None, false),
        k if k.starts_with("marshaler:") => Value::Bool(false),
        _ => Value::Null,
    }
}

/// Go `omitempty`: false, 0, "", nil, and empty slices or maps (never structs).
fn empty(shape: &Shape, v: &Value) -> bool {
    match v {
        Value::Null => true,
        Value::Bool(b) => !b && !shape.ptr,
        Value::Number(n) => n.as_f64() == Some(0.0) && !shape.ptr,
        Value::String(s) => s.is_empty() && !shape.ptr,
        Value::Array(a) => a.is_empty(),
        Value::Object(o) => shape.kind == "map" && o.is_empty(),
    }
}

/// yaml.v3 leaves a non-pointer scalar or struct unchanged on null (its pre-decode
/// default stands) and skips null elements of such types in sequences and maps.
pub(super) fn nilable(shape: &Shape) -> bool {
    shape.ptr || matches!(shape.kind.as_str(), "slice" | "map" | "any")
}

fn skipped_null(shape: &Shape, v: &Yaml) -> bool {
    !nilable(shape) && matches!(v, Yaml::Null)
}

/// One value decoded into a shape.
pub(super) fn convert(shape: &Shape, v: &Yaml) -> Value {
    if let Yaml::Tagged(t) = v {
        return convert(shape, &t.value);
    }
    if v.is_null() && (shape.ptr || matches!(shape.kind.as_str(), "slice" | "map" | "any")) {
        return Value::Null;
    }
    match shape.kind.as_str() {
        "bool" => Value::Bool(v.as_bool().unwrap_or(false)),
        "int" | "uint" => v
            .as_i64()
            .or_else(|| v.as_f64().map(|f| f as i64))
            .map_or(Value::from(0), Value::from),
        "float" => v
            .as_f64()
            .and_then(serde_json::Number::from_f64)
            .map_or(Value::from(0), Value::Number),
        "duration" => duration_nanos(v),
        "string" => Value::from(yaml_string(v)),
        "any" => any_json(v),
        "struct" => object(shape, Some(v), None, false),
        "slice" => match v.as_sequence() {
            Some(items) => {
                let elem = shape.elem.as_deref().expect("slice element");
                Value::Array(
                    items
                        .iter()
                        .filter(|i| !skipped_null(elem, i))
                        .map(|i| convert(elem, i))
                        .collect(),
                )
            }
            None => Value::Null,
        },
        "map" => match v.as_mapping() {
            Some(map) => {
                let elem = shape.elem.as_deref().expect("map element");
                // encoding/json sorts map keys.
                let sorted: BTreeMap<String, Value> = map
                    .iter()
                    .filter(|(_, v)| !skipped_null(elem, v))
                    .map(|(k, v)| (yaml_string(k), convert(elem, v)))
                    .collect();
                Value::Object(sorted.into_iter().collect())
            }
            None => Value::Null,
        },
        k if k.starts_with("marshaler:") => match v {
            Yaml::Bool(b) => Value::Bool(*b),
            Yaml::String(s) => match s.trim().go_lower().as_str() {
                "true" => Value::Bool(true),
                "chat" => Value::from("chat"),
                "passthrough" => Value::from("passthrough"),
                _ => Value::Bool(false),
            },
            _ => Value::Bool(false),
        },
        _ => any_json(v),
    }
}

/// Structs Go decodes through an `UnmarshalYAML` into a zeroed value that records key
/// presence (`CredentialConcurrencyConfig`): a null there is a present zero.
const ZEROED_STRUCTS: [&str; 1] = ["credential-concurrency"];

/// A struct: present fields decoded, absent ones from `defaults` (Go's load defaults)
/// or the zero value; `omitempty` fields dropped when empty. `zeroed` marks a struct
/// in `ZEROED_STRUCTS`.
fn object(shape: &Shape, present: Option<&Yaml>, defaults: Option<&Value>, zeroed: bool) -> Value {
    let mut out = Map::new();
    for f in &shape.fields {
        // A null on a non-nilable field leaves the pre-decode default, like absence.
        let value = match present
            .and_then(|p| p.get(f.yaml.as_str()))
            .filter(|v| zeroed || !skipped_null(f, v))
        {
            Some(v) if f.kind == "struct" && !f.ptr => object(
                f,
                Some(v),
                defaults.and_then(|d| d.get(&f.json)),
                ZEROED_STRUCTS.contains(&f.json.as_str()),
            ),
            Some(v) => convert(f, v),
            None => match defaults.and_then(|d| d.get(&f.json)) {
                Some(d) => d.clone(),
                None => zero(f),
            },
        };
        if f.omit && empty(f, &value) {
            continue;
        }
        out.insert(f.json.clone(), value);
    }
    Value::Object(out)
}

/// Go's runtime config as GET /v0/management/config returns it.
pub(super) fn config(doc: &Yaml) -> Value {
    let legacy = flatten(doc);
    let mut cfg = object(shape(), Some(&legacy), Some(&DEFAULTS), false);
    super::keys::normalize_config(&mut cfg);
    load_normalize(&mut cfg);
    cfg
}

/// Reload comparisons need zero values and nil/empty slices, not JSON omitempty.
pub(crate) fn config_for_diff(doc: &Yaml, snapshot: bool) -> Value {
    fn retain_empty(shape: &mut Shape) {
        shape.omit = false;
        for field in &mut shape.fields {
            retain_empty(field);
        }
        if let Some(elem) = &mut shape.elem {
            retain_empty(elem);
        }
    }
    let mut shape = shape().clone();
    retain_empty(&mut shape);
    let legacy = flatten(doc);
    let mut cfg = object(&shape, Some(&legacy), Some(&DEFAULTS), false);
    // DeepEqual compares interface values before JSON presentation: 1 != 1.0.
    for section in ["default", "default-raw", "override", "override-raw", "filter"] {
        let raw = legacy
            .get("payload")
            .and_then(|p| p.get(section))
            .and_then(Yaml::as_sequence);
        let typed = cfg["payload"][section].as_array_mut();
        if let (Some(raw), Some(typed)) = (raw, typed) {
            for (raw, typed) in raw.iter().zip(typed) {
                if section != "filter"
                    && let Some(params) = raw.get("params")
                {
                    typed["params"] = serde_json::to_value(cpa_core::config::AsJson(params)).unwrap_or(Value::Null);
                }
                let raw_models = raw.get("models").and_then(Yaml::as_sequence);
                let typed_models = typed["models"].as_array_mut();
                if let (Some(raw_models), Some(typed_models)) = (raw_models, typed_models) {
                    for (raw_model, typed_model) in raw_models.iter().zip(typed_models) {
                        for field in ["match", "not-match"] {
                            if let Some(value) = raw_model.get(field) {
                                typed_model[field] =
                                    serde_json::to_value(cpa_core::config::AsJson(value)).unwrap_or(Value::Null);
                            }
                        }
                    }
                }
            }
        }
    }
    super::keys::normalize_config(&mut cfg);
    load_normalize(&mut cfg);
    if snapshot {
        // Go yaml.Marshal/Unmarshal: nil collections become empty unless omitted;
        // empty omitempty collections disappear. Integral floats emit as integers.
        fn collections(shape: &Shape, value: &mut Value) {
            if matches!(shape.kind.as_str(), "slice" | "map") {
                if shape.omit && empty(shape, value) {
                    *value = Value::Null;
                    return;
                }
                if value.is_null() {
                    *value = if shape.kind == "slice" {
                        Value::Array(Vec::new())
                    } else {
                        Value::Object(Map::new())
                    };
                }
            }
            for field in &shape.fields {
                if let Some(v) = value.get_mut(&field.json) {
                    collections(field, v);
                }
            }
            if let Some(elem) = &shape.elem {
                match value {
                    Value::Array(items) => {
                        for item in items {
                            collections(elem, item);
                        }
                    }
                    Value::Object(items) => {
                        for item in items.values_mut() {
                            collections(elem, item);
                        }
                    }
                    _ => {}
                }
            }
        }
        fn numbers(value: &mut Value) {
            match value {
                Value::Number(n) if n.is_f64() => {
                    if let Some(f) = n.as_f64()
                        && f.fract() == 0.0
                        && f.abs() < 1e6
                    {
                        *value = Value::from(f as i64);
                    }
                }
                Value::Array(items) => {
                    for item in items {
                        numbers(item);
                    }
                }
                Value::Object(items) => {
                    for item in items.values_mut() {
                        numbers(item);
                    }
                }
                _ => {}
            }
        }
        collections(self::shape(), &mut cfg);
        numbers(&mut cfg["payload"]);
    }
    cfg
}

/// The scalar clamps and defaults of Go `LoadConfig` after decoding.
fn load_normalize(cfg: &mut Value) {
    let Some(c) = cfg.as_object_mut() else { return };
    let int = |c: &Map<String, Value>, k: &str| c.get(k).and_then(Value::as_i64).unwrap_or(0);
    if int(c, "logs-max-total-size-mb") < 0 {
        c.insert("logs-max-total-size-mb".into(), 0.into());
    }
    if int(c, "error-logs-max-files") < 0 {
        c.insert("error-logs-max-files".into(), 10.into());
    }
    match int(c, "redis-usage-queue-retention-seconds") {
        n if n <= 0 => c.insert("redis-usage-queue-retention-seconds".into(), 60.into()),
        n if n > 3600 => c.insert("redis-usage-queue-retention-seconds".into(), 3600.into()),
        _ => None,
    };
    if int(c, "max-retry-credentials") < 0 {
        c.insert("max-retry-credentials".into(), 0.into());
    }
    if let Some(d) = c.get_mut("discovery").and_then(Value::as_object_mut) {
        if d.get("service-type").and_then(Value::as_str) == Some("") {
            d.insert("service-type".into(), "_ai-gateway._tcp".into());
        }
        if d.get("subtypes").and_then(Value::as_array).is_none_or(Vec::is_empty) {
            d.insert(
                "subtypes".into(),
                serde_json::json!([
                    "_chat-completions",
                    "_responses",
                    "_messages",
                    "_generate-content",
                    "_interactions"
                ]),
            );
        }
    }
    if let Some(p) = c.get_mut("plugins").and_then(Value::as_object_mut) {
        let dir = plugins_dir(p.get("dir").and_then(Value::as_str).unwrap_or_default());
        p.insert("dir".into(), dir.into());
        // PluginInstanceConfig.UnmarshalYAML starts `enabled` as a non-nil false;
        // NormalizePluginsConfig makes a nil map empty.
        let configs = p.entry("configs").or_insert(Value::Null);
        if configs.is_null() {
            *configs = Value::Object(Map::new());
        }
        for entry in configs.as_object_mut().into_iter().flat_map(|m| m.values_mut()) {
            if !entry.is_object() {
                *entry = Value::Object(Map::new());
            }
            let o = entry.as_object_mut().expect("object");
            // Plugin entries stay raw in the live document (Go `PluginInstanceConfig.Raw`);
            // the typed config decodes `enabled` (YAML 1.1 spellings) and truncates a
            // float `priority`, as yaml.v3 does.
            let priority = o.shift_remove("priority");
            let enabled = match o.shift_remove("enabled") {
                Some(Value::Bool(b)) => b,
                Some(Value::String(s)) => cpa_core::config::go_bool(&s).unwrap_or(false),
                _ => false,
            };
            o.insert("enabled".into(), enabled.into());
            if let Some(p) = priority {
                let typed = p.as_i64().or_else(|| p.as_f64().map(|f| f.trunc() as i64));
                o.insert("priority".into(), typed.map_or(p, Value::from));
            }
        }
    }
    if let Some(payload) = c.get_mut("payload").and_then(Value::as_object_mut) {
        for section in ["default-raw", "override-raw"] {
            if let Some(rules) = payload.get_mut(section).and_then(Value::as_array_mut) {
                rules.retain(payload_raw_rule_valid);
            }
        }
    }
    if let Some(p) = c.get_mut("pprof").and_then(Value::as_object_mut) {
        let addr = p
            .get("addr")
            .and_then(Value::as_str)
            .unwrap_or_default()
            .trim()
            .to_owned();
        p.insert(
            "addr".into(),
            if addr.is_empty() {
                "127.0.0.1:8316".into()
            } else {
                addr.into()
            },
        );
    }
    for (section, keys) in [
        ("codex-header-defaults", &["user-agent", "beta-features"][..]),
        (
            "claude-header-defaults",
            &[
                "user-agent",
                "package-version",
                "runtime-version",
                "os",
                "arch",
                "timeout",
                "timezone",
            ][..],
        ),
    ] {
        if let Some(s) = c.get_mut(section).and_then(Value::as_object_mut) {
            for k in keys {
                if let Some(v) = s.get(*k).and_then(Value::as_str).map(|v| super::go_trim(v).to_owned()) {
                    s.insert((*k).into(), v.into());
                }
            }
        }
    }
}

/// Go `sanitizePayloadRawRules`: a rule needs params, and every string param must be
/// valid JSON once trimmed (non-string params are kept as they are).
fn payload_raw_rule_valid(rule: &Value) -> bool {
    let Some(params) = rule.get("params").and_then(Value::as_object).filter(|p| !p.is_empty()) else {
        return false;
    };
    params.values().all(|v| match v.as_str() {
        Some(raw) => {
            let trimmed = super::go_trim(raw);
            !trimmed.is_empty() && serde_json::from_str::<serde::de::IgnoredAny>(trimmed).is_ok()
        }
        None => true,
    })
}

/// Go `filepath.Clean` (Unix separators).
fn go_clean(p: &str) -> String {
    let rooted = p.starts_with('/');
    let mut out: Vec<&str> = Vec::new();
    for part in p.split('/') {
        match part {
            "" | "." => {}
            ".." if out.last().is_some_and(|l| *l != "..") => {
                out.pop();
            }
            ".." if rooted => {}
            part => out.push(part),
        }
    }
    let joined = out.join("/");
    match (rooted, joined.is_empty()) {
        (true, _) => format!("/{joined}"),
        (false, true) => ".".into(),
        (false, false) => joined,
    }
}

/// Go `ResolvePluginsDir`: trimmed, `plugins` when empty, `~` expanded, cleaned.
fn plugins_dir(dir: &str) -> String {
    let dir = super::go_trim(dir);
    let dir = if dir.is_empty() { "plugins" } else { dir };
    match dir.strip_prefix('~') {
        Some(rest) => {
            let home = std::env::var("HOME").unwrap_or_default();
            let rest = rest.trim_start_matches(['/', '\\']).replace('\\', "/");
            if rest.is_empty() {
                go_clean(&home)
            } else {
                go_clean(&format!("{home}/{rest}"))
            }
        }
        None => go_clean(dir),
    }
}

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

    #[test]
    fn paths_clean_like_go() {
        for (p, want) in [
            ("./p", "p"),
            ("a//b/../c/", "a/c"),
            ("/../x", "/x"),
            ("../../y", "../../y"),
            ("", "."),
            ("/", "/"),
        ] {
            assert_eq!(go_clean(p), want, "{p}");
        }
        assert_eq!(plugins_dir("  "), "plugins");
    }

    #[test]
    fn durations_parse_like_go() {
        for (s, want) in [
            ("2s", 2_000_000_000),
            ("1m30s", 90_000_000_000),
            ("250ms", 250_000_000),
            ("0", 0),
            ("1.5h", 5_400_000_000_000),
        ] {
            assert_eq!(cpa_core::config::parse_duration(s), Some(want), "{s}");
        }
        assert_eq!(cpa_core::config::parse_duration("5x"), None);
    }

    #[test]
    fn flatten_expands_v8_key_groups() {
        let doc: Yaml = serde_yaml_ng::from_str(
            "observability:\n  logs:\n    debug: true\napi-keys:\n  gemini:\n    - name: g\n      base-url: b\n      keys:\n        - api-key: k1\n        - api-key: k2\n          prefix: p\naccess:\n  api-keys: [c]\n",
        )
        .unwrap();
        let flat = flatten(&doc);
        assert_eq!(flat.get("debug"), Some(&Yaml::Bool(true)));
        let gemini = flat.get("gemini-api-key").unwrap().as_sequence().unwrap();
        assert_eq!(gemini.len(), 2);
        assert_eq!(gemini[1].get("base-url").unwrap().as_str(), Some("b"));
        assert_eq!(gemini[1].get("prefix").unwrap().as_str(), Some("p"));
        assert_eq!(flat.get("api-keys").unwrap().as_sequence().unwrap().len(), 1);
    }
}