mirror of
https://github.com/shinyobjectz/raea.git
synced 2026-12-06 05:33:38 -10:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
43f730837a |
No files matched your search
@@ -43,7 +43,9 @@ pub fn rendered(args: &[String]) -> i32 {
|
||||
let excused: Vec<Despite> = through.iter().map(|(c, w)| Despite { check: c.clone(), why: w.clone() }).collect();
|
||||
let out = raea_runtime_bundle::flag(args, "-o").or_else(|| raea_runtime_bundle::flag(args, "--review")).map(PathBuf::from);
|
||||
// the manifest every render writes beside its output (DR2), or where --manifest put it
|
||||
let manifest = raea_runtime_bundle::flag(args, "--manifest").map(PathBuf::from).or_else(|| Some(raea_runtime_world::manifest_for(out.as_deref()?, std::path::Path::new(args.get(1)?))));
|
||||
// a plan's manifest is its -o (render --plan)
|
||||
let plan = args.iter().any(|a| a == "--plan");
|
||||
let manifest = if plan { out.clone() } else { raea_runtime_bundle::flag(args, "--manifest").map(PathBuf::from).or_else(|| Some(raea_runtime_world::manifest_for(out.as_deref()?, std::path::Path::new(args.get(1)?)))) };
|
||||
if let Some(m) = manifest {
|
||||
if let Some(mut v) = std::fs::read(&m).ok().and_then(|b| serde_json::from_slice::<Value>(&b).ok()) {
|
||||
// a video's text, held to the check's text rules as it finishes, a check's round sooner
|
||||
@@ -62,7 +64,8 @@ pub fn rendered(args: &[String]) -> i32 {
|
||||
}
|
||||
}
|
||||
// a render that is part of another (a review's tiles, a quick check's stills) leaves the entry to that one
|
||||
let file = args.get(1).filter(|a| !a.starts_with('-') && std::env::var("RAEA_RECORD").as_deref() != Ok("off")).map(PathBuf::from);
|
||||
// and a plan, which drew nothing, isn't a render to keep
|
||||
let file = args.get(1).filter(|a| !plan && !a.starts_with('-') && std::env::var("RAEA_RECORD").as_deref() != Ok("off")).map(PathBuf::from);
|
||||
if let Some(e) = file.and_then(|f| record::keep("raea render", &f, out.as_deref(), &found, excused, &raea_io_trace::utc(SystemTime::now()).1)) {
|
||||
println!("raea render: kept in the project's record as {} (raea findings reads it)", e.id);
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ raea render piece.tsx --quality master -o final.mp4 # constant quality for
|
||||
raea render scene.tsx --review review/ # a 3D scene from six fixed cameras, in colour and clay
|
||||
raea render piece.tsx -o piece.wav # the sound alone, no frames drawn
|
||||
raea render piece.tsx -o piece.mp4 --audio piece.wav # the video, and its sound beside it from the same pass
|
||||
raea render piece.tsx --plan -o piece.plan.json # what every frame shows and plays, nothing drawn
|
||||
```
|
||||
|
||||
What `-o` names decides what you get: a name ending in `.mp4` is a video, `.png` is one frame, `.wav` is the sound
|
||||
@@ -41,6 +42,14 @@ frames), or where `--manifest` says. It holds what each frame showed as laid out
|
||||
size, each video's source and time, each picture's box), the sounds heard and what the render found. `raea check`
|
||||
reads it, and so does [`raea world`](world.md), which measures the output against it when a check asks.
|
||||
|
||||
`--plan` writes that manifest without drawing: every frame is stepped through React and laid out, and its sounds are
|
||||
gathered, but no video frame is decoded, nothing is painted and nothing is encoded, so a 30-second cut is planned in
|
||||
seconds where its render takes minutes. `-o` names the JSON file. It has a frame entry for every frame (each video's
|
||||
source, time, box and fit, each text's words, box and size), the sounds heard (each clip's source, in point and
|
||||
frames) and `"plan": true`; what only drawing finds (exposure, 3D clipping, layers) is left out. `raea goal check --at
|
||||
edit --manifest PLAN.json` holds a cut to the rules a plan can answer (text in a UI zone, a cut inside a word, text over
|
||||
a face) before any render.
|
||||
|
||||
A render checks what it draws: 3D parts passing into each other (the clipping check), how its 3D is staged (3D type
|
||||
too small or turned to read, page type over a part, parts that snap, a camera that lurches, frames with almost nothing
|
||||
on screen; `raea scene stage` runs these without drawing, all but the page's) and its pictures' exposure (clipping to
|
||||
@@ -61,6 +70,7 @@ the reason in the manifest. A render of a file in a raea project also keeps its
|
||||
|
||||
```sh
|
||||
raea render EDIT.tsx -o OUT.mp4|OUT.png|OUT.wav|DIR [--audio OUT.wav] [--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] [--props JSON|P.json] [--scale S] [--hold FRAME[:FRAMES]] [--manifest render.json] [--layers] [--stage WxH] [--10bit] [--aov] [--alpha [--alpha-codec prores|hevc|rle|png]] [--kbps N | --quality draft|high|master|0..1] [--clay] [--despite CHECK WHY] (also: --lite --comps)
|
||||
raea render EDIT.tsx --plan -o PLAN.json [--composition ID] [--props JSON|P.json] [--words W.json] [--perception P.json] (every frame through React and layout and its sounds gathered, nothing decoded, drawn or encoded: the render manifest with "plan": true, in seconds, for raea goal check --at edit)
|
||||
raea render EDIT.tsx --review DIR [--frame N] (fixed cameras hero, front, right, top, iso, low in colour and clay: DIR/colour.png, clay.png, review.json)
|
||||
raea render PAGE.html -o OUT.mp4|OUT.png|DIR [--at A,B] [--alpha] (an HTML composition)
|
||||
raea render --bundle NAME.comp.js -o OUT.png|DIR [--dir DIR] [--frame N] (a bundle from raea bundle, as render_bundle draws it)
|
||||
@@ -95,6 +105,7 @@ Headless: it needs nothing running and opens no window. Takes up to 1 argument b
|
||||
| `--lite` | – | Draw with raea's live view runtime instead of React, as a live game does. Used by the app when it opens a game. |
|
||||
| `--manifest` | `render.json` | Write the render's manifest to this file instead of beside the output: the composition's length in frames (`length`, whichever frames were rendered), every frame's element boxes as drawn, what the render found and the sounds heard, which `raea check` and `raea world` read. |
|
||||
| `--perception` | `P.json` | The perception the composition's Clock reads (faces, boxes, one for every frame or by frame), when it isn't the `perception.json` beside it. |
|
||||
| `--plan` | – | Write the render manifest of every frame to `-o PLAN.json` without drawing: React and layout run for each frame and its sounds are gathered, but no video is decoded, nothing painted and nothing encoded. The file has `"plan": true`; `raea goal check --at edit --manifest PLAN.json` reads it. |
|
||||
| `--props` | `JSON\|P.json` | Input props, as a JSON object or a file holding one. `getInputProps()` returns them, and they go over the composition's `defaultProps` before `calculateMetadata` runs. |
|
||||
| `--quality` | `draft\|high\|master\|0..1` | Constant-quality encoding: `draft` for previews, `high` for most deliveries, `master` for type and hard edges, or a number from 0 to 1. On Windows and Linux (OpenH264) it scales the bitrate instead, and once a frame fits at OpenH264's finest quantiser (12), a higher setting writes the same file. |
|
||||
| `--review` | `DIR` | Render a 3D scene from six fixed cameras (hero, front, right, top, iso, low), in colour and in clay, to `DIR/colour.png`, `DIR/clay.png` and `DIR/review.json`. |
|
||||
|
||||
@@ -384,7 +384,7 @@ pub fn run(args: &[String]) -> R<String> {
|
||||
}
|
||||
if args.first().map(String::as_str) != Some("render") || args.len() < 2 {
|
||||
return Err(format!(
|
||||
"raea render EDIT.tsx -o OUT.mp4|OUT.png|OUT.wav|DIR [--audio OUT.wav] [--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] [--props JSON|P.json] [--scale S] [--hold FRAME[:FRAMES]] [--manifest render.json] [--keys keys.json] [--layers] [--stage WxH] [--10bit] [--aov] [--alpha [--alpha-codec prores|hevc|rle|png]] [--kbps N | --quality draft|high|master|0..1] [--clay] [--despite CHECK WHY] (also: --lite --comps)\n raea render EDIT.tsx --review DIR [--frame N] (fixed cameras hero, front, right, top, iso, low in colour and clay: DIR/colour.png, clay.png, review.json)\n raea render PAGE.html -o OUT.mp4|OUT.png|DIR [--at A,B] [--alpha] (an HTML composition)\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|OUT.wav|DIR [--audio OUT.wav] [--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] [--props JSON|P.json] [--scale S] [--hold FRAME[:FRAMES]] [--manifest render.json] [--keys keys.json] [--layers] [--stage WxH] [--10bit] [--aov] [--alpha [--alpha-codec prores|hevc|rle|png]] [--kbps N | --quality draft|high|master|0..1] [--clay] [--despite CHECK WHY] (also: --lite --comps)\n raea render EDIT.tsx --plan -o PLAN.json [--composition ID] [--props JSON|P.json] [--words W.json] [--perception P.json] (every frame through React and layout and its sounds gathered, nothing decoded, drawn or encoded: the render manifest with \"plan\": true, in seconds, for raea goal check --at edit)\n raea render EDIT.tsx --review DIR [--frame N] (fixed cameras hero, front, right, top, iso, low in colour and clay: DIR/colour.png, clay.png, review.json)\n raea render PAGE.html -o OUT.mp4|OUT.png|DIR [--at A,B] [--alpha] (an HTML composition)\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|share|lod|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 make sounds [WORDS] | sounds get PACK/INSTRUMENT [--notes ..|--all] [-o DIR] (open sample libraries for a Sampler)\n {} (the clip's camera solved, for <Matchmove>)",
|
||||
tools::sound::SAO_USAGE, tools::sound::TOKENSYNTH_USAGE, tools::song::USAGE, motion::track::USAGE
|
||||
|
||||
@@ -59,6 +59,7 @@ fn a_verb_refuses_what_it_doesnt_take() {
|
||||
&["render", "e.tsx", "-o", "o.mp4", "--frame", "20", "--input", "i.json", "--manifest", "m.json", "--stage", "1080x1920", "--words", "w.json"][..],
|
||||
&["render", "e.tsx", "-o", "d", "--at", "0,30", "--composition", "Main", "--w", "1080", "--h", "1920", "--fps", "30", "--frames", "90", "--lite"],
|
||||
&["render", "e.tsx", "-o", "o.mp4", "--kbps", "-6"],
|
||||
&["render", "edit.tsx", "--composition", "cut-a", "--plan", "-o", "out/cuts/cut-a.plan.json"],
|
||||
&["render", "--bundle", "a.comp.js", "-o", "o.png", "--dir", "d", "--frame", "3"],
|
||||
&["play", "g.tsx", "--input-script", "k.json", "--input-log", "l.json", "--offscreen", "--seconds", "end", "--size", "540x960", "--snapshot", "1.5", "a.png", "--seek", "30", "b.png", "--json", "p.json"],
|
||||
&["play", "g.tsx", "--input", "--baked", "--scrub", "8", "--autoplay", "--no-vsync", "--master", "--3d"],
|
||||
|
||||
@@ -33,6 +33,8 @@ mod bevy_frame;
|
||||
use bevy_frame::*;
|
||||
mod keys;
|
||||
mod pages;
|
||||
mod plan;
|
||||
pub use plan::plan_refused;
|
||||
use pages::*;
|
||||
mod program;
|
||||
use program::*;
|
||||
@@ -68,20 +70,30 @@ pub(crate) struct Sound {
|
||||
/// `render --keys PATH`: each frame's key written there and nothing drawn (keys.rs).
|
||||
pub(crate) static KEYS: std::sync::Mutex<Option<PathBuf>> = std::sync::Mutex::new(None);
|
||||
|
||||
/// `render --plan -o PLAN.json`: every frame stepped through React and laid out, its sounds gathered, nothing decoded,
|
||||
/// drawn or encoded; the render manifest written to MANIFEST with "plan": true (plan.rs).
|
||||
pub(crate) static PLAN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
|
||||
|
||||
/// `render --manifest PATH` (the CLI's; render_bundle keeps its signature for the iPhone): where render.json goes.
|
||||
static MANIFEST: std::sync::Mutex<Option<PathBuf>> = std::sync::Mutex::new(None);
|
||||
|
||||
/// The manifest, its folder made first (2D stills write it before their frames): the composition's length in frames
|
||||
/// (whatever was rendered of it; raea check --quick samples by it, #86), boxes as drawn, findings, sounds, and whether
|
||||
/// it drew 3D (an export in layers draws the 3D in the layer under the page, docs/layers.feature LA2a).
|
||||
fn write_manifest(cx: &mut Ctx, (w, h, fps, length): (u32, u32, f64, i64), found: Vec<raea_core_facts::Finding>, heard: impl FnOnce(&Ctx) -> Value) -> R<()> {
|
||||
fn write_manifest(cx: &mut Ctx, size: (u32, u32, f64, i64), found: Vec<raea_core_facts::Finding>, heard: impl FnOnce(&Ctx) -> Value) -> R<()> {
|
||||
write_manifest_with(cx, size, found, heard, |_| {})
|
||||
}
|
||||
|
||||
/// write_manifest, with `more` given the document before it's written (a plan's own fields, plan.rs).
|
||||
fn write_manifest_with(cx: &mut Ctx, (w, h, fps, length): (u32, u32, f64, i64), found: Vec<raea_core_facts::Finding>, heard: impl FnOnce(&Ctx) -> Value, more: impl FnOnce(&mut Value)) -> R<()> {
|
||||
let (Some(path), Some(frames)) = (MANIFEST.lock().unwrap().clone(), cx.manifest.take()) else { return Ok(()) };
|
||||
path.parent().map_or(Ok(()), std::fs::create_dir_all).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
path.parent().filter(|d| !d.as_os_str().is_empty()).map_or(Ok(()), std::fs::create_dir_all).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
let mut v = json!({"width": w, "height": h, "fps": fps, "length": length, "frames": frames, "findings": raea_core_facts::finding::ranked(found), "sounds": heard(cx), "not_applied": not_applied::seen(), "layers": raea_sys_layers::finish(fps), "has3d": cx.scene3d.is_some() || cx.live3d.is_some()});
|
||||
// the parts SG9 needs (scene.rs's SEEN: stills' parts on screen, a longer render's remounts), and --props and --scale
|
||||
for more in [scene::SEEN.lock().unwrap().take(), GIVEN.lock().unwrap().clone()] {
|
||||
v.as_object_mut().into_iter().zip(more.and_then(|m| m.as_object().cloned())).for_each(|(m, more)| m.extend(more));
|
||||
for given in [scene::SEEN.lock().unwrap().take(), GIVEN.lock().unwrap().clone()] {
|
||||
v.as_object_mut().into_iter().zip(given.and_then(|m| m.as_object().cloned())).for_each(|(m, given)| m.extend(given));
|
||||
}
|
||||
more(&mut v);
|
||||
std::fs::write(&path, v.to_string()).map_err(|e| format!("{}: {e}", path.display()))
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
//! `render --plan -o PLAN.json`: what a render would show and play, frame by frame, with nothing drawn. React is stepped
|
||||
//! through every frame as a render steps it, the page made to match each frame's tree and laid out (styles, fonts,
|
||||
//! layout: Blitz's main world, never its render world), and each frame's sounds gathered as a render gathers them, but
|
||||
//! no video's frame is decoded (the page syncs as `render --keys` does), nothing is painted and nothing is encoded.
|
||||
//!
|
||||
//! PLAN.json is the render manifest (`render --manifest`): width, height, fps, length, a frame entry for every frame of
|
||||
//! the composition (its videos' sources, times and boxes, its text's words, boxes and sizes, its pictures), the sounds
|
||||
//! heard (each clip's source, in point and frames), with "plan": true and whether a frame holds 3D. What a render's
|
||||
//! manifest says that only drawing finds isn't in it: its exposure, its 3D's clipping and its layers (null).
|
||||
//!
|
||||
//! It is the edit moment's input (`raea goal check --at edit --manifest PLAN.json`): a cut's text in a UI zone, a
|
||||
//! clip's in point inside a word, a caption over a face are known from it before any frame is drawn. A 32 s cut (952
|
||||
//! frames at 1080x1920, 5 clips of one interview, a caption a line) is planned in 4 s on a raea cloud box's 8 CPUs (8 s
|
||||
//! with nothing cached), where its render took 130 s on the same box and 152 s on the farm's 32 CPU containers; the
|
||||
//! plan's frames and sounds are the render's own manifest's, box for box (12-04, on three projects' cuts).
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Why `--plan` can't be taken with the other flags in `args`, or None. A plan is every frame of the composition, has
|
||||
/// no picture, and is written where -o says.
|
||||
pub fn plan_refused(args: &[String]) -> Option<String> {
|
||||
if !args.iter().any(|a| a == "--plan") {
|
||||
return None;
|
||||
}
|
||||
for f in ["--frame", "--at", "--keys", "--review", "--hold", "--aov", "--alpha", "--layers", "--audio", "--bundle"] {
|
||||
if args.iter().any(|a| a == f) {
|
||||
return Some(format!("--plan lays out every frame of the composition and draws none, so it doesn't take {f}"));
|
||||
}
|
||||
}
|
||||
let out = flag(args, "-o");
|
||||
if !out.as_deref().is_some_and(|o| o.to_lowercase().ends_with(".json")) {
|
||||
return Some("--plan writes the render manifest of every frame: -o PLAN.json".into());
|
||||
}
|
||||
if flag(args, "--manifest").is_some_and(|m| Some(&m) != out.as_ref()) {
|
||||
return Some("--plan writes its manifest where -o says (PLAN.json): leave --manifest out".into());
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub(crate) fn write(app: &mut App, page: &mut raea_runtime_page::BevyPage, cx: &mut Ctx, (w, h, fps, total): (u32, u32, f64, i64)) -> R<String> {
|
||||
let t0 = std::time::Instant::now();
|
||||
// a keyed sync places no video's frame: nothing decoded (bevy_page.rs)
|
||||
page.keyed = Some(0);
|
||||
let (mut frames, mut tones) = (Vec::with_capacity(total.max(0) as usize), Vec::new());
|
||||
let mut has3d = false;
|
||||
// RAEA_TIMES: where the plan's time goes, totals in ms
|
||||
let times = raea_io_trace::stat("RAEA_TIMES");
|
||||
let (mut t_react, mut t_sync, mut t_lay) = (0f64, 0f64, 0f64);
|
||||
for f in 0..total {
|
||||
let a = std::time::Instant::now();
|
||||
step_react(app, page, cx, (f, fps), true)?;
|
||||
let b = std::time::Instant::now();
|
||||
page.at_frame(f, fps);
|
||||
bevy_page_sync(app.world_mut(), page, cx)?;
|
||||
let c = std::time::Instant::now();
|
||||
page.lay_out();
|
||||
if let Some(m) = cx.manifest.as_mut() {
|
||||
m.push(page.manifest_frame(f));
|
||||
}
|
||||
has3d |= !cx.scene.is_empty();
|
||||
tones.push(raea_runtime_sound::tone_at(app.world_mut(), f, fps, cx.dir, media_path, true));
|
||||
frames.push((f, Frame { mix: cx.mix, page: None, sounds: cx.sounds.clone(), scene: Vec::new(), clear: None, same: false, screens: Vec::new() }));
|
||||
if times {
|
||||
t_react += (b - a).as_secs_f64() * 1e3;
|
||||
t_sync += (c - b).as_secs_f64() * 1e3;
|
||||
t_lay += c.elapsed().as_secs_f64() * 1e3;
|
||||
}
|
||||
}
|
||||
if times {
|
||||
eprintln!("raea times: react {t_react:.0} ms, page synced {t_sync:.0} ms, laid out and read {t_lay:.0} ms over {total} frames");
|
||||
}
|
||||
let to = MANIFEST.lock().unwrap().clone().ok_or("--plan: no -o PLAN.json")?;
|
||||
write_manifest_with(cx, (w, h, fps, total), Vec::new(), |cx| heard(&frames, &tones, cx, fps), |v| mark(v, has3d))?;
|
||||
Ok(format!("APPLIED {total} frames planned in {} (laid out with nothing drawn, {:.1} s)", to.display(), t0.elapsed().as_secs_f64()))
|
||||
}
|
||||
|
||||
/// A manifest made a plan: "plan": true, and whether any frame holds 3D (the plan draws none, so the manifest's own
|
||||
/// "has3d", the drawn 3D's, would say no). Its other keys stay as a render's manifest has them.
|
||||
fn mark(v: &mut Value, has3d: bool) {
|
||||
if let Some(o) = v.as_object_mut() {
|
||||
o.insert("plan".into(), json!(true));
|
||||
o.insert("has3d".into(), json!(has3d));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn a(s: &[&str]) -> Vec<String> {
|
||||
s.iter().map(|a| a.to_string()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plan_is_every_frame_written_where_o_says() {
|
||||
assert_eq!(plan_refused(&a(&["render", "e.tsx", "--composition", "c", "--plan", "-o", "out/c.plan.json"])), None);
|
||||
assert_eq!(plan_refused(&a(&["render", "e.tsx", "--plan", "-o", "p.json", "--manifest", "p.json", "--props", "{}"])), None);
|
||||
// not a plan: nothing to refuse
|
||||
assert_eq!(plan_refused(&a(&["render", "e.tsx", "--at", "3", "-o", "d/"])), None);
|
||||
assert!(plan_refused(&a(&["render", "e.tsx", "--plan", "-o", "c.mp4"])).unwrap().contains("-o PLAN.json"));
|
||||
assert!(plan_refused(&a(&["render", "e.tsx", "--plan"])).unwrap().contains("-o PLAN.json"));
|
||||
assert!(plan_refused(&a(&["render", "e.tsx", "--plan", "--at", "0,30", "-o", "p.json"])).unwrap().contains("--at"));
|
||||
assert!(plan_refused(&a(&["render", "e.tsx", "--plan", "--keys", "k.json", "-o", "p.json"])).unwrap().contains("--keys"));
|
||||
assert!(plan_refused(&a(&["render", "e.tsx", "--plan", "-o", "p.json", "--manifest", "m.json"])).unwrap().contains("--manifest"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plan_says_so_in_the_manifests_own_shape() {
|
||||
let mut v = json!({"width": 1080, "height": 1920, "fps": 30.0, "length": 2, "frames": [{"frame": 0}, {"frame": 1}], "has3d": false, "layers": null, "sounds": {"clips": []}});
|
||||
mark(&mut v, true);
|
||||
assert_eq!(v["plan"], true);
|
||||
assert_eq!(v["has3d"], true);
|
||||
// every key a render's manifest has stays, so a reader of one reads the other
|
||||
for k in ["width", "height", "fps", "length", "frames", "layers", "sounds"] {
|
||||
assert!(v.get(k).is_some(), "{k}");
|
||||
}
|
||||
assert_eq!(v["frames"].as_array().unwrap().len(), 2);
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,9 @@ pub fn render(args: &[String]) -> R<String> {
|
||||
if args.iter().any(|a| a == "--clay") {
|
||||
raea_runtime_scene3d::clay::CLAY.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
if let Some(why) = plan_refused(args) {
|
||||
return Err(why);
|
||||
}
|
||||
let tsx = dunce::canonicalize(&PathBuf::from(&args[1])).map_err(|e| format!("{}: {e}", args[1]))?;
|
||||
let out = PathBuf::from(flag(args, "-o").ok_or("-o OUT.mp4|OUT.png|DIR")?);
|
||||
let dir = tsx.parent().unwrap().to_path_buf();
|
||||
@@ -65,6 +68,15 @@ pub fn render(args: &[String]) -> R<String> {
|
||||
(_, Some(at)) => Some(at.split(',').map(|f| f.trim().parse::<i64>().map_err(|_| "--at takes frame numbers".to_string())).collect::<R<_>>()?),
|
||||
_ => None,
|
||||
};
|
||||
// --plan: every frame laid out and its sounds gathered, nothing decoded, drawn or encoded; the manifest at -o (plan.rs)
|
||||
if args.iter().any(|a| a == "--plan") {
|
||||
*MANIFEST.lock().unwrap() = Some(out.clone());
|
||||
PLAN.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
let said = render_bundle_with(&js, &dir, &out, None, false, None, false);
|
||||
PLAN.store(false, std::sync::atomic::Ordering::Relaxed);
|
||||
let _ = std::fs::remove_file(&js);
|
||||
return said;
|
||||
}
|
||||
if let Some(k) = flag(args, "--keys") {
|
||||
*KEYS.lock().unwrap() = Some(PathBuf::from(k));
|
||||
let said = render_bundle_with(&js, &dir, &out, None, false, None, false);
|
||||
@@ -306,6 +318,9 @@ pub(crate) fn render_bundle_with(js: &Path, dir: &Path, out: &Path, wanted: Opti
|
||||
if let Some(to) = KEYS.lock().unwrap().take() {
|
||||
return crate::keys::write(&to, &mut app, &mut page, &mut cx, (w, h, fps, total));
|
||||
}
|
||||
if PLAN.load(std::sync::atomic::Ordering::Relaxed) {
|
||||
return crate::plan::write(&mut app, &mut page, &mut cx, (w, h, fps, total));
|
||||
}
|
||||
if fed {
|
||||
if let Some(p) = scene {
|
||||
aov_on(raea_render::engine::Engine::open_in(&mut cx.scene3d, &p, dir)?);
|
||||
|
||||
@@ -50,11 +50,6 @@ ARG AGENTS="antigravity-acp claude-acp kimi-code"
|
||||
RUN node server/agents.ts install $AGENTS
|
||||
COPY src src
|
||||
COPY image image
|
||||
# raea's SDK files fixed after the release the image installs (image/sdk-overlay, by their path under share/raea/sdk),
|
||||
# each only while the installed file still has the fault, so a release with the fix keeps its own. 12-03: 0.1.17-rc4's
|
||||
# goal.ts named-imports spawn, which raea's runtime hasn't got, and every raea goal check on a box died (raea #329)
|
||||
RUN f=/opt/raea/share/raea/sdk/goal/src/packs/goal.ts; \
|
||||
if grep -q 'import { spawn } from "node:child_process"' "$f"; then cp image/sdk-overlay/goal/src/packs/goal.ts "$f" && echo "overlay: goal.ts"; fi
|
||||
COPY deploy/git deploy/git
|
||||
COPY deploy/fly/start.sh image/fly-start.sh
|
||||
# readable by raea whatever modes the files had where the image was built (12-03: a checkout made with umask 077 gave
|
||||
|
||||
@@ -2,6 +2,10 @@
|
||||
# raea in raea cloud's image (docs/cloud.feature CL15): with RAEA_CLOUD_GPU_URL set, `raea render ...` (each command in
|
||||
# RAEA_CLOUD_GPU_COMMANDS) goes to that GPU worker (server/offload.ts); everything else, and everything when it isn't
|
||||
# set, is raea itself. The server, the agents and their shells all reach raea through this one.
|
||||
# A render's plan (`raea render EDIT.tsx --plan -o PLAN.json`) draws nothing: it runs here, on the box's CPU, in seconds.
|
||||
for a in "$@"; do
|
||||
[ "$a" = "--plan" ] && exec /opt/raea/bin/raea "$@"
|
||||
done
|
||||
if [ -n "${RAEA_CLOUD_GPU_URL:-}" ] && [ -n "${1:-}" ]; then
|
||||
case " ${RAEA_CLOUD_GPU_COMMANDS:-render} " in
|
||||
*" $1 "*) exec node /opt/raea-cloud/server/offload.ts "$@" ;;
|
||||
|
||||
@@ -1,312 +0,0 @@
|
||||
// The rule packs (MK29, MK38; Rust's goal gates until 11-29, now here alone): any goal held to its rules,
|
||||
// from what's on disk and what a fresh critic said, never from the agent that did the work (11-26, Shane: "it can't
|
||||
// stop unless all the goals pass").
|
||||
// run the command exits 0 in the brief's folder, within its timeout (300 s by default), run again each time
|
||||
// says a fresh critic (`raea goal judge`) found it true of the work, after the work's last change
|
||||
// (file rules are deliverables: the deliverables pack holds them)
|
||||
// The critic's verdict is review/judge/NAME.json (the goal's name): {at, by, goal, rules: {ID: {pass, why}}}.
|
||||
// a namespace import: raea's own runtime (engine/native/src/node.js) has spawnSync and no spawn, and a named import of
|
||||
// spawn failed the whole module there, so every `raea goal check` on a box died before it read a file (12-03, raea
|
||||
// 0.1.17-rc4: no StreetTalk cut could publish)
|
||||
import * as cp from "node:child_process"
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"
|
||||
import path from "node:path"
|
||||
import { check, found } from "raea/check"
|
||||
import { type Contract, nameOf, type Said, saysOf } from "../contract.ts"
|
||||
import type { Job } from "../facts.ts"
|
||||
import { RAEA } from "../media.ts"
|
||||
|
||||
/** where a goal's critic verdict is kept, relative to the brief */
|
||||
export const verdictPath = (g: Contract) => `review/judge/${nameOf(g)}.json`
|
||||
export const TIMEOUT = 300
|
||||
/** folders that aren't the work: what the job writes about itself, and what tools keep */
|
||||
const NOT_WORK = new Set(["review", ".git", "node_modules", ".raea", "target", ".cache", ".raea-cloud"])
|
||||
|
||||
/** what a check keeps beside a file it read (its report, its words, its scene): a reading of the work, not a change
|
||||
* to it. A done check that heard a cut's words wrote them beside it, and the critic's verdict of a minute before read
|
||||
* as older than the work (12-01) */
|
||||
const READING = /\.(check|words|scene|floor|montage)\.json$/
|
||||
|
||||
/** when the work last changed (ms): the newest file under dir, its own bookkeeping left out (a bounded walk) */
|
||||
export function newest(dir: string): number | null {
|
||||
let best: number | null = null
|
||||
const stack = [dir]
|
||||
let seen = 0
|
||||
while (stack.length) {
|
||||
const d = stack.pop()!
|
||||
let names: string[] = []
|
||||
try {
|
||||
names = readdirSync(d)
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
for (const name of names) {
|
||||
if (++seen > 20_000) return best
|
||||
const p = path.join(d, name)
|
||||
let st
|
||||
try {
|
||||
st = statSync(p)
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
if (st.isDirectory()) {
|
||||
if (!(d === dir && NOT_WORK.has(name)) && name !== "node_modules" && name !== ".git") stack.push(p)
|
||||
} else if (st.isFile() && name !== "NOTES.md" && !READING.test(name)) best = Math.max(best ?? 0, st.mtimeMs)
|
||||
}
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
type Verdict = { at: number; by: string; goal?: string; rules: Record<string, { pass: boolean; why: string } | undefined> }
|
||||
export function verdict(dir: string, g: Contract): Verdict | null {
|
||||
try {
|
||||
return JSON.parse(readFileSync(path.join(dir, verdictPath(g)), "utf8")) as Verdict
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
const goalOf = (j: Job): Contract | null => j.contract
|
||||
|
||||
export const runPack = check<Job>({ id: "run", text: "each command rule exits 0", over: "job", at: ["done"] }, async (j) => {
|
||||
for (const r of goalOf(j)?.rules ?? []) {
|
||||
if (!r.run) continue
|
||||
const { ok, said } = await j.run(r.run, r.timeout ?? TIMEOUT)
|
||||
if (!ok) found({ says: `${r.id}: \`${r.run}\` ${said}`, about: [r.id] })
|
||||
}
|
||||
})
|
||||
|
||||
export const saysPack = check<Job>({ id: "says", text: "each `says` rule found true by a fresh critic after the work's last change", over: "job", at: ["done"] }, async (j) => {
|
||||
const says = saysOf(goalOf(j) ?? null)
|
||||
if (!says.length) return
|
||||
let v = verdict(j.root, j.contract!)
|
||||
// at whole seconds, as the verdict keeps its time: work saved in the second the critic was asked counts as judged
|
||||
const freshOf = (x: Verdict | null) => !!x && (newest(j.root) === null || x.at >= Math.floor(newest(j.root)! / 1000))
|
||||
// a verdict missing, stale or short of a rule is asked for here (the check is the one command; the agent never
|
||||
// judges by hand), where this session has a critic to ask
|
||||
if (!(freshOf(v) && says.every((r) => v!.rules?.[r.id])) && hasCritic(j.root, says)) {
|
||||
try {
|
||||
v = await judge(j.contract!, j.root)
|
||||
} catch (e) {
|
||||
found({ says: `the critic couldn't judge: ${(e as Error).message}` })
|
||||
return
|
||||
}
|
||||
}
|
||||
const fresh = freshOf(v)
|
||||
for (const r of says) {
|
||||
const one = v?.rules?.[r.id]
|
||||
const fix = NO_CRITIC
|
||||
if (!v) found({ says: `${r.id}: not judged yet`, about: [r.id], fix })
|
||||
else if (!one) found({ says: `${r.id}: the last judging didn't cover it`, about: [r.id], fix })
|
||||
else if (!fresh) found({ says: `${r.id}: the work changed after the critic judged it`, about: [r.id], fix })
|
||||
else if (!one.pass) found({ says: `${r.id}: a fresh critic found it not true yet: ${one.why}`, about: [r.id] })
|
||||
}
|
||||
})
|
||||
|
||||
/** what the critic is asked: the goal, each `says` rule by id, and the answer's shape. It reads; it changes nothing */
|
||||
export function prompt(g: Contract, dir: string, only: Said[] = saysOf(g)): string {
|
||||
const rules = only.map((r) => `- ${r.id}: ${r.says}`)
|
||||
return `You are a fresh critic. You did none of this work and owe it nothing. The work is in ${dir}: read whatever you need there (its files, its renders, NOTES.md), and change nothing.\n\nThe goal, as the person said it: ${g.aim ?? nameOf(g)}\n\nFor each rule below, decide whether it is true of the work as it is on disk now. Count it true only when you have seen it hold; if you can't tell, it isn't true yet. Say why in one sentence, naming what you looked at.\n\n${rules.join("\n")}\n\nAnswer last with one JSON object and nothing after it: {"rules": {"ID": {"pass": true, "why": "..."}}}`
|
||||
}
|
||||
|
||||
/** the verdict: the object around the text's last "rules" key (a critic may think aloud, or quote the shape, first) */
|
||||
export function lastVerdict(text: string): Verdict | null {
|
||||
const key = text.lastIndexOf('"rules"')
|
||||
if (key < 0) return null
|
||||
for (let open = text.lastIndexOf("{", key); open >= 0; open = text.lastIndexOf("{", open - 1)) {
|
||||
let depth = 0
|
||||
let inStr = false
|
||||
for (let i = open; i < text.length; i++) {
|
||||
const ch = text[i]
|
||||
if (inStr) {
|
||||
if (ch === "\\") i++
|
||||
else if (ch === '"') inStr = false
|
||||
continue
|
||||
}
|
||||
if (ch === '"') inStr = true
|
||||
else if (ch === "{") depth++
|
||||
else if (ch === "}" && --depth === 0) {
|
||||
try {
|
||||
const v = JSON.parse(text.slice(open, i + 1))
|
||||
if (v && typeof v.rules === "object") return v
|
||||
} catch {}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** where a rule is judged, chosen here and never by the agent (Shane, 12-03): a rule with a piece to watch or hear
|
||||
* (a file it names, or the videos under out/) by Clef-Omni; any other by a fresh session of the agent this project
|
||||
* runs on, which the host that started the agent offers as RAEA_JUDGE_URL (raea cloud's box, critic.ts; the raea app) */
|
||||
const criticUrl = () => process.env.RAEA_JUDGE_URL || null
|
||||
export const NO_CRITIC = "it's judged by a fresh session of the agent this project runs on, which only an agent session the raea app or raea cloud started has: it's judged when that session checks the goal"
|
||||
/** whether every rule here can be judged in this session */
|
||||
export function hasCritic(dir: string, rules: Said[]): boolean {
|
||||
return !!criticUrl() || rules.every((r) => piecesOf(r, dir).length > 0)
|
||||
}
|
||||
const PIECE = /[\w@./-]+\.(?:mp4|mov|webm|m4v|png|jpe?g|webp|wav|mp3|m4a)\b/gi
|
||||
const VIDEO = /\.(?:mp4|mov|webm|m4v)$/i
|
||||
/** the videos under out/, newest first */
|
||||
function made(dir: string): string[] {
|
||||
const out: { f: string; at: number }[] = []
|
||||
const walk = (d: string) => {
|
||||
for (const e of existsSync(d) ? readdirSync(d, { withFileTypes: true }) : []) {
|
||||
const f = path.join(d, e.name)
|
||||
if (e.isDirectory()) walk(f)
|
||||
else if (VIDEO.test(e.name)) out.push({ f, at: statSync(f).mtimeMs })
|
||||
}
|
||||
}
|
||||
walk(path.join(dir, "out"))
|
||||
return out.sort((x, y) => y.at - x.at).map((x) => path.relative(dir, x.f))
|
||||
}
|
||||
/** clef-omni as the critic (`raea ask`, paid as ask is): it watches and hears a piece, and reads no folder. A rule is
|
||||
* asked of the files it names, in its "from A s to B s" window if it has one, else of every video under out/ (the
|
||||
* newest CLEF_PIECES), and passes when it's true of each; the rules about one piece go in one call */
|
||||
const CLEF_PIECES = 12
|
||||
/** the pieces a rule is about: the files it names that are on disk, else the newest videos under out/ */
|
||||
function piecesOf(r: Said, dir: string): string[] {
|
||||
const named = [...new Set(r.says.match(PIECE) ?? [])].filter((f) => existsSync(path.join(dir, f)))
|
||||
return named.length ? named : made(dir).slice(0, CLEF_PIECES)
|
||||
}
|
||||
/** how many `raea ask`s run at once: each is one cut (or one stretch of it) heard and watched; one after another, a
|
||||
* project's beats took 6-17 minutes of every goal check (12-03, StreetTalk: 18 of them, a cut's beats each a stretch) */
|
||||
export const CLEF_AT_ONCE = 6
|
||||
|
||||
/** `f` on each item, at most `n` at once, the answers in the items' order */
|
||||
async function pool<T, R>(items: T[], n: number, f: (t: T) => Promise<R>): Promise<R[]> {
|
||||
const out: R[] = new Array(items.length)
|
||||
let next = 0
|
||||
const worker = async () => {
|
||||
for (let i = next++; i < items.length; i = next++) out[i] = await f(items[i])
|
||||
}
|
||||
await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker))
|
||||
return out
|
||||
}
|
||||
|
||||
export async function clefVerdict(g: Contract, dir: string, ask: Ask = askClef, only: Said[] = saysOf(g)): Promise<Verdict["rules"]> {
|
||||
const groups = new Map<string, { file: string; from?: string; to?: string; rules: Said[] }>()
|
||||
const pieces = new Map<string, string[]>()
|
||||
for (const r of only) {
|
||||
const files = piecesOf(r, dir)
|
||||
const w = /from (\d+(?:\.\d+)?) s to (?:(\d+(?:\.\d+)?) s|its end)/.exec(r.says)
|
||||
pieces.set(r.id, files)
|
||||
for (const file of files) {
|
||||
const key = [file, w?.[1], w?.[2]].join("\u001f")
|
||||
const at = groups.get(key) ?? { file, from: w?.[1], to: w?.[2], rules: [] }
|
||||
at.rules.push(r)
|
||||
groups.set(key, at)
|
||||
}
|
||||
}
|
||||
const got = new Map<string, { pass: boolean; why: string }[]>()
|
||||
const list = [...groups.values()]
|
||||
const heard = ask === askClef && !asyncSpawn()
|
||||
? askClefMany(dir, list.map((k) => ({ file: k.file, says: k.rules.map((r) => r.says), from: k.from, to: k.to })))
|
||||
: await pool(list, CLEF_AT_ONCE, async (k) => ask(dir, k.file, k.rules.map((r) => r.says), k.from, k.to))
|
||||
for (const [j, k] of list.entries()) {
|
||||
const answers = heard[j]
|
||||
k.rules.forEach((r, i) => got.set(r.id, [...(got.get(r.id) ?? []), { pass: answers[i]?.choice === "true" && !answers[i]?.problem, why: `${k.file}: ${answers[i]?.problem ?? answers[i]?.says ?? "no answer"}` }]))
|
||||
}
|
||||
const rules: Verdict["rules"] = {}
|
||||
for (const r of only) {
|
||||
const a = got.get(r.id) ?? []
|
||||
const open = a.filter((x) => !x.pass)
|
||||
rules[r.id] = !pieces.get(r.id)?.length
|
||||
? { pass: false, why: "it names no file on disk and out/ holds no video yet, so there's nothing to watch or hear" }
|
||||
: { pass: !open.length, why: (open.length ? open : a).map((x) => x.why).join("; ") }
|
||||
}
|
||||
return rules
|
||||
}
|
||||
type Answer = { choice?: string; says?: string; problem?: string | null }
|
||||
type Ask = (dir: string, file: string, says: string[], from?: string, to?: string) => Answer[] | Promise<Answer[]>
|
||||
const askArgs = (file: string, says: string[], from?: string, to?: string) => ["ask", file, ...says, "--choose", "true,false", "--json", ...(from ? ["--from", from] : []), ...(to ? ["--to", to] : [])]
|
||||
const rowsOf = (out: string) => out.split("\n").flatMap((l) => { try { const o = JSON.parse(l); return o.answer ? [o as Answer] : [] } catch { return [] } })
|
||||
/** whether this runtime has an async spawn (raea's own has only spawnSync) */
|
||||
const asyncSpawn = () => typeof (cp as { spawn?: unknown }).spawn === "function"
|
||||
/** every ask at once where there's no async spawn (raea's runtime): one shell runs them CLEF_AT_ONCE at a time, each
|
||||
* into its own file under review/ (12-04, StreetTalk round 18: asked one after another, a stop's 18 beats took 7.7 of
|
||||
* its 10.5 minutes) */
|
||||
export function askClefMany(dir: string, jobs: { file: string; says: string[]; from?: string; to?: string }[]): Answer[][] {
|
||||
if (!jobs.length) return []
|
||||
const tmp = path.join(dir, "review", `.ask-${process.pid}-${Date.now()}`)
|
||||
mkdirSync(tmp, { recursive: true })
|
||||
const sq = (t: string) => `'${t.replace(/'/g, `'\\''`)}'`
|
||||
const lines = jobs.map((k, i) => `${[RAEA, ...askArgs(k.file, k.says, k.from, k.to)].map(sq).join(" ")} > ${sq(`${tmp}/${i}.out`)} 2> ${sq(`${tmp}/${i}.err`)} &${(i + 1) % CLEF_AT_ONCE === 0 ? "\nwait" : ""}`)
|
||||
try {
|
||||
const r = cp.spawnSync("sh", ["-c", [...lines, "wait"].join("\n")], { cwd: dir, encoding: "utf8" }) as { error?: Error }
|
||||
if (r.error) throw new Error(`couldn't run raea ask: ${r.error.message}`)
|
||||
const read = (f: string) => (existsSync(f) ? String(readFileSync(f, "utf8")) : "")
|
||||
return jobs.map((k, i) => {
|
||||
const rows = rowsOf(read(`${tmp}/${i}.out`))
|
||||
if (rows.length !== k.says.length) throw new Error(`raea ask answered ${rows.length} of ${k.says.length} about ${k.file}: ${read(`${tmp}/${i}.err`).trim().slice(-300) || read(`${tmp}/${i}.out`).trim().slice(-300)}`)
|
||||
return rows
|
||||
})
|
||||
} finally {
|
||||
rmSync(tmp, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
/** `raea ask` on one file (or a stretch of it): run as a child, so several hear at once */
|
||||
function askClef(dir: string, file: string, says: string[], from?: string, to?: string): Promise<Answer[]> {
|
||||
const args = askArgs(file, says, from, to)
|
||||
// where there's no async spawn (raea's runtime), one at a time (clefVerdict asks them all at once: askClefMany)
|
||||
if (!asyncSpawn()) {
|
||||
const r = cp.spawnSync(RAEA, args, { cwd: dir, encoding: "utf8" }) as { stdout?: string; stderr?: string; error?: Error }
|
||||
if (r.error) return Promise.reject(new Error(`couldn't run raea ask: ${r.error.message}`))
|
||||
const rows = rowsOf(String(r.stdout ?? ""))
|
||||
if (rows.length !== says.length) return Promise.reject(new Error(`raea ask answered ${rows.length} of ${says.length} about ${file}: ${String(r.stderr ?? "").trim().slice(-300) || String(r.stdout ?? "").trim().slice(-300)}`))
|
||||
return Promise.resolve(rows)
|
||||
}
|
||||
return new Promise((ok, no) => {
|
||||
const c = cp.spawn(RAEA, args, { cwd: dir, stdio: ["ignore", "pipe", "pipe"] })
|
||||
let out = "", err = ""
|
||||
c.stdout.setEncoding("utf8").on("data", (t: string) => (out += t))
|
||||
c.stderr.setEncoding("utf8").on("data", (t: string) => (err = (err + t).slice(-4000)))
|
||||
c.on("error", (e) => no(new Error(`couldn't run raea ask: ${e.message}`)))
|
||||
c.on("close", () => {
|
||||
const rows = rowsOf(out)
|
||||
if (rows.length !== says.length) return no(new Error(`raea ask answered ${rows.length} of ${says.length} about ${file}: ${err.trim().slice(-300) || out.trim().slice(-300)}`))
|
||||
ok(rows)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/** the goal's `says` rules judged (`raea goal check` asks this itself; `raea goal judge` too): each where it's judged
|
||||
* (criticUrl above), its verdict kept at review/judge/NAME.json, stamped with when it was asked (so work changed while
|
||||
* it judged counts as changed after) */
|
||||
export async function judge(g: Contract, dir: string, o: { ask?: typeof askClef; agent?: (cwd: string, prompt: string) => Promise<string> } = {}): Promise<Verdict> {
|
||||
const all = saysOf(g)
|
||||
if (!all.length) throw new Error(`goal ${nameOf(g)} has no \`says\` rules; its \`run\` and \`file\` rules are held by raea goal check`)
|
||||
const asked = Math.floor(Date.now() / 1000)
|
||||
const watched = all.filter((r) => piecesOf(r, dir).length > 0)
|
||||
const read = all.filter((r) => !watched.includes(r))
|
||||
// what's watched and heard, and what's read, at once: neither waits on the other
|
||||
const [heard, said] = await Promise.all([
|
||||
watched.length ? clefVerdict(g, dir, o.ask ?? askClef, watched) : Promise.resolve({} as Verdict["rules"]),
|
||||
read.length ? (o.agent ?? askAgent)(dir, prompt(g, dir, read)) : Promise.resolve(null),
|
||||
])
|
||||
const rules: Verdict["rules"] = { ...heard }
|
||||
if (said !== null) {
|
||||
const v = lastVerdict(said)
|
||||
if (!v) throw new Error(`the critic gave no verdict: ${said.slice(-300).trim()}`)
|
||||
for (const r of read) rules[r.id] = v.rules?.[r.id] ?? { pass: false, why: "the critic didn't answer this rule" }
|
||||
}
|
||||
return keep(g, dir, { at: asked, by: [watched.length ? "clef" : "", read.length ? "agent" : ""].filter(Boolean).join("+"), goal: g.aim ?? nameOf(g), rules })
|
||||
}
|
||||
/** a fresh session of this project's own agent, through the host that started it (RAEA_JUDGE_URL): what it says */
|
||||
async function askAgent(cwd: string, p: string): Promise<string> {
|
||||
const url = criticUrl()
|
||||
if (!url) throw new Error(NO_CRITIC)
|
||||
const r = await fetch(url, { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${process.env.RAEA_JUDGE_TOKEN ?? ""}` }, body: JSON.stringify({ cwd, prompt: p }), signal: AbortSignal.timeout(15 * 60_000) })
|
||||
const j = (await r.json().catch(() => ({}))) as { text?: string; error?: string }
|
||||
if (!r.ok || typeof j.text !== "string") throw new Error(j.error ?? `the critic answered ${r.status}`)
|
||||
return j.text
|
||||
}
|
||||
function keep(g: Contract, dir: string, out: Verdict): Verdict {
|
||||
const file = path.join(dir, verdictPath(g))
|
||||
mkdirSync(path.dirname(file), { recursive: true })
|
||||
writeFileSync(file, `${JSON.stringify(out, null, 2)}\n`)
|
||||
return out
|
||||
}
|
||||
|
||||
export const hasVerdict = (dir: string, g: Contract) => existsSync(path.join(dir, verdictPath(g)))
|
||||
@@ -5,11 +5,8 @@
|
||||
// says a fresh critic (`raea goal judge`) found it true of the work, after the work's last change
|
||||
// (file rules are deliverables: the deliverables pack holds them)
|
||||
// The critic's verdict is review/judge/NAME.json (the goal's name): {at, by, goal, rules: {ID: {pass, why}}}.
|
||||
// a namespace import: raea's own runtime (engine/native/src/node.js) has spawnSync and no spawn, and a named import of
|
||||
// spawn failed the whole module there, so every `raea goal check` on a box died before it read a file (12-03, raea
|
||||
// 0.1.17-rc4: no StreetTalk cut could publish)
|
||||
import * as cp from "node:child_process"
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"
|
||||
import { spawn } from "node:child_process"
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"
|
||||
import path from "node:path"
|
||||
import { check, found } from "raea/check"
|
||||
import { type Contract, nameOf, type Said, saysOf } from "../contract.ts"
|
||||
@@ -201,9 +198,7 @@ export async function clefVerdict(g: Contract, dir: string, ask: Ask = askClef,
|
||||
}
|
||||
const got = new Map<string, { pass: boolean; why: string }[]>()
|
||||
const list = [...groups.values()]
|
||||
const heard = ask === askClef && !asyncSpawn()
|
||||
? askClefMany(dir, list.map((k) => ({ file: k.file, says: k.rules.map((r) => r.says), from: k.from, to: k.to })))
|
||||
: await pool(list, CLEF_AT_ONCE, async (k) => ask(dir, k.file, k.rules.map((r) => r.says), k.from, k.to))
|
||||
const heard = await pool(list, CLEF_AT_ONCE, async (k) => ask(dir, k.file, k.rules.map((r) => r.says), k.from, k.to))
|
||||
for (const [j, k] of list.entries()) {
|
||||
const answers = heard[j]
|
||||
k.rules.forEach((r, i) => got.set(r.id, [...(got.get(r.id) ?? []), { pass: answers[i]?.choice === "true" && !answers[i]?.problem, why: `${k.file}: ${answers[i]?.problem ?? answers[i]?.says ?? "no answer"}` }]))
|
||||
@@ -220,51 +215,16 @@ export async function clefVerdict(g: Contract, dir: string, ask: Ask = askClef,
|
||||
}
|
||||
type Answer = { choice?: string; says?: string; problem?: string | null }
|
||||
type Ask = (dir: string, file: string, says: string[], from?: string, to?: string) => Answer[] | Promise<Answer[]>
|
||||
const askArgs = (file: string, says: string[], from?: string, to?: string) => ["ask", file, ...says, "--choose", "true,false", "--json", ...(from ? ["--from", from] : []), ...(to ? ["--to", to] : [])]
|
||||
const rowsOf = (out: string) => out.split("\n").flatMap((l) => { try { const o = JSON.parse(l); return o.answer ? [o as Answer] : [] } catch { return [] } })
|
||||
/** whether this runtime has an async spawn (raea's own has only spawnSync) */
|
||||
const asyncSpawn = () => typeof (cp as { spawn?: unknown }).spawn === "function"
|
||||
/** every ask at once where there's no async spawn (raea's runtime): one shell runs them CLEF_AT_ONCE at a time, each
|
||||
* into its own file under review/ (12-04, StreetTalk round 18: asked one after another, a stop's 18 beats took 7.7 of
|
||||
* its 10.5 minutes) */
|
||||
export function askClefMany(dir: string, jobs: { file: string; says: string[]; from?: string; to?: string }[]): Answer[][] {
|
||||
if (!jobs.length) return []
|
||||
const tmp = path.join(dir, "review", `.ask-${process.pid}-${Date.now()}`)
|
||||
mkdirSync(tmp, { recursive: true })
|
||||
const sq = (t: string) => `'${t.replace(/'/g, `'\\''`)}'`
|
||||
const lines = jobs.map((k, i) => `${[RAEA, ...askArgs(k.file, k.says, k.from, k.to)].map(sq).join(" ")} > ${sq(`${tmp}/${i}.out`)} 2> ${sq(`${tmp}/${i}.err`)} &${(i + 1) % CLEF_AT_ONCE === 0 ? "\nwait" : ""}`)
|
||||
try {
|
||||
const r = cp.spawnSync("sh", ["-c", [...lines, "wait"].join("\n")], { cwd: dir, encoding: "utf8" }) as { error?: Error }
|
||||
if (r.error) throw new Error(`couldn't run raea ask: ${r.error.message}`)
|
||||
const read = (f: string) => (existsSync(f) ? String(readFileSync(f, "utf8")) : "")
|
||||
return jobs.map((k, i) => {
|
||||
const rows = rowsOf(read(`${tmp}/${i}.out`))
|
||||
if (rows.length !== k.says.length) throw new Error(`raea ask answered ${rows.length} of ${k.says.length} about ${k.file}: ${read(`${tmp}/${i}.err`).trim().slice(-300) || read(`${tmp}/${i}.out`).trim().slice(-300)}`)
|
||||
return rows
|
||||
})
|
||||
} finally {
|
||||
rmSync(tmp, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
/** `raea ask` on one file (or a stretch of it): run as a child, so several hear at once */
|
||||
function askClef(dir: string, file: string, says: string[], from?: string, to?: string): Promise<Answer[]> {
|
||||
const args = askArgs(file, says, from, to)
|
||||
// where there's no async spawn (raea's runtime), one at a time (clefVerdict asks them all at once: askClefMany)
|
||||
if (!asyncSpawn()) {
|
||||
const r = cp.spawnSync(RAEA, args, { cwd: dir, encoding: "utf8" }) as { stdout?: string; stderr?: string; error?: Error }
|
||||
if (r.error) return Promise.reject(new Error(`couldn't run raea ask: ${r.error.message}`))
|
||||
const rows = rowsOf(String(r.stdout ?? ""))
|
||||
if (rows.length !== says.length) return Promise.reject(new Error(`raea ask answered ${rows.length} of ${says.length} about ${file}: ${String(r.stderr ?? "").trim().slice(-300) || String(r.stdout ?? "").trim().slice(-300)}`))
|
||||
return Promise.resolve(rows)
|
||||
}
|
||||
return new Promise((ok, no) => {
|
||||
const c = cp.spawn(RAEA, args, { cwd: dir, stdio: ["ignore", "pipe", "pipe"] })
|
||||
const c = spawn(RAEA, ["ask", file, ...says, "--choose", "true,false", "--json", ...(from ? ["--from", from] : []), ...(to ? ["--to", to] : [])], { cwd: dir, stdio: ["ignore", "pipe", "pipe"] })
|
||||
let out = "", err = ""
|
||||
c.stdout.setEncoding("utf8").on("data", (t: string) => (out += t))
|
||||
c.stderr.setEncoding("utf8").on("data", (t: string) => (err = (err + t).slice(-4000)))
|
||||
c.on("error", (e) => no(new Error(`couldn't run raea ask: ${e.message}`)))
|
||||
c.on("close", () => {
|
||||
const rows = rowsOf(out)
|
||||
const rows = out.split("\n").flatMap((l) => { try { const o = JSON.parse(l); return o.answer ? [o as Answer] : [] } catch { return [] } })
|
||||
if (rows.length !== says.length) return no(new Error(`raea ask answered ${rows.length} of ${says.length} about ${file}: ${err.trim().slice(-300) || out.trim().slice(-300)}`))
|
||||
ok(rows)
|
||||
})
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
import { expect, test } from "bun:test"
|
||||
import { spawnSync } from "node:child_process"
|
||||
import { mkdtempSync } from "node:fs"
|
||||
import { tmpdir } from "node:os"
|
||||
import path from "node:path"
|
||||
|
||||
// raea's own runtime has no async spawn, so clefVerdict asks every question through one shell (askClefMany): six at
|
||||
// once, each answer in its job's order (12-04: one after another, a stop's 18 beats took 7.7 minutes). A child with a
|
||||
// stand-in raea (a second an ask), since RAEA is read once, as goal.ts is loaded
|
||||
test("askClefMany asks every job at once, CLEF_AT_ONCE at a time, and keeps each job's answers", () => {
|
||||
const dir = mkdtempSync(path.join(tmpdir(), "raea-ask-many-"))
|
||||
const script = `
|
||||
import { askClefMany } from ${JSON.stringify(path.join(import.meta.dir, "../src/packs/goal.ts"))}
|
||||
const jobs = Array.from({ length: 6 }, (_, i) => ({ file: "out/cut " + i + "'s.mp4", says: i % 2 ? ["one", "two"] : ["one"], from: "1", to: "2" }))
|
||||
const t0 = Date.now()
|
||||
const got = askClefMany(${JSON.stringify(dir)}, jobs)
|
||||
console.log(JSON.stringify({ ms: Date.now() - t0, n: got.map((r) => r.length), file: got[1][0].file }))
|
||||
`
|
||||
const r = spawnSync("bun", ["-e", script], { encoding: "utf8", env: { ...process.env, RAEA_REAL: path.join(import.meta.dir, "fixtures/fake-ask/raea") } })
|
||||
expect(r.stderr.trim().split("\n").filter((l) => /error/i.test(l))).toEqual([])
|
||||
const o = JSON.parse(r.stdout.trim().split("\n").at(-1)!)
|
||||
expect(o.ms).toBeLessThan(3_000)
|
||||
expect(o.n).toEqual([1, 2, 1, 2, 1, 2])
|
||||
expect(o.file).toBe("out/cut 1's.mp4")
|
||||
})
|
||||
Vendored
-5
@@ -1,5 +0,0 @@
|
||||
#!/bin/sh
|
||||
# a stand-in `raea ask FILE SAYS... --choose true,false --json`: one answer a line for each SAYS, after a second
|
||||
sleep 1
|
||||
shift; f=$1; shift
|
||||
for a in "$@"; do case "$a" in --*) break;; esac; echo "{\"answer\":\"a\",\"file\":\"$f\",\"choice\":\"true\",\"says\":\"true (0.9)\",\"problem\":null}"; done
|
||||
Reference in new issue
Block a user