Compare commits

..
Author SHA1 Message Date
shinyobjectz 3b5934aeae Farm: a job's files are listed 32 at a time, and a slow start says where it went
Each file's stat is a trip to the volume: one after another, 511 files took 9.7 s at each end of every job. A job that drew nothing took 46 s; it takes 16 s.
2026-12-01 22:21:53 -08:00
shaneandshinyobjectz 06a48730d1 A box says a Claude agent's turn has ended from its Stop hook (#302)
The hook is written into the socket's own settings and touches a file the box watches; as with a transcript's end, it's said only when nothing the agent started still runs.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 21:53:29 -08:00
shaneandshinyobjectz 28d89f8ffd Goal check: montage reads frames from a file, and keeps its findings beside the video (#301)
* The montage pack reads a video's frames from a file, not down a pipe

13 MB of small frames through the pipe took 9.7 s of a 35 s cut's read on a cloud box; into a file, 4.6 s.

* A video's montage findings are kept beside it, measured again when it or its beats change

Reading a 35 s cut's frames took 7 s each time the goal was checked, on files that hadn't changed.

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 21:40:48 -08:00
shaneandshinyobjectz 7b8317764a A made video's floor report is kept beside it, measured again only for cause (#300)
The measure took 26 s a cut and ran again on the same file at publish and at done. A kept report with an error is always measured again: what it names can be put right without the video changing.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 20:59:21 -08:00
shaneandshinyobjectz c69e28fac3 A box says when its agent's turn has ended: its transcript ended a step and nothing of its own still runs (#299)
Gemini wrote its last message without answering session/prompt, and the run stayed open 45 minutes until the idle agent was ended, read as cut off and started again. A step with no tool call is also how it waits on a job in the background (123 of 131 in one run), so the agent's processes are read with it.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 20:39:50 -08:00
shaneandshinyobjectz 83da71b62d A video's scene reading is kept beside it, and a kept reading isn't the work changing (#298)
A cut checked at its render was read again at publish and again at done, 30 s a file each time: a done check of 11 files took 334 s. And a done check that heard a cut's words wrote them beside it, so the critic's verdict of a minute before read as older than the work and every says rule failed again.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 19:01:29 -08:00
shaneandshinyobjectz 4d896d2b2f One size is one size however it's told: a name's 9x16, a 1080x1920 video, never a still (#297)
Told by pixels alone, an ad named _9x16 beside its own 1080x1920 renders and a 540x960 still read as three sizes, and an agent with one size made couldn't stop for its sign-off.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 18:43:59 -08:00
shaneandshinyobjectz d4d13925fa Farm: scene frames in parallel, 32 warm containers a video (#296)
* The farm reads a cut's scene frames on containers of their own, side by side

They went through the API's one core one after another inside its event loop: 70 frames of a 35 s ad took 37-47 s, and for that long every other call waited (a render's start 48 s, /v1/health 41 s, each job's follow). A whole goal check on a 35 s cut: 34 s, from 77-98.

* The farm draws a video on up to 32 containers, kept warm a minute, and says where a slow job's end went

A 35 s 1080x1920 cut: 80 s from the box's call to its file, from 104-160. At 8 containers its parts ran two after another on each; at 2 s idle every render's containers started cold.

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 18:22:58 -08:00
shaneandshinyobjectz a8d7263235 A caption over a person's body is a warning; over a face or what the shot shows it stays an error (#295)
Two people fill a 9:16 interview frame, and each caption's clearest place is a different one: an agent spent hours cropping shots and rendering again to clear errors that a steady caption position can't. The warning still names the clear place.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 18:22:53 -08:00
shaneandshinyobjectz d0f09511fe A file of another codec is refused from its moov box, not after the whole file is read (#294)
On Linux every open of an HEVC file tried the portable backend first, which read the whole file into memory to learn
it wasn't H.264 (0.1.16-rc4 on a Sprite: a cold probe of a 1.1 GB interview still took minutes, warm 1.8 s). The
sample entry is read from the moov box first. rotation_of read the whole file for a matrix: the moov box alone.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 12:38:36 -08:00
shaneandshinyobjectz 1a8a7df53d Opening a video, probing it and making its contact sheet no longer read the whole file (#293)
On a cloud Sprite one `raea media probe` of a 1.1 GB 4K interview took 112 s, and its 16-frame sheet 32 s where
ffmpeg alone takes 7 (12-01, measured). Three causes:

- The ffmpeg backend asked ffprobe for every packet's time on each open, and for MP4 and QuickTime ffprobe reads every
  packet to answer: 1 GB read per open, and a sheet opened its file once a frame. The times now come from the file's
  own sample tables (io/ffmpeg mov.rs; the same times as ffprobe's on 45 of 45 real client clips, up to one shift),
  and ffprobe is asked only for the stream's facts. Fragments, other containers and edit lists that do more than set
  a start are asked of ffprobe as before.
- `media probe` decoded the whole sound track to learn its rate, channels and length: read from the track's tables.
- A sheet's frames are read four at a time.

The Sprite's service sets its disks' read-ahead to 16 MB at each start: at the disk's own 256 KB, with each read
answered in about 26 ms, a pass over footage ran at 10 MB/s.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 11:22:11 -08:00
shaneandshinyobjectz ef8ea7563d On Windows a file asked for by its whole path is that file, not a package's name (#278) (#292)
0.1.16-rc2's Windows build failed its own new check: brief.ts importing react found the React raea ships, which was
then asked for again by its path (D:\..\react\index.js) and read as a package named that: "Cannot find package
'D:\...\index.js'". The resolver knew a whole path only by a leading slash.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 09:42:49 -08:00
shaneandshinyobjectz 6716b6b9f0 A Sprite's setup installs the open faces brands are closest to, and box.sh up builds a Sprite just made (#291)
A Sprite had Liberation and DejaVu alone, so every cut's type fell back to Liberation Sans. setup.sh now installs Inter,
Roboto, Open Sans, Lato, Montserrat, Noto, IBM Plex, Bebas Neue and the URW base 35, each when the Ubuntu has it.
box.sh up ended with curl's exit 7 on a Sprite just made (its wait for running agents asked a server that isn't there
yet).

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 09:12:06 -08:00
shaneandshinyobjectz 313ac8ab83 A project's file that imports react finds the React raea ships (#278) (#290)
* A project's file that imports react finds the React raea ships, as raea's own files do (#278)

0.1.15 let raea's own files (sdk/app) find react in the release's one node_modules. A project's file still could not:
brief.ts, or a scene it registers, imports its hooks from "react", a project has no package.json, and the render's
own checks load brief.ts. So a render was applied, then failed with "brief.ts doesn't run: Cannot find package
'react'" and "fix every ERROR above, then render again", on every release through 0.1.16-rc1.

Any file with no node_modules of its own above it now gets the package raea ships (the bundler gives a scene the same
React); a project's own copy still wins, and a package raea doesn't ship is still not found. The release's check of
the built archive renders beside such a brief.ts on every platform.

* The archive's check of a brief.ts that imports react runs on every build, not only on real machines

* node.rs back under the size limit

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 08:41:09 -08:00
shaneandshinyobjectz cdfb043026 clef's second opinion on a cut is a list of pointed picture and sound checks, the faults it found first (#289)
Asked "do the graphics look designed", clef graded Dutch's plain boxes "strong". Asked pointed yes/no checks of the
same cut it found three of them: three or more text boxes at once (0.93), captions, cards and badges all the same
plain box (0.57), the app shown only as a box of text (0.80). Shane, 12-01: "you just have to have them be more
specific or pointed like giving it some list of design checks to answer ... a few catch all checks on visual and
audio design"; "the agent itself is really responsible for design".

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 06:16:58 -08:00
shaneandshinyobjectz 35267727b8 raea goal seen judges a video's design at full size; a project's design is the agent's own (#288)
* raea goal seen judges a video's design at full size, with clef as a second opinion; a project's design is the agent's own within the brand's colours

A contact sheet's tiles show what happens in a cut, never whether its type, captions and cards look good, and it was
the only picture an agent looked at before sign-off. raea goal seen FILE now also writes six frames at full size
(FILE.looks/) and the seen pack holds a video until --look says how its design stands beside a reference. On raea
cloud it prints clef's grades of the whole cut, picture and sound, lowest first, as a second opinion.
A project's AGENTS.md no longer says "never a colour, font or size of your own": the brand's colours and faces are
the palette, and size, weight, shape, layout and motion are designed for the piece.

* skills: raea goal seen's frames at full size and --look (raea-skills #148)

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 06:02:21 -08:00
shaneandshinyobjectz c72717a635 RAEA_MEDIA=ffmpeg encodes with the system's H.264 encoder where ffmpeg has no libx264 (the LGPL build raea ships on Windows: h264_mf), at the bitrate (#279) (#287)
Co-authored-by: shinyobjectz <[email protected]>
2026-11-30 22:15:21 -08:00
shaneandshinyobjectz 0256cb9673 The AppImage's two pinned tools come from raea's own copy when GitHub's download fails (the runner got HTTP 618 three times for v0.1.15-rc1, and the Linux archive waits on it) (#286)
Co-authored-by: shinyobjectz <[email protected]>
2026-11-30 21:57:25 -08:00
41 changed files with 1152 additions and 178 deletions

No files matched your search

+26 -4
View File
@@ -40,6 +40,29 @@ pub fn still(path: &Path, at: f64, out: &Path, width: Option<u32>) -> R<Value> {
Ok(json!({"wrote": out, "at": at, "width": img.width(), "height": img.height()}))
}
/// `f(0..n)`, up to four at a time, in order: a sheet's frames are each a seek and a decode of their own (16 of a 4K
/// interview: 7 s one after another, 4 s so).
fn at_once<T: Send>(n: usize, f: impl Fn(usize) -> R<T> + Sync) -> R<Vec<T>> {
use std::sync::{Mutex, atomic::{AtomicUsize, Ordering}};
let workers = std::thread::available_parallelism().map_or(2, |c| c.get()).clamp(1, 4).min(n.max(1));
let next = AtomicUsize::new(0);
let out: Vec<Mutex<Option<R<T>>>> = (0..n).map(|_| Mutex::new(None)).collect();
std::thread::scope(|s| {
for _ in 0..workers {
s.spawn(|| {
loop {
let i = next.fetch_add(1, Ordering::Relaxed);
if i >= n {
break;
}
*out[i].lock().unwrap() = Some(f(i));
}
});
}
});
out.into_iter().map(|m| m.into_inner().unwrap().unwrap_or_else(|| Err("a frame wasn't read".into()))).collect()
}
pub fn sheet(files: &[PathBuf], n: usize, w: u32, out: &Path) -> R<Value> {
if files.is_empty() {
return Err("raea media sheet FILE... -o OUT: which files?".into());
@@ -47,10 +70,9 @@ pub fn sheet(files: &[PathBuf], n: usize, w: u32, out: &Path) -> R<Value> {
let mut tiles = Vec::new();
if files.len() == 1 {
let p = probe_of(&files[0])?;
for i in 0..n.max(1) {
let t = (i as f64 + 0.5) / n.max(1) as f64 * p.duration;
tiles.push((t, frame(&files[0], t)?));
}
let at: Vec<f64> = (0..n.max(1)).map(|i| (i as f64 + 0.5) / n.max(1) as f64 * p.duration).collect();
let read = at_once(at.len(), |i| frame(&files[0], at[i]))?;
tiles.extend(at.into_iter().zip(read));
} else {
for f in files {
let p = probe_of(f)?;
+69 -62
View File
@@ -1,6 +1,7 @@
//! `media probe`: what a file is (duration, size, fps, codec, audio), with the MP4 boxes read directly for a track's own timing.
use super::*;
use raea_io_media::mp4box::{be32, be64, boxes, child, moov_of};
pub(crate) fn round3(x: f64) -> f64 {
(x * 1000.0).round() / 1000.0
@@ -38,7 +39,11 @@ pub fn probe_of(path: &Path) -> R<Probe> {
}
i
});
let audio = soft()?.decode_audio(path).ok().filter(|a| a.len() > 0).map(|a| (a.rate, a.channels.len(), a.duration()));
// what the file states, when it does; else the track decoded (WAV, MP3, a container read no other way)
let audio = match audio_track(path) {
Some(a) => Some(a),
None => soft()?.decode_audio(path).ok().filter(|a| a.len() > 0).map(|a| (a.rate, a.channels.len(), a.duration())),
};
if video.is_none() && audio.is_none() {
// what each backend said about the picture: a missing FFmpeg, a codec none of them reads
let why = why.map(|w| format!(" ({})", w.split_once(": no backend reads it (").map_or(w.as_str(), |(_, r)| r.trim_end_matches(')')).to_string())).unwrap_or_default();
@@ -124,74 +129,37 @@ impl Track {
}
}
/// The boxes inside `b` (a box's payload): (type, payload).
pub(crate) fn boxes(b: &[u8]) -> Vec<([u8; 4], &[u8])> {
let mut out = Vec::new();
let mut i = 0usize;
while i + 8 <= b.len() {
let mut size = u32::from_be_bytes(b[i..i + 4].try_into().unwrap()) as usize;
let kind: [u8; 4] = b[i + 4..i + 8].try_into().unwrap();
let mut hdr = 8;
if size == 1 && i + 16 <= b.len() {
size = u64::from_be_bytes(b[i + 8..i + 16].try_into().unwrap()) as usize;
hdr = 16;
} else if size == 0 {
size = b.len() - i;
/// The first sound track as the file states it (rate, channels, seconds), for MP4 and QuickTime files: `media probe`
/// decoded the whole track to learn these, which read every byte of a 1 GB interview (two minutes on a network disk).
pub fn audio_track(path: &Path) -> Option<(u32, usize, f64)> {
audio_in(&moov_of(path)?)
}
pub(crate) fn audio_in(moov: &[u8]) -> Option<(u32, usize, f64)> {
for (k, trak) in boxes(moov) {
if &k != b"trak" {
continue;
}
if size < hdr || i + size > b.len() {
break;
let Some(mdia) = child(trak, b"mdia") else { continue };
if child(mdia, b"hdlr").and_then(|h| h.get(8..12)) != Some(&b"soun"[..]) {
continue;
}
out.push((kind, &b[i + hdr..i + size]));
i += size;
let mdhd = child(mdia, b"mdhd")?;
let (scale, dur) = if mdhd.first() == Some(&1) { (be32(mdhd, 20)? as f64, be64(mdhd, 24)? as f64) } else { (be32(mdhd, 12)? as f64, be32(mdhd, 16)? as f64) };
// the first sample description: version at 24, channels at 32, rate (16.16) at 40; QuickTime's version 2 states
// them again as a double at 48 and a count at 56
let stsd = child(child(child(mdia, b"minf")?, b"stbl")?, b"stsd")?;
let v2 = stsd.get(24..26) == Some(&[0u8, 2][..]);
let rate = if v2 { f64::from_bits(be64(stsd, 48)?) } else { be32(stsd, 40)? as f64 / 65536.0 };
let channels = if v2 { be32(stsd, 56)? as usize } else { u16::from_be_bytes(stsd.get(32..34)?.try_into().ok()?) as usize };
return (scale > 0.0 && dur > 0.0 && rate >= 1.0 && (1..=64).contains(&channels)).then_some((rate.round() as u32, channels, dur / scale));
}
out
}
pub(crate) fn child<'a>(b: &'a [u8], kind: &[u8; 4]) -> Option<&'a [u8]> {
boxes(b).into_iter().find(|(k, _)| k == kind).map(|(_, p)| p)
}
pub(crate) fn be32(b: &[u8], at: usize) -> Option<u32> {
Some(u32::from_be_bytes(b.get(at..at + 4)?.try_into().ok()?))
}
pub(crate) fn be64(b: &[u8], at: usize) -> Option<u64> {
Some(u64::from_be_bytes(b.get(at..at + 8)?.try_into().ok()?))
None
}
/// The first video track's timing, for MP4 and QuickTime files.
pub fn video_track(path: &Path) -> Option<Track> {
use std::io::{Read, Seek, SeekFrom};
let mut f = std::fs::File::open(path).ok()?;
let len = f.metadata().ok()?.len();
// the top-level boxes, to moov (read alone: mdat can be gigabytes)
let mut at = 0u64;
let moov = loop {
if at + 8 > len {
return None;
}
let mut h = [0u8; 16];
f.seek(SeekFrom::Start(at)).ok()?;
f.read_exact(&mut h[..8]).ok()?;
let mut size = u32::from_be_bytes(h[..4].try_into().ok()?) as u64;
let mut hdr = 8u64;
if size == 1 {
f.read_exact(&mut h[8..]).ok()?;
size = u64::from_be_bytes(h[8..].try_into().ok()?);
hdr = 16;
} else if size == 0 {
size = len - at;
}
if size < hdr {
return None;
}
if &h[4..8] == b"moov" {
let mut m = vec![0u8; (size - hdr).min(256 << 20) as usize];
f.read_exact(&mut m).ok()?;
break m;
}
at += size;
};
let moov = moov_of(path)?;
for (k, trak) in boxes(&moov) {
if &k != b"trak" {
continue;
@@ -295,3 +263,42 @@ pub(crate) fn rate_fraction(fps: f64) -> String {
}
// ---- pictures
#[cfg(test)]
mod tests {
use super::*;
fn bx(kind: &[u8; 4], body: &[u8]) -> Vec<u8> {
let mut v = ((body.len() + 8) as u32).to_be_bytes().to_vec();
v.extend_from_slice(kind);
v.extend_from_slice(body);
v
}
#[test]
fn a_sound_track_is_read_from_the_file_s_own_tables() {
// mdhd v0: 48 kHz timescale, 10 s; stsd: one mp4a entry, 2 channels, 48000 Hz
let mut mdhd = vec![0u8; 24];
mdhd[12..16].copy_from_slice(&48000u32.to_be_bytes());
mdhd[16..20].copy_from_slice(&480000u32.to_be_bytes());
let mut hdlr = vec![0u8; 24];
hdlr[8..12].copy_from_slice(b"soun");
let mut stsd = vec![0u8; 44];
stsd[7] = 1;
stsd[12..16].copy_from_slice(b"mp4a");
stsd[32..34].copy_from_slice(&2u16.to_be_bytes());
stsd[40..44].copy_from_slice(&(48000u32 << 16).to_be_bytes());
let mdia = [bx(b"mdhd", &mdhd), bx(b"hdlr", &hdlr), bx(b"minf", &bx(b"stbl", &bx(b"stsd", &stsd)))].concat();
// a picture track ahead of it is passed over
let mut vh = vec![0u8; 24];
vh[8..12].copy_from_slice(b"vide");
let moov = [bx(b"trak", &bx(b"mdia", &bx(b"hdlr", &vh))), bx(b"trak", &bx(b"mdia", &mdia))].concat();
assert_eq!(audio_in(&moov), Some((48000, 2, 10.0)));
// no sound track, or one that states no rate: nothing (the track is decoded instead)
assert_eq!(audio_in(&bx(b"trak", &bx(b"mdia", &bx(b"hdlr", &vh)))), None);
let mut silent = stsd.clone();
silent[40..44].copy_from_slice(&0u32.to_be_bytes());
let mdia = [bx(b"mdhd", &mdhd), bx(b"hdlr", &hdlr), bx(b"minf", &bx(b"stbl", &bx(b"stsd", &silent)))].concat();
assert_eq!(audio_in(&bx(b"trak", &bx(b"mdia", &mdia))), None);
}
}
+4
View File
@@ -456,6 +456,10 @@ Feature: Goal: the loop every piece of work runs, one goal or a workflow of them
And the seen pack holds it until its contact sheet has been shown since its last render (FILE.seen.json: the
render's time and size, what the agent said it sees and would change, at least 80 characters), and the
surprise pack, when on, until it names its moment in seconds and what it is
And it holds a video until its design is judged too, on its frames at full size (FILE.looks/, six through the
cut, made by `raea goal seen FILE`): `--look "..."`, at least 80 characters on its type, captions, cards and
end beside a reference and what was changed, since a sheet's tiles show what happens and never how it looks
(12-01, Shane on Dutch: "why do components not look good. is it even proofing or reviewing the work?")
And on a Mac the same packs hold through `raea goal seen FILE` (the sheet, shown in the raea app with
`raea show`) and `raea goal seen FILE "WHAT I SEE AND WOULD CHANGE"`, which write FILE.seen.json; raea cloud's
publish tool writes it through the same command
+5 -4
View File
@@ -33,7 +33,7 @@ The packs, and what each holds:
| `place` | cut | no text over a face, a person or what the shot is about where a clear place of its size exists |
| `floor` | cut, floor | no clipped text, low contrast, freeze, flash or loudness out of range |
| `stills` | every kind, floor | a composition's three stills as it's saved: no clipped or cramped text, nothing out of the safe areas |
| `seen` | cut, floor | its contact sheet looked at since its last render (`raea goal seen FILE`, then `raea goal seen FILE "..."`) |
| `seen` | cut, floor | its contact sheet and its frames at full size looked at since its last render (`raea goal seen FILE`, then `raea goal seen FILE "..." --look "..."`) |
| `surprise` | when a brief turns it on | one earned surprise named with its moment in seconds |
| `naming` | cut | every video and still named client_concept_variant_v#_size |
| `sizes` | cut | one size first: no other size before a person approves the first |
@@ -80,7 +80,7 @@ export default brief({
```sh
raea goal check # done: everything, as the Stop hook runs it
raea goal check out/cuts/acme_dog_hook1_v2_9x16.mp4 --at render
raea goal seen out/cuts/acme_dog_hook1_v2_9x16.mp4 && raea goal seen out/cuts/acme_dog_hook1_v2_9x16.mp4 "..."
raea goal seen out/cuts/acme_dog_hook1_v2_9x16.mp4 && raea goal seen out/cuts/acme_dog_hook1_v2_9x16.mp4 "..." --look "..."
raea goal tasks --json # the brief's plan, every task
raea goal next
```
@@ -97,7 +97,7 @@ goal's rules are never copied into the plan: the plan is the work, the goal is w
```sh
raea goal check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--manifest render.json] [--json] (every rule each goal of brief.ts is held to at that moment: its kind's packs, its rules and its own checks; with no goal, the floor; every project is also held to `registered`, every raea file reached from brief.ts; review/goal.json; exit 1 on an error. The hook runs it at every save (edit) and stop (done), a render at its end, raea cloud at publish)
raea goal tasks [DIR] [--json] | raea goal tasks [DIR] --apply EDITS.json|- | raea goal tasks [DIR] --put PUT.json|- (the brief's plan as the brief's run gives it: open tasks by id, or all as JSON; --apply writes edits by task id back where each task is written, refusing one made by code; a project with no plan gets plan.ts, imported by brief.ts; --put {plan, base} writes the whole plan back only while the brief's is still base)
raea goal seen FILE ["what you see and would change"] [--surprise "SECONDS s: what it is"] (FILE's contact sheet beside it, to look at every frame; with words, what was seen of FILE as it is now)
raea goal seen FILE ["what you see and would change" --look "its design at full size, beside a reference"] [--surprise "SECONDS s: what it is"] (FILE's contact sheet beside it, and its frames at full size in FILE.looks/, to look at; with words, what was seen of FILE as it is now, and --look how a video's type, captions and cards look at full size)
raea goal judge [--goal NAME] [--by claude|kimi|clef] (a goal's `says` rules judged by a fresh critic that only reads; review/judge/NAME.json. clef watches and hears the files a rule names, else the videos under out/, paid as `raea ask` is: the critic where RAEA_AGENT_KEY is set, as on raea cloud, else claude)
raea goal next [DIR] (the two or three useful next steps for the project, from its brief, its goals, compositions, renders and checks)
raea goal gates [DIR] [--goal NAME] --json (a scene, kit or shot goal's record and critic gates, as raea/goal's packs read them)
@@ -111,9 +111,10 @@ Headless: it needs nothing running and opens no window. Takes any number of argu
| --- | --- | --- |
| `--apply` | `EDITS.json\|-` | plan edits (JSON, `-` for stdin), each written where its task is written |
| `--at` | `edit\|render\|publish\|done` | The moment `check` runs the rules of (default `done`); for `place`, the seconds to read (`S[,S...]`). |
| `--by` | `claude\|kimi` | The critic `judge` asks, a fresh session that may only read (default `claude`). |
| `--by` | `claude\|kimi\|clef` | The critic `judge` asks, a fresh session that may only read (default `claude`). |
| `--goal` | `NAME` | only this goal of the brief's (by its name) |
| `--json` | – | `check`: print the report (review/goal.json's shape). `gates`: the record and critic gates as JSON. |
| `--look` | `"its design` | `seen`: a video's design judged on its frames at full size (FILE.looks/): its type, captions, cards and end beside a reference, and what was changed. |
| `--manifest` | `render.json` | the render's manifest, for the sound pack's takes and effects |
| `--only` | `ID,...` | `check`: only these checks. Otherwise only these objects (refs, gen, pick-sheet, prep) or shots (framing), by id or name. |
| `--put` | `PUT.json\|-` | `{plan, base}`: the whole plan written back only while the brief's is still `base` |
+1 -1
View File
@@ -14,7 +14,7 @@ pub const GOAL_TS: &[&str] = &["check", "tasks", "seen", "judge"];
/// The goal verbs' usage, under the help's (usage.rs reads each verb's flags from it).
pub const GOAL_USAGE: &str = "raea goal check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--manifest render.json] [--json] (every rule each goal of brief.ts is held to at that moment: its kind's packs, its rules and its own checks; with no goal, the floor; every project is also held to `registered`, every raea file reached from brief.ts; review/goal.json; exit 1 on an error. The hook runs it at every save (edit) and stop (done), a render at its end, raea cloud at publish)
raea goal tasks [DIR] [--json] | raea goal tasks [DIR] --apply EDITS.json|- | raea goal tasks [DIR] --put PUT.json|- (the brief's plan as the brief's run gives it: open tasks by id, or all as JSON; --apply writes edits by task id back where each task is written, refusing one made by code; a project with no plan gets plan.ts, imported by brief.ts; --put {plan, base} writes the whole plan back only while the brief's is still base)
raea goal seen FILE [\"what you see and would change\"] [--surprise \"SECONDS s: what it is\"] (FILE's contact sheet beside it, to look at every frame; with words, what was seen of FILE as it is now)
raea goal seen FILE [\"what you see and would change\" --look \"its design at full size, beside a reference\"] [--surprise \"SECONDS s: what it is\"] (FILE's contact sheet beside it, and its frames at full size in FILE.looks/, to look at; with words, what was seen of FILE as it is now, and --look how a video's type, captions and cards look at full size)
raea goal judge [--goal NAME] [--by claude|kimi|clef] (a goal's `says` rules judged by a fresh critic that only reads; review/judge/NAME.json. clef watches and hears the files a rule names, else the videos under out/, paid as `raea ask` is: the critic where RAEA_AGENT_KEY is set, as on raea cloud, else claude)
raea goal next [DIR] (the two or three useful next steps for the project, from its brief, its goals, compositions, renders and checks)";
+8 -5
View File
@@ -80,11 +80,14 @@ A video edit as a React + TypeScript project, rendered by raea.
- cuts.ts: the clips (\`raea cut\` writes it, with cuts.json and words.json beside it; re-run it rather than editing
by hand, or captions and checks lose their timing). components/: components you added (\`raea make component add\`), yours to change.
- brand/brand.css: the brand's tokens (\`raea brand DOMAIN\` reads them from the brand's site). edit.tsx loads them with the project's
Tailwind: \`<style>{css}</style>\`, css from "./styles.gen" (raea render writes it). Style only with the brand
classes: colour text-brand-accent, bg-brand-accent, bg-brand-surface (bg-brand-bg), text-brand-on-surface,
text-brand-on-accent, text-brand-ink, brand-1/2/3; face font-brand, font-brand-body; size text-display,
text-title, text-caption, text-body, text-label (scaled for a 1080-wide frame); corners rounded-brand. Where a
class can't reach, the --brand-* variables. Never a colour, font or size of your own.
Tailwind: \`<style>{css}</style>\`, css from "./styles.gen" (raea render writes it). The brand's colours and
faces are the palette, as classes: colour text-brand-accent, bg-brand-accent, bg-brand-surface (bg-brand-bg),
text-brand-on-surface, text-brand-on-accent, text-brand-ink, brand-1/2/3; face font-brand, font-brand-body (where
the brand's face is missing, install a free face close to it, never a system fallback); the --brand-* variables
where a class can't reach. Never a colour from outside the brand. The design is yours: size, weight, shape, layout
and motion are chosen for this piece, against how the brand's own best work looks, not from a default. The sizes
text-display, text-title, text-caption, text-body, text-label (scaled for a 1080-wide frame) and rounded-brand are
a start, not a limit.
- \`raea render edit.tsx -o final.mp4 --manifest render.json\`, then \`raea check final.mp4 --manifest render.json
--words words.json --perception perception.json\` says what's wrong; \`raea render edit.tsx --at 105 -o stills/\`
gives frame 105 to look at. \`raea guide\` has the craft (\`raea guide motion\` for writing the TSX);
+6 -6
View File
@@ -30,11 +30,11 @@ const EXTS: &[&str] = &["", ".ts", ".tsx", ".mts", ".js", ".mjs", ".cjs", ".json
/// `spec` imported from a file in `dir` (`esm`: an import, else a require), to the file it names
pub fn resolve_file(spec: &str, dir: &Path, esm: bool) -> Result<PathBuf, String> {
let raw = spec.strip_prefix("file://").unwrap_or(spec);
if raw.starts_with("./") || raw.starts_with("../") || raw.starts_with('/') || raw == "." || raw == ".." {
let want = if raw.starts_with('/') { PathBuf::from(raw) } else { dir.join(raw) };
// (a path whole on Windows too, `D:\..`: the React raea ships, found, was asked for again by its path and read as a package's name, #278)
if raw.starts_with("./") || raw.starts_with("../") || raw.starts_with('/') || raw == "." || raw == ".." || Path::new(raw).is_absolute() {
let want = if raw.starts_with('/') || Path::new(raw).is_absolute() { PathBuf::from(raw) } else { dir.join(raw) };
return as_file(&want).ok_or_else(|| format!("Cannot find module '{spec}' from {}", dir.display()));
}
// a package: its name (a scope takes two parts) and the subpath after it
let mut parts = raw.splitn(if raw.starts_with('@') { 3 } else { 2 }, '/');
let name = if raw.starts_with('@') { format!("{}/{}", parts.next().unwrap_or(""), parts.next().unwrap_or("")) } else { parts.next().unwrap_or("").to_string() };
let sub = parts.next().map(|s| format!("./{s}")).unwrap_or_else(|| ".".into());
@@ -53,9 +53,9 @@ pub fn resolve_file(spec: &str, dir: &Path, esm: bool) -> Result<PathBuf, String
return Ok(f);
}
}
// raea's own file (sdk/app, under `raea goal check`) importing a package raea ships: a release has those in the React runtime's node_modules alone (#278)
let (home, own) = (raea_io_home::home(), raea_io_home::home().join("sdk/react/js/node_modules").join(&name));
if dir.starts_with(&home) && own.is_dir() {
// a package raea ships, imported by a file with no node_modules of its own: raea's (sdk/app), or a project's brief.ts or scene (#278)
let own = raea_io_home::home().join("sdk/react/js/node_modules").join(&name);
if own.is_dir() {
return package_entry(&own, &sub, esm).ok_or_else(|| format!("Cannot find module '{spec}': {} has no {sub}", own.display()));
}
Err(format!("Cannot find package '{name}' imported from {}", dir.display()))
+17 -3
View File
@@ -1,4 +1,4 @@
//! A file of raea's own importing a package raea ships finds it in the React runtime's node_modules (#278): a release has
//! A file importing a package raea ships (raea's own, or a project's with no node_modules) finds it in the React runtime's node_modules (#278): a release has
//! no node_modules above sdk/app, so `raea goal check` ended every render "Cannot find package 'react'". Its own test
//! binary: raea's home is read once a process.
#![cfg(feature = "modules")]
@@ -16,7 +16,21 @@ fn raeas_own_file_finds_the_react_raea_ships() {
// SAFETY: the one test here, before anything reads the environment
unsafe { std::env::set_var("RAEA_HOME", &home) };
assert_eq!(raea_native::node::resolve_file("react", &own, true).unwrap(), pkg.join("index.js"));
// a project's own file never reaches into raea's packages
assert!(raea_native::node::resolve_file("react", &theirs, true).unwrap_err().contains("Cannot find package 'react'"));
// a project's file with no node_modules of its own gets the same React (brief.ts, a scene it registers): a release's
// render was applied and then failed its checks on "Cannot find package 'react'"
fs::create_dir_all(&theirs).unwrap();
assert_eq!(raea_native::node::resolve_file("react", &theirs, true).unwrap(), pkg.join("index.js"));
// its own copy, when it has one, wins
let mine = theirs.join("node_modules/react");
fs::create_dir_all(&mine).unwrap();
fs::write(mine.join("package.json"), r#"{"name":"react","main":"index.js"}"#).unwrap();
fs::write(mine.join("index.js"), "module.exports = {}").unwrap();
assert_eq!(raea_native::node::resolve_file("react", &theirs, true).unwrap(), mine.join("index.js"));
// a file asked for by its whole path is that file, on Windows too (`D:\..` was read as a package's name)
let whole = pkg.join("index.js");
assert_eq!(raea_native::node::resolve_file(whole.to_str().unwrap(), &theirs, true).unwrap(), whole);
// and a package raea doesn't ship is still not found
assert!(raea_native::node::resolve_file("left-pad", &own, true).unwrap_err().contains("Cannot find package 'left-pad'"));
fs::remove_dir_all(&theirs).ok();
fs::remove_dir_all(&home).ok();
}
+1
View File
@@ -5,6 +5,7 @@
pub mod audio;
pub mod mezz;
pub mod mp4box;
#[cfg(feature = "mux")]
pub mod remux;
pub mod samples;
+73
View File
@@ -0,0 +1,73 @@
//! An MP4 or QuickTime file's boxes, read directly: what `media probe` and the ffmpeg backend take a track's own facts
//! from (its frame times, its sound's rate) without reading the gigabytes of pictures beside them.
use std::io::{Read, Seek, SeekFrom};
use std::path::Path;
/// The boxes inside `b` (a box's payload): (type, payload).
pub fn boxes(b: &[u8]) -> Vec<([u8; 4], &[u8])> {
let mut out = Vec::new();
let mut i = 0usize;
while i + 8 <= b.len() {
let mut size = u32::from_be_bytes(b[i..i + 4].try_into().unwrap()) as usize;
let kind: [u8; 4] = b[i + 4..i + 8].try_into().unwrap();
let mut hdr = 8;
if size == 1 && i + 16 <= b.len() {
size = u64::from_be_bytes(b[i + 8..i + 16].try_into().unwrap()) as usize;
hdr = 16;
} else if size == 0 {
size = b.len() - i;
}
if size < hdr || i + size > b.len() {
break;
}
out.push((kind, &b[i + hdr..i + size]));
i += size;
}
out
}
pub fn child<'a>(b: &'a [u8], kind: &[u8; 4]) -> Option<&'a [u8]> {
boxes(b).into_iter().find(|(k, _)| k == kind).map(|(_, p)| p)
}
pub fn be32(b: &[u8], at: usize) -> Option<u32> {
Some(u32::from_be_bytes(b.get(at..at + 4)?.try_into().ok()?))
}
pub fn be64(b: &[u8], at: usize) -> Option<u64> {
Some(u64::from_be_bytes(b.get(at..at + 8)?.try_into().ok()?))
}
/// The file's moov box, read alone (mdat can be gigabytes).
pub fn moov_of(path: &Path) -> Option<Vec<u8>> {
let mut f = std::fs::File::open(path).ok()?;
let len = f.metadata().ok()?.len();
let mut at = 0u64;
loop {
if at + 8 > len {
return None;
}
let mut h = [0u8; 16];
f.seek(SeekFrom::Start(at)).ok()?;
f.read_exact(&mut h[..8]).ok()?;
let mut size = u32::from_be_bytes(h[..4].try_into().ok()?) as u64;
let mut hdr = 8u64;
if size == 1 {
f.read_exact(&mut h[8..]).ok()?;
size = u64::from_be_bytes(h[8..].try_into().ok()?);
hdr = 16;
} else if size == 0 {
size = len - at;
}
if size < hdr {
return None;
}
if &h[4..8] == b"moov" {
let mut m = vec![0u8; usize::try_from(size - hdr).ok().filter(|n| *n <= 256 << 20)?];
f.read_exact(&mut m).ok()?;
return Some(m);
}
at += size;
}
}
+19 -10
View File
@@ -9,6 +9,8 @@ use raea_io_codec::{
Audio, Backend, EncodeOpts, EncodeStats, Frame, Info, R, VideoDecoder, VideoEncoder, as_of,
};
mod mov;
pub struct Ffmpeg;
/// The ffmpeg or ffprobe to run: the PATH's, else raea's own (raea_io_assets::ffmpeg_tool). Opening a video (`fetch`)
@@ -124,6 +126,12 @@ const NVENC: [&str; 14] = ["-c:v", "h264_nvenc", "-preset", "p5", "-tune", "hq",
/// The facts, the presentation times, whether the colour matrix is untagged, and the decoder a VP8 or VP9 stream with
/// alpha needs (libvpx: ffmpeg's own VP9 decoder drops the alpha WebM keeps beside the picture, #113).
fn probe(path: &Path) -> R<(Info, Vec<f64>, bool, Option<&'static str>)> {
probe_with(path, mov::frame_times(path))
}
/// `tabled`: the frame times the file's own tables state (mov.rs). Without them ffprobe is asked for every packet's
/// time, which reads the whole file.
fn probe_with(path: &Path, tabled: Option<Vec<f64>>) -> R<(Info, Vec<f64>, bool, Option<&'static str>)> {
let out = cli("ffprobe", named_video(path))?
.args([
"-v",
@@ -132,11 +140,9 @@ fn probe(path: &Path) -> R<(Info, Vec<f64>, bool, Option<&'static str>)> {
"v:0",
"-show_entries",
"stream=codec_name,width,height,r_frame_rate,color_space:stream_tags=alpha_mode:stream_side_data=rotation:format=duration",
"-show_entries",
"packet=pts_time",
"-of",
"json",
])
.args(if tabled.is_none() { &["-show_entries", "packet=pts_time"][..] } else { &[] })
.args(["-of", "json"])
.arg(path)
.output()
.map_err(|e| format!("ffprobe: {e}"))?;
@@ -159,12 +165,15 @@ fn probe(path: &Path) -> R<(Info, Vec<f64>, bool, Option<&'static str>)> {
.and_then(|r| r.split_once('/'))
.map(|(n, d)| n.parse::<f64>().unwrap_or(30.0) / d.parse::<f64>().unwrap_or(1.0))
.unwrap_or(30.0);
let mut pts: Vec<f64> = j["packets"]
.as_array()
.into_iter()
.flatten()
.filter_map(|p| p["pts_time"].as_str().and_then(|t| t.parse().ok()))
.collect();
let mut pts: Vec<f64> = match tabled {
Some(t) => t,
None => j["packets"]
.as_array()
.into_iter()
.flatten()
.filter_map(|p| p["pts_time"].as_str().and_then(|t| t.parse().ok()))
.collect(),
};
pts.sort_by(f64::total_cmp);
let duration = j["format"]["duration"]
.as_str()
+81
View File
@@ -0,0 +1,81 @@
//! An MP4 or QuickTime file's frame times from its own sample tables. Opening a video asked ffprobe for every packet's
//! time, and for these files ffprobe reads every packet to say it: each open of a 1 GB interview read 1 GB (two
//! minutes on a cloud Sprite's disk, 12-01), and a contact sheet opened its file once a frame.
use std::path::Path;
use raea_io_codec::mp4box::{be32, be64, boxes, child, moov_of};
/// Every frame's presentation time in seconds, sorted, as ffprobe's packets give them up to one shift of them all
/// (the decoder uses them from the first on). None for a file that isn't MP4 or QuickTime, one in fragments (mvex), and one
/// whose edit list does more than set where the track starts: those are asked of ffprobe as before.
pub(crate) fn frame_times(path: &Path) -> Option<Vec<f64>> {
let ext = path.extension()?.to_string_lossy().to_ascii_lowercase();
if !["mp4", "mov", "m4v"].contains(&ext.as_str()) {
return None;
}
times_in(&moov_of(path)?)
}
fn times_in(moov: &[u8]) -> Option<Vec<f64>> {
if child(moov, b"mvex").is_some() {
return None;
}
for (k, trak) in boxes(moov) {
if &k != b"trak" {
continue;
}
let Some(mdia) = child(trak, b"mdia") else { continue };
if child(mdia, b"hdlr").and_then(|h| h.get(8..12)) != Some(&b"vide"[..]) {
continue;
}
// an edit list that plays the track from one place on is a shift of every time; one with a gap ahead of it,
// or more than one piece, moves frames apart
if let Some(elst) = child(trak, b"edts").and_then(|e| child(e, b"elst")) {
if be32(elst, 4)? != 1 {
return None;
}
let from = if elst.first() == Some(&1) { be64(elst, 16)? as i64 } else { be32(elst, 12)? as i32 as i64 };
if from < 0 {
return None;
}
}
let mdhd = child(mdia, b"mdhd")?;
let scale = if mdhd.first() == Some(&1) { be32(mdhd, 20)? } else { be32(mdhd, 12)? } as f64;
if scale <= 0.0 {
return None;
}
let stbl = child(child(mdia, b"minf")?, b"stbl")?;
let stts = child(stbl, b"stts")?;
let mut times: Vec<i64> = Vec::new();
let mut dts = 0i64;
for e in 0..be32(stts, 4)? as usize {
let (n, d) = (be32(stts, 8 + e * 8)?, be32(stts, 12 + e * 8)? as i64);
// a table that claims more frames than a day of 240 a second isn't one to trust
if times.len() + n as usize > 20_736_000 {
return None;
}
for _ in 0..n {
times.push(dts);
dts += d;
}
}
if let Some(ctts) = child(stbl, b"ctts") {
let mut i = 0usize;
for e in 0..be32(ctts, 4)? as usize {
// signed whatever the version says: QuickTime writes negative offsets in version 0 boxes
let (n, off) = (be32(ctts, 8 + e * 8)? as usize, be32(ctts, 12 + e * 8)? as i32 as i64);
for t in times.iter_mut().skip(i).take(n) {
*t += off;
}
i += n;
}
}
if times.is_empty() {
return None;
}
times.sort_unstable();
return Some(times.into_iter().map(|t| t as f64 / scale).collect());
}
None
}
+36
View File
@@ -65,3 +65,39 @@ fn a_system_encoder_takes_the_bitrate() {
assert!(ok && std::fs::metadata(&out).is_ok_and(|m| m.len() > 500), "ffmpeg encodes with the system encoder's arguments");
let _ = std::fs::remove_file(&out);
}
/// An MP4's and a QuickTime file's frame times, read from their own tables, are the ones ffprobe's packets give (up to
/// one shift of them all), with B-frames, at a rate that isn't whole, and the same frames come out either way.
#[test]
fn a_file_s_own_tables_give_ffprobe_s_frame_times() {
let dir = std::env::temp_dir().join(format!("raea-ffmpeg-tables-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let make = |name: &str, args: &[&str]| {
let p = dir.join(name);
let ok = Command::new("ffmpeg").args(["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=s=128x72:r=30000/1001:d=2", "-pix_fmt", "yuv420p"]).args(args).arg(&p).status().is_ok_and(|s| s.success());
ok.then_some(p)
};
let files = [make("b.mp4", &["-c:v", "libx264", "-bf", "3"]), make("b.mov", &["-c:v", "libx264", "-bf", "2", "-g", "12"]), make("plain.mp4", &["-c:v", "mpeg4"])];
let mut seen = 0;
for f in files.into_iter().flatten() {
let Some(tabled) = mov::frame_times(&f) else { panic!("{}: its tables weren't read", f.display()) };
let (_, asked, ..) = probe_with(&f, None).unwrap();
assert_eq!(tabled.len(), asked.len(), "{}: as many frames", f.display());
for (a, b) in tabled.iter().zip(&asked) {
assert!(((a - tabled[0]) - (b - asked[0])).abs() < 2e-4, "{}: {a} against {b}", f.display());
}
// and the decoder gives the same picture at a time either way
let (info, pts, ..) = probe(&f).unwrap();
assert_eq!(pts.len(), info.frames);
let mut d = Ffmpeg.open_video(&f).unwrap();
let at = d.frame_at(1.0).unwrap();
assert!((at.pts - 1.0).abs() < 0.04, "{}: the frame at 1 s is at {}", f.display(), at.pts);
seen += 1;
}
let _ = std::fs::remove_dir_all(&dir);
if seen == 0 {
eprintln!("skipped: no ffmpeg here to make a file with");
}
// a file in fragments, or of another kind, is asked of ffprobe as before
assert!(mov::frame_times(Path::new("a.webm")).is_none());
}
+22 -1
View File
@@ -58,7 +58,23 @@ pub struct Track {
/// A file's first video track's display rotation (clockwise degrees; 0 when it has none or isn't an MP4/MOV).
pub fn rotation_of(path: &Path) -> i32 {
std::fs::read(path).map(|b| mp4_rotation(&b)).unwrap_or(0)
// the moov box alone, as a file of that one box (the whole file was read for it: gigabytes, for a matrix)
let Some(moov) = raea_io_codec::mp4box::moov_of(path) else { return 0 };
let mut b = ((moov.len() + 8) as u32).to_be_bytes().to_vec();
b.extend_from_slice(b"moov");
b.extend_from_slice(&moov);
mp4_rotation(&b)
}
/// The first video track's sample entry (avc1, hvc1, av01, ...), from the moov box alone.
fn video_fourcc(path: &Path) -> Option<[u8; 4]> {
use raea_io_codec::mp4box::{boxes, child, moov_of};
let moov = moov_of(path)?;
boxes(&moov).into_iter().filter(|(k, _)| k == b"trak").find_map(|(_, trak)| {
let mdia = child(trak, b"mdia")?;
(child(mdia, b"hdlr")?.get(8..12)? == b"vide").then_some(())?;
child(child(child(mdia, b"minf")?, b"stbl")?, b"stsd")?.get(12..16)?.try_into().ok()
})
}
/// The first video track's display rotation, from its tkhd matrix (QuickTime's 16.16 a, b, c, d).
@@ -107,6 +123,11 @@ fn mp4_rotation(b: &[u8]) -> i32 {
}
pub fn demux(path: &Path, want: &str) -> R<Track> {
// another codec's file is refused before it is read: every open of a 4K HEVC interview on Linux read its whole
// gigabyte here to learn it wasn't H.264, then went to the backend that reads it (two minutes on a cloud disk)
if let Some(is) = video_fourcc(path).filter(|f| want.len() >= 3 && f[..3] != want.as_bytes()[..3]) {
return Err(format!("{}: {}, not {want} (this backend reads {want} mezzanines)", path.display(), String::from_utf8_lossy(&is)));
}
let bytes = std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?;
let mp4 = re_mp4::Mp4::read_bytes(&bytes).map_err(|e| format!("{}: {e}", path.display()))?;
let (_, t) = mp4
+37
View File
@@ -0,0 +1,37 @@
//! A file of another codec is refused from its moov box alone, and a rotation is read from it, without the file's
//! pictures being read (a 1 GB HEVC interview was read whole on every open to learn it wasn't H.264).
use std::path::{Path, PathBuf};
use std::process::Command;
fn made(dir: &Path, name: &str, args: &[&str]) -> Option<PathBuf> {
let p = dir.join(name);
Command::new("ffmpeg").args(["-v", "error", "-y"]).args(args).arg(&p).status().is_ok_and(|s| s.success()).then_some(p)
}
#[test]
fn another_codec_is_refused_by_its_tables_and_a_rotation_read_from_them() {
let dir = std::env::temp_dir().join(format!("raea-soft-refuse-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let src = ["-f", "lavfi", "-i", "testsrc2=s=128x72:r=30:d=1", "-pix_fmt", "yuv420p"];
let Some(other) = made(&dir, "other.mp4", &[&src[..], &["-c:v", "mpeg4"]].concat()) else { return eprintln!("skipped: no ffmpeg here") };
let e = raea_io_soft::demux(&other, "avc1").err().expect("an MPEG-4 file isn't H.264");
assert!(e.contains("mp4v, not avc1"), "{e}");
// cut short after its moov, the refusal is the same: nothing past the tables was needed
if let Some(front) = made(&dir, "front.mp4", &[&src[..], &["-c:v", "mpeg4", "-movflags", "+faststart"]].concat()) {
let bytes = std::fs::read(&front).unwrap();
let mdat = bytes.windows(4).position(|w| w == b"mdat").unwrap();
std::fs::write(&front, &bytes[..mdat + 4]).unwrap();
assert!(raea_io_soft::demux(&front, "avc1").err().unwrap().contains("mp4v, not avc1"));
assert_eq!(raea_io_soft::rotation_of(&front), 0);
}
// an H.264 file is read as before, and one turned on its side says so
if let Some(h264) = made(&dir, "h264.mp4", &[&src[..], &["-c:v", "libx264"]].concat()) {
assert!(raea_io_soft::demux(&h264, "avc1").is_ok());
assert_eq!(raea_io_soft::rotation_of(&h264), 0);
let h = h264.to_string_lossy().to_string();
if let Some(turned) = made(&dir, "turned.mp4", &["-display_rotation:v:0", "90", "-i", &h, "-c", "copy"]) {
assert_eq!(raea_io_soft::rotation_of(&turned).rem_euclid(180), 90);
}
}
let _ = std::fs::remove_dir_all(&dir);
}
+101 -43
View File
@@ -32,6 +32,7 @@ import re
import resource
import shutil
import subprocess
import threading
import time
import uuid
@@ -81,8 +82,10 @@ GPUS = int(os.environ.get("RAEA_FARM_GPUS", "10")) # Modal Starter's GPU limit;
JOB_GPUS = int(os.environ.get("RAEA_FARM_JOB_GPUS", "4"))
# the containers with no GPU a job's video with no 3D is drawn on at once (raea_cpu_run), and the farm's in all: no
# workspace limit holds these back as it does GPUs
JOB_CPUS = int(os.environ.get("RAEA_FARM_JOB_CPUS", "8"))
CPUS = int(os.environ.get("RAEA_FARM_CPUS", "40"))
# 32 since 12-01: at 8, a 34 s ad's 16 parts ran two after another on each container, 53 s of a 104 s render, and
# at 16 a 35 s one still drew for 73 s beside another job; the containers' seconds, and so the bill, are the same
JOB_CPUS = int(os.environ.get("RAEA_FARM_JOB_CPUS", "32"))
CPUS = int(os.environ.get("RAEA_FARM_CPUS", "128"))
ROOT = "/farm"
JOBS = f"{ROOT}/jobs"
@@ -168,6 +171,8 @@ CACHES = {"__GL_SHADER_DISK_CACHE": "1", "__GL_SHADER_DISK_CACHE_PATH": f"{ROOT}
# the scene reader's models, loaded once a container (/v1/scene)
SCENE = None
# one reading at a time a container: the models aren't safe to run from two threads
SCENE_LOCK = threading.Lock()
# when this container's Python started, for the job's bill (farm_plan.Bill)
BOOTED = time.time()
@@ -199,16 +204,21 @@ def run(cmd, cwd=None, env=None, timeout=6 * 3600):
def snapshot(d):
out = {}
for base, _, files in os.walk(d):
for f in files:
p = os.path.join(base, f)
try:
s = os.stat(p)
except OSError: # a link that points nowhere here (a box's kits/ link to its cache): not a file of the job's
continue
out[os.path.relpath(p, d)] = f"{s.st_size}:{s.st_mtime_ns}"
return out
# each file's stat is a trip to the volume (about 19 ms): one after another, 511 files took 9.7 s at each end of
# every job, drawn or not (12-01). Asked 32 at once
from concurrent.futures import ThreadPoolExecutor
paths = [os.path.join(base, f) for base, _, files in os.walk(d) for f in files]
def one(p):
try:
s = os.stat(p)
except OSError: # a link that points nowhere here (a box's kits/ link to its cache): not a file of the job's
return None
return os.path.relpath(p, d), f"{s.st_size}:{s.st_mtime_ns}"
with ThreadPoolExecutor(32) as pool:
return dict(x for x in pool.map(one, paths) if x)
class Log:
@@ -228,6 +238,10 @@ class Log:
# a GPU stays up this long after its last run, billed (farm_plan.SCALEDOWN): at 60 s, the farm's jobs of 11-17 billed
# about five times their GPUs' working seconds
SCALEDOWN = 2
# a container with no GPU stays up this long: an agent renders its cuts one after another and each again after an
# edit, and at 2 s every render's containers started cold, about 20 s of a 54 s draw (12-01). A minute of 16 idle ones
# is about $0.06, which a job's own bill (farm_plan.Bill) leaves out: the next job may be the one that uses it
CPU_SCALEDOWN = 60
def on(gpus, job):
@@ -291,7 +305,7 @@ def raea_run(id: str, args: list[str], frames: list[int] | None = None, first: i
return raea_frames(id, args, frames, first, probe, video, {"RAEA_NV": "1"} if nv else None)
@app.function(cpu=farm_cpu[0], memory=farm_cpu[1] * 1024, volumes={ROOT: vol, "/models": models}, timeout=6 * 3600, max_containers=CPUS, scaledown_window=SCALEDOWN)
@app.function(cpu=farm_cpu[0], memory=farm_cpu[1] * 1024, volumes={ROOT: vol, "/models": models}, timeout=6 * 3600, max_containers=CPUS, scaledown_window=CPU_SCALEDOWN)
def raea_cpu_run(id: str, args: list[str], frames: list[int] | None = None, first: int = 0, probe: bool = False, video: bool = False, nv: bool = False) -> dict:
"""raea_run on a container with no GPU (lavapipe draws), for a video with no 3D in it: the planner sends those
here after frame 0 (farm_plan.raea_render), and a run that fails here or has 3D in it goes back to a GPU."""
@@ -408,7 +422,9 @@ def coordinate(id: str, args: list[str], opts: dict):
log = Log(id)
log(f"raea farm: raea {' '.join(args)}")
t_start = [time.time()]
vol.reload()
t_start.append(time.time())
work = f"{JOBS}/{id}/work"
try:
farm_media.fetch(work, f"{ROOT}/blobs", log)
@@ -420,8 +436,15 @@ def coordinate(id: str, args: list[str], opts: dict):
return
# the media just linked (or fetched) into the job, committed before any GPU container reloads to render it: without
# this a still on this container found the footage and every GPU run of a video didn't ("No such file", 11-25)
t_start.append(time.time())
vol.commit()
t_start.append(time.time())
before = snapshot(work)
t_start.append(time.time())
# where a job's start goes, said when it's slow, as its end is
if t_start[-1] - t_start[0] > 5:
d = [b - a for a, b in zip(t_start, t_start[1:])]
log(f"raea farm: the job's start took {sum(d):.0f} s: reloading {d[0]:.1f} s, its media {d[1]:.1f} s, saving {d[2]:.1f} s, listing its files {d[3]:.1f} s")
try:
# a video's frames' keys (farm_keys.py): its runs kept by them under the raea that drew them (a release's
# version and the build's own file, so a new engine starts a store of its own; kept=0 draws every frame), and
@@ -434,7 +457,9 @@ def coordinate(id: str, args: list[str], opts: dict):
except Exception as e: # the job's own failure, said in its log; the farm goes on
log(f"raea farm: {e!r}", err=True)
code = 1
t_end = [time.time()]
vol.commit()
t_end.append(time.time())
# what the job's GPU containers committed (a whole render's stills, its folder output) is only seen here after a
# reload: without it a render to a folder came back empty while a joined .mp4, written here, came back (11-20).
# Another job's open files in this coordinator refuse a reload (ConflictError, 11-21: a 500 for the box): try again,
@@ -448,7 +473,9 @@ def coordinate(id: str, args: list[str], opts: dict):
log(f"raea farm: the volume wouldn't reload ({e}); returning what this container sees", err=True)
else:
time.sleep(pause)
t_end.append(time.time())
after = snapshot(work)
t_end.append(time.time())
changed = [p for p, v in after.items() if before.get(p) != v]
if opts.get("media"):
# the job's media stays here until the box names where in R2 it goes (POST media); the rest comes back in /out
@@ -460,10 +487,66 @@ def coordinate(id: str, args: list[str], opts: dict):
with open(f"{JOBS}/{id}/changed.txt", "w") as f:
f.write("".join(p + "\n" for p in changed))
shutil.rmtree(f"{JOBS}/{id}/frames", ignore_errors=True)
t_end.append(time.time())
vol.commit()
t_end.append(time.time())
# where a job's end goes, said when it's slow (12-01: 17-60 s between the join and the box hearing it's done)
if t_end[-1] - t_end[0] > 5:
d = [b - a for a, b in zip(t_end, t_end[1:])]
log(f"raea farm: the job's end took {sum(d):.0f} s: saving {d[0]:.1f} s, reloading {d[1]:.1f} s, listing what changed {d[2]:.1f} s, clearing its frames {d[3]:.1f} s, saving again {d[4]:.1f} s")
log.end(code)
def seams(g):
"""a split screen's seams: rows (h) or columns (v) where the picture jumps across nearly all of the frame, as a
cut between two pictures does and nothing filmed does (a caption's box spans part of it, a horizon is soft)"""
import numpy as np
found = []
for axis, d in (("h", np.abs(np.diff(g, axis=0))), ("v", np.abs(np.diff(g, axis=1)).T)):
n = d.shape[0]
share = (d > 24).mean(axis=1)
for i in range(int(n * 0.08), int(n * 0.92)):
if share[i] > 0.7 and share[i] >= share[max(i - 1, 0)] and share[i] >= share[min(i + 1, n - 1)]:
found.append([axis, i + 1, round(float(share[i]), 2)])
return found
def read_scenes(frames):
"""Each base64 JPEG's scene (farm_scene.Scene.read and its seams), None for one that isn't a picture"""
import base64
import cv2
import numpy as np
import farm_scene
global SCENE
with SCENE_LOCK:
if SCENE is None:
SCENE = farm_scene.Scene()
out = []
for b64 in frames:
im = cv2.imdecode(np.frombuffer(base64.b64decode(b64), np.uint8), cv2.IMREAD_COLOR)
if im is None:
out.append(None)
continue
r = SCENE.read(im)
r["seams"] = seams(cv2.cvtColor(im, cv2.COLOR_BGR2GRAY).astype(np.int16))
out.append(r)
return out
# A cut's frames went through the API's one core one after another, inside its event loop: 70 frames of a 35 s ad took
# 37-47 s, and for that long every other call waited (a render's start 48 s, /v1/health 41 s, each job's follow; 12-01).
# More than SCENE_HERE frames are shared out to these, SCENE_PART each; fewer are read in the API on a thread.
SCENE_HERE = 4
SCENE_PART = 6
@app.function(cpu=2, memory=4096, timeout=600, max_containers=CPUS, scaledown_window=60)
def scene_run(frames: list[str]) -> list:
return read_scenes(frames)
@app.function(cpu=1, memory=4096, volumes={ROOT: vol}, secrets=[secret, words_secret], timeout=3600)
@modal.concurrent(max_inputs=32)
@modal.asgi_app()
@@ -548,19 +631,6 @@ def api():
# cloud's library index uses (apps/app host/library/words.ts) hears it here. The body is one MP3 piece (16 kHz mono,
# at most 10 minutes; the box cuts the pieces), the answer its words in the piece's own seconds. 11-25, Shane: "give
# it whatever we use for indexing and libraries and sync", so agents check the words their cuts say.
def seams(g):
"""a split screen's seams: rows (h) or columns (v) where the picture jumps across nearly all of the frame, as a
cut between two pictures does and nothing filmed does (a caption's box spans part of it, a horizon is soft)"""
import numpy as np
found = []
for axis, d in (("h", np.abs(np.diff(g, axis=0))), ("v", np.abs(np.diff(g, axis=1)).T)):
n = d.shape[0]
share = (d > 24).mean(axis=1)
for i in range(int(n * 0.08), int(n * 0.92)):
if share[i] > 0.7 and share[i] >= share[max(i - 1, 0)] and share[i] >= share[min(i + 1, n - 1)]:
found.append([axis, i + 1, round(float(share[i]), 2)])
return found
@web.post("/v1/scene")
async def scene(req: Request):
@@ -569,11 +639,6 @@ def api():
(each face [x, y, w, h, "face", score]), a grid of where people are, and its things
(COCO's, and words in the shot as "text") as [x, y, w, h, label, score], and each line of text read as texts
[x, y, w, h, "the text", score], in that frame's pixels"""
import base64
import cv2
import numpy as np
import farm_scene
check(req)
body = await req.json()
frames = body.get("frames") if isinstance(body, dict) else None
@@ -581,18 +646,11 @@ def api():
raise HTTPException(400, 'the body is {"frames": [base64 JPEG, ...]}')
if len(frames) > 400:
raise HTTPException(413, "at most 400 frames a call")
global SCENE
if SCENE is None:
SCENE = farm_scene.Scene()
out = []
for b64 in frames:
im = cv2.imdecode(np.frombuffer(base64.b64decode(b64), np.uint8), cv2.IMREAD_COLOR)
if im is None:
out.append(None)
continue
r = SCENE.read(im)
r["seams"] = seams(cv2.cvtColor(im, cv2.COLOR_BGR2GRAY).astype(np.int16))
out.append(r)
if len(frames) <= SCENE_HERE:
out = await asyncio.to_thread(read_scenes, frames)
else:
parts = [frames[i:i + SCENE_PART] for i in range(0, len(frames), SCENE_PART)]
out = [r async for part in scene_run.map.aio(parts) for r in part]
return {"model": "pphumanseg-2023mar+yolox-s-2022nov+ppocrv3-db-2023may+yunet-2023mar+rapidocr-ppocrv4", "frames": out}
@web.post("/v1/words")
+2 -1
View File
@@ -86,7 +86,8 @@ up)
# rebuilds anyway (raea cloud then resumes the cut-off runs, projects.ts resumeRequest).
if [ "${RAEA_BOX_FORCE:-}" != 1 ]; then
for i in $(seq 1 90); do
n=$(x ". ~/.raea-cloud.env 2>/dev/null; curl -fsS -m 5 -H \"authorization: Bearer \$RAEA_CLOUD_TOKEN\" localhost:8080/v1/health 2>/dev/null" | python3 -c 'import json,sys
# (a Sprite just made has no server yet: curl's own exit ended this script, 12-01)
n=$(x ". ~/.raea-cloud.env 2>/dev/null; curl -fsS -m 5 -H \"authorization: Bearer \$RAEA_CLOUD_TOKEN\" localhost:8080/v1/health 2>/dev/null || true" | python3 -c 'import json,sys
try: print(json.load(sys.stdin).get("running", "unknown"))
except Exception: print("down")')
# down: nothing to cut off; unknown: a server too old to say, so it isn't rebuilt blind
+8
View File
@@ -21,6 +21,11 @@ say packages
sudo -E apt-get update -qq
sudo -E apt-get install -y -qq --no-install-recommends ca-certificates curl git git-lfs zstd xz-utils procps ripgrep \
libasound2t64 libfontconfig1 libvulkan1 mesa-vulkan-drivers vulkan-tools > /dev/null
# faces an ad is set in (12-01: a box had Liberation and DejaVu alone, so every cut fell back to Liberation Sans): the
# open families brands are closest to, each taken when this Ubuntu has it
for f in fonts-inter fonts-roboto fonts-open-sans fonts-lato fonts-montserrat fonts-noto-core fonts-ibm-plex fonts-bebas-neue fonts-urw-base35 fonts-liberation2; do
dpkg -s "$f" > /dev/null 2>&1 || sudo -E apt-get install -y -qq --no-install-recommends "$f" > /dev/null 2>&1 || say "no $f here"
done
node -v 2> /dev/null | grep -q '^v24' || {
say "node $NODE"
curl -fsSL "https://nodejs.org/dist/v$NODE/node-v$NODE-linux-x64.tar.xz" | sudo tar -xJ -C /opt
@@ -103,6 +108,9 @@ cat > /opt/raea-cloud/image/sprite-start.sh << 'EOF'
set -a
. ~/.raea-cloud.env
set +a
# footage is read 16 MB ahead: a Sprite's disk answers each read in about 26 ms, and at its own 256 KB a pass over
# a 1 GB interview took two minutes that takes 14 s so (12-01, measured). Set at each start: a Sprite woken keeps none.
for b in /sys/class/bdi/*/read_ahead_kb /sys/block/*/queue/read_ahead_kb; do sudo sh -c "echo 16384 > $b" 2> /dev/null || true; done
export PORT=8080 RAEA_CLOUD_DEVICE=cpu WGPU_BACKEND=vulkan __EGL_VENDOR_LIBRARY_DIRS=/nonexistent
export VK_DRIVER_FILES=$(ls /usr/share/vulkan/icd.d/lvp_icd*.json | head -1)
mkdir -p ~/work
+22 -1
View File
@@ -34,6 +34,7 @@
// Every route but /healthz needs RAEA_CLOUD_TOKEN: `Authorization: Bearer TOKEN`, or ?token= (a browser's WebSocket
// can't set headers). The agent and raea get the container's environment without the token or the state keys.
import { claudeStopHook, jobsOf, markedEnd, watchEnd, watchTurnEnd } from "./turn-end.ts"
import { execFileSync, spawn } from "node:child_process"
import { timingSafeEqual } from "node:crypto"
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, symlinkSync, writeFileSync } from "node:fs"
@@ -412,7 +413,27 @@ server.on("upgrade", (req, socket, head) => {
buf += c
for (let i; (i = buf.indexOf("\n")) >= 0; buf = buf.slice(i + 1)) if (i > 0) ws.send(buf.slice(0, i))
})
ws.on("message", (m) => ((heard = Date.now()), child.stdin.write(m.toString() + "\n")))
let heardFromCaller = Date.now()
ws.on("message", (m) => ((heard = heardFromCaller = Date.now()), child.stdin.write(m.toString() + "\n")))
// the turn's end from the agent's own transcript, said along the socket (turn-end.ts): raea cloud closes the turn
// on it without waiting for an answer to session/prompt that may not come
{
const tellEnd = (by: string) => ws.readyState === ws.OPEN && ws.send(JSON.stringify({ jsonrpc: "2.0", method: "_raea/turn_end", params: { by } }))
const busy = () => !!child.pid && jobsOf(child.pid, path.dirname(agent.command), WORK).length > 0
let stopWatch: (() => void) | undefined
if (agent.id === "antigravity-acp" && env.GEMINI_HOME) stopWatch = watchTurnEnd(env.GEMINI_HOME, () => heardFromCaller, tellEnd, busy)
else if (agent.id === "claude-acp" && own && env.CLAUDE_CONFIG_DIR) {
// Claude says it itself, through a Stop hook in the socket's own settings (never the box's own home's)
try {
const mark = claudeStopHook(env.CLAUDE_CONFIG_DIR)
stopWatch = watchEnd(() => markedEnd(mark), "its Stop hook", () => heardFromCaller, tellEnd, busy)
} catch {}
}
if (stopWatch) {
ws.on("close", stopWatch)
child.on("exit", stopWatch)
}
}
ws.on("close", stopAll)
child.on("error", (e) => ws.close(1011, `couldn't start ${agent.id}: ${e.message}`.slice(0, 120)))
child.on("exit", (code) => (ws.close(1011, `${agent.id} exited ${code}`), stopAll()))
+165
View File
@@ -0,0 +1,165 @@
// A turn's end, read off the agent's own records and said along its socket as a `_raea/turn_end` notification, so raea
// cloud closes the turn in seconds whether or not the agent answers its session/prompt (12-01: Gemini wrote its delivery
// message and never answered; the run stayed open 45 minutes, until the idle agent was ended here, and was then read
// as cut off and started again. Shane: "should not be more than a couple seconds to detect a stall").
//
// Antigravity keeps a transcript of each session, a JSON line a step. A model step that finished and called no tool is
// the end of its turn only when nothing it started still runs: it ends a step the same way to wait on a render it left
// in the background (123 of 131 such steps in one run), and is woken when that finishes. So both are read:
// the transcript's last line, and the processes that are the agent's own.
import { closeSync, openSync, readdirSync, readFileSync, readlinkSync, readSync, statSync, writeFileSync } from "node:fs"
import path from "node:path"
/** the step a transcript line ends a turn at, and when it was made (ms); null for any other line */
export function turnEndOf(line: string): { step: number; at: number } | null {
let m: any
try {
m = JSON.parse(line)
} catch {
return null
}
if (!m || m.type !== "PLANNER_RESPONSE" || m.status !== "DONE" || m.source !== "MODEL") return null
if (Array.isArray(m.tool_calls) && m.tool_calls.length) return null
const at = Date.parse(m.created_at ?? "")
return typeof m.step_index === "number" && Number.isFinite(at) ? { step: m.step_index, at } : null
}
/** a file's last whole line */
export function lastLine(file: string, most = 1 << 20): string {
const size = statSync(file).size
const n = Math.min(size, most)
const b = Buffer.alloc(n)
const fd = openSync(file, "r")
try {
readSync(fd, b, 0, n, size - n)
} finally {
closeSync(fd)
}
const lines = b.toString("utf8").split("\n").filter(Boolean)
return lines.at(-1) ?? ""
}
/** the transcript written to last under an Antigravity home (GEMINI_HOME), or null */
export function newestTranscript(geminiHome: string): { file: string; mtime: number } | null {
const brain = path.join(geminiHome, "antigravity-acp", "brain")
let best: { file: string; mtime: number } | null = null
let names: string[] = []
try {
names = readdirSync(brain)
} catch {
return null
}
for (const n of names) {
const f = path.join(brain, n, ".system_generated", "logs", "transcript.jsonl")
try {
const m = statSync(f).mtimeMs
if (!best || m > best.mtime) best = { file: f, mtime: m }
} catch {}
}
return best
}
/** What an agent has running that isn't the agent itself: every process in its session (it's started detached, so
* the session is its own), descended from it, or working under `work` (a job started with a session of its own),
* but for the agent's own programs (under `agentDir`) and raea cloud's (their command names .raea-cloud). Linux /proc. */
export function jobsOf(pid: number, agentDir: string, work: string, proc = "/proc"): number[] {
const all: { pid: number; ppid: number; sid: number }[] = []
let names: string[] = []
try {
names = readdirSync(proc)
} catch {
return []
}
for (const n of names) {
if (!/^\d+$/.test(n)) continue
try {
// "pid (comm) state ppid pgrp session ...": comm may hold spaces and brackets, so read from its last ")"
const st = readFileSync(path.join(proc, n, "stat"), "utf8")
const f = st.slice(st.lastIndexOf(")") + 2).split(" ")
all.push({ pid: Number(n), ppid: Number(f[1]), sid: Number(f[3]) })
} catch {}
}
const kids = new Set<number>([pid])
for (let grew = true; grew; ) {
grew = false
for (const p of all) if (!kids.has(p.pid) && kids.has(p.ppid)) (kids.add(p.pid), (grew = true))
}
const link = (n: number, what: string) => {
try {
return readlinkSync(path.join(proc, String(n), what))
} catch {
return ""
}
}
const cmd = (n: number) => {
try {
return readFileSync(path.join(proc, String(n), "cmdline"), "utf8").replace(/\0/g, " ")
} catch {
return ""
}
}
return all
.filter((p) => p.pid !== pid && p.pid !== process.pid)
.filter((p) => p.sid === pid || kids.has(p.pid) || (link(p.pid, "cwd") + "/").startsWith(work.replace(/\/?$/, "/")))
.filter((p) => !link(p.pid, "exe").startsWith(agentDir) && !cmd(p.pid).includes(".raea-cloud"))
.map((p) => p.pid)
}
/** Claude Code's own word that its turn ended: a Stop hook in the agent's settings (CLAUDE_CONFIG_DIR/settings.json)
* that touches a file here. Other settings and hooks already there are kept. Returns the file. */
export function claudeStopHook(configDir: string): string {
const mark = path.join(configDir, ".raea-turn-end")
const file = path.join(configDir, "settings.json")
let settings: any = {}
try {
settings = JSON.parse(readFileSync(file, "utf8"))
} catch {}
if (!settings || typeof settings !== "object" || Array.isArray(settings)) settings = {}
const command = `touch '${mark.replace(/'/g, "'\\''")}'`
const hooks = (settings.hooks ??= {})
const stop: any[] = Array.isArray(hooks.Stop) ? hooks.Stop : (hooks.Stop = [])
if (!stop.some((g) => Array.isArray(g?.hooks) && g.hooks.some((h: any) => h?.command === command))) {
stop.push({ hooks: [{ type: "command", command }] })
writeFileSync(file, `${JSON.stringify(settings, null, 2)}\n`)
}
return mark
}
/** when a Stop hook's file was last touched, as a turn's end; null before the first */
export function markedEnd(mark: string): { step: number; at: number } | null {
try {
const at = statSync(mark).mtimeMs
return { step: at, at }
} catch {
return null
}
}
/** Calls `said` once for each turn's end that `ended` reads (an agent's own record of it) after `told()` (when the
* agent was last sent anything: an end from before its newest prompt isn't this turn's), once `busy()` has been
* false two looks running. Returns its stop. */
export function watchEnd(ended: () => { step: number; at: number } | null, by: string, told: () => number, said: (by: string) => void, busy: () => boolean = () => false, everyMs = 1000): () => void {
let seen = -1
let idle = 0
const t = setInterval(() => {
try {
const end = ended()
// a second's slack: a transcript's times are whole seconds
if (!end || end.step === seen || end.at < told() - 1000 || busy()) return void (idle = 0)
if (++idle < 2) return
seen = end.step
said(`${by}, and nothing of its own running`)
} catch {}
}, everyMs)
t.unref?.()
return () => clearInterval(t)
}
/** watchEnd on an Antigravity agent's transcript */
export function watchTurnEnd(geminiHome: string, told: () => number, said: (by: string) => void, busy: () => boolean = () => false, everyMs = 1000): () => void {
const ended = () => {
const tr = newestTranscript(geminiHome)
return tr ? turnEndOf(lastLine(tr.file)) : null
}
return watchEnd(ended, "its transcript", told, said, busy, everyMs)
}
+73 -1
View File
@@ -3,12 +3,14 @@
// paths read on the worker)
import assert from "node:assert/strict"
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"
import { execSync } from "node:child_process"
import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"
import os from "node:os"
import path from "node:path"
import { parseSummary, pick } from "../server/gpu.ts"
import { plan, projectRoot } from "../server/offload.ts"
import { shellEnv } from "../server/shell-os.ts"
import { claudeStopHook, jobsOf, lastLine, markedEnd, newestTranscript, turnEndOf, watchEnd, watchTurnEnd } from "../server/turn-end.ts"
import { landedQuery, linkIn, packCredential, unpackCredential } from "../server/google-token.ts"
const L4 = `Devices:
@@ -107,3 +109,73 @@ console.log("units: ok")
console.log("ok google-token")
}
{
// a turn's end in Antigravity's transcript: a finished model step that called no tool (turn-end.ts)
const done = { step_index: 1716, source: "MODEL", type: "PLANNER_RESPONSE", status: "DONE", created_at: "2026-12-02T03:34:18Z", content: "All six cuts are delivered." }
assert.deepEqual(turnEndOf(JSON.stringify(done)), { step: 1716, at: Date.parse("2026-12-02T03:34:18Z") })
assert.equal(turnEndOf(JSON.stringify({ ...done, tool_calls: [{ name: "run_command" }] })), null)
assert.equal(turnEndOf(JSON.stringify({ ...done, status: "RUNNING" })), null)
assert.equal(turnEndOf(JSON.stringify({ ...done, type: "RUN_COMMAND" })), null)
assert.equal(turnEndOf("not json"), null)
const home = mkdtempSync(path.join(os.tmpdir(), "raea-turn-end-"))
const logs = path.join(home, "antigravity-acp", "brain", "s1", ".system_generated", "logs")
mkdirSync(logs, { recursive: true })
const file = path.join(logs, "transcript.jsonl")
const now = Date.now()
const line = (o: object) => JSON.stringify(o) + "\n"
writeFileSync(file, line({ ...done, step_index: 1, created_at: new Date(now - 60_000).toISOString() }))
assert.equal(newestTranscript(home)?.file, file)
assert.equal(JSON.parse(lastLine(file)).step_index, 1)
// an end from before the agent was last told anything isn't this turn's; one after it is said once
const said: string[] = []
let busy = true
const stop = watchTurnEnd(home, () => now, (by) => said.push(by), () => busy, 10)
await new Promise((ok) => setTimeout(ok, 60))
assert.deepEqual(said, [])
writeFileSync(file, line({ ...done, step_index: 2, tool_calls: [{ name: "x" }], created_at: new Date(now + 1000).toISOString() }) + line({ ...done, step_index: 3, created_at: new Date(now + 2000).toISOString() }))
// the step ended, but a job the agent started still runs: it's waiting, not done
await new Promise((ok) => setTimeout(ok, 80))
assert.deepEqual(said, [])
busy = false
await new Promise((ok) => setTimeout(ok, 80))
stop()
assert.deepEqual(said, ["its transcript, and nothing of its own running"])
// an agent's own jobs, from a made-up /proc: its session's and its children's, not its own programs or raea cloud's
const proc = path.join(home, "proc")
const put = (pid: number, ppid: number, sid: number, exe: string, cmd: string, cwd = "/") => {
mkdirSync(path.join(proc, String(pid)), { recursive: true })
writeFileSync(path.join(proc, String(pid), "stat"), `${pid} (a (odd) name) S ${ppid} ${sid} ${sid} 0 -1`)
writeFileSync(path.join(proc, String(pid), "cmdline"), cmd.replace(/ /g, "\0"))
symlinkSync(exe, path.join(proc, String(pid), "exe"))
symlinkSync(cwd, path.join(proc, String(pid), "cwd"))
}
put(100, 1, 100, "/opt/raea-cloud/agents/antigravity-acp/agy", "agy")
put(101, 100, 100, "/opt/raea-cloud/agents/antigravity-acp/localharness_external", "localharness_external")
put(50, 1, 50, "/usr/bin/node", "node /opt/raea-cloud/server/main.ts")
put(60, 50, 50, "/usr/bin/node", "node .raea-cloud/live/live.cjs", "/srv/work/threads/r1")
assert.deepEqual(jobsOf(100, "/opt/raea-cloud/agents/antigravity-acp", "/srv/work", proc), [])
put(200, 101, 100, "/opt/raea/bin/raea", "raea render edit.tsx")
put(300, 1, 300, "/usr/bin/ffmpeg", "ffmpeg -i a.mp4", "/srv/work/threads/r1/out")
assert.deepEqual(jobsOf(100, "/opt/raea-cloud/agents/antigravity-acp", "/srv/work", proc).sort(), [200, 300])
// Claude's Stop hook: added to the settings there once, what was there kept; its file's touch is the turn's end
const cfg = path.join(home, "claude")
mkdirSync(cfg, { recursive: true })
writeFileSync(path.join(cfg, "settings.json"), JSON.stringify({ model: "opus", hooks: { Stop: [{ hooks: [{ type: "command", command: "true" }] }] } }))
const mark = claudeStopHook(cfg)
claudeStopHook(cfg)
const set = JSON.parse(readFileSync(path.join(cfg, "settings.json"), "utf8"))
assert.equal(set.model, "opus")
assert.deepEqual(set.hooks.Stop.map((g: any) => g.hooks[0].command), ["true", `touch '${mark}'`])
assert.equal(markedEnd(mark), null)
const heard: string[] = []
const stop2 = watchEnd(() => markedEnd(mark), "its Stop hook", () => Date.now() - 500, (by) => heard.push(by), () => false, 10)
await new Promise((ok) => setTimeout(ok, 40))
assert.deepEqual(heard, [])
execSync(set.hooks.Stop[1].hooks[0].command)
await new Promise((ok) => setTimeout(ok, 80))
stop2()
assert.deepEqual(heard, ["its Stop hook, and nothing of its own running"])
rmSync(home, { recursive: true, force: true })
console.log("ok turn-end")
}
+1 -1
View File
@@ -36,7 +36,7 @@ export const PACKS = {
frames: "no face cut by the frame or a split screen's seam, no text too small to read",
montage: "each cut's pace kept to its beats, and eye trace, screen direction and tone kept across its cuts",
place: "no text over a face, hands or what the shot is about where a clear place of its size exists",
seen: "its contact sheet looked at since its last render, and what was seen and would change said",
seen: "its contact sheet and its frames at full size looked at since its last render, and what was seen, how it looks and what would change said",
surprise: "one earned surprise, named with its moment in seconds",
naming: "files named client_concept_variant_v#_size",
sizes: "one size first: no other size before the first is approved",
+2 -2
View File
@@ -17,8 +17,8 @@ export type Clip = { key?: string; from: number; to: number; src: string; at: nu
export type ManifestText = { text: string; box?: number[]; ink?: number[]; opacity?: number; size?: number }
/** `raea render --manifest`: the frames with their texts, and the sound's clips */
export type Manifest = { width?: number; height?: number; fps?: number; length?: number; frames?: { frame: number; text?: ManifestText[] }[]; sounds?: { fps?: number; clips?: Clip[] } }
/** what was seen of a file and said (FILE.seen.json, `raea goal seen`) */
export type Seen = { video: string; render: string; seen: string; surprise?: string; at?: string }
/** what was seen of a file and said (FILE.seen.json, `raea goal seen`); `look` is its design judged at full size */
export type Seen = { video: string; render: string; seen: string; look?: string; surprise?: string; at?: string }
export interface FileFacts {
/** as the project names it (relative to its folder) */
+39 -1
View File
@@ -3,7 +3,7 @@
// large-v3; POST /v1/scene, people, faces, things and words in the shot); elsewhere raea's own `raea words` hears, and a
// need nothing here can meet throws `Unmet`, which makes its check wait and say why, as a render need does.
import { spawnSync } from "node:child_process"
import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"
import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"
import os from "node:os"
import path from "node:path"
import type { Scene } from "./packs/place.ts"
@@ -208,10 +208,23 @@ export async function words(file: string, anyAge = false): Promise<Word[]> {
/** frames read a second for the scene, and the width they're read at (places are in shares of the picture) */
export const RATE = 2
const SIDE = 540
/** a video's scene reading, kept beside it */
export const SCENE_EXT = "scene.json"
/** what's in a file's frames (`at`: those seconds, else RATE a second): each frame's faces and seams, and its scene
* (people, faces, things, words in the shot) for placement. The farm reads them; with no farm here, Unmet */
export async function scene(file: string, at?: number[]): Promise<{ rate: number; faces: Faces[]; scenes: Scene[] }> {
// a video's whole reading is kept beside it, as its words are, and read again only when the file is newer: a cut
// checked at its render was read again at publish and again at done, 30 s a file each time, so a done check of 11
// files took 334 s (12-01)
const whole = !at?.length && !/\.(png|jpe?g|webp)$/i.test(file)
if (whole) {
const kept = freshBeside(file, SCENE_EXT)
try {
const k = kept ? (JSON.parse(readFileSync(kept, "utf8")) as { rate: number; side: number; faces: Faces[]; scenes: Scene[] }) : null
if (k && k.rate === RATE && k.side === SIDE && Array.isArray(k.scenes) && k.scenes.length) return { rate: k.rate, faces: k.faces, scenes: k.scenes }
} catch {}
}
if (!farm()) throw new Unmet(`no scene reader on this machine for ${path.basename(file)} (people, faces and things are read by raea cloud's farm: set RAEA_CLOUD_GPU_URL)`)
const dir = mkdtempSync(path.join(os.tmpdir(), "raea-scene-"))
try {
@@ -238,6 +251,11 @@ export async function scene(file: string, at?: number[]): Promise<{ rate: number
scenes.push({ w: g.w, h: g.h, grid: g.grid, things: g.things ?? [], faces: fs, ...(Array.isArray(g.texts) ? { texts: g.texts } : {}) } as Scene)
}
}
if (whole && scenes.length) {
try {
writeFileSync(`${stem(file)}.${SCENE_EXT}`, `${JSON.stringify({ rate: RATE, side: SIDE, faces, scenes })}\n`)
} catch {}
}
return { rate: at?.length ? 0 : RATE, faces, scenes }
} finally {
rmSync(dir, { recursive: true, force: true })
@@ -252,3 +270,23 @@ export function sheet(file: string): string {
if (r.status !== 0 || !existsSync(out)) throw new Unmet(`couldn't make ${path.basename(file)}'s contact sheet: ${(r.stderr || r.stdout || "").trim().slice(-200)}`)
return out
}
/** how many full-size frames a look is made of */
export const LOOKS = 6
/** a video's frames at full size beside it (FILE.looks/1.jpg ...), made again when older than the video. Type, cards
* and captions are judged on these: a contact sheet's tiles are too small to judge design on (12-01, Shane on Dutch:
* "why do components not look good. is it even proofing or reviewing the work?") */
export function looks(file: string): string[] {
const dir = `${stem(file)}.looks`
const out = Array.from({ length: LOOKS }, (_, i) => path.join(dir, `${i + 1}.jpg`))
if (out.every((p) => changed(p) >= changed(file))) return out
const d = seconds(file)
if (!d) throw new Unmet(`couldn't read ${path.basename(file)}'s length for its full-size frames`)
mkdirSync(dir, { recursive: true })
out.forEach((p, i) => ffmpeg(["-v", "error", "-y", "-ss", ((d * (i + 0.5)) / LOOKS).toFixed(2), "-i", file, "-frames:v", "1", "-q:v", "3", p]))
return out
}
/** whether FILE's full-size frames were made since it last changed */
export const looksFresh = (file: string) => Array.from({ length: LOOKS }, (_, i) => path.join(`${stem(file)}.looks`, `${i + 1}.jpg`)).every((p) => changed(p) >= changed(file))
+27 -3
View File
@@ -4,7 +4,7 @@
// stills a composition as it's saved (`raea check EDIT.tsx --quick`): three stills rendered with their manifest, and
// the text rules and the person's text taste on them; what it can't see waits for the export's floor
import { spawnSync } from "node:child_process"
import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs"
import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"
import os from "node:os"
import path from "node:path"
import { check, found } from "raea/check"
@@ -12,7 +12,7 @@ import type { FileFacts } from "../facts.ts"
import { RAEA, stem } from "../media.ts"
import { bookkeeping } from "./naming.ts"
type Measured = { level: "error" | "warn" | "note"; says: string; fix?: string | null; frames?: [number, number] | null }
export type Measured = { level: "error" | "warn" | "note"; says: string; fix?: string | null; frames?: [number, number] | null }
/** raea's measure of a file, its findings as it wrote them (-o) */
function measure(args: string[], cwd: string): Measured[] {
@@ -27,12 +27,36 @@ function measure(args: string[], cwd: string): Measured[] {
}
}
/** a video's floor report, kept beside it */
export const FLOOR_EXT = "floor.json"
let version: string | undefined
const raeaVersion = () => (version ??= String(spawnSync(RAEA, ["--version"], { encoding: "utf8" }).stdout ?? "").trim())
const when = (f: string) => (existsSync(f) ? statSync(f).mtimeMs : 0)
/** A made video's floor findings: kept beside it (FILE.floor.json) and measured again only when the video or its
* manifest is newer, raea is another version, or the kept report holds an error. The measure took 26 s a cut and ran
* again on the same file at publish and at done (12-01). An error is always measured again, since what it names (a
* placeholder brand kit) can be put right without the video changing, and a kept error would hold a finished run. */
export function floorOf(abs: string, manifest: string | undefined, cwd: string, by: (args: string[], cwd: string) => Measured[] = measure): Measured[] {
const kept = `${stem(abs)}.${FLOOR_EXT}`
try {
const k = JSON.parse(readFileSync(kept, "utf8")) as { raea: string; findings: Measured[] }
const fresh = when(kept) >= when(abs) && (!manifest || when(kept) >= when(manifest))
if (fresh && k.raea === raeaVersion() && !k.findings.some((x) => x.level === "error")) return k.findings
} catch {}
const findings = by([abs, ...(manifest ? ["--manifest", manifest] : [])], cwd)
try {
writeFileSync(kept, `${JSON.stringify({ raea: raeaVersion(), findings })}\n`)
} catch {}
return findings
}
const say = (x: Measured) => found({ level: x.level, says: x.says, fix: x.fix ?? undefined, frames: x.frames ?? undefined })
export const floorPack = check<FileFacts>({ id: "floor", text: "no clipped text, low contrast, freeze, flash or loudness out of range", over: "file", at: ["render", "publish", "done"] }, async (f) => {
if (!f.made || f.kind !== "video" || bookkeeping(f.path)) return
const m = [`${stem(f.abs)}.render.json`, `${stem(f.abs)}.manifest.json`].find(existsSync)
for (const x of measure([f.abs, ...(m ? ["--manifest", m] : [])], f.root)) say(x)
for (const x of floorOf(f.abs, m, f.root)) say(x)
})
export const stillsPack = check<FileFacts>({ id: "stills", text: "a composition's stills: no clipped or cramped text, nothing out of the safe areas", over: "file", at: ["edit"], needs: "render" }, async (f) => {
+6 -1
View File
@@ -19,6 +19,11 @@ 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
@@ -43,7 +48,7 @@ export function newest(dir: string): number | null {
}
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" && !name.endsWith(".check.json")) best = Math.max(best ?? 0, st.mtimeMs)
} else if (st.isFile() && name !== "NOTES.md" && !READING.test(name)) best = Math.max(best ?? 0, st.mtimeMs)
}
}
return best
+56 -2
View File
@@ -2,26 +2,35 @@
// at video clips"; "a way of prompting the agent to go above and beyond by adding little surprises").
// seen a video made here has been looked at since its last render: `raea goal seen FILE` makes its contact
// sheet and shows it, and `raea goal seen FILE "what I see and would change"` says what was seen. Both
// are tied to the file as it is now (its time and size): a render after it needs a new look.
// are tied to the file as it is now (its time and size): a render after it needs a new look. A video's
// design is judged apart, on its frames at full size (`--look "..."`): a sheet's tiles show what
// happens, never whether the type, captions and cards look good (12-01, Shane on Dutch).
// surprise (off unless the brief turns it on) the look names the cut's one earned surprise with its moment in
// seconds: `raea goal seen FILE "..." --surprise "12.5 s: the dog barks on the punchline"`.
import { spawnSync } from "node:child_process"
import { readFileSync, statSync, writeFileSync } from "node:fs"
import path from "node:path"
import { check, found } from "raea/check"
import type { FileFacts } from "../facts.ts"
import { RAEA, stem } from "../media.ts"
import { bookkeeping } from "./naming.ts"
/** the least a look says: what's in it and what would change, not "looks good" */
export const SEEN_LEAST = 80
const MOMENT = /\b\d+(\.\d+)?\s*s\b/
/** a look that says nothing of the design at full size (a sheet's tiles can't show it) */
export const unjudged = (s: { look?: string }) => (s.look?.trim().length ?? 0) < SEEN_LEAST
const looked = (f: FileFacts) => f.made && f.kind === "video" && !bookkeeping(f.path)
export const seenPack = check<FileFacts>({ id: "seen", text: "its contact sheet looked at since its last render, and what was seen and would change said", over: "file", at: ["publish", "done"], needs: "sheet" }, async (f) => {
export const seenPack = check<FileFacts>({ id: "seen", text: "its contact sheet and its frames at full size looked at since its last render, and what was seen, how it looks and what would change said", over: "file", at: ["publish", "done"], needs: "sheet" }, async (f) => {
if (!looked(f)) return
const s = f.seen()
const name = path.basename(f.path)
if (!s) return found({ says: `${name} hasn't been looked at since its last render`, fix: `raea goal seen ${f.path}, look at every frame of the sheet, then raea goal seen ${f.path} "what you see and would change"` })
if (s.seen.trim().length < SEEN_LEAST) found({ says: `what was seen of ${name} is ${s.seen.trim().length} characters: say what's in it, frame by frame, and what you'd change (${SEEN_LEAST} at least)`, fix: `raea goal seen ${f.path} "..."` })
if (unjudged(s)) found({ says: `${name}'s design isn't judged at full size: its type, captions, cards and end, beside a reference ad's frame (${SEEN_LEAST} characters at least)`, fix: `raea goal seen ${f.path}, open each full-size frame beside a reference's, then raea goal seen ${f.path} "..." --look "how it looks beside the reference and what you changed"` })
})
export const surprisePack = check<FileFacts>({ id: "surprise", text: "one earned surprise, named with its moment in seconds", over: "file", at: ["publish", "done"] }, async (f) => {
@@ -30,3 +39,48 @@ export const surprisePack = check<FileFacts>({ id: "surprise", text: "one earned
if (!s) return
if (!s.surprise?.trim() || !MOMENT.test(s.surprise)) found({ says: `${path.basename(f.path)}'s surprise isn't named with its moment ("12.5 s: the dog barks on the punchline")`, fix: `raea goal seen ${f.path} "..." --surprise "SECONDS s: what it is"` })
})
/** what the second opinion is asked of a whole cut, picture and sound (`raea ask`, clef-omni): pointed checks, each
* a yes when the fault is there. Never "does it look good": asked whether Dutch's plain boxes looked designed, clef
* said "strong". 12-01, Shane: "you just have to have them be more specific or pointed like giving it some list of
* design checks to answer ... a few catch all checks on visual and audio design"; "the agent itself is really
* responsible for design" */
export const SECOND = [
// picture
"Are three or more separate text boxes or cards on screen at the same moment at any point?",
"Do the captions, cards and badges all look like the same plain rounded box, with nothing but colour telling them apart?",
"Is any text too small or too cluttered to read at a glance on a phone?",
"Does any text or graphic cover a person's face, or sit cut off at the edge of the frame?",
"Is a product or an app shown only as a box of text, and never as the real product or its screen?",
"Does the end card hold more than a logo, one line and one thing to do?",
"Is there a rendering glitch: a black or frozen frame, torn or blocky video, or a flash?",
// sound
"Is a voice muffled, distant or hard to understand, or is music louder than the person speaking?",
"Is there harsh, shrill or clipping sound, or music that starts or stops abruptly?",
"Is there a stretch of dead air, where nothing is said and nothing is heard?",
"Is the same sound effect used in the same way more than three times?",
]
type Opinion = { choice?: string; says?: string }
/** a second opinion on a cut, from clef watching and hearing all of it (12-01, Shane: "the agent itself should be
* watching and revising itself always and use clef omni as a secondary opinion or catch all"): each check, the
* faults it found first, kept beside the file (FILE.second.json) for the file as it is now. Null where it couldn't
* be asked. */
export function second(file: string, ask = askSecond): string | null {
const [st, kept] = [statSync(file), `${stem(file)}.second.json`]
const stamp = `${Math.round(st.mtimeMs)} ${st.size}`
try {
const k = JSON.parse(readFileSync(kept, "utf8")) as { render: string; says: string }
if (k.render === stamp) return k.says
} catch {}
const got = ask(file)
if (got.length !== SECOND.length) return null
const rows = got.map((o, i) => ({ q: SECOND[i], found: o.choice === "yes", says: o.says ?? o.choice ?? "no answer" }))
const says = [...rows.filter((r) => r.found), ...rows.filter((r) => !r.found)].map((r) => ` ${r.found ? "FOUND" : "clear"} (${r.says}): ${r.q}`).join("\n")
writeFileSync(kept, `${JSON.stringify({ render: stamp, says }, null, 1)}\n`)
return says
}
function askSecond(file: string): Opinion[] {
const r = spawnSync(RAEA, ["ask", file, ...SECOND, "--choose", "yes,no", "--json", "--brief", "none"], { cwd: path.dirname(file), encoding: "utf8", maxBuffer: 1 << 26 })
return String(r.stdout ?? "").split("\n").flatMap((l) => { try { const o = JSON.parse(l); return o.answer ? [o as Opinion] : [] } catch { return [] } })
}
+41 -8
View File
@@ -13,6 +13,9 @@
// eye, plane and tone are warnings at each cut, in Murch's order; one becomes an error when it breaks at more than half
// of a file's cuts (a habit, not a choice). A cut on a word is the sound pack's (edit-on-sound), not this one's.
import { spawnSync } from "node:child_process"
import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import path from "node:path"
import { check, found } from "raea/check"
import type { Beat } from "raea/brief.gen"
import type { FileFacts } from "../facts.ts"
@@ -42,9 +45,18 @@ export type Finding = { level: "error" | "warn"; kind: "pace" | "tempo" | "eye"
export function read(file: string, fps: number, width: number, height: number): Read {
const w = READ_W
const h = Math.max(2, Math.round((READ_W * height) / width / 2) * 2)
const r = spawnSync("ffmpeg", ["-v", "error", "-i", file, "-vf", `scale=${w}:${h},format=rgb24`, "-f", "rawvideo", "-"], { maxBuffer: 1 << 30 })
if (r.status !== 0) throw new Error(`ffmpeg couldn't read ${file}: ${String(r.stderr).trim().slice(-200)}`)
const buf = r.stdout as Buffer
// into a file, not down a pipe: 13 MB of frames through the pipe took 9.7 s of a 35 s cut's read on a cloud box, and
// 4.6 s into a file (12-01)
const dir = mkdtempSync(path.join(tmpdir(), "raea-montage-read-"))
let buf: Buffer
try {
const raw = path.join(dir, "frames.raw")
const r = spawnSync("ffmpeg", ["-v", "error", "-an", "-i", file, "-vf", `scale=${w}:${h},format=rgb24`, "-f", "rawvideo", raw], { encoding: "utf8" })
if (r.status !== 0) throw new Error(`ffmpeg couldn't read ${file}: ${String(r.stderr).trim().slice(-200)}`)
buf = readFileSync(raw)
} finally {
rmSync(dir, { recursive: true, force: true })
}
const size = w * h * 3
const frames: Frame[] = []
for (let o = 0; o + size <= buf.length; o += size) {
@@ -235,6 +247,25 @@ export function acrossCuts(r: Read, cuts: number[], o: { faces?: Faces[]; rate?:
return out
}
/** a video's montage findings, kept beside it */
export const MONTAGE_EXT = "montage.json"
/** A video's findings from `measure`, kept beside it (FILE.montage.json) and measured again only when the video is
* newer or what they were measured against (`given`: its beats, its scene reading) is another. Reading a 35 s cut's
* frames took 7 s each time the goal was checked, on files that hadn't changed (12-01). */
export function keptOr(abs: string, given: string, measure: () => Finding[]): Finding[] {
const kept = `${abs.replace(/\.[^./]+$/, "")}.${MONTAGE_EXT}`
try {
const k = JSON.parse(readFileSync(kept, "utf8")) as { given: string; findings: Finding[] }
if (statSync(kept).mtimeMs >= statSync(abs).mtimeMs && k.given === given) return k.findings
} catch {}
const findings = measure()
try {
writeFileSync(kept, `${JSON.stringify({ given, findings })}\n`)
} catch {}
return findings
}
const where = ([x, y]: [number, number]) => `${y < 0.34 ? "top" : y > 0.66 ? "bottom" : "middle"} ${x < 0.34 ? "left" : x > 0.66 ? "right" : "centre"}`
export default check<FileFacts>(
@@ -244,9 +275,6 @@ export default check<FileFacts>(
const c = f.contract?.kind === "cut" ? f.contract.cut : undefined
const plan = c ? cutOf(c, f.path) : null
const beats = plan?.plan.beats ?? []
const r = read(f.abs, f.fps, f.width, f.height)
if (r.frames.length < 2) return
const cuts = cutsOf(r)
let faces: Faces[] | undefined
let rate = 0
try {
@@ -258,7 +286,12 @@ export default check<FileFacts>(
if (!(e instanceof Unmet)) throw e
}
const say = (x: Finding) => found({ level: x.level, says: x.says, seconds: x.at === null ? undefined : x.until === undefined ? x.at : [x.at, x.until] })
for (const x of pace(beats, cuts, r.fps, r.frames.length / r.fps)) say(x)
for (const x of acrossCuts(r, cuts, { faces, rate, beatsAt: beats.map((b) => b.at) })) say(x)
for (const x of keptOr(f.abs, JSON.stringify({ beats, faces: faces?.length ?? null, rate }), () => {
const r = read(f.abs, f.fps, f.width!, f.height!)
if (r.frames.length < 2) return []
const cuts = cutsOf(r)
return [...pace(beats, cuts, r.fps, r.frames.length / r.fps), ...acrossCuts(r, cuts, { faces, rate, beatsAt: beats.map((b) => b.at) })]
}))
say(x)
},
)
+1 -1
View File
@@ -32,7 +32,7 @@ export const sizeOf = (name: string) => path.basename(name).replace(/\.[a-z0-9]{
export const adOf = (name: string) => path.basename(name).replace(/\.[a-z0-9]{2,4}$/i, "").split("_").filter((p) => !VERSION.test(p) && !SIZE.test(p) && !EXTRA.test(p)).join("_")
/** the job's own writing about itself: review rounds, previews, sheets */
export const bookkeeping = (rel: string) => /^(\.\/)?(review|previews|\.raea)\//.test(rel) || /\.(sheet|seen|check)\.[a-z]+$/i.test(rel)
export const bookkeeping = (rel: string) => /^(\.\/)?(review|previews|\.raea)\//.test(rel) || /\.(sheet|seen|second|check)\.[a-z]+$/i.test(rel) || /\.looks\//.test(rel)
export default check<FileFacts>(
{ id: "naming", text: "files named client_concept_variant_v#_size", over: "file", at: ["edit", "render", "publish", "done"] },
+7 -2
View File
@@ -7,6 +7,7 @@
// itself, and the box around them a little), then the edges a phone's own buttons and captions cover; open ground is
// free. A text's cost is the mean of the cells it covers. A text is badly placed when it covers a face or a thing, or
// a person, and a place of the same size costs much less; that place is what's said.
// Over a face or a thing it's an error; over a person's body alone, a warning.
//
// raea make place FILE [--at S[,S...]] [--box WxH] [-o REPORT.json]
// FILE (a take or an export, a picture or a video) read at those seconds (a video: one a second, at most 12):
@@ -257,8 +258,12 @@ export function textOver(manifest: any, scenes: Scene[], rate: number): Finding[
const q = `${on.text.length > 40 ? `“${on.text.slice(0, 40)}...”` : `“${on.text}”`}${on.lines > 1 ? ` (and the ${on.lines - 1} line${on.lines > 2 ? "s" : ""} under it)` : ""}`
const when = on.to - on.from < 0.5 ? `at ${on.from.toFixed(1)} s` : `from ${on.from.toFixed(1)} s to ${on.to.toFixed(1)} s`
if (best && best.cost <= here - BETTER) {
const face = under.includes("a face")
out.push({ level: face || here >= BAD + 1.5 ? "error" : "warn", kind: "text-over", at: on.from, until: on.to, says: `${q} covers ${what} ${when}: move it to left ${px(best.box[0], W)} px, top ${px(best.box[1], H)} px (${Math.round(best.box[1] * 100)}% down), which is clear there. raea make place shows the clear places in a shot` })
// an error only for what a shot can't lose: a face, or the thing it shows (the product, the dog, a phone held
// up). A caption over someone's coat with clearer ground elsewhere is a warning with the place said (12-01: two
// people fill a 9:16 interview frame, each caption's clearest place is a different one, and an agent spent
// hours cropping shots and rendering again to clear errors a steady caption position can't)
const hard = under.some((u) => u !== "a person in the shot")
out.push({ level: hard ? "error" : "warn", kind: "text-over", at: on.from, until: on.to, says: `${q} covers ${what} ${when}: move it to left ${px(best.box[0], W)} px, top ${px(best.box[1], H)} px (${Math.round(best.box[1] * 100)}% down), which is clear there. raea make place shows the clear places in a shot` })
} else if (under.includes("a face")) {
out.push({ level: "error", kind: "text-over", at: on.from, until: on.to, says: `${q} covers a face ${when} and no place of its size is clear: make it smaller, put it on a shot with room, or cut to one` })
} else if (here >= BAD + 1.5) {
+14 -1
View File
@@ -11,11 +11,24 @@ import { check, found } from "raea/check"
import type { Job } from "../facts.ts"
import { adOf, bookkeeping, sizeOf } from "./naming.ts"
/** The size a made file is in, as a name says one (9x16): its name's, else a video's own shape (1080x1920 is 9x16).
* A picture with no size in its name is a still of the work, a sheet or a strip, not a size of an ad. Told by pixels
* alone, an ad named _9x16 beside its own 1080x1920 renders and one 540x960 still read as three sizes, and an agent
* with one size made couldn't stop for its sign-off (12-01). */
export function shapeOf(f: { path: string; kind?: string; width?: number; height?: number }): string | null {
const named = sizeOf(f.path)
if (named) return named
if (f.kind !== "video" || !f.width || !f.height) return null
const gcd = (a: number, b: number): number => (b ? gcd(b, a % b) : a)
const g = gcd(f.width, f.height)
return `${f.width / g}x${f.height / g}`
}
export default check<Job>({ id: "sizes", text: "one size first: no other size before the first is approved", over: "job", at: ["render", "publish", "done"] }, async (j) => {
const made = j.files.filter((f) => f.made && !bookkeeping(f.path) && (f.kind === "video" || f.kind === "image"))
const sizes = new Map<string, string[]>()
for (const f of made) {
const s = sizeOf(f.path) ?? (f.width && f.height ? `${f.width}x${f.height}` : null)
const s = shapeOf(f)
if (s) sizes.set(s, [...(sizes.get(s) ?? []), f.path])
}
if (sizes.size < 2) return
+15 -7
View File
@@ -26,6 +26,7 @@ import { tastePack } from "./packs/taste.ts"
import { loadProject, type Project } from "./project.ts"
import { critic, judge } from "./packs/goal.ts"
import { PACK_CHECKS } from "./packs/index.ts"
import { second } from "./packs/look.ts"
import { deliverablesOf } from "./packs/job.ts"
import { bookkeeping } from "./packs/naming.ts"
import { placeReport } from "./packs/place.ts"
@@ -227,8 +228,8 @@ const positional = (a: string[], valued: string[]) => a.filter((x, i) => !x.star
const USAGE = `raea goal check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--json]
raea goal tasks [DIR] [--json] | raea goal tasks [DIR] --apply EDITS.json|-
raea goal seen FILE (its contact sheet, to look at every frame)
raea goal seen FILE "what you see and would change" [--surprise "SECONDS s: what it is"]
raea goal seen FILE (its contact sheet and its frames at full size, to look at)
raea goal seen FILE "what you see and would change" --look "its design at full size, beside a reference" [--surprise "SECONDS s: what it is"]
raea goal judge [--goal NAME] [--by claude|kimi|clef]
raea make place FILE [--at S[,S...]] [--box WxH]`
@@ -254,11 +255,15 @@ export async function main(argv: string[]): Promise<number> {
}
if (verb === "tasks") return tasksMain(a)
if (verb === "seen") {
const [file, said] = positional(a, ["--surprise"])
const [file, said] = positional(a, ["--surprise", "--look"])
if (!file || !existsSync(file)) return usage()
if (!said?.trim()) {
const sheet = media.sheet(path.resolve(file))
console.log(`${sheet}\nlook at every frame, then: raea goal seen ${file} "what you see and would change"`)
const full = kindOf(path.resolve(file)) === "video" ? media.looks(path.resolve(file)) : []
// on raea cloud (where the critic is clef), a second opinion on the whole cut with its sound: never the look itself
const op = full.length && critic() === "clef" ? second(path.resolve(file)) : null
if (op) console.log(`a second opinion (clef watched and heard all of it and answered a list of checks; a FOUND is a fix or a reason it's wrong; how it looks is still yours to judge, on the frames):\n${op}`)
console.log(`${sheet}\n${full.join("\n")}\nlook at every frame of the sheet for what happens, and open each full-size frame for how it looks (type, captions, cards, the end: beside a reference ad's frame, not from the sheet), then: raea goal seen ${file} "what you see and would change"${full.length ? ' --look "its design at full size, beside a reference, and what you changed"' : ""}`)
return 0
}
const abs = path.resolve(file)
@@ -267,9 +272,12 @@ export async function main(argv: string[]): Promise<number> {
console.error(`raea goal seen: ${path.basename(file)} has no sheet since its last render: raea goal seen ${file}, and look at it first`)
return 1
}
const st = statSync(abs)
const surprise = flag(a, "--surprise")
writeFileSync(`${media.stem(abs)}.seen.json`, `${JSON.stringify({ video: path.basename(abs), render: `${Math.round(st.mtimeMs)} ${st.size}`, sheet: path.basename(sheet), seen: said.trim(), ...(surprise ? { surprise } : {}), at: new Date().toISOString() }, null, 1)}\n`)
const [st, surprise, look] = [statSync(abs), flag(a, "--surprise"), flag(a, "--look")?.trim()]
if (kindOf(abs) === "video" && (!look || !media.looksFresh(abs))) {
console.error(`raea goal seen: ${path.basename(file)}'s design isn't judged yet: raea goal seen ${file} makes its frames at full size; open them, then say --look "its type, captions and cards beside a reference, and what you changed"`)
return 1
}
writeFileSync(`${media.stem(abs)}.seen.json`, `${JSON.stringify({ video: path.basename(abs), render: `${Math.round(st.mtimeMs)} ${st.size}`, sheet: path.basename(sheet), seen: said.trim(), ...(look ? { look } : {}), ...(surprise ? { surprise } : {}), at: new Date().toISOString() }, null, 1)}\n`)
console.log(`${media.stem(path.basename(abs))}.seen.json: seen as it is now`)
return 0
}
+52
View File
@@ -0,0 +1,52 @@
// A made video's floor report is kept beside it and measured again only for cause (packs/floor.ts)
import { expect, test } from "bun:test"
import { mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import path from "node:path"
import { floorOf, type Measured } from "../src/packs/floor.ts"
import { keptOr } from "../src/packs/montage.ts"
test("a floor report is kept: measured once, again when the video is newer, and always while it holds an error", () => {
const d = mkdtempSync(path.join(tmpdir(), "raea-floor-kept-"))
const v = path.join(d, "a.mp4")
writeFileSync(v, "x")
let runs = 0
let out: Measured[] = [{ level: "warn", says: "quiet" }]
const by = () => (runs++, out)
expect(floorOf(v, undefined, d, by)).toEqual(out)
expect(floorOf(v, undefined, d, by)).toEqual(out)
expect(runs).toBe(1)
// the video made again
const later = new Date(Date.now() + 60_000)
utimesSync(v, later, later)
floorOf(v, undefined, d, by)
expect(runs).toBe(2)
utimesSync(path.join(d, "a.floor.json"), new Date(Date.now() + 120_000), new Date(Date.now() + 120_000))
floorOf(v, undefined, d, by)
expect(runs).toBe(2)
// an error isn't kept as an answer
utimesSync(v, new Date(Date.now() + 180_000), new Date(Date.now() + 180_000))
out = [{ level: "error", says: "a placeholder brand kit" }]
floorOf(v, undefined, d, by)
utimesSync(path.join(d, "a.floor.json"), new Date(Date.now() + 240_000), new Date(Date.now() + 240_000))
floorOf(v, undefined, d, by)
expect(runs).toBe(4)
rmSync(d, { recursive: true, force: true })
})
test("montage findings are kept: measured again when the video is newer or its beats are others", () => {
const d = mkdtempSync(path.join(tmpdir(), "raea-montage-kept-"))
const v = path.join(d, "a.mp4")
writeFileSync(v, "x")
let runs = 0
const by = () => (runs++, [{ level: "warn" as const, kind: "pace" as const, at: 1, says: "long" }])
keptOr(v, "a", by)
expect(keptOr(v, "a", by)).toEqual([{ level: "warn", kind: "pace", at: 1, says: "long" }])
expect(runs).toBe(1)
keptOr(v, "b", by)
expect(runs).toBe(2)
utimesSync(v, new Date(Date.now() + 60_000), new Date(Date.now() + 60_000))
keptOr(v, "b", by)
expect(runs).toBe(3)
rmSync(d, { recursive: true, force: true })
})
+13 -1
View File
@@ -1,7 +1,7 @@
// The rule packs (MK29, ported from Rust's goal gate tests): run rules pass or say why, says rules need a fresh critic;
// any goal carries rules.
import { expect, test } from "bun:test"
import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs"
import { mkdirSync, mkdtempSync, utimesSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import path from "node:path"
import { clefVerdict, lastVerdict, newest } from "../src/packs/goal.ts"
@@ -80,3 +80,15 @@ test("clef judges a rule on the file it names, else on every video made, and say
const empty = mkdtempSync(path.join(tmpdir(), "raea-goal-clef-"))
expect(clefVerdict(g, empty, () => []).all?.why).toContain("names no file on disk")
})
test("a reading kept beside a file isn't the work changing", () => {
const d = mkdtempSync(path.join(tmpdir(), "raea-newest-"))
mkdirSync(path.join(d, "out/cuts"), { recursive: true })
const cut = path.join(d, "out/cuts/a_b_c_v1_9x16.mp4")
writeFileSync(cut, "x")
utimesSync(cut, 1000, 1000)
for (const ext of ["words.json", "scene.json", "check.json", "floor.json", "montage.json"]) writeFileSync(path.join(d, `out/cuts/a_b_c_v1_9x16.${ext}`), "{}")
expect(newest(d)).toBe(1_000_000)
writeFileSync(path.join(d, "out/cuts/a_b_c_v1_9x16.render.json"), "{}")
expect(newest(d)!).toBeGreaterThan(1_000_000)
})
+40
View File
@@ -0,0 +1,40 @@
// The seen pack's two looks (12-01): what happens, on the contact sheet, and how it looks, on frames at full size.
import { expect, test } from "bun:test"
import { existsSync, readFileSync, writeFileSync } from "node:fs"
import { LOOKS, looks, looksFresh, stem } from "../src/media.ts"
import { SECOND, second, unjudged } from "../src/packs/look.ts"
import { CLIP, project, put, touch } from "./project.ts"
test("a video's frames at full size are made beside it, and again only after it changes", () => {
const f = put(project({}), "out/cuts/acme_dog_hook1_v1_9x16.mp4", readFileSync(CLIP))
touch(f, -60)
expect(looksFresh(f)).toBe(false)
const made = looks(f)
expect(made.length).toBe(LOOKS)
expect(made.every((p) => existsSync(p) && p.startsWith(`${stem(f)}.looks`))).toBe(true)
expect(looksFresh(f)).toBe(true)
writeFileSync(f, readFileSync(CLIP))
touch(f, 60)
expect(looksFresh(f)).toBe(false)
})
test("a look at the sheet alone doesn't pass: the design is judged at full size, in its own words", () => {
expect(unjudged({})).toBe(true)
expect(unjudged({ look: "looks good" })).toBe(true)
expect(unjudged({ look: "Captions are 72 px bold with the spoken word in yellow, as the reference's; the offer is one pill, not three boxes." })).toBe(false)
})
test("the second opinion is asked once for a file as it is, the faults it found first, and again after it changes", () => {
const f = put(project({}), "out/cuts/acme_dog_hook1_v1_9x16.mp4", readFileSync(CLIP))
let asked = 0
const ask = () => (asked++, SECOND.map((_, i) => ({ choice: i === 3 ? "yes" : "no", says: i === 3 ? "yes (0.81)" : "no (0.9)" })))
const says = second(f, ask)!
expect(says.split("\n")[0]).toBe(` FOUND (yes (0.81)): ${SECOND[3]}`)
expect(says.split("\n")[1]).toStartWith(" clear")
expect(second(f, ask)).toBe(says)
expect(asked).toBe(1)
touch(f, 60)
second(f, ask)
expect(asked).toBe(2)
expect(second(put(project({}), "out/a_b_c_v1_9x16.mp4", readFileSync(CLIP)), () => [])).toBeNull()
})
+31 -1
View File
@@ -1,6 +1,9 @@
import { test } from "bun:test"
import assert from "node:assert/strict"
import { readFileSync } from "node:fs"
import { mkdtempSync, readFileSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import path from "node:path"
import { RATE, scene, SCENE_EXT, useSender } from "../src/media.ts"
import { placeReport, textOver } from "../src/packs/place.ts"
test("the place pack's model", async () => {
@@ -42,4 +45,31 @@ test("the place pack's model", async () => {
assert.ok(b.every((x) => x.level === "warn"), JSON.stringify(b))
ok("a caption over a person who fills the frame is at most a warning")
// a: a caption across the woman's body with clear ground above her: a warning that names the place, never an error
// (12-01: errors here had an agent cropping interview shots and rendering again for hours)
for (const y of [300, 400, 500]) {
const d = textOver(man([t("Did you know you", 480, y, 536, 88)]), [sc.a], 1).filter((x) => /covers a person in the shot (at|from)/.test(x.says))
assert.ok(d.length === 1 && d[0].level === "warn", JSON.stringify(d))
}
assert.match(textOver(man([t("Did you know you", 480, 400, 536, 88)]), [sc.a], 1)[0].says, /covers a person in the shot at 0\.0 s: move it to left \d+ px, top \d+ px/)
ok("a caption over a body with clearer ground elsewhere is a warning with the place said")
})
test("a video's scene reading is kept beside it and read again only when the video is newer", async () => {
const d = mkdtempSync(path.join(tmpdir(), "raea-scene-kept-"))
const cut = path.join(d, "a_b_c_v1_9x16.mp4")
writeFileSync(cut, "not a real video")
const kept = { rate: RATE, side: 540, faces: [null], scenes: [{ w: 540, h: 960, grid: { cols: 1, rows: 1, people: ["0"] }, things: [], faces: [] }] }
writeFileSync(path.join(d, `a_b_c_v1_9x16.${SCENE_EXT}`), JSON.stringify(kept))
let asked = 0
useSender(async () => (asked++, { status: 500, ok: false, text: "" }))
delete process.env.RAEA_CLOUD_GPU_URL
// no farm here at all, and the reading still comes back: from beside the file
const r = await scene(cut)
assert.equal(r.scenes.length, 1)
assert.equal(r.rate, RATE)
assert.equal(asked, 0)
// a reading at named seconds is never the whole file's
await assert.rejects(scene(cut, [1, 2]), /no scene reader/)
})
+11
View File
@@ -4,6 +4,7 @@ import { beforeAll, expect, test } from "bun:test"
import { goalCheck } from "../src/run.ts"
import { CLIP, project, put } from "./project.ts"
import { readFileSync } from "node:fs"
import { shapeOf } from "../src/packs/sizes.ts"
beforeAll(() => {
process.env.RAEA_REAL = "/usr/bin/false"
@@ -31,3 +32,13 @@ test("every size of the newest version passes; a person's answer can say fewer",
expect((await all(answered, sizes)).filter((x) => x.check === "sizes-all")).toEqual([])
expect((await all(answered, ["out/cuts/dutch_vetbill_hooka_v2_9x16.mp4"])).filter((x) => x.check === "sizes-all")).toEqual([])
})
test("one size is one size however it's told: a name's 9x16, a 1080x1920 video, never a still", () => {
expect(shapeOf({ path: "out/cuts/dutch_vetbill_hooka_v1_9x16.mp4", kind: "video", width: 1080, height: 1920 })).toBe("9x16")
expect(shapeOf({ path: "out/cuts/hooka.mp4", kind: "video", width: 1080, height: 1920 })).toBe("9x16")
expect(shapeOf({ path: "out/cuts/hooka_small.mp4", kind: "video", width: 540, height: 960 })).toBe("9x16")
expect(shapeOf({ path: "out/cuts/hooka.mp4", kind: "video", width: 1080, height: 1350 })).toBe("4x5")
expect(shapeOf({ path: "out/stills/a1_38.jpg", kind: "image", width: 540, height: 960 })).toBe(null)
expect(shapeOf({ path: "out/stills/strip.png", kind: "image", width: 1080, height: 480 })).toBe(null)
expect(shapeOf({ path: "out/stills/dutch_vetbill_end_v1_1x1.png", kind: "image", width: 1080, height: 1080 })).toBe("1x1")
})
+3 -2
View File
@@ -38,8 +38,9 @@ media/brief.txt, so a rule can't be made up and a line can't be paraphrased away
out/cuts/ID_WxH.mp4 (name each cut's id client_concept_variant_v#, so the file is client_concept_variant_v#_9x16.mp4):
its shape and length; what it says, heard after its last change, for each `say`, `never` and the CTA; its words
against CUT.lines.txt beside it; its edit points, line levels and effects; its faces, text sizes and text placement;
and that you looked at its contact sheet since its last render (`raea goal seen CUT`, then `raea goal seen CUT
"..."`). Every render ends with `raea goal check CUT --at render`; the job isn't done, and the Stop hook won't let
and that you looked at it since its last render: its contact sheet for what happens, and its frames at full size
(CUT.looks/) for how it looks, since a sheet's tiles are too small to judge type, captions and cards on (`raea goal
seen CUT`, then `raea goal seen CUT "..." --look "its design beside a reference, and what you changed"`). Every render ends with `raea goal check CUT --at render`; the job isn't done, and the Stop hook won't let
you end, until `--at done` passes and every `open` item has the person's answer, written in with who gave it. Turn a
pack off on the contract (`packs: { place: false }`) only when the brief says so.
+1 -1
Submodule skills updated: de0767b1f8...a2481c23ef.
+8 -2
View File
@@ -40,12 +40,18 @@ cp "$work/raea/README" "$appdir/usr/share/doc/raea/README-linux"
# The bundler is opened with dlopen beside raea, so keep it in usr/bin and ask
# linuxdeploy to process its dependencies there, rather than move it to usr/lib.
# A pinned linuxdeploy also carries its AppImage output plugin and appimagetool.
# A pinned tool from its GitHub release, else raea's own copy of it (media.raea.io/build): the runner got HTTP 618 for
# the runtime three times in a row while it downloaded from anywhere else (v0.1.15-rc1, 12-01), and the Linux archive
# waits on this script. Either copy is held to the checksum below.
fetch() {
curl -fLsS --retry 3 --retry-all-errors "$1" -o "$3" || curl -fLsS --retry 3 --retry-all-errors "https://media.raea.io/build/$2" -o "$3"
}
deploy_version=1-alpha-20251107-1
deploy_sha=c20cd71e3a4e3b80c3483cef793cda3f4e990aca14014d23c544ca3ce1270b4d
# An existing download can be supplied for offline packaging; it is still verified.
deploy=${RAEA_LINUXDEPLOY:-$work/linuxdeploy-x86_64.AppImage}
if [[ -z ${RAEA_LINUXDEPLOY:-} ]]; then
curl -fLsS --retry 3 "https://github.com/linuxdeploy/linuxdeploy/releases/download/$deploy_version/linuxdeploy-x86_64.AppImage" -o "$deploy"
fetch "https://github.com/linuxdeploy/linuxdeploy/releases/download/$deploy_version/linuxdeploy-x86_64.AppImage" "linuxdeploy/$deploy_version/linuxdeploy-x86_64.AppImage" "$deploy"
fi
deploy=$(realpath "$deploy")
echo "$deploy_sha $deploy" | sha256sum -c -
@@ -55,7 +61,7 @@ runtime_version=20251108
runtime_sha=2fca8b443c92510f1483a883f60061ad09b46b978b2631c807cd873a47ec260d
runtime=${RAEA_APPIMAGE_RUNTIME:-$work/runtime-x86_64}
if [[ -z ${RAEA_APPIMAGE_RUNTIME:-} ]]; then
curl -fLsS --retry 3 "https://github.com/AppImage/type2-runtime/releases/download/$runtime_version/runtime-x86_64" -o "$runtime"
fetch "https://github.com/AppImage/type2-runtime/releases/download/$runtime_version/runtime-x86_64" "type2-runtime/$runtime_version/runtime-x86_64" "$runtime"
fi
runtime=$(realpath "$runtime")
echo "$runtime_sha $runtime" | sha256sum -c -
+8
View File
@@ -195,6 +195,14 @@ if [ -f "$check/raea/bin/raea.exe" ]; then
done
"$check/raea/bin/uv.exe" --version 2>&1 | grep -q '^uv ' || fail "bin/uv.exe doesn't run"
fi
# a project whose brief.ts imports React, as its scenes do, and has no node_modules: a render's own checks load brief.ts,
# and a render that was applied ended "Cannot find package 'react'" and "render again" (#278). The checks' verdict on
# an empty project isn't the point here: that brief.ts ran is
mkdir -p "$check/brief" && cp "$check/p/hello.tsx" "$check/brief/hello.tsx"
printf '%s\n' 'import { useMemo } from "react"' 'import { goal } from "raea/goal"' 'export const hook = useMemo' 'export default goal({ title: "Check", make: "one short video" })' > "$check/brief/brief.ts"
(cd "$check/brief" && RAEA_NO_TREE=1 "$raea" goal check > check.log 2>&1) || true
[ -s "$check/brief/check.log" ] || fail "raea goal check said nothing beside a brief.ts that imports react"
! grep -q "Cannot find package\|doesn't run" "$check/brief/check.log" || { tail -20 "$check/brief/check.log" >&2; fail "a brief.ts that imports react doesn't run: a package raea ships wasn't found"; }
# RAEA_CHECK_HARD=1 (tools/release-machines.sh, on real machines: a PC's own GPU, the Linux box): what reports from
# other systems needed and a runner's one pass doesn't show.
if [ "${RAEA_CHECK_HARD:-}" = 1 ]; then