Compare commits

..
Author SHA1 Message Date
shinyobjectz f86933383b Judges never pick a harness: a fresh session of the project's own agent, or Clef
Shane, 12-03: nothing judges or checks with another harness, and nothing the agent reads makes it choose a harness,
model or provider. Dutch's plan turn spent about 3 minutes on raea goal judge --by claude (not signed in on a box),
--by clef (no video at plan) and --by kimi (not on PATH), because sdk/goal spawned claude -p and kimi -p itself.

- sdk/cloud/server/critic.ts: each agent session the box server starts gets RAEA_JUDGE_URL and RAEA_JUDGE_TOKEN;
  POST /host/judge {cwd, prompt} starts a fresh session of that same agent (command, sign-in, environment) over ACP
  stdio, allows reads only, and returns what it says. The desktop's local cloud runs the same server.
- sdk/goal: judge() takes no critic. A rule with a piece to watch or hear goes to Clef-Omni, any other to the session's
  critic. raea goal check asks for a verdict itself when it's missing, stale or partial, so the check is the one
  command and the hooks judge with it. BY, critic() and --by are gone.
- raea judge and raea fingerprint read: the same critic through io/clef/src/critic.rs (one call for every caller);
  --by kimi|claude gone, judge eye --read in its place.
- Help, the manual and the Bevy guides name no harness.
2026-12-03 16:43:42 -08:00
102 changed files with 1124 additions and 2677 deletions

No files matched your search

+2 -2
View File
@@ -52,7 +52,7 @@ pub fn stop(v: &Value) -> Option<String> {
let cwd = PathBuf::from(v["cwd"].as_str()?);
let brief = brief_with_job(&cwd)?;
let exe = std::env::current_exe().ok()?;
let out = std::process::Command::new(exe).args(["check", "--at", "done", "--json"]).current_dir(brief.parent()?).env("RAEA_RECORD", "off").output().ok()?;
let out = std::process::Command::new(exe).args(["goal", "check", "--at", "done", "--json"]).current_dir(brief.parent()?).env("RAEA_RECORD", "off").output().ok()?;
let r: Value = serde_json::from_slice(&out.stdout).ok()?;
let home = raea_io_home::user_home()?;
let session = v["session_id"].as_str().unwrap_or("");
@@ -67,7 +67,7 @@ pub fn stop(v: &Value) -> Option<String> {
}
let goals: Vec<String> = r["goals"].as_array().into_iter().flatten().filter(|g| g["passed"] != true).filter_map(|g| g["name"].as_str().map(String::from)).collect();
let open = if goals.is_empty() { String::new() } else { format!("goal {}, ", goals.join(", ")) };
Some(format!("Not done ({open}{}): {items}. Fix each in its composition and render it again (its check runs at the render's end): `raea check --at done` lists them with their fixes, and review/goal.json holds them all.", brief.display()))
Some(format!("Not done ({open}{}): {items}. Keep going: `raea goal check` lists each with its fix; review/goal.json holds them all.", brief.display()))
}
/// The open items, one line each: each error-level finding (its check and file), then each check that broke.
+37 -6
View File
@@ -3,10 +3,10 @@
//! --agent A` adds them, and they hold inside the raea app too, which leaves each agent its own shell). Before a shell
//! command: media opened in the Mac's viewer or a browser is stopped once while the raea app is installed, the reason
//! naming `raea show`; the same command tried again goes through, so an agent that means it says so twice. After a
//! file is saved: nothing (docs/check.feature: a render checks its own output at its end). As a turn ends: `raea check
//! --at done` on the brief's goals (apps/check/make), which reads each deliverable's kept check. After any tool, and as
//! a turn ends: what the person sent from the raea app (inbox.rs). A stop is exit 2 with the reason on stderr, which
//! every harness hands its agent; what was sent goes back in the shape each one reads.
//! file is saved: `raea goal check --at edit` on a composition, or on a file under a brief. As a turn ends: `raea
//! goal check --at done` on the brief's goals (apps/check/make). After any tool, and as a turn ends: what the person sent from
//! the raea app (inbox.rs). A stop is exit 2 with the reason on stderr, which every harness hands its agent; the edit
//! moment's findings go back in the shape each one reads.
use serde_json::{Value, json};
use std::path::{Path, PathBuf};
@@ -114,6 +114,23 @@ pub fn steer(files: &[String]) -> String {
format!("raea: the raea app is installed here, so show this in it, not the Mac's viewer: `raea show {list}` (several stills make a storyboard; add --ask \"what you want from the person\"; inside the raea app, feed_post does the same). It brings the app's window up on it as an item the person can answer, and their answer comes to the inbox file it prints. If the Mac's viewer really is what's wanted (the person asked for it, or raea show can't), run the same command again and it goes through.")
}
/// The files a tool call saved: `file_path` or `path` (Claude Code, Kimi Code, Gemini CLI), or the files an apply_patch
/// adds or updates (Codex).
fn saved(v: &Value) -> Vec<String> {
let i = &v["tool_input"];
if let Some(p) = i["file_path"].as_str().or(i["path"].as_str()).or(i["absolute_path"].as_str()) {
return vec![p.to_string()];
}
let patch = i["command"].as_str().or(i["input"].as_str()).unwrap_or("");
patch.lines().filter_map(|l| ["*** Add File: ", "*** Update File: "].iter().find_map(|head| l.strip_prefix(head))).map(str::trim).map(String::from).collect()
}
/// Whether a saved file is held at the edit moment: a composition (a .tsx that registers a root), or any file under a
/// brief.ts
fn held_at_edit(p: &Path) -> bool {
(p.extension().is_some_and(|e| e == "tsx") && std::fs::read_to_string(p).is_ok_and(|t| t.contains("registerRoot"))) || p.parent().is_some_and(|d| raea_app_check_make::brief_with_job(d).is_some())
}
/// Findings for the agent in the shape its harness reads after a tool: Gemini CLI's AfterTool context, Kimi Code's
/// plain stdout, Claude Code's and Codex's PostToolUse context.
fn after(agent: &str, text: &str) -> String {
@@ -161,8 +178,20 @@ pub fn hook(args: &[String]) -> R<String> {
}
return Ok(String::new());
}
// no check after a save (docs/check.feature CK1): a render checks its own output at its end, once
Ok(sent.map(|t| after(agent, &t)).unwrap_or_default())
// the edit moment of the loop (docs/goal.feature MK33): `raea goal check FILE --at edit` on a saved composition, or
// on any file under a brief; a save that passes says nothing
let me = std::env::current_exe().map_err(|e| e.to_string())?;
let mut found = Vec::new();
for path in saved(&v).iter().filter(|p| held_at_edit(Path::new(p))) {
let dir = Path::new(path).parent().filter(|d| d.is_dir()).map(Path::to_path_buf).unwrap_or_else(|| PathBuf::from(v["cwd"].as_str().unwrap_or(".")));
let Ok(out) = std::process::Command::new(&me).args(["goal", "check", "--at", "edit"]).arg(path).current_dir(dir).env("RAEA_RECORD", "off").output() else { continue };
if out.status.code() == Some(1) {
found.extend(String::from_utf8_lossy(&out.stdout).lines().filter(|l| !l.starts_with("PASSED")).map(String::from));
}
}
let edit = (!found.is_empty()).then(|| format!("raea goal check --at edit after this save:\n{}", found.join("\n")));
let text = [sent, edit].into_iter().flatten().collect::<Vec<_>>().join("\n\n");
Ok(if text.is_empty() { String::new() } else { after(agent, &text) })
}
#[cfg(test)]
@@ -188,6 +217,8 @@ mod tests {
assert_eq!(agent_of(&json!({"hook_event_name": "PreToolUse", "tool_name": "Bash"})), "claude");
assert_eq!(shell_command(&json!({"tool_name": "shell_command", "tool_input": {"command": "open a.png"}})), Some("open a.png"));
assert_eq!(shell_command(&json!({"tool_name": "apply_patch", "tool_input": {"command": "*** Begin Patch\n"}})), None);
assert_eq!(saved(&json!({"tool_input": {"command": "*** Begin Patch\n*** Update File: a/E.tsx\n@@\n*** Add File: b.ts\n"}})), ["a/E.tsx", "b.ts"]);
assert_eq!(saved(&json!({"tool_input": {"path": "E.tsx"}})), ["E.tsx"]);
assert_eq!(after("kimi", "x"), "x");
assert!(after("gemini", "x").contains("AfterTool") && after("codex", "x").contains("PostToolUse"));
assert!(steer(&["a b.png".into()]).contains("`raea show \"a b.png\"`"));
+1 -20
View File
@@ -192,10 +192,6 @@ pub fn face_cover(runs: &[Run], faces: &[(f64, f64, [f64; 4])], issues: &mut Vec
}
}
/// The app's right-hand buttons start this far down the frame (sdk/video/src/zones.ts RAIL): the right zone is under it.
/// 12-05: a centred end card at 35% down was an error for the right zone, where no app draws anything.
pub const RAIL: f64 = 0.45;
/// the zones where text can't go, as [top, right, bottom, left] at 1080 wide (sdk/guides/craft/floor.md)
pub fn zones(w: f64, h: f64, shape: Option<&str>, platform: Option<&str>) -> [f64; 4] {
let r = w / h;
@@ -228,8 +224,7 @@ pub fn text_rules(runs: &[Run], heard: Option<&[Word]>, w: f64, h: f64, shape: O
let [x, y, bw, bh] = r.box_;
let q = quote(&r.text);
let off = |&[x, y, bw, bh]: &[f64; 4]| x < -1.0 || y < -1.0 || x + bw > w + 1.0 || y + bh > h + 1.0;
// the right zone is the app's buttons, which start RAIL down the frame: above them the right edge is clear
let zoned = |&[x, y, bw, bh]: &[f64; 4]| y < zt || (x + bw > w - zr && y + bh > RAIL * h) || y + bh > h - zb || x < zl;
let zoned = |&[x, y, bw, bh]: &[f64; 4]| y < zt || x + bw > w - zr || y + bh > h - zb || x < zl;
if r.boxes.iter().all(off) {
clipped += 1;
issues.push(Issue { rule: "clipped", p: 0, at: Some(r.from), says: format!("{q} runs off the frame (box {x:.0},{y:.0} {bw:.0}x{bh:.0} in {w:.0}x{h:.0}); fit it or break the line") });
@@ -318,20 +313,6 @@ pub fn cues(runs: &[Run], words: &[Word], issues: &mut Vec<Issue>, passed: &mut
#[cfg(test)]
mod tests {
/// The right zone is the app's buttons, from RAIL down: a centred end card above them is clear (12-05, an end card 35%
/// down was an error); the same card over the buttons isn't.
#[test]
fn the_right_zone_starts_where_the_apps_buttons_do() {
let right = |y: f64| {
let m = serde_json::json!({"fps": 1.0, "frames": [{"frame": 0, "text": [{"text": "THE BODY SHOP", "box": [134.0, y, 812.0, 112.0]}]}]});
let (mut issues, mut passed) = (vec![], vec![]);
text_rules(&text_runs(&m), None, 1080.0, 1920.0, None, None, &mut issues, &mut passed);
issues.into_iter().filter(|i| i.rule == "safe-area").map(|i| i.says).collect::<String>()
};
assert_eq!(right(682.0), "");
assert!(right(1290.0).contains("at the right (keep 140 px clear)"), "{}", right(1290.0));
}
use super::*;
use serde_json::json;
+1 -1
View File
@@ -83,7 +83,7 @@ pub struct CutPlan {
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(optional_fields)]
#[ts(rename = "CutBeat")]
#[ts(rename = "Beat")]
pub struct Beat {
/// where it starts, in seconds from the cut's start (0 for the first)
pub at: f64,
+3 -3
View File
@@ -54,11 +54,11 @@ pub fn declarations() -> String {
/// The goal's declarations (what the work is held to: goal.rs, cut.rs, playable.rs, rules.rs): sdk/raea/src/brief-goal.gen.ts
pub fn goal_declarations() -> String {
let cfg = Config::new();
// a cut's beats are its own (cut.rs Beat, CutBeat in TypeScript: feel, story, asl, tempo), not a script's
let mut out = vec!["// Generated from raea-core-brief (core/brief) by its `goal_declarations`; edit the Rust, not this.".to_string()];
// a cut's beats are a script's (script.rs Beat)
let mut out = vec!["// Generated from raea-core-brief (core/brief) by its `goal_declarations`; edit the Rust, not this.\nimport type { Beat } from \"./brief.gen\";".to_string()];
out.extend(decls!(cfg;
goal::Goal, goal::Kind, goal::Source, goal::DialValue, goal::Dial, goal::Route, goal::Origin, goal::Pick, goal::Object, goal::Shot, goal::Goals,
cut::Cut, cut::Quoted<u32>, cut::CutPlan, cut::Beat, cut::Phrase, cut::Cta, cut::Open,
cut::Cut, cut::Quoted<u32>, cut::CutPlan, cut::Phrase, cut::Cta, cut::Open,
playable::Playable, playable::Orientation,
rules::Rule,
));
-60
View File
@@ -1,60 +0,0 @@
Feature: one check (12-04, Shane: "fix how every agent checks its work ... removing ask and judge completely and all
that exists is check as the overarching method")
Round 26's agents met about nine ways to check their work (raea goal check, goal seen, goal judge, raea ask, raea
check's taste, the old frames command, a lines.txt words check, raea cloud's stop critic and run eval, and the render and
publish tools' own copies), two of them broken on the boxes, and 183 findings on 10 cuts of which about 10 were real
faults. Every agent, on raea cloud, in the desktop app or with the raea skill, now has one: `raea check`.
Rule: every rule lives in one of three places, or nowhere (12-04, Shane)
Built in: a component or an SDK default that can't produce the fault (captions from the words file, in the safe area;
a Region that keeps text off faces and the app's buttons; raea cut, which cuts only in pauses). Its check is a
backstop that shouldn't fire.
A check, hard or soft: hard is an error (a fault in the deliverable), soft a warning (a note for the person, never a
reason to render again).
Context the agent retrieves while it makes the work: craft and taste (how captions read, pacing, a hook, a brand's
fingerprint, the person's past notes) live in the skill, the guides and memory. Nothing grades the work against them.
A rule that fits none of these isn't a rule: no ritual (the agent saying it looked: `seen`) and no model's opinion
of the work (taste, a critic, a judge, an ask).
Scenario: CK0 one verb
Given any project
When an agent or a person runs `raea check [FILE...] [--at edit|render|publish|done]`
Then it runs every rule the project's goal holds at that moment, and nothing else checks the work
And `raea goal check` still runs as `raea check`, for boxes and tools on an older raea
And `raea ask`, `raea goal judge`, `raea judge` and `raea goal seen` are gone: raea says so, and names `raea check`
Scenario: CK1 run once, after the render
Given a render that wrote OUT.mp4 (on this machine, or on raea cloud's farm and checked by the box that sent it)
When it ends
Then `raea check OUT.mp4 --at render` runs once and keeps OUT.check.json beside it
And publish and done read OUT.check.json while it's no older than OUT.mp4 or its manifest, and never run its rules again
Scenario: CK2 only real faults, one line a rule
Given a cut
Then it is held to: a word clipped or missing (words, sound), a face cut by the frame edge (frames), text over a face,
a sign or the app's buttons (place, floor), captions over talking (captions), the brief's must-say, never-say and
CTA (say, never, cta), its size, length and name (shape, sizes, naming), the brief's count and open items, and what
the render itself found (render)
And a 3D scene, kit or shot is held to its deliverables and what its render found: clipping, a part out of place or
under its detail, light that jumps
And each rule says at most one line a file: its first finding and how many more like it
Scenario: CK3 our own text from the manifest
Given a render manifest beside a video
Then captions, placement and size read the texts raea drew from it, never by reading the frames
And text in the source footage (a sign, a phone's screen) is never counted as the edit's
Scenario: CK4 no critic, no ritual in the loop
Then no check asks a model to judge the work, and no check waits for the agent to say it looked
And a check that can't run on a machine (Mac, Linux, Windows, a raea cloud box) is removed, not left waiting
Scenario: CK5 a brief that can't break the check
Given brief.ts with `goal: [steps, cut({...})]`, `goal: steps` or `goal: cut({...})`
Then `raea check` reads every goal in it, and never crashes on what an agent wrote
And a cut's beats are the agent's plan, never a rule it is checked against
Scenario: CK6 one set of instructions
Then raea's skill, its guides, `raea help`, the AGENTS.md raea writes, raea cloud's method, workflows and skills, and
the desktop app all name `raea check` as the one way to check, and none names ask, judge, seen, frames check or a
lines.txt words check
-14
View File
@@ -103,20 +103,6 @@ Feature: raea cloud: raea and an ACP agent on a server of your own (sdk/cloud)
And a worker that can't be reached fails the render unless RAEA_CLOUD_GPU_FALLBACK=cpu
And every other raea command runs on the box
Scenario: CL16. raea cloud's boxes are Fly Machines
Given the boxes were Sprites (deploy/sprites/), which ran at most 10 at once, read their disk in about 26 ms a
read and stopped at 8 cores and 16 GB (12-03)
Then each box is a Fly app of its own (raea-box-N for the box raea-N) with one Machine of deploy/fly/Dockerfile,
8 dedicated cores and 16 GB, and a volume for its home folder: the agents' sign-ins, ~/.raea-cloud.env, ~/work
And its work folder is /home/sprite/work as on a Sprite (the image links /home/sprite to /home/raea), so a moved
project's folders and paths are the same
And the server exits when the box has been idle RAEA_CLOUD_IDLE_STOP_MIN minutes (no request, connection,
process working in ~/work, or hold file touched lately: server/idle.ts), the Machine stays stopped, and Fly's
proxy starts it again at the next request
And deploy/fly/box.sh makes a box (up), moves a Sprite's (move: its token kept, its home sent from the Sprite
straight to the new box's file API), and puts every box on a release (latest)
And a file PUT to a box streams to disk and lands whole, never held in memory
Rule: it is proven end to end
Scenario: CL12. A stand-in agent, then a real one
Then test/smoke.sh builds the image, starts it, and checks CL4-CL7, CL14 and CL15 with test/echo-agent.mjs (a
+9 -21
View File
@@ -9,27 +9,13 @@ use std::path::Path;
/// `raea goal`'s verbs (docs/goal.feature): the loop's runner, sdk/goal/src/run.ts, run here on raea's JavaScriptCore
/// with Node's core. `goal gates` (the record and critic gates the packs read) is apps/make's, and `goal next` this
/// binary's own (next()).
pub const GOAL_TS: &[&str] = &["check", "tasks"];
/// Verbs that asked a model for its opinion of the work, or the agent to say it looked (docs/check.feature): gone, and
/// said so with where their part went, so an old skill or AGENTS.md that names one is set right at once.
pub fn gone(args: &[String]) -> Option<String> {
let v = |i: usize| args.get(i).map(String::as_str);
let what = match (v(0), v(1)) {
(Some("ask"), _) => "raea ask",
(Some("judge"), _) => "raea judge",
(Some("goal"), Some("seen")) => "raea goal seen",
(Some("goal"), Some("judge")) => "raea goal judge",
(Some("goal"), Some("gates")) => "raea goal gates",
(Some("check"), _) if args.iter().any(|a| a == "--taste" || a == "--quick") => "raea check --taste",
_ => return None,
};
Some(format!("{what} is gone (docs/check.feature): `raea check` is the one check, and a render checks its own output at its end. How the work should look and sound is the raea skill's and its guides', read while you make it; nothing grades it after."))
}
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 check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--manifest render.json] [--json] (the one check (docs/check.feature): every rule each goal of brief.ts holds at that moment, real faults only, one line a rule a file; with no goal, the floor. A render runs it on its output at its end and keeps OUT.check.json beside it; publish and done read that and never run it again. review/goal.json; exit 1 on an error. `raea goal check` is its old name)
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\" --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] (a goal's `says` rules judged now, as `raea goal check` judges them itself: a rule with a piece to watch or hear (a file it names, else the videos under out/) by clef-omni, any other by a fresh session of the agent this project runs on, which only reads; review/judge/NAME.json. Who judges is raea's to settle, never yours)
raea goal next [DIR] (the two or three useful next steps for the project, from its brief, its goals, compositions, renders and checks)";
/// One of GOAL_TS's verbs (or `make place`): printed as it says, and the process exits with its code (1 on an
@@ -56,12 +42,14 @@ pub fn render_moment(args: &[String]) -> i32 {
a.extend(["--manifest".into(), m]);
}
match goal_run(&a) {
// an ERROR is a fault in the deliverable: fix its cause in the composition before this render is handed over
Ok(1) => 1,
Ok(1) => {
println!("fix every ERROR above, then render again");
1
}
Ok(_) => 0,
// no runner (an install without the SDK): the render stands, and says so
Err(e) => {
println!("raea check: {e}");
println!("raea goal check: {e}");
0
}
}
+13 -12
View File
@@ -204,17 +204,17 @@ pub fn run(args: &[String]) -> R<String> {
if args[0] == "spec" {
return spec::spec_cli(&args[1..]);
}
// `check VIDEO --taste taste.ts|DIR`: the taste's .ts files evaluated here, then the check (main.rs takes the rest)
if args[0] == "check" && args.iter().any(|a| a == "--quick") {
let (report, bad) = raea_app_check::quick::quick(&args[1..], spec::tastes_ts(args)?)?;
println!("{report}");
std::process::exit(i32::from(bad));
}
// `hook [AGENT]`: every agent harness's tool hooks (A5d): raea show over Preview, the quick check after a save (SK10)
if args[0] == "hook" { return raea_app_check::hook::hook(&args[1..]); }
// `check [FILE...] [--at MOMENT]`: the one check (docs/check.feature), sdk/goal/src/run.ts; a model's opinion
// (`--taste`, `ask`, `judge`, `goal seen|judge`) is no check, and refused with where its part went
if let Some(why) = gone(args) { return Err(why); }
// `check EDIT.tsx|NAME.story.ts`: a project's own checks over a composition's frames or a story (DR4), before a
// render; the deliverables' check is the runner's
if args[0] == "check" && args[1..].iter().find(|a| !a.starts_with('-')).is_some_and(|a| a.ends_with(".tsx") || a.ends_with(".ts")) {
std::process::exit(raea_app_direction::check::cli(&args[1..], &CHECK));
}
if args[0] == "check" { return goal_ts(&[&["goal".to_string()], args].concat()); }
// `check PROJECT|EDIT.tsx`: every rule's check over the compositions' worlds (DR4); a video is the floor alone
if args[0] == "check" && !raea_app_direction::check::of_video(&args[1..]) { std::process::exit(raea_app_direction::check::cli(&args[1..], &CHECK)); }
if args[0] == "check" { std::process::exit(raea_app_check::cli_with(&args[1..], spec::tastes_ts(args)?)); }
if args[0] == "world" { std::process::exit(raea_app_direction::cli(&args[1..])); } // a frame as one world of facts (docs/direction.feature DR1)
if args[0] == "findings" { return raea_app_direction::findings::cli(args); } // the project's record read back (DR3)
if args[0] == "notes" { std::process::exit(raea_app_notes::cli(&args[1..], spec::spec_json, notes_run)); } // a person's notes as files, restated as asks, each with a check (DR5, DR6)
@@ -280,12 +280,13 @@ pub fn run(args: &[String]) -> R<String> {
Some("gen") => return raea_app_tools::generate::generate(args),
// the agent shell's own verbs ported here (`init`, `cut`, `frame`): engine/cli's handler, run by its native.ts (shell())
Some(v) if SHELL.contains(&v) => return shell(args),
// `goal check|tasks` and `make place`: the loop's runner, sdk/goal/src/run.ts (goal_ts()); `goal check` is `raea
// check`'s old name; `goal next` this binary's
// `goal check|tasks|seen|judge` and `make place`: the loop's runner, sdk/goal/src/run.ts (goal_ts()); `goal gates`
// apps/make's; `goal next` this binary's
Some("goal") if args.get(1).is_some_and(|v| GOAL_TS.contains(&v.as_str())) => return goal_ts(args),
Some("make") if args.get(1).map(String::as_str) == Some("place") => return goal_ts(&[&["goal".to_string()], &args[1..]].concat()),
Some("goal") if args.get(1).map(String::as_str) == Some("gates") => return raea_app_make::cli(args),
Some("goal") if args.get(1).map(String::as_str) == Some("next") => return next(&args[2..]),
Some("goal") => return Err(format!("raea goal tasks|next (raea check checks the work)\n {GOAL_USAGE}")),
Some("goal") => return Err(format!("raea goal check|tasks|seen|judge|gates|next\n {GOAL_USAGE}")),
_ => if let Some(r) = raea_app_solid::verb(args) { return r }, // `solid info|view FILE.ts`, `judge DIR`, `ask FILE` (apps/solid)
}
// `master-gain BUNDLE.js DIR`: the gain and ceiling a composition's render masters its sound with, as JSON (live
+23 -18
View File
@@ -79,15 +79,19 @@ A video edit as a React + TypeScript project, rendered by raea.
- edit.tsx: the composition. Change anything: layout, timing, which component plays when.
- 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 its site), loaded with the project's
Tailwind: \`<style>{css}</style>\`, css from "./styles.gen". Its colours and faces are the palette, as classes
(text-brand-accent, bg-brand-surface, text-brand-on-accent, text-brand-ink, brand-1/2/3, font-brand,
font-brand-body) or --brand-* variables; never a colour from outside it. Size, weight, layout and motion are yours,
chosen against the brand's own best work.
- \`raea render edit.tsx -o final.mp4 --manifest render.json\` renders, then checks the export once as it ends
(\`raea check\`: real faults only, each ERROR with its fix, kept as final.check.json; nothing runs it again). Fix the
ERRORs; a warning is a note for the person. \`raea render edit.tsx --at 105 -o review/stills/\` gives frame 105 to
look at. \`raea guide\` has the craft (\`raea guide motion\` for writing the TSX); \`raea help\` lists the rest.
- 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). 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);
\`raea help\` lists the rest.
## raea (everything there is; import from "raea")
@@ -95,18 +99,19 @@ Time: useCurrentFrame() (frames, from 0 inside the nearest Sequence), useVideoCo
durationInFrames}, interpolate(frame, [in...], [out...], {extrapolateLeft, extrapolateRight: "clamp", easing}),
spring({frame, fps, config}), Easing.bezier(a, b, c, d) / Easing.inOut(...).
Layout: <AbsoluteFill>, <Sequence from durationInFrames>, <Series><Series.Sequence durationInFrames>, <Loop>, <Freeze>.
Media: <Video src startFrom endAt volume playbackRate muted punchIn style>; a take cropped to another shape goes
through components/Framed.tsx when the project has it (<Framed src startFrom endAt at? punchIn?>: the crop on the
person's face, from footage/faces.json; at picks a face), else an objectPosition you
measured on the take, never a guess. <Audio src startFrom endAt volume={n | (f) => n} gainDb fadeIn fadeOut>,
Media: <Video src startFrom endAt volume playbackRate muted framing="face" punchIn style> (framing="face" keeps the
eyes 38% down as the speaker moves; an objectPosition or transform turns it off), <Audio src startFrom endAt volume={n | (f) => n} gainDb fadeIn fadeOut>,
<Img src>. Media files import as modules: import take from
"./media/x.mov". Sound: decide what each scene is heard as first (silence, its own sound, effects, music), and make
it as \`raea guide sound\` says; narration is <Speech text start> from raea/speech. <Mix lufs ceiling> masters the sound.
"./media/x.mov". Sound: decide what each scene is heard as first (silence, its own sound, score, effects); music,
where there is some, in Tone.js (import * as Tone from "raea/tone"), composed for the cut (a motif, chords that move,
a part with rhythm, ending on a cut; never a pad or drone by default): instruments in a Tone.Sampler playing Parts and
Sequences, the notes from a sample library (\`raea make sounds\`, \`raea guide sources\`) or, for a timbre no library has,
Tone.tokensynth("a bowed saw, close", ["C3", "C4", "C5"]); sao("prompt", {seconds}) for an effect, as an <Audio src>; narration
is <Speech text start> from raea/speech (Pocket TTS). All of it local. <Mix lufs ceiling> masters the sound.
Words: useWords() -> [{text, from, to}] (frames, the cuts' words), word("phrase") -> the frame it's said,
findPhrase(words, "phrase", {occurrence, edge: "start" | "end"}).
Placement: <Captions said?> (said: each cut's own words) captions in the brand's style; titles go in <Region
name="top" | "bottom" | "center" | "auto" | "full">. Both keep clear of faces and the app's buttons: never type a
text's top or left.
Placement: <Region name="top" | "bottom" | "center" | "auto" | "full"> keeps a part in a band clear of the face and
the platforms' buttons; useRegion() gives its box.
Composition: registerRoot(() => <Composition id component width height fps durationInFrames />).
Not there: React hooks come from "react" (useMemo, useState), not from raea.
`;
+3 -2
View File
@@ -37,8 +37,9 @@ pub fn main() -> i32 {
}
};
match args.first().map(String::as_str) {
// `floor VIDEO.mp4 …`: the floor's measurable lines on an export, ranked P0-P3, as raea check's floor pack reads them
Some("floor") => raea_app_check::cli_with(&args[1..], Vec::new()),
// `check VIDEO.mp4 …`: the floor's measurable lines on an export, ranked P0-P3
// (with --taste or --quick, through the engine, which evaluates the taste.ts files or renders stills: `check` here)
Some("check") if !args.iter().any(|a| a == "--taste" || a == "--quick") && raea_app_direction::check::of_video(&args[1..]) => raea_app_check::cli_with(&args[1..], Vec::new()),
// `ci …`: the gates' sound measurements and lightspeed's process measurements
Some("ci") => raea_app_ci::cli(&args[1..]),
_ => {
+3 -29
View File
@@ -4,9 +4,8 @@
//
// native.ts RAEA VERB ARGS... RAEA: the native raea's path, for the engine's own verbs
import { spawnSync } from "node:child_process";
import { createHash } from "node:crypto";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
import { homedir, tmpdir } from "node:os";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { basename, delimiter, dirname, extname } from "node:path";
import { brandKit, pixelsOf } from "./brand";
import { readSite, stylesOf } from "./scrape";
@@ -119,31 +118,6 @@ function hearTake(take: string, out: string) {
}
}
/** A take's own jump cuts (raea media cuts, every frame decoded: 43 s for a 4-minute take on a box), found once per take
* and kept by its path, size and time in raea's cache, so the second `raea cut` on a take doesn't decode it again
* (12-04: three cuts on one take in a step ran past a box step's 3 minutes, and the run stopped with nothing made) */
function jumpCuts(take: string): number[] {
const file = at(take);
let kept = "";
try {
const s = statSync(file);
const dir = `${process.env.XDG_CACHE_HOME || `${homedir()}/.cache`}/raea/cuts`;
kept = `${dir}/${createHash("sha1").update(`${realpathSync(file)}|${s.size}|${s.mtimeMs}|0.08`).digest("hex")}.json`;
if (existsSync(kept)) return JSON.parse(readFileSync(kept, "utf8")) as number[];
} catch {
kept = "";
}
const cuts = (engineJson(["media", "cuts", file, "--threshold", "0.08"]).cuts as { at: number }[]).map((c) => c.at);
if (kept)
try {
mkdirSync(dirname(kept), { recursive: true });
writeFileSync(kept, JSON.stringify(cuts));
} catch {
// a cache that can't be written costs the next cut the decode, nothing else
}
return cuts;
}
/** Where to cut a take for each line: found word for word in its transcript, in order (a line that follows the last one
* in the take joins its clip), else where 70% of its words are said in a window its length (and a note says so); each
* cut inside the pauses around it, off the take's own jump cuts, on the take's frame grid. [from, to, said] in the
@@ -152,7 +126,7 @@ function cutPlan(take: string, ws: Word[], lines: string[]): { plan: [number, nu
const norm = (s: string) => s.toLowerCase().replace(/[^\p{L}\p{N}'\s]/gu, "");
const toks = ws.map((w) => norm(w.text).trim());
// a sound-only take has no jump cuts to keep off, and its grid is the edit's usual 30 (a probe has no video fps)
const cuts = isAudio(take) ? [] : jumpCuts(take);
const cuts = isAudio(take) ? [] : (engineJson(["media", "cuts", at(take), "--threshold", "0.08"]).cuts as { at: number }[]).map((c) => c.at);
const fps = (engineJson(["media", "probe", at(take)]).video?.fps as number) || 30;
let from = 0;
const spans: [number, number][] = [];
+5
View File
@@ -83,6 +83,11 @@ pub fn taste_file(dir: &Path, name: &str) -> Option<(PathBuf, String)> {
})
}
/// `--taste`'s .ts files, each checked as Taste.
pub fn tastes_ts(args: &[String]) -> R<Vec<schema::Taste>> {
raea_app_direction::check::taste_files(args).iter().map(|f| read_spec(f)).collect()
}
/// `raea spec FILE.ts [--as KIND]`: the default export as JSON, checked as KIND (by default from the file's name:
/// brief, script, taste or parts in it; anything else is checked as Taste, the files in
/// ~/.raea/taste being named for their kind).
-3
View File
@@ -84,9 +84,6 @@ fn a_verb_refuses_what_it_doesnt_take() {
let why = stray(&help, &a(&["render", "e.tsx", "f.tsx", "-o", "o.mp4"])).unwrap();
assert!(why.contains("\"f.tsx\": it takes 1 argument besides its flags"), "{why}");
assert!(stray(&help, &a(&["play", "g.tsx", "--full"])).unwrap().starts_with("raea play doesn't take \"--full\""));
// `goal check`, check's old name, takes check's flags (CK0)
assert_eq!(stray(&help, &a(&["goal", "check", "out/cuts/a_9x16.mp4", "--at", "render", "--manifest", "out/cuts/a_9x16.render.json"])), None);
assert!(stray(&help, &a(&["goal", "check", "--frobnicate"])).unwrap().starts_with("raea check doesn't take \"--frobnicate\""));
assert!(stray(&help, &a(&["track", "c.mp4", "--setup"])).is_some());
assert!(stray(&help, &a(&["splat", "train", "v.mp4", "-o", "o.ply", "--steps", "100"])).is_none());
}
-5
View File
@@ -143,11 +143,6 @@ use raea_cli_goal::verb_at;
/// the ones it takes. None when it is, or when the help doesn't give the verb's usage.
pub fn stray(help: &str, args: &[String]) -> Option<String> {
let verb = args.first()?;
// `goal check` is `check`'s old name (docs/check.feature CK0): its flags are check's, which the help lists under
// check alone (12-04: `raea goal check OUT --at render`, raea cloud's render tool, was refused for --at)
if verb == "goal" && args.get(1).is_some_and(|v| v == "check") {
return stray(help, &args[1..]);
}
// physics hands its subverb's arguments to the bake, the goo or the part, which check them; gen to raea-io-gen's own
if verb == "physics" || verb == "gen" {
return None;
+1 -1
View File
@@ -95,7 +95,7 @@ pub fn mezz(args: &[String]) -> R<String> {
pub use raea_cli_goal::{GOAL_TS, GOAL_USAGE, gone, goal_ts, render_moment};
pub use raea_cli_goal::{GOAL_TS, GOAL_USAGE, goal_ts, render_moment};
/// The agent shell's own verbs (engine/cli/src/index.ts) this binary runs; the rest come one by one (docs/agent-surfaces.md)
pub const SHELL: &[&str] = &["init", "cut", "words", "frame", "component", "brand", "library", "show", "clothes", "bug"];
-3
View File
@@ -2,6 +2,3 @@ node_modules
deploy
test
README.md
# a box image (deploy/fly/Dockerfile) takes these two from deploy/
!deploy/git
!deploy/fly/start.sh
-76
View File
@@ -1,76 +0,0 @@
# A raea cloud box as a Fly Machine (12-03: the boxes moved off Sprites, which ran at most 10 at once, read their disk
# in about 26 ms a read, and stopped at 8 cores and 16 GB). What deploy/sprites/setup.sh put on a Sprite is built in
# here once: Ubuntu as the Sprites ran it, raea's Linux release, Node, Chrome for the Google sign-in, ffmpeg, the PDF
# tools and brand faces, the ACP agents and sdk/cloud's server. The home folder (/home/raea: the agents' sign-ins,
# ~/.raea-cloud.env, ~/work) is the Machine's volume, so a new image changes the programs and keeps everything else.
# deploy/fly/box.sh builds it from sdk/cloud:
#
# fly deploy --build-only --push -c deploy/fly/image.toml --build-arg RAEA_VERSION=0.1.17-rc3 ...
FROM ubuntu:26.04
ENV DEBIAN_FRONTEND=noninteractive
# what setup.sh installed: raea's runtime libraries and Mesa's lavapipe (the box draws previews on its CPU; its renders
# go to the farm), ffmpeg and the PDF tools (12-02: every agent installed them itself at each project's start), Python
# (the footage prep's transcript file), the sign-in browser's display, and sudo for an agent that needs a package
RUN apt-get update -qq && apt-get install -y -qq --no-install-recommends \
ca-certificates curl git git-lfs zstd xz-utils bzip2 unzip procps less ripgrep openssl sudo python3 \
libasound2t64 libfontconfig1 libvulkan1 mesa-vulkan-drivers vulkan-tools ffmpeg poppler-utils \
xvfb x11vnc xdotool fonts-noto-color-emoji > /dev/null \
&& 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 apt-get install -y -qq --no-install-recommends "$f" > /dev/null 2>&1 || echo "no $f"; done \
&& curl -fsSLo /tmp/chrome.deb https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb \
&& apt-get install -y -qq /tmp/chrome.deb > /dev/null && rm -f /tmp/chrome.deb \
&& rm -rf /var/lib/apt/lists/*
ARG NODE=24.22.0
RUN curl -fsSL "https://nodejs.org/dist/v$NODE/node-v$NODE-linux-x64.tar.xz" | tar -xJ -C /opt \
&& ln -sf /opt/node-v$NODE-linux-x64/bin/node /opt/node-v$NODE-linux-x64/bin/npm /opt/node-v$NODE-linux-x64/bin/npx /usr/local/bin/
# the box's user, uid 1000 as the image's entrypoint expects; /home/sprite is the same folder, so the paths a project
# moved from a Sprite wrote down (its agents' transcripts, its settings) still open
RUN (userdel -r ubuntu 2> /dev/null || true) && useradd -m -u 1000 -s /bin/bash raea \
&& echo 'raea ALL=(ALL) NOPASSWD:ALL' > /etc/sudoers.d/raea && chmod 440 /etc/sudoers.d/raea \
&& ln -s /home/raea /home/sprite
# raea, checked against its release's .sha256
ARG RAEA_VERSION
ARG RAEA_REPO=shinyobjectz/raea
RUN set -e; : "${RAEA_VERSION:?--build-arg RAEA_VERSION}"; f=raea-$RAEA_VERSION-linux-x86_64.tar.gz; \
u=https://github.com/$RAEA_REPO/releases/download/v$RAEA_VERSION; \
cd /tmp && curl -fsSL -o $f "$u/$f" && curl -fsSL -o $f.sha256 "$u/$f.sha256" && sha256sum -c --quiet $f.sha256 \
&& mkdir -p /opt/raea && tar -xzf $f -C /opt/raea --strip-components=1 && rm -f $f $f.sha256 \
&& /opt/raea/bin/raea --version
WORKDIR /opt/raea-cloud
COPY package.json package-lock.json ./
RUN npm ci --omit=dev --no-fund --no-audit --loglevel=error
# the agents, by ACP registry id, with the server they're started by (agents.ts reads its neighbours)
COPY server server
ARG AGENTS="antigravity-acp claude-acp kimi-code"
RUN node server/agents.ts install $AGENTS
COPY src src
COPY image image
# raea's SDK files fixed after the release the image installs (image/sdk-overlay, by their path under share/raea/sdk),
# each only while the installed file still has the fault, so a release with the fix keeps its own. 12-03: 0.1.17-rc4's
# goal.ts named-imports spawn, which raea's runtime hasn't got, and every raea goal check on a box died (raea #329)
RUN f=/opt/raea/share/raea/sdk/goal/src/packs/goal.ts; \
if grep -q 'import { spawn } from "node:child_process"' "$f"; then cp image/sdk-overlay/goal/src/packs/goal.ts "$f" && echo "overlay: goal.ts"; fi
COPY deploy/git deploy/git
COPY deploy/fly/start.sh image/fly-start.sh
# readable by raea whatever modes the files had where the image was built (12-03: a checkout made with umask 077 gave
# the entrypoint 711, and it re-runs itself as raea)
RUN chmod -R a+rX /opt/raea-cloud && chmod +x image/*.sh deploy/git/* \
&& ln -sf /opt/raea-cloud/image/raea.sh /usr/local/bin/raea \
&& ln -sf /opt/raea-cloud/deploy/git/repo.sh /usr/local/bin/raea-repo \
&& git lfs install --system --skip-repo > /dev/null
# the build, shown on GET /v1/health and raea cloud's /v1/admin/boxes, so which code a box runs is never a guess
ARG COMMIT=unknown
ARG DIRTY=false
RUN printf '{"commit":"%s","build":"%.12s","dirty":%s,"raea":"%s","image":"fly","built_at":"%s"}\n' \
"$COMMIT" "$COMMIT" "$DIRTY" "$RAEA_VERSION" "$(date -u +%Y-%m-%dT%H:%M:%S+00:00)" > /opt/raea-cloud/BUILD.json
# RAEA_CLOUD_IDLE_STOP_MIN: the server exits when the box has been idle this long, and the Machine stops (idle.ts)
ENV HOME=/home/raea NODE_ENV=production PORT=8080 WGPU_BACKEND=vulkan RAEA_CLOUD_DEVICE=cpu RAEA_CLOUD_IDLE_STOP_MIN=10
EXPOSE 8080
ENTRYPOINT ["/opt/raea-cloud/image/fly-start.sh"]
-234
View File
@@ -1,234 +0,0 @@
#!/bin/bash
# raea cloud's agent boxes as Fly Machines (12-03; they were Sprites, deploy/sprites/, which ran at most 10 at once and
# read their disk in about 26 ms a read). Each box is a Fly app of its own (raea-box-2 is the box raea-2) with one
# Machine of the box image (Dockerfile here) and one volume for its home folder: the agents' sign-ins, the box's
# settings (~/.raea-cloud.env) and ~/work. The Machine stops itself when the box is idle (server/idle.ts) and Fly's
# proxy starts it at the next request, so it bills while it works. From sdk/cloud:
#
# deploy/fly/box.sh image [VERSION] the box image built and pushed: raea VERSION's Linux release (the newest when
# none is named) and sdk/cloud's server from this tree (RAEA_CLOUD_REF: from
# raea's repo at that commit). Prints the image, kept in ~/.config/raea-cloud/fly-image
# deploy/fly/box.sh up NAME the box made or brought onto the last image built: its app, addresses, volume,
# settings and Machine, then its health
# deploy/fly/box.sh move NAME a Sprite box onto Fly: its settings (its token too, so raea cloud's list only
# changes address) and its home folder copied, then listed in raea cloud
# deploy/fly/box.sh register NAME the box into raea cloud's list at its Fly address (POST /v1/admin/boxes)
# deploy/fly/box.sh status NAME its address, Machine and health
# deploy/fly/box.sh token NAME its RAEA_CLOUD_TOKEN
# deploy/fly/box.sh list raea cloud's boxes in order, each one's health and build
# deploy/fly/box.sh latest [VERSION] the image built for a release and every Fly box in raea cloud's list put on it
# deploy/fly/box.sh key NAME a raea agent key (raea_ak_...) from stdin, or the clipboard, onto the box
# deploy/fly/box.sh sh NAME [CMD] a shell on the box (as root), or CMD there
#
# The org is raea's, written once in ~/.config/raea-cloud/fly.env (RAEA_FLY_ORG=raea), never another business's. Each
# box's settings are kept on this Mac too, in ~/.config/raea-cloud/boxes/NAME.env (mode 600), and go to the box as Fly
# secrets; the farm's come from ~/.config/raea-cloud/farm.env.
set -euo pipefail
REPO=shinyobjectz/raea
HERE=$(cd "$(dirname "$0")/../.." && pwd)
CONF=$HOME/.config/raea-cloud
FLY_CONF=${RAEA_FLY_ENV:-$CONF/fly.env}
ORG=$([ -f "$FLY_CONF" ] && sed -n 's/^RAEA_FLY_ORG=//p' "$FLY_CONF" | tail -1 || true)
[ -n "$ORG" ] || { echo "fly box: write RAEA_FLY_ORG=<the Fly org raea owns> in $FLY_CONF (fly orgs list)"; exit 2; }
# Content Jet's org and any other business's: never (private/cloud/sprites-denied.txt lists them for Sprites too)
DENIED=$(git -C "$HERE" rev-parse --show-toplevel 2> /dev/null)/private/cloud/sprites-denied.txt
if { [ -f "$DENIED" ] && grep -qxF "$ORG" "$DENIED"; } || [ "$ORG" = kamal-hafid ]; then
echo "fly box: $ORG belongs to another business; raea's boxes go in an org raea owns"; exit 2
fi
REGION=${RAEA_FLY_REGION:-iad}
SIZE=${RAEA_BOX_SIZE:-performance-8x}
VOLUME_GB=${RAEA_BOX_DISK_GB:-100}
IMAGE_APP=raea-box-image
FARM=${RAEA_FARM_ENV:-$CONF/farm.env}
newest() { gh release view -R "$REPO" --json tagName -q .tagName 2> /dev/null | sed 's/^v//'; }
NAME=${2:-}
app() { echo "raea-box-${1#raea-}"; }
url() { echo "https://$(app "$1").fly.dev"; }
envfile() { echo "$CONF/boxes/$1.env"; }
need_name() { [ -n "$NAME" ] || { echo "fly box: name the box (raea-2)"; exit 2; }; }
# whether the org has an app by this name (fly apps list --json: its table draws borders round each name)
has_app() { fly apps list --org "$ORG" --json 2> /dev/null | python3 -c 'import json,sys; sys.exit(0 if any(a.get("Name") == sys.argv[1] for a in json.load(sys.stdin)) else 1)' "$1"; }
machine() { fly machines list -a "$(app "$1")" --json 2> /dev/null | python3 -c 'import json,sys
m=[x for x in json.load(sys.stdin) if x.get("state")!="destroyed"]
print(m[0]["id"] if m else "")'; }
healthy() {
local u t
u=$(url "$1") t=$(sed -n 's/^RAEA_CLOUD_TOKEN=//p' "$(envfile "$1")")
for _ in $(seq 1 60); do
curl -fsS -m 20 -H "authorization: Bearer $t" "$u/v1/health" 2> /dev/null && return 0
sleep 5
done
return 1
}
case "${1:-}" in
image)
version=${2:-${RAEA_VERSION:-$(newest)}}
[ -n "$version" ] || { echo "fly box: couldn't read raea's newest release (gh signed in?)"; exit 2; }
src=$HERE
if [ -n "${RAEA_CLOUD_REF:-}" ]; then
# sdk/cloud at that commit of raea's repo, as a release's boxes take it
src=$(mktemp -d)
git -C "$src" init -q && git -C "$src" sparse-checkout set sdk/cloud
git -C "$src" fetch -q --depth 1 --filter=blob:none "https://github.com/$REPO" "$RAEA_CLOUD_REF" && git -C "$src" checkout -q FETCH_HEAD
src=$src/sdk/cloud
commit=$RAEA_CLOUD_REF dirty=false
else
commit=$(git -C "$HERE" rev-parse HEAD)
dirty=$([ -n "$(git -C "$HERE" status --porcelain -- .)" ] && echo true || echo false)
fi
has_app "$IMAGE_APP" || fly apps create "$IMAGE_APP" --org "$ORG" > /dev/null
# (|| true: on a clean tree the test fails, and set -e ended the script there with nothing said)
label=v$version-${commit:0:10}$([ "$dirty" = true ] && echo "-dirty-$(date +%s)" || true)
(cd "$src" && fly deploy --build-only --push -a "$IMAGE_APP" -c deploy/fly/image.toml --dockerfile deploy/fly/Dockerfile \
--image-label "$label" --build-arg RAEA_VERSION="$version" --build-arg COMMIT="$commit" --build-arg DIRTY="$dirty" .) >&2
echo "registry.fly.io/$IMAGE_APP:$label" | tee "$CONF/fly-image"
;;
up)
need_name
image=${RAEA_BOX_IMAGE:-$(cat "$CONF/fly-image" 2> /dev/null || true)}
[ -n "$image" ] || { echo "fly box: no image built yet (deploy/fly/box.sh image)"; exit 2; }
a=$(app "$NAME") f=$(envfile "$NAME")
mkdir -p "$CONF/boxes" && chmod 700 "$CONF/boxes"
if [ ! -s "$f" ]; then
# a new box: its own token, and the farm's settings
[ -f "$FARM" ] || { echo "fly box: $FARM names no farm (RAEA_CLOUD_GPU_URL, RAEA_CLOUD_GPU_TOKEN)"; exit 2; }
(umask 077; { echo "RAEA_CLOUD_TOKEN=$(openssl rand -hex 32)"; grep '^RAEA_CLOUD_GPU_' "$FARM"; echo "RAEA_API=https://api.raea.cloud"; } > "$f")
echo "fly box: $NAME is new: settings in $f (its agent key: deploy/fly/box.sh key $NAME)"
fi
has_app "$a" || fly apps create "$a" --org "$ORG" > /dev/null
fly ips list -a "$a" 2> /dev/null | grep -q 'v6' || {
fly ips allocate-v4 --shared -a "$a" > /dev/null
fly ips allocate-v6 -a "$a" > /dev/null
}
# the box's settings as Fly secrets, from the file (never on a command line)
fly secrets import --stage -a "$a" < "$f" > /dev/null
fly volumes list -a "$a" --json 2> /dev/null | python3 -c 'import json,sys; sys.exit(0 if any(v.get("name") == "home" and v.get("state") != "destroyed" for v in json.load(sys.stdin)) else 1)' || fly volumes create home --size "$VOLUME_GB" --region "$REGION" -a "$a" -y > /dev/null
id=$(machine "$NAME")
if [ -z "$id" ]; then
fly machine run "$image" -a "$a" -r "$REGION" --vm-size "$SIZE" -v home:/home/raea -n box \
-p 443:8080/tcp:tls:http -p 80:8080/tcp:http --autostart --autostop=off --restart on-failure --detach > /dev/null
# a Machine made by run takes the app's secrets as it's made; from then on the box reads its settings from
# ~/.raea-cloud.env on its volume (start.sh)
fly secrets deploy -a "$a" > /dev/null 2>&1 || true
elif [ "$(fly machines list -a "$a" --json 2> /dev/null | python3 -c 'import json, sys; print(json.load(sys.stdin)[0]["config"]["image"].split("@")[0])')" != "${image%@*}" ]; then
# a new image: the Machine made again from it (it restarts; its volume stays). Only then: a restart cut off a
# home's upload that had started after the health check passed on the instance before it (12-03, raea-3, 5, 11)
fly machine update "$id" -a "$a" --image "$image" --vm-size "$SIZE" --autostart --autostop=off --restart on-failure -y > /dev/null
fly machine wait "$id" -a "$a" --state started --wait-timeout 120 > /dev/null 2>&1 || true
fi
healthy "$NAME" > /dev/null || { echo "fly box: $NAME didn't answer at $(url "$NAME")"; exit 1; }
"$0" status "$NAME"
;;
move)
need_name
# the Sprite's settings, its token among them, so raea cloud only changes the box's address
. "$(dirname "$0")/../sprites/org.sh"
f=$(envfile "$NAME")
mkdir -p "$CONF/boxes" && chmod 700 "$CONF/boxes"
(umask 077; sprite exec -o "$ORG" -s "$NAME" -- cat /home/sprite/.raea-cloud.env > "$f")
grep -q '^RAEA_CLOUD_TOKEN=' "$f" || { echo "fly box: couldn't read $NAME's settings from its Sprite"; exit 1; }
ORG=$(sed -n 's/^RAEA_FLY_ORG=//p' "$FLY_CONF" | tail -1) "$0" up "$NAME"
# its home folder, but for caches anything can make again: agents' sign-ins, their sessions, ~/work. Sent by the
# Sprite itself straight to the new box's file API (it streams to disk), never through this Mac (12-03: through
# sprite exec it came at about 4 MB/s), then unpacked there
a=$(app "$NAME")
# a home that arrived whole in a try before this one is unpacked, not sent again (a .part is only part of one)
healthy "$NAME" > /dev/null || true
if fly ssh console -a "$a" -q -C "test -s /home/raea/work/.move/home.tar.zst" > /dev/null 2>&1; then
echo "fly box: $NAME's home arrived in a try before this one: unpacking it"
else
fly ssh console -a "$a" -q -C "rm -rf /home/raea/work/.move" > /dev/null 2>&1 || true
echo "fly box: sending $NAME's home from its Sprite to $(url "$NAME")"
# --no-stdin: a dropped link to the Sprite reconnects to the same session (12-03: all four copies lost theirs at
# once, 6 minutes in, and with stdin attached sprite exec refuses to reconnect)
sprite exec --no-stdin -o "$ORG" -s "$NAME" -- bash -c ". ~/.raea-cloud.env && tar -C /home/sprite --exclude=./.cache --exclude=./.npm --exclude=./.raea-cloud.env --exclude=./work/.move -cf - . | zstd -q -T0 -3 | curl -fsS --retry 0 -T - -H \"authorization: Bearer \$RAEA_CLOUD_TOKEN\" '$(url "$NAME")/v1/files?path=.move/home.tar.zst' && echo SENT-WHOLE" > "$CONF/boxes/$NAME.move.log" 2>&1 &
sending=$!
# what has arrived, every 15 s; nothing more in MOVE_STILL_S (2 minutes) and the copy is stopped there, never waited
# out (12-03, Shane: fail fast at every step)
tok=$(sed -n 's/^RAEA_CLOUD_TOKEN=//p' "$f" | tail -1)
got=-1 since=$SECONDS
while kill -0 "$sending" 2> /dev/null; do
n=$(curl -s -m 20 -H "authorization: Bearer $tok" "$(url "$NAME")/v1/files?path=.move" | python3 -c 'import json, sys
try: print(sum(d.get("bytes") or 0 for d in json.load(sys.stdin)))
except Exception: print(-1)')
if [ "${n:--1}" -gt "$got" ]; then
echo "fly box: $NAME: $((n / 1048576)) MB arrived"
got=$n since=$SECONDS
elif [ $((SECONDS - since)) -ge "${MOVE_STILL_S:-120}" ]; then
kill "$sending" 2> /dev/null
echo "fly box: $NAME's upload stopped growing at $((got / 1048576)) MB for $((SECONDS - since)) s: stopped; run move again"
exit 1
fi
sleep 15
done
wait "$sending"
grep -v 'bind: warning' "$CONF/boxes/$NAME.move.log"
grep -q SENT-WHOLE "$CONF/boxes/$NAME.move.log" || { echo "fly box: $NAME's home didn't arrive whole (above); nothing unpacked, run move again"; exit 1; }
fi
# unpacked there, saying so every 500 MB (a silent unpack of 26 GB looked stalled: 12-03, raea-4 and raea-6)
# run from inside the work folder, which the box's idle stop sees as work going on (server/idle.ts); the box woken
# first, as fly ssh doesn't start a stopped Machine
healthy "$NAME" > /dev/null || true
# and the box held while it unpacks (~/.raea-hold, which its idle stop reads): its image may be older than idle.ts's
# real-path match
fly ssh console -a "$a" -q -C "sh -c '(while kill -0 \$\$ 2> /dev/null; do touch /home/raea/.raea-hold; sleep 60; done) & cd /home/raea/work/.move && zstd -dqc home.tar.zst | tar -C /home/raea -xf - --checkpoint=50000 --checkpoint-action=echo=\"fly box: $NAME: %{}T unpacked\" && cd /home/raea && rm -rf work/.move && chown -R raea:raea /home/raea && du -sh /home/raea'"
# its own settings on its disk too, as a Sprite kept them
fly ssh console -a "$a" -q -C "sh -c 'umask 077; cat > /home/raea/.raea-cloud.env && chown raea:raea /home/raea/.raea-cloud.env'" < "$f"
# RAEA_BOX_REGISTER=0: copied, but raea cloud still sends work to the Sprite until deploy/fly/box.sh register NAME
if [ "${RAEA_BOX_REGISTER:-1}" = 0 ]; then echo "fly box: $NAME copied; not registered yet"; else "$0" register "$NAME"; fi
;;
register)
need_name
api=${RAEA_CLOUD_API:-https://api.raea.cloud}
key=${RAEA_CLOUD_ADMIN_KEY:-$(security find-generic-password -s raea-cloud-prod-staff-key -w 2> /dev/null || true)}
[ -n "$key" ] || { echo "fly box: no staff key (RAEA_CLOUD_ADMIN_KEY, or raea-cloud-prod-staff-key in the keychain)"; exit 2; }
tok=$(sed -n 's/^RAEA_CLOUD_TOKEN=//p' "$(envfile "$NAME")")
body=$(python3 -c 'import json,sys; print(json.dumps({"name": sys.argv[1], "url": sys.argv[2], "token": sys.argv[3], "first": sys.argv[4] == "1"}))' "$NAME" "$(url "$NAME")" "$tok" "${RAEA_BOX_FIRST:-0}")
curl -fsS -X POST -H "authorization: Bearer $key" -H 'content-type: application/json' --data-binary @- "$api/v1/admin/boxes" <<< "$body" > /dev/null || { echo "fly box: raea cloud refused $NAME"; exit 1; }
echo "fly box: $NAME is listed in raea cloud at $(url "$NAME")"
;;
status)
need_name
echo "$(url "$NAME") machine $(machine "$NAME")"
t=$(sed -n 's/^RAEA_CLOUD_TOKEN=//p' "$(envfile "$NAME")")
curl -fsS -m 60 -H "authorization: Bearer $t" "$(url "$NAME")/v1/health" | head -c 600
echo
;;
token) need_name; sed -n 's/^RAEA_CLOUD_TOKEN=//p' "$(envfile "$NAME")" ;;
list) exec "$(dirname "$0")/../sprites/box.sh" list ;;
latest)
version=${2:-$(newest)}
[ -n "$version" ] || { echo "fly box: couldn't read raea's newest release (gh signed in?)"; exit 2; }
linux=raea-$version-linux-x86_64.tar.gz
gh release view "v$version" -R "$REPO" --json assets -q '.assets[].name' 2> /dev/null | grep -qx "$linux" || { echo "fly box: v$version has no $linux yet: no box changed"; exit 1; }
ref=$(gh api "repos/$REPO/commits/v$version" -q .sha) || { echo "fly box: couldn't read v$version's commit"; exit 1; }
RAEA_CLOUD_REF=$ref "$0" image "$version" > /dev/null
names=$("$0" list | sed 's/^[* ] *//' | awk '{print $1}' | grep '^raea-' || true)
failed=""
for b in $names; do
[ -s "$(envfile "$b")" ] || { echo "fly box: $b isn't a Fly box here (no $(envfile "$b")): passed over"; continue; }
echo "fly box: $b onto raea $version (${ref:0:10})"
"$0" up "$b" > /dev/null || failed+=" $b"
done
[ -z "$failed" ] || { echo "fly box: not on $version:$failed"; exit 1; }
echo "fly box: every Fly box is on raea $version"
;;
key)
need_name
if [ -t 0 ]; then k=$(pbpaste); else k=$(cat); fi
k=$(printf %s "$k" | tr -d '[:space:]')
case "$k" in raea_ak_*) ;; *) echo "fly box: that isn't a raea agent key (raea_ak_...)"; exit 2 ;; esac
f=$(envfile "$NAME")
(umask 077; { grep -v '^RAEA_AGENT_KEY=' "$f" || true; echo "RAEA_AGENT_KEY=$k"; } > "$f.new" && mv "$f.new" "$f")
printf 'RAEA_AGENT_KEY=%s\n' "$k" | fly secrets import -a "$(app "$NAME")" > /dev/null && echo "fly box: agent key on $NAME, its Machine restarted"
;;
sh)
need_name
if [ -n "${3:-}" ]; then fly ssh console -a "$(app "$NAME")" -q -C "$3"; else fly ssh console -a "$(app "$NAME")"; fi
;;
*)
sed -n '2,25p' "$0"
exit 2
;;
esac
-7
View File
@@ -1,7 +0,0 @@
# The app whose registry holds the box image (deploy/fly/box.sh image): it runs no machines of its own. Each box is an
# app of its own (raea-box-2, ...) whose one Machine runs this image with its volume.
app = "raea-box-image"
primary_region = "iad"
[build]
dockerfile = "Dockerfile"
-43
View File
@@ -1,43 +0,0 @@
#!/bin/bash
# A Fly box's start, as root: the volume made the box's home, the box's own settings read from it, then the image's
# entrypoint (image/entrypoint.sh), which goes on as raea and runs the server. The server exits 0 when the box has been
# idle RAEA_CLOUD_IDLE_STOP_MIN minutes (server/idle.ts), and with the Machine's restart policy on-failure it then stays
# stopped until Fly's proxy starts it for the next request.
set -uo pipefail
H=/home/raea
# the box's name: RAEA_BOX, else the app's (raea-box-2 is the box raea-2)
BOX=${RAEA_BOX:-${FLY_APP_NAME:-box}}
BOX=${BOX/raea-box-/raea-}
mkdir -p "$H/work"
[ "$(stat -c %u "$H")" = 1000 ] || chown -R raea:raea "$H"
[ "$(stat -c %u "$H/work")" = 1000 ] || chown raea:raea "$H/work"
# footage is read 16 MB ahead (setup.sh's 12-01 measure on a Sprite; a volume gains the same on long reads)
for b in /sys/block/*/queue/read_ahead_kb; do echo 16384 > "$b" 2> /dev/null || true; done
# the box's own token, the farm's address and key, the agent key and raea cloud's address: kept on the volume, as a
# Sprite kept them (box.sh writes it; a box moved from a Sprite brings its own). Fly secrets, when set, come first.
if [ -s "$H/.raea-cloud.env" ]; then
while IFS='=' read -r k v; do
[[ "$k" =~ ^[A-Z_][A-Z0-9_]*$ ]] || continue
[ -n "${!k:-}" ] || export "$k=$v"
done < "$H/.raea-cloud.env"
fi
: "${RAEA_CLOUD_TOKEN:?the box has no RAEA_CLOUD_TOKEN: a Fly secret, or a line of ~/.raea-cloud.env}"
# what the box runs with, written back to its disk: raea cloud's fleet makes a new box from a healthy one by reading it
(umask 077; for k in RAEA_CLOUD_TOKEN RAEA_AGENT_KEY RAEA_API RAEA_CLOUD_GPU_URL RAEA_CLOUD_GPU_TOKEN; do
[ -n "${!k:-}" ] && echo "$k=${!k}"
done > "$H/.raea-cloud.env.new" && mv "$H/.raea-cloud.env.new" "$H/.raea-cloud.env" && chown 1000:1000 "$H/.raea-cloud.env")
# the work folder by the path raea cloud names it on every box (/home/sprite is /home/raea: the image links it), so
# the folders and paths of projects made on a Sprite are the same here
export RAEA_CLOUD_WORK=/home/sprite/work
# the box's commits say which box made them
[ -s "$H/.gitconfig" ] || {
sudo -u raea HOME=$H git config --global user.name "raea cloud $BOX"
sudo -u raea HOME=$H git config --global user.email "$BOX@box.raea.io"
sudo -u raea HOME=$H git config --global init.defaultBranch main
}
python3 - "$BOX" << 'PY'
import json, sys
p = "/opt/raea-cloud/BUILD.json"
b = json.load(open(p)); b["box"] = sys.argv[1]; json.dump(b, open(p, "w"))
PY
exec /opt/raea-cloud/image/entrypoint.sh
+11 -95
View File
@@ -148,20 +148,8 @@ image = (
# a test farm's own raea (deploy/modal/build.py: an engine change built into the volume, timed here before a release
# carries it): RAEA_FARM_BUILD=NAME at the deploy. The live farm has none, and runs the release above
.env({"RAEA_FARM_BUILD": os.environ.get("RAEA_FARM_BUILD", "")})
.add_local_python_source("farm_plan", "farm_media", "prices", "farm_scene", "farm_keys", "farm_proxy")
)
# raea's SDK files the box image overlays on the release (image/sdk-overlay, deploy/fly/Dockerfile), here too: the farm
# bundles each composition it's sent with its own SDK, so the box's zone-aware <Region> never reached a render (12-05,
# run 17: titles through <Title> still landed at y=154, inside the app's top 220 px). Only while the release lacks them
OVERLAY = os.path.join(CLOUD, "image", "sdk-overlay")
if os.path.isdir(os.path.join(OVERLAY, "video")):
image = image.add_local_dir(OVERLAY, "/opt/sdk-overlay", copy=True).run_commands(
"set -e; S=/opt/raea/share/raea/sdk; O=/opt/sdk-overlay; if [ ! -f $S/video/src/zones.ts ]; then "
"cp $O/video/src/captions.tsx $O/video/src/index.ts $O/video/src/region.tsx $O/video/src/zones.ts "
"$O/video/src/registry.tsx $S/video/src/ && cp $O/video/package.json $S/video/package.json && "
"cp $O/raea/src/index.tsx $S/raea/src/index.tsx && echo 'overlay: zones'; fi"
)
# last: files added without copy (these) can't be followed by a build step
image = image.add_local_python_source("farm_plan", "farm_media", "prices", "farm_scene", "farm_keys", "farm_proxy")
app = modal.App(os.environ.get("RAEA_FARM_APP", "raea-farm"), image=image)
vol = modal.Volume.from_name("raea-farm", create_if_missing=True, version=2)
@@ -185,11 +173,7 @@ CPU_ENV = {"VK_DRIVER_FILES": "/usr/share/vulkan/icd.d/lvp_icd.json", "__EGL_VEN
# NVIDIA's shader cache and Cycles' kernels on the farm's volume, so a GPU's start reuses what an earlier one compiled
CACHES = {"__GL_SHADER_DISK_CACHE": "1", "__GL_SHADER_DISK_CACHE_PATH": f"{ROOT}/cache/nvidia", "__GL_SHADER_DISK_CACHE_SKIP_CLEANUP": "1",
"__GL_SHADER_DISK_CACHE_SIZE": str(4 << 30), "XDG_CACHE_HOME": f"{ROOT}/cache/xdg",
# but a composition's bundle on this container's own disk (12-05, Dutch run 6: a job's 32 parts each missed the
# shared cache at once, wrote the same file and committed it, and parts that read it mid-commit got zeros:
# "bundle.js: String contained internal null bytes", up to 23 of a cut's 32 parts sent back to the 10 GPUs)
"RAEA_BUNDLE_CACHE": "/tmp/raea-bundles"}
"__GL_SHADER_DISK_CACHE_SIZE": str(4 << 30), "XDG_CACHE_HOME": f"{ROOT}/cache/xdg"}
# the scene reader's models, loaded once a container (/v1/scene)
@@ -213,7 +197,7 @@ def life():
def run(cmd, cwd=None, env=None, timeout=6 * 3600):
t = time.time()
for d in (CACHES["__GL_SHADER_DISK_CACHE_PATH"], CACHES["XDG_CACHE_HOME"], CACHES["RAEA_BUNDLE_CACHE"]):
for d in (CACHES["__GL_SHADER_DISK_CACHE_PATH"], CACHES["XDG_CACHE_HOME"]):
os.makedirs(d, exist_ok=True)
build = os.environ.get("RAEA_FARM_BUILD")
if build and cmd[0] == "raea":
@@ -263,10 +247,8 @@ class Log:
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. 180 since
# 12-03: an agent renders all its cuts at once, then each one its fix touched a minute or two later, and every one of
# those started cold at 60 (Shane: "no workflow should take more than 20 minutes")
CPU_SCALEDOWN = 180
# 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):
@@ -354,43 +336,12 @@ def raea_proxy(src: str, dest: str, w: int, h: int, matrix: str) -> dict:
return {"code": code, "out": out[-1000:], "s": s}
def stills_run(args, frames, first, work, env, seg, man):
"""A video run drawn as stills and encoded: the run's frames from `first` (its warm-up ones dropped) at the piece's
rate (its manifest's, else 30)"""
import farm_plan
tmp = f"/tmp/{uuid.uuid4().hex}"
code, out, s = run(["raea", *args, "--at", ",".join(map(str, frames)), "-o", tmp, "--manifest", man], cwd=work, env=env)
made = sorted(n for n in os.listdir(tmp) if re.fullmatch(r"frame-\d+\.png", n)) if os.path.isdir(tmp) else []
if code or len(made) != len(frames):
return code or 1, out + f"\n{len(made)} of {len(frames)} stills drawn", s
kept = f"{tmp}/kept"
os.makedirs(kept)
n = 0
for i, name in enumerate(made):
if frames[i] >= first:
os.replace(os.path.join(tmp, name), f"{kept}/frame-{n:05d}.png")
n += 1
try:
fps = float(json.load(open(man)).get("fps") or 30)
except Exception:
fps = 30.0
c, o, _ = farm_plan.encode(kept, seg, fps, None, run, start=0, frames=n)
shutil.rmtree(tmp, ignore_errors=True)
return c, out + o, s
def raea_frames(id, args, frames=None, first=0, probe=False, video=False, env=None):
vol.reload()
work = f"{JOBS}/{id}/work"
if probe:
code, out, s = run(["raea", *args, "--frame", "0", "-o", "/tmp/probe.png", "--manifest", "/tmp/probe.json"], cwd=work, env=env)
m = json.load(open("/tmp/probe.json")) if os.path.exists("/tmp/probe.json") else {}
# what frame 0 brought up to date in the work folder (styles.gen.ts, written by raea when it's older than the
# code), for the parts after it: uncommitted, every part's container rewrote it on the volume at once, truncating
# it under the others, and 14 of a Dutch cut's parts refused with "couldn't bundle edit.tsx: Unterminated
# string" (12-05, run 19: the cut was lost)
vol.commit()
return {"code": code, "out": out[-3000:], "s": s, "length": m.get("length"), "fps": m.get("fps"), "w": m.get("width"), "h": m.get("height"), "kind": kind(), "manifest": m, **life()}
if frames is None:
code, out, s = run(["raea", *args], cwd=work)
@@ -405,11 +356,6 @@ def raea_frames(id, args, frames=None, first=0, probe=False, video=False, env=No
# (farm_plan.joined), so a cut's whole edit comes back, not frame 0's alone (11-29, Dutch)
man = f"/tmp/run-{first:05d}.json"
code, out, s = run(["raea", *args, "--at", ",".join(map(str, frames)), "-o", seg, "--manifest", man], cwd=work, env={**(env or {}), "RAEA_TIMES": "1"})
# a piece whose --at draws only stills (a game's, 12-05: "/tmp/run-00024.mp4: The file extension .mp4 was not
# recognized as an image format" on every run, and a playable's capture never came back): its frames as stills,
# encoded here into the run's H.264 part, as a Blender run's are
if code and "not recognized as an image format" in out:
code, out, s = stills_run(args, frames, first, work, env, seg, man)
if os.path.exists(seg):
shutil.move(seg, f"{dest}/run-{first:05d}.mp4")
vol.commit()
@@ -626,22 +572,15 @@ def api():
# (POST jobs: 500) whenever two agents rendered together. So requests that touch the volume share it, and a
# reload waits until none of them is in it.
class Gate:
# 12-04 (one-check proof, 12 cuts in flight): blob uploads and other requests kept the volume in use without a
# break, a reload waited for none of them to be in it, and GET out sat behind it past Modal's 150 s web limit:
# 408, and Elfster's finished cut was lost. So a waiting reload holds new users back (it goes next), a reload
# that starts after a request asked for one serves that request too, and a wait has a limit (a 503, asked again)
def __init__(self):
self.users = 0
self.reloading = False
self.waiting = 0
self.begun = 0 # reloads started
self.fresh = 0 # the latest reload that worked, by its start
self.cond = asyncio.Condition()
@contextlib.asynccontextmanager
async def use(self):
async with self.cond:
await self.cond.wait_for(lambda: not self.reloading and not self.waiting)
await self.cond.wait_for(lambda: not self.reloading)
self.users += 1
try:
yield
@@ -650,36 +589,17 @@ def api():
self.users -= 1
self.cond.notify_all()
async def reload(self, wait: bool = True, within: "float | None" = None) -> bool:
"""the volume as other containers committed it; with wait=False skipped (False) while the volume is in use,
and False when `within` seconds pass first"""
async def reload(self, wait: bool = True) -> bool:
"""the volume as other containers committed it; with wait=False skipped (False) while the volume is in use"""
async with self.cond:
if not wait and (self.users or self.reloading or self.waiting):
if not wait and (self.users or self.reloading):
return False
want = self.begun + 1
self.waiting += 1
try:
ready = lambda: self.fresh >= want or (not self.users and not self.reloading)
if within is None:
await self.cond.wait_for(ready)
else:
await asyncio.wait_for(self.cond.wait_for(ready), within)
except asyncio.TimeoutError:
return False
finally:
self.waiting -= 1
self.cond.notify_all()
if self.fresh >= want:
return True
await self.cond.wait_for(lambda: not self.users and not self.reloading)
self.reloading = True
self.begun += 1
mine = self.begun
ok = False
try:
for pause in (0.5, 1, 2, 4, 0):
try:
await vol.reload.aio()
ok = True
return True
except Exception as e: # modal.exception.ConflictError: a file open elsewhere in this container
if not pause:
@@ -690,17 +610,13 @@ def api():
finally:
async with self.cond:
self.reloading = False
if ok:
self.fresh = mine
self.cond.notify_all()
gate = Gate()
# under Modal's 150 s web request limit, past which the request is lost (408) and a box can't ask again
RELOAD_WAIT_S = 100
async def reloaded():
"""the coordinator's commits seen here, or a 503 the box tries again on (the job is still all here)"""
if not await gate.reload(within=RELOAD_WAIT_S):
if not await gate.reload():
raise HTTPException(503, "the farm's volume is busy: try again")
def check(req: Request):
+5 -119
View File
@@ -94,19 +94,6 @@ PARTS = 4
# another: 2 parts each. At 4 an 894-frame ad went out as 32 parts of 28 frames, each paying about 5 s to start
# (raea, the composition, each clip read on from its last keyframe) for 10 s of frames (11-30)
CPU_PARTS = 2
# A video with no 3D (its keys say so) is planned for the time it takes, not the containers' seconds (12-03, Shane: "no
# workflow should take more than 20 minutes"): its runs go out at once, with no timed first run before them (that run
# and its wait were 15-25 s of every render), each run at least FLAT_PART frames, on as many containers as the job may
# have. A 1080x1920 ad cut drew 0.46-0.69 s a frame on a container with no GPU (11-30, 12-03), which FLAT_FRAME_S plans
# the bill by.
FLAT_PART = 24
FLAT_FRAME_S = 0.6
# a run still out once this share of a job's runs are in, and after HEDGE_AFTER times the slowest finished one (or
# HEDGE_MIN_S more than it), is sent again to another container, and the first answer is kept (12-03: one of 21 runs took
# 81 s where the others took 11-15, and the whole render waited on it)
HEDGE_SHARE = 0.7
HEDGE_AFTER = 1.5
HEDGE_MIN_S = 8.0
# a video part's start is never planned at less than this (s): the timed run's own start is measured on a warm
# container with the clips' first frames, and came out at 2.8-3.6 s where the parts after it paid about 5
PART_START = 5.0
@@ -267,81 +254,6 @@ def spread(fn, kind, calls, log, what, bill=None, most=None, got=None, again=Non
return code
def _ready(h):
"""a spawned run's answer, the exception it raised, or None while it's still running"""
try:
return h.get(timeout=0)
except Exception as e:
# Modal's "not yet" is a TimeoutError; its FunctionTimeoutError (the run ran out of time) is the run's answer
if isinstance(e, TimeoutError) and type(e).__name__ != "FunctionTimeoutError":
return None
return e
def hedged(fn, kind, calls, log, what, bill=None, most=None, got=None, again=None, clock=time.time, pause=None, wait_s=0.5):
"""`calls` on `fn` as spread() runs them, each spawned at once (at most `most` containers), and a run still out
once HEDGE_SHARE of them are in and it has taken HEDGE_AFTER times the slowest finished one (HEDGE_MIN_S more at
least) sent once more: the first answer of the two is kept and the other cancelled. A run draws the same frames
to the same files wherever it runs, so either answer is the run's."""
if not calls:
return 0
pause = pause or time.sleep
if most and len(calls) > most:
fn = fn.with_options(max_containers=most)
code = 0
t0 = clock()
out = {c[3]: {"call": c, "h": [fn.spawn(*c)], "at": t0, "again": False} for c in calls}
took = []
while out:
for first in list(out):
o = out[first]
r = None
for h in o["h"]:
r = _ready(h)
if r is not None:
break
if r is None:
continue
for h in o["h"]:
try:
h.cancel()
except Exception:
pass
del out[first]
took.append(clock() - o["at"])
if isinstance(r, Exception):
log(f"raea farm: a run failed{' without a GPU' if again is not None else ''}: {r!r}"[:600], err=again is None)
if again is not None:
again.append(o["call"])
else:
code = code or 1
continue
if bill:
bill.add(r)
if again is not None and (r["code"] or (r.get("manifest") or {}).get("has3d")):
why = "it drew 3D" if not r["code"] else f"exit {r['code']}: " + " | ".join((r.get("out") or "").strip().splitlines()[-3:])
log(f"raea farm: frames from {r.get('first')} didn't draw without a GPU ({why})"[:600])
again.append(o["call"])
continue
if got is not None:
got.append(r)
log(f"raea farm: {r.get('frames')} {what} on a {r.get('kind') or kind} in {r['s']:.1f} s")
if r["code"]:
log(r["out"], err=True)
code = code or r["code"]
if not out:
break
if took and len(calls) - len(out) >= HEDGE_SHARE * len(calls):
slow = max(took)
for first, o in out.items():
if not o["again"] and clock() - o["at"] > max(slow * HEDGE_AFTER, slow + HEDGE_MIN_S):
o["again"] = True
o["h"].append(fn.spawn(*o["call"]))
log(f"raea farm: frames from {first} still out after {clock() - o['at']:.0f} s (the others took {slow:.0f} s at most): sent again, the first answer kept")
pause(wait_s)
return code
def timed(r, n):
"""A timed run's (seconds a frame, seconds to start): the frame from raea's own clocks over the whole frame (React,
the page, the clips read, the draw, the encode: farm.py's work_ms) when the run says them, else from its "N ms a
@@ -412,10 +324,6 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
nv = bool((p.get("manifest") or {}).get("has3d"))
flat = bool(video and cpu_render and not opts.get("gpu") and (p.get("manifest") or {}).get("has3d") is False)
r0 = None
# a flat video whose keys said so goes out at once: no timed first run (FLAT_PART)
quick = bool(flat and p.get("keys"))
if quick:
n0 = 0
first = list(range(at0, at0 + n0))
if flat and n0:
r0 = bill.add(waited(cpu_render, log, id, rest, first, at0, video=video))
@@ -436,22 +344,17 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
if r0 and r0["code"]:
log(r0["out"], err=True)
return r0["code"]
frame_s, start_s = timed(r0, n0) if r0 else ((FLAT_FRAME_S, PART_START) if quick else (0.0, 0.0))
frame_s, start_s = timed(r0, n0) if r0 else (0.0, 0.0)
left = todo - n0
# a container beyond the first starts cold: frame 0's whole time, less its one frame (the first is warm by now)
cold_s = start_s if flat else max(start_s, p["s"] - frame_s)
if quick:
k, m = (max(1, min(most, -(-left // FLAT_PART))) if left else 0), 1
else:
k = gpus_for(left, frame_s, cold_s, most)
m = parts_per_gpu(left, k, frame_s, max(start_s, PART_START) if video else start_s, CPU_PARTS if flat else PARTS)
k = gpus_for(left, frame_s, cold_s, most)
m = parts_per_gpu(left, k, frame_s, max(start_s, PART_START) if video else start_s, CPU_PARTS if flat else PARTS)
cost = price(gpu_kind, p["s"]) + price(kind, (r0["s"] if r0 else 0) + k * m * start_s + (k - 1) * (cold_s - start_s) + left * frame_s, busy=(r0 or {}).get("cores") or 0)
parts = f" in {k * m} parts" if m > 1 else ""
on = f"{k} {kind}s" if not flat else f"{k} containers with no GPU (no 3D in it)"
if r0:
log(f"raea farm: {frame_s * 1000:.0f} ms a frame, {start_s:.1f} s to start; {left} frames left on {on}{parts}, about ${cost:.3f} in all")
elif quick and left:
log(f"raea farm: {left} frames on {on}, all at once, about ${cost:.3f} in all")
else:
log("raea farm: nothing to draw: every frame is in a run kept from an earlier render")
if opts.get("max_usd") is not None and cost > opts["max_usd"]:
@@ -462,38 +365,24 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
got = [r0] if r0 else []
calls = [(id, rest, f, at, False, video, *([True] if nv and not flat else [])) for a, b, share in farm_keys.spans(gaps, n0, k * m) for f, at in runs(a, b, share, warm)] if left else []
again = [] if flat else None
code = (hedged if quick else spread)(render, kind, calls, log, "frames", bill, k, got, again) if calls else 0
code = spread(render, kind, calls, log, "frames", bill, k, got, again) if calls else 0
if again:
# what a container with no GPU couldn't draw, or drew 3D in (on a software rasteriser): a GPU draws it again
log(f"raea farm: {len(again)} of {len(calls)} runs go to a GPU (they failed without one, or have 3D in them)")
code = spread(gpu_render, gpu_kind, again, log, "frames", bill, opts["gpus"], got)
if code:
return code
# each step from here says how long it took when it took a second or more (12-03: a render whose every frame was
# kept still took 64 s between "nothing to draw" and "joined", and nothing said where; Shane: fail fast at every step)
def took(what, t0):
if time.time() - t0 >= 1:
log(f"raea farm: {what} took {time.time() - t0:.1f} s")
# the sound's run finished first: its open files in the job's folder refuse the reload that brings the other
# containers' frames (11-25: "the volume wouldn't reload ... cwd of raea render")
if video:
t0 = time.time()
t.join()
took("the sound", t0)
t0 = time.time()
reload() # the other containers' frames
took("reloading the volume", t0)
frames = f"{os.path.dirname(work)}/frames"
dest = os.path.join(work, out)
# (a run that drew 3D after all isn't kept: its frames can hang on the frames before them)
if store and not any((r.get("manifest") or {}).get("has3d") for r in got):
t0 = time.time()
farm_keys.put(store, keyed["keys"], got, frames)
took("keeping the runs drawn", t0)
t0 = time.time()
got += farm_keys.take(hits, frames)
took(f"bringing {len(hits)} kept runs", t0)
if manifest and p.get("manifest"):
path = os.path.join(work, manifest)
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
@@ -540,10 +429,7 @@ def joined(probe, parts):
pieces = sorted((c for s in snd for c in s.get("clips") or []), key=lambda c: (c.get("from", 0), str(c.get("key"))))
clips = []
for c in pieces:
# the same source carried on across a run's seam, whatever its React key: each run numbers its nodes its own
# way (12-04, StreetTalk round 22: Body Shop's clips came back keyed n3 and n11 by turns, split at frames 60,
# 420, 720 and 807, and the sound check called each seam a cut inside a word)
prev = next((p for p in reversed(clips) if p.get("src") == c.get("src") and p.get("to") == c.get("from")), None)
prev = next((p for p in reversed(clips) if p.get("key") == c.get("key") and p.get("src") == c.get("src") and p.get("to") == c.get("from")), None)
if prev is not None and abs(prev.get("at", 0) + (prev["to"] - prev["from"]) / fps - c.get("at", 0)) < 1.5 / fps:
prev["to"] = c["to"]
if "fadeOut" in c:
+2 -5
View File
@@ -38,10 +38,7 @@ align_image = (
ALIGNS = {"en": "English", "zh": "Chinese", "yue": "Cantonese", "fr": "French", "de": "German", "it": "Italian", "ja": "Japanese", "ko": "Korean", "pt": "Portuguese", "ru": "Russian", "es": "Spanish"}
# 12-05, run 8: three projects' 8-at-once transcriptions queued on 2 of each, and Elfster's 51 takes took 6.5 minutes
# (its wait for them ran past the fetch step's 4). Hear 4 and Align 3 hold 7 of the account's 10 GPUs at a run's start,
# before its renders, which draw on CPUs and use the GPUs only for each cut's first frame
@app.cls(gpu="L4", image=align_image, volumes={"/models": models}, timeout=900, max_containers=3, scaledown_window=60)
@app.cls(gpu="L4", image=align_image, volumes={"/models": models}, timeout=900, max_containers=2, scaledown_window=60)
class Align:
@modal.enter()
def load(self):
@@ -83,7 +80,7 @@ def aligned(heard: list, got: list) -> "list | None":
FULL_S = 180
@app.cls(gpu="T4", image=image, volumes={"/models": models}, timeout=900, max_containers=4, scaledown_window=60)
@app.cls(gpu="T4", image=image, volumes={"/models": models}, timeout=900, max_containers=2, scaledown_window=60)
class Hear:
@modal.enter()
def load(self):
@@ -1,312 +0,0 @@
// The rule packs (MK29, MK38; Rust's goal gates until 11-29, now here alone): any goal held to its rules,
// from what's on disk and what a fresh critic said, never from the agent that did the work (11-26, Shane: "it can't
// stop unless all the goals pass").
// run the command exits 0 in the brief's folder, within its timeout (300 s by default), run again each time
// says a fresh critic (`raea goal judge`) found it true of the work, after the work's last change
// (file rules are deliverables: the deliverables pack holds them)
// The critic's verdict is review/judge/NAME.json (the goal's name): {at, by, goal, rules: {ID: {pass, why}}}.
// a namespace import: raea's own runtime (engine/native/src/node.js) has spawnSync and no spawn, and a named import of
// spawn failed the whole module there, so every `raea goal check` on a box died before it read a file (12-03, raea
// 0.1.17-rc4: no StreetTalk cut could publish)
import * as cp from "node:child_process"
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"
import path from "node:path"
import { check, found } from "raea/check"
import { type Contract, nameOf, type Said, saysOf } from "../contract.ts"
import type { Job } from "../facts.ts"
import { RAEA } from "../media.ts"
/** where a goal's critic verdict is kept, relative to the brief */
export const verdictPath = (g: Contract) => `review/judge/${nameOf(g)}.json`
export const TIMEOUT = 300
/** folders that aren't the work: what the job writes about itself, and what tools keep */
const NOT_WORK = new Set(["review", ".git", "node_modules", ".raea", "target", ".cache", ".raea-cloud"])
/** what a check keeps beside a file it read (its report, its words, its scene): a reading of the work, not a change
* to it. A done check that heard a cut's words wrote them beside it, and the critic's verdict of a minute before read
* as older than the work (12-01) */
const READING = /\.(check|words|scene|floor|montage)\.json$/
/** when the work last changed (ms): the newest file under dir, its own bookkeeping left out (a bounded walk) */
export function newest(dir: string): number | null {
let best: number | null = null
const stack = [dir]
let seen = 0
while (stack.length) {
const d = stack.pop()!
let names: string[] = []
try {
names = readdirSync(d)
} catch {
continue
}
for (const name of names) {
if (++seen > 20_000) return best
const p = path.join(d, name)
let st
try {
st = statSync(p)
} catch {
continue
}
if (st.isDirectory()) {
if (!(d === dir && NOT_WORK.has(name)) && name !== "node_modules" && name !== ".git") stack.push(p)
} else if (st.isFile() && name !== "NOTES.md" && !READING.test(name)) best = Math.max(best ?? 0, st.mtimeMs)
}
}
return best
}
type Verdict = { at: number; by: string; goal?: string; rules: Record<string, { pass: boolean; why: string } | undefined> }
export function verdict(dir: string, g: Contract): Verdict | null {
try {
return JSON.parse(readFileSync(path.join(dir, verdictPath(g)), "utf8")) as Verdict
} catch {
return null
}
}
const goalOf = (j: Job): Contract | null => j.contract
export const runPack = check<Job>({ id: "run", text: "each command rule exits 0", over: "job", at: ["done"] }, async (j) => {
for (const r of goalOf(j)?.rules ?? []) {
if (!r.run) continue
const { ok, said } = await j.run(r.run, r.timeout ?? TIMEOUT)
if (!ok) found({ says: `${r.id}: \`${r.run}\` ${said}`, about: [r.id] })
}
})
export const saysPack = check<Job>({ id: "says", text: "each `says` rule found true by a fresh critic after the work's last change", over: "job", at: ["done"] }, async (j) => {
const says = saysOf(goalOf(j) ?? null)
if (!says.length) return
let v = verdict(j.root, j.contract!)
// at whole seconds, as the verdict keeps its time: work saved in the second the critic was asked counts as judged
const freshOf = (x: Verdict | null) => !!x && (newest(j.root) === null || x.at >= Math.floor(newest(j.root)! / 1000))
// a verdict missing, stale or short of a rule is asked for here (the check is the one command; the agent never
// judges by hand), where this session has a critic to ask
if (!(freshOf(v) && says.every((r) => v!.rules?.[r.id])) && hasCritic(j.root, says)) {
try {
v = await judge(j.contract!, j.root)
} catch (e) {
found({ says: `the critic couldn't judge: ${(e as Error).message}` })
return
}
}
const fresh = freshOf(v)
for (const r of says) {
const one = v?.rules?.[r.id]
const fix = NO_CRITIC
if (!v) found({ says: `${r.id}: not judged yet`, about: [r.id], fix })
else if (!one) found({ says: `${r.id}: the last judging didn't cover it`, about: [r.id], fix })
else if (!fresh) found({ says: `${r.id}: the work changed after the critic judged it`, about: [r.id], fix })
else if (!one.pass) found({ says: `${r.id}: a fresh critic found it not true yet: ${one.why}`, about: [r.id] })
}
})
/** what the critic is asked: the goal, each `says` rule by id, and the answer's shape. It reads; it changes nothing */
export function prompt(g: Contract, dir: string, only: Said[] = saysOf(g)): string {
const rules = only.map((r) => `- ${r.id}: ${r.says}`)
return `You are a fresh critic. You did none of this work and owe it nothing. The work is in ${dir}: read whatever you need there (its files, its renders, NOTES.md), and change nothing.\n\nThe goal, as the person said it: ${g.aim ?? nameOf(g)}\n\nFor each rule below, decide whether it is true of the work as it is on disk now. Count it true only when you have seen it hold; if you can't tell, it isn't true yet. Say why in one sentence, naming what you looked at.\n\n${rules.join("\n")}\n\nAnswer last with one JSON object and nothing after it: {"rules": {"ID": {"pass": true, "why": "..."}}}`
}
/** the verdict: the object around the text's last "rules" key (a critic may think aloud, or quote the shape, first) */
export function lastVerdict(text: string): Verdict | null {
const key = text.lastIndexOf('"rules"')
if (key < 0) return null
for (let open = text.lastIndexOf("{", key); open >= 0; open = text.lastIndexOf("{", open - 1)) {
let depth = 0
let inStr = false
for (let i = open; i < text.length; i++) {
const ch = text[i]
if (inStr) {
if (ch === "\\") i++
else if (ch === '"') inStr = false
continue
}
if (ch === '"') inStr = true
else if (ch === "{") depth++
else if (ch === "}" && --depth === 0) {
try {
const v = JSON.parse(text.slice(open, i + 1))
if (v && typeof v.rules === "object") return v
} catch {}
break
}
}
}
return null
}
/** where a rule is judged, chosen here and never by the agent (Shane, 12-03): a rule with a piece to watch or hear
* (a file it names, or the videos under out/) by Clef-Omni; any other by a fresh session of the agent this project
* runs on, which the host that started the agent offers as RAEA_JUDGE_URL (raea cloud's box, critic.ts; the raea app) */
const criticUrl = () => process.env.RAEA_JUDGE_URL || null
export const NO_CRITIC = "it's judged by a fresh session of the agent this project runs on, which only an agent session the raea app or raea cloud started has: it's judged when that session checks the goal"
/** whether every rule here can be judged in this session */
export function hasCritic(dir: string, rules: Said[]): boolean {
return !!criticUrl() || rules.every((r) => piecesOf(r, dir).length > 0)
}
const PIECE = /[\w@./-]+\.(?:mp4|mov|webm|m4v|png|jpe?g|webp|wav|mp3|m4a)\b/gi
const VIDEO = /\.(?:mp4|mov|webm|m4v)$/i
/** the videos under out/, newest first */
function made(dir: string): string[] {
const out: { f: string; at: number }[] = []
const walk = (d: string) => {
for (const e of existsSync(d) ? readdirSync(d, { withFileTypes: true }) : []) {
const f = path.join(d, e.name)
if (e.isDirectory()) walk(f)
else if (VIDEO.test(e.name)) out.push({ f, at: statSync(f).mtimeMs })
}
}
walk(path.join(dir, "out"))
return out.sort((x, y) => y.at - x.at).map((x) => path.relative(dir, x.f))
}
/** clef-omni as the critic (`raea ask`, paid as ask is): it watches and hears a piece, and reads no folder. A rule is
* asked of the files it names, in its "from A s to B s" window if it has one, else of every video under out/ (the
* newest CLEF_PIECES), and passes when it's true of each; the rules about one piece go in one call */
const CLEF_PIECES = 12
/** the pieces a rule is about: the files it names that are on disk, else the newest videos under out/ */
function piecesOf(r: Said, dir: string): string[] {
const named = [...new Set(r.says.match(PIECE) ?? [])].filter((f) => existsSync(path.join(dir, f)))
return named.length ? named : made(dir).slice(0, CLEF_PIECES)
}
/** how many `raea ask`s run at once: each is one cut (or one stretch of it) heard and watched; one after another, a
* project's beats took 6-17 minutes of every goal check (12-03, StreetTalk: 18 of them, a cut's beats each a stretch) */
export const CLEF_AT_ONCE = 6
/** `f` on each item, at most `n` at once, the answers in the items' order */
async function pool<T, R>(items: T[], n: number, f: (t: T) => Promise<R>): Promise<R[]> {
const out: R[] = new Array(items.length)
let next = 0
const worker = async () => {
for (let i = next++; i < items.length; i = next++) out[i] = await f(items[i])
}
await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker))
return out
}
export async function clefVerdict(g: Contract, dir: string, ask: Ask = askClef, only: Said[] = saysOf(g)): Promise<Verdict["rules"]> {
const groups = new Map<string, { file: string; from?: string; to?: string; rules: Said[] }>()
const pieces = new Map<string, string[]>()
for (const r of only) {
const files = piecesOf(r, dir)
const w = /from (\d+(?:\.\d+)?) s to (?:(\d+(?:\.\d+)?) s|its end)/.exec(r.says)
pieces.set(r.id, files)
for (const file of files) {
const key = [file, w?.[1], w?.[2]].join("\u001f")
const at = groups.get(key) ?? { file, from: w?.[1], to: w?.[2], rules: [] }
at.rules.push(r)
groups.set(key, at)
}
}
const got = new Map<string, { pass: boolean; why: string }[]>()
const list = [...groups.values()]
const heard = ask === askClef && !asyncSpawn()
? askClefMany(dir, list.map((k) => ({ file: k.file, says: k.rules.map((r) => r.says), from: k.from, to: k.to })))
: await pool(list, CLEF_AT_ONCE, async (k) => ask(dir, k.file, k.rules.map((r) => r.says), k.from, k.to))
for (const [j, k] of list.entries()) {
const answers = heard[j]
k.rules.forEach((r, i) => got.set(r.id, [...(got.get(r.id) ?? []), { pass: answers[i]?.choice === "true" && !answers[i]?.problem, why: `${k.file}: ${answers[i]?.problem ?? answers[i]?.says ?? "no answer"}` }]))
}
const rules: Verdict["rules"] = {}
for (const r of only) {
const a = got.get(r.id) ?? []
const open = a.filter((x) => !x.pass)
rules[r.id] = !pieces.get(r.id)?.length
? { pass: false, why: "it names no file on disk and out/ holds no video yet, so there's nothing to watch or hear" }
: { pass: !open.length, why: (open.length ? open : a).map((x) => x.why).join("; ") }
}
return rules
}
type Answer = { choice?: string; says?: string; problem?: string | null }
type Ask = (dir: string, file: string, says: string[], from?: string, to?: string) => Answer[] | Promise<Answer[]>
const askArgs = (file: string, says: string[], from?: string, to?: string) => ["ask", file, ...says, "--choose", "true,false", "--json", ...(from ? ["--from", from] : []), ...(to ? ["--to", to] : [])]
const rowsOf = (out: string) => out.split("\n").flatMap((l) => { try { const o = JSON.parse(l); return o.answer ? [o as Answer] : [] } catch { return [] } })
/** whether this runtime has an async spawn (raea's own has only spawnSync) */
const asyncSpawn = () => typeof (cp as { spawn?: unknown }).spawn === "function"
/** every ask at once where there's no async spawn (raea's runtime): one shell runs them CLEF_AT_ONCE at a time, each
* into its own file under review/ (12-04, StreetTalk round 18: asked one after another, a stop's 18 beats took 7.7 of
* its 10.5 minutes) */
export function askClefMany(dir: string, jobs: { file: string; says: string[]; from?: string; to?: string }[]): Answer[][] {
if (!jobs.length) return []
const tmp = path.join(dir, "review", `.ask-${process.pid}-${Date.now()}`)
mkdirSync(tmp, { recursive: true })
const sq = (t: string) => `'${t.replace(/'/g, `'\\''`)}'`
const lines = jobs.map((k, i) => `${[RAEA, ...askArgs(k.file, k.says, k.from, k.to)].map(sq).join(" ")} > ${sq(`${tmp}/${i}.out`)} 2> ${sq(`${tmp}/${i}.err`)} &${(i + 1) % CLEF_AT_ONCE === 0 ? "\nwait" : ""}`)
try {
const r = cp.spawnSync("sh", ["-c", [...lines, "wait"].join("\n")], { cwd: dir, encoding: "utf8" }) as { error?: Error }
if (r.error) throw new Error(`couldn't run raea ask: ${r.error.message}`)
const read = (f: string) => (existsSync(f) ? String(readFileSync(f, "utf8")) : "")
return jobs.map((k, i) => {
const rows = rowsOf(read(`${tmp}/${i}.out`))
if (rows.length !== k.says.length) throw new Error(`raea ask answered ${rows.length} of ${k.says.length} about ${k.file}: ${read(`${tmp}/${i}.err`).trim().slice(-300) || read(`${tmp}/${i}.out`).trim().slice(-300)}`)
return rows
})
} finally {
rmSync(tmp, { recursive: true, force: true })
}
}
/** `raea ask` on one file (or a stretch of it): run as a child, so several hear at once */
function askClef(dir: string, file: string, says: string[], from?: string, to?: string): Promise<Answer[]> {
const args = askArgs(file, says, from, to)
// where there's no async spawn (raea's runtime), one at a time (clefVerdict asks them all at once: askClefMany)
if (!asyncSpawn()) {
const r = cp.spawnSync(RAEA, args, { cwd: dir, encoding: "utf8" }) as { stdout?: string; stderr?: string; error?: Error }
if (r.error) return Promise.reject(new Error(`couldn't run raea ask: ${r.error.message}`))
const rows = rowsOf(String(r.stdout ?? ""))
if (rows.length !== says.length) return Promise.reject(new Error(`raea ask answered ${rows.length} of ${says.length} about ${file}: ${String(r.stderr ?? "").trim().slice(-300) || String(r.stdout ?? "").trim().slice(-300)}`))
return Promise.resolve(rows)
}
return new Promise((ok, no) => {
const c = cp.spawn(RAEA, args, { cwd: dir, stdio: ["ignore", "pipe", "pipe"] })
let out = "", err = ""
c.stdout.setEncoding("utf8").on("data", (t: string) => (out += t))
c.stderr.setEncoding("utf8").on("data", (t: string) => (err = (err + t).slice(-4000)))
c.on("error", (e) => no(new Error(`couldn't run raea ask: ${e.message}`)))
c.on("close", () => {
const rows = rowsOf(out)
if (rows.length !== says.length) return no(new Error(`raea ask answered ${rows.length} of ${says.length} about ${file}: ${err.trim().slice(-300) || out.trim().slice(-300)}`))
ok(rows)
})
})
}
/** the goal's `says` rules judged (`raea goal check` asks this itself; `raea goal judge` too): each where it's judged
* (criticUrl above), its verdict kept at review/judge/NAME.json, stamped with when it was asked (so work changed while
* it judged counts as changed after) */
export async function judge(g: Contract, dir: string, o: { ask?: typeof askClef; agent?: (cwd: string, prompt: string) => Promise<string> } = {}): Promise<Verdict> {
const all = saysOf(g)
if (!all.length) throw new Error(`goal ${nameOf(g)} has no \`says\` rules; its \`run\` and \`file\` rules are held by raea goal check`)
const asked = Math.floor(Date.now() / 1000)
const watched = all.filter((r) => piecesOf(r, dir).length > 0)
const read = all.filter((r) => !watched.includes(r))
// what's watched and heard, and what's read, at once: neither waits on the other
const [heard, said] = await Promise.all([
watched.length ? clefVerdict(g, dir, o.ask ?? askClef, watched) : Promise.resolve({} as Verdict["rules"]),
read.length ? (o.agent ?? askAgent)(dir, prompt(g, dir, read)) : Promise.resolve(null),
])
const rules: Verdict["rules"] = { ...heard }
if (said !== null) {
const v = lastVerdict(said)
if (!v) throw new Error(`the critic gave no verdict: ${said.slice(-300).trim()}`)
for (const r of read) rules[r.id] = v.rules?.[r.id] ?? { pass: false, why: "the critic didn't answer this rule" }
}
return keep(g, dir, { at: asked, by: [watched.length ? "clef" : "", read.length ? "agent" : ""].filter(Boolean).join("+"), goal: g.aim ?? nameOf(g), rules })
}
/** a fresh session of this project's own agent, through the host that started it (RAEA_JUDGE_URL): what it says */
async function askAgent(cwd: string, p: string): Promise<string> {
const url = criticUrl()
if (!url) throw new Error(NO_CRITIC)
const r = await fetch(url, { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${process.env.RAEA_JUDGE_TOKEN ?? ""}` }, body: JSON.stringify({ cwd, prompt: p }), signal: AbortSignal.timeout(15 * 60_000) })
const j = (await r.json().catch(() => ({}))) as { text?: string; error?: string }
if (!r.ok || typeof j.text !== "string") throw new Error(j.error ?? `the critic answered ${r.status}`)
return j.text
}
function keep(g: Contract, dir: string, out: Verdict): Verdict {
const file = path.join(dir, verdictPath(g))
mkdirSync(path.dirname(file), { recursive: true })
writeFileSync(file, `${JSON.stringify(out, null, 2)}\n`)
return out
}
export const hasVerdict = (dir: string, g: Contract) => existsSync(path.join(dir, verdictPath(g)))
-27
View File
@@ -1,27 +0,0 @@
// An agent socket kept alive, and ended when its caller is gone (the /v1/acp socket, main.ts).
// A message every 20 s, so the socket is never idle: between raea cloud and the box it's closed after about two minutes
// without traffic, and an agent waiting on a long render sends nothing (11-25: five of StreetTalk's seven "socket
// closed" ends came 114-125 s into a silence). raea cloud skips notifications it doesn't know; the agent never sees it.
// And a ping with it: a caller that answers none for CALLER_GONE_MS is gone though its half of the socket stayed open
// (an API restart), and the socket is ended, which stops its agent (12-03: a stopped project's Gemini, busy, so never
// idle, went on an hour running goal checks on raea-5).
import type { WebSocket } from "ws"
export const CALLER_GONE_MS = 3 * 60_000
const EVERY_MS = 20_000
/** the keepalive's timer: clear it when the socket closes */
export function keepAlive(ws: WebSocket, who: string, goneMs = CALLER_GONE_MS, everyMs = EVERY_MS): ReturnType<typeof setInterval> {
let pong = Date.now()
ws.on("pong", () => (pong = Date.now()))
return setInterval(() => {
if (ws.readyState !== ws.OPEN) return
if (Date.now() - pong > goneMs) {
process.stderr.write(`raea-cloud: ${who}'s caller answered no ping in ${Math.round(goneMs / 1000)} s: ended\n`)
ws.terminate()
return
}
ws.send('{"jsonrpc":"2.0","method":"_raea/keepalive"}')
ws.ping()
}, everyMs)
}
-37
View File
@@ -1,37 +0,0 @@
// GET and PUT /v1/files: a file of the work folder read or written, or a folder listed. Both ways stream: a body is
// never held in memory (12-03: a box's home folder, gigabytes, moved from a Sprite to a Fly Machine in one request).
import { createReadStream, createWriteStream, mkdirSync, readdirSync, renameSync, rmSync, statSync } from "node:fs"
import type { IncomingMessage, ServerResponse } from "node:http"
import path from "node:path"
import { pipeline } from "node:stream/promises"
type Json = (res: ServerResponse, v: unknown, status?: number) => unknown
export function files(req: IncomingMessage, res: ServerResponse, url: URL, o: { resolve: (p: string) => string; work: string; json: Json }) {
const { json } = o
const p = o.resolve(url.searchParams.get("path") ?? ".")
if (req.method === "PUT") {
// to disk as it comes, beside the file, then put in its place whole
mkdirSync(path.dirname(p), { recursive: true })
const part = `${p}.part-${process.pid}-${Date.now()}`
return pipeline(req, createWriteStream(part)).then(
() => {
renameSync(part, p)
json(res, { path: path.relative(o.work, p), bytes: statSync(p).size })
},
(e) => {
rmSync(part, { force: true })
if (!res.headersSent) json(res, { error: `the file didn't arrive whole: ${(e as Error).message}` }, 500)
},
)
}
let st
try {
st = statSync(p)
} catch {
return json(res, { error: `${url.searchParams.get("path")} doesn't exist` }, 404)
}
if (st.isDirectory()) return json(res, readdirSync(p, { withFileTypes: true }).map((d) => ({ name: d.name, dir: d.isDirectory(), bytes: d.isFile() ? statSync(path.join(p, d.name)).size : undefined })))
res.writeHead(200, { "content-type": "application/octet-stream", "content-length": st.size })
return pipeline(createReadStream(p), res).catch(() => res.destroy())
}
-98
View File
@@ -1,98 +0,0 @@
// A box on a Fly Machine stops itself when nothing is going on (12-03: the boxes moved off Sprites, which paused on
// their own; a Machine runs, and bills, until something stops it). Fly's proxy starts a stopped Machine again on the
// next request, so a box only has to know when it's idle: then the server exits 0, the entrypoint saves and exits, and
// the Machine (restart policy on-failure) stays stopped.
//
// Idle is all of: no request for `quietMs`, no connection open (an agent's ACP socket, a shell's stream), nothing the
// server runs, no process anywhere working in the box's work folder (a render, the footage prep, an agent's
// background job: each runs in a project's folder), and no hold. A hold is the file HOLD_FILE touched within
// `holdMs`: raea cloud touches it while a project is unfinished (its awake alarm), as it held a Sprite's task before.
//
// Off unless RAEA_CLOUD_IDLE_STOP_MIN is set (the Fly image sets it), so a box elsewhere never stops itself.
import { readdirSync, readFileSync, readlinkSync, realpathSync, statSync } from "node:fs"
import type { Server } from "node:http"
import path from "node:path"
export const HOLD_FILE = ".raea-hold"
/** a process other than this one (and its parents) whose working folder is under `work` */
export function workingIn(work: string, self = process.pid): number[] {
const mine = new Set<number>()
for (let p = self; p > 1; ) {
mine.add(p)
try {
// /proc/PID/stat: "PID (name) STATE PPID ...", the name in brackets may hold spaces
const stat = readFileSync(`/proc/${p}/stat`, "utf8")
p = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1])
} catch {
break
}
}
const out: number[] = []
let pids: string[] = []
try {
pids = readdirSync("/proc").filter((d) => /^\d+$/.test(d))
} catch {
return out
}
// the folder by the name it's given and by its real one: /proc says where a process is with no symlink in the way, and
// a Fly box's work folder is /home/sprite/work, a link to /home/raea/work (12-03: a 64 GB unpack in it was taken for
// idle and the box stopped under it)
const roots = [path.resolve(work) + "/"]
try {
roots.push(realpathSync(work) + "/")
} catch {}
for (const d of pids) {
const pid = Number(d)
if (mine.has(pid)) continue
try {
const cwd = readlinkSync(`/proc/${d}/cwd`) + "/"
if (roots.some((r) => cwd.startsWith(r))) out.push(pid)
} catch {}
}
return out
}
export interface IdleOptions {
server: Server
work: string
home: string
/** whether the server itself has something running (an agent, a shell, a job) */
busy: () => boolean
quietMs: number
holdMs?: number
everyMs?: number
log?: (line: string) => void
exit?: () => void
}
/** watches for the box going idle and exits when it has been idle a whole `quietMs`; returns what marks a request */
export function stopWhenIdle(o: IdleOptions): { touch: () => void; stop: () => void } {
let last = Date.now()
const holdMs = o.holdMs ?? 10 * 60_000
const log = o.log ?? ((l) => process.stderr.write(l + "\n"))
const exit = o.exit ?? (() => process.exit(0))
const why = (): string | null => {
if (Date.now() - last < o.quietMs) return "a request came lately"
if (o.busy()) return "the server runs something"
try {
const held = statSync(path.join(o.home, HOLD_FILE)).mtimeMs
if (Date.now() - held < holdMs) return "a project holds it"
} catch {}
const w = workingIn(o.work)
if (w.length) return `${w.length} processes work in ${o.work}`
return null
}
const timer = setInterval(() => {
o.server.getConnections((e, n) => {
if (!e && n > 0) return
if (why()) return
log(`raea-cloud: idle for ${Math.round(o.quietMs / 60_000)} min (no request, connection, process or hold): stopping, so the machine stops`)
clearInterval(timer)
o.server.close()
exit()
})
}, o.everyMs ?? 30_000)
timer.unref()
return { touch: () => void (last = Date.now()), stop: () => clearInterval(timer) }
}
+25 -21
View File
@@ -39,13 +39,9 @@
import { claudeStopHook, jobsOf, markedEnd, sessionIn, watchEnd, watchTurnEnd } from "./turn-end.ts"
import { execFile, spawn } from "node:child_process"
import { timingSafeEqual } from "node:crypto"
import { existsSync, mkdirSync, readFileSync, symlinkSync } from "node:fs"
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, symlinkSync, writeFileSync } from "node:fs"
import { createServer, type IncomingMessage, type ServerResponse } from "node:http"
import path from "node:path"
import { homedir } from "node:os"
import { keepAlive } from "./alive.ts"
import { files } from "./files.ts"
import { stopWhenIdle } from "./idle.ts"
import { WebSocketServer } from "ws"
import { installed, spawnFor } from "./agents.ts"
import { guard } from "./memguard.ts"
@@ -177,6 +173,24 @@ async function body(req: IncomingMessage): Promise<Buffer> {
return Buffer.concat(parts)
}
function files(req: IncomingMessage, res: ServerResponse, url: URL) {
const p = resolve(url.searchParams.get("path") ?? ".")
if (req.method === "PUT")
return body(req).then((b) => {
mkdirSync(path.dirname(p), { recursive: true })
writeFileSync(p, b)
json(res, { path: path.relative(WORK, p), bytes: b.length })
})
let st
try {
st = statSync(p)
} catch {
return json(res, { error: `${url.searchParams.get("path")} doesn't exist` }, 404)
}
if (st.isDirectory()) return json(res, readdirSync(p, { withFileTypes: true }).map((d) => ({ name: d.name, dir: d.isDirectory(), bytes: d.isFile() ? statSync(path.join(p, d.name)).size : undefined })))
res.writeHead(200, { "content-type": "application/octet-stream", "content-length": st.size }).end(readFileSync(p))
}
/** An NDJSON answer's headers sent at once, and an empty line ({}) every KEEPALIVE_MS until it ends: the box sits
* behind Cloudflare, which answers 524 when nothing comes back for 100 s, and `raea goal check --json` over seven
* cuts prints nothing until it's done (11-30, Dutch's stop at Client sign-off was sent back on it). Readers skip a
@@ -239,10 +253,6 @@ async function shell(req: IncomingMessage, res: ServerResponse) {
const server = createServer(async (req, res) => {
const url = new URL(req.url ?? "/", "http://raea-cloud")
// a request (other than a platform's health check) keeps an idle box up (idle.ts)
// a request is the box at work from when it starts until it ends: a 19-minute upload counted only its start, and the
// box stopped as idle the moment it ended (12-03)
if (url.pathname !== "/healthz") (idle?.touch(), res.on("close", () => idle?.touch()))
if (url.pathname === "/healthz") return res.writeHead(200, { "content-type": "text/plain" }).end("ok")
// the critic an agent's shell asks (critic.ts): its own session's token, not the box's
if (url.pathname === "/host/judge" && req.method === "POST") {
@@ -283,7 +293,7 @@ const server = createServer(async (req, res) => {
running: running.size,
})
}
if (url.pathname === "/v1/files" && (req.method === "GET" || req.method === "PUT")) return await files(req, res, url, { resolve, work: WORK, json })
if (url.pathname === "/v1/files" && (req.method === "GET" || req.method === "PUT")) return await files(req, res, url)
if (url.pathname === "/v1/run" && req.method === "POST") return await run(req, res)
if (url.pathname === "/v1/shell" && req.method === "POST") return await shell(req, res)
if (url.pathname === "/v1/jobs" && req.method === "POST") {
@@ -396,7 +406,11 @@ server.on("upgrade", (req, socket, head) => {
}
running.add(child)
agentSockets.add(ws)
const beat = keepAlive(ws, agent.id)
// a message every 20 s, so the socket is never idle: between raea cloud and the box it's closed after about two
// minutes without traffic, and an agent waiting on a long render sends nothing (11-25: five of StreetTalk's seven
// "socket closed" ends came 114-125 s into a silence). raea cloud skips notifications it doesn't know; the agent
// never sees it
const beat = setInterval(() => ws.readyState === ws.OPEN && ws.send('{"jsonrpc":"2.0","method":"_raea/keepalive"}'), 20_000)
// an agent that has said nothing and been sent nothing for IDLE_AGENT_MS is ended: raea cloud ends a turn whose
// agent is quiet 30 min (acp-run.ts QUIET_TOOL_MS), and a socket whose caller went away without closing it (an API
// restart; the Sprite's proxy kept the box's half open) otherwise kept its agent forever (11-30: two Gemini agents
@@ -475,16 +489,6 @@ if (existsSync("/proc/meminfo") && process.env.RAEA_CLOUD_MEMGUARD !== "0")
process.stderr.write(line + "\n")
for (const ws of agentSockets) if (ws.readyState === ws.OPEN) ws.send(JSON.stringify({ jsonrpc: "2.0", method: "_raea/stderr", params: { text: line + "\n" } }))
})
// a box on a Fly Machine stops itself when nothing is going on, and Fly's proxy starts it at the next request (idle.ts)
const idleMin = Number(process.env.RAEA_CLOUD_IDLE_STOP_MIN ?? 0)
const idle =
idleMin > 0
? stopWhenIdle({ server, work: WORK, home: homedir(), busy: () => running.size > 0 || agentSockets.size > 0, quietMs: idleMin * 60_000 })
: null
// a request may take as long as its body takes to come: Node's 5 minutes cut a home folder's upload off at 408
// (12-03, a Sprite's home moved to a Fly box). A client still has 60 s to send its headers.
server.requestTimeout = 0
server.headersTimeout = 60_000
server.listen(PORT, async () => {
await versionKnown
const d = device(childEnv())
+3 -44
View File
@@ -225,54 +225,13 @@ export async function farmInputs(root: string, farm: FarmBlobs, skip: (p: string
let sent = 0
const todo = media.filter((m, i) => !have.has(m.oid) && media.findIndex((x) => x.oid === m.oid) === i)
if (todo.length) said(`sending ${todo.length} media files (${(todo.reduce((n, m) => n + m.size, 0) / 1e6).toFixed(1)} MB) to the farm's cache, once`)
// four at a time: one by one, 50 takes took minutes on a box whose uplink sits mostly idle
let next = 0
const one = async () => {
for (let i = next++; i < todo.length; i = next++) {
await farm.put(todo[i].abs, todo[i].oid, todo[i].size)
sent += todo[i].size
}
for (const m of todo) {
await farm.put(m.abs, m.oid, m.size)
sent += m.size
}
await Promise.all(Array.from({ length: Math.min(4, todo.length) }, one))
return { media: media.map(({ abs: _, ...m }) => m), sent }
}
/** the project's video and audio that no source file names, which a render doesn't need: neither sent to the farm nor
* packed. 12-03: footage/originals/ (the full-size takes, several GB) went to the farm on the first render of every
* StreetTalk run, a still included, and the render ran past its 5 minutes. A file is named by its path, its file name,
* or its stem with its folder's name ("originals/" + `${id}.mov`). When no source names any, all of it is used, as
* before; RAEA_CLOUD_GPU_ALL_MEDIA=1 sends it all regardless */
export function unusedMedia(root: string, skip: (p: string) => boolean = () => false): string[] {
if (process.env.RAEA_CLOUD_GPU_ALL_MEDIA === "1") return []
const AV = new Set(["mp4", "mov", "m4v", "webm", "mkv", "mxf", "avi", "wav", "mp3", "m4a", "aac", "flac", "ogg"])
const SRC = new Set(["tsx", "ts", "jsx", "js", "mjs", "json", "css"])
// folders of what's made for the agent or by a render, not what a composition reads from (footage/index.json lists
// every take)
const NOT_SOURCE = new Set(["footage", "brief_docs", "review", "out", "node_modules", "previews"])
const av: string[] = []
let text = ""
const walk = (dir: string, source: boolean) => {
for (const e of readdirSync(dir, { withFileTypes: true })) {
const abs = path.join(dir, e.name)
const rel = path.relative(root, abs).split(path.sep).join("/")
if (skip(rel) || e.name === ".git" || e.name.startsWith(".raea-cloud")) continue
const ext = e.name.includes(".") ? e.name.split(".").pop()!.toLowerCase() : ""
if (e.isDirectory()) walk(abs, source && !(dir === root && NOT_SOURCE.has(e.name)))
else if (e.isFile() && AV.has(ext)) av.push(rel)
else if (e.isFile() && source && SRC.has(ext) && statSync(abs).size < 2 << 20) text += readFileSync(abs, "utf8") + "\n"
}
}
walk(root, true)
const named = (rel: string) => {
const name = rel.split("/").pop()!
const stem = name.replace(/\.[^.]+$/, "")
const folder = rel.includes("/") ? rel.split("/").slice(-2, -1)[0] + "/" : ""
return text.includes(rel) || text.includes(name) || (stem.length >= 3 && text.includes(stem) && (!folder || text.includes(folder)))
}
const used = av.filter(named)
return used.length ? av.filter((f) => !used.includes(f)) : []
}
/** tar's exclude-from lines for paths that go by hash: each matched as written (glob characters escaped) */
export const excludes = (media: Media[]) => media.map((m) => "./" + m.path.replace(/[\\*?[\]]/g, (c) => "\\" + c)).join("\n") + "\n"
+3 -11
View File
@@ -21,7 +21,7 @@ import os from "node:os"
import path from "node:path"
import { pathToFileURL } from "node:url"
import { RaeaCloud } from "../src/index.ts"
import { excluded, excludes as mediaExcludes, farmBlobs, farmInputs, inputs, lfsOf, localSources, outputs, unusedMedia } from "./media.ts"
import { excluded, excludes as mediaExcludes, farmBlobs, farmInputs, inputs, lfsOf, localSources, outputs } from "./media.ts"
const REAL = process.env.RAEA_REAL ?? "/opt/raea/bin/raea"
// flags whose value is a path raea writes; the rest of a render's path arguments are read
@@ -111,24 +111,16 @@ async function main() {
const sent = path.join(tmp, "in.tar")
// the media that goes by hash: out of the tar, named in its manifest
const lfs = lfsOf(p.root)
// video and audio no source file names stays here, out of the tar and the farm's cache (media.ts unusedMedia)
const unused = new Set(unusedMedia(p.root, excluded(excludes)))
if (unused.size) say(`${unused.size} video and audio files no source names stay here`)
const skip = (rel: string) => excluded(excludes)(rel) || unused.has(rel)
let byHash = typeof lfs === "string" ? [] : await inputs(p.root, lfs, skip)
let byHash = typeof lfs === "string" ? [] : await inputs(p.root, lfs, excluded(excludes))
// not in raea's LFS: the media goes into the farm's own cache by hash, once, instead of in every render's tar
// (RAEA_CLOUD_GPU_BLOBS=0 puts it back in the tar). A farm without the cache, or one that can't be reached here,
// leaves it in the tar, and the health check below says why the farm can't be reached
let viaFarm: { media: typeof byHash; sent: number } | null = null
if (typeof lfs === "string" && process.env.RAEA_CLOUD_GPU_BLOBS !== "0") {
viaFarm = await farmInputs(p.root, farmBlobs(url, token), skip, say).catch((e) => (say(`the farm's media cache: ${(e as Error).message}; the media goes in the tar`), null))
viaFarm = await farmInputs(p.root, farmBlobs(url, token), excluded(excludes), say).catch((e) => (say(`the farm's media cache: ${(e as Error).message}; the media goes in the tar`), null))
if (viaFarm) byHash = viaFarm.media
}
const extra: string[] = []
if (unused.size) {
writeFileSync(path.join(tmp, "unused-excludes"), mediaExcludes([...unused].map((f) => ({ path: f, oid: "", size: 0 }))))
extra.push("-X", path.join(tmp, "unused-excludes"))
}
if (byHash.length) {
writeFileSync(path.join(tmp, "media-excludes"), mediaExcludes(byHash))
writeFileSync(path.join(tmp, ".raea-cloud-media.json"), JSON.stringify({ objects: byHash }))
+1 -11
View File
@@ -91,15 +91,6 @@ async function follow(res: Response, onOutput: ((text: string, stream: "out" | "
throw new Error(`${what} ended without an exit code`)
}
/** whether a box's address is a Sprite's (behind the Sprite's own auth) */
export const onSprite = (url: string): boolean => {
try {
return new URL(url).hostname.endsWith(".sprites.app")
} catch {
return false
}
}
export class RaeaCloud {
readonly url: string
private token: string
@@ -112,8 +103,7 @@ export class RaeaCloud {
constructor(o: { url: string; token: string; spriteToken?: string }) {
this.url = o.url.replace(/\/+$/, "")
this.token = o.token
// only a box on a Sprite is behind the Sprite's auth; a box elsewhere (a Fly Machine's own app) takes its token
this.spriteToken = onSprite(this.url) ? o.spriteToken : undefined
this.spriteToken = o.spriteToken
}
/** A request to the box, its response as it comes, for a caller that reads the body itself (a stream of a file
-104
View File
@@ -1,104 +0,0 @@
# The farm API's volume gate (deploy/modal/farm.py's Gate, cut from the file as it is) against a stand-in volume:
# python3 test/farm_gate.py from sdk/cloud. 12-04: a reload starved behind uploads lost a finished cut (GET out: 408).
import asyncio
import contextlib
import os
import sys
import textwrap
src = open(sys.argv[1] if len(sys.argv) > 1 else os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "deploy", "modal", "farm.py")).read()
a = src.index(" class Gate:\n")
b = src.index(" gate = Gate()\n")
code = textwrap.dedent(src[a:b])
class Vol:
def __init__(self):
self.reloads = 0
async def _reload(self):
await asyncio.sleep(0.05)
self.reloads += 1
class _R:
def __init__(self, v):
self.v = v
async def aio(self):
await self.v._reload()
@property
def reload(self):
return Vol._R(self)
async def main():
vol = Vol()
ns = {"asyncio": asyncio, "contextlib": contextlib, "vol": vol}
exec(code, ns)
Gate = ns["Gate"]
# 1. users that overlap without a break (each 0.2 s, a new one every 0.1 s) for 3 s: a reload still happens quickly
g = Gate()
stop = False
async def user():
async with g.use():
await asyncio.sleep(0.2)
async def stream():
tasks = []
while not stop:
tasks.append(asyncio.create_task(user()))
await asyncio.sleep(0.1)
await asyncio.gather(*tasks)
s = asyncio.create_task(stream())
await asyncio.sleep(0.3)
t0 = asyncio.get_running_loop().time()
ok = await g.reload(within=2)
took = asyncio.get_running_loop().time() - t0
stop = True
await s
assert ok, "a reload behind a stream of users gave up"
assert took < 0.6, f"a reload behind a stream of users took {took:.2f} s"
print(f"ok: a reload behind a stream of users in {took:.2f} s")
# 2. ten reloads asked at once share: fewer volume reloads than asks, and all True
g = Gate()
before = vol.reloads
rs = await asyncio.gather(*[g.reload() for _ in range(10)])
assert all(rs)
n = vol.reloads - before
assert n <= 2, f"10 asks made {n} reloads"
print(f"ok: 10 reloads asked together made {n} volume reload(s)")
# 3. a user that holds the volume past the limit: the reload gives up (False), and the gate still works after
g = Gate()
async def long_user():
async with g.use():
await asyncio.sleep(0.5)
lu = asyncio.create_task(long_user())
await asyncio.sleep(0.05)
assert await g.reload(within=0.2) is False
await lu
async with g.use():
pass
assert await g.reload(within=1) is True
print("ok: a wait past its limit gives up, and the gate is usable after")
# 4. wait=False while a reload is waiting: skipped
g = Gate()
lu = asyncio.create_task(long_user())
await asyncio.sleep(0.05)
w = asyncio.create_task(g.reload())
await asyncio.sleep(0.05)
assert await g.reload(wait=False) is False
await lu
assert await w is True
print("ok: wait=False skips while a reload waits")
asyncio.run(main())
-60
View File
@@ -69,11 +69,6 @@ class FakeGpu:
def starmap(self, calls, order_outputs=False, return_exceptions=True):
return [self.remote(*c) for c in calls]
def spawn(self, *a, **kw):
# a run spawned on its own (farm_plan.hedged, waited): answered at once
r = self.remote(*a, **kw)
return type("Done", (), {"get": lambda self, timeout=None: r, "cancel": lambda self: None})()
lines = []
log = lambda t, err=False: lines.append(t)
@@ -128,14 +123,6 @@ clips = sorted(man["sounds"]["clips"], key=lambda c: c["from"])
assert [(c["key"], c["from"], c["to"]) for c in clips] == [("n3", 0, 40), ("n8", 40, 60)], clips
assert abs(clips[0]["at"] - 1.0) < 1e-6 and abs(clips[1]["at"] - 9.0) < 1e-6 and clips[0].get("fadeIn") == 0.012 and clips[1].get("fadeOut") == 0.012, clips
ok("a split render's manifest is its runs' joined: all 60 frames, and each clip whole with its source time")
# 12-04 (StreetTalk round 22): each run numbers its React nodes its own way, so one clip came back as n3 then n11 by
# turns; joined only by key, it stayed in pieces and the sound check called every seam a cut inside a word
m2 = fp.joined({"frames": []}, [
{"frames": [{"frame": 0}], "sounds": {"fps": 30, "clips": [{"key": "n3", "src": "t.mp4", "from": 0, "to": 60, "at": 194.667}]}},
{"frames": [{"frame": 60}], "sounds": {"fps": 30, "clips": [{"key": "n11", "src": "t.mp4", "from": 60, "to": 90, "at": 196.667}]}},
])
assert [(c["src"], c["from"], c["to"]) for c in m2["sounds"]["clips"]] == [("t.mp4", 0, 90)], m2["sounds"]["clips"]
ok("a clip carried across a run's seam under another key is joined whole")
lines.clear()
long = FakeGpu(root, length=1000)
@@ -357,50 +344,3 @@ assert not any("waiting" in l for l in lines), lines
ok("a GPU run that timed out fails the job instead of being waited on forever")
shutil.rmtree(root)
# a flat video's runs go out at once, and a run that hangs back is sent again (farm_plan.hedged, 12-03)
class Call:
def __init__(self, answer_at, r, clock):
self.answer_at, self.r, self.clock, self.cancelled = answer_at, r, clock, False
def get(self, timeout=None):
if self.clock() >= self.answer_at:
return self.r
raise TimeoutError()
def cancel(self):
self.cancelled = True
class Straggly:
"""runs that answer after 10 s, but the first try of the run from frame 40 answers only after 500 s"""
def __init__(self, clock):
self.clock, self.spawned = clock, []
def with_options(self, **kw):
return self
def spawn(self, id, args, frames, first, *rest):
late = first == 40 and not any(f == 40 for f, _ in self.spawned)
c = Call(self.clock() + (500 if late else 10), {"code": 0, "s": 10.0, "frames": len(frames), "first": first}, self.clock)
self.spawned.append((first, c))
return c
now = [0.0]
clock = lambda: now[0]
def tick(_s):
now[0] += 1
st = Straggly(clock)
lines.clear()
calls = [("jh", ["render"], list(range(a, a + 10)), a, False, True) for a in range(0, 60, 10)]
got = []
assert fp.hedged(st, "CPU", calls, log, "frames", got=got, again=[], clock=clock, pause=tick) == 0, lines
assert sorted(r["first"] for r in got) == [0, 10, 20, 30, 40, 50], got
assert [f for f, _ in st.spawned].count(40) == 2, st.spawned
assert now[0] < 100, now
assert any("sent again" in l for l in lines), lines
assert [c.cancelled for f, c in st.spawned if f == 40] == [True, True]
ok("a run that hangs back while the rest are in is sent again, and the first answer kept: the render doesn't wait on it")
-26
View File
@@ -13,7 +13,6 @@ import { shellEnv } from "../server/shell-os.ts"
import { claudeStopHook, jobsOf, lastLine, markedEnd, sessionIn, transcriptOf, turnEndOf, watchEnd, watchTurnEnd } from "../server/turn-end.ts"
import { landedQuery, linkIn, packCredential, unpackCredential } from "../server/google-token.ts"
import { localSources } from "../server/media.ts"
import { keepAlive } from "../server/alive.ts"
import { answerPermission, ask as askCritic, criticFor, register as registerCritic } from "../server/critic.ts"
const L4 = `Devices:
@@ -238,28 +237,3 @@ console.log("units: ok")
rmSync(root, { recursive: true, force: true })
console.log("ok critic")
}
{
// a caller that answers pings keeps its socket; one that answers none is ended, which stops its agent (alive.ts)
const { WebSocketServer, WebSocket } = await import("ws")
const wss = new WebSocketServer({ port: 0 })
const port = (wss.address() as { port: number }).port
const ended: boolean[] = []
wss.on("connection", (ws) => {
const beat = keepAlive(ws, "test", 120, 20)
ws.on("close", () => (clearInterval(beat), ended.push(true)))
})
const live = new WebSocket(`ws://127.0.0.1:${port}`)
await new Promise((ok) => live.on("open", ok))
await new Promise((ok) => setTimeout(ok, 400))
assert.equal(live.readyState, WebSocket.OPEN, "a caller that answers pings was ended")
live.close()
await new Promise((ok) => setTimeout(ok, 50))
// autoPong off: this caller answers nothing, as one whose half stayed open after it went away
const gone = new WebSocket(`ws://127.0.0.1:${port}`, { autoPong: false } as never)
await new Promise((ok) => gone.on("open", ok))
const closed = await new Promise<boolean>((ok) => (gone.on("close", () => ok(true)), setTimeout(() => ok(false), 1000)))
assert.ok(closed, "a caller that answered no ping wasn't ended")
wss.close()
console.log("ok an agent socket's caller gone is ended")
}
-40
View File
@@ -1,40 +0,0 @@
// What a render leaves on the box (server/media.ts unusedMedia): video and audio no source file names. 12-03: every
// StreetTalk run's first render sent footage/originals/ (several GB) to the farm, a still included, and ran past its
// 5 minutes. Run: node test/unused-media.ts (prints ok, or FAIL and exits 1)
import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import path from "node:path"
import { unusedMedia } from "../server/media.ts"
const fail = (m: string): never => {
console.error(`FAIL ${m}`)
process.exit(1)
}
const project = (files: Record<string, string>) => {
const root = mkdtempSync(path.join(tmpdir(), "raea-unused-"))
for (const [f, c] of Object.entries(files)) {
mkdirSync(path.dirname(path.join(root, f)), { recursive: true })
writeFileSync(path.join(root, f), c)
}
return root
}
const same = (a: string[], b: string[], what: string) => JSON.stringify([...a].sort()) === JSON.stringify([...b].sort()) || fail(`${what}: ${JSON.stringify([...a].sort())}`)
// a cut on the light copies: the originals and the untouched takes stay; index.json (which lists every take) isn't source
const takes = {
"footage/Angle1-Take1.mp4": "x", "footage/Angle1-Take2.mp4": "x", "footage/Angle2-Take1.mp4": "x",
"footage/originals/Angle1-Take1.mov": "x", "footage/originals/Angle1-Take2.mov": "x", "footage/originals/Angle2-Take1.mov": "x",
"footage/index.json": JSON.stringify(["Angle1-Take1.mp4", "Angle1-Take2.mp4", "Angle2-Take1.mp4"]),
"media/music/bed.mp3": "x",
}
same(unusedMedia(project({ ...takes, "cut_a.tsx": `<Video src="footage/Angle1-Take1.mp4" /><Video src={"footage/" + "Angle1-Take2.mp4"} /><Audio src="media/music/bed.mp3" />` })),
["footage/Angle2-Take1.mp4", "footage/originals/Angle1-Take1.mov", "footage/originals/Angle1-Take2.mov", "footage/originals/Angle2-Take1.mov"], "a cut on the light copies")
// the final render on the originals by id: originals/ named, the stem from data. The take's light copy goes too
// ("footage/" is in "footage/originals/"): a few MB, against the GB of originals that stay
same(unusedMedia(project({ ...takes, "cut_a.tsx": "const src = (id: string) => `footage/originals/${id}.mov`", "cuts.json": JSON.stringify({ shots: ["Angle1-Take1"] }) })),
["footage/Angle1-Take2.mp4", "footage/Angle2-Take1.mp4", "footage/originals/Angle1-Take2.mov", "footage/originals/Angle2-Take1.mov", "media/music/bed.mp3"], "the final render on the originals")
// nothing names any media: all of it is used, as before
same(unusedMedia(project({ ...takes, "cut_a.tsx": "export default () => null" })), [], "no source names any")
console.log("ok")
+40 -21
View File
@@ -36,6 +36,8 @@ 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 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",
quotes: "every rule quotes the brief's own words",
@@ -46,37 +48,55 @@ export const PACKS = {
cta: "each cut ends on the CTA",
shape: "each cut in its format and length",
run: "each command rule exits 0",
says: "each `says` rule found true by a fresh critic after the work's last change",
deliverables: "every deliverable exists",
floor: "no clipped text, text in the app's buttons, low contrast, freeze, flash or loudness out of range",
render: "nothing the render's own end checks found: a missing font, clipping, a part out of place or under its detail, light that jumps",
critic: "the critic's rounds: a pass newer than the work, its blocking defects fixed or answered",
record: "every composition the plan names rendered or checked clean since it last changed",
notes: "NOTES.md, with what the skill got wrong",
floor: "no clipped text, low contrast, freeze, flash or loudness out of range",
stills: "a composition's stills as it's saved: no clipped or cramped text, nothing out of the safe areas",
playable: "each network's page under 5 MB, in the orientations asked for, exported since the game last changed",
} as const
export type PackName = keyof typeof PACKS
/** each kind's packs, on unless the brief switches them off. Only rules that catch a real fault in that kind of work,
* each run once on a deliverable after its render (12-04, Shane: "fix how every agent checks its work"; round 26's
* checks gave 183 findings on 10 cuts, about 10 of them real faults, and the agents spent their 20 minutes on the
* rest). The others stay a brief's to switch on (`packs: { montage: true }`),
* never an agent's loop: voice, reading, hook, airgaps, montage, quotes. Nothing asks a model to judge the work. */
/** each kind's packs, on unless the brief switches them off (surprise is on only where a brief turns it on) */
export const DEFAULTS: Record<GoalKind | "floor", PackName[]> = {
// a word clipped or missing, a face cut by the frame, text over a face, a sign or the app's buttons, captions over
// talking, the brief's must-say, never-say and CTA, the size, length and name, and what the render itself found
cut: ["words", "sound", "frames", "place", "captions", "floor", "render", "say", "never", "cta", "shape", "naming", "sizes", "count", "open"],
rules: ["deliverables", "render"],
// a 3D scene, kit or shot: what its render found (clipping, a part out of place or under its detail, light that
// jumps or boils: the render's own end checks, in its manifest)
scene: ["deliverables", "render"],
kit: ["deliverables", "render"],
shot: ["deliverables", "render"],
playable: ["deliverables", "playable", "render"],
// a project with no `goal`: what any made video is held to
floor: ["frames", "place", "captions", "floor", "render"],
cut: ["words", "captions", "voice", "reading", "hook", "airgaps", "sound", "frames", "montage", "place", "floor", "stills", "seen", "naming", "sizes", "quotes", "count", "open", "say", "never", "cta", "shape"],
rules: ["deliverables", "stills"],
scene: ["deliverables", "record", "critic", "notes", "stills"],
kit: ["deliverables", "record", "critic", "notes", "stills"],
shot: ["deliverables", "record", "critic", "notes", "stills"],
playable: ["deliverables", "playable", "stills"],
// a project with no `goal`: what any made video is held to, and any composition as it's saved
floor: ["frames", "captions", "voice", "reading", "hook", "airgaps", "floor", "seen", "stills"],
}
/** a `says` rule: what a fresh critic must find true of the work (`raea goal judge`) */
export type Said = { id: string; says: string }
/** every `says` rule a goal is held to: its own, then a cut goal's beats (MK48), each judged on its cut as a viewer sees
* it, shots in sequence: what a shot means comes from its neighbours (Kuleshov), so a beat is read in the cut, never
* shot by shot. Murch puts emotion (51%) and story (23%) above all a cut's other reasons; no measure finds them */
export function saysOf(g: Contract | null): Said[] {
const own = (g?.rules ?? []).flatMap((r) => (r.says ? [{ id: r.id, says: r.says }] : []))
const c = g?.kind === "cut" ? g.cut : undefined
const beats = (c?.cuts ?? []).flatMap((p) => {
const formats = p.formats?.length ? p.formats : (c?.formats ?? [])
const file = formats.length ? `out/cuts/${p.id}_${formats[0].replace(":", "x")}.mp4` : `cut ${p.id}`
const bs = p.beats ?? []
return bs.map((b, i) => {
const until = bs[i + 1] ? `${bs[i + 1].at} s` : "its end"
return { id: `beat_${p.id}_${i + 1}`, says: `In ${file}, from ${b.at} s to ${until}, watched in sequence as cut (a shot reads by its neighbours), the viewer feels ${b.feel}${b.story ? `, and by its end understands ${b.story}` : ""}` }
})
})
return [...own, ...beats]
}
/** the packs that hold a goal: its kind's, its rules' (any goal with rules is held to them), then its switches */
export function packsOf(c: Contract | null): PackName[] {
const on = new Set<PackName>(DEFAULTS[c?.kind ?? "floor"])
if (c?.rules?.some((r) => r.run)) on.add("run")
if (saysOf(c).length) on.add("says")
for (const [k, v] of Object.entries(c?.packs ?? {})) {
if (!(k in PACKS)) continue
if (v) on.add(k as PackName)
@@ -110,8 +130,7 @@ export const rules = (m: Kindless): Contract => ({ kind: "rules", ...m })
export const workflow = (w: Workflow): Workflow => w
/** brief.ts's `goal` (or a workflow's steps) as a list, in order */
export const goalsOf = (g: Goals | Workflow | (Contract | Workflow)[] | null | undefined): Contract[] =>
!g ? [] : Array.isArray(g) ? g.flatMap((x) => goalsOf(x as Contract | Workflow)) : typeof g === "object" && "steps" in g && Array.isArray(g.steps) ? g.steps : typeof g === "object" ? [g as Contract] : []
export const goalsOf = (g: Goals | Workflow | null | undefined): Contract[] => (!g ? [] : Array.isArray(g) ? g : "steps" in g ? g.steps : [g])
/** a goal's name: its own, else its kind's */
export const nameOf = (c: Contract) => c.name ?? c.kind
+14
View File
@@ -17,6 +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`); `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) */
@@ -48,6 +50,8 @@ export interface FileFacts {
scene(at?: number[]): Promise<{ rate: number; faces: Faces[]; scenes: Scene[] }>
/** its contact sheet's path */
sheet(): string
/** what was seen of it since its last change, or null */
seen(): Seen | null
}
export interface Job {
@@ -138,6 +142,16 @@ export function fileFacts(rel: string, root: string, moment: Moment, contract: C
return scenes.get(k)!
},
sheet: () => media.sheet(abs),
seen: () => {
const f = `${media.stem(abs)}.seen.json`
if (!existsSync(f)) return null
try {
const s = JSON.parse(readFileSync(f, "utf8")) as Seen
return s.render === stamp ? s : null
} catch {
return null
}
},
}
}
+1 -1
View File
@@ -1,5 +1,5 @@
// raea/goal (@raea/goal): the loop's goals (docs/goal.feature): plan, run, check, done, for one goal or a workflow of
// them. This entry is pure, as brief.ts imports it: the packs (./packs) and the runner (./run, `raea check`) read
// them. This entry is pure, as brief.ts imports it: the packs (./packs) and the runner (./run, `raea goal check`) read
// files and run programs, and are loaded only by the runner.
export { cut, DEFAULTS, goal, goalsOf, kit, momentsOf, nameOf, PACKS, packsOf, playable, rules, scene, shot, unknownPacks, workflow } from "./contract.ts"
export type { Contract, Goals, Moment, PackName, Workflow } from "./contract.ts"
+15 -79
View File
@@ -18,8 +18,6 @@ import { check, found } from "raea/check"
import type { FileFacts } from "../facts.ts"
import type { Word } from "../media.ts"
import type { TextLine } from "./place.ts"
import { asDigits, digitsIn } from "./numbers.ts"
import { busOf } from "./sound.ts"
/** a line of text the reader found in a frame: [x, y, w, h, text, score], in that frame's pixels */
export type Read = TextLine
@@ -31,6 +29,9 @@ export const letters = (s: string) => s.toLowerCase().normalize("NFKD").replace(
const FILLER = new Set(["um", "uh", "uhh", "umm", "mm", "mhm", "hmm", "er", "erm", "ah"])
/** a line is a caption when this share of its letters is matched by what's said around it */
export const CAPTION = 0.6
/** the time around a caption that what it says may be heard: before it shows, after */
const BEFORE = 2.5
const AFTER = 1.0
/** least score a read line counts at */
export const LEAST = 0.6
@@ -65,6 +66,7 @@ export function fit(cap: string, said: string): { dist: number; bad: boolean[];
/** the heard words whose time falls in [a, b] */
const heardIn = (heard: Word[], a: number, b: number) => heard.filter((w) => w.end >= a && w.start <= b)
const saidAround = (heard: Word[], a: number, b: number) => heardIn(heard, a - BEFORE, b + AFTER).map((w) => letters(w.text)).join("")
/** a caption's showings: one line of text, from its first frame to its last (the same line in frames side by side), and
* how far down the frame its middle is (a share of the frame's height) */
@@ -94,14 +96,13 @@ const LINE = 0.7
* fitting what's said while they're up with few edits. A badge, an app's screen, a sign or an end card stays up or
* says something else. With captions up for under TRACK of the speech, the cut has none to hold */
export function captionsOf(frames: Frame[], rate: number, heard: Word[]): Shown[] {
heard = asDigits(heard)
const all: (Shown & { caps: boolean })[] = []
frames.forEach((fr, i) => {
const t = i / rate
// a frame full of text is a screen or a card (an app, an end card, a product's label), not a caption over the picture
if (fr.lines.filter(([, , , , text, score]) => score >= LEAST && letters(text).length >= 4).length > BUSY) return
for (const [, y, , h, text, score] of fr.lines) {
const key = letters(digitsIn(text))
const key = letters(text)
if (score < LEAST || key.length < 4) continue
const mid = (y + h / 2) / Math.max(1, fr.h)
const last = all.findLast((s) => s.to >= t - 1.01 / rate && Math.abs(s.y - mid) <= ROW && similar(s.key, key))
@@ -148,20 +149,12 @@ function wholeWord(text: string, key: string, i: number, j: number): boolean {
}
/** the captions held to what's heard: letters shown that weren't said, and words said that no caption up then shows */
export function compare(shown: Shown[], heard: Word[], placed: Word[] = []): Finding[] {
heard = asDigits(heard)
placed = asDigits(placed)
export function compare(shown: Shown[], heard: Word[]): Finding[] {
if (!shown.length) return []
const out: Finding[] = []
// shown, not said: a run of three letters or more in a caption that the stretch of speech it fits doesn't have, in
// the export as heard again or in its takes' own words where the edit placed them (what captions are built from):
// 12-05, run 11, a second hearing of the same speech wrote "That's" and "take" otherwise, and right captions read as
// retyped
// shown, not said: a run of three letters or more in a caption that the stretch of speech it fits doesn't have
for (const s of shown) {
const f0 = fit(s.key, heardIn(heard, s.from - 0.8, s.to + 0.4).map((w) => letters(w.text)).join(""))
const near = heardIn(placed, s.from - 0.8, s.to + 0.4)
const f1 = near.length ? fit(s.key, near.map((w) => letters(w.text)).join("")) : null
const f = f1 ? { ...f0, bad: f0.bad.map((b, i) => b && !!f1.bad[i]) } : f0
const f = fit(s.key, heardIn(heard, s.from - 0.8, s.to + 0.4).map((w) => letters(w.text)).join(""))
for (let i = 0; i < f.bad.length; ) {
if (!f.bad[i]) { i++; continue }
let j = i
@@ -197,17 +190,6 @@ export function compare(shown: Shown[], heard: Word[], placed: Word[] = []): Fin
const a = dropped[i].k - 1
const b = dropped[j - 1].k + 1
const inside = phrases && run.length >= 3 && shownAt(a) && shownAt(b) && run[0].start - heard[a].end < LINE && heard[b].start - run[run.length - 1].end < LINE
// the take's own words over the same stretch, captioned: the export heard again wrote them otherwise (12-05, run 11:
// the take's "he heard his label paw", captioned, was heard again as "he sleep with Paul")
const theirs = heardIn(placed, run[0].start - 0.2, run[run.length - 1].end + 0.2).filter((w) => letters(w.text) && !FILLER.has(letters(w.text)))
const covered = theirs.length > 0 && theirs.every((w) => {
const near = shown.filter((s) => w.end >= s.from - 2 && w.start <= s.to + 1.5).map((s) => s.key).join("")
return fit(letters(w.text), near).dist <= (letters(w.text).length >= 5 ? 1 : 0)
})
if (covered) {
i = j
continue
}
const words = run.map((w) => w.text).join(" ")
out.push(inside
? { level: "error", kind: "dropped", at: run[0].start, says: `"${words}" is said at ${run[0].start.toFixed(1)} s, between words the captions show, but no caption shows ${run.length > 1 ? "them" : "it"}: build the captions from the words file so they say every word` }
@@ -227,7 +209,6 @@ const HOOK_S = 5
* and so is a stretch of talking with none up. A text hook may be on screen beside them; it doesn't stand in for them.
* A brief that wants no captions says so, and the render says it with --despite captions WHY */
export function uncaptioned(shown: Shown[], heard: Word[], textUp: (t: number) => boolean = () => false): Finding[] {
heard = asDigits(heard)
// a brief's "captions OR a text hook, never both" means not both in one frame (12-03, Shane): the hook may hold the
// opening alone, so words in the first HOOK_S with other text up are covered by it; anywhere later it's no caption
const said = heard.filter((w) => {
@@ -253,63 +234,18 @@ export function uncaptioned(shown: Shown[], heard: Word[], textUp: (t: number) =
return out
}
/** a render manifest's texts as frames read at `RATE` a second: each text its ink box, read with full confidence */
const RATE = 5
export function framesOfManifest(manifest: unknown): { frames: Frame[]; rate: number } | null {
const m = manifest as { height?: number; fps?: number; frames?: { frame: number; text?: { text?: string; ink?: number[]; box?: number[]; opacity?: number }[] }[] } | null
if (!m?.frames?.length) return null
const fps = Number(m.fps) || 30
const h = Number(m.height) || 1920
const step = Math.max(1, Math.round(fps / RATE))
const frames: Frame[] = []
for (let i = 0; i < m.frames.length; i += step) {
const fr = m.frames[i]
const lines = (fr?.text ?? []).flatMap((t) => {
const b = t.ink ?? t.box
const text = String(t.text ?? "").trim()
return b && b.length >= 4 && text && (t.opacity ?? 1) > 0.2 ? [[b[0], b[1], b[2], b[3], text, 1] as Read] : []
})
frames.push({ h, lines })
}
return { frames, rate: fps / step }
}
/** the takes' own words where the edit placed them, on the cut's clock: each voice clip of the manifest's sound, its
* take's words over the stretch it plays. A take that isn't here adds none */
export async function placedWords(f: FileFacts): Promise<Word[]> {
const m = f.manifest
const fps = m?.sounds?.fps ?? m?.fps ?? 30
const out: Word[] = []
for (const c of m?.sounds?.clips ?? []) {
if (busOf(c) !== "voice") continue
const file = f.take(c.src)
if (!file) continue
const words = await f.takeWords(file).catch(() => [] as Word[])
const a = c.at
const b = c.at + (c.to - c.from) / fps
const shift = c.from / fps - c.at
for (const w of words) if (w.end > a && w.start < b) out.push({ ...w, start: Math.max(a, w.start) + shift, end: Math.min(b, w.end) + shift })
}
return out.sort((x, y) => x.start - y.start)
}
export default check<FileFacts>(
{ id: "captions", text: "everything said is captioned, and every caption says exactly what's heard there, no word added, changed or left out", over: "file", at: ["render", "publish", "done"], needs: ["words", "scene"] },
async (f) => {
if (!f.made || f.kind !== "video") return
// numbers in words and in digits read alike on both sides (numbers.ts)
const heard = asDigits(await f.words())
const heard = await f.words()
if (!heard.length) return
// the render's own texts when its manifest is here: exactly what it drew, where, every frame, and never the footage's
// own text (12-04, round 26: Elfster's phone recordings read as "HO Nam Grou Too Ur", and its captions, drawn at the
// top, weren't recognised as captions at all); else the export read frame by frame
const own = f.manifest ? framesOfManifest(f.manifest) : null
const sc = own ? null : await f.scene()
const frames: Frame[] = own ? own.frames : sc!.scenes.map((s) => ({ h: s?.h ?? 1, lines: (s?.texts ?? []) as Read[] }))
if (!own && !frames.some((f) => f.lines.length) && sc!.scenes.some((s) => s && s.texts === undefined)) return void found({ level: "note", says: "the scene reader here doesn't read text yet, so the captions weren't held to what's heard" })
const rate = own ? own.rate : sc!.rate || 2
const shown = captionsOf(frames, rate, heard)
const sc = await f.scene()
const frames: Frame[] = sc.scenes.map((s) => ({ h: s?.h ?? 1, lines: (s?.texts ?? []) as Read[] }))
if (!frames.some((f) => f.lines.length) && sc.scenes.some((s) => s && s.texts === undefined)) return void found({ level: "note", says: "the scene reader here doesn't read text yet, so the captions weren't held to what's heard" })
const shown = captionsOf(frames, sc.rate || 2, heard)
const rate = sc.rate || 2
const textUp = (t: number) => (frames[Math.round(t * rate)]?.lines ?? []).some(([, , , , text, score]) => score >= LEAST && letters(text).length >= 4)
for (const x of [...uncaptioned(shown, heard, textUp), ...compare(shown, heard, own ? await placedWords(f) : [])].sort((a, b) => a.at - b.at)) found({ level: x.level, says: x.says, seconds: x.at })
for (const x of [...uncaptioned(shown, heard, textUp), ...compare(shown, heard)].sort((a, b) => a.at - b.at)) found({ level: x.level, says: x.says, seconds: x.at })
},
)
+8 -30
View File
@@ -13,8 +13,6 @@ import { check, found } from "raea/check"
import type { CutGoal, CutPlan } from "raea/brief.gen"
import type { FileFacts, Job, Manifest } from "../facts.ts"
import { has, inOrder, joined, norm, SAY_GAP, saidAt } from "../text.ts"
import { quote } from "../text.ts"
import { asDigits } from "./numbers.ts"
export const CTA_WITHIN = 8
/** how much of the CTA a run of words must have, in order */
@@ -62,21 +60,6 @@ export function shown(m: Manifest | null): [string, number][] {
return out
}
/** what each frame from `from` (s) on shows, its texts read together in the order drawn: an end card draws its CTA as
* lines (12-04, Elfster run 4: "Make your Wishlist and organize your Gift Exchange on Elfster." over "It's free.", each
* alone under the CTA's share, and a cut ending on its CTA was failed for none) */
export function shownTogether(m: Manifest | null, from: number): string[] {
if (!m) return []
const fps = m.fps && m.fps > 0 ? m.fps : 30
const out = new Set<string>()
for (const fr of m.frames ?? []) {
if (fr.frame / fps < from) continue
const s = (fr.text ?? []).filter((t) => (t.opacity ?? 1) > 0.05).map((t) => norm(t.text ?? "")).filter(Boolean).join(" ")
if (s) out.add(s)
}
return [...out]
}
const cutJob = (j: Job) => (j.contract?.kind === "cut" ? (j.contract.cut ?? null) : null)
const cutFile = (f: FileFacts) => {
const c = f.contract?.kind === "cut" ? f.contract.cut : undefined
@@ -86,8 +69,7 @@ const cutFile = (f: FileFacts) => {
/** what a cut says and shows */
async function heardOf(f: FileFacts) {
// numbers said in words as the brief writes them ("pets sixty" is PETS60, "sixty dollars" $60): 12-05, Dutch run 10
const words = asDigits(await f.words())
const words = await f.words()
const spoken = words.map((w) => norm(w.text)).filter(Boolean)
const times = words.filter((w) => norm(w.text)).map((w) => w)
return { spoken, times, screen: shown(f.manifest) }
@@ -101,7 +83,7 @@ export const quotesPack = check<Job>({ id: "quotes", text: "every rule quotes th
if (!existsSync(file)) return found({ says: `no brief text at ${c.brief}: pdftotext -layout BRIEF.pdf ${c.brief}`, fix: `pdftotext -layout BRIEF.pdf ${c.brief}` })
const text = norm(readFileSync(file, "utf8"))
const unfound = quotes(c).filter(([, from]) => !has(text, norm(from)))
if (unfound.length) found({ says: `not in the brief's text, word for word: ${unfound.map(([what, from]) => `${what} ("${quote(from, 60)}")`).join("; ")}` })
if (unfound.length) found({ says: `not in the brief's text, word for word: ${unfound.map(([what, from]) => `${what} ("${from.slice(0, 60)}")`).join("; ")}` })
})
export const countPack = check<Job>({ id: "count", text: "as many cuts as the brief asks for, or a person's answer saying why not", over: "job", at: ["edit", "done"] }, async (j) => {
@@ -135,9 +117,8 @@ export const shapePack = check<FileFacts>({ id: "shape", text: "each cut in its
export const sayPack = check<FileFacts>({ id: "say", text: "every phrase the brief says each cut says, heard or shown", over: "file", at: ["render", "publish", "done"], needs: "words" }, async (f) => {
const at = cutFile(f)
if (!at?.c.say?.length) return
const { spoken } = await heardOf(f)
const together = shownTogether(f.manifest, 0)
const on = (p: string) => saidAt(spoken, p, SAY_GAP) !== null || together.some((s) => onScreen(s, p, SAY_GAP))
const { spoken, screen } = await heardOf(f)
const on = (p: string) => saidAt(spoken, p, SAY_GAP) !== null || screen.some(([s]) => onScreen(s, p, SAY_GAP))
const missing = at.c.say.filter((p) => p.every !== false && !on(norm(p.text)))
if (missing.length) found({ says: `never says or shows: ${missing.map((m) => `"${m.text}"`).join(", ")}` })
})
@@ -162,7 +143,7 @@ export const ctaPack = check<FileFacts>({ id: "cta", text: "each cut ends on the
const at = cutFile(f)
const cta = at?.c.cta
if (!cta) return
const { times } = await heardOf(f)
const { times, screen } = await heardOf(f)
const within = cta.within ?? CTA_WITHIN
const end = f.seconds ?? times[times.length - 1]?.end ?? 0
const last = times.filter((w) => w.end >= end - within).map((w) => norm(w.text))
@@ -174,10 +155,7 @@ export const ctaPack = check<FileFacts>({ id: "cta", text: "each cut ends on the
const heard = lines.map((l) => share(l, last))
const best = Math.max(0, ...heard)
const line = best > 0 ? lines[heard.indexOf(best)] : cta.text
// said and shown together: 12-05, Dutch run 10, the host said "use code PETS60 for sixty dollars off your first" as the
// end card showed "Code PETS60: $60 off your first year", and neither alone was 85% of the line
const late = shownTogether(f.manifest, end - within)
const shownLate = late.some((s) => lines.some((l) => share(l, s.split(" ")) >= CTA_SHARE || share(l, [...last, ...s.split(" ")]) >= CTA_SHARE || share(l, [...s.split(" "), ...last]) >= CTA_SHARE))
const shownLate = screen.some(([s, t]) => t >= end - within && lines.some((l) => share(l, s.split(" ")) >= CTA_SHARE))
if (best < CTA_SHARE && !shownLate) found({ says: `no CTA in its last ${within.toFixed(0)} s (${(best * 100).toFixed(0)}% of the nearest one's words heard there): "${line}"`, seconds: [Math.max(0, end - within), end] })
})
@@ -187,10 +165,10 @@ export const sayOncePack = check<Job>({ id: "say-once", text: "each phrase one c
const once = (c?.say ?? []).filter((p) => p.every === false)
if (!c || !once.length) return
const cuts = j.files.filter((f) => cutOf(c, f.path))
const heard = await Promise.all(cuts.map(async (f) => ({ ...(await heardOf(f)), together: shownTogether(f.manifest, 0) })))
const heard = await Promise.all(cuts.map(heardOf))
for (const p of once) {
const n = norm(p.text)
const by = heard.some(({ spoken, together }) => saidAt(spoken, n, SAY_GAP) !== null || together.some((s) => onScreen(s, n, SAY_GAP)))
const by = heard.some(({ spoken, screen }) => saidAt(spoken, n, SAY_GAP) !== null || screen.some(([s]) => onScreen(s, n, SAY_GAP)))
if (!by) found({ says: `no cut says or shows "${p.text}" (brief: "${p.from}")` })
}
})
+3 -32
View File
@@ -19,11 +19,8 @@ function measure(args: string[], cwd: string): Measured[] {
const dir = mkdtempSync(path.join(os.tmpdir(), "raea-floor-"))
try {
const out = path.join(dir, "check.json")
const run = (verb: string) => spawnSync(RAEA, [verb, ...args, "-o", out], { cwd, encoding: "utf8", env: { ...process.env, RAEA_RECORD: "off" }, maxBuffer: 1 << 24 })
// `raea floor` since 12-04; a raea from before it measures as `raea check VIDEO`
let r = run("floor")
if (!existsSync(out)) r = run("check")
if (!existsSync(out)) throw new Error(`raea floor ${args[0]} wrote no report: ${String(r.stderr || r.stdout).trim().slice(-200)}`)
const r = spawnSync(RAEA, ["check", ...args, "-o", out], { cwd, encoding: "utf8", env: { ...process.env, RAEA_RECORD: "off" }, maxBuffer: 1 << 24 })
if (!existsSync(out)) throw new Error(`raea check ${args[0]} wrote no report: ${String(r.stderr || r.stdout).trim().slice(-200)}`)
return (JSON.parse(readFileSync(out, "utf8")).findings ?? []) as Measured[]
} finally {
rmSync(dir, { recursive: true, force: true })
@@ -56,36 +53,10 @@ export function floorOf(abs: string, manifest: string | undefined, cwd: string,
const say = (x: Measured) => found({ level: x.level, says: x.says, fix: x.fix ?? undefined, frames: x.frames ?? undefined })
/** what the floor reports that isn't a fault in the delivery (12-04, round 26: 48 of Elfster's 85 floor lines were
* "3 words need 1.0 s to read" on captions, which follow speech at its own pace, and 4 a brand kit's provenance): a
* text's reading time is a brief's to ask for (the reading pack), where its kit came from is the brand step's */
export const NOT_A_FAULT = [/ words? need [0-9.]+ s to read/, /wasn't read from the brand/, /blocky patches in dark areas.*: the picture's own/]
/** blocky darks the floor couldn't trace to the encode (12-04, Body Shop: an ERROR on a 17 Mbps cut whose frame shows no
* blocks at full size; the footage's own compression, a phone's): an error only when it measured that the encode added
* them, a warning otherwise */
const UNTOLD = /blocky patches in dark areas.*(or the footage holds them|couldn't be told)/
/** the app's right-hand buttons start this far down (sdk/video/src/zones.ts RAIL, apps/check/text RAIL) */
const RAIL = 0.45
const RIGHT = /in the app's UI zone at the right \(keep [0-9]+ px clear\): its (?:box|letters) -?[0-9]+,(-?[0-9]+) [0-9]+x([0-9]+) in [0-9]+x([0-9]+)/
/** a raea from before the rail (12-05) held the right zone the whole height: text in it above the buttons isn't a fault
* (Body Shop's centred end card at 35% down was an error). Where more texts like it were found it's a warning, since
* one of those may reach the buttons */
function aboveRail(x: Measured): Measured | null {
const m = RIGHT.exec(x.says)
if (!m || +m[1] + +m[2] > RAIL * +m[3]) return x
return / more like it/.test(x.says) ? { ...x, level: x.level === "error" ? "warn" : x.level } : null
}
export const faultsOf = (xs: Measured[]) =>
xs
.filter((x) => !NOT_A_FAULT.some((r) => r.test(x.says)))
.map((x) => (x.level === "error" && UNTOLD.test(x.says) ? { ...x, level: "warn" as const } : x))
.map(aboveRail)
.filter((x): x is Measured => !!x)
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 faultsOf(floorOf(f.abs, 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) => {
+1 -2
View File
@@ -13,7 +13,6 @@ import { existsSync, readFileSync } from "node:fs"
import { check, found } from "raea/check"
import type { FileFacts } from "../facts.ts"
import { RATE, stem, type Faces } from "../media.ts"
import { quote } from "../text.ts"
/** a face this share of the frame's height or more is someone in the shot, not a passer-by far behind */
export const FACE_MIN = 0.05
@@ -128,7 +127,7 @@ export function smallText(manifest: any): Finding[] {
}
const out: Finding[] = []
for (const [text, { at, px }] of seen) {
const q = `"${quote(text, 40)}"`
const q = text.length > 40 ? `"${text.slice(0, 40)}..."` : `"${text}"`
if (px < TEXT_ERROR) out.push({ level: "error", kind: "text-small", at, says: `${q} is ${px.toFixed(0)} px (in a 1080-wide frame): under ${TEXT_ERROR} px no one reads it on a phone. Make it bigger, or cut words so it fits bigger` })
else if (px < TEXT_WARN) out.push({ level: "warn", kind: "text-small", at, says: `${q} is ${px.toFixed(0)} px: small for anything but a badge or small print (captions 52 px, hooks 64 px)` })
}
+232 -4
View File
@@ -1,15 +1,243 @@
// The rules pack: a goal's command rules, each run in the brief's folder within its timeout (300 s by default), run
// again each time. A goal's `file` rules are deliverables (the deliverables pack holds them). Nothing here asks a model
// to judge the work (12-04, Shane: "removing ask and judge completely and all that exists is check").
// The rule packs (MK29, MK38; Rust's goal gates until 11-29, now here alone): any goal held to its rules,
// from what's on disk and what a fresh critic said, never from the agent that did the work (11-26, Shane: "it can't
// stop unless all the goals pass").
// run the command exits 0 in the brief's folder, within its timeout (300 s by default), run again each time
// says a fresh critic (`raea goal judge`) found it true of the work, after the work's last change
// (file rules are deliverables: the deliverables pack holds them)
// The critic's verdict is review/judge/NAME.json (the goal's name): {at, by, goal, rules: {ID: {pass, why}}}.
import { spawnSync } from "node:child_process"
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"
import path from "node:path"
import { check, found } from "raea/check"
import { type Contract, nameOf, type Said, saysOf } from "../contract.ts"
import type { Job } from "../facts.ts"
import { RAEA } from "../media.ts"
/** where a goal's critic verdict is kept, relative to the brief */
export const verdictPath = (g: Contract) => `review/judge/${nameOf(g)}.json`
export const TIMEOUT = 300
/** folders that aren't the work: what the job writes about itself, and what tools keep */
const NOT_WORK = new Set(["review", ".git", "node_modules", ".raea", "target", ".cache", ".raea-cloud"])
/** what a check keeps beside a file it read (its report, its words, its scene): a reading of the work, not a change
* to it. A done check that heard a cut's words wrote them beside it, and the critic's verdict of a minute before read
* as older than the work (12-01) */
const READING = /\.(check|words|scene|floor|montage)\.json$/
/** when the work last changed (ms): the newest file under dir, its own bookkeeping left out (a bounded walk) */
export function newest(dir: string): number | null {
let best: number | null = null
const stack = [dir]
let seen = 0
while (stack.length) {
const d = stack.pop()!
let names: string[] = []
try {
names = readdirSync(d)
} catch {
continue
}
for (const name of names) {
if (++seen > 20_000) return best
const p = path.join(d, name)
let st
try {
st = statSync(p)
} catch {
continue
}
if (st.isDirectory()) {
if (!(d === dir && NOT_WORK.has(name)) && name !== "node_modules" && name !== ".git") stack.push(p)
} else if (st.isFile() && name !== "NOTES.md" && !READING.test(name)) best = Math.max(best ?? 0, st.mtimeMs)
}
}
return best
}
type Verdict = { at: number; by: string; goal?: string; rules: Record<string, { pass: boolean; why: string } | undefined> }
export function verdict(dir: string, g: Contract): Verdict | null {
try {
return JSON.parse(readFileSync(path.join(dir, verdictPath(g)), "utf8")) as Verdict
} catch {
return null
}
}
const goalOf = (j: Job): Contract | null => j.contract
export const runPack = check<Job>({ id: "run", text: "each command rule exits 0", over: "job", at: ["done"] }, async (j) => {
for (const r of j.contract?.rules ?? []) {
for (const r of goalOf(j)?.rules ?? []) {
if (!r.run) continue
const { ok, said } = await j.run(r.run, r.timeout ?? TIMEOUT)
if (!ok) found({ says: `${r.id}: \`${r.run}\` ${said}`, about: [r.id] })
}
})
export const saysPack = check<Job>({ id: "says", text: "each `says` rule found true by a fresh critic after the work's last change", over: "job", at: ["done"] }, async (j) => {
const says = saysOf(goalOf(j) ?? null)
if (!says.length) return
let v = verdict(j.root, j.contract!)
// at whole seconds, as the verdict keeps its time: work saved in the second the critic was asked counts as judged
const freshOf = (x: Verdict | null) => !!x && (newest(j.root) === null || x.at >= Math.floor(newest(j.root)! / 1000))
// a verdict missing, stale or short of a rule is asked for here (the check is the one command; the agent never
// judges by hand), where this session has a critic to ask
if (!(freshOf(v) && says.every((r) => v!.rules?.[r.id])) && hasCritic(j.root, says)) {
try {
v = await judge(j.contract!, j.root)
} catch (e) {
found({ says: `the critic couldn't judge: ${(e as Error).message}` })
return
}
}
const fresh = freshOf(v)
for (const r of says) {
const one = v?.rules?.[r.id]
const fix = NO_CRITIC
if (!v) found({ says: `${r.id}: not judged yet`, about: [r.id], fix })
else if (!one) found({ says: `${r.id}: the last judging didn't cover it`, about: [r.id], fix })
else if (!fresh) found({ says: `${r.id}: the work changed after the critic judged it`, about: [r.id], fix })
else if (!one.pass) found({ says: `${r.id}: a fresh critic found it not true yet: ${one.why}`, about: [r.id] })
}
})
/** what the critic is asked: the goal, each `says` rule by id, and the answer's shape. It reads; it changes nothing */
export function prompt(g: Contract, dir: string, only: Said[] = saysOf(g)): string {
const rules = only.map((r) => `- ${r.id}: ${r.says}`)
return `You are a fresh critic. You did none of this work and owe it nothing. The work is in ${dir}: read whatever you need there (its files, its renders, NOTES.md), and change nothing.\n\nThe goal, as the person said it: ${g.aim ?? nameOf(g)}\n\nFor each rule below, decide whether it is true of the work as it is on disk now. Count it true only when you have seen it hold; if you can't tell, it isn't true yet. Say why in one sentence, naming what you looked at.\n\n${rules.join("\n")}\n\nAnswer last with one JSON object and nothing after it: {"rules": {"ID": {"pass": true, "why": "..."}}}`
}
/** the verdict: the object around the text's last "rules" key (a critic may think aloud, or quote the shape, first) */
export function lastVerdict(text: string): Verdict | null {
const key = text.lastIndexOf('"rules"')
if (key < 0) return null
for (let open = text.lastIndexOf("{", key); open >= 0; open = text.lastIndexOf("{", open - 1)) {
let depth = 0
let inStr = false
for (let i = open; i < text.length; i++) {
const ch = text[i]
if (inStr) {
if (ch === "\\") i++
else if (ch === '"') inStr = false
continue
}
if (ch === '"') inStr = true
else if (ch === "{") depth++
else if (ch === "}" && --depth === 0) {
try {
const v = JSON.parse(text.slice(open, i + 1))
if (v && typeof v.rules === "object") return v
} catch {}
break
}
}
}
return null
}
/** where a rule is judged, chosen here and never by the agent (Shane, 12-03): a rule with a piece to watch or hear
* (a file it names, or the videos under out/) by Clef-Omni; any other by a fresh session of the agent this project
* runs on, which the host that started the agent offers as RAEA_JUDGE_URL (raea cloud's box, critic.ts; the raea app) */
const criticUrl = () => process.env.RAEA_JUDGE_URL || null
export const NO_CRITIC = "it's judged by a fresh session of the agent this project runs on, which only an agent session the raea app or raea cloud started has: it's judged when that session checks the goal"
/** whether every rule here can be judged in this session */
export function hasCritic(dir: string, rules: Said[]): boolean {
return !!criticUrl() || rules.every((r) => piecesOf(r, dir).length > 0)
}
const PIECE = /[\w@./-]+\.(?:mp4|mov|webm|m4v|png|jpe?g|webp|wav|mp3|m4a)\b/gi
const VIDEO = /\.(?:mp4|mov|webm|m4v)$/i
/** the videos under out/, newest first */
function made(dir: string): string[] {
const out: { f: string; at: number }[] = []
const walk = (d: string) => {
for (const e of existsSync(d) ? readdirSync(d, { withFileTypes: true }) : []) {
const f = path.join(d, e.name)
if (e.isDirectory()) walk(f)
else if (VIDEO.test(e.name)) out.push({ f, at: statSync(f).mtimeMs })
}
}
walk(path.join(dir, "out"))
return out.sort((x, y) => y.at - x.at).map((x) => path.relative(dir, x.f))
}
/** clef-omni as the critic (`raea ask`, paid as ask is): it watches and hears a piece, and reads no folder. A rule is
* asked of the files it names, in its "from A s to B s" window if it has one, else of every video under out/ (the
* newest CLEF_PIECES), and passes when it's true of each; the rules about one piece go in one call */
const CLEF_PIECES = 12
/** the pieces a rule is about: the files it names that are on disk, else the newest videos under out/ */
function piecesOf(r: Said, dir: string): string[] {
const named = [...new Set(r.says.match(PIECE) ?? [])].filter((f) => existsSync(path.join(dir, f)))
return named.length ? named : made(dir).slice(0, CLEF_PIECES)
}
export function clefVerdict(g: Contract, dir: string, ask = askClef, only: Said[] = saysOf(g)): Verdict["rules"] {
const groups = new Map<string, { file: string; from?: string; to?: string; rules: Said[] }>()
const pieces = new Map<string, string[]>()
for (const r of only) {
const files = piecesOf(r, dir)
const w = /from (\d+(?:\.\d+)?) s to (?:(\d+(?:\.\d+)?) s|its end)/.exec(r.says)
pieces.set(r.id, files)
for (const file of files) {
const key = [file, w?.[1], w?.[2]].join("\u001f")
const at = groups.get(key) ?? { file, from: w?.[1], to: w?.[2], rules: [] }
at.rules.push(r)
groups.set(key, at)
}
}
const got = new Map<string, { pass: boolean; why: string }[]>()
for (const k of groups.values()) {
const answers = ask(dir, k.file, k.rules.map((r) => r.says), k.from, k.to)
k.rules.forEach((r, i) => got.set(r.id, [...(got.get(r.id) ?? []), { pass: answers[i]?.choice === "true" && !answers[i]?.problem, why: `${k.file}: ${answers[i]?.problem ?? answers[i]?.says ?? "no answer"}` }]))
}
const rules: Verdict["rules"] = {}
for (const r of only) {
const a = got.get(r.id) ?? []
const open = a.filter((x) => !x.pass)
rules[r.id] = !pieces.get(r.id)?.length
? { pass: false, why: "it names no file on disk and out/ holds no video yet, so there's nothing to watch or hear" }
: { pass: !open.length, why: (open.length ? open : a).map((x) => x.why).join("; ") }
}
return rules
}
type Answer = { choice?: string; says?: string; problem?: string | null }
function askClef(dir: string, file: string, says: string[], from?: string, to?: string): Answer[] {
const r = spawnSync(RAEA, ["ask", file, ...says, "--choose", "true,false", "--json", ...(from ? ["--from", from] : []), ...(to ? ["--to", to] : [])], { cwd: dir, encoding: "utf8", maxBuffer: 1 << 26 })
if (r.error) throw new Error(`couldn't run raea ask: ${r.error.message}`)
const rows = String(r.stdout ?? "").split("\n").flatMap((l) => { try { const o = JSON.parse(l); return o.answer ? [o as Answer] : [] } catch { return [] } })
if (rows.length !== says.length) throw new Error(`raea ask answered ${rows.length} of ${says.length} about ${file}: ${String(r.stderr ?? "").trim().slice(-300) || String(r.stdout ?? "").trim().slice(-300)}`)
return rows
}
/** the goal's `says` rules judged (`raea goal check` asks this itself; `raea goal judge` too): each where it's judged
* (criticUrl above), its verdict kept at review/judge/NAME.json, stamped with when it was asked (so work changed while
* it judged counts as changed after) */
export async function judge(g: Contract, dir: string, o: { ask?: typeof askClef; agent?: (cwd: string, prompt: string) => Promise<string> } = {}): Promise<Verdict> {
const all = saysOf(g)
if (!all.length) throw new Error(`goal ${nameOf(g)} has no \`says\` rules; its \`run\` and \`file\` rules are held by raea goal check`)
const asked = Math.floor(Date.now() / 1000)
const watched = all.filter((r) => piecesOf(r, dir).length > 0)
const read = all.filter((r) => !watched.includes(r))
const rules: Verdict["rules"] = watched.length ? clefVerdict(g, dir, o.ask ?? askClef, watched) : {}
if (read.length) {
const agent = o.agent ?? askAgent
const words = await agent(dir, prompt(g, dir, read))
const v = lastVerdict(words)
if (!v) throw new Error(`the critic gave no verdict: ${words.slice(-300).trim()}`)
for (const r of read) rules[r.id] = v.rules?.[r.id] ?? { pass: false, why: "the critic didn't answer this rule" }
}
return keep(g, dir, { at: asked, by: [watched.length ? "clef" : "", read.length ? "agent" : ""].filter(Boolean).join("+"), goal: g.aim ?? nameOf(g), rules })
}
/** a fresh session of this project's own agent, through the host that started it (RAEA_JUDGE_URL): what it says */
async function askAgent(cwd: string, p: string): Promise<string> {
const url = criticUrl()
if (!url) throw new Error(NO_CRITIC)
const r = await fetch(url, { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${process.env.RAEA_JUDGE_TOKEN ?? ""}` }, body: JSON.stringify({ cwd, prompt: p }), signal: AbortSignal.timeout(15 * 60_000) })
const j = (await r.json().catch(() => ({}))) as { text?: string; error?: string }
if (!r.ok || typeof j.text !== "string") throw new Error(j.error ?? `the critic answered ${r.status}`)
return j.text
}
function keep(g: Contract, dir: string, out: Verdict): Verdict {
const file = path.join(dir, verdictPath(g))
mkdirSync(path.dirname(file), { recursive: true })
writeFileSync(file, `${JSON.stringify(out, null, 2)}\n`)
return out
}
export const hasVerdict = (dir: string, g: Contract) => existsSync(path.join(dir, verdictPath(g)))
+11 -5
View File
@@ -3,18 +3,18 @@ import type { Check } from "raea/check"
import type { PackName } from "../contract.ts"
import captions from "./captions.ts"
import { countPack, ctaPack, neverPack, openPack, quotesPack, sayOncePack, sayPack, shapePack } from "./cut.ts"
import { floorPack } from "./floor.ts"
import { floorPack, stillsPack } from "./floor.ts"
import frames from "./frames.ts"
import montage from "./montage.ts"
import { runPack } from "./goal.ts"
import { deliverablesPack } from "./job.ts"
import { runPack, saysPack } from "./goal.ts"
import { criticPack, deliverablesPack, notesPack, recordPack } from "./job.ts"
import { seenPack, surprisePack } from "./look.ts"
import naming from "./naming.ts"
import place from "./place.ts"
import { playablePack } from "./playable.ts"
import sizes, { allSizes } from "./sizes.ts"
import sound from "./sound.ts"
import reading from "./reading.ts"
import render from "./render.ts"
import { airgapsPack, hookPack } from "./hook.ts"
import voice from "./voice.ts"
import words from "./words.ts"
@@ -31,6 +31,8 @@ export const PACK_CHECKS: Record<PackName, Check[]> = {
frames: [frames],
montage: [montage],
place: [place],
seen: [seenPack],
surprise: [surprisePack],
naming: [naming],
sizes: [sizes, allSizes],
quotes: [quotesPack],
@@ -41,8 +43,12 @@ export const PACK_CHECKS: Record<PackName, Check[]> = {
cta: [ctaPack],
shape: [shapePack],
run: [runPack],
says: [saysPack],
deliverables: [deliverablesPack],
critic: [criticPack],
record: [recordPack],
notes: [notesPack],
floor: [floorPack],
stills: [stillsPack],
playable: [playablePack],
render: [render],
}
+61 -3
View File
@@ -1,12 +1,23 @@
// The deliverables pack: every file the contract names (its own list, else its kind's: a cut's cuts, a goal's `file`
// rules, a kit's GLBs, LODs, thumbnails, lineup and kit.json, a shot's still or move, a scene's three stills).
import { existsSync, readdirSync, statSync } from "node:fs"
// The job packs: what must exist, and for a scene, kit or shot job the record of its renders and its critic's rounds.
// deliverables every file the contract names (its own list, else its kind's: a cut's cuts, a goal's `file` rules, a
// kit's GLBs, LODs, thumbnails, lineup and kit.json, a shot's still or move, a scene's three stills)
// notes NOTES.md with a "What the skill got wrong" section (scene, kit and shot jobs)
// record every composition the plan names rendered or checked clean since it last changed, and its LODs held
// critic a fresh critic's round newer than the newest deliverable, on the kind's rubric, its blocking
// defects fixed or answered in NOTES.md, and the make questions asked of its sheets
// record and critic read raea's record and the judge's rounds through `raea goal gates --json`.
import { spawnSync } from "node:child_process"
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs"
import path from "node:path"
import { check, found } from "raea/check"
import type { Contract } from "../contract.ts"
import type { Job } from "../facts.ts"
import { RAEA } from "../media.ts"
import { deliverables as cutFiles } from "./cut.ts"
import { deliverables as playableFiles } from "./playable.ts"
import { unregistered } from "../project.ts"
export const SKILL_HEADING = "What the skill got wrong"
/** what must exist when the goal is done, relative to the brief's folder: its own list, else its kind's; and each of
* its `file` rules */
@@ -51,3 +62,50 @@ export const deliverablesPack = check<Job>({ id: "deliverables", text: "every de
if (typeof a === "string") found({ says: `missing: ${a}`, about: [want] })
}
})
/** MK43: every file in the folder that uses raea's SDK is reached from brief.ts (or taste.ts), so it's compiled and
* run; one nothing reaches is said at every moment, an error once the work is handed over or called done */
export const registeredPack = check<Job>({ id: "registered", text: "every raea file is reached from brief.ts", over: "job", at: ["edit", "render", "publish", "done"] }, async (j) => {
if (j.project.problem) {
found({ says: `brief.ts doesn't run: ${j.project.problem}`, level: "error" })
return
}
if (!j.project.brief) return
const loose = unregistered(j.project)
const level = j.moment === "publish" || j.moment === "done" ? "error" : "warn"
for (const f of loose)
found({ says: `${f} uses raea but nothing in brief.ts reaches it, so it never runs`, about: [f], level, fix: "import it from a file the brief reaches, name its path in the brief (a deliverable, a shot's composition, a rule), or delete it" })
})
export const notesPack = check<Job>({ id: "notes", text: "NOTES.md, with what the skill got wrong", over: "job", at: ["done"] }, async (j) => {
const p = path.join(j.root, "NOTES.md")
const t = existsSync(p) ? readFileSync(p, "utf8") : ""
if (!t.toLowerCase().includes(SKILL_HEADING.toLowerCase())) found({ says: `NOTES.md has no "${SKILL_HEADING}" section: one line per thing that cost time, and what the guide got wrong for this job` })
})
type Gate = { gate: string; of?: string; clear: boolean; says: string }
type Gates = { gates: Gate[]; short?: string[]; error?: string }
/** raea's record and critic gates for a scene, kit or shot job (`raea goal gates --json` in the brief's folder) */
function gatesOf(j: Job): Gates {
const r = spawnSync(RAEA, ["goal", "gates", "--json"], { cwd: j.root, encoding: "utf8", maxBuffer: 1 << 24 })
try {
return JSON.parse(String(r.stdout)) as Gates
} catch {
throw new Error(`raea goal gates said no JSON: ${String(r.stderr || r.stdout).trim().slice(-200)}`)
}
}
const RECORD = new Set(["checks", "lod"])
function gatePack(id: "record" | "critic", text: string, mine: (g: Gate) => boolean) {
return check<Job>({ id, text, over: "job", at: ["done"] }, async (j) => {
if (!["scene", "kit", "shot"].includes(j.contract?.kind ?? "")) return
const g = gatesOf(j)
if (g.error) throw new Error(g.error)
// out of rounds or stalled: delivered with what's still open, said as warnings
const short = (g.short ?? []).length > 0
for (const x of g.gates.filter((x) => mine(x) && !x.clear)) found({ says: `${x.gate}${x.of ? ` ${x.of}` : ""}: ${x.says}`, level: short ? "warn" : "error", about: x.of ? [x.of] : [] })
if (short && id === "critic") found({ level: "warn", says: (g.short ?? []).join("; ") })
})
}
export const recordPack = gatePack("record", "every composition the plan names rendered or checked clean since it last changed", (g) => RECORD.has(g.gate))
export const criticPack = gatePack("critic", "the critic's rounds: a pass newer than the work, its blocking defects fixed or answered", (g) => !RECORD.has(g.gate))
+86
View File
@@ -0,0 +1,86 @@
// The looking packs (11-29, Shane on Dutch: "the agent clearly didnt see it. we should be encouraging the agent to look
// 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. 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 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) => {
if (!looked(f)) return
const s = f.seen()
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 [] } })
}
+1 -1
View File
@@ -17,7 +17,7 @@ import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node
import { tmpdir } from "node:os"
import path from "node:path"
import { check, found } from "raea/check"
import type { CutBeat as Beat } from "raea/brief.gen"
import type { Beat } from "raea/brief.gen"
import type { FileFacts } from "../facts.ts"
import { type Faces, Unmet } from "../media.ts"
import { cutOf } from "./cut.ts"
-93
View File
@@ -1,93 +0,0 @@
// Numbers said in words, as a caption writes them: 12-05, Dutch run 9, "it's twenty four seven" was captioned "24-7"
// and the captions check called "247" a word that isn't said. Runs of number words become one word in digits, each
// number its own ("twenty four seven" is 24 and 7), so a caption in digits and one in words both match what's heard.
import type { Word } from "../media.ts"
const UNITS: Record<string, number> = { zero: 0, one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9, ten: 10, eleven: 11, twelve: 12, thirteen: 13, fourteen: 14, fifteen: 15, sixteen: 16, seventeen: 17, eighteen: 18, nineteen: 19 }
const TENS: Record<string, number> = { twenty: 20, thirty: 30, forty: 40, fifty: 50, sixty: 60, seventy: 70, eighty: 80, ninety: 90 }
const SCALES: Record<string, number> = { hundred: 100, thousand: 1000, million: 1_000_000 }
const bare = (s: string) => s.toLowerCase().replace(/[^a-z]/g, "")
/** a word that is a number or part of one ("twenty-four" counts as two) */
const parts = (s: string) => s.toLowerCase().split(/[-\s]+/).map((p) => p.replace(/[^a-z]/g, "")).filter(Boolean)
const isNum = (p: string) => p in UNITS || p in TENS || p in SCALES
/** the numbers a run of number words says, each in digits: ["twenty","four","seven"] -> ["24","7"] */
export function numbersOf(ps: string[]): string[] {
const out: string[] = []
let total = 0
let cur = 0
let last: "unit" | "teen" | "tens" | "scale" | null = null
const close = () => {
if (last !== null) out.push(String(total + cur))
total = 0
cur = 0
last = null
}
for (const p of ps) {
if (p in SCALES) {
const s = SCALES[p]
if (s === 100) cur = (cur || 1) * 100
else {
total += (cur || 1) * s
cur = 0
}
last = "scale"
} else if (p in TENS) {
// "twenty" after a unit or tens starts a new number; after a scale it adds ("one hundred twenty")
if (last === "unit" || last === "teen" || last === "tens" || (cur % 100 !== 0 && last !== "scale")) close()
cur += TENS[p]
last = "tens"
} else {
const v = UNITS[p]
// a unit joins a bare tens ("twenty four") or a scale ("hundred one"); otherwise it's its own number
const joins = (last === "tens" && cur % 10 === 0) || last === "scale"
if (!joins && last !== null) close()
cur += v
last = v >= 10 ? "teen" : "unit"
}
}
close()
return out
}
/** `heard` with each run of number words ("a hundred and forty nine", "twenty four seven") one word in digits */
/** "$60" as it's said, "60 dollars" (12-05, Dutch run 10: the transcript wrote "sixty dollars" as "$60", a caption wrote
* it out, and "dollars" read as a word the host never said) */
const money = (w: Word): Word => {
const m = w.text.match(/^\$(\d[\d,]*(?:\.\d+)?)([^\d]*)$/)
return m ? { ...w, text: `${m[1]} dollars${m[2]}` } : w
}
export function asDigits(heard: Word[]): Word[] {
heard = heard.map(money)
const out: Word[] = []
for (let i = 0; i < heard.length; ) {
const run: Word[] = []
let j = i
for (; j < heard.length; j++) {
const ps = parts(heard[j].text)
const joiner = run.length > 0 && (bare(heard[j].text) === "and" || bare(heard[j].text) === "a") && j + 1 < heard.length && parts(heard[j + 1].text).every(isNum)
const lead = run.length === 0 && bare(heard[j].text) === "a" && j + 1 < heard.length && parts(heard[j + 1].text).some((p) => p in SCALES)
if (ps.length && ps.every(isNum)) run.push(heard[j])
else if (joiner || lead) run.push({ ...heard[j], text: "" })
else break
}
if (!run.some((w) => parts(w.text).length)) {
out.push(heard[i])
i++
continue
}
const ps = run.flatMap((w) => parts(w.text))
// "a" before a scale is one ("a hundred")
const text = numbersOf(ps).join(" ")
const tail = heard[j - 1]?.text.match(/[^A-Za-z0-9]+$/)?.[0] ?? ""
out.push({ ...run[0], text: `${text}${tail}`, end: run[run.length - 1].end })
i = j
}
return out
}
/** a caption's text with its numbers in words written in digits, as asDigits writes what's heard ("One more" -> "1 more") */
export const digitsIn = (text: string): string =>
asDigits(text.split(/\s+/).filter(Boolean).map((t, i) => ({ text: t, start: i, end: i + 1 }))).map((w) => w.text).join(" ")
+2 -6
View File
@@ -17,7 +17,6 @@ import path from "node:path"
import { check, found } from "raea/check"
import type { FileFacts } from "../facts.ts"
import { RATE } from "../media.ts"
import { quote } from "../text.ts"
/** a frame's scene, as the farm reads it (deploy/modal/farm_scene.py), in the pixels of the frame it was sent */
/** the scene reader's reading of a frame's text: [x, y, w, h, text, score] a line (the captions pack) */
@@ -256,17 +255,14 @@ export function textOver(manifest: any, scenes: Scene[], rate: number): Finding[
const best = places(ks, W, H, [on.box[2], on.box[3]], 1)[0]
const under = [...new Set(on.frames.flatMap((i) => (scenes[i] ? thingsUnder(scenes[i]!, on.box, onFrame.get(i) ?? []) : [])))]
const what = under.length ? under.join(", ") : "what the shot shows"
const q = `“${quote(on.text, 40)}”${on.lines > 1 ? ` (and the ${on.lines - 1} line${on.lines > 2 ? "s" : ""} under it)` : ""}`
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) {
// 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)
// 12-05, Shane's rule list for a cut: text over a face, a sign or the app's buttons. Over anything else the
// detector names (a dog, a suitcase, a coat) it's a warning with the place said: run 12 held "covers a suitcase"
// as an error
const hard = under.some((u) => u === "a face" || u.startsWith("words in the shot"))
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` })
+10 -28
View File
@@ -1,7 +1,7 @@
// The reading pack (11-30, Shane: "the words on screen relative to duration ... if a wordy CTA or component or scene is
// meant to be fully read or if it just adds glossable content or context, and if it's on screen long enough to be
// read"). From the render's own texts when its manifest is here (exactly what it drew, five times a second, no farm
// call), else the scene reader's (the farm's texts, two frames a second), every block of text that isn't a caption (captions are read while they're heard: the captions pack holds them) is timed against the words it holds.
// read"). From the scene reader's text (the farm's texts, two frames a second), every block of text that isn't a
// caption (captions are read while they're heard: the captions pack holds them) is timed against the words it holds.
//
// time to read: READ_BASE s to find it, then WPS words a second (a feed viewer's skim of short ad text; subtitle
// standards sit near 3 words a second). A block up for under its time is a warning; under SHORT of it an error,
@@ -12,8 +12,7 @@
import { check, found } from "raea/check"
import type { FileFacts } from "../facts.ts"
import type { Word } from "../media.ts"
import { captionsOf, fit, type Frame, framesOfManifest, LEAST, letters, type Read, similar } from "./captions.ts"
import { quote } from "../text.ts"
import { captionsOf, fit, type Frame, LEAST, letters, type Read, similar } from "./captions.ts"
export type Block = { text: string; words: number; from: number; to: number; size?: number }
export type Finding = { level: "error" | "warn"; at: number; says: string; block: Block }
@@ -97,41 +96,24 @@ export function reading(blocks: Block[]): Finding[] {
const up = b.to - b.from
const n = need(b.words)
if (up >= n) continue
const said = quote(b.text, 67)
const quote = b.text.length > 70 ? `${b.text.slice(0, 67)}...` : b.text
const load = `${b.words} words up ${up.toFixed(1)} s (${(b.words / up).toFixed(1)} words a second; reading takes about ${n.toFixed(1)} s at ${WPS} a second)`
if (b.words >= GLOSS || CLOCK.test(b.text) || (b.size !== undefined && b.size < SMALL)) out.push({ level: "warn", at: b.from, block: b, says: `"${said}" at ${b.from.toFixed(1)} s: ${load}. That's texture, not reading (a screen, a page, fine print): fine if it's shown for context, but if a viewer is meant to read it, cut it to the words that matter and hold them ${need(Math.min(b.words, 8)).toFixed(1)} s or more` })
else out.push({ level: up < n * SHORT ? "error" : "warn", at: b.from, block: b, says: `"${said}" at ${b.from.toFixed(1)} s: ${load}. Hold it ${(n - up).toFixed(1)} s longer, or say it in fewer words` })
if (b.words >= GLOSS || CLOCK.test(b.text) || (b.size !== undefined && b.size < SMALL)) out.push({ level: "warn", at: b.from, block: b, says: `"${quote}" at ${b.from.toFixed(1)} s: ${load}. That's texture, not reading (a screen, a page, fine print): fine if it's shown for context, but if a viewer is meant to read it, cut it to the words that matter and hold them ${need(Math.min(b.words, 8)).toFixed(1)} s or more` })
else out.push({ level: up < n * SHORT ? "error" : "warn", at: b.from, block: b, says: `"${quote}" at ${b.from.toFixed(1)} s: ${load}. Hold it ${(n - up).toFixed(1)} s longer, or say it in fewer words` })
}
return out
}
/** a render manifest's texts as `framesOfManifest` steps them, each a line as tall as one of its lines: a text set on
* three lines has one ink box over all three, and its size (fine print or a headline) is a line's, not the box's */
export function readingFrames(manifest: unknown): { frames: Frame[]; rate: number } | null {
const own = framesOfManifest(manifest)
const m = manifest as { fps?: number; frames?: { text?: { text?: string; ink?: number[]; box?: number[]; opacity?: number; lines?: number }[] }[] } | null
if (!own || !m?.frames) return null
const step = Math.max(1, Math.round((Number(m.fps) || 30) / own.rate))
const frames = own.frames.map((fr, k) => {
const texts = (m.frames![k * step]?.text ?? []).filter((t) => { const b = t.ink ?? t.box; return !!b && b.length >= 4 && !!String(t.text ?? "").trim() && (t.opacity ?? 1) > 0.2 }) // framesOfManifest's own test, so each line is its text
return { h: fr.h, lines: fr.lines.map((l, i) => [l[0], l[1], l[2], l[3] / Math.max(1, Number(texts[i]?.lines) || 1), l[4], l[5]] as Read) }
})
return { frames, rate: own.rate }
}
export default check<FileFacts>(
{ id: "reading", text: "every block of text on screen that isn't a caption is up long enough to read (half a second, then 3 words a second), or is plainly texture", over: "file", at: ["render", "publish", "done"], needs: ["words", "scene"] },
async (f) => {
if (!f.made || f.kind !== "video") return
// the render's own texts when its manifest is here (no farm call, and never the footage's own text), else the export
// read frame by frame; captions are found in the same frames the captions pack reads
const own = f.manifest ? readingFrames(f.manifest) : null
const sc = own ? null : await f.scene()
const frames: Frame[] = own ? own.frames : sc!.scenes.map((s) => ({ h: s?.h ?? 1, lines: (s?.texts ?? []) as Read[] }))
const sc = await f.scene()
const frames: Frame[] = sc.scenes.map((s) => ({ h: s?.h ?? 1, lines: (s?.texts ?? []) as Read[] }))
if (!frames.some((x) => x.lines.length)) return
const rate = own ? own.rate : sc!.rate || 2
const rate = sc.rate || 2
const heard = await f.words()
const caps = captionsOf(own ? framesOfManifest(f.manifest)!.frames : frames, rate, heard)
const caps = captionsOf(frames, rate, heard)
const isCaption = (t: number, key: string) => caps.some((c) => t >= c.from - 0.01 && t < c.to && (similar(c.key, key) || c.key.includes(key)))
for (const x of reading(blocksOf(frames, rate, isCaption, heard))) found({ level: x.level, says: x.says, seconds: x.at })
},
-34
View File
@@ -1,34 +0,0 @@
// The render pack: what the render itself found as it drew (its manifest's `findings`: a missing font, clipping, a part
// out of place or under its planned detail, light that jumps, a frame drawn empty), held to the deliverable it made.
// Read, never measured again: the render's end checks saw every frame as it was drawn, which nothing after it can do
// as cheaply (12-04, Shane: "fix how every agent checks its work": one check, after the render, everything else
// reusing it). One line a kind of finding: its first, and how many more like it.
import { check, found } from "raea/check"
import type { FileFacts } from "../facts.ts"
import { bookkeeping } from "./naming.ts"
type Said = { check?: string; level?: string; says?: string; fix?: string | null; frames?: [number, number] | null }
/** what the floor pack measures again on the video itself (the app's UI zones): read there, not twice */
const MEASURED_AGAIN = new Set(["safe-area"])
/** the manifest's findings, one a kind: the first of each (by check and level), with how many more there were */
export function renderFindings(manifest: unknown): Said[] {
const all = ((manifest as { findings?: Said[] } | null)?.findings ?? []).filter((x) => x && (x.level === "error" || x.level === "warn"))
const firsts = new Map<string, Said & { more: number }>()
for (const x of all) {
const k = x.check ?? "render"
if (MEASURED_AGAIN.has(k)) continue
const key = `${k} ${x.level}`
const had = firsts.get(key)
if (had) had.more++
else firsts.set(key, { ...x, more: 0 })
}
return [...firsts.values()].map((x) => ({ ...x, says: `${x.check ?? "render"}: ${x.says ?? ""}${x.more ? ` (and ${x.more} more like it)` : ""}` }))
}
export default check<FileFacts>({ id: "render", text: "nothing the render's own end checks found", over: "file", at: ["render", "publish", "done"] }, async (f) => {
if (!f.made || bookkeeping(f.path) || !f.manifest) return
for (const x of renderFindings(f.manifest))
found({ level: x.level as "error" | "warn", says: x.says ?? "", fix: x.fix ?? undefined, frames: x.frames ?? undefined })
})
+1 -1
View File
@@ -15,7 +15,7 @@ import { adOf, bookkeeping, sizeOf } from "./naming.ts"
* 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 | null; height?: number | null }): string | null {
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
+3 -16
View File
@@ -29,8 +29,6 @@ const GAP_LEAST = 8
const FLOOR_Q = 0.1
/** how far either side of a cut point a gap is looked for (s) */
const NEAR = 0.4
/** sound this close to a word (s) at a cut is the word's, cut; further off it's another sound */
const WORD_NEAR = 0.6
/** lines this far apart (dB) are an error, a warning */
const LEVEL_ERROR = 6
const LEVEL_WARN = 4
@@ -104,9 +102,6 @@ export function nearestGap(l: Levels, t: number, ref: number, words: Word[], ins
return null
}
/** the longest a spoken word runs (s): a drawn-out "sooo" is under it */
export const WORD_MAX = 2.5
/** how close (s) a cut is to a boundary between two words that run together to count as on it (word timings are good
* to about 30 ms) */
const SEAM = 0.03
@@ -139,9 +134,7 @@ export function editPoints(c: Clip, fps: number, words: Word[], l: Levels): Find
out.push({ level: "warn", kind: "edit-on-sound", at: cutAt, says: `${where} is between “${seam.before}” and “${seam.after}” with no pause: a tight cut. Look at it on the waveform, or move it to a pause if one is near` })
continue
}
// a "word" longer than WORD_MAX is a transcriber's timing gone wrong, not a word (12-04, Elfster run 5: "secret"
// timed 143.28-166.96 s, and a cut 15 s into it was called a word cut in two): the sound there is read instead
const word = words.find((w) => w.start + 0.02 < t && w.end - 0.02 > t && w.end - w.start <= WORD_MAX)
const word = words.find((w) => w.start + 0.02 < t && w.end - 0.02 > t)
const gap = nearestGap(l, t, ref, words, inside, inside === 1 ? tout - 0.1 : tin + 0.1)
const ms = (x: number) => `${x >= t ? "+" : ""}${Math.round((x - t) * 1000)} ms`
const bound = gap === null ? seams(words).filter((x) => Math.abs(x.at - t) <= NEAR && (inside === 1 ? x.at < tout - 0.1 : x.at > tin + 0.1)).sort((p, q) => Math.abs(p.at - t) - Math.abs(q.at - t))[0] : undefined
@@ -159,10 +152,7 @@ export function editPoints(c: Clip, fps: number, words: Word[], l: Levels): Find
const here = edge === "in" ? peak(l, t, t + 0.01) : peak(l, t - 0.01, t)
if (here >= Math.max(ref - ON_SOUND, pct(l.db, FLOOR_Q) + GAP_FLOOR + 2)) {
const near = words.reduce<Word | null>((b, w) => (Math.min(Math.abs(w.start - t), Math.abs(w.end - t)) < (b ? Math.min(Math.abs(b.start - t), Math.abs(b.end - t)) : 9) ? w : b), null)
// sound with no word near it isn't a word cut (12-05, run 12: a cut "5397 ms from" the nearest word was an
// error): a laugh, a noise, or speech the transcript missed, for the ear: a warning
const off = near ? Math.min(Math.abs(near.start - t), Math.abs(near.end - t)) : Infinity
out.push({ level: off <= WORD_NEAR ? "error" : "warn", kind: "edit-on-sound", at: cutAt, says: `${where} lands on sound ${Math.max(0, ref - here).toFixed(0)} dB under the speech${near ? `, ${Math.round(Math.min(Math.abs(near.start - t), Math.abs(near.end - t)) * 1000)} ms from “${near.text}”` : ""}: the word's ${edge === "in" ? "first sound" : "tail"} is cut. ${move[0].toUpperCase()}${move.slice(1)}` })
out.push({ level: "error", kind: "edit-on-sound", at: cutAt, says: `${where} lands on sound ${Math.max(0, ref - here).toFixed(0)} dB under the speech${near ? `, ${Math.round(Math.min(Math.abs(near.start - t), Math.abs(near.end - t)) * 1000)} ms from “${near.text}”` : ""}: the word's ${edge === "in" ? "first sound" : "tail"} is cut. ${move[0].toUpperCase()}${move.slice(1)}` })
}
}
return out
@@ -227,10 +217,7 @@ export async function soundOf(f: FileFacts): Promise<{ findings: Finding[]; voic
const words = await f.takeWords(file)
const l = f.levels(c.at - NEAR - 0.1, c.at + dur + NEAR + 0.1, file)
out.push(...editPoints(c, fps, words, l))
// a line is a clip a word is said in: one with none, or only a transcriber's broken timing (a "word" 90 s long,
// 12-05 run 12), is a pause or a reaction, never "a line 51 dB under the others"
const said = words.filter((w) => w.end - w.start <= WORD_MAX && w.end > c.at && w.start < c.at + dur)
if (said.length) heard.push({ clip: c, kind, level: speechLevel(l, c.at, c.at + dur, said) + (c.gainDb ?? 0) })
heard.push({ clip: c, kind, level: speechLevel(l, c.at, c.at + dur, words) + (c.gainDb ?? 0) })
} else {
const l = f.levels(c.at, c.at + Math.min(dur, kind === "sfx" ? 2 : 20), file)
const level = kind === "sfx" ? pct(l.db, 0.98) : pct(l.db.filter((x) => x > -70), 0.5)
+35
View File
@@ -0,0 +1,35 @@
// The taste pack (docs/goal.feature MK47): every rule a project registers runs inside the loop. The person's, the
// workspace's and the project's taste lines (with their checks: raea's forms, raea's checks by name, a project's own
// .ts check such as a story check) and a person's signed asks are run by `raea check`, the instrument, over each
// composition's newest render; their findings become the goal check's, so none runs only when an agent remembers to.
// What needs a render that isn't there waits, and says so; it never fails the goal.
import { spawnSync } from "node:child_process"
import { check, found } from "raea/check"
import type { Job } from "../facts.ts"
import { RAEA, Unmet } from "../media.ts"
type Said = { check: string; level: "error" | "warn" | "note"; says: string; fix?: string | null; by?: string; about?: { name?: string }[] }
type Report = { unread?: Said[]; compositions?: { file: string; composition?: string; findings: Said[]; waits: { rule: string; for: string }[] }[]; asks?: unknown }
/** `raea check ROOT --no-render --json`, read; null when the instrument couldn't run */
export function tasteReport(root: string): Report | null {
const r = spawnSync(RAEA, ["check", root, "--no-render", "--json"], { cwd: root, encoding: "utf8", maxBuffer: 1 << 26, env: { ...process.env, RAEA_RECORD: "off" } })
const text = String(r.stdout ?? "")
const at = text.indexOf("{")
if (at < 0) return null
try {
return JSON.parse(text.slice(at)) as Report
} catch {
return null
}
}
export const tastePack = check<Job>({ id: "taste", text: "every taste line and signed ask the project is held to", over: "job", at: ["publish", "done"] }, async (j) => {
const r = tasteReport(j.root)
if (!r) throw new Unmet("raea check didn't answer here, so the taste lines wait")
for (const u of r.unread ?? []) found({ says: u.says, level: u.level })
for (const c of r.compositions ?? []) {
// raea's own floor is the floor and stills packs' already; here, only what the taste lines and asks found
for (const f of c.findings.filter((x) => x.by !== "raea")) found({ says: `${f.check}: ${f.says}`, level: f.level, about: [c.file], ...(f.fix ? { fix: f.fix } : {}) })
}
})
+1 -2
View File
@@ -11,7 +11,6 @@
import { check, found } from "raea/check"
import type { FileFacts } from "../facts.ts"
import type { Word } from "../media.ts"
import { quote } from "../text.ts"
export type Finding = { level: "error" | "warn"; kind: "buried" | "quiet"; at: number; says: string }
@@ -81,7 +80,7 @@ export function voice(db: number[], heard: Word[]): Finding[] {
const under = typical - d
if (under < QUIET_WARN || l.length < 2) continue
const text = l.map((w) => w.text).join(" ")
out.push({ level: under >= QUIET_ERROR ? "error" : "warn", kind: "quiet", at: l[0].start, says: `"${quote(text, 57)}" at ${l[0].start.toFixed(1)} s is ${under.toFixed(1)} dB quieter than the other lines: lift it about ${under.toFixed(0)} dB so it's heard like the rest` })
out.push({ level: under >= QUIET_ERROR ? "error" : "warn", kind: "quiet", at: l[0].start, says: `"${text.length > 60 ? `${text.slice(0, 57)}...` : text}" at ${l[0].start.toFixed(1)} s is ${under.toFixed(1)} dB quieter than the other lines: lift it about ${under.toFixed(0)} dB so it's heard like the rest` })
}
return out.sort((a, b) => a.at - b.at)
}
+2
View File
@@ -5,6 +5,7 @@
// crossfades on audio that make it so you can't hear it, and cuts where it will cut early over someone speaking").
// With no lines beside it, only the fades and the edges are held.
import { existsSync, readFileSync } from "node:fs"
import path from "node:path"
import { check, found } from "raea/check"
import type { FileFacts } from "../facts.ts"
import { stem, type Word } from "../media.ts"
@@ -129,5 +130,6 @@ export default check<FileFacts>(
const l = f.levels()
const out = [...(lines ? compare(readFileSync(lines, "utf8"), heard) : []), ...fades(l.db, heard, f.seconds ?? heard[heard.length - 1].end)]
for (const x of out.sort((a, b) => (a.at ?? 0) - (b.at ?? 0))) found({ level: x.level, says: x.says, seconds: x.at ?? undefined })
if (!lines && f.moment !== "edit") found({ level: "note", says: `no ${path.basename(stem(f.abs))}.lines.txt beside it: write the words this cut should say there, in order, and every one is held to what's heard` })
},
)
+71 -79
View File
@@ -1,81 +1,41 @@
// `raea check` (docs/check.feature): the one check. Every rule each goal of brief.ts holds at one of four moments, on
// raea's own engine (raea's Rust runs this file with Node's core) or under node on a box. A brief's `goal` is one goal
// or several in order (a workflow): each is checked alone, and the report says each one's verdict and the whole's.
// `raea goal` (docs/goal.feature): every rule each goal of brief.ts is held to, run at one of four moments, on raea's
// own engine (raea's Rust runs this file with Node's core) or under node on a box. A brief's `goal` is one goal or
// several in order (a workflow): each is checked alone, and the report says each one's verdict and the whole's.
//
// raea check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--manifest M] [--json]
// raea goal check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--manifest M] [--json]
// the project is the folder with brief.ts (from FILE's folder or this one, upwards); its goals are brief.ts's
// `goal`, and with none, the floor. The files are the ones named, else (publish, done) every deliverable and
// every video or still made under out/. Each check whose moments include --at (done by default) runs: a file
// check on each file, a job check once. A file's check after its render is kept beside it (FILE.check.json) and
// publish and done read it while it's fresh, never running it again. One line a rule a file. Writes
// review/goal.json and prints each finding. Exit 1 on an error, 2 when it can't run (brief.ts doesn't load). A
// check that needs what this machine hasn't (a transcriber) waits, and says what for; it holds nothing.
// `goal`, and with none, the floor (every made video looked at, its faces whole and its text big enough). The
// files are the ones named, else (publish, done) every deliverable and every video or still made under out/.
// Each check whose moments include --at (done by default) runs: a file check on each file, a job check once.
// Every project is also held to `registered` (every raea file reached from brief.ts). Writes review/goal.json
// (and FILE.check.json beside each file named) and prints each finding. Exit 1 on an error, 2 when it can't run
// (brief.ts doesn't load). A check that needs what this machine hasn't (a scene reader, a transcriber) waits, and
// says what for; it holds nothing.
// raea goal tasks [DIR] [--json] | --apply EDITS.json|- the brief's plan as tasks, and edits written back (tasks.ts)
// raea goal seen FILE "WHAT" [--surprise "S s: WHAT"] what was seen of FILE as it is now, and its surprise
// raea goal judge [--goal NAME] a goal's `says` rules judged now (review/judge/); raea goal check asks it itself
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"
import path from "node:path"
import { pathToFileURL } from "node:url"
import { type Check, type Finding, type Moment, MOMENTS, runOnce, type Threw } from "raea/check"
import { type Contract, type Goals, goalsOf, momentsOf, nameOf, packsOf, unknownPacks } from "./contract.ts"
import { type Contract, type Goals, goalsOf, momentsOf, nameOf, packsOf, saysOf, unknownPacks } from "./contract.ts"
import { fileFacts, type FileFacts, type Job, kindOf, runIn } from "./facts.ts"
import * as media from "./media.ts"
import { registeredPack } from "./packs/job.ts"
import { tastePack } from "./packs/taste.ts"
import { loadProject, type Project } from "./project.ts"
import { 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"
import { tasksMain } from "./tasks.ts"
import { wellFormed } from "./text.ts"
/** the checks every project is held to once, whatever its goals: none in the loop (12-04: `registered`, how brief.ts
* imports files, failed every Dutch cut, and the taste check waits on every box; neither is a fault in the work) */
const ALWAYS: Check[] = []
/** the checks every project is held to once, whatever its goals */
const ALWAYS: Check[] = [registeredPack, tastePack]
/** the moments a deliverable's own check, run once after its render, stands for: publish and done read it, never run it again */
const REUSED: Moment[] = ["publish", "done"]
/** a deliverable's check kept beside it (FILE.check.json), while it's no older than the file or its manifest: the
* checks it ran and what they found */
export function keptCheck(abs: string): { checks: string[]; findings: Said[] } | null {
const k = `${media.stem(abs)}.check.json`
const when = (f: string) => (existsSync(f) ? statSync(f).mtimeMs : 0)
if (!existsSync(k) || when(k) < when(abs) || when(k) < when(`${media.stem(abs)}.render.json`)) return null
try {
const j = JSON.parse(readFileSync(k, "utf8")) as { checks?: string[]; findings?: Said[] }
return Array.isArray(j.checks) ? { checks: j.checks, findings: j.findings ?? [] } : null
} catch {
return null
}
}
/** one line a rule a file (12-04, round 26: 34 of one cut's errors were each caption phrase in the same UI zone; 12-05,
* run 5: an ERROR and a WARN of the same check each had a line, and a cut listed 12): of a check's findings at moments
* in the file, the most severe first one, and how many more there were; findings with no moment are distinct faults,
* said once each */
const RANK: Record<Said["level"], number> = { error: 0, warn: 1, note: 2 }
export function collapse(xs: Said[]): Said[] {
const firsts = new Map<string, { x: Said; same: number; lesser: number; to: number | null }>()
for (const x of xs) {
// a fault found at many moments (located in time) is one line; distinct faults with no moment each keep theirs
const key = `${x.goal ?? ""}\u0000${x.file ?? ""}\u0000${x.check}\u0000${x.seconds ? "" : `${x.level}\u0000${x.says}`}`
const had = firsts.get(key)
if (!had) firsts.set(key, { x, same: 0, lesser: 0, to: x.seconds?.[1] ?? null })
else {
if (RANK[x.level] < RANK[had.x.level]) {
// a worse one leads the line; what led it is counted under it
had.lesser += had.same + 1
had.same = 0
had.x = x
} else if (x.level === had.x.level) had.same++
else had.lesser++
if (x.seconds && (had.to === null || x.seconds[1] > had.to)) had.to = x.seconds[1]
}
}
return [...firsts.values()].map(({ x, same, lesser }) => {
const more = [same ? `${same} more like it${x.seconds ? ", to the same fix" : ""}` : "", lesser ? `${lesser} lesser` : ""].filter(Boolean).join("; ")
return more ? { ...x, says: `${x.says} (and ${more})` } : x
})
}
/** a finding as `raea check` reports it: its goal, its check, the file it's in, and where in it */
/** a finding as `raea goal check` reports it: its goal, its check, the file it's in, and where in it */
export type Said = { goal: string | null; check: string; level: Finding["level"]; file: string | null; seconds: [number, number] | null; says: string; fix: string | null; by: string }
/** one goal's verdict at a moment */
export type GoalVerdict = { name: string; kind: Contract["kind"] | "floor"; step: string | null; after: string[]; passed: boolean; errors: number; warnings: number; checks: string[]; files: string[] }
@@ -158,10 +118,8 @@ function planOf(goals: Contract[]): string[] {
const out = [...doctor]
for (const c of goals) {
const at = goals.length > 1 ? `${nameOf(c)}: ` : ""
out.push(...unknownPacks(c).map((k) => `${at}packs.${k}: raea has no pack of that name (raea check --json lists them)`))
out.push(...unknownPacks(c).map((k) => `${at}packs.${k}: raea has no pack of that name (raea goal check --json lists them)`))
for (const k of (c.checks ?? []) as unknown[]) if (!k || typeof (k as Check).id !== "string") out.push(`${at}checks: each is a check() imported from the project's checks/ folder`)
// nothing judges a `says` rule any more (12-04): said, so it isn't taken for checked
for (const r of c.rules ?? []) if (r.says && !r.run && !r.file) out.push(`${at}rules.${r.id}: a \`says\` rule isn't checked by anything: make it a command (\`run\`) or a file (\`file\`), or leave it to the person's review`)
}
return out
}
@@ -204,16 +162,9 @@ export async function goalCheck(o: { files?: string[]; at?: Moment; goal?: strin
const before = findings.length
const brokeBefore = broke.length
const j = job(contract, deliverables, files)
const kept = new Map(files.map((f) => [f.path, REUSED.includes(at) ? keptCheck(f.abs) : null]))
for (const c of checks) {
if (c.over === "job") keep(contract ? name : null, null, await runOnce([{ check: c, on: j }]))
else
for (const f of files) {
const k = kept.get(f.path)
// run once, after its render: what it found then stands (its own findings, at this goal)
if (k?.checks.includes(c.id)) findings.push(...k.findings.filter((x) => x.check === c.id).map((x) => ({ ...x, goal: contract ? name : null })))
else keep(contract ? name : null, f, await runOnce([{ check: c, on: f, fps: f.fps }]))
}
else for (const f of files) keep(contract ? name : null, f, await runOnce([{ check: c, on: f, fps: f.fps }]))
}
const mine = findings.slice(before)
const errors = mine.filter((x) => x.level === "error").length
@@ -221,8 +172,6 @@ export async function goalCheck(o: { files?: string[]; at?: Moment; goal?: strin
verdicts.push({ name, kind: contract?.kind ?? "floor", step: contract?.step ?? null, after: contract?.after ?? [], passed: errors === 0 && broke.length === brokeBefore, errors, warnings: mine.filter((x) => x.level === "warn").length, checks: checks.map((c) => c.id), files: files.map((f) => f.path) })
}
findings.sort((a, b) => (a.file ?? "").localeCompare(b.file ?? "") || (a.seconds?.[0] ?? -1) - (b.seconds?.[0] ?? -1))
// printed and saved whole: no finding holds half a character (12-05, Dutch run 9: one broke the check as it printed)
findings.splice(0, findings.length, ...collapse(findings).map((x) => ({ ...x, says: wellFormed(x.says), fix: x.fix && wellFormed(x.fix) })))
const errors = findings.filter((x) => x.level === "error").length
return {
object: "goal.check",
@@ -250,7 +199,7 @@ export function writeReport(r: Report, named: string[]) {
writeFileSync(path.join(dir, "goal.json"), `${JSON.stringify(r, null, 1)}\n`)
for (const f of named) {
const mine = r.findings.filter((x) => x.file === f)
writeFileSync(`${media.stem(path.join(r.root, f))}.check.json`, `${JSON.stringify({ object: "goal.check.file", at: r.at, file: f, passed: !mine.some((x) => x.level === "error"), checks: r.checks, findings: mine }, null, 1)}\n`)
writeFileSync(`${media.stem(path.join(r.root, f))}.check.json`, `${JSON.stringify({ object: "goal.check.file", at: r.at, file: f, passed: !mine.some((x) => x.level === "error"), findings: mine }, null, 1)}\n`)
}
}
@@ -267,7 +216,7 @@ export function text(r: Report): string {
for (const b of r.broke) t.push(`BROKE ${b.check}${b.file ? ` ${b.file}` : ""} ${b.says}`)
if (r.goals.length > 1) for (const g of r.goals) t.push(`${g.passed ? "ok " : "open"} goal ${g.name} (${g.kind}${g.step ? `, step ${g.step}` : ""}${g.after.length ? `, after ${g.after.join(", ")}` : ""}): ${g.errors} errors, ${g.warnings} warnings`)
const kinds = r.goals.map((g) => (r.goals.length > 1 ? g.name : g.kind)).join(", ")
t.push(`${r.passed ? "PASSED" : "FAILED"} raea check --at ${r.at} (${kinds}): ${r.files.length} file${r.files.length === 1 ? "" : "s"}, ${r.checks.length} checks, ${r.errors} errors, ${r.warnings} warnings${r.waits.length ? `, ${r.waits.length} waiting` : ""}; review/goal.json`)
t.push(`${r.passed ? "PASSED" : "FAILED"} goal check --at ${r.at} (${kinds}): ${r.files.length} file${r.files.length === 1 ? "" : "s"}, ${r.checks.length} checks, ${r.errors} errors, ${r.warnings} warnings${r.waits.length ? `, ${r.waits.length} waiting` : ""}; review/goal.json`)
return t.join("\n")
}
@@ -277,8 +226,11 @@ function flag(a: string[], name: string): string | undefined {
}
const positional = (a: string[], valued: string[]) => a.filter((x, i) => !x.startsWith("-") && !valued.includes(a[i - 1] ?? ""))
const USAGE = `raea check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--json]
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 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]
raea make place FILE [--at S[,S...]] [--box WxH]`
export async function main(argv: string[]): Promise<number> {
@@ -286,7 +238,7 @@ export async function main(argv: string[]): Promise<number> {
if (verb === "check") {
const at = (flag(a, "--at") ?? "done") as Moment
if (!MOMENTS.includes(at)) {
console.error(`raea check: --at is one of ${MOMENTS.join(", ")}`)
console.error(`raea goal check: --at is one of ${MOMENTS.join(", ")}`)
return 2
}
const files = positional(a, ["--at", "--only", "--manifest", "--goal"])
@@ -294,7 +246,7 @@ export async function main(argv: string[]): Promise<number> {
try {
r = await goalCheck({ files, at, goal: flag(a, "--goal"), only: flag(a, "--only")?.split(",").filter(Boolean), manifest: flag(a, "--manifest") })
} catch (e) {
console.error(`raea check: ${(e as Error).message}`)
console.error(`raea goal check: ${(e as Error).message}`)
return 2
}
writeReport(r, r.files.filter((f) => files.some((n) => path.resolve(n) === path.join(r.root, f))))
@@ -302,6 +254,33 @@ export async function main(argv: string[]): Promise<number> {
return r.passed ? 0 : 1
}
if (verb === "tasks") return tasksMain(a)
if (verb === "seen") {
const [file, said] = positional(a, ["--surprise", "--look"])
if (!file || !existsSync(file)) return usage()
if (!said?.trim()) {
const sheet = media.sheet(path.resolve(file))
const full = kindOf(path.resolve(file)) === "video" ? media.looks(path.resolve(file)) : []
// on raea cloud (where Clef-Omni is paid for), a second opinion on the whole cut with its sound: never the look itself
const op = full.length && process.env.RAEA_AGENT_KEY && process.env.RAEA_API ? 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)
const sheet = `${media.stem(abs)}.sheet.jpg`
if (kindOf(abs) === "video" && !media.freshBeside(abs, "sheet.jpg")) {
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, 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
}
if (verb === "place") {
const file = positional(a, ["--at", "--box", "-o"])[0]
if (!file || !existsSync(file)) return usage()
@@ -324,6 +303,19 @@ export async function main(argv: string[]): Promise<number> {
if (o) writeFileSync(o, JSON.stringify(rep, null, 1))
return 0
}
if (verb === "judge") {
const root = rootOf(process.cwd())
const { goals } = root ? await goalsIn(root) : { goals: [] as Contract[] }
const name = flag(a, "--goal")
const said = goals.filter((g) => (name ? nameOf(g) === name : true) && saysOf(g).length)
if (!root || said.length !== 1) {
console.error(`raea goal judge: ${!root ? "no brief.ts here or above" : !said.length ? `no goal${name ? ` named ${name}` : ""} here has \`says\` rules` : `several goals have \`says\` rules (${said.map(nameOf).join(", ")}): name one with --goal`}`)
return 2
}
const v = await judge(said[0], root)
for (const [id, r] of Object.entries(v.rules)) console.log(`${r?.pass ? "ok " : "open"} ${id}: ${r?.why ?? ""}`)
return 0
}
return usage()
}
-15
View File
@@ -64,18 +64,3 @@ export function inOrder(want: string[], got: string[]): number {
}
return row[got.length] / want.length
}
// A finding's quoted text, safe to print. 12-05, Dutch run 9: a caption's text cut at 40 UTF-16 units split an emoji, the
// report held half of it, and printing it broke the check ("Conversion from string failed: invalid utf-8 sequence").
/** a lone half of a surrogate pair: no character, and nothing UTF-8 can hold */
const LONE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g
/** `s` with any half character replaced by U+FFFD */
export const wellFormed = (s: string): string => s.replace(LONE, "�")
/** `s` cut to at most `n` characters (whole code points, never half an emoji), with "..." when it was longer */
export function quote(s: string, n: number): string {
const cs = Array.from(s)
return cs.length > n ? `${cs.slice(0, n).join("")}...` : s
}
-19
View File
@@ -93,22 +93,3 @@ test("captions are a must: a cut that talks with only a text hook up fails, a ba
// a cut with hardly any talking needs none
expect(uncaptioned([], said.slice(0, 4))).toEqual([])
})
test("a caption the takes' own words say passes, though a second hearing of the export wrote it otherwise (12-05, run 11)", () => {
const shown = captionsOf(frames, 2, said)
// the export heard again has no "god" after "my,"; the take's own words, placed where the edit plays them, do
const placed = said.map((x) => (x.text === "my," ? { ...x, text: "my, god" } : x))
expect(compare(shown, said).some((x) => x.kind === "shown" && x.says.includes("god"))).toBe(true)
expect(compare(shown, said, placed).some((x) => x.kind === "shown" && x.says.includes("god"))).toBe(false)
// a word in neither is still found
expect(compare(shown, said, said).some((x) => x.kind === "shown" && x.says.includes("god"))).toBe(true)
})
test("words said but uncaptioned that the take's own words have captioned are a second hearing's, not a fault (12-05, run 11)", () => {
const shown = captionsOf(frames, 2, said)
// the export heard again inserts words where the take's own words, which the captions follow, have none
const again = said.flatMap((x) => (x.text === "know?" ? [x, { ...x, text: "sleep with Paul", start: x.end + 0.01, end: x.end + 0.2 }] : [x]))
expect(compare(shown, said, said).filter((x) => x.kind === "dropped" && x.says.includes("okay, this is")).length).toBe(1)
// "okay, this is" is in the take's words too: still a fault
expect(compare(shown, again, said).some((x) => x.kind === "dropped" && x.says.includes("okay, this is"))).toBe(true)
})
-46
View File
@@ -1,46 +0,0 @@
// docs/check.feature: one check, run once after the render, one line a rule a file, our own text from the manifest.
import { expect, test } from "bun:test"
import { mkdtempSync, utimesSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import path from "node:path"
import { renderFindings } from "../src/packs/render.ts"
import { collapse, keptCheck } from "../src/run.ts"
const at = (s: number, says = "a caption under the app's buttons") => ({ goal: null, check: "floor", file: "a.mp4", level: "error" as const, says, seconds: [s, s + 1] as [number, number] })
test("CK2: one fault found at many moments is one line, distinct faults keep theirs", () => {
const xs = collapse([at(1), at(4, "another phrase in the same zone"), at(9), { goal: null, check: "playable", file: null, level: "error", says: "no landscape composition", seconds: null }, { goal: null, check: "playable", file: null, level: "error", says: "over the 5120 KB cap", seconds: null }] as never)
expect(xs).toHaveLength(3)
expect(xs[0].says).toContain("(and 2 more like it")
expect(xs.filter((x) => x.check === "playable")).toHaveLength(2)
})
test("CK1: a kept check stands while it's no older than the file and its manifest", () => {
const d = mkdtempSync(path.join(tmpdir(), "raea-kept-"))
const v = path.join(d, "a.mp4")
writeFileSync(v, "x")
writeFileSync(path.join(d, "a.check.json"), JSON.stringify({ checks: ["words", "floor"], findings: [at(1)] }))
utimesSync(v, new Date(1_000_000), new Date(1_000_000))
expect(keptCheck(v)?.checks).toEqual(["words", "floor"])
// re-rendered after it was checked: stale
utimesSync(v, new Date(), new Date(Date.now() + 60_000))
expect(keptCheck(v)).toBeNull()
})
test("CK2: the render's own findings, one line a kind; safe-area is measured on the video", () => {
const said = renderFindings({ findings: [
{ check: "font-missing", level: "error", says: "Inter isn't installed" },
{ check: "font-missing", level: "error", says: "Inter Bold isn't installed" },
{ check: "safe-area", level: "warn", says: "text in the bottom zone" },
{ check: "clipping", level: "info", says: "fine" },
] })
expect(said).toHaveLength(1)
expect(said[0].says).toBe("font-missing: Inter isn't installed (and 1 more like it)")
})
test("CK3: one line a rule a file across levels: the worst leads, the rest counted under it (12-05, run 5)", () => {
const f = (level: string, check: string, s: number, says: string) => ({ goal: "g", check, file: "out/cuts/a.mp4", level, says, seconds: [s, s + 1], fix: null, by: "raea" })
const xs = collapse([f("warn", "place", 3.5, "text covers a person"), f("error", "place", 0, "text covers a dog"), f("warn", "frames", 4, "face cut by the bottom edge"), f("error", "frames", 3, "face cut by the right edge"), f("warn", "sound", 8.8, "a tight cut"), f("error", "sound", 14.1, "cuts a word")] as never)
expect(xs.map((x: any) => [x.check, x.level])).toEqual([["place", "error"], ["frames", "error"], ["sound", "error"]])
expect(xs[0].says).toBe("text covers a dog (and 1 lesser)")
})
+7 -7
View File
@@ -7,17 +7,17 @@ import { cut, packsOf, rules } from "../src/contract.ts"
import { goalCheck } from "../src/run.ts"
import { project } from "./project.ts"
test("a cut holds only the rules that catch real faults (docs/check.feature CK2)", () => {
test("a cut holds the craft by default, surprise only when asked", () => {
const on = packsOf(cut({ cut: { brief: "b.txt" } }))
for (const p of ["words", "sound", "frames", "place", "captions", "floor", "render", "say", "never", "cta", "shape", "naming", "sizes", "count", "open"] as const) expect(on).toContain(p)
for (const p of ["voice", "reading", "hook", "airgaps", "montage", "quotes"] as const) expect(on).not.toContain(p)
expect(packsOf(cut({ cut: { brief: "b.txt" }, packs: { montage: true, place: false } }))).toContain("montage")
for (const p of ["words", "sound", "frames", "place", "seen", "naming", "sizes", "say", "cta"] as const) expect(on).toContain(p)
expect(on).not.toContain("surprise")
expect(packsOf(cut({ cut: { brief: "b.txt" }, packs: { surprise: true, place: false } }))).toContain("surprise")
expect(packsOf(cut({ cut: { brief: "b.txt" }, packs: { place: false } }))).not.toContain("place")
expect(packsOf(rules({ aim: "x" }))).toEqual(["deliverables", "render"])
expect(packsOf(rules({ aim: "x", rules: [{ id: "t", run: "true" }, { id: "w", says: "it reads" }] }))).toEqual(["deliverables", "render", "run"])
expect(packsOf(rules({ aim: "x" }))).toEqual(["deliverables", "stills"])
expect(packsOf(rules({ aim: "x", rules: [{ id: "t", run: "true" }, { id: "w", says: "it reads" }] }))).toEqual(["deliverables", "stills", "run", "says"])
expect(packsOf(cut({ cut: { brief: "b.txt" }, rules: [{ id: "t", run: "true" }] }))).toContain("run")
// no contract: the floor every made video is held to
expect(packsOf(null)).toEqual(["frames", "place", "captions", "floor", "render"])
expect(packsOf(null)).toEqual(["frames", "captions", "voice", "reading", "hook", "airgaps", "floor", "seen", "stills"])
})
test("a project's own check runs at its moments", async () => {
+1 -28
View File
@@ -14,7 +14,7 @@ beforeAll(() => {
const BRIEF = 'Deliverables: 10 total videos (4 solos / 1 mashup per angle).\nUse the phrase "free, fun, and easy."\nDon\'t let it read as White Elephant.\nEnd on the CTA: "Make your Wishlist and organize your Gift Exchange on Elfster. It\'s free."\nCTV specs from the client [TO CONFIRM]\n'
const contract = (cut: Record<string, unknown> = {}) => ({
kind: "cut",
packs: { words: false, sound: false, frames: false, place: false, captions: false, floor: false, render: false, naming: false, sizes: false, quotes: true },
packs: { words: false, sound: false, frames: false, place: false, floor: false, stills: false, seen: false, naming: false, sizes: false, hook: false, airgaps: false },
cut: {
brief: "media/brief.txt",
count: { value: 2, from: "10 total videos" },
@@ -128,30 +128,3 @@ test("a rotated CTA lands on any of its lines", async () => {
put(d2, "media/brief.txt", `${BRIEF}"See a vet today at Dutch.com."\n`)
expect(of(await run(d2), "quotes")).toHaveLength(1)
})
test("an end card's lines are read together: a CTA drawn as two lines is shown (12-04, Elfster run 4)", async () => {
const d = project(contract({ cuts: [{ id: "a1_s1" }] }))
put(d, "media/brief.txt", BRIEF)
// nothing of the CTA is said; the end card draws it as two lines at the clip's end
deliver(d, S1, "so it draws the names for you and everyone gets a gift they want")
const card = (lines: string[]) => JSON.stringify({ fps: 30, frames: [{ frame: 0, text: lines.map((text) => ({ text, opacity: 1 })) }] })
put(d, S1.replace(/\.mp4$/, ".render.json"), card(["Elfster", "Make your Wishlist and organize your Gift Exchange on Elfster.", "It's free."]))
expect(of(await run(d), "cta")).toEqual([])
// its first line alone isn't the CTA
put(d, S1.replace(/\.mp4$/, ".render.json"), card(["Make your Wishlist and organize your Gift Exchange on Elfster."]))
expect(of(await run(d), "cta")).toHaveLength(1)
})
test("a CTA said in part and shown in part lands, numbers said in words included (12-05, Dutch run 10)", async () => {
const cta = { text: "Go to Dutch.com and use code PETS60 for $60 off your first year.", from: "Go to Dutch.com and use code PETS60 for $60 off your first year." }
const d = project(contract({ cta, cuts: [{ id: "a1_s1" }] }))
put(d, "media/brief.txt", `${BRIEF}"Go to Dutch.com and use code PETS60 for $60 off your first year."\n`)
// the host's words (Dutch.com misheard), cut before "year"; the end card shows the offer
deliver(d, S1, "go visit Dodge com and use code pets sixty for sixty dollars off your first")
const card = (lines: string[]) => JSON.stringify({ fps: 30, frames: [{ frame: 0, text: lines.map((text) => ({ text, opacity: 1 })) }] })
put(d, S1.replace(/\.mp4$/, ".render.json"), card(["Code PETS60: $60 off your first year"]))
expect(of(await run(d), "cta")).toEqual([])
// with no end card it's 79%, and still held
put(d, S1.replace(/\.mp4$/, ".render.json"), card(["Dutch"]))
expect(of(await run(d), "cta")).toHaveLength(1)
})
+1 -20
View File
@@ -3,7 +3,7 @@ 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 { faultsOf, floorOf, type Measured } from "../src/packs/floor.ts"
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", () => {
@@ -50,22 +50,3 @@ test("montage findings are kept: measured again when the video is newer or its b
expect(runs).toBe(3)
rmSync(d, { recursive: true, force: true })
})
test("blocky darks are an error only when the encode added them; untraced, a warning; the picture's own, nothing (12-04)", () => {
const xs: Measured[] = [
{ level: "error", says: "blocky patches in dark areas in 1 of 1 sampled frames (worst 6% of dark blocks stepping): the encode starved the near-blacks, or the footage holds them; render with --quality master" },
{ level: "error", says: "blocky patches in dark areas in 2 of 9 sampled frames (worst 5% of dark blocks stepping); whether the encode made them or the picture holds them couldn't be told (no composition)" },
{ level: "note", says: "blocky patches in dark areas in 3 of 9 sampled frames (worst 4%): the picture's own, there as the composition draws them" },
{ level: "error", says: "the encode added blocky patches in dark areas: 4 of 9 samples are blotchier than the composition draws them unencoded" },
]
expect(faultsOf(xs).map((x) => x.level)).toEqual(["warn", "warn", "error"])
})
test("text at the right edge above the app's buttons isn't in its UI zone; below them it is (12-05)", () => {
const at = (y: number, more = "") => ({ level: "error" as const, says: `“THE BODY SHOP” sits in the app's UI zone at the right (keep 140 px clear): its box 134,${y} 812x112 in 1080x1920${more}` })
expect(faultsOf([at(682)])).toEqual([])
expect(faultsOf([at(1290)])).toEqual([at(1290)])
expect(faultsOf([at(682, " (and 1 more like it)")])[0].level).toBe("warn")
const top = { level: "error" as const, says: "“Hook” sits in the app's UI zone at the top (keep 220 px clear): its letters 86,150 908x196 in 1080x1920" }
expect(faultsOf([top])).toEqual([top])
})
+114 -5
View File
@@ -1,10 +1,15 @@
// 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, utimesSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import path from "node:path"
import { clefVerdict, judge, lastVerdict, NO_CRITIC, newest } from "../src/packs/goal.ts"
import { goalCheck } from "../src/run.ts"
import { project, put } from "./project.ts"
const goal = (rules: unknown[]) => ({ kind: "rules", aim: "tests pass", rules })
const VERDICT = "review/judge/rules.json"
test("a command passes or says why", async () => {
const d = project(goal([{ id: "ok", run: "true" }, { id: "bad", run: "echo broke; exit 3" }]))
@@ -21,6 +26,81 @@ test("a command past its timeout fails", async () => {
expect(r.findings.find((x) => x.check === "run")?.says).toContain("still running after 1 s")
})
test("words need a fresh critic", async () => {
const d = project(goal([{ id: "friendly", says: "the reply is friendly" }]))
put(d, "work.txt", "the work")
const says = async () => (await goalCheck({ cwd: d })).findings.filter((x) => x.check === "says")
// no critic in this session: it says so, and names no tool or agent to run
expect((await says())[0].fix).toBe(NO_CRITIC)
const later = Math.floor(Date.now() / 1000) + 5
mkdirSync(path.join(d, "review/judge"), { recursive: true })
writeFileSync(path.join(d, VERDICT), JSON.stringify({ at: later, by: "claude", rules: { friendly: { pass: true, why: "it says hello warmly" } } }))
expect(await says()).toEqual([])
// the critic's own file (and raea's report) don't count as the work changing
expect(newest(d)!).toBeLessThan(later * 1000)
writeFileSync(path.join(d, VERDICT), JSON.stringify({ at: 1, rules: { friendly: { pass: true, why: "" } } }))
expect((await says())[0].says).toContain("changed after")
writeFileSync(path.join(d, VERDICT), JSON.stringify({ at: later, rules: { friendly: { pass: false, why: "it is curt" } } }))
expect((await says())[0].says).toContain("it is curt")
})
test("the check asks this session's critic itself", async () => {
const d = project(goal([{ id: "friendly", says: "the reply is friendly" }]))
put(d, "work.txt", "the work")
const heard: { auth: string | null; cwd: string; prompt: string }[] = []
const server = Bun.serve({
port: 0,
async fetch(req) {
const b = (await req.json()) as { cwd: string; prompt: string }
heard.push({ auth: req.headers.get("authorization"), ...b })
return Response.json({ text: 'thinking... {"rules": {"friendly": {"pass": true, "why": "it says hello warmly"}}}' })
},
})
process.env.RAEA_JUDGE_URL = `http://127.0.0.1:${server.port}/host/judge`
process.env.RAEA_JUDGE_TOKEN = "t0k"
try {
const r = await goalCheck({ cwd: d })
expect(r.findings.filter((x) => x.check === "says")).toEqual([])
expect(heard).toHaveLength(1)
expect(heard[0].auth).toBe("Bearer t0k")
expect(heard[0].prompt).toContain("friendly: the reply is friendly")
// judged once: a second check reads the kept verdict
await goalCheck({ cwd: d })
expect(heard).toHaveLength(1)
} finally {
delete process.env.RAEA_JUDGE_URL
delete process.env.RAEA_JUDGE_TOKEN
server.stop(true)
}
})
test("a rule with a piece to watch goes to clef, any other to the agent", async () => {
const g = goal([
{ id: "plan", says: "plan.md names every cut" },
{ id: "cut", says: "out/a.mp4 opens on the hook" },
])
const d = project(g)
put(d, "out/a.mp4", "video")
const clefAsked: string[] = []
const agentAsked: string[] = []
const v = await judge(g as never, d, {
ask: (_dir, file, says) => (clefAsked.push(file), says.map(() => ({ choice: "true" }))),
agent: async (_cwd, p) => (agentAsked.push(p), '{"rules": {"plan": {"pass": false, "why": "cut 3 is missing"}}}'),
})
// out/ holds a video, so both are about a piece: clef judges both, and nothing asks the agent
expect(agentAsked).toEqual([])
expect(Object.keys(v.rules).sort()).toEqual(["cut", "plan"])
const bare = project(g)
const v2 = await judge(g as never, bare, {
ask: (_dir, file, says) => (clefAsked.push(file), says.map(() => ({ choice: "true" }))),
agent: async (_cwd, p) => (agentAsked.push(p), '{"rules": {"plan": {"pass": false, "why": "cut 3 is missing"}, "cut": {"pass": false, "why": "no cut yet"}}}'),
})
expect(agentAsked).toHaveLength(1)
expect(agentAsked[0]).toContain("plan: plan.md names every cut")
expect(v2.rules.plan?.why).toBe("cut 3 is missing")
expect(v2.by).toBe("agent")
})
test("file rules are deliverables", async () => {
const d = project(goal([{ id: "export", file: "out/final.txt" }]))
expect((await goalCheck({ cwd: d })).findings.map((x) => [x.check, x.says])).toEqual([["deliverables", "missing: out/final.txt"]])
@@ -28,6 +108,12 @@ test("file rules are deliverables", async () => {
expect((await goalCheck({ cwd: d })).passed).toBe(true)
})
test("the verdict is the last JSON with rules", () => {
const t = 'the shape is {"rules": {"ID": ...}} so: {"x": 1} then {"rules": {"a": {"pass": true, "why": "seen"}}}'
expect(lastVerdict(t)?.rules.a?.pass).toBe(true)
expect(lastVerdict("no json here")).toBeNull()
})
test("a check runs only at its moments", async () => {
const d = project(goal([{ id: "bad", run: "exit 1" }]))
// run rules hold at done, not at an edit
@@ -35,9 +121,32 @@ test("a check runs only at its moments", async () => {
expect((await goalCheck({ cwd: d, at: "done" })).checks).toContain("run")
})
test("a `says` rule is said to be unchecked: nothing judges the work (docs/check.feature CK4)", async () => {
const d = project(goal([{ id: "friendly", says: "the reply is friendly" }]))
const r = await goalCheck({ cwd: d })
expect(r.plan.some((p) => p.includes("rules.friendly") && p.includes("isn't checked"))).toBe(true)
expect(r.checks).not.toContain("says")
test("clef judges a rule on the file it names, else on every video made, and says when there's nothing to watch", () => {
const d = mkdtempSync(path.join(tmpdir(), "raea-goal-clef-"))
mkdirSync(path.join(d, "out/cuts"), { recursive: true })
for (const f of ["out/cuts/a_9x16.mp4", "out/cuts/b_9x16.mp4"]) writeFileSync(path.join(d, f), "x")
const g = { name: "rules", rules: [{ id: "named", says: "In out/cuts/a_9x16.mp4, from 0 s to 3 s, the host is speaking" }, { id: "all", says: "No caption covers a face" }] } as never
const asked: string[] = []
const rules = clefVerdict(g, d, (_dir, file, says, from, to) => {
asked.push(`${file} ${from ?? ""}-${to ?? ""} ${says.length}`)
return says.map((q) => ({ choice: q.includes("caption") && file.includes("b_") ? "false" : "true", says: "said" }))
})
expect(asked.sort()).toEqual(["out/cuts/a_9x16.mp4 - 1", "out/cuts/a_9x16.mp4 0-3 1", "out/cuts/b_9x16.mp4 - 1"])
expect(rules.named?.pass).toBe(true)
expect(rules.all?.pass).toBe(false)
expect(rules.all?.why).toBe("out/cuts/b_9x16.mp4: said")
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()
})
+10 -1
View File
@@ -5,7 +5,8 @@ import { spawnSync } from "node:child_process"
import { mkdtempSync } from "node:fs"
import { tmpdir } from "node:os"
import path from "node:path"
import type { CutBeat as Beat } from "raea/brief.gen"
import type { Beat } from "raea/brief.gen"
import { saysOf } from "../src/contract.ts"
import { acrossCuts, cutsOf, pace, read, tau } from "../src/packs/montage.ts"
const W = 96
@@ -73,3 +74,11 @@ test("a beat's shots average within a third of its asl; build shortens and relea
expect(flat[0]).toMatchObject({ kind: "tempo" })
expect(tau([3, 2, 1])).toBe(-1)
})
test("a cut goal's beats are rules a fresh critic judges on the cut in sequence", () => {
const said = saysOf({ kind: "cut", cut: { brief: "b.txt", formats: ["9:16"], cuts: [{ id: "a1", beats: [{ at: 0, feel: "the itch of a chore", story: "the app reminds you" }, { at: 4, feel: "relief" }] }] } } as never)
expect(said.map((r) => r.id)).toEqual(["beat_a1_1", "beat_a1_2"])
expect(said[0].says).toContain("out/cuts/a1_9x16.mp4, from 0 s to 4 s")
expect(said[0].says).toContain("in sequence")
expect(said[1].says).toContain("to its end")
})
-31
View File
@@ -1,31 +0,0 @@
import { test, expect } from "bun:test"
import { asDigits, digitsIn, numbersOf } from "../src/packs/numbers.ts"
test("numbers said in words read as digits (12-05, Dutch run 9: \"twenty four seven\" captioned \"24-7\")", () => {
expect(numbersOf(["twenty", "four", "seven"])).toEqual(["24", "7"])
expect(numbersOf(["one", "hundred", "forty", "nine"])).toEqual(["149"])
expect(numbersOf(["one", "thousand"])).toEqual(["1000"])
expect(numbersOf(["nineteen"])).toEqual(["19"])
const w = (text: string, start: number) => ({ text, start, end: start + 0.2 })
const got = asDigits([w("it's", 0), w("twenty", 1), w("four", 1.2), w("seven", 1.4), w("virtual", 2)])
expect(got.map((x) => x.text)).toEqual(["it's", "24 7", "virtual"])
expect(got[1].end).toBeCloseTo(1.6)
expect(asDigits([w("a", 0), w("hundred", 0.2), w("and", 0.4), w("forty-nine", 0.6), w("bucks.", 1)]).map((x) => x.text)).toEqual(["149", "bucks."])
expect(asDigits([w("I", 0), w("want", 0.2), w("a", 0.4), w("dog", 0.6)]).map((x) => x.text)).toEqual(["I", "want", "a", "dog"])
expect(asDigits([w("One", 0), w("more", 0.2)]).map((x) => x.text)).toEqual(["1", "more"])
})
test("a caption in words and one in digits both match what's heard", async () => {
const { digitsIn } = await import("../src/packs/numbers.ts")
const { letters } = await import("../src/packs/captions.ts")
const heard = (await import("../src/packs/numbers.ts")).asDigits([{ text: "One", start: 0, end: 0.2 }, { text: "more", start: 0.2, end: 0.4 }]).map((w) => letters(w.text)).join("")
expect(letters(digitsIn("One more"))).toBe(heard)
expect(letters(digitsIn("it's 24-7"))).toBe(letters(digitsIn("it's twenty-four seven")))
})
test("dollars written as $ match dollars said (12-05, Dutch run 10)", () => {
expect(digitsIn("for sixty dollars off")).toBe("for 60 dollars off")
expect(digitsIn("for $60 off")).toBe("for 60 dollars off")
const w = (t: string, i: number) => ({ text: t, start: i, end: i + 1 })
expect(asDigits(["for", "$60", "off"].map(w)).map((x) => x.text)).toEqual(["for", "60 dollars", "off"])
})
+2 -3
View File
@@ -20,12 +20,11 @@ test("the place pack's model", async () => {
// c: a woman sitting with her dog; the caption on the dog, the hook over the crowd behind her
const c = textOver(man([t("$1,000 for one vet visit?", 116, 236, 848, 112), t("He hurt his little", 290, 1335, 630, 90)]), [sc.c], 1)
assert.equal(c.length, 1, JSON.stringify(c))
// a face or a sign is an error (Shane's rule list, 12-05); the dog, a warning that names the clear place
assert.equal(c[0].level, "warn")
assert.equal(c[0].level, "error")
assert.match(c[0].says, /“He hurt his little” covers a dog/)
const top = Number(/top (\d+) px/.exec(c[0].says)?.[1])
assert.ok(top >= 1380, `moved below the dog, not ${top}`)
ok("a caption over the dog is a warning, moved to the clear ground under it; the hook over passers-by is fine")
ok("a caption over the dog is an error, moved to the clear ground under it; the hook over passers-by is fine")
// a: a checklist on a woman's lap, a sign under her, a man standing behind: no clear place for a block that size
const a = textOver(man([t("✓ 24/7 virtual vet care", 256, 1044, 568, 80), t("✓ Price-matched Rx", 280, 1130, 520, 76), t("✓ Free delivery", 336, 1214, 410, 76)]), [sc.a], 1)
-21
View File
@@ -33,24 +33,3 @@ test("a frame full of lines (a shelf of labels) is left out, and words said as t
const heard = "so good I want to eat it".split(" ").map((t, i) => ({ text: t, start: 0.2 + i * 0.3, end: 0.45 + i * 0.3 }))
expect(blocksOf(frames(4, (t) => (t < 0.5 ? [line(300, "SO GOOD I WANT TO EAT IT")] : [])), 2, none, heard)).toEqual([])
})
test("a render's manifest is read as the texts it drew: a three-line card's size is a line's, and its time is exact", async () => {
const { readingFrames } = await import("../src/packs/reading.ts")
const card = { text: "How does your group do Secret Santa this year? Names in a hat or chaos", ink: [60, 300, 900, 288], opacity: 1, lines: 3 }
const frames = Array.from({ length: 60 }, (_, i) => ({ frame: i, text: [{ ...card, opacity: i < 30 ? 1 : 0.1 }] }))
const own = readingFrames({ fps: 30, height: 1920, frames })!
expect(own.rate).toBe(5)
expect(own.frames[0].lines[0][3]).toBe(96)
// up exactly a second (frames 0-29), gone once it fades below 0.2: 15 words in a second is an error
const blocks = blocksOf(own.frames, own.rate, none)
expect(blocks.length).toBe(1)
expect(blocks[0].to - blocks[0].from).toBeCloseTo(1, 5)
expect(reading(blocks)[0].level).toBe("error")
// fine print a line 24 px tall is texture: a warning that asks
const fine = { text: "Terms apply. See site for details on the offer and its dates", ink: [60, 1800, 600, 24], opacity: 1, lines: 1 }
const small = readingFrames({ fps: 30, height: 1920, frames: Array.from({ length: 60 }, (_, i) => ({ frame: i, text: i < 15 ? [fine] : [] })) })!
const f = reading(blocksOf(small.frames, small.rate, none))
expect(f.length).toBe(1)
expect(f[0].level).toBe("warn")
expect(f[0].says).toContain("texture")
})
-17
View File
@@ -38,15 +38,8 @@ test("the sound pack's measures", async () => {
const onSound = editPoints(clip(1.01, 1.0), fps, words, take)
assert.equal(onSound[0]?.kind, "edit-on-sound", JSON.stringify(onSound))
assert.match(onSound[0].says, /first sound/)
assert.equal(onSound[0].level, "error")
ok("an in point on a word's first sound is an error")
// a loud sound 3 s from any word (a laugh, a door): a cut on it is no word cut, a warning for the ear (12-05, run 12)
const noisy: number[] = db.map((x, i) => (i >= 340 && i < 360 ? -22 : x))
const away = editPoints(clip(3.45, 0.4), fps, [{ text: "very", start: 0.1, end: 0.3 }], { start: 0, db: noisy })
assert.ok(away.length >= 1 && away.every((x) => x.level === "warn"), JSON.stringify(away))
ok("a cut on a sound far from any word is a warning, not a word cut")
// "loud" and "next" run together with no pause: a cut on their boundary is tight (a warning), not a cut word
const run = [{ text: "say", start: 1.0, end: 1.4 }, { text: "so", start: 1.42, end: 1.7 }, { text: "then", start: 1.72, end: 2.0 }]
const runDb: number[] = []
@@ -104,13 +97,3 @@ test("a voice clip, or a take named only by a farm cache's hash, that isn't here
assert.deepEqual(findings.map((x) => [x.level, x.at]), [["error", 0], ["warn", 0], ["error", 1]])
assert.match(findings[0].says, /^a take named only by its hash isn't on this machine/)
})
test("a word timed longer than a word runs is no word to cut in two (12-04, Elfster run 5: \"secret\" over 23.7 s)", () => {
const words = [{ text: "secret", start: 1.0, end: 24.7 }]
const db: number[] = []
for (let t = 0; t < 30; t += 0.01) db.push(-50)
const take: Levels = { start: 0, db }
const clip: Clip = { key: "n1", from: 150, to: 300, src: "/w/work/media/raw/take.mov", at: 5, gainDb: 0, bus: "voice" }
// a cut 4 s into the stretch, on quiet: nothing to say about a word
assert.equal(editPoints(clip, 30, words, take).filter((f) => f.kind === "edit-in-word").length, 0)
})
+13 -1
View File
@@ -4,7 +4,7 @@ import { expect, test } from "bun:test"
import { readFileSync, writeFileSync } from "node:fs"
import path from "node:path"
import { applyTasks, putTasks, tasksOf } from "../src/tasks.ts"
import { goalCheck } from "../src/run.ts"
import { project, put } from "./project.ts"
test("tasks come from the brief's run, and an edit lands in the module that writes the task", async () => {
@@ -41,3 +41,15 @@ test("--put writes the whole plan back only while the brief's is still the base
expect(r).toMatchObject({ put: true, written: ["brief.ts"] })
expect(readFileSync(path.join(d, "brief.ts"), "utf8")).toContain('keyword: "DONE"')
})
test("a raea file the brief never reaches is said at every moment, an error once it's handed over", async () => {
const d = project({ kind: "rules", aim: "x", rules: [], compositions: ["compositions/hero.tsx"] })
put(d, "compositions/hero.tsx", `import { Box } from "raea"\nimport { Logo } from "../components/logo.tsx"\nexport default () => null\n`)
put(d, "components/logo.tsx", `import { Text } from "raea"\nexport const Logo = () => null\n`)
put(d, "compositions/old-test.tsx", `import { Box } from "raea"\nexport default () => null\n`)
put(d, "tools/notes.ts", `// import { x } from "raea/brief" is only a comment\nexport const n = 1\n`)
const edit = await goalCheck({ cwd: d, at: "edit" })
expect(edit.findings.filter((x) => x.check === "registered").map((x) => [x.level, x.file])).toEqual([["warn", "compositions/old-test.tsx"]])
const done = await goalCheck({ cwd: d, at: "done" })
expect(done.findings.filter((x) => x.check === "registered").map((x) => [x.level, x.file])).toEqual([["error", "compositions/old-test.tsx"]])
})
-15
View File
@@ -1,15 +0,0 @@
import { test, expect } from "bun:test"
import { quote, wellFormed } from "../src/text.ts"
import { collapse } from "../src/run.ts"
test("a quote never splits an emoji, and a half character is replaced (12-05, Dutch run 9)", () => {
const s = "Asking NYC dogs what they really think 🐶🐶 about it"
const q = quote(s, 40)
expect(q).toBe("Asking NYC dogs what they really think 🐶...")
expect(wellFormed(q)).toBe(q)
const half = s.slice(0, 40) // the first half of 🐶
expect(wellFormed(half).endsWith("�")).toBe(true)
expect(new TextDecoder().decode(new TextEncoder().encode(wellFormed(half)))).toBe(wellFormed(half))
expect(quote("short", 40)).toBe("short")
expect(collapse([{ goal: null, check: "place", file: "a.mp4", level: "error", says: half, seconds: [1, 2], fix: null, by: "raea" }] as never)).toHaveLength(1)
})
+2 -3
View File
@@ -20,8 +20,7 @@ Run `raea context PROJECT` before anything else and read all of it. It prints, i
every project. A line there beats any guide.
2. **The brief** (`brief.ts`): who it's for (`audience`), the one thing they should think afterwards (`believe`),
what kind of piece it is (`mode`), the narrator and tone (`voice`), what it delivers, the tasks and the agents.
Deliverables can have their own briefs, with a storyboard (`NAME.script.ts`) and a direction. To write one,
`raea guide brief` has its types, a cut goal's contract and an example.
Deliverables can have their own briefs, with a storyboard (`NAME.script.ts`) and a direction.
3. **The look** (the brief's `look`, and `brand/brand.css` when there is one): the project's committed world.
4. **The floor**: what breaks a piece, read again right before every edit.
5. **One guide per mode**: what that kind of piece has to do.
@@ -112,7 +111,7 @@ names. A note with three asks is three moves, not one:
- **extract:** a brand kit read from finished work;
- **generate:** variants of one element to pick from;
- **polish:** close out the latest critique;
- **critique:** when the person asks "is it good?": an honest look at the piece as it rendered.
- **critique:** judge the piece honestly before you call it done.
Each move has a short guide: `raea guide quieter` (and the rest). Read the one an ask calls for before you act on
it. Never show these words to the person. Answer the note in their terms.
+5 -4
View File
@@ -3,7 +3,7 @@
A kit is a set of objects that belong together (a 1970s flight desk's phone, clock, ashtray and lamp) and land as
components any project can import. It holds together because every reference comes from the same style images and
paragraph, every model is picked on clay from two generators, and the whole set is checked on one sheet before
anything costs much. This is AnyKit's loop (MIT), each step on a `raea make` verb; `raea check` holds you to it
anything costs much. This is AnyKit's loop (MIT), each step on a `raea make` verb; `raea goal check` holds you to it
and the Stop hook won't let you end before it says done.
## What to do
@@ -31,9 +31,10 @@ and the Stop hook won't let you end before it says done.
project's `components/KIT/`): one component per object (`RotaryPhone.tsx`, importing its model and LOD from
beside it, `lod` for when it's small on screen), `lineup.tsx` (every piece at its real size beside a 1 m bar),
`cover.png`, `thumbs/` and `kit.json`. Import it as `@shared/components/KIT/RotaryPhone`.
7. **Review.** `raea render shared/components/KIT/lineup.tsx --review review/rN`, and look at every tile yourself:
the pieces belong together, match their references and the brief, hold their form in clay, and stand at their real
size. Fix every ERROR the render's check names; keep a list of what you'd still change.
7. **Review and judge.** `raea render shared/components/KIT/lineup.tsx --review review/rN`, then
`raea judge review/rN --kind kit --brief brief.ts --json`. The kit rubric: cohesion, reference
fidelity, the brief, mesh (clay), texture, assembly (clay), scale (clay), labels. Fix its blocking defects or
answer them in NOTES.md, and keep going until `raea goal check` passes.
Cost: a six-piece kit is about $8-10 (references about $0.25 each, Tripo H3.1 and Meshy about $0.60-0.80 each).
`--dry` on refs and gen says the price first; ask before going over $10.
+86 -27
View File
@@ -1,25 +1,28 @@
# Scene prompts: the brief and the builder
# Scene prompts: the brief, the builder and the judge
There are two texts to copy and fill: a brief template and a builder prompt. `bevy/scenes` says why each step
exists. This page gives the words.
There are three texts to copy and fill: a brief template, a builder prompt and a judge prompt for a fresh context.
`bevy/scenes` says why each step exists. This page gives the words.
You are the builder. What the scene must hold is checked by raea as each render ends: a part floating, sinking or
passing through another, a part out of place or under its planned detail, light that jumps or boils. Those are
faults, each with its fix (`raea check`). How it should look is the brief's, the target's and this page's, read while
you build; nothing grades it after (raea docs/check.feature).
Who plays which role: you are the builder; `raea judge` is the judge, a fresh session every round that raea starts
for you (the agent this project runs on where the raea app or raea cloud started it, else clef-omni for the numbers).
You never pick it.
The judge sees only pictures and the brief's words, never the code or the builder's notes. Code decides
the pass, and the builder never sees the pass line. A figure the builder can read becomes a target to game.
Where these texts come from: the published Blender + Claude workflows.
- dream-loop: the target is a real in-engine screenshot; a per-category rubric; defects named precisely.
- Muska and KOBATAKA: plan before code; route each object.
- ProfRino and AnyScene: placement is measured; pass is decided in code.
- hayashimon: coarse to fine; one shared wear recipe.
- kiln and prasenx: fixed clay and colour cameras, the same every round.
- kiln and prasenx: fixed clay and colour cameras; a fresh judge each round; stop after two clean reads.
## What to do
1. Write the brief from the template (section 1). Write a `NAME.parts.ts` for every hero object.
2. Start the builder with the builder prompt (section 2), filled from the brief.
3. After every stage and every fix, run step R: the review sheets, looked at by you, and the render's own check.
3. After every stage and every fix, run step R: the review sheets, then the judge prompt (section 3) in a new context
and `raea judge` on the same sheets.
## 1. The brief template
@@ -40,8 +43,8 @@ export default brief({
references: [
// the TARGET: a real in-engine screenshot of this scene from the hero camera
{ /* media/ref/target.png, role: target */ },
// real photos, to compare against; they never ship
{ /* media/ref/real-*.jpg, role: compare-only */ },
// real photos, for the judge only; they never ship
{ /* media/ref/real-*.jpg, role: judge-only */ },
],
notDoing: [
// the do-not-add list: without it the builder adds rain, neon and UI
@@ -57,7 +60,7 @@ export default brief({
{ heading: "Wear", text: "[one recipe for every surface: dust on tops, dirt in gaps and at the floor line, worn edges]" },
{ heading: "Printed matter", text: "[every sign, label and screen: exact text, fictional names, size, age]" },
{ heading: "Motion", text: "[added last, small: one dryer turning, irregular flicker, a slow push-in]" },
{ heading: "Budget", text: "[gen cents cap; review rounds cap (4)]" },
{ heading: "Budget", text: "[gen cents cap; judge rounds cap (8)]" },
],
});
```
@@ -68,8 +71,8 @@ Each generated object needs a reference picture made from this template:
> light, plain pale grey seamless background, the whole object in frame with margin, three-quarter view from slightly
> above, sharp focus, no people, no text, no brand names, no logos.
Each hero object gets its parts (NAME.parts.ts). Its fields are the frozen contract that `raea make solid info --expect` and the render's check hold it
to:
Each hero object gets its parts (NAME.parts.ts). Its fields are the frozen contract that `raea make solid info --expect` and the judge check
against:
```ts
import { parts } from "raea/brief";
@@ -140,34 +143,90 @@ STEP R: REVIEW (after every stage, and after every fix)
the same cameras every round.
- Open both sheets and look at every tile yourself. Write your own list. "Looks good" is not a review. Name each
problem precisely ("the dryer doors are flat grey discs", not "the dryers look off"), with its tile and its fix.
- Read the render's check (`raea render` prints it as it ends; `raea check out/scene.mp4` reads it back): fix every
ERROR. A warning is a note for the person. Change one material per round; every fix is code in the scene.
- Run `raea judge review/r<n>`. It's a new session that sees only the sheets, the brief's words, the target, the real
photos, this round's sheets, and last round's sheets and verdict: never your code, your log or your list. Who reads
them is raea's to settle, not yours.
- Fix every blocking defect named, or write in review/log.md why it is wrong and what you checked. A judge can be
wrong: a shadow read as a hole. Change one material per round. Every fix is code in the scene.
- Re-run the stage's checks after every fix. A fix that breaks a check is not done.
STOPPING
- Done: the render's check has no ERROR, and your own list for the round names nothing blocking.
- Stall: the same problem on your list twice. Stop tweaking and change the approach for that part: another route
(solid, sdf, Tripo HD, Tripo Smart Mesh), a rebuilt light plan, a moved camera. A defect that comes back after two
fixes is the method's fault, not the dose's.
- Cap: 4 review rounds per scene. At the cap, deliver and list what is still wrong.
STOPPING (the loop decides, not you)
- Done: `raea judge` prints "done" (two passes in a row), and the last fresh judge named no blocking defect.
- Stall: the score hasn't risen a full point in 2 rounds, or the same defect is named twice. Stop tweaking and change
the approach for that part: another route (solid, sdf, Tripo HD, Tripo Smart Mesh), a rebuilt light plan, a moved
camera. A defect that comes back after two fixes is the method's fault, not the dose's.
- Stalled: the big change didn't move it. Stop and show Shane the latest sheets and the open defects.
- Cap: 8 judge rounds per scene. At the cap, deliver and list what is still wrong.
RULES
- One builder at a time on coupled systems (light, exposure, materials). Generation may run in parallel.
- Never trust a command just because it ran: back every claim with an image or a check's output.
- A Blender fix counts only once it is a saved script that re-runs from the source; the live MCP is for looking.
- Never edit the plans or the review cameras to pass.
- Never edit the judge prompt, the plans or the review cameras to pass.
- Quote every paid step first, and never spend past the brief's cap.
- Keep review/NOTES.md: one line per thing that cost time.
```
## 3. The judge prompt (a new context every round)
It takes only images and the brief's words, and answers JSON. The pass threshold is not in it.
```text
You review a 3D scene from images only, as the person who will use it would. You have never seen how it was built
and you never will. Judge what is in the pixels; do not guess at intentions.
PART 1, BLIND (answer before reading the brief below):
hero-colour.png is one frame. In one sentence: what place is this, what time, what era? List five objects you can
name. Is it a photograph or a render, and which three tells decided it?
PART 2, SCORED. The brief: "<brief.ts look + logline + notDoing>". The target picture is TARGET.png. Real photos of
this kind of place: REAL_*.jpg. This round's sheets: colour.png and clay.png, tiles hero, front, right, top, iso, low.
The previous round's sheets and verdict, if any: PREV_*.png, PREV.json.
Score each 0-10 (5 = a believable draft; 7 = a production base an artist would accept; 9 = indistinguishable from
the reference). Halves are allowed.
- composition: camera, framing, layout, and the position and scale of every major object, against the target and the
brief's space.
- form, judged on CLAY: silhouettes read at a glance; parts have real thickness; nothing blobby, melted or a
primitive standing in for a thing; repeated things vary.
- assembly, judged on CLAY first: nothing floats, sinks, pokes through or rests on the wrong thing; joints touch; the
low tile shows the feet.
- materials: every surface reads as its real material, with wear where use puts it; nothing a flat default colour.
- light: motivated by the place's own sources; exposure and contrast match the target.
- detail: close views hold real geometry or texture, not a smooth stand-in; printed matter reads; nothing from the
do-not-add list.
- world: the same place as the target and the real photos; nothing off-era, no real brands, nothing invented
beyond the brief.
Then list EVERY defect, most damaging first, each as:
{tile, where in the tile, what is wrong, what the real thing would look like, the fix, blocking|detail}
"Blocking" means someone using this scene would notice it in the views it will be seen in. Name exactly what gives
the scene away: not "the dryer looks fake" but "the dryer door is a flat disc with no rim or glass depth; a real
door has a 3 cm chrome ring and domed glass". If a part must be rebuilt another way, say so. If a previous verdict is
given, stay consistent with it, but don't feel bound to match it or to raise the score; a regression scores lower.
Where the target and the real photos disagree on physics (scale, light falloff, contact), the real photos win.
Answer only this JSON:
{"blind": {"place": "", "objects": [], "photo": "yes|no", "tells": []},
"scores": {"composition": 0, "form": 0, "assembly": 0, "materials": 0, "light": 0, "detail": 0, "world": 0},
"defects": [{"tile": "", "where": "", "wrong": "", "real": "", "fix": "", "level": "blocking|detail"}],
"show_as_is": "one line: would you show this to the person as is, and why"}
```
The loop's rules live in code (`raea judge`), out of the builder's sight:
- A round passes when there is no blocking defect, the lowest score is at least 6 and the mean is at least 7.
- The scene is done after two passes in a row.
- The blind read is reported, not gated, until it is calibrated. Track how often the judge calls our render a photo.
## Why
- A picture first and a do-not-add list keep the builder from inventing a scene nobody asked for.
- Faults are measured by raea as each render ends, the same way every time, so a fix is known to have worked.
- The same cameras every round, in colour and clay, show what changed and hide nothing.
- A judge that has seen the code forgives what it knows was meant. One that sees only pixels judges what a viewer will.
- Numbers and named defects, with the pass decided in code, stop "looks great" from ending a loop early.
## Common mistakes
- Giving the judge the builder's notes, or the pass line. Its scores then drift toward what the builder hoped.
- Skipping the clay sheet. Materials hide broken form and floating parts; clay shows them.
- Fixing three things in one round. When it changes, you can't tell which fix did it.
- Calling the scene done with an ERROR in its render's check.
- Fixing three things in one round. When the score moves, you can't tell which fix did it.
- Calling the scene done on the builder's own reading. Done is two judge passes in a row.
+42 -23
View File
@@ -1,24 +1,25 @@
# Whole scenes: brief, build, review
# Whole scenes: brief, build, review, judge
A believable scene is planned before it is modelled, built big to small with a measured check after every step, and
reviewed from the same fixed cameras every round, and checked once by `raea check` as each render ends. This is the loop the people
reviewed from the same fixed cameras every round by a judge that has never seen the code. This is the loop the people
who make striking Blender scenes with an agent use (the 11-06 research: dream-loop, AnyScene, kiln, prasenx,
hayashimon, KOBATAKA), each step on a raea verb.
## What to do
The brief template and the builder prompt to paste are in `bevy/prompts`. A kit of props is
The brief template, the builder prompt and the judge prompt to paste are in `bevy/prompts`. A kit of props is
`bevy/kits`; shooting a finished set is `bevy/shots`.
### 0. The job: `make` on brief.ts, held by `raea check`
### 0. The job: `make` on brief.ts, held by `raea goal check`
- Put the job on the brief: `goal: scene({ references, style, dials, objects })` from `raea/brief`. Each object has
one size (`h`, `dims` or `max`), a `route`, `source: "reference" | "invented"` and, in a scene, `at` and `rot`
(metres from the floor's front-left corner; rot 0 faces the entrance). Dials you don't set are read from the
reference, so set only the ones the person asked for (`source: "customer"`).
- `raea check` decides in code whether you're done: the deliverables on disk, and no ERROR in their renders' checks.
The Stop hook reads it at the end of a turn (`--at done`) and holds you once for what's still failing. Each
finding says what to change; review/goal.json holds them all.
- `raea goal check` decides in code whether you're done: the deliverables on disk, the record of renders, the judge's
rounds, the make questions, NOTES.md. The Stop hook runs it at the end of every turn (`--at done`), and you can't
stop while it fails (the loop gives way at the 8-round cap, on a stall, or when the same thing is failing three
turns running). Each finding says what to change; review/goal.json holds them all.
- `raea make blockout` is the stop before anything costs money: `review/plan/floor-plan.png` (every footprint, invented
ones dashed), a grey-box blockout seen from the entrance with its review sheets, and `comparison.png` beside the
reference. Show it, fix positions and sizes, and only then generate.
@@ -29,7 +30,7 @@ The brief template and the builder prompt to paste are in `bevy/prompts`. A kit
`<Entity transform lod={4}>` plans everything inside it. Every render then says `lod-closer` when a shot shows a
part finer than planned (a camera move added later, a box you meant to replace and forgot), and
`raea scene lod EDIT.tsx` lists every part's plan beside the largest the frames show it, the unplanned ones too.
Two levels finer is an error; one holds `raea check` until you build it up and replan it, keep the camera
Two levels finer is an error; one holds `raea goal check` until you build it up and replan it, keep the camera
off it, or answer it in NOTES.md on a line with `lod` and its name.
- NOTES.md beside the brief ends with `## What the skill got wrong`: what the guides or tools led you into. The notes
pack checks it's there once the work is.
@@ -52,7 +53,7 @@ The brief template and the builder prompt to paste are in `bevy/prompts`. A kit
- Wear.
- Printed matter.
- Motion.
- Budget: generation cents and review rounds.
- Budget: generation cents and judge rounds.
- Each hero object gets a `NAME.parts.ts` (`parts()`) with its concept (what, style, size, seenFrom, material) and parts, each
with a role, a level (primary, secondary, tertiary), a parent, a count and `near` detail. Below it, add a connection
map with one line per joint: `door <-> cabinet hinge side touches`.
@@ -124,10 +125,10 @@ and its materials as jobs (`<Mat job="steel" />`), so a note can name it and the
6. **Motion, last and small.** First `raea scene stage EDIT.tsx`: it steps every frame without drawing and holds it
to the checks the render fails on (3D words too small or turned too far to read, a part that snaps, a camera that
lurches or goes in and back out, frames with almost nothing on screen). A sign nobody is meant to read takes
`read={false}`. Then `raea render EDIT.tsx -o out/scene.mp4`: it checks its export as it ends (`raea check`).
`read={false}`. Then `raea render EDIT.tsx -o out/scene.mp4` and `raea check out/scene.mp4`.
- Once things move, check how they move. Render with `--layers`, and render `--aov -o out/scene.aov` beside it for
depth. Then run `raea fingerprint things out/scene.mp4 --json > things.json` and
`raea floor out/scene.mp4 --things things.json`. It finds a thing floating or passing through another, the
`raea check out/scene.mp4 --things things.json`. It finds a thing floating or passing through another, the
camera lurching mid-move, and an empty frame.
### R. Review after every stage and every fix
@@ -141,29 +142,47 @@ and its materials as jobs (`<Mat job="steel" />`), so a note can name it and the
`--clay` alone renders any frame in clay.
- Open the sheets and look at every tile yourself. "Looks good" is not a review. Name each problem with its tile and
its fix, for example "the dryer doors are flat grey discs".
- Read the render's check and fix every ERROR in it. A warning is a note for the person.
- Hand the sheets to the judge (below). Fix every blocking defect it names, or write down why it is wrong and what
you checked.
- Change one thing per material per round. Re-run the stage's checks after every fix.
### The checks
### The judge, and the gates
Only measured faults hold the work (raea docs/check.feature), and each says its fix: `raea scene lint` (floats and
sinks at the feet, clips with the move that clears them, faces z-fighting in one plane), `raea gen check` on every
generated model, `raea scene stage --clearance 0.45` on a moving camera, the render's own end checks (a part out of
place or under its planned detail, light that jumps or boils), and the deliverables' counts. How it should look is
this guide's, the brief's and the target's, read while you build: nothing grades it after.
Three tiers, each gating once it has earned it (`raea goal check` lists them):
1. **Measured checks always gate:** `raea scene lint` (floats and sinks at the feet, clips with the move that clears
them, faces z-fighting in one plane), `raea gen check` on every generated model, `raea scene stage --clearance 0.45` on
a moving camera, and the deliverables' counts.
2. **`raea ask` questions gate one at a time, once calibrated.** The make set (`raea ask SHEET --set make`, or the
command the critic pack prints) asks yes/no about one sheet: floating, intersecting, blobby, a stand-in, flat colour,
plastic, opaque glass, garbled hero text, a real brand, too dark or bright; on a reference sheet, an outlier, two
objects, a brand; on a framing sheet, a camera through a wall or a subject lost. Every answer lands in the ask
ledger, matched to the sheet's bytes, so a re-rendered sheet needs asking again. A question gates once
`raea ask calibrate` passes it (16 problem and 16 clean labels, held-out AUC 0.8); until then it's advice.
3. **A fresh critic for the fixes.** `raea judge review/rN --kind scene --brief brief.ts --target
media/ref/target.png --json` scores the kind's rubric (scene: layout, props, signage, materials,
light, atmosphere, plausibility, composition; layout and props judged on clay), on a production bar: don't
nitpick, at most five fixes. It sees the sheets and the brief's words only, never the code or your log. Code
decides the pass; the thresholds aren't in the prompt. A round judged on another kind's rubric doesn't count.
Fix every blocking defect it names, or answer it in NOTES.md (its words, then what you checked). Its score gates
once `raea judge calibrate --kind scene` agrees with Shane's eye (`raea judge eye`).
### Stopping
- **Done:** every deliverable on disk, and no ERROR in its render's check (`raea check` reads them all back).
- **Stall:** the same problem on your list twice. Stop tweaking and change the approach for that part: another route
(solid, field, Tripo HD, Meshy), a rebuilt light plan, or a moved camera. A defect that comes back after two fixes
belongs to the method, not the dose.
- **Cap:** 4 review rounds a job. At the cap or a stall, deliver and say what's still wrong.
`raea goal check` says it; you don't decide it.
- **Done:** every deliverable on disk, every gate clear, and two fresh critic passes in a row on the latest renders.
- **Stall:** three rounds without beating the best score, or the same defect named twice. Stop tweaking and change
the approach for that part: another route (solid, field, Tripo HD, Meshy), a rebuilt light plan, or a moved camera.
A defect that comes back after two fixes belongs to the method, not the dose.
- **Cap:** 8 critic rounds a job. At the cap or a stall the job is delivered short: status lists what's still
missing, and the Stop hook lets you end with it said.
## Why
- Fixed cameras and a clay pass are what every strong source judges on. Colour hides bad form, and a moving camera
hides regressions.
- A judge that has seen the code grades the intent, not the pixels. A judge that knows the pass line gets gamed.
- Measured checks (lint, light, exposure, gen check) catch what eyes miss: a 3 cm float, a fridge at 4 m tall, a
frame two stops under.
+3 -2
View File
@@ -3,7 +3,7 @@
A shot list in a crew's words ("slow push on the counter, handheld, 35 mm") becomes camera paths that can't lurch,
checked on a framing sheet and for clearance before anything is rendered long. This is AnyShot's loop (MIT) on raea's
camera: `raea/camera` for the moves, `raea make framing` and `lenschart` for the sheets, `raea scene stage
--clearance` for the camera's path through the set. `raea check` holds the job; the Stop hook won't let you end
--clearance` for the camera's path through the set. `raea goal check` holds the job; the Stop hook won't let you end
before it says done.
## What to do
@@ -43,7 +43,8 @@ before it says done.
(`review/lens-SHOT.png`). Pick from it and set the shot's `lens`.
4. **Block it.** `raea make framing` renders every shot's first, middle and last frame onto `review/framing.png`,
stamped with the name and time. Look at every row: the subject in frame at the start and the end, nothing through
a wall.
a wall. Ask it (`raea ask review/framing.png --std make.framing.through_wall --std make.framing.subject_lost`) and
judge it (`raea judge review --kind shot`: framing, move, focus, clearance, continuity, grade).
5. **Clearance.** `raea scene stage SHOT.tsx --clearance 0.45` holds the camera 0.45 m (a carried camera) off every solid part on every frame
(`--clearance 0.15` for a camera on a rig). Glass, decals, volumes and parts under 5 cm are passed over.
6. **Grade.** `<Grade {...gradeLook("cinematic")} />` from `raea/post_process`: clean, cinematic, gritty or vintage,
+2 -3
View File
@@ -16,9 +16,8 @@ Before you say a piece is done, every line here is true of the last render, not
- **Text stays out of the app's buttons.** In a vertical frame with the platform unknown, keep the top 220 px, the
bottom 420, the right 140 and the left 60 clear (TikTok: top 108, bottom 320, right 120; Reels: top 210, bottom 310,
right 84; Shorts: top 120, bottom 300, right 96). A 4:5 feed frame needs top 110, bottom 170, sides 60; a 1:1 frame
top 70, bottom 120, sides 60; 16:9 top and bottom 120, sides 60. The right zone is the app's buttons, which start 45%
down the frame: above them the right edge keeps the left's 60. `<Region>` and `<Captions>` place inside these zones.
These zones are only where text can't go. Where it should go is a design choice.
top 70, bottom 120, sides 60; 16:9 top and bottom 120, sides 60. These zones are only where text can't go. Where it
should go is a design choice.
- **Nothing flashes past the limit.** No more than three flashes in any one second over a sizable part of the frame
(WCAG 2.3.1): past that, flashing can cause seizures. A strobe or a fast flicker needs slowing, shrinking or less contrast.
- **Cues land on their words.** A cut, a move or a caption tied to speech starts on the word, timed from the
+7 -5
View File
@@ -33,13 +33,15 @@ is only context, and context gets lost. Run `pdftotext -layout BRIEF.pdf media/b
- `cta`: the exact line every cut ends on;
- `open`: each [TO CONFIRM], gap or contradiction in it, as a question for the review.
Every rule carries `from`, the brief's own words for it, copied exactly. `raea check` finds each one in
Every rule carries `from`, the brief's own words for it, copied exactly. `raea goal check` finds each one in
media/brief.txt, so a rule can't be made up and a line can't be paraphrased away. Then it holds every file at
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, size and name; what it says, heard after its last change, for each `say`, `never` and the CTA; a word
clipped or missing; a face cut by the frame's edge; text over a face, a sign or the app's buttons; captions over
talking. Every render ends with that check (`raea check CUT --at render`), kept beside the cut; the job isn't done,
and the Stop hook won't let you end, until `raea check --at done` passes and every `open` item has the person's answer, written in with who gave it. Turn a
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 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.
## The decisions
-112
View File
@@ -1,112 +0,0 @@
# brief.ts: the brief as code
A project's brief.ts is a module whose default export is `brief({...})` from `raea/brief`. raea runs it, `raea goal
check` holds the work to its `goal`, and tsc checks it against the same types raea reads. Everything you need to write
one is on this page, so you don't need to open the SDK.
## The shape
```ts
import { brief, cut, rules } from "raea/brief"
export default brief({
title: string, // the project as people name it
for?: string, // the client or person it's for
audience?: string, // who watches, and where
believe?: string, // the one thing they should think afterwards
voice?: string, look?: string, sound?: string,
notDoing?: string[], // the anti-goals
assumed?: string[], // facts you wrote that the person hasn't confirmed, by key ("audience")
sections?: { heading: string, text: string }[],
goal?: Goal | Goal[], // what the work is held to: cut(), rules(), scene(), kit(), shot(), playable()
plan?: PlanFile, // tasks (raea/task plan()), inline or imported
})
```
A goal made with `cut({...})` or `rules({...})` takes these fields:
| Field | What it is |
| --- | --- |
| `aim` | what the goal is, in the person's words |
| `rules` | `{ id, run?, timeout?, file? }[]`: what must hold before you stop (below) |
| `cut` | a cut job's contract, the brief as rules (below) |
| `deliverables` | files that must exist when it's done, relative to brief.ts (a cut goal lists its own) |
| `previews` | what it shows but never delivers (`review/` and `previews/` when left out) |
| `checks` | the project's own `check()`s from raea/check, imported into brief.ts |
| `name`, `after`, `step` | for several goals in order: a goal's name, the goals before it, its workflow step |
## A cut job's contract (`cut: {...}`)
Every `from` is the brief's own words, copied from its text file as they are, so a person can find the line the
rule came from. raea refuses a `from` it can't find.
| Field | Type | What it holds |
| --- | --- | --- |
| `brief` | `string` | the brief as text, relative to brief.ts (`pdftotext -layout brief.pdf brief_docs/brief.txt`) |
| `count` | `{ value: number, from }` | how many cuts the brief asks for. Fewer planned stays open until a person answers an `open` item about `"count"` |
| `seconds` | `[least, most]` | a cut's length when the cut doesn't give its own |
| `formats` | `string[]` | `"9:16"`, `"16:9"`, `"1:1"`, `"4:5"`: every cut's formats when the cut doesn't give its own |
| `cuts` | `CutPlan[]` | one per cut: `{ id, angle?, kind?, hook?, text?, formats?, seconds?, beats? }` |
| `say` | `{ text, from, every? }[]` | what is said or shown in every cut (`every: false`: one cut is enough) |
| `never` | `{ text, from }[]` | what no cut says or shows: a banned claim, a word, a name |
| `cta` | `{ text, from, also?, within? }` | the line every cut ends on, heard or shown in its last `within` seconds (8 by default); `also` lists other lines the brief rotates |
| `open` | `{ question, from, about?, answer?, by? }[]` | the brief's open items (TBD, to confirm). Each holds the job open until a person's answer is written in, with who gave it |
| `frames` | `boolean` | every face whole and every text big enough, in every frame (true by default) |
A cut's `id` is `[a-z0-9_]` and unique. Each format lands as `out/cuts/<id>_<format with x>.mp4`, for example
`out/cuts/a1_s1_9x16.mp4`. `text` is `"captions"`, `"hook"` or `"none"`. `kind` is `"solo"` or `"mashup"`. `hook` is
one of the brief's hook types, as the brief names it.
A cut's `beats` are optional and yours, never the brief's: plan them in your own notes, not in brief.ts, unless the
brief itself sets the cut's pace. When it does, `{ at, asl?, tempo? }[]` (`asl` the beat's average shot length in
seconds, `tempo` `"build"`, `"release"` or `"hold"`) is measured by the montage check, which the brief switches on.
## Rules
| Kind | Example | How it's checked |
| --- | --- | --- |
| `run` | `{ id: "tests", run: "bun test" }` | the command must exit 0 in brief.ts's folder (300 s unless `timeout` says otherwise) |
| `file` | `{ id: "sheet", file: "review/sheet.png" }` | the file must exist (`a\|b`: either one; `dir/`: three or more pictures in it) |
Nothing else is a rule: a sentence that must be true of the work ("the wordmark is on screen at the end") is how you
build it, not something a model grades after (raea docs/check.feature). Where it can be measured, make it a `run`
rule or a `file`; otherwise leave it to the person's review.
## An example
```ts
// brief.ts
import { brief, cut } from "raea/brief"
export default brief({
title: "Juniper Tea · street interviews, round 1",
for: "Juniper Tea",
audience: "TikTok and Reels, 25-40, already buying loose-leaf",
believe: "Juniper tastes like the tea shop, at home",
goal: cut({
aim: "Ten 9:16 cuts from the street interviews, each ending on the free-trial line",
cut: {
brief: "brief_docs/brief.txt",
count: { value: 10, from: "10 unique cuts total" },
seconds: [20, 40],
formats: ["9:16"],
cuts: [
{ id: "a1_s1", angle: "Angle 1", kind: "solo", hook: "Direct Problem", text: "captions" },
{ id: "a1_s2", angle: "Angle 1", kind: "mashup", hook: "Reaction", text: "captions" },
],
say: [{ text: "free shipping over $35", from: "Mention: free shipping over $35", every: false }],
never: [{ text: "cures", from: "Never claim the tea cures or treats anything" }],
cta: { text: "Try Juniper free for 30 days", from: "CTA: \"Try Juniper free for 30 days\"" },
open: [
{
question: "The footage holds 4 usable interviews, not 10: deliver 4 this round?",
from: "10 unique cuts total", about: "count",
// left out until the person answers; then their words and who gave them
answer: "Yes, 4 now and the rest after the reshoot", by: "the client's producer",
},
],
},
}),
})
```
Write it, then run `raea check`. It names each rule that doesn't hold and the line of the brief it came from.
+1 -2
View File
@@ -5,8 +5,7 @@
- Write one file (usually `edit.tsx` at the space's root) that exports the piece's component as its default and
ends with `registerRoot(Root)`. `Root` returns one `<Composition>` per output.
- Give each `<Composition>` an `id`, its `component`, `width`, `height`, `fps` and `durationInFrames`:
- `id` uses letters, digits, hyphens and underscores only (no spaces) and is unique in the root: a deliverable's
name (client_concept_variant_v1) is a good id.
- `id` uses letters, digits and hyphens only (no spaces, no underscores) and is unique in the root.
- `width`, `height` and `durationInFrames` are positive whole numbers, and `fps` is a positive number.
- `defaultProps` (optional) is a plain object of JSON values, which the component receives as its props.
- `controls` (optional) says which of those props a person may tune: see "Controls" below.
+7 -6
View File
@@ -1,14 +1,15 @@
# Rendering and checking: raea render, its one check, stills
# Rendering and checking: raea render, raea check, stills
## What to do
- **The render checks itself, once.** `raea render edit.tsx -o final.mp4 --manifest render.json` ends with `raea
check` on the export and keeps what it found as final.check.json; publishing and a stop read that, and nothing runs
it again (`raea check final.mp4` reads it back). It measures clipped text, text under a platform's buttons, text over the face, captions on too briefly to read,
- **`raea check` after every real change.** Render with the manifest, then check the export against the floor:
`raea render edit.tsx -o final.mp4 --manifest render.json` and
`raea check final.mp4 --manifest render.json --words words.json --perception perception.json [--platform tiktok]`.
It measures clipped text, text under a platform's buttons, text over the face, captions on too briefly to read,
caption contrast against the pixels behind them, frozen stretches, flashing past the limit, cues that miss their word, loudness, a sound that
stops dead or (with `--words`) fights the voice, and encoder blotching in the darks. Each finding is ranked P0 to P3
with its fix; an ERROR is a fault in the export, a warning a note for the person. Fix every ERROR in one pass
before rendering again. `raea floor final.mp4 --words words.json` measures a file raea didn't render. A finding that ends `[also in …]` was in the earlier export too: what you changed
with its fix; it exits 1 while a P0 or P1 stands, and `-o check.json` writes them for the critique. Fix every error
in one pass before rendering again. A finding that ends `[also in …]` was in the earlier export too: what you changed
didn't move it, so don't repeat that change; try another, or say why it stands. A note is for the person, not a
reason to render again. An
exception in the composition (an unclamped value going NaN, keyframes out of order, a phrase `word()` can't find, a
+4 -4
View File
@@ -46,14 +46,14 @@
6 dB under the talking that comes back up where nobody talks, so a wordless end card keeps its music. It is slight
on purpose: set the bed's own level from the table below. `bus="master"` keeps a sound out of it; your own
`Tone.buses` are never changed by it. The check is on the export: the voice at least 10 dB above what's under it
between words (the voice check, which a brief switches on).
between words (`raea goal check`'s voice check).
- Air between words reads as dead air in social cuts and ads, most of all in the first 3 seconds. `tighten(words,
{ levels })` (`import { tighten, airGaps } from "raea"`) returns the spans of a take to keep: each gap cut down to
about 0.15 s in the hook and 0.25 s after, only between words, 80 ms kept either side, and pulled back wherever the
take is still loud (a transcript often ends a word early). Run it on the source take's words (`raea words TAKE`) and
levels, never the mixed export, lay each span as its own `<Video startFrom endAt>`, and read the words pass after.
A hook opens on its first word within about 0.3 s; a board or a sign held in silence for people to read is dead
air, not a hook (the hook and airgaps checks, which a brief switches on).
air, not a hook (`raea goal check`'s hook and airgaps checks).
- Put the sounds in the tree in time order. The engine keys a sound's stretch by its place in the tree, so adding a
sound in the middle of the list can split the ones after it.
- Balance relative to the voice. The approved pieces, mastered to -14 LUFS, sit like this (each a `gainDb` on top of
@@ -104,8 +104,8 @@ everyone else. Two checks, both cheap:
sound loops only between `startFrom` and `endAt`, and that loop is a hard jump. Tile it instead: copies of the take
end to end, each in its own Sequence, crossfading over 1.5 s (`fadeIn`/`fadeOut`), or make the take as long as the
span.
- **Check the finished file.** Its render's check (`raea floor FILM.mp4 --words words.json` on a file raea didn't
render, with the voice's words on the film's clock) reports, by timecode, dead stops (a steady sound that ends in one 10 ms step: fade it out over 100 ms or more;
- **Check the finished file.** `raea check FILM.mp4 --words words.json` (the voice's words on the film's clock)
reports, by timecode, dead stops (a steady sound that ends in one 10 ms step: fade it out over 100 ms or more;
a voice ending its word isn't one), stretches with no voice louder than
the voice, music closer than 12 dB to the voice over it, and a true peak over -1 dBTP. Fix every line it prints, or
say why it stands.
-5
View File
@@ -16,11 +16,6 @@
- Size captions at 60 px or more at 1080 wide (scale with the width), with at least 3:1 contrast against the pixels
behind them. Keep them in one place unless a move means something, and keep them off cards, logos, burned-in text
and the face (`motion/placement`).
- To put a caption or hook in a box that hugs each line, as TikTok draws its text, use `HugText` from
`raea/hug-text`: `<HugText lines={[...]} fill="#E8423F" color="#fff" className="..." />`. Each line gets a fill as
wide as its words, with one rounded shape around them all. You give the lines, so you decide where each breaks
(a caption's come from its word groups). Its emoji draw in colour on any machine, as `EmojiText` from the same
module also does. The box is allowed, never required.
- Mark each caption: `data-raea-role="caption"` on the element holding its words. A layered export (`raea export
capcut`, `raea export xml`; `motion/delivery`) then puts the captions on a track of their own, styled as they're
drawn, and writes their words as an .srt beside them; unmarked, they're part of the graphics.
+5 -4
View File
@@ -19,9 +19,9 @@ cut({ aim: "Three TikTok ads for Choreo", cut: { brief: "brief.md", formats: ["9
] } })
```
Each beat's `feel` and `story` are your plan for the cut: what you build it to do, never a rule it's graded on. `asl`
(the beat's average shot length) and `tempo` (`build`: shots shorter as it goes, `release`: longer, `hold`: even) are
measured by the montage pack, when the brief switches it on (`packs: { montage: true }`).
Each beat's `feel` and `story` are rules a fresh critic judges on the cut as it plays (`raea goal judge`). `asl` (the
beat's average shot length) and `tempo` (`build`: shots shorter as it goes, `release`: longer, `hold`: even) are
measured by the montage pack (`raea goal check`).
## Murch's order: what to give up first
@@ -56,4 +56,5 @@ fine to leave; say why in the cut's notes. One broken at most of a file's cuts i
1. Write each beat's `feel` and `story` first: Murch's top two carry three quarters of his weight.
2. Set each beat's pace (`asl`, `tempo`) for the build-ups and releases you want.
3. Cut on motion and match light across cuts inside a beat.
4. Fix eye trace, screen direction and tone where they don't cost a higher reason, and read the render's check.
4. Run `raea goal check`, then fix eye trace, screen direction and tone where they don't cost a higher reason.
5. Run `raea goal judge` so a fresh critic watches each beat in sequence.
+2 -3
View File
@@ -1,13 +1,12 @@
# critique
When the person asks "is it good?": look at the piece as it rendered, not as you meant it. It's no step in making the
piece: the render's own check (`raea check`) is the only check.
Judge the piece as it rendered, not as you meant it, before you call it done or when the person asks "is it good?".
## How
- Watch the export once, all the way through, at the size it ships, with sound. Then pull stills at the moments that
matter and look at them together.
- Judge it against the brief (`believe:`, `audience:`), the person's taste, the mode's guide and the floor.
- Read the render's check (OUT.check.json) for what was measured, and the rest by the rubric (`raea guide rubric`).
- Run `raea check` for what can be measured, and judge the rest by the rubric (`raea guide rubric`).
## Decide
- Judge against the brief and the mode first, and the person's taste second. Your own taste is the easy default.
+11 -28
View File
@@ -2,7 +2,7 @@
// "3D in the same tree", "Toon surfaces and ink outlines", "The camera's lens", "Motion blur", "Page layers under and
// over the 3D", "Games: state from input, frame by frame").
import { beforeEach, describe, expect, test } from "bun:test";
import { Audio, Captions, Region, lyria, proofBoxes, sao, useGameEvents, useGameState, useInput, useRegion } from "../src";
import { Audio, Region, lyria, proofBoxes, sao, useGameEvents, useGameState, useInput, useRegion } from "../src";
import { Canvas3D, Cylinder, Fisheye, LensDistortion, Model, MotionBlur, Sphere } from "../src/3d";
import { DirectionalLight, Mesh, MeshStandardMaterial, MeshToonMaterial, PointLight } from "@raea/render/three";
// the retired three.js shapes, compared against (M5: no longer exported from raea)
@@ -19,28 +19,24 @@ const near = (a: number, b: number) => expect(Math.abs(a - b)).toBeLessThan(1e-6
describe("Region", () => {
test("auto takes the taller band clear of the face", () => {
renderFrame(<Region><Ask f={() => useRegion()} /></Region>, { ...base, frame: 0, perception: { face } });
// m = 65; the app's UI zones (top 220, bottom 420, right 140 where the band reaches its buttons): top band
// 220..435, bottom band 1045..1500
// m = 65; top band 153.6..435, bottom band 1045..1536
expect(got.name).toBe("auto");
expect(got.x).toBe(65); expect(got.w).toBe(1080 - 65 - 140);
near(got.y, 1045); near(got.h, 455);
expect(got.x).toBe(65); expect(got.w).toBe(950);
near(got.y, 1045); near(got.h, 491);
});
test("top and center by name", () => {
renderFrame(<Region name="top"><Ask f={() => useRegion()} /></Region>, { ...base, frame: 0, perception: { face } });
near(got.y, 220); near(got.h, 435 - 220);
near(got.y, 153.6); near(got.h, 435 - 153.6);
renderFrame(<Region name="center"><Ask f={() => useRegion()} /></Region>, { ...base, frame: 0, perception: { face } });
near(got.y, 0.33 * 1920); near(got.h, 0.34 * 1920);
});
test("without a face: top is the app's top zone (220 px) to 0.45 H, and auto picks it; above the buttons both sides keep the margin", () => {
test("without a face: top is 0.08 H to 0.45 H, and auto picks it", () => {
renderFrame(<Region><Ask f={() => useRegion()} /></Region>, { ...base, frame: 0 });
near(got.y, 220); near(got.h, 864 - 220);
expect(got.x).toBe(65); expect(got.w).toBe(950);
near(got.y, 153.6); near(got.h, 864 - 153.6);
});
test("the safe area moves the edges in, never into the app's zones", () => {
renderFrame(<Region name="top"><Ask f={() => useRegion()} /></Region>, { ...base, frame: 0, perception: { safe: { top: 300, bottom: 1400 } } });
near(got.y, 300); near(got.h, 564);
renderFrame(<Region name="top"><Ask f={() => useRegion()} /></Region>, { ...base, frame: 0, perception: { safe: { top: 100, bottom: 1700 } } });
near(got.y, 220);
test("the safe area moves the edges", () => {
renderFrame(<Region name="top"><Ask f={() => useRegion()} /></Region>, { ...base, frame: 0, perception: { safe: { top: 200, bottom: 1500 } } });
near(got.y, 200); near(got.h, 664);
});
test("no room renders nothing and says why", () => {
const big = { x: 100, y: 100, w: 880, h: 1500 };
@@ -53,7 +49,7 @@ describe("Region", () => {
const html = renderFrame(<Region name="bottom" />, { ...base, frame: 0, perception: { face } });
expect(html).toContain('data-region="bottom"');
expect(html).toContain("--face-top:500px");
expect(html).toContain("--region-height:455px");
expect(html).toContain("--region-height:491px");
});
});
@@ -299,16 +295,3 @@ test("an input changed far back refolds from a let-go state correctly", () => {
for (let g = 0; g < 2999; g++) s = step(s, { keys: input[g]?.keys ?? [] }, g);
expect(got).toBe(s);
});
describe("Captions", () => {
test("a cut's own words (said) caption it inside the app's zones, when the edit's words are another cut's", () => {
const said = [{ text: "So", from: 0, to: 6 }, { text: "fresh.", from: 7, to: 20 }];
const html = renderFrame(<Captions said={said} />, { ...base, frame: 3, words: [{ text: "other", from: 0, to: 30 }] });
expect(html).toContain('data-raea-role="caption"');
expect(html).toContain("So");
expect(html).not.toContain("other");
// the bottom band ends 420 px over the bottom, and its right side keeps the buttons' 140
expect(html).toContain("width:875px");
expect(html).toContain('data-band-bottom="1500"');
});
});
-4
View File
@@ -17,10 +17,6 @@ test("a bad id fails", () => {
expect(() => registerRoot(() => <Composition id="ad 1" component={Uses} width={1080} height={1920} fps={30} durationInFrames={90} />)).toThrow();
});
test("a deliverable's name is an id: underscores pass (12-05)", () => {
expect(() => registerRoot(() => <Composition id="client_concept_hook_v1" component={() => null} width={1080} height={1920} fps={30} durationInFrames={9} />)).not.toThrow();
});
test("registering twice fails", () => {
registerRoot(() => <Composition id="a" component={Uses} width={1080} height={1920} fps={30} durationInFrames={9} />);
expect(() => registerRoot(() => null)).toThrow();
+1 -1
View File
@@ -8,7 +8,7 @@ Feature: raea, the behaviour of its API
Rule: A composition is a component rendered once per frame
Scenario: Declaring and registering
Given `<Composition id component width height fps durationInFrames defaultProps?>` inside the root component
Then the id is letters, digits, hyphens and underscores, unique among the root's compositions; width, height and
Then the id is letters, digits and hyphens, unique among the root's compositions; width, height and
durationInFrames are positive integers and fps a positive number, or registering fails with a message naming
the composition and the field
And `registerRoot(Root)` names the root component the renderer starts from; calling it twice is an error
+2 -23
View File
@@ -1,4 +1,5 @@
// Generated from raea-core-brief (core/brief) by its `goal_declarations`; edit the Rust, not this.
import type { Beat } from "./brief.gen";
export type Goal = { kind: GoalKind,
/**
@@ -232,29 +233,7 @@ text?: string, formats?: Array<string>, seconds?: [number, number],
* the cut's beats in order (docs/goal.feature MK48): what each must make the viewer feel and understand, decided
* before the cut (Murch: emotion and story weigh most), and its pace
*/
beats?: Array<CutBeat>, };
export type CutBeat = {
/**
* where it starts, in seconds from the cut's start (0 for the first)
*/
at: number,
/**
* what the viewer feels here, in the person's words ("the itch of a chore left undone")
*/
feel: string,
/**
* what the viewer understands by its end ("the app does the reminding")
*/
story?: string,
/**
* its average shot length in seconds: the shots inside it average within a third of this
*/
asl?: number,
/**
* how its shot lengths move: "build" (shorter as it goes), "release" (longer) or "hold" (even)
*/
tempo?: string, };
beats?: Array<Beat>, };
export type Phrase = {
/**
-1
View File
@@ -41,7 +41,6 @@ export {
type VolumeProp,
} from "@raea/video/media";
export { word, useWords, findPhrase, type WordOptions } from "@raea/video/words";
export { Captions, groupWords, captionAt, type CaptionsProps } from "@raea/video/captions";
// names a project moving from another React video tool uses (#176)
export { random, interpolateColors, OffthreadVideo, type OffthreadVideoProps } from "./random-colors";
export {
-1
View File
@@ -20,7 +20,6 @@
"./cutout": "./src/cutout.ts",
"./adjust": "./src/adjust.ts",
"./words": "./src/words.tsx",
"./captions": "./src/captions.tsx",
"./airgaps": "./src/airgaps.ts",
"./region": "./src/region.tsx",
"./overlay": "./src/overlay.tsx",
-101
View File
@@ -1,101 +0,0 @@
// <Captions>: a cut's captions from its words, built in (raea docs/check.feature: a rule built into a component can't
// be broken, so its check is a backstop). The words are the edit's own (useWords: what's left after the cut, in this
// Sequence's frames), so a caption never says what isn't heard, and never lags a trim. They are grouped as approved
// pieces group them, drawn in the brand's caption style, inside a Region (the safe area, clear of the face and the
// platforms' buttons), and marked as captions for a layered export. Everything about the look can be changed.
import type { CSSProperties, ReactNode } from "react";
import { useClockState, useCurrentFrame, type TimelineWord } from "@raea/app/clock";
import { Region, type RegionName } from "./region";
import { useWords } from "./words";
export interface CaptionsProps {
/** the band they sit in (Region): "bottom" by default, "top" when something owns the bottom */
region?: RegionName;
/** the cut's words, in frames on its clock, when the edit's own (useWords, from the words.json `raea cut` writes) aren't
* this cut's: an edit holding several cuts passes each its words (12-05: agents with six cuts in one edit wrote their
* own captions at a typed top, in the app's zones, for want of this) */
said?: readonly TimelineWord[];
/** the most words a caption holds (3) */
words?: number;
/** a pause longer than this many frames starts a new caption (8) */
pause?: number;
/** how a misheard word is written on screen, keyed by how the transcript has it, case ignored ({ "dutch": "Dutch" }) */
fix?: Record<string, string>;
/** the size in px at 1080 wide, scaled with the frame's width (84; never under 60) */
size?: number;
/** light the word being said in the brand's accent (true) */
accent?: boolean;
/** merged over the caption's own style */
style?: CSSProperties;
/** Tailwind or CSS classes on the caption */
className?: string;
/** draws one caption yourself: its words, and which one is being said (-1 between words) */
children?: (words: TimelineWord[], saying: number) => ReactNode;
}
/** The edit's words in captions: a new one after `max` words, after a word ending in punctuation, and after a pause of
* more than `pause` frames. */
export function groupWords(words: TimelineWord[], max = 3, pause = 8): TimelineWord[][] {
const groups: TimelineWord[][] = [];
for (const w of words) {
const g = groups[groups.length - 1];
const prev = g?.[g.length - 1];
if (!g || g.length >= max || /[.,?!;:]$/.test(prev!.text) || w.from - prev!.to > pause) groups.push([w]);
else g.push(w);
}
return groups;
}
/** The caption on screen at frame `f`: from its first word until the next starts, or `pause` frames after its last. */
export function captionAt(groups: TimelineWord[][], f: number, pause = 8): number {
return groups.findIndex((g, n) => f >= g[0].from && f < Math.min(groups[n + 1]?.[0].from ?? Infinity, g[g.length - 1].to + pause));
}
const spell = (fix: Record<string, string> | undefined, text: string) => {
if (!fix) return text;
const bare = text.replace(/[.,?!;:]+$/, "");
const said = fix[bare] ?? fix[bare.toLowerCase()];
return said === undefined ? text : said + text.slice(bare.length);
};
/** Captions of everything said in the edit, in the brand's caption style, in a safe band. */
export function Captions({ region = "bottom", said, words: max = 3, pause = 8, fix, size = 84, accent = true, style, className, children }: CaptionsProps) {
const f = useCurrentFrame();
const { width } = useClockState("Captions").config;
const own = useWords();
const groups = groupWords([...(said ?? own)], max, pause);
const i = captionAt(groups, f, pause);
const g = i < 0 ? null : groups[i].map((w) => ({ ...w, text: spell(fix, w.text) }));
const saying = g ? g.findIndex((w) => f >= w.from && f < Math.max(w.to, w.from + 4)) : -1;
const px = Math.max(60, size) * (width / 1080);
return (
<Region name={region} style={{ display: "flex", flexDirection: "column", justifyContent: region === "top" ? "flex-start" : "flex-end", alignItems: "center" }}>
{g ? (
<div
data-raea-role="caption"
className={className}
style={{
maxWidth: "100%",
textAlign: "center",
fontFamily: "var(--brand-font-heading, var(--brand-font, inherit))",
fontWeight: 800,
fontSize: px,
lineHeight: 1.05,
color: "var(--brand-text, #fff)",
textShadow: "0 4px 24px rgba(0,0,0,0.55)",
overflowWrap: "break-word",
...style,
}}
>
{children
? children(g, saying)
: g.map((w, j) => (
<span key={j} style={accent && j === saying ? { color: "var(--brand-accent, #ffd400)" } : undefined}>
{w.text + (j < g.length - 1 ? " " : "")}
</span>
))}
</div>
) : null}
</Region>
);
}
-1
View File
@@ -8,7 +8,6 @@ export * from "./nudge";
export * from "./speed";
export * from "./transition";
export * from "./words";
export * from "./captions";
export * from "./airgaps";
export * from "./region";
export * from "./overlay";
+3 -10
View File
@@ -1,7 +1,6 @@
// Placement from perception, and the proof (spec: "Placement from perception", "The proof").
import { createContext, useContext, type CSSProperties, type ReactNode } from "react";
import { useClockState, type Perception, type Rect } from "@raea/app/clock";
import { rightZone, uiZones } from "./zones";
export type RegionName = "auto" | "top" | "bottom" | "center" | "full";
const NAMES: readonly RegionName[] = ["auto", "top", "bottom", "center", "full"];
@@ -32,10 +31,8 @@ interface Band {
/** Works out the vertical band each name stands for, given perception and the composition size. */
export function regionBand(name: RegionName, width: number, height: number, perception: Perception, margin = 0.06): Band {
const m = Math.round(margin * width);
// the app's UI zones, the same the check holds text to (./zones): a part placed here is never in them
const z = uiZones(width, height);
const edgeTop = Math.max(perception.safe?.top ?? 0, z.top, MIN_BAND * height);
const edgeBottom = Math.min(perception.safe?.bottom ?? height, height - z.bottom);
const edgeTop = perception.safe?.top ?? MIN_BAND * height;
const edgeBottom = perception.safe?.bottom ?? (height > width ? 0.8 : 0.92) * height;
const face = perception.face;
const top: Band = { name: "top", top: edgeTop, bottom: face ? face.y - m : 0.45 * height };
const bottom: Band = { name: "bottom", top: face ? face.y + face.h + m : 0.55 * height, bottom: edgeBottom };
@@ -88,11 +85,7 @@ export function Region({ name = "auto", margin = 0.06, style, className, childre
const face = clock.perception.face;
const band = regionBand(name, width, height, clock.perception, margin);
const m = Math.round(margin * width);
// the sides keep the margin and the app's side zones: the right one (its buttons) where the band reaches them
const z = uiZones(width, height);
const left = Math.max(m, z.left);
const right = Math.max(m, rightZone(z, height, band.bottom));
const box: RegionBox = { name, x: left, y: band.top, w: width - left - right, h: band.bottom - band.top };
const box: RegionBox = { name, x: m, y: band.top, w: width - 2 * m, h: band.bottom - band.top };
const attrs = {
className,
+2 -4
View File
@@ -81,9 +81,7 @@ export interface RegisteredComposition {
controls: Readonly<Record<string, RegisteredControl>>;
}
// underscores too: a deliverable's name (client_concept_variant_v1, raea's naming rule) is its composition's id, and
// an id refused for them cost a render pass (12-05, a run lost 7 minutes)
const ID_PATTERN = /^[A-Za-z0-9_-]+$/;
const ID_PATTERN = /^[A-Za-z0-9-]+$/;
function isJsonLike(v: unknown, seen: Set<unknown>): boolean {
if (v === null || typeof v === "string" || typeof v === "boolean") return true;
@@ -104,7 +102,7 @@ function validate(props: CompositionProps<any>, taken: readonly RegisteredCompos
throw new Error(`${name}: ${field} ${why}`);
};
if (typeof props.id !== "string" || !ID_PATTERN.test(props.id)) {
fail("id", `must be letters, digits, hyphens and underscores, got ${JSON.stringify(props.id)}`);
fail("id", `must be letters, digits and hyphens, got ${JSON.stringify(props.id)}`);
}
if (taken.some((c) => c.id === props.id)) fail("id", "is already used by another composition in this root");
if (typeof props.component !== "function" && (typeof props.component !== "object" || props.component === null)) {
-39
View File
@@ -1,39 +0,0 @@
// The app's UI zones: where a feed's own buttons and words sit over a video, so text raea draws keeps out of them. The
// same table as the check's (apps/check/text zones(), sdk/guides/craft/floor.md): <Region> places inside it and the
// floor measures against it, so a part the component placed is never in the zone the check holds it to (12-05: Region
// kept 8% at the top while the check wanted 220 px, and every title it placed was an error).
/** [top, right, bottom, left] in px at 1080 wide, by shape */
const TABLE: Record<string, [number, number, number, number]> = {
"9:16": [220, 140, 420, 60],
"4:5": [110, 60, 170, 60],
"1:1": [70, 60, 120, 60],
};
/** The right-hand buttons (like, comment, share) start this far down the frame: above it the right edge is clear */
export const RAIL = 0.45;
export interface Zones {
top: number;
right: number;
bottom: number;
left: number;
}
/** The zones of a frame this size, px */
export function uiZones(width: number, height: number): Zones {
const r = width / height;
const shape = r < 0.7 ? "9:16" : r < 0.9 ? "4:5" : r < 1.2 ? "1:1" : "16:9";
if (shape === "16:9") {
const [v, h] = [(120 * height) / 1080, (60 * width) / 1920];
return { top: v, right: h, bottom: v, left: h };
}
const s = width / 1080;
const [top, right, bottom, left] = TABLE[shape].map((v) => v * s);
return { top, right, bottom, left };
}
/** The right zone for a box reaching down to `bottom` px: the rail's where it reaches the rail, else the left's */
export function rightZone(z: Zones, height: number, bottom: number): number {
return bottom > RAIL * height ? z.right : z.left;
}
-21
View File
@@ -1,21 +0,0 @@
// <Captions>'s grouping (raea docs/check.feature: captions built in): what's on screen at each frame.
import { expect, test } from "bun:test"
import { captionAt, groupWords } from "../src/captions"
const w = (text: string, from: number, to: number) => ({ text, from, to })
const said = [w("So", 0, 6), w("it", 7, 10), w("draws", 11, 20), w("names,", 21, 30), w("free", 31, 40), w("fun", 60, 70)]
test("a caption holds up to 3 words, and breaks at punctuation and at a pause", () => {
expect(groupWords(said).map((g) => g.map((x) => x.text).join(" "))).toEqual(["So it draws", "names,", "free", "fun"])
})
test("a caption shows from its first word until the next starts, or a moment after its last word, and never between", () => {
const g = groupWords(said)
expect(captionAt(g, 0)).toBe(0)
expect(captionAt(g, 20)).toBe(0)
expect(captionAt(g, 21)).toBe(1)
// a pause: the caption leaves 8 frames after its last word, so nothing is captioned over silence
expect(captionAt(g, 47)).toBe(2)
expect(captionAt(g, 50)).toBe(-1)
expect(captionAt(g, 61)).toBe(3)
})
+1 -1
Submodule skills updated: a67a08005f...fb72c5e256.
Loaded 100 of 102 files, more files were not shown because too many files have changed in this diff. Show more