Skip to main content

sva_cli/
new.rs

1// Concern: scaffolds a starter composition and the order to read it in | Non-concern: rendering it, or the JSON shape (output.rs) | IO: (dir, name) -> a written tree or CliError
2
3use std::path::{Path, PathBuf};
4
5use sva_core::CliError;
6
7/// `(path under the new directory, contents)`, written in this order so a directory always
8/// exists before a file lands in it. Every body stays a closed form until its own layer's
9/// written `sample()`, and each node's comment says why it is written that way rather than
10/// the way that costs orders of magnitude more.
11pub const FILES: [(&str, &str); 11] = [
12    (
13        "variables/bpm",
14        r"; Models: the pulse every `b` literal is measured against | Neglects: the meter, which variables/meter states | IO: () -> beats per minute | Tags: tempo
15120
16",
17    ),
18    (
19        "variables/meter",
20        r"; Models: how many beats a bar holds, so `1b` resolves to seconds | Neglects: the pulse itself, which variables/bpm states | IO: () -> beats per bar | Tags: meter
214/4
22",
23    ),
24    (
25        "variables/key",
26        r"; Models: the tonic every `st` offset is measured from, so transposing the piece is editing this one number | Neglects: the mode, which chord/home and grid/phrase-2b spell out in their own offsets | IO: () -> hertz | Tags: key
27C3
28",
29    ),
30    (
31        "voice/tone",
32        r"; Models: one voice's timbre, three harmonics rolled off by a lowpass at the third, held for len | Neglects: the envelope, which lib/env owns; every parameter carries a default and the crop ends it, so a bare `@voice/tone` plays | IO: (t, f0, vel, len) -> amplitude | Tags: voice, harmonics
33f0 = @../variables/key
34vel = 0.2
35len = 0.5s
36crop(lowpass(vel*(sin(2*pi*f0*t) + 0.5*sin(2*pi*2*f0*t) + 0.3333*sin(2*pi*3*f0*t)), 3*f0), 0s, len)
37",
38    ),
39    (
40        "lib/env",
41        r"; Models: one exponential decay under a shouldered crop, the shape every note wears | Neglects: the timbre it multiplies, which voice/tone owns; written as one window and never as a `min`/`max` pair, which would leave no dual and no exact reading | IO: (t, attack, decay, fade, len) -> a gain | Tags: envelope
42attack = 0.005s
43decay = 0.25s
44fade = 0.05s
45len = 0.5s
46crop(exp(-t/decay), 0s, len, rise=attack, fall=fade)
47",
48    ),
49    (
50        "voice/note",
51        r"; Models: one played note, a timbre under an envelope | Neglects: which pitch and when, which chord/home and grid/phrase-2b state | IO: (t, f0, vel, len) -> amplitude | Tags: voice, note
52f0 = @../variables/key
53vel = 0.2
54len = 0.5s
55@../voice/tone(t, f0=f0, vel=vel, len=len) * @../lib/env(t, len=len)
56",
57    ),
58    (
59        "chord/home",
60        r"; Models: the tonic triad, a third and a fifth stacked on variables/key as `st` offsets and never as written frequencies, so editing the key transposes the chord | Neglects: the envelope and the rhythm, which voice/note and grid/phrase-2b own | IO: (t) -> amplitude | Tags: chord, triad
61@../voice/tone(t, f0=@../variables/key*0st) + @../voice/tone(t, f0=@../variables/key*4st) + @../voice/tone(t, f0=@../variables/key*7st)
62",
63    ),
64    (
65        "grid/phrase-2b",
66        r"; Models: eight steps over two bars, one note a step, each pitch an `st` offset off variables/key | Neglects: the timbre and the envelope, which voice/tone and lib/env own | IO: (t) -> amplitude | Tags: grid, phrase
67@../voice/note(t, f0=@../variables/key*12st)
68@../voice/note(t, f0=@../variables/key*7st)
69@../voice/note(t, f0=@../variables/key*4st)
70@../voice/note(t, f0=@../variables/key*7st)
71@../voice/note(t, f0=@../variables/key*9st)
72@../voice/note(t, f0=@../variables/key*7st)
73@../voice/note(t, f0=@../variables/key*4st)
74@../voice/note(t, f0=@../variables/key*0st)
75",
76    ),
77    (
78        "perc/hat",
79        r"; Models: a closed hat -- one noise band under a shouldered crop, its 0.5 s period commensurate with this 2 s bar, its gain small because a noise's own rms is the square root of half its line count | Neglects: pitch, which no hat has; a `noise(...)*exp(...)` tail would cost orders of magnitude more | IO: (t, gain) -> amplitude | Tags: percussion, noise
80gain = 0.0005
81crop(gain*noise(1, period=0.5, color=1), 0s, 0.4s, rise=0.002s, fall=0.2s)
82",
83    ),
84    (
85        "fx/glue",
86        r"; Models: the pitched layers glued by one short feedback -- the pitched chain's one crossing into samples, and the last thing that chain does, because `self` may read only what `sample` has already written | Neglects: the hats, which master sums in beside this under a `sample` of their own; a loop rings on forever, so it is cropped to the two bars it plays | IO: (t) -> amplitude | Tags: fx, feedback
87crop(sample(0.5*@../chord/home(t) + @../grid/phrase-2b(t)) + 0.3*self[idx(t) - 1], 0s, 2b)
88",
89    ),
90    (
91        "master",
92        r"; Models: two bars of the whole piece, each layer sampled on its own | Neglects: nothing it does not name; one closed form over the noise and the grid together costs far more than this, and a mono master broadcasts to any width, so no `join` of a value with itself is written | IO: (t) -> amplitude | Tags: master, arrangement
93crop(0.6*(@fx/glue(t) + sample(@perc/hat(t)) + sample(@perc/hat(t - 1b))), 0s, 2b)
94",
95    ),
96];
97
98/// `(command, why)`, in the order a stranger should run them: what the composition IS before
99/// what it sounds like. Answered beside the
100/// tree `new` wrote, so the first thing an agent reads is the next thing it should do.
101pub const NEXT: [(&str, &str); 8] = [
102    (
103        "sva-cli lint",
104        "structure, comments, grid rows, key, whether each node plays bare; refuses before any audio",
105    ),
106    (
107        "sva-cli builtins",
108        "the whole vocabulary; nothing outside it parses",
109    ),
110    (
111        "sva-cli trace master",
112        "what master reads, and why it is samples",
113    ),
114    (
115        "sva-cli render 'sample(@voice/tone)' --representation spectrum(peaks=3)",
116        "the three harmonics the lowpass leaves, measured off its samples",
117    ),
118    (
119        "sva-cli render 'sample(@chord/home)' --representation spectrum(peaks=9)",
120        "the same triad follows variables/key",
121    ),
122    (
123        "sva-cli render '@perc/hat' --representation atoms",
124        "a noise is a line series, one atom per line, 2 Hz apart at period=0.5",
125    ),
126    (
127        "sva-cli render '@master' --representation ledger(skim=1)",
128        "per-node rms, peak, clipped",
129    ),
130    (
131        "sva-cli render '@master' --representation samples=/tmp/song.wav --rate 48000",
132        "the audio itself, at whatever rate you name",
133    ),
134];
135
136#[derive(Debug)]
137pub struct Scaffolded {
138    pub root: PathBuf,
139    pub files: Vec<String>,
140}
141
142/// Refuses if `<dir>/<name>` already exists, so `new` never overwrites a caller's own work.
143/// An `idempotency_key` is recorded beside the composition and answers the same `Scaffolded`
144/// again when the same key is retried over a tree still holding exactly this scaffold, so a
145/// network retry or an agent restart converges rather than erroring.
146pub fn scaffold(
147    dir: &Path,
148    name: &str,
149    idempotency_key: Option<&str>,
150) -> Result<Scaffolded, CliError> {
151    if name.is_empty() || name.contains('/') || name.contains(std::path::MAIN_SEPARATOR) {
152        return Err(CliError::Usage(format!(
153            "`{name}` must be a single directory name, not a path"
154        )));
155    }
156    let root = dir.join(name);
157    if root.exists() {
158        let key = idempotency_key.ok_or_else(|| CliError::Conflict {
159            by: "new",
160            message: format!(
161                "{} already exists; `new` never overwrites a composition. State \
162                 `--idempotency-key <key>` to have a retry of your own create succeed instead",
163                root.display()
164            ),
165        })?;
166        let taken = || CliError::Conflict {
167            by: "new",
168            message: format!(
169                "{} already exists and is not what `--idempotency-key {key}` scaffolded; \
170                 `new` never overwrites a composition",
171                root.display()
172            ),
173        };
174        if std::fs::read_to_string(key_path(dir, name)).ok().as_deref() != Some(key) {
175            return Err(taken());
176        }
177        if !holds_scaffold(&root) {
178            return Err(taken());
179        }
180        return Ok(Scaffolded {
181            root,
182            files: FILES.iter().map(|(path, _)| path.to_string()).collect(),
183        });
184    }
185    // Written aside, renamed in, the key last: a create that stopped leaves nothing behind.
186    let staging = dir.join(format!(".{name}.sva-new-{}", std::process::id()));
187    let _ = std::fs::remove_dir_all(&staging);
188    let files = staged(&staging).inspect_err(|_| {
189        let _ = std::fs::remove_dir_all(&staging);
190    })?;
191    std::fs::rename(&staging, &root).map_err(|e| {
192        let _ = std::fs::remove_dir_all(&staging);
193        CliError::Io(format!("could not put {} in place: {e}", root.display()))
194    })?;
195    if let Some(key) = idempotency_key {
196        std::fs::write(key_path(dir, name), key).map_err(|e| {
197            let _ = std::fs::remove_dir_all(&root);
198            let _ = std::fs::remove_file(key_path(dir, name));
199            CliError::Io(format!(
200                "could not record the idempotency key beside {}: {e}",
201                root.display()
202            ))
203        })?;
204    }
205    Ok(Scaffolded { root, files })
206}
207
208fn staged(staging: &Path) -> Result<Vec<String>, CliError> {
209    let mut files = Vec::with_capacity(FILES.len());
210    for (path, contents) in FILES {
211        let full = staging.join(path);
212        if let Some(parent) = full.parent() {
213            std::fs::create_dir_all(parent)
214                .map_err(|e| CliError::Io(format!("could not create {}: {e}", parent.display())))?;
215        }
216        std::fs::write(&full, contents)
217            .map_err(|e| CliError::Io(format!("could not write {}: {e}", full.display())))?;
218        files.push(path.to_string());
219    }
220    Ok(files)
221}
222
223/// Beside the composition, never inside it: every file under a composition root is a node.
224fn key_path(dir: &Path, name: &str) -> std::path::PathBuf {
225    dir.join(format!(".{name}.sva-idempotency-key"))
226}
227
228/// Byte-for-byte, so a retry only succeeds over a tree nothing has edited since.
229fn holds_scaffold(root: &Path) -> bool {
230    FILES.iter().all(|(path, contents)| {
231        std::fs::read_to_string(root.join(path)).is_ok_and(|held| held == *contents)
232    })
233}
234
235#[cfg(test)]
236mod tests {
237    use super::*;
238
239    fn tmp(name: &str) -> PathBuf {
240        let dir = std::env::temp_dir().join(format!("sva-cli-new-{name}-{:x}", std::process::id()));
241        let _ = std::fs::remove_dir_all(&dir);
242        std::fs::create_dir_all(&dir).unwrap();
243        dir
244    }
245
246    #[test]
247    fn scaffold_writes_every_file_and_reports_it() {
248        let dir = tmp("basic");
249        let scaffolded = scaffold(&dir, "song1", None).unwrap();
250        assert_eq!(scaffolded.root, dir.join("song1"));
251        assert_eq!(scaffolded.files.len(), FILES.len());
252        for (path, contents) in FILES {
253            let on_disk = std::fs::read_to_string(scaffolded.root.join(path)).unwrap();
254            assert_eq!(on_disk, contents);
255        }
256        let _ = std::fs::remove_dir_all(&dir);
257    }
258
259    #[test]
260    fn scaffold_refuses_a_name_that_already_exists() {
261        let dir = tmp("exists");
262        std::fs::create_dir_all(dir.join("song1")).unwrap();
263        let err = scaffold(&dir, "song1", None).unwrap_err();
264        assert!(matches!(err, CliError::Conflict { .. }));
265        assert_eq!(
266            err.exit_code(),
267            4,
268            "a taken name is a conflict, not a fault"
269        );
270        assert!(err.message().contains("already exists"));
271        let _ = std::fs::remove_dir_all(&dir);
272    }
273
274    /// The `cli` standard's own requirement for a create verb: a retry succeeds identically
275    /// rather than erroring, so an agent restart converges instead of dead-ending.
276    #[test]
277    fn a_retry_under_the_same_idempotency_key_answers_the_first_call_again() {
278        let dir = tmp("idempotent");
279        let first = scaffold(&dir, "song1", Some("k-1")).expect("a fresh scaffold");
280        let again = scaffold(&dir, "song1", Some("k-1")).expect("a retry over the same tree");
281        assert_eq!(first.root, again.root);
282        assert_eq!(first.files, again.files);
283
284        std::fs::write(first.root.join("master"), "0.0\n").unwrap();
285        let other = scaffold(&dir, "song1", Some("k-2")).unwrap_err();
286        assert!(
287            matches!(other, CliError::Conflict { .. }),
288            "someone else's key is not a retry of this create"
289        );
290
291        std::fs::write(first.root.join("master"), "0.0\n").unwrap();
292        let edited = scaffold(&dir, "song1", Some("k-1")).unwrap_err();
293        assert!(
294            matches!(edited, CliError::Conflict { .. }),
295            "an edited tree is not a retry"
296        );
297
298        let _ = std::fs::remove_dir_all(&dir);
299    }
300
301    #[test]
302    fn scaffold_refuses_a_name_that_is_a_path() {
303        let dir = tmp("pathlike");
304        assert!(matches!(
305            scaffold(&dir, "a/b", None).unwrap_err(),
306            CliError::Usage(_)
307        ));
308        let _ = std::fs::remove_dir_all(&dir);
309    }
310
311    /// A caller's very first `sva-cli lint` after `new` must not immediately refuse them —
312    /// the scaffold is the canonical example of the doc-comment convention, not an exception.
313    /// `missing-comment`/`multiline-comment`/`malformed-comment` are hard errors now, so a
314    /// violation here would surface as `Err`, not as a `Finding` to filter out.
315    #[test]
316    fn the_scaffolded_composition_lints_clean_of_every_doc_comment_check() {
317        let dir = tmp("lints-clean");
318        let scaffolded = scaffold(&dir, "song1", None).unwrap();
319        let report = crate::lint::lint(&scaffolded.root, None);
320        assert!(
321            report.is_ok(),
322            "a freshly scaffolded composition must carry a well-formed doc comment on every \
323             node: {}",
324            report.err().map(|e| e.message()).unwrap_or_default()
325        );
326        assert!(
327            report.is_ok_and(|held| held.findings.is_empty()),
328            "and no warning either: the quickstart's very first command must come back silent"
329        );
330        let _ = std::fs::remove_dir_all(&dir);
331    }
332
333    /// A `next` line an argv change broke would send a stranger's first move into a refusal.
334    #[test]
335    fn every_next_command_this_build_still_parses() {
336        for (command, why) in NEXT {
337            let argv: Vec<String> = command
338                .split_whitespace()
339                .skip(1)
340                .map(str::to_string)
341                .collect();
342            assert!(
343                crate::parse_args(&argv).is_ok(),
344                "`new` answers `{command}`, which this build refuses"
345            );
346            assert!(!why.is_empty(), "`{command}` is answered with no reason");
347        }
348    }
349
350    /// Nothing the house style refuses outright may be what a first composition teaches.
351    #[test]
352    fn no_scaffold_body_writes_what_this_engine_reads_expensively() {
353        for (path, contents) in FILES {
354            let body: String = contents
355                .lines()
356                .filter(|line| !line.trim_start().starts_with(';'))
357                .collect::<Vec<_>>()
358                .join("\n");
359            for banned in [
360                "44100", "48000", "96000", "rand(", "sat(", "tanh(", "min(", "max(", "sum(",
361                "join(",
362            ] {
363                assert!(
364                    !body.contains(banned),
365                    "`{path}` writes `{banned}`, which the scaffold teaches against"
366                );
367            }
368        }
369    }
370}