Compare commits

...
40 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
shaneandshinyobjectz 67277ab967 The farm joins a clip across a run's seam whatever its React key (#334)
Each run numbers its React nodes its own way, so one clip came back keyed n3 then n11 by turns, split at each seam, and
raea goal check's sound pack called every seam a cut inside a word: on two of round 22's cuts, 7 of 11 and 13 of 15 of
those errors (found by the pre-render check's engine work, raea #333). Pieces of the same source that meet in frames at
the source time they should now join whole. Deployed to raea-farm as v42 on 12-04.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-05 08:27:56 -08:00
shaneandshinyobjectz 4695f03650 raea goal check runs on raea's runtime again: no named import of spawn (#329)
* raea goal check runs on raea's own runtime again: no named import of spawn

#323 imported spawn from node:child_process for parallel raea ask; raea's runtime (engine/native/src/node.js) has
spawnSync and no spawn, and the named import failed the whole module, so every raea goal check on a box died before it
read a file (raea 0.1.17-rc4) and no StreetTalk cut could publish. A namespace import; spawn where it exists, spawnSync
one at a time where it doesn't. Checked on raea-5 against the installed runtime: the check runs and reports.

* Box image: overlay goal.ts (the spawn fix) on releases that still have the fault

The image installs raea from a release tarball, so the fix reaches boxes only with a new release. Until then the image
copies the fixed goal.ts over the installed one, and only while the installed file still has the named spawn import.

* raea goal check asks Clef six at a time on raea's own runtime too

With no async spawn (raea's runtime), clefVerdict's pool ran every raea ask one after another: StreetTalk round 18's
stop (12-04) spent 7.7 of its 10.5 minutes on 18 beats. askClefMany runs them all through one spawnSync'd shell,
CLEF_AT_ONCE at a time, each into its own file under review/. Measured on raea-4 with that project: the whole done check
in 157 s, the same verdict (14 of 18). The box image's overlay takes the same file.

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-12-05 08:27:49 -08:00
shaneandshinyobjectz 41fbcfc2ab A render sends the farm only the video and audio its source names (#326)
12-03: every StreetTalk run's first render, a few stills included, hashed and uploaded all of footage/ and
footage/originals/ (36-51 takes and several GB of full-size originals) to the farm's cache one file at a time, and
Elfster's stills render ran past its 5-minute step limit. Video and audio that no source file names, by path, file
name or stem with its folder, now stays on the box, out of the tar and the cache (media.ts unusedMedia); when none is
named, all of it goes, as before, and RAEA_CLOUD_GPU_ALL_MEDIA=1 sends it all regardless. The cache's uploads run four
at a time. Test: node sdk/cloud/test/unused-media.ts

Co-authored-by: shinyobjectz <[email protected]>
2026-12-05 08:27:43 -08:00
shane bec1ab1947 Merge pull request #325 from shinyobjectz/idle-real-path
A box's idle stop sees work by its folder's real path; box.sh holds the box while unpacking
2026-12-03 22:19:39 -08:00
shinyobjectz c261ecdfbc box.sh image on a clean tree: its label's dirty test ended the script under set -e, saying nothing 2026-12-03 21:18:41 -08:00
shinyobjectz 712e5ba3a0 A box's idle stop sees work in its folder by the folder's real path too; box.sh holds the box while it unpacks
On a Fly box the work folder is /home/sprite/work, a link to /home/raea/work, and /proc names a process's folder
without the link: a 64 GB unpack in it was taken for idle and the box stopped under it (12-03, raea-3).
2026-12-03 20:48:01 -08:00
shaneandshinyobjectz 51e2d87c76 HugText taught with captions (the skills gate rc3 failed on), a request counts as the box at work until it ends, and box.sh move resumes an arrived home and says what it unpacks (#324)
12-03: a box stopped as idle the moment a 19-minute upload ended (only its start counted), cutting off the unpack that
followed; an unpack of 26 GB said nothing for 3 minutes and was stopped as stalled.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-03 20:38:05 -08:00
shaneandshinyobjectz 9fed1783dc raea cloud's boxes as Fly Machines; 2D farm renders out at once, stragglers sent again (#323)
* raea cloud's boxes as Fly Machines, and a 2D render's runs out at once with stragglers sent again

Boxes: deploy/fly (image, start, box.sh up/move/latest), the server stops itself when idle (idle.ts), a file PUT
streams to disk, the client sends a Sprite's token only to a Sprite (CL16).
Farm: a video with no 3D goes out at once on up to the job's containers (no timed first run), a run hanging back is
sent again and the first answer kept, and containers with no GPU stay warm 180 s.

* The public guard passes raea cloud's box users' folders (/home/sprite, /home/raea); the Fly box scripts are executable

* A goal's says rules judged at once: up to 6 cuts heard by Clef together, and the critic reads while they're heard

One raea ask after another, a project's beats took 6-17 minutes of every goal check (12-03, StreetTalk).

* A box takes a request as long as its body takes (Node's 5 minutes cut a home's upload at 408); box.sh move stops when the home didn't arrive whole

* A box's files route in its own module, streamed both ways; box.sh move says what has arrived every 15 s and stops a copy that stops growing for 2 minutes

main.ts was 520 lines (tools/size.sh). Shane 12-03: fail fast at every step.

* farm: each step after the draw says how long it took when it took a second or more

A render whose every frame was kept took 64 s between "nothing to draw" and "joined" (12-03), and nothing said where.

* An agent socket whose caller answers no ping in 3 minutes is ended, and its agent with it; box.sh restarts a box only for a new image, and its copy reconnects to the Sprite

12-03: a stopped StreetTalk project's Gemini, busy so never idle, went on an hour running goal checks on raea-5: its caller
(the API, restarted) had gone with the box's half of the socket open. A Machine restarted by box.sh up after its health
check passed cut three homes' uploads off; and sprite exec lost all four copies' sessions at once, 6 minutes in, without
reconnecting while stdin was attached (--no-stdin).

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-12-03 20:02:40 -08:00
shaneandshinyobjectz 23918c2c23 Pin raea-skills at ff03a87: references for v0.1.17-rc3 (#322)
Co-authored-by: shinyobjectz <[email protected]>
2026-12-03 19:00:17 -08:00
shaneandshinyobjectz c5c87e2cfb raea guide brief: brief.ts's types and an example, and a cut's beats typed as they are (#321)
Dutch's plan turn (12-03) spent about 2 minutes looking for raea/brief's types: raea guide brief had no guide, so it
read sdk/raea/src under /opt/raea. And what it found was wrong: brief-goal.gen.ts imported the screenplay's Beat
(onScreen, lines, cues) for a cut's beats, while cut.rs's own Beat (at, feel, story, asl, tempo, MK48) is what raea
reads and validates. tsc refused a correct cut beat and accepted a wrong one.

- core/brief: a cut's beat is CutBeat in TypeScript and declared in brief-goal.gen.ts (regenerated); montage.ts uses it.
- sdk/guides/craft/motion/brief.md: the Brief fields, a cut goal's contract, rules and who judges a says rule (raea,
  never the agent), and a fictional example that type-checks against the SDK; the router points to it.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-03 17:50:07 -08:00
shaneandshinyobjectz 743b35677c Judges never pick a harness: a fresh session of the project's own agent, or Clef (#320)
Shane, 12-03: nothing judges or checks with another harness, and nothing the agent reads makes it choose a harness,
model or provider. Dutch's plan turn spent about 3 minutes on raea goal judge --by claude (not signed in on a box),
--by clef (no video at plan) and --by kimi (not on PATH), because sdk/goal spawned claude -p and kimi -p itself.

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

Co-authored-by: shinyobjectz <[email protected]>
2026-12-03 17:50:03 -08:00
116 changed files with 2923 additions and 1182 deletions

No files matched your search

Generated
+1
View File
@@ -13820,6 +13820,7 @@ dependencies = [
"fastrand", "fastrand",
"raea-app-check", "raea-app-check",
"raea-app-double", "raea-app-double",
"raea-io-clef",
"raea-io-home", "raea-io-home",
"raea-sys-columns", "raea-sys-columns",
"raea-sys-fingerprint", "raea-sys-fingerprint",
+2 -2
View File
@@ -52,7 +52,7 @@ pub fn stop(v: &Value) -> Option<String> {
let cwd = PathBuf::from(v["cwd"].as_str()?); let cwd = PathBuf::from(v["cwd"].as_str()?);
let brief = brief_with_job(&cwd)?; let brief = brief_with_job(&cwd)?;
let exe = std::env::current_exe().ok()?; 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 r: Value = serde_json::from_slice(&out.stdout).ok()?;
let home = raea_io_home::user_home()?; let home = raea_io_home::user_home()?;
let session = v["session_id"].as_str().unwrap_or(""); 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 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(", ")) }; 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. /// 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 //! --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 //! 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 //! 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 //! file is saved: nothing (docs/check.feature: a render checks its own output at its end). As a turn ends: `raea check
//! 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 //! --at done` on the brief's goals (apps/check/make), which reads each deliverable's kept check. After any tool, and as
//! the raea app (inbox.rs). A stop is exit 2 with the reason on stderr, which every harness hands its agent; the edit //! a turn ends: what the person sent from the raea app (inbox.rs). A stop is exit 2 with the reason on stderr, which
//! moment's findings go back in the shape each one reads. //! every harness hands its agent; what was sent goes back in the shape each one reads.
use serde_json::{Value, json}; use serde_json::{Value, json};
use std::path::{Path, PathBuf}; 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.") 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 /// 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. /// plain stdout, Claude Code's and Codex's PostToolUse context.
fn after(agent: &str, text: &str) -> String { fn after(agent: &str, text: &str) -> String {
@@ -178,20 +161,8 @@ pub fn hook(args: &[String]) -> R<String> {
} }
return Ok(String::new()); 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 // no check after a save (docs/check.feature CK1): a render checks its own output at its end, once
// on any file under a brief; a save that passes says nothing Ok(sent.map(|t| after(agent, &t)).unwrap_or_default())
let me = std::env::current_exe().map_err(|e| e.to_string())?;
let mut found = Vec::new();
for path in saved(&v).iter().filter(|p| held_at_edit(Path::new(p))) {
let dir = Path::new(path).parent().filter(|d| d.is_dir()).map(Path::to_path_buf).unwrap_or_else(|| PathBuf::from(v["cwd"].as_str().unwrap_or(".")));
let Ok(out) = std::process::Command::new(&me).args(["goal", "check", "--at", "edit"]).arg(path).current_dir(dir).env("RAEA_RECORD", "off").output() else { continue };
if out.status.code() == Some(1) {
found.extend(String::from_utf8_lossy(&out.stdout).lines().filter(|l| !l.starts_with("PASSED")).map(String::from));
}
}
let edit = (!found.is_empty()).then(|| format!("raea goal check --at edit after this save:\n{}", found.join("\n")));
let text = [sent, edit].into_iter().flatten().collect::<Vec<_>>().join("\n\n");
Ok(if text.is_empty() { String::new() } else { after(agent, &text) })
} }
#[cfg(test)] #[cfg(test)]
@@ -217,8 +188,6 @@ mod tests {
assert_eq!(agent_of(&json!({"hook_event_name": "PreToolUse", "tool_name": "Bash"})), "claude"); 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": "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!(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_eq!(after("kimi", "x"), "x");
assert!(after("gemini", "x").contains("AfterTool") && after("codex", "x").contains("PostToolUse")); assert!(after("gemini", "x").contains("AfterTool") && after("codex", "x").contains("PostToolUse"));
assert!(steer(&["a b.png".into()]).contains("`raea show \"a b.png\"`")); 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) /// 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] { pub fn zones(w: f64, h: f64, shape: Option<&str>, platform: Option<&str>) -> [f64; 4] {
let r = w / h; 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 [x, y, bw, bh] = r.box_;
let q = quote(&r.text); 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 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) { if r.boxes.iter().all(off) {
clipped += 1; 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") }); 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)] #[cfg(test)]
mod tests { 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 super::*;
use serde_json::json; use serde_json::json;
+2
View File
@@ -15,6 +15,8 @@ raea-sys-fingerprint = { path = "../../systems/fingerprint" }
raea-sys-fingerprint-use = { path = "../../systems/fingerprint-use" } raea-sys-fingerprint-use = { path = "../../systems/fingerprint-use" }
# score --ask: each flag asked again of the decision model (docs/ask.feature AK8) # score --ask: each flag asked again of the decision model (docs/ask.feature AK8)
raea-app-double = { path = "../double" } raea-app-double = { path = "../double" }
# the critic a note is read by: a fresh session of the project's own agent (critic.rs)
raea-io-clef = { path = "../../io/clef" }
raea-sys-fingerprint-things = { path = "../../systems/fingerprint-things" } raea-sys-fingerprint-things = { path = "../../systems/fingerprint-things" }
# the encoders and the columns they make # the encoders and the columns they make
raea-sys-columns = { path = "../../systems/columns" } raea-sys-columns = { path = "../../systems/columns" }
+2 -3
View File
@@ -21,13 +21,13 @@ use std::path::Path;
pub use serve::serve; pub use serve::serve;
pub const USAGE: &str = "raea fingerprint new NAME [--who W] [--about TEXT] [--extends FP] [--kinds K,K] [--tags T,T] | raea fingerprint bootstrap FILE... [--from LIST] [--per N] | raea fingerprint teach FILE --axis A --at T [--bad|--good] [--span S] [--box x0,y0,x1,y1] [--words W] [--project P] | raea fingerprint approve FILE... [--project P] | raea fingerprint pair WORSE BETTER --axis A [--at T] [--then T2] | raea fingerprint versions V1 V2... | raea fingerprint profile REFS... --as NAME [--against LIST] | raea fingerprint score FILE [--was OLD] [--ask flags|unsure] [--json] [--sheet out.png] [--timeline] [--profile NAME] | raea fingerprint report [--json] | raea fingerprint which [PATH] [--json] | raea fingerprint use NAME [--in project|workspace] [PATH] | raea fingerprint diff A B [--json] | raea fingerprint share NAME [--in project|workspace] [PATH] | raea fingerprint reembed PLACE... | raea fingerprint read PROJECT [--by kimi|claude] | raea fingerprint readings [PROJECT] [--ask N] [--tally] | raea fingerprint learn-notes [PROJECT] | raea fingerprint move [--fp CHILD] [--to PARENT] [--axis A] [--source S] [--project P] | raea fingerprint postmortem [PROJECT] [--ask N] [--tally] | raea fingerprint things FILE [--project P] [--json] | raea fingerprint stop [--fp NAME] (a person's sense of good work as axes with small heads over on-device encoders, docs/fingerprint.md: new makes ~/.raea/fingerprints/NAME with raea's base taxonomy in fingerprint.ts (or FP's axes with --extends), what it's for, the kinds of piece and project tags it judges, and every axis scoring from its words; bootstrap puts known defects into windows of real work and trains the mechanical axes, held out by source, and patch heads that say where in the frame a picture defect is; teach adds a label at a moment; approve makes approved work clean on every axis, away from its notes; pair says one moment is better than another on an axis (a pick, a hand edit); versions makes weak pairs of noted moments the next version changed; score prints the moments it expects a note on first (where in the frame, and the layers there, when its patch head points held out), then every axis per window with --json, a sheet PNG with --sheet, or the piece second by second in words with --timeline, and with --was OLD whether each of OLD's gating flags is fixed, still there, or looks disguised (nearer the axis's disguised defects than clean work), and with --ask flags each flag put to clef again on its own window, whether clef agrees said beside it and kept as clef's evidence (unsure: the moments it's unsure of too); profile takes the ranges of work you admire (loudness, tilt, cut rate, motion, brightness, contrast, saturation, sharpness), checked leave-one-out, and score --profile says what falls outside them, where and which way; report says each head's held-out score, labels, cheats, gate and what it can't judge; which says the one that judges a piece (its project's, its workspace's, then yours) and why, use pins one there, diff lists the axes two fingerprints rank the same evidence most differently on, and share copies one's taxonomy and evidence (no heads, no media) into a project or workspace for its team; reembed moves a fingerprint's evidence to this machine's encoders, re-embedding the rows whose media it finds; read has a fresh kimi or claude session read a project's pinned notes into kinds and axes, readings puts them to you to check and tallies your answers, and learn-notes makes the defects and praise evidence once you've agreed with 45 kinds and 40 axes in 50, each project's in the fingerprint that judges it; move takes a child's own labels (by axis, source or project) up into a fingerprint it extends, which never reads them otherwise; postmortem scores every version in a project's feed and asks you at most ten yes/no questions in the app, each with its moment playing, where the fingerprint disagrees with your labels or is least sure, and --tally makes your answers evidence and says how each head's held-out score moved; things finds a piece's shots, its things (a render's layers, and the marks drawn on its notes) with their depth, and the camera's path, and says where a thing floats, two pass through each other, the camera lurches mid-move or nothing is on screen, as JSON for `raea check --things` with --json)"; pub const USAGE: &str = "raea fingerprint new NAME [--who W] [--about TEXT] [--extends FP] [--kinds K,K] [--tags T,T] | raea fingerprint bootstrap FILE... [--from LIST] [--per N] | raea fingerprint teach FILE --axis A --at T [--bad|--good] [--span S] [--box x0,y0,x1,y1] [--words W] [--project P] | raea fingerprint approve FILE... [--project P] | raea fingerprint pair WORSE BETTER --axis A [--at T] [--then T2] | raea fingerprint versions V1 V2... | raea fingerprint profile REFS... --as NAME [--against LIST] | raea fingerprint score FILE [--was OLD] [--ask flags|unsure] [--json] [--sheet out.png] [--timeline] [--profile NAME] | raea fingerprint report [--json] | raea fingerprint which [PATH] [--json] | raea fingerprint use NAME [--in project|workspace] [PATH] | raea fingerprint diff A B [--json] | raea fingerprint share NAME [--in project|workspace] [PATH] | raea fingerprint reembed PLACE... | raea fingerprint read PROJECT | raea fingerprint readings [PROJECT] [--ask N] [--tally] | raea fingerprint learn-notes [PROJECT] | raea fingerprint move [--fp CHILD] [--to PARENT] [--axis A] [--source S] [--project P] | raea fingerprint postmortem [PROJECT] [--ask N] [--tally] | raea fingerprint things FILE [--project P] [--json] | raea fingerprint stop [--fp NAME] (a person's sense of good work as axes with small heads over on-device encoders, docs/fingerprint.md: new makes ~/.raea/fingerprints/NAME with raea's base taxonomy in fingerprint.ts (or FP's axes with --extends), what it's for, the kinds of piece and project tags it judges, and every axis scoring from its words; bootstrap puts known defects into windows of real work and trains the mechanical axes, held out by source, and patch heads that say where in the frame a picture defect is; teach adds a label at a moment; approve makes approved work clean on every axis, away from its notes; pair says one moment is better than another on an axis (a pick, a hand edit); versions makes weak pairs of noted moments the next version changed; score prints the moments it expects a note on first (where in the frame, and the layers there, when its patch head points held out), then every axis per window with --json, a sheet PNG with --sheet, or the piece second by second in words with --timeline, and with --was OLD whether each of OLD's gating flags is fixed, still there, or looks disguised (nearer the axis's disguised defects than clean work), and with --ask flags each flag put to clef again on its own window, whether clef agrees said beside it and kept as clef's evidence (unsure: the moments it's unsure of too); profile takes the ranges of work you admire (loudness, tilt, cut rate, motion, brightness, contrast, saturation, sharpness), checked leave-one-out, and score --profile says what falls outside them, where and which way; report says each head's held-out score, labels, cheats, gate and what it can't judge; which says the one that judges a piece (its project's, its workspace's, then yours) and why, use pins one there, diff lists the axes two fingerprints rank the same evidence most differently on, and share copies one's taxonomy and evidence (no heads, no media) into a project or workspace for its team; reembed moves a fingerprint's evidence to this machine's encoders, re-embedding the rows whose media it finds; read has a fresh session of the project's own agent read its pinned notes into kinds and axes, readings puts them to you to check and tallies your answers, and learn-notes makes the defects and praise evidence once you've agreed with 45 kinds and 40 axes in 50, each project's in the fingerprint that judges it; move takes a child's own labels (by axis, source or project) up into a fingerprint it extends, which never reads them otherwise; postmortem scores every version in a project's feed and asks you at most ten yes/no questions in the app, each with its moment playing, where the fingerprint disagrees with your labels or is least sure, and --tally makes your answers evidence and says how each head's held-out score moved; things finds a piece's shots, its things (a render's layers, and the marks drawn on its notes) with their depth, and the camera's path, and says where a thing floats, two pass through each other, the camera lurches mid-move or nothing is on screen, as JSON for `raea check --things` with --json)";
/// Evaluates a .ts file's default export to its JSON (the CLI's spec host) /// Evaluates a .ts file's default export to its JSON (the CLI's spec host)
pub type Eval = fn(&Path) -> Result<String, String>; pub type Eval = fn(&Path) -> Result<String, String>;
/// The flags each verb takes, and whether each takes a value /// The flags each verb takes, and whether each takes a value
pub(crate) const FLAGS: [(&str, bool); 31] = [ pub(crate) const FLAGS: [(&str, bool); 30] = [
("--fp", true), ("--fp", true),
("--was", true), ("--was", true),
("--to", true), ("--to", true),
@@ -51,7 +51,6 @@ pub(crate) const FLAGS: [(&str, bool); 31] = [
("--as", true), ("--as", true),
("--against", true), ("--against", true),
("--profile", true), ("--profile", true),
("--by", true),
("--ask", true), ("--ask", true),
("--tally", false), ("--tally", false),
("--bad", false), ("--bad", false),
+11 -32
View File
@@ -1,5 +1,5 @@
//! Notes become evidence (docs/fingerprint.feature FP5a, FP5b). `raea fingerprint read PROJECT [--by kimi|claude]` //! Notes become evidence (docs/fingerprint.feature FP5a, FP5b). `raea fingerprint read PROJECT` has a fresh session of
//! has a fresh agent session read each pinned note on the project's videos into a kind (defect, direction, praise or //! the project's own agent (its host's critic, raea_io_clef::critic; never one raea or the agent picks) read each pinned note on the project's videos into a kind (defect, direction, praise or
//! both) and an axis from the fingerprint's own axes, kept in the fingerprint's readings.jsonl. Nothing trains on them //! both) and an axis from the fingerprint's own axes, kept in the fingerprint's readings.jsonl. Nothing trains on them
//! yet: `raea fingerprint readings --ask N` puts N readings to the person as questions in the app (`raea show //! yet: `raea fingerprint readings --ask N` puts N readings to the person as questions in the app (`raea show
//! --question`, answers to the "fingerprint" inbox), `readings --tally` counts how often the person agreed, and only //! --question`, answers to the "fingerprint" inbox), `readings --tally` counts how often the person agreed, and only
@@ -99,30 +99,9 @@ pub fn fold(notes: &mut [Reading], fp: &Fingerprint, ans: &[Value], by: &str) {
} }
} }
/// One fresh session's words: kimi's or claude's stream, the assistant's text joined /// One fresh session of the project's own agent, through its host (raea_io_clef::critic): its words
fn ask(by: &str, p: &str) -> Result<String, String> { fn ask(cwd: &Path, p: &str) -> Result<String, String> {
let mut c = std::process::Command::new(by); raea_io_clef::critic::ask(cwd, p)
match by {
"kimi" => c.args(["-p", p, "--output-format", "stream-json"]),
"claude" => c.args(["-p", p, "--output-format", "stream-json", "--verbose", "--allowedTools", ""]),
o => return Err(format!("--by {o}: kimi or claude")),
};
let out = c.output().map_err(|e| format!("couldn't run {by}: {e}"))?;
let mut text = String::new();
for line in String::from_utf8_lossy(&out.stdout).lines() {
let Ok(v) = serde_json::from_str::<Value>(line) else { continue };
let content = if v["role"] == "assistant" { &v["content"] } else if v["type"] == "assistant" { &v["message"]["content"] } else if v["type"] == "result" { &v["result"] } else { continue };
match content {
Value::String(s) => text += s,
Value::Array(a) => a.iter().filter_map(|p| p["text"].as_str()).for_each(|s| text += s),
_ => {}
}
text.push('\n');
}
if text.trim().is_empty() {
return Err(format!("{by} said nothing: {}", String::from_utf8_lossy(&out.stderr).lines().last().unwrap_or("")));
}
Ok(text)
} }
pub fn readings_of(dir: &Folder) -> Vec<Reading> { pub fn readings_of(dir: &Folder) -> Vec<Reading> {
@@ -133,12 +112,12 @@ pub fn write_readings(dir: &Folder, r: &[Reading]) -> std::io::Result<()> {
std::fs::write(dir.dir.join("readings.jsonl"), r.iter().filter_map(|x| serde_json::to_string(x).ok()).map(|l| l + "\n").collect::<String>()) std::fs::write(dir.dir.join("readings.jsonl"), r.iter().filter_map(|x| serde_json::to_string(x).ok()).map(|l| l + "\n").collect::<String>())
} }
/// `raea fingerprint read PROJECT [--by kimi|claude]` /// `raea fingerprint read PROJECT`
pub(crate) fn read_here(args: &[String], cwd: &Path) -> i32 { pub(crate) fn read_here(args: &[String], cwd: &Path) -> i32 {
let run = || -> Result<String, String> { let run = || -> Result<String, String> {
let w = words(args)?; let w = words(args)?;
let project = w.first().map_or(cwd.to_path_buf(), |p| cwd.join(p)); let project = w.first().map_or(cwd.to_path_buf(), |p| cwd.join(p));
let by = flag(args, "--by").unwrap_or("kimi"); let by = "agent";
let dir = crate::pick::chosen(args, Some(&crate::pick::piece_in(args, cwd))).0; let dir = crate::pick::chosen(args, Some(&crate::pick::piece_in(args, cwd))).0;
let fp = dir.read(None).map_err(|e| e.to_string())?; let fp = dir.read(None).map_err(|e| e.to_string())?;
let mut notes = pinned(&project); let mut notes = pinned(&project);
@@ -148,15 +127,15 @@ pub(crate) fn read_here(args: &[String], cwd: &Path) -> i32 {
return Ok(format!("no new pinned notes in {}", project.display())); return Ok(format!("no new pinned notes in {}", project.display()));
} }
for chunk in notes.chunks_mut(40) { for chunk in notes.chunks_mut(40) {
let text = ask(by, &prompt(&fp, chunk))?; let text = ask(&project, &prompt(&fp, chunk))?;
let ans = answer(&text).ok_or_else(|| format!("{by} answered no readings JSON"))?; let ans = answer(&text).ok_or_else(|| "the critic answered no readings JSON".to_string())?;
fold(chunk, &fp, &ans, by); fold(chunk, &fp, &ans, by);
eprintln!("read {} notes", chunk.len()); eprintln!("read {} notes", chunk.len());
} }
let read = notes.iter().filter(|n| !n.kind.is_empty()).count(); let read = notes.iter().filter(|n| !n.kind.is_empty()).count();
kept.extend(notes.into_iter().filter(|n| !n.kind.is_empty())); kept.extend(notes.into_iter().filter(|n| !n.kind.is_empty()));
write_readings(&dir, &kept).map_err(|e| e.to_string())?; write_readings(&dir, &kept).map_err(|e| e.to_string())?;
Ok(format!("{read} notes read into labels by {by}, kept in {}; none trains a head until you've checked them: raea fingerprint readings --ask 50", dir.dir.join("readings.jsonl").display())) Ok(format!("{read} notes read into labels by a fresh session of the project's agent, kept in {}; none trains a head until you've checked them: raea fingerprint readings --ask 50", dir.dir.join("readings.jsonl").display()))
}; };
match run() { match run() {
Ok(o) => { Ok(o) => {
@@ -285,7 +264,7 @@ mod tests {
let fp = raea_sys_fingerprint::taxonomy::base("me"); let fp = raea_sys_fingerprint::taxonomy::base("me");
let mut n = vec![Reading { note: "n1".into(), ..Default::default() }, Reading { note: "n2".into(), ..Default::default() }, Reading { note: "n3".into(), ..Default::default() }]; let mut n = vec![Reading { note: "n1".into(), ..Default::default() }, Reading { note: "n2".into(), ..Default::default() }, Reading { note: "n3".into(), ..Default::default() }];
let ans = answer("I read them.\n[{\"id\": \"n1\", \"kind\": \"defect\", \"axis\": \"glitch\"}, {\"id\": \"n2\", \"kind\": \"direction\", \"axis\": \"made up\"}, {\"id\": \"n3\", \"kind\": \"rant\", \"axis\": null}]").unwrap(); let ans = answer("I read them.\n[{\"id\": \"n1\", \"kind\": \"defect\", \"axis\": \"glitch\"}, {\"id\": \"n2\", \"kind\": \"direction\", \"axis\": \"made up\"}, {\"id\": \"n3\", \"kind\": \"rant\", \"axis\": null}]").unwrap();
fold(&mut n, &fp, &ans, "kimi"); fold(&mut n, &fp, &ans, "agent");
assert_eq!((n[0].kind.as_str(), n[0].axis.as_deref()), ("defect", Some("glitch"))); assert_eq!((n[0].kind.as_str(), n[0].axis.as_deref()), ("defect", Some("glitch")));
assert_eq!((n[1].kind.as_str(), n[1].axis.as_deref()), ("direction", None), "an axis the fingerprint hasn't is dropped"); assert_eq!((n[1].kind.as_str(), n[1].axis.as_deref()), ("direction", None), "an axis the fingerprint hasn't is dropped");
assert_eq!(n[2].kind, "", "a kind it doesn't know is no reading"); assert_eq!(n[2].kind, "", "a kind it doesn't know is no reading");
+17 -72
View File
@@ -1,8 +1,9 @@
//! A judge that is an agent CLI rather than clef-omni: `raea judge DIR --by kimi|claude` (Shane, 11-06: "use claude or //! A judge that is an agent rather than clef-omni (Shane, 11-06: an agent as the judge; 12-03: never a harness raea
//! kimi cli as the judge"). Each call is a new session, run in DIR with only the sheets to look at (kimi's media tool; //! picks or the agent names): a fresh session of the agent this project runs on, which the host that started it (raea
//! claude with Read alone), given the fresh-context judge prompt (sdk/guides/craft/bevy/prompts.md section 3) and //! cloud's box, the raea app) offers as RAEA_JUDGE_URL. Each call is a new session, run in DIR with only the sheets to
//! never the code or the builder's notes. It answers JSON: the seven scores 0-10, the blind read and every defect named; //! look at, given the fresh-context judge prompt (sdk/guides/craft/bevy/prompts.md section 3) and never the code or
//! the pass, done and stall are still decided in code (rubric::pass, progress). `raea judge eye DIR --by kimi` records //! the builder's notes. It answers JSON: the seven scores 0-10, the blind read and every defect named;
//! the pass, done and stall are still decided in code (rubric::pass, progress). `raea judge eye DIR --read` records
//! its reading as the eye clef is calibrated against. //! its reading as the eye clef is calibrated against.
use std::path::Path; use std::path::Path;
@@ -11,7 +12,10 @@ use serde_json::{Map, Value, json};
use crate::rubric::{BAR, scores}; use crate::rubric::{BAR, scores};
pub const BY: [&str; 2] = ["kimi", "claude"]; /// Whether this session has a critic to ask: where it has, the agent judges; else clef.
pub fn critic() -> bool {
raea_io_clef::critic::here()
}
/// The judge prompt: the sheets by name, the brief's words, and the JSON to answer. A `raea make` job's kind asks its /// The judge prompt: the sheets by name, the brief's words, and the JSON to answer. A `raea make` job's kind asks its
/// own categories and the bar (docs/goal.feature MK5); none asks the rubric raea judge has always asked. /// own categories and the bar (docs/goal.feature MK5); none asks the rubric raea judge has always asked.
@@ -125,70 +129,11 @@ pub fn read(kind: Option<&str>, v: &Value) -> (Map<String, Value>, Vec<Value>, V
(out, defects, photo) (out, defects, photo)
} }
/// One fresh judging session by `by` over DIR's sheets: its verdict JSON. Its steps stream (kimi's stream-json), each /// One fresh judging session of this project's own agent over DIR's sheets, through the host (RAEA_JUDGE_URL): its
/// said on stderr as it comes, so a watcher sees it working through a judgement that can take minutes. /// verdict JSON.
pub fn ask(kind: Option<&str>, by: &str, dir: &Path, brief: &Value, target: Option<&Path>) -> Result<Value, String> { pub fn ask(kind: Option<&str>, dir: &Path, brief: &Value, target: Option<&Path>) -> Result<Value, String> {
use std::io::BufRead as _; let dir = dunce::canonicalize(dir).map_err(|e| format!("judge: {}: {e}", dir.display()))?;
let dir = dunce::canonicalize(&dir).map_err(|e| format!("judge: {}: {e}", dir.display()))?; eprintln!("judge: a fresh session of this project's agent is reading the sheets");
let p = prompt(kind, &dir, brief, target); let text = raea_io_clef::critic::ask(&dir, &prompt(kind, &dir, brief, target)).map_err(|e| format!("judge: {e}"))?;
let mut cmd = match by { last_verdict(&text).ok_or_else(|| format!("judge: the critic gave no verdict JSON: {}", text.trim().chars().rev().take(300).collect::<String>().chars().rev().collect::<String>()))
"kimi" => {
let mut c = std::process::Command::new("kimi");
c.args(["-p", &p, "--output-format", "stream-json"]);
c
}
"claude" => {
let mut c = std::process::Command::new("claude");
c.args(["-p", &p, "--allowedTools", "Read", "--output-format", "stream-json", "--verbose"]);
c
}
o => return Err(format!("judge: --by {o}: the judges are clef (the default), {}", BY.join(", "))),
};
let mut child = cmd.current_dir(&dir).stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped()).spawn()
.map_err(|e| format!("judge: couldn't run {by}: {e} (is the {by} CLI installed and signed in?)"))?;
let mut said = Vec::new();
let mut last = String::new();
for line in std::io::BufReader::new(child.stdout.take().ok_or("judge: no output pipe")?).lines().map_while(Result::ok) {
let Ok(v) = serde_json::from_str::<Value>(&line) else { continue };
said.extend(texts(&v));
let step = match (v["role"].as_str(), v["type"].as_str()) {
(Some("tool") | Some("user"), _) => "looked at a picture".to_string(),
(Some("assistant"), _) | (_, Some("assistant")) => texts(&v).last().map_or_else(|| "thinking".into(), |t| t[..t.floor_char_boundary(100)].to_string()),
_ => continue,
};
if step != last {
eprintln!("judge ({by}): {}", step.replace('\n', " "));
last = step;
}
}
let out = child.wait_with_output().map_err(|e| format!("judge: {by}: {e}"))?;
let text = said.join("\n");
if !out.status.success() && last_verdict(&text).is_none() {
return Err(format!("judge: {by} failed: {}", String::from_utf8_lossy(&out.stderr).lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("no output")));
}
last_verdict(&text).ok_or_else(|| format!("judge: {by} answered no verdict JSON: {}", text.trim().chars().rev().take(300).collect::<String>().chars().rev().collect::<String>()))
}
/// The words in one streamed line: kimi's {role: assistant, content: "..."}; claude's {type: assistant, message:
/// {content: [{type: text, text}]}} and its final {type: result, result}.
fn texts(v: &Value) -> Vec<String> {
let mut out = Vec::new();
if v["role"] == "assistant"
&& let Some(s) = v["content"].as_str()
{
out.push(s.to_string());
}
for c in v["message"]["content"].as_array().into_iter().flatten() {
if c["type"] == "text"
&& let Some(s) = c["text"].as_str()
{
out.push(s.to_string());
}
}
if v["type"] == "result"
&& let Some(s) = v["result"].as_str()
{
out.push(s.to_string());
}
out
} }
+5 -4
View File
@@ -3,7 +3,7 @@
//! ~/.raea/judge/eye.jsonl. `raea judge calibrate` fits, per category, a line from the judge's score to his //! ~/.raea/judge/eye.jsonl. `raea judge calibrate` fits, per category, a line from the judge's score to his
//! (least squares), and says how often the mapped judge's pass agrees with his. The judge gates only once it has 10 //! (least squares), and says how often the mapped judge's pass agrees with his. The judge gates only once it has 10
//! rounds or more, some passed by the eye and some not, and agrees on 8 in 10 or better; until then `gating` is false and its verdict is advice //! rounds or more, some passed by the eye and some not, and agrees on 8 in 10 or better; until then `gating` is false and its verdict is advice
//! (clef has rated almost everything acceptable: docs/craft-system.md). `raea judge eye DIR --by kimi|claude` records a //! (clef has rated almost everything acceptable: docs/craft-system.md). `raea judge eye DIR --read` records a
//! fresh agent session's reading instead (Shane, 11-06), each row saying whose eye it is. //! fresh agent session's reading instead (Shane, 11-06), each row saying whose eye it is.
use std::path::PathBuf; use std::path::PathBuf;
@@ -46,9 +46,10 @@ pub fn record(args: &[String]) -> Result<String, String> {
let verdict: Value = serde_json::from_str(&std::fs::read_to_string(dir.join("judge.json")).map_err(|_| format!("judge eye: no {}: judge the round first (raea judge {})", dir.join("judge.json").display(), dir.display()))?).map_err(|e| e.to_string())?; let verdict: Value = serde_json::from_str(&std::fs::read_to_string(dir.join("judge.json")).map_err(|_| format!("judge eye: no {}: judge the round first (raea judge {})", dir.join("judge.json").display(), dir.display()))?).map_err(|e| e.to_string())?;
let kind = kind_in(&verdict); let kind = kind_in(&verdict);
let cats = scores(kind); let cats = scores(kind);
// an agent's reading as the eye (`--by kimi`): a fresh session's scores, and its pass by the same rule in code // the session's agent's reading as the eye (`--read`): a fresh session's scores, and its pass by the same rule in code
if let Some(by) = args.iter().position(|a| a == "--by").and_then(|i| args.get(i + 1)) { if args.iter().any(|a| a == "--read") {
let v = crate::agent::ask(kind, by, &dir, &json!({}), None)?; let by = "agent";
let v = crate::agent::ask(kind, &dir, &json!({}), None)?;
let (eye, defects, _) = crate::agent::read(kind, &v); let (eye, defects, _) = crate::agent::read(kind, &v);
if eye.len() < cats.len() { if eye.len() < cats.len() {
return Err(format!("judge eye: {by} scored only {} of {} categories", eye.len(), cats.len())); return Err(format!("judge eye: {by} scored only {} of {} categories", eye.len(), cats.len()));
+8 -7
View File
@@ -2,8 +2,10 @@
//! fresh every round and blind to the code, with the pass decided here in code. Until it is calibrated against Shane's //! fresh every round and blind to the code, with the pass decided here in code. Until it is calibrated against Shane's
//! eye (`raea judge eye`, `raea judge calibrate`, eye.rs) its verdict is advice: `gating` says which. //! eye (`raea judge eye`, `raea judge calibrate`, eye.rs) its verdict is advice: `gating` says which.
//! //!
//! raea judge DIR [--kind scene|kit|shot] [--by clef|kimi|claude] [--brief brief.ts] [--target T.png] [--json] [--dry] //! raea judge DIR [--kind scene|kit|shot] [--brief brief.ts] [--target T.png] [--json] [--dry]
//! raea judge eye DIR composition=6 form=5 ... [--pass yes|no] (or --by kimi: an agent's reading as the eye) //! raea judge eye DIR composition=6 form=5 ... [--pass yes|no] (or --read: the session's agent's reading as the eye)
//! Who judges is never asked: a fresh session of the project's own agent where its host offers one (agent.rs), else
//! clef-omni.
//! raea judge calibrate [--kind scene|kit|shot] [--json] //! raea judge calibrate [--kind scene|kit|shot] [--json]
//! //!
//! `--kind` asks a `raea make` job's own rubric (docs/goal.feature MK5): a scene's, a kit's or a shot list's categories, //! `--kind` asks a `raea make` job's own rubric (docs/goal.feature MK5): a scene's, a kit's or a shot list's categories,
@@ -22,7 +24,6 @@ pub fn kind_gates(kind: &str) -> bool {
} }
pub mod rubric; pub mod rubric;
pub use agent::BY;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
@@ -30,7 +31,7 @@ use raea_core_facts::{Finding, Level, finding};
use raea_runtime_bundle::flag; use raea_runtime_bundle::flag;
use serde_json::{Value, json}; use serde_json::{Value, json};
pub const USAGE: &str = "raea judge DIR [--kind scene|kit|shot] [--by clef|kimi|claude] [--brief brief.ts] [--target T.png] [--json] [--dry] | judge eye DIR (CATEGORY=SCORE ... [--pass yes|no] | --by kimi|claude) | judge calibrate [--kind scene|kit|shot] [--json] (a --review folder's sheets judged blind: clef-omni on the frozen rubric, or a fresh kimi or claude session on the judge prompt; --kind asks a scene, kit or shot goal's own rubric (a shot list's framing.png); the pass decided in code; clef advises until calibrated against your eye or an agent's, each kind on its own)"; pub const USAGE: &str = "raea judge DIR [--kind scene|kit|shot] [--brief brief.ts] [--target T.png] [--json] [--dry] | judge eye DIR [--read] [CATEGORY=SCORE ...] [--pass yes|no] | judge calibrate [--kind scene|kit|shot] [--json] (a --review folder's sheets judged blind: a fresh session of the project's own agent on the judge prompt where its host offers one, else clef-omni on the frozen rubric; --kind asks a scene, kit or shot goal's own rubric (a shot list's framing.png); the pass decided in code; clef advises until calibrated against your eye or an agent's, each kind on its own)";
/// `--kind`, checked: one of the rubric's kinds, or none (the default rubric). /// `--kind`, checked: one of the rubric's kinds, or none (the default rubric).
pub fn kind_of(args: &[String]) -> Result<Option<String>, String> { pub fn kind_of(args: &[String]) -> Result<Option<String>, String> {
@@ -107,12 +108,12 @@ pub fn cli(args: &[String]) -> Result<String, String> {
let brief = brief_of(flag(args, "--brief").as_deref())?; let brief = brief_of(flag(args, "--brief").as_deref())?;
let target = flag(args, "--target").map(PathBuf::from); let target = flag(args, "--target").map(PathBuf::from);
let dry = args.iter().any(|a| a == "--dry"); let dry = args.iter().any(|a| a == "--dry");
let by = flag(args, "--by").unwrap_or_else(|| "clef".into()); let by = if agent::critic() { "agent".to_string() } else { "clef".into() };
if by != "clef" { if by != "clef" {
if dry { if dry {
return Ok(agent::prompt(kind, &dir, &brief, target.as_deref())); return Ok(agent::prompt(kind, &dir, &brief, target.as_deref()));
} }
let v = agent::ask(kind, &by, &dir, &brief, target.as_deref())?; let v = agent::ask(kind, &dir, &brief, target.as_deref())?;
let (scores, defects, photo) = agent::read(kind, &v); let (scores, defects, photo) = agent::read(kind, &v);
return finish(args, kind, &dir, scores.clone(), scores, defects, photo, 0.0, &by, false, json!({"blind": v["blind"], "show_as_is": v["show_as_is"]})); return finish(args, kind, &dir, scores.clone(), scores, defects, photo, 0.0, &by, false, json!({"blind": v["blind"], "show_as_is": v["show_as_is"]}));
} }
@@ -190,7 +191,7 @@ fn finish(args: &[String], kind: Option<&str>, dir: &Path, scores: serde_json::M
let (pass, why) = rubric::pass_for(kind, &scores, &defects); let (pass, why) = rubric::pass_for(kind, &scores, &defects);
let vals: Vec<f64> = scores.values().filter_map(Value::as_f64).collect(); let vals: Vec<f64> = scores.values().filter_map(Value::as_f64).collect();
let mean = if vals.is_empty() { 0.0 } else { (vals.iter().sum::<f64>() / vals.len() as f64 * 100.0).round() / 100.0 }; let mean = if vals.is_empty() { 0.0 } else { (vals.iter().sum::<f64>() / vals.len() as f64 * 100.0).round() / 100.0 };
let model = if by == "clef" { "@cf/cloudflare/clef-omni".to_string() } else { format!("{by} cli") }; let model = if by == "clef" { "@cf/cloudflare/clef-omni".to_string() } else { "the project's agent".to_string() };
let found = findings(&defects, by, advice); let found = findings(&defects, by, advice);
let mut verdict = json!({"dir": dir.display().to_string(), "kind": kind, "by": by, "scores": scores, "raw": raw, "mean": mean, "defects": defects, "photo": photo, let mut verdict = json!({"dir": dir.display().to_string(), "kind": kind, "by": by, "scores": scores, "raw": raw, "mean": mean, "defects": defects, "photo": photo,
"pass": pass, "why": why, "gating": !advice, "cost": cost, "model": model, "findings": found, "count": finding::count(&found)}); "pass": pass, "why": why, "gating": !advice, "cost": cost, "model": model, "findings": found, "count": finding::count(&found)});
+3 -3
View File
@@ -70,10 +70,10 @@ fn an_agent_verdict_is_read_from_the_end_of_its_thinking() {
assert!(!pass && why[0].starts_with("blocking")); assert!(!pass && why[0].starts_with("blocking"));
assert!(crate::agent::last_verdict("no json here").is_none()); assert!(crate::agent::last_verdict("no json here").is_none());
// what it saw, as Findings (DR3): a gating judge's blocking defect is an error, an advising one's a warn // what it saw, as Findings (DR3): a gating judge's blocking defect is an error, an advising one's a warn
let f = &crate::findings(&defects, "kimi", false)[0]; let f = &crate::findings(&defects, "agent", false)[0];
assert_eq!((f.check.as_str(), f.level, f.fix.as_deref(), f.by.as_str()), ("judge.iso", raea_core_facts::Level::Error, Some("model legs"), "raea judge (kimi)")); assert_eq!((f.check.as_str(), f.level, f.fix.as_deref(), f.by.as_str()), ("judge.iso", raea_core_facts::Level::Error, Some("model legs"), "raea judge (agent)"));
assert!(f.says.starts_with("iso sheet: "), "{}", f.says); assert!(f.says.starts_with("iso sheet: "), "{}", f.says);
assert_eq!(crate::findings(&defects, "kimi", true)[0].level, raea_core_facts::Level::Warn); assert_eq!(crate::findings(&defects, "agent", true)[0].level, raea_core_facts::Level::Warn);
} }
#[test] #[test]
+1 -1
View File
@@ -83,7 +83,7 @@ pub struct CutPlan {
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)] #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)] #[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(optional_fields)] #[ts(optional_fields)]
#[ts(rename = "Beat")] #[ts(rename = "CutBeat")]
pub struct Beat { pub struct Beat {
/// where it starts, in seconds from the cut's start (0 for the first) /// where it starts, in seconds from the cut's start (0 for the first)
pub at: f64, pub at: f64,
+3 -3
View File
@@ -54,11 +54,11 @@ pub fn declarations() -> String {
/// The goal's declarations (what the work is held to: goal.rs, cut.rs, playable.rs, rules.rs): sdk/raea/src/brief-goal.gen.ts /// The goal's declarations (what the work is held to: goal.rs, cut.rs, playable.rs, rules.rs): sdk/raea/src/brief-goal.gen.ts
pub fn goal_declarations() -> String { pub fn goal_declarations() -> String {
let cfg = Config::new(); let cfg = Config::new();
// a cut's beats are a script's (script.rs Beat) // a cut's beats are its own (cut.rs Beat, CutBeat in TypeScript: feel, story, asl, tempo), not a script's
let mut out = vec!["// Generated from raea-core-brief (core/brief) by its `goal_declarations`; edit the Rust, not this.\nimport type { Beat } from \"./brief.gen\";".to_string()]; let mut out = vec!["// Generated from raea-core-brief (core/brief) by its `goal_declarations`; edit the Rust, not this.".to_string()];
out.extend(decls!(cfg; out.extend(decls!(cfg;
goal::Goal, goal::Kind, goal::Source, goal::DialValue, goal::Dial, goal::Route, goal::Origin, goal::Pick, goal::Object, goal::Shot, goal::Goals, goal::Goal, goal::Kind, goal::Source, goal::DialValue, goal::Dial, goal::Route, goal::Origin, goal::Pick, goal::Object, goal::Shot, goal::Goals,
cut::Cut, cut::Quoted<u32>, cut::CutPlan, cut::Phrase, cut::Cta, cut::Open, cut::Cut, cut::Quoted<u32>, cut::CutPlan, cut::Beat, cut::Phrase, cut::Cta, cut::Open,
playable::Playable, playable::Orientation, playable::Playable, playable::Orientation,
rules::Rule, rules::Rule,
)); ));
+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
+14
View File
@@ -103,6 +103,20 @@ Feature: raea cloud: raea and an ACP agent on a server of your own (sdk/cloud)
And a worker that can't be reached fails the render unless RAEA_CLOUD_GPU_FALLBACK=cpu And a worker that can't be reached fails the render unless RAEA_CLOUD_GPU_FALLBACK=cpu
And every other raea command runs on the box And every other raea command runs on the box
Scenario: CL16. raea cloud's boxes are Fly Machines
Given the boxes were Sprites (deploy/sprites/), which ran at most 10 at once, read their disk in about 26 ms a
read and stopped at 8 cores and 16 GB (12-03)
Then each box is a Fly app of its own (raea-box-N for the box raea-N) with one Machine of deploy/fly/Dockerfile,
8 dedicated cores and 16 GB, and a volume for its home folder: the agents' sign-ins, ~/.raea-cloud.env, ~/work
And its work folder is /home/sprite/work as on a Sprite (the image links /home/sprite to /home/raea), so a moved
project's folders and paths are the same
And the server exits when the box has been idle RAEA_CLOUD_IDLE_STOP_MIN minutes (no request, connection,
process working in ~/work, or hold file touched lately: server/idle.ts), the Machine stays stopped, and Fly's
proxy starts it again at the next request
And deploy/fly/box.sh makes a box (up), moves a Sprite's (move: its token kept, its home sent from the Sprite
straight to the new box's file API), and puts every box on a release (latest)
And a file PUT to a box streams to disk and lands whole, never held in memory
Rule: it is proven end to end Rule: it is proven end to end
Scenario: CL12. A stand-in agent, then a real one Scenario: CL12. A stand-in agent, then a real one
Then test/smoke.sh builds the image, starts it, and checks CL4-CL7, CL14 and CL15 with test/echo-agent.mjs (a Then test/smoke.sh builds the image, starts it, and checks CL4-CL7, CL14 and CL15 with test/echo-agent.mjs (a
+1 -2
View File
@@ -37,7 +37,7 @@ raea fingerprint things shot.mp4 --json > things.json
## Usage ## Usage
```sh ```sh
raea fingerprint new NAME [--who W] [--about TEXT] [--extends FP] [--kinds K,K] [--tags T,T] | raea fingerprint bootstrap FILE... [--from LIST] [--per N] | raea fingerprint teach FILE --axis A --at T [--bad|--good] [--span S] [--box x0,y0,x1,y1] [--words W] [--project P] | raea fingerprint approve FILE... [--project P] | raea fingerprint pair WORSE BETTER --axis A [--at T] [--then T2] | raea fingerprint versions V1 V2... | raea fingerprint profile REFS... --as NAME [--against LIST] | raea fingerprint score FILE [--was OLD] [--ask flags|unsure] [--json] [--sheet out.png] [--timeline] [--profile NAME] | raea fingerprint report [--json] | raea fingerprint which [PATH] [--json] | raea fingerprint use NAME [--in project|workspace] [PATH] | raea fingerprint diff A B [--json] | raea fingerprint share NAME [--in project|workspace] [PATH] | raea fingerprint reembed PLACE... | raea fingerprint read PROJECT [--by kimi|claude] | raea fingerprint readings [PROJECT] [--ask N] [--tally] | raea fingerprint learn-notes [PROJECT] | raea fingerprint move [--fp CHILD] [--to PARENT] [--axis A] [--source S] [--project P] | raea fingerprint postmortem [PROJECT] [--ask N] [--tally] | raea fingerprint things FILE [--project P] [--json] | raea fingerprint stop [--fp NAME] (a person's sense of good work as axes with small heads over on-device encoders, docs/fingerprint.md: new makes ~/.raea/fingerprints/NAME with raea's base taxonomy in fingerprint.ts (or FP's axes with --extends), what it's for, the kinds of piece and project tags it judges, and every axis scoring from its words; bootstrap puts known defects into windows of real work and trains the mechanical axes, held out by source, and patch heads that say where in the frame a picture defect is; teach adds a label at a moment; approve makes approved work clean on every axis, away from its notes; pair says one moment is better than another on an axis (a pick, a hand edit); versions makes weak pairs of noted moments the next version changed; score prints the moments it expects a note on first (where in the frame, and the layers there, when its patch head points held out), then every axis per window with --json, a sheet PNG with --sheet, or the piece second by second in words with --timeline, and with --was OLD whether each of OLD's gating flags is fixed, still there, or looks disguised (nearer the axis's disguised defects than clean work), and with --ask flags each flag put to clef again on its own window, whether clef agrees said beside it and kept as clef's evidence (unsure: the moments it's unsure of too); profile takes the ranges of work you admire (loudness, tilt, cut rate, motion, brightness, contrast, saturation, sharpness), checked leave-one-out, and score --profile says what falls outside them, where and which way; report says each head's held-out score, labels, cheats, gate and what it can't judge; which says the one that judges a piece (its project's, its workspace's, then yours) and why, use pins one there, diff lists the axes two fingerprints rank the same evidence most differently on, and share copies one's taxonomy and evidence (no heads, no media) into a project or workspace for its team; reembed moves a fingerprint's evidence to this machine's encoders, re-embedding the rows whose media it finds; read has a fresh kimi or claude session read a project's pinned notes into kinds and axes, readings puts them to you to check and tallies your answers, and learn-notes makes the defects and praise evidence once you've agreed with 45 kinds and 40 axes in 50, each project's in the fingerprint that judges it; move takes a child's own labels (by axis, source or project) up into a fingerprint it extends, which never reads them otherwise; postmortem scores every version in a project's feed and asks you at most ten yes/no questions in the app, each with its moment playing, where the fingerprint disagrees with your labels or is least sure, and --tally makes your answers evidence and says how each head's held-out score moved; things finds a piece's shots, its things (a render's layers, and the marks drawn on its notes) with their depth, and the camera's path, and says where a thing floats, two pass through each other, the camera lurches mid-move or nothing is on screen, as JSON for `raea check --things` with --json) raea fingerprint new NAME [--who W] [--about TEXT] [--extends FP] [--kinds K,K] [--tags T,T] | raea fingerprint bootstrap FILE... [--from LIST] [--per N] | raea fingerprint teach FILE --axis A --at T [--bad|--good] [--span S] [--box x0,y0,x1,y1] [--words W] [--project P] | raea fingerprint approve FILE... [--project P] | raea fingerprint pair WORSE BETTER --axis A [--at T] [--then T2] | raea fingerprint versions V1 V2... | raea fingerprint profile REFS... --as NAME [--against LIST] | raea fingerprint score FILE [--was OLD] [--ask flags|unsure] [--json] [--sheet out.png] [--timeline] [--profile NAME] | raea fingerprint report [--json] | raea fingerprint which [PATH] [--json] | raea fingerprint use NAME [--in project|workspace] [PATH] | raea fingerprint diff A B [--json] | raea fingerprint share NAME [--in project|workspace] [PATH] | raea fingerprint reembed PLACE... | raea fingerprint read PROJECT | raea fingerprint readings [PROJECT] [--ask N] [--tally] | raea fingerprint learn-notes [PROJECT] | raea fingerprint move [--fp CHILD] [--to PARENT] [--axis A] [--source S] [--project P] | raea fingerprint postmortem [PROJECT] [--ask N] [--tally] | raea fingerprint things FILE [--project P] [--json] | raea fingerprint stop [--fp NAME] (a person's sense of good work as axes with small heads over on-device encoders, docs/fingerprint.md: new makes ~/.raea/fingerprints/NAME with raea's base taxonomy in fingerprint.ts (or FP's axes with --extends), what it's for, the kinds of piece and project tags it judges, and every axis scoring from its words; bootstrap puts known defects into windows of real work and trains the mechanical axes, held out by source, and patch heads that say where in the frame a picture defect is; teach adds a label at a moment; approve makes approved work clean on every axis, away from its notes; pair says one moment is better than another on an axis (a pick, a hand edit); versions makes weak pairs of noted moments the next version changed; score prints the moments it expects a note on first (where in the frame, and the layers there, when its patch head points held out), then every axis per window with --json, a sheet PNG with --sheet, or the piece second by second in words with --timeline, and with --was OLD whether each of OLD's gating flags is fixed, still there, or looks disguised (nearer the axis's disguised defects than clean work), and with --ask flags each flag put to clef again on its own window, whether clef agrees said beside it and kept as clef's evidence (unsure: the moments it's unsure of too); profile takes the ranges of work you admire (loudness, tilt, cut rate, motion, brightness, contrast, saturation, sharpness), checked leave-one-out, and score --profile says what falls outside them, where and which way; report says each head's held-out score, labels, cheats, gate and what it can't judge; which says the one that judges a piece (its project's, its workspace's, then yours) and why, use pins one there, diff lists the axes two fingerprints rank the same evidence most differently on, and share copies one's taxonomy and evidence (no heads, no media) into a project or workspace for its team; reembed moves a fingerprint's evidence to this machine's encoders, re-embedding the rows whose media it finds; read has a fresh session of the project's own agent read its pinned notes into kinds and axes, readings puts them to you to check and tallies your answers, and learn-notes makes the defects and praise evidence once you've agreed with 45 kinds and 40 axes in 50, each project's in the fingerprint that judges it; move takes a child's own labels (by axis, source or project) up into a fingerprint it extends, which never reads them otherwise; postmortem scores every version in a project's feed and asks you at most ten yes/no questions in the app, each with its moment playing, where the fingerprint disagrees with your labels or is least sure, and --tally makes your answers evidence and says how each head's held-out score moved; things finds a piece's shots, its things (a render's layers, and the marks drawn on its notes) with their depth, and the camera's path, and says where a thing floats, two pass through each other, the camera lurches mid-move or nothing is on screen, as JSON for `raea check --things` with --json)
``` ```
Headless: it needs nothing running and opens no window. Takes any number of arguments besides its flags. Headless: it needs nothing running and opens no window. Takes any number of arguments besides its flags.
@@ -54,7 +54,6 @@ Headless: it needs nothing running and opens no window. Takes any number of argu
| `--axis` | `A` | The axis a label is for, by name, such as blur or clip | | `--axis` | `A` | The axis a label is for, by name, such as blur or clip |
| `--bad` | – | The moment has the problem the axis names (the default) | | `--bad` | – | The moment has the problem the axis names (the default) |
| `--box` | `x0,y0,x1,y1` | Where in the frame the label is, as fractions of the width and height | | `--box` | `x0,y0,x1,y1` | Where in the frame the label is, as fractions of the width and height |
| `--by` | `kimi\|claude` | With read: which fresh session reads your notes, kimi (the default) or claude |
| `--extends` | `FP` | Another of your fingerprints to start from: the new one takes its axes and adds its own | | `--extends` | `FP` | Another of your fingerprints to start from: the new one takes its axes and adds its own |
| `--fp` | `CHILD` | Which fingerprint to use, by name; without it, the default | | `--fp` | `CHILD` | Which fingerprint to use, by name; without it, the default |
| `--from` | `LIST` | A file listing the renders to learn from, one path a line, relative to the file; lines starting with # are skipped | | `--from` | `LIST` | A file listing the renders to learn from, one path a line, relative to the file; lines starting with # are skipped |
+8 -7
View File
@@ -54,11 +54,13 @@ findings are then warnings.
A rules goal (`rules({...})`, what raea.app's `/goal` writes) is any other work: the aim in your words and the rules A rules goal (`rules({...})`, what raea.app's `/goal` writes) is any other work: the aim in your words and the rules
that must hold before the agent stops. A `run` rule is a command that must exit 0 in the brief's folder (300 seconds that must hold before the agent stops. A `run` rule is a command that must exit 0 in the brief's folder (300 seconds
unless its `timeout` says otherwise); a `file` rule is a deliverable; a `says` rule is words that must be true of the unless its `timeout` says otherwise); a `file` rule is a deliverable; a `says` rule is words that must be true of the
work, judged by a fresh critic that may only read: `raea goal judge` asks one (`--by claude`, `kimi` or `clef`) and work, judged by a fresh critic that may only read. `raea goal check` asks for the verdict itself when it's missing or
keeps its verdict in review/judge/NAME.json, and the rule clears only while that verdict is no older than the work's older than the work (`raea goal judge` asks now), and keeps it in review/judge/NAME.json, and the rule clears only while that verdict is no older than the work's
newest file. `clef` is clef-omni, as `raea ask` reaches it: it watches and hears the files a rule names (in the rule's newest file. Who judges is raea's to settle, never the agent's: a rule with a piece to watch or hear (the files it
"from A s to B s" window if it has one), else every video under out/, and reads no folder, so a rule about text it names, in its "from A s to B s" window if it has one, else every video under out/) goes to clef-omni, as `raea ask`
can't see stays open. It is the critic where `RAEA_AGENT_KEY` is set, as on raea cloud; elsewhere the critic is `claude`. reaches it; any other goes to a fresh session of the agent this project runs on, which the raea app or raea cloud
started (it offers the session's critic as `RAEA_JUDGE_URL`). Outside such a session a rule with nothing to watch
stays open and says why.
```ts ```ts
import { brief, rules } from "raea/brief" import { brief, rules } from "raea/brief"
@@ -98,7 +100,7 @@ goal's rules are never copied into the plan: the plan is the work, the goal is w
raea goal check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--manifest render.json] [--json] (every rule each goal of brief.ts is held to at that moment: its kind's packs, its rules and its own checks; with no goal, the floor; every project is also held to `registered`, every raea file reached from brief.ts; review/goal.json; exit 1 on an error. The hook runs it at every save (edit) and stop (done), a render at its end, raea cloud at publish) raea goal check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--manifest render.json] [--json] (every rule each goal of brief.ts is held to at that moment: its kind's packs, its rules and its own checks; with no goal, the floor; every project is also held to `registered`, every raea file reached from brief.ts; review/goal.json; exit 1 on an error. The hook runs it at every save (edit) and stop (done), a render at its end, raea cloud at publish)
raea goal tasks [DIR] [--json] | raea goal tasks [DIR] --apply EDITS.json|- | raea goal tasks [DIR] --put PUT.json|- (the brief's plan as the brief's run gives it: open tasks by id, or all as JSON; --apply writes edits by task id back where each task is written, refusing one made by code; a project with no plan gets plan.ts, imported by brief.ts; --put {plan, base} writes the whole plan back only while the brief's is still base) raea goal 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 seen FILE ["what you see and would change" --look "its design at full size, beside a reference"] [--surprise "SECONDS s: what it is"] (FILE's contact sheet beside it, and its frames at full size in FILE.looks/, to look at; with words, what was seen of FILE as it is now, and --look how a video's type, captions and cards look at full size)
raea goal judge [--goal NAME] [--by claude|kimi|clef] (a goal's `says` rules judged by a fresh critic that only reads; review/judge/NAME.json. clef watches and hears the files a rule names, else the videos under out/, paid as `raea ask` is: the critic where RAEA_AGENT_KEY is set, as on raea cloud, else claude) raea goal 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) raea goal next [DIR] (the two or three useful next steps for the project, from its brief, its goals, compositions, renders and checks)
raea goal gates [DIR] [--goal NAME] --json (a scene, kit or shot goal's record and critic gates, as raea/goal's packs read them) raea goal gates [DIR] [--goal NAME] --json (a scene, kit or shot goal's record and critic gates, as raea/goal's packs read them)
``` ```
@@ -111,7 +113,6 @@ Headless: it needs nothing running and opens no window. Takes any number of argu
| --- | --- | --- | | --- | --- | --- |
| `--apply` | `EDITS.json\|-` | plan edits (JSON, `-` for stdin), each written where its task is written | | `--apply` | `EDITS.json\|-` | plan edits (JSON, `-` for stdin), each written where its task is written |
| `--at` | `edit\|render\|publish\|done` | The moment `check` runs the rules of (default `done`); for `place`, the seconds to read (`S[,S...]`). | | `--at` | `edit\|render\|publish\|done` | The moment `check` runs the rules of (default `done`); for `place`, the seconds to read (`S[,S...]`). |
| `--by` | `claude\|kimi\|clef` | The critic `judge` asks, a fresh session that may only read (default `claude`). |
| `--goal` | `NAME` | only this goal of the brief's (by its name) | | `--goal` | `NAME` | only this goal of the brief's (by its name) |
| `--json` | – | `check`: print the report (review/goal.json's shape). `gates`: the record and critic gates as JSON. | | `--json` | – | `check`: print the report (review/goal.json's shape). `gates`: the record and critic gates as JSON. |
| `--look` | `"its design` | `seen`: a video's design judged on its frames at full size (FILE.looks/): its type, captions, cards and end beside a reference, and what was changed. | | `--look` | `"its design` | `seen`: a video's design judged on its frames at full size (FILE.looks/): its type, captions, cards and end beside a reference, and what was changed. |
+7 -6
View File
@@ -6,8 +6,9 @@ sources: ["apps/judge/src/lib.rs", "apps/judge/src/rubric.rs", "apps/judge/src/a
--- ---
`raea judge` reads the sheets [`raea render --review`](render.md) makes (`colour.png`, `clay.png`) and has them `raea judge` reads the sheets [`raea render --review`](render.md) makes (`colour.png`, `clay.png`) and has them
judged without the code or the conversation that made them: by clef-omni on a frozen rubric (the default), or by a judged without the code or the conversation that made them: by a fresh session of the agent this project runs on,
fresh Kimi or Claude session on the judge prompt. The scores come back as data, and whether the scene passes is on the judge prompt, where the raea app or raea cloud started that agent; else by clef-omni on a frozen rubric. Who
judges is raea's to settle: there's no flag for it. The scores come back as data, and whether the scene passes is
decided in code from them. clef only advises until it has been calibrated against a person's or an agent's eye. decided in code from them. clef only advises until it has been calibrated against a person's or an agent's eye.
`--kind scene|kit|shot` judges on that kind's own rubric, for a scene, kit or shot goal ([`raea goal`](goal.md)): a scene on layout, `--kind scene|kit|shot` judges on that kind's own rubric, for a scene, kit or shot goal ([`raea goal`](goal.md)): a scene on layout,
@@ -21,8 +22,8 @@ own.
```sh ```sh
raea render scene.tsx --review review/ raea render scene.tsx --review review/
raea judge review/ --brief brief.ts raea judge review/ --brief brief.ts
raea judge review/ --by claude --target reference.png --json raea judge review/ --target reference.png --json
raea judge review/r3 --kind kit --by claude --brief brief.ts # a kit job's round, on the kit rubric raea judge review/r3 --kind kit --brief brief.ts # a kit job's round, on the kit rubric
raea judge eye review/ composition=4 light=3 --pass yes # record your own scores, for calibration raea judge eye review/ composition=4 light=3 --pass yes # record your own scores, for calibration
raea judge calibrate raea judge calibrate
``` ```
@@ -32,7 +33,7 @@ raea judge calibrate
## Usage ## Usage
```sh ```sh
raea judge DIR [--kind scene|kit|shot] [--by clef|kimi|claude] [--brief brief.ts] [--target T.png] [--json] [--dry] | judge eye DIR (CATEGORY=SCORE ... [--pass yes|no] | --by kimi|claude) | judge calibrate [--kind scene|kit|shot] [--json] (a --review folder's sheets judged blind: clef-omni on the frozen rubric, or a fresh kimi or claude session on the judge prompt; --kind asks a scene, kit or shot goal's own rubric (a shot list's framing.png); the pass decided in code; clef advises until calibrated against your eye or an agent's, each kind on its own) raea judge DIR [--kind scene|kit|shot] [--brief brief.ts] [--target T.png] [--json] [--dry] | judge eye DIR [--read] [CATEGORY=SCORE ...] [--pass yes|no] | judge calibrate [--kind scene|kit|shot] [--json] (a --review folder's sheets judged blind: a fresh session of the project's own agent on the judge prompt where its host offers one, else clef-omni on the frozen rubric; --kind asks a scene, kit or shot goal's own rubric (a shot list's framing.png); the pass decided in code; clef advises until calibrated against your eye or an agent's, each kind on its own)
``` ```
Headless: it needs nothing running and opens no window. Takes any number of arguments besides its flags. Headless: it needs nothing running and opens no window. Takes any number of arguments besides its flags.
@@ -42,11 +43,11 @@ Headless: it needs nothing running and opens no window. Takes any number of argu
| Flag | Takes | What it does | | Flag | Takes | What it does |
| --- | --- | --- | | --- | --- | --- |
| `--brief` | `brief.ts` | The project's brief, so the judge knows what the scene is for. | | `--brief` | `brief.ts` | The project's brief, so the judge knows what the scene is for. |
| `--by` | `clef\|kimi\|claude` | Who judges: clef-omni on the rubric (default), or a fresh Kimi or Claude session. With `judge eye`, the agent whose eye is recorded. |
| `--dry` | – | Print what the judge would be asked, with its images, without asking. | | `--dry` | – | Print what the judge would be asked, with its images, without asking. |
| `--json` | – | Print the verdict as JSON: each score, the defects found and the pass. | | `--json` | – | Print the verdict as JSON: each score, the defects found and the pass. |
| `--kind` | `scene\|kit\|shot` | The rubric: `scene`, `kit` or `shot` (the make loop's categories), instead of the film rubric. | | `--kind` | `scene\|kit\|shot` | The rubric: `scene`, `kit` or `shot` (the make loop's categories), instead of the film rubric. |
| `--pass` | `yes\|no` | With `judge eye`: whether you'd pass it, recorded with your scores. | | `--pass` | `yes\|no` | With `judge eye`: whether you'd pass it, recorded with your scores. |
| `--read` | – | With `judge eye`: a fresh session of the project's agent reads the round, recorded as its eye. |
| `--target` | `T.png` | A reference image the colour sheet is judged against. | | `--target` | `T.png` | A reference image the colour sheet is judged against. |
<!-- generated:end --> <!-- generated:end -->
+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 /// `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 /// 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()). /// 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). /// 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 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] [--by claude|kimi|clef] (a goal's `says` rules judged by a fresh critic that only reads; review/judge/NAME.json. clef watches and hears the files a rule names, else the videos under out/, paid as `raea ask` is: the critic where RAEA_AGENT_KEY is set, as on raea cloud, else claude)
raea goal next [DIR] (the two or three useful next steps for the project, from its brief, its goals, compositions, renders and checks)"; raea goal 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 /// 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]); a.extend(["--manifest".into(), m]);
} }
match goal_run(&a) { match goal_run(&a) {
Ok(1) => { // an ERROR is a fault in the deliverable: fix its cause in the composition before this render is handed over
println!("fix every ERROR above, then render again"); Ok(1) => 1,
1
}
Ok(_) => 0, Ok(_) => 0,
// no runner (an install without the SDK): the render stands, and says so // no runner (an install without the SDK): the render stands, and says so
Err(e) => { Err(e) => {
println!("raea goal check: {e}"); println!("raea check: {e}");
0 0
} }
} }
+12 -13
View File
@@ -204,17 +204,17 @@ pub fn run(args: &[String]) -> R<String> {
if args[0] == "spec" { if args[0] == "spec" {
return spec::spec_cli(&args[1..]); 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) // `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..]); } 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 // `check [FILE...] [--at MOMENT]`: the one check (docs/check.feature), sdk/goal/src/run.ts; a model's opinion
if args[0] == "check" && !raea_app_direction::check::of_video(&args[1..]) { std::process::exit(raea_app_direction::check::cli(&args[1..], &CHECK)); } // (`--taste`, `ask`, `judge`, `goal seen|judge`) is no check, and refused with where its part went
if args[0] == "check" { std::process::exit(raea_app_check::cli_with(&args[1..], spec::tastes_ts(args)?)); } 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] == "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] == "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) 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), 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()) // 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), 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` // `goal check|tasks` and `make place`: the loop's runner, sdk/goal/src/run.ts (goal_ts()); `goal check` is `raea
// apps/make's; `goal next` this binary's // 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("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("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") 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) _ => 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 // `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. - 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 - 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. 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 - 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" (raea render writes it). The brand's colours and Tailwind: \`<style>{css}</style>\`, css from "./styles.gen". Its colours and faces are the palette, as classes
faces are the palette, as classes: colour text-brand-accent, bg-brand-accent, bg-brand-surface (bg-brand-bg), (text-brand-accent, bg-brand-surface, text-brand-on-accent, text-brand-ink, brand-1/2/3, font-brand,
text-brand-on-surface, text-brand-on-accent, text-brand-ink, brand-1/2/3; face font-brand, font-brand-body (where font-brand-body) or --brand-* variables; never a colour from outside it. Size, weight, layout and motion are yours,
the brand's face is missing, install a free face close to it, never a system fallback); the --brand-* variables chosen against the brand's own best work.
where a class can't reach. Never a colour from outside the brand. The design is yours: size, weight, shape, layout - \`raea render edit.tsx -o final.mp4 --manifest render.json\` renders, then checks the export once as it ends
and motion are chosen for this piece, against how the brand's own best work looks, not from a default. The sizes (\`raea check\`: real faults only, each ERROR with its fix, kept as final.check.json; nothing runs it again). Fix the
text-display, text-title, text-caption, text-body, text-label (scaled for a 1080-wide frame) and rounded-brand are ERRORs; a warning is a note for the person. \`raea render edit.tsx --at 105 -o review/stills/\` gives frame 105 to
a start, not a limit. look at. \`raea guide\` has the craft (\`raea guide motion\` for writing the TSX); \`raea help\` lists the rest.
- \`raea render edit.tsx -o final.mp4 --manifest render.json\`, then \`raea check final.mp4 --manifest render.json
--words words.json --perception perception.json\` says what's wrong; \`raea render edit.tsx --at 105 -o stills/\`
gives frame 105 to look at. \`raea guide\` has the craft (\`raea guide motion\` for writing the TSX);
\`raea help\` lists the rest.
## raea (everything there is; import from "raea") ## 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}), durationInFrames}, interpolate(frame, [in...], [out...], {extrapolateLeft, extrapolateRight: "clamp", easing}),
spring({frame, fps, config}), Easing.bezier(a, b, c, d) / Easing.inOut(...). spring({frame, fps, config}), Easing.bezier(a, b, c, d) / Easing.inOut(...).
Layout: <AbsoluteFill>, <Sequence from durationInFrames>, <Series><Series.Sequence durationInFrames>, <Loop>, <Freeze>. 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 Media: <Video src startFrom endAt volume playbackRate muted punchIn style>; a take cropped to another shape goes
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>, 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 <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, "./media/x.mov". Sound: decide what each scene is heard as first (silence, its own sound, effects, music), and make
where there is some, in Tone.js (import * as Tone from "raea/tone"), composed for the cut (a motif, chords that move, it as \`raea guide sound\` says; narration is <Speech text start> from raea/speech. <Mix lufs ceiling> masters the sound.
a part with rhythm, ending on a cut; never a pad or drone by default): instruments in a Tone.Sampler playing Parts and
Sequences, the notes from a sample library (\`raea make sounds\`, \`raea guide sources\`) or, for a timbre no library has,
Tone.tokensynth("a bowed saw, close", ["C3", "C4", "C5"]); sao("prompt", {seconds}) for an effect, as an <Audio src>; narration
is <Speech text start> from raea/speech (Pocket TTS). All of it local. <Mix lufs ceiling> masters the sound.
Words: useWords() -> [{text, from, to}] (frames, the cuts' words), word("phrase") -> the frame it's said, Words: useWords() -> [{text, from, to}] (frames, the cuts' words), word("phrase") -> the frame it's said,
findPhrase(words, "phrase", {occurrence, edge: "start" | "end"}). 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 Placement: <Captions said?> (said: each cut's own words) captions in the brand's style; titles go in <Region
the platforms' buttons; useRegion() gives its box. 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 />). Composition: registerRoot(() => <Composition id component width height fps durationInFrames />).
Not there: React hooks come from "react" (useMemo, useState), not from raea. 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) { match args.first().map(String::as_str) {
// `check VIDEO.mp4 …`: the floor's measurable lines on an export, ranked P0-P3 // `floor VIDEO.mp4 …`: the floor's measurable lines on an export, ranked P0-P3, as raea check's floor pack reads them
// (with --taste or --quick, through the engine, which evaluates the taste.ts files or renders stills: `check` here) Some("floor") => raea_app_check::cli_with(&args[1..], Vec::new()),
Some("check") if !args.iter().any(|a| a == "--taste" || a == "--quick") && raea_app_direction::check::of_video(&args[1..]) => raea_app_check::cli_with(&args[1..], Vec::new()),
// `ci …`: the gates' sound measurements and lightspeed's process measurements // `ci …`: the gates' sound measurements and lightspeed's process measurements
Some("ci") => raea_app_ci::cli(&args[1..]), 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 // native.ts RAEA VERB ARGS... RAEA: the native raea's path, for the engine's own verbs
import { spawnSync } from "node:child_process"; import { spawnSync } from "node:child_process";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import { createHash } from "node:crypto";
import { tmpdir } from "node:os"; 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 { basename, delimiter, dirname, extname } from "node:path";
import { brandKit, pixelsOf } from "./brand"; import { brandKit, pixelsOf } from "./brand";
import { readSite, stylesOf } from "./scrape"; 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 /** 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 * 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 * 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 norm = (s: string) => s.toLowerCase().replace(/[^\p{L}\p{N}'\s]/gu, "");
const toks = ws.map((w) => norm(w.text).trim()); 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) // 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; const fps = (engineJson(["media", "probe", at(take)]).video?.fps as number) || 30;
let from = 0; let from = 0;
const spans: [number, number][] = []; 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: /// `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 /// brief, script, taste or parts in it; anything else is checked as Taste, the files in
/// ~/.raea/taste being named for their kind). /// ~/.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(); 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!(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\"")); 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(&["track", "c.mp4", "--setup"])).is_some());
assert!(stray(&help, &a(&["splat", "train", "v.mp4", "-o", "o.ply", "--steps", "100"])).is_none()); 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. /// 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> { pub fn stray(help: &str, args: &[String]) -> Option<String> {
let verb = args.first()?; 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 // 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" { if verb == "physics" || verb == "gen" {
return None; 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) /// 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"]; pub const SHELL: &[&str] = &["init", "cut", "words", "frame", "component", "brand", "library", "show", "clothes", "bug"];
+28
View File
@@ -0,0 +1,28 @@
//! The critic a project's rules are judged by when the judgement needs reading rather than watching (Shane, 12-03:
//! never a harness raea picks or the agent names): a fresh session of the agent this project runs on, which the host
//! that started the agent (raea cloud's box, sdk/cloud/server/critic.ts; the raea app) offers as RAEA_JUDGE_URL, with
//! the session's RAEA_JUDGE_TOKEN. `raea judge`, `raea fingerprint read` and `raea goal judge` (sdk/goal) ask it.
use serde_json::{Value, json};
/// What a person reads when there's no critic here: no tool, agent or model named, because none is theirs to pick.
pub const NONE_HERE: &str = "an agent's reading is a fresh session of the agent this project runs on, which only an agent session the raea app or raea cloud started has";
/// Whether this session has a critic to ask.
pub fn here() -> bool {
std::env::var("RAEA_JUDGE_URL").is_ok_and(|u| !u.is_empty())
}
/// One question to a fresh session of this project's agent, in `cwd`: what it says back.
pub fn ask(cwd: &std::path::Path, prompt: &str) -> Result<String, String> {
let url = std::env::var("RAEA_JUDGE_URL").ok().filter(|u| !u.is_empty()).ok_or(NONE_HERE)?;
let token = std::env::var("RAEA_JUDGE_TOKEN").unwrap_or_default();
let r = ureq::post(&url).set("authorization", &format!("Bearer {token}")).timeout(std::time::Duration::from_secs(15 * 60))
.send_json(json!({"cwd": cwd.display().to_string(), "prompt": prompt}));
let body: Value = match r {
Ok(r) => r.into_json().map_err(|e| format!("the critic's answer: {e}"))?,
Err(ureq::Error::Status(_, r)) => return Err(format!("the critic couldn't: {}", r.into_json::<Value>().ok().and_then(|v| v["error"].as_str().map(String::from)).unwrap_or_default())),
Err(e) => return Err(format!("the critic: {e}")),
};
body["text"].as_str().map(String::from).ok_or_else(|| "the critic gave no text".into())
}
+1
View File
@@ -4,6 +4,7 @@
pub mod cache; pub mod cache;
pub mod client; pub mod client;
pub mod critic;
pub mod media; pub mod media;
pub mod route; pub mod route;
+3
View File
@@ -2,3 +2,6 @@ node_modules
deploy deploy
test test
README.md README.md
# a box image (deploy/fly/Dockerfile) takes these two from deploy/
!deploy/git
!deploy/fly/start.sh
+76
View File
@@ -0,0 +1,76 @@
# A raea cloud box as a Fly Machine (12-03: the boxes moved off Sprites, which ran at most 10 at once, read their disk
# in about 26 ms a read, and stopped at 8 cores and 16 GB). What deploy/sprites/setup.sh put on a Sprite is built in
# here once: Ubuntu as the Sprites ran it, raea's Linux release, Node, Chrome for the Google sign-in, ffmpeg, the PDF
# tools and brand faces, the ACP agents and sdk/cloud's server. The home folder (/home/raea: the agents' sign-ins,
# ~/.raea-cloud.env, ~/work) is the Machine's volume, so a new image changes the programs and keeps everything else.
# deploy/fly/box.sh builds it from sdk/cloud:
#
# fly deploy --build-only --push -c deploy/fly/image.toml --build-arg RAEA_VERSION=0.1.17-rc3 ...
FROM ubuntu:26.04
ENV DEBIAN_FRONTEND=noninteractive
# what setup.sh installed: raea's runtime libraries and Mesa's lavapipe (the box draws previews on its CPU; its renders
# go to the farm), ffmpeg and the PDF tools (12-02: every agent installed them itself at each project's start), Python
# (the footage prep's transcript file), the sign-in browser's display, and sudo for an agent that needs a package
RUN apt-get update -qq && apt-get install -y -qq --no-install-recommends \
ca-certificates curl git git-lfs zstd xz-utils bzip2 unzip procps less ripgrep openssl sudo python3 \
libasound2t64 libfontconfig1 libvulkan1 mesa-vulkan-drivers vulkan-tools ffmpeg poppler-utils \
xvfb x11vnc xdotool fonts-noto-color-emoji > /dev/null \
&& for f in fonts-inter fonts-roboto fonts-open-sans fonts-lato fonts-montserrat fonts-noto-core fonts-ibm-plex \
fonts-bebas-neue fonts-urw-base35 fonts-liberation2; do apt-get install -y -qq --no-install-recommends "$f" > /dev/null 2>&1 || echo "no $f"; done \
&& curl -fsSLo /tmp/chrome.deb https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb \
&& apt-get install -y -qq /tmp/chrome.deb > /dev/null && rm -f /tmp/chrome.deb \
&& rm -rf /var/lib/apt/lists/*
ARG NODE=24.22.0
RUN curl -fsSL "https://nodejs.org/dist/v$NODE/node-v$NODE-linux-x64.tar.xz" | tar -xJ -C /opt \
&& ln -sf /opt/node-v$NODE-linux-x64/bin/node /opt/node-v$NODE-linux-x64/bin/npm /opt/node-v$NODE-linux-x64/bin/npx /usr/local/bin/
# the box's user, uid 1000 as the image's entrypoint expects; /home/sprite is the same folder, so the paths a project
# moved from a Sprite wrote down (its agents' transcripts, its settings) still open
RUN (userdel -r ubuntu 2> /dev/null || true) && useradd -m -u 1000 -s /bin/bash raea \
&& echo 'raea ALL=(ALL) NOPASSWD:ALL' > /etc/sudoers.d/raea && chmod 440 /etc/sudoers.d/raea \
&& ln -s /home/raea /home/sprite
# raea, checked against its release's .sha256
ARG RAEA_VERSION
ARG RAEA_REPO=shinyobjectz/raea
RUN set -e; : "${RAEA_VERSION:?--build-arg RAEA_VERSION}"; f=raea-$RAEA_VERSION-linux-x86_64.tar.gz; \
u=https://github.com/$RAEA_REPO/releases/download/v$RAEA_VERSION; \
cd /tmp && curl -fsSL -o $f "$u/$f" && curl -fsSL -o $f.sha256 "$u/$f.sha256" && sha256sum -c --quiet $f.sha256 \
&& mkdir -p /opt/raea && tar -xzf $f -C /opt/raea --strip-components=1 && rm -f $f $f.sha256 \
&& /opt/raea/bin/raea --version
WORKDIR /opt/raea-cloud
COPY package.json package-lock.json ./
RUN npm ci --omit=dev --no-fund --no-audit --loglevel=error
# the agents, by ACP registry id, with the server they're started by (agents.ts reads its neighbours)
COPY server server
ARG AGENTS="antigravity-acp claude-acp kimi-code"
RUN node server/agents.ts install $AGENTS
COPY src src
COPY image image
# raea's SDK files fixed after the release the image installs (image/sdk-overlay, by their path under share/raea/sdk),
# each only while the installed file still has the fault, so a release with the fix keeps its own. 12-03: 0.1.17-rc4's
# goal.ts named-imports spawn, which raea's runtime hasn't got, and every raea goal check on a box died (raea #329)
RUN f=/opt/raea/share/raea/sdk/goal/src/packs/goal.ts; \
if grep -q 'import { spawn } from "node:child_process"' "$f"; then cp image/sdk-overlay/goal/src/packs/goal.ts "$f" && echo "overlay: goal.ts"; fi
COPY deploy/git deploy/git
COPY deploy/fly/start.sh image/fly-start.sh
# readable by raea whatever modes the files had where the image was built (12-03: a checkout made with umask 077 gave
# the entrypoint 711, and it re-runs itself as raea)
RUN chmod -R a+rX /opt/raea-cloud && chmod +x image/*.sh deploy/git/* \
&& ln -sf /opt/raea-cloud/image/raea.sh /usr/local/bin/raea \
&& ln -sf /opt/raea-cloud/deploy/git/repo.sh /usr/local/bin/raea-repo \
&& git lfs install --system --skip-repo > /dev/null
# the build, shown on GET /v1/health and raea cloud's /v1/admin/boxes, so which code a box runs is never a guess
ARG COMMIT=unknown
ARG DIRTY=false
RUN printf '{"commit":"%s","build":"%.12s","dirty":%s,"raea":"%s","image":"fly","built_at":"%s"}\n' \
"$COMMIT" "$COMMIT" "$DIRTY" "$RAEA_VERSION" "$(date -u +%Y-%m-%dT%H:%M:%S+00:00)" > /opt/raea-cloud/BUILD.json
# RAEA_CLOUD_IDLE_STOP_MIN: the server exits when the box has been idle this long, and the Machine stops (idle.ts)
ENV HOME=/home/raea NODE_ENV=production PORT=8080 WGPU_BACKEND=vulkan RAEA_CLOUD_DEVICE=cpu RAEA_CLOUD_IDLE_STOP_MIN=10
EXPOSE 8080
ENTRYPOINT ["/opt/raea-cloud/image/fly-start.sh"]
+234
View File
@@ -0,0 +1,234 @@
#!/bin/bash
# raea cloud's agent boxes as Fly Machines (12-03; they were Sprites, deploy/sprites/, which ran at most 10 at once and
# read their disk in about 26 ms a read). Each box is a Fly app of its own (raea-box-2 is the box raea-2) with one
# Machine of the box image (Dockerfile here) and one volume for its home folder: the agents' sign-ins, the box's
# settings (~/.raea-cloud.env) and ~/work. The Machine stops itself when the box is idle (server/idle.ts) and Fly's
# proxy starts it at the next request, so it bills while it works. From sdk/cloud:
#
# deploy/fly/box.sh image [VERSION] the box image built and pushed: raea VERSION's Linux release (the newest when
# none is named) and sdk/cloud's server from this tree (RAEA_CLOUD_REF: from
# raea's repo at that commit). Prints the image, kept in ~/.config/raea-cloud/fly-image
# deploy/fly/box.sh up NAME the box made or brought onto the last image built: its app, addresses, volume,
# settings and Machine, then its health
# deploy/fly/box.sh move NAME a Sprite box onto Fly: its settings (its token too, so raea cloud's list only
# changes address) and its home folder copied, then listed in raea cloud
# deploy/fly/box.sh register NAME the box into raea cloud's list at its Fly address (POST /v1/admin/boxes)
# deploy/fly/box.sh status NAME its address, Machine and health
# deploy/fly/box.sh token NAME its RAEA_CLOUD_TOKEN
# deploy/fly/box.sh list raea cloud's boxes in order, each one's health and build
# deploy/fly/box.sh latest [VERSION] the image built for a release and every Fly box in raea cloud's list put on it
# deploy/fly/box.sh key NAME a raea agent key (raea_ak_...) from stdin, or the clipboard, onto the box
# deploy/fly/box.sh sh NAME [CMD] a shell on the box (as root), or CMD there
#
# The org is raea's, written once in ~/.config/raea-cloud/fly.env (RAEA_FLY_ORG=raea), never another business's. Each
# box's settings are kept on this Mac too, in ~/.config/raea-cloud/boxes/NAME.env (mode 600), and go to the box as Fly
# secrets; the farm's come from ~/.config/raea-cloud/farm.env.
set -euo pipefail
REPO=shinyobjectz/raea
HERE=$(cd "$(dirname "$0")/../.." && pwd)
CONF=$HOME/.config/raea-cloud
FLY_CONF=${RAEA_FLY_ENV:-$CONF/fly.env}
ORG=$([ -f "$FLY_CONF" ] && sed -n 's/^RAEA_FLY_ORG=//p' "$FLY_CONF" | tail -1 || true)
[ -n "$ORG" ] || { echo "fly box: write RAEA_FLY_ORG=<the Fly org raea owns> in $FLY_CONF (fly orgs list)"; exit 2; }
# Content Jet's org and any other business's: never (private/cloud/sprites-denied.txt lists them for Sprites too)
DENIED=$(git -C "$HERE" rev-parse --show-toplevel 2> /dev/null)/private/cloud/sprites-denied.txt
if { [ -f "$DENIED" ] && grep -qxF "$ORG" "$DENIED"; } || [ "$ORG" = kamal-hafid ]; then
echo "fly box: $ORG belongs to another business; raea's boxes go in an org raea owns"; exit 2
fi
REGION=${RAEA_FLY_REGION:-iad}
SIZE=${RAEA_BOX_SIZE:-performance-8x}
VOLUME_GB=${RAEA_BOX_DISK_GB:-100}
IMAGE_APP=raea-box-image
FARM=${RAEA_FARM_ENV:-$CONF/farm.env}
newest() { gh release view -R "$REPO" --json tagName -q .tagName 2> /dev/null | sed 's/^v//'; }
NAME=${2:-}
app() { echo "raea-box-${1#raea-}"; }
url() { echo "https://$(app "$1").fly.dev"; }
envfile() { echo "$CONF/boxes/$1.env"; }
need_name() { [ -n "$NAME" ] || { echo "fly box: name the box (raea-2)"; exit 2; }; }
# whether the org has an app by this name (fly apps list --json: its table draws borders round each name)
has_app() { fly apps list --org "$ORG" --json 2> /dev/null | python3 -c 'import json,sys; sys.exit(0 if any(a.get("Name") == sys.argv[1] for a in json.load(sys.stdin)) else 1)' "$1"; }
machine() { fly machines list -a "$(app "$1")" --json 2> /dev/null | python3 -c 'import json,sys
m=[x for x in json.load(sys.stdin) if x.get("state")!="destroyed"]
print(m[0]["id"] if m else "")'; }
healthy() {
local u t
u=$(url "$1") t=$(sed -n 's/^RAEA_CLOUD_TOKEN=//p' "$(envfile "$1")")
for _ in $(seq 1 60); do
curl -fsS -m 20 -H "authorization: Bearer $t" "$u/v1/health" 2> /dev/null && return 0
sleep 5
done
return 1
}
case "${1:-}" in
image)
version=${2:-${RAEA_VERSION:-$(newest)}}
[ -n "$version" ] || { echo "fly box: couldn't read raea's newest release (gh signed in?)"; exit 2; }
src=$HERE
if [ -n "${RAEA_CLOUD_REF:-}" ]; then
# sdk/cloud at that commit of raea's repo, as a release's boxes take it
src=$(mktemp -d)
git -C "$src" init -q && git -C "$src" sparse-checkout set sdk/cloud
git -C "$src" fetch -q --depth 1 --filter=blob:none "https://github.com/$REPO" "$RAEA_CLOUD_REF" && git -C "$src" checkout -q FETCH_HEAD
src=$src/sdk/cloud
commit=$RAEA_CLOUD_REF dirty=false
else
commit=$(git -C "$HERE" rev-parse HEAD)
dirty=$([ -n "$(git -C "$HERE" status --porcelain -- .)" ] && echo true || echo false)
fi
has_app "$IMAGE_APP" || fly apps create "$IMAGE_APP" --org "$ORG" > /dev/null
# (|| true: on a clean tree the test fails, and set -e ended the script there with nothing said)
label=v$version-${commit:0:10}$([ "$dirty" = true ] && echo "-dirty-$(date +%s)" || true)
(cd "$src" && fly deploy --build-only --push -a "$IMAGE_APP" -c deploy/fly/image.toml --dockerfile deploy/fly/Dockerfile \
--image-label "$label" --build-arg RAEA_VERSION="$version" --build-arg COMMIT="$commit" --build-arg DIRTY="$dirty" .) >&2
echo "registry.fly.io/$IMAGE_APP:$label" | tee "$CONF/fly-image"
;;
up)
need_name
image=${RAEA_BOX_IMAGE:-$(cat "$CONF/fly-image" 2> /dev/null || true)}
[ -n "$image" ] || { echo "fly box: no image built yet (deploy/fly/box.sh image)"; exit 2; }
a=$(app "$NAME") f=$(envfile "$NAME")
mkdir -p "$CONF/boxes" && chmod 700 "$CONF/boxes"
if [ ! -s "$f" ]; then
# a new box: its own token, and the farm's settings
[ -f "$FARM" ] || { echo "fly box: $FARM names no farm (RAEA_CLOUD_GPU_URL, RAEA_CLOUD_GPU_TOKEN)"; exit 2; }
(umask 077; { echo "RAEA_CLOUD_TOKEN=$(openssl rand -hex 32)"; grep '^RAEA_CLOUD_GPU_' "$FARM"; echo "RAEA_API=https://api.raea.cloud"; } > "$f")
echo "fly box: $NAME is new: settings in $f (its agent key: deploy/fly/box.sh key $NAME)"
fi
has_app "$a" || fly apps create "$a" --org "$ORG" > /dev/null
fly ips list -a "$a" 2> /dev/null | grep -q 'v6' || {
fly ips allocate-v4 --shared -a "$a" > /dev/null
fly ips allocate-v6 -a "$a" > /dev/null
}
# the box's settings as Fly secrets, from the file (never on a command line)
fly secrets import --stage -a "$a" < "$f" > /dev/null
fly volumes list -a "$a" --json 2> /dev/null | python3 -c 'import json,sys; sys.exit(0 if any(v.get("name") == "home" and v.get("state") != "destroyed" for v in json.load(sys.stdin)) else 1)' || fly volumes create home --size "$VOLUME_GB" --region "$REGION" -a "$a" -y > /dev/null
id=$(machine "$NAME")
if [ -z "$id" ]; then
fly machine run "$image" -a "$a" -r "$REGION" --vm-size "$SIZE" -v home:/home/raea -n box \
-p 443:8080/tcp:tls:http -p 80:8080/tcp:http --autostart --autostop=off --restart on-failure --detach > /dev/null
# a Machine made by run takes the app's secrets as it's made; from then on the box reads its settings from
# ~/.raea-cloud.env on its volume (start.sh)
fly secrets deploy -a "$a" > /dev/null 2>&1 || true
elif [ "$(fly machines list -a "$a" --json 2> /dev/null | python3 -c 'import json, sys; print(json.load(sys.stdin)[0]["config"]["image"].split("@")[0])')" != "${image%@*}" ]; then
# a new image: the Machine made again from it (it restarts; its volume stays). Only then: a restart cut off a
# home's upload that had started after the health check passed on the instance before it (12-03, raea-3, 5, 11)
fly machine update "$id" -a "$a" --image "$image" --vm-size "$SIZE" --autostart --autostop=off --restart on-failure -y > /dev/null
fly machine wait "$id" -a "$a" --state started --wait-timeout 120 > /dev/null 2>&1 || true
fi
healthy "$NAME" > /dev/null || { echo "fly box: $NAME didn't answer at $(url "$NAME")"; exit 1; }
"$0" status "$NAME"
;;
move)
need_name
# the Sprite's settings, its token among them, so raea cloud only changes the box's address
. "$(dirname "$0")/../sprites/org.sh"
f=$(envfile "$NAME")
mkdir -p "$CONF/boxes" && chmod 700 "$CONF/boxes"
(umask 077; sprite exec -o "$ORG" -s "$NAME" -- cat /home/sprite/.raea-cloud.env > "$f")
grep -q '^RAEA_CLOUD_TOKEN=' "$f" || { echo "fly box: couldn't read $NAME's settings from its Sprite"; exit 1; }
ORG=$(sed -n 's/^RAEA_FLY_ORG=//p' "$FLY_CONF" | tail -1) "$0" up "$NAME"
# its home folder, but for caches anything can make again: agents' sign-ins, their sessions, ~/work. Sent by the
# Sprite itself straight to the new box's file API (it streams to disk), never through this Mac (12-03: through
# sprite exec it came at about 4 MB/s), then unpacked there
a=$(app "$NAME")
# a home that arrived whole in a try before this one is unpacked, not sent again (a .part is only part of one)
healthy "$NAME" > /dev/null || true
if fly ssh console -a "$a" -q -C "test -s /home/raea/work/.move/home.tar.zst" > /dev/null 2>&1; then
echo "fly box: $NAME's home arrived in a try before this one: unpacking it"
else
fly ssh console -a "$a" -q -C "rm -rf /home/raea/work/.move" > /dev/null 2>&1 || true
echo "fly box: sending $NAME's home from its Sprite to $(url "$NAME")"
# --no-stdin: a dropped link to the Sprite reconnects to the same session (12-03: all four copies lost theirs at
# once, 6 minutes in, and with stdin attached sprite exec refuses to reconnect)
sprite exec --no-stdin -o "$ORG" -s "$NAME" -- bash -c ". ~/.raea-cloud.env && tar -C /home/sprite --exclude=./.cache --exclude=./.npm --exclude=./.raea-cloud.env --exclude=./work/.move -cf - . | zstd -q -T0 -3 | curl -fsS --retry 0 -T - -H \"authorization: Bearer \$RAEA_CLOUD_TOKEN\" '$(url "$NAME")/v1/files?path=.move/home.tar.zst' && echo SENT-WHOLE" > "$CONF/boxes/$NAME.move.log" 2>&1 &
sending=$!
# what has arrived, every 15 s; nothing more in MOVE_STILL_S (2 minutes) and the copy is stopped there, never waited
# out (12-03, Shane: fail fast at every step)
tok=$(sed -n 's/^RAEA_CLOUD_TOKEN=//p' "$f" | tail -1)
got=-1 since=$SECONDS
while kill -0 "$sending" 2> /dev/null; do
n=$(curl -s -m 20 -H "authorization: Bearer $tok" "$(url "$NAME")/v1/files?path=.move" | python3 -c 'import json, sys
try: print(sum(d.get("bytes") or 0 for d in json.load(sys.stdin)))
except Exception: print(-1)')
if [ "${n:--1}" -gt "$got" ]; then
echo "fly box: $NAME: $((n / 1048576)) MB arrived"
got=$n since=$SECONDS
elif [ $((SECONDS - since)) -ge "${MOVE_STILL_S:-120}" ]; then
kill "$sending" 2> /dev/null
echo "fly box: $NAME's upload stopped growing at $((got / 1048576)) MB for $((SECONDS - since)) s: stopped; run move again"
exit 1
fi
sleep 15
done
wait "$sending"
grep -v 'bind: warning' "$CONF/boxes/$NAME.move.log"
grep -q SENT-WHOLE "$CONF/boxes/$NAME.move.log" || { echo "fly box: $NAME's home didn't arrive whole (above); nothing unpacked, run move again"; exit 1; }
fi
# unpacked there, saying so every 500 MB (a silent unpack of 26 GB looked stalled: 12-03, raea-4 and raea-6)
# run from inside the work folder, which the box's idle stop sees as work going on (server/idle.ts); the box woken
# first, as fly ssh doesn't start a stopped Machine
healthy "$NAME" > /dev/null || true
# and the box held while it unpacks (~/.raea-hold, which its idle stop reads): its image may be older than idle.ts's
# real-path match
fly ssh console -a "$a" -q -C "sh -c '(while kill -0 \$\$ 2> /dev/null; do touch /home/raea/.raea-hold; sleep 60; done) & cd /home/raea/work/.move && zstd -dqc home.tar.zst | tar -C /home/raea -xf - --checkpoint=50000 --checkpoint-action=echo=\"fly box: $NAME: %{}T unpacked\" && cd /home/raea && rm -rf work/.move && chown -R raea:raea /home/raea && du -sh /home/raea'"
# its own settings on its disk too, as a Sprite kept them
fly ssh console -a "$a" -q -C "sh -c 'umask 077; cat > /home/raea/.raea-cloud.env && chown raea:raea /home/raea/.raea-cloud.env'" < "$f"
# RAEA_BOX_REGISTER=0: copied, but raea cloud still sends work to the Sprite until deploy/fly/box.sh register NAME
if [ "${RAEA_BOX_REGISTER:-1}" = 0 ]; then echo "fly box: $NAME copied; not registered yet"; else "$0" register "$NAME"; fi
;;
register)
need_name
api=${RAEA_CLOUD_API:-https://api.raea.cloud}
key=${RAEA_CLOUD_ADMIN_KEY:-$(security find-generic-password -s raea-cloud-prod-staff-key -w 2> /dev/null || true)}
[ -n "$key" ] || { echo "fly box: no staff key (RAEA_CLOUD_ADMIN_KEY, or raea-cloud-prod-staff-key in the keychain)"; exit 2; }
tok=$(sed -n 's/^RAEA_CLOUD_TOKEN=//p' "$(envfile "$NAME")")
body=$(python3 -c 'import json,sys; print(json.dumps({"name": sys.argv[1], "url": sys.argv[2], "token": sys.argv[3], "first": sys.argv[4] == "1"}))' "$NAME" "$(url "$NAME")" "$tok" "${RAEA_BOX_FIRST:-0}")
curl -fsS -X POST -H "authorization: Bearer $key" -H 'content-type: application/json' --data-binary @- "$api/v1/admin/boxes" <<< "$body" > /dev/null || { echo "fly box: raea cloud refused $NAME"; exit 1; }
echo "fly box: $NAME is listed in raea cloud at $(url "$NAME")"
;;
status)
need_name
echo "$(url "$NAME") machine $(machine "$NAME")"
t=$(sed -n 's/^RAEA_CLOUD_TOKEN=//p' "$(envfile "$NAME")")
curl -fsS -m 60 -H "authorization: Bearer $t" "$(url "$NAME")/v1/health" | head -c 600
echo
;;
token) need_name; sed -n 's/^RAEA_CLOUD_TOKEN=//p' "$(envfile "$NAME")" ;;
list) exec "$(dirname "$0")/../sprites/box.sh" list ;;
latest)
version=${2:-$(newest)}
[ -n "$version" ] || { echo "fly box: couldn't read raea's newest release (gh signed in?)"; exit 2; }
linux=raea-$version-linux-x86_64.tar.gz
gh release view "v$version" -R "$REPO" --json assets -q '.assets[].name' 2> /dev/null | grep -qx "$linux" || { echo "fly box: v$version has no $linux yet: no box changed"; exit 1; }
ref=$(gh api "repos/$REPO/commits/v$version" -q .sha) || { echo "fly box: couldn't read v$version's commit"; exit 1; }
RAEA_CLOUD_REF=$ref "$0" image "$version" > /dev/null
names=$("$0" list | sed 's/^[* ] *//' | awk '{print $1}' | grep '^raea-' || true)
failed=""
for b in $names; do
[ -s "$(envfile "$b")" ] || { echo "fly box: $b isn't a Fly box here (no $(envfile "$b")): passed over"; continue; }
echo "fly box: $b onto raea $version (${ref:0:10})"
"$0" up "$b" > /dev/null || failed+=" $b"
done
[ -z "$failed" ] || { echo "fly box: not on $version:$failed"; exit 1; }
echo "fly box: every Fly box is on raea $version"
;;
key)
need_name
if [ -t 0 ]; then k=$(pbpaste); else k=$(cat); fi
k=$(printf %s "$k" | tr -d '[:space:]')
case "$k" in raea_ak_*) ;; *) echo "fly box: that isn't a raea agent key (raea_ak_...)"; exit 2 ;; esac
f=$(envfile "$NAME")
(umask 077; { grep -v '^RAEA_AGENT_KEY=' "$f" || true; echo "RAEA_AGENT_KEY=$k"; } > "$f.new" && mv "$f.new" "$f")
printf 'RAEA_AGENT_KEY=%s\n' "$k" | fly secrets import -a "$(app "$NAME")" > /dev/null && echo "fly box: agent key on $NAME, its Machine restarted"
;;
sh)
need_name
if [ -n "${3:-}" ]; then fly ssh console -a "$(app "$NAME")" -q -C "$3"; else fly ssh console -a "$(app "$NAME")"; fi
;;
*)
sed -n '2,25p' "$0"
exit 2
;;
esac
+7
View File
@@ -0,0 +1,7 @@
# The app whose registry holds the box image (deploy/fly/box.sh image): it runs no machines of its own. Each box is an
# app of its own (raea-box-2, ...) whose one Machine runs this image with its volume.
app = "raea-box-image"
primary_region = "iad"
[build]
dockerfile = "Dockerfile"
+43
View File
@@ -0,0 +1,43 @@
#!/bin/bash
# A Fly box's start, as root: the volume made the box's home, the box's own settings read from it, then the image's
# entrypoint (image/entrypoint.sh), which goes on as raea and runs the server. The server exits 0 when the box has been
# idle RAEA_CLOUD_IDLE_STOP_MIN minutes (server/idle.ts), and with the Machine's restart policy on-failure it then stays
# stopped until Fly's proxy starts it for the next request.
set -uo pipefail
H=/home/raea
# the box's name: RAEA_BOX, else the app's (raea-box-2 is the box raea-2)
BOX=${RAEA_BOX:-${FLY_APP_NAME:-box}}
BOX=${BOX/raea-box-/raea-}
mkdir -p "$H/work"
[ "$(stat -c %u "$H")" = 1000 ] || chown -R raea:raea "$H"
[ "$(stat -c %u "$H/work")" = 1000 ] || chown raea:raea "$H/work"
# footage is read 16 MB ahead (setup.sh's 12-01 measure on a Sprite; a volume gains the same on long reads)
for b in /sys/block/*/queue/read_ahead_kb; do echo 16384 > "$b" 2> /dev/null || true; done
# the box's own token, the farm's address and key, the agent key and raea cloud's address: kept on the volume, as a
# Sprite kept them (box.sh writes it; a box moved from a Sprite brings its own). Fly secrets, when set, come first.
if [ -s "$H/.raea-cloud.env" ]; then
while IFS='=' read -r k v; do
[[ "$k" =~ ^[A-Z_][A-Z0-9_]*$ ]] || continue
[ -n "${!k:-}" ] || export "$k=$v"
done < "$H/.raea-cloud.env"
fi
: "${RAEA_CLOUD_TOKEN:?the box has no RAEA_CLOUD_TOKEN: a Fly secret, or a line of ~/.raea-cloud.env}"
# what the box runs with, written back to its disk: raea cloud's fleet makes a new box from a healthy one by reading it
(umask 077; for k in RAEA_CLOUD_TOKEN RAEA_AGENT_KEY RAEA_API RAEA_CLOUD_GPU_URL RAEA_CLOUD_GPU_TOKEN; do
[ -n "${!k:-}" ] && echo "$k=${!k}"
done > "$H/.raea-cloud.env.new" && mv "$H/.raea-cloud.env.new" "$H/.raea-cloud.env" && chown 1000:1000 "$H/.raea-cloud.env")
# the work folder by the path raea cloud names it on every box (/home/sprite is /home/raea: the image links it), so
# the folders and paths of projects made on a Sprite are the same here
export RAEA_CLOUD_WORK=/home/sprite/work
# the box's commits say which box made them
[ -s "$H/.gitconfig" ] || {
sudo -u raea HOME=$H git config --global user.name "raea cloud $BOX"
sudo -u raea HOME=$H git config --global user.email "$BOX@box.raea.io"
sudo -u raea HOME=$H git config --global init.defaultBranch main
}
python3 - "$BOX" << 'PY'
import json, sys
p = "/opt/raea-cloud/BUILD.json"
b = json.load(open(p)); b["box"] = sys.argv[1]; json.dump(b, open(p, "w"))
PY
exec /opt/raea-cloud/image/entrypoint.sh
+95 -11
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 # 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 # 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", "")}) .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) 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) 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 # 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", 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) # 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): def run(cmd, cwd=None, env=None, timeout=6 * 3600):
t = time.time() 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) os.makedirs(d, exist_ok=True)
build = os.environ.get("RAEA_FARM_BUILD") build = os.environ.get("RAEA_FARM_BUILD")
if build and cmd[0] == "raea": if build and cmd[0] == "raea":
@@ -247,8 +263,10 @@ class Log:
SCALEDOWN = 2 SCALEDOWN = 2
# a container with no GPU stays up this long: an agent renders its cuts one after another and each again after an # a container with no GPU stays up this long: an agent renders its cuts one after another and each again after an
# edit, and at 2 s every render's containers started cold, about 20 s of a 54 s draw (12-01). A minute of 16 idle ones # edit, and at 2 s every render's containers started cold, about 20 s of a 54 s draw (12-01). A minute of 16 idle ones
# is about $0.06, which a job's own bill (farm_plan.Bill) leaves out: the next job may be the one that uses it # is about $0.06, which a job's own bill (farm_plan.Bill) leaves out: the next job may be the one that uses it. 180 since
CPU_SCALEDOWN = 60 # 12-03: an agent renders all its cuts at once, then each one its fix touched a minute or two later, and every one of
# those started cold at 60 (Shane: "no workflow should take more than 20 minutes")
CPU_SCALEDOWN = 180
def on(gpus, job): def on(gpus, job):
@@ -336,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} 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): def raea_frames(id, args, frames=None, first=0, probe=False, video=False, env=None):
vol.reload() vol.reload()
work = f"{JOBS}/{id}/work" work = f"{JOBS}/{id}/work"
if probe: if probe:
code, out, s = run(["raea", *args, "--frame", "0", "-o", "/tmp/probe.png", "--manifest", "/tmp/probe.json"], cwd=work, env=env) 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 {} 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()} 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: if frames is None:
code, out, s = run(["raea", *args], cwd=work) code, out, s = run(["raea", *args], cwd=work)
@@ -356,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) # (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" 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"}) 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): if os.path.exists(seg):
shutil.move(seg, f"{dest}/run-{first:05d}.mp4") shutil.move(seg, f"{dest}/run-{first:05d}.mp4")
vol.commit() vol.commit()
@@ -572,15 +626,22 @@ def api():
# (POST jobs: 500) whenever two agents rendered together. So requests that touch the volume share it, and a # (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. # reload waits until none of them is in it.
class Gate: 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): def __init__(self):
self.users = 0 self.users = 0
self.reloading = False 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() self.cond = asyncio.Condition()
@contextlib.asynccontextmanager @contextlib.asynccontextmanager
async def use(self): async def use(self):
async with self.cond: 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 self.users += 1
try: try:
yield yield
@@ -589,17 +650,36 @@ def api():
self.users -= 1 self.users -= 1
self.cond.notify_all() self.cond.notify_all()
async def reload(self, wait: bool = True) -> bool: 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""" """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: 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 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.reloading = True
self.begun += 1
mine = self.begun
ok = False
try: try:
for pause in (0.5, 1, 2, 4, 0): for pause in (0.5, 1, 2, 4, 0):
try: try:
await vol.reload.aio() await vol.reload.aio()
ok = True
return True return True
except Exception as e: # modal.exception.ConflictError: a file open elsewhere in this container except Exception as e: # modal.exception.ConflictError: a file open elsewhere in this container
if not pause: if not pause:
@@ -610,13 +690,17 @@ def api():
finally: finally:
async with self.cond: async with self.cond:
self.reloading = False self.reloading = False
if ok:
self.fresh = mine
self.cond.notify_all() self.cond.notify_all()
gate = Gate() 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(): async def reloaded():
"""the coordinator's commits seen here, or a 503 the box tries again on (the job is still all here)""" """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") raise HTTPException(503, "the farm's volume is busy: try again")
def check(req: Request): def check(req: Request):
+119 -5
View File
@@ -94,6 +94,19 @@ PARTS = 4
# another: 2 parts each. At 4 an 894-frame ad went out as 32 parts of 28 frames, each paying about 5 s to start # another: 2 parts each. At 4 an 894-frame ad went out as 32 parts of 28 frames, each paying about 5 s to start
# (raea, the composition, each clip read on from its last keyframe) for 10 s of frames (11-30) # (raea, the composition, each clip read on from its last keyframe) for 10 s of frames (11-30)
CPU_PARTS = 2 CPU_PARTS = 2
# A video with no 3D (its keys say so) is planned for the time it takes, not the containers' seconds (12-03, Shane: "no
# workflow should take more than 20 minutes"): its runs go out at once, with no timed first run before them (that run
# and its wait were 15-25 s of every render), each run at least FLAT_PART frames, on as many containers as the job may
# have. A 1080x1920 ad cut drew 0.46-0.69 s a frame on a container with no GPU (11-30, 12-03), which FLAT_FRAME_S plans
# the bill by.
FLAT_PART = 24
FLAT_FRAME_S = 0.6
# a run still out once this share of a job's runs are in, and after HEDGE_AFTER times the slowest finished one (or
# HEDGE_MIN_S more than it), is sent again to another container, and the first answer is kept (12-03: one of 21 runs took
# 81 s where the others took 11-15, and the whole render waited on it)
HEDGE_SHARE = 0.7
HEDGE_AFTER = 1.5
HEDGE_MIN_S = 8.0
# a video part's start is never planned at less than this (s): the timed run's own start is measured on a warm # a video part's start is never planned at less than this (s): the timed run's own start is measured on a warm
# container with the clips' first frames, and came out at 2.8-3.6 s where the parts after it paid about 5 # container with the clips' first frames, and came out at 2.8-3.6 s where the parts after it paid about 5
PART_START = 5.0 PART_START = 5.0
@@ -254,6 +267,81 @@ def spread(fn, kind, calls, log, what, bill=None, most=None, got=None, again=Non
return code return code
def _ready(h):
"""a spawned run's answer, the exception it raised, or None while it's still running"""
try:
return h.get(timeout=0)
except Exception as e:
# Modal's "not yet" is a TimeoutError; its FunctionTimeoutError (the run ran out of time) is the run's answer
if isinstance(e, TimeoutError) and type(e).__name__ != "FunctionTimeoutError":
return None
return e
def hedged(fn, kind, calls, log, what, bill=None, most=None, got=None, again=None, clock=time.time, pause=None, wait_s=0.5):
"""`calls` on `fn` as spread() runs them, each spawned at once (at most `most` containers), and a run still out
once HEDGE_SHARE of them are in and it has taken HEDGE_AFTER times the slowest finished one (HEDGE_MIN_S more at
least) sent once more: the first answer of the two is kept and the other cancelled. A run draws the same frames
to the same files wherever it runs, so either answer is the run's."""
if not calls:
return 0
pause = pause or time.sleep
if most and len(calls) > most:
fn = fn.with_options(max_containers=most)
code = 0
t0 = clock()
out = {c[3]: {"call": c, "h": [fn.spawn(*c)], "at": t0, "again": False} for c in calls}
took = []
while out:
for first in list(out):
o = out[first]
r = None
for h in o["h"]:
r = _ready(h)
if r is not None:
break
if r is None:
continue
for h in o["h"]:
try:
h.cancel()
except Exception:
pass
del out[first]
took.append(clock() - o["at"])
if isinstance(r, Exception):
log(f"raea farm: a run failed{' without a GPU' if again is not None else ''}: {r!r}"[:600], err=again is None)
if again is not None:
again.append(o["call"])
else:
code = code or 1
continue
if bill:
bill.add(r)
if again is not None and (r["code"] or (r.get("manifest") or {}).get("has3d")):
why = "it drew 3D" if not r["code"] else f"exit {r['code']}: " + " | ".join((r.get("out") or "").strip().splitlines()[-3:])
log(f"raea farm: frames from {r.get('first')} didn't draw without a GPU ({why})"[:600])
again.append(o["call"])
continue
if got is not None:
got.append(r)
log(f"raea farm: {r.get('frames')} {what} on a {r.get('kind') or kind} in {r['s']:.1f} s")
if r["code"]:
log(r["out"], err=True)
code = code or r["code"]
if not out:
break
if took and len(calls) - len(out) >= HEDGE_SHARE * len(calls):
slow = max(took)
for first, o in out.items():
if not o["again"] and clock() - o["at"] > max(slow * HEDGE_AFTER, slow + HEDGE_MIN_S):
o["again"] = True
o["h"].append(fn.spawn(*o["call"]))
log(f"raea farm: frames from {first} still out after {clock() - o['at']:.0f} s (the others took {slow:.0f} s at most): sent again, the first answer kept")
pause(wait_s)
return code
def timed(r, n): def timed(r, n):
"""A timed run's (seconds a frame, seconds to start): the frame from raea's own clocks over the whole frame (React, """A timed run's (seconds a frame, seconds to start): the frame from raea's own clocks over the whole frame (React,
the page, the clips read, the draw, the encode: farm.py's work_ms) when the run says them, else from its "N ms a the page, the clips read, the draw, the encode: farm.py's work_ms) when the run says them, else from its "N ms a
@@ -324,6 +412,10 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
nv = bool((p.get("manifest") or {}).get("has3d")) nv = bool((p.get("manifest") or {}).get("has3d"))
flat = bool(video and cpu_render and not opts.get("gpu") and (p.get("manifest") or {}).get("has3d") is False) flat = bool(video and cpu_render and not opts.get("gpu") and (p.get("manifest") or {}).get("has3d") is False)
r0 = None r0 = None
# a flat video whose keys said so goes out at once: no timed first run (FLAT_PART)
quick = bool(flat and p.get("keys"))
if quick:
n0 = 0
first = list(range(at0, at0 + n0)) first = list(range(at0, at0 + n0))
if flat and n0: if flat and n0:
r0 = bill.add(waited(cpu_render, log, id, rest, first, at0, video=video)) r0 = bill.add(waited(cpu_render, log, id, rest, first, at0, video=video))
@@ -344,17 +436,22 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
if r0 and r0["code"]: if r0 and r0["code"]:
log(r0["out"], err=True) log(r0["out"], err=True)
return r0["code"] return r0["code"]
frame_s, start_s = timed(r0, n0) if r0 else (0.0, 0.0) frame_s, start_s = timed(r0, n0) if r0 else ((FLAT_FRAME_S, PART_START) if quick else (0.0, 0.0))
left = todo - n0 left = todo - n0
# a container beyond the first starts cold: frame 0's whole time, less its one frame (the first is warm by now) # a container beyond the first starts cold: frame 0's whole time, less its one frame (the first is warm by now)
cold_s = start_s if flat else max(start_s, p["s"] - frame_s) cold_s = start_s if flat else max(start_s, p["s"] - frame_s)
k = gpus_for(left, frame_s, cold_s, most) if quick:
m = parts_per_gpu(left, k, frame_s, max(start_s, PART_START) if video else start_s, CPU_PARTS if flat else PARTS) k, m = (max(1, min(most, -(-left // FLAT_PART))) if left else 0), 1
else:
k = gpus_for(left, frame_s, cold_s, most)
m = parts_per_gpu(left, k, frame_s, max(start_s, PART_START) if video else start_s, CPU_PARTS if flat else PARTS)
cost = price(gpu_kind, p["s"]) + price(kind, (r0["s"] if r0 else 0) + k * m * start_s + (k - 1) * (cold_s - start_s) + left * frame_s, busy=(r0 or {}).get("cores") or 0) cost = price(gpu_kind, p["s"]) + price(kind, (r0["s"] if r0 else 0) + k * m * start_s + (k - 1) * (cold_s - start_s) + left * frame_s, busy=(r0 or {}).get("cores") or 0)
parts = f" in {k * m} parts" if m > 1 else "" parts = f" in {k * m} parts" if m > 1 else ""
on = f"{k} {kind}s" if not flat else f"{k} containers with no GPU (no 3D in it)" on = f"{k} {kind}s" if not flat else f"{k} containers with no GPU (no 3D in it)"
if r0: if r0:
log(f"raea farm: {frame_s * 1000:.0f} ms a frame, {start_s:.1f} s to start; {left} frames left on {on}{parts}, about ${cost:.3f} in all") log(f"raea farm: {frame_s * 1000:.0f} ms a frame, {start_s:.1f} s to start; {left} frames left on {on}{parts}, about ${cost:.3f} in all")
elif quick and left:
log(f"raea farm: {left} frames on {on}, all at once, about ${cost:.3f} in all")
else: else:
log("raea farm: nothing to draw: every frame is in a run kept from an earlier render") log("raea farm: nothing to draw: every frame is in a run kept from an earlier render")
if opts.get("max_usd") is not None and cost > opts["max_usd"]: if opts.get("max_usd") is not None and cost > opts["max_usd"]:
@@ -365,24 +462,38 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
got = [r0] if r0 else [] got = [r0] if r0 else []
calls = [(id, rest, f, at, False, video, *([True] if nv and not flat else [])) for a, b, share in farm_keys.spans(gaps, n0, k * m) for f, at in runs(a, b, share, warm)] if left else [] calls = [(id, rest, f, at, False, video, *([True] if nv and not flat else [])) for a, b, share in farm_keys.spans(gaps, n0, k * m) for f, at in runs(a, b, share, warm)] if left else []
again = [] if flat else None again = [] if flat else None
code = spread(render, kind, calls, log, "frames", bill, k, got, again) if calls else 0 code = (hedged if quick else spread)(render, kind, calls, log, "frames", bill, k, got, again) if calls else 0
if again: if again:
# what a container with no GPU couldn't draw, or drew 3D in (on a software rasteriser): a GPU draws it again # what a container with no GPU couldn't draw, or drew 3D in (on a software rasteriser): a GPU draws it again
log(f"raea farm: {len(again)} of {len(calls)} runs go to a GPU (they failed without one, or have 3D in them)") log(f"raea farm: {len(again)} of {len(calls)} runs go to a GPU (they failed without one, or have 3D in them)")
code = spread(gpu_render, gpu_kind, again, log, "frames", bill, opts["gpus"], got) code = spread(gpu_render, gpu_kind, again, log, "frames", bill, opts["gpus"], got)
if code: if code:
return code return code
# each step from here says how long it took when it took a second or more (12-03: a render whose every frame was
# kept still took 64 s between "nothing to draw" and "joined", and nothing said where; Shane: fail fast at every step)
def took(what, t0):
if time.time() - t0 >= 1:
log(f"raea farm: {what} took {time.time() - t0:.1f} s")
# the sound's run finished first: its open files in the job's folder refuse the reload that brings the other # the sound's run finished first: its open files in the job's folder refuse the reload that brings the other
# containers' frames (11-25: "the volume wouldn't reload ... cwd of raea render") # containers' frames (11-25: "the volume wouldn't reload ... cwd of raea render")
if video: if video:
t0 = time.time()
t.join() t.join()
took("the sound", t0)
t0 = time.time()
reload() # the other containers' frames reload() # the other containers' frames
took("reloading the volume", t0)
frames = f"{os.path.dirname(work)}/frames" frames = f"{os.path.dirname(work)}/frames"
dest = os.path.join(work, out) dest = os.path.join(work, out)
# (a run that drew 3D after all isn't kept: its frames can hang on the frames before them) # (a run that drew 3D after all isn't kept: its frames can hang on the frames before them)
if store and not any((r.get("manifest") or {}).get("has3d") for r in got): if store and not any((r.get("manifest") or {}).get("has3d") for r in got):
t0 = time.time()
farm_keys.put(store, keyed["keys"], got, frames) farm_keys.put(store, keyed["keys"], got, frames)
took("keeping the runs drawn", t0)
t0 = time.time()
got += farm_keys.take(hits, frames) got += farm_keys.take(hits, frames)
took(f"bringing {len(hits)} kept runs", t0)
if manifest and p.get("manifest"): if manifest and p.get("manifest"):
path = os.path.join(work, manifest) path = os.path.join(work, manifest)
os.makedirs(os.path.dirname(path) or ".", exist_ok=True) os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
@@ -429,7 +540,10 @@ def joined(probe, parts):
pieces = sorted((c for s in snd for c in s.get("clips") or []), key=lambda c: (c.get("from", 0), str(c.get("key")))) pieces = sorted((c for s in snd for c in s.get("clips") or []), key=lambda c: (c.get("from", 0), str(c.get("key"))))
clips = [] clips = []
for c in pieces: for c in pieces:
prev = next((p for p in reversed(clips) if p.get("key") == c.get("key") and p.get("src") == c.get("src") and p.get("to") == c.get("from")), None) # the same source carried on across a run's seam, whatever its React key: each run numbers its nodes its own
# way (12-04, StreetTalk round 22: Body Shop's clips came back keyed n3 and n11 by turns, split at frames 60,
# 420, 720 and 807, and the sound check called each seam a cut inside a word)
prev = next((p for p in reversed(clips) if p.get("src") == c.get("src") and p.get("to") == c.get("from")), None)
if prev is not None and abs(prev.get("at", 0) + (prev["to"] - prev["from"]) / fps - c.get("at", 0)) < 1.5 / fps: if prev is not None and abs(prev.get("at", 0) + (prev["to"] - prev["from"]) / fps - c.get("at", 0)) < 1.5 / fps:
prev["to"] = c["to"] prev["to"] = c["to"]
if "fadeOut" in c: if "fadeOut" in c:
+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"} 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: class Align:
@modal.enter() @modal.enter()
def load(self): def load(self):
@@ -80,7 +83,7 @@ def aligned(heard: list, got: list) -> "list | None":
FULL_S = 180 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: class Hear:
@modal.enter() @modal.enter()
def load(self): def load(self):
@@ -0,0 +1,312 @@
// The rule packs (MK29, MK38; Rust's goal gates until 11-29, now here alone): any goal held to its rules,
// from what's on disk and what a fresh critic said, never from the agent that did the work (11-26, Shane: "it can't
// stop unless all the goals pass").
// run the command exits 0 in the brief's folder, within its timeout (300 s by default), run again each time
// says a fresh critic (`raea goal judge`) found it true of the work, after the work's last change
// (file rules are deliverables: the deliverables pack holds them)
// The critic's verdict is review/judge/NAME.json (the goal's name): {at, by, goal, rules: {ID: {pass, why}}}.
// a namespace import: raea's own runtime (engine/native/src/node.js) has spawnSync and no spawn, and a named import of
// spawn failed the whole module there, so every `raea goal check` on a box died before it read a file (12-03, raea
// 0.1.17-rc4: no StreetTalk cut could publish)
import * as cp from "node:child_process"
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"
import path from "node:path"
import { check, found } from "raea/check"
import { type Contract, nameOf, type Said, saysOf } from "../contract.ts"
import type { Job } from "../facts.ts"
import { RAEA } from "../media.ts"
/** where a goal's critic verdict is kept, relative to the brief */
export const verdictPath = (g: Contract) => `review/judge/${nameOf(g)}.json`
export const TIMEOUT = 300
/** folders that aren't the work: what the job writes about itself, and what tools keep */
const NOT_WORK = new Set(["review", ".git", "node_modules", ".raea", "target", ".cache", ".raea-cloud"])
/** what a check keeps beside a file it read (its report, its words, its scene): a reading of the work, not a change
* to it. A done check that heard a cut's words wrote them beside it, and the critic's verdict of a minute before read
* as older than the work (12-01) */
const READING = /\.(check|words|scene|floor|montage)\.json$/
/** when the work last changed (ms): the newest file under dir, its own bookkeeping left out (a bounded walk) */
export function newest(dir: string): number | null {
let best: number | null = null
const stack = [dir]
let seen = 0
while (stack.length) {
const d = stack.pop()!
let names: string[] = []
try {
names = readdirSync(d)
} catch {
continue
}
for (const name of names) {
if (++seen > 20_000) return best
const p = path.join(d, name)
let st
try {
st = statSync(p)
} catch {
continue
}
if (st.isDirectory()) {
if (!(d === dir && NOT_WORK.has(name)) && name !== "node_modules" && name !== ".git") stack.push(p)
} else if (st.isFile() && name !== "NOTES.md" && !READING.test(name)) best = Math.max(best ?? 0, st.mtimeMs)
}
}
return best
}
type Verdict = { at: number; by: string; goal?: string; rules: Record<string, { pass: boolean; why: string } | undefined> }
export function verdict(dir: string, g: Contract): Verdict | null {
try {
return JSON.parse(readFileSync(path.join(dir, verdictPath(g)), "utf8")) as Verdict
} catch {
return null
}
}
const goalOf = (j: Job): Contract | null => j.contract
export const runPack = check<Job>({ id: "run", text: "each command rule exits 0", over: "job", at: ["done"] }, async (j) => {
for (const r of goalOf(j)?.rules ?? []) {
if (!r.run) continue
const { ok, said } = await j.run(r.run, r.timeout ?? TIMEOUT)
if (!ok) found({ says: `${r.id}: \`${r.run}\` ${said}`, about: [r.id] })
}
})
export const saysPack = check<Job>({ id: "says", text: "each `says` rule found true by a fresh critic after the work's last change", over: "job", at: ["done"] }, async (j) => {
const says = saysOf(goalOf(j) ?? null)
if (!says.length) return
let v = verdict(j.root, j.contract!)
// at whole seconds, as the verdict keeps its time: work saved in the second the critic was asked counts as judged
const freshOf = (x: Verdict | null) => !!x && (newest(j.root) === null || x.at >= Math.floor(newest(j.root)! / 1000))
// a verdict missing, stale or short of a rule is asked for here (the check is the one command; the agent never
// judges by hand), where this session has a critic to ask
if (!(freshOf(v) && says.every((r) => v!.rules?.[r.id])) && hasCritic(j.root, says)) {
try {
v = await judge(j.contract!, j.root)
} catch (e) {
found({ says: `the critic couldn't judge: ${(e as Error).message}` })
return
}
}
const fresh = freshOf(v)
for (const r of says) {
const one = v?.rules?.[r.id]
const fix = NO_CRITIC
if (!v) found({ says: `${r.id}: not judged yet`, about: [r.id], fix })
else if (!one) found({ says: `${r.id}: the last judging didn't cover it`, about: [r.id], fix })
else if (!fresh) found({ says: `${r.id}: the work changed after the critic judged it`, about: [r.id], fix })
else if (!one.pass) found({ says: `${r.id}: a fresh critic found it not true yet: ${one.why}`, about: [r.id] })
}
})
/** what the critic is asked: the goal, each `says` rule by id, and the answer's shape. It reads; it changes nothing */
export function prompt(g: Contract, dir: string, only: Said[] = saysOf(g)): string {
const rules = only.map((r) => `- ${r.id}: ${r.says}`)
return `You are a fresh critic. You did none of this work and owe it nothing. The work is in ${dir}: read whatever you need there (its files, its renders, NOTES.md), and change nothing.\n\nThe goal, as the person said it: ${g.aim ?? nameOf(g)}\n\nFor each rule below, decide whether it is true of the work as it is on disk now. Count it true only when you have seen it hold; if you can't tell, it isn't true yet. Say why in one sentence, naming what you looked at.\n\n${rules.join("\n")}\n\nAnswer last with one JSON object and nothing after it: {"rules": {"ID": {"pass": true, "why": "..."}}}`
}
/** the verdict: the object around the text's last "rules" key (a critic may think aloud, or quote the shape, first) */
export function lastVerdict(text: string): Verdict | null {
const key = text.lastIndexOf('"rules"')
if (key < 0) return null
for (let open = text.lastIndexOf("{", key); open >= 0; open = text.lastIndexOf("{", open - 1)) {
let depth = 0
let inStr = false
for (let i = open; i < text.length; i++) {
const ch = text[i]
if (inStr) {
if (ch === "\\") i++
else if (ch === '"') inStr = false
continue
}
if (ch === '"') inStr = true
else if (ch === "{") depth++
else if (ch === "}" && --depth === 0) {
try {
const v = JSON.parse(text.slice(open, i + 1))
if (v && typeof v.rules === "object") return v
} catch {}
break
}
}
}
return null
}
/** where a rule is judged, chosen here and never by the agent (Shane, 12-03): a rule with a piece to watch or hear
* (a file it names, or the videos under out/) by Clef-Omni; any other by a fresh session of the agent this project
* runs on, which the host that started the agent offers as RAEA_JUDGE_URL (raea cloud's box, critic.ts; the raea app) */
const criticUrl = () => process.env.RAEA_JUDGE_URL || null
export const NO_CRITIC = "it's judged by a fresh session of the agent this project runs on, which only an agent session the raea app or raea cloud started has: it's judged when that session checks the goal"
/** whether every rule here can be judged in this session */
export function hasCritic(dir: string, rules: Said[]): boolean {
return !!criticUrl() || rules.every((r) => piecesOf(r, dir).length > 0)
}
const PIECE = /[\w@./-]+\.(?:mp4|mov|webm|m4v|png|jpe?g|webp|wav|mp3|m4a)\b/gi
const VIDEO = /\.(?:mp4|mov|webm|m4v)$/i
/** the videos under out/, newest first */
function made(dir: string): string[] {
const out: { f: string; at: number }[] = []
const walk = (d: string) => {
for (const e of existsSync(d) ? readdirSync(d, { withFileTypes: true }) : []) {
const f = path.join(d, e.name)
if (e.isDirectory()) walk(f)
else if (VIDEO.test(e.name)) out.push({ f, at: statSync(f).mtimeMs })
}
}
walk(path.join(dir, "out"))
return out.sort((x, y) => y.at - x.at).map((x) => path.relative(dir, x.f))
}
/** clef-omni as the critic (`raea ask`, paid as ask is): it watches and hears a piece, and reads no folder. A rule is
* asked of the files it names, in its "from A s to B s" window if it has one, else of every video under out/ (the
* newest CLEF_PIECES), and passes when it's true of each; the rules about one piece go in one call */
const CLEF_PIECES = 12
/** the pieces a rule is about: the files it names that are on disk, else the newest videos under out/ */
function piecesOf(r: Said, dir: string): string[] {
const named = [...new Set(r.says.match(PIECE) ?? [])].filter((f) => existsSync(path.join(dir, f)))
return named.length ? named : made(dir).slice(0, CLEF_PIECES)
}
/** how many `raea ask`s run at once: each is one cut (or one stretch of it) heard and watched; one after another, a
* project's beats took 6-17 minutes of every goal check (12-03, StreetTalk: 18 of them, a cut's beats each a stretch) */
export const CLEF_AT_ONCE = 6
/** `f` on each item, at most `n` at once, the answers in the items' order */
async function pool<T, R>(items: T[], n: number, f: (t: T) => Promise<R>): Promise<R[]> {
const out: R[] = new Array(items.length)
let next = 0
const worker = async () => {
for (let i = next++; i < items.length; i = next++) out[i] = await f(items[i])
}
await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker))
return out
}
export async function clefVerdict(g: Contract, dir: string, ask: Ask = askClef, only: Said[] = saysOf(g)): Promise<Verdict["rules"]> {
const groups = new Map<string, { file: string; from?: string; to?: string; rules: Said[] }>()
const pieces = new Map<string, string[]>()
for (const r of only) {
const files = piecesOf(r, dir)
const w = /from (\d+(?:\.\d+)?) s to (?:(\d+(?:\.\d+)?) s|its end)/.exec(r.says)
pieces.set(r.id, files)
for (const file of files) {
const key = [file, w?.[1], w?.[2]].join("\u001f")
const at = groups.get(key) ?? { file, from: w?.[1], to: w?.[2], rules: [] }
at.rules.push(r)
groups.set(key, at)
}
}
const got = new Map<string, { pass: boolean; why: string }[]>()
const list = [...groups.values()]
const heard = ask === askClef && !asyncSpawn()
? askClefMany(dir, list.map((k) => ({ file: k.file, says: k.rules.map((r) => r.says), from: k.from, to: k.to })))
: await pool(list, CLEF_AT_ONCE, async (k) => ask(dir, k.file, k.rules.map((r) => r.says), k.from, k.to))
for (const [j, k] of list.entries()) {
const answers = heard[j]
k.rules.forEach((r, i) => got.set(r.id, [...(got.get(r.id) ?? []), { pass: answers[i]?.choice === "true" && !answers[i]?.problem, why: `${k.file}: ${answers[i]?.problem ?? answers[i]?.says ?? "no answer"}` }]))
}
const rules: Verdict["rules"] = {}
for (const r of only) {
const a = got.get(r.id) ?? []
const open = a.filter((x) => !x.pass)
rules[r.id] = !pieces.get(r.id)?.length
? { pass: false, why: "it names no file on disk and out/ holds no video yet, so there's nothing to watch or hear" }
: { pass: !open.length, why: (open.length ? open : a).map((x) => x.why).join("; ") }
}
return rules
}
type Answer = { choice?: string; says?: string; problem?: string | null }
type Ask = (dir: string, file: string, says: string[], from?: string, to?: string) => Answer[] | Promise<Answer[]>
const askArgs = (file: string, says: string[], from?: string, to?: string) => ["ask", file, ...says, "--choose", "true,false", "--json", ...(from ? ["--from", from] : []), ...(to ? ["--to", to] : [])]
const rowsOf = (out: string) => out.split("\n").flatMap((l) => { try { const o = JSON.parse(l); return o.answer ? [o as Answer] : [] } catch { return [] } })
/** whether this runtime has an async spawn (raea's own has only spawnSync) */
const asyncSpawn = () => typeof (cp as { spawn?: unknown }).spawn === "function"
/** every ask at once where there's no async spawn (raea's runtime): one shell runs them CLEF_AT_ONCE at a time, each
* into its own file under review/ (12-04, StreetTalk round 18: asked one after another, a stop's 18 beats took 7.7 of
* its 10.5 minutes) */
export function askClefMany(dir: string, jobs: { file: string; says: string[]; from?: string; to?: string }[]): Answer[][] {
if (!jobs.length) return []
const tmp = path.join(dir, "review", `.ask-${process.pid}-${Date.now()}`)
mkdirSync(tmp, { recursive: true })
const sq = (t: string) => `'${t.replace(/'/g, `'\\''`)}'`
const lines = jobs.map((k, i) => `${[RAEA, ...askArgs(k.file, k.says, k.from, k.to)].map(sq).join(" ")} > ${sq(`${tmp}/${i}.out`)} 2> ${sq(`${tmp}/${i}.err`)} &${(i + 1) % CLEF_AT_ONCE === 0 ? "\nwait" : ""}`)
try {
const r = cp.spawnSync("sh", ["-c", [...lines, "wait"].join("\n")], { cwd: dir, encoding: "utf8" }) as { error?: Error }
if (r.error) throw new Error(`couldn't run raea ask: ${r.error.message}`)
const read = (f: string) => (existsSync(f) ? String(readFileSync(f, "utf8")) : "")
return jobs.map((k, i) => {
const rows = rowsOf(read(`${tmp}/${i}.out`))
if (rows.length !== k.says.length) throw new Error(`raea ask answered ${rows.length} of ${k.says.length} about ${k.file}: ${read(`${tmp}/${i}.err`).trim().slice(-300) || read(`${tmp}/${i}.out`).trim().slice(-300)}`)
return rows
})
} finally {
rmSync(tmp, { recursive: true, force: true })
}
}
/** `raea ask` on one file (or a stretch of it): run as a child, so several hear at once */
function askClef(dir: string, file: string, says: string[], from?: string, to?: string): Promise<Answer[]> {
const args = askArgs(file, says, from, to)
// where there's no async spawn (raea's runtime), one at a time (clefVerdict asks them all at once: askClefMany)
if (!asyncSpawn()) {
const r = cp.spawnSync(RAEA, args, { cwd: dir, encoding: "utf8" }) as { stdout?: string; stderr?: string; error?: Error }
if (r.error) return Promise.reject(new Error(`couldn't run raea ask: ${r.error.message}`))
const rows = rowsOf(String(r.stdout ?? ""))
if (rows.length !== says.length) return Promise.reject(new Error(`raea ask answered ${rows.length} of ${says.length} about ${file}: ${String(r.stderr ?? "").trim().slice(-300) || String(r.stdout ?? "").trim().slice(-300)}`))
return Promise.resolve(rows)
}
return new Promise((ok, no) => {
const c = cp.spawn(RAEA, args, { cwd: dir, stdio: ["ignore", "pipe", "pipe"] })
let out = "", err = ""
c.stdout.setEncoding("utf8").on("data", (t: string) => (out += t))
c.stderr.setEncoding("utf8").on("data", (t: string) => (err = (err + t).slice(-4000)))
c.on("error", (e) => no(new Error(`couldn't run raea ask: ${e.message}`)))
c.on("close", () => {
const rows = rowsOf(out)
if (rows.length !== says.length) return no(new Error(`raea ask answered ${rows.length} of ${says.length} about ${file}: ${err.trim().slice(-300) || out.trim().slice(-300)}`))
ok(rows)
})
})
}
/** the goal's `says` rules judged (`raea goal check` asks this itself; `raea goal judge` too): each where it's judged
* (criticUrl above), its verdict kept at review/judge/NAME.json, stamped with when it was asked (so work changed while
* it judged counts as changed after) */
export async function judge(g: Contract, dir: string, o: { ask?: typeof askClef; agent?: (cwd: string, prompt: string) => Promise<string> } = {}): Promise<Verdict> {
const all = saysOf(g)
if (!all.length) throw new Error(`goal ${nameOf(g)} has no \`says\` rules; its \`run\` and \`file\` rules are held by raea goal check`)
const asked = Math.floor(Date.now() / 1000)
const watched = all.filter((r) => piecesOf(r, dir).length > 0)
const read = all.filter((r) => !watched.includes(r))
// what's watched and heard, and what's read, at once: neither waits on the other
const [heard, said] = await Promise.all([
watched.length ? clefVerdict(g, dir, o.ask ?? askClef, watched) : Promise.resolve({} as Verdict["rules"]),
read.length ? (o.agent ?? askAgent)(dir, prompt(g, dir, read)) : Promise.resolve(null),
])
const rules: Verdict["rules"] = { ...heard }
if (said !== null) {
const v = lastVerdict(said)
if (!v) throw new Error(`the critic gave no verdict: ${said.slice(-300).trim()}`)
for (const r of read) rules[r.id] = v.rules?.[r.id] ?? { pass: false, why: "the critic didn't answer this rule" }
}
return keep(g, dir, { at: asked, by: [watched.length ? "clef" : "", read.length ? "agent" : ""].filter(Boolean).join("+"), goal: g.aim ?? nameOf(g), rules })
}
/** a fresh session of this project's own agent, through the host that started it (RAEA_JUDGE_URL): what it says */
async function askAgent(cwd: string, p: string): Promise<string> {
const url = criticUrl()
if (!url) throw new Error(NO_CRITIC)
const r = await fetch(url, { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${process.env.RAEA_JUDGE_TOKEN ?? ""}` }, body: JSON.stringify({ cwd, prompt: p }), signal: AbortSignal.timeout(15 * 60_000) })
const j = (await r.json().catch(() => ({}))) as { text?: string; error?: string }
if (!r.ok || typeof j.text !== "string") throw new Error(j.error ?? `the critic answered ${r.status}`)
return j.text
}
function keep(g: Contract, dir: string, out: Verdict): Verdict {
const file = path.join(dir, verdictPath(g))
mkdirSync(path.dirname(file), { recursive: true })
writeFileSync(file, `${JSON.stringify(out, null, 2)}\n`)
return out
}
export const hasVerdict = (dir: string, g: Contract) => existsSync(path.join(dir, verdictPath(g)))
+27
View File
@@ -0,0 +1,27 @@
// An agent socket kept alive, and ended when its caller is gone (the /v1/acp socket, main.ts).
// A message every 20 s, so the socket is never idle: between raea cloud and the box it's closed after about two minutes
// without traffic, and an agent waiting on a long render sends nothing (11-25: five of StreetTalk's seven "socket
// closed" ends came 114-125 s into a silence). raea cloud skips notifications it doesn't know; the agent never sees it.
// And a ping with it: a caller that answers none for CALLER_GONE_MS is gone though its half of the socket stayed open
// (an API restart), and the socket is ended, which stops its agent (12-03: a stopped project's Gemini, busy, so never
// idle, went on an hour running goal checks on raea-5).
import type { WebSocket } from "ws"
export const CALLER_GONE_MS = 3 * 60_000
const EVERY_MS = 20_000
/** the keepalive's timer: clear it when the socket closes */
export function keepAlive(ws: WebSocket, who: string, goneMs = CALLER_GONE_MS, everyMs = EVERY_MS): ReturnType<typeof setInterval> {
let pong = Date.now()
ws.on("pong", () => (pong = Date.now()))
return setInterval(() => {
if (ws.readyState !== ws.OPEN) return
if (Date.now() - pong > goneMs) {
process.stderr.write(`raea-cloud: ${who}'s caller answered no ping in ${Math.round(goneMs / 1000)} s: ended\n`)
ws.terminate()
return
}
ws.send('{"jsonrpc":"2.0","method":"_raea/keepalive"}')
ws.ping()
}, everyMs)
}
+107
View File
@@ -0,0 +1,107 @@
// The critic a project's rules are judged by on this box (Shane, 12-03: "nothing should judge or check with another
// harness ... the context should never tell the agent to even have to decide what harness or model or provider"):
// a fresh session of the same agent the project runs on, with the same sign-in, asked one question and given nothing
// it could change. Each agent session started here (WS /v1/acp) gets RAEA_JUDGE_URL and RAEA_JUDGE_TOKEN in its
// environment; `raea goal judge` and `raea judge` in that agent's shell POST to it, and the critic runs as that agent.
//
// POST /host/judge {cwd, prompt} authorization: Bearer RAEA_JUDGE_TOKEN -> {text}
//
// The token is the session's: it names the agent and environment to start, and is forgotten when the session ends.
import { spawn } from "node:child_process"
import { randomBytes } from "node:crypto"
import path from "node:path"
interface Critic {
command: string
args: string[]
env: NodeJS.ProcessEnv
root: string
}
const critics = new Map<string, Critic>()
/** the environment an agent session adds so its shell can ask for a critic: the URL and the session's token */
export function register(c: Critic, port: number): { env: Record<string, string>; forget: () => void } {
const token = randomBytes(24).toString("hex")
critics.set(token, c)
return { env: { RAEA_JUDGE_URL: `http://127.0.0.1:${port}/host/judge`, RAEA_JUDGE_TOKEN: token }, forget: () => critics.delete(token) }
}
/** the critic a token names, or null */
export const criticFor = (token: string | null | undefined): Critic | null => (token ? (critics.get(token) ?? null) : null)
/** a permission the critic asks for: what only reads is allowed once, anything else refused (it judges, it changes nothing) */
type Option = { optionId: string; kind: string }
export function answerPermission(p: { options: Option[]; toolCall?: { kind?: string } }): string {
const reads = ["read", "search", "fetch", "think"].includes(String(p.toolCall?.kind ?? ""))
const want = reads ? ["allow_once", "allow_always"] : ["reject_once", "reject_always"]
return (p.options.find((o) => want.includes(o.kind)) ?? p.options.find((o) => (reads ? o.kind.startsWith("allow") : o.kind.startsWith("reject"))) ?? p.options[0]).optionId
}
/** one question to a fresh session of the critic's agent in `cwd`: what it says back */
export function ask(c: Critic, cwd: string, prompt: string, timeoutMs = 10 * 60_000): Promise<string> {
const dir = path.resolve(c.root, cwd)
if (dir !== c.root && !dir.startsWith(c.root + path.sep)) return Promise.reject(new Error(`${cwd} isn't in the workspace`))
return new Promise((done, fail) => {
const child = spawn(c.command, c.args, { cwd: dir, env: c.env, stdio: ["pipe", "pipe", "pipe"], detached: true })
let said = ""
let err = ""
let n = 0
let finished = false
const waiting = new Map<number, (m: { result?: unknown; error?: { message?: string } }) => void>()
const stop = () => {
try {
if (child.pid) process.kill(-child.pid, "SIGTERM")
} catch {}
}
const end = (e: Error | null) => {
if (finished) return
finished = true
clearTimeout(timer)
stop()
e ? fail(e) : done(said)
}
const timer = setTimeout(() => end(new Error(`the critic said nothing final in ${Math.round(timeoutMs / 60_000)} min`)), timeoutMs)
const send = (m: object) => child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", ...m })}\n`)
const call = (method: string, params: object) =>
new Promise<any>((ok, no) => {
const id = ++n
waiting.set(id, (m) => (m.error ? no(new Error(m.error.message ?? JSON.stringify(m.error))) : ok(m.result)))
send({ id, method, params })
})
let buf = ""
child.stdout.setEncoding("utf8").on("data", (chunk: string) => {
buf += chunk
for (let i; (i = buf.indexOf("\n")) >= 0; buf = buf.slice(i + 1)) {
let m: any
try {
m = JSON.parse(buf.slice(0, i))
} catch {
continue
}
if (m.id != null && !m.method && waiting.has(m.id)) {
const w = waiting.get(m.id)!
waiting.delete(m.id)
w(m)
} else if (m.method === "session/update") {
const u = m.params?.update
if (u?.sessionUpdate === "agent_message_chunk" && u.content?.type === "text") said += u.content.text ?? ""
} else if (m.method === "session/request_permission") {
send({ id: m.id, result: { outcome: { outcome: "selected", optionId: answerPermission(m.params) } } })
} else if (m.id != null && m.method) {
// a client method this critic doesn't offer (it reads with its own tools)
send({ id: m.id, error: { code: -32601, message: `${m.method} isn't offered here` } })
}
}
})
child.stderr.setEncoding("utf8").on("data", (c: string) => (err = (err + c).slice(-4000)))
child.on("error", (e) => end(new Error(`the critic didn't start: ${e.message}`)))
child.on("exit", (code) => end(finished ? null : new Error(`the critic ended (${code}) before it answered: ${err.trim().slice(-300)}`)))
;(async () => {
await call("initialize", { protocolVersion: 1, clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false } })
const s = await call("session/new", { cwd: dir, mcpServers: [] })
await call("session/prompt", { sessionId: s.sessionId, prompt: [{ type: "text", text: prompt }] })
end(null)
})().catch((e) => end(e as Error))
})
}
+37
View File
@@ -0,0 +1,37 @@
// GET and PUT /v1/files: a file of the work folder read or written, or a folder listed. Both ways stream: a body is
// never held in memory (12-03: a box's home folder, gigabytes, moved from a Sprite to a Fly Machine in one request).
import { createReadStream, createWriteStream, mkdirSync, readdirSync, renameSync, rmSync, statSync } from "node:fs"
import type { IncomingMessage, ServerResponse } from "node:http"
import path from "node:path"
import { pipeline } from "node:stream/promises"
type Json = (res: ServerResponse, v: unknown, status?: number) => unknown
export function files(req: IncomingMessage, res: ServerResponse, url: URL, o: { resolve: (p: string) => string; work: string; json: Json }) {
const { json } = o
const p = o.resolve(url.searchParams.get("path") ?? ".")
if (req.method === "PUT") {
// to disk as it comes, beside the file, then put in its place whole
mkdirSync(path.dirname(p), { recursive: true })
const part = `${p}.part-${process.pid}-${Date.now()}`
return pipeline(req, createWriteStream(part)).then(
() => {
renameSync(part, p)
json(res, { path: path.relative(o.work, p), bytes: statSync(p).size })
},
(e) => {
rmSync(part, { force: true })
if (!res.headersSent) json(res, { error: `the file didn't arrive whole: ${(e as Error).message}` }, 500)
},
)
}
let st
try {
st = statSync(p)
} catch {
return json(res, { error: `${url.searchParams.get("path")} doesn't exist` }, 404)
}
if (st.isDirectory()) return json(res, readdirSync(p, { withFileTypes: true }).map((d) => ({ name: d.name, dir: d.isDirectory(), bytes: d.isFile() ? statSync(path.join(p, d.name)).size : undefined })))
res.writeHead(200, { "content-type": "application/octet-stream", "content-length": st.size })
return pipeline(createReadStream(p), res).catch(() => res.destroy())
}
+98
View File
@@ -0,0 +1,98 @@
// A box on a Fly Machine stops itself when nothing is going on (12-03: the boxes moved off Sprites, which paused on
// their own; a Machine runs, and bills, until something stops it). Fly's proxy starts a stopped Machine again on the
// next request, so a box only has to know when it's idle: then the server exits 0, the entrypoint saves and exits, and
// the Machine (restart policy on-failure) stays stopped.
//
// Idle is all of: no request for `quietMs`, no connection open (an agent's ACP socket, a shell's stream), nothing the
// server runs, no process anywhere working in the box's work folder (a render, the footage prep, an agent's
// background job: each runs in a project's folder), and no hold. A hold is the file HOLD_FILE touched within
// `holdMs`: raea cloud touches it while a project is unfinished (its awake alarm), as it held a Sprite's task before.
//
// Off unless RAEA_CLOUD_IDLE_STOP_MIN is set (the Fly image sets it), so a box elsewhere never stops itself.
import { readdirSync, readFileSync, readlinkSync, realpathSync, statSync } from "node:fs"
import type { Server } from "node:http"
import path from "node:path"
export const HOLD_FILE = ".raea-hold"
/** a process other than this one (and its parents) whose working folder is under `work` */
export function workingIn(work: string, self = process.pid): number[] {
const mine = new Set<number>()
for (let p = self; p > 1; ) {
mine.add(p)
try {
// /proc/PID/stat: "PID (name) STATE PPID ...", the name in brackets may hold spaces
const stat = readFileSync(`/proc/${p}/stat`, "utf8")
p = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1])
} catch {
break
}
}
const out: number[] = []
let pids: string[] = []
try {
pids = readdirSync("/proc").filter((d) => /^\d+$/.test(d))
} catch {
return out
}
// the folder by the name it's given and by its real one: /proc says where a process is with no symlink in the way, and
// a Fly box's work folder is /home/sprite/work, a link to /home/raea/work (12-03: a 64 GB unpack in it was taken for
// idle and the box stopped under it)
const roots = [path.resolve(work) + "/"]
try {
roots.push(realpathSync(work) + "/")
} catch {}
for (const d of pids) {
const pid = Number(d)
if (mine.has(pid)) continue
try {
const cwd = readlinkSync(`/proc/${d}/cwd`) + "/"
if (roots.some((r) => cwd.startsWith(r))) out.push(pid)
} catch {}
}
return out
}
export interface IdleOptions {
server: Server
work: string
home: string
/** whether the server itself has something running (an agent, a shell, a job) */
busy: () => boolean
quietMs: number
holdMs?: number
everyMs?: number
log?: (line: string) => void
exit?: () => void
}
/** watches for the box going idle and exits when it has been idle a whole `quietMs`; returns what marks a request */
export function stopWhenIdle(o: IdleOptions): { touch: () => void; stop: () => void } {
let last = Date.now()
const holdMs = o.holdMs ?? 10 * 60_000
const log = o.log ?? ((l) => process.stderr.write(l + "\n"))
const exit = o.exit ?? (() => process.exit(0))
const why = (): string | null => {
if (Date.now() - last < o.quietMs) return "a request came lately"
if (o.busy()) return "the server runs something"
try {
const held = statSync(path.join(o.home, HOLD_FILE)).mtimeMs
if (Date.now() - held < holdMs) return "a project holds it"
} catch {}
const w = workingIn(o.work)
if (w.length) return `${w.length} processes work in ${o.work}`
return null
}
const timer = setInterval(() => {
o.server.getConnections((e, n) => {
if (!e && n > 0) return
if (why()) return
log(`raea-cloud: idle for ${Math.round(o.quietMs / 60_000)} min (no request, connection, process or hold): stopping, so the machine stops`)
clearInterval(timer)
o.server.close()
exit()
})
}, o.everyMs ?? 30_000)
timer.unref()
return { touch: () => void (last = Date.now()), stop: () => clearInterval(timer) }
}
+41 -27
View File
@@ -19,6 +19,8 @@
// browser): {credential, email?}, handed back once, or {pending: true} // browser): {credential, email?}, handed back once, or {pending: true}
// WS /v1/google-token/ID/screen the box's own browser for that sign-in, over VNC (google-screen.ts) // WS /v1/google-token/ID/screen the box's own browser for that sign-in, over VNC (google-screen.ts)
// POST /v1/google-token/check {credential} one short Antigravity turn on it (or a Gemini API key): {ok, said, models} // POST /v1/google-token/check {credential} one short Antigravity turn on it (or a Gemini API key): {ok, said, models}
// POST /host/judge {cwd, prompt} a fresh session of the asking agent session's own agent, as the critic its rules are
// judged by: {text}. Its token is the session's RAEA_JUDGE_TOKEN (critic.ts)
// WS /v1/acp?agent=ID one agent process per socket: a text frame is one ACP message to its stdin, // WS /v1/acp?agent=ID one agent process per socket: a text frame is one ACP message to its stdin,
// each line it prints is one frame back. A caller signing the agent in as one of // each line it prints is one frame back. A caller signing the agent in as one of
// its own clients (raea cloud, per workspace) sends x-raea-agent-env: JSON of the // its own clients (raea cloud, per workspace) sends x-raea-agent-env: JSON of the
@@ -37,9 +39,13 @@
import { claudeStopHook, jobsOf, markedEnd, sessionIn, watchEnd, watchTurnEnd } from "./turn-end.ts" import { claudeStopHook, jobsOf, markedEnd, sessionIn, watchEnd, watchTurnEnd } from "./turn-end.ts"
import { execFile, spawn } from "node:child_process" import { execFile, spawn } from "node:child_process"
import { timingSafeEqual } from "node:crypto" import { timingSafeEqual } from "node:crypto"
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, symlinkSync, writeFileSync } from "node:fs" import { existsSync, mkdirSync, readFileSync, symlinkSync } from "node:fs"
import { createServer, type IncomingMessage, type ServerResponse } from "node:http" import { createServer, type IncomingMessage, type ServerResponse } from "node:http"
import path from "node:path" import path from "node:path"
import { homedir } from "node:os"
import { keepAlive } from "./alive.ts"
import { files } from "./files.ts"
import { stopWhenIdle } from "./idle.ts"
import { WebSocketServer } from "ws" import { WebSocketServer } from "ws"
import { installed, spawnFor } from "./agents.ts" import { installed, spawnFor } from "./agents.ts"
import { guard } from "./memguard.ts" import { guard } from "./memguard.ts"
@@ -50,6 +56,7 @@ import { checkGoogle, finishGoogleSignIn, screenPort, startGoogleSignIn, unpackC
import { connect as tcp } from "node:net" import { connect as tcp } from "node:net"
import { login, loginState } from "./login.ts" import { login, loginState } from "./login.ts"
import { Outside, resolve, WORK } from "./workspace.ts" import { Outside, resolve, WORK } from "./workspace.ts"
import { ask as askCritic, criticFor, register as registerCritic } from "./critic.ts"
const TOKEN = process.env.RAEA_CLOUD_TOKEN ?? "" const TOKEN = process.env.RAEA_CLOUD_TOKEN ?? ""
if (TOKEN.length < 16) { if (TOKEN.length < 16) {
@@ -170,24 +177,6 @@ async function body(req: IncomingMessage): Promise<Buffer> {
return Buffer.concat(parts) return Buffer.concat(parts)
} }
function files(req: IncomingMessage, res: ServerResponse, url: URL) {
const p = resolve(url.searchParams.get("path") ?? ".")
if (req.method === "PUT")
return body(req).then((b) => {
mkdirSync(path.dirname(p), { recursive: true })
writeFileSync(p, b)
json(res, { path: path.relative(WORK, p), bytes: b.length })
})
let st
try {
st = statSync(p)
} catch {
return json(res, { error: `${url.searchParams.get("path")} doesn't exist` }, 404)
}
if (st.isDirectory()) return json(res, readdirSync(p, { withFileTypes: true }).map((d) => ({ name: d.name, dir: d.isDirectory(), bytes: d.isFile() ? statSync(path.join(p, d.name)).size : undefined })))
res.writeHead(200, { "content-type": "application/octet-stream", "content-length": st.size }).end(readFileSync(p))
}
/** An NDJSON answer's headers sent at once, and an empty line ({}) every KEEPALIVE_MS until it ends: the box sits /** An NDJSON answer's headers sent at once, and an empty line ({}) every KEEPALIVE_MS until it ends: the box sits
* behind Cloudflare, which answers 524 when nothing comes back for 100 s, and `raea goal check --json` over seven * behind Cloudflare, which answers 524 when nothing comes back for 100 s, and `raea goal check --json` over seven
* cuts prints nothing until it's done (11-30, Dutch's stop at Client sign-off was sent back on it). Readers skip a * cuts prints nothing until it's done (11-30, Dutch's stop at Client sign-off was sent back on it). Readers skip a
@@ -250,7 +239,23 @@ async function shell(req: IncomingMessage, res: ServerResponse) {
const server = createServer(async (req, res) => { const server = createServer(async (req, res) => {
const url = new URL(req.url ?? "/", "http://raea-cloud") const url = new URL(req.url ?? "/", "http://raea-cloud")
// a request (other than a platform's health check) keeps an idle box up (idle.ts)
// a request is the box at work from when it starts until it ends: a 19-minute upload counted only its start, and the
// box stopped as idle the moment it ended (12-03)
if (url.pathname !== "/healthz") (idle?.touch(), res.on("close", () => idle?.touch()))
if (url.pathname === "/healthz") return res.writeHead(200, { "content-type": "text/plain" }).end("ok") if (url.pathname === "/healthz") return res.writeHead(200, { "content-type": "text/plain" }).end("ok")
// the critic an agent's shell asks (critic.ts): its own session's token, not the box's
if (url.pathname === "/host/judge" && req.method === "POST") {
const c = criticFor(/^Bearer (.+)$/.exec(String(req.headers.authorization ?? ""))?.[1])
if (!c) return json(res, { error: "no agent session with that token here" }, 401)
try {
const b = JSON.parse(String(await body(req)))
if (typeof b.prompt !== "string" || !b.prompt) return json(res, { error: "prompt is the question" }, 400)
return json(res, { text: await askCritic(c, typeof b.cwd === "string" ? b.cwd : ".", b.prompt) })
} catch (e) {
return json(res, { error: (e as Error).message }, 502)
}
}
if (!authorized(req, url)) return json(res, { error: "unauthorized" }, 401) if (!authorized(req, url)) return json(res, { error: "unauthorized" }, 401)
try { try {
if (url.pathname === "/v1/health" && req.method === "GET") { if (url.pathname === "/v1/health" && req.method === "GET") {
@@ -278,7 +283,7 @@ const server = createServer(async (req, res) => {
running: running.size, running: running.size,
}) })
} }
if (url.pathname === "/v1/files" && (req.method === "GET" || req.method === "PUT")) return await files(req, res, url) if (url.pathname === "/v1/files" && (req.method === "GET" || req.method === "PUT")) return await files(req, res, url, { resolve, work: WORK, json })
if (url.pathname === "/v1/run" && req.method === "POST") return await run(req, res) if (url.pathname === "/v1/run" && req.method === "POST") return await run(req, res)
if (url.pathname === "/v1/shell" && req.method === "POST") return await shell(req, res) if (url.pathname === "/v1/shell" && req.method === "POST") return await shell(req, res)
if (url.pathname === "/v1/jobs" && req.method === "POST") { if (url.pathname === "/v1/jobs" && req.method === "POST") {
@@ -370,7 +375,10 @@ server.on("upgrade", (req, socket, head) => {
} catch (e) { } catch (e) {
return socket.end(`HTTP/1.1 400 Bad Request\r\ncontent-type: text/plain\r\n\r\n${(e as Error).message}`) return socket.end(`HTTP/1.1 400 Bad Request\r\ncontent-type: text/plain\r\n\r\n${(e as Error).message}`)
} }
const env = own ? { ...withoutKeys(childEnv()), ...agent.env, ...RUN_DEFAULTS, ...own } : { ...childEnv(), ...agent.env } const base = own ? { ...withoutKeys(childEnv()), ...agent.env, ...RUN_DEFAULTS, ...own } : { ...childEnv(), ...agent.env }
// this session's critic (critic.ts): the same agent, sign-in and environment, which `raea goal judge` in its shell asks
const critic = registerCritic({ command: agent.command, args: agent.args, env: base, root: WORK }, PORT)
const env = { ...base, ...critic.env }
wss.handleUpgrade(req, socket, head, (ws) => { wss.handleUpgrade(req, socket, head, (ws) => {
// its own process group, so what it started (a render left running in the background) stops with it: a killed // its own process group, so what it started (a render left running in the background) stops with it: a killed
// agent's renders went on as orphans, 4 GB of them on raea-2 (11-25) // agent's renders went on as orphans, 4 GB of them on raea-2 (11-25)
@@ -388,11 +396,7 @@ server.on("upgrade", (req, socket, head) => {
} }
running.add(child) running.add(child)
agentSockets.add(ws) agentSockets.add(ws)
// a message every 20 s, so the socket is never idle: between raea cloud and the box it's closed after about two const beat = keepAlive(ws, agent.id)
// minutes without traffic, and an agent waiting on a long render sends nothing (11-25: five of StreetTalk's seven
// "socket closed" ends came 114-125 s into a silence). raea cloud skips notifications it doesn't know; the agent
// never sees it
const beat = setInterval(() => ws.readyState === ws.OPEN && ws.send('{"jsonrpc":"2.0","method":"_raea/keepalive"}'), 20_000)
// an agent that has said nothing and been sent nothing for IDLE_AGENT_MS is ended: raea cloud ends a turn whose // an agent that has said nothing and been sent nothing for IDLE_AGENT_MS is ended: raea cloud ends a turn whose
// agent is quiet 30 min (acp-run.ts QUIET_TOOL_MS), and a socket whose caller went away without closing it (an API // agent is quiet 30 min (acp-run.ts QUIET_TOOL_MS), and a socket whose caller went away without closing it (an API
// restart; the Sprite's proxy kept the box's half open) otherwise kept its agent forever (11-30: two Gemini agents // restart; the Sprite's proxy kept the box's half open) otherwise kept its agent forever (11-30: two Gemini agents
@@ -404,7 +408,7 @@ server.on("upgrade", (req, socket, head) => {
ws.terminate() ws.terminate()
stopAll() stopAll()
}, Math.min(60_000, IDLE_AGENT_MS / 2)) }, Math.min(60_000, IDLE_AGENT_MS / 2))
ws.on("close", () => (agentSockets.delete(ws), clearInterval(beat), clearInterval(idle))) ws.on("close", () => (agentSockets.delete(ws), clearInterval(beat), clearInterval(idle), critic.forget()))
child.on("exit", () => (running.delete(child), clearInterval(idle))) child.on("exit", () => (running.delete(child), clearInterval(idle)))
// its stderr to the box's log as before, and along the socket as _raea/stderr notifications, so raea cloud keeps // its stderr to the box's log as before, and along the socket as _raea/stderr notifications, so raea cloud keeps
// it with the run's trace (runtrace.ts) instead of only on this box's disk (11-25: raea-1's logs died with it) // it with the run's trace (runtrace.ts) instead of only on this box's disk (11-25: raea-1's logs died with it)
@@ -471,6 +475,16 @@ if (existsSync("/proc/meminfo") && process.env.RAEA_CLOUD_MEMGUARD !== "0")
process.stderr.write(line + "\n") process.stderr.write(line + "\n")
for (const ws of agentSockets) if (ws.readyState === ws.OPEN) ws.send(JSON.stringify({ jsonrpc: "2.0", method: "_raea/stderr", params: { text: line + "\n" } })) for (const ws of agentSockets) if (ws.readyState === ws.OPEN) ws.send(JSON.stringify({ jsonrpc: "2.0", method: "_raea/stderr", params: { text: line + "\n" } }))
}) })
// a box on a Fly Machine stops itself when nothing is going on, and Fly's proxy starts it at the next request (idle.ts)
const idleMin = Number(process.env.RAEA_CLOUD_IDLE_STOP_MIN ?? 0)
const idle =
idleMin > 0
? stopWhenIdle({ server, work: WORK, home: homedir(), busy: () => running.size > 0 || agentSockets.size > 0, quietMs: idleMin * 60_000 })
: null
// a request may take as long as its body takes to come: Node's 5 minutes cut a home folder's upload off at 408
// (12-03, a Sprite's home moved to a Fly box). A client still has 60 s to send its headers.
server.requestTimeout = 0
server.headersTimeout = 60_000
server.listen(PORT, async () => { server.listen(PORT, async () => {
await versionKnown await versionKnown
const d = device(childEnv()) const d = device(childEnv())
+44 -3
View File
@@ -225,13 +225,54 @@ export async function farmInputs(root: string, farm: FarmBlobs, skip: (p: string
let sent = 0 let sent = 0
const todo = media.filter((m, i) => !have.has(m.oid) && media.findIndex((x) => x.oid === m.oid) === i) const todo = media.filter((m, i) => !have.has(m.oid) && media.findIndex((x) => x.oid === m.oid) === i)
if (todo.length) said(`sending ${todo.length} media files (${(todo.reduce((n, m) => n + m.size, 0) / 1e6).toFixed(1)} MB) to the farm's cache, once`) if (todo.length) said(`sending ${todo.length} media files (${(todo.reduce((n, m) => n + m.size, 0) / 1e6).toFixed(1)} MB) to the farm's cache, once`)
for (const m of todo) { // four at a time: one by one, 50 takes took minutes on a box whose uplink sits mostly idle
await farm.put(m.abs, m.oid, m.size) let next = 0
sent += m.size const one = async () => {
for (let i = next++; i < todo.length; i = next++) {
await farm.put(todo[i].abs, todo[i].oid, todo[i].size)
sent += todo[i].size
}
} }
await Promise.all(Array.from({ length: Math.min(4, todo.length) }, one))
return { media: media.map(({ abs: _, ...m }) => m), sent } return { media: media.map(({ abs: _, ...m }) => m), sent }
} }
/** the project's video and audio that no source file names, which a render doesn't need: neither sent to the farm nor
* packed. 12-03: footage/originals/ (the full-size takes, several GB) went to the farm on the first render of every
* StreetTalk run, a still included, and the render ran past its 5 minutes. A file is named by its path, its file name,
* or its stem with its folder's name ("originals/" + `${id}.mov`). When no source names any, all of it is used, as
* before; RAEA_CLOUD_GPU_ALL_MEDIA=1 sends it all regardless */
export function unusedMedia(root: string, skip: (p: string) => boolean = () => false): string[] {
if (process.env.RAEA_CLOUD_GPU_ALL_MEDIA === "1") return []
const AV = new Set(["mp4", "mov", "m4v", "webm", "mkv", "mxf", "avi", "wav", "mp3", "m4a", "aac", "flac", "ogg"])
const SRC = new Set(["tsx", "ts", "jsx", "js", "mjs", "json", "css"])
// folders of what's made for the agent or by a render, not what a composition reads from (footage/index.json lists
// every take)
const NOT_SOURCE = new Set(["footage", "brief_docs", "review", "out", "node_modules", "previews"])
const av: string[] = []
let text = ""
const walk = (dir: string, source: boolean) => {
for (const e of readdirSync(dir, { withFileTypes: true })) {
const abs = path.join(dir, e.name)
const rel = path.relative(root, abs).split(path.sep).join("/")
if (skip(rel) || e.name === ".git" || e.name.startsWith(".raea-cloud")) continue
const ext = e.name.includes(".") ? e.name.split(".").pop()!.toLowerCase() : ""
if (e.isDirectory()) walk(abs, source && !(dir === root && NOT_SOURCE.has(e.name)))
else if (e.isFile() && AV.has(ext)) av.push(rel)
else if (e.isFile() && source && SRC.has(ext) && statSync(abs).size < 2 << 20) text += readFileSync(abs, "utf8") + "\n"
}
}
walk(root, true)
const named = (rel: string) => {
const name = rel.split("/").pop()!
const stem = name.replace(/\.[^.]+$/, "")
const folder = rel.includes("/") ? rel.split("/").slice(-2, -1)[0] + "/" : ""
return text.includes(rel) || text.includes(name) || (stem.length >= 3 && text.includes(stem) && (!folder || text.includes(folder)))
}
const used = av.filter(named)
return used.length ? av.filter((f) => !used.includes(f)) : []
}
/** tar's exclude-from lines for paths that go by hash: each matched as written (glob characters escaped) */ /** tar's exclude-from lines for paths that go by hash: each matched as written (glob characters escaped) */
export const excludes = (media: Media[]) => media.map((m) => "./" + m.path.replace(/[\\*?[\]]/g, (c) => "\\" + c)).join("\n") + "\n" export const excludes = (media: Media[]) => media.map((m) => "./" + m.path.replace(/[\\*?[\]]/g, (c) => "\\" + c)).join("\n") + "\n"
+11 -3
View File
@@ -21,7 +21,7 @@ import os from "node:os"
import path from "node:path" import path from "node:path"
import { pathToFileURL } from "node:url" import { pathToFileURL } from "node:url"
import { RaeaCloud } from "../src/index.ts" import { RaeaCloud } from "../src/index.ts"
import { excluded, excludes as mediaExcludes, farmBlobs, farmInputs, inputs, lfsOf, localSources, outputs } from "./media.ts" import { excluded, excludes as mediaExcludes, farmBlobs, farmInputs, inputs, lfsOf, localSources, outputs, unusedMedia } from "./media.ts"
const REAL = process.env.RAEA_REAL ?? "/opt/raea/bin/raea" const REAL = process.env.RAEA_REAL ?? "/opt/raea/bin/raea"
// flags whose value is a path raea writes; the rest of a render's path arguments are read // flags whose value is a path raea writes; the rest of a render's path arguments are read
@@ -111,16 +111,24 @@ async function main() {
const sent = path.join(tmp, "in.tar") const sent = path.join(tmp, "in.tar")
// the media that goes by hash: out of the tar, named in its manifest // the media that goes by hash: out of the tar, named in its manifest
const lfs = lfsOf(p.root) const lfs = lfsOf(p.root)
let byHash = typeof lfs === "string" ? [] : await inputs(p.root, lfs, excluded(excludes)) // video and audio no source file names stays here, out of the tar and the farm's cache (media.ts unusedMedia)
const unused = new Set(unusedMedia(p.root, excluded(excludes)))
if (unused.size) say(`${unused.size} video and audio files no source names stay here`)
const skip = (rel: string) => excluded(excludes)(rel) || unused.has(rel)
let byHash = typeof lfs === "string" ? [] : await inputs(p.root, lfs, skip)
// not in raea's LFS: the media goes into the farm's own cache by hash, once, instead of in every render's tar // not in raea's LFS: the media goes into the farm's own cache by hash, once, instead of in every render's tar
// (RAEA_CLOUD_GPU_BLOBS=0 puts it back in the tar). A farm without the cache, or one that can't be reached here, // (RAEA_CLOUD_GPU_BLOBS=0 puts it back in the tar). A farm without the cache, or one that can't be reached here,
// leaves it in the tar, and the health check below says why the farm can't be reached // leaves it in the tar, and the health check below says why the farm can't be reached
let viaFarm: { media: typeof byHash; sent: number } | null = null let viaFarm: { media: typeof byHash; sent: number } | null = null
if (typeof lfs === "string" && process.env.RAEA_CLOUD_GPU_BLOBS !== "0") { if (typeof lfs === "string" && process.env.RAEA_CLOUD_GPU_BLOBS !== "0") {
viaFarm = await farmInputs(p.root, farmBlobs(url, token), excluded(excludes), say).catch((e) => (say(`the farm's media cache: ${(e as Error).message}; the media goes in the tar`), null)) viaFarm = await farmInputs(p.root, farmBlobs(url, token), skip, say).catch((e) => (say(`the farm's media cache: ${(e as Error).message}; the media goes in the tar`), null))
if (viaFarm) byHash = viaFarm.media if (viaFarm) byHash = viaFarm.media
} }
const extra: string[] = [] const extra: string[] = []
if (unused.size) {
writeFileSync(path.join(tmp, "unused-excludes"), mediaExcludes([...unused].map((f) => ({ path: f, oid: "", size: 0 }))))
extra.push("-X", path.join(tmp, "unused-excludes"))
}
if (byHash.length) { if (byHash.length) {
writeFileSync(path.join(tmp, "media-excludes"), mediaExcludes(byHash)) writeFileSync(path.join(tmp, "media-excludes"), mediaExcludes(byHash))
writeFileSync(path.join(tmp, ".raea-cloud-media.json"), JSON.stringify({ objects: byHash })) writeFileSync(path.join(tmp, ".raea-cloud-media.json"), JSON.stringify({ objects: byHash }))
+11 -1
View File
@@ -91,6 +91,15 @@ async function follow(res: Response, onOutput: ((text: string, stream: "out" | "
throw new Error(`${what} ended without an exit code`) throw new Error(`${what} ended without an exit code`)
} }
/** whether a box's address is a Sprite's (behind the Sprite's own auth) */
export const onSprite = (url: string): boolean => {
try {
return new URL(url).hostname.endsWith(".sprites.app")
} catch {
return false
}
}
export class RaeaCloud { export class RaeaCloud {
readonly url: string readonly url: string
private token: string private token: string
@@ -103,7 +112,8 @@ export class RaeaCloud {
constructor(o: { url: string; token: string; spriteToken?: string }) { constructor(o: { url: string; token: string; spriteToken?: string }) {
this.url = o.url.replace(/\/+$/, "") this.url = o.url.replace(/\/+$/, "")
this.token = o.token this.token = o.token
this.spriteToken = o.spriteToken // only a box on a Sprite is behind the Sprite's auth; a box elsewhere (a Fly Machine's own app) takes its token
this.spriteToken = onSprite(this.url) ? o.spriteToken : undefined
} }
/** A request to the box, its response as it comes, for a caller that reads the body itself (a stream of a file /** A request to the box, its response as it comes, for a caller that reads the body itself (a stream of a file
+104
View File
@@ -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())
+60
View File
@@ -69,6 +69,11 @@ class FakeGpu:
def starmap(self, calls, order_outputs=False, return_exceptions=True): def starmap(self, calls, order_outputs=False, return_exceptions=True):
return [self.remote(*c) for c in calls] return [self.remote(*c) for c in calls]
def spawn(self, *a, **kw):
# a run spawned on its own (farm_plan.hedged, waited): answered at once
r = self.remote(*a, **kw)
return type("Done", (), {"get": lambda self, timeout=None: r, "cancel": lambda self: None})()
lines = [] lines = []
log = lambda t, err=False: lines.append(t) log = lambda t, err=False: lines.append(t)
@@ -123,6 +128,14 @@ clips = sorted(man["sounds"]["clips"], key=lambda c: c["from"])
assert [(c["key"], c["from"], c["to"]) for c in clips] == [("n3", 0, 40), ("n8", 40, 60)], clips assert [(c["key"], c["from"], c["to"]) for c in clips] == [("n3", 0, 40), ("n8", 40, 60)], clips
assert abs(clips[0]["at"] - 1.0) < 1e-6 and abs(clips[1]["at"] - 9.0) < 1e-6 and clips[0].get("fadeIn") == 0.012 and clips[1].get("fadeOut") == 0.012, clips assert abs(clips[0]["at"] - 1.0) < 1e-6 and abs(clips[1]["at"] - 9.0) < 1e-6 and clips[0].get("fadeIn") == 0.012 and clips[1].get("fadeOut") == 0.012, clips
ok("a split render's manifest is its runs' joined: all 60 frames, and each clip whole with its source time") ok("a split render's manifest is its runs' joined: all 60 frames, and each clip whole with its source time")
# 12-04 (StreetTalk round 22): each run numbers its React nodes its own way, so one clip came back as n3 then n11 by
# turns; joined only by key, it stayed in pieces and the sound check called every seam a cut inside a word
m2 = fp.joined({"frames": []}, [
{"frames": [{"frame": 0}], "sounds": {"fps": 30, "clips": [{"key": "n3", "src": "t.mp4", "from": 0, "to": 60, "at": 194.667}]}},
{"frames": [{"frame": 60}], "sounds": {"fps": 30, "clips": [{"key": "n11", "src": "t.mp4", "from": 60, "to": 90, "at": 196.667}]}},
])
assert [(c["src"], c["from"], c["to"]) for c in m2["sounds"]["clips"]] == [("t.mp4", 0, 90)], m2["sounds"]["clips"]
ok("a clip carried across a run's seam under another key is joined whole")
lines.clear() lines.clear()
long = FakeGpu(root, length=1000) long = FakeGpu(root, length=1000)
@@ -344,3 +357,50 @@ assert not any("waiting" in l for l in lines), lines
ok("a GPU run that timed out fails the job instead of being waited on forever") ok("a GPU run that timed out fails the job instead of being waited on forever")
shutil.rmtree(root) shutil.rmtree(root)
# a flat video's runs go out at once, and a run that hangs back is sent again (farm_plan.hedged, 12-03)
class Call:
def __init__(self, answer_at, r, clock):
self.answer_at, self.r, self.clock, self.cancelled = answer_at, r, clock, False
def get(self, timeout=None):
if self.clock() >= self.answer_at:
return self.r
raise TimeoutError()
def cancel(self):
self.cancelled = True
class Straggly:
"""runs that answer after 10 s, but the first try of the run from frame 40 answers only after 500 s"""
def __init__(self, clock):
self.clock, self.spawned = clock, []
def with_options(self, **kw):
return self
def spawn(self, id, args, frames, first, *rest):
late = first == 40 and not any(f == 40 for f, _ in self.spawned)
c = Call(self.clock() + (500 if late else 10), {"code": 0, "s": 10.0, "frames": len(frames), "first": first}, self.clock)
self.spawned.append((first, c))
return c
now = [0.0]
clock = lambda: now[0]
def tick(_s):
now[0] += 1
st = Straggly(clock)
lines.clear()
calls = [("jh", ["render"], list(range(a, a + 10)), a, False, True) for a in range(0, 60, 10)]
got = []
assert fp.hedged(st, "CPU", calls, log, "frames", got=got, again=[], clock=clock, pause=tick) == 0, lines
assert sorted(r["first"] for r in got) == [0, 10, 20, 30, 40, 50], got
assert [f for f, _ in st.spawned].count(40) == 2, st.spawned
assert now[0] < 100, now
assert any("sent again" in l for l in lines), lines
assert [c.cancelled for f, c in st.spawned if f == 40] == [True, True]
ok("a run that hangs back while the rest are in is sent again, and the first answer kept: the render doesn't wait on it")
+51 -1
View File
@@ -4,7 +4,7 @@
import assert from "node:assert/strict" import assert from "node:assert/strict"
import { execSync } from "node:child_process" import { execSync } from "node:child_process"
import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs" import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs"
import os from "node:os" import os from "node:os"
import path from "node:path" import path from "node:path"
import { parseSummary, pick } from "../server/gpu.ts" import { parseSummary, pick } from "../server/gpu.ts"
@@ -13,6 +13,8 @@ import { shellEnv } from "../server/shell-os.ts"
import { claudeStopHook, jobsOf, lastLine, markedEnd, sessionIn, transcriptOf, turnEndOf, watchEnd, watchTurnEnd } from "../server/turn-end.ts" import { claudeStopHook, jobsOf, lastLine, markedEnd, sessionIn, transcriptOf, turnEndOf, watchEnd, watchTurnEnd } from "../server/turn-end.ts"
import { landedQuery, linkIn, packCredential, unpackCredential } from "../server/google-token.ts" import { landedQuery, linkIn, packCredential, unpackCredential } from "../server/google-token.ts"
import { localSources } from "../server/media.ts" import { localSources } from "../server/media.ts"
import { keepAlive } from "../server/alive.ts"
import { answerPermission, ask as askCritic, criticFor, register as registerCritic } from "../server/critic.ts"
const L4 = `Devices: const L4 = `Devices:
======== ========
@@ -213,3 +215,51 @@ console.log("units: ok")
assert.equal(localSources({}, [], "/x"), 0) assert.equal(localSources({}, [], "/x"), 0)
console.log("ok localSources") console.log("ok localSources")
} }
{
// the critic (critic.ts): a session's token names its agent; a fresh session of it answers; reads only
const root = realpathSync(mkdtempSync(path.join(os.tmpdir(), "critic-")))
mkdirSync(path.join(root, "proj"))
const agent = { command: process.execPath, args: [path.join(import.meta.dirname, "echo-agent.mjs")], env: { ...process.env }, root }
const r = registerCritic(agent, 8080)
assert.equal(r.env.RAEA_JUDGE_URL, "http://127.0.0.1:8080/host/judge")
assert.equal(criticFor(r.env.RAEA_JUDGE_TOKEN), agent)
assert.equal(criticFor("nope"), null)
const said = await askCritic(agent, "proj", "is the plan complete?")
assert.match(said, /echo: is the plan complete\?/)
assert.match(said, new RegExp(`cwd: ${path.join(root, "proj").replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`))
// the echo agent's permission names no kind of tool: refused, as anything but a read is
assert.match(said, /permission: no/)
await assert.rejects(askCritic(agent, "../elsewhere", "x"), /isn't in the workspace/)
assert.equal(answerPermission({ toolCall: { kind: "read" }, options: [{ optionId: "a", kind: "allow_once" }, { optionId: "r", kind: "reject_once" }] }), "a")
assert.equal(answerPermission({ toolCall: { kind: "edit" }, options: [{ optionId: "a", kind: "allow_once" }, { optionId: "r", kind: "reject_once" }] }), "r")
r.forget()
assert.equal(criticFor(r.env.RAEA_JUDGE_TOKEN), null)
rmSync(root, { recursive: true, force: true })
console.log("ok critic")
}
{
// a caller that answers pings keeps its socket; one that answers none is ended, which stops its agent (alive.ts)
const { WebSocketServer, WebSocket } = await import("ws")
const wss = new WebSocketServer({ port: 0 })
const port = (wss.address() as { port: number }).port
const ended: boolean[] = []
wss.on("connection", (ws) => {
const beat = keepAlive(ws, "test", 120, 20)
ws.on("close", () => (clearInterval(beat), ended.push(true)))
})
const live = new WebSocket(`ws://127.0.0.1:${port}`)
await new Promise((ok) => live.on("open", ok))
await new Promise((ok) => setTimeout(ok, 400))
assert.equal(live.readyState, WebSocket.OPEN, "a caller that answers pings was ended")
live.close()
await new Promise((ok) => setTimeout(ok, 50))
// autoPong off: this caller answers nothing, as one whose half stayed open after it went away
const gone = new WebSocket(`ws://127.0.0.1:${port}`, { autoPong: false } as never)
await new Promise((ok) => gone.on("open", ok))
const closed = await new Promise<boolean>((ok) => (gone.on("close", () => ok(true)), setTimeout(() => ok(false), 1000)))
assert.ok(closed, "a caller that answered no ping wasn't ended")
wss.close()
console.log("ok an agent socket's caller gone is ended")
}
+40
View File
@@ -0,0 +1,40 @@
// What a render leaves on the box (server/media.ts unusedMedia): video and audio no source file names. 12-03: every
// StreetTalk run's first render sent footage/originals/ (several GB) to the farm, a still included, and ran past its
// 5 minutes. Run: node test/unused-media.ts (prints ok, or FAIL and exits 1)
import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import path from "node:path"
import { unusedMedia } from "../server/media.ts"
const fail = (m: string): never => {
console.error(`FAIL ${m}`)
process.exit(1)
}
const project = (files: Record<string, string>) => {
const root = mkdtempSync(path.join(tmpdir(), "raea-unused-"))
for (const [f, c] of Object.entries(files)) {
mkdirSync(path.dirname(path.join(root, f)), { recursive: true })
writeFileSync(path.join(root, f), c)
}
return root
}
const same = (a: string[], b: string[], what: string) => JSON.stringify([...a].sort()) === JSON.stringify([...b].sort()) || fail(`${what}: ${JSON.stringify([...a].sort())}`)
// a cut on the light copies: the originals and the untouched takes stay; index.json (which lists every take) isn't source
const takes = {
"footage/Angle1-Take1.mp4": "x", "footage/Angle1-Take2.mp4": "x", "footage/Angle2-Take1.mp4": "x",
"footage/originals/Angle1-Take1.mov": "x", "footage/originals/Angle1-Take2.mov": "x", "footage/originals/Angle2-Take1.mov": "x",
"footage/index.json": JSON.stringify(["Angle1-Take1.mp4", "Angle1-Take2.mp4", "Angle2-Take1.mp4"]),
"media/music/bed.mp3": "x",
}
same(unusedMedia(project({ ...takes, "cut_a.tsx": `<Video src="footage/Angle1-Take1.mp4" /><Video src={"footage/" + "Angle1-Take2.mp4"} /><Audio src="media/music/bed.mp3" />` })),
["footage/Angle2-Take1.mp4", "footage/originals/Angle1-Take1.mov", "footage/originals/Angle1-Take2.mov", "footage/originals/Angle2-Take1.mov"], "a cut on the light copies")
// the final render on the originals by id: originals/ named, the stem from data. The take's light copy goes too
// ("footage/" is in "footage/originals/"): a few MB, against the GB of originals that stay
same(unusedMedia(project({ ...takes, "cut_a.tsx": "const src = (id: string) => `footage/originals/${id}.mov`", "cuts.json": JSON.stringify({ shots: ["Angle1-Take1"] }) })),
["footage/Angle1-Take2.mp4", "footage/Angle2-Take1.mp4", "footage/originals/Angle1-Take2.mov", "footage/originals/Angle2-Take1.mov", "media/music/bed.mp3"], "the final render on the originals")
// nothing names any media: all of it is used, as before
same(unusedMedia(project({ ...takes, "cut_a.tsx": "export default () => null" })), [], "no source names any")
console.log("ok")
+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", 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", 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", 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", naming: "files named client_concept_variant_v#_size",
sizes: "one size first: no other size before the first is approved", sizes: "one size first: no other size before the first is approved",
quotes: "every rule quotes the brief's own words", quotes: "every rule quotes the brief's own words",
@@ -48,55 +46,37 @@ export const PACKS = {
cta: "each cut ends on the CTA", cta: "each cut ends on the CTA",
shape: "each cut in its format and length", shape: "each cut in its format and length",
run: "each command rule exits 0", 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", deliverables: "every deliverable exists",
critic: "the critic's rounds: a pass newer than the work, its blocking defects fixed or answered", floor: "no clipped text, text in the app's buttons, low contrast, freeze, flash or loudness out of range",
record: "every composition the plan names rendered or checked clean since it last changed", 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",
notes: "NOTES.md, with what the skill got wrong",
floor: "no clipped text, low contrast, freeze, flash or loudness out of range",
stills: "a composition's stills as it's saved: no clipped or cramped text, nothing out of the safe areas",
playable: "each network's page under 5 MB, in the orientations asked for, exported since the game last changed", playable: "each network's page under 5 MB, in the orientations asked for, exported since the game last changed",
} as const } as const
export type PackName = keyof typeof PACKS 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[]> = { 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"], // a word clipped or missing, a face cut by the frame, text over a face, a sign or the app's buttons, captions over
rules: ["deliverables", "stills"], // talking, the brief's must-say, never-say and CTA, the size, length and name, and what the render itself found
scene: ["deliverables", "record", "critic", "notes", "stills"], cut: ["words", "sound", "frames", "place", "captions", "floor", "render", "say", "never", "cta", "shape", "naming", "sizes", "count", "open"],
kit: ["deliverables", "record", "critic", "notes", "stills"], rules: ["deliverables", "render"],
shot: ["deliverables", "record", "critic", "notes", "stills"], // a 3D scene, kit or shot: what its render found (clipping, a part out of place or under its detail, light that
playable: ["deliverables", "playable", "stills"], // jumps or boils: the render's own end checks, in its manifest)
// a project with no `goal`: what any made video is held to, and any composition as it's saved scene: ["deliverables", "render"],
floor: ["frames", "captions", "voice", "reading", "hook", "airgaps", "floor", "seen", "stills"], kit: ["deliverables", "render"],
} shot: ["deliverables", "render"],
playable: ["deliverables", "playable", "render"],
/** a `says` rule: what a fresh critic must find true of the work (`raea goal judge`) */ // a project with no `goal`: what any made video is held to
export type Said = { id: string; says: string } floor: ["frames", "place", "captions", "floor", "render"],
/** every `says` rule a goal is held to: its own, then a cut goal's beats (MK48), each judged on its cut as a viewer sees
* it, shots in sequence: what a shot means comes from its neighbours (Kuleshov), so a beat is read in the cut, never
* shot by shot. Murch puts emotion (51%) and story (23%) above all a cut's other reasons; no measure finds them */
export function saysOf(g: Contract | null): Said[] {
const own = (g?.rules ?? []).flatMap((r) => (r.says ? [{ id: r.id, says: r.says }] : []))
const c = g?.kind === "cut" ? g.cut : undefined
const beats = (c?.cuts ?? []).flatMap((p) => {
const formats = p.formats?.length ? p.formats : (c?.formats ?? [])
const file = formats.length ? `out/cuts/${p.id}_${formats[0].replace(":", "x")}.mp4` : `cut ${p.id}`
const bs = p.beats ?? []
return bs.map((b, i) => {
const until = bs[i + 1] ? `${bs[i + 1].at} s` : "its end"
return { id: `beat_${p.id}_${i + 1}`, says: `In ${file}, from ${b.at} s to ${until}, watched in sequence as cut (a shot reads by its neighbours), the viewer feels ${b.feel}${b.story ? `, and by its end understands ${b.story}` : ""}` }
})
})
return [...own, ...beats]
} }
/** the packs that hold a goal: its kind's, its rules' (any goal with rules is held to them), then its switches */ /** 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[] { export function packsOf(c: Contract | null): PackName[] {
const on = new Set<PackName>(DEFAULTS[c?.kind ?? "floor"]) const on = new Set<PackName>(DEFAULTS[c?.kind ?? "floor"])
if (c?.rules?.some((r) => r.run)) on.add("run") 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 ?? {})) { for (const [k, v] of Object.entries(c?.packs ?? {})) {
if (!(k in PACKS)) continue if (!(k in PACKS)) continue
if (v) on.add(k as PackName) 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 export const workflow = (w: Workflow): Workflow => w
/** brief.ts's `goal` (or a workflow's steps) as a list, in order */ /** 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 */ /** a goal's name: its own, else its kind's */
export const nameOf = (c: Contract) => c.name ?? c.kind 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 } 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 */ /** `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[] } } 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 { export interface FileFacts {
/** as the project names it (relative to its folder) */ /** 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[] }> scene(at?: number[]): Promise<{ rate: number; faces: Faces[]; scenes: Scene[] }>
/** its contact sheet's path */ /** its contact sheet's path */
sheet(): string sheet(): string
/** what was seen of it since its last change, or null */
seen(): Seen | null
} }
export interface Job { export interface Job {
@@ -142,16 +138,6 @@ export function fileFacts(rel: string, root: string, moment: Moment, contract: C
return scenes.get(k)! return scenes.get(k)!
}, },
sheet: () => media.sheet(abs), 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 // 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. // 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 { 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" 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 { FileFacts } from "../facts.ts"
import type { Word } from "../media.ts" import type { Word } from "../media.ts"
import type { TextLine } from "./place.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 */ /** 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 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"]) 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 */ /** a line is a caption when this share of its letters is matched by what's said around it */
export const CAPTION = 0.6 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 */ /** least score a read line counts at */
export const LEAST = 0.6 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] */ /** 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 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 /** 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) */ * 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 * 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 */ * 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[] { export function captionsOf(frames: Frame[], rate: number, heard: Word[]): Shown[] {
heard = asDigits(heard)
const all: (Shown & { caps: boolean })[] = [] const all: (Shown & { caps: boolean })[] = []
frames.forEach((fr, i) => { frames.forEach((fr, i) => {
const t = i / rate 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 // 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 if (fr.lines.filter(([, , , , text, score]) => score >= LEAST && letters(text).length >= 4).length > BUSY) return
for (const [, y, , h, text, score] of fr.lines) { 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 if (score < LEAST || key.length < 4) continue
const mid = (y + h / 2) / Math.max(1, fr.h) 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)) 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 */ /** 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 [] if (!shown.length) return []
const out: Finding[] = [] 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) { 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; ) { for (let i = 0; i < f.bad.length; ) {
if (!f.bad[i]) { i++; continue } if (!f.bad[i]) { i++; continue }
let j = i let j = i
@@ -190,6 +197,17 @@ export function compare(shown: Shown[], heard: Word[]): Finding[] {
const a = dropped[i].k - 1 const a = dropped[i].k - 1
const b = dropped[j - 1].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 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(" ") const words = run.map((w) => w.text).join(" ")
out.push(inside 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` } ? { 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. * 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 */ * 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[] { 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 // 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 // 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) => { const said = heard.filter((w) => {
@@ -234,18 +253,63 @@ export function uncaptioned(shown: Shown[], heard: Word[], textUp: (t: number) =
return out 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>( 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"] }, { 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) => { async (f) => {
if (!f.made || f.kind !== "video") return 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 if (!heard.length) return
const sc = await f.scene() // the render's own texts when its manifest is here: exactly what it drew, where, every frame, and never the footage's
const frames: Frame[] = sc.scenes.map((s) => ({ h: s?.h ?? 1, lines: (s?.texts ?? []) as Read[] })) // own text (12-04, round 26: Elfster's phone recordings read as "HO Nam Grou Too Ur", and its captions, drawn at the
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" }) // top, weren't recognised as captions at all); else the export read frame by frame
const shown = captionsOf(frames, sc.rate || 2, heard) const own = f.manifest ? framesOfManifest(f.manifest) : null
const rate = sc.rate || 2 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) 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 { CutGoal, CutPlan } from "raea/brief.gen"
import type { FileFacts, Job, Manifest } from "../facts.ts" import type { FileFacts, Job, Manifest } from "../facts.ts"
import { has, inOrder, joined, norm, SAY_GAP, saidAt } from "../text.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 export const CTA_WITHIN = 8
/** how much of the CTA a run of words must have, in order */ /** 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 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 cutJob = (j: Job) => (j.contract?.kind === "cut" ? (j.contract.cut ?? null) : null)
const cutFile = (f: FileFacts) => { const cutFile = (f: FileFacts) => {
const c = f.contract?.kind === "cut" ? f.contract.cut : undefined const c = f.contract?.kind === "cut" ? f.contract.cut : undefined
@@ -69,7 +86,8 @@ const cutFile = (f: FileFacts) => {
/** what a cut says and shows */ /** what a cut says and shows */
async function heardOf(f: FileFacts) { 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 spoken = words.map((w) => norm(w.text)).filter(Boolean)
const times = words.filter((w) => norm(w.text)).map((w) => w) const times = words.filter((w) => norm(w.text)).map((w) => w)
return { spoken, times, screen: shown(f.manifest) } 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}` }) 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 text = norm(readFileSync(file, "utf8"))
const unfound = quotes(c).filter(([, from]) => !has(text, norm(from))) 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) => { 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) => { 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) const at = cutFile(f)
if (!at?.c.say?.length) return if (!at?.c.say?.length) return
const { spoken, screen } = await heardOf(f) const { spoken } = await heardOf(f)
const on = (p: string) => saidAt(spoken, p, SAY_GAP) !== null || screen.some(([s]) => onScreen(s, p, SAY_GAP)) 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))) 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(", ")}` }) 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 at = cutFile(f)
const cta = at?.c.cta const cta = at?.c.cta
if (!cta) return if (!cta) return
const { times, screen } = await heardOf(f) const { times } = await heardOf(f)
const within = cta.within ?? CTA_WITHIN const within = cta.within ?? CTA_WITHIN
const end = f.seconds ?? times[times.length - 1]?.end ?? 0 const end = f.seconds ?? times[times.length - 1]?.end ?? 0
const last = times.filter((w) => w.end >= end - within).map((w) => norm(w.text)) 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 heard = lines.map((l) => share(l, last))
const best = Math.max(0, ...heard) const best = Math.max(0, ...heard)
const line = best > 0 ? lines[heard.indexOf(best)] : cta.text 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] }) 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) const once = (c?.say ?? []).filter((p) => p.every === false)
if (!c || !once.length) return if (!c || !once.length) return
const cuts = j.files.filter((f) => cutOf(c, f.path)) 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) { for (const p of once) {
const n = norm(p.text) 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}")` }) 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-")) const dir = mkdtempSync(path.join(os.tmpdir(), "raea-floor-"))
try { try {
const out = path.join(dir, "check.json") 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 }) const run = (verb: string) => spawnSync(RAEA, [verb, ...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)}`) // `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[] return (JSON.parse(readFileSync(out, "utf8")).findings ?? []) as Measured[]
} finally { } finally {
rmSync(dir, { recursive: true, force: true }) 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 }) 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) => { 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 if (!f.made || f.kind !== "video" || bookkeeping(f.path)) return
const m = [`${stem(f.abs)}.render.json`, `${stem(f.abs)}.manifest.json`].find(existsSync) 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) => { 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 { check, found } from "raea/check"
import type { FileFacts } from "../facts.ts" import type { FileFacts } from "../facts.ts"
import { RATE, stem, type Faces } from "../media.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 */ /** 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 export const FACE_MIN = 0.05
@@ -127,7 +128,7 @@ export function smallText(manifest: any): Finding[] {
} }
const out: Finding[] = [] const out: Finding[] = []
for (const [text, { at, px }] of seen) { 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` }) 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)` }) 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 -206
View File
@@ -1,217 +1,15 @@
// The rule packs (MK29, MK38; Rust's goal gates until 11-29, now here alone): any goal held to its rules, // The rules pack: a goal's command rules, each run in the brief's folder within its timeout (300 s by default), run
// 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 // again each time. A goal's `file` rules are deliverables (the deliverables pack holds them). Nothing here asks a model
// stop unless all the goals pass"). // to judge the work (12-04, Shane: "removing ask and judge completely and all that exists is check").
// run the command exits 0 in the brief's folder, within its timeout (300 s by default), run again each time
// says a fresh critic (`raea goal judge`) found it true of the work, after the work's last change
// (file rules are deliverables: the deliverables pack holds them)
// The critic's verdict is review/judge/NAME.json (the goal's name): {at, by, goal, rules: {ID: {pass, why}}}.
import { spawnSync } from "node:child_process"
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"
import path from "node:path"
import { check, found } from "raea/check" import { check, found } from "raea/check"
import { type Contract, nameOf, type Said, saysOf } from "../contract.ts"
import type { Job } from "../facts.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 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) => { 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 if (!r.run) continue
const { ok, said } = await j.run(r.run, r.timeout ?? TIMEOUT) const { ok, said } = await j.run(r.run, r.timeout ?? TIMEOUT)
if (!ok) found({ says: `${r.id}: \`${r.run}\` ${said}`, about: [r.id] }) 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
const v = verdict(j.root, j.contract!)
const changed = newest(j.root)
// at whole seconds, as the verdict keeps its time: work saved in the second the critic was asked counts as judged
const fresh = !!v && (changed === null || v.at >= Math.floor(changed / 1000))
for (const r of says) {
const one = v?.rules?.[r.id]
const fix = `raea goal judge${j.contract?.name ? ` --goal ${j.contract.name}` : ""}`
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): string {
const rules = saysOf(g).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
}
export const BY = ["claude", "kimi", "clef"] as const
/** the critic when none is named: clef where an agent key is set (a raea cloud box, whose shell has no Claude
* sign-in: 12-01, every judging there answered "Not logged in"), else Claude Code */
export const critic = () => (process.env.RAEA_AGENT_KEY && process.env.RAEA_API ? "clef" : "claude")
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
export function clefVerdict(g: Contract, dir: string, ask = askClef): Verdict["rules"] {
const all = made(dir)
const groups = new Map<string, { file: string; from?: string; to?: string; rules: Said[] }>()
const pieces = new Map<string, string[]>()
for (const r of saysOf(g)) {
const named = [...new Set(r.says.match(PIECE) ?? [])].filter((f) => existsSync(path.join(dir, f)))
const files = named.length ? named : all.slice(0, CLEF_PIECES)
const w = /from (\d+(?:\.\d+)?) s to (?:(\d+(?:\.\d+)?) s|its end)/.exec(r.says)
pieces.set(r.id, files)
for (const file of files) {
const key = [file, w?.[1], w?.[2]].join("\u001f")
const at = groups.get(key) ?? { file, from: w?.[1], to: w?.[2], rules: [] }
at.rules.push(r)
groups.set(key, at)
}
}
const got = new Map<string, { pass: boolean; why: string }[]>()
for (const k of groups.values()) {
const answers = ask(dir, k.file, k.rules.map((r) => r.says), k.from, k.to)
k.rules.forEach((r, i) => got.set(r.id, [...(got.get(r.id) ?? []), { pass: answers[i]?.choice === "true" && !answers[i]?.problem, why: `${k.file}: ${answers[i]?.problem ?? answers[i]?.says ?? "no answer"}` }]))
}
const rules: Verdict["rules"] = {}
for (const r of saysOf(g)) {
const a = got.get(r.id) ?? []
const open = a.filter((x) => !x.pass)
rules[r.id] = !pieces.get(r.id)?.length
? { pass: false, why: "clef watches and hears a piece, and this rule names no file on disk while out/ holds no video: name the file in the rule, or judge it --by claude where Claude Code is signed in" }
: { pass: !open.length, why: (open.length ? open : a).map((x) => x.why).join("; ") }
}
return rules
}
type Answer = { choice?: string; says?: string; problem?: string | null }
function askClef(dir: string, file: string, says: string[], from?: string, to?: string): Answer[] {
const r = spawnSync(RAEA, ["ask", file, ...says, "--choose", "true,false", "--json", ...(from ? ["--from", from] : []), ...(to ? ["--to", to] : [])], { cwd: dir, encoding: "utf8", maxBuffer: 1 << 26 })
if (r.error) throw new Error(`couldn't run raea ask: ${r.error.message}`)
const rows = String(r.stdout ?? "").split("\n").flatMap((l) => { try { const o = JSON.parse(l); return o.answer ? [o as Answer] : [] } catch { return [] } })
if (rows.length !== says.length) throw new Error(`raea ask answered ${rows.length} of ${says.length} about ${file}: ${String(r.stderr ?? "").trim().slice(-300) || String(r.stdout ?? "").trim().slice(-300)}`)
return rows
}
/** one fresh critic over a goal's `says` rules (`raea goal judge`): 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 function judge(g: Contract, dir: string, by: string): Verdict {
if (!saysOf(g).length) throw new Error(`goal ${nameOf(g)} has no \`says\` rules; its \`run\` and \`file\` rules are held by raea goal check`)
if (!(BY as readonly string[]).includes(by)) throw new Error(`--by ${by}: the critics are ${BY.join(", ")}`)
const asked = Math.floor(Date.now() / 1000)
if (by === "clef") return keep(g, dir, { at: asked, by, goal: g.aim ?? nameOf(g), rules: clefVerdict(g, dir) })
const p = prompt(g, dir)
const r = by === "claude" ? spawnSync("claude", ["-p", p, "--allowedTools", "Read Grep Glob", "--output-format", "json"], { cwd: dir, encoding: "utf8", maxBuffer: 1 << 26 }) : spawnSync("kimi", ["-p", p], { cwd: dir, encoding: "utf8", maxBuffer: 1 << 26 })
if (r.error) throw new Error(`couldn't run ${by}: ${r.error.message} (is its CLI installed and signed in?)`)
let words = String(r.stdout ?? "")
try {
const o = JSON.parse(words)
if (typeof o.result === "string") words = o.result
} catch {}
const v = lastVerdict(words)
if (!v) throw new Error(`${by} answered no verdict: ${words.slice(-300).trim()}`)
return keep(g, dir, { ...v, at: asked, by, goal: g.aim ?? nameOf(g) })
}
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 type { PackName } from "../contract.ts"
import captions from "./captions.ts" import captions from "./captions.ts"
import { countPack, ctaPack, neverPack, openPack, quotesPack, sayOncePack, sayPack, shapePack } from "./cut.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 frames from "./frames.ts"
import montage from "./montage.ts" import montage from "./montage.ts"
import { runPack, saysPack } from "./goal.ts" import { runPack } from "./goal.ts"
import { criticPack, deliverablesPack, notesPack, recordPack } from "./job.ts" import { deliverablesPack } from "./job.ts"
import { seenPack, surprisePack } from "./look.ts"
import naming from "./naming.ts" import naming from "./naming.ts"
import place from "./place.ts" import place from "./place.ts"
import { playablePack } from "./playable.ts" import { playablePack } from "./playable.ts"
import sizes, { allSizes } from "./sizes.ts" import sizes, { allSizes } from "./sizes.ts"
import sound from "./sound.ts" import sound from "./sound.ts"
import reading from "./reading.ts" import reading from "./reading.ts"
import render from "./render.ts"
import { airgapsPack, hookPack } from "./hook.ts" import { airgapsPack, hookPack } from "./hook.ts"
import voice from "./voice.ts" import voice from "./voice.ts"
import words from "./words.ts" import words from "./words.ts"
@@ -31,8 +31,6 @@ export const PACK_CHECKS: Record<PackName, Check[]> = {
frames: [frames], frames: [frames],
montage: [montage], montage: [montage],
place: [place], place: [place],
seen: [seenPack],
surprise: [surprisePack],
naming: [naming], naming: [naming],
sizes: [sizes, allSizes], sizes: [sizes, allSizes],
quotes: [quotesPack], quotes: [quotesPack],
@@ -43,12 +41,8 @@ export const PACK_CHECKS: Record<PackName, Check[]> = {
cta: [ctaPack], cta: [ctaPack],
shape: [shapePack], shape: [shapePack],
run: [runPack], run: [runPack],
says: [saysPack],
deliverables: [deliverablesPack], deliverables: [deliverablesPack],
critic: [criticPack],
record: [recordPack],
notes: [notesPack],
floor: [floorPack], floor: [floorPack],
stills: [stillsPack],
playable: [playablePack], 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. // The deliverables pack: every file the contract names (its own list, else its kind's: a cut's cuts, a goal's `file`
// deliverables every file the contract names (its own list, else its kind's: a cut's cuts, a goal's `file` rules, a // rules, a kit's GLBs, LODs, thumbnails, lineup and kit.json, a shot's still or move, a scene's three stills).
// 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"
// notes NOTES.md with a "What the skill got wrong" section (scene, kit and shot jobs)
// record every composition the plan names rendered or checked clean since it last changed, and its LODs held
// critic a fresh critic's round newer than the newest deliverable, on the kind's rubric, its blocking
// defects fixed or answered in NOTES.md, and the make questions asked of its sheets
// record and critic read raea's record and the judge's rounds through `raea goal gates --json`.
import { spawnSync } from "node:child_process"
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs"
import path from "node:path" import path from "node:path"
import { check, found } from "raea/check" import { check, found } from "raea/check"
import type { Contract } from "../contract.ts" import type { Contract } from "../contract.ts"
import type { Job } from "../facts.ts" import type { Job } from "../facts.ts"
import { RAEA } from "../media.ts"
import { deliverables as cutFiles } from "./cut.ts" import { deliverables as cutFiles } from "./cut.ts"
import { deliverables as playableFiles } from "./playable.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 /** 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 */ * 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] }) 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 [] } })
}
+1 -1
View File
@@ -17,7 +17,7 @@ import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node
import { tmpdir } from "node:os" import { tmpdir } from "node:os"
import path from "node:path" import path from "node:path"
import { check, found } from "raea/check" import { check, found } from "raea/check"
import type { Beat } from "raea/brief.gen" import type { CutBeat as Beat } from "raea/brief.gen"
import type { FileFacts } from "../facts.ts" import type { FileFacts } from "../facts.ts"
import { type Faces, Unmet } from "../media.ts" import { type Faces, Unmet } from "../media.ts"
import { cutOf } from "./cut.ts" import { cutOf } from "./cut.ts"
+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 { check, found } from "raea/check"
import type { FileFacts } from "../facts.ts" import type { FileFacts } from "../facts.ts"
import { RATE } from "../media.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 */ /** 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) */ /** 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 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 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 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` 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) { 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 // 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 // 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 // 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) // 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` }) 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")) { } 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` }) 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 // 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 // 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 // read"). From the render's own texts when its manifest is here (exactly what it drew, five times a second, no farm
// caption (captions are read while they're heard: the captions pack holds them) is timed against the words it holds. // 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 // 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, // 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 { check, found } from "raea/check"
import type { FileFacts } from "../facts.ts" import type { FileFacts } from "../facts.ts"
import type { Word } from "../media.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 Block = { text: string; words: number; from: number; to: number; size?: number }
export type Finding = { level: "error" | "warn"; at: number; says: string; block: Block } 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 up = b.to - b.from
const n = need(b.words) const n = need(b.words)
if (up >= n) continue 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)` 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` }) 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: `"${quote}" at ${b.from.toFixed(1)} s: ${load}. Hold it ${(n - up).toFixed(1)} s longer, or say it in fewer words` }) 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 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>( 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"] }, { 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) => { async (f) => {
if (!f.made || f.kind !== "video") return if (!f.made || f.kind !== "video") return
const sc = await f.scene() // the render's own texts when its manifest is here (no farm call, and never the footage's own text), else the export
const frames: Frame[] = sc.scenes.map((s) => ({ h: s?.h ?? 1, lines: (s?.texts ?? []) as Read[] })) // 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 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 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))) 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 }) 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 * 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 * 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). */ * 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) const named = sizeOf(f.path)
if (named) return named if (named) return named
if (f.kind !== "video" || !f.width || !f.height) return null 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 const FLOOR_Q = 0.1
/** how far either side of a cut point a gap is looked for (s) */ /** how far either side of a cut point a gap is looked for (s) */
const NEAR = 0.4 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 */ /** lines this far apart (dB) are an error, a warning */
const LEVEL_ERROR = 6 const LEVEL_ERROR = 6
const LEVEL_WARN = 4 const LEVEL_WARN = 4
@@ -102,6 +104,9 @@ export function nearestGap(l: Levels, t: number, ref: number, words: Word[], ins
return null 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 /** 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) */ * to about 30 ms) */
const SEAM = 0.03 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` }) 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 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 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 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 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) 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)) { 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) 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 return out
@@ -217,7 +227,10 @@ export async function soundOf(f: FileFacts): Promise<{ findings: Finding[]; voic
const words = await f.takeWords(file) const words = await f.takeWords(file)
const l = f.levels(c.at - NEAR - 0.1, c.at + dur + NEAR + 0.1, file) const l = f.levels(c.at - NEAR - 0.1, c.at + dur + NEAR + 0.1, file)
out.push(...editPoints(c, fps, words, l)) 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 { } else {
const l = f.levels(c.at, c.at + Math.min(dur, kind === "sfx" ? 2 : 20), file) 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) 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 { check, found } from "raea/check"
import type { FileFacts } from "../facts.ts" import type { FileFacts } from "../facts.ts"
import type { Word } from "../media.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 } 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 const under = typical - d
if (under < QUIET_WARN || l.length < 2) continue if (under < QUIET_WARN || l.length < 2) continue
const text = l.map((w) => w.text).join(" ") 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) 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"). // 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. // With no lines beside it, only the fades and the edges are held.
import { existsSync, readFileSync } from "node:fs" import { existsSync, readFileSync } from "node:fs"
import path from "node:path"
import { check, found } from "raea/check" import { check, found } from "raea/check"
import type { FileFacts } from "../facts.ts" import type { FileFacts } from "../facts.ts"
import { stem, type Word } from "../media.ts" import { stem, type Word } from "../media.ts"
@@ -130,6 +129,5 @@ export default check<FileFacts>(
const l = f.levels() const l = f.levels()
const out = [...(lines ? compare(readFileSync(lines, "utf8"), heard) : []), ...fades(l.db, heard, f.seconds ?? heard[heard.length - 1].end)] 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 }) 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 // `raea check` (docs/check.feature): the one check. Every rule each goal of brief.ts holds at one of four moments, on
// 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 // 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
// several in order (a workflow): each is checked alone, and the report says each one's verdict and the whole's. // 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 // 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 // `goal`, and with none, the floor. The files are the ones named, else (publish, done) every deliverable and
// files are the ones named, else (publish, done) every deliverable and every video or still made under out/. // every video or still made under out/. Each check whose moments include --at (done by default) runs: a file
// Each check whose moments include --at (done by default) runs: a file check on each file, a job check once. // check on each file, a job check once. A file's check after its render is kept beside it (FILE.check.json) and
// Every project is also held to `registered` (every raea file reached from brief.ts). Writes review/goal.json // publish and done read it while it's fresh, never running it again. One line a rule a file. Writes
// (and FILE.check.json beside each file named) and prints each finding. Exit 1 on an error, 2 when it can't run // review/goal.json and prints each finding. Exit 1 on an error, 2 when it can't run (brief.ts doesn't load). A
// (brief.ts doesn't load). A check that needs what this machine hasn't (a scene reader, a transcriber) waits, and // check that needs what this machine hasn't (a transcriber) waits, and says what for; it holds nothing.
// 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 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] [--by claude|kimi|clef] a fresh critic over a goal's `says` rules (review/judge/)
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs" import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"
import path from "node:path" import path from "node:path"
import { pathToFileURL } from "node:url" import { pathToFileURL } from "node:url"
import { type Check, type Finding, type Moment, MOMENTS, runOnce, type Threw } from "raea/check" 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 { fileFacts, type FileFacts, type Job, kindOf, runIn } from "./facts.ts"
import * as media from "./media.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 { loadProject, type Project } from "./project.ts"
import { critic, judge } from "./packs/goal.ts"
import { PACK_CHECKS } from "./packs/index.ts" import { PACK_CHECKS } from "./packs/index.ts"
import { second } from "./packs/look.ts"
import { deliverablesOf } from "./packs/job.ts" import { deliverablesOf } from "./packs/job.ts"
import { bookkeeping } from "./packs/naming.ts" import { bookkeeping } from "./packs/naming.ts"
import { placeReport } from "./packs/place.ts" import { placeReport } from "./packs/place.ts"
import { tasksMain } from "./tasks.ts" import { tasksMain } from "./tasks.ts"
import { wellFormed } from "./text.ts"
/** the checks every project is held to once, whatever its goals */ /** the checks every project is held to once, whatever its goals: none in the loop (12-04: `registered`, how brief.ts
const ALWAYS: Check[] = [registeredPack, tastePack] * 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 } 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 */ /** 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[] } 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] const out = [...doctor]
for (const c of goals) { for (const c of goals) {
const at = goals.length > 1 ? `${nameOf(c)}: ` : "" 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`) 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 return out
} }
@@ -162,9 +204,16 @@ export async function goalCheck(o: { files?: string[]; at?: Moment; goal?: strin
const before = findings.length const before = findings.length
const brokeBefore = broke.length const brokeBefore = broke.length
const j = job(contract, deliverables, files) 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) { for (const c of checks) {
if (c.over === "job") keep(contract ? name : null, null, await runOnce([{ check: c, on: j }])) 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 mine = findings.slice(before)
const errors = mine.filter((x) => x.level === "error").length 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) }) 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)) 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 const errors = findings.filter((x) => x.level === "error").length
return { return {
object: "goal.check", 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`) writeFileSync(path.join(dir, "goal.json"), `${JSON.stringify(r, null, 1)}\n`)
for (const f of named) { for (const f of named) {
const mine = r.findings.filter((x) => x.file === f) 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}`) 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`) 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(", ") 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") 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 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 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] [--by claude|kimi|clef]
raea make place FILE [--at S[,S...]] [--box WxH]` raea make place FILE [--at S[,S...]] [--box WxH]`
export async function main(argv: string[]): Promise<number> { export async function main(argv: string[]): Promise<number> {
@@ -238,7 +286,7 @@ export async function main(argv: string[]): Promise<number> {
if (verb === "check") { if (verb === "check") {
const at = (flag(a, "--at") ?? "done") as Moment const at = (flag(a, "--at") ?? "done") as Moment
if (!MOMENTS.includes(at)) { 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 return 2
} }
const files = positional(a, ["--at", "--only", "--manifest", "--goal"]) const files = positional(a, ["--at", "--only", "--manifest", "--goal"])
@@ -246,7 +294,7 @@ export async function main(argv: string[]): Promise<number> {
try { try {
r = await goalCheck({ files, at, goal: flag(a, "--goal"), only: flag(a, "--only")?.split(",").filter(Boolean), manifest: flag(a, "--manifest") }) r = await goalCheck({ files, at, goal: flag(a, "--goal"), only: flag(a, "--only")?.split(",").filter(Boolean), manifest: flag(a, "--manifest") })
} catch (e) { } catch (e) {
console.error(`raea goal check: ${(e as Error).message}`) console.error(`raea check: ${(e as Error).message}`)
return 2 return 2
} }
writeReport(r, r.files.filter((f) => files.some((n) => path.resolve(n) === path.join(r.root, f)))) 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 return r.passed ? 0 : 1
} }
if (verb === "tasks") return tasksMain(a) 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 the critic is clef), a second opinion on the whole cut with its sound: never the look itself
const op = full.length && critic() === "clef" ? second(path.resolve(file)) : null
if (op) console.log(`a second opinion (clef watched and heard all of it and answered a list of checks; a FOUND is a fix or a reason it's wrong; how it looks is still yours to judge, on the frames):\n${op}`)
console.log(`${sheet}\n${full.join("\n")}\nlook at every frame of the sheet for what happens, and open each full-size frame for how it looks (type, captions, cards, the end: beside a reference ad's frame, not from the sheet), then: raea goal seen ${file} "what you see and would change"${full.length ? ' --look "its design at full size, beside a reference, and what you changed"' : ""}`)
return 0
}
const abs = path.resolve(file)
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") { if (verb === "place") {
const file = positional(a, ["--at", "--box", "-o"])[0] const file = positional(a, ["--at", "--box", "-o"])[0]
if (!file || !existsSync(file)) return usage() 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)) if (o) writeFileSync(o, JSON.stringify(rep, null, 1))
return 0 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 = judge(said[0], root, flag(a, "--by") ?? critic())
for (const [id, r] of Object.entries(v.rules)) console.log(`${r?.pass ? "ok " : "open"} ${id}: ${r?.why ?? ""}`)
return 0
}
return usage() return usage()
} }
+15
View File
@@ -64,3 +64,18 @@ export function inOrder(want: string[], got: string[]): number {
} }
return row[got.length] / want.length return row[got.length] / want.length
} }
// A finding's quoted text, safe to print. 12-05, Dutch run 9: a caption's text cut at 40 UTF-16 units split an emoji, the
// report held half of it, and printing it broke the check ("Conversion from string failed: invalid utf-8 sequence").
/** a lone half of a surrogate pair: no character, and nothing UTF-8 can hold */
const LONE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g
/** `s` with any half character replaced by U+FFFD */
export const wellFormed = (s: string): string => s.replace(LONE, "�")
/** `s` cut to at most `n` characters (whole code points, never half an emoji), with "..." when it was longer */
export function quote(s: string, n: number): string {
const cs = Array.from(s)
return cs.length > n ? `${cs.slice(0, n).join("")}...` : s
}
+19
View File
@@ -93,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 // a cut with hardly any talking needs none
expect(uncaptioned([], said.slice(0, 4))).toEqual([]) 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 { goalCheck } from "../src/run.ts"
import { project } from "./project.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" } })) 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) 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)
expect(on).not.toContain("surprise") 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: { surprise: true, place: false } }))).toContain("surprise") 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(cut({ cut: { brief: "b.txt" }, packs: { place: false } }))).not.toContain("place")
expect(packsOf(rules({ aim: "x" }))).toEqual(["deliverables", "stills"]) 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", "stills", "run", "says"]) 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") expect(packsOf(cut({ cut: { brief: "b.txt" }, rules: [{ id: "t", run: "true" }] }))).toContain("run")
// no contract: the floor every made video is held to // 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 () => { 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 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> = {}) => ({ const contract = (cut: Record<string, unknown> = {}) => ({
kind: "cut", 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: { cut: {
brief: "media/brief.txt", brief: "media/brief.txt",
count: { value: 2, from: "10 total videos" }, 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`) put(d2, "media/brief.txt", `${BRIEF}"See a vet today at Dutch.com."\n`)
expect(of(await run(d2), "quotes")).toHaveLength(1) 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)
})
+20 -1
View File
@@ -3,7 +3,7 @@ import { expect, test } from "bun:test"
import { mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs" import { mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os" import { tmpdir } from "node:os"
import path from "node:path" import path from "node:path"
import { 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" 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", () => { 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) expect(runs).toBe(3)
rmSync(d, { recursive: true, force: true }) 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 -56
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; // 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. // any goal carries rules.
import { expect, test } from "bun:test" 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, lastVerdict, newest } from "../src/packs/goal.ts"
import { goalCheck } from "../src/run.ts" import { goalCheck } from "../src/run.ts"
import { project, put } from "./project.ts" import { project, put } from "./project.ts"
const goal = (rules: unknown[]) => ({ kind: "rules", aim: "tests pass", rules }) const goal = (rules: unknown[]) => ({ kind: "rules", aim: "tests pass", rules })
const VERDICT = "review/judge/rules.json"
test("a command passes or says why", async () => { test("a command passes or says why", async () => {
const d = project(goal([{ id: "ok", run: "true" }, { id: "bad", run: "echo broke; exit 3" }])) const d = project(goal([{ id: "ok", run: "true" }, { id: "bad", run: "echo broke; exit 3" }]))
@@ -26,23 +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") 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")
expect((await says())[0].fix).toBe("raea goal judge")
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("file rules are deliverables", async () => { test("file rules are deliverables", async () => {
const d = project(goal([{ id: "export", file: "out/final.txt" }])) 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"]]) expect((await goalCheck({ cwd: d })).findings.map((x) => [x.check, x.says])).toEqual([["deliverables", "missing: out/final.txt"]])
@@ -50,12 +28,6 @@ test("file rules are deliverables", async () => {
expect((await goalCheck({ cwd: d })).passed).toBe(true) 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 () => { test("a check runs only at its moments", async () => {
const d = project(goal([{ id: "bad", run: "exit 1" }])) const d = project(goal([{ id: "bad", run: "exit 1" }]))
// run rules hold at done, not at an edit // run rules hold at done, not at an edit
@@ -63,32 +35,9 @@ test("a check runs only at its moments", async () => {
expect((await goalCheck({ cwd: d, at: "done" })).checks).toContain("run") 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", () => { test("a `says` rule is said to be unchecked: nothing judges the work (docs/check.feature CK4)", async () => {
const d = mkdtempSync(path.join(tmpdir(), "raea-goal-clef-")) const d = project(goal([{ id: "friendly", says: "the reply is friendly" }]))
mkdirSync(path.join(d, "out/cuts"), { recursive: true }) const r = await goalCheck({ cwd: d })
for (const f of ["out/cuts/a_9x16.mp4", "out/cuts/b_9x16.mp4"]) writeFileSync(path.join(d, f), "x") expect(r.plan.some((p) => p.includes("rules.friendly") && p.includes("isn't checked"))).toBe(true)
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 expect(r.checks).not.toContain("says")
const asked: string[] = []
const rules = clefVerdict(g, d, (_dir, file, says, from, to) => {
asked.push(`${file} ${from ?? ""}-${to ?? ""} ${says.length}`)
return says.map((q) => ({ choice: q.includes("caption") && file.includes("b_") ? "false" : "true", says: "said" }))
})
expect(asked.sort()).toEqual(["out/cuts/a_9x16.mp4 - 1", "out/cuts/a_9x16.mp4 0-3 1", "out/cuts/b_9x16.mp4 - 1"])
expect(rules.named?.pass).toBe(true)
expect(rules.all?.pass).toBe(false)
expect(rules.all?.why).toBe("out/cuts/b_9x16.mp4: said")
const empty = mkdtempSync(path.join(tmpdir(), "raea-goal-clef-"))
expect(clefVerdict(g, empty, () => []).all?.why).toContain("names no file on disk")
})
test("a reading kept beside a file isn't the work changing", () => {
const d = mkdtempSync(path.join(tmpdir(), "raea-newest-"))
mkdirSync(path.join(d, "out/cuts"), { recursive: true })
const cut = path.join(d, "out/cuts/a_b_c_v1_9x16.mp4")
writeFileSync(cut, "x")
utimesSync(cut, 1000, 1000)
for (const ext of ["words.json", "scene.json", "check.json", "floor.json", "montage.json"]) writeFileSync(path.join(d, `out/cuts/a_b_c_v1_9x16.${ext}`), "{}")
expect(newest(d)).toBe(1_000_000)
writeFileSync(path.join(d, "out/cuts/a_b_c_v1_9x16.render.json"), "{}")
expect(newest(d)!).toBeGreaterThan(1_000_000)
}) })
-40
View File
@@ -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 { mkdtempSync } from "node:fs"
import { tmpdir } from "node:os" import { tmpdir } from "node:os"
import path from "node:path" import path from "node:path"
import type { Beat } from "raea/brief.gen" import type { CutBeat as Beat } from "raea/brief.gen"
import { saysOf } from "../src/contract.ts"
import { acrossCuts, cutsOf, pace, read, tau } from "../src/packs/montage.ts" import { acrossCuts, cutsOf, pace, read, tau } from "../src/packs/montage.ts"
const W = 96 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(flat[0]).toMatchObject({ kind: "tempo" })
expect(tau([3, 2, 1])).toBe(-1) 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 // 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) 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.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/) assert.match(c[0].says, /“He hurt his little” covers a dog/)
const top = Number(/top (\d+) px/.exec(c[0].says)?.[1]) const top = Number(/top (\d+) px/.exec(c[0].says)?.[1])
assert.ok(top >= 1380, `moved below the dog, not ${top}`) 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 // 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) 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 })) 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([]) 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) const onSound = editPoints(clip(1.01, 1.0), fps, words, take)
assert.equal(onSound[0]?.kind, "edit-on-sound", JSON.stringify(onSound)) assert.equal(onSound[0]?.kind, "edit-on-sound", JSON.stringify(onSound))
assert.match(onSound[0].says, /first sound/) 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") 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 // "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 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[] = [] 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.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/) 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 { readFileSync, writeFileSync } from "node:fs"
import path from "node:path" import path from "node:path"
import { applyTasks, putTasks, tasksOf } from "../src/tasks.ts" import { applyTasks, putTasks, tasksOf } from "../src/tasks.ts"
import { goalCheck } from "../src/run.ts"
import { project, put } from "./project.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 () => { 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(r).toMatchObject({ put: true, written: ["brief.ts"] })
expect(readFileSync(path.join(d, "brief.ts"), "utf8")).toContain('keyword: "DONE"') 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)
})
+3 -2
View File
@@ -20,7 +20,8 @@ Run `raea context PROJECT` before anything else and read all of it. It prints, i
every project. A line there beats any guide. every project. A line there beats any guide.
2. **The brief** (`brief.ts`): who it's for (`audience`), the one thing they should think afterwards (`believe`), 2. **The brief** (`brief.ts`): who it's for (`audience`), the one thing they should think afterwards (`believe`),
what kind of piece it is (`mode`), the narrator and tone (`voice`), what it delivers, the tasks and the agents. what kind of piece it is (`mode`), the narrator and tone (`voice`), what it delivers, the tasks and the agents.
Deliverables can have their own briefs, with a storyboard (`NAME.script.ts`) and a direction. Deliverables can have their own briefs, with a storyboard (`NAME.script.ts`) and a direction. To write one,
`raea guide brief` has its types, a cut goal's contract and an example.
3. **The look** (the brief's `look`, and `brand/brand.css` when there is one): the project's committed world. 3. **The look** (the brief's `look`, and `brand/brand.css` when there is one): the project's committed world.
4. **The floor**: what breaks a piece, read again right before every edit. 4. **The floor**: what breaks a piece, read again right before every edit.
5. **One guide per mode**: what that kind of piece has to do. 5. **One guide per mode**: what that kind of piece has to do.
@@ -111,7 +112,7 @@ names. A note with three asks is three moves, not one:
- **extract:** a brand kit read from finished work; - **extract:** a brand kit read from finished work;
- **generate:** variants of one element to pick from; - **generate:** variants of one element to pick from;
- **polish:** close out the latest critique; - **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 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. 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 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 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 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. and the Stop hook won't let you end before it says done.
## What to do ## 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 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), 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`. `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 7. **Review.** `raea render shared/components/KIT/lineup.tsx --review review/rN`, and look at every tile yourself:
`raea judge review/rN --kind kit --by claude --brief brief.ts --json`. The kit rubric: cohesion, reference the pieces belong together, match their references and the brief, hold their form in clay, and stand at their real
fidelity, the brief, mesh (clay), texture, assembly (clay), scale (clay), labels. Fix its blocking defects or size. Fix every ERROR the render's check names; keep a list of what you'd still change.
answer them in NOTES.md, and keep going until `raea goal check` passes.
Cost: a six-piece kit is about $8-10 (references about $0.25 each, Tripo H3.1 and Meshy about $0.60-0.80 each). 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. `--dry` on refs and gen says the price first; ask before going over $10.
+27 -89
View File
@@ -1,29 +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. There are two texts to copy and fill: a brief template and a builder prompt. `bevy/scenes` says why each step
`bevy/scenes` says why each step exists. This page gives the words. exists. This page gives the words.
Who plays which role: You are the builder. What the scene must hold is checked by raea as each render ends: a part floating, sinking or
- **In Claude Code:** the session is the builder. The judge is a new subagent every round, plus `raea judge` (clef-omni) passing through another, a part out of place or under its planned detail, light that jumps or boils. Those are
for the numbers. faults, each with its fix (`raea check`). How it should look is the brief's, the target's and this page's, read while
- **In the raea app's feed:** Kimi is the builder and `raea judge` is the judge. you build; nothing grades it after (raea docs/check.feature).
Either way, the judge sees only pictures and the brief's words, never the code or the builder's notes. Code decides
the pass, and the builder never sees the pass line. A figure the builder can read becomes a target to game.
Where these texts come from: the published Blender + Claude workflows. 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. - 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. - Muska and KOBATAKA: plan before code; route each object.
- ProfRino and AnyScene: placement is measured; pass is decided in code. - ProfRino and AnyScene: placement is measured; pass is decided in code.
- hayashimon: coarse to fine; one shared wear recipe. - 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 ## What to do
1. Write the brief from the template (section 1). Write a `NAME.parts.ts` for every hero object. 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. 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 3. After every stage and every fix, run step R: the review sheets, looked at by you, and the render's own check.
and `raea judge` on the same sheets.
## 1. The brief template ## 1. The brief template
@@ -44,8 +40,8 @@ export default brief({
references: [ references: [
// the TARGET: a real in-engine screenshot of this scene from the hero camera // the TARGET: a real in-engine screenshot of this scene from the hero camera
{ /* media/ref/target.png, role: target */ }, { /* media/ref/target.png, role: target */ },
// real photos, for the judge only; they never ship // real photos, to compare against; they never ship
{ /* media/ref/real-*.jpg, role: judge-only */ }, { /* media/ref/real-*.jpg, role: compare-only */ },
], ],
notDoing: [ notDoing: [
// the do-not-add list: without it the builder adds rain, neon and UI // the do-not-add list: without it the builder adds rain, neon and UI
@@ -61,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: "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: "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: "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)]" },
], ],
}); });
``` ```
@@ -72,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 > 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. > 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 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
against: to:
```ts ```ts
import { parts } from "raea/brief"; import { parts } from "raea/brief";
@@ -144,92 +140,34 @@ STEP R: REVIEW (after every stage, and after every fix)
the same cameras every round. 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 - 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. 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> --by kimi` (or `--by claude`; plain `raea judge` is clef-omni, cheap but advice only - Read the render's check (`raea render` prints it as it ends; `raea check out/scene.mp4` reads it back): fix every
until calibrated). Each is a new session that sees only the sheets. In Claude Code you can also hand the sheets to a ERROR. A warning is a note for the person. Change one material per round; every fix is code in the scene.
NEW subagent with the judge prompt. Give it only the
brief's words, the target, the real photos, this round's sheets, and last round's sheets and verdict. Never give it
your code, your log or your list.
- Fix every blocking defect named, or write in review/log.md why it is wrong and what you checked. A judge can be
wrong: a shadow read as a hole. Change one material per round. Every fix is code in the scene.
- Re-run the stage's checks after every fix. A fix that breaks a check is not done. - Re-run the stage's checks after every fix. A fix that breaks a check is not done.
STOPPING (the loop decides, not you) STOPPING
- Done: `raea judge` prints "done" (two passes in a row), and the last fresh judge named no blocking defect. - Done: the render's check has no ERROR, and your own list for the round names nothing blocking.
- Stall: the score hasn't risen a full point in 2 rounds, or the same defect is named twice. Stop tweaking and change - Stall: the same problem on your list twice. Stop tweaking and change the approach for that part: another route
the approach for that part: another route (solid, sdf, Tripo HD, Tripo Smart Mesh), a rebuilt light plan, a moved (solid, sdf, Tripo HD, Tripo Smart Mesh), a rebuilt light plan, a moved camera. A defect that comes back after two
camera. A defect that comes back after two fixes is the method's fault, not the dose's. 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: 4 review rounds per scene. At the cap, deliver and list what is still wrong.
- Cap: 8 judge rounds per scene. At the cap, deliver and list what is still wrong.
RULES RULES
- One builder at a time on coupled systems (light, exposure, materials). Generation may run in parallel. - 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. - 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. - 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. - Quote every paid step first, and never spend past the brief's cap.
- Keep review/NOTES.md: one line per thing that cost time. - 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 ## Why
- A picture first and a do-not-add list keep the builder from inventing a scene nobody asked for. - 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. - Faults are measured by raea as each render ends, the same way every time, so a fix is known to have worked.
- Numbers and named defects, with the pass decided in code, stop "looks great" from ending a loop early. - The same cameras every round, in colour and clay, show what changed and hide nothing.
## Common mistakes ## 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. - 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. - Fixing three things in one round. When it changes, 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. - 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 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, 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. hayashimon, KOBATAKA), each step on a raea verb.
## What to do ## 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`. `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 - 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` 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 (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"`). 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 - `raea check` decides in code whether you're done: the deliverables on disk, and no ERROR in their renders' checks.
rounds, the make questions, NOTES.md. The Stop hook runs it at the end of every turn (`--at done`), and you can't The Stop hook reads it at the end of a turn (`--at done`) and holds you once for what's still failing. Each
stop while it fails (the loop gives way at the 8-round cap, on a stall, or when the same thing is failing three finding says what to change; review/goal.json holds them all.
turns running). Each finding says what to change; review/goal.json holds them all.
- `raea make blockout` is the stop before anything costs money: `review/plan/floor-plan.png` (every footprint, invented - `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 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. 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 `<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 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. `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. 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 - 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. 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. - Wear.
- Printed matter. - Printed matter.
- Motion. - 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 - 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 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`. 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 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 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 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 - 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 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. camera lurching mid-move, and an empty frame.
### R. Review after every stage and every fix ### 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. `--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 - 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". 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 - Read the render's check and fix every ERROR in it. A warning is a note for the person.
you checked.
- Change one thing per material per round. Re-run the stage's checks after every fix. - 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): 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
1. **Measured checks always gate:** `raea scene lint` (floats and sinks at the feet, clips with the move that clears generated model, `raea scene stage --clearance 0.45` on a moving camera, the render's own end checks (a part out of
them, faces z-fighting in one plane), `raea gen check` on every generated model, `raea scene stage --clearance 0.45` on place or under its planned detail, light that jumps or boils), and the deliverables' counts. How it should look is
a moving camera, and the deliverables' counts. this guide's, the brief's and the target's, read while you build: nothing grades it after.
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 --by claude --brief brief.ts --target
media/ref/target.png --json` (or clef, kimi) scores the kind's rubric (scene: layout, props, signage, materials,
light, atmosphere, plausibility, composition; layout and props judged on clay), on a production bar: don't
nitpick, at most five fixes. It sees the sheets and the brief's words only, never the code or your log. Code
decides the pass; the thresholds aren't in the prompt. A round judged on another kind's rubric doesn't count.
Fix every blocking defect it names, or answer it in NOTES.md (its words, then what you checked). Its score gates
once `raea judge calibrate --kind scene` agrees with Shane's eye (`raea judge eye`).
### Stopping ### Stopping
`raea goal check` says it; you don't decide it. - **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
- **Done:** every deliverable on disk, every gate clear, and two fresh critic passes in a row on the latest renders. (solid, field, Tripo HD, Meshy), a rebuilt light plan, or a moved camera. A defect that comes back after two fixes
- **Stall:** three rounds without beating the best score, or the same defect named twice. Stop tweaking and change belongs to the method, not the dose.
the approach for that part: another route (solid, field, Tripo HD, Meshy), a rebuilt light plan, or a moved camera. - **Cap:** 4 review rounds a job. At the cap or a stall, deliver and say what's still wrong.
A defect that comes back after two fixes belongs to the method, not the dose.
- **Cap:** 8 critic rounds a job. At the cap or a stall the job is delivered short: status lists what's still
missing, and the Stop hook lets you end with it said.
## Why ## Why
- Fixed cameras and a clay pass are what every strong source judges on. Colour hides bad form, and a moving camera - Fixed cameras and a clay pass are what every strong source judges on. Colour hides bad form, and a moving camera
hides regressions. 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 - 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. 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, 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 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 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. before it says done.
## What to do ## What to do
@@ -43,8 +43,7 @@ before it says done.
(`review/lens-SHOT.png`). Pick from it and set the shot's `lens`. (`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`, 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 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 a wall.
judge it (`raea judge review --kind shot --by claude`: framing, move, focus, clearance, continuity, grade).
5. **Clearance.** `raea scene stage SHOT.tsx --clearance 0.45` holds the camera 0.45 m (a carried camera) off every solid part on every frame 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. (`--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, 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 - **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, 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 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 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%
should go is a design choice. 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 - **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. (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 - **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; - `cta`: the exact line every cut ends on;
- `open`: each [TO CONFIRM], gap or contradiction in it, as a question for the review. - `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 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): 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 its shape, size and name; what it says, heard after its last change, for each `say`, `never` and the CTA; a word
against CUT.lines.txt beside it; its edit points, line levels and effects; its faces, text sizes and text placement; clipped or missing; a face cut by the frame's edge; text over a face, a sign or the app's buttons; captions over
and that you looked at it since its last render: its contact sheet for what happens, and its frames at full size talking. Every render ends with that check (`raea check CUT --at render`), kept beside the cut; the job isn't done,
(CUT.looks/) for how it looks, since a sheet's tiles are too small to judge type, captions and cards on (`raea goal 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
seen CUT`, then `raea goal seen CUT "..." --look "its design beside a reference, and what you changed"`). Every render ends with `raea goal check CUT --at render`; the job isn't done, and the Stop hook won't let
you end, until `--at done` passes and every `open` item has the person's answer, written in with who gave it. Turn a
pack off on the contract (`packs: { place: false }`) only when the brief says so. pack off on the contract (`packs: { place: false }`) only when the brief says so.
## The decisions ## The decisions
+112
View File
@@ -0,0 +1,112 @@
# brief.ts: the brief as code
A project's brief.ts is a module whose default export is `brief({...})` from `raea/brief`. raea runs it, `raea goal
check` holds the work to its `goal`, and tsc checks it against the same types raea reads. Everything you need to write
one is on this page, so you don't need to open the SDK.
## The shape
```ts
import { brief, cut, rules } from "raea/brief"
export default brief({
title: string, // the project as people name it
for?: string, // the client or person it's for
audience?: string, // who watches, and where
believe?: string, // the one thing they should think afterwards
voice?: string, look?: string, sound?: string,
notDoing?: string[], // the anti-goals
assumed?: string[], // facts you wrote that the person hasn't confirmed, by key ("audience")
sections?: { heading: string, text: string }[],
goal?: Goal | Goal[], // what the work is held to: cut(), rules(), scene(), kit(), shot(), playable()
plan?: PlanFile, // tasks (raea/task plan()), inline or imported
})
```
A goal made with `cut({...})` or `rules({...})` takes these fields:
| Field | What it is |
| --- | --- |
| `aim` | what the goal is, in the person's words |
| `rules` | `{ id, run?, timeout?, file? }[]`: what must hold before you stop (below) |
| `cut` | a cut job's contract, the brief as rules (below) |
| `deliverables` | files that must exist when it's done, relative to brief.ts (a cut goal lists its own) |
| `previews` | what it shows but never delivers (`review/` and `previews/` when left out) |
| `checks` | the project's own `check()`s from raea/check, imported into brief.ts |
| `name`, `after`, `step` | for several goals in order: a goal's name, the goals before it, its workflow step |
## A cut job's contract (`cut: {...}`)
Every `from` is the brief's own words, copied from its text file as they are, so a person can find the line the
rule came from. raea refuses a `from` it can't find.
| Field | Type | What it holds |
| --- | --- | --- |
| `brief` | `string` | the brief as text, relative to brief.ts (`pdftotext -layout brief.pdf brief_docs/brief.txt`) |
| `count` | `{ value: number, from }` | how many cuts the brief asks for. Fewer planned stays open until a person answers an `open` item about `"count"` |
| `seconds` | `[least, most]` | a cut's length when the cut doesn't give its own |
| `formats` | `string[]` | `"9:16"`, `"16:9"`, `"1:1"`, `"4:5"`: every cut's formats when the cut doesn't give its own |
| `cuts` | `CutPlan[]` | one per cut: `{ id, angle?, kind?, hook?, text?, formats?, seconds?, beats? }` |
| `say` | `{ text, from, every? }[]` | what is said or shown in every cut (`every: false`: one cut is enough) |
| `never` | `{ text, from }[]` | what no cut says or shows: a banned claim, a word, a name |
| `cta` | `{ text, from, also?, within? }` | the line every cut ends on, heard or shown in its last `within` seconds (8 by default); `also` lists other lines the brief rotates |
| `open` | `{ question, from, about?, answer?, by? }[]` | the brief's open items (TBD, to confirm). Each holds the job open until a person's answer is written in, with who gave it |
| `frames` | `boolean` | every face whole and every text big enough, in every frame (true by default) |
A cut's `id` is `[a-z0-9_]` and unique. Each format lands as `out/cuts/<id>_<format with x>.mp4`, for example
`out/cuts/a1_s1_9x16.mp4`. `text` is `"captions"`, `"hook"` or `"none"`. `kind` is `"solo"` or `"mashup"`. `hook` is
one of the brief's hook types, as the brief names it.
A cut's `beats` are optional and yours, never the brief's: plan them in your own notes, not in brief.ts, unless the
brief itself sets the cut's pace. When it does, `{ at, asl?, tempo? }[]` (`asl` the beat's average shot length in
seconds, `tempo` `"build"`, `"release"` or `"hold"`) is measured by the montage check, which the brief switches on.
## Rules
| Kind | Example | How it's checked |
| --- | --- | --- |
| `run` | `{ id: "tests", run: "bun test" }` | the command must exit 0 in brief.ts's folder (300 s unless `timeout` says otherwise) |
| `file` | `{ id: "sheet", file: "review/sheet.png" }` | the file must exist (`a\|b`: either one; `dir/`: three or more pictures in it) |
Nothing else is a rule: a sentence that must be true of the work ("the wordmark is on screen at the end") is how you
build it, not something a model grades after (raea docs/check.feature). Where it can be measured, make it a `run`
rule or a `file`; otherwise leave it to the person's review.
## An example
```ts
// brief.ts
import { brief, cut } from "raea/brief"
export default brief({
title: "Juniper Tea · street interviews, round 1",
for: "Juniper Tea",
audience: "TikTok and Reels, 25-40, already buying loose-leaf",
believe: "Juniper tastes like the tea shop, at home",
goal: cut({
aim: "Ten 9:16 cuts from the street interviews, each ending on the free-trial line",
cut: {
brief: "brief_docs/brief.txt",
count: { value: 10, from: "10 unique cuts total" },
seconds: [20, 40],
formats: ["9:16"],
cuts: [
{ id: "a1_s1", angle: "Angle 1", kind: "solo", hook: "Direct Problem", text: "captions" },
{ id: "a1_s2", angle: "Angle 1", kind: "mashup", hook: "Reaction", text: "captions" },
],
say: [{ text: "free shipping over $35", from: "Mention: free shipping over $35", every: false }],
never: [{ text: "cures", from: "Never claim the tea cures or treats anything" }],
cta: { text: "Try Juniper free for 30 days", from: "CTA: \"Try Juniper free for 30 days\"" },
open: [
{
question: "The footage holds 4 usable interviews, not 10: deliver 4 this round?",
from: "10 unique cuts total", about: "count",
// left out until the person answers; then their words and who gave them
answer: "Yes, 4 now and the rest after the reshoot", by: "the client's producer",
},
],
},
}),
})
```
Write it, then run `raea check`. It names each rule that doesn't hold and the line of the brief it came from.
+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 - 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. ends with `registerRoot(Root)`. `Root` returns one `<Composition>` per output.
- Give each `<Composition>` an `id`, its `component`, `width`, `height`, `fps` and `durationInFrames`: - 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. - `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. - `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. - `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 ## What to do
- **`raea check` after every real change.** Render with the manifest, then check the export against the floor: - **The render checks itself, once.** `raea render edit.tsx -o final.mp4 --manifest render.json` ends with `raea
`raea render edit.tsx -o final.mp4 --manifest render.json` and check` on the export and keeps what it found as final.check.json; publishing and a stop read that, and nothing runs
`raea check final.mp4 --manifest render.json --words words.json --perception perception.json [--platform tiktok]`. 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,
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 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 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 with its fix; an ERROR is a fault in the export, a warning a note for the person. Fix every ERROR in one pass
in one pass before rendering again. A finding that ends `[also in …]` was in the earlier export too: what you changed 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 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 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 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 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 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 `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, - 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 { 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 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 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. 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 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 - 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. 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 - 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 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 end to end, each in its own Sequence, crossfading over 1.5 s (`fadeIn`/`fadeOut`), or make the take as long as the
span. span.
- **Check the finished file.** `raea check FILM.mp4 --words words.json` (the voice's words on the film's clock) - **Check the finished file.** Its render's check (`raea floor FILM.mp4 --words words.json` on a file raea didn't
reports, by timecode, dead stops (a steady sound that ends in one 10 ms step: fade it out over 100 ms or more; 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 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 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. say why it stands.
+5
View File
@@ -16,6 +16,11 @@
- Size captions at 60 px or more at 1080 wide (scale with the width), with at least 3:1 contrast against the pixels - Size captions at 60 px or more at 1080 wide (scale with the width), with at least 3:1 contrast against the pixels
behind them. Keep them in one place unless a move means something, and keep them off cards, logos, burned-in text behind them. Keep them in one place unless a move means something, and keep them off cards, logos, burned-in text
and the face (`motion/placement`). and the face (`motion/placement`).
- To put a caption or hook in a box that hugs each line, as TikTok draws its text, use `HugText` from
`raea/hug-text`: `<HugText lines={[...]} fill="#E8423F" color="#fff" className="..." />`. Each line gets a fill as
wide as its words, with one rounded shape around them all. You give the lines, so you decide where each breaks
(a caption's come from its word groups). Its emoji draw in colour on any machine, as `EmojiText` from the same
module also does. The box is allowed, never required.
- Mark each caption: `data-raea-role="caption"` on the element holding its words. A layered export (`raea export - Mark each caption: `data-raea-role="caption"` on the element holding its words. A layered export (`raea export
capcut`, `raea export xml`; `motion/delivery`) then puts the captions on a track of their own, styled as they're capcut`, `raea export xml`; `motion/delivery`) then puts the captions on a track of their own, styled as they're
drawn, and writes their words as an .srt beside them; unmarked, they're part of the graphics. drawn, and writes their words as an .srt beside them; unmarked, they're part of the graphics.
+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 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`
beat's average shot length) and `tempo` (`build`: shots shorter as it goes, `release`: longer, `hold`: even) are (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`). measured by the montage pack, when the brief switches it on (`packs: { montage: true }`).
## Murch's order: what to give up first ## 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. 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. 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. 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. 4. Fix eye trace, screen direction and tone where they don't cost a higher reason, and read the render's check.
5. Run `raea goal judge` so a fresh critic watches each beat in sequence.
Loaded 100 of 116 files, more files were not shown because too many files have changed in this diff. Show more