tono-core 1.9.0

The pure, headless audio engine behind tono: synthesis-graph DSL, DSP, deterministic renderer, instruments, songs, and analysis — no I/O, no transport.
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
//! Surgical, path-addressed edits to a sound graph.
//!
//! Instead of re-submitting the whole [`SoundDoc`] to change one number
//! (`refine_sound`), the agent addresses a node or parameter by a JSON path —
//! `root.inputs[0].freq`, `root.stages[1].cutoff` — and applies small ops:
//! many ordered edits in one render. Edits are applied on the `serde_json`
//! representation, then parsed back to a `SoundDoc` and validated, so an
//! illegal edit is rejected with a readable error rather than producing a
//! broken graph.

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::Value as Json;

use crate::dsl::{SoundDoc, ValidateError};

/// One element of a path: an object key or an array index.
enum Seg {
    Key(String),
    Index(usize),
}

/// Parse a path like `root.inputs[0].freq`, `root.stages[1].cutoff`, or
/// `root.notes[0].pitch`. Both `name[0]` and `name.0` index forms are accepted.
fn parse_path(path: &str) -> Result<Vec<Seg>, String> {
    let mut segs = Vec::new();
    for raw in path.split('.') {
        if raw.is_empty() {
            continue;
        }
        if let Some(br) = raw.find('[') {
            let key = &raw[..br];
            if !key.is_empty() {
                segs.push(Seg::Key(key.to_string()));
            }
            let mut s = &raw[br..];
            while let Some(rest) = s.strip_prefix('[') {
                let end = rest.find(']').ok_or("unclosed '[' in path")?;
                let num = &rest[..end];
                let idx: usize = num
                    .parse()
                    .map_err(|_| format!("bad array index '{num}' in path"))?;
                segs.push(Seg::Index(idx));
                s = &rest[end + 1..];
            }
            if !s.is_empty() {
                return Err(format!("trailing '{s}' after index in path"));
            }
        } else if let Ok(idx) = raw.parse::<usize>() {
            segs.push(Seg::Index(idx));
        } else {
            segs.push(Seg::Key(raw.to_string()));
        }
    }
    Ok(segs)
}

/// Navigate to a mutable reference at `segs`.
fn nav_mut<'a>(root: &'a mut Json, segs: &[Seg]) -> Result<&'a mut Json, String> {
    let mut cur = root;
    for seg in segs {
        cur = match seg {
            Seg::Key(k) => cur
                .get_mut(k)
                .ok_or_else(|| format!("no field '{k}' at this path"))?,
            Seg::Index(i) => cur
                .get_mut(*i)
                .ok_or_else(|| format!("no array index {i} at this path"))?,
        };
    }
    Ok(cur)
}

/// A single edit operation, externally tagged by `op`. (`Serialize` so the
/// session journal can record edit calls verbatim.)
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "op", rename_all = "snake_case")]
pub enum EditOp {
    /// Set the JSON value at `path`. Works for a numeric parameter
    /// (`root.inputs[0].freq` → `180` or a modulator object), a scalar field
    /// (`duration`, `seed`, `root.stages[0].q`), or an entire node
    /// (`root.inputs[1]` → `{ "type": "sine", "freq": 220 }`).
    Set {
        /// Path to the target value.
        path: String,
        /// The new JSON value (number, modulator object, or whole node).
        value: Json,
    },
    /// Insert a node into the array at `path` (a `chain`'s `stages` or a
    /// `mix`/`mul`'s `inputs`) at `index` (appended if omitted).
    Insert {
        /// Path to the array (e.g. `root.inputs` or `root.stages`).
        path: String,
        /// Insertion index; appends when omitted or past the end.
        #[serde(default)]
        index: Option<usize>,
        /// The node to insert.
        node: Json,
    },
    /// Remove an array element: either the element at `index` within the array
    /// at `path`, or the element a path ending in `[n]` points to.
    Remove {
        /// Path to an array, or to an array element ending in `[n]`.
        path: String,
        /// Index to remove within the array at `path`.
        #[serde(default)]
        index: Option<usize>,
    },
}

fn apply_one(json: &mut Json, op: &EditOp) -> Result<(), String> {
    match op {
        EditOp::Set { path, value } => {
            let segs = parse_path(path)?;
            if segs.is_empty() {
                return Err("set: path must not be empty".into());
            }
            let target = nav_mut(json, &segs)?;
            *target = value.clone();
            Ok(())
        }
        EditOp::Insert { path, index, node } => {
            let segs = parse_path(path)?;
            let target = nav_mut(json, &segs)?;
            let arr = target
                .as_array_mut()
                .ok_or("insert: path does not point to an array (use a chain's `stages` or a mix/mul `inputs`)")?;
            let i = index.unwrap_or(arr.len()).min(arr.len());
            arr.insert(i, node.clone());
            Ok(())
        }
        EditOp::Remove { path, index } => {
            let segs = parse_path(path)?;
            match index {
                Some(i) => {
                    let arr = nav_mut(json, &segs)?
                        .as_array_mut()
                        .ok_or("remove: path does not point to an array")?;
                    if *i >= arr.len() {
                        return Err(format!(
                            "remove: index {i} out of range (len {})",
                            arr.len()
                        ));
                    }
                    arr.remove(*i);
                    Ok(())
                }
                None => match segs.last() {
                    Some(Seg::Index(i)) => {
                        let i = *i;
                        let parent = nav_mut(json, &segs[..segs.len() - 1])?
                            .as_array_mut()
                            .ok_or("remove: parent of the indexed element is not an array")?;
                        if i >= parent.len() {
                            return Err(format!(
                                "remove: index {i} out of range (len {})",
                                parent.len()
                            ));
                        }
                        parent.remove(i);
                        Ok(())
                    }
                    _ => Err("remove: provide `index`, or a path ending in `[n]`".into()),
                },
            }
        }
    }
}

/// Why an edit failed.
#[derive(Debug, Clone, PartialEq)]
pub enum EditError {
    /// Op `index` failed — a missing path, a bad array index, or a value the
    /// node can't take. The reason names the offending path.
    Op {
        /// Index of the failing op in the batch.
        index: usize,
        /// What went wrong, naming the path.
        reason: String,
    },
    /// The edited JSON no longer deserializes as a `SoundDoc`.
    InvalidGraph(String),
    /// The edited document fails validation.
    Invalid(ValidateError),
    /// `morph`: the two graphs are not the same shape (or hold values that
    /// cannot be interpolated) at the named path.
    Morph(String),
}

impl std::fmt::Display for EditError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            EditError::Op { index, reason } => write!(f, "op[{index}]: {reason}"),
            EditError::InvalidGraph(e) => write!(f, "edited graph is invalid: {e}"),
            EditError::Invalid(e) => write!(f, "edited document fails validation: {e}"),
            EditError::Morph(e) => f.write_str(e),
        }
    }
}

impl std::error::Error for EditError {}

impl From<ValidateError> for EditError {
    fn from(e: ValidateError) -> Self {
        EditError::Invalid(e)
    }
}

/// Apply `ops` to `doc` in order, returning the edited, re-validated graph.
/// An op referencing a missing path, or producing an invalid graph, fails
/// with an [`EditError`] naming the offending op index.
pub fn apply_ops(doc: &SoundDoc, ops: &[EditOp]) -> Result<SoundDoc, EditError> {
    let mut json = serde_json::to_value(doc).map_err(|e| EditError::InvalidGraph(e.to_string()))?;
    for (index, op) in ops.iter().enumerate() {
        apply_one(&mut json, op).map_err(|reason| EditError::Op { index, reason })?;
    }
    let edited: SoundDoc =
        serde_json::from_value(json).map_err(|e| EditError::InvalidGraph(e.to_string()))?;
    edited.validate()?;
    Ok(edited)
}

/// A flattened description of one node in the graph: its path, type, and the
/// immediate (non-child) parameters addressable by path.
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct NodeInfo {
    /// Path to this node (e.g. `root`, `root.inputs[0]`, `root.stages[1]`).
    pub path: String,
    /// Node type (`square`, `lowpass`, `mix`, ...).
    #[serde(rename = "type")]
    pub node_type: String,
    /// Immediate scalar / modulator parameters, keyed by name. Child node arrays
    /// (`inputs` / `stages` / `notes`) are listed as separate `NodeInfo` rows.
    pub params: Json,
}

/// Recognised child-array field names (arrays of nodes / notes / modal modes).
fn is_child_array(key: &str) -> bool {
    matches!(key, "inputs" | "stages" | "notes" | "modes")
}

/// Join a path prefix and a segment (layer-relative paths start empty: the
/// layer's own node is path `""`, its children `inputs[0]`, `env`, ...).
fn join(prefix: &str, seg: &str) -> String {
    if prefix.is_empty() {
        seg.to_string()
    } else {
        format!("{prefix}.{seg}")
    }
}

fn walk(json: &Json, path: &str, out: &mut Vec<NodeInfo>) {
    let Some(obj) = json.as_object() else { return };
    if let Some(t) = obj.get("type").and_then(|v| v.as_str()) {
        let mut params = serde_json::Map::new();
        for (k, v) in obj {
            // Child structures get their own rows — duplicating the whole
            // tracks/master subtree into a params blob helps nobody.
            if k == "type" || is_child_array(k) || k == "tracks" || k == "master" {
                continue;
            }
            params.insert(k.clone(), v.clone());
        }
        out.push(NodeInfo {
            path: path.to_string(),
            node_type: t.to_string(),
            params: Json::Object(params),
        });
    }
    // Recurse into child node arrays regardless (covers nested mix/chain).
    for (k, v) in obj {
        if k == "tracks" {
            // Mixer channels: each element wraps its graph in `node`.
            if let Some(arr) = v.as_array() {
                for (i, ch) in arr.iter().enumerate() {
                    if let Some(node) = ch.get("node") {
                        walk(node, &join(path, &format!("tracks[{i}].node")), out);
                    }
                }
            }
            continue;
        }
        if k == "trigger" || k == "node" {
            walk(v, &join(path, k), out);
            continue;
        }
        if k == "modes" {
            // Modal partials have no `type` tag (like seq notes); give each its
            // own addressable row so `modes[i].freq` is discoverable.
            if let Some(arr) = v.as_array() {
                for (i, mode) in arr.iter().enumerate() {
                    out.push(NodeInfo {
                        path: join(path, &format!("modes[{i}]")),
                        node_type: "mode".to_string(),
                        params: mode.clone(),
                    });
                }
            }
            continue;
        }
        if k == "notes" {
            // Seq notes have no `type` tag but ARE the most-edited leaves in
            // the music workflow — every note gets an addressable row.
            if let Some(arr) = v.as_array() {
                for (i, note) in arr.iter().enumerate() {
                    out.push(NodeInfo {
                        path: join(path, &format!("notes[{i}]")),
                        node_type: "note".to_string(),
                        params: note.clone(),
                    });
                }
            }
            continue;
        }
        if !is_child_array(k) {
            continue;
        }
        if let Some(arr) = v.as_array() {
            for (i, child) in arr.iter().enumerate() {
                walk(child, &join(path, &format!("{k}[{i}]")), out);
            }
        }
    }
}

/// One mixer layer's addressing map: its mixer fields plus the node rows of its
/// graph. Node paths are LAYER-RELATIVE — combined with the layer id when
/// editing; the layer's own node is path `""`.
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct LayerInfo {
    /// The stable layer id (edits address a layer by this id plus a path).
    pub id: String,
    /// Stereo position −1..1.
    pub pan: f32,
    /// Fader 0..2.
    pub gain: f32,
    /// Start offset in seconds.
    pub at: f32,
    /// Muted layers are off the bus (and off every export).
    pub mute: bool,
    /// The layer's nodes, with layer-relative paths.
    pub nodes: Vec<NodeInfo>,
}

/// The full addressing map of a document.
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct DescribeMap {
    /// Node rows of a plain (non-mixer) document, absolute paths from `root`.
    pub nodes: Vec<NodeInfo>,
    /// Mixer layers, keyed by stable id (empty for plain documents).
    pub layers: Vec<LayerInfo>,
    /// Master-chain processors, addressed absolutely (`root.master[0]`, no
    /// `layer` arg).
    pub master: Vec<NodeInfo>,
}

/// Produce the addressing map for a graph — exactly what can be edited, and the
/// path (and layer id) to reach each field.
pub fn describe(doc: &SoundDoc) -> DescribeMap {
    let mut map = DescribeMap {
        nodes: Vec::new(),
        layers: Vec::new(),
        master: Vec::new(),
    };
    // Serializing a derived-Serialize SoundDoc is infallible in practice (the
    // presets::patch precedent); failing loud beats returning an empty map an
    // agent would read as "nothing editable".
    let json = serde_json::to_value(doc).expect("SoundDoc serializes");
    if let crate::dsl::Node::Tracks { tracks, master } = &doc.root {
        for (i, t) in tracks.iter().enumerate() {
            let mut nodes = Vec::new();
            if let Some(node_json) = json["root"]["tracks"][i].get("node") {
                walk(node_json, "", &mut nodes);
            }
            map.layers.push(LayerInfo {
                id: t.id.clone().unwrap_or_else(|| format!("layer_{i}")),
                pan: t.pan,
                gain: t.gain,
                at: t.at,
                mute: t.mute,
                nodes,
            });
        }
        for (i, _) in master.iter().enumerate() {
            if let Some(m) = json["root"]["master"].get(i) {
                walk(m, &format!("root.master[{i}]"), &mut map.master);
            }
        }
        return map;
    }
    if let Some(root) = json.get("root") {
        walk(root, "root", &mut map.nodes);
    }
    map
}

/// Linearly interpolate two same-shaped graphs at `t ∈ [0, 1]`: every numeric
/// parameter is lerped (integers re-rounded), note-name strings are lerped in
/// Hz, and any structural difference is a clear error. `t = 0` ⇒ `a`,
/// `t = 1` ⇒ `b`.
pub fn morph(a: &SoundDoc, b: &SoundDoc, t: f32) -> Result<SoundDoc, EditError> {
    let mut ja = serde_json::to_value(a).map_err(|e| EditError::InvalidGraph(e.to_string()))?;
    let mut jb = serde_json::to_value(b).map_err(|e| EditError::InvalidGraph(e.to_string()))?;
    // Name/version/engine/seed/sample_rate are identity and provenance, not
    // parameters — unify them before the walk. Interpolating `engine` would
    // sweep a morph through different DSP kernels mid-t (audible timbre
    // jumps), and an optional-field presence mismatch would reject two
    // structurally identical sounds.
    jb["name"] = ja["name"].clone();
    jb["seed"] = ja["seed"].clone();
    jb["sample_rate"] = ja["sample_rate"].clone();
    // `version` is optional on the wire: mirror a's presence/absence exactly
    // so the key sets always match.
    if let Some(v) = ja.get("version") {
        jb["version"] = v.clone();
    } else if let Some(o) = jb.as_object_mut() {
        o.remove("version");
    }
    // The newer kernel of the two wins, so a morph never downgrades either
    // sound's DSP (engine 0 = the legacy omitted field).
    let engine = a.effective_engine().max(b.effective_engine());
    for j in [&mut ja, &mut jb] {
        if let Some(o) = j.as_object_mut() {
            if engine > 0 {
                o.insert("engine".into(), serde_json::json!(engine));
            } else {
                o.remove("engine");
            }
        }
    }
    // Layer identity is positional in a morph: two same-shaped mixer docs
    // almost always carry different layer ids (they're unique per doc), and
    // ids/mute are not interpolatable — copy a's onto b instead of erroring.
    if let Some(ta) = ja["root"].get("tracks").and_then(|v| v.as_array()).cloned()
        && let Some(tb) = jb["root"].get_mut("tracks").and_then(|v| v.as_array_mut())
    {
        for (i, track_b) in tb.iter_mut().enumerate() {
            let Some(track_a) = ta.get(i) else { break };
            for key in ["id", "mute"] {
                match track_a.get(key) {
                    Some(v) => track_b[key] = v.clone(),
                    None => {
                        if let Some(o) = track_b.as_object_mut() {
                            o.remove(key);
                        }
                    }
                }
            }
        }
    }
    let merged = lerp_json(&ja, &jb, t, "$").map_err(EditError::Morph)?;
    let doc: SoundDoc = serde_json::from_value(merged)
        .map_err(|e| EditError::InvalidGraph(format!("morphed graph invalid: {e}")))?;
    doc.validate()?;
    Ok(doc)
}

fn lerp_json(a: &Json, b: &Json, t: f32, path: &str) -> Result<Json, String> {
    match (a, b) {
        (Json::Number(x), Json::Number(y)) => {
            let (fx, fy) = (x.as_f64().unwrap_or(0.0), y.as_f64().unwrap_or(0.0));
            let v = fx + (fy - fx) * t as f64;
            if (x.is_i64() || x.is_u64()) && (y.is_i64() || y.is_u64()) {
                Ok(Json::from(v.round() as i64))
            } else {
                Ok(serde_json::Number::from_f64(v)
                    .map(Json::Number)
                    .unwrap_or_else(|| Json::from(0)))
            }
        }
        (Json::String(x), Json::String(y)) => {
            if x == y {
                Ok(a.clone())
            } else if let (Some(fa), Some(fb)) =
                (crate::dsl::note_to_hz(x), crate::dsl::note_to_hz(y))
            {
                // Two different note names: morph the pitch in Hz.
                let hz = fa + (fb - fa) * t;
                Ok(serde_json::Number::from_f64(hz as f64)
                    .map(Json::Number)
                    .unwrap_or_else(|| Json::from(0)))
            } else {
                Err(format!(
                    "{path}: cannot morph between '{x}' and '{y}' — node types / enum choices must match"
                ))
            }
        }
        (Json::Array(x), Json::Array(y)) => {
            if x.len() != y.len() {
                return Err(format!(
                    "{path}: array lengths differ ({} vs {}) — morph needs identical structure",
                    x.len(),
                    y.len()
                ));
            }
            x.iter()
                .zip(y)
                .enumerate()
                .map(|(i, (xa, xb))| lerp_json(xa, xb, t, &format!("{path}[{i}]")))
                .collect::<Result<Vec<_>, _>>()
                .map(Json::Array)
        }
        (Json::Object(x), Json::Object(y)) => {
            if x.len() != y.len() || x.keys().any(|k| !y.contains_key(k)) {
                return Err(format!(
                    "{path}: object fields differ — morph needs graphs with identical shape"
                ));
            }
            let mut out = serde_json::Map::new();
            for (k, va) in x {
                out.insert(k.clone(), lerp_json(va, &y[k], t, &format!("{path}.{k}"))?);
            }
            Ok(Json::Object(out))
        }
        (Json::Bool(x), Json::Bool(y)) if x == y => Ok(a.clone()),
        (Json::Null, Json::Null) => Ok(Json::Null),
        _ => Err(format!(
            "{path}: structure mismatch — morph interpolates parameters of two same-shaped graphs"
        )),
    }
}

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

    fn laser() -> SoundDoc {
        serde_json::from_str(
            r#"{ "name": "laser", "duration": 0.2, "root": { "type": "mix", "inputs": [
                { "type": "mul", "inputs": [
                    { "type": "square", "freq": 880, "duty": 0.25 },
                    { "type": "env", "d": 0.18 } ] },
                { "type": "noise" }
            ] } }"#,
        )
        .unwrap()
    }

    fn op(json: &str) -> EditOp {
        serde_json::from_str(json).unwrap()
    }

    #[test]
    fn set_changes_a_nested_param() {
        let edited = apply_ops(
            &laser(),
            &[op(
                r#"{ "op": "set", "path": "root.inputs[0].inputs[0].freq", "value": 440 }"#,
            )],
        )
        .unwrap();
        let v = serde_json::to_value(&edited).unwrap();
        assert_eq!(v["root"]["inputs"][0]["inputs"][0]["freq"], 440.0);
    }

    #[test]
    fn insert_and_remove_reshape_arrays() {
        let edited = apply_ops(
            &laser(),
            &[
                op(r#"{ "op": "insert", "path": "root.inputs",
                         "node": { "type": "sine", "freq": 220 } }"#),
                op(r#"{ "op": "remove", "path": "root.inputs[1]" }"#),
            ],
        )
        .unwrap();
        let v = serde_json::to_value(&edited).unwrap();
        let inputs = v["root"]["inputs"].as_array().unwrap();
        assert_eq!(inputs.len(), 2); // noise removed, sine appended
        assert_eq!(inputs[1]["type"], "sine");
    }

    #[test]
    fn bad_edits_fail_with_op_index_and_reason() {
        let err = apply_ops(
            &laser(),
            &[op(
                r#"{ "op": "set", "path": "root.nope.freq", "value": 1 }"#,
            )],
        )
        .unwrap_err();
        assert!(err.to_string().contains("op[0]"), "{err}");
        assert!(err.to_string().contains("no field 'nope'"), "{err}");
        // An edit that parses but breaks validation is also rejected.
        let err = apply_ops(
            &laser(),
            &[op(r#"{ "op": "set", "path": "duration", "value": -1 }"#)],
        )
        .unwrap_err();
        assert!(err.to_string().contains("duration"), "{err}");
    }

    #[test]
    fn describe_maps_layers_notes_and_master() {
        let doc: SoundDoc = serde_json::from_str(
            r#"{ "name": "song", "duration": 1.0, "root": { "type": "tracks",
                "tracks": [
                  { "id": "lead", "node": { "type": "seq", "bpm": 120, "wave": "sine",
                      "env": { "d": 0.1 },
                      "notes": [ { "step": 0, "len": 2, "pitch": "C4" } ] } },
                  { "id": "pad", "node": { "type": "chain", "stages": [
                      { "type": "sine", "freq": 220 },
                      { "type": "lowpass", "cutoff": 900 } ] }, "pan": -0.3 }
                ],
                "master": [ { "type": "compress", "threshold": -12, "ratio": 4 } ] } }"#,
        )
        .unwrap();
        let map = describe(&doc);
        assert!(map.nodes.is_empty()); // mixer docs describe per layer
        assert_eq!(map.layers.len(), 2);
        let lead = &map.layers[0];
        assert_eq!(lead.id, "lead");
        // The seq itself (layer-relative path "") and its note both get rows.
        assert_eq!(lead.nodes[0].path, "");
        assert_eq!(lead.nodes[0].node_type, "seq");
        assert!(
            !lead.nodes[0]
                .params
                .as_object()
                .unwrap()
                .contains_key("notes")
        );
        assert_eq!(lead.nodes[1].path, "notes[0]");
        assert_eq!(lead.nodes[1].node_type, "note");
        assert_eq!(lead.nodes[1].params["pitch"], "C4");
        let pad = &map.layers[1];
        assert_eq!(pad.nodes[1].path, "stages[0]");
        assert_eq!(pad.pan, -0.3);
        // Master processors are addressable without a layer arg.
        assert_eq!(map.master[0].path, "root.master[0]");
        assert_eq!(map.master[0].node_type, "compress");
    }

    #[test]
    fn describe_lists_every_node_with_paths() {
        let infos = describe(&laser()).nodes;
        let paths: Vec<&str> = infos.iter().map(|i| i.path.as_str()).collect();
        assert_eq!(
            paths,
            vec![
                "root",
                "root.inputs[0]",
                "root.inputs[0].inputs[0]",
                "root.inputs[0].inputs[1]",
                "root.inputs[1]",
            ]
        );
        assert_eq!(infos[2].node_type, "square");
        assert_eq!(infos[2].params["freq"], 880.0);
    }

    #[test]
    fn morph_unifies_layer_identity() {
        let mk = |id1: &str, id2: &str, f: f32| -> SoundDoc {
            serde_json::from_str(&format!(
                r#"{{ "name": "m", "duration": 0.2, "version": 2,
                     "root": {{ "type": "tracks", "tracks": [
                        {{ "id": "{id1}", "node": {{ "type": "sine", "freq": {f} }} }},
                        {{ "id": "{id2}", "node": {{ "type": "noise" }}, "mute": true }}
                     ] }} }}"#
            ))
            .unwrap()
        };
        // Independently-minted layer ids must never block a morph.
        let a = mk("crack", "tail_a", 200.0);
        let b = mk("snap", "tail_b", 400.0);
        let mid = morph(&a, &b, 0.5).unwrap();
        let v = serde_json::to_value(&mid).unwrap();
        assert_eq!(v["root"]["tracks"][0]["id"], "crack"); // a's identity wins
        assert_eq!(v["root"]["tracks"][0]["node"]["freq"], 300.0);
        assert_eq!(v["root"]["tracks"][1]["mute"], true);
    }

    #[test]
    fn morph_midpoint_lerps_numbers_and_notes() {
        let a: SoundDoc = serde_json::from_str(
            r#"{ "name": "a", "duration": 0.2, "root": { "type": "sine", "freq": 200 } }"#,
        )
        .unwrap();
        let b: SoundDoc = serde_json::from_str(
            r#"{ "name": "b", "duration": 0.4, "root": { "type": "sine", "freq": 400 } }"#,
        )
        .unwrap();
        let mid = morph(&a, &b, 0.5).unwrap();
        let v = serde_json::to_value(&mid).unwrap();
        assert_eq!(v["root"]["freq"], 300.0);
        assert!((mid.duration - 0.3).abs() < 1e-6);
        // Structural mismatch is a clear error.
        let c: SoundDoc =
            serde_json::from_str(r#"{ "name": "c", "root": { "type": "noise" } }"#).unwrap();
        assert!(morph(&a, &c, 0.5).is_err());
    }

    #[test]
    fn morph_unifies_engine_seed_and_rate_instead_of_lerping() {
        // Presence mismatch (engine on one side only) must not reject the
        // morph, and the value must never interpolate through intermediate
        // kernels — the newer of the two wins.
        let a: SoundDoc = serde_json::from_str(
            r#"{ "name": "a", "duration": 0.2, "seed": 7,
                 "root": { "type": "sine", "freq": 200 } }"#,
        )
        .unwrap();
        let b: SoundDoc = serde_json::from_str(
            r#"{ "name": "b", "duration": 0.2, "seed": 99, "engine": 3,
                 "root": { "type": "sine", "freq": 400 } }"#,
        )
        .unwrap();
        let mid = morph(&a, &b, 0.5).unwrap();
        assert_eq!(mid.engine, Some(3), "max engine wins, never a lerp");
        assert_eq!(mid.seed, 7, "a's seed is identity, not a parameter");
        // Both legacy (no engine) stays legacy.
        let c: SoundDoc = serde_json::from_str(
            r#"{ "name": "c", "duration": 0.2, "root": { "type": "sine", "freq": 300 } }"#,
        )
        .unwrap();
        assert_eq!(morph(&a, &c, 0.5).unwrap().engine, None);
    }
}