Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

AK1: raea-core-ask: the question, how its answer reads, the standard sets and clef's limits

shinyobjectz6c7bf70a4ed9
diff --git a/Cargo.lock b/Cargo.lock
index bb598681..6ed82e90 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -14327,6 +14327,15 @@ dependencies = [
"serde_json",
]
+[[package]]
+name = "raea-core-ask"
+version = "0.1.0"
+dependencies = [
+ "serde",
+ "serde_json",
+ "ts-rs",
+]
+
[[package]]
name = "raea-core-brief"
version = "0.1.0"
diff --git a/Cargo.toml b/Cargo.toml
index a9c85e6e..729bcb9c 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -4,6 +4,7 @@
resolver = "2"
members = [
"core/animate",
+ "core/ask",
"core/brief",
"core/facts",
"core/ease",
diff --git a/core/ask/Cargo.toml b/core/ask/Cargo.toml
new file mode 100644
index 00000000..72894f95
--- /dev/null
+++ b/core/ask/Cargo.toml
@@ -0,0 +1,13 @@
+[package]
+name = "raea-core-ask"
+version = "0.1.0"
+edition = "2024"
+license = "FSL-1.1-ALv2"
+publish = false
+description = "Questions for the decision model (clef-omni): their types, how answers read, the standard sets and the model's limits"
+
+[dependencies]
+serde = { version = "1", features = ["derive"] }
+serde_json = "1"
+# the TypeScript declarations are generated from these types, so the two can't drift
+ts-rs = "12"
diff --git a/core/ask/library/av.json b/core/ask/library/av.json
new file mode 100644
index 00000000..03a9cc3e
--- /dev/null
+++ b/core/ask/library/av.json
@@ -0,0 +1,9 @@
+[
+ {"id": "av.together", "type": "grade", "ask": "How well do the sound and the picture work together: does what you hear belong to what you see, moment by moment?", "uses": ["brief"]},
+ {"id": "av.sound-fits", "ask": "Does every sound fit what is on screen: an action that would make a sound has one, and each thing sounds like what it is made of?", "flags": ["no"]},
+ {"id": "av.music-mood", "ask": "Does the music's mood match what the picture shows at each point?", "flags": ["no"], "uses": ["brief"]},
+ {"id": "av.music-fights-voice", "ask": "At any point do the music or the effects make the voice hard to follow?", "when": {"voice": true}},
+ {"id": "av.voice-suits", "ask": "Does the voice suit the person shown speaking: their age, their manner and their energy?", "flags": ["no"], "when": {"voice": true}},
+ {"id": "av.ambience", "ask": "Does the background sound match the place the picture shows (a street, a kitchen, a room, outdoors)?", "flags": ["no"]},
+ {"id": "av.effects-mark", "ask": "Does each sound effect mark something happening on screen, rather than filling space?", "flags": ["no"]}
+]
diff --git a/core/ask/library/decide.json b/core/ask/library/decide.json
new file mode 100644
index 00000000..af77db91
--- /dev/null
+++ b/core/ask/library/decide.json
@@ -0,0 +1,5 @@
+[
+ {"id": "decide.best", "type": "choose", "ask": "Which of these best fits what the piece is for, for the audience it's for?", "picks": "all", "uses": ["brief"]},
+ {"id": "decide.nearest", "type": "choose", "ask": "The first is the reference. Of the others, which looks and sounds most like it?", "picks": "after-first"},
+ {"id": "decide.changed", "ask": "These are two versions, before and after a change. Does the second change what a viewer sees or hears?", "flags": ["no"]}
+]
diff --git a/core/ask/library/defects.json b/core/ask/library/defects.json
new file mode 100644
index 00000000..19b53941
--- /dev/null
+++ b/core/ask/library/defects.json
@@ -0,0 +1,9 @@
+[
+ {"id": "defect.muffled-voice", "ask": "Is there a muffled, distant voice that is hard to understand?", "sees": "nothing", "when": {"voice": true}, "label_words": ["muffled", "can't hear", "hard to hear", "distant voice"]},
+ {"id": "defect.harsh-music", "ask": "Is there harsh, shrill music that hurts to listen to?", "sees": "nothing", "label_words": ["harsh", "shrill", "piercing"]},
+ {"id": "defect.glitch", "ask": "Is there a rendering glitch: broken or torn geometry, or corrupted, blocky video?", "hears": false, "label_words": ["glitch", "torn", "corrupted", "artifact"]},
+ {"id": "defect.fake", "ask": "Does the scene look fake: plastic and computer generated, like a cheap video game render?", "hears": false, "label_words": ["fake", "plastic", "cgi", "video game"]},
+ {"id": "defect.barren", "ask": "Is the scene empty and barren: a bare room or space with nothing in it and no detail?", "hears": false, "label_words": ["empty", "barren", "bare", "nothing in it"]},
+ {"id": "defect.unreadable-text", "ask": "Is there small or cluttered text that is hard to read?", "hears": false, "label_words": ["can't read", "unreadable", "too small", "cluttered"]},
+ {"id": "defect.shaky-camera", "ask": "Is the camera shaky, like an unsteady handheld shot?", "hears": false, "label_words": ["shaky", "wobbly", "unsteady", "jittery"]}
+]
diff --git a/core/ask/library/platform.json b/core/ask/library/platform.json
new file mode 100644
index 00000000..21b08356
--- /dev/null
+++ b/core/ask/library/platform.json
@@ -0,0 +1,19 @@
+[
+ {"id": "face.text_over", "ask": "At any point does on-screen text or a graphic cover the speaker's eyes, nose or mouth?", "label_words": ["over the face", "covers the face", "cover the face", "over the speaker's", "over his face", "over her face", "over their face", "mouth", "covering the face", "across the face", "on the face"], "calibration": {"auc": 0.85, "n": 126, "positives": 14, "threshold": 0.3487, "date": "2026-10-16", "by": "raea"}, "fix": "look at the frames where cards and captions sit and move them off the face"},
+ {"id": "frame.too_tight", "ask": "Is the framing so tight that the speaker's face is cut off (forehead, chin, or part of the face out of frame) for much of the video?", "label_words": ["too tight", "forehead", "chin", "top of his head", "top of her head", "top of the head", "head is cut", "face is cut", "cuts off the head", "cut off the head", "cropped too tight", "tight crop", "face cut off"], "calibration": {"auc": 0.66, "n": 126, "positives": 32, "threshold": 0.2, "date": "2026-10-16", "by": "raea"}, "fix": "zoom the clips out (framing)"},
+ {"id": "speech.uncaptioned", "ask": "While someone is talking, are their words missing from the screen, so a viewer with the sound off can't follow?", "uses": ["words", "screen-words"], "label_words": ["no captions", "no speech captions", "captions stop", "uncaptioned", "without captions"], "calibration": {"auc": 0.45, "n": 126, "positives": 22, "threshold": 0.5, "date": "2026-10-16", "by": "raea"}, "fix": "caption what's said (captions), unless the piece is meant to run without"},
+ {"id": "text.hard_to_read", "ask": "Is any on-screen text hard to read: too faint against what's behind it, overlapping other text, or too small for a phone?", "uses": ["screen-words"], "label_words": ["low-contrast", "low contrast", "unreadable", "illegible", "hard to read", "overlap", "collide", "invisible", "blends into"], "calibration": {"auc": 0.77, "n": 126, "positives": 45, "threshold": 0.2184, "date": "2026-10-16", "by": "raea"}, "fix": "give the text contrast and room: a scrim or shadow, a stronger colour, one line at a time"},
+ {"id": "end.unfinished", "ask": "Does the video stop before its point lands: mid-sentence, mid-step, or without the ending it set up?", "uses": ["words"], "label_words": ["cuts off", "cut off", "mid-sentence", "mid-thought", "abruptly", "no ending", "mid-word", "never finished"], "calibration": {"auc": 0.51, "n": 126, "positives": 55, "threshold": 0.5, "date": "2026-10-16", "by": "raea"}, "fix": "end on a finished sentence and the payoff or the ask the opening promised"},
+ {"id": "screen.empty", "ask": "Is there a stretch of a second or more with nothing worth looking at: black, blank, frozen or washed out?", "label_words": ["black", "blank", "empty", "washed out", "dead air", "frozen", "static", "nothing usable"], "calibration": {"auc": 0.71, "n": 126, "positives": 88, "threshold": 0.5, "date": "2026-10-16", "by": "raea"}, "fix": "give those seconds a picture: a clip, b-roll, the product, or cut them"},
+ {"id": "message.clear", "ask": "How clearly does the video get one point across to a viewer who has never heard of the brand?", "type": "grade", "uses": ["words", "screen-words", "brand"], "label_words": ["never explains", "no idea what", "never mentions", "confusing", "unclear", "structure is broken"], "calibration": {"auc": 0.39, "n": 126, "positives": 4, "threshold": 0.5, "date": "2026-10-16", "by": "raea"}, "fix": "say the one thing the piece is for earlier and plainer; cut what doesn't serve it"},
+ {"id": "hook.someone_or_something", "ask": "In these opening seconds, is a person's face or the thing being sold clearly on screen?", "flags": ["no"], "window": {"to": 3}, "uses": ["brand"], "label_words": ["opens on a black", "black screen", "empty", "no face", "hook"], "calibration": {"auc": 0.42, "n": 127, "positives": 54, "threshold": 0.5, "date": "2026-10-16", "by": "raea"}, "fix": "open on the speaker's face or the product, not a title card or an empty frame"},
+ {"id": "hook.headline", "ask": "Is there short on-screen text in these opening seconds that gives the viewer a reason to keep watching?", "flags": ["no"], "window": {"to": 3}, "uses": ["screen-words", "words"], "label_words": ["no text overlays to hook", "no hook", "weak hook", "killing the hook"], "calibration": {"auc": 0.25, "n": 127, "positives": 6, "threshold": 0.5, "date": "2026-10-16", "by": "raea"}, "fix": "put the hook line on screen in the first second, short and readable"},
+ {"id": "hook.stops_scroll", "ask": "How likely is someone scrolling a feed to stop on this opening?", "type": "grade", "window": {"to": 3}, "uses": ["words", "screen-words", "platform"], "label_words": ["hook", "opening", "first second"], "calibration": {"auc": 0.48, "n": 127, "positives": 46, "threshold": 0.5, "date": "2026-10-16", "by": "raea"}, "fix": "lead with the most surprising line or picture the takes have; cut the warm-up"},
+ {"id": "board.bar_over_face", "ask": "The panels are a storyboard in time order, with text drawn as solid bars. In any panel, does a bar or graphic sit over a person's eyes, nose or mouth?", "sees": "stills", "hears": false, "label_words": ["over the face", "covers the face", "mouth", "over the speaker's", "across the face"], "calibration": {"auc": 0.87, "n": 124, "positives": 15, "threshold": 0.4354, "date": "2026-10-16", "by": "raea"}, "fix": "move that text or graphic off the face before rendering"},
+ {"id": "board.bars_collide", "ask": "The panels are a storyboard in time order, with text drawn as solid bars. In any panel, do two blocks of text overlap or touch each other?", "sees": "stills", "hears": false, "label_words": ["overlap", "stacked on the exact same line", "collide", "text over text"], "calibration": {"auc": 0.72, "n": 124, "positives": 27, "threshold": 0.5, "date": "2026-10-16", "by": "raea"}, "fix": "give each line its own band, or show them one after another"},
+ {"id": "board.no_change", "ask": "The panels are a storyboard in time order. Do most panels look nearly the same, as if the picture barely changes through the video?", "sees": "stills", "hears": false, "label_words": ["static shot", "held for", "no movement", "monotonous", "same shot", "nothing changes"], "calibration": {"auc": 0.84, "n": 124, "positives": 2, "threshold": 0.5, "date": "2026-10-16", "by": "raea"}, "fix": "vary the picture: punch-ins, b-roll, the product, a designed moment"},
+ {"id": "board.empty_panel", "ask": "The panels are a storyboard in time order. Is any panel empty: black, blank, or with nothing to look at?", "sees": "stills", "hears": false, "label_words": ["black", "blank", "empty", "nothing on screen", "dead air"], "calibration": {"auc": 0.58, "n": 124, "positives": 78, "threshold": 0.5, "date": "2026-10-16", "by": "raea"}, "fix": "cover that moment with a clip, b-roll or a card"},
+ {"id": "brand.named", "ask": "Is the brand or product name said aloud or shown on screen at some point?", "flags": ["no"], "uses": ["brand", "words", "screen-words"], "label_words": ["never mentions", "no idea what the product", "never names", "brand name", "app name"], "calibration": {"auc": 0.4, "n": 127, "positives": 8, "threshold": 0.5, "date": "2026-10-16", "by": "raea"}, "fix": "say or show the name: on screen in the first seconds and again at the end"},
+ {"id": "brand.logo", "ask": "Is the brand's logo or wordmark visible at some point in the video?", "flags": ["no"], "uses": ["brand"], "label_words": ["no logo", "logo", "wordmark", "no branding"], "calibration": {"auc": 0.2, "n": 127, "positives": 6, "threshold": 0.5, "date": "2026-10-16", "by": "raea"}, "fix": "place the logo from media/brand on the end card or as a small lockup"},
+ {"id": "brand.look", "ask": "How well do the on-screen graphics (type, colours, cards) match the brand described?", "type": "grade", "uses": ["brand"], "label_words": ["off-brand", "generic", "template", "same branding", "doesn't match the brand"], "calibration": {"auc": 0.46, "n": 127, "positives": 6, "threshold": 0.5, "date": "2026-10-16", "by": "raea"}, "fix": "take type and colours from brand/brand.css and BRAND.md; drop the house look"}
+]
diff --git a/core/ask/src/lib.rs b/core/ask/src/lib.rs
new file mode 100644
index 00000000..fd9c3b48
--- /dev/null
+++ b/core/ask/src/lib.rs
@@ -0,0 +1,27 @@
+//! 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 library;
+pub mod limits;
+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;
diff --git a/core/ask/src/library.rs b/core/ask/src/library.rs
new file mode 100644
index 00000000..ac0a5ae5
--- /dev/null
+++ b/core/ask/src/library.rs
@@ -0,0 +1,75 @@
+//! 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) and `decide` (picks and
+//! comparisons). The JSON sets ship inside raea; the rubric is read from the guide the caller hands in.
+
+use crate::question::{Kind, Question};
+
+/// Every set, in the order `raea ask list` shows them.
+pub const SETS: [&str; 5] = ["rubric", "av", "defects", "platform", "decide"];
+
+fn embedded(name: &str) -> Option<&'static str> {
+ Some(match name {
+ "av" => include_str!("../library/av.json"),
+ "defects" => include_str!("../library/defects.json"),
+ "platform" => include_str!("../library/platform.json"),
+ "decide" => include_str!("../library/decide.json"),
+ _ => return None,
+ })
+}
+
+/// The rubric's questions from its guide: each line under "## The questions" is `- id (modes): the question`. A grade
+/// over the five levels, as critique asks it. `silent` is when no one speaks, not a mode; a question with an `ID-silent`
+/// twin is asked only when someone speaks, and its twin in its place otherwise.
+pub fn rubric(md: &str) -> Vec<Question> {
+ let body = md.split("## The questions").nth(1).unwrap_or("");
+ let body = body.split("\n## ").next().unwrap_or("");
+ let mut out: Vec<Question> = body
+ .lines()
+ .filter_map(|l| {
+ let l = l.strip_prefix("- ")?;
+ let (head, ask) = l.split_once("): ")?;
+ let (id, modes) = head.split_once(" (")?;
+ let mut q = Question::plain(id.trim(), ask.trim());
+ q.kind = Kind::Grade;
+ q.uses = vec!["brief".into(), "measures".into()];
+ for m in modes.split(',').map(str::trim) {
+ match m {
+ "all" => {}
+ "silent" => q.when.voice = Some(false),
+ m => q.when.modes.push(m.to_string()),
+ }
+ }
+ Some(q)
+ })
+ .collect();
+ let ids: Vec<String> = out.iter().map(|q| q.id.clone()).collect();
+ for q in &mut out {
+ let twin = format!("{}-silent", q.id);
+ if ids.contains(&twin) {
+ q.when.voice = Some(true);
+ q.swap = Some(twin);
+ }
+ }
+ out
+}
+
+/// 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 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(", ")))?;
+ serde_json::from_str(text).map_err(|e| format!("the {name} set doesn't read: {e}"))
+}
+
+/// Every standard question.
+pub fn all(rubric_md: Option<&str>) -> Vec<Question> {
+ SETS.iter().filter_map(|s| set(s, rubric_md).ok()).flatten().collect()
+}
+
+/// A standard question by id.
+pub fn find(id: &str, rubric_md: Option<&str>) -> Option<Question> {
+ all(rubric_md).into_iter().find(|q| q.id == id)
+}
diff --git a/core/ask/src/limits.rs b/core/ask/src/limits.rs
new file mode 100644
index 00000000..36a3a001
--- /dev/null
+++ b/core/ask/src/limits.rs
@@ -0,0 +1,68 @@
+//! clef-omni's limits, and raea-api's where it's stricter (POST /v1/clef/ask), so a call that passes here passes on
+//! every route (docs/ask.feature AK1). Verified against clef's schema and probe calls 2026-10-18 (sdk/app playtest.ts).
+
+use crate::question::{Kind, Question};
+
+/// questions in one call (clef refuses 65)
+pub const QUESTIONS: usize = 64;
+/// a question id's length (raea-api's; clef takes 100)
+pub const ID_LEN: usize = 64;
+/// a choice's options (raea-api's; clef takes 255)
+pub const OPTIONS: (usize, usize) = (2, 16);
+/// a rate's levels
+pub const LEVELS: (usize, usize) = (2, 10);
+/// stills a call: 4 MiB each, 8 MiB in all
+pub const STILLS: usize = 4;
+pub const STILL_BYTES: usize = 4 << 20;
+pub const STILLS_BYTES: usize = 8 << 20;
+/// videos a call: 60 s and 16 MiB each, sampled at 2 fps
+pub const VIDEOS: usize = 2;
+pub const VIDEO_SECONDS: f64 = 60.0;
+pub const VIDEO_BYTES: usize = 16 << 20;
+/// sounds a call: 300 s and 8 MiB each
+pub const SOUNDS: usize = 4;
+pub const SOUND_SECONDS: f64 = 300.0;
+pub const SOUND_BYTES: usize = 8 << 20;
+/// sound and video together, decoded
+pub const AV_BYTES: usize = 16 << 20;
+/// the state paragraph (raea-api cuts it at 8,000 characters)
+pub const STATE_CHARS: usize = 8000;
+/// dollars a million input tokens
+pub const USD_PER_M: f64 = 0.15;
+/// input tokens, for the estimate `--dry` prints: a second of 480 px video (about 1,400 a two-second clip, 11-18), a
+/// minute of sound, a still
+pub const TOKENS_VIDEO_S: f64 = 700.0;
+pub const TOKENS_SOUND_MIN: f64 = 780.0;
+pub const TOKENS_STILL: f64 = 1024.0;
+
+/// Why a question can't be sent, or None.
+pub fn check(q: &Question) -> Option<String> {
+ let id_ok = !q.id.is_empty() && q.id.len() <= ID_LEN && q.id.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-'));
+ if !id_ok {
+ return Some(format!("{:?}: an id is 1 to {ID_LEN} letters, digits, _ . or -", q.id));
+ }
+ if q.ask.trim().is_empty() {
+ return Some(format!("{}: it asks nothing", q.id));
+ }
+ let n = q.levels().len();
+ let (lo, hi) = match q.kind {
+ Kind::Yes => return None,
+ Kind::Choose | Kind::Grade => OPTIONS,
+ Kind::Rate => LEVELS,
+ };
+ if q.picks.is_none() && !(lo..=hi).contains(&n) {
+ return Some(format!("{}: {lo} to {hi} {}, not {n}", q.id, if q.kind == Kind::Choose { "options" } else { "levels" }));
+ }
+ let mut seen = std::collections::BTreeSet::new();
+ if let Some(o) = q.levels().into_iter().find(|o| !seen.insert(o.clone())) {
+ return Some(format!("{}: {o:?} is there twice", q.id));
+ }
+ None
+}
+
+/// The estimated cost of one call, in dollars.
+pub fn estimate(video_s: f64, sound_s: f64, stills: usize, state_chars: usize, questions: usize) -> f64 {
+ let text = (state_chars as f64 + questions as f64 * 120.0) / 4.0;
+ let tokens = video_s * TOKENS_VIDEO_S + sound_s / 60.0 * TOKENS_SOUND_MIN + stills as f64 * TOKENS_STILL + text;
+ tokens * USD_PER_M / 1e6
+}
diff --git a/core/ask/src/question.rs b/core/ask/src/question.rs
new file mode 100644
index 00000000..21ffe6ee
--- /dev/null
+++ b/core/ask/src/question.rs
@@ -0,0 +1,291 @@
+//! A question for the decision model (docs/ask.feature AK1): clef-omni's own types, what a question needs to be asked,
+//! and how its answer reads as a problem score, so every question is calibrated the same way whatever its type.
+
+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, TS)]
+#[serde(rename_all = "lowercase")]
+pub enum Kind {
+ /// the probability of yes
+ #[default]
+ Yes,
+ /// one of its options, with a probability on each
+ Choose,
+ /// ordered levels, lowest first, read as the expected level
+ Grade,
+ /// clef's own rubric: 2 to 10 levels, its probability-weighted level
+ Rate,
+}
+
+/// What of the picture a question looks at.
+#[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)
+ #[default]
+ Video,
+ /// stills (a sheet, a storyboard's panels, frames picked out)
+ Stills,
+ /// no picture: the sound or the words alone
+ Nothing,
+}
+
+/// 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, TS)]
+#[serde(rename_all = "kebab-case")]
+pub enum Picks {
+ All,
+ AfterFirst,
+}
+
+/// What a piece must be for a question to be asked of it. Unset is any.
+#[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")]
+ pub voice: Option<bool>,
+ /// true: only for a game; false: never for one
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub game: Option<bool>,
+}
+
+/// The seconds a question looks at; unset ends are the file's.
+#[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>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub to: Option<f64>,
+}
+
+/// How well a question's answers separate work with the problem from work without it, on labels (AK7).
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
+#[ts(optional_fields)]
+pub struct Calibration {
+ pub auc: f64,
+ pub n: u32,
+ pub positives: u32,
+ /// the problem score at which it flags (10% false positives on its labels)
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub threshold: Option<f64>,
+ /// YYYY-MM-DD
+ pub date: String,
+ /// whose labels: "raea" (raea's bench, shipped) or "you"
+ pub by: String,
+}
+
+/// A question, as the standard sets, a taste line, a batch file or the command line write it.
+#[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
+ #[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")]
+ pub swap: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub window: Option<Window>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ 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>,
+ /// what to change when it flags
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub fix: Option<String>,
+}
+
+fn yes() -> bool {
+ true
+}
+fn is_true(b: &bool) -> bool {
+ *b
+}
+
+impl When {
+ pub fn is_any(&self) -> bool {
+ self.modes.is_empty() && self.voice.is_none() && self.game.is_none()
+ }
+}
+
+/// What raea knows of a piece before asking (apps/ask prepare.rs reads it), for `when` and for what the media can be.
+#[derive(Debug, Clone, Default)]
+pub struct Facts {
+ pub modes: Vec<String>,
+ /// someone is heard speaking: Some(true), no one: Some(false), unknown: None
+ pub voice: Option<bool>,
+ pub game: bool,
+ pub sound: bool,
+ pub video: bool,
+}
+
+/// An answer read: its value (yes's probability, choose's top probability, a level), its problem score (0 to 1, higher
+/// is likelier a problem; none for a pick), and a line in words.
+#[derive(Debug, Clone, PartialEq, Serialize)]
+pub struct Reading {
+ pub value: f64,
+ pub problem: Option<f64>,
+ pub choice: Option<String>,
+ pub says: String,
+}
+
+impl Question {
+ /// A yes or no question in plain words, as the command line and a taste line make one.
+ pub fn plain(id: &str, ask: &str) -> Question {
+ serde_json::from_value(json!({"id": id, "ask": ask})).expect("a plain question")
+ }
+
+ /// Its levels or options as clef is sent them.
+ pub fn levels(&self) -> Vec<String> {
+ match (self.kind, self.options.is_empty()) {
+ (Kind::Grade, true) => LEVELS.iter().map(|s| s.to_string()).collect(),
+ _ => self.options.clone(),
+ }
+ }
+
+ /// A hash of what clef reads (its words, type, options and their meanings): a new wording is a new version, with
+ /// its own calibration. FNV-1a, so it's the same on every build.
+ pub fn version(&self) -> String {
+ let text = format!("{:?}\u{1f}{}\u{1f}{}\u{1f}{:?}", self.kind, self.ask, self.levels().join("\u{1e}"), self.means);
+ let h = text.bytes().fold(0xcbf2_9ce4_8422_2325u64, |h, b| (h ^ b as u64).wrapping_mul(0x0100_0000_01b3));
+ format!("{h:016x}")
+ }
+
+ /// Why it can't be asked of this piece, or None when it can.
+ pub fn not_for(&self, f: &Facts) -> Option<String> {
+ let w = &self.when;
+ if !w.modes.is_empty() && !w.modes.iter().any(|m| m == "all" || f.modes.contains(m)) {
+ return Some(format!("it's for {} work, and this is {}", w.modes.join(" or "), if f.modes.is_empty() { "unnamed".into() } else { f.modes.join(" and ") }));
+ }
+ match (w.voice, f.voice) {
+ (Some(true), Some(false)) => return Some("no one speaks in it".into()),
+ (Some(false), Some(true)) => return Some("someone speaks in it".into()),
+ _ => {}
+ }
+ if w.game.is_some_and(|g| g != f.game) {
+ return Some(if f.game { "it isn't asked of a game".into() } else { "it's asked of games".into() });
+ }
+ if self.hears && self.sees == Sees::Nothing && !f.sound {
+ return Some("it listens, and the file has no sound".into());
+ }
+ if self.sees == Sees::Video && !f.video && !(self.hears && f.sound) {
+ return Some("it watches the picture move, and the file is a still".into());
+ }
+ None
+ }
+
+ /// The question as clef is sent it.
+ pub fn wire(&self) -> Value {
+ match self.kind {
+ Kind::Yes => {
+ let mut q = json!({"type": "noul", "instructions": self.ask});
+ if let (Some(y), Some(n)) = (self.means.get("yes"), self.means.get("no")) {
+ q["criteria"] = json!({"true": y, "false": n});
+ }
+ q
+ }
+ Kind::Choose | Kind::Grade => {
+ let criteria: serde_json::Map<String, Value> = self.levels().into_iter().map(|o| {
+ let m = self.means.get(&o).map(|s| Value::from(s.as_str())).unwrap_or(Value::Null);
+ (o, m)
+ }).collect();
+ json!({"type": "choice", "instructions": self.ask, "criteria": criteria})
+ }
+ Kind::Rate => json!({"type": "score", "instructions": self.ask, "criteria": self.levels()}),
+ }
+ }
+
+ /// clef's answer read (the reading checks.rs and the playtest DSL make).
+ pub fn read(&self, answer: &Value) -> Reading {
+ let levels = self.levels();
+ let top = (levels.len().max(2) - 1) as f64;
+ let pr = |k: &str| answer["probabilities"][k].as_f64().unwrap_or(0.0);
+ match self.kind {
+ Kind::Yes => {
+ let p = answer["noul"].as_f64().unwrap_or(0.0);
+ let bad = if self.flags.first().is_some_and(|f| f == "no") { 1.0 - p } else { p };
+ Reading { value: p, problem: Some(bad), choice: None, says: format!("{} ({p:.2} yes)", if p >= 0.5 { "yes" } else { "no" }) }
+ }
+ Kind::Choose => {
+ let choice = answer["choice"].as_str().map(str::to_string);
+ let p = choice.as_deref().map(pr).unwrap_or(0.0);
+ let problem = (!self.flags.is_empty()).then(|| self.flags.iter().map(|f| pr(f)).sum::<f64>());
+ Reading { value: p, problem, says: format!("{} ({p:.2})", choice.as_deref().unwrap_or("no answer")), choice }
+ }
+ Kind::Grade | Kind::Rate => {
+ let v = if self.kind == Kind::Rate {
+ answer["score"].as_f64().unwrap_or(0.0)
+ } else {
+ let total: f64 = levels.iter().map(|l| pr(l)).sum();
+ match total > 0.0 {
+ true => levels.iter().enumerate().map(|(i, l)| i as f64 * pr(l)).sum::<f64>() / total,
+ false => levels.iter().position(|l| answer["choice"].as_str() == Some(l)).unwrap_or(0) as f64,
+ }
+ };
+ let name = levels.get(v.round() as usize).cloned();
+ Reading { value: v, problem: Some((1.0 - v / top).clamp(0.0, 1.0)), says: format!("{} ({v:.1} of {top})", name.as_deref().unwrap_or("?")), choice: name }
+ }
+ }
+ }
+
+ /// Calibrated: its labels separate (an AUC of 0.8 or more, the fingerprint's gate) and it has a threshold. Until
+ /// then its answers are advice.
+ pub fn calibrated(&self) -> bool {
+ self.calibration.as_ref().is_some_and(|c| c.auc >= 0.8 && c.threshold.is_some())
+ }
+
+ /// Whether a reading flags a problem: past its calibrated threshold, else past even odds (as advice).
+ pub fn flagged(&self, r: &Reading) -> bool {
+ let at = self.calibration.as_ref().and_then(|c| c.threshold).filter(|_| self.calibrated()).unwrap_or(0.5);
+ r.problem.is_some_and(|p| p >= at)
+ }
+}
diff --git a/core/ask/src/tests.rs b/core/ask/src/tests.rs
new file mode 100644
index 00000000..91299324
--- /dev/null
+++ b/core/ask/src/tests.rs
@@ -0,0 +1,119 @@
+use super::*;
+use serde_json::json;
+
+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() {
+ let all = library::all(Some(RUBRIC));
+ assert!(all.len() >= 45, "{} questions", all.len());
+ for q in &all {
+ assert_eq!(limits::check(q), None, "{}", q.id);
+ }
+ let mut ids: Vec<&str> = all.iter().map(|q| q.id.as_str()).collect();
+ ids.sort();
+ let before = ids.len();
+ ids.dedup();
+ assert_eq!(before, ids.len(), "an id is used twice");
+ for q in all.iter().filter(|q| q.swap.is_some()) {
+ assert!(library::find(q.swap.as_deref().unwrap(), Some(RUBRIC)).is_some(), "{} swaps to a question that isn't there", q.id);
+ }
+}
+
+#[test]
+fn the_rubric_comes_from_its_guide_and_sound_swaps_when_no_one_speaks() {
+ let r = library::rubric(RUBRIC);
+ let sound = r.iter().find(|q| q.id == "sound").unwrap();
+ assert_eq!((sound.kind, sound.when.voice, sound.swap.as_deref()), (Kind::Grade, Some(true), Some("sound-silent")));
+ let silent = r.iter().find(|q| q.id == "sound-silent").unwrap();
+ assert_eq!(silent.when.voice, Some(false));
+ let open = r.iter().find(|q| q.id == "open").unwrap();
+ assert_eq!(open.when.modes, ["pitch", "story", "explain"]);
+ let facts = Facts { modes: vec!["pitch".into()], voice: Some(false), sound: true, video: true, ..Default::default() };
+ assert_eq!(sound.not_for(&facts).as_deref(), Some("no one speaks in it"));
+ assert_eq!(silent.not_for(&facts), None);
+ assert!(r.iter().find(|q| q.id == "loop").unwrap().not_for(&facts).unwrap().contains("explain"));
+}
+
+#[test]
+fn a_question_needs_what_the_file_has() {
+ let mut q = Question::plain("hum", "Is there a hum under the voice?");
+ q.sees = Sees::Nothing;
+ let still = Facts { video: false, sound: false, ..Default::default() };
+ assert!(q.not_for(&still).unwrap().contains("no sound"));
+ let picture = Question::plain("cut", "Does the cut jump?");
+ assert!(picture.not_for(&still).unwrap().contains("still"));
+ assert_eq!(picture.not_for(&Facts { video: true, ..Default::default() }), None);
+}
+
+#[test]
+fn each_type_goes_out_as_clefs_own_and_reads_back_as_a_problem_score() {
+ let mut q = Question::plain("fits", "Does the sound fit the picture?");
+ q.flags = vec!["no".into()];
+ assert_eq!(q.wire(), json!({"type": "noul", "instructions": "Does the sound fit the picture?"}));
+ let r = q.read(&json!({"noul": 0.2}));
+ assert_eq!((r.value, r.problem), (0.2, Some(0.8)));
+ assert!(q.flagged(&r), "advice flags past even odds");
+
+ let mut g = Question::plain("pace", "How well is it paced?");
+ g.kind = Kind::Grade;
+ assert_eq!(g.wire()["criteria"].as_object().unwrap().len(), 5);
+ let r = g.read(&json!({"choice": "strong", "probabilities": {"strong": 0.5, "excellent": 0.5}}));
+ assert_eq!((r.value, r.problem, r.choice.as_deref()), (3.5, Some(0.125), Some("excellent")));
+
+ let mut rate = Question::plain("look", "How strong is the look?");
+ rate.kind = Kind::Rate;
+ rate.options = vec!["none".into(), "some".into(), "strong".into()];
+ assert_eq!(rate.wire()["criteria"], json!(["none", "some", "strong"]), "a score's levels are a list");
+ assert_eq!(rate.read(&json!({"score": 1.0})).problem, Some(0.5));
+
+ let mut c = Question::plain("best", "Which is best?");
+ c.kind = Kind::Choose;
+ c.options = vec!["first".into(), "second".into()];
+ let r = c.read(&json!({"choice": "second", "probabilities": {"first": 0.3, "second": 0.7}}));
+ assert_eq!((r.choice.as_deref(), r.problem), (Some("second"), None), "a pick has no problem score");
+}
+
+#[test]
+fn a_calibrated_question_flags_at_its_own_threshold() {
+ let q = library::find("face.text_over", None).unwrap();
+ assert!(q.calibrated());
+ assert!(q.flagged(&q.read(&json!({"noul": 0.36}))), "0.36 is past its 0.3487");
+ let weak = library::find("speech.uncaptioned", None).unwrap();
+ assert!(!weak.calibrated(), "an AUC of 0.45 is advice");
+}
+
+#[test]
+fn a_new_wording_is_a_new_version_and_the_id_is_not_part_of_it() {
+ let a = Question::plain("a", "Is it loud?");
+ let b = Question::plain("b", "Is it loud?");
+ let c = Question::plain("a", "Is it too loud?");
+ assert_eq!(a.version(), b.version());
+ assert_ne!(a.version(), c.version());
+ assert_eq!(a.version(), "3ab49a6dcc96d4ad", "the same on every build (FNV-1a)");
+}
+
+#[test]
+fn limits_refuse_what_raea_api_would() {
+ let mut q = Question::plain("a b", "x");
+ assert!(limits::check(&q).unwrap().contains("id"));
+ q.id = "ok".into();
+ q.kind = Kind::Choose;
+ q.options = vec!["one".into()];
+ assert!(limits::check(&q).unwrap().contains("2 to 16"));
+ q.options = vec!["one".into(), "one".into()];
+ assert!(limits::check(&q).unwrap().contains("twice"));
+ let e = limits::estimate(60.0, 60.0, 0, 400, 3);
+ assert!(e > 0.005 && e < 0.008, "{e}");
+}
diff --git a/docs/ask.feature b/docs/ask.feature
index 4b29b0c0..92a1733d 100644
--- a/docs/ask.feature
+++ b/docs/ask.feature
@@ -63,7 +63,10 @@ Feature: Ask: questions about a piece's picture and sound, answered by the decis
levels, poor to excellent unless given, read as the expected level) or `rate` (2 to 10 levels)
And `when` says what a question needs to be asked (modes; a voice heard or none; a game), and `swap` names the
question asked in its place when it doesn't apply, so `sound` to `sound-silent` is data, not code
- And sdk/app's playtest DSL imports clef's limits from the generated TypeScript instead of keeping its own
+ And every answer reads as a problem score from 0 to 1 whatever its type (a yes's probability on the answer that
+ flags, a choice's on its flagging options, one less a grade's level over its top), so one calibration fits all
+ And the limits are raea-api's where they're stricter than clef's (ids of 64 characters, 16 options), so a call that
+ passes them passes on every route
@needs:AK1
Scenario: AK1b. One clef client, routed to the person's plan
diff --git a/sdk/raea/src/ask.gen.ts b/sdk/raea/src/ask.gen.ts
new file mode 100644
index 00000000..479e672a
--- /dev/null
+++ b/sdk/raea/src/ask.gen.ts
@@ -0,0 +1,81 @@
+// Generated from raea-core-ask (core/ask) by its `declarations`; edit the Rust, not this.
+
+export 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 no) means, when its name alone doesn't say
+ */
+means?: { [key in string]: string },
+/**
+ * the answers that mean a problem: yes's "yes" (the default) or "no"; choose's options (none: a pick, no problem)
+ */
+flags?: Array<string>, sees?: Sees,
+/**
+ * whether it listens to the sound (true unless set)
+ */
+hears?: boolean,
+/**
+ * what the state tells clef beside the media: brief, words (heard), screen-words, measures, brand, platform
+ */
+uses?: Array<string>, when?: When,
+/**
+ * the question asked in its place when `when` doesn't hold (sound -> sound-silent)
+ */
+swap?: string, window?: Window, picks?: Picks,
+/**
+ * words in a person's note that mean they saw this problem (AK6)
+ */
+label_words?: Array<string>, calibration?: Calibration,
+/**
+ * what to change when it flags
+ */
+fix?: string, };
+
+export type Kind = "yes" | "choose" | "grade" | "rate";
+
+export type Sees = "video" | "stills" | "nothing";
+
+export type Picks = "all" | "after-first";
+
+export 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, };
+
+export type Window = { from?: number, to?: number, };
+
+export 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, };
+
+export const SETS = ["rubric", "av", "defects", "platform", "decide"] as const;
diff --git a/tools/layers.toml b/tools/layers.toml
index d6cb16eb..810a3262 100644
--- a/tools/layers.toml
+++ b/tools/layers.toml
@@ -48,6 +48,7 @@ raea-gpu-device = "gpu"
raea-core-k = "core"
raea-core-calls = "core"
raea-core-brief = "core"
+raea-core-ask = "core"
raea-sys-k = "systems"
raea-sys-mix = "systems"
raea-sys-tone = "systems"