Compare commits

..
Author SHA1 Message Date
shinyobjectz e4ded20521 taxonomy: Captions is raea's own name (the one-line captions component) 2026-12-05 08:38:12 -08:00
shinyobjectz ab9f552cd3 goal: the batch critic's test goes with the critic (one check removes raea ask) 2026-12-05 08:31:11 -08:00
shinyobjectz d0de1f3fee check.feature: name the retired frames command without its old name (the legacy-names gate) 2026-12-05 08:30:45 -08:00
shinyobjectz 357941a032 Farm: a piece whose runs draw only stills (a game's capture) is drawn as stills and encoded on the run's GPU
Every run of a playable's capture refused: the file extension .mp4 was not recognized as an image format.
2026-12-05 08:30:43 -08:00
shinyobjectz 5ab59a30be Farm: frame 0's run commits the work folder, so a render's parts don't each rewrite styles.gen.ts at once
Uncommitted, every part's container found styles.gen.ts older than the code and rewrote it on the shared volume,
truncating it under the others: 14 of one cut's parts refused with "couldn't bundle edit.tsx: Unterminated string"
and the cut was lost. Deployed (raea-farm, RAEA_VERSION=0.1.17-rc4).
2026-12-05 08:30:42 -08:00
shinyobjectz 0e376d66ed Farm: the box image's SDK overlay on the release, so a render's Region keeps out of the app's zones
The farm bundles each composition with its own SDK; rc4's has no zones.ts, and titles placed by Region landed at
y=154, inside the top 220 px. Deployed (raea-farm, RAEA_VERSION=0.1.17-rc4).
2026-12-05 08:30:41 -08:00
shinyobjectz 6191d3d7fa Composition ids take underscores: a deliverable's name is its id
The naming rule names cuts client_concept_variant_v1, and registerRoot refused that id, so an agent that used the
deliverable's name lost a render pass (7 minutes in one run).
2026-12-05 08:30:41 -08:00
shinyobjectz c6e1faecd4 AGENTS.md: shorter placement and Framed lines, back under the start-text limit 2026-12-05 08:30:40 -08:00
shinyobjectz 6ed150d21f Captions take a cut's own words; AGENTS.md: captions and titles through Captions and Region, never a typed top
An edit holding several cuts has one words.json, so Captions had no words for each cut and agents wrote their own
captions at a typed top, in the app's UI zones.
2026-12-05 08:30:39 -08:00
shinyobjectz 98beb04318 Sound check: a clip with no well-timed word in it isn't a line held to the others' level
A take whose transcript has broken timing (a word 90 s long) made a 0.6 s pause read as a line 51 dB under the rest.
2026-12-05 08:30:38 -08:00
shinyobjectz 92699313d0 One UI zone table for Region and the check; ERRORs only for the faults a cut's rules name
- sdk/video zones.ts: the app's UI zones, the same table as the floor's zones(). Region's edges and sides keep them,
  so a title or caption it places is never in the zone the check holds it to (Region kept 8% at the top against the
  check's 220 px, and every hook title it placed was an error).
- The right zone is the app's buttons, from 45% down the frame (RAIL), in the Rust floor and in the goal's floor pack
  for a raea from before it: a centred end card above the buttons is clear.
- place: an error over a face or a sign (words in the shot); over another thing the detector names, a warning with
  the clear place said.
- sound: a cut on sound more than 0.6 s from any word is a warning (a laugh, a noise, a missed word), not a word cut.
2026-12-05 08:30:38 -08:00
shinyobjectz 68a5877a30 Captions check: the takes' own words where the edit placed them count as said
The check heard the export a second time, while captions are built from the takes' own transcripts. Run 11: a second hearing wrote the take's "he heard his label paw" as "he sleep with Paul", and "That's" and "take" otherwise, so right captions read as retyped or as dropping words (4 false ERRORs over Dutch's 6 cuts). A caption's letters now count as said when either hearing has them, and words heard but uncaptioned are a fault only when the take's own words there aren't captioned either. A retyped caption is still caught.
2026-12-05 08:30:36 -08:00
shinyobjectz a0f6054a37 Check: "$60" reads as "60 dollars" in what's heard and what's captioned
Dutch run 10: the transcript wrote "sixty dollars" as "$60", the caption wrote it out, and the captions check called "dollars" a word the host never said.
2026-12-05 08:30:35 -08:00
shinyobjectz d6aec574b3 Check: a CTA said in part and shown in part lands; numbers said in words match the brief's digits
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". Heard alone was 79% of the line and shown alone 58%, so 5 of 6 cuts got a false CTA ERROR. The heard words now take numbers in digits (as the captions check does) and the CTA counts what is heard and shown together at the end.
2026-12-05 08:30:34 -08:00
shinyobjectz fc03e3f4b7 AGENTS.md: the brand paragraph in five lines
A box agent starts with at most 2,500 words (docs/check.feature); this paragraph was 150 of them.
2026-12-05 08:30:33 -08:00
shinyobjectz c9dc9af60c AGENTS.md: a take cropped to another shape goes through components/Framed.tsx, never a guessed objectPosition
12-05: agents guessed each 9:16 crop and cut the speaker off at the frame's edge.
2026-12-05 08:30:32 -08:00
shinyobjectz 4246ac76b2 Check: quotes cut by whole characters, and numbers said in words match digits
12-05, Dutch run 9: a caption quoted to 40 UTF-16 units split an emoji, and printing the report broke the check ("Conversion from string failed: invalid utf-8 sequence"). Quotes now cut by code point, and every finding is made well-formed before it's printed or saved. The same cut's caption "24-7" was called a word not said, against "twenty four seven" in the words file: the captions pack now reads numbers in words as digits on both sides.
2026-12-05 08:30:31 -08:00
shinyobjectz c31564db15 Words: Hear on up to 4 GPUs and Align on 3
12-05, run 8: three projects' transcriptions, 8 at a time each, queued on 2 of each class. Elfster's 51 takes took 6.5 minutes and its wait for them ran past the fetch step's 4. Seven of the account's 10 GPUs at a run's start leave 3 for the cuts' first frames; the cuts themselves draw on CPUs.
2026-12-05 08:30:30 -08:00
shinyobjectz abff42d288 Farm: a composition's bundle cached on each container's own disk
12-05, run 6: a job's 32 CPU parts missed the shared bundle cache on the volume at once, each 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 went back to the 10 GPUs, and other jobs' frame-0 probes waited behind them.
2026-12-05 08:30:29 -08:00
shinyobjectz 2b6243d983 One line a rule a file across levels, and no lines.txt note
12-05, run 5: a cut's ERROR and WARN from the same check each took a line, and Dutch's cuts listed 11-12 lines. The worst finding of a rule now leads its one line and the rest are counted under it. The "no lines.txt beside it" note is gone: a hint, not a fault in the cut.
2026-12-05 08:30:28 -08:00
shinyobjectz 73d778f8d8 Sound: a word timed longer than 2.5 s is a transcriber's slip, not a word cut in two
12-04, Elfster run 5: "secret" was timed 143.28-166.96 s, and a clip starting 15 s into it got an ERROR for cutting the word.
2026-12-05 08:30:26 -08:00
shinyobjectz a2d02687ca CTA and must-say read a frame's texts together
12-04, Elfster run 4: the end card drew the CTA as two texts ("Make your Wishlist and organize your Gift Exchange on Elfster." over "It's free."), each alone under the CTA's 85% share, and a cut ending on its CTA was failed for having none. A frame's texts are now read together, in the order drawn.
2026-12-05 08:30:26 -08:00
shinyobjectz 1f3f87b6ea Floor: blocky darks are an error only when the encode is measured to have added them
12-04, one-check proof: Body Shop's cut (17 Mbps) got an ERROR for blocky dark patches that its frame doesn't show at full size; the check couldn't tell the encode from the footage's own compression. Untraced, it's now a warning; the picture's own, no line.
2026-12-05 08:30:23 -08:00
shinyobjectz e4453a23d6 Farm: a volume reload goes next, shared and limited, so a busy farm never loses a finished render
With a dozen cuts in flight, blob uploads and other requests kept the farm API's 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), losing a finished cut. Now a waiting reload holds new users back, a reload that starts after a request asked serves it too, and the wait is held to 100 s and answered with a 503 the box asks again on. test/farm_gate.py runs the class from farm.py: the old gate never reloads behind a stream of users; this one does in 0.16 s.
2026-12-05 08:30:22 -08:00
shinyobjectz 3dd0c05375 raea goal check takes check's flags again: the old name runs, as CK0 says
The help lists check's flags under check alone, so a verb's flags read from it refused `raea goal check OUT --at
render` (raea cloud's render tool) for --at. goal check's arguments are now checked as check's.
2026-12-05 08:30:20 -08:00
shinyobjectz 7034fc5705 raea/goal typechecks: a dead helper gone, shapeOf takes FileFacts' sizes, the montage test's beats are CutBeats 2026-12-05 08:30:18 -08:00
shinyobjectz 4b41bef93f The reading check reads the render's own texts from its manifest (Unrender J2)
What raea drew is checked from the render manifest, never by reading frames (docs/check.feature): the reading pack
takes each text's ink box from the manifest at the captions pack's step, a multi-line card sized by one line, and
reads the export's frames only when no manifest is beside it.
2026-12-05 08:30:17 -08:00
shinyobjectz a5f432bc15 raea cut keeps a take's jump cuts: the second cut on a take doesn't decode it again
raea media cuts decodes every frame of a take (43 s for a 4-minute take on a box), and every raea cut ran it again,
so three cut lists on one take in a step ran past a box step's 3 minutes and the run stopped with nothing made.
The cuts are kept in raea's cache by the take's path, size and time: a second cut on the take took 0.5 s.
2026-12-05 08:30:15 -08:00
shinyobjectz fa80c2666a One check: raea check is the only way any agent's work is checked
docs/check.feature (CK0-CK6). Every rule lives in one of three places: a check, a component or the SDK,
or a skill or retrievable context; a rule that fits none is dropped.

- raea check runs a project's goal at a moment (--at edit|render|publish|done); raea goal check still runs
  as its alias for older tools. raea ask, raea judge, goal seen, goal judge, goal gates and check
  --taste/--quick are refused, naming raea check. raea floor is raea's measures for files outside a goal.
- a render's check runs once as it ends and is kept as OUT.check.json; publish and done reuse it while it
  is no older than the file and its manifest, and every rule says at most one line per file
- the goal SDK has no seen, says, critic, record, notes, stills or surprise packs and no taste or look
  checks; a says rule is reported as unchecked; brief.ts holds only what the brief asks
- the edit-moment hook check is gone; the Stop hook reads the kept check
- <Captions /> (raea/video, exported from raea): words in, the brand's caption style, inside the safe area
- the craft guides and AGENTS.md lose judge tiers, ask, Tone.js and framing="face" text
2026-12-05 08:30:13 -08:00
80 changed files with 1350 additions and 1218 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(["goal", "check", "--at", "done", "--json"]).current_dir(brief.parent()?).env("RAEA_RECORD", "off").output().ok()?;
let out = std::process::Command::new(exe).args(["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}. Keep going: `raea goal check` lists each with its fix; review/goal.json holds them all.", brief.display()))
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()))
}
/// The open items, one line each: each error-level finding (its check and file), then each check that broke.
+6 -37
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: `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.
//! 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.
use serde_json::{Value, json};
use std::path::{Path, PathBuf};
@@ -114,23 +114,6 @@ 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 {
@@ -178,20 +161,8 @@ pub fn hook(args: &[String]) -> R<String> {
}
return Ok(String::new());
}
// 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) })
// 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())
}
#[cfg(test)]
@@ -217,8 +188,6 @@ 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\"`"));
+20 -1
View File
@@ -192,6 +192,10 @@ 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;
@@ -224,7 +228,8 @@ 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;
let zoned = |&[x, y, bw, bh]: &[f64; 4]| y < zt || x + bw > w - zr || y + bh > h - zb || x < zl;
// 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;
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") });
@@ -313,6 +318,20 @@ 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;
+60
View File
@@ -0,0 +1,60 @@
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
+21 -9
View File
@@ -9,13 +9,27 @@ 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", "seen", "judge"];
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."))
}
/// The goal verbs' usage, under the help's (usage.rs reads each verb's flags from it).
pub const GOAL_USAGE: &str = "raea goal check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--manifest render.json] [--json] (every rule each goal of brief.ts is held to at that moment: its kind's packs, its rules and its own checks; with no goal, the floor; every project is also held to `registered`, every raea file reached from brief.ts; review/goal.json; exit 1 on an error. The hook runs it at every save (edit) and stop (done), a render at its end, raea cloud at publish)
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)
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
@@ -42,14 +56,12 @@ pub fn render_moment(args: &[String]) -> i32 {
a.extend(["--manifest".into(), m]);
}
match goal_run(&a) {
Ok(1) => {
println!("fix every ERROR above, then render again");
1
}
// an ERROR is a fault in the deliverable: fix its cause in the composition before this render is handed over
Ok(1) => 1,
Ok(_) => 0,
// no runner (an install without the SDK): the render stands, and says so
Err(e) => {
println!("raea goal check: {e}");
println!("raea check: {e}");
0
}
}
+12 -13
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 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)?)); }
// `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()); }
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,13 +280,12 @@ 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|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
// `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
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 check|tasks|seen|judge|gates|next\n {GOAL_USAGE}")),
Some("goal") => return Err(format!("raea goal tasks|next (raea check checks the work)\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
+18 -23
View File
@@ -79,19 +79,15 @@ 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 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.
- 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.
## raea (everything there is; import from "raea")
@@ -99,19 +95,18 @@ 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 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>,
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>,
<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, 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.
"./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.
Words: useWords() -> [{text, from, to}] (frames, the cuts' words), word("phrase") -> the frame it's said,
findPhrase(words, "phrase", {occurrence, edge: "start" | "end"}).
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.
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.
Composition: registerRoot(() => <Composition id component width height fps durationInFrames />).
Not there: React hooks come from "react" (useMemo, useState), not from raea.
`;
+2 -3
View File
@@ -37,9 +37,8 @@ pub fn main() -> i32 {
}
};
match args.first().map(String::as_str) {
// `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()),
// `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()),
// `ci …`: the gates' sound measurements and lightspeed's process measurements
Some("ci") => raea_app_ci::cli(&args[1..]),
_ => {
+29 -3
View File
@@ -4,8 +4,9 @@
//
// native.ts RAEA VERB ARGS... RAEA: the native raea's path, for the engine's own verbs
import { spawnSync } from "node:child_process";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
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 { basename, delimiter, dirname, extname } from "node:path";
import { brandKit, pixelsOf } from "./brand";
import { readSite, stylesOf } from "./scrape";
@@ -118,6 +119,31 @@ 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
@@ -126,7 +152,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) ? [] : (engineJson(["media", "cuts", at(take), "--threshold", "0.08"]).cuts as { at: number }[]).map((c) => c.at);
const cuts = isAudio(take) ? [] : jumpCuts(take);
const fps = (engineJson(["media", "probe", at(take)]).video?.fps as number) || 30;
let from = 0;
const spans: [number, number][] = [];
-5
View File
@@ -83,11 +83,6 @@ 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,6 +84,9 @@ 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,6 +143,11 @@ 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, goal_ts, render_moment};
pub use raea_cli_goal::{GOAL_TS, GOAL_USAGE, gone, 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"];
+91 -9
View File
@@ -148,8 +148,20 @@ 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)
@@ -173,7 +185,11 @@ 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"}
"__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"}
# the scene reader's models, loaded once a container (/v1/scene)
@@ -197,7 +213,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"]):
for d in (CACHES["__GL_SHADER_DISK_CACHE_PATH"], CACHES["XDG_CACHE_HOME"], CACHES["RAEA_BUNDLE_CACHE"]):
os.makedirs(d, exist_ok=True)
build = os.environ.get("RAEA_FARM_BUILD")
if build and cmd[0] == "raea":
@@ -338,12 +354,43 @@ 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)
@@ -358,6 +405,11 @@ 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()
@@ -574,15 +626,22 @@ 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)
await self.cond.wait_for(lambda: not self.reloading and not self.waiting)
self.users += 1
try:
yield
@@ -591,17 +650,36 @@ def api():
self.users -= 1
self.cond.notify_all()
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 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 with self.cond:
if not wait and (self.users or self.reloading):
if not wait and (self.users or self.reloading or self.waiting):
return False
await self.cond.wait_for(lambda: not self.users and not self.reloading)
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
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:
@@ -612,13 +690,17 @@ 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():
if not await gate.reload(within=RELOAD_WAIT_S):
raise HTTPException(503, "the farm's volume is busy: try again")
def check(req: Request):
+1 -4
View File
@@ -75,9 +75,6 @@ def api():
PROXY_SHORT = 540
PROXY_LIGHT_BPS = 2_500_000
PART = 64 << 20
# every proxy says what it is in its comment tag, and ffmpeg carries the tag into what's made from it: a box's renders
# and publishes read it (raea-platform harness/light.ts) so nothing made from a proxy is shown to a person as a final
LIGHT_TAG = "raea-light-copy"
AGENT = {"user-agent": "raea-ingest/1"}
@@ -163,7 +160,7 @@ def proxy_job(url: str, put: str, ticket: str) -> dict:
scale = f"scale='if(gt(iw,ih),-2,trunc(min({PROXY_SHORT},iw)/2)*2)':'if(gt(iw,ih),trunc(min({PROXY_SHORT},ih)/2)*2,-2)',format=yuv420p"
r = subprocess.run(
["ffmpeg", "-v", "error", "-y", "-i", src, "-map", "0:v:0", "-map", "0:a:0?", "-vf", scale, "-c:v", "libx264", "-preset", "veryfast", "-crf", "28",
"-force_key_frames", "expr:gte(t,n_forced*1)", "-c:a", "aac", "-b:a", "96k", "-ac", "2", "-metadata", f"comment={LIGHT_TAG}", "-movflags", "+faststart", out],
"-force_key_frames", "expr:gte(t,n_forced*1)", "-c:a", "aac", "-b:a", "96k", "-ac", "2", "-movflags", "+faststart", out],
capture_output=True, text=True, timeout=3300,
)
if r.returncode != 0 or not os.path.exists(out):
+5 -2
View File
@@ -38,7 +38,10 @@ 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"}
@app.cls(gpu="L4", image=align_image, volumes={"/models": models}, timeout=900, max_containers=2, scaledown_window=60)
# 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)
class Align:
@modal.enter()
def load(self):
@@ -80,7 +83,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=2, scaledown_window=60)
@app.cls(gpu="T4", image=image, volumes={"/models": models}, timeout=900, max_containers=4, scaledown_window=60)
class Hear:
@modal.enter()
def load(self):
+104
View File
@@ -0,0 +1,104 @@
# 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())
+21 -40
View File
@@ -36,8 +36,6 @@ 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",
@@ -48,55 +46,37 @@ 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",
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",
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",
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 (surprise is on only where a brief turns it on) */
/** 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. */
export const DEFAULTS: Record<GoalKind | "floor", PackName[]> = {
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]
// 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"],
}
/** 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)
@@ -130,7 +110,8 @@ 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 | null | undefined): Contract[] => (!g ? [] : Array.isArray(g) ? g : "steps" in g ? g.steps : [g])
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] : []
/** a goal's name: its own, else its kind's */
export const nameOf = (c: Contract) => c.name ?? c.kind
-14
View File
@@ -17,8 +17,6 @@ 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) */
@@ -50,8 +48,6 @@ 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 {
@@ -142,16 +138,6 @@ 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 goal check`) read
// them. This entry is pure, as brief.ts imports it: the packs (./packs) and the runner (./run, `raea 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"
+79 -15
View File
@@ -18,6 +18,8 @@ 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
@@ -29,9 +31,6 @@ 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
@@ -66,7 +65,6 @@ 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) */
@@ -96,13 +94,14 @@ 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(text)
const key = letters(digitsIn(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))
@@ -149,12 +148,20 @@ 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[]): Finding[] {
export function compare(shown: Shown[], heard: Word[], placed: Word[] = []): Finding[] {
heard = asDigits(heard)
placed = asDigits(placed)
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
// 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
for (const s of shown) {
const f = fit(s.key, heardIn(heard, s.from - 0.8, s.to + 0.4).map((w) => letters(w.text)).join(""))
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
for (let i = 0; i < f.bad.length; ) {
if (!f.bad[i]) { i++; continue }
let j = i
@@ -190,6 +197,17 @@ export function compare(shown: Shown[], heard: Word[]): Finding[] {
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` }
@@ -209,6 +227,7 @@ 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) => {
@@ -234,18 +253,63 @@ 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
const heard = await f.words()
// numbers in words and in digits read alike on both sides (numbers.ts)
const heard = asDigits(await f.words())
if (!heard.length) return
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
// 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 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)].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, own ? await placedWords(f) : [])].sort((a, b) => a.at - b.at)) found({ level: x.level, says: x.says, seconds: x.at })
},
)
+30 -8
View File
@@ -13,6 +13,8 @@ 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 */
@@ -60,6 +62,21 @@ 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
@@ -69,7 +86,8 @@ const cutFile = (f: FileFacts) => {
/** what a cut says and shows */
async function heardOf(f: FileFacts) {
const words = await f.words()
// 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 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) }
@@ -83,7 +101,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} ("${from.slice(0, 60)}")`).join("; ")}` })
if (unfound.length) found({ says: `not in the brief's text, word for word: ${unfound.map(([what, from]) => `${what} ("${quote(from, 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) => {
@@ -117,8 +135,9 @@ 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, screen } = await heardOf(f)
const on = (p: string) => saidAt(spoken, p, SAY_GAP) !== null || screen.some(([s]) => onScreen(s, p, SAY_GAP))
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 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(", ")}` })
})
@@ -143,7 +162,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, screen } = await heardOf(f)
const { times } = 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))
@@ -155,7 +174,10 @@ 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
const shownLate = screen.some(([s, t]) => t >= end - within && lines.some((l) => share(l, s.split(" ")) >= CTA_SHARE))
// 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))
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] })
})
@@ -165,10 +187,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(heardOf))
const heard = await Promise.all(cuts.map(async (f) => ({ ...(await heardOf(f)), together: shownTogether(f.manifest, 0) })))
for (const p of once) {
const n = norm(p.text)
const by = heard.some(({ spoken, screen }) => saidAt(spoken, n, SAY_GAP) !== null || screen.some(([s]) => onScreen(s, n, SAY_GAP)))
const by = heard.some(({ spoken, together }) => saidAt(spoken, n, SAY_GAP) !== null || together.some((s) => onScreen(s, n, SAY_GAP)))
if (!by) found({ says: `no cut says or shows "${p.text}" (brief: "${p.from}")` })
}
})
+32 -3
View File
@@ -19,8 +19,11 @@ 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 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)}`)
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)}`)
return (JSON.parse(readFileSync(out, "utf8")).findings ?? []) as Measured[]
} finally {
rmSync(dir, { recursive: true, force: true })
@@ -53,10 +56,36 @@ 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 floorOf(f.abs, m, f.root)) say(x)
for (const x of faultsOf(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) => {
+2 -1
View File
@@ -13,6 +13,7 @@ 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
@@ -127,7 +128,7 @@ export function smallText(manifest: any): Finding[] {
}
const out: Finding[] = []
for (const [text, { at, px }] of seen) {
const q = text.length > 40 ? `"${text.slice(0, 40)}..."` : `"${text}"`
const q = `"${quote(text, 40)}"`
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)` })
}
+4 -301
View File
@@ -1,312 +1,15 @@
// 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"
// 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").
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 ?? []) {
for (const r of j.contract?.rules ?? []) {
if (!r.run) continue
const { ok, said } = await j.run(r.run, r.timeout ?? TIMEOUT)
if (!ok) found({ says: `${r.id}: \`${r.run}\` ${said}`, about: [r.id] })
}
})
export const saysPack = check<Job>({ id: "says", text: "each `says` rule found true by a fresh critic after the work's last change", over: "job", at: ["done"] }, async (j) => {
const says = saysOf(goalOf(j) ?? null)
if (!says.length) return
let v = verdict(j.root, j.contract!)
// at whole seconds, as the verdict keeps its time: work saved in the second the critic was asked counts as judged
const freshOf = (x: Verdict | null) => !!x && (newest(j.root) === null || x.at >= Math.floor(newest(j.root)! / 1000))
// a verdict missing, stale or short of a rule is asked for here (the check is the one command; the agent never
// judges by hand), where this session has a critic to ask
if (!(freshOf(v) && says.every((r) => v!.rules?.[r.id])) && hasCritic(j.root, says)) {
try {
v = await judge(j.contract!, j.root)
} catch (e) {
found({ says: `the critic couldn't judge: ${(e as Error).message}` })
return
}
}
const fresh = freshOf(v)
for (const r of says) {
const one = v?.rules?.[r.id]
const fix = NO_CRITIC
if (!v) found({ says: `${r.id}: not judged yet`, about: [r.id], fix })
else if (!one) found({ says: `${r.id}: the last judging didn't cover it`, about: [r.id], fix })
else if (!fresh) found({ says: `${r.id}: the work changed after the critic judged it`, about: [r.id], fix })
else if (!one.pass) found({ says: `${r.id}: a fresh critic found it not true yet: ${one.why}`, about: [r.id] })
}
})
/** what the critic is asked: the goal, each `says` rule by id, and the answer's shape. It reads; it changes nothing */
export function prompt(g: Contract, dir: string, only: Said[] = saysOf(g)): string {
const rules = only.map((r) => `- ${r.id}: ${r.says}`)
return `You are a fresh critic. You did none of this work and owe it nothing. The work is in ${dir}: read whatever you need there (its files, its renders, NOTES.md), and change nothing.\n\nThe goal, as the person said it: ${g.aim ?? nameOf(g)}\n\nFor each rule below, decide whether it is true of the work as it is on disk now. Count it true only when you have seen it hold; if you can't tell, it isn't true yet. Say why in one sentence, naming what you looked at.\n\n${rules.join("\n")}\n\nAnswer last with one JSON object and nothing after it: {"rules": {"ID": {"pass": true, "why": "..."}}}`
}
/** the verdict: the object around the text's last "rules" key (a critic may think aloud, or quote the shape, first) */
export function lastVerdict(text: string): Verdict | null {
const key = text.lastIndexOf('"rules"')
if (key < 0) return null
for (let open = text.lastIndexOf("{", key); open >= 0; open = text.lastIndexOf("{", open - 1)) {
let depth = 0
let inStr = false
for (let i = open; i < text.length; i++) {
const ch = text[i]
if (inStr) {
if (ch === "\\") i++
else if (ch === '"') inStr = false
continue
}
if (ch === '"') inStr = true
else if (ch === "{") depth++
else if (ch === "}" && --depth === 0) {
try {
const v = JSON.parse(text.slice(open, i + 1))
if (v && typeof v.rules === "object") return v
} catch {}
break
}
}
}
return null
}
/** where a rule is judged, chosen here and never by the agent (Shane, 12-03): a rule with a piece to watch or hear
* (a file it names, or the videos under out/) by Clef-Omni; any other by a fresh session of the agent this project
* runs on, which the host that started the agent offers as RAEA_JUDGE_URL (raea cloud's box, critic.ts; the raea app) */
const criticUrl = () => process.env.RAEA_JUDGE_URL || null
export const NO_CRITIC = "it's judged by a fresh session of the agent this project runs on, which only an agent session the raea app or raea cloud started has: it's judged when that session checks the goal"
/** whether every rule here can be judged in this session */
export function hasCritic(dir: string, rules: Said[]): boolean {
return !!criticUrl() || rules.every((r) => piecesOf(r, dir).length > 0)
}
const PIECE = /[\w@./-]+\.(?:mp4|mov|webm|m4v|png|jpe?g|webp|wav|mp3|m4a)\b/gi
const VIDEO = /\.(?:mp4|mov|webm|m4v)$/i
/** the videos under out/, newest first */
function made(dir: string): string[] {
const out: { f: string; at: number }[] = []
const walk = (d: string) => {
for (const e of existsSync(d) ? readdirSync(d, { withFileTypes: true }) : []) {
const f = path.join(d, e.name)
if (e.isDirectory()) walk(f)
else if (VIDEO.test(e.name)) out.push({ f, at: statSync(f).mtimeMs })
}
}
walk(path.join(dir, "out"))
return out.sort((x, y) => y.at - x.at).map((x) => path.relative(dir, x.f))
}
/** clef-omni as the critic (`raea ask`, paid as ask is): it watches and hears a piece, and reads no folder. A rule is
* asked of the files it names, in its "from A s to B s" window if it has one, else of every video under out/ (the
* newest CLEF_PIECES), and passes when it's true of each; the rules about one piece go in one call */
const CLEF_PIECES = 12
/** the pieces a rule is about: the files it names that are on disk, else the newest videos under out/ */
function piecesOf(r: Said, dir: string): string[] {
const named = [...new Set(r.says.match(PIECE) ?? [])].filter((f) => existsSync(path.join(dir, f)))
return named.length ? named : made(dir).slice(0, CLEF_PIECES)
}
/** how many `raea ask`s run at once: each is one cut (or one stretch of it) heard and watched; one after another, a
* project's beats took 6-17 minutes of every goal check (12-03, StreetTalk: 18 of them, a cut's beats each a stretch) */
export const CLEF_AT_ONCE = 6
/** `f` on each item, at most `n` at once, the answers in the items' order */
async function pool<T, R>(items: T[], n: number, f: (t: T) => Promise<R>): Promise<R[]> {
const out: R[] = new Array(items.length)
let next = 0
const worker = async () => {
for (let i = next++; i < items.length; i = next++) out[i] = await f(items[i])
}
await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker))
return out
}
export async function clefVerdict(g: Contract, dir: string, ask: Ask = askClef, only: Said[] = saysOf(g)): Promise<Verdict["rules"]> {
const groups = new Map<string, { file: string; from?: string; to?: string; rules: Said[] }>()
const pieces = new Map<string, string[]>()
for (const r of only) {
const files = piecesOf(r, dir)
const w = /from (\d+(?:\.\d+)?) s to (?:(\d+(?:\.\d+)?) s|its end)/.exec(r.says)
pieces.set(r.id, files)
for (const file of files) {
const key = [file, w?.[1], w?.[2]].join("\u001f")
const at = groups.get(key) ?? { file, from: w?.[1], to: w?.[2], rules: [] }
at.rules.push(r)
groups.set(key, at)
}
}
const got = new Map<string, { pass: boolean; why: string }[]>()
const list = [...groups.values()]
const heard = ask === askClef && !asyncSpawn()
? askClefMany(dir, list.map((k) => ({ file: k.file, says: k.rules.map((r) => r.says), from: k.from, to: k.to })))
: await pool(list, CLEF_AT_ONCE, async (k) => ask(dir, k.file, k.rules.map((r) => r.says), k.from, k.to))
for (const [j, k] of list.entries()) {
const answers = heard[j]
k.rules.forEach((r, i) => got.set(r.id, [...(got.get(r.id) ?? []), { pass: answers[i]?.choice === "true" && !answers[i]?.problem, why: `${k.file}: ${answers[i]?.problem ?? answers[i]?.says ?? "no answer"}` }]))
}
const rules: Verdict["rules"] = {}
for (const r of only) {
const a = got.get(r.id) ?? []
const open = a.filter((x) => !x.pass)
rules[r.id] = !pieces.get(r.id)?.length
? { pass: false, why: "it names no file on disk and out/ holds no video yet, so there's nothing to watch or hear" }
: { pass: !open.length, why: (open.length ? open : a).map((x) => x.why).join("; ") }
}
return rules
}
type Answer = { choice?: string; says?: string; problem?: string | null }
type Ask = (dir: string, file: string, says: string[], from?: string, to?: string) => Answer[] | Promise<Answer[]>
const askArgs = (file: string, says: string[], from?: string, to?: string) => ["ask", file, ...says, "--choose", "true,false", "--json", ...(from ? ["--from", from] : []), ...(to ? ["--to", to] : [])]
const rowsOf = (out: string) => out.split("\n").flatMap((l) => { try { const o = JSON.parse(l); return o.answer ? [o as Answer] : [] } catch { return [] } })
/** whether this runtime has an async spawn (raea's own has only spawnSync) */
const asyncSpawn = () => typeof (cp as { spawn?: unknown }).spawn === "function"
/** every ask at once where there's no async spawn (raea's runtime): one shell runs them CLEF_AT_ONCE at a time, each
* into its own file under review/ (12-04, StreetTalk round 18: asked one after another, a stop's 18 beats took 7.7 of
* its 10.5 minutes) */
export function askClefMany(dir: string, jobs: { file: string; says: string[]; from?: string; to?: string }[]): Answer[][] {
if (!jobs.length) return []
const tmp = path.join(dir, "review", `.ask-${process.pid}-${Date.now()}`)
mkdirSync(tmp, { recursive: true })
const sq = (t: string) => `'${t.replace(/'/g, `'\\''`)}'`
const lines = jobs.map((k, i) => `${[RAEA, ...askArgs(k.file, k.says, k.from, k.to)].map(sq).join(" ")} > ${sq(`${tmp}/${i}.out`)} 2> ${sq(`${tmp}/${i}.err`)} &${(i + 1) % CLEF_AT_ONCE === 0 ? "\nwait" : ""}`)
try {
const r = cp.spawnSync("sh", ["-c", [...lines, "wait"].join("\n")], { cwd: dir, encoding: "utf8" }) as { error?: Error }
if (r.error) throw new Error(`couldn't run raea ask: ${r.error.message}`)
const read = (f: string) => (existsSync(f) ? String(readFileSync(f, "utf8")) : "")
return jobs.map((k, i) => {
const rows = rowsOf(read(`${tmp}/${i}.out`))
if (rows.length !== k.says.length) throw new Error(`raea ask answered ${rows.length} of ${k.says.length} about ${k.file}: ${read(`${tmp}/${i}.err`).trim().slice(-300) || read(`${tmp}/${i}.out`).trim().slice(-300)}`)
return rows
})
} finally {
rmSync(tmp, { recursive: true, force: true })
}
}
/** `raea ask` on one file (or a stretch of it): run as a child, so several hear at once */
function askClef(dir: string, file: string, says: string[], from?: string, to?: string): Promise<Answer[]> {
const args = askArgs(file, says, from, to)
// where there's no async spawn (raea's runtime), one at a time (clefVerdict asks them all at once: askClefMany)
if (!asyncSpawn()) {
const r = cp.spawnSync(RAEA, args, { cwd: dir, encoding: "utf8" }) as { stdout?: string; stderr?: string; error?: Error }
if (r.error) return Promise.reject(new Error(`couldn't run raea ask: ${r.error.message}`))
const rows = rowsOf(String(r.stdout ?? ""))
if (rows.length !== says.length) return Promise.reject(new Error(`raea ask answered ${rows.length} of ${says.length} about ${file}: ${String(r.stderr ?? "").trim().slice(-300) || String(r.stdout ?? "").trim().slice(-300)}`))
return Promise.resolve(rows)
}
return new Promise((ok, no) => {
const c = cp.spawn(RAEA, args, { cwd: dir, stdio: ["ignore", "pipe", "pipe"] })
let out = "", err = ""
c.stdout.setEncoding("utf8").on("data", (t: string) => (out += t))
c.stderr.setEncoding("utf8").on("data", (t: string) => (err = (err + t).slice(-4000)))
c.on("error", (e) => no(new Error(`couldn't run raea ask: ${e.message}`)))
c.on("close", () => {
const rows = rowsOf(out)
if (rows.length !== says.length) return no(new Error(`raea ask answered ${rows.length} of ${says.length} about ${file}: ${err.trim().slice(-300) || out.trim().slice(-300)}`))
ok(rows)
})
})
}
/** the goal's `says` rules judged (`raea goal check` asks this itself; `raea goal judge` too): each where it's judged
* (criticUrl above), its verdict kept at review/judge/NAME.json, stamped with when it was asked (so work changed while
* it judged counts as changed after) */
export async function judge(g: Contract, dir: string, o: { ask?: typeof askClef; agent?: (cwd: string, prompt: string) => Promise<string> } = {}): Promise<Verdict> {
const all = saysOf(g)
if (!all.length) throw new Error(`goal ${nameOf(g)} has no \`says\` rules; its \`run\` and \`file\` rules are held by raea goal check`)
const asked = Math.floor(Date.now() / 1000)
const watched = all.filter((r) => piecesOf(r, dir).length > 0)
const read = all.filter((r) => !watched.includes(r))
// what's watched and heard, and what's read, at once: neither waits on the other
const [heard, said] = await Promise.all([
watched.length ? clefVerdict(g, dir, o.ask ?? askClef, watched) : Promise.resolve({} as Verdict["rules"]),
read.length ? (o.agent ?? askAgent)(dir, prompt(g, dir, read)) : Promise.resolve(null),
])
const rules: Verdict["rules"] = { ...heard }
if (said !== null) {
const v = lastVerdict(said)
if (!v) throw new Error(`the critic gave no verdict: ${said.slice(-300).trim()}`)
for (const r of read) rules[r.id] = v.rules?.[r.id] ?? { pass: false, why: "the critic didn't answer this rule" }
}
return keep(g, dir, { at: asked, by: [watched.length ? "clef" : "", read.length ? "agent" : ""].filter(Boolean).join("+"), goal: g.aim ?? nameOf(g), rules })
}
/** a fresh session of this project's own agent, through the host that started it (RAEA_JUDGE_URL): what it says */
async function askAgent(cwd: string, p: string): Promise<string> {
const url = criticUrl()
if (!url) throw new Error(NO_CRITIC)
const r = await fetch(url, { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${process.env.RAEA_JUDGE_TOKEN ?? ""}` }, body: JSON.stringify({ cwd, prompt: p }), signal: AbortSignal.timeout(15 * 60_000) })
const j = (await r.json().catch(() => ({}))) as { text?: string; error?: string }
if (!r.ok || typeof j.text !== "string") throw new Error(j.error ?? `the critic answered ${r.status}`)
return j.text
}
function keep(g: Contract, dir: string, out: Verdict): Verdict {
const file = path.join(dir, verdictPath(g))
mkdirSync(path.dirname(file), { recursive: true })
writeFileSync(file, `${JSON.stringify(out, null, 2)}\n`)
return out
}
export const hasVerdict = (dir: string, g: Contract) => existsSync(path.join(dir, verdictPath(g)))
+5 -11
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, stillsPack } from "./floor.ts"
import { floorPack } from "./floor.ts"
import frames from "./frames.ts"
import montage from "./montage.ts"
import { runPack, saysPack } from "./goal.ts"
import { criticPack, deliverablesPack, notesPack, recordPack } from "./job.ts"
import { seenPack, surprisePack } from "./look.ts"
import { runPack } from "./goal.ts"
import { deliverablesPack } from "./job.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,8 +31,6 @@ export const PACK_CHECKS: Record<PackName, Check[]> = {
frames: [frames],
montage: [montage],
place: [place],
seen: [seenPack],
surprise: [surprisePack],
naming: [naming],
sizes: [sizes, allSizes],
quotes: [quotesPack],
@@ -43,12 +41,8 @@ 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],
}
+3 -61
View File
@@ -1,23 +1,12 @@
// 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"
// 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"
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 */
@@ -62,50 +51,3 @@ 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
@@ -1,86 +0,0 @@
// 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 [] } })
}
+93
View File
@@ -0,0 +1,93 @@
// 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(" ")
+6 -2
View File
@@ -17,6 +17,7 @@ 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) */
@@ -255,14 +256,17 @@ 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 = `${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 q = `“${quote(on.text, 40)}”${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)
const hard = under.some((u) => u !== "a person in the shot")
// 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"))
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` })
+28 -10
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 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.
// 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.
//
// 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,7 +12,8 @@
import { check, found } from "raea/check"
import type { FileFacts } from "../facts.ts"
import type { Word } from "../media.ts"
import { captionsOf, fit, type Frame, LEAST, letters, type Read, similar } from "./captions.ts"
import { captionsOf, fit, type Frame, framesOfManifest, LEAST, letters, type Read, similar } from "./captions.ts"
import { quote } from "../text.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 }
@@ -96,24 +97,41 @@ export function reading(blocks: Block[]): Finding[] {
const up = b.to - b.from
const n = need(b.words)
if (up >= n) continue
const quote = b.text.length > 70 ? `${b.text.slice(0, 67)}...` : b.text
const said = quote(b.text, 67)
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: `"${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` })
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` })
}
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
const sc = await f.scene()
const frames: Frame[] = sc.scenes.map((s) => ({ h: s?.h ?? 1, lines: (s?.texts ?? []) as Read[] }))
// 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[] }))
if (!frames.some((x) => x.lines.length)) return
const rate = sc.rate || 2
const rate = own ? own.rate : sc!.rate || 2
const heard = await f.words()
const caps = captionsOf(frames, rate, heard)
const caps = captionsOf(own ? framesOfManifest(f.manifest)!.frames : 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
@@ -0,0 +1,34 @@
// 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; height?: number }): string | null {
export function shapeOf(f: { path: string; kind?: string; width?: number | null; height?: number | null }): string | null {
const named = sizeOf(f.path)
if (named) return named
if (f.kind !== "video" || !f.width || !f.height) return null
+16 -3
View File
@@ -29,6 +29,8 @@ 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
@@ -102,6 +104,9 @@ 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
@@ -134,7 +139,9 @@ 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
}
const word = words.find((w) => w.start + 0.02 < t && w.end - 0.02 > t)
// 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 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
@@ -152,7 +159,10 @@ 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)
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)}` })
// 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)}` })
}
}
return out
@@ -217,7 +227,10 @@ 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))
heard.push({ clip: c, kind, level: speechLevel(l, c.at, c.at + dur, words) + (c.gainDb ?? 0) })
// 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) })
} 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
@@ -1,35 +0,0 @@
// 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 } : {}) })
}
})
+2 -1
View File
@@ -11,6 +11,7 @@
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 }
@@ -80,7 +81,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: `"${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` })
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` })
}
return out.sort((a, b) => a.at - b.at)
}
-2
View File
@@ -5,7 +5,6 @@
// 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"
@@ -130,6 +129,5 @@ 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` })
},
)
+79 -71
View File
@@ -1,41 +1,81 @@
// `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` (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 check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--manifest M] [--json]
// raea 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 (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.
// `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.
// 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, saysOf, unknownPacks } from "./contract.ts"
import { type Contract, type Goals, goalsOf, momentsOf, nameOf, packsOf, 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 */
const ALWAYS: Check[] = [registeredPack, tastePack]
/** 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[] = []
/** a finding as `raea goal check` reports it: its goal, its check, the file it's in, and where in it */
/** 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 */
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[] }
@@ -118,8 +158,10 @@ 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 goal check --json lists them)`))
out.push(...unknownPacks(c).map((k) => `${at}packs.${k}: raea has no pack of that name (raea 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
}
@@ -162,9 +204,16 @@ 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) keep(contract ? name : null, f, await runOnce([{ check: c, on: f, fps: f.fps }]))
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 }]))
}
}
const mine = findings.slice(before)
const errors = mine.filter((x) => x.level === "error").length
@@ -172,6 +221,8 @@ 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",
@@ -199,7 +250,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"), 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"), checks: r.checks, findings: mine }, null, 1)}\n`)
}
}
@@ -216,7 +267,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"} 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`)
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`)
return t.join("\n")
}
@@ -226,11 +277,8 @@ 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 goal check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--json]
const USAGE = `raea 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> {
@@ -238,7 +286,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 goal check: --at is one of ${MOMENTS.join(", ")}`)
console.error(`raea check: --at is one of ${MOMENTS.join(", ")}`)
return 2
}
const files = positional(a, ["--at", "--only", "--manifest", "--goal"])
@@ -246,7 +294,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 goal check: ${(e as Error).message}`)
console.error(`raea check: ${(e as Error).message}`)
return 2
}
writeReport(r, r.files.filter((f) => files.some((n) => path.resolve(n) === path.join(r.root, f))))
@@ -254,33 +302,6 @@ 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()
@@ -303,19 +324,6 @@ 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,3 +64,18 @@ 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
}
-25
View File
@@ -1,25 +0,0 @@
import { expect, test } from "bun:test"
import { spawnSync } from "node:child_process"
import { mkdtempSync } from "node:fs"
import { tmpdir } from "node:os"
import path from "node:path"
// raea's own runtime has no async spawn, so clefVerdict asks every question through one shell (askClefMany): six at
// once, each answer in its job's order (12-04: one after another, a stop's 18 beats took 7.7 minutes). A child with a
// stand-in raea (a second an ask), since RAEA is read once, as goal.ts is loaded
test("askClefMany asks every job at once, CLEF_AT_ONCE at a time, and keeps each job's answers", () => {
const dir = mkdtempSync(path.join(tmpdir(), "raea-ask-many-"))
const script = `
import { askClefMany } from ${JSON.stringify(path.join(import.meta.dir, "../src/packs/goal.ts"))}
const jobs = Array.from({ length: 6 }, (_, i) => ({ file: "out/cut " + i + "'s.mp4", says: i % 2 ? ["one", "two"] : ["one"], from: "1", to: "2" }))
const t0 = Date.now()
const got = askClefMany(${JSON.stringify(dir)}, jobs)
console.log(JSON.stringify({ ms: Date.now() - t0, n: got.map((r) => r.length), file: got[1][0].file }))
`
const r = spawnSync("bun", ["-e", script], { encoding: "utf8", env: { ...process.env, RAEA_REAL: path.join(import.meta.dir, "fixtures/fake-ask/raea") } })
expect(r.stderr.trim().split("\n").filter((l) => /error/i.test(l))).toEqual([])
const o = JSON.parse(r.stdout.trim().split("\n").at(-1)!)
expect(o.ms).toBeLessThan(3_000)
expect(o.n).toEqual([1, 2, 1, 2, 1, 2])
expect(o.file).toBe("out/cut 1's.mp4")
})
+19
View File
@@ -93,3 +93,22 @@ 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
@@ -0,0 +1,46 @@
// 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 the craft by default, surprise only when asked", () => {
test("a cut holds only the rules that catch real faults (docs/check.feature CK2)", () => {
const on = packsOf(cut({ cut: { brief: "b.txt" } }))
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")
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")
expect(packsOf(cut({ cut: { brief: "b.txt" }, packs: { place: false } }))).not.toContain("place")
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(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(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", "captions", "voice", "reading", "hook", "airgaps", "floor", "seen", "stills"])
expect(packsOf(null)).toEqual(["frames", "place", "captions", "floor", "render"])
})
test("a project's own check runs at its moments", async () => {
+28 -1
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, floor: false, stills: false, seen: false, naming: false, sizes: false, hook: false, airgaps: false },
packs: { words: false, sound: false, frames: false, place: false, captions: false, floor: false, render: false, naming: false, sizes: false, quotes: true },
cut: {
brief: "media/brief.txt",
count: { value: 2, from: "10 total videos" },
@@ -128,3 +128,30 @@ 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)
})
-5
View File
@@ -1,5 +0,0 @@
#!/bin/sh
# a stand-in `raea ask FILE SAYS... --choose true,false --json`: one answer a line for each SAYS, after a second
sleep 1
shift; f=$1; shift
for a in "$@"; do case "$a" in --*) break;; esac; echo "{\"answer\":\"a\",\"file\":\"$f\",\"choice\":\"true\",\"says\":\"true (0.9)\",\"problem\":null}"; done
+20 -1
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 { floorOf, type Measured } from "../src/packs/floor.ts"
import { faultsOf, 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,3 +50,22 @@ 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])
})
+5 -131
View File
@@ -1,15 +1,10 @@
// 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" }]))
@@ -26,81 +21,6 @@ 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"]])
@@ -108,12 +28,6 @@ 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
@@ -121,49 +35,9 @@ test("a check runs only at its moments", async () => {
expect((await goalCheck({ cwd: d, at: "done" })).checks).toContain("run")
})
test("clef judges a rule on the file it names, else on every video made, and says when there's nothing to watch", async () => {
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 = await 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((await 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)
})
test("clef hears several cuts at once, and the critic reads while it does", async () => {
const d = mkdtempSync(path.join(tmpdir(), "raea-goal-clef-at-once-"))
mkdirSync(path.join(d, "out/cuts"), { recursive: true })
const names = ["a", "b", "c", "d", "e", "f", "g", "h"]
for (const n of names) writeFileSync(path.join(d, `out/cuts/${n}_9x16.mp4`), "x")
const g = { name: "rules", rules: [{ id: "seen", says: "No caption covers a face" }] } as never
let now = 0, most = 0
const rules = await clefVerdict(g, d, async (_dir, _file, says) => {
most = Math.max(most, ++now)
await new Promise((ok) => setTimeout(ok, 20))
now--
return says.map(() => ({ choice: "true", says: "fine" }))
})
expect(most).toBe(6)
expect(rules.seen?.pass).toBe(true)
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")
})
-40
View File
@@ -1,40 +0,0 @@
// 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()
})
+1 -10
View File
@@ -5,8 +5,7 @@ import { spawnSync } from "node:child_process"
import { mkdtempSync } from "node:fs"
import { tmpdir } from "node:os"
import path from "node:path"
import type { Beat } from "raea/brief.gen"
import { saysOf } from "../src/contract.ts"
import type { CutBeat as Beat } from "raea/brief.gen"
import { acrossCuts, cutsOf, pace, read, tau } from "../src/packs/montage.ts"
const W = 96
@@ -74,11 +73,3 @@ 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
@@ -0,0 +1,31 @@
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"])
})
+3 -2
View File
@@ -20,11 +20,12 @@ 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))
assert.equal(c[0].level, "error")
// 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.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 an error, moved to the clear ground under it; the hook over passers-by is fine")
ok("a caption over the dog is a warning, 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,3 +33,24 @@ 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,8 +38,15 @@ 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[] = []
@@ -97,3 +104,13 @@ 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)
})
+1 -13
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,15 +41,3 @@ 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
@@ -0,0 +1,15 @@
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)
})
+1 -1
View File
@@ -112,7 +112,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:** judge the piece honestly before you call it done.
- **critique:** when the person asks "is it good?": an honest look at the piece as it rendered.
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.
+4 -5
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 goal check` holds you to it
anything costs much. This is AnyKit's loop (MIT), each step on a `raea make` verb; `raea check` holds you to it
and the Stop hook won't let you end before it says done.
## What to do
@@ -31,10 +31,9 @@ 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 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.
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.
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.
+27 -86
View File
@@ -1,28 +1,25 @@
# Scene prompts: the brief, the builder and the judge
# Scene prompts: the brief and the builder
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.
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.
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.
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).
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; a fresh judge each round; stop after two clean reads.
- kiln and prasenx: fixed clay and colour cameras, the same every round.
## 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, then the judge prompt (section 3) in a new context
and `raea judge` on the same sheets.
3. After every stage and every fix, run step R: the review sheets, looked at by you, and the render's own check.
## 1. The brief template
@@ -43,8 +40,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, for the judge only; they never ship
{ /* media/ref/real-*.jpg, role: judge-only */ },
// real photos, to compare against; they never ship
{ /* media/ref/real-*.jpg, role: compare-only */ },
],
notDoing: [
// the do-not-add list: without it the builder adds rain, neon and UI
@@ -60,7 +57,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; judge rounds cap (8)]" },
{ heading: "Budget", text: "[gen cents cap; review rounds cap (4)]" },
],
});
```
@@ -71,8 +68,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 judge check
against:
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:
```ts
import { parts } from "raea/brief";
@@ -143,90 +140,34 @@ 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.
- 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.
- 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.
- Re-run the stage's checks after every fix. A fix that breaks a check is not done.
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.
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.
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 judge prompt, the plans or the review cameras to pass.
- Never edit 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.
- 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.
- 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.
## 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 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.
- 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.
+23 -42
View File
@@ -1,25 +1,24 @@
# Whole scenes: brief, build, review, judge
# Whole scenes: brief, build, review
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 by a judge that has never seen the code. This is the loop the people
reviewed from the same fixed cameras every round, and checked once by `raea check` as each render ends. 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, the builder prompt and the judge prompt to paste are in `bevy/prompts`. A kit of props is
The brief template and the builder 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 goal check`
### 0. The job: `make` on brief.ts, held by `raea 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 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 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 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.
@@ -30,7 +29,7 @@ The brief template, the builder prompt and the judge prompt to paste are in `bev
`<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 goal check` until you build it up and replan it, keep the camera
Two levels finer is an error; one holds `raea 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.
@@ -53,7 +52,7 @@ The brief template, the builder prompt and the judge prompt to paste are in `bev
- Wear.
- Printed matter.
- Motion.
- Budget: generation cents and judge rounds.
- Budget: generation cents and review 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`.
@@ -125,10 +124,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` and `raea check out/scene.mp4`.
`read={false}`. Then `raea render EDIT.tsx -o out/scene.mp4`: it checks its export as it ends (`raea check`).
- 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 check out/scene.mp4 --things things.json`. It finds a thing floating or passing through another, the
`raea floor 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
@@ -142,47 +141,29 @@ 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".
- Hand the sheets to the judge (below). Fix every blocking defect it names, or write down why it is wrong and what
you checked.
- Read the render's check and fix every ERROR in it. A warning is a note for the person.
- Change one thing per material per round. Re-run the stage's checks after every fix.
### The judge, and the gates
### The checks
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`).
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.
### Stopping
`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.
- **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.
## 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.
+2 -3
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 goal check` holds the job; the Stop hook won't let you end
--clearance` for the camera's path through the set. `raea check` holds the job; the Stop hook won't let you end
before it says done.
## What to do
@@ -43,8 +43,7 @@ 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. 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).
a wall.
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,
+3 -2
View File
@@ -16,8 +16,9 @@ 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. 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. 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.
- **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
+5 -7
View File
@@ -33,15 +33,13 @@ 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 goal check` finds each one in
Every rule carries `from`, the brief's own words for it, copied exactly. `raea 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 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
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
pack off on the contract (`packs: { place: false }`) only when the brief says so.
## The decisions
+9 -23
View File
@@ -28,7 +28,7 @@ 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?, says? }[]`: what must hold before you stop (below) |
| `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) |
@@ -57,11 +57,9 @@ A cut's `id` is `[a-z0-9_]` and unique. Each format lands as `out/cuts/<id>_<for
`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 decided before it's cut, in order: `{ at, feel, story?, asl?, tempo? }[]`. `at` is where the beat
starts, in seconds from the cut's start (0 for the first). `feel` is what the viewer feels there, in the person's
words, and `story` is what they understand by its end. A fresh critic watches each beat for both. `asl` is the beat's
average shot length in seconds, and `tempo` is how its shot lengths move: `"build"` (shorter as it goes), `"release"`
(longer) or `"hold"` (even). The montage check holds the cut to them.
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
@@ -69,11 +67,9 @@ average shot length in seconds, and `tempo` is how its shot lengths move: `"buil
| --- | --- | --- |
| `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) |
| `says` | `{ id: "logo_end", says: "The wordmark is on screen in each cut's last 3 seconds" }` | words that must be true of the work, judged by a fresh critic, never by you |
You don't run the critic yourself or choose it: `raea goal check` asks for a verdict when one is missing or older than
the work. A `says` rule about a video ("in each cut's last 3 seconds") is watched and heard. One about files or text
is read.
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
@@ -94,14 +90,7 @@ export default brief({
seconds: [20, 40],
formats: ["9:16"],
cuts: [
{
id: "a1_s1", angle: "Angle 1", kind: "solo", hook: "Direct Problem", text: "captions",
beats: [
{ at: 0, feel: "caught off guard, curious", story: "she's a real tea drinker, not an actor", asl: 1.5, tempo: "build" },
{ at: 4, feel: "the small sadness of bad tea at home", story: "bagged tea tastes like paper to her", asl: 3, tempo: "hold" },
{ at: 14, feel: "the surprise of a good first sip", story: "Juniper is the shop's taste at home", asl: 2, tempo: "release" },
],
},
{ 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 }],
@@ -116,11 +105,8 @@ export default brief({
},
],
},
rules: [
{ id: "wordmark_end", says: "The Juniper wordmark is on screen in each cut's last 3 seconds" },
],
}),
})
```
Write it, then run `raea goal check`. It names each rule that doesn't hold and the line of the brief it came from.
Write it, then run `raea check`. It names each rule that doesn't hold and the line of the brief it came from.
+2 -1
View File
@@ -5,7 +5,8 @@
- 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 and hyphens only (no spaces, no underscores) and is unique in the root.
- `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.
- `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.
+6 -7
View File
@@ -1,15 +1,14 @@
# Rendering and checking: raea render, raea check, stills
# Rendering and checking: raea render, its one check, stills
## What to do
- **`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,
- **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,
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; 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
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
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 (`raea goal check`'s voice check).
between words (the voice check, which a brief switches on).
- 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 (`raea goal check`'s hook and airgaps checks).
air, not a hook (the hook and airgaps checks, which a brief switches on).
- 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.** `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;
- **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;
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.
+4 -5
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 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`).
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 }`).
## Murch's order: what to give up first
@@ -56,5 +56,4 @@ 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. 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.
4. Fix eye trace, screen direction and tone where they don't cost a higher reason, and read the render's check.
+3 -2
View File
@@ -1,12 +1,13 @@
# critique
Judge the piece as it rendered, not as you meant it, before you call it done or when the person asks "is it good?".
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.
## 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.
- Run `raea check` for what can be measured, and judge the rest by the rubric (`raea guide rubric`).
- Read the render's check (OUT.check.json) for what was measured, and 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.
+28 -11
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, Region, lyria, proofBoxes, sao, useGameEvents, useGameState, useInput, useRegion } from "../src";
import { Audio, Captions, 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,24 +19,28 @@ 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; top band 153.6..435, bottom band 1045..1536
// 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
expect(got.name).toBe("auto");
expect(got.x).toBe(65); expect(got.w).toBe(950);
near(got.y, 1045); near(got.h, 491);
expect(got.x).toBe(65); expect(got.w).toBe(1080 - 65 - 140);
near(got.y, 1045); near(got.h, 455);
});
test("top and center by name", () => {
renderFrame(<Region name="top"><Ask f={() => useRegion()} /></Region>, { ...base, frame: 0, perception: { face } });
near(got.y, 153.6); near(got.h, 435 - 153.6);
near(got.y, 220); near(got.h, 435 - 220);
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 0.08 H to 0.45 H, and auto picks it", () => {
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", () => {
renderFrame(<Region><Ask f={() => useRegion()} /></Region>, { ...base, frame: 0 });
near(got.y, 153.6); near(got.h, 864 - 153.6);
near(got.y, 220); near(got.h, 864 - 220);
expect(got.x).toBe(65); expect(got.w).toBe(950);
});
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("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("no room renders nothing and says why", () => {
const big = { x: 100, y: 100, w: 880, h: 1500 };
@@ -49,7 +53,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:491px");
expect(html).toContain("--region-height:455px");
});
});
@@ -295,3 +299,16 @@ 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,6 +17,10 @@ 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 and hyphens, unique among the root's compositions; width, height and
Then the id is letters, digits, hyphens and underscores, 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
+1
View File
@@ -41,6 +41,7 @@ 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,6 +20,7 @@
"./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
@@ -0,0 +1,101 @@
// <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,6 +8,7 @@ export * from "./nudge";
export * from "./speed";
export * from "./transition";
export * from "./words";
export * from "./captions";
export * from "./airgaps";
export * from "./region";
export * from "./overlay";
+10 -3
View File
@@ -1,6 +1,7 @@
// 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"];
@@ -31,8 +32,10 @@ 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);
const edgeTop = perception.safe?.top ?? MIN_BAND * height;
const edgeBottom = perception.safe?.bottom ?? (height > width ? 0.8 : 0.92) * height;
// 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 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 };
@@ -85,7 +88,11 @@ 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);
const box: RegionBox = { name, x: m, y: band.top, w: width - 2 * m, h: band.bottom - band.top };
// 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 attrs = {
className,
+4 -2
View File
@@ -81,7 +81,9 @@ export interface RegisteredComposition {
controls: Readonly<Record<string, RegisteredControl>>;
}
const ID_PATTERN = /^[A-Za-z0-9-]+$/;
// 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_-]+$/;
function isJsonLike(v: unknown, seen: Set<unknown>): boolean {
if (v === null || typeof v === "string" || typeof v === "boolean") return true;
@@ -102,7 +104,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 and hyphens, got ${JSON.stringify(props.id)}`);
fail("id", `must be letters, digits, hyphens and underscores, 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
@@ -0,0 +1,39 @@
// 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
@@ -0,0 +1,21 @@
// <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
View File
@@ -94,3 +94,4 @@ raea BevyApp Bevy's App as a TypeScript object for programs (App is its
raea BevyComponent any reflected Bevy component on an entity by its type path (the TypeRegistry)
raea BevyResource any reflected Bevy resource by its type path (the TypeRegistry)
raea UiTexture the UI roots a Camera2d with RenderTarget::Image draws into a named image (Bevy spreads it over camera, target and UiTargetCamera)
raea Captions raea's own: a cut's spoken words as captions, one line, in the brand's caption style and the safe area; the check reads them from the manifest