Compare commits

..
Author SHA1 Message Date
shinyobjectz 43f730837a raea render --plan: every frame's manifest with nothing drawn
`raea render EDIT.tsx --composition ID --plan -o PLAN.json` steps React through every frame, makes the page match each frame's tree and lays it out, and gathers each frame's sounds as a render does. It decodes no video frame, paints nothing and encodes nothing. PLAN.json is the render manifest's own shape (a frame entry for every frame, the sounds heard, findings) with "plan": true, so the edit moment's checks can read a cut before it is rendered.

The plan pass is the --keys loop, plus lay_out and manifest_frame each frame, written through the same write_manifest and heard(). A plan's findings go into PLAN.json, and a plan isn't kept in the project's record as a render. On a raea cloud box a render with --plan runs on the box, not through offload.ts.

Measured on a 952-frame 1080x1920 cut, on a raea cloud box with 8 CPUs: the plan took 4.0 s, or 8.3 s with the page cache dropped. Rendering the same cut took 130 s on the same box and 152 s on the farm. Compared with full renders of the same edits on the same box, every frame's videos, text boxes (0 px apart) and sound clips match. Tested with plan::tests and the CLI's refusal test, run on Modal.
2026-12-04 10:44:40 -08:00
25 changed files with 222 additions and 1039 deletions

No files matched your search

+1 -1
View File
@@ -125,7 +125,7 @@ fn labels_from_three_projects_calibrate_a_question_and_new_words_are_measured_on
let sent = &groups[0].questions[0]; let sent = &groups[0].questions[0];
assert!(sent.calibrated() && sent.calibration.as_ref().is_some_and(|c| c.by == "you"), "{sent:?}"); assert!(sent.calibrated() && sent.calibration.as_ref().is_some_and(|c| c.by == "you"), "{sent:?}");
// new words for the flat question, asked of its labelled clips // new words for the flat question, asked of its labelled clips
let (sum, both) = calibrate::try_words("cal.flat", "Does anything look broken?", &Opts { jobs: 4, dry: false, ask: sees_bad, by_ref: None }, &mut |_| {}).unwrap(); let (sum, both) = calibrate::try_words("cal.flat", "Does anything look broken?", &Opts { jobs: 4, dry: false, ask: sees_bad }, &mut |_| {}).unwrap();
let (old, new) = both.unwrap(); let (old, new) = both.unwrap();
assert_eq!(sum.calls, 36); assert_eq!(sum.calls, 36);
assert_eq!((old.auc, new.auc, new.problems + new.clean), (Some(0.5), Some(1.0), 36), "{new:?}"); assert_eq!((old.auc, new.auc, new.problems + new.clean), (Some(0.5), Some(1.0), 36), "{new:?}");
+26 -118
View File
@@ -5,12 +5,6 @@
//! reports the rest as waiting for it. `dry` cuts the media and says what would be sent, and spends nothing. A group can //! reports the rest as waiting for it. `dry` cuts the media and says what would be sent, and spends nothing. A group can
//! carry clips kept from an earlier call instead of a file to cut (`raea ask try`), and every question goes out with the //! carry clips kept from an earlier call instead of a file to cut (`raea ask try`), and every question goes out with the
//! person's own calibration when it has earned one (calibrate.rs). //! person's own calibration when it has earned one (calibrate.rs).
//!
//! Through an agent key (a pipeline, CI, a raea cloud box), a call about the picture with its sound, at most a minute,
//! names the video kept on raea-api and its window instead of cutting clips here (raea_io_clef::by_reference, 12-04): the
//! video goes up once, raea-api cuts the window, and this machine decodes nothing, so every call goes at once. Where
//! that isn't offered, each file's video windows are cut in one pass over the stretch they cover (`media::videos`),
//! not one decode per window.
use std::collections::{BTreeSet, HashMap}; use std::collections::{BTreeSet, HashMap};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
@@ -18,7 +12,7 @@ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, mpsc}; use std::sync::{Arc, Mutex, mpsc};
use raea_core_ask::{Kind, Picks, Question, Sees, Window, limits}; use raea_core_ask::{Kind, Picks, Question, Sees, Window, limits};
use raea_io_clef::{Answered, ByReference, Call, Fail, Media, Source, media}; use raea_io_clef::{Answered, Call, Fail, Media, media};
use serde::Serialize; use serde::Serialize;
use serde_json::{Value, json}; use serde_json::{Value, json};
@@ -108,20 +102,11 @@ pub struct Opts {
pub dry: bool, pub dry: bool,
/// how a call is made: `raea_io_clef::ask` (a test gives its own) /// how a call is made: `raea_io_clef::ask` (a test gives its own)
pub ask: fn(&Call) -> Result<Answered, Fail>, pub ask: fn(&Call) -> Result<Answered, Fail>,
/// how a call by reference is made, when one can be (an agent key is the first route): `raea_io_clef::ask_by_reference`;
/// its `Fail::Next` means the clips are cut here and `ask` is used
pub by_ref: Option<fn(&ByReference) -> Result<Answered, Fail>>,
} }
impl Opts { impl Opts {
pub fn new(jobs: usize, dry: bool) -> Opts { pub fn new(jobs: usize, dry: bool) -> Opts {
let by_ref = !raea_io_clef::by_reference::off(&raea_io_clef::route::open()); Opts { jobs, dry, ask: raea_io_clef::ask }
Opts { jobs, dry, ask: raea_io_clef::ask, by_ref: by_ref.then_some(raea_io_clef::ask_by_reference as fn(&ByReference) -> Result<Answered, Fail>) }
}
/// Whether this machine cuts the picture: nothing goes by reference, or raea-api has said it can't take it.
fn cuts_here(&self) -> bool {
self.by_ref.is_none() || raea_io_clef::by_reference::off(&raea_io_clef::route::open())
} }
} }
@@ -181,50 +166,6 @@ pub fn plan(entries: &[Entry]) -> (Vec<Group>, Vec<Answer>) {
/// Clips cut once a run, by what they are. /// Clips cut once a run, by what they are.
type Cuts = Mutex<HashMap<String, Result<Arc<Vec<u8>>, String>>>; type Cuts = Mutex<HashMap<String, Result<Arc<Vec<u8>>, String>>>;
/// A clip's name among the cuts: what it is, of which file, over which window.
fn cut_key(what: &str, f: &Path, from: f64, to: Option<f64>) -> String {
format!("{what}:{}:{from}:{to:?}", f.display())
}
/// Each file's video windows the run's calls look at, cut in one pass the first time any of them is needed here.
struct Batches {
windows: HashMap<PathBuf, Vec<(f64, Option<f64>)>>,
done: Mutex<HashMap<PathBuf, Arc<Mutex<bool>>>>,
}
impl Batches {
fn plan(groups: &[Group]) -> Batches {
let mut windows: HashMap<PathBuf, Vec<(f64, Option<f64>)>> = HashMap::new();
for g in groups.iter().filter(|g| g.kept.is_none() && g.sees == Sees::Video && g.piece.probe.video) {
let w = windows.entry(g.piece.file.clone()).or_default();
if !w.contains(&(g.from, g.to)) {
w.push((g.from, g.to));
}
}
Batches { windows, done: Mutex::default() }
}
/// Every window of `f` not cut yet, cut in one pass (once a run); a window it fails leaves is cut on its own later.
fn cut(&self, cuts: &Cuts, f: &Path) {
let Some(all) = self.windows.get(f).filter(|w| w.len() > 1) else { return };
let lock = self.done.lock().unwrap().entry(f.to_path_buf()).or_default().clone();
let mut done = lock.lock().unwrap();
if std::mem::replace(&mut *done, true) {
return;
}
let left: Vec<(f64, Option<f64>)> = all.iter().filter(|(from, to)| !cuts.lock().unwrap().contains_key(&cut_key("video", f, *from, *to))).copied().collect();
if left.len() < 2 {
return;
}
if let Ok(clips) = media::videos(f, &left) {
let mut c = cuts.lock().unwrap();
for ((from, to), clip) in left.iter().zip(clips) {
c.insert(cut_key("video", f, *from, *to), Ok(Arc::new(clip)));
}
}
}
}
fn cut(cuts: &Cuts, key: String, make: impl FnOnce() -> Result<Vec<u8>, String>) -> Result<Arc<Vec<u8>>, String> { fn cut(cuts: &Cuts, key: String, make: impl FnOnce() -> Result<Vec<u8>, String>) -> Result<Arc<Vec<u8>>, String> {
if let Some(r) = cuts.lock().unwrap().get(&key) { if let Some(r) = cuts.lock().unwrap().get(&key) {
return r.clone(); return r.clone();
@@ -235,7 +176,7 @@ fn cut(cuts: &Cuts, key: String, make: impl FnOnce() -> Result<Vec<u8>, String>)
} }
/// A group's media, and its seconds of video and of sound (for the estimate). /// A group's media, and its seconds of video and of sound (for the estimate).
fn media_of(g: &Group, cuts: &Cuts, batches: Option<&Batches>) -> Result<(Media, f64, f64), String> { fn media_of(g: &Group, cuts: &Cuts) -> Result<(Media, f64, f64), String> {
if let Some(k) = &g.kept { if let Some(k) = &g.kept {
return Ok((k.media.clone(), k.video_seconds, k.sound_seconds)); return Ok((k.media.clone(), k.video_seconds, k.sound_seconds));
} }
@@ -246,12 +187,9 @@ fn media_of(g: &Group, cuts: &Cuts, batches: Option<&Batches>) -> Result<(Media,
let (mut vs, mut ss) = (0.0, 0.0); let (mut vs, mut ss) = (0.0, 0.0);
for f in &files { for f in &files {
let p = if *f == g.piece.file.as_path() { g.piece.probe } else { media::probe(f)? }; let p = if *f == g.piece.file.as_path() { g.piece.probe } else { media::probe(f)? };
let k = |what: &str| cut_key(what, f, from, to); let k = |what: &str| format!("{what}:{}:{from}:{to:?}", f.display());
match g.sees { match g.sees {
Sees::Video if p.video => { Sees::Video if p.video => {
if let Some(b) = batches {
b.cut(cuts, f);
}
m.videos.push(cut(cuts, k("video"), || media::video(f, from, to))?.to_vec()); m.videos.push(cut(cuts, k("video"), || media::video(f, from, to))?.to_vec());
vs += span(&p).min(limits::VIDEO_SECONDS); vs += span(&p).min(limits::VIDEO_SECONDS);
} }
@@ -297,34 +235,40 @@ pub fn run_groups(groups: Vec<Group>, unasked: Vec<Answer>, o: &Opts, out: &mut
out(Event::Answer(a)); out(Event::Answer(a));
} }
let cuts: Cuts = Mutex::default(); let cuts: Cuts = Mutex::default();
let batches = Batches::plan(&groups);
let (next, spent) = (AtomicUsize::new(0), AtomicBool::new(false)); let (next, spent) = (AtomicUsize::new(0), AtomicBool::new(false));
let spent_why = Mutex::new(String::new()); let spent_why = Mutex::new(String::new());
let (tx, rx) = mpsc::channel::<(usize, Done)>(); let (tx, rx) = mpsc::channel::<(usize, Done)>();
std::thread::scope(|s| { std::thread::scope(|s| {
for _ in 0..o.jobs.clamp(1, JOBS_MOST).min(groups.len().max(1)) { for _ in 0..o.jobs.clamp(1, 16).min(groups.len().max(1)) {
let (tx, groups, cuts, batches, next, spent, spent_why) = (tx.clone(), &groups, &cuts, &batches, &next, &spent, &spent_why); let (tx, groups, cuts, next, spent, spent_why) = (tx.clone(), &groups, &cuts, &next, &spent, &spent_why);
s.spawn(move || { s.spawn(move || {
loop { loop {
let i = next.fetch_add(1, Ordering::Relaxed); let i = next.fetch_add(1, Ordering::Relaxed);
let Some(g) = groups.get(i) else { break }; let Some(g) = groups.get(i) else { break };
let spend = |why: String| { let done = if spent.load(Ordering::Relaxed) {
Done::Waits(spent_why.lock().unwrap().clone())
} else {
match media_of(g, cuts) {
Err(e) => Done::Failed(e),
Ok((m, vs, ss)) => {
let state = g.kept.as_ref().map_or_else(|| g.piece.state(), |k| k.state.clone());
let call = Call { state, questions: g.questions.clone(), media: m };
let estimate = limits::estimate(vs, ss, call.media.stills.len(), call.state.len(), call.questions.len());
if o.dry {
Done::Would(would(g, &call, estimate))
} else {
match (o.ask)(&call) {
Ok(a) => Done::Asked(a, kept(&call.media), call.state),
Err(Fail::Spent(why)) => {
spent.store(true, Ordering::Relaxed); spent.store(true, Ordering::Relaxed);
*spent_why.lock().unwrap() = why.clone(); *spent_why.lock().unwrap() = why.clone();
Done::Waits(why) Done::Waits(why)
};
let done = if spent.load(Ordering::Relaxed) {
Done::Waits(spent_why.lock().unwrap().clone())
} else if let Some(r) = by_reference(g, o) {
// asked by reference; when it can't be, the clips are cut here below
match r {
Ok(a) => Done::Asked(a, vec![], g.piece.state()),
Err(Fail::Spent(why)) => spend(why),
Err(Fail::Stop(why)) => Done::Failed(why),
Err(Fail::Next(_)) => here(g, o, cuts, batches, &spend),
} }
} else { Err(f) => Done::Failed(f.to_string()),
here(g, o, cuts, batches, &spend) }
}
}
}
}; };
if tx.send((i, done)).is_err() { if tx.send((i, done)).is_err() {
break; break;
@@ -341,42 +285,6 @@ pub fn run_groups(groups: Vec<Group>, unasked: Vec<Answer>, o: &Opts, out: &mut
sum sum
} }
/// Calls at once: by reference each is a request and no work here, so more than a machine has cores.
const JOBS_MOST: usize = 32;
/// A call by reference, when this group can go that way: the picture with its sound (or none), of one file, a minute at
/// most, not clips kept from an earlier call, not a dry run. None: it can't, and its clips are cut here.
fn by_reference(g: &Group, o: &Opts) -> Option<Result<Answered, Fail>> {
let ask = o.by_ref?;
let p = g.piece.probe;
let end = g.to.unwrap_or(p.seconds).min(p.seconds);
if o.dry || g.kept.is_some() || !g.with.is_empty() || g.sees != Sees::Video || !p.video || end <= g.from || end - g.from > limits::VIDEO_SECONDS {
return None;
}
let source = Source { file: g.piece.file.clone(), from: g.from, to: g.to, sound: g.hears && p.sound };
Some(ask(&ByReference { state: g.piece.state(), questions: g.questions.clone(), source }))
}
/// A call with its clips cut here (or kept from an earlier call): asked, or (dry) what would be sent.
fn here(g: &Group, o: &Opts, cuts: &Cuts, batches: &Batches, spend: &dyn Fn(String) -> Done) -> Done {
match media_of(g, cuts, o.cuts_here().then_some(batches)) {
Err(e) => Done::Failed(e),
Ok((m, vs, ss)) => {
let state = g.kept.as_ref().map_or_else(|| g.piece.state(), |k| k.state.clone());
let call = Call { state, questions: g.questions.clone(), media: m };
let estimate = limits::estimate(vs, ss, call.media.stills.len(), call.state.len(), call.questions.len());
if o.dry {
return Done::Would(would(g, &call, estimate));
}
match (o.ask)(&call) {
Ok(a) => Done::Asked(a, kept(&call.media), call.state),
Err(Fail::Spent(why)) => spend(why),
Err(f) => Done::Failed(f.to_string()),
}
}
}
}
/// The clips a call sent, kept by hash for `raea ask try`. /// The clips a call sent, kept by hash for `raea ask try`.
fn kept(m: &Media) -> Vec<String> { fn kept(m: &Media) -> Vec<String> {
let each = |v: &[Vec<u8>], ext: &str| v.iter().map(|b| record::keep_media(b, ext)).collect::<Vec<_>>(); let each = |v: &[Vec<u8>], ext: &str| v.iter().map(|b| record::keep_media(b, ext)).collect::<Vec<_>>();
+1 -1
View File
@@ -124,7 +124,7 @@ fn clip(name: &str) -> PathBuf {
fn run(entries: Vec<Entry>, jobs: usize, ask: fn(&Call) -> Result<Answered, Fail>) -> (runner::Summary, Vec<Answer>) { fn run(entries: Vec<Entry>, jobs: usize, ask: fn(&Call) -> Result<Answered, Fail>) -> (runner::Summary, Vec<Answer>) {
setup(); setup();
let mut got = Vec::new(); let mut got = Vec::new();
let sum = runner::run(entries, &Opts { jobs, dry: false, ask, by_ref: None }, &mut |e| { let sum = runner::run(entries, &Opts { jobs, dry: false, ask }, &mut |e| {
if let Event::Answer(a) = e { if let Event::Answer(a) = e {
got.push(a.clone()); got.push(a.clone());
} }
+5 -2
View File
@@ -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 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); 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 // 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(m) = manifest {
if let Some(mut v) = std::fs::read(&m).ok().and_then(|b| serde_json::from_slice::<Value>(&b).ok()) { 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 // 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 // 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)) { 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); println!("raea render: kept in the project's record as {} (raea findings reads it)", e.id);
} }
-28
View File
@@ -136,34 +136,6 @@ Feature: Ask: questions about a piece's picture and sound, answered by the decis
pool spent on the third call keeps two calls' answers and sends nothing more. `raea check`, the critique and pool spent on the third call keeps two calls' answers and sends nothing more. `raea check`, the critique and
the fingerprint move onto the runner in AK5, AK4 and AK8. docs/manual/reference/sdk/ask.md is `raea/ask`'s. the fingerprint move onto the runner in AK5, AK4 and AK8. docs/manual/reference/sdk/ask.md is `raea/ask`'s.
@needs:AK3
Scenario: AK3b. A window asked by reference: the video kept once on raea-api, cut there
Given a raea cloud box judging a project's beats (12-04): about 18 questions a stop, each about its own window of
one of about six cuts (94 MB each, 1080x1920), every `raea ask` decoding its cut, cutting its window and
encoding it (6.4 s and 18 s of CPU an ask on the box's 8 cores, so six at a time was the ceiling)
And raea-api's `POST /v1/clef/media {sha256, size}` (kept, or a URL to PUT it to once) and `POST /v1/clef/ask
{state, questions, source: {sha256, from, to, sound}}`, which cuts the window with Cloudflare's Media
Transformations (480 px wide H.264, the sound in the clip), keeps the clip, and asks clef as any ask
(raea-platform apps/site/api/src/clef.ts)
When a call is asked through an agent key (`RAEA_AGENT_KEY` is the first route) about the picture with its
sound, one file, at most 60 s
Then each video goes up once a run by its SHA-256, or not at all when the account's storage has it already
(Git LFS, an upload), every call names it and its window, and the machine decodes nothing, so `--jobs` can be
as many as the calls (32 at most)
And a raea-api that doesn't offer it (an older one: 404 or 403 for the route, bad_media for the source; one
without Media Transformations: 501) turns it off for the run, and a window it can't cut (too large, not kept,
a failed cut) is cut here for that call alone; the app's route, stills, a sound alone, files set beside it
(`--with`) and windows over 60 s are cut here as before; `RAEA_ASK_BY_REFERENCE=0` turns it off
And where windows are cut here, each file's video windows are cut in one pass over the stretch they cover (one
decode, one scale, a split to each window's encode), and windows more than 2 s apart are separate passes
And `raea goal check` asks all of a stop's windows in one `raea ask --batch` (sdk/goal goal.ts askClefMany), so the
brief and each file are read once and each video goes up once
Status: in review 12-04 (raea PR on goal-spawn-fallback, raea-platform PR clef-by-reference). io/clef tests (a
video goes up once and each window is asked by its hash, a kept one isn't sent, an older raea-api turns it off,
a window too large is cut here alone, a spent pool stops), media.rs's stretches test and raea-platform's
test/clef-source.sh (a fake cutter in place of Media Transformations) are written; the Rust is unbuilt (the
machine had 7 GB free), and Media Transformations on a real cut is unmeasured.
Rule: AK4. On the person's plan Rule: AK4. On the person's plan
@needs:AK3 @needs:AK3
+11
View File
@@ -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 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.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 -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 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` 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. 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 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 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 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 ```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 -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 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 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) 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. | | `--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. | | `--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. | | `--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. | | `--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. | | `--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`. | | `--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`. |
-1
View File
@@ -44,7 +44,6 @@ libraries (pianos, General MIDI instruments, orchestral and percussion samples,
| `CLOUDFLARE_ACCOUNT_ID`, `CLOUDFLARE_API_TOKEN` | The decision model (clef-omni on Workers AI) on your own Cloudflare account, for `raea ask`, `raea judge` and the checks that ask. Signed in to raea on Pro or Studio, the app pays from your plan's monthly pool first (docs/ask.feature) | | `CLOUDFLARE_ACCOUNT_ID`, `CLOUDFLARE_API_TOKEN` | The decision model (clef-omni on Workers AI) on your own Cloudflare account, for `raea ask`, `raea judge` and the checks that ask. Signed in to raea on Pro or Studio, the app pays from your plan's monthly pool first (docs/ask.feature) |
| `RAEA_AGENT_KEY`, `RAEA_API` | An agent key with the `ask` scope, and the API address it came with: asks from your plan's pool with no app running (a pipeline, CI, a server) | | `RAEA_AGENT_KEY`, `RAEA_API` | An agent key with the `ask` scope, and the API address it came with: asks from your plan's pool with no app running (a pipeline, CI, a server) |
| `RAEA_ASK_ROUTE` | `app`, `agent` or `own`: ask only that way, rather than the first that answers | | `RAEA_ASK_ROUTE` | `app`, `agent` or `own`: ask only that way, rather than the first that answers |
| `RAEA_ASK_BY_REFERENCE` | `0`: never ask about a window by naming the video kept on raea-api; cut its clips here (docs/ask.feature AK3b) |
| `RAEA_ASK_DIR` | Where `raea ask` keeps its answers, the clips it cut and its cache (`~/.raea/ask`) | | `RAEA_ASK_DIR` | Where `raea ask` keeps its answers, the clips it cut and its cache (`~/.raea/ask`) |
| `RAEA_CLEF_REPLAY` | A JSON file of answers by question id, given back for every call: for tests, which then never spend | | `RAEA_CLEF_REPLAY` | A JSON file of answers by question id, given back for every call: for tests, which then never spend |
| `RAEA_GUIDES` | A folder of craft references for the agent's `guide` tool (`captions.md`, `motion-rules.md`, ...) | | `RAEA_GUIDES` | A folder of craft references for the agent's `guide` tool (`captions.md`, `motion-rules.md`, ...) |
+1 -1
View File
@@ -384,7 +384,7 @@ pub fn run(args: &[String]) -> R<String> {
} }
if args.first().map(String::as_str) != Some("render") || args.len() < 2 { if args.first().map(String::as_str) != Some("render") || args.len() < 2 {
return Err(format!( 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 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>)", 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 tools::sound::SAO_USAGE, tools::sound::TOKENSYNTH_USAGE, tools::song::USAGE, motion::track::USAGE
+1
View File
@@ -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", "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", "d", "--at", "0,30", "--composition", "Main", "--w", "1080", "--h", "1920", "--fps", "30", "--frames", "90", "--lite"],
&["render", "e.tsx", "-o", "o.mp4", "--kbps", "-6"], &["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"], &["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-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"], &["play", "g.tsx", "--input", "--baked", "--scrub", "8", "--autoplay", "--no-vsync", "--master", "--3d"],
-170
View File
@@ -1,170 +0,0 @@
//! A call that names a video kept on raea-api and a window of it, in place of its clips (docs/ask.feature AK3b; raea-api
//! clef.ts, "Asking by reference"). A raea cloud box judging a project's beats decoded the same cut for every window it
//! asked about (12-04: 6.4 s and 18 s of CPU an ask, so six at a time was its ceiling). Now each video goes up once a
//! run, by its SHA-256 (`POST /v1/clef/media`, then one PUT; nothing at all when it's there already, in the account's
//! storage or Git LFS), and each call names it and a window, which raea-api cuts with Cloudflare's Media
//! Transformations: nothing is decoded here, so every window can be asked at once. Only through an agent key (the route
//! a pipeline, CI or a raea cloud box asks by), and only for the picture with its sound, at most 60 s (runner.rs says
//! which calls); anything else, and every call once raea-api has shown it doesn't offer this, cuts its clips here as
//! before. `RAEA_ASK_BY_REFERENCE=0` turns it off.
use std::collections::{HashMap, HashSet};
use std::io::Read as _;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, OnceLock};
use raea_core_ask::Question;
use raea_io_home::setting;
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use crate::cache;
use crate::client::{Answered, Call, Fail, Transport, api_answer, said};
use crate::route::Route;
/// The largest video raea-api cuts (Media Transformations' input limit).
pub const MAX_BYTES: u64 = 100 * 1024 * 1024;
const ROUTE: &str = "your raea plan, with an agent key (cut on raea-api)";
/// A window of a video, to be cut on raea-api: `sound` puts its sound in the clip (clef hears a video's soundtrack with
/// its frames).
#[derive(Debug, Clone)]
pub struct Source {
pub file: PathBuf,
pub from: f64,
pub to: Option<f64>,
pub sound: bool,
}
/// One call by reference: what the piece is, its questions, and the window they're about.
#[derive(Debug, Clone)]
pub struct ByReference {
pub state: String,
pub questions: Vec<Question>,
pub source: Source,
}
/// The raea-apis that have shown they don't offer it this run (an older one, or one that can't cut): every call to them
/// cuts its own clips.
fn refused() -> &'static Mutex<HashSet<String>> {
static OFF: OnceLock<Mutex<HashSet<String>>> = OnceLock::new();
OFF.get_or_init(Mutex::default)
}
fn turn_off(api: &str) {
refused().lock().unwrap().insert(api.to_string());
}
/// Whether asking by reference is off for the rest of this run (or wasn't open: no agent key first, or turned off).
pub fn off(routes: &[Route]) -> bool {
api(routes).is_none()
}
/// The agent key's raea-api and key, when a call can go by reference: an agent key is the first route, and neither
/// `RAEA_ASK_BY_REFERENCE=0` nor that raea-api has turned it off.
pub fn api(routes: &[Route]) -> Option<(&str, &str)> {
if setting("RAEA_ASK_BY_REFERENCE").as_deref() == Some("0") {
return None;
}
match routes.first() {
Some(Route::Agent { api, key }) if !refused().lock().unwrap().contains(api.as_str()) => Some((api.as_str(), key.as_str())),
_ => None,
}
}
type Kept = Arc<OnceLock<Result<String, Fail>>>;
/// Each file hashed and kept once a run, by its path, length and time written: every call about it waits for that once.
fn memo(file: &Path) -> Kept {
static FILES: OnceLock<Mutex<HashMap<String, Kept>>> = OnceLock::new();
let m = std::fs::metadata(file).ok();
let id = format!("{}\u{1f}{:?}\u{1f}{:?}", file.display(), m.as_ref().map(|m| m.len()), m.and_then(|m| m.modified().ok()));
FILES.get_or_init(Mutex::default).lock().unwrap().entry(id).or_default().clone()
}
/// A file's SHA-256 and length, read once in 1 MiB pieces.
pub fn hashed(file: &Path) -> Result<(String, u64), String> {
let mut f = std::fs::File::open(file).map_err(|e| format!("{}: {e}", file.display()))?;
let (mut h, mut buf, mut n) = (Sha256::new(), vec![0u8; 1 << 20], 0u64);
loop {
let got = f.read(&mut buf).map_err(|e| format!("{}: {e}", file.display()))?;
if got == 0 {
break;
}
h.update(&buf[..got]);
n += got as u64;
}
Ok((h.finalize().iter().map(|b| format!("{b:02x}")).collect(), n))
}
/// The video on raea-api, by its SHA-256: there already, or sent once. A raea-api that doesn't know the route turns
/// asking by reference off for the run.
fn keep(t: &dyn Transport, api: &str, key: &str, file: &Path) -> Result<String, Fail> {
let (sha, size) = hashed(file).map_err(Fail::Next)?;
if size > MAX_BYTES {
return Err(Fail::Next(format!("{} is over {} MB, more than raea-api cuts", file.display(), MAX_BYTES >> 20)));
}
let (code, j) = t.post(&format!("{api}/v1/clef/media"), Some(key), &json!({"sha256": sha, "size": size})).map_err(|e| Fail::Next(format!("keeping {} for asking: {e}", file.display())))?;
match code {
200 if j["kept"] == true => Ok(sha),
200 => {
let url = j["url"].as_str().ok_or_else(|| Fail::Next("raea-api gave no URL to keep the video at".into()))?;
match t.put_file(url, file) {
Ok(200..=299) => Ok(sha),
Ok(c) => Err(Fail::Next(format!("keeping {} for asking: HTTP {c}", file.display()))),
Err(e) => Err(Fail::Next(e)),
}
}
// no plan, a spent pool, a file too large to cut there: this call's clips are cut here, and its ask says why
402 | 413 => Err(Fail::Next(said(&j, code))),
// an older raea-api (404, or 403 for an agent key's route it doesn't know): cut here for the rest of the run
_ => {
turn_off(api);
Err(Fail::Next(format!("raea-api doesn't keep videos for asking: {}", said(&j, code))))
}
}
}
/// The body raea-api takes: the state, the questions, and the video by its hash with the window.
fn body(call: &ByReference, sha: &str) -> Value {
let c = Call { state: call.state.clone(), questions: call.questions.clone(), ..Default::default() };
let s = &call.source;
let mut source = json!({"sha256": sha, "from": s.from, "sound": s.sound});
if let Some(to) = s.to {
source["to"] = json!(to);
}
json!({"state": c.state(), "questions": c.questions(), "source": source})
}
/// One call by reference through the agent key's raea-api. `Fail::Next` means cut the clips here and ask as before.
pub fn ask(t: &dyn Transport, call: &ByReference, routes: &[Route]) -> Result<Answered, Fail> {
let Some((api, key)) = api(routes) else { return Err(Fail::Next("asked by reference only with an agent key".into())) };
let questions = Call { questions: call.questions.clone(), ..Default::default() };
if let Some(p) = questions.question_problem() {
return Err(Fail::Stop(p));
}
let file = &call.source.file;
let sha = memo(file).get_or_init(|| keep(t, api, key, file)).clone()?;
let body = body(call, &sha);
let ckey = cache::key_of(&body);
if let Some(answers) = cache::get(&ckey) {
return Ok(Answered { answers, cost: 0.0, cached: true, route: "asked before (cache)".into(), pool_left: None });
}
let own = routes.iter().any(|r| matches!(r, Route::Own { .. }));
let (code, j) = t.post(&format!("{api}/v1/clef/ask"), Some(key), &body).map_err(|e| Fail::Next(format!("{ROUTE} didn't answer: {e}")))?;
match (code, j["error"].as_str()) {
// an older raea-api (it reads no source), or one that can't cut: cut here for the rest of the run
(400, Some("bad_media")) | (501, _) => {
turn_off(api);
Err(Fail::Next(format!("{ROUTE}: {}", said(&j, code))))
}
// not kept any more, too large to cut there, the cut failed: this call's clips are cut here
(404 | 413 | 502, _) | (400, Some("bad_source")) => Err(Fail::Next(format!("{ROUTE}: {}", said(&j, code)))),
_ => {
let a = api_answer(code, &j, ROUTE, own)?;
cache::put(&ckey, &a.answers);
Ok(a)
}
}
}
+1 -6
View File
@@ -16,13 +16,8 @@ pub fn dir() -> PathBuf {
/// The request's hash. /// The request's hash.
pub fn key(call: &Call) -> String { pub fn key(call: &Call) -> String {
key_of(&call.clef_body())
}
/// The hash of a request's body as sent (an ask by reference names its video by hash and window: by_reference.rs).
pub fn key_of(body: &Value) -> String {
let mut h = Sha256::new(); let mut h = Sha256::new();
h.update(body.to_string().as_bytes()); h.update(call.clef_body().to_string().as_bytes());
h.finalize().iter().map(|b| format!("{b:02x}")).collect() h.finalize().iter().map(|b| format!("{b:02x}")).collect()
} }
+10 -38
View File
@@ -3,8 +3,6 @@
//! The answers come back by question id with the call's cost. A transport is handed in, so tests replay recorded //! The answers come back by question id with the call's cost. A transport is handed in, so tests replay recorded
//! answers and never spend. //! answers and never spend.
use std::path::Path;
use base64::Engine as _; use base64::Engine as _;
use base64::engine::general_purpose::STANDARD as B64; use base64::engine::general_purpose::STANDARD as B64;
use raea_core_ask::{Question, limits}; use raea_core_ask::{Question, limits};
@@ -57,10 +55,6 @@ impl std::fmt::Display for Fail {
/// An HTTP POST of JSON: its status and body. `Http` is the real one; a test hands in its own. /// An HTTP POST of JSON: its status and body. `Http` is the real one; a test hands in its own.
pub trait Transport { pub trait Transport {
fn post(&self, url: &str, bearer: Option<&str>, body: &Value) -> Result<(u16, Value), String>; fn post(&self, url: &str, bearer: Option<&str>, body: &Value) -> Result<(u16, Value), String>;
/// A file's bytes PUT to a presigned URL (a video kept on raea-api to be asked about by reference): its status.
fn put_file(&self, url: &str, file: &Path) -> Result<u16, String> {
Err(format!("this transport doesn't send files ({url}, {})", file.display()))
}
} }
pub struct Http; pub struct Http;
@@ -77,25 +71,16 @@ impl Transport for Http {
Err(e) => Err(format!("{url}: {e}")), Err(e) => Err(format!("{url}: {e}")),
} }
} }
fn put_file(&self, url: &str, file: &Path) -> Result<u16, String> {
let f = std::fs::File::open(file).map_err(|e| format!("{}: {e}", file.display()))?;
let len = f.metadata().map_err(|e| format!("{}: {e}", file.display()))?.len();
// a Content-Length of its own, so the body isn't chunked: R2 and raea-api's own URLs take only a known length
let r = ureq::put(url).timeout(std::time::Duration::from_secs(600)).set("content-length", &len.to_string());
match r.send(f) {
Ok(res) => Ok(res.status()),
Err(ureq::Error::Status(code, _)) => Ok(code),
Err(e) => Err(format!("sending {}: {e}", file.display())),
}
}
} }
impl Call { impl Call {
/// Why it can't be sent as it stands, or None: clef's counts and sizes, every question's own limits. /// Why it can't be sent as it stands, or None: clef's counts and sizes, every question's own limits.
pub fn problem(&self) -> Option<String> { pub fn problem(&self) -> Option<String> {
let m = &self.media; let m = &self.media;
if let Some(p) = self.question_problem() { if self.questions.is_empty() || self.questions.len() > limits::QUESTIONS {
return Some(format!("a call asks 1 to {} questions, not {}", limits::QUESTIONS, self.questions.len()));
}
if let Some(p) = self.questions.iter().find_map(limits::check) {
return Some(p); return Some(p);
} }
if m.stills.is_empty() && m.videos.is_empty() && m.sounds.is_empty() { if m.stills.is_empty() && m.videos.is_empty() && m.sounds.is_empty() {
@@ -111,19 +96,11 @@ impl Call {
(m.videos.iter().chain(&m.sounds).map(Vec::len).sum::<usize>() > limits::AV_BYTES).then(|| "the videos and sounds together are over 16 MiB".into()) (m.videos.iter().chain(&m.sounds).map(Vec::len).sum::<usize>() > limits::AV_BYTES).then(|| "the videos and sounds together are over 16 MiB".into())
} }
/// Why its questions can't be sent, or None: how many, and each one's own limits. fn questions(&self) -> Value {
pub(crate) fn question_problem(&self) -> Option<String> {
if self.questions.is_empty() || self.questions.len() > limits::QUESTIONS {
return Some(format!("a call asks 1 to {} questions, not {}", limits::QUESTIONS, self.questions.len()));
}
self.questions.iter().find_map(limits::check)
}
pub(crate) fn questions(&self) -> Value {
Value::Object(self.questions.iter().map(|q| (q.id.clone(), q.wire())).collect()) Value::Object(self.questions.iter().map(|q| (q.id.clone(), q.wire())).collect())
} }
pub(crate) fn state(&self) -> String { fn state(&self) -> String {
self.state.chars().take(limits::STATE_CHARS).collect() self.state.chars().take(limits::STATE_CHARS).collect()
} }
@@ -151,7 +128,7 @@ impl Call {
} }
} }
pub(crate) fn said(body: &Value, code: u16) -> String { fn said(body: &Value, code: u16) -> String {
body["message"].as_str().or(body["error"].as_str()).map(str::to_string).unwrap_or_else(|| format!("HTTP {code}")) body["message"].as_str().or(body["error"].as_str()).map(str::to_string).unwrap_or_else(|| format!("HTTP {code}"))
} }
@@ -174,11 +151,6 @@ pub fn workers_ai(t: &dyn Transport, call: &Call, account: &str, token: &str) ->
/// to the account's pool. `own_keys` says whether a spent pool may fall through to the person's own account. /// to the account's pool. `own_keys` says whether a spent pool may fall through to the person's own account.
pub fn raea_api(t: &dyn Transport, call: &Call, url: &str, bearer: Option<&str>, route: &str, own_keys: bool) -> Result<Answered, Fail> { pub fn raea_api(t: &dyn Transport, call: &Call, url: &str, bearer: Option<&str>, route: &str, own_keys: bool) -> Result<Answered, Fail> {
let (code, j) = t.post(url, bearer, &call.api_body()).map_err(|e| Fail::Next(format!("{route} didn't answer: {e}")))?; let (code, j) = t.post(url, bearer, &call.api_body()).map_err(|e| Fail::Next(format!("{route} didn't answer: {e}")))?;
api_answer(code, &j, route, own_keys)
}
/// raea-api's answer read: the answers, or why not (a spent pool stops a batch unless the person's own keys can go on).
pub(crate) fn api_answer(code: u16, j: &Value, route: &str, own_keys: bool) -> Result<Answered, Fail> {
match (code, j["error"].as_str()) { match (code, j["error"].as_str()) {
(200..=299, _) => Ok(Answered { (200..=299, _) => Ok(Answered {
answers: j["answers"].as_object().cloned().unwrap_or_default(), answers: j["answers"].as_object().cloned().unwrap_or_default(),
@@ -187,8 +159,8 @@ pub(crate) fn api_answer(code: u16, j: &Value, route: &str, own_keys: bool) -> R
route: route.into(), route: route.into(),
pool_left: j["pool_left_usd"].as_f64(), pool_left: j["pool_left_usd"].as_f64(),
}), }),
(402, Some("pool_spent")) if !own_keys => Err(Fail::Spent(said(j, code))), (402, Some("pool_spent")) if !own_keys => Err(Fail::Spent(said(&j, code))),
(400 | 413, _) => Err(Fail::Stop(said(j, code))), (400 | 413, _) => Err(Fail::Stop(said(&j, code))),
_ => Err(Fail::Next(format!("{route}: {}", said(j, code)))), _ => Err(Fail::Next(format!("{route}: {}", said(&j, code)))),
} }
} }
+1 -10
View File
@@ -1,16 +1,13 @@
//! The decision model, called one way for every caller (docs/ask.feature AK1b): a call's body and its answers //! The decision model, called one way for every caller (docs/ask.feature AK1b): a call's body and its answers
//! (`client`), the media cut to what it reads (`media`), the route it takes, the person's plan first (`route`), and the //! (`client`), the media cut to what it reads (`media`), the route it takes, the person's plan first (`route`), and the
//! answers kept by request (`cache`). `raea ask` (apps/ask) and `raea judge` call it. Through an agent key, a call about //! answers kept by request (`cache`). `raea ask` (apps/ask) and `raea judge` call it.
//! a window of a video can name the video kept on raea-api instead of sending its clips (`by_reference`).
pub mod by_reference;
pub mod cache; pub mod cache;
pub mod client; pub mod client;
pub mod critic; pub mod critic;
pub mod media; pub mod media;
pub mod route; pub mod route;
pub use by_reference::{ByReference, Source};
pub use client::{Answered, Call, Fail, Http, Media, Transport}; pub use client::{Answered, Call, Fail, Http, Media, Transport};
pub use route::Route; pub use route::Route;
@@ -19,11 +16,5 @@ pub fn ask(call: &Call) -> Result<Answered, Fail> {
route::ask(&Http, call, &route::open()) route::ask(&Http, call, &route::open())
} }
/// One call by reference (a window of a video kept on raea-api), by the routes open on this computer. `Fail::Next`
/// means it can't go that way: cut the clips here and `ask`.
pub fn ask_by_reference(call: &ByReference) -> Result<Answered, Fail> {
by_reference::ask(&Http, call, &route::open())
}
#[cfg(test)] #[cfg(test)]
mod tests; mod tests;
-72
View File
@@ -99,68 +99,6 @@ pub fn video(file: &Path, from: f64, to: Option<f64>) -> Result<Vec<u8>, String>
out.read() out.read()
} }
/// Windows a pass reads together: those that overlap or sit within this many seconds of each other. Further apart, each
/// stretch is its own pass, so two short windows a minute apart don't decode the minute between them.
const STRETCH_GAP: f64 = 2.0;
/// Each window as seconds from and to, held to 60 s as `video` holds it.
fn spans(windows: &[(f64, Option<f64>)]) -> Vec<(f64, f64)> {
windows.iter().map(|&(from, to)| (from, from + to.map(|t| (t - from).max(0.1)).unwrap_or(limits::VIDEO_SECONDS).min(limits::VIDEO_SECONDS))).collect()
}
/// The windows (by index) gathered into stretches read in one pass each.
fn stretches(spans: &[(f64, f64)]) -> Vec<Vec<usize>> {
let mut order: Vec<usize> = (0..spans.len()).collect();
order.sort_by(|a, b| spans[*a].0.total_cmp(&spans[*b].0));
let mut out: Vec<Vec<usize>> = Vec::new();
let mut end = f64::NEG_INFINITY;
for i in order {
match out.last_mut() {
Some(s) if spans[i].0 <= end + STRETCH_GAP => s.push(i),
_ => out.push(vec![i]),
}
end = if out.last().is_some_and(|s| s.len() > 1) { end.max(spans[i].1) } else { spans[i].1 };
}
out
}
/// Several windows of one file's picture, as `video` cuts each (480 px wide, 10 frames a second, no sound), in the
/// windows' order: each stretch of nearby windows decoded once, scaled once and split to each window's own encode,
/// rather than decoded again for every window (12-04: a raea cloud box asked 18 windows of six cuts, each decoded on its
/// own).
pub fn videos(file: &Path, windows: &[(f64, Option<f64>)]) -> Result<Vec<Vec<u8>>, String> {
let spans = spans(windows);
let mut out: Vec<Option<Vec<u8>>> = vec![None; windows.len()];
for s in stretches(&spans) {
if let &[i] = s.as_slice() {
out[i] = Some(video(file, windows[i].0, windows[i].1)?);
continue;
}
let start = s.iter().map(|&i| spans[i].0).fold(f64::INFINITY, f64::min);
let end = s.iter().map(|&i| spans[i].1).fold(f64::NEG_INFINITY, f64::max);
let outs: Vec<Temp> = s.iter().map(|_| Temp::new("mp4")).collect();
let mut graph = format!("[0:v]scale=480:-2,fps=10,split={}", s.len());
for n in 0..s.len() {
graph += &format!("[s{n}]");
}
for (n, &i) in s.iter().enumerate() {
graph += &format!(";[s{n}]trim=start={:.3}:end={:.3},setpts=PTS-STARTPTS[v{n}]", spans[i].0 - start, spans[i].1 - start);
}
let mut c = tool("ffmpeg", file)?;
c.args(["-nostdin", "-v", "error", "-y", "-ss", &format!("{start:.3}"), "-t", &format!("{:.3}", end - start)]).arg("-i").arg(file);
c.args(["-filter_complex", &graph]);
let enc = small_h264()?;
for (n, t) in outs.iter().enumerate() {
c.args(["-map", &format!("[v{n}]"), "-an"]).args(&enc).args(["-movflags", "+faststart"]).arg(&t.0);
}
run(c, "cutting the pictures")?;
for (&i, t) in s.iter().zip(&outs) {
out[i] = Some(t.read()?);
}
}
Ok(out.into_iter().map(Option::unwrap_or_default).collect())
}
/// The sound from `from` to `to` (at most 300 s), mono 16 kHz MP3. /// The sound from `from` to `to` (at most 300 s), mono 16 kHz MP3.
pub fn sound(file: &Path, from: f64, to: Option<f64>) -> Result<Vec<u8>, String> { pub fn sound(file: &Path, from: f64, to: Option<f64>) -> Result<Vec<u8>, String> {
let out = Temp::new("mp3"); let out = Temp::new("mp3");
@@ -194,14 +132,4 @@ mod tests {
assert_eq!(window(0.0, None, 60.0), ["-ss", "0.000", "-t", "60.000"]); assert_eq!(window(0.0, None, 60.0), ["-ss", "0.000", "-t", "60.000"]);
assert_eq!(window(0.0, Some(400.0), 300.0)[3], "300.000"); assert_eq!(window(0.0, Some(400.0), 300.0)[3], "300.000");
} }
#[test]
fn nearby_windows_are_read_in_one_pass_and_far_ones_apart() {
// a cut's beats, one after another, and a window to its end; one more a minute later
let w = [(0.0, Some(3.5)), (3.5, Some(7.2)), (7.2, Some(12.0)), (5.0, None), (90.0, Some(94.0))];
let s = spans(&w);
assert_eq!(s[3], (5.0, 65.0), "a window to the end is held to 60 s");
assert_eq!(stretches(&s), [vec![0, 1, 3, 2], vec![4]]);
assert_eq!(stretches(&spans(&[(0.0, Some(1.0)), (2.5, Some(3.0)), (6.0, Some(7.0))])), [vec![0, 1], vec![2]]);
}
} }
-108
View File
@@ -106,111 +106,3 @@ fn workers_ai_gets_data_urls_and_raea_api_bare_base64() {
assert_eq!(c.api_body()["audio"][0], "AQ=="); assert_eq!(c.api_body()["audio"][0], "AQ==");
assert_eq!(clef["questions"]["q"]["type"], "noul"); assert_eq!(clef["questions"]["q"]["type"], "noul");
} }
// ---- asking by reference (by_reference.rs): a video kept on raea-api once, each window asked by its hash
use crate::by_reference::{self, ByReference, Source};
/// Canned replies by URL ending, every URL asked (a file sent as "PUT url") and every body sent.
struct Api {
replies: Vec<(&'static str, u16, Value)>,
seen: RefCell<Vec<String>>,
bodies: RefCell<Vec<Value>>,
}
impl Api {
fn new(replies: Vec<(&'static str, u16, Value)>) -> Api {
Api { replies, seen: RefCell::default(), bodies: RefCell::default() }
}
}
impl Transport for Api {
fn post(&self, url: &str, _bearer: Option<&str>, body: &Value) -> Result<(u16, Value), String> {
self.seen.borrow_mut().push(url.to_string());
self.bodies.borrow_mut().push(body.clone());
self.replies.iter().find(|(end, ..)| url.ends_with(end)).map(|(_, c, j)| (*c, j.clone())).ok_or_else(|| format!("{url}: connection refused"))
}
fn put_file(&self, url: &str, file: &std::path::Path) -> Result<u16, String> {
self.seen.borrow_mut().push(format!("PUT {url}"));
std::fs::metadata(file).map(|_| 200).map_err(|e| e.to_string())
}
}
/// A "video" unique to its test (the files kept are remembered by path), and an agent key's route to its own raea-api
/// (a raea-api that turns asking by reference off does so for itself alone).
fn video(test: &str) -> (std::path::PathBuf, Vec<Route>) {
setup();
let f = std::env::temp_dir().join(format!("raea-clef-ref-{}-{test}.mp4", std::process::id()));
std::fs::write(&f, format!("not really a video: {test}")).unwrap();
(f, vec![Route::Agent { api: format!("https://{test}.api.test"), key: "k".into() }])
}
fn by_ref(file: &std::path::Path, from: f64, to: Option<f64>) -> ByReference {
let source = Source { file: file.to_path_buf(), from, to, sound: true };
ByReference { state: format!("a test piece: {}", file.display()), questions: vec![Question::plain("q", "Is the product on screen?")], source }
}
const BY_REF: &str = r#"{"answers": {"q": {"noul": 0.4}}, "cost_usd": 0.001, "cached": false, "pool_left_usd": 1.5}"#;
#[test]
fn a_video_goes_up_once_and_each_window_is_asked_by_its_hash() {
let (file, routes) = video("once");
let api = Api::new(vec![("/v1/clef/media", 200, json!({"kept": false, "url": "https://r2.test/put"})), ("/v1/clef/ask", 200, serde_json::from_str(BY_REF).unwrap())]);
let a = by_reference::ask(&api, &by_ref(&file, 1.0, Some(3.5)), &routes).unwrap();
assert_eq!((a.answers["q"]["noul"].as_f64(), a.route.as_str()), (Some(0.4), "your raea plan, with an agent key (cut on raea-api)"));
by_reference::ask(&api, &by_ref(&file, 3.5, None), &routes).unwrap();
let seen = api.seen.borrow();
assert_eq!(seen.iter().map(|u| u.rsplit('/').next().unwrap()).collect::<Vec<_>>(), ["media", "put", "ask", "ask"], "{seen:?}");
let (sha, size) = by_reference::hashed(&file).unwrap();
let bodies = api.bodies.borrow();
assert_eq!(bodies[0], json!({"sha256": sha, "size": size}));
assert_eq!(bodies[1]["source"], json!({"sha256": sha, "from": 1.0, "to": 3.5, "sound": true}));
assert_eq!(bodies[2]["source"], json!({"sha256": sha, "from": 3.5, "sound": true}), "a window to the end names no end");
assert!(bodies[1].get("videos").is_none() && bodies[1]["questions"]["q"]["type"] == "noul");
// the same call again comes from the cache
let again = by_reference::ask(&api, &by_ref(&file, 1.0, Some(3.5)), &routes).unwrap();
assert!(again.cached && api.seen.borrow().len() == 4);
}
#[test]
fn a_video_already_there_isnt_sent() {
let (file, routes) = video("there");
let api = Api::new(vec![("/v1/clef/media", 200, json!({"kept": true})), ("/v1/clef/ask", 200, serde_json::from_str(BY_REF).unwrap())]);
by_reference::ask(&api, &by_ref(&file, 0.0, Some(2.0)), &routes).unwrap();
assert!(!api.seen.borrow().iter().any(|u| u.starts_with("PUT")), "{:?}", api.seen.borrow());
}
#[test]
fn an_older_raea_api_turns_it_off_and_the_clips_are_cut_here() {
let (file, routes) = video("older");
let api = Api::new(vec![("/v1/clef/media", 403, json!({"error": "agent_scope", "message": "an agent key reaches ..."}))]);
assert!(by_reference::api(&routes).is_some());
assert!(matches!(by_reference::ask(&api, &by_ref(&file, 0.0, Some(2.0)), &routes), Err(crate::Fail::Next(_))));
assert!(by_reference::off(&routes), "the rest of the run cuts its own clips");
// one that keeps videos but reads no source (bad_media) or can't cut (501) does the same
for (test, code, error) in [("no-source", 400, "bad_media"), ("no-cutter", 501, "cut_unavailable")] {
let (file, routes) = video(test);
let api = Api::new(vec![("/v1/clef/media", 200, json!({"kept": true})), ("/v1/clef/ask", code, json!({"error": error, "message": "no"}))]);
assert!(matches!(by_reference::ask(&api, &by_ref(&file, 0.0, Some(2.0)), &routes), Err(crate::Fail::Next(_))), "{test}");
assert!(by_reference::off(&routes), "{test}");
}
}
#[test]
fn a_window_raea_api_cant_cut_is_cut_here_and_the_rest_still_go_by_reference() {
let (file, routes) = video("too-large");
let api = Api::new(vec![("/v1/clef/media", 200, json!({"kept": true})), ("/v1/clef/ask", 413, json!({"error": "media_too_large", "message": "over 16 MB"}))]);
assert!(matches!(by_reference::ask(&api, &by_ref(&file, 0.0, Some(60.0)), &routes), Err(crate::Fail::Next(m)) if m.contains("16 MB")));
assert!(!by_reference::off(&routes));
}
#[test]
fn a_spent_pool_stops_and_only_an_agent_key_asks_by_reference() {
let (file, routes) = video("spent");
let api = Api::new(vec![("/v1/clef/media", 200, json!({"kept": true})), ("/v1/clef/ask", 402, json!({"error": "pool_spent", "message": "used up"}))]);
assert!(matches!(by_reference::ask(&api, &by_ref(&file, 0.0, Some(2.0)), &routes), Err(crate::Fail::Spent(_))));
let app_first = [Route::App("http://127.0.0.1:9".into()), routes[0].clone()];
let none = Api::new(vec![]);
assert!(matches!(by_reference::ask(&none, &by_ref(&file, 0.0, Some(2.0)), &app_first), Err(crate::Fail::Next(_))));
assert!(none.seen.borrow().is_empty(), "the app's route cuts its own clips");
}
+16 -4
View File
@@ -33,6 +33,8 @@ mod bevy_frame;
use bevy_frame::*; use bevy_frame::*;
mod keys; mod keys;
mod pages; mod pages;
mod plan;
pub use plan::plan_refused;
use pages::*; use pages::*;
mod program; mod program;
use 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). /// `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); 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. /// `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); 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 /// 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 /// (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). /// 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(()) }; 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()}); 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 // 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()] { for given 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)); 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())) std::fs::write(&path, v.to_string()).map_err(|e| format!("{}: {e}", path.display()))
} }
+119
View File
@@ -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);
}
}
+15
View File
@@ -28,6 +28,9 @@ pub fn render(args: &[String]) -> R<String> {
if args.iter().any(|a| a == "--clay") { if args.iter().any(|a| a == "--clay") {
raea_runtime_scene3d::clay::CLAY.store(true, std::sync::atomic::Ordering::Relaxed); 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 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 out = PathBuf::from(flag(args, "-o").ok_or("-o OUT.mp4|OUT.png|DIR")?);
let dir = tsx.parent().unwrap().to_path_buf(); 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<_>>()?), (_, Some(at)) => Some(at.split(',').map(|f| f.trim().parse::<i64>().map_err(|_| "--at takes frame numbers".to_string())).collect::<R<_>>()?),
_ => None, _ => 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") { if let Some(k) = flag(args, "--keys") {
*KEYS.lock().unwrap() = Some(PathBuf::from(k)); *KEYS.lock().unwrap() = Some(PathBuf::from(k));
let said = render_bundle_with(&js, &dir, &out, None, false, None, false); 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() { if let Some(to) = KEYS.lock().unwrap().take() {
return crate::keys::write(&to, &mut app, &mut page, &mut cx, (w, h, fps, total)); 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 fed {
if let Some(p) = scene { if let Some(p) = scene {
aov_on(raea_render::engine::Engine::open_in(&mut cx.scene3d, &p, dir)?); aov_on(raea_render::engine::Engine::open_in(&mut cx.scene3d, &p, dir)?);
-5
View File
@@ -50,11 +50,6 @@ ARG AGENTS="antigravity-acp claude-acp kimi-code"
RUN node server/agents.ts install $AGENTS RUN node server/agents.ts install $AGENTS
COPY src src COPY src src
COPY image image 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/git deploy/git
COPY deploy/fly/start.sh image/fly-start.sh 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 # readable by raea whatever modes the files had where the image was built (12-03: a checkout made with umask 077 gave
+4
View File
@@ -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 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 # 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. # 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 if [ -n "${RAEA_CLOUD_GPU_URL:-}" ] && [ -n "${1:-}" ]; then
case " ${RAEA_CLOUD_GPU_COMMANDS:-render} " in case " ${RAEA_CLOUD_GPU_COMMANDS:-render} " in
*" $1 "*) exec node /opt/raea-cloud/server/offload.ts "$@" ;; *" $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)))
+8 -99
View File
@@ -5,11 +5,8 @@
// says a fresh critic (`raea goal judge`) found it true of the work, after the work's last change // 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) // (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}}}. // 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 import { spawn } from "node:child_process"
// spawn failed the whole module there, so every `raea goal check` on a box died before it read a file (12-03, raea import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"
// 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 path from "node:path"
import { check, found } from "raea/check" import { check, found } from "raea/check"
import { type Contract, nameOf, type Said, saysOf } from "../contract.ts" import { type Contract, nameOf, type Said, saysOf } from "../contract.ts"
@@ -170,12 +167,9 @@ function piecesOf(r: Said, dir: string): string[] {
const named = [...new Set(r.says.match(PIECE) ?? [])].filter((f) => existsSync(path.join(dir, f))) 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) return named.length ? named : made(dir).slice(0, CLEF_PIECES)
} }
/** how many calls `raea ask` makes at once: one after another, a project's beats took 6-17 minutes of every goal check /** how many `raea ask`s run at once: each is one cut (or one stretch of it) heard and watched; one after another, a
* (12-03, StreetTalk: 18 of them, a cut's beats each a stretch); six `raea ask`s at once was a raea cloud box's ceiling, * project's beats took 6-17 minutes of every goal check (12-03, StreetTalk: 18 of them, a cut's beats each a stretch) */
* each decoding its cut (12-04). Now one `raea ask --batch` asks them all: through an agent key each window is asked by export const CLEF_AT_ONCE = 6
* reference (the cut sent once, raea-api cuts the window: docs/ask.feature AK3b) and costs the box nothing, so all at
* once; cut on the machine, each cut's windows are cut in one pass */
export const CLEF_AT_ONCE = 24
/** `f` on each item, at most `n` at once, the answers in the items' order */ /** `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[]> { async function pool<T, R>(items: T[], n: number, f: (t: T) => Promise<R>): Promise<R[]> {
@@ -204,11 +198,7 @@ export async function clefVerdict(g: Contract, dir: string, ask: Ask = askClef,
} }
const got = new Map<string, { pass: boolean; why: string }[]>() const got = new Map<string, { pass: boolean; why: string }[]>()
const list = [...groups.values()] const list = [...groups.values()]
const jobs = list.map((k) => ({ file: k.file, says: k.rules.map((r) => r.says), from: k.from, to: 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))
// raea's own: one `raea ask --batch` for every window; a caller's own `ask` (a test) one job at a time
const heard = ask !== askClef
? await pool(list, CLEF_AT_ONCE, async (k) => ask(dir, k.file, k.rules.map((r) => r.says), k.from, k.to))
: asyncSpawn() ? await askClefManyAsync(dir, jobs) : askClefMany(dir, jobs)
for (const [j, k] of list.entries()) { for (const [j, k] of list.entries()) {
const answers = heard[j] 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"}` }])) 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"}` }]))
@@ -225,97 +215,16 @@ export async function clefVerdict(g: Contract, dir: string, ask: Ask = askClef,
} }
type Answer = { choice?: string; says?: string; problem?: string | null } type Answer = { choice?: string; says?: string; problem?: string | null }
type Ask = (dir: string, file: string, says: string[], from?: string, to?: string) => Answer[] | Promise<Answer[]> type Ask = (dir: string, file: string, says: string[], from?: string, to?: string) => Answer[] | Promise<Answer[]>
type AskJob = { file: string; says: string[]; from?: string; to?: string }
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"
/** a question's id from its words, as `raea ask` makes it (apps/ask verbs.rs own_id), so a batch's ids are the command
* line's and its cached answers still count */
export const ownId = (words: string) => `own-${words.split(/[^A-Za-z0-9]+/).filter(Boolean).slice(0, 6).map((w) => w.toLowerCase()).join("-")}`.slice(0, 64)
/** one job a batch line (apps/ask verbs.rs from_batch): its file, its window, its rules as true-or-false questions */
const batchLine = (k: AskJob) => JSON.stringify({
file: k.file,
...(k.from || k.to ? { window: { ...(k.from ? { from: Number(k.from) } : {}), ...(k.to ? { to: Number(k.to) } : {}) } } : {}),
questions: k.says.map((s) => ({ id: ownId(s), ask: s, type: "choose", options: ["true", "false"] })),
})
/** the batch's answers back to their jobs, by file, window and question id: each job's in its rules' order */
function answersOf(jobs: AskJob[], out: string, err: string): Answer[][] {
const at = (file: string, from: number, to: number | null) => [file, from, to].join("\u001f")
const want = new Map(jobs.map((k, i) => [at(k.file, Number(k.from ?? 0), k.to ? Number(k.to) : null), i]))
const got: (Answer | undefined)[][] = jobs.map((k) => k.says.map(() => undefined))
const why = new Map<number, string>()
for (const l of out.split("\n")) {
let o: { answer?: string; file?: string; id?: string; from?: number; to?: number | null; not_asked?: string; waits?: string } & Answer
try { o = JSON.parse(l) } catch { continue }
const j = want.get(at(String(o.file), Number(o.from ?? 0), o.to ?? null))
if (j === undefined) continue
if (!o.answer) { if (o.not_asked || o.waits) why.set(j, String(o.not_asked ?? o.waits)); continue }
const i = jobs[j].says.findIndex((s, n) => ownId(s) === o.id && !got[j][n])
if (i >= 0) got[j][i] = o
}
return jobs.map((k, j) => {
const rows = got[j].filter((a): a is Answer => !!a)
if (rows.length !== k.says.length) throw new Error(`raea ask answered ${rows.length} of ${k.says.length} about ${k.file}: ${why.get(j) ?? (err.trim().slice(-300) || out.trim().slice(-300))}`)
return rows
})
}
/** the batch written for `raea ask --batch`, in review/ (gone after) */
function batchFile(dir: string, jobs: AskJob[]): { file: string; args: string[]; done: () => void } {
const tmp = path.join(dir, "review", `.ask-${process.pid}-${Date.now()}`)
mkdirSync(tmp, { recursive: true })
const file = path.join(tmp, "batch.jsonl")
writeFileSync(file, jobs.map(batchLine).join("\n") + "\n")
return { file, args: ["ask", "--batch", file, "--json", "--jobs", String(Math.min(CLEF_AT_ONCE, jobs.length))], done: () => rmSync(tmp, { recursive: true, force: true }) }
}
/** every job in one `raea ask --batch` (12-04): the brief and each cut read once, each cut sent to raea-api once when the
* windows are asked by reference, else each cut's windows cut in one pass, CLEF_AT_ONCE calls at once. Where there's
* no async spawn (raea's runtime) it waits here; askClefManyAsync is the same with node's spawn */
export function askClefMany(dir: string, jobs: AskJob[]): Answer[][] {
if (!jobs.length) return []
const b = batchFile(dir, jobs)
try {
const r = cp.spawnSync(RAEA, b.args, { cwd: dir, encoding: "utf8", maxBuffer: 64 << 20 }) as { stdout?: string; stderr?: string; error?: Error }
if (r.error) throw new Error(`couldn't run raea ask: ${r.error.message}`)
return answersOf(jobs, String(r.stdout ?? ""), String(r.stderr ?? ""))
} finally {
b.done()
}
}
export function askClefManyAsync(dir: string, jobs: AskJob[]): Promise<Answer[][]> {
if (!jobs.length) return Promise.resolve([])
const b = batchFile(dir, jobs)
return new Promise<Answer[][]>((ok, no) => {
const c = cp.spawn(RAEA, b.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", () => {
try { ok(answersOf(jobs, out, err)) } catch (e) { no(e) }
})
}).finally(b.done)
}
/** `raea ask` on one file (or a stretch of it): run as a child, so several hear at once */ /** `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[]> { 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) => { 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 = "" let out = "", err = ""
c.stdout.setEncoding("utf8").on("data", (t: string) => (out += t)) c.stdout.setEncoding("utf8").on("data", (t: string) => (out += t))
c.stderr.setEncoding("utf8").on("data", (t: string) => (err = (err + t).slice(-4000))) 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("error", (e) => no(new Error(`couldn't run raea ask: ${e.message}`)))
c.on("close", () => { 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)}`)) 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) ok(rows)
}) })
-46
View File
@@ -1,46 +0,0 @@
import { expect, test } from "bun:test"
import { spawnSync } from "node:child_process"
import { mkdtempSync, readdirSync, readFileSync } from "node:fs"
import { tmpdir } from "node:os"
import path from "node:path"
// a stop's windows in one `raea ask --batch` (12-04): one after another its 18 beats took 7.7 minutes, and six `raea
// ask`s at once was a raea cloud box's ceiling, each decoding its cut. One batch reads the brief and each cut once and
// asks every window by reference (docs/ask.feature AK3b). A child with a stand-in raea (a second a run), since RAEA is
// read once, as goal.ts is loaded; on raea's runtime (no async spawn) and under node's spawn alike
for (const how of ["askClefMany", "askClefManyAsync"]) {
test(`${how} asks every job in one raea ask --batch and gives each job its answers in its rules' order`, () => {
const dir = mkdtempSync(path.join(tmpdir(), "raea-ask-many-"))
const log = path.join(dir, "runs.log")
const script = `
import { ${how} as ask } 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 ? ["The product is on screen from 1 s to 2 s", "Someone speaks"] : ["one"], ...(i < 5 ? { from: String(i), to: String(i + 1.5) } : {}) }))
const t0 = Date.now()
const got = await ask(${JSON.stringify(dir)}, jobs)
console.log(JSON.stringify({ ms: Date.now() - t0, n: got.map((r) => r.length), file: got[1][0].file, ids: got[1].map((a) => a.id), to: got[4][0].to, end: got[5][0].to }))
`
const r = spawnSync("bun", ["-e", script], { encoding: "utf8", env: { ...process.env, RAEA_REAL: path.join(import.meta.dir, "fixtures/fake-ask/raea"), FAKE_ASK_LOG: log } })
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")
expect(o.ids).toEqual(["own-the-product-is-on-screen-from", "own-someone-speaks"])
expect([o.to, o.end]).toEqual([5.5, null])
const runs = readFileSync(log, "utf8").trim().split("\n").map((l) => JSON.parse(l))
expect(runs.length).toBe(1)
expect(runs[0].slice(0, 1).concat(runs[0].slice(3))).toEqual(["ask", "--json", "--jobs", "6"])
expect(readdirSync(path.join(dir, "review"))).toEqual([])
})
}
test("a job the batch doesn't answer says why", () => {
const dir = mkdtempSync(path.join(tmpdir(), "raea-ask-short-"))
const script = `
import { askClefMany } from ${JSON.stringify(path.join(import.meta.dir, "../src/packs/goal.ts"))}
try { askClefMany(${JSON.stringify(dir)}, [{ file: "out/a.mp4", says: ["one"] }]) ; console.log("no error") } catch (e) { console.log(String(e.message)) }
`
// a raea that answers nothing (it only says its arguments back)
const r = spawnSync("bun", ["-e", script], { encoding: "utf8", env: { ...process.env, RAEA_REAL: "/bin/echo" } })
expect(r.stdout).toContain("raea ask answered 0 of 1 about out/a.mp4: ask --batch")
})
-14
View File
@@ -1,14 +0,0 @@
#!/usr/bin/env bun
// a stand-in `raea ask --batch FILE --json --jobs N`: after a second, one answer a line for each question of each line,
// as `raea ask --json` prints them; every run noted in $FAKE_ASK_LOG (one line a run, its arguments)
import { appendFileSync, readFileSync } from "node:fs"
const args = process.argv.slice(2)
if (process.env.FAKE_ASK_LOG) appendFileSync(process.env.FAKE_ASK_LOG, JSON.stringify(args) + "\n")
const at = args.indexOf("--batch")
if (args[0] !== "ask" || at < 0) { console.error(`the fake only answers a batch: ${args.join(" ")}`); process.exit(1) }
await Bun.sleep(1000)
for (const l of readFileSync(args[at + 1], "utf8").split("\n").filter(Boolean)) {
const e = JSON.parse(l)
for (const q of e.questions) console.log(JSON.stringify({ answer: "a", file: e.file, id: q.id, from: e.window?.from ?? 0, to: e.window?.to ?? null, choice: "true", says: "true (0.9)", problem: null }))
}
console.log(JSON.stringify({ summary: {} }))
+2 -3
View File
@@ -4,7 +4,7 @@ import { expect, test } from "bun:test"
import { mkdirSync, mkdtempSync, utimesSync, writeFileSync } from "node:fs" import { mkdirSync, mkdtempSync, utimesSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os" import { tmpdir } from "node:os"
import path from "node:path" import path from "node:path"
import { CLEF_AT_ONCE, clefVerdict, judge, lastVerdict, NO_CRITIC, newest } from "../src/packs/goal.ts" import { clefVerdict, judge, lastVerdict, NO_CRITIC, newest } from "../src/packs/goal.ts"
import { goalCheck } from "../src/run.ts" import { goalCheck } from "../src/run.ts"
import { project, put } from "./project.ts" import { project, put } from "./project.ts"
@@ -164,7 +164,6 @@ test("clef hears several cuts at once, and the critic reads while it does", asyn
now-- now--
return says.map(() => ({ choice: "true", says: "fine" })) return says.map(() => ({ choice: "true", says: "fine" }))
}) })
// a caller's own ask is held to CLEF_AT_ONCE (24): all eight at once expect(most).toBe(6)
expect(most).toBe(Math.min(CLEF_AT_ONCE, names.length))
expect(rules.seen?.pass).toBe(true) expect(rules.seen?.pass).toBe(true)
}) })