diff --git a/.gitignore b/.gitignore index 6aed7ec8..6e24ab4c 100644 --- a/.gitignore +++ b/.gitignore @@ -88,3 +88,13 @@ engine/media/real/ # phase-9 run material (footage frames, transcripts, briefs) is client data: it lives in ~/films/parts-9e/, never in git docs/craft/phase9/ + +.projects/cache +.projects/vault +.projects/state.test.json +.projects/state.local.test.json +.env +.env.* +!.env.example +# a session's throwaway scripts beside the SDK (sdk/raea/.scratch-N/), never committed +sdk/raea/.scratch-*/ diff --git a/Cargo.lock b/Cargo.lock index f0bcd261..c7314f56 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -11193,6 +11193,17 @@ dependencies = [ "objc2-foundation 0.3.2", ] +[[package]] +name = "objc2-metal-fx" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2db6f3a9d3b07481d9e5884f592aff6fd3f99e155423d1d1af3977e77a90ea0e" +dependencies = [ + "objc2 0.6.5", + "objc2-foundation 0.3.2", + "objc2-metal 0.3.2", +] + [[package]] name = "objc2-quartz-core" version = "0.2.2" @@ -13295,6 +13306,7 @@ checksum = "019b4b213425016d7d84a153c4c73afb0946fbb4840e4eece7ba8848b9d6da22" name = "raea-app-check" version = "0.1.0" dependencies = [ + "raea-core-brief", "serde_json", ] @@ -13360,6 +13372,7 @@ name = "raea-app-tools" version = "0.1.0" dependencies = [ "raea-io-assets", + "raea-io-gen", "raea-io-home", "raea-io-media", "raea-runtime-bundle", @@ -13367,6 +13380,14 @@ dependencies = [ "serde_json", ] +[[package]] +name = "raea-app-workspace" +version = "0.1.0" +dependencies = [ + "raea-core-brief", + "serde_json", +] + [[package]] name = "raea-bench-swatch" version = "0.1.0" @@ -13415,6 +13436,7 @@ dependencies = [ "bevy_trauma_shake", "bevy_tweening", "fastnoise-lite", + "moonshine-save", "noise", "noisy_bevy", "serde", @@ -13470,13 +13492,13 @@ dependencies = [ "lightyear", "lightyear_core", "mock_instant", - "moonshine-save", "noisy_bevy", "raea-bench-swatch", "raea-bevy-adapters", "raea-bevy-calls", "raea-bevy-world", "raea-core-calls", + "raea-io-home", "raea-runtime-plugins", "raea-sys-page", "rand_pcg", @@ -13567,15 +13589,18 @@ dependencies = [ "raea-app-media", "raea-app-play", "raea-app-tools", + "raea-app-workspace", "raea-bevy-plugins", "raea-core-alloc", "raea-core-animate", + "raea-core-brief", "raea-core-program", "raea-io-home", "raea-io-media", "raea-io-npm", "raea-io-trace", "raea-native", + "raea-neural", "raea-render", "raea-runtime-bake", "raea-runtime-export", @@ -13584,6 +13609,7 @@ dependencies = [ "raea-runtime-react", "raea-runtime-sound", "regex", + "serde", "serde_json", "wsx", ] @@ -13760,6 +13786,34 @@ dependencies = [ "serde_json", ] +[[package]] +name = "raea-io-gen" +version = "0.1.0" +dependencies = [ + "image", + "raea-io-gen-comfy", + "raea-io-gen-core", + "raea-io-home", + "serde_json", +] + +[[package]] +name = "raea-io-gen-comfy" +version = "0.1.0" +dependencies = [ + "raea-io-gen-core", + "serde_json", +] + +[[package]] +name = "raea-io-gen-core" +version = "0.1.0" +dependencies = [ + "raea-io-home", + "serde_json", + "sha2 0.10.9", +] + [[package]] name = "raea-io-home" version = "0.1.0" @@ -13804,6 +13858,7 @@ dependencies = [ "indexmap", "junction", "libc", + "raea-io-home", "reqwest", "serde", "serde_json", @@ -13820,6 +13875,7 @@ dependencies = [ "flate2", "htmd", "raea-core-calls", + "raea-io-home", "raea-io-net", "rusqlite", "serde_json", @@ -13876,6 +13932,14 @@ dependencies = [ "url", ] +[[package]] +name = "raea-neural" +version = "0.1.0" +dependencies = [ + "image", + "raea-runtime-bundle", +] + [[package]] name = "raea-page" version = "0.1.0" @@ -13888,6 +13952,7 @@ dependencies = [ "raea-gpu-device", "raea-io-media", "raea-runtime-dom", + "raea-runtime-edit", "raea-runtime-input", "raea-runtime-js", "raea-runtime-plugins", @@ -13910,27 +13975,56 @@ dependencies = [ "blitz-dom", "blitz-traits", "image", - "raea-gpu-device", "raea-io-media", "raea-page", - "raea-runtime-bake", + "raea-page-stage", + "raea-page-window", "raea-runtime-dom", "raea-runtime-input", "raea-runtime-js", - "raea-runtime-live", - "raea-runtime-react", - "raea-runtime-sound", + "raea-runtime-plugins", "raea-runtime-view", "raea-sys-a11y", "raea-sys-fonts", "raea-sys-page", - "raea-sys-tweak", "serde_json", "stylo", "tiny_http", +] + +[[package]] +name = "raea-page-stage" +version = "0.1.0" +dependencies = [ + "bevy", + "blitz-dom", + "raea-gpu-device", + "raea-runtime-bake", + "raea-runtime-dom", + "raea-runtime-js", + "raea-runtime-live", + "raea-runtime-react", + "raea-runtime-sound", + "raea-sys-page", + "raea-sys-tweak", + "serde_json", "wgpu", ] +[[package]] +name = "raea-page-window" +version = "0.1.0" +dependencies = [ + "bevy", + "block2 0.6.2", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "raea-runtime-js", + "raw-window-handle", + "serde_json", +] + [[package]] name = "raea-perceive" version = "0.1.0" @@ -13957,6 +14051,7 @@ dependencies = [ "raea-gpu-device", "raea-io-media", "raea-io-trace", + "raea-render-raytrace", "raea-runtime-gpuframe", "raea-runtime-plugins", "raea-runtime-scene3d", @@ -13988,6 +14083,17 @@ dependencies = [ "wgpu", ] +[[package]] +name = "raea-render-raytrace" +version = "0.1.0" +dependencies = [ + "bevy", + "objc2 0.6.5", + "objc2-metal 0.3.2", + "objc2-metal-fx", + "wgpu", +] + [[package]] name = "raea-runtime-bake" version = "0.1.0" @@ -14022,6 +14128,7 @@ dependencies = [ "bevy", "image", "manifold-rust", + "raea-core-scene", "raea-core-shape", "raea-io-media", "raea-io-net", @@ -14054,6 +14161,19 @@ dependencies = [ "vello", ] +[[package]] +name = "raea-runtime-edit" +version = "0.1.0" +dependencies = [ + "bevy", + "blitz-dom", + "parley", + "raea-runtime-dom", + "raea-runtime-js", + "raea-sys-page", + "serde_json", +] + [[package]] name = "raea-runtime-encode" version = "0.1.0" @@ -14141,8 +14261,10 @@ dependencies = [ "bevy", "raea-bevy-world", "raea-core-wire", + "raea-io-home", "raea-io-media", "raea-io-net", + "raea-runtime-bundle", "raea-runtime-jsengine", "serde", "serde_json", @@ -14415,6 +14537,7 @@ dependencies = [ "resvg", "serde_json", "tiny-skia 0.12.0", + "ttf-parser", "usvg", ] @@ -14658,6 +14781,7 @@ dependencies = [ "anyhow", "half", "ort", + "raea-io-home", "ureq 2.12.1", ] @@ -14706,6 +14830,7 @@ version = "0.1.0" dependencies = [ "image", "ocrs", + "raea-io-home", "raea-sys-layout", "raea-sys-vision", "rten", diff --git a/Cargo.toml b/Cargo.toml index bb015d6e..994496b0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -25,15 +25,21 @@ members = [ "engine/bevy-world", "engine/bundle", "engine/cli", + "engine/neural", "engine/modules", "engine/native", "io/npm", "engine/page", "engine/page/host", + "engine/page/stage", + "engine/page/window", "io/trace", "io/codec", "io/media", "io/assets", + "io/gen", + "io/gen-comfy", + "io/gen-core", "io/home", "io/soft", "io/av1", @@ -87,12 +93,14 @@ members = [ "systems/image", "runtime/twins", "runtime/dom", + "runtime/edit", "runtime/view", "runtime/encode", "runtime/plugins", "runtime/input", "tools/perceive", "engine/render", + "engine/render/raytrace", "engine/seedling", "runtime/react", "bench/bridge", @@ -109,6 +117,7 @@ members = [ "runtime/scene", "runtime/shared", "apps/check", + "apps/workspace", "apps/ci", "apps/tools", "apps/media", diff --git a/README.md b/README.md index 8a436037..538ecdf0 100644 --- a/README.md +++ b/README.md @@ -111,8 +111,11 @@ cargo build --release -p raea-cli --no-default-features target/release/raea render sdk/react/bench/games/pong/edit.tsx -o pong.mp4 ``` -`--no-default-features` builds the public engine. The default features add raea's hosted services, which aren't -part of this repository. [docs/settings.md](docs/settings.md) lists the settings raea reads. +`--no-default-features` builds the public engine, as the releases are. The default features add one hosted service, +Content Credentials signed by raea's signing server, which isn't part of this repository. raea sends nothing on its +own: no telemetry, crash reports or update checks. What reaches the network is what you ask for (a remote URL in a +composition, a model downloaded on first use, a `raea gen` step on a provider you hold a key for), and `RAEA_OFFLINE=1` +refuses all of it. [docs/settings.md](docs/settings.md) lists the settings raea reads. ## What's in here diff --git a/apps/check/Cargo.toml b/apps/check/Cargo.toml index d2827139..5bb7e74a 100644 --- a/apps/check/Cargo.toml +++ b/apps/check/Cargo.toml @@ -7,4 +7,6 @@ publish = false description = "`raea check`: the floor's measurable lines on an export, ranked P0-P3" [dependencies] +# taste.ts rules, as the raea CLI evaluates them (docs/projects.feature PJ0) +raea-core-brief = { path = "../../core/brief" } serde_json = "1" diff --git a/apps/check/src/lib.rs b/apps/check/src/lib.rs index 40eb61ef..020eb6f0 100644 --- a/apps/check/src/lib.rs +++ b/apps/check/src/lib.rs @@ -7,9 +7,9 @@ //! manifest (`raea render … --manifest render.json`): text clipped off the frame, text in the platform's UI zones, //! text held too briefly to read, caption contrast against the pixels behind it. With the transcript too: captions //! that come on away from the word they carry. With the face's place (`--perception`, the perception.json `raea cut` -//! writes): text over more than 8% of the face. With `--taste FILE|DIR`: the person's own mechanical rules, from the -//! `## Checks` section of their taste briefs (`- text-above 62%: Captions sit clear of the bottom.`), each a P1 when -//! broken, since the person's rule beats the floor's default (docs/craft-system.md, J). Exits 1 when a P0 or P1 is found. +//! writes): text over more than 8% of the face. With `--taste taste.ts|DIR`: the person's own mechanical rules, the +//! rules in their taste.ts files that carry a check (`{ text: "Captions sit clear of the bottom.", check: { form: +//! "text-above", value: 62 } }`), each a P1 when broken, since the person's rule beats the floor's default (docs/craft-system.md, J). Exits 1 when a P0 or P1 is found. use serde_json::{Value, json}; use std::collections::BTreeMap; use std::process::Command; @@ -20,6 +20,7 @@ mod picture; use picture::*; mod text; use text::*; +pub mod quick; #[cfg(test)] mod tests; @@ -33,8 +34,10 @@ struct Issue { says: String, } -pub fn cli(args: &[String]) -> i32 { - match run(args) { +/// `raea check …` with the person's taste, none or more (taste.ts and the kinds beside it, which the raea CLI evaluates: it owns the engine): +/// its rules' checks hold the export to the person's own lines. +pub fn cli_with(args: &[String], tastes: Vec) -> i32 { + match run(args, tastes) { Ok((report, bad)) => { println!("{report}"); i32::from(bad) @@ -50,7 +53,7 @@ fn flag<'a>(args: &'a [String], name: &str) -> Option<&'a str> { args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).map(String::as_str) } -pub const USAGE: &str = "raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--shape 16:9|9:16|4:5|1:1] [--platform tiktok|reels|shorts] [--taste FILE|DIR] [-o check.json] (an export against the floor: clipped text, contrast, safe areas, freezes, cues, loudness, blotching, a placeholder brand kit; P0-P3)"; +pub const USAGE: &str = "raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--shape 16:9|9:16|4:5|1:1] [--platform tiktok|reels|shorts] [--taste taste.ts|DIR] [-o check.json] (an export against the floor: clipped text, contrast, safe areas, freezes, cues, loudness, blotching, a placeholder brand kit; P0-P3)"; /// A rule from the person's taste: a form raea can measure, its value, and the taste line it stands for. #[derive(Clone, Debug, PartialEq)] @@ -60,56 +63,9 @@ struct Taste { line: String, } -/// the forms a taste check can take, and what each measures (apps/app/host/taste.ts offers the Director these) -pub const TASTE_FORMS: [(&str, &str); 6] = [ - ("text-hold", "S: every text holds at least S seconds"), - ("text-above", "P%: every text's bottom edge sits above P% of the frame's height"), - ("text-below", "P%: every text's top edge sits below P% of the frame's height"), - ("text-margin", "N: every text keeps N px (at 1080 on the short side) from each edge"), - ("loudness", "L: integrated loudness within 1 LU of L LUFS (instead of -14)"), - ("still-max", "S: nothing holds still longer than S seconds (instead of 3)"), -]; - -/// The `## Checks` lines of a taste brief, or of every `.brief` in a folder. A form raea doesn't know is skipped and -/// named, so a hand-written line never breaks a check. -fn taste_rules(path: &str) -> R<(Vec, Vec)> { - let p = std::path::Path::new(path); - let files: Vec = if p.is_dir() { - let mut v: Vec<_> = std::fs::read_dir(p).map_err(|e| format!("{path}: {e}"))?.filter_map(|e| e.ok().map(|e| e.path())).filter(|f| f.extension().is_some_and(|x| x == "brief")).collect(); - v.sort(); - v - } else { - vec![p.to_path_buf()] - }; - let (mut rules, mut skipped) = (Vec::new(), Vec::new()); - for f in files { - let text = std::fs::read_to_string(&f).map_err(|e| format!("{}: {e}", f.display()))?; - let (r, s) = parse_taste(&text); - rules.extend(r); - skipped.extend(s); - } - Ok((rules, skipped)) -} - -fn parse_taste(text: &str) -> (Vec, Vec) { - let (mut rules, mut skipped, mut on) = (Vec::new(), Vec::new(), false); - for l in text.lines() { - let t = l.trim(); - if let Some(h) = t.strip_prefix("## ") { - on = h.trim().eq_ignore_ascii_case("checks"); - continue; - } - let Some(item) = t.strip_prefix("- ").filter(|_| on) else { continue }; - let (rule, line) = item.split_once(':').map(|(a, b)| (a.trim(), b.trim())).unwrap_or((item, "")); - let mut words = rule.split_whitespace(); - let form = words.next().unwrap_or("").to_lowercase(); - let value = words.next().map(|v| v.trim_end_matches(|c: char| c.is_alphabetic() || c == '%')).and_then(|v| v.parse::().ok()); - match value { - Some(value) if TASTE_FORMS.iter().any(|(f, _)| *f == form) => rules.push(Taste { form, value, line: if line.is_empty() { rule.to_string() } else { line.to_string() } }), - _ => skipped.push(rule.to_string()), - } - } - (rules, skipped) +/// The checks among a person's taste rules (taste.ts and its kinds), each with the line it stands for. +fn taste_rules(tastes: &[raea_core_brief::Taste]) -> Vec { + tastes.iter().flat_map(|t| &t.sections).flat_map(|s| &s.rules).filter_map(|r| r.check.map(|c| Taste { form: c.form().to_string(), value: c.value(), line: r.text.clone() })).collect() } fn taste_of<'a>(rules: &'a [Taste], form: &str) -> Option<&'a Taste> { @@ -148,7 +104,7 @@ fn taste_text(rules: &[Taste], runs: &[Run], w: f64, h: f64, issues: &mut Vec R<(String, bool)> { +fn run(args: &[String], tastes: Vec) -> R<(String, bool)> { let video = args.iter().enumerate().find(|(i, a)| !a.starts_with('-') && !(*i > 0 && TAKES.contains(&args[i - 1].as_str()))).map(|(_, a)| a.clone()).ok_or(USAGE)?; if !std::path::Path::new(&video).exists() { return Err(format!("no file at {video}\n{USAGE}")); @@ -156,14 +112,7 @@ fn run(args: &[String]) -> R<(String, bool)> { let probe = Probe::of(&video)?; let mut issues = Vec::new(); let mut passed = Vec::new(); - let (taste, skipped) = match flag(args, "--taste") { - Some(t) if std::path::Path::new(t).exists() => taste_rules(t)?, - _ => (Vec::new(), Vec::new()), - }; - for s in skipped { - passed.push(format!("taste: \"{s}\" isn't a form raea measures; kept as a line, not checked")); - } - + let taste = taste_rules(&tastes); let manifest: Option = match flag(args, "--manifest") { Some(m) => Some(serde_json::from_str(&std::fs::read_to_string(m).map_err(|e| format!("{m}: {e}"))?).map_err(|e| format!("{m}: {e}"))?), None => None, @@ -192,9 +141,14 @@ fn run(args: &[String]) -> R<(String, bool)> { } } + report(&video, issues, passed, flag(args, "-o")) +} + +/// The issues ranked, written to -o as JSON when asked, and the report's text; true when a P0 or P1 is among them. +fn report(video: &str, mut issues: Vec, passed: Vec, out: Option<&str>) -> R<(String, bool)> { issues.sort_by(|a, b| a.p.cmp(&b.p).then(a.at.unwrap_or(0.0).total_cmp(&b.at.unwrap_or(0.0)))); let bad = issues.iter().any(|i| i.p <= 1); - if let Some(out) = flag(args, "-o") { + if let Some(out) = out { let j = json!({ "file": video, "issues": issues.iter().map(|i| json!({"rule": i.rule, "p": format!("P{}", i.p), "at": i.at, "says": i.says})).collect::>(), diff --git a/apps/check/src/quick.rs b/apps/check/src/quick.rs new file mode 100644 index 00000000..2d163812 --- /dev/null +++ b/apps/check/src/quick.rs @@ -0,0 +1,87 @@ +//! `raea check EDIT.tsx --quick` and `raea hook claude` (docs/skills.feature SK10). The quick check renders three stills +//! of a composition (a quarter in, the middle, the last frame) with their manifest, about a second, and runs the full +//! check's text rules and the person's text taste on it: clipped and cramped text, safe areas, sizes. The hook is +//! Claude Code's PostToolUse command (`raea skills install --agent claude` adds it): after a .tsx that registers a root +//! is written, the quick check's findings go back to the agent; a clean check says nothing. +use super::*; +use std::path::Path; + +/// The composition's length in frames, read from its source (the first `durationInFrames={N}`), 90 without one. +fn frames(src: &str) -> u64 { + src.split("durationInFrames={").nth(1).and_then(|r| r.split('}').next()).and_then(|n| n.trim().parse().ok()).unwrap_or(90) +} + +/// `raea check EDIT.tsx --quick [--shape S] [--platform P] [-o check.json]`: (report, P0 or P1 found). `tastes` are the +/// person's, evaluated by the raea CLI when --taste names them. +pub fn quick(args: &[String], tastes: Vec) -> R<(String, bool)> { + let file = args.iter().find(|a| a.ends_with(".tsx")).ok_or("raea check --quick takes a composition: EDIT.tsx")?; + let src = std::fs::read_to_string(file).map_err(|e| format!("{file}: {e}"))?; + let n = frames(&src).max(1); + let at = format!("{},{},{}", n / 4, n / 2, n - 1); + let tmp = std::env::temp_dir().join(format!("raea-quick-{}", std::process::id())); + std::fs::create_dir_all(&tmp).map_err(|e| format!("{}: {e}", tmp.display()))?; + let manifest = tmp.join("render.json"); + let me = std::env::current_exe().map_err(|e| e.to_string())?; + let out = std::process::Command::new(me).arg("render").arg(file).args(["--at", &at, "-o"]).arg(format!("{}/", tmp.display())).arg("--manifest").arg(&manifest).output().map_err(|e| e.to_string())?; + let result = if out.status.success() { + on_manifest(file, &manifest, args, tastes) + } else { + // a render that fails is the finding: the agent sees why + let (err, out) = (String::from_utf8_lossy(&out.stderr), String::from_utf8_lossy(&out.stdout)); + let mut why = Vec::new(); + for line in err.lines().chain(out.lines()) { + if line.contains("REFUSED") || line.contains("rror") { + why.push(line); + } + } + let why = why.join("\n"); + Ok((format!("raea check {file}: it doesn't render\nP0 render {why}"), true)) + }; + let _ = std::fs::remove_dir_all(&tmp); + result +} + +/// `raea hook claude`: Claude Code's PostToolUse input on stdin; for a saved composition, the quick check's findings as +/// the hook's additionalContext. Anything else, or a clean check, prints nothing. +pub fn hook(args: &[String]) -> R { + if args.first().map(String::as_str) != Some("claude") { + return Err("usage: raea hook claude (Claude Code's PostToolUse hook; raea skills install --agent claude adds it)".into()); + } + let mut input = String::new(); + std::io::Read::read_to_string(&mut std::io::stdin(), &mut input).map_err(|e| e.to_string())?; + let v: serde_json::Value = serde_json::from_str(&input).unwrap_or_default(); + let path = v["tool_input"]["file_path"].as_str().unwrap_or_default(); + let composition = path.ends_with(".tsx") && std::fs::read_to_string(path).map(|t| t.contains("registerRoot")).unwrap_or(false); + if !composition { + return Ok(String::new()); + } + let (report, _) = quick(&[path.to_string()], Vec::new())?; + if report.lines().nth(1).is_none_or(|l| l.starts_with("ok ")) { + return Ok(String::new()); + } + let found: Vec<&str> = report.lines().filter(|l| !l.starts_with("ok ")).collect(); + Ok(json!({"hookSpecificOutput": {"hookEventName": "PostToolUse", "additionalContext": format!("raea check --quick after this save:\n{}", found.join("\n"))}}).to_string()) +} + +/// `raea check --quick`'s half (docs/skills.feature SK10): the text rules and the person's text taste on the manifest +/// of a few stills (`raea render EDIT.tsx --at ... --manifest`), no video. What it can't see (contrast, freezes, +/// sound, blotching) waits for the full check on the export. +fn on_manifest(file: &str, manifest: &Path, args: &[String], tastes: Vec) -> R<(String, bool)> { + let at = manifest.display(); + let m: Value = serde_json::from_str(&std::fs::read_to_string(manifest).map_err(|e| format!("{at}: {e}"))?).map_err(|e| format!("{at}: {e}"))?; + let (mut issues, mut passed) = (Vec::new(), Vec::new()); + let runs = text_runs(&m); + let (w, h) = (m["width"].as_f64().unwrap_or(1080.0), m["height"].as_f64().unwrap_or(1920.0)); + text_rules(&runs, None, w, h, flag(args, "--shape"), flag(args, "--platform"), &mut issues, &mut passed); + taste_text(&taste_rules(&tastes), &runs, w, h, &mut issues, &mut passed); + report(file, issues, passed, flag(args, "-o")) +} + +#[cfg(test)] +mod tests { + #[test] + fn frames_come_from_the_source() { + assert_eq!(super::frames(""), 240); + assert_eq!(super::frames("no composition"), 90); + } +} diff --git a/apps/check/src/sound.rs b/apps/check/src/sound.rs index e6ebcee8..8c7e61f2 100644 --- a/apps/check/src/sound.rs +++ b/apps/check/src/sound.rs @@ -23,8 +23,10 @@ pub(crate) fn pct(v: &[f64], q: f64) -> f64 { s[lo] + (s[hi] - s[lo]) * (r - lo as f64) } -/// Each 10 ms step's level in dB, for the whole mix and in three bands (low < 500 Hz, mid to 4 kHz, high to 12 kHz): -/// a bed that stops under a voice shows in the band the voice doesn't fill (a projector's clatter in the highs) +/// Each 10 ms step's level in dBFS, for the whole mix and in three bands (low < 500 Hz, mid to 4 kHz, high to 12 kHz): +/// a bed that stops under a voice shows in the band the voice doesn't fill (a projector's clatter in the highs). A band's +/// level is its share of the step's mean square (Parseval, undoing the Hann window's power), so a tone reads the same in +/// its band as in the mix pub(crate) fn levels(x: &[f32]) -> (Vec, [Vec; 3]) { use std::f64::consts::PI; let n = x.len() / HOP; @@ -38,6 +40,8 @@ pub(crate) fn levels(x: &[f32]) -> (Vec, [Vec; 3]) { let bins: Vec<(usize, Vec<(f64, f64)>)> = (0..=HOP / 2) .filter_map(|k| Some((band(k)?, (0..HOP).map(|i| (-2.0 * PI * ((k * i) % HOP) as f64 / HOP as f64).sin_cos()).collect()))) .collect(); + // one-sided bins (no DC or Nyquist in any band) count twice; the window keeps mean(w²) of the power + let scale = 2.0 / (HOP * HOP) as f64 / (hann.iter().map(|h| h * h).sum::() / HOP as f64); let (mut rms, mut bands) = (Vec::with_capacity(n), [Vec::with_capacity(n), Vec::with_capacity(n), Vec::with_capacity(n)]); for f in x.chunks_exact(HOP) { let ms = f.iter().map(|&v| (v as f64).powi(2)).sum::() / HOP as f64; @@ -49,17 +53,22 @@ pub(crate) fn levels(x: &[f32]) -> (Vec, [Vec; 3]) { e[*b] += re * re + im * im; } for b in 0..3 { - bands[b].push(10.0 * (e[b] / HOP as f64 + 1e-12).log10()); + bands[b].push(10.0 * (e[b] * scale + 1e-18).log10()); } } (rms, bands) } /// Dead stops: a steady sound (a bed: a projector, rain, room tone, a held chord) that goes in one 10 ms step instead of -/// fading. Steady: over the second before, its level smoothed to 50 ms varies by under 3 dB (a voice or music with -/// phrases never holds that still). The stop: down 12 dB or more in one step, and the 300 ms after it DROP dB under the -/// bed. In the whole mix or one band, so a bed that stops under a voice shows where the voice doesn't cover it. +/// fading. Steady: over the second before, its level smoothed to 50 ms varies by under 3 dB. The stop: down 12 dB or more +/// in one step, from within AT dB of the bed one or two steps before (a fade that has already brought it down isn't a +/// stop), to DROP dB under the bed by the next step (gone, not a voice's tail that comes back up), and the 300 ms after it +/// DROP dB under the bed. In the whole mix or one band, so a bed that stops under a voice shows where the voice doesn't +/// cover it. Dense speech can pass for steady in the lows (its pitch fills them evenly), but a word ends in a tail that +/// rises again after the first drop, where a cut source is gone in one step. pub(crate) fn dead_stops(rms: &[f64], bands: &[Vec; 3]) -> Vec<(f64, String)> { + /// dB under the bed the sound may be just before it stops + const AT: f64 = 6.0; let mut found: Vec<(f64, String)> = Vec::new(); let n = rms.len(); for (name, lv) in [("the mix", rms), ("the lows", &bands[0][..]), ("the mids", &bands[1][..]), ("the highs", &bands[2][..])] { @@ -71,10 +80,13 @@ pub(crate) fn dead_stops(rms: &[f64], bands: &[Vec; 3]) -> Vec<(f64, String let pre = &sm[i - 100..i - 2]; let (bed, mean) = (pct(pre, 50.0), pre.iter().sum::() / pre.len() as f64); let sd = (pre.iter().map(|v| (v - mean).powi(2)).sum::() / pre.len() as f64).sqrt(); - let floor = if name == "the mix" { -50.0 } else { -65.0 }; + // under this nobody hears it stop + let floor = if name == "the mix" { -50.0 } else { -80.0 }; let at = i as f64 * HOP as f64 / SR as f64; - if bed > floor && sd < 3.0 && bed - pct(&lv[i..i + 30], 10.0) >= DROP && !found.iter().any(|(t, _)| (t - at).abs() < 0.5) { - found.push((at, format!("{name}: a steady sound at {bed:.0} dB stops dead in 10 ms: its source ran out (make it as long as its Sequence), or a Sequence cut it with no fadeOut"))); + let was_up = lv[i - 1].max(lv[i - 2]) >= bed - AT; + let gone = lv[i + 1] <= bed - DROP && bed - pct(&lv[i..i + 30], 10.0) >= DROP; + if bed > floor && sd < 3.0 && was_up && gone && !found.iter().any(|(t, _)| (t - at).abs() < 0.5) { + found.push((at, format!("{name}: a steady sound at {bed:.0} dBFS stops dead in 10 ms: its source ran out (make it as long as its Sequence), or a Sequence cut it with no fadeOut or one too short to hear (fade a bed out over 100 ms or more)"))); } } } diff --git a/apps/check/src/testdata/its-a-race-12s.levels b/apps/check/src/testdata/its-a-race-12s.levels new file mode 100644 index 00000000..c0fd6459 --- /dev/null +++ b/apps/check/src/testdata/its-a-race-12s.levels @@ -0,0 +1,6 @@ +# its-a-race (raea 0.1.0-canary.2, Linux export), 12.00-14.00 s: each 10 ms step's level in dBFS, one line per track: +# the mix, the lows, the mids, the highs. The voice ends "thing." at 13.36 s and pauses; nothing is cut there. +-9.4 -9.8 -10.1 -9.6 -9.2 -10.6 -11.9 -11.6 -10.1 -11.4 -11.0 -12.3 -10.0 -12.4 -12.2 -11.9 -11.6 -14.0 -16.2 -19.8 -17.9 -18.8 -22.8 -23.0 -25.0 -27.5 -26.2 -27.7 -30.9 -25.5 -17.2 -12.1 -11.3 -11.6 -12.3 -12.5 -12.2 -11.0 -12.4 -12.0 -12.5 -12.5 -12.3 -11.7 -12.8 -11.9 -12.1 -12.9 -12.4 -11.4 -11.1 -10.2 -11.2 -12.2 -11.8 -11.6 -12.7 -11.6 -12.0 -13.0 -13.1 -12.1 -13.8 -13.2 -14.3 -16.3 -19.5 -17.7 -17.0 -19.2 -16.0 -12.7 -12.9 -13.2 -15.4 -15.0 -15.6 -18.1 -19.1 -16.3 -17.9 -22.2 -28.5 -27.6 -28.4 -26.2 -12.5 -13.3 -12.2 -13.1 -12.3 -13.4 -14.6 -15.2 -12.2 -13.0 -12.4 -13.1 -13.3 -11.8 -13.2 -14.1 -11.5 -14.8 -16.7 -16.5 -16.2 -17.0 -19.1 -21.8 -22.1 -22.2 -22.3 -16.9 -12.7 -11.9 -14.7 -13.1 -12.9 -13.9 -16.6 -15.8 -14.9 -15.1 -18.6 -15.9 -17.3 -18.9 -15.6 -19.4 -21.3 -16.8 -18.7 -22.6 -17.7 -19.1 -27.5 -28.1 -29.8 -41.1 -35.5 -37.2 -39.2 -40.4 -40.4 -39.4 -47.0 -39.7 -40.4 -51.7 -42.6 -44.1 -46.9 -48.2 -51.3 -48.3 -54.1 -54.6 -55.0 -50.8 -54.1 -51.6 -55.5 -53.5 -51.7 -54.7 -51.8 -55.6 -57.5 -54.8 -51.2 -54.0 -51.8 -51.8 -47.9 -50.9 -51.1 -47.9 -53.1 -50.0 -46.5 -49.4 -49.4 -48.3 -55.7 -51.1 -48.7 -58.9 -54.4 -54.6 -50.3 -51.6 -58.0 -60.7 -60.2 -56.3 -58.9 -55.1 -48.8 -48.3 +-14.9 -13.6 -13.9 -11.8 -10.1 -11.9 -13.2 -13.9 -13.7 -14.6 -14.1 -15.8 -17.2 -14.8 -13.9 -15.5 -13.5 -13.1 -16.6 -21.9 -21.1 -20.4 -23.3 -22.7 -28.8 -27.3 -26.5 -29.2 -35.7 -27.5 -22.6 -22.5 -19.2 -18.5 -19.7 -20.1 -17.9 -17.9 -15.1 -15.8 -15.0 -13.3 -12.8 -13.5 -13.7 -13.6 -16.6 -18.3 -17.9 -17.1 -17.1 -18.0 -16.5 -14.8 -15.7 -15.5 -16.9 -15.5 -15.9 -16.3 -16.4 -15.2 -15.0 -13.5 -15.7 -16.3 -23.9 -18.8 -18.5 -23.4 -18.3 -14.9 -16.9 -17.7 -16.7 -14.8 -15.0 -18.9 -21.1 -15.8 -16.0 -21.6 -29.5 -28.3 -27.8 -29.9 -10.9 -13.0 -12.6 -15.2 -15.0 -15.2 -15.6 -16.4 -10.9 -11.7 -13.4 -16.4 -17.2 -16.1 -13.2 -12.7 -11.2 -14.8 -20.7 -20.7 -15.1 -16.6 -20.0 -21.9 -21.4 -21.1 -24.0 -20.7 -14.1 -12.1 -14.9 -13.9 -15.8 -17.8 -18.0 -17.5 -18.0 -17.0 -19.3 -18.6 -19.4 -17.7 -15.2 -19.0 -21.7 -16.0 -21.9 -26.4 -17.1 -18.4 -30.6 -32.5 -28.5 -40.9 -36.5 -39.9 -42.0 -41.9 -39.9 -38.6 -48.0 -39.9 -41.4 -51.5 -41.3 -44.6 -49.2 -51.7 -51.6 -46.6 -55.4 -54.4 -57.2 -51.8 -53.6 -54.4 -67.4 -54.8 -52.1 -59.4 -52.1 -60.5 -57.8 -56.5 -50.9 -55.9 -56.8 -54.8 -50.8 -52.6 -53.3 -48.0 -51.4 -50.9 -49.4 -53.1 -50.5 -48.2 -60.7 -51.3 -48.6 -57.8 -54.4 -56.1 -50.3 -53.1 -61.4 -63.3 -63.1 -55.4 -63.0 -64.0 -49.9 -47.3 +-12.0 -10.4 -12.3 -11.7 -10.7 -10.7 -14.9 -14.4 -12.3 -16.6 -13.5 -14.5 -11.1 -16.7 -15.5 -18.9 -13.4 -22.6 -23.6 -21.8 -26.7 -20.9 -28.7 -30.7 -30.0 -33.2 -34.9 -34.4 -36.3 -31.4 -24.7 -16.0 -10.5 -9.2 -9.7 -10.8 -12.7 -15.1 -19.7 -17.3 -19.4 -19.3 -20.1 -19.5 -21.5 -19.3 -18.7 -18.7 -15.4 -13.5 -14.9 -12.2 -15.0 -15.6 -14.6 -13.9 -16.5 -13.7 -13.6 -15.2 -14.7 -13.5 -16.3 -19.3 -20.2 -19.0 -23.1 -24.0 -23.2 -23.2 -17.9 -13.7 -16.6 -17.8 -22.7 -24.8 -28.6 -28.2 -32.4 -34.7 -34.6 -36.6 -38.0 -40.1 -42.3 -35.2 -23.1 -16.8 -16.8 -18.0 -18.1 -23.6 -26.2 -29.0 -29.4 -35.4 -27.7 -27.3 -21.4 -26.4 -28.5 -27.2 -31.6 -32.5 -31.8 -36.6 -30.0 -35.9 -34.5 -38.9 -46.2 -36.8 -36.4 -28.6 -24.0 -19.9 -20.8 -18.7 -14.8 -20.7 -21.7 -21.0 -17.7 -24.2 -26.8 -25.9 -25.1 -35.3 -33.6 -35.9 -31.9 -33.1 -37.1 -37.0 -39.4 -41.9 -41.4 -41.3 -44.5 -52.1 -49.2 -51.5 -50.8 -55.7 -54.8 -54.7 -59.0 -53.6 -56.8 -62.2 -59.4 -59.3 -58.9 -61.8 -63.8 -64.5 -65.8 -59.9 -62.2 -60.3 -64.8 -63.2 -62.9 -61.9 -64.4 -68.0 -64.8 -63.3 -65.8 -65.6 -60.6 -59.4 -60.2 -62.9 -61.1 -65.1 -61.8 -61.2 -63.9 -60.1 -60.1 -63.2 -64.3 -62.1 -64.6 -58.1 -62.4 -63.1 -60.3 -64.0 -65.1 -66.5 -64.5 -64.1 -61.3 -63.4 -63.7 -64.4 -61.6 -61.3 +-67.9 -67.4 -67.8 -66.7 -64.9 -65.1 -68.8 -66.5 -65.0 -67.2 -65.0 -68.4 -65.1 -63.2 -62.2 -64.6 -69.9 -69.5 -65.1 -59.3 -71.5 -71.7 -73.7 -70.1 -73.6 -71.9 -70.5 -68.0 -64.9 -59.0 -52.7 -48.0 -46.1 -43.3 -46.8 -49.0 -48.5 -45.5 -46.1 -48.9 -42.3 -48.5 -48.3 -53.6 -53.2 -52.8 -47.4 -44.4 -54.5 -56.1 -56.2 -54.6 -52.5 -53.6 -53.8 -57.0 -54.5 -55.2 -54.0 -53.7 -51.1 -59.0 -56.1 -55.7 -57.7 -58.6 -64.5 -65.6 -64.7 -66.6 -61.2 -51.6 -49.8 -51.2 -54.4 -58.5 -57.3 -62.0 -59.5 -58.1 -51.3 -45.8 -48.4 -47.1 -45.8 -50.3 -46.3 -42.4 -42.0 -47.7 -51.6 -52.3 -56.7 -59.0 -61.9 -65.4 -64.7 -63.4 -59.2 -58.6 -54.0 -55.7 -53.6 -47.1 -44.8 -41.1 -44.5 -41.3 -44.8 -43.8 -45.0 -46.5 -47.4 -48.1 -52.2 -52.5 -53.3 -54.0 -57.1 -58.2 -61.1 -60.7 -60.3 -59.0 -57.6 -59.4 -62.1 -66.4 -65.6 -68.2 -66.6 -66.0 -72.4 -68.6 -68.9 -72.2 -73.0 -71.9 -75.4 -73.8 -73.7 -76.3 -74.6 -77.1 -76.4 -76.4 -75.2 -76.3 -75.4 -76.6 -77.8 -77.1 -74.6 -76.5 -74.6 -77.6 -76.2 -77.3 -74.8 -78.0 -76.6 -79.6 -80.0 -77.4 -75.6 -77.0 -76.9 -75.9 -77.0 -76.4 -76.4 -76.5 -78.2 -77.6 -76.1 -77.6 -77.7 -76.8 -76.7 -77.5 -76.9 -77.7 -75.2 -76.9 -78.1 -76.3 -76.9 -78.3 -79.3 -78.9 -77.1 -76.9 -79.3 -77.4 -78.4 -77.1 -76.3 -77.9 -76.2 -76.3 diff --git a/apps/check/src/tests.rs b/apps/check/src/tests.rs index 1f1deea2..b9b0970b 100644 --- a/apps/check/src/tests.rs +++ b/apps/check/src/tests.rs @@ -56,14 +56,17 @@ fn flat_dark_is_clean_and_stepped_dark_is_blotchy() { } #[test] -fn taste_checks_read_their_section_and_hold_text_to_the_persons_line() { - let brief = "# Shane's taste\n\n## Always\n- text-above 60%: not a check here\n\n## Checks\n- text-above 62%: Captions sit clear of the bottom.\n- glow-free: no glow\n- text-hold 2 s\n"; - let (rules, skipped) = parse_taste(brief); +fn taste_checks_hold_text_to_the_persons_line() { + let taste: raea_core_brief::Taste = serde_json::from_value(json!({"title": "Shane's taste", "sections": [{"heading": "Always", "rules": [ + {"text": "Captions sit clear of the bottom.", "check": {"form": "text-above", "value": 62.0}}, + {"text": "No glow"}, + {"text": "Text holds two seconds", "check": {"form": "text-hold", "value": 2.0}}, + ]}]})).unwrap(); + let rules = taste_rules(&[taste]); assert_eq!(rules, vec![ Taste { form: "text-above".into(), value: 62.0, line: "Captions sit clear of the bottom.".into() }, - Taste { form: "text-hold".into(), value: 2.0, line: "text-hold 2 s".into() }, + Taste { form: "text-hold".into(), value: 2.0, line: "Text holds two seconds".into() }, ]); - assert_eq!(skipped, vec!["glow-free".to_string()]); let low = Run { text: "Render anything.".into(), from: 1.0, to: 4.0, box_: [800.0, 800.0, 300.0, 60.0], boxes: vec![[800.0, 800.0, 300.0, 60.0]], color: String::new(), size: 48.0 }; let high = Run { text: "raea".into(), from: 5.0, to: 6.0, box_: [800.0, 300.0, 300.0, 60.0], boxes: vec![[800.0, 300.0, 300.0, 60.0]], color: String::new(), size: 48.0 }; let (mut issues, mut passed) = (vec![], vec![]); @@ -79,7 +82,7 @@ fn taste_checks_read_their_section_and_hold_text_to_the_persons_line() { #[ignore] fn on_a_real_export() { let args: Vec = std::env::var("RAEA_CHECK_ARGS").expect("RAEA_CHECK_ARGS").split_whitespace().map(String::from).collect(); - let code = cli(&args); + let code = cli_with(&args, Vec::new()); println!("exit {code}"); } @@ -103,6 +106,45 @@ fn a_steady_sound_that_stops_dead_is_found_and_a_faded_one_isnt() { let faded: Vec = tone(4.0, &[(0.0, 3.0, -20.0)]).into_iter().enumerate().map(|(i, v)| v * (1.0 - ((i as f32 / SR as f32) - 2.0).clamp(0.0, 1.0))).collect(); let (rms, bands) = levels(&faded); assert!(dead_stops(&rms, &bands).is_empty()); + // a source cut partway through a 10 ms step is as dead + let cut: Vec = tone(4.0, &[(0.0, 2.0 + 117.0 / SR as f64, -20.0)]); + let (rms, bands) = levels(&cut); + assert_eq!(dead_stops(&rms, &bands).len(), 1); + // a 100 ms fadeOut is a fade, though its last step falls into silence + let short: Vec = tone(4.0, &[(0.0, 2.0, -20.0)]).into_iter().enumerate().map(|(i, v)| v * ((2.0 - i as f32 / SR as f32) / 0.1).clamp(0.0, 1.0)).collect(); + let (rms, bands) = levels(&short); + assert!(dead_stops(&rms, &bands).is_empty(), "{:?}", dead_stops(&rms, &bands)); +} + +#[test] +fn bands_read_in_dbfs() { + // a tone in the middle of its band reads there what it reads in the mix: -20 dBFS peak is -23 dBFS RMS + let sine = |hz: f64| (0..SR).map(|i| (0.1 * (2.0 * std::f64::consts::PI * hz * i as f64 / SR as f64).sin()) as f32).collect::>(); + for (hz, band) in [(200.0, 0), (2000.0, 1), (8000.0, 2)] { + let (rms, bands) = levels(&sine(hz)); + assert!((rms[50] + 23.0).abs() < 0.1, "{}", rms[50]); + assert!((bands[band][50] - rms[50]).abs() < 0.2, "{hz} Hz: band {} vs the mix {}", bands[band][50], rms[50]); + } +} + +#[test] +fn a_voice_that_ends_a_sentence_isnt_a_dead_stop() { + // its-a-race at 12-14 s: "AI became a thing." ends at 13.36 s and the speaker pauses. Its lows held within 2.6 dB over + // the second before and fell 12 dB in one step, so they read as a bed cut dead ("a steady sound at -0 dB", before the + // bands read in dBFS), but the mix follows the source there and the word's tail comes back up after the first drop + let tracks: Vec> = include_str!("testdata/its-a-race-12s.levels") + .lines() + .filter(|l| !l.starts_with('#')) + .map(|l| l.split_whitespace().map(|v| v.parse().unwrap()).collect()) + .collect(); + let bands = [tracks[1].clone(), tracks[2].clone(), tracks[3].clone()]; + let stops = dead_stops(&tracks[0], &bands); + assert!(stops.is_empty(), "{stops:?}"); + // the same voice with a bed under it that's cut at 13.6 s: that one is still found + let bed = 10f64.powf(-30.0 / 10.0); + let highs: Vec = tracks[3].iter().enumerate().map(|(i, v)| 10.0 * (10f64.powf(v / 10.0) + if i < 160 { bed } else { 0.0 }).log10()).collect(); + let found = dead_stops(&tracks[0], &[tracks[1].clone(), tracks[2].clone(), highs]); + assert!(found.iter().any(|(at, says)| (at - 1.6).abs() < 0.02 && says.starts_with("the highs")), "{found:?}"); } #[test] diff --git a/apps/game/src/gather.rs b/apps/game/src/gather.rs index cc956575..a67533dc 100644 --- a/apps/game/src/gather.rs +++ b/apps/game/src/gather.rs @@ -94,7 +94,7 @@ pub(crate) fn gather(bundle: &mut String, dir: &Path, game: &Path, got: &mut Gat let decoded = raea_io_net::percent_decode_str(s); let mut cands: Vec = Vec::new(); if let Some(rest) = decoded.strip_prefix("/media/") { - cands.push(dir.join("media").join(rest)); + cands.push(raea_runtime_react::scene::media_path(dir, &format!("/media/{rest}"))); } if decoded.starts_with('/') { cands.push(PathBuf::from(&decoded)); diff --git a/apps/tools/Cargo.toml b/apps/tools/Cargo.toml index ad8d04a1..4214cadd 100644 --- a/apps/tools/Cargo.toml +++ b/apps/tools/Cargo.toml @@ -4,7 +4,7 @@ version = "0.1.0" edition = "2024" license = "FSL-1.1-ALv2" publish = false -description = "The `raea` verbs that run raea's local model tools: sao, tokensynth, setup-audio, sounds, splat and song" +description = "The `raea` verbs that run raea's model tools: sao, tokensynth, setup-audio, sounds, splat, song and gen" [features] # a made sound signed as generated (raea's own API; the public engine goes without) @@ -12,6 +12,8 @@ service = [] [dependencies] raea-io-assets = { path = "../../io/assets" } +# generation flows: made.app, fal, Replicate, OpenRouter, Modal, ComfyUI (`raea gen`) +raea-io-gen = { path = "../../io/gen" } raea-io-home = { path = "../../io/home" } raea-io-media = { path = "../../io/media", default-features = false } serde_json = "1" diff --git a/apps/tools/src/agent_mcp.rs b/apps/tools/src/agent_mcp.rs new file mode 100644 index 00000000..a4758091 --- /dev/null +++ b/apps/tools/src/agent_mcp.rs @@ -0,0 +1,174 @@ +//! The MCP servers `raea skills install` offers an agent (docs/skills.feature SK11): today `blender`, which drives a +//! running Blender through the MCP for Blender add-on (`raea setup blender` installs it). Each agent keeps MCP servers +//! in its own place; a server already registered under the name is left as the person set it. +use serde_json::{json, Value}; +use std::path::{Path, PathBuf}; +use std::process::Command; + +/// The blender MCP server: uv runs it, so nothing is installed until an agent starts it. +const NAME: &str = "blender"; +const CMD: &str = "uvx"; +const ARGS: [&str; 1] = ["mcp-for-blender"]; + +type R = Result; + +/// The person's home folder (HOME, or USERPROFILE on Windows). +pub fn user_home() -> R { + std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(PathBuf::from).ok_or_else(|| "no home folder (HOME)".into()) +} + +/// The JSON file holding `mcpServers` for agents configured that way (Kimi Code, Gemini CLI, Claude Code's own file). +fn json_file(agent: &str) -> R> { + let h = user_home()?; + Ok(match agent { + "claude" => Some(h.join(".claude.json")), + "kimi" => Some(std::env::var_os("KIMI_CODE_HOME").filter(|v| !v.is_empty()).map(PathBuf::from).unwrap_or_else(|| h.join(".kimi-code")).join("mcp.json")), + "gemini" => Some(h.join(".gemini/settings.json")), + _ => None, + }) +} + +/// Adds `blender` to a JSON config's `mcpServers` unless one is there; true when it added. +pub fn add_json(path: &Path) -> R { + let mut doc: Value = match std::fs::read_to_string(path) { + Ok(t) if !t.trim().is_empty() => serde_json::from_str(&t).map_err(|e| format!("{}: {e}", path.display()))?, + _ => json!({}), + }; + let servers = doc.as_object_mut().ok_or_else(|| format!("{} isn't a JSON object", path.display()))?.entry("mcpServers").or_insert_with(|| json!({})); + let servers = servers.as_object_mut().ok_or_else(|| format!("{}: mcpServers isn't an object", path.display()))?; + if servers.contains_key(NAME) { + return Ok(false); + } + servers.insert(NAME.into(), json!({"command": CMD, "args": ARGS})); + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?; + } + let tmp = path.with_extension("raea-tmp"); + std::fs::write(&tmp, serde_json::to_string_pretty(&doc).unwrap_or_default() + "\n").map_err(|e| format!("{}: {e}", tmp.display()))?; + std::fs::rename(&tmp, path).map_err(|e| format!("{}: {e}", path.display()))?; + Ok(true) +} + +/// Adds a `[mcp_servers.blender]` table to Codex's config.toml unless one is there; true when it added. +pub fn add_toml(path: &Path) -> R { + let text = std::fs::read_to_string(path).unwrap_or_default(); + if text.lines().any(|l| l.trim() == format!("[mcp_servers.{NAME}]")) { + return Ok(false); + } + let args = ARGS.iter().map(|a| format!("{a:?}")).collect::>().join(", "); + let sep = if text.is_empty() || text.ends_with("\n\n") { "" } else if text.ends_with('\n') { "\n" } else { "\n\n" }; + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?; + } + std::fs::write(path, format!("{text}{sep}[mcp_servers.{NAME}]\ncommand = {CMD:?}\nargs = [{args}]\n")).map_err(|e| format!("{}: {e}", path.display()))?; + Ok(true) +} + +/// Registers the blender MCP server for an agent; the line says what happened. Claude Code rewrites ~/.claude.json while +/// it runs, so its own `claude mcp add` is used when `claude` is on PATH. +pub fn offer(agent: &str) -> R { + let line = |added: bool, at: &Path| if added { format!("{}: MCP server {NAME} added", at.display()) } else { format!("{}: MCP server {NAME} already there", at.display()) }; + if agent == "codex" { + let p = user_home()?.join(".codex/config.toml"); + return Ok(line(add_toml(&p)?, &p)); + } + let p = json_file(agent)?.ok_or_else(|| format!("no agent {agent:?}"))?; + if agent == "claude" { + let listed = Command::new("claude").args(["mcp", "get", NAME]).output(); + match listed { + Ok(o) if o.status.success() => return Ok(line(false, &p)), + Ok(_) => { + let o = Command::new("claude").args(["mcp", "add", "--scope", "user", NAME, "--", CMD]).args(ARGS).output().map_err(|e| e.to_string())?; + if !o.status.success() { + return Err(format!("claude mcp add {NAME}: {}", String::from_utf8_lossy(&o.stderr).trim())); + } + return Ok(line(true, &p)); + } + Err(_) => {} // no claude on PATH: write its file + } + } + Ok(line(add_json(&p)?, &p)) +} + +/// A hook entry raea added (its command is `raea hook ...`). +fn ours(hook: &Value) -> bool { + hook["command"].as_str().unwrap_or("").starts_with("raea hook") +} + +/// Claude Code's PostToolUse hook running `raea hook claude` after a file is written, in its settings.json, unless one +/// is there; true when it added. Its findings reach the agent as the hook's additionalContext. +pub fn claude_hook(settings: &Path) -> R { + let mut doc: Value = match std::fs::read_to_string(settings) { + Ok(t) if !t.trim().is_empty() => serde_json::from_str(&t).map_err(|e| format!("{}: {e}", settings.display()))?, + _ => json!({}), + }; + let post = doc.as_object_mut().ok_or("settings.json isn't an object")?.entry("hooks").or_insert_with(|| json!({})).as_object_mut().ok_or("settings.json: hooks isn't an object")?.entry("PostToolUse").or_insert_with(|| json!([])); + let list = post.as_array_mut().ok_or("settings.json: hooks.PostToolUse isn't a list")?; + if list.iter().any(|m| m["hooks"].as_array().into_iter().flatten().any(ours)) { + return Ok(false); + } + list.push(json!({"matcher": "Write|Edit|MultiEdit", "hooks": [{"type": "command", "command": "raea hook claude", "timeout": 60}]})); + let tmp = settings.with_extension("raea-tmp"); + std::fs::write(&tmp, serde_json::to_string_pretty(&doc).unwrap_or_default() + "\n").map_err(|e| format!("{}: {e}", tmp.display()))?; + std::fs::rename(&tmp, settings).map_err(|e| format!("{}: {e}", settings.display()))?; + Ok(true) +} + +/// A move's guide as a skill of its own, named for the move: its description from the guide's first paragraph. +pub fn pin(to: &Path, mv: &str, v: &str) -> R { + let guide = raea_io_home::home().join("sdk/guides/craft/verbs").join(format!("{mv}.md")); + let no = format!("no move {mv:?}: `raea guide` lists them"); + if mv.is_empty() || !mv.chars().all(|c| c.is_ascii_lowercase()) { + return Err(no); + } + let text = std::fs::read_to_string(&guide).map_err(|_| no)?; + let first = text.split("\n\n").nth(1).unwrap_or_default().replace('\n', " "); + let md = format!("---\nname: {mv}\ndescription: raea's {mv} move, for a note on a raea piece. {}\nversion: {v}\n---\n\n# {mv}\n\nRun `raea guide {mv}` and follow it on the part or moment the note names. Answer the person in their words, never with the move's name. The raea skill has the rest.\n", first.replace(':', " -")); + let dir = to.join(mv); + std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?; + std::fs::write(dir.join("SKILL.md"), md).map_err(|e| e.to_string())?; + Ok(format!("{}: /{mv} pinned\n", dir.display())) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn adds_once_and_keeps_what_was_there() { + let d = std::env::temp_dir().join(format!("raea-agent-mcp-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + let j = d.join("kimi/mcp.json"); + assert!(add_json(&j).unwrap()); + assert!(!add_json(&j).unwrap()); + std::fs::write(&j, r#"{"theme":"dark","mcpServers":{"blender":{"command":"mine"}}}"#).unwrap(); + assert!(!add_json(&j).unwrap()); + let kept: Value = serde_json::from_str(&std::fs::read_to_string(&j).unwrap()).unwrap(); + assert_eq!(kept["mcpServers"]["blender"]["command"], "mine"); + let t = d.join("codex/config.toml"); + std::fs::create_dir_all(t.parent().unwrap()).unwrap(); + std::fs::write(&t, "model = \"x\"\n").unwrap(); + assert!(add_toml(&t).unwrap()); + assert!(!add_toml(&t).unwrap()); + assert_eq!(std::fs::read_to_string(&t).unwrap(), "model = \"x\"\n\n[mcp_servers.blender]\ncommand = \"uvx\"\nargs = [\"mcp-for-blender\"]\n"); + let h = d.join("claude/settings.json"); + std::fs::create_dir_all(h.parent().unwrap()).unwrap(); + std::fs::write(&h, r#"{"model":"x","hooks":{"PostToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"other"}]}]}}"#).unwrap(); + assert!(claude_hook(&h).unwrap()); + assert!(!claude_hook(&h).unwrap()); + let v: Value = serde_json::from_str(&std::fs::read_to_string(&h).unwrap()).unwrap(); + assert_eq!(v["hooks"]["PostToolUse"].as_array().unwrap().len(), 2); + assert_eq!(v["model"], "x"); + let _ = std::fs::remove_dir_all(&d); + } + + #[test] + fn a_pinned_move_is_a_skill_of_its_own() { + let d = std::env::temp_dir().join(format!("raea-pin-{}", std::process::id())); + assert!(pin(&d, "quieter", "9.9").unwrap().contains("/quieter pinned")); + let md = std::fs::read_to_string(d.join("quieter/SKILL.md")).unwrap(); + assert!(md.starts_with("---\nname: quieter\ndescription: raea's quieter move") && md.contains("\nversion: 9.9\n---\n") && md.contains("raea guide quieter"), "{md}"); + assert!(pin(&d, "../x", "1").is_err() && pin(&d, "nomove", "1").is_err()); + let _ = std::fs::remove_dir_all(&d); + } +} diff --git a/apps/tools/src/blender.rs b/apps/tools/src/blender.rs new file mode 100644 index 00000000..3af96b14 --- /dev/null +++ b/apps/tools/src/blender.rs @@ -0,0 +1,225 @@ +//! `raea setup blender` and `raea blender run` (docs/skills.feature SK11). Blender is GPL, so raea never bundles it: it +//! finds the person's Blender, or downloads the current LTS from blender.org into ~/.raea/tools/blender, and runs it as +//! its own program. The setup also installs the MCP for Blender add-on (github.com/ahujasid/mcp-for-blender, MIT) into +//! that Blender, so an agent's `blender` MCP server (raea skills install adds it) can drive a running Blender. +use std::path::{Path, PathBuf}; +use std::process::Command; + +type R = Result; + +pub const USAGE: &str = "raea setup blender [--check] [--download] (find Blender or download the LTS into ~/.raea/tools/blender, and install its MCP add-on)\n raea blender run SCRIPT.py [ARGS...] (blender --background --python SCRIPT.py -- ARGS, headless)"; + +/// The LTS series raea downloads; the newest patch in blender.org/release/Blender/ is taken. Moved when Blender +/// ships a new LTS (blender.org/download/lts). +const LTS: &str = "5.2"; + +/// Where raea keeps the Blender it downloads. +fn own_dir() -> R { + Ok(crate::agent_mcp::user_home()?.join(".raea/tools/blender")) +} + +/// The Blender binary inside raea's own download, per platform. +fn own_binary() -> R { + let d = own_dir()?; + Ok(if cfg!(target_os = "macos") { d.join("Blender.app/Contents/MacOS/Blender") } else if cfg!(windows) { d.join("blender.exe") } else { d.join("blender") }) +} + +fn on_path(name: &str) -> Option { + std::env::split_paths(&std::env::var_os("PATH")?).map(|d| d.join(name)).find(|p| p.is_file()) +} + +/// The Blender to use and where it came from: `git config --global raea.blender`, raea's own download, the usual app +/// folders, then PATH. +pub fn find() -> Option<(PathBuf, &'static str)> { + let configured = run(Command::new("git").args(["config", "--global", "raea.blender"]), "git config").ok().map(|out| PathBuf::from(out.trim())); + if let Some(p) = configured.filter(|p| p.is_file()) { + return Some((p, "raea.blender in git config")); + } + if let Some(p) = own_binary().ok().filter(|p| p.is_file()) { + return Some((p, "raea's download")); + } + let mut apps = vec![PathBuf::from("/Applications/Blender.app/Contents/MacOS/Blender")]; + if let Ok(h) = crate::agent_mcp::user_home() { + apps.push(h.join("Applications/Blender.app/Contents/MacOS/Blender")); + } + if let Some(p) = apps.into_iter().find(|p| cfg!(target_os = "macos") && p.is_file()) { + return Some((p, "Applications")); + } + on_path(if cfg!(windows) { "blender.exe" } else { "blender" }).map(|p| (p, "PATH")) +} + +/// `blender --version`'s first line ("Blender 5.2.1 LTS"). +fn version(bin: &Path) -> R { + let o = Command::new(bin).arg("--version").output().map_err(|e| format!("{}: {e}", bin.display()))?; + String::from_utf8_lossy(&o.stdout).lines().find(|l| l.starts_with("Blender ")).map(str::to_string).ok_or_else(|| format!("{} --version printed no version", bin.display())) +} + +fn run(cmd: &mut Command, what: &str) -> R { + let o = cmd.output().map_err(|e| format!("{what}: {e}"))?; + if !o.status.success() { + return Err(format!("{what} failed: {}{}", String::from_utf8_lossy(&o.stderr).trim(), String::from_utf8_lossy(&o.stdout).trim())); + } + Ok(String::from_utf8_lossy(&o.stdout).into_owned()) +} + +/// This platform's file name in a release folder, for a version. +fn asset(v: &str) -> R { + match (std::env::consts::OS, std::env::consts::ARCH) { + ("macos", "aarch64") => Ok(format!("blender-{v}-macos-arm64.dmg")), + ("macos", _) => Ok(format!("blender-{v}-macos-x64.dmg")), + ("linux", "x86_64") => Ok(format!("blender-{v}-linux-x64.tar.xz")), + ("windows", "aarch64") => Ok(format!("blender-{v}-windows-arm64.zip")), + ("windows", _) => Ok(format!("blender-{v}-windows-x64.zip")), + (os, arch) => Err(format!("blender.org has no build for {os} {arch}: install Blender yourself and `git config --global raea.blender PATH`")), + } +} + +/// The newest patch of the LTS series in a release folder's listing. +fn newest(listing: &str) -> Option { + let pre = format!("blender-{LTS}."); + let mut best: Option<(u32, String)> = None; + for part in listing.split(&pre).skip(1) { + let digits: String = part.chars().take_while(char::is_ascii_digit).collect(); + if let Ok(n) = digits.parse::() { + if part[digits.len()..].starts_with('-') && best.as_ref().map_or(true, |(b, _)| n > *b) { + best = Some((n, format!("{LTS}.{n}"))); + } + } + } + best.map(|(_, v)| v) +} + +fn sha256(file: &Path) -> R { + let out = if cfg!(windows) { + run(Command::new("certutil").arg("-hashfile").arg(file).arg("SHA256"), "certutil")?.lines().nth(1).unwrap_or_default().replace(' ', "") + } else { + run(Command::new("shasum").args(["-a", "256"]).arg(file), "shasum")?.split_whitespace().next().unwrap_or_default().to_string() + }; + Ok(out.to_lowercase()) +} + +/// Downloads the LTS into ~/.raea/tools/blender, checked against blender.org's sha256 list, and returns its binary. +fn download() -> R<(PathBuf, String)> { + let base = format!("https://download.blender.org/release/Blender{LTS}/"); + let listing = run(Command::new("curl").args(["-fsSL", &base]), "curl")?; + let v = newest(&listing).ok_or_else(|| format!("no Blender {LTS} release listed at {base}"))?; + let name = asset(&v)?; + let dir = own_dir()?; + let tmp = dir.with_file_name("blender.download"); + let _ = std::fs::remove_dir_all(&tmp); + std::fs::create_dir_all(&tmp).map_err(|e| format!("{}: {e}", tmp.display()))?; + let file = tmp.join(&name); + run(Command::new("curl").args(["-fL", "--retry", "3", "-o"]).arg(&file).arg(format!("{base}{name}")), "downloading Blender")?; + let sums = run(Command::new("curl").args(["-fsSL", &format!("{base}blender-{v}.sha256")]), "curl")?; + let want = sums.lines().find(|l| l.ends_with(&name)).and_then(|l| l.split_whitespace().next()).ok_or_else(|| format!("blender-{v}.sha256 doesn't list {name}"))?.to_lowercase(); + if sha256(&file)? != want { + return Err(format!("{name} doesn't match blender.org's sha256; nothing installed (it's in {})", tmp.display())); + } + let unpacked = tmp.join("unpacked"); + std::fs::create_dir_all(&unpacked).map_err(|e| e.to_string())?; + if name.ends_with(".dmg") { + let mnt = tmp.join("mnt"); + run(Command::new("hdiutil").args(["attach", "-nobrowse", "-readonly", "-mountpoint"]).arg(&mnt).arg(&file), "hdiutil attach")?; + let copied = run(Command::new("ditto").arg(mnt.join("Blender.app")).arg(unpacked.join("Blender.app")), "copying Blender.app"); + let _ = Command::new("hdiutil").args(["detach", "-quiet"]).arg(&mnt).status(); + copied?; + } else { + // tar unpacks .tar.xz on Linux and .zip on Windows 10 and 11; both hold one top folder + run(Command::new("tar").arg("-xf").arg(&file).arg("-C").arg(&unpacked).args(if cfg!(windows) { vec![] } else { vec!["--strip-components=1"] }), "unpacking Blender")?; + if cfg!(windows) { + let top = std::fs::read_dir(&unpacked).map_err(|e| e.to_string())?.flatten().find(|e| e.path().is_dir()).ok_or("the zip held no folder")?.path(); + let flat = tmp.join("flat"); + std::fs::rename(&top, &flat).map_err(|e| e.to_string())?; + std::fs::remove_dir_all(&unpacked).map_err(|e| e.to_string())?; + std::fs::rename(&flat, &unpacked).map_err(|e| e.to_string())?; + } + } + let _ = std::fs::remove_dir_all(&dir); + std::fs::rename(&unpacked, &dir).map_err(|e| format!("{}: {e}", dir.display()))?; + let _ = std::fs::remove_dir_all(&tmp); + Ok((own_binary()?, format!("downloaded Blender {v} LTS from blender.org"))) +} + +/// Python run inside Blender (background): prints the user add-ons folder, or whether the add-on is enabled. +const ADDONS_DIR: &str = "import bpy; print('RAEA_ADDONS=' + bpy.utils.user_resource('SCRIPTS', path='addons', create=True))"; +const ENABLE: &str = "import addon_utils, bpy; addon_utils.enable('blender_mcp', default_set=True, persistent=True); bpy.ops.wm.save_userpref(); print('RAEA_ENABLED=' + str(addon_utils.check('blender_mcp')[1]))"; +const CHECK: &str = "import addon_utils; print('RAEA_ENABLED=' + str(addon_utils.check('blender_mcp')[1]))"; + +fn py(bin: &Path, code: &str, key: &str) -> R { + let out = run(Command::new(bin).args(["--background", "--factory-startup", "--python-expr", code]), "blender")?; + out.lines().find_map(|l| l.strip_prefix(key)).map(str::to_string).ok_or_else(|| format!("blender printed no {key}")) +} + +/// The add-on: uvx mcp-for-blender's own installer writes it into this Blender's add-ons folder, then Blender enables it. +fn addon(bin: &Path, check: bool) -> R { + // --factory-startup skips the person's add-ons for speed, so the check reads the saved preferences instead + let state = |b: &Path| run(Command::new(b).args(["--background", "--python-expr", CHECK]), "blender").map(|o| o.contains("RAEA_ENABLED=True")); + if state(bin)? { + return Ok("MCP add-on enabled".into()); + } + if check { + return Ok("MCP add-on not installed: raea setup blender installs it".into()); + } + let uvx = on_path(if cfg!(windows) { "uvx.exe" } else { "uvx" }).ok_or("the MCP add-on comes from uv's uvx: install uv (https://docs.astral.sh/uv/getting-started/installation/), then run raea setup blender again")?; + let dir = py(bin, ADDONS_DIR, "RAEA_ADDONS=")?; + run(Command::new(&uvx).args(["mcp-for-blender", "install-addon", "--addons-dir", &dir]), "uvx mcp-for-blender install-addon")?; + let on = run(Command::new(bin).args(["--background", "--python-expr", ENABLE]), "blender")?; + if !on.contains("RAEA_ENABLED=True") { + return Err(format!("the add-on is in {dir} but Blender didn't enable it: enable \"MCP for Blender\" in Preferences > Add-ons")); + } + Ok(format!("MCP add-on installed now ({dir})")) +} + +/// `raea setup blender [--check] [--download]`. +pub fn setup(args: &[String]) -> R { + let check = args.iter().any(|a| a == "--check"); + let fresh = args.iter().any(|a| a == "--download"); + let (bin, from) = match find().filter(|_| !fresh) { + Some((b, f)) => (b, f.to_string()), + None if check => return Ok(format!("CHECKED no Blender found (raea.blender, {}, PATH): raea setup blender downloads Blender {LTS} LTS", own_dir()?.display())), + None => { + let (b, f) = download()?; + run(Command::new("git").args(["config", "--global", "raea.blender"]).arg(&b), "git config")?; + (b, f) + } + }; + let v = version(&bin)?; + let add = addon(&bin, check)?; + let head = if check { "CHECKED " } else { "APPLIED " }; + Ok(format!("{head} {v} ({from})\n {}\n {add}\n headless: raea blender run SCRIPT.py; live: start Blender and the agent's `blender` MCP server connects (raea skills install adds it)", bin.display())) +} + +/// `raea blender run SCRIPT.py [ARGS...]`: the script in a windowless Blender, its args after `--` (sys.argv), its +/// output passed through. Exits as Blender's Python did: --python-exit-code makes an uncaught error fail the run. +pub fn blender(args: &[String]) -> R { + if args.get(1).map(String::as_str) != Some("run") { + return Err(format!("usage: {USAGE}")); + } + let script = args.get(2).ok_or_else(|| format!("which script: {USAGE}"))?; + if !Path::new(script).is_file() { + return Err(format!("no script {script}")); + } + let (bin, _) = find().ok_or("no Blender: raea setup blender finds or downloads one")?; + let st = Command::new(&bin).args(["--background", "--factory-startup", "--python-exit-code", "1", "--python", script, "--"]).args(&args[3..]).status().map_err(|e| format!("{}: {e}", bin.display()))?; + if !st.success() { + return Err(format!("{script} failed in Blender ({st})")); + } + Ok(String::new()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn newest_takes_the_highest_patch_of_the_lts() { + let listing = format!(" blender-{LTS}.9.sha256 blender-{LTS}.99beta"); + assert_eq!(newest(&listing), Some(format!("{LTS}.12"))); + assert_eq!(newest("nothing here"), None); + } + + #[test] + fn every_supported_platform_names_one_file() { + assert!(asset("5.2.1").unwrap().starts_with("blender-5.2.1-")); + } +} diff --git a/apps/tools/src/generate.rs b/apps/tools/src/generate.rs new file mode 100644 index 00000000..d932f642 --- /dev/null +++ b/apps/tools/src/generate.rs @@ -0,0 +1,53 @@ +//! `raea gen …` (raea-io-gen's verbs), with raea's own local models as the flow's `local:` backend: sao for sound +//! effects, made through the edit's asset store as a render would. + +use std::path::{Path, PathBuf}; + +use raea_io_gen::flow::Step; +use serde_json::json; + +struct Local; + +impl raea_io_gen::run::Local for Local { + fn names(&self) -> Vec { + vec!["sao".to_string()] + } + + fn make(&self, name: &str, step: &Step, dir: &Path, key: &str) -> Result { + let text = |k: &str| step.inputs.get(k).and_then(|v| v.as_str()).unwrap_or("").to_string(); + let (prompt, params) = match name { + "sao" => (text("prompt"), json!({"seconds": step.inputs.get("seconds").and_then(|v| v.as_f64()).unwrap_or(2.0)})), + _ => return Err(format!("no local model `{name}` (this host runs sao)")), + }; + let store = raea_io_assets::Store { dir: dir.join("assets") }; + let seed = step.inputs.get("seed").and_then(|v| v.as_u64()).unwrap_or(1); + let a = store.make(name, &prompt, seed, ¶ms)?; + let out = dir.join(format!("{key}.{}", a.ext)); + std::fs::copy(store.path(&a), &out).map_err(|e| format!("{}: {e}", out.display()))?; + Ok(out) + } +} + +pub fn generate(args: &[String]) -> Result { + raea_io_gen::cli::command(&args[1..], Some(&Local)) +} + +#[cfg(test)] +mod tests { + // GN14: a flow's sfx step on this Mac's sao, through `raea gen run` as the CLI calls it. It runs the model (about 2 + // GB, installed on first use), so it's ignored by default: cargo test -p raea-app-tools generate -- --ignored + #[test] + #[ignore] + fn sfx_step_runs_on_sao() { + let dir = std::env::temp_dir().join(format!("raea-gen-sao-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let flow = dir.join("flow.json"); + std::fs::write(&flow, r#"{"flow":1,"steps":{"knock":{"op":"audio.sfx","in":{"prompt":"three firm knocks on a wooden door, close, dry room","seconds":2}}},"out":["knock"]}"#).unwrap(); + // as engine/cli hands it over: the verb first + let args: Vec = ["gen", "run", flow.to_str().unwrap(), "-o", dir.to_str().unwrap()].iter().map(|s| s.to_string()).collect(); + let out = super::generate(&args).unwrap(); + assert!(out.contains("local:sao"), "{out}"); + let wav = dir.join("knock.wav"); + assert!(std::fs::metadata(&wav).unwrap().len() > 10_000, "{}", wav.display()); + } +} diff --git a/apps/tools/src/lib.rs b/apps/tools/src/lib.rs index 35f18311..f6341669 100644 --- a/apps/tools/src/lib.rs +++ b/apps/tools/src/lib.rs @@ -1,7 +1,14 @@ //! The verbs that run raea's local tools: sound (`raea sao`, `tokensynth`, `setup-audio`, `sounds`: foley and an //! instrument's notes made by local models, and the open sample libraries), `raea splat` (footage trained into a -//! Gaussian splat) and `raea song` (a song's energy map, apps/tools/src/song.rs). +//! Gaussian splat), `raea song` (a song's energy map, apps/tools/src/song.rs) and `raea gen` (generation flows on +//! made.app, fal, Replicate, OpenRouter, Modal and ComfyUI, with sao as the local model: apps/tools/src/generate.rs). +pub mod generate; pub mod song; pub mod sound; pub mod splat; + +/// the MCP servers `raea skills install` offers an agent (blender, for a running Blender) +pub mod agent_mcp; +/// `raea setup blender` and `raea blender run` +pub mod blender; diff --git a/apps/tools/src/sound/library.rs b/apps/tools/src/sound/library.rs index 2d700be6..cac20db5 100644 --- a/apps/tools/src/sound/library.rs +++ b/apps/tools/src/sound/library.rs @@ -86,6 +86,7 @@ pub(crate) fn fetch(url: &str, cached: &Path) -> R<()> { if cached.exists() { return Ok(()); } + raea_io_home::offline(&format!("the sample library file {url}"))?; std::fs::create_dir_all(cached.parent().unwrap()).map_err(|e| e.to_string())?; let part = cached.with_extension("part"); let o = std::process::Command::new("curl").args(["-fsSL", "--retry", "2", "-o"]).arg(&part).arg(url).output().map_err(|e| format!("curl: {e}"))?; diff --git a/apps/workspace/Cargo.toml b/apps/workspace/Cargo.toml new file mode 100644 index 00000000..fe1799cf --- /dev/null +++ b/apps/workspace/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "raea-app-workspace" +version = "0.1.0" +edition = "2024" +license = "FSL-1.1-ALv2" +publish = false +description = "`raea workspace`, `raea project` and `raea controller`: a workspace's folders, projects and controllers, each change a commit" + +[dependencies] +# the controller schema (core/brief controller.rs): a controller file is checked and normalized against it +raea-core-brief = { path = "../../core/brief" } +serde_json = "1" diff --git a/apps/workspace/src/controllers.rs b/apps/workspace/src/controllers.rs new file mode 100644 index 00000000..c2e0fb1f --- /dev/null +++ b/apps/workspace/src/controllers.rs @@ -0,0 +1,209 @@ +//! A workspace's controllers on disk (docs/projects.feature PJ2): controllers/.ts, each `export default +//! controller({...})` from "raea/brief", checked by core/brief's normalize. A project overrides a field's value in its +//! .raea/project (`[controller "delivery.format"] aspect-ratio = 16:9`), so the project's value wins, as git config's +//! own scopes do. Every change is a commit by who made it ("you", or the agent's name with --by). +use super::*; +use raea_core_brief::controller::{self as ctl, Controller, Field, Kind}; + +use std::process::Command; + +const USAGE: &str = "usage: raea controller ls [--json] | get PATH [--json] | set PATH VALUE [--project] [--by NAME] | write FILE.ts [--by NAME] | rm ID [--by NAME]\n (PATH is controller.group.field; a VALUE is JSON for numbers, toggles and lists, else text)"; + +fn workspace_dir() -> R { + let here = std::env::current_dir().map_err(|e| e.to_string())?; + workspace::up(&here, ".raea/workspace").ok_or_else(|| "not in a workspace: raea workspace init NAME makes one".to_string()) +} + +/// Every controller in the workspace, checked, in file order. +pub fn load(ws: &Path, eval: Eval) -> R> { + let mut files: Vec = std::fs::read_dir(ws.join("controllers")).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "ts")).collect(); + files.sort(); + files.into_iter().map(|f| read(&f, eval).map(|c| (f, c))).collect() +} + +fn read(f: &Path, eval: Eval) -> R { + let raw: serde_json::Value = serde_json::from_str(&eval(f)?).map_err(|e| format!("{}: {e}", f.display()))?; + ctl::normalize(&raw).map_err(|e| format!("{}: {e}", f.display())) +} + +/// The module a controller is kept as. +pub fn module(c: &Controller) -> String { + format!("import {{ controller }} from \"raea/brief\";\n\nexport default controller({});\n", ts_literal(&serde_json::to_value(c).unwrap_or_default(), 0)) +} + +/// A field's value as JSON (its kind's `value`). +fn value_of(f: &Field) -> serde_json::Value { + serde_json::to_value(&f.kind).ok().and_then(|v| v.get("value").cloned()).unwrap_or_default() +} + +/// The git-config key for a field's override: `controller...`, which git reads as section +/// controller, subsection ".", key . +fn key(path: &str) -> String { + format!("controller.{path}") +} + +/// A value as typed on the command line or kept in git config: JSON when it parses as JSON of the field's kind, else +/// the text itself (a choice, a text field). +fn parse(f: &Field, s: &str) -> R { + let v = match (&f.kind, serde_json::from_str::(s)) { + (Kind::Text { .. } | Kind::Choice { .. }, Ok(serde_json::Value::String(t))) => serde_json::Value::String(t), + (Kind::Text { .. } | Kind::Choice { .. }, _) => serde_json::Value::String(s.to_string()), + (_, Ok(v)) => v, + (_, Err(_)) => serde_json::Value::String(s.to_string()), + }; + ctl::check_value(f, &v) +} + +/// The overrides of the project `from` is in, by path. +fn overrides(from: &Path) -> Vec<(String, String)> { + let Some(p) = workspace::up(from, ".raea/project") else { return vec![] }; + let text = workspace::config(Some(&p.join(".raea/project")), &["--get-regexp", "^controller\\."]).unwrap_or_default(); + text.lines().filter_map(|l| l.split_once(' ')).map(|(k, v)| (k.trim_start_matches("controller.").to_string(), v.to_string())).collect() +} + +fn commit(ws: &Path, paths: &[&Path], what: &str, by: &str) -> R<()> { + let mut add = Command::new("git"); + add.arg("-C").arg(ws).args(["add", "-A", "--"]).args(paths); + add.status().map_err(|e| format!("git: {e}"))?; + let ok = Command::new("git").arg("-C").arg(ws).args(["-c", &format!("user.name={by}"), "commit", "-q", "-m", &format!("{by}: {what}"), "--"]).args(paths).status().map_err(|e| format!("git: {e}"))?; + if ok.success() { Ok(()) } else { Err(format!("couldn't commit {what}")) } +} + +/// `raea controller …`, its specs evaluated by `eval` +pub fn controller(args: &[String], eval: Eval) -> R { + let json_out = args.iter().any(|a| a == "--json"); + let by = workspace::flag(args, "--by").unwrap_or("you").trim_start_matches('@').to_string(); + let w: Vec<&str> = args.iter().enumerate().filter(|(i, a)| !a.starts_with("--") && !(*i > 0 && args[i - 1] == "--by")).map(|(_, a)| a.as_str()).collect(); + let ws = workspace_dir()?; + match w.as_slice() { + ["ls"] | [] => ls(&ws, json_out, eval), + ["get", path] => get(&ws, path, json_out, eval), + ["set", path, value] => set(&ws, path, value, args.iter().any(|a| a == "--project"), &by, eval), + ["write", file] => write(&ws, Path::new(file), &by, eval), + ["rm", id] => rm(&ws, id, &by), + _ => Err(USAGE.into()), + } +} + +/// The controllers as `raea controller ls` prints them, with the overrides of the project `from` is in: what `raea +/// context` shows an agent. None outside a workspace or when it has no controllers. +pub fn summary(from: &Path, eval: Eval) -> Option { + let ws = workspace::up(from, ".raea/workspace")?; + load(&ws, eval).ok().filter(|cs| !cs.is_empty())?; + ls_from(&ws, from, false, eval).ok() +} + +fn ls(ws: &Path, json_out: bool, eval: Eval) -> R { + ls_from(ws, &std::env::current_dir().map_err(|e| e.to_string())?, json_out, eval) +} + +fn ls_from(ws: &Path, from: &Path, json_out: bool, eval: Eval) -> R { + let cs = load(ws, eval)?; + let over = overrides(from); + let mut rows = vec![]; + for (_, c) in &cs { + for g in &c.groups { + for f in &g.fields { + let path = format!("{}.{}.{}", c.id, g.id, f.id); + let mine = over.iter().find(|(k, _)| *k == path).and_then(|(_, v)| parse(f, v).ok()); + rows.push((path, f, mine.clone().unwrap_or_else(|| value_of(f)), mine.is_some())); + } + } + } + if json_out { + let fields: Vec<_> = rows.iter().map(|(p, f, v, o)| json!({"path": p, "label": f.label, "type": serde_json::to_value(&f.kind).ok().and_then(|k| k.get("type").cloned()), "value": v, "project": o})).collect(); + let list: Vec<_> = cs.iter().map(|(_, c)| serde_json::to_value(c).map(|v| tidy_deep(&v)).unwrap_or_default()).collect(); + return Ok(json!({"controllers": list, "fields": fields}).to_string()); + } + if cs.is_empty() { + return Ok("no controllers yet: raea controller write FILE.ts adds one (`export default controller({ title, groups })` from \"raea/brief\")".into()); + } + let mut out = String::new(); + for (_, c) in &cs { + out.push_str(&format!("{} ({})\n", c.title, c.id)); + for (p, f, v, o) in rows.iter().filter(|r| r.0.starts_with(&format!("{}.", c.id))) { + out.push_str(&format!(" {p} {}: {}{}\n", f.label, tidy(v), if *o { " (this project)" } else { "" })); + } + } + Ok(out.trim_end().to_string()) +} + +/// Where a path's field is: its controller, group and field, by index. +fn locate(cs: &[(PathBuf, Controller)], path: &str) -> R<(usize, usize, usize)> { + let mut p = path.splitn(3, '.'); + let (c, g, f) = (p.next().unwrap_or(""), p.next().unwrap_or(""), p.next().unwrap_or("")); + let ci = cs.iter().position(|x| x.1.id == c); + let gi = ci.and_then(|ci| cs[ci].1.groups.iter().position(|y| y.id == g)); + let fi = ci.zip(gi).and_then(|(ci, gi)| cs[ci].1.groups[gi].fields.iter().position(|z| z.id == f)); + match (ci, gi, fi) { + (Some(c), Some(g), Some(f)) => Ok((c, g, f)), + _ => Err(format!("no field at {path}: raea controller ls lists the paths (controller.group.field)")), + } +} + +fn find<'a>(cs: &'a [(PathBuf, Controller)], path: &str) -> R<&'a Field> { + let (c, g, f) = locate(cs, path)?; + Ok(&cs[c].1.groups[g].fields[f]) +} + +fn get(ws: &Path, path: &str, json_out: bool, eval: Eval) -> R { + let cs = load(ws, eval)?; + let f = find(&cs, path)?; + let here = std::env::current_dir().map_err(|e| e.to_string())?; + let mine = overrides(&here).into_iter().find(|(k, _)| k == path).map(|(_, v)| parse(f, &v)).transpose()?; + let v = mine.clone().unwrap_or_else(|| value_of(f)); + let v = tidy(&v); + Ok(if json_out { json!({"path": path, "value": v, "project": mine.is_some()}).to_string() } else { v.to_string() }) +} + +fn set(ws: &Path, path: &str, value: &str, project: bool, by: &str, eval: Eval) -> R { + let mut cs = load(ws, eval)?; + let v = parse(find(&cs, path)?, value)?; + if project { + let here = std::env::current_dir().map_err(|e| e.to_string())?; + let p = workspace::up(&here, ".raea/project").ok_or("--project: not in a project")?; + let text = match &v { + serde_json::Value::String(s) => s.clone(), + v => v.to_string(), + }; + let file = p.join(".raea/project"); + workspace::set(&file, &key(path), &text)?; + // a submodule project is its own repo; an inline one commits in the workspace + let repo = if p.join(".git").exists() { p.clone() } else { ws.to_path_buf() }; + commit(&repo, &[&file], &format!("{path} = {text} for this project"), by)?; + return Ok(format!("{path} = {text} (this project)")); + } + let (c, g, f) = locate(&cs, path)?; + let (file, ctrl) = &mut cs[c]; + let field = &mut ctrl.groups[g].fields[f]; + let mut kind = serde_json::to_value(&field.kind).map_err(|e| e.to_string())?; + kind["value"] = v.clone(); + field.kind = serde_json::from_value(kind).map_err(|e| e.to_string())?; + std::fs::write(&*file, module(ctrl)).map_err(|e| format!("{}: {e}", file.display()))?; + let file = file.clone(); + let v = tidy(&v); + let said = v.as_str().map(String::from).unwrap_or_else(|| v.to_string()); + commit(ws, &[&file], &format!("{path} = {said}"), by)?; + Ok(format!("{path} = {v}")) +} + +fn write(ws: &Path, file: &Path, by: &str, eval: Eval) -> R { + let c = read(file, eval)?; + let to = ws.join("controllers").join(format!("{}.ts", c.id)); + let new = !to.exists(); + std::fs::create_dir_all(ws.join("controllers")).map_err(|e| e.to_string())?; + std::fs::write(&to, module(&c)).map_err(|e| format!("{}: {e}", to.display()))?; + commit(ws, &[&to], &format!("{} controller {}", if new { "add" } else { "rewrite" }, c.id), by)?; + let n = |k: usize, what: &str| format!("{k} {what}{}", if k == 1 { "" } else { "s" }); + Ok(format!("{}: {} ({}, {})", to.display(), c.title, n(c.groups.len(), "group"), n(c.groups.iter().map(|g| g.fields.len()).sum(), "field"))) +} + +fn rm(ws: &Path, id: &str, by: &str) -> R { + let file = ws.join("controllers").join(format!("{id}.ts")); + if !file.is_file() { + return Err(format!("no controller {id}: raea controller ls lists them")); + } + std::fs::remove_file(&file).map_err(|e| format!("{}: {e}", file.display()))?; + commit(ws, &[&file], &format!("remove controller {id}"), by)?; + Ok(format!("removed {id} (git revert brings it back)")) +} diff --git a/apps/workspace/src/doctor.rs b/apps/workspace/src/doctor.rs new file mode 100644 index 00000000..a2e14113 --- /dev/null +++ b/apps/workspace/src/doctor.rs @@ -0,0 +1,138 @@ +//! `raea doctor [--fix]` (docs/skills.feature SK10): drift between a project's files and what this raea reads. Old brief +//! files raea no longer reads, a workspace or project file missing what this version writes (or not included from the +//! repo's git config), and an agent's copy of the raea skill from another version. `raea context` runs the same checks +//! and prints CONTEXT_STALE when any finds something, so they stay cheap: file reads and git config, no engine. +use super::*; +use crate::workspace::{get, git, include, new_id, set}; + +/// One thing doctor found, and whether `--fix` can fix it. +pub struct Finding { + pub says: String, + fix: Fix, +} + +enum Fix { + No, + /// a key missing from a git-config file: (file, key, value) + Set(PathBuf, String, String), + /// the include in a repo's config that makes `git config` read its committed file: (repo, file) + Include(PathBuf, PathBuf), + /// an agent's skills reinstalled from this raea + Skills(String), +} + +impl Finding { + pub fn fixable(&self) -> bool { + !matches!(self.fix, Fix::No) + } +} + +/// Old brief files under a folder (raea reads only brief.ts, script.ts and taste.ts since 11-05), a few levels down. +fn old_briefs(dir: &Path, depth: usize, out: &mut Vec) { + let Ok(rd) = std::fs::read_dir(dir) else { return }; + for e in rd.flatten() { + let p = e.path(); + let name = e.file_name().to_string_lossy().into_owned(); + if p.is_dir() { + if depth > 0 && !name.starts_with('.') && name != "node_modules" && name != "media" && name != "out" { + old_briefs(&p, depth - 1, out); + } + } else if [".brief", ".board"].iter().any(|x| name.ends_with(x)) { + out.push(Finding { says: format!("{}: an old brief file, which raea no longer reads; rewrite it as brief.ts (export default brief({{...}}) from \"raea/brief\") and delete it", p.display()), fix: Fix::No }); + } + } +} + +/// A committed git-config file's keys this version writes, and its include from the repo's config. +fn format(repo: &Path, file: &Path, keys: &[(&str, String)], out: &mut Vec) { + for (k, v) in keys { + if get(file, k).is_none() { + out.push(Finding { says: format!("{}: no {k} (an older format); --fix sets it to {v}", file.display()), fix: Fix::Set(file.to_path_buf(), k.to_string(), v.clone()) }); + } + } + // only a folder that is its own repo includes its file (a workspace, a split project); an inline project shares + // the workspace's repo, whose config must not take one project's keys + let own = git(repo, &["rev-parse", "--show-toplevel"]).ok().and_then(|t| Path::new(&t).canonicalize().ok()) == repo.canonicalize().ok(); + let first = keys.first().map(|(k, _)| *k).unwrap_or_default(); + let read = git(repo, &["config", first]).ok().filter(|v| !v.is_empty()); + if own && read.is_none() && get(file, first).is_some() { + out.push(Finding { says: format!("{}: git config doesn't read it (no include in the repo's config); --fix adds it", file.display()), fix: Fix::Include(repo.to_path_buf(), file.to_path_buf()) }); + } +} + +/// The `version:` in a SKILL.md's front matter. +fn skill_version(md: &Path) -> Option { + let text = std::fs::read_to_string(md).ok()?; + let front = text.strip_prefix("---\n")?.split("\n---\n").next()?; + front.lines().find_map(|l| l.strip_prefix("version:")).map(|v| v.trim().to_string()) +} + +/// What doctor finds from a folder: `skills` are (agent, its skills folder), `version` this raea's. +pub fn findings(from: &Path, skills: &[(&str, PathBuf)], version: &str) -> Vec { + let mut out = Vec::new(); + let ws = up(from, ".raea/workspace"); + let project = up(from, ".raea/project"); + let base = project.clone().or_else(|| ws.clone()).unwrap_or_else(|| from.to_path_buf()); + old_briefs(&base, if project.is_some() { 2 } else { 1 }, &mut out); + if let Some(ws) = &ws { + let name = ws.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + let keys = [("workspace.id", new_id("ws")), ("workspace.name", name), ("workspace.layout", "monorepo".to_string())]; + format(ws, &ws.join(".raea/workspace"), &keys, &mut out); + } + if let Some(p) = &project { + let name = p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + let keys = [("project.id", new_id("pj")), ("project.name", name)]; + format(p, &p.join(".raea/project"), &keys, &mut out); + } + for (agent, dir) in skills { + let md = dir.join("raea/SKILL.md"); + if !md.is_file() { + continue; + } + let have = skill_version(&md).unwrap_or_else(|| "unversioned".into()); + if have != version { + out.push(Finding { says: format!("{}: the raea skill {agent} reads is {have}, this raea is {version}; --fix reinstalls it", md.display()), fix: Fix::Skills(agent.to_string()) }); + } + } + out +} + +/// `raea doctor [--fix] [DIR]`: what it found and, with --fix, what it fixed. `reinstall` puts an agent's skills back +/// (the raea CLI's `skills install`). +pub fn doctor(args: &[String], skills: &[(&str, PathBuf)], version: &str, reinstall: &dyn Fn(&str) -> R) -> R { + let fix = args.iter().any(|a| a == "--fix"); + let from = PathBuf::from(args.iter().find(|a| !a.starts_with("--")).map(String::as_str).unwrap_or(".")); + let found = findings(&from, skills, version); + if found.is_empty() { + return Ok("CHECKED nothing to fix: this folder's files and the agents' raea skill match this raea".into()); + } + let mut lines = Vec::new(); + let mut fixed = 0; + for f in &found { + let done = match (&f.fix, fix) { + (Fix::Set(file, k, v), true) => set(file, k, v).map(|_| true), + (Fix::Include(repo, file), true) => include(repo, file).map(|_| true), + (Fix::Skills(agent), true) => reinstall(agent).map(|_| true), + _ => Ok(false), + }; + match done { + Ok(true) => { + fixed += 1; + lines.push(format!(" fixed {}", f.says)); + } + Ok(false) => lines.push(format!(" {} {}", if f.fixable() { "fix " } else { "by hand" }, f.says)), + Err(e) => lines.push(format!(" failed {}: {e}", f.says)), + } + } + // a workspace's own files changed: commit them, as every change raea makes there is + if fix && fixed > 0 { + for marker in [".raea/workspace", ".raea/project"] { + if let Some(repo) = up(&from, marker) { + let _ = crate::workspace::commit(&repo, &[marker], "doctor --fix"); + } + } + } + let can = found.iter().filter(|f| f.fixable()).count(); + let head = if fix { format!("APPLIED {fixed} of {} fixed", found.len()) } else { format!("CHECKED {} to fix ({can} by raea doctor --fix)", found.len()) }; + Ok(format!("{head}\n{}", lines.join("\n"))) +} diff --git a/apps/workspace/src/lib.rs b/apps/workspace/src/lib.rs new file mode 100644 index 00000000..b42a1f21 --- /dev/null +++ b/apps/workspace/src/lib.rs @@ -0,0 +1,25 @@ +//! A workspace's folders and files (docs/projects.feature PJ1-PJ4): `raea workspace`, `raea project` (with split and +//! join) and `raea controller`. A workspace is a git repo raea changes by commits; its controllers are spec modules, +//! which the raea CLI evaluates on the engine and hands in as an `Eval`, so this crate needs no engine of its own. +use std::path::{Path, PathBuf}; + +use serde_json::json; + +mod controllers; +pub mod doctor; +mod literal; +pub mod next; +mod storage; +mod workspace; + +pub use controllers::{controller, module, summary}; +pub use literal::{tidy, tidy_deep, ts_literal}; +pub use workspace::{project, projects, root, slug, up, workspace}; + +pub type R = Result; + +/// A spec module's default export as JSON: the raea CLI's spec_json, which runs it on the engine. +pub type Eval = fn(&Path) -> R; + +#[cfg(test)] +mod tests; diff --git a/apps/workspace/src/literal.rs b/apps/workspace/src/literal.rs new file mode 100644 index 00000000..ee908400 --- /dev/null +++ b/apps/workspace/src/literal.rs @@ -0,0 +1,37 @@ +//! Spec modules as raea writes them: a value as a TypeScript literal, and whole numbers kept whole. +/// A value as a TypeScript literal for a spec module: unquoted keys where they can be, nulls and empty lists left out. +pub fn ts_literal(v: &serde_json::Value, indent: usize) -> String { + use serde_json::Value; + let (pad, end) = (" ".repeat(indent + 1), " ".repeat(indent)); + match v { + Value::Array(a) if a.iter().all(Value::is_string) && v.to_string().len() < 70 => format!("[{}]", a.iter().map(Value::to_string).collect::>().join(", ")), + Value::Array(a) => format!("[\n{}{end}]", a.iter().map(|x| format!("{pad}{},\n", ts_literal(x, indent + 1))).collect::()), + Value::Object(o) => { + let ident = |k: &str| k.chars().next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_') && k.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'); + let kept = o.iter().filter(|(_, x)| !x.is_null() && !x.as_array().is_some_and(Vec::is_empty)); + let body: String = kept.map(|(k, x)| format!("{pad}{}: {},\n", if ident(k) { k.clone() } else { Value::String(k.clone()).to_string() }, ts_literal(x, indent + 1))).collect(); + format!("{{\n{body}{end}}}") + } + v => tidy(v).to_string(), + } +} + +/// A number that's whole (as f64 values from Rust are, 45.0) written as an integer. +pub fn tidy(v: &serde_json::Value) -> serde_json::Value { + match v.as_f64() { + Some(n) if v.is_f64() && n.fract() == 0.0 && n.abs() < 1e15 => serde_json::Value::from(n as i64), + _ => match v { + serde_json::Value::Array(a) => serde_json::Value::Array(a.iter().map(tidy).collect()), + v => v.clone(), + }, + } +} + +/// `tidy` through a whole value: objects and arrays too. +pub fn tidy_deep(v: &serde_json::Value) -> serde_json::Value { + match v { + serde_json::Value::Object(o) => serde_json::Value::Object(o.iter().filter(|(_, x)| !x.is_null()).map(|(k, x)| (k.clone(), tidy_deep(x))).collect()), + serde_json::Value::Array(a) => serde_json::Value::Array(a.iter().map(tidy_deep).collect()), + v => tidy(v), + } +} diff --git a/apps/workspace/src/next.rs b/apps/workspace/src/next.rs new file mode 100644 index 00000000..88edd868 --- /dev/null +++ b/apps/workspace/src/next.rs @@ -0,0 +1,86 @@ +//! `raea next` (docs/skills.feature SK10): the two or three useful next steps for a project, read from its files: the +//! brief (what it still needs, from the raea CLI's brief doctor), the storyboard its modes want, its compositions, its +//! renders in out/ and their checks (`raea check ... -o out/NAME.check.json`). A menu for the agent or the person to +//! pick from; nothing runs. +use super::*; +use std::time::SystemTime; + +/// What the raea CLI read from the project's brief. +pub struct Brief { + /// what the brief still needs (empty when it's shaped) + pub needs: Vec, + pub modes: Vec, +} + +fn modified(p: &Path) -> SystemTime { + std::fs::metadata(p).and_then(|m| m.modified()).unwrap_or(SystemTime::UNIX_EPOCH) +} + +fn files(dir: &Path, ext: &str) -> Vec { + let mut v: Vec = std::fs::read_dir(dir).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| p.is_file() && p.to_string_lossy().ends_with(ext)).collect(); + v.sort_by_key(|p| std::cmp::Reverse(modified(p))); + v +} + +fn name(p: &Path) -> String { + let full = p.to_string_lossy(); + full.rsplit(['/', '\\']).next().unwrap_or_default().to_string() +} + +/// The P0 and P1 issues a check file holds, as its lines. +fn blocking(check: &Path) -> Vec { + let Ok(j) = std::fs::read_to_string(check).map_err(drop).and_then(|t| serde_json::from_str::(&t).map_err(drop)) else { return vec![] }; + let mut out = Vec::new(); + for i in j["issues"].as_array().into_iter().flatten() { + if let (Some(p @ ("P0" | "P1")), Some(says)) = (i["p"].as_str(), i["says"].as_str()) { + out.push(format!("{p} {says}")); + } + } + out +} + +/// The steps, most useful first, at most three. `stale` is what `raea doctor` found here. +pub fn steps(dir: &Path, brief: &Brief, stale: usize) -> Vec { + let mut out = Vec::new(); + if stale > 0 { + out.push(format!("raea doctor: {stale} thing(s) in this project's files or your raea skill don't match this raea (`raea doctor --fix`)")); + } + if let Some(first) = brief.needs.first() { + out.push(format!("shape the brief: {first} (ask the person, or write your best guess and add it to `assumed`)")); + } + let boarded = brief.modes.iter().any(|m| ["pitch", "explain", "story"].contains(&m.as_str())); + let scripts = files(dir, ".script.ts"); + if boarded && scripts.is_empty() { + out.push("plan it: write the storyboard as NAME.script.ts beside the brief (`raea spec NAME.script.ts` checks it) and wait for the person's approval".into()); + } + let comps: Vec = files(dir, ".tsx").into_iter().filter(|p| std::fs::read_to_string(p).map(|t| t.contains("registerRoot")).unwrap_or(false)).collect(); + let renders = files(&dir.join("out"), ".mp4"); + match (comps.first(), renders.first()) { + (None, _) => out.push("make the first item: one .tsx whose root registers a Composition (`raea guide craft` first)".into()), + (Some(c), None) => out.push(format!("render {}: stills to look at first (`raea render {} --at 0,45,89 -o frames/`), then the video into out/", name(c), name(c))), + (Some(c), Some(r)) if modified(c) > modified(r) => out.push(format!("render again: {} changed after {}", name(c), name(r))), + (_, Some(r)) => { + let check = r.with_extension("check.json"); + if !check.is_file() || modified(&check) < modified(r) { + out.push(format!("check {}: `raea check out/{} -o out/{}` (add --manifest when the render wrote one)", name(r), name(r), name(&check))); + } else { + match blocking(&check).first() { + Some(issue) => out.push(format!("polish {}: {issue} (`raea guide polish`)", name(r))), + None => out.push(format!("show {}: post it to the project's feed (feed_post), or give the person its path, and read their notes", name(r))), + } + } + } + } + out.truncate(3); + out +} + +/// `raea next`'s text. +pub fn text(dir: &Path, brief: &Brief, stale: usize) -> String { + let s = steps(dir, brief, stale); + let mut t = format!("raea next: {}\n", dir.display()); + for (i, line) in s.iter().enumerate() { + t.push_str(&format!("{}. {line}\n", i + 1)); + } + t.trim_end().to_string() +} diff --git a/apps/workspace/src/storage.rs b/apps/workspace/src/storage.rs new file mode 100644 index 00000000..4b9ac8c1 --- /dev/null +++ b/apps/workspace/src/storage.rs @@ -0,0 +1,95 @@ +//! A project changing storage with its history (docs/projects.feature PJ4): `raea project split NAME` makes an inline +//! project its own repo, a submodule, from `git subtree split` (its commits, rewritten to the folder); `raea project +//! join NAME` brings a submodule back in as a folder, its history merged under projects/NAME (`git subtree add`). +//! .raea/workspace and .gitmodules change in the same commit. +use super::*; +use workspace::{commit, get, git, include, set}; + +fn workspace_and(name: &str) -> R<(PathBuf, String, PathBuf)> { + let here = std::env::current_dir().map_err(|e| e.to_string())?; + let ws = workspace::up(&here, ".raea/workspace").ok_or("not in a workspace")?; + let key = workspace::slug(name); + let rel = get(&ws.join(".raea/workspace"), &format!("project.{key}.path")).ok_or_else(|| format!("no project {name} in this workspace: raea workspace lists them"))?; + let dir = ws.join(&rel); + Ok((ws, rel, dir)) +} + +fn storage_of(ws: &Path, name: &str) -> String { + get(&ws.join(".raea/workspace"), &format!("project.{}.storage", workspace::slug(name))).unwrap_or_else(|| "inline".into()) +} + +fn clean(ws: &Path) -> R<()> { + if !git(ws, &["status", "--porcelain", "--untracked-files=no"])?.is_empty() { + return Err("the workspace has changes not yet committed: commit or drop them first, so the move is one change".into()); + } + Ok(()) +} + +/// `raea project split NAME [--remote URL]`: an inline project made a submodule, its history kept. +pub fn split(name: &str, remote: Option<&str>) -> R { + let (ws, rel, dir) = workspace_and(name)?; + if storage_of(&ws, name) == "submodule" { + return Err(format!("{name} is a submodule already")); + } + clean(&ws)?; + let branch = format!("raea-split-{}", workspace::slug(name)); + let tip = git(&ws, &["subtree", "split", "-q", &format!("--prefix={rel}"), "-b", &branch])?; + let n = git(&ws, &["rev-list", "--count", &branch])?; + // the project's folder leaves the workspace's tree, then comes back as its own repo with that history + git(&ws, &["rm", "-r", "-q", "--", &rel])?; + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?; + git(&dir, &["init", "-q"])?; + git(&dir, &["fetch", "-q", &ws.to_string_lossy(), &branch])?; + git(&dir, &["reset", "-q", "--hard", "FETCH_HEAD"])?; + git(&ws, &["branch", "-q", "-D", &branch])?; + if Path::new(&dir.join(".gitattributes")).is_file() || ws.join(".gitattributes").is_file() { + // media stays in LFS: the workspace's attributes come along + let _ = std::fs::copy(ws.join(".gitattributes"), dir.join(".gitattributes")); + let _ = git(&dir, &["add", ".gitattributes"]).and_then(|_| git(&dir, &["commit", "-q", "-m", "raea: LFS for media/ and out/", "--", ".gitattributes"])); + } + let url = match remote { + Some(u) => { + git(&dir, &["remote", "add", "origin", u])?; + git(&dir, &["push", "-q", "-u", "origin", "HEAD"])?; + u.to_string() + } + None => format!("./{rel}"), + }; + git(&ws, &["-c", "protocol.file.allow=always", "submodule", "add", "-q", &url, &rel])?; + set(&ws.join(".raea/workspace"), &format!("project.{}.storage", workspace::slug(name)), "submodule")?; + include(&dir, &dir.join(".raea/project"))?; + commit(&ws, &[".raea/workspace", ".gitmodules", &rel], &format!("project {name} split into its own repo ({n} commits kept)"))?; + Ok(format!("{}: {name} is a submodule now, its own repo with {n} commits (tip {})", dir.display(), &tip[..tip.len().min(9)])) +} + +/// `raea project join NAME`: a submodule brought back in as a folder, its history merged under its path. +pub fn join(name: &str) -> R { + let (ws, rel, dir) = workspace_and(name)?; + if storage_of(&ws, name) != "submodule" { + return Err(format!("{name} is a folder in the workspace already")); + } + clean(&ws)?; + if !git(&dir, &["status", "--porcelain"])?.is_empty() { + return Err(format!("{name} has changes not yet committed: commit them first, so they come along")); + } + // the submodule's repo is kept aside while its folder leaves, then its history comes in under the same path + let aside = std::env::temp_dir().join(format!("raea-join-{}-{}", workspace::slug(name), std::process::id())); + let _ = std::fs::remove_dir_all(&aside); + git(&ws, &["clone", "-q", "--no-local", &dir.to_string_lossy(), &aside.to_string_lossy()])?; + git(&ws, &["submodule", "deinit", "-q", "-f", "--", &rel])?; + git(&ws, &["rm", "-q", "-f", "--", &rel])?; + let modules = PathBuf::from(git(&ws, &["rev-parse", "--path-format=absolute", "--git-common-dir"])?).join("modules").join(&rel); + let _ = std::fs::remove_dir_all(&modules); + let _ = std::fs::remove_dir_all(&dir); + set(&ws.join(".raea/workspace"), &format!("project.{}.storage", workspace::slug(name)), "inline")?; + let gitmodules = ws.join(".gitmodules"); + let mut paths = vec![".raea/workspace"]; + if gitmodules.is_file() { + paths.push(".gitmodules"); + } + commit(&ws, &paths, &format!("project {name} leaves its submodule"))?; + git(&ws, &["subtree", "add", "-q", &format!("--prefix={rel}"), &aside.to_string_lossy(), "HEAD", "-m", &format!("raea: project {name} joined, its history under {rel}")])?; + let _ = std::fs::remove_dir_all(&aside); + Ok(format!("{}: {name} is a folder in the workspace now, its history merged", dir.display())) +} diff --git a/apps/workspace/src/tests.rs b/apps/workspace/src/tests.rs new file mode 100644 index 00000000..6dbc449f --- /dev/null +++ b/apps/workspace/src/tests.rs @@ -0,0 +1,73 @@ +use super::*; + +#[test] +fn a_name_is_its_folder() { + assert_eq!(slug("Shane's Studio"), "shane-s-studio"); + assert_eq!(slug(" CJ / Reel 2 "), "cj-reel-2"); +} + +#[test] +fn a_spec_module_is_tidy_typescript() { + // keys unquoted where they can be, nulls and empty lists left out, whole numbers whole, short string lists inline + let v = json!({"id": "delivery", "help": null, "tags": [], "n": 45.0, "options": ["9:16", "16:9"], "odd-key": 1}); + assert_eq!(ts_literal(&v, 0), "{\n id: \"delivery\",\n n: 45,\n \"odd-key\": 1,\n options: [\"9:16\", \"16:9\"],\n}"); +} + +#[test] +fn up_finds_the_nearest_marker() { + let root = std::env::temp_dir().canonicalize().unwrap().join(format!("raea-ws-up-{}", std::process::id())); + let deep = root.join("projects/launch/media"); + std::fs::create_dir_all(&deep).unwrap(); + std::fs::create_dir_all(root.join(".raea")).unwrap(); + std::fs::write(root.join(".raea/workspace"), "").unwrap(); + assert_eq!(up(&deep, ".raea/workspace").as_deref(), Some(root.as_path())); + assert_eq!(up(&deep, ".raea/project"), None); + let _ = std::fs::remove_dir_all(&root); +} + +fn scratch(name: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("raea-ws-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +#[test] +fn next_walks_a_project_from_brief_to_show() { + let d = scratch("next"); + let shaped = next::Brief { needs: vec![], modes: vec!["tool".into()] }; + let unshaped = next::Brief { needs: vec!["who it's for (audience)".into()], modes: vec!["pitch".into()] }; + let s = next::steps(&d, &unshaped, 0); + assert!(s[0].starts_with("shape the brief: who it's for") && s[1].starts_with("plan it") && s[2].starts_with("make the first item"), "{s:?}"); + assert!(next::steps(&d, &shaped, 2)[0].starts_with("raea doctor: 2")); + std::fs::write(d.join("piece.tsx"), "registerRoot(() => null)").unwrap(); + assert!(next::steps(&d, &shaped, 0)[0].starts_with("render piece.tsx")); + std::fs::create_dir_all(d.join("out")).unwrap(); + std::thread::sleep(std::time::Duration::from_millis(20)); + std::fs::write(d.join("out/piece.mp4"), "").unwrap(); + assert!(next::steps(&d, &shaped, 0)[0].starts_with("check piece.mp4")); + std::thread::sleep(std::time::Duration::from_millis(20)); + std::fs::write(d.join("out/piece.check.json"), r#"{"issues":[{"p":"P1","says":"text clipped at 2 s"}]}"#).unwrap(); + assert_eq!(next::steps(&d, &shaped, 0)[0], "polish piece.mp4: P1 text clipped at 2 s (`raea guide polish`)"); + std::fs::write(d.join("out/piece.check.json"), r#"{"issues":[{"p":"P3","says":"minor"}]}"#).unwrap(); + assert!(next::steps(&d, &shaped, 0)[0].starts_with("show piece.mp4")); + let _ = std::fs::remove_dir_all(&d); +} + +#[test] +fn doctor_finds_old_briefs_and_old_skills() { + let d = scratch("doctor"); + std::fs::write(d.join("acme.brief"), "title: x").unwrap(); + std::fs::create_dir_all(d.join("skills/raea")).unwrap(); + std::fs::write(d.join("skills/raea/SKILL.md"), "---\nname: raea\nversion: 0.0.1\n---\n").unwrap(); + let skills = [("claude", d.join("skills"))]; + let found = doctor::findings(&d, &skills, "0.0.2"); + assert_eq!(found.len(), 2, "{:?}", found.iter().map(|f| &f.says).collect::>()); + assert!(found[0].says.contains("acme.brief") && !found[0].fixable()); + assert!(found[1].says.contains("is 0.0.1, this raea is 0.0.2") && found[1].fixable()); + assert!(doctor::findings(&d, &skills, "0.0.1").len() == 1); + let reinstalled = std::cell::Cell::new(false); + let out = doctor::doctor(&["--fix".into(), d.display().to_string()], &skills, "0.0.2", &|a| { reinstalled.set(a == "claude"); Ok(String::new()) }).unwrap(); + assert!(reinstalled.get() && out.starts_with("APPLIED 1 of 2 fixed"), "{out}"); + let _ = std::fs::remove_dir_all(&d); +} diff --git a/apps/workspace/src/workspace.rs b/apps/workspace/src/workspace.rs new file mode 100644 index 00000000..377d9e2f --- /dev/null +++ b/apps/workspace/src/workspace.rs @@ -0,0 +1,359 @@ +//! Workspaces and projects on disk (docs/projects.feature PJ1). A workspace is a git repo holding .raea/workspace, a +//! git-config file that is committed, and projects//, each holding .raea/project. raea writes an include into +//! the repo's own .git/config, so `git config workspace.layout` answers from the committed file; git never loads a +//! committed config by itself. Every change raea makes here is a commit. +use super::*; +use std::process::Command; + +const USAGE: &str = "usage: raea workspace [--json] | raea workspace init [NAME] [--layout monorepo|submodules] | raea workspace adopt DIR [--name NAME] [--layout monorepo|submodules]\n raea project [--json] | raea project new NAME [--storage inline|submodule] | raea project split NAME [--remote URL] | raea project join NAME"; + +pub(crate) fn git(dir: &Path, args: &[&str]) -> R { + let out = Command::new("git").arg("-C").arg(dir).args(args).output().map_err(|e| format!("git: {e}"))?; + if !out.status.success() { + return Err(format!("git {}: {}", args.join(" "), String::from_utf8_lossy(&out.stderr).trim())); + } + Ok(String::from_utf8_lossy(&out.stdout).trim().to_string()) +} + +/// `git config` on a file (or the global config when `file` is None), its output trimmed; Err when git says no. +pub(crate) fn config(file: Option<&Path>, args: &[&str]) -> R { + let mut c = Command::new("git"); + c.arg("config"); + if let Some(f) = file { + c.arg("-f").arg(f); + } + let out = c.args(args).output().map_err(|e| format!("git: {e}"))?; + if !out.status.success() { + return Err(format!("git config {}: {}", args.join(" "), String::from_utf8_lossy(&out.stderr).trim())); + } + Ok(String::from_utf8_lossy(&out.stdout).trim().to_string()) +} + +/// A git-config file's value, None when unset. +pub(crate) fn get(file: &Path, key: &str) -> Option { + config(Some(file), &[key]).ok().filter(|v| !v.is_empty()) +} + +pub(crate) fn set(file: &Path, key: &str, value: &str) -> R<()> { + let dir = file.parent().unwrap_or(Path::new(".")); + std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?; + config(Some(file), &[key, value]).map(drop) +} + +/// Every key of a git-config file, in order, as (key, value). +fn all(file: &Path) -> Vec<(String, String)> { + let list = config(Some(file), &["--list", "-z"]).unwrap_or_default(); + list.split('\0').filter_map(|e| e.split_once('\n')).map(|(k, v)| (k.to_string(), v.to_string())).collect() +} + +/// The value after `name` in args. +pub(crate) fn flag<'a>(args: &'a [String], name: &str) -> Option<&'a str> { + args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).map(String::as_str) +} + +/// The words of a command that aren't flags or a flag's value. +fn words(args: &[String]) -> Vec<&str> { + let takes = ["--layout", "--storage", "--name", "--remote"]; + args.iter().enumerate().filter(|(i, a)| !a.starts_with("--") && !(*i > 0 && takes.contains(&args[i - 1].as_str()))).map(|(_, a)| a.as_str()).collect() +} + +/// A name as a folder: lowercase, dashes. +pub fn slug(s: &str) -> String { + let mut out = String::new(); + for c in s.trim().to_lowercase().chars() { + if c.is_ascii_alphanumeric() { + out.push(c); + } else if !out.is_empty() && !out.ends_with('-') { + out.push('-'); + } + } + out.trim_end_matches('-').to_string() +} + +/// A new id: the prefix and eight hex digits from the clock and the process. +pub(crate) fn new_id(prefix: &str) -> String { + let t = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0); + format!("{prefix}_{:08x}", (t as u64 ^ (std::process::id() as u64) << 20) as u32) +} + +/// Where workspaces live on this machine: `git config --global raea.root`, else ~/Studio. +pub fn root() -> PathBuf { + let set = config(None, &["--global", "raea.root"]).ok().filter(|s| !s.is_empty()); + let home = std::env::var_os("HOME").map(PathBuf::from).unwrap_or_default(); + match set { + Some(s) if s.starts_with("~/") => home.join(&s[2..]), + Some(s) => PathBuf::from(s), + None => home.join("Studio"), + } +} + +/// The nearest folder at or above `from` that holds `marker` (.raea/workspace, .raea/project). +pub fn up(from: &Path, marker: &str) -> Option { + let from = from.canonicalize().ok()?; + from.ancestors().find(|d| d.join(marker).is_file()).map(Path::to_path_buf) +} + +/// The include in a repo's own config that makes `git config` read a committed file. Idempotent; the path is relative +/// to the config file, which for a submodule lives under the workspace's .git/modules. +pub(crate) fn include(repo: &Path, file: &Path) -> R<()> { + let cfg = PathBuf::from(git(repo, &["rev-parse", "--path-format=absolute", "--git-path", "config"])?); + let file = file.canonicalize().map_err(|e| format!("{}: {e}", file.display()))?; + let rel = relative(cfg.parent().unwrap_or(Path::new("/")), &file); + let have = config(Some(&cfg), &["--get-all", "include.path"]).unwrap_or_default(); + if have.lines().any(|l| l.trim() == rel) { + return Ok(()); + } + config(Some(&cfg), &["--add", "include.path", &rel]).map(drop) +} + +fn relative(from: &Path, to: &Path) -> String { + let (a, b): (Vec<_>, Vec<_>) = (from.components().collect(), to.components().collect()); + let same = a.iter().zip(&b).take_while(|(x, y)| x == y).count(); + let mut out: Vec = std::iter::repeat_n("..".to_string(), a.len() - same).collect(); + out.extend(b[same..].iter().map(|c| c.as_os_str().to_string_lossy().into_owned())); + out.join("/") +} + +fn write_new(path: &Path, text: &str) -> R<()> { + if path.exists() { + return Ok(()); + } + if let Some(d) = path.parent() { + std::fs::create_dir_all(d).map_err(|e| format!("{}: {e}", d.display()))?; + } + std::fs::write(path, text).map_err(|e| format!("{}: {e}", path.display())) +} + +/// A commit of these paths, when they changed: "raea: what". +pub(crate) fn commit(repo: &Path, paths: &[&str], what: &str) -> R<()> { + let mut add = vec!["add", "--"]; + add.extend(paths); + git(repo, &add)?; + if git(repo, &["diff", "--cached", "--quiet"]).is_ok() { + return Ok(()); + } + git(repo, &["commit", "-q", "-m", &format!("raea: {what}"), "--"]).map(|_| ()) +} + +const AGENTS_PROJECT: &str = "# Agents\n\nRun `raea context .` here before any work: the taste, this project's brief.ts and script.ts, its look and the guides\nits modes need, in the order to read them. Specs are TypeScript (`export default brief({...})` from \"raea/brief\").\n"; + +/// `raea workspace …` +pub fn workspace(args: &[String]) -> R { + let w = words(args); + match w.first().copied() { + None => show_workspace(args.iter().any(|a| a == "--json")), + Some("init") => init(w.get(1).copied(), flag(args, "--layout")), + Some("adopt") => adopt(Path::new(w.get(1).ok_or(USAGE)?), flag(args, "--name"), flag(args, "--layout")), + Some(v) => Err(format!("raea workspace has no {v:?}\n{USAGE}")), + } +} + +fn layout_of(l: Option<&str>) -> R<&str> { + match l.unwrap_or("monorepo") { + l @ ("monorepo" | "submodules") => Ok(l), + l => Err(format!("a layout is monorepo or submodules, not {l:?}")), + } +} + +/// `init` in a workspace makes it work after a clone (the includes again, for it and its submodule projects); `init +/// NAME` elsewhere makes a new workspace under raea.root. +fn init(name: Option<&str>, layout: Option<&str>) -> R { + let here = std::env::current_dir().map_err(|e| e.to_string())?; + if let Some(ws) = up(&here, ".raea/workspace").filter(|_| name.is_none()) { + include(&ws, &ws.join(".raea/workspace"))?; + let mut fixed = 0; + for (_, path, storage) in projects(&ws) { + let dir = ws.join(&path); + if storage == "submodule" && dir.join(".git").exists() && dir.join(".raea/project").is_file() { + include(&dir, &dir.join(".raea/project"))?; + fixed += 1; + } + } + return Ok(format!("{}: git config reads .raea/workspace{}", ws.display(), match fixed { 0 => String::new(), 1 => " and a submodule project's .raea/project".into(), n => format!(" and {n} submodule projects' .raea/project") })); + } + let name = name.ok_or(USAGE)?; + let dir = root().join(slug(name)); + if dir.join(".raea/workspace").is_file() { + return Err(format!("{} is a workspace already: `cd` there and `raea workspace init` re-adds its includes", dir.display())); + } + make_workspace(&dir, name, layout_of(layout)?)?; + Ok(format!("{}: workspace {name:?} ({}); next: cd there, raea project new NAME", dir.display(), layout_of(layout)?)) +} + +/// An existing folder made a workspace in place: git when it isn't a repo, .raea/workspace, and each folder in it +/// holding a brief.ts registered as an inline project. Nothing is moved or deleted. +fn adopt(dir: &Path, name: Option<&str>, layout: Option<&str>) -> R { + let dir = dir.canonicalize().map_err(|e| format!("{}: {e}", dir.display()))?; + let name = name.map(String::from).unwrap_or_else(|| dir.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default()); + make_workspace(&dir, &name, layout_of(layout)?)?; + let mut found = vec![]; + for base in [dir.clone(), dir.join("projects")] { + for e in std::fs::read_dir(&base).into_iter().flatten().flatten() { + let p = e.path(); + if p.join("brief.ts").is_file() && !p.join(".raea/project").is_file() { + let rel = relative(&dir, &p); + register(&dir, &p, &rel, "inline")?; + found.push(rel); + } + } + } + let mut paths = vec![".raea/workspace"]; + let projs: Vec = found.iter().map(|r| format!("{r}/.raea/project")).collect(); + paths.extend(projs.iter().map(String::as_str)); + commit(&dir, &paths, &format!("adopt {name} as a workspace ({})", count(found.len())))?; + Ok(format!("{}: workspace {name:?}, {}{}", dir.display(), count(found.len()), if found.is_empty() { String::new() } else { format!(": {}", found.join(", ")) })) +} + +fn count(n: usize) -> String { + if n == 1 { "1 project".into() } else { format!("{n} projects") } +} + +fn make_workspace(dir: &Path, name: &str, layout: &str) -> R<()> { + // never a workspace in another repo's own folder (on a case-insensitive disk ~/Raea is ~/raea, raea's checkout); a + // repo further up, as a home folder kept in git, is fine: the workspace is a repo of its own inside it + let parent = dir.parent().unwrap_or(Path::new("/")); + if !dir.join(".git").exists() && parent.exists() { + let top = git(parent, &["rev-parse", "--show-toplevel"]).ok().map(PathBuf::from); + if top.is_some_and(|t| t.canonicalize().ok() == parent.canonicalize().ok()) { + return Err(format!("{} would be a folder of the git repo {}: set where workspaces go, `git config --global raea.root ~/Studio`", dir.display(), parent.display())); + } + } + std::fs::create_dir_all(dir.join("projects")).map_err(|e| format!("{}: {e}", dir.display()))?; + if !dir.join(".git").exists() { + git(dir, &["init", "-q"])?; + } + let file = dir.join(".raea/workspace"); + if get(&file, "workspace.id").is_none() { + set(&file, "workspace.id", &new_id("ws"))?; + } + set(&file, "workspace.name", name)?; + set(&file, "workspace.layout", layout)?; + include(dir, &file)?; + write_new(&dir.join("controllers/.gitkeep"), "")?; + write_new(&dir.join("projects/.gitkeep"), "")?; + write_new(&dir.join("taste.ts"), &format!("import {{ taste }} from \"raea/brief\";\n\n// {name}'s house rules: every project here follows them, after the person's own taste.\nexport default taste({{\n title: {:?},\n sections: [],\n}});\n", format!("{name}: house rules")))?; + write_new(&dir.join(".gitattributes"), "media/** filter=lfs diff=lfs merge=lfs -text\nout/** filter=lfs diff=lfs merge=lfs -text\n")?; + commit(dir, &[".raea/workspace", "controllers/.gitkeep", "projects/.gitkeep", "taste.ts", ".gitattributes"], &format!("workspace {name}")) +} + +/// The workspace's projects: (name, path, storage), from .raea/workspace. +pub fn projects(ws: &Path) -> Vec<(String, String, String)> { + let mut out: Vec<(String, String, String)> = vec![]; + for (k, v) in all(&ws.join(".raea/workspace")) { + let Some(rest) = k.strip_prefix("project.") else { continue }; + let Some((name, key)) = rest.rsplit_once('.') else { continue }; + let at = out.iter().position(|p| p.0 == name).unwrap_or_else(|| { + out.push((name.to_string(), format!("projects/{name}"), "inline".into())); + out.len() - 1 + }); + match key { + "path" => out[at].1 = v, + "storage" => out[at].2 = v, + _ => {} + } + } + out +} + +/// A project's own .raea/project, and its line in the workspace's. +fn register(ws: &Path, dir: &Path, rel: &str, storage: &str) -> R { + let name = dir.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + let file = dir.join(".raea/project"); + let id = get(&file, "project.id").unwrap_or_else(|| new_id("pj")); + set(&file, "project.id", &id)?; + set(&file, "project.name", &name)?; + let wsf = ws.join(".raea/workspace"); + set(&wsf, &format!("project.{name}.path"), rel)?; + set(&wsf, &format!("project.{name}.id"), &id)?; + set(&wsf, &format!("project.{name}.storage"), storage)?; + Ok(id) +} + +fn show_workspace(json_out: bool) -> R { + let here = std::env::current_dir().map_err(|e| e.to_string())?; + let ws = up(&here, ".raea/workspace").ok_or("not in a workspace: raea workspace init NAME makes one (under `git config --global raea.root`, else ~/Studio)")?; + let file = ws.join(".raea/workspace"); + let ps = projects(&ws); + if json_out { + let projects: Vec<_> = ps.iter().map(|(n, p, s)| json!({"name": n, "path": p, "storage": s, "id": get(&file, &format!("project.{n}.id"))})).collect(); + return Ok(json!({"path": ws, "id": get(&file, "workspace.id"), "name": get(&file, "workspace.name"), "layout": get(&file, "workspace.layout"), "projects": projects}).to_string()); + } + let mut out = format!("{} ({}, {})\n{}\n", get(&file, "workspace.name").unwrap_or_default(), get(&file, "workspace.id").unwrap_or_default(), get(&file, "workspace.layout").unwrap_or_default(), ws.display()); + for (n, p, s) in &ps { + out.push_str(&format!(" {n} {p} {s}\n")); + } + Ok(out.trim_end().to_string()) +} + +/// `raea project …` +pub fn project(args: &[String]) -> R { + let w = words(args); + match w.first().copied() { + None => show_project(args.iter().any(|a| a == "--json")), + Some("new") => new_project(w.get(1).ok_or(USAGE)?, flag(args, "--storage")), + Some("split") => storage::split(w.get(1).ok_or(USAGE)?, flag(args, "--remote")), + Some("join") => storage::join(w.get(1).ok_or(USAGE)?), + Some(v) => Err(format!("raea project has no {v:?}\n{USAGE}")), + } +} + +fn new_project(name: &str, storage: Option<&str>) -> R { + let here = std::env::current_dir().map_err(|e| e.to_string())?; + let ws = up(&here, ".raea/workspace").ok_or("not in a workspace: raea workspace init NAME makes one")?; + let slugged = slug(name); + if slugged.is_empty() { + return Err(format!("{name:?} has no letters or digits to name a folder by")); + } + let rel = format!("projects/{slugged}"); + let dir = ws.join(&rel); + if dir.join(".raea/project").is_file() { + return Err(format!("{} is a project already", dir.display())); + } + let layout = get(&ws.join(".raea/workspace"), "workspace.layout").unwrap_or_else(|| "monorepo".into()); + let storage = match storage.unwrap_or(if layout == "submodules" { "submodule" } else { "inline" }) { + s @ ("inline" | "submodule") => s, + s => return Err(format!("a project's storage is inline or submodule, not {s:?}")), + }; + std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?; + write_new(&dir.join("brief.ts"), &format!("import {{ brief }} from \"raea/brief\";\n\nexport default brief({{\n title: {name:?},\n}});\n"))?; + write_new(&dir.join("AGENTS.md"), AGENTS_PROJECT)?; + for d in ["media", "brand", "out"] { + write_new(&dir.join(d).join(".gitkeep"), "")?; + } + let id = register(&ws, &dir, &rel, storage)?; + let files = [".raea/project", "brief.ts", "AGENTS.md", "media/.gitkeep", "brand/.gitkeep", "out/.gitkeep"]; + if storage == "submodule" { + git(&dir, &["init", "-q"])?; + commit(&dir, &files, &format!("project {name}"))?; + // the project's own repo, added where it stands; its url is the folder until it has a remote of its own + git(&ws, &["-c", "protocol.file.allow=always", "submodule", "add", "-q", &format!("./{rel}"), &rel])?; + include(&dir, &dir.join(".raea/project"))?; + commit(&ws, &[".raea/workspace", ".gitmodules", &rel], &format!("project {name} (submodule)"))?; + } else { + let paths: Vec = files.iter().map(|f| format!("{rel}/{f}")).collect(); + let mut all_paths: Vec<&str> = vec![".raea/workspace"]; + all_paths.extend(paths.iter().map(String::as_str)); + commit(&ws, &all_paths, &format!("project {name}"))?; + } + Ok(format!("{}: project {name:?} ({id}, {storage}); next: shape brief.ts, then raea context .", dir.display())) +} + +fn show_project(json_out: bool) -> R { + let here = std::env::current_dir().map_err(|e| e.to_string())?; + let dir = up(&here, ".raea/project").ok_or("not in a project: raea project new NAME (in a workspace) makes one")?; + let file = dir.join(".raea/project"); + let ws = up(&dir, ".raea/workspace").filter(|w| *w != dir); + let overrides: Vec<(String, String)> = all(&file).into_iter().filter(|(k, _)| k.starts_with("controller.")).collect(); + if json_out { + let o: serde_json::Map = overrides.iter().map(|(k, v)| (k.trim_start_matches("controller.").to_string(), json!(v))).collect(); + return Ok(json!({"path": dir, "id": get(&file, "project.id"), "name": get(&file, "project.name"), "workspace": ws, "controllers": o}).to_string()); + } + let mut out = format!("{} ({})\n{}\n", get(&file, "project.name").unwrap_or_default(), get(&file, "project.id").unwrap_or_default(), dir.display()); + if let Some(ws) = &ws { + out.push_str(&format!("in workspace {}\n", ws.display())); + } + for (k, v) in overrides { + out.push_str(&format!(" {} = {v}\n", k.trim_start_matches("controller."))); + } + Ok(out.trim_end().to_string()) +} diff --git a/core/brief/src/controller.rs b/core/brief/src/controller.rs new file mode 100644 index 00000000..0807670d --- /dev/null +++ b/core/brief/src/controller.rs @@ -0,0 +1,201 @@ +//! A workspace's controllers: settings its Director puts together with the person, out of a small set of parts. A +//! controller has groups, a group has typed fields, and every agent in the workspace works to the values (`describe`). +//! The agent writes one as `controllers/.ts` (`export default controller({...})`, docs/projects.feature PJ2); +//! `normalize` checks it and fills in ids, with errors in a sentence the agent can act on. The same contract as +//! apps/app src/controllers/types.ts, whose page reads these types. + +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; +use ts_rs::TS; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)] +#[ts(optional_fields)] +pub struct Controller { + pub id: String, + pub title: String, + #[serde(skip_serializing_if = "Option::is_none")] pub help: Option, + pub groups: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)] +#[ts(optional_fields)] +pub struct Group { + pub id: String, + pub title: String, + #[serde(skip_serializing_if = "Option::is_none")] pub help: Option, + pub fields: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)] +#[ts(optional_fields)] +pub struct Field { + pub id: String, + pub label: String, + #[serde(skip_serializing_if = "Option::is_none")] pub help: Option, + #[serde(flatten)] + #[ts(flatten)] + pub kind: Kind, +} + +/// One step of a workflow field: who does it (an agent's name, or "you" for the person) and where a failure goes back to. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)] +#[ts(optional_fields)] +pub struct Step { + pub name: String, + #[serde(skip_serializing_if = "Option::is_none")] pub by: Option, + #[serde(skip_serializing_if = "Option::is_none")] pub back: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)] +#[serde(tag = "type", rename_all = "lowercase")] +#[ts(optional_fields)] +pub enum Kind { + Toggle { value: bool }, + Choice { options: Vec, value: String }, + Number { value: f64, #[serde(skip_serializing_if = "Option::is_none")] unit: Option, #[serde(skip_serializing_if = "Option::is_none")] min: Option, #[serde(skip_serializing_if = "Option::is_none")] max: Option, #[serde(skip_serializing_if = "Option::is_none")] step: Option }, + Text { value: String, #[serde(skip_serializing_if = "Option::is_none")] placeholder: Option, #[serde(skip_serializing_if = "Option::is_none")] multiline: Option }, + List { value: Vec, #[serde(skip_serializing_if = "Option::is_none")] placeholder: Option }, + Agents { value: Vec }, + Channels { value: Vec }, + /// steps in order; `channels` run it (all of them when unset) + Workflow { value: Vec, #[serde(skip_serializing_if = "Option::is_none")] channels: Option> }, + /// MCP servers: URLs, commands or GitHub repos, given to every agent's session + Servers { value: Vec }, + /// skills: links to SKILL.md, read into every agent's context + Skills { value: Vec }, +} + +const TYPES: &str = "toggle, choice, number, text, list, agents, channels, workflow, servers, skills"; + +fn slug(s: &str) -> String { + let mut out = String::new(); + for c in s.to_lowercase().chars() { + if c.is_ascii_alphanumeric() { + out.push(c); + } else if !out.ends_with('-') { + out.push('-'); + } + } + let out: String = out.trim_matches('-').chars().take(48).collect(); + if out.is_empty() { "x".into() } else { out.trim_end_matches('-').into() } +} + +fn is_id(s: &str) -> bool { + let b = s.as_bytes(); + !b.is_empty() && b.len() <= 48 && b[0].is_ascii_lowercase() && b.iter().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || *c == b'-') +} + +fn text(o: &Map, k: &str) -> Option { + o.get(k).and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).map(String::from) +} + +fn id_of(o: &Map, fallback: &str) -> String { + o.get("id").and_then(Value::as_str).filter(|s| is_id(s)).map(String::from).unwrap_or_else(|| slug(fallback)) +} + +fn strings(v: Option<&Value>, what: &str) -> Result, String> { + match v { + None | Some(Value::Null) => Ok(vec![]), + Some(Value::Array(a)) if a.iter().all(Value::is_string) => { + Ok(a.iter().filter_map(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).map(String::from).collect()) + } + _ => Err(format!("{what} must be a list of strings")), + } +} + +fn number(o: &Map, k: &str) -> Option { + o.get(k).and_then(Value::as_f64).filter(|n| n.is_finite()) +} + +fn steps(v: Option<&Value>, at: &str) -> Result, String> { + let Some(Value::Array(a)) = v else { return Err(format!("{at}: a workflow's value is a list of steps: {{ name, by?, back? }}")) }; + a.iter() + .enumerate() + .map(|(i, s)| { + let o = s.as_object().ok_or_else(|| format!("{at}: step {} needs a name", i + 1))?; + let name = text(o, "name").ok_or_else(|| format!("{at}: step {} needs a name", i + 1))?; + Ok(Step { name, by: text(o, "by").map(|b| b.trim_start_matches('@').to_string()), back: text(o, "back") }) + }) + .collect() +} + +/// A field as the agent wrote it, checked and filled in; an error names the field and what it needs. +pub fn normalize_field(raw: &Value, at: &str) -> Result { + let o = raw.as_object().ok_or_else(|| format!("{at}: a field is an object"))?; + let label = text(o, "label").ok_or_else(|| format!("{at}: a field needs a label"))?; + let id = id_of(o, &label); + let w = format!("{at}.{id}"); + let value = o.get("value"); + let kind = match o.get("type").and_then(Value::as_str) { + Some("toggle") => Kind::Toggle { value: value == Some(&Value::Bool(true)) }, + Some("choice") => { + let options = strings(o.get("options"), &format!("{w}: options"))?; + if options.len() < 2 { + return Err(format!("{w}: a choice needs at least two options")); + } + let value = value.and_then(Value::as_str).filter(|v| options.iter().any(|x| x == v)).map(String::from).unwrap_or_else(|| options[0].clone()); + Kind::Choice { options, value } + } + Some("number") => Kind::Number { value: number(o, "value").unwrap_or(0.0), unit: o.get("unit").and_then(Value::as_str).map(String::from), min: number(o, "min"), max: number(o, "max"), step: number(o, "step") }, + Some("text") => Kind::Text { value: value.and_then(Value::as_str).unwrap_or("").into(), placeholder: o.get("placeholder").and_then(Value::as_str).map(String::from), multiline: Some(o.get("multiline") == Some(&Value::Bool(true))) }, + Some("list") => Kind::List { value: strings(value, &format!("{w}: value"))?, placeholder: o.get("placeholder").and_then(Value::as_str).map(String::from) }, + Some("agents") => Kind::Agents { value: strings(value, &format!("{w}: value"))? }, + Some("channels") => Kind::Channels { value: strings(value, &format!("{w}: value"))? }, + Some("servers") => Kind::Servers { value: strings(value, &format!("{w}: value"))? }, + Some("skills") => Kind::Skills { value: strings(value, &format!("{w}: value"))? }, + Some("workflow") => Kind::Workflow { value: steps(value, &w)?, channels: o.get("channels").map(|c| strings(Some(c), &format!("{w}: channels"))).transpose()? }, + _ => return Err(format!("{w}: type must be one of {TYPES}")), + }; + Ok(Field { id, label, help: text(o, "help"), kind }) +} + +/// A controller as the agent wrote it (a module's default export, as JSON), checked: ids filled in from titles, each +/// field's value of its type. +pub fn normalize(raw: &Value) -> Result { + let o = raw.as_object().filter(|o| text(o, "title").is_some()).ok_or("a controller needs a title")?; + let title = text(o, "title").unwrap_or_default(); + let id = id_of(o, &title); + let gs = o.get("groups").and_then(Value::as_array).filter(|g| !g.is_empty()).ok_or_else(|| format!("{id}: a controller needs groups: [{{ title, fields: [...] }}]"))?; + let mut groups = vec![]; + for (i, g) in gs.iter().enumerate() { + let g = g.as_object().filter(|g| text(g, "title").is_some()).ok_or_else(|| format!("{id}: group {} needs a title", i + 1))?; + let gtitle = text(g, "title").unwrap_or_default(); + let gid = id_of(g, >itle); + let at = format!("{id}.{gid}"); + let fs = g.get("fields").and_then(Value::as_array).ok_or_else(|| format!("{at}: a group needs fields"))?; + let fields = fs.iter().map(|f| normalize_field(f, &at)).collect::, _>>()?; + if let Some(d) = fields.iter().enumerate().find(|(j, f)| fields.iter().position(|x| x.id == f.id) != Some(*j)) { + return Err(format!("{at}: two fields are called {}", d.1.id)); + } + groups.push(Group { id: gid, title: gtitle, help: text(g, "help"), fields }); + } + Ok(Controller { id, title, help: text(o, "help"), groups }) +} + +/// A value checked against its field: the same type, a choice among its options, a number within its range. The +/// value as it's kept (a workflow's steps filled in, a list's strings trimmed). +pub fn check_value(f: &Field, v: &Value) -> Result { + let w = &f.label; + match &f.kind { + Kind::Toggle { .. } => v.as_bool().map(Value::Bool).ok_or_else(|| format!("{w} is on or off: true or false")), + Kind::Choice { options, .. } => v.as_str().filter(|s| options.iter().any(|o| o == s)).map(|s| Value::String(s.into())).ok_or_else(|| format!("{w} is one of: {}", options.join(", "))), + Kind::Number { min, max, .. } => { + let n = v.as_f64().filter(|n| n.is_finite()).ok_or_else(|| format!("{w} is a number"))?; + if min.is_some_and(|m| n < m) || max.is_some_and(|m| n > m) { + let (lo, hi) = (min.map_or("-∞".into(), |m| m.to_string()), max.map_or("∞".into(), |m| m.to_string())); + return Err(format!("{w} is between {lo} and {hi}")); + } + Ok(v.clone()) + } + Kind::Text { .. } => v.as_str().map(|s| Value::String(s.into())).ok_or_else(|| format!("{w} is text")), + Kind::Workflow { .. } => Ok(serde_json::to_value(steps(Some(v), w)?).unwrap_or_default()), + _ => Ok(serde_json::to_value(strings(Some(v), w)?).unwrap_or_default()), + } +} + +/// The field at a path (controller.group.field) among the controllers. +pub fn field<'a>(cs: &'a [Controller], path: &str) -> Option<&'a Field> { + let mut p = path.splitn(3, '.'); + let (c, g, f) = (p.next()?, p.next()?, p.next()?); + cs.iter().find(|x| x.id == c)?.groups.iter().find(|x| x.id == g)?.fields.iter().find(|x| x.id == f) +} diff --git a/core/brief/src/lib.rs b/core/brief/src/lib.rs index a0b035a5..b0a1c96b 100644 --- a/core/brief/src/lib.rs +++ b/core/brief/src/lib.rs @@ -4,11 +4,13 @@ //! types (`declarations`), so what tsc checks is exactly what this crate reads. pub mod brief; +pub mod controller; pub mod plan; pub mod script; pub mod taste; pub use brief::Brief; +pub use controller::Controller; pub use plan::Plan; pub use script::Script; pub use taste::Taste; @@ -26,7 +28,8 @@ macro_rules! decls { ($cfg:ident; $($t:ty),* $(,)?) => { vec![$(format!("export {}", <$t as TS>::decl(&$cfg))),*] }; } -/// The TypeScript declarations of every schema, one file's worth (core/brief/brief.d.ts is this, checked by a test). +/// The TypeScript declarations of every schema, one file's worth: sdk/raea/src/brief.gen.ts is this, checked by a test, and +/// `raea/brief` (sdk/raea/src/brief.ts) types its builders with it, so the declarations ship with the SDK. pub fn declarations() -> String { let cfg = Config::new(); let mut out = vec!["// Generated from raea-core-brief (core/brief) by its `declarations`; edit the Rust, not this.".to_string()]; @@ -35,6 +38,7 @@ pub fn declarations() -> String { script::Script, script::Scene, script::Beat, script::Line, taste::Taste, taste::TasteSection, taste::Rule, taste::Check, plan::Plan, plan::Concept, plan::Level, plan::Count, plan::Part, + controller::Controller, controller::Group, controller::Field, controller::Kind, controller::Step, )); out.join("\n\n") + "\n" } diff --git a/core/brief/src/tests.rs b/core/brief/src/tests.rs index 4c4ea73d..775bbb5e 100644 --- a/core/brief/src/tests.rs +++ b/core/brief/src/tests.rs @@ -2,13 +2,13 @@ use super::*; #[test] fn declarations_match_the_committed_file() { - let path = concat!(env!("CARGO_MANIFEST_DIR"), "/brief.d.ts"); + let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../sdk/raea/src/brief.gen.ts"); let now = declarations(); if std::env::var_os("RAEA_WRITE").is_some() { std::fs::write(path, &now).unwrap(); } let committed = std::fs::read_to_string(path).unwrap_or_default(); - assert!(committed == now, "core/brief/brief.d.ts is out of date: RAEA_WRITE=1 cargo test -p raea-core-brief"); + assert!(committed == now, "sdk/raea/src/brief.gen.ts is out of date: RAEA_WRITE=1 cargo test -p raea-core-brief"); } #[test] @@ -75,3 +75,45 @@ fn a_close_view_needs_tertiary_detail() { "parts": {"body": {"role": "body", "level": "primary"}, "rocker": {"role": "rocker", "level": "secondary", "parent": "body", "count": 2}}}"#).unwrap(); assert!(plan::check(&p).iter().any(|m| m.contains("tertiary"))); } + +const DELIVERY: &str = r#"{"title": "Delivery", "help": "What every final keeps", "groups": [{"title": "Format", "fields": [ + {"label": "Aspect ratio", "type": "choice", "options": ["9:16", "4:5", "1:1"], "value": "9:16"}, + {"label": "Loudness", "type": "number", "value": -14, "unit": "LUFS", "min": -30, "max": 0}, + {"label": "Burn in captions", "type": "toggle", "value": true}, + {"label": "Steps", "type": "workflow", "value": [{"name": "Cut", "by": "@cutter"}, {"name": "Review", "by": "you", "back": "Cut"}]}]}]}"#; + +#[test] +fn a_controller_fills_ids_from_titles_and_labels() { + let c = controller::normalize(&serde_json::from_str(DELIVERY).unwrap()).unwrap(); + assert_eq!(c.id, "delivery"); + assert_eq!(c.groups[0].id, "format"); + let ids: Vec<_> = c.groups[0].fields.iter().map(|f| f.id.as_str()).collect(); + assert_eq!(ids, ["aspect-ratio", "loudness", "burn-in-captions", "steps"]); + let controller::Kind::Workflow { value, .. } = &c.groups[0].fields[3].kind else { panic!("a workflow") }; + assert_eq!(value[0].by.as_deref(), Some("cutter")); + // what it writes back reads as the same controller (the page's types are these) + let again = controller::normalize(&serde_json::to_value(&c).unwrap()).unwrap(); + assert_eq!(again, c); +} + +#[test] +fn a_controller_says_what_is_wrong_in_a_sentence_the_agent_can_act_on() { + let bad = |j: &str| controller::normalize(&serde_json::from_str(j).unwrap()).unwrap_err(); + assert!(bad(r#"{"title": "X", "groups": [{"title": "G", "fields": [{"label": "A", "type": "slider"}]}]}"#).contains("type must be one of")); + assert!(bad(r#"{"title": "X", "groups": [{"title": "G", "fields": [{"label": "A", "type": "choice", "options": ["one"]}]}]}"#).contains("at least two options")); + assert!(bad(r#"{"title": "X"}"#).contains("needs groups")); + assert!(bad(r#"{"groups": []}"#).contains("needs a title")); + assert!(bad(r#"{"title": "X", "groups": [{"title": "G", "fields": [{"label": "A", "type": "toggle"}, {"label": "a", "type": "toggle"}]}]}"#).contains("two fields are called a")); +} + +#[test] +fn a_value_is_checked_against_its_field() { + let c = controller::normalize(&serde_json::from_str(DELIVERY).unwrap()).unwrap(); + let cs = [c]; + let f = |p: &str| controller::field(&cs, p).unwrap(); + assert!(controller::check_value(f("delivery.format.loudness"), &serde_json::json!(-16)).is_ok()); + assert!(controller::check_value(f("delivery.format.loudness"), &serde_json::json!(4)).unwrap_err().contains("between -30 and 0")); + assert!(controller::check_value(f("delivery.format.aspect-ratio"), &serde_json::json!("16:9")).unwrap_err().contains("one of: 9:16, 4:5, 1:1")); + assert!(controller::check_value(f("delivery.format.burn-in-captions"), &serde_json::json!("yes")).is_err()); + assert!(controller::field(&cs, "delivery.format.nope").is_none()); +} diff --git a/core/k/kernels/composite.k b/core/k/kernels/composite.k index 01e739f2..b03db4cc 100644 --- a/core/k/kernels/composite.k +++ b/core/k/kernels/composite.k @@ -9,6 +9,7 @@ bg:tex[T;x;y] r:and[bg;255] g:and[shr[bg;8];255] b:and[shr[bg;16];255] +a:and[shr[bg;24];255] / clip slot 0 on0:word[C;0] bx0:word[C;1] @@ -62,6 +63,7 @@ bb0:clamp[shr[k0+(541*cu0)+128;8];0;255] r:shr[(am0*rr0)+((256-am0)*r);8] g:shr[(am0*gg0)+((256-am0)*g);8] b:shr[(am0*bb0)+((256-am0)*b);8] +a:shr[(am0*255)+((256-am0)*a);8] end / clip slot 1 on1:word[C;12] @@ -116,6 +118,7 @@ bb1:clamp[shr[k1+(541*cu1)+128;8];0;255] r:shr[(am1*rr1)+((256-am1)*r);8] g:shr[(am1*gg1)+((256-am1)*g);8] b:shr[(am1*bb1)+((256-am1)*b);8] +a:shr[(am1*255)+((256-am1)*a);8] end / clip slot 2 on2:word[C;24] @@ -170,6 +173,7 @@ bb2:clamp[shr[k2+(541*cu2)+128;8];0;255] r:shr[(am2*rr2)+((256-am2)*r);8] g:shr[(am2*gg2)+((256-am2)*g);8] b:shr[(am2*bb2)+((256-am2)*b);8] +a:shr[(am2*255)+((256-am2)*a);8] end / clip slot 3 on3:word[C;36] @@ -224,6 +228,7 @@ bb3:clamp[shr[k3+(541*cu3)+128;8];0;255] r:shr[(am3*rr3)+((256-am3)*r);8] g:shr[(am3*gg3)+((256-am3)*g);8] b:shr[(am3*bb3)+((256-am3)*b);8] +a:shr[(am3*255)+((256-am3)*a);8] end / the overlay, premultiplied: o + below * (255 - a) / 255 o:word[O;i] @@ -231,4 +236,5 @@ oa:and[shr[o;24];255] r:and[o;255]+((r*(255-oa))+127)%255 g:and[shr[o;8];255]+((g*(255-oa))+127)%255 b:and[shr[o;16];255]+((b*(255-oa))+127)%255 -px:pack[r;g;b;255] +a:oa+((a*(255-oa))+127)%255 +px:pack[r;g;b;a] diff --git a/core/k/kernels/composite_tex.k b/core/k/kernels/composite_tex.k index 514d12f8..9e624b9a 100644 --- a/core/k/kernels/composite_tex.k +++ b/core/k/kernels/composite_tex.k @@ -8,6 +8,7 @@ bg:tex[T;x;y] r:and[bg;255] g:and[shr[bg;8];255] b:and[shr[bg;16];255] +a:and[shr[bg;24];255] / clip slot 0 on0:word[C;0] bx0:word[C;1] @@ -60,6 +61,7 @@ bb0:clamp[shr[k0+(541*cu0)+128;8];0;255] r:shr[(am0*rr0)+((256-am0)*r);8] g:shr[(am0*gg0)+((256-am0)*g);8] b:shr[(am0*bb0)+((256-am0)*b);8] +a:shr[(am0*255)+((256-am0)*a);8] end / clip slot 1 on1:word[C;12] @@ -113,6 +115,7 @@ bb1:clamp[shr[k1+(541*cu1)+128;8];0;255] r:shr[(am1*rr1)+((256-am1)*r);8] g:shr[(am1*gg1)+((256-am1)*g);8] b:shr[(am1*bb1)+((256-am1)*b);8] +a:shr[(am1*255)+((256-am1)*a);8] end / clip slot 2 on2:word[C;24] @@ -166,6 +169,7 @@ bb2:clamp[shr[k2+(541*cu2)+128;8];0;255] r:shr[(am2*rr2)+((256-am2)*r);8] g:shr[(am2*gg2)+((256-am2)*g);8] b:shr[(am2*bb2)+((256-am2)*b);8] +a:shr[(am2*255)+((256-am2)*a);8] end / clip slot 3 on3:word[C;36] @@ -219,6 +223,7 @@ bb3:clamp[shr[k3+(541*cu3)+128;8];0;255] r:shr[(am3*rr3)+((256-am3)*r);8] g:shr[(am3*gg3)+((256-am3)*g);8] b:shr[(am3*bb3)+((256-am3)*b);8] +a:shr[(am3*255)+((256-am3)*a);8] end / the overlay, premultiplied: o + below * (255 - a) / 255 o:word[O;i] @@ -226,4 +231,5 @@ oa:and[shr[o;24];255] r:and[o;255]+((r*(255-oa))+127)%255 g:and[shr[o;8];255]+((g*(255-oa))+127)%255 b:and[shr[o;16];255]+((b*(255-oa))+127)%255 -px:pack[r;g;b;255] +a:oa+((a*(255-oa))+127)%255 +px:pack[r;g;b;a] diff --git a/core/k/kernels/gen.py b/core/k/kernels/gen.py index 2682976c..d3a7a562 100644 --- a/core/k/kernels/gen.py +++ b/core/k/kernels/gen.py @@ -9,7 +9,10 @@ L = ["/ The frame on the GPU: the camera's target T is the background (clear col "/ Luma and chroma are bilinear; YUV is BT.709 limited range in 8.8 fixed point. One RGBA word per pixel.", "x:i!w", "y:i%w", "bg:tex[T;x;y]", - "r:and[bg;255]", "g:and[shr[bg;8];255]", "b:and[shr[bg;16];255]"] + "r:and[bg;255]", "g:and[shr[bg;8];255]", "b:and[shr[bg;16];255]", + # coverage, carried so a transparent clear (render --alpha) stays transparent where nothing is drawn; over an + # opaque background every step below keeps it 255, so those frames are the same pixels as before + "a:and[shr[bg;24];255]"] for s in range(SLOTS): P, c = f"P{s}", lambda k: f"word[C;{s * 12 + k}]" L += [f"/ clip slot {s}", @@ -46,13 +49,15 @@ for s in range(SLOTS): f"r:shr[(am{s}*rr{s})+((256-am{s})*r);8]", f"g:shr[(am{s}*gg{s})+((256-am{s})*g);8]", f"b:shr[(am{s}*bb{s})+((256-am{s})*b);8]", + f"a:shr[(am{s}*255)+((256-am{s})*a);8]", "end"] L += ["/ the overlay, premultiplied: o + below * (255 - a) / 255", "o:word[O;i]", "oa:and[shr[o;24];255]", "r:and[o;255]+((r*(255-oa))+127)%255", "g:and[shr[o;8];255]+((g*(255-oa))+127)%255", "b:and[shr[o;16];255]+((b*(255-oa))+127)%255", - "px:pack[r;g;b;255]"] + "a:oa+((a*(255-oa))+127)%255", + "px:pack[r;g;b;a]"] open("kernels/composite.k", "w").write("\n".join(L) + "\n") # composite_tex.k: the same, with each slot's planes as textures, as VideoToolbox's IOSurface-backed buffers wrap diff --git a/core/scene/src/media.rs b/core/scene/src/media.rs index d99bb642..86300515 100644 --- a/core/scene/src/media.rs +++ b/core/scene/src/media.rs @@ -44,11 +44,32 @@ pub fn decoded(src: &str) -> String { String::from_utf8(out).unwrap_or_else(|_| s.to_string()) } -/// A media src as a file: a path from staticFile (/media/x under the edit's folder), absolute, or relative to it. +/// The project an edit belongs to: the nearest folder at or above the edit's holding space.json (an object's folder, +/// docs/sdk.feature S5a, whose edit is src/main.tsx), else the edit's own folder. Remembered per folder, since media +/// paths are resolved every frame. +pub fn project_dir(dir: &Path) -> PathBuf { + static SEEN: std::sync::Mutex>> = std::sync::Mutex::new(None); + let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + let seen = seen.get_or_insert_with(Default::default); + if let Some(p) = seen.get(dir) { + return p.clone(); + } + let p = dir.ancestors().find(|d| d.join("space.json").is_file()).unwrap_or(dir).to_path_buf(); + seen.insert(dir.to_path_buf(), p.clone()); + p +} + +/// A media src as a file: a path from staticFile (/media/x: the project's media/, then its assets/, as Bevy's assets +/// folder; the edit's own media/ first when the edit isn't the project's folder), absolute, or relative to the edit. pub fn media_path(dir: &Path, src: &str) -> PathBuf { if let Some(rest) = src.strip_prefix("/media/") { - let p = dir.join("media").join(rest); - if p.exists() { + let project = project_dir(dir); + let mut tried = vec![dir.join("media")]; + if project != dir { + tried.push(project.join("media")); + } + tried.push(project.join("assets")); + if let Some(p) = tried.iter().map(|d| d.join(rest)).find(|p| p.exists()) { return p; } } @@ -58,3 +79,36 @@ pub fn media_path(dir: &Path, src: &str) -> PathBuf { } dir.join(src.trim_start_matches('/')) } + +#[cfg(test)] +mod tests { + use super::*; + + // an object's folder (S5a): space.json at its root, the edit in src/, files in assets/ or media/ + #[test] + fn media_from_the_project() { + let root = std::env::temp_dir().join(format!("raea-media-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let src = root.join("src"); + for d in [&src, &root.join("assets"), &root.join("media"), &src.join("media")] { + std::fs::create_dir_all(d).unwrap(); + } + std::fs::write(root.join("space.json"), "{}").unwrap(); + for f in ["assets/a.png", "assets/b.png", "media/b.png", "src/media/c.png", "assets/c.png"] { + std::fs::write(root.join(f), "").unwrap(); + } + assert_eq!(project_dir(&src), root); + assert_eq!(media_path(&src, "/media/a.png"), root.join("assets/a.png")); + assert_eq!(media_path(&src, "/media/b.png"), root.join("media/b.png")); + assert_eq!(media_path(&src, "/media/c.png"), src.join("media/c.png")); + // missing: where it was always looked for + assert_eq!(media_path(&src, "/media/d.png"), src.join("media/d.png")); + // no space.json above: the edit's folder is the project, its assets/ after its media/ + let plain = root.join("plain"); + std::fs::create_dir_all(plain.join("assets")).unwrap(); + std::fs::write(plain.join("assets/e.png"), "").unwrap(); + std::fs::remove_file(root.join("space.json")).unwrap(); + assert_eq!(media_path(&plain, "/media/e.png"), plain.join("assets/e.png")); + let _ = std::fs::remove_dir_all(&root); + } +} diff --git a/docs/bevy-upgrade.md b/docs/bevy-upgrade.md index 56b5a59a..c2b00826 100644 --- a/docs/bevy-upgrade.md +++ b/docs/bevy-upgrade.md @@ -15,9 +15,10 @@ pinned in rust-toolchain.toml at the root (1.97.1, what 0.20 was ported and veri in every checkout and on the CI runner; Homebrew's rust is uninstalled so nothing on PATH comes ahead of them. A bump that needs a newer rustc moves that pin in the same branch. -## The pipeline: three subagents +## The pipeline: three lanes -When a Bevy release comes out, run these three in order (they live in .claude/agents/, and each reads this file): +When a Bevy release comes out, run these three in order as lanes, `tools/agents/agent start bevy-scout` and so on (their briefs +are docs/handoff/bevy-{scout,porter,verifier}.md, and each reads this file): 1. **bevy-scout** (read-only): can raea move yet? It compares crates.io against the pins, names the plugins that haven't caught up, picks out the migration-guide items that hit raea's code, and checks whether upstream now covers diff --git a/docs/settings.md b/docs/settings.md index f46c9001..0291d6a6 100644 --- a/docs/settings.md +++ b/docs/settings.md @@ -8,6 +8,18 @@ which setting is missing. mkdir -p ~/.raea && touch ~/.raea/env && chmod 600 ~/.raea/env ``` +## Network + +| Setting | What | +|---|---| +| `RAEA_OFFLINE=1` | raea makes no network requests: a remote URL not already in raea's cache, a model or sample library not yet installed, a composition's own `fetch()` or WebSocket, Bevy's http asset source and every `raea gen` step are refused with what wanted out. What's on disk keeps working | + +## Generation (`raea gen`, optional) + +| Setting | What | +|---|---| +| `FISH_API_KEY` | Your Fish Audio key, for an `audio.speech` step on `fish:` (`fish:` alone is s2.1-pro); a plan quotes Fish's price for the words first | + ## Local audio models Two models make sound on your Mac, free, with no account. Each installs itself the first time a composition or a diff --git a/engine/bevy-calls/Cargo.toml b/engine/bevy-calls/Cargo.toml index 13313fde..46d203b0 100644 --- a/engine/bevy-calls/Cargo.toml +++ b/engine/bevy-calls/Cargo.toml @@ -25,6 +25,7 @@ fastnoise-lite = { version = "=1.1.1", optional = true, default-features = false noisy_bevy = { version = "=0.15.0", optional = true, default-features = false, features = ["cpu", "gpu"] } bevy_northstar = { version = "=0.8.0", optional = true, default-features = false, features = ["parallel"] } bevy_quinnet = { version = "=0.22.0", optional = true, default-features = false, features = ["client", "server", "shared-client-id", "recv_channels"] } +moonshine-save = { version = "=0.8.0", optional = true, default-features = false, features = [] } bevy_simple_tilemap = { version = "=0.21.0", optional = true, default-features = false, features = [] } bevy_sprite3d = { version = "=10.1.0", optional = true, default-features = false, features = [] } bevy_trauma_shake = { version = "=0.9.0", optional = true, default-features = false, features = ["events", "commands", "system_param"] } @@ -44,6 +45,7 @@ noise = ["dep:noise", "dep:fastnoise-lite"] noisy = ["dep:noisy_bevy"] northstar = ["dep:bevy_northstar"] quinnet = ["dep:bevy_quinnet"] +save = ["dep:moonshine-save"] simple_tilemap = ["dep:bevy_simple_tilemap"] sprite3d = ["dep:bevy_sprite3d"] trauma_shake = ["dep:bevy_trauma_shake"] diff --git a/engine/bevy-calls/src/lib.rs b/engine/bevy-calls/src/lib.rs index 7fd3ba0a..a08ab5fe 100644 --- a/engine/bevy-calls/src/lib.rs +++ b/engine/bevy-calls/src/lib.rs @@ -32,6 +32,8 @@ pub mod noisy; pub mod northstar; #[cfg(feature = "quinnet")] pub mod quinnet; +#[cfg(feature = "save")] +pub mod save; #[cfg(feature = "simple_tilemap")] pub mod simple_tilemap; #[cfg(feature = "sprite3d")] diff --git a/engine/bevy-calls/src/save.rs b/engine/bevy-calls/src/save.rs new file mode 100644 index 00000000..f4dcb9d6 --- /dev/null +++ b/engine/bevy-calls/src/save.rs @@ -0,0 +1,78 @@ +//! moonshine-save (the declaration's `"calls": "save"`): saving marked entities to a file and loading them back +//! (docs/plugins.feature PL16). Its markers (Save, Unload) aren't reflected and saving is an event a Rust system +//! triggers, so TypeScript marks and saves through methods. moonshine-save's own observers do the work; these record +//! what each save and load did. +//! +//! save/mark {entities: [entity, ...], unload?} -> null: marks them Save (saved, and replaced on load), or with +//! unload Unload (never saved, despawned on load: a saved entity's visuals) +//! save/save {path} -> {saved: [entity, ...]}: every Save entity's reflected, serializable components, as RON +//! save/load {path} -> {loaded: [entity, ...]}: despawns the Save and Unload entities, then spawns the file's and +//! marks them Save again (Save itself isn't saved, being unreflected) + +use bevy::prelude::*; +use bevy_remote::BrpResult; +use moonshine_save::prelude::{Loaded, Save, SaveWorld, Saved, TriggerLoad, TriggerSave, Unload, LoadWorld, load_on_default_event, save_on_default_event}; +use serde_json::{Value, json}; + +use crate::{add_method, entity, fail, params}; + +pub fn calls(app: &mut App) { + app.add_observer(save_on_default_event).add_observer(load_on_default_event).add_observer(saved).add_observer(loaded); + add_method(app, "save/mark", mark); + add_method(app, "save/save", file(true)); + add_method(app, "save/load", file(false)); +} + +/// What the last save or load did: None until it finishes (moonshine-save logs why one failed) +#[derive(Resource, Default)] +struct Done(Option>); + +fn saved(s: On, mut commands: Commands) { + commands.insert_resource(Done(Some(s.entities().collect()))); +} + +fn loaded(l: On, mut commands: Commands) { + let es: Vec = l.entities().collect(); + for &e in &es { + if let Ok(mut c) = commands.get_entity(e) { + c.insert(Save); + } + } + commands.insert_resource(Done(Some(es))); +} + +#[derive(serde::Deserialize)] +struct MarkParams { + entities: Vec, + #[serde(default)] + unload: bool, +} + +fn mark(In(p): In>, world: &mut World) -> BrpResult { + let p: MarkParams = params(p)?; + for bits in p.entities { + let e = entity(bits)?; + let mut at = world.get_entity_mut(e).map_err(|_| fail(format!("no entity {e}")))?; + if p.unload { at.insert(Unload) } else { at.insert(Save) }; + } + Ok(Value::Null) +} + +#[derive(serde::Deserialize)] +struct PathParams { + path: String, +} + +/// save/save or save/load: one file through moonshine-save, and the entities it did, or why it didn't +fn file(save: bool) -> impl FnMut(In>, &mut World) -> BrpResult { + move |In(p), world| { + let p: PathParams = params(p)?; + world.insert_resource(Done(None)); + if save { world.trigger_save(SaveWorld::default_into_file(&p.path)) } else { world.trigger_load(LoadWorld::default_from_file(&p.path)) } + world.flush(); + let (what, key) = if save { ("save to", "saved") } else { ("load from", "loaded") }; + let done = world.remove_resource::().and_then(|d| d.0).ok_or_else(|| fail(format!("{what} {} failed (the log says why)", p.path)))?; + let bits: Vec = done.into_iter().map(Entity::to_bits).collect(); + Ok(Value::Object([(key.to_string(), json!(bits))].into_iter().collect())) + } +} diff --git a/engine/bevy-plugins/Cargo.toml b/engine/bevy-plugins/Cargo.toml index f09404d9..50eceb9e 100644 --- a/engine/bevy-plugins/Cargo.toml +++ b/engine/bevy-plugins/Cargo.toml @@ -7,6 +7,7 @@ publish = false description = "Bevy plugins compiled into raea's engine, each behind a feature (sdk/raea/docs/bevy-plugins.md): declared in a project's package.json, resolved here by tools/bevy-plugins.sh, registered with raea-render's plugin hooks, driven from TSX by generic reflect rows and from TypeScript by bevy_remote's method table, stepped by the frame index" [dependencies] +raea-io-home = { path = "../../io/home" } raea-runtime-plugins = { path = "../../runtime/plugins" } # a declaration's Blitz widgets, registered for every page App (declared.rs) raea-sys-page = { path = "../../systems/page" } @@ -51,7 +52,6 @@ iyes_progress = { version = "=0.18.0", optional = true, default-features = false bevy_quinnet = { version = "=0.22.0", optional = true, default-features = false, features = ["client", "server", "shared-client-id", "recv_channels"] } bevy_rand = { version = "=0.16.0", optional = true, default-features = false, features = ["std", "wyrand", "bevy_reflect", "thread_local_entropy"] } bevy_remote = { version = "=0.20.0", default-features = false } -moonshine-save = { version = "=0.8.0", optional = true, default-features = false, features = [] } bevy_simple_tilemap = { version = "=0.21.0", optional = true, default-features = false, features = [] } bevy_skein = { version = "=0.7.0-rc.1", optional = true, default-features = false, features = [] } bevy_smud = { version = "=0.15.0", optional = true, default-features = false, features = [] } @@ -108,7 +108,7 @@ rand = ["dep:bevy_rand"] rapier2d = ["raea-bevy-adapters/rapier2d"] rapier3d = ["raea-bevy-adapters/rapier3d"] remote = ["bevy_remote/http"] -save = ["dep:moonshine-save"] +save = ["raea-bevy-calls/save"] simple_tilemap = ["dep:bevy_simple_tilemap", "raea-bevy-calls/simple_tilemap"] skein = ["dep:bevy_skein"] smud = ["dep:bevy_smud"] diff --git a/engine/bevy-plugins/src/bevy.rs b/engine/bevy-plugins/src/bevy.rs index d449eadd..643d2eb9 100644 --- a/engine/bevy-plugins/src/bevy.rs +++ b/engine/bevy-plugins/src/bevy.rs @@ -3,7 +3,7 @@ //! They need no plugin of raea's: turning a feature on puts its plugin in Bevy's DefaultPlugins, which raea-render's Engine //! builds. One exception is handled here: bevy_audio's AudioPlugin plays to the device, not into raea's mixer, so a //! render wouldn't hear it and a play would hear it twice. The Engine leaves it out; a TypeScript App that wants -//! Bevy's audio asks for it by name (`plugins: ["bevy_audio"]`). +//! Bevy's audio asks for it by name (`plugins: ["bevy_audio"]`). And under RAEA_OFFLINE the http asset source is left out. use bevy::app::PluginGroupBuilder; use bevy::prelude::*; @@ -21,5 +21,7 @@ pub fn register() { } fn group(b: PluginGroupBuilder) -> PluginGroupBuilder { - b.disable::() + let b = b.disable::(); + // RAEA_OFFLINE: no http(s) asset source, so a model or texture named by URL is refused rather than fetched + if raea_io_home::offline("Bevy's http asset source").is_err() { b.disable::() } else { b } } diff --git a/engine/bevy-plugins/src/declared.rs b/engine/bevy-plugins/src/declared.rs index 9f6b2577..8b118e82 100644 --- a/engine/bevy-plugins/src/declared.rs +++ b/engine/bevy-plugins/src/declared.rs @@ -82,7 +82,7 @@ pub fn install() { #[cfg(feature = "rapier3d")] raea_bevy_adapters::rapier3d::register(); #[cfg(feature = "save")] - use moonshine_save as _; + raea_runtime_plugins::register(raea_runtime_plugins::Registered { name: "save", install: |app| { raea_bevy_calls::save::calls(app); }, group: None, on_demand: false }); #[cfg(feature = "simple_tilemap")] raea_runtime_plugins::register(raea_runtime_plugins::Registered { name: "simple_tilemap", install: |app| { crate::AddOnce::add_once(bevy_simple_tilemap::prelude::SimpleTileMapPlugin, app); raea_bevy_calls::simple_tilemap::calls(app); }, group: None, on_demand: false }); #[cfg(feature = "skein")] @@ -164,7 +164,7 @@ pub fn declared() -> Vec { #[cfg(feature = "rapier2d")] v.push(Declared { name: "rapier2d", krate: "bevy_rapier2d", source: "version = \"=0.37.0\"", prefixes: &["bevy_rapier2d::", "raea_bevy_adapters::rapier2d::"], headless: &[], on_demand: false }); #[cfg(feature = "rapier3d")] v.push(Declared { name: "rapier3d", krate: "bevy_rapier3d", source: "version = \"=0.37.0\"", prefixes: &["bevy_rapier3d::", "raea_bevy_adapters::rapier3d::"], headless: &[], on_demand: false }); v.push(Declared { name: "remote", krate: "bevy_remote", source: "version = \"=0.20.0\"", prefixes: &["bevy_remote::"], headless: &[], on_demand: false }); - #[cfg(feature = "save")] v.push(Declared { name: "save", krate: "moonshine-save", source: "version = \"=0.8.0\"", prefixes: &["moonshine_save::"], headless: &[], on_demand: false }); + #[cfg(feature = "save")] v.push(Declared { name: "save", krate: "moonshine-save", source: "version = \"=0.8.0\"", prefixes: &["moonshine_save::"], headless: &["assets"], on_demand: false }); #[cfg(feature = "simple_tilemap")] v.push(Declared { name: "simple_tilemap", krate: "bevy_simple_tilemap", source: "version = \"=0.21.0\"", prefixes: &["bevy_simple_tilemap::"], headless: &["shader", "image"], on_demand: false }); #[cfg(feature = "skein")] v.push(Declared { name: "skein", krate: "bevy_skein", source: "version = \"=0.7.0-rc.1\"", prefixes: &["bevy_skein::"], headless: &[], on_demand: false }); #[cfg(feature = "smud")] v.push(Declared { name: "smud", krate: "bevy_smud", source: "version = \"=0.15.0\"", prefixes: &["bevy_smud::"], headless: &["shader", "mesh"], on_demand: false }); diff --git a/engine/cli/Cargo.toml b/engine/cli/Cargo.toml index 518351aa..d0b423a2 100644 --- a/engine/cli/Cargo.toml +++ b/engine/cli/Cargo.toml @@ -22,6 +22,10 @@ required-features = ["bevy-plugins"] [dependencies] raea-runtime-plugins = { path = "../../runtime/plugins" } raea-io-home = { path = "../../io/home" } +# the schemas of what an agent writes (brief.ts, script.ts, taste.ts, controllers): raea context reads specs against them +raea-core-brief = { path = "../../core/brief" } +# `raea workspace`, `raea project` and `raea controller` (docs/projects.feature PJ1-PJ4) +raea-app-workspace = { path = "../../apps/workspace" } raea-runtime-react = { path = "../../runtime/react", default-features = false, features = ["h264", "av1", "scripts", "modules", "network", "ml"] } # the sound of its renders and plays: samples and speech (raea-runtime-sound's features) raea-runtime-sound = { path = "../../runtime/sound", features = ["seedling", "ml"] } @@ -38,7 +42,10 @@ raea-io-media = { path = "../../io/media", default-features = false, features = raea-io-npm = { path = "../../io/npm" } # the agent's sandbox (WASI tools on Wasmtime/Pulley) as wsx.* native calls wsx = { path = "../../engine/sandbox/wsx" } +serde = "1" serde_json = "1" +# `raea neural` (docs/raytracing.feature RT2) +raea-neural = { path = "../neural" } regex = "1" # the app crates' verbs: `raea check`, `raea ci`, and the local tools' (sao, tokensynth, setup-audio, sounds, splat) raea-app-check = { path = "../../apps/check" } diff --git a/engine/cli/conformance/surface.test.ts b/engine/cli/conformance/surface.test.ts index ca6fe062..ef81ba27 100644 --- a/engine/cli/conformance/surface.test.ts +++ b/engine/cli/conformance/surface.test.ts @@ -49,10 +49,11 @@ const listed = new Set([...help.matchAll(/raea ([a-z][\w-]*)/g), ...help.matchAl const shellVerbs = JSON.parse(/const SHELL: &\[&str\] = &(\[[^\]]*\]);/.exec(readFileSync(join(raea, "engine/cli/src/verbs.rs"), "utf8"))![1]) as string[]; const handled = new Set([...cli.matchAll(/case "(\w+)":/g)].map((m) => m[1]).filter((c) => c !== "--help" && c !== "help")); +/** the hand-written text under dir: a skill's reference/ is the help itself, written by tools/skills.sh gen */ function files(dir: string, out: string[] = []): string[] { for (const f of readdirSync(dir)) { const p = join(dir, f); - if (lstatSync(p).isDirectory()) files(p, out); + if (lstatSync(p).isDirectory()) f !== "reference" && files(p, out); else if (f.endsWith(".md")) out.push(p); } return out; @@ -134,6 +135,18 @@ describe("raea's surface", () => { } finally { rmSync(dir, { recursive: true, force: true }); } + // by feature (S5a): space.json, package.json, assets/, src/ with main.tsx, a feature, shots/; never components/ + const feat = mkdtempSync(join(tmpdir(), "raea-init-feature-")); + const go = (...a: string[]) => spawnSync("bun", [join(here, "src/native.ts"), bin, ...a], { cwd: feat, encoding: "utf8" }); + try { + expect(go("init", "--layout", "feature").stdout).toContain("made space.json, package.json, src/main.tsx"); + expect(["space.json", "package.json", "assets", "src/main.tsx", "src/title.tsx", "src/shots/opening.tsx", "src/screens", "src/ui", "AGENTS.md"].filter((f) => !existsSync(join(feat, f)))).toEqual([]); + expect(existsSync(join(feat, "components"))).toBe(false); + expect(go("init", "--layout", "feature").stdout).toContain("nothing to make"); + expect(go("init", "--layout", "other").status).toBe(2); + } finally { + rmSync(feat, { recursive: true, force: true }); + } }); // a made clip (two colours: the take has a jump cut at 2 s) and a made-up transcript, never real footage diff --git a/engine/cli/src/cli.rs b/engine/cli/src/cli.rs index b5acb40e..a92bf56b 100644 --- a/engine/cli/src/cli.rs +++ b/engine/cli/src/cli.rs @@ -95,13 +95,26 @@ pub fn run_script(args: &[String]) -> R { pub fn run(args: &[String]) -> R { // no arguments, or asking for help: the usage, plainly (the render line's refusal is for a render missing its file) + // `help --json`: the same help, each verb's usage, flags and access tag (tools/skills.sh gen reads it) + if args.len() == 2 && args[0] == "help" && args[1] == "--json" { + return Ok(usage::help_json(&run(&["help".to_string()])?).to_string()); + } if args.is_empty() || matches!(args[0].as_str(), "help" | "--help" | "-h") { + let neural_usage = neural::USAGE; let was = IN_HELP.replace(true); let usage = run(&["render".to_string()]).err().unwrap_or_default(); IN_HELP.set(was); + // `raea library` (engine/cli/src/library.ts), listed under render's usage + let usage = format!("{usage}\n raea library [new NAME [--cloud] | add LIBRARY PATH | files LIBRARY | tag SHA TAGS | status | scan ...] | raea library search \"WORDS\" [--library LIBRARY] [--kind KIND] [--limit N] [--sound] (the person's libraries in the raea app: folders and drives indexed on this machine, searched by meaning; a folder an agent adds waits for the person's yes)"); + // a workspace's files and specs (docs/projects.feature), listed under render's usage like library + let usage = format!("{usage}\n raea spec FILE.ts [--as brief|script|taste|plan|controller] (a spec's default export as JSON, checked against its schema: brief.ts, script.ts, taste.ts, plan.ts, controllers/ID.ts)\n raea workspace init [NAME] [--layout LAYOUT] | raea workspace adopt DIR [--name NAME] | raea workspace [--json] (a workspace: a git repo of projects and controllers under raea.root, ~/Studio unless git config says)\n raea project new NAME [--storage inline|submodule] | raea project split NAME [--remote URL] | raea project join NAME | raea project [--json] (a project in the workspace: its folder, brief.ts, media/, out/; split and join keep its history)\n raea controller ls [--json] | raea controller get PATH [--json] | raea controller set PATH VALUE [--project] [--by NAME] | raea controller write FILE.ts [--by NAME] | raea controller rm ID [--by NAME] (the workspace's controllers, controllers/ID.ts; PATH is controller.group.field; every change a commit)\n raea check EDIT.tsx --quick [--shape S] [--platform P] [--taste T] [-o check.json] (three stills of a composition checked for text: clipped, cramped, safe areas, sizes; about a second)\n raea hook claude (Claude Code's PostToolUse hook: the quick check after a composition is saved)\n raea next [DIR] (the two or three useful next steps for the project, from its brief, compositions, renders and checks)\n raea doctor [--fix] [DIR] (what doesn't match this raea: old brief files, an older workspace format, an agent's skill from another version)\n {}\n {}", skill::USAGE, tools::blender::USAGE); let (export_game, scene, physics, splat) = (raea_app_game::USAGE, export::SCENE_USAGE, motion::physics::USAGE, tools::splat::USAGE); let apps = format!(" {}\n", raea_app_check::USAGE); - return Ok(format!("raea: renders, plays and checks raea compositions (React and TypeScript) on the GPU.\n\nusage: {usage}\n raea init (a project's files where they're missing: edit.tsx, cuts.ts, components/, AGENTS.md)\n raea cut TAKE \"line\" ... | --at A-B ... [--append] (cuts.ts and words.json: a take under media/ cut in the pauses around each line it says, transcribed first if it has no TAKE.words.json; or at those seconds)\n raea frame TAKE [--at S] (how a take fits the edit: a talking take for , a screen for , from where its face is)\n raea part list | raea part add NAME ... [--force] (a ready part copied into components/, yours to change)\n raea brand DOMAIN|URL (the brand kit read from its website on this machine: brand/brand.css, brand/brand.json, BRAND.md, logos in media/brand; says when a plain fetch saw too little)\n raea guide [NAME] (craft, the floor read before any edit; the modes: pitch, explain, story, play, tool; motion, music, layout and the rest; bevy and bevy/NAME for 3D)\n raea context PROJECT (what to read before working on a project: taste, brief, look, the floor and its modes' guides)\n{apps} raea play EDIT.tsx [--input | --input-script KEYS.json] [--size WxH] [--seconds N|end] (a game, live; also: --input-log FILE --offscreen --snapshot T FILE --json FILE --seek F FILE --scrub N --baked --autoplay --no-vsync --master --3d)\n {export_game} (a game as a program of its own: a Mac app or a command)\n {scene} (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)\n {physics} (the bakes and make)\n {splat} (footage trained into a Gaussian splat for ; setup installs its tools)\n raea run SCRIPT.ts (a TypeScript program on the engine, headless: its default export is called, what it prints is the answer; a check like a room's checkLayout; also: --timeout S)\n raea mezz [--check] PATH... (an intra-only ProRes copy of each long-GOP source over 1080p, for smooth scrubbing; --check says which would get one)\n raea traces [show [N|last|DIR]] (the sessions raea left, newest first: how each ended, its glitches; show tells one in full)")); + return Ok(format!("raea: renders, plays and checks raea compositions (React and TypeScript) on the GPU.\n\nusage: {usage}\n raea init (a project's files where they're missing: edit.tsx, cuts.ts, components/, AGENTS.md)\n raea cut TAKE \"line\" ... | --at A-B ... [--append] (cuts.ts and words.json: a take under media/ cut in the pauses around each line it says, transcribed first if it has no TAKE.words.json; or at those seconds)\n raea frame TAKE [--at S] (how a take fits the edit: a talking take for , a screen for , from where its face is)\n raea part list | raea part add NAME ... [--force] (a ready part copied into components/, yours to change)\n raea brand DOMAIN|URL (the brand kit read from its website on this machine: brand/brand.css, brand/brand.json, BRAND.md, logos in media/brand; says when a plain fetch saw too little)\n raea guide [NAME] (craft, the floor read before any edit; the modes: pitch, explain, story, play, tool; motion, music, layout and the rest; bevy and bevy/NAME for 3D)\n raea context PROJECT (what to read before working on a project: taste, brief, look, the floor and its modes' guides)\n{apps} raea play EDIT.tsx [--input | --input-script KEYS.json] [--size WxH] [--seconds N|end] (a game, live; also: --input-log FILE --offscreen --snapshot T FILE --json FILE --seek F FILE --scrub N --baked --autoplay --no-vsync --master --3d)\n {export_game} (a game as a program of its own: a Mac app or a command)\n {scene} (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)\n {physics} (the bakes and make)\n {splat} (footage trained into a Gaussian splat for ; setup installs its tools)\n raea run SCRIPT.ts (a TypeScript program on the engine, headless: its default export is called, what it prints is the answer; a check like a room's checkLayout; also: --timeout S)\n raea gen image|video|music|sfx|speech|mesh|text \"PROMPT\" | gen plan|run FLOW.ts|FLOW.json | gen comfy import|export|run|schema FILE | gen models | gen balance (generated media through made.app, fal, Replicate, OpenRouter, Modal or ComfyUI; ComfyUI workflows both ways: raea gen alone lists its flags)\n {neural_usage} (DLSS 5 neural rendering on a `render --aov` folder, with its motion and depth: your own MLX-DLSS build and weights, RAEA_MLXDLSS and RAEA_DLSS_MODEL)\n raea mezz [--check] PATH... (an intra-only ProRes copy of each long-GOP source over 1080p, for smooth scrubbing; --check says which would get one)\n raea traces [show [N|last|DIR]] (the sessions raea left, newest first: how each ended, its glitches; show tells one in full)")); + } + // `--version`: the release's version, which a skill's front matter names (docs/skills.feature SK6) + if args.len() == 1 && matches!(args[0].as_str(), "--version" | "-V") { + return Ok(skill::version()); } // an argument the verb doesn't take is refused with its usage, never dropped (zsh's "--frame 20", one word, rendered // every frame): the verb's flags and how many arguments it takes are read from its lines in the help, the one list @@ -118,6 +131,55 @@ pub fn run(args: &[String]) -> R { if args[0] == "context" { return context(args.get(1).map(String::as_str)); } + // `workspace …` and `project …`: the folder format, configured by committed git-config (docs/projects.feature PJ1) + if args[0] == "workspace" { + return raea_app_workspace::workspace(&args[1..]); + } + if args[0] == "project" { + return raea_app_workspace::project(&args[1..]); + } + // `controller …`: the workspace's controllers/.ts and a project's overrides (PJ2) + if args[0] == "controller" { + return raea_app_workspace::controller(&args[1..], spec::spec_json); + } + // `skill [NAME]` and `skills install --agent A`: the skills this raea ships, for its version (SK6) + if args[0] == "skill" { + return skill::skill(&args[1..]); + } + if args[0] == "skills" { + return skill::install(&args[1..]); + } + // `next [DIR]` and `doctor [--fix] [DIR]`: the project's next steps, and its drift from this raea (SK10) + if args[0] == "next" { + return next(&args[1..]); + } + if args[0] == "doctor" { + return skill::doctor(&args[1..]); + } + // `setup blender` and `blender run SCRIPT.py`: Blender found or downloaded, its MCP add-on, headless scripts (SK11) + if args[0] == "setup" && args.get(1).map(String::as_str) == Some("blender") { + return tools::blender::setup(&args[2..]); + } + if args[0] == "blender" { + return tools::blender::blender(args); + } + // `spec FILE.ts`: a spec's data as JSON, for a program that reads specs without evaluating TypeScript (the feed's host) + if args[0] == "spec" { + return spec::spec_cli(&args[1..]); + } + // `check VIDEO --taste taste.ts|DIR`: the taste's .ts files evaluated here, then the check (main.rs takes the rest) + if args[0] == "check" && args.iter().any(|a| a == "--quick") { + let (report, bad) = raea_app_check::quick::quick(&args[1..], spec::tastes_ts(args)?)?; + println!("{report}"); + std::process::exit(i32::from(bad)); + } + // `hook claude`: Claude Code's PostToolUse hook, the quick check after a composition is saved (SK10) + if args[0] == "hook" { + return raea_app_check::quick::hook(&args[1..]); + } + if args[0] == "check" { + std::process::exit(raea_app_check::cli_with(&args[1..], spec::tastes_ts(args)?)); + } if args.first().map(String::as_str) == Some("traces") { return traces(args); } @@ -136,6 +198,10 @@ pub fn run(args: &[String]) -> R { } // `mezz [--check] PATH...`: optimized media (raea_io_media::mezz, lightspeed F4): each long-GOP source over 1080p under // PATH (a file, or a folder's videos) gets its intra-only ProRes copy, one at a time; --check only says which would + // `neural mlxdlss DIR -o OUT`: DLSS 5 on a `render --aov` folder, through the founder's own MLX-DLSS (RT2) + if args.first().map(String::as_str) == Some("neural") { + return neural::neural(&args[1..]); + } if args.first().map(String::as_str) == Some("mezz") { return mezz(&args[1..]); } @@ -157,6 +223,9 @@ pub fn run(args: &[String]) -> R { Some("song") => return tools::song::song(args), // `track CLIP.mp4 [--subject X,Y,W,H] [--from S]`: the clip's camera solved for (motion/track.rs) Some("track") => return motion::track::track(args), + // `gen …`: generation flows on made.app, fal, Replicate, OpenRouter, Modal and ComfyUI, and ComfyUI workflows read + // and written (raea-io-gen, through apps/tools generate.rs for the local models) + Some("gen") => return raea_app_tools::generate::generate(args), // the agent shell's own verbs ported here (`init`, `cut`, `frame`): engine/cli's handler, run by its native.ts (shell()) Some(v) if SHELL.contains(&v) => return shell(args), _ => {} @@ -255,7 +324,7 @@ pub fn run(args: &[String]) -> R { } if args.first().map(String::as_str) != Some("render") || args.len() < 2 { return Err(format!( - "raea render EDIT.tsx -o OUT.mp4|OUT.png|DIR [--frame N | --at A,B] [--composition ID] [--w W] [--h H] [--fps FPS] [--frames N] [--words W.json] [--perception P.json] [--input I.json|inputs.rrl] [--manifest render.json] [--stage WxH] [--10bit] [--kbps N | --quality draft|high|master|0..1] (also: --lite --comps)\n raea render PAGE.html -o OUT.mp4|DIR [--at A,B] (an HTML composition, the HTML composition format format)\n raea render --bundle NAME.comp.js -o OUT.png|DIR [--dir DIR] [--frame N] (a bundle from raea bundle, as render_bundle draws it) + "raea render EDIT.tsx -o OUT.mp4|OUT.png|DIR [--frame N | --at A,B] [--composition ID] [--w W] [--h H] [--fps FPS] [--frames N] [--words W.json] [--perception P.json] [--input I.json|inputs.rrl] [--manifest render.json] [--stage WxH] [--10bit] [--aov] [--alpha] [--kbps N | --quality draft|high|master|0..1] (also: --lite --comps)\n raea render PAGE.html -o OUT.mp4|DIR [--at A,B] (an HTML composition, the HTML composition format format)\n raea render --bundle NAME.comp.js -o OUT.png|DIR [--dir DIR] [--frame N] (a bundle from raea bundle, as render_bundle draws it) raea media probe|still|sheet|audio|loudness|motion|cuts|freezes|proxy|trim|concat FILE ... | ffmpeg ARGS | ffprobe ARGS (media work, native: media help) raea bundle EDIT.tsx --composition-bundle -o OUT.js [--portable DIR] (a composition for render_bundle, on the Mac or the iPhone)\n raea add PKG[@RANGE]... [--dev] | remove NAME... | install [--offline] [--in DIR] (npm packages for the project: raea.lock, node_modules)\n {} (foley, local)\n {} (an instrument's notes, local)\n raea setup-audio [--check] [sao|tokensynth] (install or check the local audio models)\n {} (the song's energy map: beats, sections, builds, drops, stops, hits, cuts per bar; also: --backend NAME)\n raea sounds [WORDS] | sounds get PACK/INSTRUMENT [--notes ..|--all] [-o DIR] (open sample libraries for a Sampler)\n {} (the clip's camera solved, for )", tools::sound::SAO_USAGE, tools::sound::TOKENSYNTH_USAGE, tools::song::USAGE, motion::track::USAGE diff --git a/engine/cli/src/guide.rs b/engine/cli/src/guide.rs index 79d52f9b..68ea5668 100644 --- a/engine/cli/src/guide.rs +++ b/engine/cli/src/guide.rs @@ -43,7 +43,7 @@ pub fn guide(name: Option<&str>) -> R { Ok(if shell { format!("{GUIDE_NOTE}{text}") } else { text }) } -/// The taste files a mode reads beside taste.brief, which is always read +/// The taste files a mode reads beside taste.ts, which is always read pub fn taste_kinds(mode: &str) -> &'static [&'static str] { match mode { "pitch" | "explain" | "story" => &["motion", "sound"], @@ -53,86 +53,65 @@ pub fn taste_kinds(mode: &str) -> &'static [&'static str] { } } -/// A brief's head facts (the `key: value` lines before its first `## `), "(assumed)" dropped -pub fn brief_fact(text: &str, key: &str) -> Option { - text.lines() - .take_while(|l| !l.starts_with("## ")) - .find_map(|l| { - let (k, v) = l.split_once(':')?; - (k.trim().eq_ignore_ascii_case(key)).then(|| v.trim().trim_end_matches("(assumed)").trim().to_string()) - }) - .filter(|v| !v.is_empty()) -} - -/// One `## Heading` section's text, without its heading -pub fn brief_section(text: &str, heading: &str) -> Option { - let mut out = String::new(); - let mut inside = false; - for l in text.lines() { - if let Some(h) = l.strip_prefix("## ") { - if inside { - break; - } - inside = h.trim().eq_ignore_ascii_case(heading); - continue; - } - if inside { - out.push_str(l); - out.push('\n'); - } - } - let out = out.trim().to_string(); - (!out.is_empty()).then_some(out) -} - /// `raea context PROJECT`: everything an agent reads before working on a project, in the order it should be read. That -/// is the person's taste (~/.raea/taste/taste.brief, then the files its modes need; RAEA_TASTE moves the folder), the -/// project's brief and any deliverable briefs it links, its look (the brief's ## Look and brand/brand.css), and the -/// craft floor and each mode's guide. PROJECT is a folder holding brief.brief, or a .brief file. +/// is the person's taste (~/.raea/taste/taste.ts, then the files its modes need; RAEA_TASTE moves the folder), the +/// project's brief and the briefs and script it names, its look (the brief's look and brand/brand.css), and the craft +/// floor and each mode's guide. PROJECT is a folder holding brief.ts, or the file. pub fn context(project: Option<&str>) -> R { - let project = project.ok_or("usage: raea context PROJECT (a folder with brief.brief, or a .brief file)")?; - let path = Path::new(project); - let brief_path = if path.is_dir() { path.join("brief.brief") } else { path.to_path_buf() }; - let brief = std::fs::read_to_string(&brief_path).map_err(|e| format!("no brief at {} ({e}): a project starts as brief.brief", brief_path.display()))?; + let project = project.ok_or("usage: raea context PROJECT (a folder with brief.ts, or a brief.ts file)")?; + let brief_path = brief_at(project)?; + let spec::Loaded { path: brief_path, text: brief, title, modes, more: subs, look, .. } = spec::load_brief_ts(&brief_path)?; let dir = brief_path.parent().unwrap_or(Path::new(".")).to_path_buf(); - let title = brief.lines().find_map(|l| l.strip_prefix("# ")).unwrap_or("Untitled").trim().to_string(); - let modes_of = |text: &str| -> Vec { - brief_fact(text, "mode").map(|m| m.split([',', '+', '&']).map(|s| s.trim().to_ascii_lowercase()).filter(|s| !s.is_empty()).collect()).unwrap_or_default() - }; - // deliverable briefs: a Deliver line naming a .brief beside the project's - let mut subs: Vec<(PathBuf, String)> = Vec::new(); - if let Some(deliver) = brief_section(&brief, "deliver") { - for tok in deliver.split(['·', '\n']).map(str::trim) { - let tok = tok.split(['→', ' ']).next().unwrap_or("").trim(); - if tok.ends_with(".brief") { - let p = dir.join(tok); - match std::fs::read_to_string(&p) { - Ok(t) => subs.push((p, t)), - Err(e) => subs.push((p, format!("(missing: {e})"))), - } - } - } - } - let mut modes = modes_of(&brief); - for (_, t) in &subs { - for m in modes_of(t) { - if !modes.contains(&m) { - modes.push(m); - } - } - } let taste_dir = std::env::var_os("RAEA_TASTE").map(PathBuf::from).or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".raea/taste"))); + // a cheap doctor (file reads and git config): CONTEXT_STALE when this project or the agent's skill is from another raea + let stale = raea_app_workspace::doctor::findings(&dir, &skill::agents(), &skill::version()); + let stale = match stale.first() { + Some(f) => format!("CONTEXT_STALE raea doctor finds {} thing(s), first: {} (raea doctor --fix)\n\n", stale.len(), f.says), + None => String::new(), + }; let mut out = format!( - "# raea context: {title}\n\nRead all of this before any work on the project, in this order. The person's taste beats every guide's default; the brief\nbeats your own taste. Modes: {}.\n", + "{stale}# raea context: {title}\n\nRead all of this before any work on the project, in this order. The person's taste beats every guide's default; the brief\nbeats your own taste. Modes: {}.\n", if modes.is_empty() { "none yet (shape the brief first: who it's for, what they should believe, what kind of piece)".to_string() } else { modes.join(", ") } ); + context_body(&mut out, &dir, taste_dir, &modes, &brief_path, brief, subs, look); + Ok(out) +} + +/// `raea next [DIR]`: the two or three useful next steps for the project (apps/workspace next.rs). +pub fn next(args: &[String]) -> R { + let brief_path = brief_at(args.first().map(String::as_str).unwrap_or("."))?; + let l = spec::load_brief_ts(&brief_path)?; + let dir = brief_path.parent().unwrap_or(Path::new(".")).to_path_buf(); + let stale = raea_app_workspace::doctor::findings(&dir, &skill::agents(), &skill::version()).len(); + Ok(raea_app_workspace::next::text(&dir, &raea_app_workspace::next::Brief { needs: l.missing, modes: l.modes }, stale)) +} + +/// The brief.ts for a folder anywhere inside a project, or the file named. +fn brief_at(project: &str) -> R { + let path = Path::new(project); + let brief_path = if path.is_dir() { + // from anywhere inside a project: the nearest folder up with a brief.ts or a .raea/project + let dir = path.canonicalize().ok().and_then(|d| d.ancestors().find(|a| a.join("brief.ts").is_file() || a.join(".raea/project").is_file()).map(Path::to_path_buf)); + dir.unwrap_or_else(|| path.to_path_buf()).join("brief.ts") + } else { + path.to_path_buf() + }; + if !brief_path.is_file() { + return Err(format!("no brief at {}: a project starts as brief.ts (`export default brief({{ title: ... }})` from \"raea/brief\")", brief_path.display())); + } + Ok(brief_path) +} + +/// The sections of `raea context` after its head, in reading order. +#[allow(clippy::too_many_arguments)] +fn context_body(out: &mut String, dir: &Path, taste_dir: Option, modes: &[String], brief_path: &Path, brief: String, subs: Vec<(PathBuf, String)>, look: Option) { let mut section = |name: String, body: String| out.push_str(&format!("\n\n===== {name} =====\n\n{}\n", body.trim_end())); - // the person's taste: always taste.brief, then each kind its modes need, once - match &taste_dir { - Some(t) if t.join("taste.brief").is_file() => { - section(format!("TASTE {}", t.join("taste.brief").display()), std::fs::read_to_string(t.join("taste.brief")).unwrap_or_default()); + // the person's taste: always taste.ts, then each kind its modes need, once + match taste_dir.as_deref().and_then(|t| spec::taste_file(t, "taste").map(|f| (t, f))) { + Some((t, (p, text))) => { + section(format!("TASTE {}", p.display()), text); let mut kinds: Vec<&str> = Vec::new(); - for m in &modes { + for m in modes { for k in taste_kinds(m) { if !kinds.contains(k) { kinds.push(k); @@ -140,20 +119,27 @@ pub fn context(project: Option<&str>) -> R { } } for k in kinds { - let p = t.join(format!("{k}.brief")); - if let Ok(text) = std::fs::read_to_string(&p) { + if let Some((p, text)) = spec::taste_file(t, k) { section(format!("TASTE {}", p.display()), text); } } } - _ => section("TASTE".into(), "(no taste yet: ~/.raea/taste/taste.brief holds the person's standing corrections)".into()), + None => section("TASTE".into(), "(no taste yet: ~/.raea/taste/taste.ts holds the person's standing corrections)".into()), + } + // the workspace's house rules, which every project in it follows (docs/projects.feature) + if let Some((p, text)) = raea_app_workspace::up(&dir, ".raea/workspace").and_then(|ws| spec::taste_file(&ws, "taste")) { + section(format!("WORKSPACE TASTE {}", p.display()), text); + } + // the workspace's controllers, with this project's overrides: its settings and workflows, which the work follows + if let Some(text) = raea_app_workspace::summary(&dir, spec::spec_json) { + section("CONTROLLERS (raea controller ls; a project's own values marked)".into(), text); } section(format!("BRIEF {}", brief_path.display()), brief.clone()); for (p, t) in &subs { - section(format!("BRIEF {}", p.display()), t.clone()); + section(format!("{} {}", if p.to_string_lossy().contains("script") { "SCRIPT" } else { "BRIEF" }, p.display()), t.clone()); } // the look: the brief's own section, and the brand's tokens when the project has them - let mut look = brief_section(&brief, "look").unwrap_or_else(|| "(the brief has no ## Look yet)".into()); + let mut look = look.unwrap_or_else(|| "(the brief has no look yet)".into()); if let Ok(css) = std::fs::read_to_string(dir.join("brand/brand.css")) { look.push_str(&format!("\n\nbrand/brand.css:\n{css}")); } @@ -163,12 +149,11 @@ pub fn context(project: Option<&str>) -> R { if let Ok(t) = std::fs::read_to_string(craft.join("floor.md")) { section(format!("GUIDE craft floor ({})", craft.join("floor.md").display()), t); } - for m in &modes { + for m in modes { let p = craft.join("modes").join(format!("{m}.md")); match std::fs::read_to_string(&p) { Ok(t) => section(format!("GUIDE mode {m} ({})", p.display()), t), Err(_) => section(format!("GUIDE mode {m}"), format!("(raea has no guide for the mode {m:?} yet)")), } } - Ok(out) } diff --git a/engine/cli/src/index.ts b/engine/cli/src/index.ts index dcd805fb..110e40ab 100644 --- a/engine/cli/src/index.ts +++ b/engine/cli/src/index.ts @@ -4,6 +4,7 @@ // (native.ts answers it), and every other verb is the engine's own command line (`engine`: the native `raea`), so there // is one `raea`, and its help is the native one. Every command prints what a person would read; files hold the rest. import { REGISTRY, TEMPLATE } from "./registry.gen"; +import { FEATURE_DIRS, featureLayout } from "./layout"; /** The host's answer to an op (src/native.ts answers shape, cut, frame and brand). Throws when there's no host. */ export type Host = (op: string, args: Record) => any; @@ -20,6 +21,8 @@ type Fs = { }; type Ctx = { cwd: string; fs: Fs }; const out = (stdout: string, exitCode = 0, stderr = "") => ({ stdout, stderr, exitCode }); +// `raea library` (library.ts), kept apart from the imports above +import { libraryVerb } from "./library"; function flag(args: string[], name: string): string | undefined { const i = args.indexOf(name); @@ -88,8 +91,8 @@ eyes 38% down as the speaker moves; an objectPosition or transform turns it off) . Media files import as modules: import take from "./media/x.mov". Sound: music in Tone.js (import * as Tone from "raea/tone"): instruments in a Tone.Sampler playing a Part or Sequence, the instrument's notes from Tone.tokensynth("a warm upright bass", ["C2", "C3", "C4"]) or a -sample library (\`raea sounds\`); sao("prompt", {seconds}) for an effect, as an