Compare commits

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

- raea check runs a project's goal at a moment (--at edit|render|publish|done); raea goal check still runs
  as its alias for older tools. raea ask, raea judge, goal seen, goal judge, goal gates and check
  --taste/--quick are refused, naming raea check. raea floor is raea's measures for files outside a goal.
- a render's check runs once as it ends and is kept as OUT.check.json; publish and done reuse it while it
  is no older than the file and its manifest, and every rule says at most one line per file
- the goal SDK has no seen, says, critic, record, notes, stills or surprise packs and no taste or look
  checks; a says rule is reported as unchecked; brief.ts holds only what the brief asks
- the edit-moment hook check is gone; the Stop hook reads the kept check
- <Captions /> (raea/video, exported from raea): words in, the brand's caption style, inside the safe area
- the craft guides and AGENTS.md lose judge tiers, ask, Tone.js and framing="face" text
2026-12-05 08:30:13 -08:00
323 changed files with 7674 additions and 5676 deletions

No files matched your search

+1 -1
View File
@@ -8,7 +8,7 @@
{
"name": "raea",
"source": { "source": "git-subdir", "url": "https://github.com/shinyobjectz/raea-skills.git", "path": "skills" },
"description": "Make video, motion graphics, games and 3D scenes with raea, the Render Anything Engine: the raea skill, and hooks that show media in the raea app instead of the Mac's viewer and run raea check on the brief's goals as a turn ends (nothing is checked after a save: a render checks its own output)."
"description": "Make video, motion graphics, games and 3D scenes with raea, the Render Anything Engine: the raea skill, and hooks that run raea's quick check on a composition after it's saved and show media in the raea app instead of the Mac's viewer."
}
]
}
+12 -37
View File
@@ -1,8 +1,7 @@
# raea's public CI (docs/public-first.feature PF5), on GitHub's hosted runners only: it runs code from pull requests,
# so it never touches a self-hosted machine. What needs this Mac's GPU, VideoToolbox or audio (P26, UI parity, the
# sound gates) stays the maintainers' L1/L2 (docs/agents.md); this is the part anyone can read and rerun.
# every pull request and push to main guard (names and secrets), L0's repo-wide gates, sdk/cloud's local tests,
# cargo check of the engine, the tests of every crate that needs no GPU
# every pull request and push to main guard (names and secrets), L0's repo-wide gates, cargo check of the engine
name: ci
on:
@@ -94,24 +93,6 @@ jobs:
- name: taxonomy
run: bash tools/taxonomy.sh --check
cloud:
# sdk/cloud's tests that need no container or farm (its npm test): the box server's pure parts and memory guard,
# what a render sends the farm, and the farm's planner (its encode on ffmpeg), media and volume gate
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- uses: actions/checkout@v4
with:
lfs: false
- uses: actions/setup-node@v4
with:
node-version: 24
- name: ffmpeg
run: sudo apt-get update && sudo apt-get install -y ffmpeg
- name: sdk/cloud tests
working-directory: sdk/cloud
run: npm ci --no-fund --no-audit --loglevel=error && npm test
engine:
# a fresh clone builds as the README says (public #14): the toolchain from rust-toolchain.toml, --locked
strategy:
@@ -126,41 +107,35 @@ jobs:
lfs: false
- name: Linux libraries
if: runner.os == 'Linux'
run: sudo apt-get update && sudo apt-get install -y cmake ninja-build libasound2-dev libfontconfig1-dev libvulkan-dev libudev-dev nasm ffmpeg
run: sudo apt-get update && sudo apt-get install -y cmake ninja-build libasound2-dev libfontconfig1-dev libvulkan-dev libudev-dev nasm
- name: macOS tools
if: runner.os == 'macOS'
run: brew install cmake ninja nasm ffmpeg
run: brew install cmake ninja nasm
- uses: oven-sh/setup-bun@v2
with:
bun-version: 1.4.2
- uses: Swatinem/rust-cache@v2
- name: cargo check
run: cargo check --locked -p raea-cli --tests
- name: unit tests (every crate with no GPU)
- name: unit tests (the crates with no GPU or media device)
# debug info off: with it the test binaries of the app crates filled 27 GB of a runner's disk (#90)
env:
CARGO_PROFILE_TEST_DEBUG: "0"
# The crates come from the lock file, so a new crate's tests run without anyone naming it: every workspace crate
# that links neither wgpu nor Rolldown, then the few that link wgpu and whose tests need no GPU. All of wgpu's
# side can't join: its test binaries would fill the runner's disk (#90). Left out, with the reason:
# raea-sys-mlx its tests run on MLX's GPU device, and a hosted macOS runner has no Metal device
# raea-bundle in a call of its own: Rolldown's crates turn on serde_json's arbitrary_precision, features unify
# across one cargo call, and with it on an untagged enum can't read a number (raea-core-brief's make dials failed
# here from 11-23 while passing alone). raea itself never links Rolldown: it loads it as a library at run time.
# --no-fail-fast: one run names every crate whose tests fail, not only the first
# here from 11-23 while passing alone). raea itself never links Rolldown: it loads it as a library at run time
run: |
ws=$(cargo metadata --locked --no-deps --format-version 1 | jq -r '.packages[].name' | sort)
linked=$(for k in wgpu rolldown; do cargo tree --locked --workspace -i "$k" -e normal,build,dev --prefix none --format '{p}'; done | grep -F "($PWD/" | sed 's/ v[0-9].*//' | sort -u)
light=$(comm -23 <(echo "$ws") <(echo "$linked") | grep -vx raea-sys-mlx | sed 's/^/-p /')
cargo test --locked --no-fail-fast $light -p raea-runtime-plugins -p raea-runtime-live -p raea-app-check -p raea-app-workspace -p raea-app-tools -p raea-app-targets
cargo test --locked -p raea-runtime-plugins -p raea-io-media -p raea-core-fonts -p raea-native -p raea-core-brief -p raea-core-k -p raea-app-check -p raea-app-check-flash -p raea-io-ffmpeg -p raea-app-workspace -p raea-app-tools -p raea-app-targets
cargo test --locked -p raea-bundle
- name: Windows' and Linux's own (#169)
# what a Windows or Linux user meets that needs a feature the step above doesn't turn on: openh264 at --quality
# master (raea-io-soft's tests/quality.rs, its h264 feature) and raea's Node core under the agent shell
# (raea-native's tests/node.rs, its modules feature: Node's names for the system, Windows' paths). QuickJS's
# Intl (raea-runtime-jsengine, on Linux) and git found or fetched (raea-io-assets) run in the step above
# what a Windows or Linux user meets that no other step ran: QuickJS's Intl (raea-runtime-jsengine's
# quickjs_formats_as_javascriptcore_does, on Linux), openh264 at --quality master (raea-io-soft), git found or
# fetched (raea-io-assets), and raea's Node core under the agent shell (raea-native's tests/node.rs: Node's names
# for the system, Windows' paths); tests/node.rs needs raea-native's modules feature and tests/quality.rs
# raea-io-soft's h264
env:
CARGO_PROFILE_TEST_DEBUG: "0"
run: |
cargo test --locked -p raea-native --features modules --test node
cargo test --locked -p raea-io-soft --features h264
cargo test --locked -p raea-runtime-jsengine -p raea-io-assets
Generated
+34
View File
@@ -13863,6 +13863,19 @@ dependencies = [
"serde_json",
]
[[package]]
name = "raea-app-judge"
version = "0.1.0"
dependencies = [
"dunce",
"raea-core-ask",
"raea-core-facts",
"raea-io-clef",
"raea-io-home",
"raea-runtime-bundle",
"serde_json",
]
[[package]]
name = "raea-app-layers"
version = "0.1.0"
@@ -13895,9 +13908,13 @@ version = "0.1.0"
dependencies = [
"dunce",
"image",
"raea-app-judge",
"raea-core-ask",
"raea-core-brief",
"raea-core-facts",
"raea-core-review",
"raea-io-home",
"raea-runtime-lod-plan",
"resvg 0.48.1",
"serde_json",
]
@@ -13990,6 +14007,7 @@ version = "0.1.0"
dependencies = [
"bevy",
"dunce",
"image",
"raea-core-facts",
"raea-core-scene",
"raea-runtime-bundle",
@@ -14009,6 +14027,8 @@ name = "raea-app-solid"
version = "0.1.0"
dependencies = [
"dunce",
"raea-app-ask",
"raea-app-judge",
"raea-app-make",
"raea-core-facts",
"raea-core-meshcheck",
@@ -14296,6 +14316,7 @@ version = "0.1.0"
dependencies = [
"bevy",
"dunce",
"raea-app-ask",
"raea-app-capcut",
"raea-app-check",
"raea-app-ci",
@@ -14303,6 +14324,7 @@ dependencies = [
"raea-app-engines",
"raea-app-fingerprint",
"raea-app-game",
"raea-app-judge",
"raea-app-layers",
"raea-app-lightbake",
"raea-app-make",
@@ -14389,6 +14411,7 @@ dependencies = [
"serde",
"serde_json",
"sha2 0.10.9",
"ts-rs",
]
[[package]]
@@ -16227,6 +16250,17 @@ dependencies = [
"wgpu",
]
[[package]]
name = "raea-sys-foliage"
version = "0.1.0"
dependencies = [
"image",
"parry3d",
"raea-core-ease",
"raea-sys-glb",
"serde_json",
]
[[package]]
name = "raea-sys-fonts"
version = "0.1.0"
+2
View File
@@ -148,6 +148,7 @@ members = [
"systems/matchmove",
"systems/grid",
"systems/lod",
"systems/foliage",
"systems/viewbox",
"systems/rendermap",
"systems/meshseq",
@@ -237,6 +238,7 @@ members = [
"apps/motion",
"apps/engines",
"apps/interchange",
"apps/judge",
"apps/make",
"apps/solid",
"apps/scene",
+4 -5
View File
@@ -11,7 +11,7 @@
<p align="center">
Tell your AI what to make. Videos, motion graphics, 3D and games, written as React and TypeScript<br>
(the code your AI already writes) and rendered on your own GPU.
(the code your AI already writes) and rendered on your own GPU, faster than they play.
</p>
<p align="center">
@@ -145,10 +145,9 @@ Apache-2.0, to read, render and take apart, and its models, textures and sound f
- **Agent skills.** They live in [raea-skills](https://github.com/shinyobjectz/raea-skills), pinned here as
[`skills/`](skills): `raea` teaches an agent to write, render and check raea compositions, 3D and games
included. The installer adds it to `~/.claude/skills`, and `raea skills install --agent NAME` to other agents.
- **Claude plugin.** The raea skill and its hooks: media an agent opens goes to the raea app, and `raea check` holds
the brief's goals as a turn ends. Nothing is checked after a save, since a render checks its own output. In Claude
Code: `/plugin install raea --marketplace shinyobjectz/raea-skills`. It's the `skills/` folder of raea-skills, and
`/plugin marketplace add shinyobjectz/raea` installs the same one.
- **Claude plugin.** The raea skill and two hooks (raea's quick check after a composition is saved, and media shown in
the raea app). In Claude Code: `/plugin install raea --marketplace shinyobjectz/raea-skills`. It's the `skills/`
folder of raea-skills, and `/plugin marketplace add shinyobjectz/raea` installs the same one.
- **Craft guides.** `raea guide` prints the floor every edit is held to and the guides for pitches, explainers, stories,
games, motion, music and layout. `raea context PROJECT` says what to read before working on a project.
- **Bug reports.** When an agent finds a bug in raea itself, `raea bug TITLE --text TEXT` sends it to raea's server
+1 -1
View File
@@ -4,7 +4,7 @@ version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "Questions about a piece's picture and sound, prepared from what raea knows of it, asked of clef in parallel from the person's plan, and every answer kept"
description = "raea ask: questions about a piece's picture and sound, prepared from what raea knows of it, asked of clef in parallel from the person's plan, and every answer kept"
[dependencies]
# the question format and the standard sets; the one clef client, routed to the person's plan first (docs/ask.feature)
+5 -5
View File
@@ -3,7 +3,7 @@
//! threshold, the problem score that flags 10% of the clean labels. The gates are the fingerprint's (16 labels of each
//! kind, from 3 projects, an AUC of 0.8). A question that passes is calibrated at its threshold: its answers are
//! findings, and the person's calibration replaces raea's shipped one. One under 0.6 after 32 labels doesn't separate,
//! and says which labels it missed, so its words can be fixed. `try_words` asks new words of the labelled clips and
//! and says which labels it missed, so its words can be fixed. `raea ask try` asks new words of the labelled clips and
//! sets both AUCs side by side.
use std::collections::{BTreeMap, BTreeSet, HashMap};
@@ -135,7 +135,7 @@ fn versions(only: Option<&str>, all: &[Label]) -> Vec<Question> {
out
}
/// `calibrate(ID)`: the feed's labels read again, then every labelled version held to them. The ones that
/// `raea ask calibrate [ID]`: the feed's labels read again, then every labelled version held to them. The ones that
/// pass are kept as the person's calibration; one that no longer passes loses it.
pub fn calibrate(only: Option<&str>) -> Result<(Vec<Standing>, (usize, usize)), String> {
let feed = labels::from_feed()?;
@@ -159,7 +159,7 @@ fn today() -> String {
raea_io_trace::utc(std::time::SystemTime::now()).0.chars().take(10).collect()
}
/// The groups `try_words` sends: the new question on each labelled clip set, with the state it was asked with.
/// The groups `raea ask try` sends: the new question on each labelled clip set, with the state it was asked with.
pub fn try_groups(like: &str, words: &str) -> Result<(Question, Question, Vec<Group>), String> {
let all = labels::all();
let standing = labels::standing(&all);
@@ -182,7 +182,7 @@ pub fn try_groups(like: &str, words: &str) -> Result<(Question, Question, Vec<Gr
groups.push(Group { piece, from, to, sees: new.sees, hears: new.hears, with: vec![], questions: vec![new.clone()], kept: Some(Arc::new(kept)) });
}
if groups.is_empty() {
return Err(format!("ask try: none of {like}'s labelled clips are still kept (calibrate() lists its labels)"));
return Err(format!("ask try: none of {like}'s labelled clips are still kept (raea ask calibrate lists its labels)"));
}
Ok((old, new, groups))
}
@@ -201,7 +201,7 @@ fn media(names: &[&str]) -> Option<Media> {
Some(m)
}
/// `try_words(LIKE, WORDS)`: the new words asked of the old question's labelled clips, and both versions held to
/// `raea ask try "WORDS" --like ID`: the new words asked of the old question's labelled clips, and both versions held to
/// the same labels.
pub fn try_words(like: &str, words: &str, o: &Opts, out: &mut dyn FnMut(Event)) -> Result<(Summary, Option<(Standing, Standing)>), String> {
let (old, new, groups) = try_groups(like, words)?;
+4 -4
View File
@@ -1,14 +1,14 @@
//! Labels (docs/ask.feature AK6): whether a question's problem was really there in what one call sent, so the question
//! can be calibrated on the person's own eye (calibrate.rs). A label belongs to a question and to the clips a call sent
//! (by their hashes), never to one answer: the same question reworded, asked again of the same clips, has the same
//! labels, which is what lets `try_words` measure new words.
//! labels, which is what lets `raea ask try` measure new words.
//!
//! Where labels come from:
//! - `verdict(ANSWER, WORD)`: the person answers the question themselves, in its own terms (yes or no, an option,
//! - `raea ask verdict ANSWER WORD`: the person answers the question themselves, in its own terms (yes or no, an option,
//! a level). Theirs counts first.
//! - The feed: a note of the person's on the render (its copy in the project's feed, known by `record::ident`), pinned
//! inside the window or not pinned at all, holding one of the question's label words, is a yes; an approved post (done)
//! with no such note is a no. Read again by every `calibrate()`.
//! with no such note is a no. Read again by every `raea ask calibrate`.
//! - Another eye (`verdict --eye agent`: an agent's own look) is kept as `eye:NAME` and never counted, as the
//! fingerprint keeps another eye's readings (FP6d).
@@ -149,7 +149,7 @@ fn label(q: &str, call: &Value, bad: bool, source: &str, note: Option<String>) -
}
}
/// `verdict(ANSWER, WORD, EYE)`: the person's answer to the question on that answer's clips (or another
/// `raea ask verdict ANSWER WORD [--eye NAME]`: the person's answer to the question on that answer's clips (or another
/// eye's, kept and never counted). A verdict given again replaces the last from the same source.
pub fn verdict(answer: &str, said: &str, eye: Option<&str>) -> Result<String, String> {
let row = record::rows("answers.jsonl").into_iter().find(|a| a["id"] == answer).ok_or_else(|| format!("ask verdict: no answer {answer} in {}", record::dir().display()))?;
+8 -4
View File
@@ -1,13 +1,17 @@
//! Questions about a piece's picture and sound (docs/ask.feature AK2-AK3), asked for the fingerprint's double-check
//! (`raea fingerprint score --ask`, apps/double). `prepare` reads what raea knows of the piece and keeps the questions
//! that apply; `runner` plans the calls, cuts each clip once and asks in parallel; `record` keeps every call and answer;
//! `labels` reads the person's notes and approvals into labels, and `calibrate` holds each question to them (AK6-AK7).
//! `raea ask` (docs/ask.feature AK2-AK3): questions about a piece's picture and sound. `prepare` reads what raea knows
//! of the piece and keeps the questions that apply; `runner` plans the calls, cuts each clip once and asks in parallel;
//! `record` keeps every call and answer; `labels` reads the person's verdicts, notes and approvals into labels, and
//! `calibrate` holds each question to them (AK6-AK7); `verbs` is the command. `raea check`, the app's critique and the
//! fingerprint's double-check go through the same runner.
pub mod calibrate;
pub mod labels;
pub mod prepare;
pub mod record;
pub mod runner;
pub mod verbs;
pub use verbs::{USAGE, cli};
#[cfg(test)]
mod tests;
+2 -2
View File
@@ -3,7 +3,7 @@
//! answer in answers.jsonl (the call, the question and its version, the reading). The clips themselves are kept by hash
//! in media/, at most 2 GB, the oldest out first, so new words can be asked of the same media. A call keeps what its
//! file was (`ident`), so a note on the render's copy in the feed labels it (labels.rs), and an answer keeps its whole
//! question, so a verdict reads in its terms and `try_words` can reword it.
//! question, so a verdict reads in its terms and `raea ask try` can reword it.
use std::io::Write as _;
use std::path::{Path, PathBuf};
@@ -49,7 +49,7 @@ fn hex(digest: &[u8]) -> String {
digest.iter().take(16).map(|b| format!("{b:02x}")).collect()
}
/// What a file is, cheaply, and the size an ident names (raea-core-ask's).
/// What a file is, cheaply, and the size an ident names (raea-core-ask, so `raea goal gates` reads the same).
pub use raea_core_ask::ident::{ident, ident_len};
/// One of the record's files written whole, through a temporary file, so a reader never sees half of it.
+4 -4
View File
@@ -3,7 +3,7 @@
//! call whose questions depend on whether anyone speaks when that isn't known), each clip cut once, the calls
//! made in parallel, the answers streamed back as they come and kept. A pool that's spent partway keeps what came and
//! reports the rest as waiting for it. `dry` cuts the media and says what would be sent, and spends nothing. A group can
//! carry clips kept from an earlier call instead of a file to cut (`try_words`), and every question goes out with the
//! carry clips kept from an earlier call instead of a file to cut (`raea ask try`), and every question goes out with the
//! person's own calibration when it has earned one (calibrate.rs).
use std::collections::{BTreeSet, HashMap};
@@ -50,10 +50,10 @@ pub struct Kept {
pub sound_seconds: f64,
}
/// One answer, or why a question wasn't asked or still waits: one line of JSON each.
/// One answer, or why a question wasn't asked or still waits: the line `raea ask --json` prints for each.
#[derive(Debug, Clone, Default, Serialize)]
pub struct Answer {
/// its id in the record (`labels::verdict` takes it)
/// its id in the record (`raea ask verdict` takes it)
pub answer: Option<String>,
pub file: String,
pub id: String,
@@ -285,7 +285,7 @@ pub fn run_groups(groups: Vec<Group>, unasked: Vec<Answer>, o: &Opts, out: &mut
sum
}
/// The clips a call sent, kept by hash for `try_words`.
/// The clips a call sent, kept by hash for `raea ask try`.
fn kept(m: &Media) -> Vec<String> {
let each = |v: &[Vec<u8>], ext: &str| v.iter().map(|b| record::keep_media(b, ext)).collect::<Vec<_>>();
[each(&m.videos, "mp4"), each(&m.stills, "jpg"), each(&m.sounds, "mp3")].concat()
+7 -1
View File
@@ -11,7 +11,7 @@ use crate::prepare::{self, Piece, VOICE};
use crate::runner::{self, Answer, Entry, Event, Opts};
fn rubric() -> String {
std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/../../sdk/guides/craft/verbs/critique.md")).expect("the critique guide")
std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/../../sdk/guides/craft/rubric.md")).expect("the craft rubric")
}
pub(crate) fn setup() {
@@ -166,3 +166,9 @@ fn a_pool_spent_partway_keeps_what_came_and_the_rest_waits() {
assert_eq!(got.iter().filter(|a| a.waits.as_deref().is_some_and(|w| w.contains("used up"))).count(), 2);
assert_eq!(CALLS.load(Ordering::SeqCst), 3, "nothing is sent after the pool is spent");
}
#[test]
fn own_words_keep_their_id() {
assert_eq!(crate::verbs::own_id("Does the music fight the voice?"), "own-does-the-music-fight-the-voice");
assert_eq!(crate::verbs::own_id("Does the music fight the voice?"), crate::verbs::own_id("does the MUSIC fight the voice"));
}
+385
View File
@@ -0,0 +1,385 @@
//! `raea ask` (docs/ask.feature AK3): questions about a piece's picture and sound, from the command line or a batch,
//! prepared (prepare.rs), asked in parallel (runner.rs) and kept (record.rs). It prints as answers come: words and a
//! probability a line, or with `--json` one JSON object a line (an answer, a call `--dry` would make, then the summary).
//! `--gate` exits 1 when a calibrated question flags (`--gate any`: when any does), for a pipeline. `verdict`,
//! `calibrate` and `try` label the answers, calibrate the questions on them and measure new words (labels.rs,
//! calibrate.rs; AK6-AK7).
use std::collections::{BTreeMap, HashMap};
use std::io::Read as _;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use raea_core_ask::{Kind, Question, Window, library};
use serde_json::{Value, json};
use crate::labels::{self, span};
use crate::prepare::{self, Piece};
use crate::runner::{self, Entry, Event, Opts};
use crate::{calibrate, record};
pub const USAGE: &str = "raea ask FILE [QUESTION...] [--choose A,B,C] [--grade] [--rate N] [--flag ANSWERS] [--set NAME] [--std ID] [--from S] [--to S] [--at S] [--with FILE2] [--brief brief.ts|none] [--words words.json] [--voice yes|no] [--state TEXT] [--dry] [--json] [--gate [any]] [--jobs N] | ask --batch FILE [--dry] [--json] [--gate [any]] [--jobs N] | ask list [SET] [--json] | ask verdict ANSWER WORD [--eye NAME] | ask calibrate [ID] [--json] | ask try WORDS --like ID [--dry] [--json] [--jobs N] (questions about a piece's picture and sound, answered by clef-omni and paid from your raea plan's pool when the app is signed in, else RAEA_AGENT_KEY's, else your own Cloudflare keys: your own words, or the standard sets (rubric, av, defects, platform, decide, make); every question about one clip goes in one call, --batch (a JSON list or JSON lines, - for stdin) asks many clips in parallel; --dry says what would be sent and spends nothing; answers are advice until a question is calibrated: verdict labels an answer, calibrate holds each question to your verdicts, notes and approvals, try asks new words of its labelled clips)";
const VALUED: [&str; 17] = ["--choose", "--rate", "--flag", "--set", "--std", "--from", "--to", "--at", "--with", "--brief", "--words", "--voice", "--state", "--jobs", "--batch", "--eye", "--like"];
const BARE: [&str; 4] = ["--grade", "--dry", "--json", "--gate"];
/// The arguments: the words that aren't flags, each flag's values, and whether `--gate` is `--gate any`.
#[derive(Default)]
struct Args {
words: Vec<String>,
flags: BTreeMap<String, Vec<String>>,
gate_any: bool,
}
impl Args {
fn parse(args: &[String]) -> Result<Args, String> {
let mut a = Args::default();
let mut i = 0;
while i < args.len() {
let s = args[i].as_str();
if VALUED.contains(&s) {
let v = args.get(i + 1).ok_or_else(|| format!("ask: {s} takes a value\nusage: {USAGE}"))?;
a.flags.entry(s.into()).or_default().push(v.clone());
i += 1;
} else if BARE.contains(&s) {
a.flags.entry(s.into()).or_default();
if s == "--gate" && args.get(i + 1).is_some_and(|v| v == "any") {
a.gate_any = true;
i += 1;
}
} else if s.starts_with("--") {
return Err(format!("ask doesn't take {s}\nusage: {USAGE}"));
} else {
a.words.push(s.into());
}
i += 1;
}
Ok(a)
}
fn has(&self, f: &str) -> bool {
self.flags.contains_key(f)
}
fn one(&self, f: &str) -> Option<&str> {
self.flags.get(f).and_then(|v| v.last()).map(String::as_str)
}
fn num(&self, f: &str) -> Result<Option<f64>, String> {
self.one(f).map(|v| v.parse::<f64>().map_err(|_| format!("ask: {f} takes seconds, got {v:?}"))).transpose()
}
fn list(&self, f: &str) -> Vec<String> {
self.flags.get(f).into_iter().flatten().flat_map(|v| v.split(',')).map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect()
}
}
/// The craft rubric's text, where the guides are installed, for the `rubric` set.
pub fn rubric_md() -> Option<String> {
std::fs::read_to_string(raea_io_home::home().join("sdk/guides/craft/rubric.md")).ok()
}
/// A question's id from its words: `own-` and its first words, so the same words keep their id.
pub fn own_id(words: &str) -> String {
let slug: Vec<String> = words.split(|c: char| !c.is_ascii_alphanumeric()).filter(|w| !w.is_empty()).take(6).map(str::to_lowercase).collect();
let mut id = format!("own-{}", slug.join("-"));
id.truncate(raea_core_ask::limits::ID_LEN);
id
}
/// The questions an entry names: its own words (shaped by the kind flags), its sets and its standard ids.
fn named(own: &[Question], sets: &[String], std: &[String], rubric: Option<&str>) -> Result<Vec<Question>, String> {
let mut qs = own.to_vec();
for s in sets {
qs.extend(library::set(s, rubric)?);
}
for id in std {
qs.push(library::find(id, rubric).ok_or_else(|| format!("ask: no standard question {id} (raea ask list)"))?);
}
Ok(qs)
}
fn shaped(words: &str, a: &Args) -> Result<Question, String> {
let mut q = Question::plain(&own_id(words), words);
if let Some(c) = a.one("--choose") {
q.kind = Kind::Choose;
q.options = c.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect();
} else if let Some(n) = a.one("--rate") {
let n: usize = n.parse().map_err(|_| format!("ask: --rate takes how many levels, got {n:?}"))?;
q.kind = Kind::Rate;
q.options = (1..=n).map(|i| i.to_string()).collect();
} else if a.has("--grade") {
q.kind = Kind::Grade;
}
q.flags = a.list("--flag");
if let Some(why) = raea_core_ask::limits::check(&q) {
return Err(format!("ask: {why}"));
}
Ok(q)
}
/// The window from --from, --to and --at (three seconds around it).
fn window(a: &Args) -> Result<Option<Window>, String> {
if let Some(at) = a.num("--at")? {
return Ok(Some(Window { from: Some((at - 1.5).max(0.0)), to: Some(at + 1.5) }));
}
let (from, to) = (a.num("--from")?, a.num("--to")?);
Ok((from.is_some() || to.is_some()).then_some(Window { from, to }))
}
fn voice(v: Option<&str>) -> Result<Option<bool>, String> {
match v {
None => Ok(None),
Some("yes" | "true") => Ok(Some(true)),
Some("no" | "false") => Ok(Some(false)),
Some(v) => Err(format!("ask: --voice takes yes or no, got {v:?}")),
}
}
/// Pieces read once a run, by what they were read with.
type Pieces = HashMap<String, Arc<Piece>>;
#[allow(clippy::too_many_arguments)]
fn piece(pieces: &mut Pieces, file: &str, brief: Option<&str>, words: Option<&str>, voice: Option<bool>, state: Option<String>) -> Result<Arc<Piece>, String> {
let key = format!("{file}\u{1f}{brief:?}\u{1f}{words:?}\u{1f}{voice:?}\u{1f}{state:?}");
if let Some(p) = pieces.get(&key) {
return Ok(p.clone());
}
let p = Arc::new(Piece::read(Path::new(file), brief.map(Path::new), words.map(Path::new), voice, state).map_err(|e| format!("ask: {e}"))?);
pieces.insert(key, p.clone());
Ok(p)
}
fn entry(p: Arc<Piece>, window: Option<Window>, qs: Vec<Question>, with: Vec<PathBuf>, rubric: Option<&str>) -> Entry {
let (questions, dropped) = prepare::keep(qs, &p.facts(), rubric);
Entry { piece: p, window, questions, dropped, with }
}
/// The command line's one entry.
fn from_args(a: &Args, rubric: Option<&str>, pieces: &mut Pieces) -> Result<Vec<Entry>, String> {
let Some((file, words)) = a.words.split_first() else { return Err(USAGE.into()) };
let own = words.iter().map(|w| shaped(w, a)).collect::<Result<Vec<_>, _>>()?;
let qs = named(&own, &a.list("--set"), &a.list("--std"), rubric)?;
if qs.is_empty() {
return Err(format!("ask: nothing to ask: give a question in words, --set or --std (raea ask list)\nusage: {USAGE}"));
}
let p = piece(pieces, file, a.one("--brief"), a.one("--words"), voice(a.one("--voice"))?, a.one("--state").map(str::to_string))?;
let with = a.flags.get("--with").into_iter().flatten().map(PathBuf::from).collect();
Ok(vec![entry(p, window(a)?, qs, with, rubric)])
}
/// A batch: a JSON list of entries or JSON lines, from a file or stdin (`-`). Each entry is {file, window?, questions?
/// (words or questions), set?, std?, with?, brief?, words?, voice?, state?}.
fn from_batch(path: &str, rubric: Option<&str>, pieces: &mut Pieces) -> Result<Vec<Entry>, String> {
let text = match path {
"-" => {
let mut s = String::new();
std::io::stdin().read_to_string(&mut s).map_err(|e| format!("ask: stdin: {e}"))?;
s
}
p => std::fs::read_to_string(p).map_err(|e| format!("ask: {p}: {e}"))?,
};
let rows: Vec<Value> = match serde_json::from_str::<Value>(text.trim()) {
Ok(Value::Array(a)) => a,
Ok(v @ Value::Object(_)) => vec![v],
_ => text.lines().filter(|l| !l.trim().is_empty()).enumerate().map(|(i, l)| serde_json::from_str(l).map_err(|e| format!("ask: {path} line {}: {e}", i + 1))).collect::<Result<_, _>>()?,
};
let strs = |v: &Value| -> Vec<String> {
match v {
Value::String(s) => s.split(',').map(|s| s.trim().to_string()).collect(),
Value::Array(a) => a.iter().filter_map(Value::as_str).map(str::to_string).collect(),
_ => vec![],
}
};
let mut out = Vec::new();
for (n, r) in rows.iter().enumerate() {
let at = |e: String| format!("ask: {path} entry {}: {e}", n + 1);
let file = r["file"].as_str().ok_or_else(|| at("it has no file".into()))?;
let own = r["questions"].as_array().into_iter().flatten().map(|q| match q {
Value::String(w) => Ok(Question::plain(&own_id(w), w)),
q => serde_json::from_value::<Question>(q.clone()).map_err(|e| e.to_string()),
});
let own = own.collect::<Result<Vec<_>, _>>().map_err(at)?;
let qs = named(&own, &strs(&r["set"]), &strs(&r["std"]), rubric).map_err(at)?;
let window: Option<Window> = serde_json::from_value(r["window"].clone()).ok();
let v = voice(r["voice"].as_str()).map_err(at)?.or(r["voice"].as_bool());
let p = piece(pieces, file, r["brief"].as_str(), r["words"].as_str(), v, r["state"].as_str().map(str::to_string)).map_err(at)?;
out.push(entry(p, window, qs, strs(&r["with"]).into_iter().map(PathBuf::from).collect(), rubric));
}
Ok(out)
}
/// `raea ask list [SET]`: the standard questions.
fn list(a: &Args, rubric: Option<&str>) -> Result<String, String> {
let sets: Vec<String> = match a.words.get(1) {
Some(s) => vec![s.clone()],
None => library::SETS.iter().map(|s| s.to_string()).collect(),
};
let mut out = Vec::new();
let mine = calibrate::local();
for s in &sets {
let mut qs = library::set(s, rubric)?;
qs.iter_mut().for_each(|q| calibrate::apply(q, &mine));
if a.has("--json") {
out.push(json!({"set": s, "questions": qs}).to_string());
continue;
}
out.push(format!("{s}:"));
for q in qs {
let how = if q.calibrated() { "calibrated" } else { "advice" };
out.push(format!(" {:<28} {:<6} {:<10} {}", q.id, format!("{:?}", q.kind).to_lowercase(), how, q.ask));
}
}
Ok(out.join("\n"))
}
/// An event as a line of text.
fn line(e: &Event, files: usize) -> String {
match e {
Event::Would(v) => {
let qs: Vec<&str> = v["questions"].as_array().into_iter().flatten().filter_map(|q| q["id"].as_str()).collect();
let m = &v["media"];
let kb = |k: &str| m[k].as_array().map(|a| a.iter().filter_map(Value::as_u64).map(|b| format!("{} KB", b / 1024)).collect::<Vec<_>>().join(", ")).unwrap_or_default();
format!(
"would ask {} ({}) about {}:\n {}\n videos [{}], stills [{}], sounds [{}], about ${:.4}\n state: {}",
qs.len(),
span(v["from"].as_f64().unwrap_or(0.0), v["to"].as_f64()),
v["file"].as_str().unwrap_or(""),
qs.join(", "),
kb("videos"),
kb("stills"),
kb("sounds"),
v["estimate_usd"].as_f64().unwrap_or(0.0),
v["state"].as_str().unwrap_or("")
)
}
Event::Answer(a) => {
let who = if files > 1 { format!("{}: ", a.file) } else { String::new() };
let what = match (&a.says, &a.not_asked, &a.waits) {
(Some(s), ..) => format!("{s} [{}]{}", span(a.from, a.to), if a.flagged && a.calibrated { " <- finding" } else if a.flagged { " <- flagged" } else { "" }),
(_, Some(n), _) => format!("not asked: {n}"),
(.., Some(w)) => w.clone(),
_ => "no answer".into(),
};
format!("{who}{:<34} {what}", a.id)
}
}
}
/// `raea ask ...` with its exit code: 0, or 1 when it couldn't ask or a gate failed.
pub fn cli(args: &[String]) -> i32 {
match run(args) {
Ok(code) => code,
Err(e) => {
eprintln!("{e}");
1
}
}
}
fn run(args: &[String]) -> Result<i32, String> {
let a = Args::parse(args)?;
let rubric = rubric_md();
let jobs = a.one("--jobs").map(|j| j.parse::<usize>().map_err(|_| format!("ask: --jobs takes a number, got {j:?}"))).transpose()?.unwrap_or(4);
let sub = a.words.first().map(String::as_str).filter(|w| !Path::new(w).exists());
match sub {
Some("list") => {
println!("{}", list(&a, rubric.as_deref())?);
return Ok(0);
}
Some("verdict") => {
let [_, answer, said] = a.words.as_slice() else { return Err(format!("ask verdict ANSWER WORD: the answer's id (from --json or {}) and your answer to its question", record::dir().join("answers.jsonl").display())) };
println!("{}", labels::verdict(answer, said, a.one("--eye"))?);
return Ok(0);
}
Some("calibrate") => return calibrated(&a),
Some("try") => return tried(&a, jobs),
_ => {}
}
let mut pieces = Pieces::new();
let entries = match a.one("--batch") {
Some(b) => from_batch(b, rubric.as_deref(), &mut pieces)?,
None => from_args(&a, rubric.as_deref(), &mut pieces)?,
};
let (json_out, dry) = (a.has("--json"), a.has("--dry"));
let files = pieces.len();
let sum = runner::run(entries, &Opts::new(jobs, dry), &mut |e| {
match (&e, json_out) {
(Event::Answer(r), true) => println!("{}", serde_json::to_string(r).unwrap_or_default()),
(Event::Would(v), true) => println!("{}", json!({"would": v})),
(e, false) => println!("{}", line(e, files)),
}
});
if json_out {
println!("{}", json!({"summary": sum}));
} else if dry {
println!("{} call{}, about ${:.4}; nothing was sent", sum.calls, if sum.calls == 1 { "" } else { "s" }, sum.estimate);
} else if sum.calls > 0 {
let routes: Vec<&str> = sum.routes.iter().map(String::as_str).collect();
let left = sum.pool_left.map(|l| format!(", ${l:.2} left this month")).unwrap_or_default();
let waiting = if sum.waiting > 0 { format!("; {} wait for the pool", sum.waiting) } else { String::new() };
println!(
"asked {} question{} in {} call{} through {}: ${:.4}{left}{waiting}. Answers are advice until a question is calibrated (docs/ask.feature AK7).",
sum.asked,
if sum.asked == 1 { "" } else { "s" },
sum.calls,
if sum.calls == 1 { "" } else { "s" },
routes.join(" and "),
sum.cost
);
}
if !dry && sum.calls == 0 {
return Err("ask: nothing was asked (each question's line says why)".into());
}
// a gate fails on a flag (a calibrated one, or with `any` any), and on questions still waiting for the pool
let flagged = if a.gate_any { sum.flagged } else { sum.flagged_calibrated };
Ok(i32::from(a.has("--gate") && (flagged > 0 || sum.waiting > 0)))
}
/// A version's standing as a line, with its misses below when it doesn't separate.
fn standing_line(s: &calibrate::Standing) -> String {
let auc = s.auc.map_or_else(|| "no AUC".to_string(), |a| format!("AUC {a:.2}"));
let mut out = format!("{} ({}) \"{}\": {}, {auc} on {} labels; {}", s.id, &s.version[..8.min(s.version.len())], s.ask, s.state, s.problems + s.clean, s.why);
if s.others > 0 {
out += &format!(" ({} from other eyes, not counted)", s.others);
}
for m in &s.misses {
let what = if m.bad { "a problem it scored" } else { "clean work it scored" };
out += &format!("\n {what} {:.2}: {} ({}){}", m.problem, m.file, m.span, m.note.as_ref().map(|n| format!(" \"{n}\"")).unwrap_or_default());
}
out
}
/// `raea ask calibrate [ID]`: the feed's labels read again and each labelled question held to its labels.
fn calibrated(a: &Args) -> Result<i32, String> {
let (all, (yes, no)) = calibrate::calibrate(a.words.get(1).map(String::as_str))?;
if a.has("--json") {
println!("{}", json!({"feed": {"problems": yes, "clean": no}}));
all.iter().for_each(|s| println!("{}", serde_json::to_string(s).unwrap_or_default()));
return Ok(0);
}
println!("from the feed: {yes} note{} that saw a problem, {no} approval{} without one", if yes == 1 { "" } else { "s" }, if no == 1 { "" } else { "s" });
if all.is_empty() {
println!("no labelled questions yet: raea ask verdict ANSWER WORD labels one, and your notes on a posted render do too");
}
all.iter().for_each(|s| println!("{}", standing_line(s)));
Ok(0)
}
/// `raea ask try WORDS --like ID`: new words asked of a question's labelled clips, both held to the same labels.
fn tried(a: &Args, jobs: usize) -> Result<i32, String> {
let words = a.words[1..].join(" ");
let like = a.one("--like").ok_or("ask try WORDS --like ID: the question whose labelled clips the new words are asked of")?;
if words.trim().is_empty() {
return Err("ask try WORDS --like ID: the new words".into());
}
let json_out = a.has("--json");
let (sum, both) = calibrate::try_words(like, &words, &Opts::new(jobs, a.has("--dry")), &mut |e| match (&e, json_out) {
(Event::Would(v), true) => println!("{}", json!({"would": v})),
(Event::Answer(r), true) => println!("{}", serde_json::to_string(r).unwrap_or_default()),
(e, false) => println!("{}", line(e, 2)),
})?;
match (both, json_out) {
(None, true) => println!("{}", json!({"summary": sum})),
(None, false) => println!("{} call{}, about ${:.4}; nothing was sent", sum.calls, if sum.calls == 1 { "" } else { "s" }, sum.estimate),
(Some((old, new)), true) => println!("{}", json!({"summary": sum, "old": old, "new": new})),
(Some((old, new)), false) => println!("${:.4} for {} calls\nold words: {}\nnew words: {}", sum.cost, sum.calls, standing_line(&old), standing_line(&new)),
}
Ok(i32::from(!a.has("--dry") && sum.calls == 0))
}
+4 -4
View File
@@ -20,14 +20,14 @@ raea-io-ffmpeg = { path = "../../io/ffmpeg" }
raea-sys-measure = { path = "../../systems/measure" }
# what it reads of a video, through FFmpeg or raea's own decoders where it isn't installed
raea-app-check-read = { path = "read" }
# who can fix what it finds: the encode's or the picture's own, carried, a source
# who can fix what it finds: the encode's or the picture's own, carried, a source (split out to keep this crate small)
raea-app-check-cause = { path = "cause" }
# the text rules on a render's manifest (split out: raea render holds its own text to them)
raea-app-check-text = { path = "text" }
# the flashing screen (WCAG 2.3.1)
# the flashing screen (WCAG 2.3.1), split out to keep this crate small
raea-app-check-flash = { path = "flash" }
# what the person sent from the raea app, handed to the agent
# what the person sent from the raea app, handed to the agent (split out to keep this crate small)
raea-app-check-inbox = { path = "inbox" }
# the Stop gate for a `make` job (docs/goal.feature MK2)
# the Stop gate for a `make` job (docs/goal.feature MK2; split out to keep this crate small)
raea-app-check-make = { path = "make" }
serde_json = "1"
+1 -1
View File
@@ -53,7 +53,7 @@ pub fn luma(rgba: &[u8], width: usize, w: usize, h: usize) -> Vec<u8> {
}
/// `frames` as `comp` draws them, never encoded, as luma `w` x `h` (top-left): `raea render COMP --at F,... -o DIR/`
/// (PNG) run by `raea` from the project, kept out of its record (RAEA_RECORD=off)
/// (PNG) run by `raea` from the project, kept out of its record as the quick check's stills are
pub fn unencoded(raea: &Path, project: &Path, comp: &Path, frames: &[i64], w: usize, h: usize) -> R<Vec<Vec<u8>>> {
let mut wanted: Vec<i64> = frames.to_vec();
wanted.sort_unstable();
+2 -1
View File
@@ -1,4 +1,5 @@
//! The flashing screen behind `raea check` (apps/check flash.rs feeds it the decoded frames): a pure measure of pixels.
//! The flashing screen behind `raea check` (apps/check flash.rs feeds it the decoded frames): a pure measure of pixels,
//! in a crate of its own so the check stays small (tools/size.sh).
/// Flashing past WCAG 2.3.1: more than three flashes in any one second, over enough of the frame to matter. A flash is a
/// pair of opposing changes in the same pixels, so a shape sliding past isn't one. Each window, a third of the frame wide
+4 -3
View File
@@ -1,4 +1,4 @@
//! `raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--shape 9:16]
//! `raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--things T.json] [--shape 9:16]
//! [--platform tiktok|reels|shorts] [-o check.json]`: the floor's measurable lines on an export (docs/craft-system.md, I; sdk/guides/craft/floor.md).
//! Each issue is ranked P0 (breaks the piece) to P3 (polish), with where it is and what to do. Rules on the file alone:
//! loudness and true peak, a steady sound that stops dead (a source run out, a cut with no fade), stretches where nothing
@@ -28,6 +28,7 @@ use raea_app_check_text::*;
use raea_app_check_cause as cause;
/// a video read through FFmpeg, or raea's own decoders where it isn't installed
use raea_app_check_read::{self as read, Probe};
pub mod quick;
pub mod hook;
pub use raea_app_check_inbox as inbox;
#[cfg(test)]
@@ -65,7 +66,7 @@ fn flag<'a>(args: &'a [String], name: &str) -> Option<&'a str> {
args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).map(String::as_str)
}
pub const USAGE: &str = "raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--shape 16:9|9:16|4:5|1:1] [--platform tiktok|reels|shorts] [-o check.json] (an export against the floor: clipped text, contrast, safe areas, freezes, flashing, cues, loudness, blotching, a placeholder brand kit; its findings errors, warns and notes)";
pub const USAGE: &str = "raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--things T.json] [--shape 16:9|9:16|4:5|1:1] [--platform tiktok|reels|shorts] [--taste taste.ts|DIR] [-o check.json] (an export against the floor: clipped text, contrast, safe areas, freezes, flashing, cues, loudness, blotching, a placeholder brand kit, and with --things what `raea fingerprint things --json` found: a thing floating or passing through another, the camera lurching mid-move, an empty frame; its findings errors, warns and notes)";
/// A rule from the person's taste: a form raea can measure, its value, and the taste line it stands for.
#[derive(Clone, Debug, PartialEq)]
@@ -115,7 +116,7 @@ fn taste_text(rules: &[Taste], runs: &[Run], w: f64, h: f64, issues: &mut Vec<Is
}
/// the flags `raea check` takes, each with a value
const TAKES: [&str; 6] = ["--manifest", "--words", "--perception", "--shape", "--platform", "-o"];
const TAKES: [&str; 8] = ["--manifest", "--words", "--perception", "--things", "--shape", "--platform", "--taste", "-o"];
fn run(args: &[String], tastes: Vec<raea_core_brief::Taste>) -> R<(String, bool)> {
let (video, issues, passed, fps) = measured(args, taste_rules(&tastes))?;
+6 -18
View File
@@ -15,16 +15,6 @@ pub(crate) const MOST: f32 = 4.0;
pub(crate) const RUN: usize = 4;
pub(crate) const BACK: usize = 4;
pub(crate) const BLOTCHY: f64 = 0.009;
/// The least blotching an encoder's patches have been measured at (the VideoToolbox exports' 0.012): a score between
/// BLOTCHY and this, whose cause can't be told, is a warning, never an error (12-05: a 3D shot rendered at master
/// quality read 0.010, from its shadows' own dithered edge, and was an error whose fix, master quality, it already had)
pub(crate) const BLOTCHED: f64 = 0.012;
/// How a finding whose cause can't be told stands: an error when more than a fifth of the samples blotch and the worst
/// is past BLOTCHED, else a warning
pub(crate) fn untold_level(share: f64, worst: f64) -> u8 {
if share > 0.2 && worst >= BLOTCHED { 1 } else { 2 }
}
pub(crate) fn blotch_score(y: &[u8], w: usize, h: usize) -> Option<f64> {
let (bw, bh) = (w / 8, h / 8);
@@ -200,8 +190,8 @@ pub(crate) fn blotching_from(video: &str, probe: &Probe, scores: &[Option<f64>],
let own = if a.0.before > 0 { format!("; {} of the samples show the footage's own too, which stays", a.0.before) } else { String::new() };
(if a.0.worse as f64 / a.0.of.max(1) as f64 > 0.2 { 1 } else { 2 }, first.or(Some(at)), format!("the encode added blocky patches in dark areas: {} of {} samples are blotchier than the composition draws them unencoded; render with --quality master, which gives the darks the bits they need{own}", a.0.worse, a.0.of))
}
Some(Err(why)) => (untold_level(share, worst), Some(at), format!("{found}; whether the encode made them or the picture holds them couldn't be told ({why}): render with --quality master if the encode starved the darks")),
None => (untold_level(share, worst), Some(at), format!("{found}: the encode starved the near-blacks, or the footage holds them; render with --quality master, and check a render made in a raea project to tell which")),
Some(Err(why)) => (if share > 0.2 { 1 } else { 2 }, Some(at), format!("{found}; whether the encode made them or the picture holds them couldn't be told ({why}): render with --quality master if the encode starved the darks")),
None => (if share > 0.2 { 1 } else { 2 }, Some(at), format!("{found}: the encode starved the near-blacks, or the footage holds them; render with --quality master, and check a render made in a raea project to tell which")),
};
issues.push(Issue { rule: "blotching", p, at, says });
} else if seen > 0 {
@@ -223,15 +213,13 @@ pub(crate) fn contrast(video: &str, runs: &[Run], w: f64, h: f64, probe: &Probe,
continue;
}
// the same measure `raea world` joins to a text from its render (raea-sys-measure, DR2)
// each colour its words are drawn in (an accent word's beside the line's), held to the lowest
let measure = |color: &str| if crate::read::native() { crate::read::contrast(video, t, crop, color) } else { raea_sys_measure::contrast(std::path::Path::new(video), t, crop, color) };
let worst = r.middle_inks().into_iter().filter_map(|c| measure(c).map(|v| (v, c))).min_by(|a, b| a.0.total_cmp(&b.0));
let Some((ratio, color)) = worst else { continue };
let word = if color == r.middle_color() { String::new() } else { format!(" (its words in {color})") };
let color = r.middle_color();
let ratio = if crate::read::native() { crate::read::contrast(video, t, crop, color) } else { raea_sys_measure::contrast(std::path::Path::new(video), t, crop, color) };
let Some(ratio) = ratio else { continue };
measured += 1;
if ratio < 3.0 {
low += 1;
issues.push(Issue { rule: "contrast", p: 1, at: Some(t), says: format!("{}{word} is {:.2}:1 against what's behind it; make it at least 3:1 (a band, a shadow for separation, or another colour)", quote(&r.text), (ratio * 100.0).floor() / 100.0) });
issues.push(Issue { rule: "contrast", p: 1, at: Some(t), says: format!("{} is {ratio:.1}:1 against what's behind it; make it at least 3:1 (a band, a shadow for separation, or another colour)", quote(&r.text)) });
}
}
if measured > 0 && low == 0 {
+75
View File
@@ -0,0 +1,75 @@
//! `raea check EDIT.tsx --quick` (docs/skills.feature SK10). The quick check renders three stills of a composition (a
//! quarter in, the middle, the last frame, of the length frame 0's render reports) with their manifest, and runs the text rules
//! and the person's text taste on it: clipped and cramped text, safe areas, sizes. Every agent's after-save hook runs
//! it (hook.rs): after a .tsx that registers a root is saved, its findings go back to the agent; a clean check says
//! nothing.
use super::*;
use std::path::Path;
/// The stills' frames: a quarter in, the middle and the last of the length a render reports (render.json's `length`,
/// the composition's own however it's written; #86 read its source's `durationInFrames={N}` and took 90 for a name).
fn samples(m: &Value) -> Option<[u64; 3]> {
let n = m["length"].as_u64()?.max(1);
Some([n / 4, n / 2, n - 1])
}
/// `raea check EDIT.tsx --quick [--shape S] [--platform P] [-o check.json]`: (report, P0 or P1 found). `tastes` are the
/// person's, evaluated by the raea CLI when --taste names them.
pub fn quick(args: &[String], tastes: Vec<raea_core_brief::Taste>) -> R<(String, bool)> {
let file = args.iter().find(|a| a.ends_with(".tsx")).ok_or("raea check --quick takes a composition: EDIT.tsx")?;
let tmp = std::env::temp_dir().join(format!("raea-quick-{}", std::process::id()));
std::fs::create_dir_all(&tmp).map_err(|e| format!("{}: {e}", tmp.display()))?;
let manifest = tmp.join("render.json");
let me = std::env::current_exe().map_err(|e| e.to_string())?;
// the stills are part of this check, which keeps the one entry in the project's record (DR3)
let render = |at: &str| std::process::Command::new(&me).arg("render").arg(file).args(["--at", at, "-o"]).arg(format!("{}/", tmp.display())).arg("--manifest").arg(&manifest).env("RAEA_RECORD", "off").output().map_err(|e| e.to_string());
// frame 0 first, for the length (its manifest's), then the three stills
let mut out = render("0")?;
let at = std::fs::read_to_string(&manifest).ok().and_then(|t| samples(&serde_json::from_str(&t).ok()?));
if let Some(at) = at {
let _ = std::fs::remove_file(&manifest);
out = render(&at.map(|f| f.to_string()).join(","))?;
}
// rendered when its manifest was written: a render whose stills clip exits 1 (DR3), and those findings are read here
let result = if let (Some(at), true) = (at, manifest.is_file()) {
on_manifest(file, &manifest, args, tastes, at)
} else {
// a render that fails is the finding: the agent sees why
let (err, out) = (String::from_utf8_lossy(&out.stderr), String::from_utf8_lossy(&out.stdout));
let why: Vec<&str> = err.lines().chain(out.lines()).filter(|l| l.contains("REFUSED") || l.contains("rror")).collect();
let f = raea_core_facts::Finding::new("render", raea_core_facts::Level::Error, why.join("\n"), "raea check --quick");
Ok((format!("raea check {file}: it doesn't render\n{}\nraea check: {}", f.line(), raea_core_facts::finding::count(&[f])), true))
};
let _ = std::fs::remove_dir_all(&tmp);
result
}
/// `raea check --quick`'s half (docs/skills.feature SK10): the text rules and the person's text taste on the manifest
/// of a few stills (`raea render EDIT.tsx --at ... --manifest`), no video. What it can't see (contrast, freezes,
/// sound, blotching) waits for the full check on the export.
fn on_manifest(file: &str, manifest: &Path, args: &[String], tastes: Vec<raea_core_brief::Taste>, [a, b, c]: [u64; 3]) -> R<(String, bool)> {
let at = manifest.display();
let m: Value = serde_json::from_str(&std::fs::read_to_string(manifest).map_err(|e| format!("{at}: {e}"))?).map_err(|e| format!("{at}: {e}"))?;
let (mut issues, mut passed) = (Vec::new(), vec![format!("looked at frames {a}, {b} and {c} of {}", c + 1)]);
let runs = text_runs(&m);
let (w, h) = (m["width"].as_f64().unwrap_or(1080.0), m["height"].as_f64().unwrap_or(1920.0));
text_rules(&runs, None, w, h, flag(args, "--shape"), flag(args, "--platform"), &mut issues, &mut passed);
taste_text(&taste_rules(&tastes), &runs, w, h, &mut issues, &mut passed);
// and what the render of the stills found (the 3D's clipping, DR3)
let more = serde_json::from_value(m["findings"].clone()).unwrap_or_default();
report(file, issues, more, passed, flag(args, "-o"), m["fps"].as_f64().unwrap_or(30.0))
}
#[cfg(test)]
mod tests {
use serde_json::json;
/// the length is the render's, so a `durationInFrames={DUR}` (#86: 300 frames, read as 90) is sampled to its end
#[test]
fn frames_come_from_the_render() {
assert_eq!(super::samples(&json!({"length": 240})), Some([60, 120, 239]));
assert_eq!(super::samples(&json!({"length": 300})), Some([75, 150, 299]));
assert_eq!(super::samples(&json!({"length": 1})), Some([0, 0, 0]));
// a render that reported no length: no stills to look at, so the frame-0 render's failure is the finding
assert_eq!(super::samples(&json!({"width": 640})), None);
}
}
+13 -14
View File
@@ -22,7 +22,7 @@ fn a_placeholder_brand_kit_is_flagged() {
brand_kit(&["", video.to_str().unwrap()], &mut issues, &mut passed);
(issues.iter().map(|i| i.p).collect::<Vec<_>>(), passed.len())
};
assert_eq!(rules(Some(r#"{"domain":"acme.test","source":{"thin":["no font-family in its CSS"]}}"#)), (vec![2], 0));
assert_eq!(rules(Some(r#"{"domain":"acme.test","source":{"thin":["no font-family in its CSS"]}}"#)), (vec![1], 0));
assert_eq!(rules(Some(r#"{"domain":"acme.test","source":{"thin":["x"],"by_hand":{"palette.accent":"hero button"}}}"#)), (vec![], 1));
assert_eq!(rules(Some(r#"{"domain":"acme.test","source":{"thin":[]}}"#)), (vec![], 1));
assert_eq!(rules(None), (vec![2], 0));
@@ -51,10 +51,6 @@ fn flat_dark_is_clean_and_stepped_dark_is_blotchy() {
(20.0 - (x * x + y * y).sqrt() / 24.0).max(6.0) as u8
}).collect();
assert!(blotch_score(&rings, w, h).unwrap() < BLOTCHY / 2.0);
// a cause that can't be told: an error only past an encoder's measured blotching, on more than a fifth of samples
assert_eq!(untold_level(1.0, 0.010), 2);
assert_eq!(untold_level(1.0, 0.09), 1);
assert_eq!(untold_level(0.1, 0.09), 2);
assert_eq!(x264_crf(b"..\x05x264 - core 165 r3222 - H.264/MPEG-4 AVC codec - options: cabac=1 rc=crf mbtree=1 crf=12.0 qcomp=0.60"), Some(12.0));
assert_eq!(x264_crf(b"Lavf61 VideoToolbox"), None);
}
@@ -71,8 +67,8 @@ fn taste_checks_hold_text_to_the_persons_line() {
Taste { form: "text-above", value: 62.0, line: "Captions sit clear of the bottom.".into() },
Taste { form: "text-hold", value: 2.0, line: "Text holds two seconds".into() },
]);
let low = Run { text: "Render anything.".into(), from: 1.0, to: 4.0, box_: [800.0, 800.0, 300.0, 60.0], boxes: vec![[800.0, 800.0, 300.0, 60.0]], colors: vec![], inks: vec![], color: String::new(), size: 48.0 };
let high = Run { text: "raea".into(), from: 5.0, to: 6.0, box_: [800.0, 300.0, 300.0, 60.0], boxes: vec![[800.0, 300.0, 300.0, 60.0]], colors: vec![], inks: vec![], color: String::new(), size: 48.0 };
let low = Run { text: "Render anything.".into(), from: 1.0, to: 4.0, box_: [800.0, 800.0, 300.0, 60.0], boxes: vec![[800.0, 800.0, 300.0, 60.0]], colors: vec![], color: String::new(), size: 48.0 };
let high = Run { text: "raea".into(), from: 5.0, to: 6.0, box_: [800.0, 300.0, 300.0, 60.0], boxes: vec![[800.0, 300.0, 300.0, 60.0]], colors: vec![], color: String::new(), size: 48.0 };
let (mut issues, mut passed) = (vec![], vec![]);
taste_text(&rules, &[low, high], 1920.0, 1080.0, &mut issues, &mut passed);
let says: Vec<_> = issues.iter().map(|i| (i.rule, i.p, i.at)).collect();
@@ -189,14 +185,15 @@ fn a_bed_close_under_the_voice_and_a_loud_stretch_without_it_are_found() {
}
#[test]
fn placement_states_the_zones_check_measures() {
// zones() is where the numbers live; placement.md says them in words, held to it here
fn the_floor_and_placement_state_the_zones_check_measures() {
// zones() is where the numbers live; floor.md and placement.md say them in words, held to it here
let words = |t: &str| t.split_whitespace().collect::<Vec<_>>().join(" ");
let floor = words(include_str!("../../../sdk/guides/craft/floor.md"));
let placement = words(include_str!("../../../sdk/guides/craft/motion/placement.md"));
let n = |v: f64| format!("{v:.0}");
let [t, r, b, l] = zones(1080.0, 1920.0, Some("9:16"), None);
let said = [
format!("that is top {}, bottom {}, right {} and left {} px at 1080 wide", n(t), n(b), n(r), n(l)),
format!("keep the top {} px, the bottom {}, the right {} and the left {} clear", n(t), n(b), n(r), n(l)),
["tiktok", "reels", "shorts"].map(|p| {
let [t, r, b, _] = zones(1080.0, 1920.0, Some("9:16"), Some(p));
let name = match p { "tiktok" => "TikTok", "reels" => "Reels", _ => "Shorts" };
@@ -207,8 +204,10 @@ fn placement_states_the_zones_check_measures() {
{ let [t, r, b, l] = zones(1920.0, 1080.0, Some("16:9"), None); assert!(t == b && r == l); format!("16:9 top and bottom {}, sides {}", n(t), n(r)) },
];
for s in &said {
assert!(placement.contains(s.as_str()), "placement.md doesn't say {s:?}");
assert!(floor.contains(s.as_str()), "floor.md doesn't say {s:?}");
}
let s = format!("that is top {}, bottom {}, right {} and left {} px at 1080 wide", n(t), n(b), n(r), n(l));
assert!(placement.contains(&s), "placement.md doesn't say {s:?}");
}
#[test]
@@ -268,7 +267,7 @@ fn typing_is_one_run_and_cues_find_their_word() {
#[test]
fn a_caption_is_timed_from_the_first_word_it_shows() {
let run = |text: &str, from: f64| Run { text: text.into(), from, to: from + 1.0, box_: [0.0; 4], boxes: vec![], colors: vec![], inks: vec![], color: String::new(), size: 48.0 };
let run = |text: &str, from: f64| Run { text: text.into(), from, to: from + 1.0, box_: [0.0; 4], boxes: vec![], colors: vec![], color: String::new(), size: 48.0 };
let words: Vec<Word> = [("half", 12.2), ("of", 12.66), ("the", 12.8), ("spend", 12.96)].iter().map(|(t, s)| Word { text: (*t).into(), start: *s, end: *s }).collect();
let (mut issues, mut passed) = (vec![], vec![]);
// on with "of": on time, though "spend" (its first word of weight) is said 0.3 s later
@@ -336,7 +335,7 @@ fn safe_area_tests_the_letters_not_the_box() {
#[test]
fn a_card_sharing_one_word_with_another_line_isnt_held_to_it() {
let run = |text: &str, from: f64| Run { text: text.into(), from, to: from + 2.0, box_: [0.0; 4], boxes: vec![], colors: vec![], inks: vec![], color: String::new(), size: 48.0 };
let run = |text: &str, from: f64| Run { text: text.into(), from, to: from + 2.0, box_: [0.0; 4], boxes: vec![], colors: vec![], color: String::new(), size: 48.0 };
let said = |ws: &[(&str, f64)]| ws.iter().map(|(t, s)| Word { text: (*t).into(), start: *s, end: *s }).collect::<Vec<Word>>();
let words = said(&[("at", 37.9), ("wirestock", 38.2), ("i", 38.9), ("worked", 39.0), ("on", 39.2), ("a", 39.3), ("sora", 39.5), ("campaign", 40.2)]);
let (mut issues, mut passed) = (vec![], vec![]);
@@ -426,7 +425,7 @@ fn things_found_are_findings_and_an_unknown_rule_is_not() {
#[test]
fn a_moving_text_is_read_where_it_is() {
let ink = |f: usize| [56.7 + 4.0 * f as f64, 1000.0, 26.7, 40.0];
let run = Run { text: "E".into(), from: 0.0, to: 8.0, box_: [996.0, 1000.0, 60.0, 40.0], boxes: (0..240).map(ink).collect(), colors: vec![], inks: vec![], color: String::new(), size: 40.0 };
let run = Run { text: "E".into(), from: 0.0, to: 8.0, box_: [996.0, 1000.0, 60.0, 40.0], boxes: (0..240).map(ink).collect(), colors: vec![], color: String::new(), size: 40.0 };
let (t, b) = run.middle(30.0);
assert_eq!(t, 4.0);
assert!((b[0] - 520.0).abs() < 1e-9 && b[1..] == [1000.0, 60.0, 40.0], "{b:?}");
+5 -40
View File
@@ -46,9 +46,6 @@ pub struct Run {
/// its colour on each of those frames, beside `boxes`: a text can change colour while it reads the same (a step
/// chip lighting up, grey on dark to dark on yellow), and its contrast is its colour on the frame it's measured at
pub colors: Vec<String>,
/// the colours its words are drawn in on each of those frames, beside `colors`, when any differs from the line's (the
/// manifest's `inks`: a caption's accent word); empty when every word is in the line's colour
pub inks: Vec<Vec<String>>,
/// its colour on its last frame
pub color: String,
pub size: f64,
@@ -73,27 +70,11 @@ impl Run {
_ => &self.color,
}
}
/// Every colour its words are drawn in on that frame: the line's, and an accent span's beside it (12-06: a line
/// recorded only by its own colour hid a dark word on a dark plate)
pub fn middle_inks(&self) -> Vec<&str> {
let n = self.boxes.len();
let mut all = vec![self.middle_color()];
let at = if n > 1 && self.inks.len() == n { self.inks.get(n / 2) } else { self.inks.last() };
for i in at.into_iter().flatten() {
if !all.contains(&i.as_str()) {
all.push(i);
}
}
all
}
}
/// The brand kit the cut was styled from (brand/ at or above the manifest's or the video's folder, as render finds
/// brand.css): a kit `raea brand` read from a thin fetch that nobody corrected by hand is a placeholder, and a brand.css
/// with no brand.json beside it wasn't read from the brand at all, both P2: where a kit came from is a note for the person
/// at sign-off, not a fault in the cut (12-05, run 39: all four of Body Shop's cuts held an error for a fetch of the
/// brand's site that read 40 of its 95 colour and face variables)
/// brand.css): a kit `raea brand` read from a thin fetch that nobody corrected by hand is a placeholder, P1; a brand.css
/// with no brand.json beside it wasn't read from the brand at all, P2
pub fn brand_kit(near: &[&str], issues: &mut Vec<Issue>, passed: &mut Vec<String>) {
let mut seen = std::collections::HashSet::new();
for start in near.iter().filter(|p| !p.is_empty()) {
@@ -114,7 +95,7 @@ pub fn brand_kit(near: &[&str], issues: &mut Vec<Issue>, passed: &mut Vec<String
let thin: Vec<&str> = kit["source"]["thin"].as_array().map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default();
let by_hand = kit["source"]["by_hand"].as_object().is_some_and(|o| !o.is_empty());
if !thin.is_empty() && !by_hand {
issues.push(Issue { rule: "brand", p: 2, at: None, says: format!("styled from a placeholder kit: raea brand's fetch of {} was thin ({}) and nothing in brand.json's source.by_hand says it was checked; read the live site in a browser and fix the kit (raea guide brand, \"When the fetch was thin\")", kit["domain"].as_str().unwrap_or("the site"), thin.join("; ")) });
issues.push(Issue { rule: "brand", p: 1, at: None, says: format!("styled from a placeholder kit: raea brand's fetch of {} was thin ({}) and nothing in brand.json's source.by_hand says it was checked; read the live site in a browser and fix the kit (raea guide brand, \"When the fetch was thin\")", kit["domain"].as_str().unwrap_or("the site"), thin.join("; ")) });
} else {
passed.push(format!("brand: the cut is styled from {}'s kit{}", kit["domain"].as_str().unwrap_or("the brand"), if by_hand { ", checked by hand" } else { "" }));
}
@@ -146,21 +127,18 @@ pub fn text_runs(manifest: &Value) -> Vec<Run> {
});
let mut r = match found {
Some(i) => open.remove(i),
None => Run { text: text.clone(), from: t, to: t, box_: b, boxes: Vec::new(), colors: Vec::new(), inks: Vec::new(), color: String::new(), size: 0.0 },
None => Run { text: text.clone(), from: t, to: t, box_: b, boxes: Vec::new(), colors: Vec::new(), color: String::new(), size: 0.0 },
};
let color = x["color"].as_str().unwrap_or("rgb(255, 255, 255)").to_string();
let inks: Vec<String> = x["inks"].as_array().map(|a| a.iter().filter_map(Value::as_str).map(String::from).collect()).unwrap_or_default();
if text.len() > r.text.len() {
r.boxes.clear();
r.colors.clear();
r.inks.clear();
}
if text.len() >= r.text.len() {
r.text = text;
r.box_ = b;
r.boxes.push(ink.unwrap_or(b));
r.colors.push(color.clone());
r.inks.push(inks);
}
r.to = t + 1.0 / fps;
r.color = color;
@@ -218,7 +196,7 @@ pub fn face_cover(runs: &[Run], faces: &[(f64, f64, [f64; 4])], issues: &mut Vec
/// 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/motion/placement.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] {
let r = w / h;
let shape = shape.unwrap_or(if r < 0.7 { "9:16" } else if r < 0.9 { "4:5" } else if r < 1.2 { "1:1" } else { "16:9" });
@@ -368,17 +346,4 @@ mod tests {
assert_eq!(runs[0].color, "rgb(10, 10, 11)", "its last colour");
assert_eq!(runs[0].middle_color(), "rgb(169, 169, 174)", "the frame contrast measures is still grey");
}
#[test]
fn a_line_with_an_accent_word_is_measured_in_both_colours() {
// a white caption with one word in dark red: the manifest's line colour alone hid the red word
let m = json!({"fps": 10.0, "frames": (0..4).map(|f| json!({"frame": f, "text": [
{"text": "Stay out longer.", "box": [100, 1400, 880, 90], "size": 84, "color": "rgb(255, 255, 255)", "inks": ["rgb(255, 255, 255)", "rgb(120, 0, 0)"]}
]})).collect::<Vec<_>>()});
let runs = text_runs(&m);
assert_eq!(runs[0].middle_inks(), vec!["rgb(255, 255, 255)", "rgb(120, 0, 0)"]);
// a line drawn in its own colour only has no inks, and is measured in that colour alone
let plain = json!({"fps": 10.0, "frames": [{"frame": 0, "text": [{"text": "raea", "box": [0, 0, 10, 10], "size": 40, "color": "rgb(1, 2, 3)"}]}]});
assert_eq!(text_runs(&plain)[0].middle_inks(), vec!["rgb(1, 2, 3)"]);
}
}
+2 -2
View File
@@ -18,10 +18,10 @@ use crate::ts;
type R<T> = Result<T, String>;
pub const USAGE: &str = "raea check [PROJECT|EDIT.tsx] [--composition ID] [--only ID] [--render OUT | --no-render] [--json] (every check that applies to each composition, over its frames: raea's floor on its newest render, the person's, the workspace's and the project's taste.ts (each line's check: one of raea's forms or checks by name, or a project's .ts check); what needs a render and has none waits, and says so)";
pub const USAGE: &str = "raea check [PROJECT|EDIT.tsx] [--composition ID] [--only ID] [--taste T] [--render OUT | --no-render] [--json] (every check that applies to each composition, over its frames: raea's floor on its newest render, the person's, the workspace's and the project's taste.ts (each line's check: one of raea's forms or checks by name, or a project's .ts check); what needs a render and has none waits, and says so)";
/// The flags raea check takes with a value (its own, and the floor's on a video).
const TAKES: [&str; 9] = ["--composition", "--only", "--render", "--manifest", "--words", "--perception", "--shape", "--platform", "-o"];
const TAKES: [&str; 10] = ["--composition", "--only", "--taste", "--render", "--manifest", "--words", "--perception", "--shape", "--platform", "-o"];
/// What the CLI lends `raea check`: its TS evaluator and headless run, and the taste kinds a mode needs (as `raea
/// context` reads the person's taste).
+1 -1
View File
@@ -61,7 +61,7 @@ pub fn rendered(args: &[String]) -> i32 {
let _ = std::fs::write(&m, v.to_string());
}
}
// a render that is part of another (a review's tiles) leaves the entry to that one
// a render that is part of another (a review's tiles, a quick check's stills) leaves the entry to that one
let file = args.get(1).filter(|a| !a.starts_with('-') && std::env::var("RAEA_RECORD").as_deref() != Ok("off")).map(PathBuf::from);
if let Some(e) = file.and_then(|f| record::keep("raea render", &f, out.as_deref(), &found, excused, &raea_io_trace::utc(SystemTime::now()).1)) {
println!("raea render: kept in the project's record as {} (raea findings reads it)", e.id);
+1 -1
View File
@@ -35,7 +35,7 @@ pub struct Double {
pub problem: Option<f64>,
/// clef agrees: past even odds, or past the question's threshold once the person's labels calibrated it
pub agrees: Option<bool>,
/// its answer's id in the ask record (~/.raea/ask/answers.jsonl)
/// its answer's id in raea ask's record, for `raea ask verdict`
pub answer: Option<String>,
/// why it wasn't asked or still waits
pub not_asked: Option<String>,
+1 -1
View File
@@ -21,7 +21,7 @@ use std::path::Path;
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 | 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, for a person to look at; --json prints it as 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)
pub type Eval = fn(&Path) -> Result<String, String>;
+18
View File
@@ -0,0 +1,18 @@
[package]
name = "raea-app-judge"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "raea judge: a review's sheets judged by clef-omni on a frozen rubric, the pass decided in code, calibrated against the person's eye before it gates"
[dependencies]
dunce = "1"
raea-io-home = { path = "../../io/home" }
# what a judge saw, as raea's one Finding (docs/direction.feature DR3)
raea-core-facts = { path = "../../core/facts" }
serde_json = "1"
raea-runtime-bundle = { path = "../../runtime/bundle" }
# the one clef client: the question format and the call, routed to the person's plan first (docs/ask.feature AK1b)
raea-core-ask = { path = "../../core/ask" }
raea-io-clef = { path = "../../io/clef" }
+139
View File
@@ -0,0 +1,139 @@
//! A judge that is an agent rather than clef-omni (Shane, 11-06: an agent as the judge; 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 it (raea
//! 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
//! look at, given the fresh-context judge prompt (sdk/guides/craft/bevy/prompts.md section 3) and never the code or
//! 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.
use std::path::Path;
use serde_json::{Map, Value, json};
use crate::rubric::{BAR, scores};
/// 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
/// own categories and the bar (docs/goal.feature MK5); none asks the rubric raea judge has always asked.
pub fn prompt(kind: Option<&str>, dir: &Path, brief: &Value, target: Option<&Path>) -> String {
match kind {
None => prompt_default(dir, brief, target),
Some(k) => prompt_kind(k, dir, brief, target),
}
}
fn brief_words(brief: &Value) -> String {
["look", "logline", "notDoing"].iter().filter_map(|k| brief.get(*k).map(|v| format!("{k}: {}", v.as_str().map(str::to_string).unwrap_or_else(|| v.to_string())))).collect::<Vec<_>>().join("; ")
}
fn prompt_kind(kind: &str, dir: &Path, brief: &Value, target: Option<&Path>) -> String {
let words = brief_words(brief);
let target = target.map(|t| format!(" The reference, what it must read as, is {}.", t.display())).unwrap_or_default();
let d = dir.display();
let sheets = match kind {
"shot" => format!("This round's sheet: {d}/framing.png. Each row is one shot: its first, middle and last frame, left to right, each stamped with its name and time. Open it."),
_ => format!(
"This round's sheets: {d}/colour.png and {d}/clay.png, each six tiles, left to right, top to bottom: hero, front, right, top, iso, low (0.3 m off the floor). Clay is every surface light grey and matte. Open both{}.",
if kind == "kit" { "; the scene is the kit's lineup, its props side by side with a scale bar" } else { "" }
),
};
let blind = if kind == "shot" {
String::new()
} else {
format!("PART 1, BLIND: open {d}/hero-colour.png first, one frame. In one sentence: what is this, what era? List five objects you can name. Is it a photograph or a render, and which three tells decided it?\n\n")
};
let cats: String = scores(Some(kind)).iter().map(|(k, on, ask)| format!("- {k}{}: {}\n", if *on == "clay" { " (judged on CLAY)" } else { "" }, ask.split_once(": ").map(|(_, r)| r).unwrap_or(ask))).collect();
let json_scores = scores(Some(kind)).iter().map(|(k, _, _)| format!("\"{k}\": 0")).collect::<Vec<_>>().join(", ");
format!(
"You review a {kind} 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. Only look at images; change no file.\n\n{blind}\
PART 2, SCORED. The brief: \"{words}\".{target} {sheets}\n\n\
Score each 0-10 (5 = a believable draft; 7 = a production base an artist would accept; 9 = indistinguishable from real). Halves are allowed.\n{cats}\n\
{BAR} Each defect field is one short sentence; \"blocking\" means someone using this would notice it where it will be seen. \
Name exactly what gives it away (not \"the phone looks fake\" but \"the handset is fused to the cradle with no gap\").\n\n\
End your answer with only this JSON, nothing after it:\n\
{{\"blind\": {{\"place\": \"\", \"objects\": [], \"photo\": \"yes|no\", \"tells\": []}}, \
\"scores\": {{{json_scores}}}, \
\"defects\": [{{\"tile\": \"\", \"where\": \"\", \"wrong\": \"\", \"real\": \"\", \"fix\": \"\", \"level\": \"blocking|detail\"}}], \
\"show_as_is\": \"\"}}"
)
}
fn prompt_default(dir: &Path, brief: &Value, target: Option<&Path>) -> String {
let words = brief_words(brief);
let target = target.map(|t| format!(" The target picture, what it must read as, is {}.", t.display())).unwrap_or_default();
format!(
"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. Only look at images; change no file.\n\n\
PART 1, BLIND: open {d}/hero-colour.png first, 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?\n\n\
PART 2, SCORED. The brief: \"{words}\".{target} This round's sheets: {d}/colour.png and {d}/clay.png, each six tiles, left to right, top to bottom: \
hero, front, right, top, iso, low (0.3 m off the floor). Clay is every surface light grey and matte. Open both.\n\n\
Score each 0-10 (5 = a believable draft; 7 = a production base an artist would accept; 9 = indistinguishable from real). Halves are allowed.\n\
- composition: camera, framing, layout, the position and scale of every major object.\n\
- 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.\n\
- assembly, judged on CLAY first: nothing floats, sinks, pokes through or rests on the wrong thing; joints touch; the low tile shows the feet.\n\
- materials: every surface reads as its real material, with wear where use puts it; nothing a flat default colour.\n\
- light: motivated by the place's own sources; exposure and contrast believable.\n\
- detail: close views hold real geometry or texture, not a smooth stand-in; printed matter reads.\n\
- world: one coherent real place; nothing off-era or invented beyond the brief.\n\n\
Then list the defects, most damaging first: at most 8, each field one short sentence. \"blocking\" means someone using this scene would notice it in the views it will be seen in. \
Name exactly what gives it away (not \"the dryer looks fake\" but \"the dryer door is a flat disc with no rim or glass depth\").\n\n\
End your answer with only this JSON, nothing after it:\n\
{{\"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\": \"\"}}",
d = dir.display()
)
}
/// The last JSON object in the text that has scores (an agent may think aloud, or draft the JSON twice).
pub fn last_verdict(text: &str) -> Option<Value> {
let starts: Vec<usize> = text.match_indices('{').map(|(i, _)| i).collect();
for &s in starts.iter().rev() {
let mut de = serde_json::Deserializer::from_str(&text[s..]).into_iter::<Value>();
if let Some(Ok(v)) = de.next()
&& v.get("scores").is_some_and(Value::is_object)
{
return Some(v);
}
}
None
}
/// The verdict read into the judge's own shape: scores (0-10, the kind's categories), defects (present, level, named
/// by what is wrong), the blind read's photo (1 a photo, 0 a render) and the agent's own words.
pub fn read(kind: Option<&str>, v: &Value) -> (Map<String, Value>, Vec<Value>, Value) {
let mut out = Map::new();
for &(k, _, _) in scores(kind) {
if let Some(x) = v["scores"][k].as_f64().filter(|x| (0.0..=10.0).contains(x)) {
out.insert(k.into(), json!(x));
}
}
let defects = v["defects"].as_array().into_iter().flatten().filter(|d| d["wrong"].as_str().is_some_and(|w| !w.trim().is_empty())).map(|d| {
let level = if d["level"].as_str().unwrap_or("").starts_with("block") { "blocking" } else { "detail" };
let wrong = d["wrong"].as_str().unwrap_or("");
json!({"defect": wrong.chars().take(80).collect::<String>(), "present": true, "level": level, "sheet": d["tile"], "asked": wrong,
"where": d["where"], "real": d["real"], "fix": d["fix"]})
}).collect();
let photo = match v["blind"]["photo"].as_str() {
Some(p) if p.starts_with('y') => json!(1.0),
Some(p) if p.starts_with('n') => json!(0.0),
_ => Value::Null,
};
(out, defects, photo)
}
/// One fresh judging session of this project's own agent over DIR's sheets, through the host (RAEA_JUDGE_URL): its
/// verdict JSON.
pub fn ask(kind: Option<&str>, dir: &Path, brief: &Value, target: Option<&Path>) -> Result<Value, String> {
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 text = raea_io_clef::critic::ask(&dir, &prompt(kind, &dir, brief, target)).map_err(|e| format!("judge: {e}"))?;
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>()))
}
+169
View File
@@ -0,0 +1,169 @@
//! Shane's eye, the judge's calibration. `raea judge eye DIR form=5 light=7 ... [--pass yes|no]` records his scores for a
//! round the judge has already judged (DIR/judge.json), with the judge's raw scores beside them, in
//! ~/.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
//! 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 --read` records a
//! fresh agent session's reading instead (Shane, 11-06), each row saying whose eye it is.
use std::path::PathBuf;
use serde_json::{Map, Value, json};
use crate::rubric::{pass_for, scores};
fn home() -> PathBuf {
raea_io_home::env_path("RAEA_JUDGE_DIR", ".raea/judge")
}
/// A kind's calibration file: calibration.json for the default rubric, calibration.KIND.json for a `raea make` kind's
/// (docs/goal.feature MK6), each fitted on that kind's rounds alone.
fn file_of(kind: Option<&str>) -> PathBuf {
home().join(kind.map_or_else(|| "calibration.json".to_string(), |k| format!("calibration.{k}.json")))
}
/// The calibration in force for a kind, if one was made.
pub fn calibration(kind: Option<&str>) -> Option<Value> {
serde_json::from_str(&std::fs::read_to_string(file_of(kind)).ok()?).ok()
}
/// A row's or a verdict's kind: none for the default rubric.
fn kind_in(v: &Value) -> Option<&str> {
v["kind"].as_str()
}
/// The judge's scores mapped through the calibration's lines, kept to 0-10.
pub fn apply(c: &Value, scores: &mut Map<String, Value>) {
for (k, v) in scores.iter_mut() {
if let (Some(x), Some(a), Some(b)) = (v.as_f64(), c["maps"][k]["a"].as_f64(), c["maps"][k]["b"].as_f64()) {
*v = json!(((a * x + b).clamp(0.0, 10.0) * 100.0).round() / 100.0);
}
}
}
pub fn record(args: &[String]) -> Result<String, String> {
let dir = args.get(2).map(PathBuf::from).ok_or("raea judge eye DIR CATEGORY=SCORE... [--pass yes|no]")?;
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 cats = scores(kind);
// 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 args.iter().any(|a| a == "--read") {
let by = "agent";
let v = crate::agent::ask(kind, &dir, &json!({}), None)?;
let (eye, defects, _) = crate::agent::read(kind, &v);
if eye.len() < cats.len() {
return Err(format!("judge eye: {by} scored only {} of {} categories", eye.len(), cats.len()));
}
let eye_pass = pass_for(kind, &eye, &defects).0;
let row = json!({"dir": verdict["dir"], "kind": kind, "by": by, "judge": verdict["raw"], "judge_pass": verdict["pass"], "defects": verdict["defects"], "eye": eye, "eye_pass": eye_pass, "eye_defects": defects});
append(&row)?;
let shown: Vec<String> = eye.iter().map(|(k, v)| format!("{k} {v}")).collect();
return Ok(format!("APPLIED {by}'s eye on {} recorded ({}): {}; raea judge calibrate fits clef to it", dir.display(), if eye_pass { "a pass" } else { "not yet" }, shown.join(", ")));
}
let mut eye = Map::new();
let mut said_pass = None;
let mut i = 3;
while i < args.len() {
if args[i] == "--pass" {
said_pass = Some(matches!(args.get(i + 1).map(String::as_str), Some("yes" | "true" | "y")));
i += 2;
continue;
}
let (k, v) = args[i].split_once('=').ok_or_else(|| format!("judge eye: {:?} isn't CATEGORY=SCORE", args[i]))?;
if !cats.iter().any(|s| s.0 == k) {
return Err(format!("judge eye: no category {k}: {}", cats.iter().map(|s| s.0).collect::<Vec<_>>().join(", ")));
}
let x: f64 = v.parse().ok().filter(|x| (0.0..=10.0).contains(x)).ok_or_else(|| format!("judge eye: {k} is a score 0-10, got {v:?}"))?;
eye.insert(k.into(), json!(x));
i += 1;
}
if eye.is_empty() {
return Err("judge eye: give your scores, e.g. composition=6 form=5 assembly=7 materials=4 light=6 detail=5 world=6".into());
}
// his pass: as he says it, else the same rule on his scores with the judge's defects
let eye_pass = said_pass.unwrap_or_else(|| pass_for(kind, &eye, verdict["defects"].as_array().map(Vec::as_slice).unwrap_or(&[])).0);
let row = json!({"dir": verdict["dir"], "kind": kind, "by": "shane", "judge": verdict["raw"], "judge_pass": verdict["pass"], "defects": verdict["defects"], "eye": eye, "eye_pass": eye_pass});
append(&row)?;
Ok(format!("APPLIED your eye on {} recorded ({}): raea judge calibrate fits the judge to it", dir.display(), if eye_pass { "a pass" } else { "not yet" }))
}
/// One eye row onto ~/.raea/judge/eye.jsonl; a newer reading of the same round by the same eye replaces the older.
fn append(row: &Value) -> Result<(), String> {
std::fs::create_dir_all(home()).map_err(|e| e.to_string())?;
let path = home().join("eye.jsonl");
let mut rows: Vec<Value> = std::fs::read_to_string(&path).unwrap_or_default().lines().filter_map(|l| serde_json::from_str(l).ok()).filter(|r: &Value| !(r["dir"] == row["dir"] && whose(r) == whose(&row))).collect();
rows.push(row.clone());
std::fs::write(&path, rows.iter().map(Value::to_string).collect::<Vec<_>>().join("\n") + "\n").map_err(|e| e.to_string())
}
/// Least squares y = a x + b; flat x (one value) maps by the mean offset.
fn fit(xy: &[(f64, f64)]) -> (f64, f64) {
let n = xy.len() as f64;
let (mx, my) = (xy.iter().map(|p| p.0).sum::<f64>() / n, xy.iter().map(|p| p.1).sum::<f64>() / n);
let sxx: f64 = xy.iter().map(|p| (p.0 - mx).powi(2)).sum();
if sxx < 1e-9 {
return (1.0, my - mx);
}
let a = xy.iter().map(|p| (p.0 - mx) * (p.1 - my)).sum::<f64>() / sxx;
(a, my - a * mx)
}
/// The fit over a kind's rows of {judge, eye, defects, eye_pass} (none: the default rubric's): per-category maps and
/// errors, and the pass agreement.
pub fn fit_rows_for(kind: Option<&str>, rows: &[Value]) -> Value {
let mut maps = Map::new();
for &(k, _, _) in scores(kind) {
let xy: Vec<(f64, f64)> = rows.iter().filter_map(|r| Some((r["judge"][k].as_f64()?, r["eye"][k].as_f64()?))).collect();
if xy.len() < 2 {
continue;
}
let (a, b) = fit(&xy);
let mae = |f: &dyn Fn(f64) -> f64| xy.iter().map(|(x, y)| (f(*x) - y).abs()).sum::<f64>() / xy.len() as f64;
let r2 = |x: f64| (x * 1000.0).round() / 1000.0;
maps.insert(k.into(), json!({"a": r2(a), "b": r2(b), "n": xy.len(), "maeRaw": r2(mae(&|x| x)), "maeMapped": r2(mae(&|x| (a * x + b).clamp(0.0, 10.0)))}));
}
let cal = json!({"maps": maps});
let mut agree = 0;
for r in rows {
let mut s = r["judge"].as_object().cloned().unwrap_or_default();
apply(&cal, &mut s);
let p = pass_for(kind, &s, r["defects"].as_array().map(Vec::as_slice).unwrap_or(&[])).0;
if Value::Bool(p) == r["eye_pass"] {
agree += 1;
}
}
let n = rows.len();
let agreement = if n == 0 { 0.0 } else { agree as f64 / n as f64 };
// agreement means something only when the eye passed some rounds and failed others: all fails agree trivially
let passes = rows.iter().filter(|r| r["eye_pass"] == true).count();
let both = passes > 0 && passes < n;
json!({"maps": maps, "rounds": n, "eyePasses": passes, "agreement": (agreement * 1000.0).round() / 1000.0, "gate": n >= 10 && agreement >= 0.8 && both})
}
pub fn calibrate(args: &[String]) -> Result<String, String> {
let kind = crate::kind_of(args)?;
let kind = kind.as_deref();
let rows: Vec<Value> = std::fs::read_to_string(home().join("eye.jsonl")).unwrap_or_default().lines().filter_map(|l| serde_json::from_str(l).ok()).filter(|r: &Value| kind_in(r) == kind).collect();
if rows.is_empty() {
let k = kind.map(|k| format!(" of a {k}")).unwrap_or_default();
return Err(format!("judge calibrate: no rounds{k} with your eye yet (raea judge eye DIR form=5 ...)"));
}
let mut cal = fit_rows_for(kind, &rows);
cal["kind"] = json!(kind);
let mut eyes: Vec<String> = rows.iter().map(whose).map(str::to_string).collect();
eyes.sort();
eyes.dedup();
cal["eyes"] = json!(eyes);
std::fs::write(file_of(kind), serde_json::to_string_pretty(&cal).unwrap_or_default()).map_err(|e| e.to_string())?;
if args.iter().any(|a| a == "--json") {
return Ok(serde_json::to_string_pretty(&cal).unwrap_or_default());
}
let mut t: Vec<String> = cal["maps"].as_object().into_iter().flatten().map(|(k, m)| format!("{k:<12} eye = {} x judge {:+} (off by {} raw, {} mapped, {} rounds)", m["a"], m["b"], m["maeRaw"], m["maeMapped"], m["n"])).collect();
t.push(format!("agreement on the pass: {} over {} rounds (eyes: {}); {}", cal["agreement"], cal["rounds"], eyes.join(", "), if cal["gate"] == true { "the judge gates now".to_string() } else if cal["rounds"].as_u64() >= Some(10) && cal["agreement"].as_f64() >= Some(0.8) { format!("advice only: the eye passed {} of {} rounds, and agreement means something only with passes and fails both (judge a scene that is good)", cal["eyePasses"], cal["rounds"]) } else { "advice only until 10 rounds agree 8 in 10, with passes and fails both".to_string() }));
Ok(t.join("\n"))
}
/// Whose eye a row records: Shane's when it doesn't say.
fn whose(r: &Value) -> &str {
r["by"].as_str().unwrap_or("shane")
}
+236
View File
@@ -0,0 +1,236 @@
//! `raea judge`: a review's sheets (`raea render --review DIR`) judged by clef-omni on the frozen rubric (rubric.rs),
//! 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.
//!
//! 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 --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]
//!
//! `--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,
//! with the bar AnyKit's critic is given; each kind is calibrated on its own rounds (MK6).
//!
//! DIR/judge.json is the verdict; DIR's parent's judge.log.jsonl holds every round's, so "done" (two passes in a row,
//! each a fresh call) and the stall (the mean up by less than a point over two rounds) are read from it.
mod agent;
mod eye;
/// Whether the judge's score gates a `raea make` kind's jobs: its calibration (`raea judge calibrate --kind KIND`)
/// agreed with the person's eye (docs/goal.feature MK6).
pub fn kind_gates(kind: &str) -> bool {
eye::calibration(Some(kind)).is_some_and(|c| c["gate"] == true)
}
pub mod rubric;
use std::path::{Path, PathBuf};
use raea_core_facts::{Finding, Level, finding};
use raea_runtime_bundle::flag;
use serde_json::{Value, json};
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).
pub fn kind_of(args: &[String]) -> Result<Option<String>, String> {
match flag(args, "--kind") {
None => Ok(None),
Some(k) if rubric::KINDS.contains(&k.as_str()) => Ok(Some(k)),
Some(k) => Err(format!("judge: --kind {k}: the kinds are {}", rubric::KINDS.join(", "))),
}
}
/// One call through raea's one clef client (raea-io-clef: the person's plan first, then their own Cloudflare keys),
/// with the rubric's questions as written and each sheet as a JPEG still.
fn ask(state: &str, questions: &Value, images: &[PathBuf]) -> Result<(Value, f64), String> {
let qs = questions.as_object().ok_or("judge: the questions aren't a map")?;
let questions = qs.iter().map(|(id, w)| raea_core_ask::Question::from_wire(id, w).ok_or(format!("judge: {id} isn't one of clef's question types"))).collect::<Result<_, _>>()?;
let stills = images.iter().map(|p| raea_io_clef::media::still(p, None)).collect::<Result<_, _>>()?;
let call = raea_io_clef::Call { state: state.into(), questions, media: raea_io_clef::Media { stills, ..Default::default() } };
let a = raea_io_clef::ask(&call).map_err(|f| f.to_string())?;
Ok((Value::Object(a.answers), a.cost))
}
/// The brief's words, from `raea spec brief.ts --as brief` (look, logline, notDoing), or nothing.
fn brief_of(path: Option<&str>) -> Result<Value, String> {
let Some(p) = path else { return Ok(json!({})) };
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
let out = std::process::Command::new(exe).args(["spec", p, "--as", "brief"]).output().map_err(|e| e.to_string())?;
let text = String::from_utf8_lossy(&out.stdout);
let start = text.find('{').ok_or_else(|| format!("judge: {p} didn't read as a brief: {}", why_refused(&out)))?;
let v: Value = serde_json::from_str(&text[start..]).map_err(|e| format!("judge: {p}: {e}"))?;
Ok(v.get("brief").cloned().unwrap_or(v))
}
/// The rounds judged so far beside this one (DIR's parent's judge.log.jsonl).
fn log_of(dir: &Path) -> PathBuf {
dir.parent().unwrap_or(dir).join("judge.log.jsonl")
}
/// Done and stall, from the log's rounds (oldest first), in code.
pub fn progress(rounds: &[Value]) -> Value {
let passes = rounds.iter().rev().take_while(|r| r["pass"] == true).count();
let means: Vec<f64> = rounds.iter().filter_map(|r| r["mean"].as_f64()).collect();
let stall = means.len() >= 3 && {
let best_before = means[..means.len() - 2].iter().cloned().fold(f64::MIN, f64::max);
let best_now = means[means.len() - 2..].iter().cloned().fold(f64::MIN, f64::max);
best_now - best_before < 1.0
};
// the same blocking defect present in the last two rounds
let named = |r: &Value| -> Vec<String> { rubric::blocking(r["defects"].as_array().map(Vec::as_slice).unwrap_or_default()).into_iter().map(str::to_string).collect() };
let again: Vec<String> = match rounds {
[.., a, b] => named(a).into_iter().filter(|d| named(b).contains(d)).collect(),
_ => Vec::new(),
};
json!({"rounds": rounds.len(), "passesInARow": passes, "done": passes >= 2, "stall": stall || !again.is_empty(), "again": again})
}
pub fn cli(args: &[String]) -> Result<String, String> {
match args.get(1).map(String::as_str) {
Some("eye") => return eye::record(args),
Some("calibrate") => return eye::calibrate(args),
Some(_) => {}
None => return Err(USAGE.into()),
}
let dir = PathBuf::from(&args[1]);
let kind = kind_of(args)?;
let kind = kind.as_deref();
let hero = dir.join("hero-colour.png");
let sheets: Vec<(&str, PathBuf)> = rubric::sheets(kind).iter().map(|(s, f)| (*s, dir.join(f))).collect();
for (_, f) in &sheets {
if !f.is_file() {
let make = if kind == Some("shot") { format!("raea make framing --out {}", dir.display()) } else { format!("raea render EDIT.tsx --review {}", dir.display()) };
return Err(format!("judge: no {} (make the sheets with {make})", f.display()));
}
}
let brief = brief_of(flag(args, "--brief").as_deref())?;
let target = flag(args, "--target").map(PathBuf::from);
let dry = args.iter().any(|a| a == "--dry");
let by = if agent::critic() { "agent".to_string() } else { "clef".into() };
if by != "clef" {
if dry {
return Ok(agent::prompt(kind, &dir, &brief, target.as_deref()));
}
let v = agent::ask(kind, &dir, &brief, target.as_deref())?;
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"]}));
}
let mut calls = Vec::new();
for (sheet, img) in &sheets {
let mut images = vec![img.clone()];
if *sheet == "colour" {
images.extend(target.clone());
}
calls.push((*sheet, rubric::state_for(kind, sheet, &brief), rubric::questions_for(kind, sheet), images));
}
if hero.is_file() && kind != Some("shot") {
calls.push(("blind", "One frame. Judge only what is in the pixels.".into(), rubric::blind(), vec![hero.clone()]));
}
if dry {
let shown: Vec<Value> = calls.iter().map(|(s, st, q, im)| json!({"sheet": s, "state": st, "questions": q, "images": im.iter().map(|p| p.display().to_string()).collect::<Vec<_>>()})).collect();
return Ok(serde_json::to_string_pretty(&json!({"would_ask": shown})).unwrap_or_default());
}
let mut scores = serde_json::Map::new();
let mut defects = Vec::new();
let mut photo = Value::Null;
let mut cost = 0.0;
for (sheet, st, q, images) in &calls {
let (answers, c) = ask(st, q, images)?;
cost += c;
if *sheet == "blind" {
photo = json!(answers["photo"]["noul"].as_f64().map(|p| (p * 1000.0).round() / 1000.0));
continue;
}
let (s, d) = rubric::read_for(kind, &answers);
scores.extend(s);
defects.extend(d.into_iter().map(|mut x| {
x["sheet"] = json!(sheet);
x
}));
}
let raw = scores.clone();
let cal = eye::calibration(kind);
if let Some(c) = &cal {
eye::apply(c, &mut scores);
}
let gating = cal.as_ref().is_some_and(|c| c["gate"] == true);
finish(args, kind, &dir, scores, raw, defects, photo, cost, "clef", !gating, json!({"calibrated": cal.is_some()}))
}
/// The defects a judge saw, as raea's one Finding (docs/direction.feature DR3): a blocking one an error and a detail a
/// warn, each a level lower from a judge that only advises. A judge sees pictures, not parts: a finding names its
/// sheet in its words and is about no entity.
pub fn findings(defects: &[Value], by: &str, advice: bool) -> Vec<Finding> {
let found = defects.iter().filter(|d| d["present"] == true).map(|d| {
let blocking = d["level"] == "blocking";
let level = match (blocking, advice) {
(true, false) => Level::Error,
(true, true) | (false, false) => Level::Warn,
(false, true) => Level::Note,
};
let sheet = d["sheet"].as_str().unwrap_or("");
let check = format!("judge.{}", if by == "clef" { d["defect"].as_str().unwrap_or("defect") } else { sheet });
let mut f = Finding::new(&check, level, format!("{sheet} sheet: {}", d["asked"].as_str().unwrap_or("")), &format!("raea judge ({by})"));
if let Some(p) = d["p"].as_f64() {
f = f.measure("p", p, "", Some(0.5));
}
match d["fix"].as_str() {
Some(x) if !x.is_empty() => f.fix(x),
_ => f,
}
});
finding::ranked(found.collect())
}
/// The verdict decided in code, written (DIR/judge.json for clef, DIR/judge.BY.json for an agent; every round in the
/// log), and said. `advice` marks a judge not yet trusted to gate (clef before calibration).
#[allow(clippy::too_many_arguments)]
fn finish(args: &[String], kind: Option<&str>, dir: &Path, scores: serde_json::Map<String, Value>, raw: serde_json::Map<String, Value>, defects: Vec<Value>, photo: Value, cost: f64, by: &str, advice: bool, extra: Value) -> Result<String, String> {
let (pass, why) = rubric::pass_for(kind, &scores, &defects);
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 model = if by == "clef" { "@cf/cloudflare/clef-omni".to_string() } else { "the project's agent".to_string() };
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,
"pass": pass, "why": why, "gating": !advice, "cost": cost, "model": model, "findings": found, "count": finding::count(&found)});
if let (Some(v), Some(e)) = (verdict.as_object_mut(), extra.as_object()) {
v.extend(e.clone());
}
let log = log_of(dir);
let mut rounds: Vec<Value> = std::fs::read_to_string(&log).unwrap_or_default().lines().filter_map(|l| serde_json::from_str(l).ok()).filter(|r: &Value| r["dir"] != verdict["dir"]).collect();
rounds.push(verdict.clone());
verdict["progress"] = progress(&rounds);
let file = if by == "clef" { "judge.json".to_string() } else { format!("judge.{by}.json") };
std::fs::write(dir.join(file), serde_json::to_string_pretty(&verdict).unwrap_or_default()).map_err(|e| e.to_string())?;
let lines: Vec<String> = rounds.iter().map(|r| serde_json::to_string(&json!({"dir": r["dir"], "kind": r["kind"], "by": r["by"], "pass": r["pass"], "mean": r["mean"], "defects": r["defects"]})).unwrap_or_default()).collect();
std::fs::write(&log, lines.join("\n") + "\n").map_err(|e| e.to_string())?;
if cost > 0.0 {
let _ = std::process::Command::new("antsy").args(["spend", &format!("{cost:.6}"), "raea judge (clef-omni)"]).output();
}
if args.iter().any(|a| a == "--json") {
return Ok(serde_json::to_string_pretty(&verdict).unwrap_or_default());
}
let who = if by == "clef" { String::new() } else { format!("({by}) ") };
let mut t = vec![format!("{} {who}{}{}", if pass { "PASS" } else { "NOT YET" }, if advice { "(advice: the judge isn't calibrated against your eye yet) " } else { "" }, why.join("; "))];
t.push(format!("scores: {}", scores.iter().map(|(k, v)| format!("{k} {v}")).collect::<Vec<_>>().join(", ")));
for f in &found {
let p = f.measure.as_ref().map(|m| format!(" (p {})", m.value)).unwrap_or_default();
t.push(format!(" {}{p}", f.line()));
}
let p = &verdict["progress"];
t.push(format!("round {}: {} passes in a row{}{}; ${cost:.4}", p["rounds"], p["passesInARow"], if p["done"] == true { ", done" } else { "" }, if p["stall"] == true { ", stalled: change the approach for the part, not the dose" } else { "" }));
t.push(format!("raea judge: {}", finding::count(&found)));
Ok(t.join("\n"))
}
#[cfg(test)]
mod tests;
/// Why `raea spec` refused a brief, in its own words: its refusal is the last line it printed, on whichever stream
/// (a REFUSED line goes to stdout, a thrown module's error to stderr). Reading stderr alone left the reason empty.
pub fn why_refused(out: &std::process::Output) -> String {
let last = |b: &[u8]| String::from_utf8_lossy(b).lines().rev().find(|l| !l.trim().is_empty()).map(|l| l.trim().trim_start_matches("REFUSED").trim().to_string());
last(&out.stderr).or_else(|| last(&out.stdout)).unwrap_or_else(|| "raea spec printed nothing".into())
}
+229
View File
@@ -0,0 +1,229 @@
//! The frozen rubric (the 11-06 prompt pack, section 3, in clef-omni's native question types): a 0-10 score per category
//! as an ordered six-level rubric, and every named defect as a yes/no question, so a defect is a probability rather
//! than prose. clef-omni answers questions, not essays; the defects it can name are the ones asked. Nothing here says
//! where the pass line is (the loop decides, in code: `pass`).
use serde_json::{Value, json};
/// The six levels each category is scored on, lowest first (clef's `score`: the probability-weighted level), read as
/// 0, 2, 4, 6, 8, 10.
fn levels(what: &str) -> Value {
json!([
format!("0: no {what} to speak of; broken or missing"),
format!("2: {what} is crude: primitives and placeholders"),
format!("4: {what} is a rough draft, plainly unfinished"),
format!("6: {what} is a believable draft"),
format!("8: {what} is a production base an artist would accept"),
format!("10: {what} is indistinguishable from the real thing"),
])
}
/// A category: (id, the sheet it is judged on, the question).
pub type Score = (&'static str, &'static str, &'static str);
/// (id, the sheet it is judged on, the question): the rubric raea judge has always asked, when no `--kind` is given.
pub const SCORES: [Score; 7] = [
("composition", "colour", "Composition: the camera, framing and layout; every major object's position and scale against the brief's space."),
("form", "clay", "Form, judged on these grey clay tiles: silhouettes read at a glance, parts have real thickness, nothing blobby or melted, no primitive standing in for a thing, repeated things vary."),
("assembly", "clay", "Assembly, judged on these grey clay tiles: nothing floats, sinks, pokes through or rests on the wrong thing; joints touch; the low tile shows the feet resting."),
("materials", "colour", "Materials: every surface reads as its real material with wear where use puts it; nothing a flat default colour; glass is glass."),
("light", "colour", "Light: motivated by the place's own sources; exposure and contrast believable; no surface implausibly dark or bright."),
("detail", "colour", "Detail: close surfaces hold real geometry or texture at that distance, not smooth stand-ins; printed matter reads."),
("world", "colour", "World: one coherent real place matching the brief; nothing off-era, no real brands, nothing invented beyond the brief."),
];
/// The job kinds with a rubric of their own (docs/goal.feature MK5): `raea judge DIR --kind scene|kit|shot`.
pub const KINDS: [&str; 3] = ["scene", "kit", "shot"];
/// A scene made to a plan (AnyScene's categories): judged on the six-camera sheets.
pub const SCENE: [Score; 8] = [
("layout", "clay", "Layout, judged on these grey clay tiles: every major object where the plan and the reference put it, at its real size, with room to move between them."),
("props", "clay", "Props, judged on these grey clay tiles: each object's form reads at a glance, with real thickness; nothing blobby or a primitive standing in; nothing floats, sinks or pokes through."),
("signage", "colour", "Screens and signage: every screen, sign, label and printed thing reads, belongs to one invented world, and shows no real brand."),
("materials", "colour", "Materials: every surface reads as its real material with wear where use puts it; nothing a flat default colour; glass is glass."),
("light", "colour", "Light: motivated by the place's own sources; exposure and contrast believable; emissive things glow without lighting the room wrong."),
("atmosphere", "colour", "Atmosphere: the air, haze, dust or weather the place would have, matching the plan's dials; not empty and clinical."),
("plausibility", "colour", "Plausibility: one coherent real place a person could stand in; nothing off-era, nothing that couldn't be there."),
("composition", "colour", "Composition: the hero camera's framing and the place's layout read as the reference's."),
];
/// A kit (AnyKit's categories): judged on the six-camera sheets of its lineup.
pub const KIT: [Score; 8] = [
("cohesion", "colour", "Cohesion: every prop belongs to one set: the same era, palette, materials, wear and maker; none is an outlier."),
("fidelity", "colour", "Reference fidelity: the props read as the style references' world, at normal viewing distance."),
("brief", "colour", "Brief: the kit holds the props the brief asked for, each recognisable as what it is meant to be."),
("mesh", "clay", "Mesh, judged on these grey clay tiles: crisp silhouettes, real thickness, no melted or blobby forms, no holes or spikes."),
("texture", "colour", "Texture: real materials with wear where use puts it; no smeared, stretched or flat default surfaces; glass is glass."),
("assembly", "clay", "Assembly, judged on these grey clay tiles: every part of each prop is connected to its body; handles, legs and lids attached."),
("scale", "clay", "Scale, judged on these grey clay tiles: each prop's size is right beside the others and the scale bar."),
("labels", "colour", "Labels: printed text and logos read, belong to the one invented maker, and no real brand shows."),
];
/// A shot list (AnyShot's categories): judged on the framing sheet, each shot's first, middle and last frame.
pub const SHOT: [Score; 6] = [
("framing", "colour", "Framing: each shot frames its subject as its description says, at every one of its frames."),
("move", "colour", "Move: the camera's change from first to last frame is the move the description names, at a believable size."),
("focus", "colour", "Focus: what the description says is sharp is sharp; nothing important lost in blur."),
("clearance", "colour", "Clearance: the camera is never inside or against a wall or object; nothing blocks the frame."),
("continuity", "colour", "Continuity: the shots read as one place at one time: the same light, weather and dressing across them."),
("grade", "colour", "Grade: the look matches the plan's look dial, with believable exposure and colour."),
];
/// The categories asked for a kind: its own rubric, or the default one.
pub fn scores(kind: Option<&str>) -> &'static [Score] {
match kind {
Some("scene") => &SCENE,
Some("kit") => &KIT,
Some("shot") => &SHOT,
_ => &SCORES,
}
}
/// What a kind's critic is told the bar is (AnyKit's own words, docs/goal.feature MK5).
pub const BAR: &str = "The bar is a production base an artist then refines, judged at normal viewing distance: take no points off for choices that differ from the reference, don't nitpick, and name at most five fixes, most damaging first.";
/// The sheets a kind is judged on: the six-camera colour and clay sheets, or a shot list's framing sheet alone.
pub fn sheets(kind: Option<&str>) -> &'static [(&'static str, &'static str)] {
match kind {
Some("shot") => &[("colour", "framing.png")],
_ => &[("colour", "colour.png"), ("clay", "clay.png")],
}
}
/// (id, sheet, the yes/no question, blocking when yes)
pub const DEFECTS: [(&str, &str, &str, bool); 12] = [
("floating", "clay", "Does any object float above the surface it should rest on, with a visible gap under it?", true),
("intersecting", "clay", "Does any object pass through another object, a wall or the floor?", true),
("blobby", "clay", "Is any object a blobby, melted or lumpy shape where the real thing has crisp form?", true),
("stand_in", "clay", "Is any object just a plain box, ball or cylinder standing in for a more detailed real thing?", true),
("clones", "clay", "Are several copies of one thing identical and evenly spaced in an obviously artificial way?", false),
("flat_colour", "colour", "Is any large surface a flat, uniform default colour with no texture, variation or wear?", true),
("plastic", "colour", "Do the surfaces look like shiny uniform plastic or CG rather than their real materials?", true),
("garbled_text", "colour", "Is any visible text garbled, tiled or unreadable where it should read?", false),
("too_dark", "colour", "Is the scene so dark that important objects are hard to see?", true),
("too_bright", "colour", "Is the scene washed out, with large areas blown to white?", true),
("brands", "colour", "Is a real brand name or logo visible?", true),
("not_doing", "colour", "Does the scene show anything the brief says it must not contain?", true),
];
/// The paragraph clef reads before the sheet: what it is looking at, and the brief's words (no code, no log, no line).
pub fn state(sheet: &str, brief: &Value) -> String {
state_for(None, sheet, brief)
}
/// state, for a kind: a kind's critic also reads what it is looking at in its terms, and the bar.
pub fn state_for(kind: Option<&str>, sheet: &str, brief: &Value) -> String {
let what = match kind {
Some("shot") => "The image is a framing sheet: each row is one shot, its first, middle and last frame left to right, each stamped with the shot's name and time. Judge each shot as its description would.".to_string(),
_ => {
let tiles = "six tiles of one 3D scene, left to right and top to bottom: hero (the shot's own camera), front, right, top, iso, and low (a camera 0.3 m off the floor)";
let what = if sheet == "clay" { format!("The image is {tiles}, rendered in clay: every surface plain grey, so only form and assembly show.") } else { format!("The image is {tiles}, in full colour.") };
let target = if sheet == "colour" { " A second image, when given, is the target picture the scene should read as." } else { "" };
let kit = if kind == Some("kit") { " The scene is a kit: a lineup of props made to belong together, with a scale bar." } else { "" };
format!("{what}{target}{kit}")
}
};
// the default rubric's words stay as calibrated: "the scene"
let it = match kind { None | Some("scene") => "the scene", Some("kit") => "the kit", _ => "the shots" };
let mut s = format!("{what} Judge only what is in the pixels, as the person who will use {it} would.");
let look = brief["look"].as_str().unwrap_or("");
let logline = brief["logline"].as_str().unwrap_or("");
let not: Vec<&str> = brief["notDoing"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
if !logline.is_empty() || !look.is_empty() {
s.push_str(&format!(" The brief: {logline} Look: {look}."));
}
if !not.is_empty() {
let it = it[..1].to_uppercase() + &it[1..];
s.push_str(&format!(" {it} must not contain: {}.", not.join("; ")));
}
if kind.is_some() {
s.push(' ');
s.push_str(BAR);
}
s
}
/// The questions for one sheet, by id.
pub fn questions(sheet: &str) -> Value {
questions_for(None, sheet)
}
/// questions, for a kind's rubric.
pub fn questions_for(kind: Option<&str>, sheet: &str) -> Value {
let mut q = serde_json::Map::new();
for &(id, on, ask) in scores(kind) {
if on == sheet {
q.insert(format!("score_{id}"), json!({"type": "score", "instructions": ask, "criteria": levels(id)}));
}
}
for (id, on, ask, _) in DEFECTS {
if on == sheet {
q.insert(format!("defect_{id}"), json!({"type": "noul", "instructions": ask}));
}
}
Value::Object(q)
}
/// The blind read on the hero tile alone: is this a photograph (reported, never gated, until calibrated).
pub fn blind() -> Value {
json!({"photo": {"type": "noul", "instructions": "Is this a photograph of a real place, rather than a computer render?"}})
}
/// clef's answers read into scores (0-10) and defects (probability of yes, blocking ones flagged).
pub fn read(answers: &Value) -> (serde_json::Map<String, Value>, Vec<Value>) {
read_for(None, answers)
}
/// read, for a kind's rubric.
pub fn read_for(kind: Option<&str>, answers: &Value) -> (serde_json::Map<String, Value>, Vec<Value>) {
let mut scores = serde_json::Map::new();
let mut defects = Vec::new();
for &(id, _, _) in self::scores(kind) {
if let Some(a) = answers.get(format!("score_{id}")) {
let level = a["score"].as_f64().unwrap_or(0.0);
scores.insert(id.into(), json!((level * 2.0 * 100.0).round() / 100.0));
}
}
for (id, _, ask, blocking) in DEFECTS {
if let Some(a) = answers.get(format!("defect_{id}")) {
let p = a["noul"].as_f64().unwrap_or(0.0);
defects.push(json!({"defect": id, "p": (p * 1000.0).round() / 1000.0, "present": p >= 0.5, "level": if blocking { "blocking" } else { "detail" }, "asked": ask}));
}
}
(scores, defects)
}
/// The loop's pass, in code: no blocking defect present, the lowest score 6 or more and the mean 7 or more (raea's
/// 0-10 scale; the prompt pack's line). Scores mapped by a calibration first, when there is one.
pub fn pass(scores: &serde_json::Map<String, Value>, defects: &[Value]) -> (bool, Vec<String>) {
pass_for(None, scores, defects)
}
/// pass, for a kind's rubric: every one of its categories scored.
pub fn pass_for(kind: Option<&str>, scores: &serde_json::Map<String, Value>, defects: &[Value]) -> (bool, Vec<String>) {
let want = self::scores(kind).len();
let vals: Vec<f64> = scores.values().filter_map(Value::as_f64).collect();
let mut why = Vec::new();
let blocking = blocking(defects);
if !blocking.is_empty() {
why.push(format!("blocking: {}", blocking.join(", ")));
}
let min = vals.iter().cloned().fold(f64::INFINITY, f64::min);
let mean = if vals.is_empty() { 0.0 } else { vals.iter().sum::<f64>() / vals.len() as f64 };
if vals.len() < want {
why.push(format!("only {} of {want} categories scored", vals.len()));
}
if min < 6.0 {
let low: Vec<String> = scores.iter().filter(|(_, v)| v.as_f64().is_some_and(|x| x < 6.0)).map(|(k, _)| k.clone()).collect();
why.push(format!("below a draft: {}", low.join(", ")));
}
if mean < 7.0 {
why.push("the whole is under a production base".into());
}
(why.is_empty(), why)
}
/// The blocking defects present, by name.
pub fn blocking(defects: &[Value]) -> Vec<&str> {
defects.iter().filter(|d| d["present"] == true && d["level"] == "blocking").filter_map(|d| d["defect"].as_str()).collect()
}
+126
View File
@@ -0,0 +1,126 @@
use super::*;
use serde_json::json;
fn scores(v: f64) -> serde_json::Map<String, Value> {
rubric::SCORES.iter().map(|s| (s.0.to_string(), json!(v))).collect()
}
#[test]
fn the_pass_is_code_and_a_blocking_defect_holds_it() {
assert!(rubric::pass(&scores(7.5), &[]).0);
assert!(!rubric::pass(&scores(6.5), &[]).0, "mean under 7");
let mut s = scores(8.0);
s.insert("form".into(), json!(5.0));
let (ok, why) = rubric::pass(&s, &[]);
assert!(!ok && why.iter().any(|w| w.contains("form")));
let d = vec![json!({"defect": "floating", "present": true, "level": "blocking"})];
assert!(!rubric::pass(&scores(9.0), &d).0);
// the questions hold no pass line
let q = format!("{}{}", rubric::questions("colour"), rubric::questions("clay"));
assert!(!q.contains("mean") && !q.contains(">= 6"));
}
#[test]
fn answers_are_read_and_rounds_say_done_and_stall() {
let a = json!({"score_form": {"score": 3.5}, "defect_floating": {"noul": 0.8}});
let (s, d) = rubric::read(&a);
assert_eq!(s["form"], 7.0);
assert_eq!(d[0]["present"], true);
let r = |p: bool, m: f64| json!({"pass": p, "mean": m, "defects": []});
assert_eq!(progress(&[r(false, 5.0), r(true, 7.2), r(true, 7.4)])["done"], true);
assert_eq!(progress(&[r(false, 5.0), r(false, 5.3), r(false, 5.6)])["stall"], true);
assert_eq!(progress(&[r(false, 4.0), r(false, 5.3), r(false, 6.1)])["stall"], false);
}
#[test]
fn calibration_maps_a_lenient_judge_onto_the_eye() {
// the judge says 8 to everything the eye gives 5, and 9 to what the eye gives 8
let row = |j: f64, e: f64, p: bool| json!({"judge": scores(j), "eye": scores(e), "eye_pass": p, "defects": []});
let rows: Vec<Value> = (0..12).map(|i| if i % 2 == 0 { row(8.0, 5.0, false) } else { row(9.0, 8.0, true) }).collect();
let cal = eye::fit_rows_for(None, &rows);
assert_eq!(cal["agreement"], 1.0);
assert_eq!(cal["gate"], true);
assert!((cal["maps"]["form"]["a"].as_f64().unwrap() - 3.0).abs() < 1e-6);
let few = eye::fit_rows_for(None, &rows[..4]);
assert_eq!(few["gate"], false, "too few rounds to gate");
// an eye that failed everything agrees with a judge that fails everything, which proves nothing
let fails: Vec<Value> = (0..12).map(|_| row(3.0, 2.0, false)).collect();
let all_fail = eye::fit_rows_for(None, &fails);
assert_eq!(all_fail["agreement"], 1.0);
assert_eq!(all_fail["gate"], false, "no pass among the eye's rounds");
}
#[test]
fn an_agent_verdict_is_read_from_the_end_of_its_thinking() {
// an agent thinks aloud, may draft the JSON twice, and ends with the one it means
let text = r#"• Looking at the sheets... draft: {"scores": {"form": 1}} then the answer:
{"blind": {"place": "office", "objects": [], "photo": "no", "tells": []},
"scores": {"composition": 6, "form": 5.5, "assembly": 7, "materials": 4, "light": 6, "detail": 5, "world": 6, "vibes": 9},
"defects": [{"tile": "iso", "where": "left", "wrong": "the desks are plain boxes", "real": "a desk has legs", "fix": "model legs", "level": "blocking"},
{"tile": "low", "wrong": "", "level": "detail"}],
"show_as_is": "no"}"#;
let v = crate::agent::last_verdict(text).unwrap();
let (scores, defects, photo) = crate::agent::read(None, &v);
assert_eq!(scores.len(), 7, "only the seven categories, each 0-10");
assert_eq!(scores["form"], serde_json::json!(5.5));
assert_eq!(defects.len(), 1, "a defect with nothing wrong named is dropped");
assert_eq!(defects[0]["level"], "blocking");
assert_eq!(photo, serde_json::json!(0.0));
let (pass, why) = crate::rubric::pass(&scores, &defects);
assert!(!pass && why[0].starts_with("blocking"));
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
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 (agent)"));
assert!(f.says.starts_with("iso sheet: "), "{}", f.says);
assert_eq!(crate::findings(&defects, "agent", true)[0].level, raea_core_facts::Level::Warn);
}
#[test]
fn each_make_kind_has_its_own_rubric_and_the_default_is_unchanged() {
// docs/goal.feature MK5: a kit's categories, a shot list's on the framing sheet alone, the bar said to each
let kit = rubric::questions_for(Some("kit"), "clay");
for k in ["score_mesh", "score_assembly", "score_scale"] {
assert!(kit.get(k).is_some(), "{k} in {kit}");
}
assert!(kit.get("score_cohesion").is_none(), "cohesion is judged in colour");
assert_eq!(rubric::sheets(Some("shot")), &[("colour", "framing.png")]);
assert_eq!(rubric::sheets(None).len(), 2);
let shot = rubric::questions_for(Some("shot"), "colour");
assert!(shot.get("score_clearance").is_some() && shot.get("score_composition").is_none());
assert!(rubric::state_for(Some("kit"), "colour", &json!({})).contains(rubric::BAR));
assert!(rubric::state_for(Some("shot"), "colour", &json!({})).contains("framing sheet"));
// the default's words are what it was calibrated on
let d = rubric::state("clay", &json!({"notDoing": ["cats"]}));
assert!(d.contains("as the person who will use the scene would") && d.contains("The scene must not contain: cats.") && !d.contains(rubric::BAR), "{d}");
// every kind scored in full to pass
let all = |k: Option<&str>, v: f64| -> serde_json::Map<String, Value> { rubric::scores(k).iter().map(|s| (s.0.to_string(), json!(v))).collect() };
assert!(rubric::pass_for(Some("kit"), &all(Some("kit"), 8.0), &[]).0);
let (ok, why) = rubric::pass_for(Some("kit"), &all(None, 8.0), &[]);
assert!(!ok && why.iter().any(|w| w.contains("of 8 categories")), "{why:?}");
assert!(kind_of(&["judge".into(), "d".into(), "--kind".into(), "film".into()]).is_err());
assert_eq!(kind_of(&["judge".into(), "d".into(), "--kind".into(), "shot".into()]).unwrap().as_deref(), Some("shot"));
}
#[test]
fn an_agent_critic_is_asked_its_kinds_categories() {
let p = crate::agent::prompt(Some("shot"), std::path::Path::new("/r/r1"), &json!({"look": "dusk"}), None);
assert!(p.contains("/r/r1/framing.png") && p.contains("\"clearance\": 0") && p.contains(rubric::BAR) && !p.contains("PART 1, BLIND"), "{p}");
let k = crate::agent::prompt(Some("kit"), std::path::Path::new("/r/r1"), &json!({}), None);
assert!(k.contains("\"cohesion\": 0") && k.contains("scale bar") && k.contains("(judged on CLAY)"));
let d = crate::agent::prompt(None, std::path::Path::new("/r/r1"), &json!({}), None);
assert!(d.contains("\"composition\": 0") && !d.contains(rubric::BAR));
let v = json!({"scores": {"cohesion": 7, "fidelity": 8, "composition": 9}});
let (s, _, _) = crate::agent::read(Some("kit"), &v);
assert_eq!(s.len(), 2, "only the kit's categories");
}
#[test]
fn a_kind_is_calibrated_on_its_own_categories() {
// docs/goal.feature MK6
let s = |j: f64| -> serde_json::Map<String, Value> { rubric::KIT.iter().map(|c| (c.0.to_string(), json!(j))).collect() };
let rows: Vec<Value> = (0..12).map(|i| if i % 2 == 0 { json!({"kind": "kit", "judge": s(8.0), "eye": s(5.0), "eye_pass": false, "defects": []}) } else { json!({"kind": "kit", "judge": s(9.0), "eye": s(8.0), "eye_pass": true, "defects": []}) }).collect();
let cal = eye::fit_rows_for(Some("kit"), &rows);
assert_eq!(cal["gate"], true);
assert!(cal["maps"]["cohesion"].is_object() && cal["maps"]["form"].is_null());
}
+10 -2
View File
@@ -4,15 +4,23 @@ version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "raea make's Rust: a scene, kit or shot goal's asset steps (docs/goal.feature)"
description = "raea make's Rust: a scene, kit or shot job's steps, and the record and critic gates raea/goal's packs read (docs/goal.feature)"
[dependencies]
# the plan: `make` on brief.ts
raea-core-brief = { path = "../../core/brief" }
# the folder a project lives in
# the project's record of renders and checks, and the folder it lives in
raea-core-facts = { path = "../../core/facts" }
# the parts a render showed closer than their planned detail (MK24)
raea-runtime-lod-plan = { path = "../../runtime/lod-plan" }
# the judge's rounds, passes and blocking defects, read as it keeps them
raea-app-judge = { path = "../judge" }
# the make questions, their calibrations and a sheet's ident, as raea ask keeps them (MK4)
raea-core-ask = { path = "../../core/ask" }
# a lens's field of view (MK15's lens chart), as the review sheets work it out
raea-core-review = { path = "../../core/review" }
# raea ask's ledger folder
raea-io-home = { path = "../../io/home" }
# the contact sheets: tiles composited, labels drawn in the system's fonts
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
resvg = { version = "=0.48.1", default-features = false, features = ["text", "system-fonts"] }
+114
View File
@@ -0,0 +1,114 @@
//! The second tier of the gate (docs/goal.feature MK4): the `make` set of `raea ask` questions (core/ask
//! library/make.json), asked of the job's newest sheets. A question gates once it is calibrated on the person's labels
//! (`raea ask calibrate`: 16 problem, 16 clean, an AUC of 0.8); until then what it says is advice in the gates. An
//! answer counts for a sheet only when its call was about exactly that sheet's bytes (the ledger's `ident`), so a sheet
//! rendered again must be asked again.
use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};
use raea_core_ask::{Calibration, Question};
use serde_json::{Value, json};
/// The ledger as the gates read it: every call's ident by id, every answer, and the person's calibrations.
#[derive(Default)]
pub struct Ledger {
pub idents: HashMap<String, String>,
pub answers: Vec<Value>,
pub calibrations: BTreeMap<String, Calibration>,
}
impl Ledger {
/// `raea ask`'s record (RAEA_ASK_DIR, else ~/.raea/ask), read once.
pub fn read() -> Ledger {
let dir = raea_io_home::env_path("RAEA_ASK_DIR", ".raea/ask");
let rows = |f: &str| -> Vec<Value> { std::fs::read_to_string(dir.join(f)).unwrap_or_default().lines().filter_map(|l| serde_json::from_str(l).ok()).collect() };
let idents = rows("calls.jsonl").into_iter().filter_map(|c| Some((c["id"].as_str()?.to_string(), c["ident"].as_str()?.to_string()))).collect();
let answers = rows("answers.jsonl").into_iter().filter(|a| a["question"].as_str().is_some_and(|q| q.starts_with("make."))).collect();
let calibrations = std::fs::read_to_string(dir.join("calibration.json")).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default();
Ledger { idents, answers, calibrations }
}
}
/// The `make` set's questions with the person's calibrations in place of raea's (as `raea ask` applies them).
pub fn questions(ledger: &Ledger) -> Vec<Question> {
let mut qs = raea_core_ask::library::set("make", None).unwrap_or_default();
for q in &mut qs {
if let Some(c) = ledger.calibrations.get(&q.version()) {
q.calibration = Some(c.clone());
}
}
qs
}
/// The sheet a question is asked of: its id's second word (make.clay.floating is asked of a clay sheet).
pub fn sheet_of(q: &Question) -> &str {
match q.id.split('.').nth(1) {
Some(sheet) => sheet,
None => "",
}
}
/// The command that asks a sheet its questions.
pub fn command(sheet: &Path, qs: &[&Question]) -> String {
let std: Vec<String> = qs.iter().map(|q| format!("--std {}", q.id)).collect();
format!("raea ask {} {}", sheet.display(), std.join(" "))
}
/// Each sheet's gate, and the advice: what uncalibrated questions flagged. `sheets` are (kind, file): clay, colour,
/// refs, framing. `notes` is NOTES.md: a flagged question answered there by its id holds nothing.
pub fn gates(sheets: &[(&str, PathBuf)], ledger: &Ledger, notes: &str) -> (Vec<Value>, Vec<String>) {
let qs = questions(ledger);
let mut gates = Vec::new();
let mut advice = Vec::new();
for (kind, file) in sheets {
let mine: Vec<&Question> = qs.iter().filter(|q| sheet_of(q) == *kind).collect();
if mine.is_empty() {
continue;
}
let rel = file.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
let Some(ident) = raea_core_ask::ident::ident(file) else { continue };
// the newest answer to each question about these exact bytes
let mut latest: BTreeMap<&str, &Value> = BTreeMap::new();
for a in &ledger.answers {
let about = a["call"].as_str().and_then(|c| ledger.idents.get(c)).is_some_and(|i| *i == ident);
let Some(q) = a["question"].as_str() else { continue };
if about && latest.get(q).is_none_or(|b| at(a) >= at(b)) {
latest.insert(q, a);
}
}
let mut open = Vec::new();
let mut unasked = Vec::new();
for q in &mine {
let a = latest.get(q.id.as_str());
let flagged = a.is_some_and(|a| a["flagged"] == true);
let p = a.and_then(|a| a["problem"].as_f64()).map(|p| format!(" (p {p:.2})")).unwrap_or_default();
if q.calibrated() {
match a {
None => unasked.push(*q),
Some(_) if flagged && !notes.contains(&q.id) => open.push(format!("{} flagged{p}: {}", q.id, q.fix.as_deref().unwrap_or("fix it, or answer it in NOTES.md by its id"))),
_ => {}
}
} else if flagged {
advice.push(format!("{rel}: {} says yes{p}, advice until calibrated: {}", q.id, q.fix.as_deref().unwrap_or("")));
}
}
if !unasked.is_empty() {
open.push(format!("not asked of this {kind} sheet yet: {}", command(file, &unasked)));
}
let calibrated = mine.iter().filter(|q| q.calibrated()).count();
let says = match (open.is_empty(), calibrated) {
(true, 0) => format!("advice only: none of its {} questions is calibrated yet (raea ask calibrate)", mine.len()),
(true, n) => format!("{n} calibrated question{} clear", if n == 1 { "" } else { "s" }),
(false, _) => open.join("; "),
};
let mut g = json!({"gate": "ask", "of": rel, "clear": open.is_empty(), "says": says});
g["ask"] = json!(command(file, &mine));
gates.push(g);
}
(gates, advice)
}
fn at(a: &Value) -> u64 {
a["at"].as_str().and_then(|s| s.parse().ok()).or_else(|| a["at"].as_u64()).unwrap_or(0)
}
+202
View File
@@ -0,0 +1,202 @@
//! A scene, kit or shot job's record and critic gates (docs/goal.feature MK38), from what's on disk and nothing the agent
//! says: the record of renders and checks, the parts seen closer than planned, the judge's rounds on the kind's rubric
//! and the make questions asked of its sheets. `raea goal gates --json` prints them, and raea/goal's record and critic
//! packs hold the job to them (sdk/goal/src/packs/job.ts); deliverables and notes are packs of their own. Pure over a
//! `Job` so it is tested on fixtures.
use std::{path::{Path, PathBuf}, time::SystemTime};
use raea_core_brief::goal::{self, Goal};
use raea_core_facts::{Level, record::Entry};
use serde_json::{Value, json};
/// Everything the gates read, gathered by `lib.rs` (or a test).
pub struct Job<'a> {
pub make: &'a Goal,
/// the brief's folder: deliverables, NOTES.md and review/ are relative to it
pub dir: &'a Path,
/// the project's folder (record paths are relative to it), when it is a raea project
pub project: Option<&'a Path>,
pub record: &'a [Entry],
/// review/judge.log.jsonl's rounds, oldest first
pub rounds: &'a [Value],
/// the latest round's judge.json, when there is one
pub verdict: Option<&'a Value>,
/// when the judge last wrote its log
pub judged_at: Option<SystemTime>,
/// `raea ask`'s ledger, for the make questions' gate (asked.rs)
pub ledger: &'a crate::asked::Ledger,
/// `raea judge calibrate --kind KIND` agreed with the person's eye for this kind: its score gates too (MK6)
pub score_gates: bool,
}
/// A round's folder: as the judge wrote it when absolute, else the folder of that name beside the log (review/), since
/// `raea judge DIR` keeps its log in DIR's parent and DIR was written relative to wherever it ran.
pub fn round_dir(dir: &Path, round: &Value) -> Option<PathBuf> {
let d = Path::new(round["dir"].as_str()?);
if d.is_absolute() {
return Some(d.to_path_buf());
}
Some(dir.join("review").join(d.file_name()?))
}
/// The sheets the make questions are asked of: the newest round's (its framing sheet for a shot list, its colour and
/// clay sheets otherwise) and a kit's reference sheet.
pub fn sheets(job: &Job) -> Vec<(&'static str, PathBuf)> {
let mut out = Vec::new();
if let Some(r) = job.rounds.last().and_then(|r| round_dir(job.dir, r)) {
if job.make.kind == goal::Kind::Shot {
out.push(("framing", r.join("framing.png")));
} else {
out.push(("clay", r.join("clay.png")));
out.push(("colour", r.join("colour.png")));
}
}
if job.make.kind == goal::Kind::Kit {
out.push(("refs", job.dir.join("review/refs.png")));
}
out.into_iter().filter(|(_, f)| f.is_file()).collect()
}
/// When a file last changed, and that as seconds since 1970 (a record entry's clock).
fn mtime(p: &Path) -> Option<SystemTime> {
std::fs::metadata(p).ok()?.modified().ok()
}
fn mtime_secs(p: &Path) -> Option<u64> {
Some(mtime(p)?.duration_since(SystemTime::UNIX_EPOCH).ok()?.as_secs())
}
fn is_picture(p: &Path) -> bool {
matches!(p.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).as_deref(), Some("png" | "jpg" | "jpeg" | "exr"))
}
/// One deliverable: a file, `a|b` (either), or `dir/` (three or more pictures in it). Returns the files that answer it.
fn answered(dir: &Path, want: &str) -> Result<Vec<PathBuf>, String> {
if let Some(folder) = want.strip_suffix('/') {
let pics: Vec<PathBuf> = std::fs::read_dir(dir.join(folder)).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| is_picture(p)).collect();
return if pics.len() >= 3 { Ok(pics) } else { Err(format!("{want} holds {} picture{}; three or more", pics.len(), if pics.len() == 1 { "" } else { "s" })) };
}
let found: Vec<PathBuf> = want.split('|').map(|w| dir.join(w)).filter(|p| p.is_file()).collect();
if found.is_empty() { Err(want.replace('|', " or ")) } else { Ok(found) }
}
fn notes_text(dir: &Path) -> Option<String> {
std::fs::read_to_string(dir.join("NOTES.md")).ok()
}
/// AnyKit's stall: three rounds in a row without beating the best mean before them. Not the judge's own `stall`
/// (the same defect twice: change the approach), which is advice to the agent, not a reason to let it stop.
pub fn stalled(rounds: &[Value]) -> bool {
let means: Vec<f64> = rounds.iter().filter_map(|r| r["mean"].as_f64()).collect();
means.len() >= 4 && {
let (before, last) = means.split_at(means.len() - 3);
last.iter().cloned().fold(f64::MIN, f64::max) <= before.iter().cloned().fold(f64::MIN, f64::max)
}
}
fn gate(name: &str, of: Option<&str>, clear: bool, says: String) -> Value {
let mut g = json!({"gate": name, "clear": clear, "says": says});
if let Some(of) = of {
g["of"] = json!(of);
}
g
}
/// Tier 1: each composition the plan names has a render or check newer than it that found no error.
fn checks(job: &Job) -> Vec<Value> {
job.make
.compositions
.iter()
.map(|c| {
let file = job.dir.join(c);
let rel = job.project.map(|p| raea_core_facts::record::rel(p, &file)).unwrap_or_else(|| c.clone());
let Some(last) = job.record.iter().rev().find(|e| e.of == rel) else {
return gate("checks", Some(c), false, format!("never rendered or checked: raea render {c} (or raea scene lint {c})"));
};
let changed = mtime_secs(&file);
if changed.is_some_and(|t| t > last.at) {
return gate("checks", Some(c), false, format!("changed since its last {} ({}): run it again", last.by, last.id));
}
let errors: Vec<&str> = last.findings.iter().filter(|f| f.level == Level::Error).map(|f| f.says.as_str()).collect();
match errors.as_slice() {
[] => gate("checks", Some(c), true, format!("clean at {} ({})", last.id, last.by)),
[one] => gate("checks", Some(c), false, format!("{} found: {one}", last.id)),
many => gate("checks", Some(c), false, format!("{} found {} errors, first: {}", last.id, many.len(), many[0])),
}
})
.collect()
}
/// MK24: parts a composition's last render showed closer than planned, held until replanned or answered (raea-runtime-lod-plan)
fn lods(job: &Job, notes: &str) -> Vec<Value> {
let plans = job.make.objects.iter().any(|o| o.lod.is_some());
let last = |c: &String| job.record.iter().rev().find(|e| e.of == job.project.map(|p| raea_core_facts::record::rel(p, &job.dir.join(c))).unwrap_or_else(|| c.clone()));
job.make.compositions.iter().filter_map(|c| last(c).and_then(|l| raea_runtime_lod_plan::gate(c, &l.id, &l.findings, notes, plans)).map(|(clear, says)| gate("lod", Some(c), clear, says))).collect()
}
/// Tier 3: a fresh critic has judged a round newer than the newest deliverable, and each blocking defect it named is
/// fixed (the round passed) or answered in NOTES.md by its name. Its score gates once the judge is calibrated.
fn critic(job: &Job, newest: Option<SystemTime>, notes: &str) -> Vec<Value> {
let Some(last) = job.rounds.last() else {
let kind = job.make.kind.name();
let what = match job.make.kind {
goal::Kind::Kit => "raea render shared/components/KIT/lineup.tsx --review review/r1",
goal::Kind::Shot => "raea make framing --out review/r1",
goal::Kind::Scene | goal::Kind::Cut | goal::Kind::Rules | goal::Kind::Playable => "raea render EDIT.tsx --review review/r1",
};
return vec![gate("critic", None, false, format!("no round yet: {what}, then raea judge review/r1 --kind {kind} --by claude --brief brief.ts"))];
};
let mut out = Vec::new();
let fresh = match (job.judged_at, newest) {
(Some(j), Some(n)) => j >= n,
(Some(_), None) => true,
_ => false,
};
out.push(gate("critic", None, fresh, if fresh { format!("round {} judged after the newest deliverable", job.rounds.len()) } else { "the newest deliverable came after the last round: review and judge it again".into() }));
// the kind's own rubric (MK5): a round judged on another's doesn't count
let kind = job.make.kind.name();
if last["kind"].as_str() != Some(kind) {
let dir = last["dir"].as_str().unwrap_or("review/rN");
out.push(gate("rubric", None, false, format!("the last round wasn't judged on the {kind} rubric: raea judge {dir} --kind {kind} --by claude")));
}
let blocking: Vec<&str> = raea_app_judge::rubric::blocking(last["defects"].as_array().map(Vec::as_slice).unwrap_or_default());
let open: Vec<&str> = if last["pass"] == true { Vec::new() } else { blocking.into_iter().filter(|d| !notes.contains(d)).collect() };
out.push(gate("defects", None, open.is_empty(), if open.is_empty() { "no blocking defect left unanswered".into() } else { format!("blocking, neither fixed nor answered in NOTES.md: {}", open.join(", ")) }));
// the score gates once the judge is calibrated for this kind; before that, fixed-or-answered is enough (MK6)
if job.score_gates {
let p = raea_app_judge::progress(job.rounds);
let done = p["done"] == true;
out.push(gate("score", None, done, format!("the calibrated judge: {} passes in a row, two needed", p["passesInARow"])));
}
out
}
/// The job's gates: each, whether all are clear, and why it's delivered short (out of rounds, or stalled) when it is.
pub fn gates(job: &Job) -> Value {
// the newest deliverable: a round judged before it is stale (the deliverables pack says what's missing)
let newest = goal::deliverables(job.make).iter().filter_map(|w| answered(job.dir, w).ok()).flatten().filter_map(|f| mtime(&f)).max();
let notes = notes_text(job.dir).unwrap_or_default();
let mut gates = checks(job);
gates.extend(lods(job, &notes));
gates.extend(critic(job, newest, &notes));
let (asks, said) = crate::asked::gates(&sheets(job), job.ledger, &notes);
gates.extend(asks);
let cap = job.make.rounds.unwrap_or(goal::ROUNDS) as usize;
let clear = gates.iter().all(|g| g["clear"] == true);
let mut short = Vec::new();
if job.rounds.len() >= cap && !clear {
short.push(format!("capped: {} critic rounds, the most this job gets; delivered with what's still open", job.rounds.len()));
}
if stalled(job.rounds) && !clear {
short.push("stalled: three rounds without beating the best before them; delivered with what's still open".to_string());
}
let advice = raea_app_judge::progress(job.rounds);
json!({
"kind": job.make.kind,
"clear": clear,
"short": short,
"gates": gates,
"judge": {"rounds": job.rounds.len(), "cap": cap, "passesInARow": advice["passesInARow"], "changeApproach": advice["stall"], "again": advice["again"]},
"advice": said,
})
}
+1 -1
View File
@@ -158,7 +158,7 @@ pub fn sheet_refs(dir: &Path, m: &Goal) -> Result<String, String> {
rows.extend(refs.chunks(4).map(|c| c.iter().map(|t| Tile { img: t.img.clone(), label: t.label.clone() }).collect()));
let file = dir.join("review/refs.png");
sheet("Reference sheet: the style, then every object's reference", &rows, 320, &file)?;
Ok(format!("wrote {}: regenerate an outlier before any 3D (raea make refs --only ID)", file.display()))
Ok(format!("wrote {}: regenerate an outlier before any 3D (raea make refs --only ID); ask it: raea ask {} --std make.refs.outlier --std make.refs.two_objects --std make.refs.brands", file.display(), file.display()))
}
/// The flow that sends one reference to both generators, each at its face limit.
+43 -10
View File
@@ -1,14 +1,18 @@
//! The asset tools for a scene, kit or shot goal (docs/goal.feature): `raea make blockout|refs|...` build to the goal's
//! frozen plan (`goal` on brief.ts, core/brief goal.rs). The loop itself, every rule at its moments, is TypeScript:
//! `raea check` and `raea goal tasks` run sdk/goal/src/run.ts (engine/cli verbs.rs goal_ts).
//! frozen plan (`goal` on brief.ts, core/brief goal.rs), and `raea goal gates` gives the record and critic gates
//! raea/goal's packs read. The loop itself, every rule at its moments, is TypeScript: `raea goal check|tasks|seen|judge`
//! run sdk/goal/src/run.ts (engine/cli verbs.rs goal_ts).
//!
//! raea goal gates [DIR] [--goal NAME] --json (the record and critic gates of a scene, kit or shot goal)
//! raea make blockout|refs|sheet refs|gen|pick-sheet|pick|prep|kit|framing|lenschart ... (the steps, USAGE)
pub mod asked;
pub mod floor;
pub mod kit;
pub mod kitout;
pub mod sheet;
pub mod shots;
pub mod gates;
use std::path::{Path, PathBuf};
@@ -16,6 +20,7 @@ use raea_core_brief::goal::Goal;
use serde_json::Value;
pub const USAGE: &str = "raea make place FILE [--at S[,S...]] [--box WxH] (the clearest places in a shot for a text box that size, in a 1080-wide frame)
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 make blockout [DIR] [--no-review] (a scene's blockout stop: review/plan/floor-plan.png, a grey-box blockout from the entrance and its review sheets, comparison.png beside reference 0)
raea make refs [DIR] [--only ID,...] [--model M] [--dry] (a kit: every object's reference from the style images, in the plan's style, then review/refs.png; --dry quotes it)
raea make sheet refs [DIR] (review/refs.png again: the style images, then every reference)
@@ -54,7 +59,7 @@ pub fn read_goals(brief: &Path) -> Result<Vec<Goal>, String> {
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
let out = std::process::Command::new(exe).arg("spec").arg(brief).args(["--as", "brief"]).env("RAEA_RECORD", "off").output().map_err(|e| e.to_string())?;
let text = String::from_utf8_lossy(&out.stdout);
let start = text.find('{').ok_or_else(|| format!("{} didn't read as a brief: {}", brief.display(), why_refused(&out)))?;
let start = text.find('{').ok_or_else(|| format!("{} didn't read as a brief: {}", brief.display(), raea_app_judge::why_refused(&out)))?;
let v: Value = serde_json::from_str(&text[start..]).map_err(|e| format!("{}: {e}", brief.display()))?;
let b = v.get("brief").cloned().unwrap_or(v);
match b.get("goal") {
@@ -66,12 +71,6 @@ pub fn read_goals(brief: &Path) -> Result<Vec<Goal>, String> {
}
}
/// Why a raea that ran printed no answer: its last line said (a refusal's word taken off), else that it printed nothing.
fn why_refused(out: &std::process::Output) -> String {
let last = |b: &[u8]| String::from_utf8_lossy(b).lines().rev().find(|l| !l.trim().is_empty()).map(|l| l.trim().trim_start_matches("REFUSED").trim().to_string());
last(&out.stderr).or_else(|| last(&out.stdout)).unwrap_or_else(|| "raea spec printed nothing".into())
}
/// The scene, kit or shot goal the asset tools build to: the one named, else the only one of those kinds.
pub fn read_goal(brief: &Path) -> Result<Option<Goal>, String> {
read_goal_named(brief, None)
@@ -91,8 +90,35 @@ pub fn read_goal_named(brief: &Path, name: Option<&str>) -> Result<Option<Goal>,
}
}
/// The judge's rounds beside the brief (review/judge.log.jsonl, as `raea judge` keeps them), the newest round's
/// verdict (judge.json, or judge.BY.json for an agent critic), and when the log was last written.
fn judged(dir: &Path) -> (Vec<Value>, Option<Value>, Option<std::time::SystemTime>) {
let log = dir.join("review").join("judge.log.jsonl");
let rounds: Vec<Value> = std::fs::read_to_string(&log).unwrap_or_default().lines().filter_map(|l| serde_json::from_str(l).ok()).collect();
let verdict = rounds.last().and_then(|r| {
let d = gates::round_dir(dir, r)?;
let file = r["by"].as_str().filter(|b| *b != "clef").map_or_else(|| "judge.json".to_string(), |b| format!("judge.{b}.json"));
serde_json::from_str(&std::fs::read_to_string(d.join(file)).ok()?).ok()
});
let at = std::fs::metadata(&log).and_then(|m| m.modified()).ok();
(rounds, verdict, at)
}
/// The record and critic gates of the job whose brief is at `brief`, with its plan already read.
pub fn gates_of(brief: &Path, make: &Goal) -> Value {
let dir = brief.parent().unwrap_or(Path::new("."));
let project = raea_core_facts::record::up(dir, ".raea/project");
let record = project.as_deref().map(raea_core_facts::record::read).unwrap_or_default();
let (rounds, verdict, judged_at) = judged(dir);
let ledger = asked::Ledger::read();
let job = gates::Job { make, dir, project: project.as_deref(), record: &record, rounds: &rounds, verdict: verdict.as_ref(), judged_at, ledger: &ledger, score_gates: raea_app_judge::kind_gates(make.kind.name()) };
let mut s = gates::gates(&job);
s["brief"] = Value::String(brief.display().to_string());
s
}
/// The flags that take a value: what follows them isn't a positional argument.
const VALUED: [&str; 8] = ["--only", "--model", "--tripo", "--meshy", "--name", "--to", "--out", "--goal"];
const VALUED: [&str; 9] = ["--only", "--model", "--tripo", "--meshy", "--name", "--to", "--out", "--by", "--goal"];
fn flag<'a>(args: &'a [String], k: &str) -> Option<&'a str> {
args.iter().position(|a| a == k).and_then(|i| args.get(i + 1)).map(String::as_str)
@@ -173,10 +199,17 @@ fn step(verb: &str, args: &[String]) -> Result<String, String> {
pub fn cli(args: &[String]) -> Result<String, String> {
match args.get(1).map(String::as_str) {
Some("gates") => {
let dir = positional(args, 2).first().map(PathBuf::from).unwrap_or_else(|| PathBuf::from("."));
let (brief, make) = job(&dir, flag(args, "--goal"))?;
Ok(serde_json::to_string_pretty(&gates_of(&brief, &make)).unwrap_or_default())
}
Some(v @ ("blockout" | "refs" | "sheet" | "gen" | "pick-sheet" | "pick" | "prep" | "kit" | "framing" | "lenschart")) => step(v, args),
_ => Err(USAGE.into()),
}
}
#[cfg(test)]
mod tests;
#[cfg(test)]
mod tests_steps;
+3 -3
View File
@@ -1,6 +1,6 @@
//! The contact sheets a person looks at (docs/goal.feature MK10, MK11, MK15): pictures in rows, each labelled under it,
//! a title over them, on one PNG read at once. Labels are drawn by resvg in the system's own fonts; an SVG drawn whole
//! (the floor plan, MK18) goes through `svg_png`.
//! The contact sheets a gate looks at (docs/goal.feature MK10, MK11, MK15): pictures in rows, each labelled under it,
//! a title over them, on one PNG a person, `raea ask` and the critic read at once. Labels are drawn by resvg in the
//! system's own fonts; an SVG drawn whole (the floor plan, MK18) goes through `svg_png`.
use std::path::{Path, PathBuf};
use std::sync::{Arc, OnceLock};
+5 -4
View File
@@ -1,7 +1,8 @@
//! Blocking a shot list (docs/goal.feature MK15): `raea make framing` renders each shot's first, middle and last
//! frame and puts them on one sheet, a row a shot, each stamped with its name and time, so the person sees every shot's
//! start and end at once; `raea make lenschart SHOT` renders a shot's first frame at 18, 24, 35, 50, 85 and 135 mm
//! (RAEA_LENS, core/review) to choose its lens before it's moved.
//! frame and puts them on one sheet, a row a shot, each stamped with its name and time, so the person, `raea ask`
//! (make.framing.*) and the critic (`raea judge --kind shot`) see every shot's start and end at once; `raea make
//! lenschart SHOT` renders a shot's first frame at 18, 24, 35, 50, 85 and 135 mm (RAEA_LENS, core/review) to choose its
//! lens before it's moved.
use std::path::{Path, PathBuf};
@@ -81,7 +82,7 @@ pub fn framing(dir: &Path, m: &Goal, only: &[String], out: &Path) -> Result<Stri
}
let file = out.join("framing.png");
sheet("Framing: each shot's first, middle and last frame", &rows, 480, &file)?;
Ok(format!("wrote {} ({} shot{})", file.display(), shots.len(), if shots.len() == 1 { "" } else { "s" }))
Ok(format!("wrote {} ({} shot{}); ask it: raea ask {} --set make (the framing questions apply); judge it: raea judge {} --kind shot", file.display(), shots.len(), if shots.len() == 1 { "" } else { "s" }, file.display(), out.display()))
}
/// One shot's first frame at every lens of the chart, on one sheet (OUT/lens-SHOT.png).
+196
View File
@@ -0,0 +1,196 @@
use std::path::PathBuf;
use std::time::{Duration, SystemTime};
use raea_core_brief::{goal::Goal, read};
use raea_core_facts::record::Entry;
use serde_json::{Value, json};
use crate::asked::Ledger;
use crate::gates::{Job, gates, stalled};
fn dir(name: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("raea-make-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
d
}
fn put(d: &PathBuf, rel: &str, text: &str) {
let p = d.join(rel);
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(p, text).unwrap();
}
fn kit() -> Goal {
read("make", r#"{"kind": "kit", "style": "1970s desk, maker Aurora", "objects": [{"id": "phone", "label": "Phone", "h": 0.12, "prompt": "a rotary phone"}]}"#).unwrap()
}
fn delivered(d: &PathBuf) {
for f in ["out/kit/phone/phone.glb", "out/kit/phone/phone_lod1.glb", "out/kit/thumbs/phone.png", "out/kit/lineup.png", "out/kit/kit.json", "review/refs.png"] {
put(d, f, "x");
}
put(d, "NOTES.md", "# Notes\n\n## What the skill got wrong\n- nothing yet\n");
}
fn round(pass: bool, mean: f64, defects: Value) -> Value {
json!({"dir": "review/r1", "kind": "kit", "pass": pass, "mean": mean, "defects": defects})
}
fn run(make: &Goal, d: &PathBuf, record: &[Entry], rounds: &[Value], judged_at: Option<SystemTime>) -> Value {
run_with(make, d, record, rounds, judged_at, &Ledger::default())
}
fn run_with(make: &Goal, d: &PathBuf, record: &[Entry], rounds: &[Value], judged_at: Option<SystemTime>, ledger: &Ledger) -> Value {
gates(&Job { make, dir: d, project: None, record, rounds, verdict: None, judged_at, ledger, score_gates: false })
}
fn later() -> Option<SystemTime> {
Some(SystemTime::now() + Duration::from_secs(5))
}
#[test]
fn delivered_and_judged_after_is_done() {
let d = dir("done");
delivered(&d);
let s = run(&kit(), &d, &[], &[round(true, 7.5, json!([]))], later());
assert_eq!(s["clear"], true, "{s:#}");
assert_eq!(s["short"], json!([]));
}
#[test]
fn a_round_older_than_the_newest_deliverable_is_stale() {
let d = dir("stale");
delivered(&d);
let s = run(&kit(), &d, &[], &[round(true, 7.5, json!([]))], Some(SystemTime::UNIX_EPOCH));
assert_eq!(s["clear"], false);
assert!(s["gates"].to_string().contains("came after the last round"), "{s:#}");
}
#[test]
fn a_blocking_defect_must_be_fixed_or_answered_in_the_notes() {
let d = dir("defect");
delivered(&d);
let defects = json!([{"defect": "floating", "present": true, "level": "blocking"}]);
let s = run(&kit(), &d, &[], &[round(false, 6.0, defects.clone())], later());
assert_eq!(s["clear"], false);
assert!(s["gates"].to_string().contains("floating"));
put(&d, "NOTES.md", "## What the skill got wrong\n- floating: the handset rests in its cradle; the judge read its shadow as a gap\n");
let s = run(&kit(), &d, &[], &[round(false, 6.0, defects.clone())], later());
assert_eq!(s["clear"], true, "{s:#}");
// once the judge is calibrated for kits, its score gates too: two passes in a row (MK6)
let (rounds, ledger) = ([round(false, 6.0, defects)], Ledger::default());
let s = gates(&Job { make: &kit(), dir: &d, project: None, record: &[], rounds: &rounds, verdict: None, judged_at: later(), ledger: &ledger, score_gates: true });
assert_eq!(s["clear"], false, "{s:#}");
assert!(s["gates"].to_string().contains("two needed"), "{s:#}");
}
#[test]
fn at_the_cap_it_is_delivered_short() {
let d = dir("cap");
// eight rounds, the last still blocked by a defect no one answered
let blocked = json!([{"defect": "floating", "present": true, "level": "blocking"}]);
let rounds: Vec<Value> = (0..8).map(|i| round(false, 5.0 + i as f64 * 0.5, blocked.clone())).collect();
let s = run(&kit(), &d, &[], &rounds, later());
assert_eq!(s["clear"], false, "{s:#}");
assert!(s["short"].to_string().contains("capped"), "{s:#}");
}
#[test]
fn three_rounds_without_beating_the_best_is_a_stall() {
let r = |m: f64| json!({"mean": m});
assert!(stalled(&[r(5.0), r(6.5), r(6.0), r(6.4), r(6.5)]));
assert!(!stalled(&[r(5.0), r(6.0), r(6.2), r(6.4), r(6.6)]));
assert!(!stalled(&[r(5.0), r(5.0), r(5.0)]), "too few rounds to call it");
}
#[test]
fn a_composition_needs_a_clean_check_newer_than_it() {
let d = dir("checks");
delivered(&d);
put(&d, "scene.tsx", "x");
let mut make = kit();
make.compositions = vec!["scene.tsx".into()];
let rounds = [round(true, 7.5, json!([]))];
let s = run(&make, &d, &[], &rounds, later());
assert!(s["gates"].to_string().contains("never rendered"), "{s:#}");
let entry = |at: u64, level: &str| -> Entry {
serde_json::from_value(json!({"id": "20261123-x", "at": at, "by": "raea render", "of": "scene.tsx",
"findings": [{"check": "float", "level": level, "says": "the mug floats 2 cm", "by": "raea scene lint"}]})).unwrap()
};
let future = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs() + 60;
let s = run(&make, &d, &[entry(future, "error")], &rounds, later());
assert!(s["gates"].to_string().contains("the mug floats"), "{s:#}");
let s = run(&make, &d, &[entry(future, "warn")], &rounds, later());
assert_eq!(s["clear"], true, "a warn doesn't block: {s:#}");
let s = run(&make, &d, &[entry(1, "warn")], &rounds, later());
assert!(s["gates"].to_string().contains("changed since"), "{s:#}");
}
// MK24: a part a render showed closer than planned holds the job until it's replanned or answered in the notes
#[test]
fn a_part_seen_closer_than_planned_holds_the_job() {
let d = dir("lod");
delivered(&d);
put(&d, "scene.tsx", "x");
let mut make = kit();
make.compositions = vec!["scene.tsx".into()];
let future = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs() + 60;
let entry: Entry = serde_json::from_value(json!({"id": "r1", "at": future, "by": "raea render", "of": "scene.tsx", "findings": [{"check": "lod-closer", "level": "warn", "about": [{"name": "kiosk"}], "says": "'kiosk' is planned at LOD 3", "by": "raea render"}]})).unwrap();
let s = run(&make, &d, &[entry.clone()], &[round(true, 7.5, json!([]))], later());
assert!(s["clear"] == false && s["gates"].to_string().contains("seen closer than planned at r1: kiosk"), "{s:#}");
put(&d, "NOTES.md", "- lod kiosk: one frame at the cut, left as a box\n## What the skill got wrong\n- nothing\n");
assert_eq!(run(&make, &d, &[entry], &[round(true, 7.5, json!([]))], later())["clear"], true);
}
#[test]
fn a_round_judged_on_another_kinds_rubric_does_not_count() {
// docs/goal.feature MK5: a kit is judged on the kit's rubric
let d = dir("rubric");
delivered(&d);
let old = json!({"dir": "review/r1", "pass": true, "mean": 8.0, "defects": []});
let s = run(&kit(), &d, &[], &[old], later());
assert_eq!(s["clear"], false);
assert!(s["gates"].to_string().contains("--kind kit"), "{s:#}");
}
#[test]
fn a_calibrated_ask_question_gates_and_an_uncalibrated_one_advises() {
// docs/goal.feature MK4
let d = dir("ask");
delivered(&d);
put(&d, "review/r1/clay.png", "clay sheet bytes");
put(&d, "review/r1/colour.png", "colour sheet bytes");
let rounds = [round(true, 7.5, json!([]))];
let floating = raea_core_ask::library::find("make.clay.floating", None).unwrap();
let mut ledger = Ledger::default();
// nothing calibrated: every question is advice, and the job is done
let s = run_with(&kit(), &d, &[], &rounds, later(), &ledger);
assert_eq!(s["clear"], true, "{s:#}");
assert!(s["gates"].to_string().contains("advice only"), "{s:#}");
// floating calibrated on the person's labels: it must be asked of this exact clay sheet
ledger.calibrations.insert(floating.version(), serde_json::from_value(json!({"auc": 0.9, "n": 40, "positives": 16, "threshold": 0.4, "date": "2026-11-23", "by": "you"})).unwrap());
let s = run_with(&kit(), &d, &[], &rounds, later(), &ledger);
assert_eq!(s["clear"], false);
let gates = s["gates"].to_string();
assert!(gates.contains("not asked of this clay sheet") && gates.contains("--std make.clay.floating"), "{gates}");
// asked, and it flagged: open until fixed or answered by its id in NOTES.md
let ident = raea_core_ask::ident::ident(&d.join("review/r1/clay.png")).unwrap();
ledger.idents.insert("c-1".into(), ident);
ledger.answers.push(json!({"id": "a-1", "at": "100", "call": "c-1", "question": "make.clay.floating", "flagged": true, "problem": 0.8}));
let s = run_with(&kit(), &d, &[], &rounds, later(), &ledger);
assert_eq!(s["clear"], false);
assert!(s["gates"].to_string().contains("make.clay.floating flagged (p 0.80)"), "{s:#}");
put(&d, "NOTES.md", "## What the skill got wrong\n- make.clay.floating: the handset's shadow, not a gap; checked on the low tile\n");
let s = run_with(&kit(), &d, &[], &rounds, later(), &ledger);
assert_eq!(s["clear"], true, "{s:#}");
// the sheet rendered again: the old answer was about other bytes, so it's asked again
put(&d, "review/r1/clay.png", "a new clay sheet");
let s = run_with(&kit(), &d, &[], &rounds, later(), &ledger);
assert!(s["gates"].to_string().contains("not asked of this clay sheet"), "{s:#}");
// an uncalibrated question that flags is said as advice, holding nothing
let ident = raea_core_ask::ident::ident(&d.join("review/r1/colour.png")).unwrap();
ledger.idents.insert("c-2".into(), ident);
ledger.answers.push(json!({"id": "a-2", "at": "101", "call": "c-2", "question": "make.colour.plastic", "flagged": true, "problem": 0.7}));
let s = run_with(&kit(), &d, &[], &rounds, later(), &ledger);
assert!(s["advice"].to_string().contains("make.colour.plastic says yes"), "{s:#}");
}
+2
View File
@@ -25,4 +25,6 @@ raea-core-facts = { path = "../../core/facts" }
raea-core-scene = { path = "../../core/scene" }
bevy = { version = "=0.20.0", default-features = false, features = ["std"] }
dunce = "1"
# --ask: the fault ringed on its frame for the vision model
image = { version = "0.25", default-features = false, features = ["png"] }
serde_json = "1"
+109
View File
@@ -0,0 +1,109 @@
//! `raea scene faults EDIT.tsx --composition ID --ask N` (docs/notice.feature NT12): a vision model asked only what
//! geometry can't say, whether a likely fault is meant. The judge has already found it, measured it and found the
//! frame it shows largest on; that frame is rendered, the fault's spots ringed on it, and `raea ask` (clef-omni) is
//! handed the picture with the scene's own words for it: which part, what it's on or in, by how much. Its answer,
//! meant or a mistake, is kept as a verdict (`by: "ask"`) when it's SURE or more, and any person's verdict on the same
//! finding outranks it.
//! The ringed pictures stay in the project's review/faults-ask/ for a person to look at.
use std::path::Path;
use std::process::Command;
use serde_json::Value;
use raea_sys_notice::{FAULT, Judged, labels};
/// Rendered this wide (its height kept to the composition's shape).
const WIDE: u32 = 960;
/// An answer this sure or more is kept as a verdict; under it, said as unsure and kept out of training. On room
/// 106's shot-window (2026-11-27) the model was 0.52-0.65 sure on chair feet pressed into carpet and a leg through a
/// strap, and 0.72-0.78 on a sunk kit, a floating hat and a part sunk into a door.
const SURE: f64 = 0.7;
/// One ring around every spot of the fault on the picture, a little out from them, in red.
fn ring(png: &Path, marks: &[[f32; 2]]) -> Result<(), String> {
let mut img = image::open(png).map_err(|e| format!("{}: {e}", png.display()))?.to_rgb8();
let (w, h) = (img.width() as f32, img.height() as f32);
let pts: Vec<(f32, f32)> = marks.iter().map(|m| ((m[0] + 1.0) * 0.5 * w, (1.0 - m[1]) * 0.5 * h)).collect();
let (cx, cy) = (pts.iter().map(|p| p.0).sum::<f32>() / pts.len() as f32, pts.iter().map(|p| p.1).sum::<f32>() / pts.len() as f32);
let r = pts.iter().map(|p| (p.0 - cx).hypot(p.1 - cy)).fold(0.0f32, f32::max) + 0.03 * w;
for y in 0..img.height() {
for x in 0..img.width() {
let d = (x as f32 - cx).hypot(y as f32 - cy);
if (d - r).abs() <= 2.5 {
img.put_pixel(x, y, image::Rgb([255, 30, 30]));
}
}
}
img.save(png).map_err(|e| format!("{}: {e}", png.display()))
}
fn question(j: &Judged) -> String {
let f = &j.fault;
let what = match &f.into {
Some(into) => format!("{} (against {into})", f.part),
None => f.part.clone(),
};
format!(
"This is a frame of a 3D scene. Inside the red ring is {what}. A geometry check measured: {}. Judge only what is inside the ring. Is it meant to be like this (cloth draped over an edge, something hung, feet pressed into soft carpet, something set into a wall), or a mistake a viewer would notice (something floating, sunk into something, passing through something, faces flickering)?",
f.says
)
}
/// The likeliest `n` faults asked about, their answers kept as verdicts.
#[allow(clippy::too_many_arguments)]
pub fn run(tsx: &Path, shot: &str, judged: &[Judged], frames: &[i64], w: u32, h: u32, n: usize, dry: bool) -> Result<String, String> {
let project = labels::project_of(tsx);
let dir = project.join("review").join("faults-ask");
std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
let me = std::env::current_exe().map_err(|e| e.to_string())?;
let tall = ((WIDE as f32 * h as f32 / w as f32 / 2.0).round() as u32 * 2).max(2);
let (mut out, mut rows) = (Vec::new(), Vec::new());
for j in judged.iter().filter(|j| j.p >= FAULT && j.seen.best.is_some() && !j.seen.marks.is_empty()).take(n) {
let frame = frames[j.seen.best.unwrap()];
let name = format!("{shot}-{}", j.fault.key).replace(|c: char| !(c.is_ascii_alphanumeric() || c == '-'), "_");
let (png, mp4) = (dir.join(format!("{name}.png")), dir.join(format!("{name}.mp4")));
// the frame as the render draws it, its own end checks left out (they'd judge the scene again)
let drawn = Command::new(&me)
.args(["render", &tsx.to_string_lossy(), "--composition", shot, "--frame", &frame.to_string(), "--w", &WIDE.to_string(), "--h", &tall.to_string(), "-o", &png.to_string_lossy()])
.env("RAEA_FAULTS_CHECK", "0")
.env("RAEA_CLIP_CHECK", "0")
.output()
.map_err(|e| format!("raea render: {e}"))?;
if !drawn.status.success() {
return Err(format!("raea render frame {frame}: {}", String::from_utf8_lossy(&drawn.stderr).lines().last().unwrap_or("")));
}
ring(&png, &j.seen.marks)?;
// raea ask watches a picture move: the still as a second of video
let made = Command::new("ffmpeg").args(["-y", "-loglevel", "error", "-loop", "1", "-i", &png.to_string_lossy(), "-t", "1", "-r", "10", "-pix_fmt", "yuv420p", &mp4.to_string_lossy()]).status().map_err(|e| format!("ffmpeg: {e}"))?;
if !made.success() {
return Err(format!("ffmpeg couldn't make {}", mp4.display()));
}
let mut cmd = Command::new(&me);
cmd.args(["ask", &mp4.to_string_lossy(), &question(j), "--choose", "meant,mistake", "--brief", "none", "--json"]);
if dry {
cmd.arg("--dry");
}
let asked = cmd.output().map_err(|e| format!("raea ask: {e}"))?;
let text = String::from_utf8_lossy(&asked.stdout);
let first: Value = text.lines().find_map(|l| serde_json::from_str::<Value>(l).ok()).unwrap_or(Value::Null);
let choice = first["choice"].as_str().or_else(|| first["answer"].as_str()).map(str::to_lowercase);
let says = first["says"].as_str().unwrap_or("").to_string();
let sure = first["value"].as_f64().unwrap_or(0.0);
match choice.as_deref() {
Some(c) if (c.contains("mistake") || c.contains("meant")) && sure < SURE => {
out.push(format!("{:.2} {} -> unsure ({says}), not kept (frame {frame}, {})", j.p, j.fault.key, png.display()));
}
Some(c) if c.contains("mistake") || c.contains("meant") => {
let real = c.contains("mistake");
rows.push(labels::row(&j.fault.key, real, "ask", shot, &j.x, &j.toks));
out.push(format!("{:.2} {} -> {}{} (frame {frame}, {})", j.p, j.fault.key, if real { "a mistake" } else { "meant" }, if says.is_empty() { String::new() } else { format!(": {says}") }, png.display()));
}
_ if dry => out.push(format!("{:.2} {} would be asked on frame {frame} ({})", j.p, j.fault.key, png.display())),
_ => out.push(format!("{:.2} {} not answered: {}", j.p, j.fault.key, first["not_asked"].as_str().or(first["problem"].as_str()).unwrap_or(text.lines().next().unwrap_or("")))),
}
}
labels::append(&project, &rows)?;
out.push(format!("{} asked, {} answers kept as verdicts (by ask; a person's verdict outranks them) in {}", out.len(), rows.len(), project.join("review").join("faults.labels.jsonl").display()));
Ok(out.join("\n"))
}
+10 -2
View File
@@ -45,10 +45,12 @@ pub fn cli(args: &[String]) -> Result<String, String> {
let (found, _) = raea_sys_contact::lint(&now, &next);
// the cameras: the frame's own and evenly over the rest of the shot
let step = frames.len().div_ceil(CAMERAS).max(1);
let mut views = vec![now.clone()];
for (i, (_, fr)) in frames.iter().enumerate() {
// and each view's frame number, for the frame a fault shows largest on (--ask)
let (mut views, mut view_frames) = (vec![now.clone()], vec![frame]);
for (i, (f, fr)) in frames.iter().enumerate() {
if i != k && i % step == 0 {
views.push(items(fr));
view_frames.push(*f);
}
}
let model = Model::load();
@@ -59,6 +61,12 @@ pub fn cli(args: &[String]) -> Result<String, String> {
return Ok(crate::seed::run(&now, &next, &views, &found, w, h, &model, n));
}
// a vision model asked whether the likeliest faults are meant (ask.rs), its answers kept as verdicts
if let Some(n) = raea_runtime_bundle::flag(args, "--ask") {
let n = n.parse::<usize>().map_err(|_| "--ask takes how many of the likeliest faults to ask about")?;
return crate::ask::run(&tsx, &shot, &judged, &view_frames, w, h, n, args.iter().any(|a| a == "--dry"));
}
// what it learns from: this run against the last, and any verdict given now
let project = labels::project_of(&tsx);
let keys: Vec<String> = judged.iter().map(|j| j.fault.key.clone()).collect();
+2 -1
View File
@@ -11,6 +11,7 @@ use raea_runtime_export::{frame_of, items};
// how near the camera passes to each solid part, every frame (`--clearance M`, MK16)
pub mod clearance;
// the lint's findings judged as a viewer of the shot would see them, learning from verdicts (raea-sys-notice)
mod ask;
mod chars;
mod faults;
mod motion;
@@ -21,7 +22,7 @@ mod light;
pub mod lod;
mod stage;
pub const USAGE: &str = "raea scene lint|explain|faults|light|stage|lod EDIT.tsx [--composition ID] [--frame N] [--part NAME] [--from N] [--to N] [--clearance M] [--real KEY] [--fine KEY] [--seed N] [--motion] [--json] | raea scene faults train [FOLDER] | raea scene faults --clip CLIP.json|FOLDER [--real KEY] [--fine KEY] [--fine-from N] [--fine-upto N] [--real-from N] [--real-upto N] [--by NAME] [--seed N] [--json]";
pub const USAGE: &str = "raea scene lint|explain|faults|light|stage|lod EDIT.tsx [--composition ID] [--frame N] [--part NAME] [--from N] [--to N] [--clearance M] [--real KEY] [--fine KEY] [--seed N] [--ask N [--dry]] [--motion] [--json] | raea scene faults train [FOLDER] | raea scene faults --clip CLIP.json|FOLDER [--real KEY] [--fine KEY] [--fine-from N] [--fine-upto N] [--real-from N] [--real-upto N] [--by NAME] [--seed N] [--json]";
/// `raea scene lint|explain EDIT.tsx [--composition ID] [--frame N] [--json]`: the frame's parts measured
/// (frame 0 by default). `lint` says the faults (errors fail it: floating, sunk, clipping; warnings: in the air,
+3
View File
@@ -14,6 +14,9 @@ raea-core-facts = { path = "../../core/facts" }
serde_json = "1"
# --set's and the CLI's flags, read as the bundler reads them
raea-runtime-bundle = { path = "../../runtime/bundle" }
# `raea judge`, dispatched with `raea make solid` (verb())
raea-app-judge = { path = "../judge" }
raea-app-ask = { path = "../ask" }
# a scene, kit or shot held to its plan (docs/goal.feature)
raea-app-make = { path = "../make" }
# `raea make solid export`: the solid built, written as .glb and read back (core/shape), named and coloured (core/meshcheck)
+4 -2
View File
@@ -91,11 +91,13 @@ fn parse_set(s: &str) -> Result<Map<String, Value>, String> {
Ok(m)
}
/// `raea make solid ...` and `raea make ...` (docs/goal.feature), the verbs that build a piece (engine/cli hands them
/// over), or None for another verb.
/// `raea make solid ...`, `raea judge ...`, `raea make ...` (docs/goal.feature) and `raea ask ...` (docs/ask.feature AK3, which prints as it goes and exits with
/// its own code), the verbs that build and judge a piece (engine/cli hands them over), or None for another verb.
pub fn verb(args: &[String]) -> Option<Result<String, String>> {
match args.first().map(String::as_str) {
Some("solid") => Some(cli(args)),
Some("judge") => Some(raea_app_judge::cli(args)),
Some("ask") => std::process::exit(raea_app_ask::cli(&args[1..])),
Some("make") => Some(raea_app_make::cli(args)),
_ => None,
}
+1 -1
View File
@@ -55,7 +55,7 @@ pub fn with_preface(text: &str, dir: &Path) -> String {
return text.to_string();
}
let p = format!(
"> **On Grok Bot.** raea runs on the person's Mac, not on your computer. Run every `raea` command there, and read\n> every file this skill links (3d.md, reference/cli.md and the rest) from its copy there, in {}, both\n> with Run a command on your local computer (the person turns on Settings → Computer → Execution on this computer).\n> No raea MCP server or hook is set up for you: a render checks its own output at its end (`raea check OUT.mp4`\n> checks one again), and `raea show FILE` puts media in front of the person.\n",
"> **On Grok Bot.** raea runs on the person's Mac, not on your computer. Run every `raea` command there, and read\n> every file this skill links (3d.md, reference/cli.md and the rest) from its copy there, in {}, both\n> with Run a command on your local computer (the person turns on Settings → Computer → Execution on this computer).\n> No raea MCP server or hook is set up for you: after saving a composition run `raea check EDIT.tsx --quick` yourself,\n> and `raea show FILE` puts media in front of the person.\n",
dir.join("raea").display()
);
let Some(rest) = text.strip_prefix("---\n") else { return format!("{p}\n{text}") };
+3 -4
View File
@@ -1,9 +1,8 @@
//! The hooks `raea skills install` adds an agent (docs/agents.feature A5d, A5e; docs/skills.feature SK10), the same two
//! for every harness, each written where and how that harness reads hooks: before a shell command, `raea hook AGENT`
//! steers media opened in the Mac's viewer to `raea show`; after a file is saved, it checks nothing (a render checks its
//! own output, docs/check.feature CK1) and only hands the session what the person sent from the raea app
//! (apps/check/src/inbox.rs). Claude Code's run after every tool, and Claude Code's and Codex's as a turn ends too, where
//! `raea check --at done` holds the brief's goals. An event that already has a `raea hook` entry keeps it, its matcher widened
//! steers media opened in the Mac's viewer to `raea show`; after a file is saved, it runs the quick check on a
//! composition. Claude Code's run after every tool and as a turn ends too, to hand the session what the person sent from
//! the raea app (apps/check/src/inbox.rs). An event that already has a `raea hook` entry keeps it, its matcher widened
//! to this raea's when an older raea wrote a narrower one.
use crate::agent_mcp::user_home;
use serde_json::{Value, json};
+6 -6
View File
@@ -17,7 +17,6 @@
set -uo pipefail
ROOT=$(cd "$(dirname "$0")/../.." && pwd)
cd "$ROOT"
. bench/lib/compare.sh
# renders compared by their pixels are no exports: unsigned and unwatermarked (a TrustMark id differs per render; CI sets it too)
export RAEA_SIGN=0
PIXELS=0
@@ -76,7 +75,8 @@ if [ $PIXELS = 1 ]; then
case "$out" in *PASS*) line S2d PASS "a typed query on the host's World (HostWorld) in a plain App, a reflected component never shared: ${out#host_query: PASS }" ;; *) line S2d FAIL "a typed query on the host's World: ${out:-no result}" ;; esac
(cd "$WORK" && RAEA_PAGE=blitz "$MOTION" render edit.tsx --at 30 -o "$WORK/ref/") > "$WORK/render.log" 2>&1
target/release/examples/plain_page "$WORK/edit.js" "$WORK/plain.png" 1280 720 30 30 > "$WORK/plain.log" 2>&1
whole=$(ssim "$WORK/ref/frame-00000.png" "$WORK/plain.png") title=$(ssim "$WORK/ref/frame-00000.png" "$WORK/plain.png" crop=400:120:40:30)
ssim() { ffmpeg -hide_banner -nostats -i "${REF:-$WORK/ref/frame-00000.png}" -i "${GOT:-$WORK/plain.png}" -lavfi "[0:v]format=rgb24${1}[a];[1:v]format=rgb24${1}[b];[a][b]ssim" -f null - 2>&1 | grep -o 'All:[0-9.]*' | cut -d: -f2; }
whole=$(ssim "") title=$(ssim ",crop=400:120:40:30")
if [ -z "$whole" ]; then line H5 FAIL "the page over a plain App's scene: no frame (see plain_page, raea render)"
else
awk -v s="$whole" 'BEGIN { exit !(s >= 0.998) }' && line H5 PASS "the page over a plain App's scene (classbg frame 30, SSIM $whole against raea)" || line H5 FAIL "the page over a plain App's scene (classbg frame 30, SSIM $whole < 0.998)"
@@ -101,14 +101,14 @@ if [ $PIXELS = 1 ]; then
# would match too)
(cd "$WORK" && RAEA_PAGE=blitz "$MOTION" render video.tsx --at 30 -o "$WORK/vref/") > "$WORK/vrender.log" 2>&1
target/release/examples/plain_page "$WORK/video.js" "$WORK/video.png" 1280 720 30 30 > "$WORK/video.log" 2>&1
v=$(ssim "$WORK/vref/frame-00000.png" "$WORK/video.png" crop=320:568:80:60)
v=$(REF=$WORK/vref/frame-00000.png GOT=$WORK/video.png ssim ",crop=320:568:80:60")
mean=$(ffmpeg -v error -i "$WORK/video.png" -vf "crop=320:568:80:60,scale=1:1" -f rawvideo -pix_fmt rgb24 - 2>/dev/null | xxd -p)
if [ -n "$v" ] && [ "$mean" != 1b2230 ] && awk -v s="$v" 'BEGIN { exit !(s >= 0.999) }'; then line H11 PASS "a video playing inside a page in a plain App (its area SSIM $v against raea)"
else line H11 FAIL "a video playing inside a page in a plain App (SSIM ${v:-none}, mean ${mean:-none})"; fi
# a <Screen>: the frame against raea's, and its page on it: red at its middle, the card blue, black around
(cd "$WORK" && RAEA_PAGE=blitz "$MOTION" render screen.tsx --at 30 -o "$WORK/sref/") > "$WORK/srender.log" 2>&1
target/release/examples/plain_page "$WORK/screen.js" "$WORK/screen.png" 1280 720 30 30 > "$WORK/screen.log" 2>&1
sc=$(ssim "$WORK/sref/frame-00000.png" "$WORK/screen.png")
sc=$(REF=$WORK/sref/frame-00000.png GOT=$WORK/screen.png ssim "")
at() { ffmpeg -v error -i "$WORK/screen.png" -vf "crop=1:1:$1:$2" -f rawvideo -pix_fmt rgb24 - 2>/dev/null | xxd -p; }
if [ -n "$sc" ] && awk -v s="$sc" 'BEGIN { exit !(s >= 0.995) }' && [ "$(at 640 360)" = ff3030 ] && [ "$(at 794 424)" = 2040ff ] && [ "$(at 100 100)" = 000000 ]; then
line H5 PASS "a <Screen>'s nested composition on its screen in a plain App (SSIM $sc against raea)"
@@ -117,8 +117,8 @@ if [ $PIXELS = 1 ]; then
# the page under the sphere and over it
(cd "$WORK" && RAEA_PAGE=blitz "$MOTION" render layers.tsx --at 30 -o "$WORK/lref/") > "$WORK/lrender.log" 2>&1
target/release/examples/plain_page "$WORK/layers.js" "$WORK/layers.png" 960 540 30 30 > "$WORK/layers.log" 2>&1
L() { ssim "$WORK/lref/frame-00000.png" "$WORK/layers.png" "$@"; }
lw=$(L) lu=$(L crop=240:80:20:20) lo=$(L crop=900:40:0:250)
L() { REF=$WORK/lref/frame-00000.png GOT=$WORK/layers.png ssim "$1"; }
lw=$(L "") lu=$(L ",crop=240:80:20:20") lo=$(L ",crop=900:40:0:250")
if [ "$lw" = 1.000000 ] && [ "$lu" = 1.000000 ] && [ "$lo" = 1.000000 ]; then
line H5 PASS "a layered Canvas3D in a plain App: the page under and over its 3D as raea's (SSIM $lw; under $lu, over $lo)"
else line H5 FAIL "a layered Canvas3D in a plain App (SSIM ${lw:-none}; under ${lu:-none}, over ${lo:-none})"; fi
+11
View File
@@ -0,0 +1,11 @@
# The bench checks L2 runs on every release candidate (tools/l2.sh), each with that commit's raea as RAEA_BIN; each
# must exit 0. They hold what P26 can't: P26 compares with a baseline, and a baseline drawn by a raea with a fault
# carries the fault. These say what is right.
#
# A frame drawn alone or out of order (--at, --frame) agrees with the render of every frame (docs/stage-guards.feature
# SG17). 0.1.9 drew a CSS animation in a frame alone from the earliest <Sequence>'s start, or from the frame itself.
bench/at-0/check.sh
bench/at-time/check.sh
bench/at-3d/check.sh
bench/compute-frames/check.sh
sdk/react/bench/css/check.sh
-8
View File
@@ -1,8 +0,0 @@
# The bench checks L2 (tools/l2.sh) does not run. L2 runs every bench/**/check.sh and sdk/**/check.sh, and
# tools/settle-nudge.sh and tools/frame-pure-3d.sh, each with the release candidate's raea as RAEA_BIN; each must
# exit 0.
# They hold what P26 can't: P26 compares with a baseline, and a baseline drawn by a raea with a fault carries the fault.
# These say what is right.
#
# A check is left out only with its reason, one per line: PATH WHY (what it needs that L2 can't give, or the issue
# that tracks its failure). A check whose subject is gone is deleted, not listed here.
-27
View File
@@ -1,27 +0,0 @@
# shellcheck shell=sh disable=SC3043 # local: every shell that sources this has it
# The bench checks' frame comparison, sourced by every script that scores two frames by SSIM so that all of them
# measure the same thing. POSIX sh: sh, bash and zsh scripts source it alike.
#
# . "$ROOT/bench/lib/compare.sh"
# s=$(ssim A B [FILTER_A [FILTER_B]])
#
# ssim prints ffmpeg's SSIM of two images, both read as 8-bit RGB (an alpha channel is dropped, not blended): the
# "All" value to six decimals, 1.000000 for identical pixels. FILTER_A is an ffmpeg filter chain applied to A before
# the conversion (crop=400:120:40:30), FILTER_B the same for B (default: FILTER_A). It prints nothing when ffmpeg
# can't compare them (a file missing or unreadable, or the two sizes differ), so a caller's ${s:-none} or ${s:-0}
# says which.
#
# What the number can and can't see. The same binary rendering a frame twice repeats at 0.99998 or more
# (bench/p26-baseline), and a deband dither keyed to screen position, 2/255 at most, keeps 0.999 (sdk/raea/bench/bevy/
# view). But whole-frame SSIM forgives a small subject and a small slip: a sequence's frame 28 against frame 29 alone
# scored 0.986 (docs/stage-guards.feature SG0), a cut glyph 0.9996, a sprite on the wrong cell 0.989 (tools/
# bevy-parity). A bar under 0.999 passes a one-frame slip; a check that must catch a small subject measures it apart
# (a crop, a tile, a box).
ssim() {
local fa fb
fa=${3:+$3,}
fb=${4:-${3:-}}
fb=${fb:+$fb,}
ffmpeg -nostdin -hide_banner -nostats -i "$1" -i "$2" -lavfi "[0:v]${fa}format=rgb24[a];[1:v]${fb}format=rgb24[b];[a][b]ssim" \
-f null - 2>&1 | grep -o 'All:[0-9.]*' | tail -1 | cut -d: -f2
}
+2 -3
View File
@@ -1,8 +1,7 @@
#!/bin/bash
# P26's baseline (docs/ts-native.feature P26a): frames of every composition in list.txt rendered by the published raea
# 0.1.9, the reference every later page must match (SSIM >= 0.999 per frame, compare.sh's bar, fonts and brand styles
# included). It was the last Blitz build's until that build and its frames were lost (after 11-16); re-taken from 0.1.9
# on 11-22.
# 0.1.9, the reference every later page must match (SSIM >= 0.98 per frame, fonts and brand styles included). It was
# the last Blitz build's until that build and its frames were lost (after 11-16); re-taken from 0.1.9 on 11-22.
#
# bench/p26-baseline/capture.sh [RAEA_BIN] (default: 0.1.9's raea, unpacked at
# ~/Library/Caches/raea/p26-baseline/bin-v0.1.9, P26_STORE to move it)
+11 -17
View File
@@ -1,36 +1,30 @@
#!/bin/bash
# P26's gate (docs/ts-native.feature P26a): each baseline frame (manifest.jsonl, the last Blitz build's) rendered again
# by raea on the Blitz page (the only page since B5d; P26_PAGE names it in results.jsonl,
# docs/blitz-bevy.feature B2b) and compared, SSIM >= 0.999 a frame.
# docs/blitz-bevy.feature B2b) and compared, SSIM >= 0.98 a frame.
#
# bench/p26-baseline/compare.sh [RAEA_BIN] (default: target/release/raea)
#
# The frames go to $P26_STORE/bevy/frames/<slug>/<frame>.png beside the baseline's ($P26_STORE: ~/Library/Caches/raea/
# p26-baseline), each frame's SSIM (ffmpeg's, over RGB) to $P26_STORE/bevy/results.jsonl; a composition that didn't
# render is a failure of all its frames. ONLY=substring limits the compositions. MIN is the bar. Prints the pass rate
# and the worst frames, and exits 1 when any frame is under the bar (L2, tools/l2.sh, counts each row's pass). One
# render at a time (the GPU is shared).
# render is a failure of all its frames. ONLY=substring limits the compositions. MIN=0.98 is the bar. Prints the pass
# rate and the worst frames, and exits 1 when any frame is under the bar (CI's p26 gate reads the exit). One render at
# a time (the GPU is shared).
#
# The bar, 0.999, sits between what a run repeats at and the smallest fault it must catch. The floor (one binary, each
# row rendered twice): rows repeat at SSIM >= 0.99998 run to run, and an incremental build's float rounding (Cargo.toml's
# [profile.release] note) at 0.99997. Most are byte-identical or 1/255 apart; look/town and kitchen/wreck differ in
# about 200 pixels, on house-kit's siding, where the outside and inside skins have coincident faces and which one draws
# on top follows Bevy's draw order for equal depths, likely the asset-load order (spawning the models' scenes in a fixed
# order didn't change it). Coincident faces z-fight in any engine: whoever next touches those houses, offset the inner
# skin. The fault: a frame drawn one frame late scores 0.986 (docs/stage-guards.feature SG0, frame 28 against 29), and
# 0.9985 on a slow film (a 60 fps launch film's frame N+1 against N), both of which 0.98 passed. Whole-frame SSIM can't
# see a fault of a few pixels (SG0's cut glyph scored 0.9996): that needs a pixel measure, not a higher bar. A row that
# differs from the baseline for a good reason is taken again with recapture.sh, which writes the reason into its row.
# The floor (10-26, one binary, each row rendered twice): rows repeat at SSIM >= 0.99998 run to run. Most are
# byte-identical or 1/255 apart; look/town and kitchen/wreck differ in about 200 pixels, on house-kit's siding, where
# the outside and inside skins have coincident faces and which one draws on top follows Bevy's draw order for equal
# depths, likely the asset-load order (spawning the models' scenes in a fixed order didn't change it). Coincident faces
# z-fight in any engine: whoever next touches those houses, offset the inner skin.
set -uo pipefail
HERE=$(cd "$(dirname "$0")" && pwd)
. "$HERE/lib.sh"
# pixel checks: no Content Credentials or TrustMark id in the frames (a still's mark changes its pixels each run)
export RAEA_SIGN=0 RAEA_MARK=0
ROOT=$(cd "$HERE/../.." && pwd)
. "$ROOT/bench/lib/compare.sh"
STORE=${P26_STORE:-$HOME/Library/Caches/raea/p26-baseline}
BIN=${1:-$ROOT/target/release/raea}
MIN=${MIN:-0.999}
MIN=${MIN:-0.98}
# a composition whose baseline came from a plugin build (raea-bevy-sdk: hanabi, avian) renders with one: P26_PLUGIN_BIN
# (default sdk/raea/bench/bevy-plugins/motion.sh; it must take `render` as raea does)
PLUGIN_BIN=${P26_PLUGIN_BIN:-$ROOT/sdk/raea/bench/bevy-plugins/motion.sh}
@@ -85,7 +79,7 @@ for rel in $(jq -r '.composition' "$HERE/manifest.jsonl" | awk '!seen[$0]++'); d
continue
fi
cp "$got" "$OUT/frames/$slug/$f.png"
s=$(ssim "$ref" "$got")
s=$(ffmpeg -hide_banner -nostats -i "$ref" -i "$got" -lavfi "[0:v]format=rgb24[a];[1:v]format=rgb24[b];[a][b]ssim" -f null - 2>&1 | grep -o 'All:[0-9.]*' | cut -d: -f2)
[ -n "$s" ] || s=0
pass=$(awk -v s="$s" -v m="$MIN" 'BEGIN { print (s >= m) ? "true" : "false" }')
jq -nc --arg c "$rel" --argjson f "$f" --argjson s "$s" --argjson p "$pass" '{composition: $c, frame: $f, ssim: $s, pass: $p}' >> "$RES"
+2 -2
View File
@@ -27,8 +27,8 @@ p26_src() {
if [ -f "$WORK/proj/wrap.tsx" ]; then
src=$WORK/proj/wrap.tsx
mkdir -p "$WORK/proj/brand" && cp "$HERE/props/brand.css" "$WORK/proj/brand/brand.css"
# a stub the probe can import; the render compiles its own into the bundle
echo 'export const css = "";' > "$WORK/proj/styles.gen.ts"
# a stub older than everything, so the probe can import it and the render compiles it
echo 'export const css = "";' > "$WORK/proj/styles.gen.ts" && touch -t 200001010000 "$WORK/proj/styles.gen.ts"
fi
fi
dir=$(dirname "$src")
+1 -1
View File
@@ -26,7 +26,7 @@ PORT=${RT_PORT:-7631}
OUT=${RT_OUT:-$(mktemp -d "${TMPDIR:-/tmp}/raea-rt-stage.XXXXXX")}
mkdir -p "$OUT"
bun "$ROOT/bench/realtime/stage/build.ts" "$OUT/page.js" || { echo "FAIL the stage page didn't build"; exit 1; }
. bench/lib/compare.sh
ssim() { ffmpeg -nostdin -hide_banner -nostats -i "$1" -i "$2" -lavfi "[0:v]format=rgb24[a];[1:v]format=rgb24[b];[a][b]ssim" -f null - 2>&1 | grep -o 'All:[0-9.]*' | cut -d: -f2; }
dim() { grep '<Composition' "$1" | head -1 | grep -oE "$2=\{[0-9]+\}" | head -1 | tr -dc 0-9; }
host=""
copies=()
+2 -2
View File
@@ -9,7 +9,6 @@
# A play keeps stepping to its snapshots' frames however loaded the machine (ovw), so an unreached frame is a failure.
cd "$(dirname "$0")/../.." || exit 2
ROOT=$PWD
. bench/lib/compare.sh
# pixel checks: no Content Credentials or TrustMark id in the frames (a still's mark moves its pixels)
export RAEA_SIGN=0 RAEA_MARK=0 RAEA_AUDIO_MUTE=1
BIN=${RAEA_BIN:-$ROOT/target/release/raea}
@@ -54,7 +53,8 @@ while IFS=$'\t' read -r path input secs why; do
if [ ! -f "$OUT/$slug-play-$s.png" ]; then line="$line $f:unreached"; broke=1; continue; fi
if [ ! -f "$OUT/$slug-render/$(printf 'frame-%05d.png' "$f")" ]; then line="$line $f:render-failed"; broke=1; continue; fi
cp "$OUT/$slug-render/$(printf 'frame-%05d.png' "$f")" "$OUT/$slug-render-$s.png"
v=$(ssim "$OUT/$slug-play-$s.png" "$OUT/$slug-render-$s.png")
v=$(ffmpeg -nostdin -hide_banner -nostats -i "$OUT/$slug-play-$s.png" -i "$OUT/$slug-render-$s.png" \
-lavfi "[0:v]format=rgb24[a];[1:v]format=rgb24[b];[a][b]ssim" -f null - 2>&1 | grep -o 'All:[0-9.]*' | cut -d: -f2)
line="$line $f:${v:-none}"
worst=$(awk -v w="$worst" -v v="${v:-0}" 'BEGIN { print (v + 0 < w + 0) ? v : w }')
done
+3 -3
View File
@@ -54,9 +54,9 @@ stats() {
times=$(grep -m1 '^{"direct"' "$OUT/$id.log" || echo '{}')
# the last "first frame" mark: a piece with 3D starts again once it meets its first 3D frame
first=$(grep "the fed render's first frame" "$OUT/$id.log" | tail -1 | awk '{print $3}')
# RAEA_FRAME_LOG: frame, react, sync, gpu (ms); frame 0 is the cold one
frames=$(awk -F'\t' 'NR == 2 { r0 = $2; s0 = $3; g0 = $4 }
NR > 2 { n++; r += $2; s += $3; g += $4 }
# RAEA_FRAME_LOG: frame, react, sync, draw3d, gpu3d, page, gpupage, gpu (ms); frame 0 is the cold one
frames=$(awk -F'\t' 'NR == 2 { r0 = $2; s0 = $3; g0 = $8 }
NR > 2 { n++; r += $2; s += $3; g += $8 }
END { printf "{\"first\":{\"react\":%.2f,\"sync\":%.2f,\"gpu\":%.2f},\"rest_mean\":{\"react\":%.2f,\"sync\":%.2f,\"gpu\":%.2f},\"rows\":%d}", r0, s0, g0, (n ? r / n : 0), (n ? s / n : 0), (n ? g / n : 0), n + 1 }' "$OUT/$id.tsv" 2> /dev/null || echo '{}')
jq -n --arg id "$id" --argjson wall "$(cat "$OUT/$id.wall")" --argjson first "${first:-null}" --argjson times "$times" --argjson log "$frames" \
'{id: $id, wall_s: $wall, first_frame_ms: $first, frames: $times.frames, encoder: $times.video,
+2 -2
View File
@@ -91,8 +91,8 @@ stats() {
local id=$1 times first frames
times=$(grep -m1 '^{.*"fps_incl_encode"' "$OUT/$id.log" 2> /dev/null || echo '{}')
first=$(grep "the fed render's first frame" "$OUT/$id.log" 2> /dev/null | tail -1 | awk '{print $3}')
frames=$(awk -F'\t' 'NR == 2 { r0 = $2; s0 = $3; g0 = $4 }
NR > 2 { n++; r += $2; s += $3; g += $4 }
frames=$(awk -F'\t' 'NR == 2 { r0 = $2; s0 = $3; g0 = $8 }
NR > 2 { n++; r += $2; s += $3; g += $8 }
END { printf "{\"first\":{\"react\":%.2f,\"sync\":%.2f,\"gpu\":%.2f},\"rest_mean\":{\"react\":%.2f,\"sync\":%.2f,\"gpu\":%.2f},\"rows\":%d}", r0, s0, g0, (n ? r / n : 0), (n ? s / n : 0), (n ? g / n : 0), n + 1 }' "$OUT/$id.tsv" 2> /dev/null || echo '{}')
jq -n --arg id "$id" --argjson app "$(cat "$OUT/$id.json" 2> /dev/null || echo '{}')" --argjson launch "$(cat "$OUT/$id.launch")" \
--argjson first "${first:-null}" --argjson times "$times" --argjson log "$frames" \
+1 -1
View File
@@ -25,7 +25,7 @@ export RAEA_SIGN=0 RAEA_MARK=0 RAEA_EXPORT_CACHE=0
mkdir -p "$OUT"
fail=0
. bench/lib/compare.sh
ssim() { ffmpeg -hide_banner -nostats -i "$1" -i "$2" -lavfi ssim -f null - 2>&1 | sed -n 's/.*All:\([0-9.]*\).*/\1/p'; }
# the box the two pictures' differing pixels lie in, "x1 x2 y1 y2", or nothing when every pixel is the same
box() { ffmpeg -hide_banner -i "$1" -i "$2" -lavfi "[0][1]blend=all_mode=difference,format=gray,bbox=min_val=1" -f null - 2>&1 | grep -o "x1:[0-9]* x2:[0-9]* y1:[0-9]* y2:[0-9]*" | tail -1 | sed 's/[a-z0-9]*://g'; }
lower() { echo "$1 $2" | awk '{print ($2 < $1) ? $2 : $1}'; }
+1 -1
View File
@@ -30,7 +30,7 @@ export RAEA_SIGN=0 RAEA_MARK=0 RAEA_EXPORT_CACHE=0
mkdir -p "$OUT"
fail=0
. bench/lib/compare.sh
ssim() { ffmpeg -hide_banner -nostats -i "$1" -i "$2" -lavfi ssim -f null - 2>&1 | sed -n 's/.*All:\([0-9.]*\).*/\1/p'; }
lower() { echo "$1 $2" | awk '{print ($2 < $1) ? $2 : $1}'; }
now() { perl -MTime::HiRes=time -e 'printf "%.3f", time'; }
png() { echo "$1/frame-$(printf %05d "$2").png"; }
-68
View File
@@ -1,68 +0,0 @@
#!/bin/bash
# How fast raea renders the L2 compositions (bench/p26-baseline/manifest.jsonl, resolved as P26 resolves them; the
# plugin build's rows left out). Each is rendered whole to an MP4, once to warm up and then RUNS times, the export
# cache off. Two speeds, each the video's seconds over wall seconds (2.0x: two seconds of video for each second waited):
# frames over the time spent making and encoding the frames (the render's own count: RAEA_RENDER_STATS'
# fps_incl_encode)
# render over the whole command, spawn to exit: what a person waits for. The frames plus the rest of the command
# (the bundle, the page's start, sound, the end checks, signing), which the "rest" column holds
# One line a composition: each speed's median and the range of its runs, the rest's median, and the load. SLOW marks a
# median frame speed under 1.0x. Then the slowest medians, and how many compositions render slower than they play.
# Each run prints its own line as it ends (a game's 36000-frame bound renders for minutes).
#
# bench/speed/run.sh [RAEA_BIN] (default target/release/raea; RUNS=5; ONLY=a grep -E pattern limits the
# compositions)
#
# A measurement, not a check: it exits 1 only when a composition makes no video. Run it under antsy with a memory cap
# (a whole render of the 1-frame sdk/react/bench/css/svg.tsx grows without bound after writing its frame). A loaded
# machine is slower: read the range before the median, and the load printed with each line.
set -uo pipefail
ROOT=$(cd "$(dirname "$0")/../.." && pwd)
HERE=$ROOT/bench/p26-baseline
# shellcheck source=bench/p26-baseline/lib.sh
. "$HERE/lib.sh"
BIN=${1:-${RAEA_BIN:-$ROOT/target/release/raea}}
RUNS=${RUNS:-5}
[ -x "$BIN" ] || { echo "speed: no raea at $BIN" >&2; exit 2; }
WORK=$(mktemp -d "${TMPDIR:-/tmp}/raea-speed.XXXXXX")
trap 'rm -rf "$WORK"' EXIT
now() { perl -MTime::HiRes=time -e 'printf "%.3f", time'; }
load() { sysctl -n vm.loadavg 2>/dev/null | awk '{ print $2 }' || cut -d' ' -f1 /proc/loadavg; }
range() { printf '%s\n' "$@" | sort -n | awk '{ v[NR] = $1 } END { print v[1], v[int((NR + 1) / 2)], v[NR] }'; }
fail=0 n=0 slow=0 under=0 worst='' wrel='' rworst='' rrel=''
for rel in $(jq -r 'select(.binary | test("bevy-plugins|bin-avian") | not) | .composition' "$HERE/manifest.jsonl" | awk '!seen[$0]++'); do
[ -n "${ONLY:-}" ] && ! grep -qE "$ONLY" <<< "$rel" && continue
p26_src "$rel"
speeds=() whole=() rest=() secs=
for i in $(seq 0 "$RUNS"); do
rm -f "$WORK/out.mp4"
t0=$(now)
# its exit isn't read: the end checks (raea check --at render) fail a composition on what it shows, after the MP4
# is written, and that's no slower render
(cd "$dir" && RAEA_EXPORT_CACHE=0 RAEA_RENDER_STATS=1 RAEA_DESPITE="all: speed times the render, not what its scene says" \
"$BIN" render "$src" ${copt[@]+"${copt[@]}"} -o "$WORK/out.mp4") > "$WORK/log" 2>&1
t1=$(now)
secs=$(ffprobe -v error -select_streams v:0 -show_entries stream=duration -of csv=p=0 "$WORK/out.mp4" 2>/dev/null)
[ -n "$secs" ] || { echo "FAIL $rel: no video came out: $(grep -m1 -E 'REFUSED|error|Error|panicked' "$WORK/log" | cut -c1-200)"; fail=1; continue 2; }
fps=$(grep '^{' "$WORK/log" | grep fps_incl_encode | tail -1 | jq -r '"\(.frames) \(.fps_incl_encode)"')
[ -n "$fps" ] || { echo "FAIL $rel: the render said no frame count (RAEA_RENDER_STATS)"; fail=1; continue 2; }
# run 0 warms the caches (the bundle, shaders, fonts); it isn't counted
[ "$i" = 0 ] && continue
read -r f w r <<< "$(awk -v s="$secs" -v a="$t0" -v b="$t1" -v fps="$fps" 'BEGIN { split(fps, x, " "); t = x[1] / x[2]
printf "%.2f %.2f %.2f", s / t, s / (b - a), (b - a) - t }')"
speeds+=("$f"); whole+=("$w"); rest+=("$r")
echo " run $i of $RUNS: frames ${f}x, render ${w}x, rest $r s $rel"
done
read -r lo med hi <<< "$(range "${speeds[@]}")"
read -r rlo rmed rhi <<< "$(range "${whole[@]}")"
read -r _ xmed _ <<< "$(range "${rest[@]}")"
n=$((n + 1)) ok=ok
awk -v m="$med" 'BEGIN { exit !(m < 1) }' && { slow=$((slow + 1)); ok=SLOW; }
awk -v m="$rmed" 'BEGIN { exit !(m < 1) }' && under=$((under + 1))
if [ -z "$worst" ] || awk -v m="$med" -v w="$worst" 'BEGIN { exit !(m < w) }'; then worst=$med wrel=$rel; fi
if [ -z "$rworst" ] || awk -v m="$rmed" -v w="$rworst" 'BEGIN { exit !(m < w) }'; then rworst=$rmed rrel=$rel; fi
printf '%-4s frames %6sx (%s-%s) render %5sx (%s-%s) rest %5s s %d runs %6.2f s of video load %s %s\n' \
"$ok" "$med" "$lo" "$hi" "$rmed" "$rlo" "$rhi" "$xmed" "${#speeds[@]}" "$secs" "$(load)" "$rel"
done
echo "speed: $n compositions; frames slower than they play in $slow (slowest ${worst:-none}x, $wrel); the whole render slower than they play in $under (slowest ${rworst:-none}x, $rrel)"
exit $fail
+2
View File
@@ -11,3 +11,5 @@ serde = { version = "1", features = ["derive"] }
serde_json = "1"
# a file's ident (ident.rs), the one the ledger keeps
sha2 = "0.10"
# the TypeScript declarations are generated from these types, so the two can't drift
ts-rs = "12"
+2 -2
View File
@@ -1,6 +1,6 @@
//! What a file is, cheaply: its size and a hash of its first and last MB. The ledger keeps it on every call
//! (apps/ask record.rs), so a render is known again by its copy in the feed, and a later render to the same path isn't
//! taken for it.
//! (apps/ask record.rs), so a render is known again by its copy in the feed, a later render to the same path isn't
//! taken for it, and `raea goal gates` knows an answer was about exactly the sheet on disk now (docs/goal.feature MK4).
use std::io::{Read as _, Seek as _, SeekFrom};
use std::path::Path;
+18 -2
View File
@@ -1,5 +1,6 @@
//! Questions for the decision model (clef-omni), as every caller of apps/ask writes them (docs/ask.feature AK1): the
//! question and how its answer reads, the sets that come standard, and the model's limits.
//! Questions for the decision model (clef-omni), as every caller of `raea ask` writes them (docs/ask.feature AK1): the
//! question and how its answer reads, the sets that come standard, and the model's limits. Its TypeScript declarations
//! are generated from these types (`declarations`): sdk/raea/src/ask.gen.ts, checked by a test.
pub mod ident;
pub mod library;
@@ -8,5 +9,20 @@ pub mod question;
pub use question::{Calibration, Facts, Kind, LEVELS, Picks, Question, Reading, Sees, When, Window};
use ts_rs::{Config, TS};
macro_rules! decls {
($cfg:ident; $($t:ty),* $(,)?) => { vec![$(format!("export {}", <$t as TS>::decl(&$cfg))),*] };
}
/// The TypeScript of every type, one file's worth: sdk/raea/src/ask.gen.ts is this, checked by a test.
pub fn declarations() -> String {
let cfg = Config::new();
let mut out = vec!["// Generated from raea-core-ask (core/ask) by its `declarations`; edit the Rust, not this.".to_string()];
out.extend(decls!(cfg; question::Question, question::Kind, question::Sees, question::Picks, question::When, question::Window, question::Calibration));
out.push(format!("export const SETS = {:?} as const;", library::SETS));
out.join("\n\n") + "\n"
}
#[cfg(test)]
mod tests;
+5 -5
View File
@@ -1,5 +1,5 @@
//! The questions that come standard (docs/ask.feature AK1), each set named: `rubric` (the critique guide's questions,
//! read from sdk/guides/craft/verbs/critique.md, so there's one copy), `av` (picture with sound), `defects` (the fingerprint's
//! The questions that come standard (docs/ask.feature AK1), each set named: `rubric` (the craft rubric's own questions,
//! read from sdk/guides/craft/rubric.md, so there's one copy), `av` (picture with sound), `defects` (the fingerprint's
//! axes with no labels yet), `platform` (the check packs' questions with their calibration), `decide` (picks and
//! comparisons) and `make` (the review loop's gate questions, asked of a job's sheets: docs/goal.feature MK4; each id
//! says its sheet, make.clay.*, make.colour.*, make.refs.*, make.framing.*). The JSON sets ship inside raea; the
@@ -7,7 +7,7 @@
use crate::question::{Kind, Question};
/// Every set, in the order they're listed.
/// Every set, in the order `raea ask list` shows them.
pub const SETS: [&str; 6] = ["rubric", "av", "defects", "platform", "decide", "make"];
fn embedded(name: &str) -> Option<&'static str> {
@@ -57,10 +57,10 @@ pub fn rubric(md: &str) -> Vec<Question> {
out
}
/// A set's questions. `rubric_md` is the critique guide's text, needed only for `rubric`.
/// A set's questions. `rubric_md` is the rubric guide's text, needed only for `rubric`.
pub fn set(name: &str, rubric_md: Option<&str>) -> Result<Vec<Question>, String> {
if name == "rubric" {
let md = rubric_md.ok_or("the rubric set is read from the critique guide (raea guide critique), which wasn't found")?;
let md = rubric_md.ok_or("the rubric set is read from the rubric guide (raea guide rubric), which wasn't found")?;
return Ok(rubric(md));
}
let text = embedded(name).ok_or_else(|| format!("no set named {name:?}: {}", SETS.join(", ")))?;
+22 -7
View File
@@ -5,12 +5,13 @@ use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use ts_rs::TS;
/// The five levels a `grade` reads over unless it names its own (the rubric's, and checks.rs's "score").
pub const LEVELS: [&str; 5] = ["poor", "weak", "acceptable", "strong", "excellent"];
/// clef's question types: `yes` is its noul, `choose` and `grade` its choice, `rate` its score.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, TS)]
#[serde(rename_all = "lowercase")]
pub enum Kind {
/// the probability of yes
@@ -25,7 +26,7 @@ pub enum Kind {
}
/// What of the picture a question looks at.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, TS)]
#[serde(rename_all = "lowercase")]
pub enum Sees {
/// the moving picture (2 frames a second, at most a minute)
@@ -38,7 +39,7 @@ pub enum Sees {
}
/// Its options are the files it's given, in order (first, second ...), or all but the first, which is the reference.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
#[serde(rename_all = "kebab-case")]
pub enum Picks {
All,
@@ -46,10 +47,12 @@ pub enum Picks {
}
/// What a piece must be for a question to be asked of it. Unset is any.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, TS)]
#[ts(optional_fields)]
pub struct When {
/// the brief's modes it's for (pitch, story, explain, play, tool); empty is every mode
#[serde(default, skip_serializing_if = "Vec::is_empty")]
#[ts(as = "Option<Vec<String>>", optional)]
pub modes: Vec<String>,
/// true: only when someone is heard speaking; false: only when no one is
#[serde(skip_serializing_if = "Option::is_none")]
@@ -60,7 +63,8 @@ pub struct When {
}
/// The seconds a question looks at; unset ends are the file's.
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize, TS)]
#[ts(optional_fields)]
pub struct Window {
#[serde(skip_serializing_if = "Option::is_none")]
pub from: Option<f64>,
@@ -69,7 +73,8 @@ pub struct Window {
}
/// How well a question's answers separate work with the problem from work without it, on labels (AK7).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(optional_fields)]
pub struct Calibration {
pub auc: f64,
pub n: u32,
@@ -84,34 +89,43 @@ pub struct Calibration {
}
/// A question, as the standard sets, a taste line, a batch file or the command line write it.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(deny_unknown_fields)]
#[ts(optional_fields)]
pub struct Question {
/// letters, digits, `_`, `.` and `-`
pub id: String,
/// the question in words, as clef reads it
pub ask: String,
#[serde(rename = "type", default)]
#[ts(rename = "type", as = "Option<Kind>", optional)]
pub kind: Kind,
/// choose: its options; grade and rate: its levels, lowest first (a grade's are LEVELS unless given)
#[serde(default, skip_serializing_if = "Vec::is_empty")]
#[ts(as = "Option<Vec<String>>", optional)]
pub options: Vec<String>,
/// what an option (or yes and no) means, when its name alone doesn't say
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
#[ts(as = "Option<BTreeMap<String, String>>", optional)]
pub means: BTreeMap<String, String>,
/// the answers that mean a problem: yes's "yes" (the default) or "no"; choose's options (none: a pick, no problem)
#[serde(default, skip_serializing_if = "Vec::is_empty")]
#[ts(as = "Option<Vec<String>>", optional)]
pub flags: Vec<String>,
#[serde(default)]
#[ts(as = "Option<Sees>", optional)]
pub sees: Sees,
/// whether it listens to the sound (true unless set)
#[serde(default = "yes", skip_serializing_if = "is_true")]
#[ts(as = "Option<bool>", optional)]
pub hears: bool,
/// what the state tells clef beside the media: brief, words (heard), screen-words, measures, brand, platform; and
/// with: it compares the file with the files set beside it, so it isn't asked without them
#[serde(default, skip_serializing_if = "Vec::is_empty")]
#[ts(as = "Option<Vec<String>>", optional)]
pub uses: Vec<String>,
#[serde(default, skip_serializing_if = "When::is_any")]
#[ts(as = "Option<When>", optional)]
pub when: When,
/// the question asked in its place when `when` doesn't hold (sound -> sound-silent)
#[serde(skip_serializing_if = "Option::is_none")]
@@ -122,6 +136,7 @@ pub struct Question {
pub picks: Option<Picks>,
/// words in a person's note that mean they saw this problem (AK6)
#[serde(default, skip_serializing_if = "Vec::is_empty")]
#[ts(as = "Option<Vec<String>>", optional)]
pub label_words: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub calibration: Option<Calibration>,
+12 -1
View File
@@ -1,7 +1,18 @@
use super::*;
use serde_json::json;
const RUBRIC: &str = include_str!("../../../sdk/guides/craft/verbs/critique.md");
const RUBRIC: &str = include_str!("../../../sdk/guides/craft/rubric.md");
#[test]
fn declarations_match_the_committed_file() {
let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../sdk/raea/src/ask.gen.ts");
let now = declarations();
if std::env::var_os("RAEA_WRITE").is_some() {
std::fs::write(path, &now).unwrap();
}
let committed = std::fs::read_to_string(path).unwrap_or_default();
assert!(committed == now, "sdk/raea/src/ask.gen.ts is out of date: RAEA_WRITE=1 cargo test -p raea-core-ask");
}
#[test]
fn every_standard_question_reads_and_fits_the_limits() {
+6 -3
View File
@@ -73,7 +73,7 @@ pub struct Goal {
#[serde(default)]
#[ts(as = "Option<Vec<String>>", optional)]
pub deliverables: Vec<String>,
/// read by nothing: the critic rounds it capped are gone (docs/check.feature); kept so a brief that sets it parses
/// the most critic rounds the job gets; at the cap it is delivered with what's still missing (8 by default)
pub rounds: Option<u32>,
/// a cut job's contract: the brief as rules (cut.rs)
pub cut: Option<crate::cut::Cut>,
@@ -84,7 +84,7 @@ pub struct Goal {
#[serde(default)]
#[ts(as = "Option<Vec<String>>", optional)]
pub previews: Vec<String>,
/// raea's packs switched by name over the kind's defaults (`{ voice: true, place: false }`): which of
/// raea's packs switched by name over the kind's defaults (`{ surprise: true, place: false }`): which of
/// raea/goal's rules hold this goal (docs/goal.feature)
#[serde(default)]
#[ts(as = "Option<BTreeMap<String, bool>>", optional)]
@@ -229,7 +229,7 @@ pub struct Shot {
}
impl Kind {
/// as brief.ts writes it
/// as brief.ts writes it, and as raea judge's rubrics are named
pub fn name(self) -> &'static str {
// in the enum's order
["scene", "kit", "shot", "cut", "rules", "playable"][self as usize]
@@ -248,6 +248,9 @@ pub fn dials(kind: Kind) -> &'static [&'static str] {
}
}
/// The round cap when the plan names none: AnyKit's and raea judge's 8.
pub const ROUNDS: u32 = 8;
/// 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.
pub fn deliverables(m: &Goal) -> Vec<String> {
+1 -1
View File
@@ -22,7 +22,7 @@ pub struct Rule {
pub timeout: Option<u32>,
/// a file that must exist, relative to the brief (`a|b`: either; `dir/`: three or more pictures in it)
pub file: Option<String>,
/// words the work should make true, which nothing checks (docs/check.feature): hold them with a `run` or `file` rule
/// words that must be true of the work, judged by a fresh critic (`raea goal judge`), never by the agent that did it
pub says: Option<String>,
}
+3 -8
View File
@@ -135,7 +135,7 @@ pub const KEEP_BUFFER_AT: usize = 1 << 16;
/// (buffers/NAME.json, NAME its content's BLAKE3), so what holds the shape holds 40 characters
/// (docs/render-memory.feature RM8). halcyon's palms were 263 MB of vertex arrays as text, held by the React scene,
/// every frame's program row, the store and the evaluator: two of them 51 MB each. None for a short one, one already
/// kept, or when the caches folder can't be written (the text then goes as it is). The folder is pruned (kept.rs).
/// kept, or when the caches folder can't be written (the text then goes as it is).
pub fn kept_buffer(expr: &str) -> Option<String> {
let json = expr.strip_prefix("buffer:")?;
if json.len() < KEEP_BUFFER_AT || json.starts_with('@') {
@@ -145,10 +145,7 @@ pub fn kept_buffer(expr: &str) -> Option<String> {
let name = &hex.as_str()[..32];
let dir = crate::kept::caches()?.join("buffers");
let p = dir.join(format!("{name}.json"));
if p.exists() {
crate::kept::touch(&p);
} else {
crate::kept::prune_once(&dir);
if !p.exists() {
let part = dir.join(format!(".{name}.{}.part", std::process::id()));
std::fs::create_dir_all(&dir).ok()?;
std::fs::write(&part, json).ok()?;
@@ -164,9 +161,7 @@ pub fn buffer_json(b: &str) -> Result<std::borrow::Cow<'_, str>, String> {
return Err(format!("buffer:@{name}: not a kept buffer's name"));
}
let p = crate::kept::caches().ok_or("no caches folder for a kept buffer")?.join("buffers").join(format!("{name}.json"));
let json = std::fs::read_to_string(&p).map_err(|e| format!("buffer:@{name}: {}: {e}", p.display()))?;
crate::kept::touch(&p);
Ok(std::borrow::Cow::Owned(json))
std::fs::read_to_string(&p).map(std::borrow::Cow::Owned).map_err(|e| format!("buffer:@{name}: {}: {e}", p.display()))
}
#[cfg(test)]
+4 -77
View File
@@ -4,80 +4,9 @@
//! program's size and time: another build may cut differently), and read back as the bytes that were written, so
//! what is drawn from it is what would have been made. RAEA_SHAPE_CACHE=0 turns it off, =DIR moves it from raea's
//! caches folder (shapes/ in it).
//!
//! The kept folders (shapes/ here, buffers/ for buffer.rs's kept BufferMesh text) are pruned once a process, at its
//! first write into each: the least recently used files go until the folder holds KEEP_BYTES, and none read or written
//! in the last IN_USE goes. Every read touches its file, so a buffer a running scene names stays. Unpruned, buffers/
//! grew by an animated BufferMesh's ~10 MB a frame and filled the disk.
use crate::Tris;
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime};
/// What each kept folder holds before its least recently used files go.
const KEEP_BYTES: u64 = 4 << 30;
/// A kept file read or written this recently stays, whatever its folder holds: a render reads its buffers as its frames
/// draw, and none may go mid-render. Two hours, as a render's work folder is kept (raea-runtime-bundle's sweep).
const IN_USE: Duration = Duration::from_secs(2 * 3600);
/// A kept file just used: its time moved on, so the prune takes the least recently used first.
pub(crate) fn touch(p: &Path) {
let _ = std::fs::File::options().append(true).open(p).and_then(|f| f.set_modified(SystemTime::now()));
}
/// `dir` pruned (prune), the first time this process writes into it.
pub(crate) fn prune_once(dir: &Path) {
static DONE: std::sync::Mutex<Vec<PathBuf>> = std::sync::Mutex::new(Vec::new());
{
let mut done = DONE.lock().unwrap_or_else(|e| e.into_inner());
if done.iter().any(|d| d == dir) {
return;
}
done.push(dir.to_path_buf());
}
prune(dir, KEEP_BYTES, SystemTime::now());
}
/// Whether a file's name is one this cache writes: a shape (`<hex>-<hex>.tris`), a buffer (`<32 hex>.json`), or either's
/// write cut short (`.<that>.<pid>.part`). RAEA_SHAPE_CACHE may name a folder that holds other files: the prune never
/// takes those.
pub(crate) fn ours(name: &str) -> bool {
let hex = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_hexdigit());
let kept = |n: &str| {
n.strip_suffix(".tris").and_then(|b| b.split_once('-')).is_some_and(|(a, b)| hex(a) && hex(b))
|| n.strip_suffix(".json").is_some_and(|b| b.len() == 32 && hex(b))
};
match name.strip_prefix('.').and_then(|n| n.strip_suffix(".part")).and_then(|n| n.rsplit_once('.')) {
Some((n, pid)) => pid.bytes().all(|b| b.is_ascii_digit()) && (kept(n) || hex(n)),
None => kept(name),
}
}
/// The cache's own files in `dir` (ours; a write cut short too) removed least recently used first while they hold more
/// than `keep` bytes, stopping at the first used within IN_USE of `now`.
pub(crate) fn prune(dir: &Path, keep: u64, now: SystemTime) {
let mut files: Vec<(SystemTime, u64, PathBuf)> = std::fs::read_dir(dir)
.into_iter()
.flatten()
.flatten()
.filter(|e| ours(&e.file_name().to_string_lossy()))
.filter_map(|e| {
let m = e.metadata().ok().filter(|m| m.is_file())?;
Some((m.modified().ok()?, m.len(), e.path()))
})
.collect();
files.sort();
let mut held: u64 = files.iter().map(|f| f.1).sum();
for (t, n, p) in files {
if held <= keep || !now.duration_since(t).is_ok_and(|age| age >= IN_USE) {
break;
}
if std::fs::remove_file(&p).is_ok() {
held -= n;
}
}
}
use std::path::PathBuf;
/// raea's caches folder, as raea-io-home names it (this crate is below it): ~/Library/Caches/raea on macOS,
/// %LOCALAPPDATA%\raea\cache on Windows, $XDG_CACHE_HOME/raea or ~/.cache/raea elsewhere.
@@ -146,14 +75,13 @@ pub(crate) fn files_read(expr: &str) -> Vec<u8> {
const MAGIC: &[u8; 8] = b"raeatri1";
/// The mesh kept at `p` (touched: used now): None when there is none or it isn't whole (a write that was cut short).
pub fn read(p: &Path) -> Option<Tris> {
/// The mesh kept at `p`: None when there is none or it isn't whole (a write that was cut short).
pub fn read(p: &std::path::Path) -> Option<Tris> {
let b = std::fs::read(p).ok()?;
let n = u64::from_le_bytes(b.get(8..16)?.try_into().ok()?) as usize;
if &b[..8] != MAGIC || b.len() != 16 + n * 24 {
return None;
}
touch(p);
let f = |at: usize| f32::from_le_bytes(b[at..at + 4].try_into().unwrap());
let run = |from: usize| (0..n).map(|i| [f(from + i * 12), f(from + i * 12 + 4), f(from + i * 12 + 8)]).collect::<Vec<_>>();
Some(Tris { positions: run(16), normals: run(16 + n * 12) })
@@ -161,7 +89,7 @@ pub fn read(p: &Path) -> Option<Tris> {
/// `t` kept at `p`, written beside it and moved into place so a reader never sees half of it. Failing is fine: the
/// mesh is made again next time.
pub fn write(p: &Path, t: &Tris) {
pub fn write(p: &std::path::Path, t: &Tris) {
if t.positions.len() != t.normals.len() {
return;
}
@@ -174,7 +102,6 @@ pub fn write(p: &Path, t: &Tris) {
}
}
let Some(dir) = p.parent() else { return };
prune_once(dir);
let part = dir.join(format!(".{}.{}.part", p.file_name().unwrap_or_default().to_string_lossy(), std::process::id()));
if std::fs::create_dir_all(dir).is_ok() && std::fs::write(&part, b).is_ok() && std::fs::rename(&part, p).is_err() {
let _ = std::fs::remove_file(&part);
-37
View File
@@ -270,43 +270,6 @@ mod tests {
std::fs::remove_dir_all(&dir).unwrap();
}
/// The prune with old times: the least recently used go first until the folder is under its budget, and a file used
/// within the last two hours stays even over it
#[test]
fn a_kept_folder_is_pruned_least_recently_used_first() {
let dir = std::env::temp_dir().join(format!("raea-shape-prune-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let now = std::time::SystemTime::now();
let hours = |h: u64| now - std::time::Duration::from_secs(h * 3600);
// 100 bytes each: three days, two days, a day, and one hour since last used
const A: &str = "00000000000000aa-10.tris";
const B: &str = "0123456789abcdef0123456789abcdef.json";
const C: &str = ".00000000000000cc-10.tris.4242.part";
const D: &str = "00000000000000dd-10.tris";
// a file of the person's own, in a folder RAEA_SHAPE_CACHE named: never the cache's to take, however old
const MINE: &str = "render.mp4";
let files = [(A, hours(72)), (B, hours(48)), (C, hours(24)), (D, hours(1)), (MINE, hours(500))];
for (name, t) in files {
std::fs::write(dir.join(name), [0u8; 100]).unwrap();
std::fs::File::options().append(true).open(dir.join(name)).unwrap().set_modified(t).unwrap();
}
let left = || [A, B, C, D].map(|n| dir.join(n).exists());
kept::prune(&dir, 400, now);
assert_eq!(left(), [true; 4], "under the budget (the four the cache wrote): nothing goes");
kept::prune(&dir, 250, now);
assert_eq!(left(), [false, false, true, true], "the two least recently used go");
kept::prune(&dir, 0, now);
assert_eq!(left(), [false, false, false, true], "one used in the last two hours stays, past the budget");
assert!(dir.join(MINE).exists(), "a file the cache didn't write stays");
assert!(!kept::ours("notes.json") && !kept::ours("abc.tris") && kept::ours(B), "only the cache's own names");
// a read is a use: it moves the file's time on
kept::touch(&dir.join(D));
let t = std::fs::metadata(dir.join(D)).unwrap().modified().unwrap();
assert!(t > hours(1), "touched");
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn a_mesh_file_written_again_is_kept_under_a_new_key() {
let dir = std::env::temp_dir().join(format!("raea-shape-files-{}", std::process::id()));
-5
View File
@@ -1,10 +1,5 @@
@spec
Feature: Ask: questions about a piece's picture and sound, answered by the decision model and paid from the person's plan
Superseded by docs/check.feature (CK0) for everything but AK8: `raea ask`, `raea judge`, sdk/raea's `raea/ask` and
apps/judge are gone, and a model's opinion is no check. What stays is what the fingerprint's double-check reads
(`raea fingerprint score --ask`, apps/double): core/ask's questions, io/clef, and apps/ask's runner, record and
calibration. The scenarios below are the record of what was built.
Shane, 2026-11-20: "a decision reviewer type api that calls and utilizes their raea subscription ... for checks and
things, or extending checks to be done quickly based on audio and video, maybe even being able to ask a question
about how does this sound based on the visuals". Planned "so that it sufficiently understands first what is
+2 -2
View File
@@ -52,8 +52,8 @@ Feature: raea cloud: a synced folder is pictured, understood, embedded and organ
9x16 or 16x9; its length), and for each tag who said it and why
Scenario: IG6. raea's model reads first; the workspace's agent when there's none
(built 11-24 with raea's model as a vision model on OpenRouter, tagger.ts: description, role, client, tags with
why, on the item and its turbopuffer rows; the clef model (io/clef) takes its place when it's deployed)
Given the workspace's plan has raea's ask model (io/clef, docs/ask.feature: clef-omni on the plan's pool)
why, on the item and its turbopuffer rows; raea ask's clef model takes its place when it's deployed)
Given the workspace's plan has raea's ask model (raea ask, docs/ask.feature: clef-omni on the plan's pool)
Then the files are read by it, batched, the spend on the pool
Otherwise they are read by the workspace's own connected agent on raea cloud's box (Claude Code on its Claude, or
Antigravity on its Google AI plan), as a background job that never takes a project's turn
+4 -40
View File
@@ -91,8 +91,7 @@ Feature: raea cloud: raea and an ACP agent on a server of your own (sdk/cloud)
Scenario: CL14. A render job, and a GPU that sleeps when idle
Then POST /v1/jobs?args=JSON takes a project as a tar (zstd, gzip or none) and runs `raea ARGS` on it in a folder
of its own; GET /v1/jobs/ID?from=N follows its output in requests of 20 s at most (a serverless platform's
proxy cuts longer ones); GET /v1/jobs/ID/out returns the files it made or changed, as often as asked, and
DELETE /v1/jobs/ID drops the job once they have arrived (one nobody drops goes an hour after it ends)
proxy cuts longer ones); GET /v1/jobs/ID/out returns the files it made or changed, and the job is dropped
And deploy/modal/raea_cloud.py runs the image on a Modal GPU (an L4, else an A10G, else a T4, unless
RAEA_CLOUD_GPU names others or none), one container that starts on a request and stops after five idle
minutes, the token in a Modal secret
@@ -102,12 +101,10 @@ Feature: raea cloud: raea and an ACP agent on a server of your own (sdk/cloud)
job and lands what it made back in the project; its paths are made relative to the project, an output outside
it is moved to its place after, and an input outside it renders on the box with a line saying why
And a worker that can't be reached fails the render unless RAEA_CLOUD_GPU_FALLBACK=cpu
And a worker on another raea version than the box's fails the render before anything is sent, naming both,
unless RAEA_CLOUD_GPU_ANY_VERSION=1
And every other raea command runs on the box
Scenario: CL16. raea cloud's boxes are Fly Machines
Given the boxes were Sprites, which ran at most 10 at once, read their disk in about 26 ms a
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
@@ -116,7 +113,8 @@ Feature: raea cloud: raea and an ACP agent on a server of your own (sdk/cloud)
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), lists raea cloud's boxes (list) and puts every box on a release (latest)
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
@@ -126,37 +124,3 @@ Feature: raea cloud: raea and an ACP agent on a server of your own (sdk/cloud)
back, a second container handing its render to the first, an ACP turn round-tripped
And with Kimi Code signed in, one real turn renders a title card with raea in the container, and the file
comes back through /v1/files
Rule: a box edits on light copies, the farm renders from originals (12-05)
Scenario: CL17. Nothing on the box takes a light copy's place
Given raea cloud brought a run's footage as 540p light copies (footage/NAME.mp4, listed in .raea-cloud/light.txt)
Then every look the agent takes (a still, a frame, a probe, a check of its words) reads the light copy
And no file ever replaces footage/NAME.mp4 on the box, before a render or after one
Scenario: CL18. A farm render reads each light copy as its original, fetched by the farm
Given .raea-cloud/originals.json names a light copy's original: its hash, size and a link that hasn't ended
When a render that reads the light copy goes to the farm (server/offload.ts)
Then its media manifest names the original under the light copy's path, with its link, and the light copy's own
bytes go nowhere
And the farm fetches the original from the library into its cache, checks it against its hash, and keeps it for
every later render; the box never downloads it, hashes it or sends it
And a light copy the render doesn't read is left out, its original included
And a size raea cloud doesn't know goes as 0, which the farm takes with a link and never without one
Scenario: CL19. An original with no link goes from the box
Given a light copy whose original has no hash, or whose link ends within 5 minutes
When its original is in footage/originals/ under the light copy's name (any extension)
Then the render sends that file by its own hash, under the light copy's path
And only a farm with its media cache gets an original by its file (by LFS or in the tar it would go as the light
copy), and only that farm an original of unknown size: for any other the take is rendered as its light copy
And .raea-cloud/proxies/ never goes in a render's tar, and an original no source names stays on the box
Scenario: CL20. A render that read a light copy says so
Given a light copy with no original either way
Then the render prints NO ORIGINAL with its name, and is rendered from the light copy
And its manifest records {"originals": {"read": [...], "light": [...]}} (a still's in OUT.render.json beside it),
checked or not, from which raea cloud marks it a draft that is never shown or published
And the farm's media list holds each original by its link in its light copy's place, with everything else that
went (12-05 review: the farm-cache path dropped the links while the manifest said they were read)
And an original of unknown size over 40 GB is refused as it downloads, before it fills the farm's volume
And test/originals.ts and test/farm_media.py check CL17-CL20
+11 -10
View File
@@ -68,7 +68,7 @@ Feature: Direction that holds: one world of facts, findings and rules, so a pers
| an edit as rows and keyed columns | core/program (ir, eval, timeline) | the renderer's own; nothing queries it for checks |
| what each frame shows, as laid out | `raea render --manifest` (runtime/export/src/lib.rs write_manifest): each text's words and box, each video's source and time, the 3D's clipping, the sounds heard, the layers | written only when asked for; read by `raea check` alone; its clipping list is a second copy of what was printed |
| parts that clip, float, sink | systems/contact (every render), `raea scene lint` | findings are printed text or loose JSON `{check, level, says}` |
| an export's floor | apps/check (`raea check`: text, picture, flash, sound; `--taste`) | its own `Issue {rule, p, at, says}`; exports only |
| an export's floor | apps/check (`raea check`: text, picture, flash, sound; `--quick`; `--taste`) | its own `Issue {rule, p, at, says}`; exports only |
# `raea check` reads a video through FFmpeg where it's installed and through raea's own decoders where it isn't
# (apps/check/read; RAEA_CHECK_NATIVE=1 forces them): the same findings either way, held there by tests/parity.rs.
# 0.1.7 refused any video without FFmpeg, though `raea media probe` and `loudness` never needed it.
@@ -192,7 +192,7 @@ Feature: Direction that holds: one world of facts, findings and rules, so a pers
Then the frame is one world: its 3D items, timeline, clips and cues read as `raea scene lint` reads a 3D frame
today (React stepped, no engine, no GPU)
And the page's text and boxes come from the page's layout, which before this only a render did (the manifest's
"as laid out"): this scenario adds a layout-only
"as laid out", which `raea check --quick` gets by rendering three stills): this scenario adds a layout-only
pass (the render's own page synced and laid out by the main world's schedules, the render world's never run,
so nothing is drawn); with `--no-layout`, or where the page can't be made, its text carries `needs: "render"`
And its entities carry these components, each field measured, none typed by the author:
@@ -273,13 +273,13 @@ Feature: Direction that holds: one world of facts, findings and rules, so a pers
Scenario: DR3. One finding, for every command
# Status 11-10: built. One Finding (core/facts finding.rs: its check; error, warn or note; the entities it is
# about; frames; says; measure; fix; by) is all these write: the render's clipping (systems/contact found.rs) and
# exposure (light-meter), `raea scene lint|light`, `raea check` (--taste), `raea gen check`, `raea make solid
# info --expect`, `raea project scan`, raea/room's checkLayout and checkDecor. Every render (a video,
# exposure (light-meter), `raea scene lint|light`, `raea check` (--quick, --taste), `raea gen check`, `raea make solid
# info --expect`, `raea project scan`, raea/room's checkLayout and checkDecor, `raea judge`. Every render (a video,
# --at stills, a still, --review, a .wav) says them, writes them into its manifest and counts them on its last
# line; an error exits 1 unless `--despite CHECK WHY` (RAEA_DESPITE for harnesses that compare pixels). Each run of
# a file in a project keeps one entry in .raea/record/: what, what it wrote and its kind, the commit (+ when the
# file had changed), the findings, what was let through. A render that is part of another (a review's tiles,
# solid view's scene) keeps none. `raea findings` sets each thing's latest run against the
# file had changed), the findings, what was let through. A render that is part of another (a review's tiles, a
# quick check's stills, solid view's scene) keeps none. `raea findings` sets each thing's latest run against the
# one before of its kind and lists new, carried (since which run), renamed, fixed and let through; `raea goal next`
# steps by it: fix what the last render found, render the video, again once the composition changed, check it,
# polish what the check found, show it.
@@ -300,7 +300,8 @@ Feature: Direction that holds: one world of facts, findings and rules, so a pers
# frame; gen check's fitted fixes were JSON; a review kept 13 entries (one a tile) and was set against videos; a
# video copied from the export cache said nothing it had found; a review's right, top and iso cameras kept the
# scene camera's Transform rotation, so they faced its way and those tiles were empty.
# Not seen, or left: a part scaled to nothing or deleted reads as fixed (DR16's relations know what a part rests on);
# Not seen, or left: `raea judge` wasn't run on a real clip (a model call costs; its Findings are tested on
# fixtures). A part scaled to nothing or deleted reads as fixed (DR16's relations know what a part rests on);
# renamed and moved at once reads as fixed and new, though the error still stands in the count. The clipping
# check passes an overlap under 4% of the smaller part's diagonal (DEPTH_SHARE), so the render's own move left the
# crate 5.3 cm in the pillar, which the top view shows. The review's top tile has +x to the left.
@@ -318,8 +319,8 @@ Feature: Direction that holds: one world of facts, findings and rules, so a pers
# for Finding, holds it instead, and the registry's `up` (the nearest .raea/project) moved there with it.
| raea-app-direction | apps/direction/src/findings.rs | 160 | `raea findings` |
Then these write Findings and nothing else: the render's clipping check, `raea scene lint|light`, `raea check`
(and --taste), `raea gen check`, `raea make solid info --expect`, `raea project scan`, raea/room's
checkLayout and checkDecor
(and --quick, --taste), `raea gen check`, `raea make solid info --expect`, `raea project scan`, raea/room's
checkLayout and checkDecor, `raea judge`
And each finding names the entities it is about (the two parts that clip, the text that is cut off), so
"everything found about this part" is a query
And every render, video or `--at` stills, writes its findings into its manifest and prints their count last,
@@ -903,4 +904,4 @@ Feature: Direction that holds: one world of facts, findings and rules, so a pers
Scenario: DR27. Not in this plan
Then no film is repaired here: the abandoned one stays as it is
And no new kind of renderer, no new asset store, and no model or generation service is added
And no model judges taste (docs/check.feature); here taste is the person's signature on a clip
And judging taste by a model is as it is (`raea judge`); here taste is the person's signature on a clip
-4
View File
@@ -20,10 +20,6 @@ Feature: raea/foliage, plants grown from their species and drawn through the yea
Leaves and bark are made in code (a leaf's outline, teeth, veins and blotches from its shape's rules; bark's
fissures from noise in the shader), never photographed, so a species is a table of numbers and a seed.
The crate that grew them, raea-sys-foliage (systems/foliage), was removed while nothing called it: no verb, native
call or SDK module reached it. It comes back with FO10's caller, from the commit before its removal
(`git checkout 02051ee9 -- systems/foliage`, then its workspace member and its two tools/layers.toml entries).
Rule: 1. Plants
Scenario: FO1. A tree grown from its species
+48 -36
View File
@@ -218,7 +218,7 @@ Feature: Goal: the loop every piece of work runs, one goal or a workflow of them
And a part's plan is its own `lod` (Mesh3d, Model, and every part inside an Entity with a transform or a Group
that has one), else the `lod` of the plan's object of its name
When a frame shows a planned part at a finer level than its plan (raea-runtime-lod-plan)
Then the render's end checks and `raea scene stage` say `lod-closer`: the part, its plan,
Then the render's end checks, `raea scene stage` and `raea check --quick` say `lod-closer`: the part, its plan,
the level it is seen at, how much of the frame it spans at its largest and on which frame, how many frames it
is closer on, and the fix (build it for that level and plan it there, or keep the camera off it)
And one level finer is a warning, two or more an error, which fails the render as any error does
@@ -431,8 +431,8 @@ Feature: Goal: the loop every piece of work runs, one goal or a workflow of them
When it saves a composition, brief.ts or a check
Then the hook runs `raea goal check FILE --at edit` on a saved composition, or on any file under a brief with a
`make` job, and hands back what it found when it fails
# Removed with the stills pack (docs/check.feature CK1): nothing is checked after a save; a render checks its
# own output at its end
And the quick check is the stills pack (`at: ["edit"]`), which reads apps/check's three-stills measure; the hook
has no path of its own to it
@needs:MK32
Scenario: MK34. Render: every render ends with the render moment
@@ -524,8 +524,8 @@ Feature: Goal: the loop every piece of work runs, one goal or a workflow of them
check`, `raea sound check`, `raea frames place`, `--plan`, plan.org, the hook's quick path, runtime/cut-plan and
runtime/goal-plan, sdk/cloud/server's check code, raea cloud's make-checks logic, publish gate, naming and count
checks, and the method paragraphs (RAEA, SOUND, CRAFT, NAMING, SIZES)
And `raea check` stays a top-level instrument (MK45): its VIDEO measures are what the floor pack reads (--quick and
--taste are gone, MK47); it never decides done
And `raea check` stays a top-level instrument (MK45): its VIDEO and --quick measures are what the floor and stills
packs read, and its taste lines are held by the taste pack (MK47); it never decides done
And every project's first message carries one paragraph on the loop: write the contract, work, run
`raea goal check`, fix what it names, until it says done
And `rg` over raea, raea-platform, raea-skills and raea-feed finds none of the gone names outside this file and
@@ -580,8 +580,9 @@ Feature: Goal: the loop every piece of work runs, one goal or a workflow of them
or shot goal's steps (`make blockout|refs|gen|pick-sheet|pick|prep|kit|framing|lenschart|place`)
And the instruments stay top-level, shared by every goal: `check`, `world`, `ask`, `judge`, `findings`, `scene`,
`media`, `words`, `song`, `track`; they measure and never decide done
And an old name is refused with where it went (`raea make check` is gone, `raea check` is the one check; `raea
clothes` is now `raea make clothes`), never run under it; a name older than the release before is no verb at all
And an old name is refused with where it went (`raea make check` is now `raea goal check`; `raea clothes` is now
`raea make clothes`; `raea make plan` is now `raea make blockout`; `raea next` is now `raea goal next`; `raea
part` is gone), never run under it
And docs/make.feature is this file, and the help, the manual, the guides and the skill teach only the new names
@needs:MK31
@@ -600,12 +601,13 @@ Feature: Goal: the loop every piece of work runs, one goal or a workflow of them
And core/brief's doctor says a name given twice and an `after` naming no goal
And core/brief tests and sdk/goal/test/contract.test.ts hold it
@done
Scenario: MK47. No rule a project registers runs inside an agent's loop
Given taste lines (the person's, the workspace's, the project's) and a person's signed asks
Then none runs inside an agent's loop: the taste pack is gone and `raea check --taste` is refused (engine/cli/goal
gone()), so the one check (check.feature) is the only check an agent's work meets
And the story SDK's checks are a goal's `checks`, never a file of their own
@needs:MK43 @needs:MK45
Scenario: MK47. Every rule a project registers runs inside the loop
Given taste lines (the person's, the workspace's, the project's) with checks, and a person's signed asks (raea notes)
Then the taste pack runs them through `raea check`'s rules at the moments they name, and their findings are the
goal check's, so no registered rule runs only when an agent remembers an instrument
And the story SDK's checks (raea/story `storyCheck`) are taste-line checks or a goal's `checks`, never a file of
their own that nothing runs
Rule: The cut, read as an editor reads it (Shane, 11-29: Kuleshov, Eisenstein's methods of montage, Murch's Rule of Six)
@@ -614,30 +616,40 @@ Feature: Goal: the loop every piece of work runs, one goal or a workflow of them
# in fMRI), Eisenstein's collision of shots, Murch's six reasons for a cut weighed emotion 51%, story 23%, rhythm
# 10%, eye trace 7%, the screen's plane 5%, its 3D space 4%, given up from the bottom. Murch's weights are his
# judgment, not measurements: raea uses them as an order, never as a score. The story SDK says what a piece is
# about; these say what each cut does to it. Status 11-29: built in raea #269. 12-06: the montage pack and the beat
# critic are out (check.feature: one check, nothing grades an agent's plan); the craft stays in the guide.
# about; these say what each cut does to it. Status 11-29: built in raea #269 (sdk/goal packs/montage.ts,
# test/montage.test.ts; core/brief cut.rs Beat).
@done
Scenario: MK48. A cut's beats are the agent's plan, in its notes, never brief.ts
Given an agent planning a cut beat by beat (what each part makes the viewer feel and understand, and its pace)
Then the plan is in its notes, never in brief.ts, which holds only what the brief asks (check.feature), and the
guides say so (craft/story/montage.md, craft/motion/brief.md)
And a brief.ts that still has `beats` is read as before (core/brief keeps the field) and nothing grades them
Scenario: MK48. A cut plan's beats say what each part must make the viewer feel and understand, before it's cut
Given a cut goal's plan (`cut({ cuts: [{ id, beats: [...] }] })`)
Then each beat has `at` (seconds from the cut's start, the first at 0, in order) and `feel` in the person's words,
and may say `story` (what the viewer understands by its end), `asl` (its average shot length in seconds) and
`tempo` ("build": shots shorter as it goes, "release": longer, "hold": even)
And core/brief's doctor says a beat out of order, one with no feel, a tempo that isn't one of the three and an asl
that isn't above 0
And Dutch's cuts fail today: none says what any of its parts should make anyone feel
@done
Scenario: MK49. No critic judges a cut's emotion or story
Given a cut
Then no model is asked whether it makes the viewer feel its beats: `raea goal judge` is gone (engine/cli/goal
gone()), and emotion and story stay the editor's, from the guide, never a score
Scenario: MK49. Emotion and story are judged on the cut in sequence, by a fresh critic
Given a cut goal whose plans have beats
Then each beat is a `says` rule (`beat_<cut>_<n>`, contract.ts saysOf): "in out/cuts/<cut>_<W>x<H>.mp4, from A s
to B s, watched in sequence as cut, the viewer feels <feel>, and by its end understands <story>", judged by
`raea goal judge` with the goal's own `says` rules and held by the says pack at done
And it's asked of the shots as cut, never one by one: what a shot means comes from its neighbours (Kuleshov)
And no measure stands in for them: they're Murch's top two, 74% of his weight
@done
Scenario: MK50. No pack measures a cut against the agent's own plan
Given a brief.ts that names the montage pack (`packs: { montage: true }`)
Then the pack is skipped and the check's doctor says it's gone and why (sdk/goal run.ts GONE_PACKS), never a crash
And sdk/goal/test/contract.test.ts holds it
Scenario: MK50. Each beat's pace is its plan (Eisenstein's metric montage)
Given a delivered cut whose plan's beats say `asl` or `tempo`
Then the montage pack finds its hard cuts in its own frames (one ffmpeg pass, 48 pixels wide) and, for each beat,
its shots must average within a third of its asl, and a build's shot lengths must shorten (Kendall's tau under
-0.2), a release's lengthen (over 0.2), with three shots or more; each miss is an error naming the beat's feel,
the lengths it has and which way to go
And sdk/goal/test/montage.test.ts holds it
@done
Scenario: MK51. Eye trace, screen direction and tone are the editor's, in Murch's order
Given any cut
Then the guide gives Murch's order for what to give up first (craft/story/montage.md), and no check measures eye
trace, screen direction or tone; a cut on a word stays the one check's (sound)
Scenario: MK51. Eye trace, screen direction and tone across every cut, in Murch's order
Given any delivered cut (`packs: { montage: false }` switches it off)
Then at each cut: the focal point on the two sides (the largest face the scene reader finds, else where the
frame's contrast gathers) more than 0.4 of the frame's diagonal apart is an eye-trace warning; sideways motion
on both sides (over 0.15 widths a second) in opposite directions is a screen-direction warning; a jump in
brightness over 0.25 or warmth over 0.08 where no beat starts is a tonal warning
And each finding names its Murch weight, so a fix never gives up a higher reason for a lower one
And one of them broken at more than half a file's cuts is an error: a habit of the cut, not a choice
And a cut on a word stays the sound pack's (edit-on-sound), so no rule is held twice
+3 -2
View File
@@ -19,7 +19,7 @@ Feature: One project layout: compositions, components, assets, artifacts; and th
Built 11-12 (lane layout): LY1 (raea project new and workspace init make the folders, .gitattributes, AGENTS.md
and the @shared/ tsconfig), LY2 (the loader resolves @shared/, PJ8's lint takes it), LY3's scan and lint and
controllers over shared/controllers/, and LY4's `raea make component`. Still to do: LY3's
controllers over shared/controllers/, and LY4's `raea make component` (`raea part` still answers). Still to do: LY3's
app pages (Compositions, Controllers, Source), LY4's examples/components rename and the guides and skill wording,
LY5 (`raea project tidy`), LY6.
@@ -77,6 +77,7 @@ Feature: One project layout: compositions, components, assets, artifacts; and th
When `raea make component list` or `raea make component add reel [--shared]` runs
Then it lists and copies raea's sets as `raea part` did, into components/<set>/ (or shared/components/<set>/)
And examples/parts is examples/components, and registry.gen.ts is packed from it
And `raea part ...` still works for this release, saying once that it's `raea make component` now
And the guides, the raea skill and AGENTS.md say components, never parts
Scenario: LY5. An existing project moves into the layout with one command
@@ -89,7 +90,7 @@ Feature: One project layout: compositions, components, assets, artifacts; and th
project's feed items, render manifests and checks name
And --dry-run prints the moves and rewrites and changes nothing
And it proves the move before it commits: the scan has no new lint, tsc passes if it passed before, and each
composition's first frame renders as it did (raea render --at 0); a failure undoes the move
composition's first frame renders as it did (raea check --quick); a failure undoes the move
And it is one commit per project, moves as renames (git mv), so history follows each file
And the workspace's root artifacts/ move to shared/ the same way (`raea workspace tidy`)
+1 -1
View File
@@ -18,7 +18,7 @@ Feature: The Linux engine, as fast as it can be in the cloud
What that says:
- On a graphics card the GPU is idle (a wait of 0.01-0.06 ms): a frame is all CPU. React on QuickJS (no JIT; the Mac
runs JavaScriptCore at 1.0-1.7 ms for the same frames, docs/rerender.feature RR0) and sync (the page synced and
drawn and the 3D prepared: RAEA_FRAME_LOG's sync, runtime/export/src/fed.rs) are 83-85% of it, the rest more of the main
drawn and the 3D prepared: runtime/export/src/fed.rs's FrameLog) are 83-85% of it, the rest more of the main
thread's own work (RAEA_TIMES' fed is 98% of the frame on the A10G).
- So the host's CPU sets the speed, not the card: the L4 loses to the A10G on the CPU side alone, with the same idle
GPU. Hosts under one GPU kind differ too: A10G hosts ran 1.52-2.11 s on one single-thread probe (Intel with AVX-512
+13 -3
View File
@@ -72,9 +72,19 @@ A raea MP4 is standard but large. For a copy any player and any upload takes, re
ffmpeg -i film.mp4 -c:v libx264 -preset slow -crf 23 -maxrate 2600k -bufsize 5200k -pix_fmt yuv420p -c:a aac -b:a 128k -movflags +faststart film-share.mp4
```
## The check
## The quick check
A render checks its own export at its end. To check one again, render with a manifest, then check the export:
```sh
raea check piece.tsx --quick
```
The quick check renders three stills of a composition and measures its text: clipped, cramped, inside the safe areas
and large enough to read. It takes about a second. Run it after every save. Add `--platform tiktok` (or `reels`,
`shorts`) to check against that platform's buttons and captions.
## The full check
Render with a manifest, then check the export:
```sh
raea render piece.tsx -o piece.mp4 --manifest render.json
@@ -82,7 +92,7 @@ raea check piece.mp4 --manifest render.json --words words.json --platform tiktok
```
The manifest records where every element was on every frame, so the check can say which element a problem belongs
to. The check measures:
to. The full check measures:
- clipped text, text under the platform's buttons, and text over a face
- captions on screen too briefly to read, and caption contrast against the pixels behind them
+13 -3
View File
@@ -40,9 +40,19 @@ fingerprint.ts and teach it like any other.
## Things in a shot
How a 3D shot's things sit and move (a thing floating or passing through another, a camera that lurches, an empty
frame) is checked from what raea drew: `raea scene stage` before the render, and the render's own end checks from its
manifest. Nothing reads it back off the frames, and `raea check --things` is gone.
```sh
raea render shot.tsx --layers -o shot.mp4 # the video and its layers (shot.layers)
raea render shot.tsx --aov -o shot.aov # its depth, beside it
raea fingerprint things shot.mp4 --json > things.json
raea check shot.mp4 --things things.json
```
`things` finds a piece's shots, the things in each (a render's layers, and anything marked on its notes) with their
depth, and the camera's path. It says where a thing floats, where two pass through each other, where the camera lurches
in the middle of a move, and where nothing is on screen. `raea check --things` turns those into findings beside the
rest. Floating needs real depth: with the render's `--aov` pass beside it (`shot.aov` for `shot.mp4`) it uses the
render's own depth, and without one it estimates depth from the picture, which can't always tell a hanging box from
one on the floor.
## Profiles of work you admire
+97
View File
@@ -0,0 +1,97 @@
---
title: "raea ask"
summary: "Ask about a piece's picture and sound: clef-omni answers in words and a probability, paid from your raea plan, and every answer is kept so a question can be calibrated."
order: 131
sources: ["apps/ask/src/verbs.rs", "apps/ask/src/prepare.rs", "apps/ask/src/runner.rs", "apps/ask/src/labels.rs", "apps/ask/src/calibrate.rs", "io/clef/src/route.rs", "core/ask/src/library.rs"]
---
`raea ask` puts questions about a video, a sound or a picture to clef-omni, the decision model raea's checks use, and
prints each answer in words with its probability, the window it looked at and what it cost. Ask in your own words, or
use the standard questions: the craft rubric's (`rubric`), picture and sound together (`av`), the defects the
fingerprint can't judge yet (`defects`), the platform checks (`platform`), picking between versions (`decide`) and the
gate questions about the sheets [`raea make`](make.md) draws for a scene, kit or shot goal (`make`). `raea ask list` lists them all.
Before it spends anything it reads what it can about the piece: what the file holds, the project's brief (the nearest
`brief.ts` above the file, or `--brief`) and whether anyone speaks (`--words`, `--voice`). A question that doesn't
apply isn't asked, and its line says why: a sound question of a silent file, or the rubric's `sound` question of a piece
where no one speaks, which asks `sound-silent` instead. Every question about the same clip goes in one call, and
many questions cost about what one does.
It pays from your raea plan's monthly pool when the raea app is signed in on Pro or Studio, or with an agent key
(`RAEA_AGENT_KEY` with `RAEA_API`) where the app isn't running, as in a pipeline or CI. Otherwise it uses your own
Cloudflare keys ([settings](../../settings.md)). When the pool is spent, the questions not yet asked wait for next
month, and their lines say so. The same question about the same media comes from a cache and costs nothing.
```sh
raea ask out/piece.mp4 "Does the music fight the voice?"
raea ask out/piece.mp4 --set av --brief brief.ts
raea ask out/piece.mp4 "Which ending lands harder?" --with out/v2.mp4 --std decide.best
raea ask out/piece.mp4 "Is the logo readable?" --at 12.5 --flag no
raea ask out/piece.mp4 --set defects --dry # what would be sent and its cost; nothing is spent
raea ask --batch asks.jsonl --json --gate # a pipeline: one JSON line an answer, exit 1 on a finding
```
A batch is a JSON list, or JSON lines, of `{file, questions?, set?, std?, window?, with?, brief?, words?, voice?,
state?}`, with `-` reading stdin. Its clips are each cut once, and its calls go four at a time (`--jobs`). Scripts can
ask through [`raea/ask`](../sdk/ask.md) instead.
Answers are advice until a question is calibrated against your own eye, and the answers say which they are. With
`--gate`, a calibrated question that flags exits 1; with `--gate any`, any question that flags does. Every call and
answer is kept in `~/.raea/ask` (`RAEA_ASK_DIR`), with the clips it cut, so that a question can be labelled and
calibrated later.
A question learns from three kinds of label. Your verdict on an answer comes first: `raea ask verdict ANSWER WORD`,
with the answer's id from `--json` and your own answer to the question (yes or no, an option, a level). Then your notes:
a note of yours on the render in the project's feed, inside the window it looked at, that holds one of the question's
label words says the problem was there, and a post you approved with no such note says it wasn't. An agent's own look
(`--eye agent`) is kept beside them and never counted.
`raea ask calibrate` reads your notes again and holds each labelled question to its labels. One with 16 labels of each
kind, from 3 projects, and an AUC of 0.8 or more is calibrated: it flags where 10% of your clean work would, its answers
are findings, and your calibration replaces the one raea ships. One under 0.6 after 32 labels doesn't separate, and
lists the labels it missed so its words can be fixed. `raea ask try "new words" --like ID` asks new words of that
question's labelled clips, kept from before, and prints both AUCs on the same labels.
```sh
raea ask verdict a-3f09c2e81b44 yes # yes, the music does fight the voice there
raea ask calibrate # every labelled question, where it stands
raea ask try "Is the voice hard to hear over the music?" --like own-does-the-music-fight-the-voice
```
<!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions -->
## Usage
```sh
raea ask FILE [QUESTION...] [--choose A,B,C] [--grade] [--rate N] [--flag ANSWERS] [--set NAME] [--std ID] [--from S] [--to S] [--at S] [--with FILE2] [--brief brief.ts|none] [--words words.json] [--voice yes|no] [--state TEXT] [--dry] [--json] [--gate [any]] [--jobs N] | ask --batch FILE [--dry] [--json] [--gate [any]] [--jobs N] | ask list [SET] [--json] | ask verdict ANSWER WORD [--eye NAME] | ask calibrate [ID] [--json] | ask try WORDS --like ID [--dry] [--json] [--jobs N] (questions about a piece's picture and sound, answered by clef-omni and paid from your raea plan's pool when the app is signed in, else RAEA_AGENT_KEY's, else your own Cloudflare keys: your own words, or the standard sets (rubric, av, defects, platform, decide, make); every question about one clip goes in one call, --batch (a JSON list or JSON lines, - for stdin) asks many clips in parallel; --dry says what would be sent and spends nothing; answers are advice until a question is calibrated: verdict labels an answer, calibrate holds each question to your verdicts, notes and approvals, try asks new words of its labelled clips)
```
Headless: it needs nothing running and opens no window. Takes any number of arguments besides its flags.
## Flags
| Flag | Takes | What it does |
| --- | --- | --- |
| `--at` | `S` | The three seconds around this moment: every question looks at that window. |
| `--batch` | `FILE` | A file of entries to ask, a JSON list or JSON lines (`-` reads stdin); each is a file with its questions. |
| `--brief` | `brief.ts\|none` | The project's brief, so clef knows who it's for and what it should do (else the nearest brief.ts above the file; `none` for no brief, when `--state` says what the piece is). |
| `--choose` | `A,B,C` | Your questions pick one of these options, rather than answering yes or no. |
| `--dry` | – | Cut the media and print each call that would be made (its state, questions, media sizes) with an estimated cost, and send nothing. |
| `--eye` | `NAME` | With `verdict`: the verdict is another eye's (an agent's own look), kept and never counted toward calibration. |
| `--flag` | `ANSWERS` | The answers that mean a problem: `no` for a question where no is bad ("Is the logo readable?"), or a choice's options. |
| `--from` | `S` | Where the window starts, in seconds. |
| `--gate` | – | Exit 1 when a calibrated question flags, or questions wait for the pool; `--gate any` exits 1 when any question flags. |
| `--grade` | – | Your questions answer on a graded scale (poor, weak, acceptable, strong, excellent). |
| `--jobs` | `N` | How many calls go at once (4). |
| `--json` | – | One JSON object a line: each answer, each call `--dry` would make, then the summary. |
| `--like` | `ID` | With `try`: the question whose labelled clips the new words are asked of. |
| `--rate` | `N` | Your questions answer with a score from 1 to N. |
| `--set` | `NAME` | A standard set to ask: rubric, av, defects, platform or decide (comma-separated for several). |
| `--state` | `TEXT` | More for clef to read before the media: what you measured, the platform it's for. |
| `--std` | `ID` | Standard questions by id (`raea ask list`), comma-separated. |
| `--to` | `S` | Where the window ends, in seconds. |
| `--voice` | `yes\|no` | Whether anyone speaks in it, when no words file says: it decides which of the voice questions' variants is asked. |
| `--with` | `FILE2` | Another file beside this one, to pick between or compare (repeat it for up to four in all). |
| `--words` | `words.json` | A words file (a JSON list of the words heard): clef reads what is said, and none heard means no one speaks. |
<!-- generated:end -->
+16 -8
View File
@@ -1,18 +1,22 @@
---
title: "raea check"
summary: "The one check: a project against every rule it holds, or an export against the floor: text, contrast, safe areas, freezes, flashing, cues and loudness."
summary: "Check a composition's text in a second, a project against every rule it holds, or an export against the floor: text, contrast, safe areas, freezes, flashing, cues and loudness."
order: 43
sources: ["apps/check/src/lib.rs", "apps/direction/src/check.rs", "sdk/raea/src/check.ts"]
sources: ["apps/check/src/lib.rs", "apps/check/src/quick.rs", "apps/direction/src/check.rs", "sdk/raea/src/check.ts"]
---
`raea check` is the one check. A render runs it on its own export at its end and keeps what it found in
OUT.check.json beside it; run it yourself to check an export again. On an exported video, it measures everything the
floor asks of a finished piece. Each finding is an error, a warn or a note (raea's one finding, as `raea scene lint` and a
`raea check` has two speeds. On a composition with `--quick`, it renders three stills and measures the text:
clipped, cramped, inside the safe areas, large enough to read, and what the stills' render found (3D parts clipping).
The stills are a quarter in, the middle and the last frame of the length a render of frame 0 reports, however
`durationInFrames` is written, and the report names them (`ok looked at frames 75, 150 and 299 of 300`).
That takes about a second, so run it after every save. On an exported video, it measures everything the floor asks
of a finished piece. Each finding is an error, a warn or a note (raea's one finding, as `raea scene lint` and a
render's manifest have it), says on which frames and how to fix it, and the command exits 1 while an error stands.
A check of a file in a raea project keeps its findings in the project's record (`.raea/record/`), beside its
renders', which `raea findings` and `raea goal next` read.
```sh
raea check piece.tsx --quick --platform tiktok
raea render piece.tsx -o piece.mp4 --manifest render.json
raea check piece.mp4 --manifest render.json --words words.json --platform tiktok -o check.json
```
@@ -32,7 +36,7 @@ reported as a note, since the mix sets the delivery's level.
## Every rule a project holds
On a project, or a composition's file, `raea check` runs every rule that applies to each
On a project, or a composition's file, with no `--quick`, `raea check` runs every rule that applies to each
composition: raea's floor on its newest render, and every line with a check in your taste, the workspace's
`taste.ts` and the project's own. A rule is such a line: its words, and the check that holds it, one of raea's six
measured forms, one of raea's checks by name with its values, or a `.ts` check of your own by its path.
@@ -74,8 +78,9 @@ last change is still joined, with a note that what it measured may have moved.
## Usage
```sh
raea check [PROJECT|EDIT.tsx] [--composition ID] [--only ID] [--render OUT | --no-render] [--json] (every check that applies to each composition, over its frames: raea's floor on its newest render, the person's, the workspace's and the project's taste.ts (each line's check: one of raea's forms or checks by name, or a project's .ts check); what needs a render and has none waits, and says so)
raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--shape 16:9|9:16|4:5|1:1] [--platform tiktok|reels|shorts] [-o check.json] (an export against the floor: clipped text, contrast, safe areas, freezes, flashing, cues, loudness, blotching, a placeholder brand kit; its findings errors, warns and notes)
raea check EDIT.tsx --quick [--shape S] [--platform P] [--taste T] [-o check.json] (three stills of a composition checked for text: clipped, cramped, safe areas, sizes; about a second)
raea check [PROJECT|EDIT.tsx] [--composition ID] [--only ID] [--taste T] [--render OUT | --no-render] [--json] (every check that applies to each composition, over its frames: raea's floor on its newest render, the person's, the workspace's and the project's taste.ts (each line's check: one of raea's forms or checks by name, or a project's .ts check); what needs a render and has none waits, and says so)
raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--things T.json] [--shape 16:9|9:16|4:5|1:1] [--platform tiktok|reels|shorts] [--taste taste.ts|DIR] [-o check.json] (an export against the floor: clipped text, contrast, safe areas, freezes, flashing, cues, loudness, blotching, a placeholder brand kit, and with --things what `raea fingerprint things --json` found: a thing floating or passing through another, the camera lurching mid-move, an empty frame; its findings errors, warns and notes)
```
Headless: it needs nothing running and opens no window. Takes up to 1 argument besides its flags.
@@ -91,8 +96,11 @@ Headless: it needs nothing running and opens no window. Takes up to 1 argument b
| `--only` | `ID` | Run one rule's check: a check of raea's by name (`text-above`) or a project check's id (its `check({ id })`). |
| `--perception` | `P.json` | Where the face is on each frame (the `perception.json` `raea cut` writes), to find text over a face. |
| `--platform` | `P` | Check the safe areas against this platform's buttons and captions. |
| `--quick` | – | Check a composition's text from three stills instead of checking an export. |
| `--render` | `OUT` | Join this render instead of the composition's newest in the project's record. |
| `--shape` | `S` | The delivery's aspect ratio, for its safe areas. |
| `--taste` | `T` | The person's taste files: the rules in them that carry a `check` are applied too. |
| `--things` | `T.json` | what `raea fingerprint things FILE --json` found in the video (a thing floating or passing through another, the camera lurching mid-move, an empty frame), as findings |
| `--words` | `W.json` | The transcript, to check cues against their words and the voice against the music. |
| `-o` | `check.json` | Write the findings as JSON, for a later review or for `raea goal next`. |
+1 -1
View File
@@ -8,7 +8,7 @@ sources: ["engine/cli/src/index.ts", "engine/cli/src/registry.gen.ts", "engine/c
Components are ready-made pieces of a composition (captions, lower thirds, end cards and the like) and sets of them.
`raea make component list` shows them; `raea make component add` copies one into `components/NAME/`, where it's yours: raea
never updates or overwrites it unasked. With `--shared` it goes into the workspace's `shared/components/` instead, for
every project to import as `@shared/components/NAME`.
every project to import as `@shared/components/NAME`. `raea part` is the old name and still works.
Beside raea's own sets is the library: several hundred open-source components (text reveals, counters, charts,
transitions, product-screen demos, game HUDs and more), sorted by what they're for rather than who made them.
+1 -1
View File
@@ -21,7 +21,7 @@ raea findings piece.tsx --since 20261110-165445
A run is set against the one before it of the same kind: a video against the video before it, a review against a
review, a check against a check. A finding is the same one in a later run when its check and what it is about (or,
about nothing, its words) are the same, whatever frames it is on, so a clip that moves as the piece is cut stays one
finding. Renders that are part of another run, such as a review's tiles, keep no
finding. Renders that are part of another run, such as a review's tiles or `raea check --quick`'s stills, keep no
entry of their own.
Nothing is fixed by hiding it. An error let through with `--despite` stays standing, and its reason is listed. A part
+3 -4
View File
@@ -13,9 +13,8 @@ only what a file has. A new axis judges from its words until it has been trained
you point at. A person can keep several, each saying what it's for, and one can build on another with `--extends`.
The app's Fingerprint page shows the same thing: what each one knows, what it's still learning, and what it can't
judge yet. `postmortem` looks back on a finished project with at most ten questions, and `things` says where a
thing floats or passes through another, the camera lurches or the frame is empty, for a person to look at. It is no
check: a render checks its own 3D from its manifest, at its end, and `raea check --things` is gone.
`score --ask flags` puts each flag to clef again, through the ask runner (apps/ask), on that moment's window alone. Beside the flag it
thing floats or passes through another, the camera lurches or the frame is empty, for `raea check --things`.
`score --ask flags` puts each flag to clef again, through `raea ask`, on that moment's window alone. Beside the flag it
says "clef agrees (0.96)" or "clef doesn't see it (0.00)". It costs by the flags, never by the piece, and a render
asked again costs nothing. Clef's answers are kept as its evidence (`eye:clef`), which trains the axis's head but never
counts as your own. See
@@ -38,7 +37,7 @@ raea fingerprint things shot.mp4 --json > things.json
## Usage
```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 | 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, for a person to look at; --json prints it as 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.
+30 -12
View File
@@ -1,8 +1,8 @@
---
title: "raea goal"
summary: "The loop: the brief's goals, every rule each is held to, run at four moments (while editing, a render's end, a hand-over, a stop) by `raea check`; the brief's plan by `raea goal tasks`; the next steps."
summary: "The loop: the brief's goals, every rule each is held to, run at four moments (a save, a render's end, a hand-over, a stop) by `raea goal check`; the brief's plan by `raea goal tasks`; the next steps, the critic and a scene, kit or shot goal's gates."
order: 42
sources: ["sdk/goal/src/run.ts", "sdk/goal/src/contract.ts", "sdk/goal/src/tasks.ts", "sdk/goal/src/packs/index.ts", "core/brief/src/goal.rs", "apps/check/src/hook.rs", "engine/cli/src/verbs.rs"]
sources: ["sdk/goal/src/run.ts", "sdk/goal/src/contract.ts", "sdk/goal/src/tasks.ts", "sdk/goal/src/packs/index.ts", "core/brief/src/goal.rs", "apps/make/src/gates.rs", "apps/check/src/hook.rs", "engine/cli/src/verbs.rs"]
---
`raea goal check` holds the work to every rule it has, from what's on disk and never from what the agent says. The
@@ -10,13 +10,14 @@ rules are the brief's `goal`: one goal, or a list of them done in order (a workf
steps })`), each a `cut({...})`, `rules({...})`, `scene({...})`, `kit({...})` or `shot({...})` from `raea/brief`. A
goal's `name` is how the report and other goals' `after` name it, and `after` holds it until those goals pass. Each kind turns its packs on, `packs` switches any by
name, and `checks` adds the project's own (`check()`s from raea/check, imported into brief.ts). With no goal, a
project is held to the floor: every made video's frames, its floor measure and its look.
project is held to the floor: every made video's frames, its floor measure and its look, and every composition's
stills as it's saved.
Each check runs at its moments. raea runs `raea goal check` itself at the last three; nothing runs it after a save:
Each check runs at its moments, and raea runs `raea goal check` at each one itself:
| Moment | When | Who runs it |
| --- | --- | --- |
| `edit` | while a composition is being made | the agent or a person, as `raea check --at edit` |
| `edit` | a composition, or any file under a goal, is saved | the agent's after-save hook (`raea hook`) |
| `render` | a render's export is written | `raea render`, on a Mac and on a raea cloud box |
| `publish` | the agent hands a video over | raea cloud's publish tool |
| `done` | the agent's turn ends; a raea cloud stop or delivery | the Stop hook; raea cloud |
@@ -31,24 +32,35 @@ The packs, and what each holds:
| `montage` | cut | each cut's beats kept to their pace (`asl`, `tempo`); eye trace, screen direction and tone across every cut, in Murch's order (a break at most cuts is an error) |
| `place` | cut | no text over a face, a person or what the shot is about where a clear place of its size exists |
| `floor` | cut, floor | no clipped text, low contrast, freeze, flash or loudness out of range |
| `stills` | every kind, floor | a composition's three stills as it's saved: no clipped or cramped text, nothing out of the safe areas |
| `seen` | cut, floor | its contact sheet and its frames at full size looked at since its last render (`raea goal seen FILE`, then `raea goal seen FILE "..." --look "..."`) |
| `surprise` | when a brief turns it on | one earned surprise named with its moment in seconds |
| `naming` | cut | every video and still named client_concept_variant_v#_size |
| `sizes` | cut | one size first: no other size before a person approves the first |
| `quotes`, `count`, `open` | cut | every rule quotes the brief; as many cuts as it asks for; each open item answered by a person |
| `say`, `never`, `cta`, `shape` | cut | each cut says its phrases, none it bans, ends on the CTA, in its format and length |
| `run` | rules, cut | each command rule exits 0 |
| `run`, `says` | rules, cut | each command rule exits 0; each `says` rule found true by a fresh critic since the work last changed (a cut's beats are `says` rules: what each part makes the viewer feel and understand, judged on the cut in sequence) |
| `deliverables` | rules, scene, kit, shot | every file the goal names exists |
| `record`, `critic`, `notes` | scene, kit, shot | every composition rendered clean since it changed; the critic's rounds; NOTES.md's "What the skill got wrong" |
A finding says what to change (the out point to move to, the gainDb that evens a line, the place a caption is clear).
`raea goal check` prints each, writes review/goal.json (and FILE.check.json beside each file named), and exits 1 on
an error. A check that needs what the machine hasn't (people and faces are read by raea cloud's farm) waits and says
so; it holds nothing. The Stop hook keeps an agent working in a project whose brief has a `goal` until `--at done`
passes; the same open items block a session three times at most.
passes; the same open items block a session three times at most. A scene, kit or shot job is delivered short at its
round cap (8 by default) or after three rounds that haven't beaten the best before them: its record and critic
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
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. Nothing grades the work in words
(docs/check.feature): a rule of words (`says`) is checked by nothing, and `raea check` says so before anything runs,
so write what must hold as a command or a file.
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 check` asks for the verdict itself when it's missing or
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. Who judges is raea's to settle, never the agent's: a rule with a piece to watch or hear (the files 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`
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
import { brief, rules } from "raea/brief"
@@ -60,7 +72,7 @@ export default brief({
rules: [
{ id: "tests", run: "bun test" },
{ id: "export", file: "out/final.mp4" },
{ id: "readme", run: "grep -q 'bun install' README.md" },
{ id: "readme", says: "README.md says how to install and run it, in order" },
],
checks: [clearOfButtons],
}),
@@ -70,6 +82,7 @@ export default brief({
```sh
raea goal check # done: everything, as the Stop hook runs it
raea goal check out/cuts/acme_dog_hook1_v2_9x16.mp4 --at render
raea goal seen out/cuts/acme_dog_hook1_v2_9x16.mp4 && raea goal seen out/cuts/acme_dog_hook1_v2_9x16.mp4 "..." --look "..."
raea goal tasks --json # the brief's plan, every task
raea goal next
```
@@ -86,7 +99,10 @@ goal's rules are never copied into the plan: the plan is the work, the goal is w
```sh
raea goal check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--manifest render.json] [--json] (every rule each goal of brief.ts is held to at that moment: its kind's packs, its rules and its own checks; with no goal, the floor; every project is also held to `registered`, every raea file reached from brief.ts; review/goal.json; exit 1 on an error. The hook runs it at every save (edit) and stop (done), a render at its end, raea cloud at publish)
raea goal tasks [DIR] [--json] | raea goal tasks [DIR] --apply EDITS.json|- | raea goal tasks [DIR] --put PUT.json|- (the brief's plan as the brief's run gives it: open tasks by id, or all as JSON; --apply writes edits by task id back where each task is written, refusing one made by code; a project with no plan gets plan.ts, imported by brief.ts; --put {plan, base} writes the whole plan back only while the brief's is still base)
raea goal seen FILE ["what you see and would change" --look "its design at full size, beside a reference"] [--surprise "SECONDS s: what it is"] (FILE's contact sheet beside it, and its frames at full size in FILE.looks/, to look at; with words, what was seen of FILE as it is now, and --look how a video's type, captions and cards look at full size)
raea goal judge [--goal NAME] (a goal's `says` rules judged now, as `raea goal check` judges them itself: a rule with a piece to watch or hear (a file it names, else the videos under out/) by clef-omni, any other by a fresh session of the agent this project runs on, which only reads; review/judge/NAME.json. Who judges is raea's to settle, never yours)
raea goal next [DIR] (the two or three useful next steps for the project, from its brief, its goals, compositions, renders and checks)
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)
```
Headless: it needs nothing running and opens no window. Takes any number of arguments besides its flags.
@@ -98,9 +114,11 @@ Headless: it needs nothing running and opens no window. Takes any number of argu
| `--apply` | `EDITS.json\|-` | plan edits (JSON, `-` for stdin), each written where its task is written |
| `--at` | `edit\|render\|publish\|done` | The moment `check` runs the rules of (default `done`); for `place`, the seconds to read (`S[,S...]`). |
| `--goal` | `NAME` | only this goal of the brief's (by its name) |
| `--json` | – | `check`: print the report (review/goal.json's shape). |
| `--json` | – | `check`: print the report (review/goal.json's shape). `gates`: the record and critic gates as JSON. |
| `--look` | `"its design` | `seen`: a video's design judged on its frames at full size (FILE.looks/): its type, captions, cards and end beside a reference, and what was changed. |
| `--manifest` | `render.json` | the render's manifest, for the sound pack's takes and effects |
| `--only` | `ID,...` | `check`: only these checks. Otherwise only these objects (refs, gen, pick-sheet, prep) or shots (framing), by id or name. |
| `--put` | `PUT.json\|-` | `{plan, base}`: the whole plan written back only while the brief's is still `base` |
| `--surprise` | `"SECONDS s:` | `seen`: the one surprise and its moment, for a brief with the surprise pack on. |
<!-- generated:end -->
+5 -6
View File
@@ -1,6 +1,6 @@
---
title: "raea hook"
summary: "Every agent's tool hooks: media opened in the Mac's viewer goes to raea show, and the one check runs as a turn ends; nothing is checked after a save."
summary: "Every agent's tool hooks: media opened in the Mac's viewer goes to raea show, and the quick check after a composition is saved."
order: 52
sources: ["apps/check/src/hook.rs", "apps/tools/src/agent_hooks.rs"]
---
@@ -15,10 +15,9 @@ tells the agent to use [`raea show`](show.md) instead, so the work comes up in t
answer. The same command run again in that session within ten minutes goes through, for when the person asked for the
viewer. `open -a raea`, Finder (`open -R`), links and PDFs are never stopped.
After a file is saved, it checks nothing: a render checks its own output at its end. As a turn ends (Claude Code and
Codex), it runs `raea check --at done` on the brief's goals and keeps the agent working while one fails. After a
tool, it hands the agent what the person sent from the raea app. A stop is exit 2 with the reason on stderr, which
every harness hands its agent; what was sent goes back in the shape each harness reads.
After a file is saved, it runs `raea check --quick` on a composition and hands the findings back to the agent, so
clipped or cramped text is caught on the edit that caused it. A stop is exit 2 with the reason on stderr, which every
harness hands its agent; findings go back in the shape each harness reads.
```sh
raea skills install --agent claude # the skill and its hooks, for Claude Code
@@ -30,7 +29,7 @@ raea skills install --agent kimi # the same for Kimi Code (codex and gemin
## Usage
```sh
raea hook [claude|codex|gemini|kimi] (every agent's tool hooks, which raea skills install adds: before a shell command, media opened in the Mac's viewer while the raea app is installed is stopped once for raea show (the same command again goes through); as a turn ends, the one check on the brief's goals; nothing is checked after a save, since a render checks its own output)
raea hook [claude|codex|gemini|kimi] (every agent's tool hooks, which raea skills install adds: before a shell command, media opened in the Mac's viewer while the raea app is installed is stopped once for raea show (the same command again goes through); after a save, the quick check on a composition)
```
Headless: it needs nothing running and opens no window. Takes up to 1 argument besides its flags.
+4 -2
View File
@@ -62,8 +62,9 @@ What the work is held to (brief.ts's `goal`, checked by `raea goal`), and what's
| Verb | What it does |
| --- | --- |
| [`raea goal`](goal.md) | The loop: the brief's goals, every rule each is held to, run at four moments (while editing, a render's end, a hand-over, a stop) by `raea check`; the brief's plan by `raea goal tasks`; the next steps. |
| [`raea goal`](goal.md) | The loop: the brief's goals, every rule each is held to, run at four moments (a save, a render's end, a hand-over, a stop) by `raea goal check`; the brief's plan by `raea goal tasks`; the next steps, the critic and a scene, kit or shot goal's gates. |
| [`raea check`](check.md) | Check a composition's text in a second, a project against every rule it holds, or an export against the floor: text, contrast, safe areas, freezes, flashing, cues and loudness. |
| [`raea judge`](judge.md) | Judge a 3D scene's review sheets blind, by a model on a frozen rubric or a fresh agent session, with the pass decided in code. |
| [`raea fingerprint`](fingerprint.md) | A person's sense of good work, learned on this Mac: axes with small heads over on-device encoders that score a render moment by moment and say what they can't judge yet. |
| [`raea findings`](findings.md) | What each render and check found, read back from the project's record: fixed, new and carried since the one before. |
| [`raea scene`](scene.md) | Find floating, sunk and clipping 3D parts, say what each part rests on, meter a shot's light, hold every frame to the stage checks a render runs, and list each part's planned detail beside how large the frames show it. |
@@ -71,7 +72,7 @@ What the work is held to (brief.ts's `goal`, checked by `raea goal`), and what's
| [`raea bench`](bench.md) | Each case on each denoiser against its converged truth: FLIP, RMSE, bias, flicker, blotches, lag after a disocclusion or a light going out, a frame's cost, and how many of MetalFX's numbers each meets. |
| [`raea world`](world.md) | A frame as one world: its layers, text, 3D parts, camera, shots, clips, cues and lines as entities, queried across media. |
| [`raea doctor`](doctor.md) | Find what doesn't match this version of raea: old brief files, an older workspace format, an agent's stale skill. |
| [`raea hook`](hook.md) | Every agent's tool hooks: media opened in the Mac's viewer goes to raea show, and the one check runs as a turn ends; nothing is checked after a save. |
| [`raea hook`](hook.md) | Every agent's tool hooks: media opened in the Mac's viewer goes to raea show, and the quick check after a composition is saved. |
| [`raea traces`](traces.md) | List the sessions raea apps left, newest first, with how each ended and its glitches, or tell one in full. |
## Footage
@@ -135,5 +136,6 @@ What an agent reads and shows the person, and the tools raea installs.
| [`raea skills`](skills.md) | Install raea's agent skill where Claude Code, Codex, Kimi or Gemini read skills, with its MCP server and hook. |
| [`raea setup`](setup.md) | Find Blender, or download its current LTS, and install raea's add-on and the MCP add-on. |
| [`raea bug`](bug.md) | Report a bug in raea itself to raea's server: a line saying what's wrong and what happened, with raea's version and the OS added, no account needed. |
| [`raea ask`](ask.md) | Ask about a piece's picture and sound: clef-omni answers in words and a probability, paid from your raea plan, and every answer is kept so a question can be calibrated. |
<!-- generated:end -->
+53
View File
@@ -0,0 +1,53 @@
---
title: "raea judge"
summary: "Judge a 3D scene's review sheets blind, by a model on a frozen rubric or a fresh agent session, with the pass decided in code."
order: 44
sources: ["apps/judge/src/lib.rs", "apps/judge/src/rubric.rs", "apps/judge/src/agent.rs", "apps/judge/src/eye.rs"]
---
`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 a fresh session of the agent this project runs on,
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.
`--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,
props, signage, materials, light, atmosphere, plausibility and composition; a kit on cohesion, reference fidelity,
the brief, mesh, texture, assembly, scale and labels; a shot on framing, move, focus, clearance, continuity and grade
(read from `framing.png`, which `raea make framing` writes). Form categories (layout, props, mesh, assembly, scale) are
judged on the clay sheet. The bar is a production base: don't nitpick, at most five fixes, each to do in a script.
The verdict and the log line say the kind, and `raea judge calibrate --kind KIND` fits that kind's calibration on its
own.
```sh
raea render scene.tsx --review review/
raea judge review/ --brief brief.ts
raea judge review/ --target reference.png --json
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 calibrate
```
<!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions -->
## Usage
```sh
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.
## Flags
| Flag | Takes | What it does |
| --- | --- | --- |
| `--brief` | `brief.ts` | The project's brief, so the judge knows what the scene is for. |
| `--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. |
| `--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. |
| `--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. |
<!-- generated:end -->
+1 -1
View File
@@ -2,7 +2,7 @@
title: "raea make"
summary: "The asset tools: everything a project is made from, each a `raea make TOOL` (components, solids, clothes, motion, splats, physics, bakes, foley, instruments); and a scene, kit or shot goal's steps."
order: 102
sources: ["engine/cli/src/usage.rs", "apps/make/src/lib.rs", "apps/make/src/kit.rs", "apps/make/src/kitout.rs", "apps/make/src/shots.rs", "apps/make/src/floor.rs", "apps/make/src/sheet.rs"]
sources: ["engine/cli/src/usage.rs", "apps/make/src/lib.rs", "apps/make/src/asked.rs", "apps/make/src/kit.rs", "apps/make/src/kitout.rs", "apps/make/src/shots.rs", "apps/make/src/floor.rs", "apps/make/src/sheet.rs"]
---
`raea make` holds the tools that make things: each is `raea make TOOL`, with its own page. What the work is held to,
+2 -2
View File
@@ -37,8 +37,8 @@ A whole video made from the same inputs as an earlier one is copied from the exp
and the command says so.
Every render writes its manifest beside its output: `OUT.render.json` (`DIR/NAME.render.json` for a folder of
frames), or where `--manifest` says. It holds what each frame showed as laid out (each text's words, box, colour, the
colours its words are drawn in when one differs, such as a caption's accent word, and size, each video's source and time, each picture's box), the sounds heard and what the render found. `raea check`
frames), or where `--manifest` says. It holds what each frame showed as laid out (each text's words, box, colour and
size, each video's source and time, each picture's box), the sounds heard and what the render found. `raea check`
reads it, and so does [`raea world`](world.md), which measures the output against it when a check asks.
A render checks what it draws: 3D parts passing into each other (the clipping check), how its 3D is staged (3D type
+9 -5
View File
@@ -2,7 +2,7 @@
title: "raea scene"
summary: "Find floating, sunk and clipping 3D parts, say what each part rests on, meter a shot's light, hold every frame to the stage checks a render runs, and list each part's planned detail beside how large the frames show it."
order: 47
sources: ["apps/scene/src/lib.rs", "apps/scene/src/light.rs", "apps/scene/src/stage.rs", "apps/scene/src/lod.rs", "runtime/lod-plan/src/lib.rs", "runtime/lod-plan/src/report.rs", "runtime/lod-plan/src/plan.rs", "systems/stage/src/lib.rs", "systems/stage/src/clearance.rs", "systems/contact/src/lint.rs", "systems/contact/src/zfight.rs", "apps/scene/src/faults.rs", "apps/scene/src/seed.rs", "systems/notice/src/lib.rs", "apps/scene/src/motion.rs", "systems/motionfaults/src/lib.rs", "runtime/endchecks/src/faults.rs", "apps/scene/src/chars.rs"]
sources: ["apps/scene/src/lib.rs", "apps/scene/src/light.rs", "apps/scene/src/stage.rs", "apps/scene/src/lod.rs", "runtime/lod-plan/src/lib.rs", "runtime/lod-plan/src/report.rs", "runtime/lod-plan/src/plan.rs", "systems/stage/src/lib.rs", "systems/stage/src/clearance.rs", "systems/contact/src/lint.rs", "systems/contact/src/zfight.rs", "apps/scene/src/faults.rs", "apps/scene/src/seed.rs", "systems/notice/src/lib.rs", "apps/scene/src/motion.rs", "systems/motionfaults/src/lib.rs", "runtime/endchecks/src/faults.rs", "apps/scene/src/ask.rs", "apps/scene/src/chars.rs"]
---
`raea scene` steps a composition's frames and measures its 3D scene without rendering pictures. `lint` reports
@@ -39,8 +39,8 @@ frame's camera, the larger of its width's and its height's share. The table puts
first, then the rest of the planned parts, then the parts nobody planned by how large they get, so a part forgotten
since the plan was written is found by reading down it. Under it: each `lod-closer` finding, and any level the plan
gives a name that no part in the frames goes by. A part seen one level finer than planned is a warning; two or more
is an error, and `lod` exits 1. `raea render` and `raea scene stage` say the same finding, and
`raea check` holds a job at it. A part hidden behind other meshes isn't counted as seen; RAEA_LOD_CHECK=0
is an error, and `lod` exits 1. `raea render`, `raea scene stage` and `raea check --quick` say the same finding, and
`raea goal check` holds a job at it. A part hidden behind other meshes isn't counted as seen; RAEA_LOD_CHECK=0
leaves the check out of a render.
`faults` judges the lint's findings as a viewer of the shot would see them. Every frame's camera (up to 48 over the
@@ -63,7 +63,8 @@ of them. The lines sit just above what 107 retargeted ACCAD captures do; `--seed
every clip and says how many are caught.
`--motion` reads the characters from the composition itself, no clip written out, and also tests every finger bone
against the scene's real triangles. Motion findings also pass a critic, a tiny logistic model fitted by `raea scene faults train` to every motion verdict (fixes, `--real`, `--fine`): what it learns of one joint carries to its neighbours, and a verdict on the finding's own key at its size outranks it.
against the scene's real triangles. Motion findings also pass a critic, a tiny logistic model fitted by `raea scene faults train` to every motion verdict (fixes, `--real`, `--fine`): what it learns of one joint carries to its neighbours, and a verdict on the finding's own key at its size outranks it. `--ask N` puts the N likeliest faults to a vision model, the fault ringed on its
frame and described in the scene's own words, so it answers only whether it's meant; see docs/notice.feature NT12.
A render runs the judge too: at its end the first frame's floating, sunk, lifted and doubled-face findings are judged
through the render's own cameras, and only the likely faults are said (RAEA_FAULTS_CHECK=0 leaves it out).
@@ -76,6 +77,7 @@ raea scene faults train ~/Documents/raea # fit the judge to
raea scene faults --clip walk.json # a clip's buckles, skates, bent fingers, jolts
raea scene faults --clip clips/ --seed 2 # what it catches of faults planted in real motion
raea scene faults take.tsx --composition take --motion # the composition's characters, hands against the scene
raea scene faults room.tsx --composition shot-case --ask 3 # a vision model on whether the 3 likeliest are meant
raea scene explain room.tsx --frame 90 --json
raea scene light room.tsx --part hero
raea scene light film.tsx --composition shot1,shot2,shot3 # the light across the cuts
@@ -90,7 +92,7 @@ raea scene lod walk.tsx # every part's pl
```sh
raea scene export EDIT.tsx -o DIR [--composition ID] [--frame N | --at A-B] (the composition's 3D as data other tools build: DIR/scene.json, each part placed (y up, metres) with its shape, material or light, and the camera; meshes/ and models/ beside it)
raea scene lint|explain|faults|light|stage|lod EDIT.tsx [--composition ID] [--frame N] [--part NAME] [--from N] [--to N] [--clearance M] [--real KEY] [--fine KEY] [--seed N] [--motion] [--json] | raea scene faults train [FOLDER] | raea scene faults --clip CLIP.json|FOLDER [--real KEY] [--fine KEY] [--fine-from N] [--fine-upto N] [--real-from N] [--real-upto N] [--by NAME] [--seed N] [--json] (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)
raea scene lint|explain|faults|light|stage|lod EDIT.tsx [--composition ID] [--frame N] [--part NAME] [--from N] [--to N] [--clearance M] [--real KEY] [--fine KEY] [--seed N] [--ask N [--dry]] [--motion] [--json] | raea scene faults train [FOLDER] | raea scene faults --clip CLIP.json|FOLDER [--real KEY] [--fine KEY] [--fine-from N] [--fine-upto N] [--real-from N] [--real-upto N] [--by NAME] [--seed N] [--json] (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)
```
Headless: it needs nothing running and opens no window. Takes up to 3 arguments besides its flags.
@@ -99,11 +101,13 @@ Headless: it needs nothing running and opens no window. Takes up to 3 arguments
| Flag | Takes | What it does |
| --- | --- | --- |
| `--ask` | `N` | `faults`: render the frame each of the N likeliest faults shows largest on, ring it, and ask a vision model (`raea ask`) whether it's meant or a mistake, handing it the scene's own words for the fault. An answer 0.7 sure or more is kept as a verdict (by ask), which a person's verdict outranks. The ringed pictures stay in review/faults-ask/. |
| `--at` | `A-B` | `export`: each part's placement and the camera's field of view on every frame from A to B, for keyframes in Blender or Godot. |
| `--by` | `NAME` | With `--real`/`--fine` on motion findings: who made the call, kept with each example (`claude` for an agent that looked at the render); a person's by default. |
| `--clearance` | `M` | `stage`: every run of frames where the camera is nearer a solid part than M metres (0.45 carried, 0.15 on a rig). |
| `--clip` | `CLIP.json\|FOLDER` | `faults`: a character's motion (joints, fps, frames of root and turns) held to what a body does: buckles, skates, joints and fingers past their range, jolts, fingers through what the hand holds. A folder takes every .json in it. |
| `--composition` | `ID` | Which composition to measure. `light` takes several, comma-separated, to compare the light across their cuts. |
| `--dry` | – | With `faults --ask`: render and ring the pictures and say what would be asked, spending nothing. |
| `--fine` | `KEY` | `faults`: keep a verdict that the finding with this key (printed after its line) is meant as it is, in the project's review/faults.labels.jsonl. With `--clip`: the motion finding's line for that check and joint (its key, such as skate:foot_l) rises to just above its size, for every run after (notice/motion.json in raea's models folder). May repeat. |
| `--fine-from` | `N` | With `--fine` on motion findings: only findings of the key this size or bigger, in the finding's own units (degrees past the range for a finger or a joint limit). |
| `--fine-upto` | `N` | With `--fine` on motion findings: only findings of the key this size or smaller (a pinky's small bends fine, its big one not). |
+1 -1
View File
@@ -23,7 +23,7 @@ raea skill --reference sdk
## Usage
```sh
raea skill [NAME] [--reference cli|feed|files|sdk] | raea skills install --agent claude|codex|kimi|gemini|grokbot [--pin MOVE]... [--no-mcp] [--no-hooks] (the agent skill this raea ships, for its version, which raea --version prints: an agent whose copy names another version reads this; install puts raea's skills where that agent reads skills, adds the blender MCP server unless --no-mcp, makes each --pin MOVE a /MOVE of its own, and adds raea's hooks to that agent unless --no-hooks (raea hook AGENT: media opened in the Mac's viewer goes to raea show, and the one check runs as a turn ends; nothing is checked after a save); a skill folder that's a link is left as it is; grokbot, the Grok Bot app, keeps its skills on its own computer, so its copy is staged on this Mac (RAEA_GROKBOT_HOME moves it) with the grokbot:// links that finish it in Grok Bot, and gets no hooks or MCP server)
raea skill [NAME] [--reference cli|feed|files|sdk] | raea skills install --agent claude|codex|kimi|gemini|grokbot [--pin MOVE]... [--no-mcp] [--no-hooks] (the agent skill this raea ships, for its version, which raea --version prints: an agent whose copy names another version reads this; install puts raea's skills where that agent reads skills, adds the blender MCP server unless --no-mcp, makes each --pin MOVE a /MOVE of its own, and adds raea's hooks to that agent unless --no-hooks (raea hook AGENT: media opened in the Mac's viewer goes to raea show, and the quick check after a composition is saved); a skill folder that's a link is left as it is; grokbot, the Grok Bot app, keeps its skills on its own computer, so its copy is staged on this Mac (RAEA_GROKBOT_HOME moves it) with the grokbot:// links that finish it in Grok Bot, and gets no hooks or MCP server)
```
Headless: it needs nothing running and opens no window. Takes up to 1 argument besides its flags.
+4 -5
View File
@@ -8,9 +8,8 @@ sources: ["engine/cli/src/skill.rs"]
`raea skills install` copies the skill this raea ships into the folder an agent reads skills from, stamped with this
version: `~/.claude/skills` for Claude Code, `~/.agents/skills` for Codex, Kimi Code's skills folder, and
`~/.gemini/skills` for Gemini. It also adds the Blender MCP server to the agent, and raea's hooks to every agent
([`raea hook`](hook.md)): media opened in the Mac's viewer goes to `raea show`, and `raea check` holds the brief's goals
as a turn ends. Nothing is checked after a save. A skill folder that's a link (a checkout of raea-skills) is left
as it is.
([`raea hook`](hook.md)): media opened in the Mac's viewer goes to `raea show`, and the quick check runs after each
saved composition. A skill folder that's a link (a checkout of raea-skills) is left as it is.
The skill raea ships matches the version it ships with. An agent can hold a copy from an older or newer install;
its front matter names the version it came with, and when that differs from `raea --version` the agent reads
@@ -27,7 +26,7 @@ raea skills install --agent claude --pin quieter --pin bolder # /quieter and
## Usage
```sh
raea skill [NAME] [--reference cli|feed|files|sdk] | raea skills install --agent claude|codex|kimi|gemini|grokbot [--pin MOVE]... [--no-mcp] [--no-hooks] (the agent skill this raea ships, for its version, which raea --version prints: an agent whose copy names another version reads this; install puts raea's skills where that agent reads skills, adds the blender MCP server unless --no-mcp, makes each --pin MOVE a /MOVE of its own, and adds raea's hooks to that agent unless --no-hooks (raea hook AGENT: media opened in the Mac's viewer goes to raea show, and the one check runs as a turn ends; nothing is checked after a save); a skill folder that's a link is left as it is; grokbot, the Grok Bot app, keeps its skills on its own computer, so its copy is staged on this Mac (RAEA_GROKBOT_HOME moves it) with the grokbot:// links that finish it in Grok Bot, and gets no hooks or MCP server)
raea skill [NAME] [--reference cli|feed|files|sdk] | raea skills install --agent claude|codex|kimi|gemini|grokbot [--pin MOVE]... [--no-mcp] [--no-hooks] (the agent skill this raea ships, for its version, which raea --version prints: an agent whose copy names another version reads this; install puts raea's skills where that agent reads skills, adds the blender MCP server unless --no-mcp, makes each --pin MOVE a /MOVE of its own, and adds raea's hooks to that agent unless --no-hooks (raea hook AGENT: media opened in the Mac's viewer goes to raea show, and the quick check after a composition is saved); a skill folder that's a link is left as it is; grokbot, the Grok Bot app, keeps its skills on its own computer, so its copy is staged on this Mac (RAEA_GROKBOT_HOME moves it) with the grokbot:// links that finish it in Grok Bot, and gets no hooks or MCP server)
```
Headless: it needs nothing running and opens no window. Takes up to 1 argument besides its flags.
@@ -37,7 +36,7 @@ Headless: it needs nothing running and opens no window. Takes up to 1 argument b
| Flag | Takes | What it does |
| --- | --- | --- |
| `--agent` | `claude\|codex\|kimi\|gemini\|grokbot` | Which agent to install for. |
| `--no-hooks` | – | Don't add raea's hooks (`raea hook`) to the agent. |
| `--no-hooks` | – | Leave Claude Code's settings alone: don't add the quick-check hook. |
| `--no-mcp` | – | Don't add the Blender MCP server to the agent. |
| `--pin` | `MOVE` | Install a note's guide as a skill of its own, so `/MOVE` loads just it (`quieter`, `bolder`, `layout`, `adapt` and the rest). Repeatable. |
| `--reference` | `cli\|feed\|files\|sdk` | Used by `raea skill`; see [`raea skill`](skill.md). |
+177
View File
@@ -0,0 +1,177 @@
---
title: "raea/ask"
summary: "Ask about a piece's picture and sound from a script: the same questions, runner and record as raea ask, typed."
order: 106
sources: ["sdk/raea/src/ask.ts"]
---
`raea/ask` asks from a script what [`raea ask`](../cli/ask.md) asks from the command line: a script run with `raea run`,
a `.ts` check, or plain Node or Bun. It runs `raea ask --batch - --json`, so every question about one clip goes in one
call, the clips are cut once, the calls go in parallel, and every answer is kept for calibration. It pays the same way:
your raea plan when the app is signed in, an agent key, or your own Cloudflare keys. It throws when nothing could be
asked, and the error says why.
```ts
import { ask, askMany } from "raea/ask";
const { answers } = ask("out/piece.mp4", "Does the music fight the voice?");
const run = askMany([
{ file: "out/a.mp4", set: "av", brief: "brief.ts" },
{ file: "out/b.mp4", std: ["defect.glitch"], window: { from: 0, to: 3 } },
]);
for (const a of run.answers) if (a.flagged) console.log(a.file, a.id, a.says, a.calibrated ? "finding" : "advice");
```
<!-- generated:begin by tools/manual-ref/sdk.ts from the SDK's exports and doc comments; edit outside this block -->
```ts
import { ask, askMany, SETS } from "raea/ask"
```
`raea/ask` exports 2 functions, 1 value, 12 types. Source: [sdk/raea/src/ask.ts](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/src/ask.ts).
## Functions
### `ask`
Questions about one file: your own words (yes or no), written-out questions, or with `std`/`set` the standard ones.
```ts
function ask(file: string, question?: string | Question | (string | Question)[], more?: Omit<AskEntry, "file" | "questions"> & AskOptions): Asked
```
### `askMany`
Many files asked in one run, in parallel; throws when nothing could be asked (the error says why).
```ts
function askMany(entries: AskEntry[], o?: AskOptions): Asked
```
## Values
### `SETS`
## Types
### `Answer`
One question's answer, or why it wasn't asked or still waits: a line of `raea ask --json`.
| Field | Type | What it is |
| --- | --- | --- |
| `answer` | `string` | its id in the record, for `raea ask verdict` |
| `file` (required) | `string` | the file asked about |
| `id` (required) | `string` | the question's id |
| `version` (required) | `string` | a hash of its words, type and options: a new wording is a new version, calibrated on its own |
| `from` (required) | `number` | the window's start, in seconds |
| `to` | `number` | the window's end, in seconds (unset: the file's end) |
| `says` | `string` | the answer in words with its probability |
| `value` | `number` | yes's probability, a pick's probability, or a level |
| `problem` | `number` | 0 to 1, higher is likelier a problem (none for a pick) |
| `choice` | `string` | the option or level chosen |
| `flagged` (required) | `boolean` | past the question's threshold (its calibrated one, else even odds) |
| `calibrated` (required) | `boolean` | its labels separate well enough for its answers to be findings; until then they're advice |
| `not_asked` | `string` | why it wasn't asked (it doesn't apply to this piece, or the call failed) |
| `waits` | `string` | why it still waits (this month's pool is spent) |
| `route` | `string` | the way it was paid: your raea plan through the app, an agent key, or your Cloudflare account |
| `cached` (required) | `boolean` | answered from the cache, at no cost |
### `Asked`
A run's answers, the calls `dry` would make, and its summary.
| Field | Type | What it is |
| --- | --- | --- |
| `answers` (required) | `Answer[]` | every question's answer, or why it wasn't asked, in the order they came |
| `would` (required) | `unknown[]` | with `dry`: each call that would be made (its state, questions, media sizes and estimate) |
| `summary` (required) | `Summary` | what it came to |
### `AskEntry`
One file and what to ask of it: a line of `raea ask --batch`.
| Field | Type | What it is |
| --- | --- | --- |
| `file` (required) | `string` | the video, sound or picture asked about |
| `questions` | `(string \| Question)[]` | questions in your own words (yes or no) or written out |
| `set` | `string \| string[]` | standard sets by name: rubric, av, defects, platform, decide, make |
| `std` | `string[]` | standard questions by id (`raea ask list` lists them) |
| `window` | `Window` | the seconds to look at, for every question here (else each question's own, else the whole file) |
| `with` | `string[]` | files set beside it: to pick between, or a before and after |
| `brief` | `string` | the project's brief (else the nearest brief.ts above the file; "none": no brief, the state saying what the piece is) |
| `words` | `string` | a words file (a JSON list of the words heard), so ask knows what's said and whether anyone speaks |
| `voice` | `boolean` | whether anyone speaks in it, when no words file says |
| `state` | `string` | more for clef to read before the media: what raea measured, the platform |
### `AskOptions`
How a run goes.
| Field | Type | What it is |
| --- | --- | --- |
| `jobs` | `number` | calls at once (4 unless set) |
| `dry` | `boolean` | cut the media and say what would be sent, spending nothing |
| `bin` | `string` | the raea to run (RAEA_BIN, else raea on the PATH) |
### `Calibration`
```ts
type Calibration = { auc: number, n: number, positives: number, /** * the problem score at which it flags (10% false positives on its labels) */ threshold?: number, /** * YYYY-MM-DD */ date: string, /** * whose labels: "raea" (raea's bench, shipped) or "you" */ by: string, }
```
### `Kind`
```ts
type Kind = "yes" | "choose" | "grade" | "rate"
```
### `Picks`
```ts
type Picks = "all" | "after-first"
```
### `Question`
```ts
type Question = { /** * letters, digits, `_`, `.` and `-` */ id: string, /** * the question in words, as clef reads it */ ask: string, type?: Kind, /** * choose: its options; grade and rate: its levels, lowest first (a grade's are LEVELS unless given) */ options?: Array<string>, /** * what an option (or yes and …
```
### `Sees`
```ts
type Sees = "video" | "stills" | "nothing"
```
### `Summary`
What a run came to.
| Field | Type | What it is |
| --- | --- | --- |
| `asked` (required) | `number` | the questions sent |
| `answered` (required) | `number` | the answers read |
| `calls` (required) | `number` | the calls made (with `dry`, the calls that would be) |
| `cost` (required) | `number` | what the calls cost, in dollars |
| `estimate` (required) | `number` | with `dry`, what the calls would cost, in dollars |
| `pool_left` | `number` | what's left of this month's pool, in dollars, when the plan paid |
| `waiting` (required) | `number` | the questions waiting for the pool |
| `flagged` (required) | `number` | the answers past their threshold |
| `flagged_calibrated` (required) | `number` | the calibrated answers past their threshold: findings |
| `routes` (required) | `string[]` | the ways the calls were paid |
| `clips` (required) | `number` | the clips cut, each once |
### `When`
```ts
type When = { /** * the brief's modes it's for (pitch, story, explain, play, tool); empty is every mode */ modes?: Array<string>, /** * true: only when someone is heard speaking; false: only when no one is */ voice?: boolean, /** * true: only for a game; false: never for one */ game?: boolean, }
```
### `Window`
```ts
type Window = { from?: number, to?: number, }
```
<!-- generated:end -->
+1
View File
@@ -99,5 +99,6 @@ Checks, lints and a headless App you can drive.
| [`raea/fingerprint`](fingerprint.md) | A fingerprint (fingerprint.ts, docs/fingerprint.md): a person's or a team's sense of good work as axes, each with a small head over on-device encoders that `raea fingerprint` trains from their labels. `raea fingerprint new NAME` writes one with raea's base taxonomy; add an axis, reword one, or remove one, and raea retrains. Rust reads the default export (systems/fingerprint/src/taxonomy.rs), so these types follow its fields. | 1 function, 4 types |
| [`raea/dev_tools`](dev_tools.md) | Checks and lints you can run from code: a motion performance's lint report. | 2 functions, 3 types |
| [`raea/remote`](remote.md) | A headless Bevy App you open, step and query from TypeScript, through Bevy's remote protocol. | 1 class, 1 type |
| [`raea/ask`](ask.md) | Ask about a piece's picture and sound from a script: the same questions, runner and record as raea ask, typed. | 2 functions, 1 value, 12 types |
<!-- generated:end -->
+17 -7
View File
@@ -71,7 +71,18 @@ A composition is one `.tsx` file. The rules that keep a render right:
[Compositions and frames](../concepts/compositions.md) explains why, with examples.
## 4. Look at frames — HEADLESS
## 4. Check it in a second — HEADLESS
After every save:
```sh
raea check piece.tsx --quick
```
It renders three stills and measures their text (clipped, cramped, outside the safe areas, too small) in about a
second. With Claude Code, the installer's hook runs it for you after each save and hands you what it finds.
## 5. Look at frames — HEADLESS
Render the moments that matter as PNGs and look at all of them in one batch: each cut, each part's entrance and
settled state, the first half second, the end card.
@@ -82,34 +93,33 @@ raea render piece.tsx --at 0,45,89 -o frames/
Fix everything the batch shows, then render the batch again. Don't render one still per change.
## 5. Render and check the export — HEADLESS
## 6. Render and check the export — HEADLESS
```sh
raea render piece.tsx -o piece.mp4 --manifest render.json
raea check piece.mp4 --manifest render.json -o piece.check.json
```
The render checks its own export at its end (`raea check`, kept in piece.check.json); run `raea check` on it to check
again. It measures what a still can't: text under a platform's buttons, captions on too briefly to read, caption
`raea check` measures what a still can't: text under a platform's buttons, captions on too briefly to read, caption
contrast against the footage behind them, frozen stretches, flashing, cues that miss their words, loudness, and
blotching in dark areas. Each finding is ranked P0 to P3 with its fix. It exits 1 while a P0 or P1 stands. Don't hand
over a render while `raea check` still names a fault.
## 6. Show it and take notes — PAGE, PERSON
## 7. Show it and take notes — PAGE, PERSON
In the raea app, post the render to the project's feed. The person watches or plays it there and leaves notes.
Headless instead: leave the file in the project's `out/` folder, give the person its path, and take their notes as
text.
## 7. The next version — HEADLESS
## 8. The next version — HEADLESS
- Render each version to a new file beside the old one (`piece-v2.mp4`), never over it, so earlier versions stay
watchable.
- Keep the person's hand edits. Edits made in the raea app come back as props on the composition (`edit` segments
and `<Nudge>` offsets). Change the composition under them.
## 8. Deliver — HEADLESS
## 9. Deliver — HEADLESS
- Final exports of motion graphics and type: `--quality master`.
- Name files with lowercase letters, digits and hyphens only: `spring-launch-9x16.mp4`.
+10 -10
View File
@@ -70,7 +70,16 @@ raea render hello.tsx --at 0,30,89 -o frames/
This writes `frames/frame-00000.png`, `frame-00001.png` and `frame-00002.png`: the first frame (nothing visible yet),
frame 30 ("Hello" fully in) and the last frame ("world"). Open them and check that the text fits and nothing overlaps.
## 3. Render the video
## 3. Check the text in a second
```sh
raea check hello.tsx --quick
```
The quick check renders three stills and measures their text: clipped words, cramped lines, text outside the safe
areas and text too small to read. It takes about a second, so run it after every save.
## 4. Render the video
```sh
raea render hello.tsx -o hello.mp4
@@ -79,15 +88,6 @@ raea render hello.tsx -o hello.mp4
The MP4 is H.264 with the picture in yuv420p. On a Mac it is encoded by VideoToolbox; on Linux and Windows by
openh264.
## 4. Check the video
The render checks its own output at its end and keeps what it found in `hello.check.json`: clipped words, cramped
lines, text outside the safe areas and text too small to read, each with what to change. To check it again:
```sh
raea check hello.mp4
```
## What to try next
- Change `fontSize`, save, and run step 2 again. Every frame is computed from the code, so the same file always
Loaded 100 of 323 files, more files were not shown because too many files have changed in this diff. Show more