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.

DR6: done. Each ask of a note is held by a check that must fail on the work as it stands before the work changes, or by a clip the person signs. An ask names its check (raea's by name or a .ts check by its path), its values, its composition (Ask.of; Rule.of runs a rule only there) and, where it can't be measured, proof { shot | frames, sign }. raea notes check runs the asks through raea check's run (apps/direction, lent by the CLI): a first run that passes is refused (exit 1), a failure is kept with its check and values in .raea/notes-checks.json, a check changed after it failed is to check again, and each finding's by is its ask, so two asks on one check are counted apart; raea check runs the notes' checks beside the rules. Each clip is cut with ffmpeg from the composition's newest render, never from one the composition changed after; the person's sign comes back from the app with the render's sha256 and is kept by raea notes take. An ask reads to check, failing, to sign, passing or signed (the agent's move until there is a clip of the work as it stands), the note its worst; raea notes ls says each and raea notes post sends the badge, each ask's state and each clip (raea show --status --states, --sign --clip --render). raea/check gains a per-rule memo, after, named, turned and inside; six worked checks ship in sdk/guides/craft/checks and in the skill as craft/checks (rides, flat-type, faces, stands-on, shot-length, no-part), with their pieces and cheats in bench/direction/asks (asks.sh: 35 cases as expected). A plain element that covers another is named by the component that drew it (runtime/world). Proved end to end in a copy of the raea app (1109.87): a note sent, taken, restated, failing, the work changed and passing, the clip signed in the page, --done refused, and the sign reopened by a changed composition. Tests: raea-core-facts 16, raea-app-notes 10, raea-app-direction 16, raea-runtime-world 15, engine/cli show.test.ts 5. The craft router says the order, and the manual's notes, show and raea/check pages say what's new. The worked checks' table moves "low poly" to DR14 and "the light at the cut" to DR19, each with why.

shinyobjectzd412678357a1
diff --git a/Cargo.lock b/Cargo.lock
index 29fb95d0..40ffca3f 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -13613,6 +13613,7 @@ name = "raea-app-direction"
version = "0.1.0"
dependencies = [
"raea-app-check",
+ "raea-app-notes",
"raea-app-registry",
"raea-core-brief",
"raea-core-facts",
@@ -13674,7 +13675,10 @@ name = "raea-app-notes"
version = "0.1.0"
dependencies = [
"raea-core-facts",
+ "raea-io-trace",
+ "serde",
"serde_json",
+ "sha2 0.10.9",
"tempfile",
]
diff --git a/apps/direction/Cargo.toml b/apps/direction/Cargo.toml
index c7ddace8..d15e816a 100644
--- a/apps/direction/Cargo.toml
+++ b/apps/direction/Cargo.toml
@@ -18,5 +18,7 @@ serde_json = "1"
raea-core-brief = { path = "../../core/brief" }
raea-app-check = { path = "../check" }
raea-app-registry = { path = "../workspace/registry" }
+# the project's notes, whose asks' checks raea check runs beside its rules (DR6)
+raea-app-notes = { path = "../notes" }
# a TS check's run printing nothing to the terminal (its ECHO)
raea-runtime-react = { path = "../../runtime/react", default-features = false }
diff --git a/apps/direction/src/check.rs b/apps/direction/src/check.rs
index 2a9b0b03..508c1457 100644
--- a/apps/direction/src/check.rs
+++ b/apps/direction/src/check.rs
@@ -8,7 +8,7 @@
use std::path::{Path, PathBuf};
use raea_core_brief::{controller, taste};
-use raea_core_facts::{finding, record, Facts, Finding, Level, Rule};
+use raea_core_facts::{finding, record, Facts, Finding, Level, Rule, Shot};
use raea_runtime_bundle::flag;
use raea_runtime_world::{Ask, Render};
use serde_json::{json, Value};
@@ -74,9 +74,26 @@ enum How {
File(ts::Meta),
}
-/// Every rule `project` is held to (`given`: `--taste`'s files), and a finding for each file of rules raea couldn't
-/// read.
-fn rules(project: &Path, given: Vec<PathBuf>, host: &Host) -> (Vec<Rule>, Vec<Finding>) {
+/// Every rule `project` is held to (`given`: `--taste`'s files) with its notes' asks (DR6), the notes, and a finding
+/// for each file of rules or note raea couldn't read.
+fn rules(project: &Path, given: Vec<PathBuf>, host: &Host) -> (Vec<Rule>, Vec<Finding>, Vec<raea_app_notes::Kept>) {
+ let (mut out, mut bad) = held(project, given, host);
+ let notes = raea_app_notes::read(project, host.ts.eval);
+ let (asks, unread) = raea_app_notes::check::rules(project, &notes);
+ out.extend(asks);
+ bad.extend(unread);
+ // a check's path made plain (no `..`), as its import will name it
+ for r in out.iter_mut() {
+ if let Some(p) = r.file() {
+ r.check = raea_runtime_bundle::normalize(p).display().to_string();
+ }
+ }
+ (out, bad, notes)
+}
+
+/// raea's floor, the person's taste and the workspace's and project's controllers' rules, and a finding for each file
+/// of them raea couldn't read.
+fn held(project: &Path, given: Vec<PathBuf>, host: &Host) -> (Vec<Rule>, Vec<Finding>) {
// raea's own: the floor, and the reading check (DR28: its findings keep their own levels, so no rule level)
let read = Rule { level: None, ..Rule::named("text-read", "text can be read for as long as it needs, and OCR reads it", Default::default(), Level::Warn, "raea") };
let mut out = vec![Rule::named("floor", "raea's floor", Default::default(), Level::Error, "raea"), read];
@@ -98,11 +115,7 @@ fn rules(project: &Path, given: Vec<PathBuf>, host: &Host) -> (Vec<Rule>, Vec<Fi
files.sort();
for f in files {
match (host.ts.eval)(&f).and_then(|j| controller::of_json(&j)) {
- // a check's path made plain (no `..`), as its import will name it
- Ok(c) => out.extend(Rule::of_controller(&c, &dir, &format!("{scope} {}", name(&f))).into_iter().map(|r| match r.file() {
- Some(p) => Rule { check: raea_runtime_bundle::normalize(p).display().to_string(), ..r },
- None => r,
- })),
+ Ok(c) => out.extend(Rule::of_controller(&c, &dir, &format!("{scope} {}", name(&f)))),
Err(e) => bad.push(Finding::new("controller", Level::Error, format!("raea can't read it: {e}"), "raea check").about(name(&f), None)),
}
}
@@ -134,16 +147,21 @@ fn compositions(target: &Path, args: &[String]) -> R<Vec<(PathBuf, Option<String
Ok(out)
}
-/// What one composition's checks found, and each check that waits, with what for.
+/// What one composition's checks found, each check that waits with what for, and its newest render, its named shots
+/// (each from its first frame to its end) and its rate, for a note's clip (DR6).
struct Checked {
file: PathBuf,
id: Option<String>,
found: Vec<Finding>,
waits: Vec<(String, String)>,
+ render: Option<raea_app_notes::check::Rendered>,
+ shots: Vec<(String, i64, Option<i64>)>,
+ fps: f64,
}
-/// One composition checked against `rules` (`--only`'s already picked).
-fn check_one(tsx: &Path, id: Option<String>, rules: &[Rule], args: &[String], host: &Host) -> R<Checked> {
+/// One composition checked against `rules` (`--only`'s already picked), every frame read when `whole` or a check
+/// ranges over them.
+fn check_one(tsx: &Path, id: Option<String>, rules: &[Rule], args: &[String], whole: bool, host: &Host) -> R<Checked> {
let named = systems::named();
let mut found = Vec::new();
let mut hows = Vec::new();
@@ -161,7 +179,7 @@ fn check_one(tsx: &Path, id: Option<String>, rules: &[Rule], args: &[String], ho
}
let frames: Vec<&Frames> = hows.iter().map(|(_, h)| match h { How::Named(n) => &n.frames, How::File(m) => &m.frames }).collect();
// every frame when a check ranges over them (cuts and lines are found in them), else the frames named and the first
- let whole = frames.iter().any(|f| f.whole());
+ let whole = whole || frames.iter().any(|f| f.whole());
let mut asked: Vec<i64> = if whole { Vec::new() } else { frames.iter().flat_map(|f| if let Frames::At(v) = f { v.clone() } else { vec![] }).chain([0]).collect() };
asked.sort();
asked.dedup();
@@ -244,7 +262,39 @@ fn check_one(tsx: &Path, id: Option<String>, rules: &[Rule], args: &[String], ho
plan.push(ts::Planned { check: k, frames: on, values: r.values.clone(), level: r.level, by: r.by.clone() });
}
found.extend(ts::run(&files, &plan, &worlds, &host.ts)?);
- Ok(Checked { file: tsx.to_path_buf(), id, found: finding::ranked(found), waits })
+ let render = rendered.map(|r| {
+ // how many frames it drew, as its manifest lists them
+ let m: Value = std::fs::read(r["manifest"].as_str().unwrap_or("")).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default();
+ raea_app_notes::check::Rendered { out: PathBuf::from(r["out"].as_str().unwrap_or("")), stale: r["stale"] == true, frames: m["frames"].as_array().map_or(0, |f| f.len() as i64) }
+ });
+ let mut shots: Vec<(String, i64, Option<i64>)> = worlds.iter().flat_map(|w| w.find(&["Shot"]).into_iter().filter_map(|e| w.get::<Shot>(e.id)).filter_map(|s| Some((s.name?, s.from, s.to)))).collect();
+ shots.sort();
+ shots.dedup();
+ let fps = worlds.first().map_or(30.0, |w| w.fps);
+ Ok(Checked { file: tsx.to_path_buf(), id, found: finding::ranked(found), waits, render, shots, fps })
+}
+
+/// Whether `r` runs on the composition `tsx` (`id` where its file registers several) of `project`: a rule a note's ask
+/// scopes to one (`of`) runs there alone.
+fn applies(r: &Rule, project: &Path, tsx: &Path, id: Option<&str>) -> bool {
+ r.of.as_ref().is_none_or(|of| raea_app_notes::check::is_of(of, &named_as(project, tsx, id)))
+}
+
+/// A composition as a note's ask names it: its file from the project, `#ID` after it where the file registers several.
+fn named_as(project: &Path, tsx: &Path, id: Option<&str>) -> String {
+ format!("{}{}", record::rel(project, tsx), id.map(|i| format!("#{i}")).unwrap_or_default())
+}
+
+/// `rules` run on `project`'s compositions (`--composition` picks one), each where it applies, as `raea check` runs
+/// its own: what `raea notes check` runs a project's asks through (DR6).
+pub fn run(project: &Path, rules: &[Rule], args: &[String], whole: bool, host: &Host) -> R<Vec<raea_app_notes::check::Ran>> {
+ let mut out = Vec::new();
+ for (tsx, id) in compositions(project, args)? {
+ let mine: Vec<Rule> = rules.iter().filter(|r| applies(r, project, &tsx, id.as_deref())).cloned().collect();
+ let c = check_one(&tsx, id, &mine, args, whole, host)?;
+ out.push(raea_app_notes::check::Ran { of: named_as(project, &c.file, c.id.as_deref()), found: c.found, waits: c.waits, render: c.render, shots: c.shots, fps: c.fps });
+ }
+ Ok(out)
}
/// The frames the render joined (each with what it rendered, or says it waits), or None when it joined none.
@@ -270,7 +320,7 @@ pub fn check(args: &[String], host: &Host) -> R<(String, bool)> {
let here = if target.is_dir() { target.clone() } else { target.parent().filter(|p| !p.as_os_str().is_empty()).map_or_else(|| PathBuf::from("."), Path::to_path_buf) };
let here = here.canonicalize().map_err(|e| format!("{}: {e}", here.display()))?;
let project = record::up(&here, ".raea/project").unwrap_or(here);
- let (mut rules, unread) = rules(&project, taste_files(args), host);
+ let (mut rules, unread, notes) = rules(&project, taste_files(args), host);
if let Some(only) = flag(args, "--only") {
rules.retain(|r| r.id == only);
if rules.is_empty() {
@@ -279,20 +329,29 @@ pub fn check(args: &[String], host: &Host) -> R<(String, bool)> {
}
let mut all = Vec::new();
for (tsx, id) in compositions(&target, args)? {
- all.push(check_one(&tsx, id, &rules, args, host)?);
+ let mine: Vec<Rule> = rules.iter().filter(|r| applies(r, &project, &tsx, id.as_deref())).cloned().collect();
+ all.push(check_one(&tsx, id, &mine, args, false, host)?);
}
let stamp = raea_io_trace::utc(std::time::SystemTime::now()).1;
+ // what the notes' asks found, kept with what each has been through (DR6): an ask's first run that passes is refused
+ let ran: Vec<raea_app_notes::check::Ran> = all.iter().map(|c| raea_app_notes::check::Ran { of: named_as(&project, &c.file, c.id.as_deref()), found: c.found.clone(), waits: c.waits.clone(), render: None, shots: Vec::new(), fps: c.fps }).collect();
+ let mut kept = raea_app_notes::state::read(&project);
+ let (asks, _) = raea_app_notes::check::settle(&project, &notes, &rules, &ran, &stamp, &mut kept);
+ if !asks.is_empty() {
+ raea_app_notes::state::write(&project, &kept)?;
+ }
let mut bad = unread.iter().any(|f| f.level == Level::Error);
if args.iter().any(|a| a == "--json") {
let v: Vec<Value> = all.iter().map(|c| json!({"file": c.file, "composition": c.id, "findings": c.found, "waits": c.waits.iter().map(|(r, w)| json!({"rule": r, "for": w})).collect::<Vec<_>>()})).collect();
bad |= all.iter().any(|c| c.found.iter().any(|f| f.level == Level::Error));
- return Ok((serde_json::to_string_pretty(&json!({"unread": unread, "compositions": v})).unwrap_or_default(), bad));
+ return Ok((serde_json::to_string_pretty(&json!({"unread": unread, "compositions": v, "asks": asks})).unwrap_or_default(), bad));
}
let mut out: Vec<String> = unread.iter().map(Finding::line).collect();
let mut every = unread.clone();
for c in &all {
out.push(format!("raea check {}{}", c.file.display(), c.id.as_ref().map(|i| format!(" ({i})")).unwrap_or_default()));
- out.extend(c.found.iter().map(Finding::line));
+ // a note's ask's finding says which ask, as two asks can run one check
+ out.extend(c.found.iter().map(|f| if f.by.starts_with("note ") { format!("{} [{}]", f.line(), f.by) } else { f.line() }));
out.extend(c.waits.iter().map(|(r, w)| format!("waits {r}: needs {w}")));
// kept in its project's record (DR3), what raea findings and raea next read
if let Some(e) = record::keep("raea check", &c.file, None, &c.found, vec![], &stamp) {
@@ -301,6 +360,7 @@ pub fn check(args: &[String], host: &Host) -> R<(String, bool)> {
bad |= c.found.iter().any(|f| f.level == Level::Error);
every.extend(c.found.iter().cloned());
}
+ out.extend(asks.iter().map(|a| format!("raea check: note {a}")));
out.push(format!("raea check: {}", finding::count(&every)));
Ok((out.join("\n"), bad))
}
diff --git a/apps/notes/Cargo.toml b/apps/notes/Cargo.toml
index 50f7feb8..6926175f 100644
--- a/apps/notes/Cargo.toml
+++ b/apps/notes/Cargo.toml
@@ -4,12 +4,18 @@ version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
-description = "A person's notes on a project as files the work is held to (docs/direction.feature DR5): `raea notes take`, `ls` and `post`"
+description = "A person's notes on a project as files the work is held to (docs/direction.feature DR5, DR6): `raea notes take`, `check`, `ls` and `post`"
[dependencies]
# Note and Ask, the project found by its .raea/project, and the world a note is an entity in
raea-core-facts = { path = "../../core/facts" }
+# when a run of an ask's check was (UTC), as raea check stamps its record
+raea-io-trace = { path = "../../io/trace" }
+# what each ask has been through, kept as JSON (state.rs)
+serde = { version = "1", features = ["derive"] }
serde_json = "1"
+# the render a clip to sign is cut from, by its SHA-256 (check.rs)
+sha2 = "0.10"
[dev-dependencies]
tempfile = "3"
diff --git a/apps/notes/src/check.rs b/apps/notes/src/check.rs
new file mode 100644
index 00000000..1f22b2f1
--- /dev/null
+++ b/apps/notes/src/check.rs
@@ -0,0 +1,235 @@
+//! `raea notes check` (docs/direction.feature DR6): each ask's check run as a rule on the work as it stands, through
+//! `raea check`'s run (apps/direction, which the CLI lends). An ask's check must fail first: one that passes on its
+//! first run is refused, as it isn't measuring the ask, and the work may change only once it has failed. What each run
+//! found is kept (state.rs); `raea check` keeps it too, when it runs the notes' checks beside its rules. An ask the
+//! person signs gets its clip cut here, from its composition's newest render.
+
+use std::path::{Path, PathBuf};
+
+use raea_core_facts::{Finding, Level, record};
+/// A rule as `raea check` runs one: an ask's is one, run through the CLI's Runner.
+pub use raea_core_facts::Rule;
+
+use crate::state::{self, Clip, Failed, Run, State};
+use crate::{Eval, Kept, R, place, quoted, read};
+
+/// One composition's run: its file from the project (`#ID` after it where the file registers several), what the
+/// rules found and which waited and for what, its newest render, its shots (name, first frame, end) and its rate.
+pub struct Ran {
+ pub of: String,
+ pub found: Vec<Finding>,
+ pub waits: Vec<(String, String)>,
+ pub render: Option<Rendered>,
+ pub shots: Vec<(String, i64, Option<i64>)>,
+ pub fps: f64,
+}
+
+/// A composition's newest render: its file, whether the composition changed after it, and how many frames it drew.
+pub struct Rendered {
+ pub out: PathBuf,
+ pub stale: bool,
+ pub frames: i64,
+}
+
+/// Runs rules on a project's compositions as `raea check` runs its own (taking its --composition, --render and
+/// --no-render), every frame read when `whole` (a clip's shot is found in them).
+pub type Runner = fn(&Path, &[Rule], &[String], bool) -> R<Vec<Ran>>;
+
+/// An ask's rule's `by`, which its findings carry, so two asks that run one check are told apart.
+pub fn by(id: &str) -> String {
+ format!("note {id}")
+}
+
+/// Whether `of`, the composition an ask names (its file from the project, `#ID` after it where the file registers
+/// several), is the one a run names `named` (its file, and `#ID` when it has one): a file alone is any composition
+/// in it.
+pub fn is_of(of: &str, named: &str) -> bool {
+ let (file, id) = named.split_once('#').map_or((named, None), |(f, i)| (f, Some(i)));
+ match of.split_once('#') {
+ Some((f, i)) => f == file && id == Some(i),
+ None => of == file,
+ }
+}
+
+/// What ask `id`'s check found in a run.
+fn found_by<'a>(ran: &'a [Ran], id: &str) -> impl Iterator<Item = &'a Finding> {
+ let by = by(id);
+ ran.iter().flat_map(|r| &r.found).filter(move |f| f.by == by)
+}
+
+/// Each note's file number with the note, for those that read.
+fn numbered<'a>(project: &Path, notes: &'a [Kept]) -> Vec<(u32, &'a Kept, &'a raea_core_facts::Note)> {
+ notes.iter().filter_map(|k| Some((place(project, &project.join(&k.file))?.1, k, k.note.as_ref().ok()?))).collect()
+}
+
+/// The notes' asks that have a check, each as a rule: the ask's id (n3.2) and words, its check (a .ts check's path
+/// from the note's folder, as a controller's is from its own), its values, `by` the ask; and each note that can't be
+/// read, as a finding.
+pub fn rules(project: &Path, notes: &[Kept]) -> (Vec<Rule>, Vec<Finding>) {
+ let bad = notes.iter().filter_map(|k| k.note.as_ref().err().map(|e| Finding::new("note", Level::Error, format!("raea can't read it: {e}"), "raea notes").about(k.file.display().to_string(), None))).collect();
+ let mut out = Vec::new();
+ for (number, k, n) in numbered(project, notes) {
+ for (i, a) in n.asks.iter().enumerate() {
+ let Some(c) = &a.check else { continue };
+ let check = if c.ends_with(".ts") { project.join(k.file.parent().unwrap_or(Path::new(""))).join(c).display().to_string() } else { c.clone() };
+ let id = state::id(number, i + 1);
+ out.push(Rule { by: by(&id), id, text: a.text.clone(), check, values: a.values.clone().unwrap_or_default(), level: None, of: a.of.clone() });
+ }
+ }
+ (out, bad)
+}
+
+/// What a run of the notes' rules says of each ask whose rule was among `rules` (`--only` runs one), kept in `s`: a
+/// line for each, and whether one was refused (its first run passed).
+pub fn settle(project: &Path, notes: &[Kept], rules: &[Rule], ran: &[Ran], stamp: &str, s: &mut State) -> (Vec<String>, bool) {
+ let commit = record::commit(project, ".");
+ let (mut out, mut refused) = (Vec::new(), false);
+ for (number, k, n) in numbered(project, notes) {
+ for (i, a) in n.asks.iter().enumerate() {
+ let id = state::id(number, i + 1);
+ let Some(check) = a.check.as_ref().filter(|_| rules.iter().any(|r| r.id == id)) else { continue };
+ let found = found_by(ran, &id).count();
+ let waits = ran.iter().flat_map(|r| &r.waits).find(|(r, _)| *r == id).map(|(_, w)| w.clone());
+ let run = Run { at: stamp.into(), commit: commit.clone(), found, waits: waits.clone().filter(|_| found == 0) };
+ let kept = s.entry(id.clone()).or_default();
+ let first = kept.failed.as_ref().is_none_or(|f| !state::same_check(a, f));
+ let head = format!("{id} {}: {}", k.file.display(), quoted(&a.text, 70));
+ out.push(match (&run.waits, found, first) {
+ (Some(w), _, _) => format!("{head}: waits for {w}"),
+ (None, 0, true) => {
+ refused = true;
+ kept.refused = Some(run.clone());
+ format!("{head}: refused: its check passes on the work as it stands, so it isn't measuring the ask; write one that fails now, before the work changes")
+ }
+ (None, 0, false) => format!("{head}: passing"),
+ (None, n, true) => {
+ kept.failed = Some(Failed { check: check.clone(), values: a.values.clone().unwrap_or_default(), run: run.clone() });
+ kept.refused = None;
+ format!("{head}: fails on the work as it stands ({n} finding{}): its check measures the ask, and the work may change now", if n == 1 { "" } else { "s" })
+ }
+ (None, n, false) => format!("{head}: failing ({n} finding{})", if n == 1 { "" } else { "s" }),
+ });
+ kept.last = Some(run);
+ }
+ }
+ (out, refused)
+}
+
+/// A file's SHA-256.
+fn sha256(p: &Path) -> R<String> {
+ use sha2::{Digest, Sha256};
+ let mut f = std::fs::File::open(p).map_err(|e| format!("{}: {e}", p.display()))?;
+ let mut d = Sha256::new();
+ std::io::copy(&mut f, &mut d).map_err(|e| format!("{}: {e}", p.display()))?;
+ Ok(format!("{:x}", d.finalize()))
+}
+
+/// Frames `a` to `b` (the frame after its last) of `out` at `fps`, cut to `to` with ffmpeg.
+fn cut(out: &Path, [a, b]: [i64; 2], fps: f64, to: &Path) -> R<()> {
+ if let Some(d) = to.parent() {
+ std::fs::create_dir_all(d).map_err(|e| format!("{}: {e}", d.display()))?;
+ }
+ let (from, len) = (format!("{:.4}", a as f64 / fps), format!("{:.4}", (b - a) as f64 / fps));
+ let args = ["-hide_banner", "-loglevel", "error", "-y", "-ss", &from, "-i"];
+ let o = std::process::Command::new("ffmpeg").args(args).arg(out).args(["-t", &len, "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac"]).arg(to).output().map_err(|e| format!("ffmpeg: {e}"))?;
+ if !o.status.success() {
+ return Err(format!("ffmpeg: {}", String::from_utf8_lossy(&o.stderr).trim()));
+ }
+ Ok(())
+}
+
+/// Each ask the person signs, its clip cut from its composition's newest render (again only when the render or the
+/// frames changed), kept in `s`: a line for each.
+pub fn clips(project: &Path, notes: &[Kept], ran: &[Ran], s: &mut State) -> Vec<String> {
+ let mut out = Vec::new();
+ for (number, k, n) in numbered(project, notes) {
+ for (i, a) in n.asks.iter().enumerate() {
+ let Some(p) = a.proof.as_ref().filter(|p| p.sign) else { continue };
+ let id = state::id(number, i + 1);
+ let head = format!("{id} {}: its clip", k.file.display());
+ let comp = match &a.of {
+ Some(of) => ran.iter().find(|r| is_of(of, &r.of)),
+ None if ran.len() == 1 => ran.first(),
+ None => {
+ out.push(format!("{head}: which composition? the project has {}: name one in the ask's `of`", ran.iter().map(|r| r.of.as_str()).collect::<Vec<_>>().join(", ")));
+ continue;
+ }
+ };
+ let Some(r) = comp else {
+ out.push(format!("{head}: no composition {} was checked", a.of.as_deref().unwrap_or("")));
+ continue;
+ };
+ let Some(render) = &r.render else {
+ out.push(format!("{head} waits for a render of {}", r.of));
+ continue;
+ };
+ // a render the composition changed after isn't the work: nothing is cut from it, and the clip kept from it
+ // (what the person signed, if they did) is marked so, until it's rendered again
+ if render.stale {
+ if let Some(c) = s.get_mut(&id).and_then(|k| k.clip.as_mut()) {
+ c.stale = true;
+ }
+ out.push(format!("{head} waits for a render of {} as it stands: it changed after its newest render", r.of));
+ continue;
+ }
+ let frames = match (p.frames, &p.shot) {
+ (Some(f), _) => f,
+ (None, Some(shot)) => match r.shots.iter().find(|(name, ..)| name == shot) {
+ Some((_, from, to)) => [*from, to.unwrap_or(render.frames)],
+ None => {
+ out.push(format!("{head}: {} has no shot named {shot}", r.of));
+ continue;
+ }
+ },
+ (None, None) => [0, render.frames],
+ };
+ let hash = match sha256(&render.out) {
+ Ok(h) => h,
+ Err(e) => {
+ out.push(format!("{head}: {e}"));
+ continue;
+ }
+ };
+ let kept = s.entry(id.clone()).or_default();
+ let file = project.join(".raea/notes-clips").join(format!("{id}.mp4"));
+ let same = kept.clip.as_ref().is_some_and(|c| c.render == hash && c.frames == frames && c.file.is_file());
+ if !same {
+ if let Err(e) = cut(&render.out, frames, r.fps, &file) {
+ out.push(format!("{head}: {e}"));
+ continue;
+ }
+ }
+ kept.clip = Some(Clip { file: file.clone(), of: r.of.clone(), render: hash, frames, stale: false });
+ out.push(format!("{head}, frames {}-{} of {}, {} from its newest render", frames[0], frames[1] - 1, r.of, if same { "kept" } else { "cut" }));
+ }
+ }
+ out
+}
+
+/// `raea notes check`: each ask's check on the work as it stands, and each clip to sign cut; 1 when an ask was
+/// refused or a note can't be read.
+pub(crate) fn check(project: &Path, args: &[String], eval: Eval, run: Runner) -> R<(String, i32)> {
+ let notes = read(project, eval);
+ let (rules, bad) = rules(project, &notes);
+ let signs = notes.iter().filter_map(|k| k.note.as_ref().ok()).flat_map(|n| &n.asks).any(|a| a.proof.as_ref().is_some_and(|p| p.sign));
+ let mut out: Vec<String> = bad.iter().map(Finding::line).collect();
+ if rules.is_empty() && !signs {
+ out.push("no ask has a check or a clip to sign yet: restate the notes' asks with one each (raea notes ls)".into());
+ return Ok((out.join("\n"), i32::from(!bad.is_empty())));
+ }
+ let ran = run(project, &rules, args, signs)?;
+ let stamp = raea_io_trace::utc(std::time::SystemTime::now()).1;
+ let mut s = state::read(project);
+ let (lines, refused) = settle(project, &notes, &rules, &ran, &stamp, &mut s);
+ // each ask's line, then what its check found
+ for l in lines {
+ let id = l.split(' ').next().unwrap_or("").to_string();
+ out.push(l);
+ out.extend(found_by(&ran, &id).map(|f| format!(" {}", f.line())));
+ }
+ out.extend(clips(project, &notes, &ran, &mut s));
+ state::write(project, &s)?;
+ let tally = crate::tally(project, &notes, &s);
+ out.push(tally);
+ Ok((out.join("\n"), i32::from(refused || !bad.is_empty())))
+}
diff --git a/apps/notes/src/lib.rs b/apps/notes/src/lib.rs
index db613b8d..07f749e0 100644
--- a/apps/notes/src/lib.rs
+++ b/apps/notes/src/lib.rs
@@ -1,9 +1,11 @@
-//! A person's notes on a project (docs/direction.feature DR5). `raea notes take` writes each note the person sends
-//! from the raea app (an edit comment with its pin, or a note on an item) or says in a session to a file,
+//! A person's notes on a project (docs/direction.feature DR5, DR6). `raea notes take` writes each note the person
+//! sends from the raea app (an edit comment with its pin, or a note on an item) or says in a session to a file,
//! notes/<round>/<id>.ts, with their words verbatim and no asks. The agent restates each as its asks before anything
-//! in the work changes, and `raea notes ls` says where each stands and what its restatement still owes. `raea notes
-//! post` shows the asks on the person's comments in the app, and their corrections come back with the next take. In a
-//! project's world each note is an entity with a Note, for the checks that hold it (DR6).
+//! in the work changes, each with a check, or a clip for the person to sign. `raea notes check` runs each ask's check
+//! on the work as it stands, which must fail first, and `raea notes ls` says where each note and ask stands and what
+//! its restatement still owes. `raea notes post` shows the asks and where they stand on the person's comments in the
+//! app, and their corrections and signs come back with the next take. In a project's world each note is an entity
+//! with a Note.
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
@@ -11,10 +13,12 @@ use std::path::{Path, PathBuf};
use raea_core_facts::{Facts, Note, record};
use serde_json::json;
+pub mod check;
mod post;
+pub mod state;
mod take;
-pub const USAGE: &str = "raea notes take [PROJECT] [--inbox NAME] [--said WORDS]... | raea notes ls [PROJECT] [--json] | raea notes post [PROJECT] (a person's notes as files the work is held to: take writes each note sent from the raea app or said in a session to notes/ROUND/ID.ts, the words verbatim, to be restated as asks before anything changes, and writes in each correction the person made to a restatement; ls says where each note stands, to restate or to check, and what its restatement still owes; post shows each restated note's asks on its comment in the raea app, for the person to correct)";
+pub const USAGE: &str = "raea notes take [PROJECT] [--inbox NAME] [--said WORDS]... | raea notes check [PROJECT] [--composition ID] [--render OUT | --no-render] | raea notes ls [PROJECT] [--json] | raea notes post [PROJECT] (a person's notes as files the work is held to: take writes each note sent from the raea app or said in a session to notes/ROUND/ID.ts, the words verbatim, to be restated as asks before anything changes, and writes in each correction and sign the person sent back; check runs each ask's check on the work as it stands, which must fail before the work changes (a check that passes first is refused), and cuts each clip the person is to sign from the newest render; ls says where each note and ask stands (to restate, to check, failing, to sign, passing, signed) and what its restatement still owes; post shows each note's asks and where they stand on its comment in the raea app, and each clip to sign)";
/// Evaluates a .ts file's default export to its JSON (the CLI's spec host).
pub type Eval = fn(&Path) -> Result<String, String>;
@@ -22,7 +26,7 @@ pub type Eval = fn(&Path) -> Result<String, String>;
pub(crate) type R<T> = Result<T, String>;
/// The flags `raea notes` takes, and whether each takes a value.
-const FLAGS: [(&str, bool); 3] = [("--inbox", true), ("--said", true), ("--json", false)];
+const FLAGS: [(&str, bool); 6] = [("--inbox", true), ("--said", true), ("--json", false), ("--composition", true), ("--render", true), ("--no-render", false)];
/// One note file: where it is in the project, and the note, or why it can't be read.
pub struct Kept {
@@ -30,9 +34,10 @@ pub struct Kept {
pub note: R<Note>,
}
-/// `raea notes VERB ...`, printed; its exit code (1: a note that can't be read, 2: the command was wrong).
-pub fn cli(args: &[String], eval: Eval) -> i32 {
- match run(args, eval) {
+/// `raea notes VERB ...`, printed; its exit code (1: a note that can't be read, or an ask's check refused; 2: the
+/// command was wrong). `run` is `raea check`'s run of rules on the project's compositions (apps/direction).
+pub fn cli(args: &[String], eval: Eval, run: check::Runner) -> i32 {
+ match go(args, eval, run) {
Ok((out, code)) => {
println!("{out}");
code
@@ -44,7 +49,7 @@ pub fn cli(args: &[String], eval: Eval) -> i32 {
}
}
-fn run(args: &[String], eval: Eval) -> R<(String, i32)> {
+fn go(args: &[String], eval: Eval, run: check::Runner) -> R<(String, i32)> {
let Some(verb) = args.first().map(String::as_str).filter(|v| !matches!(*v, "--help" | "-h" | "help")) else {
return Ok((USAGE.into(), 0));
};
@@ -67,6 +72,7 @@ fn run(args: &[String], eval: Eval) -> R<(String, i32)> {
match verb {
"take" => take::take(&project, rest).map(|s| (s, 0)),
"ls" => Ok(ls(&project, rest.iter().any(|a| a == "--json"), eval)),
+ "check" => check::check(&project, rest, eval, run),
"post" => Ok(post::post(&project, eval, post::run_raea)),
v => Err(format!("no verb {v}\n{USAGE}")),
}
@@ -113,16 +119,38 @@ pub(crate) fn quoted(words: &str, n: usize) -> String {
if line.chars().count() > n { format!("\"{}…\"", line.chars().take(n).collect::<String>().trim_end()) } else { format!("\"{line}\"") }
}
-/// `raea notes ls`: each note with where it stands, its asks and what its restatement still owes; 1 when a note
-/// can't be read.
+/// Each note's number (its file's: n7 is 7), where it stands and each of its asks'.
+fn standings(project: &Path, n: &Note, file: &Path, s: &state::State) -> (u32, state::Standing, Vec<state::Standing>) {
+ let number = place(project, &project.join(file)).map_or(0, |p| p.1);
+ let (note, asks) = state::of_note(n, number, s);
+ (number, note, asks)
+}
+
+/// How many notes stand where: "5 notes: 2 failing, 1 to restate".
+pub(crate) fn tally(project: &Path, notes: &[Kept], s: &state::State) -> String {
+ let mut t: BTreeMap<&str, usize> = BTreeMap::new();
+ for k in notes {
+ *t.entry(k.note.as_ref().map_or("can't be read", |n| standings(project, n, &k.file, s).1.word())).or_default() += 1;
+ }
+ let counts: Vec<String> = t.iter().map(|(s, c)| format!("{c} {s}")).collect();
+ format!("{} note{}: {}", notes.len(), if notes.len() == 1 { "" } else { "s" }, counts.join(", "))
+}
+
+/// `raea notes ls`: each note with where it stands, each ask with its id and where it stands, and what its
+/// restatement still owes; 1 when a note can't be read.
fn ls(project: &Path, as_json: bool, eval: Eval) -> (String, i32) {
let notes = read(project, eval);
+ let s = state::read(project);
let code = i32::from(notes.iter().any(|k| k.note.is_err()));
if as_json {
let v: Vec<_> = notes
.iter()
.map(|k| match &k.note {
- Ok(n) => json!({ "file": k.file, "note": n, "state": n.state(), "flags": n.flags() }),
+ Ok(n) => {
+ let (number, note, asks) = standings(project, n, &k.file, &s);
+ let each: Vec<_> = asks.iter().enumerate().map(|(i, a)| json!({ "id": state::id(number, i + 1), "state": a.word(), "says": a.said() })).collect();
+ json!({ "file": k.file, "note": n, "state": note.word(), "asks": each, "flags": n.flags() })
+ }
Err(e) => json!({ "file": k.file, "error": e }),
})
.collect();
@@ -132,26 +160,25 @@ fn ls(project: &Path, as_json: bool, eval: Eval) -> (String, i32) {
return ("no notes yet: `raea notes take` writes each one the person sends from the raea app or says".into(), 0);
}
let mut out = Vec::new();
- let mut tally: BTreeMap<&str, usize> = BTreeMap::new();
+ let mut restate = false;
for k in &notes {
let file = k.file.display();
let Ok(n) = &k.note else {
out.push(format!("{file}: can't be read: {}", k.note.as_ref().err().map_or("", String::as_str)));
- *tally.entry("can't be read").or_default() += 1;
continue;
};
- *tally.entry(n.state()).or_default() += 1;
- out.push(format!("{file}: round {}, {}: {}", n.round, n.state(), quoted(n.words.first().map_or("", String::as_str), 90)));
- for a in &n.asks {
+ let (number, note, asks) = standings(project, n, &k.file, &s);
+ restate |= note == state::Standing::ToRestate;
+ out.push(format!("{file}: round {}, {}: {}", n.round, note.word(), quoted(n.words.first().map_or("", String::as_str), 90)));
+ for (i, (a, st)) in n.asks.iter().zip(&asks).enumerate() {
let medium = a.medium.as_deref().map(|m| format!(" [{m}]")).unwrap_or_default();
let not = if a.not.is_empty() { String::new() } else { format!("; not: {}", a.not.join(", ")) };
- out.push(format!(" - {}{medium}{not}", a.text));
+ out.push(format!(" {} {}{medium}{not}: {}", state::id(number, i + 1), a.text, st.said()));
}
out.extend(n.flags().into_iter().map(|f| format!(" ! {f}")));
}
- let counts: Vec<String> = tally.iter().map(|(s, c)| format!("{c} {s}")).collect();
- out.push(format!("{} note{}: {}", notes.len(), if notes.len() == 1 { "" } else { "s" }, counts.join(", ")));
- if tally.contains_key("to restate") {
+ out.push(tally(project, &notes, &s));
+ if restate {
out.push(take::RESTATE.into());
}
(out.join("\n"), code)
diff --git a/apps/notes/src/post.rs b/apps/notes/src/post.rs
index ad2b5806..b5869209 100644
--- a/apps/notes/src/post.rs
+++ b/apps/notes/src/post.rs
@@ -1,14 +1,18 @@
-//! `raea notes post`: each restated note sent from the raea app gets its asks shown back on its comment (DR5), through
-//! `raea show --on ITEM --working COMMENT --ask TEXT...`, before the work starts. The person reads them there and can
-//! correct one in a word; `raea notes take` writes their correction into the note, which is then restated again.
+//! `raea notes post`: each note sent from the raea app gets where it stands shown on its comment (DR5, DR6), through
+//! `raea show --on ITEM --working COMMENT`: its asks once restated (`--ask TEXT...`), for the person to correct one in
+//! a word, which `raea notes take` writes into the note to be restated again; the note's state for the comment's
+//! badge and each ask's (`--status S --states S1,S2`: to restate, to check, failing, to sign, passing, signed); and
+//! each clip the person is to sign, under its ask (`--sign N --clip FILE --render HASH`). "done" is never the agent's:
+//! a note closes when the person retires it.
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
-use crate::{Eval, R, read};
+use crate::state::{self, Standing};
+use crate::{Eval, R, place, read};
-/// What was last shown for each note, by where it came from (`.raea/notes-shown.json`): a note shown with these asks
-/// already isn't shown again, so a comment the agent has since settled isn't marked working again.
+/// What was last shown for each note, by where it came from (`.raea/notes-shown.json`): its asks, its states and its
+/// clips. A note shown so already isn't shown again, so a comment isn't marked working again for nothing.
fn shown_at(project: &Path) -> PathBuf {
project.join(".raea/notes-shown.json")
}
@@ -44,10 +48,14 @@ pub(crate) fn comment_of(from: &str) -> Option<(&str, &str)> {
(comment.starts_with("cm-") && it.next().is_none()).then_some((item, comment))
}
-/// The arguments that show a note's asks on its comment.
-pub(crate) fn args(item: &str, comment: &str, asks: &[&str]) -> Vec<String> {
+/// The arguments that show a note on its comment: its asks (none while it's to restate), its state and each ask's.
+pub(crate) fn args(item: &str, comment: &str, asks: &[&str], status: &str, states: &[&str]) -> Vec<String> {
let mut a: Vec<String> = ["show", "--on", item, "--working", comment].map(String::from).to_vec();
a.extend(asks.iter().flat_map(|t| ["--ask".to_string(), t.to_string()]));
+ a.extend(["--status".to_string(), status.to_string()]);
+ if !states.is_empty() {
+ a.extend(["--states".to_string(), states.join(",")]);
+ }
a
}
@@ -57,6 +65,7 @@ pub(crate) fn post(project: &Path, eval: Eval, run: Run) -> (String, i32) {
let mut code = 0;
let mut shown: BTreeMap<String, Vec<String>> = std::fs::read_to_string(shown_at(project)).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default();
let before = shown.clone();
+ let kept = state::read(project);
for k in read(project, eval) {
let file = k.file.display().to_string();
let n = match k.note {
@@ -67,26 +76,49 @@ pub(crate) fn post(project: &Path, eval: Eval, run: Run) -> (String, i32) {
continue;
}
};
- let owed = n.flags();
let Some((item, comment)) = comment_of(&n.from) else {
if n.from.starts_with("app ") {
out.push(format!("{file}: a note on its item as a whole has no comment to show its asks on: say them to the person"));
}
continue;
};
- if n.state() == "to restate" || !owed.is_empty() {
- out.push(format!("{file}: not posted: {}", if owed.is_empty() { "it's still to restate".to_string() } else { format!("its restatement still owes: {}", owed.join("; ")) }));
- continue;
- }
- let asks: Vec<&str> = n.asks.iter().map(|a| a.text.as_str()).collect();
- if shown.get(&n.from).is_some_and(|s| s.iter().eq(asks.iter().copied())) {
- out.push(format!("{file}: its asks are shown on {comment} of {item} already"));
+ let number = place(project, &project.join(&k.file)).map_or(0, |p| p.1);
+ let owed = n.flags();
+ let (standing, each) = state::of_note(&n, number, &kept);
+ // a restatement that still owes something isn't shown: the comment reads "to restate" until it's whole
+ let whole = n.state() != "to restate" && owed.is_empty();
+ let asks: Vec<&str> = if whole { n.asks.iter().map(|a| a.text.as_str()).collect() } else { Vec::new() };
+ let status = if whole { standing.word() } else { "to restate" };
+ let states: Vec<&str> = if whole { each.iter().map(Standing::word).collect() } else { Vec::new() };
+ // each clip the person is to sign, under its ask: (its number, file, render)
+ let clips: Vec<(usize, String, String)> = if whole {
+ each.iter().enumerate().filter(|(_, s)| matches!(s, Standing::ToSign(_))).filter_map(|(i, _)| {
+ let c = kept.get(&state::id(number, i + 1))?.clip.as_ref().filter(|c| !c.stale)?;
+ Some((i + 1, c.file.display().to_string(), c.render.clone()))
+ }).collect()
+ } else {
+ Vec::new()
+ };
+ let mut said: Vec<String> = asks.iter().map(|a| a.to_string()).collect();
+ said.push(format!("status {status} {}", states.join(",")));
+ said.extend(clips.iter().map(|(i, _, h)| format!("clip {i} {h}")));
+ if shown.get(&n.from) == Some(&said) {
+ out.push(format!("{file}: shown on {comment} of {item} as it stands already ({status})"));
continue;
}
- match run(&args(item, comment, &asks)) {
- Ok(_) => {
- out.push(format!("{file}: its {} ask{} shown on {comment} of {item}, where the person can correct one", asks.len(), if asks.len() == 1 { "" } else { "s" }));
- shown.insert(n.from.clone(), asks.iter().map(|a| a.to_string()).collect());
+ let mut calls = vec![args(item, comment, &asks, status, &states)];
+ calls.extend(clips.iter().map(|(i, f, h)| ["show", "--on", item, "--working", comment, "--sign", &i.to_string(), "--clip", f, "--render", h].map(String::from).to_vec()));
+ match calls.iter().try_for_each(|a| run(a).map(|_| ())) {
+ Ok(()) => {
+ let what = match (asks.len(), whole) {
+ (_, false) if owed.is_empty() => "to restate".to_string(),
+ (_, false) => format!("to restate: its restatement still owes: {}", owed.join("; ")),
+ (1, true) => format!("its ask, {status}"),
+ (n, true) => format!("its {n} asks, {status}"),
+ };
+ let signs = if clips.is_empty() { String::new() } else { format!(", with {} clip{} to sign", clips.len(), if clips.len() == 1 { "" } else { "s" }) };
+ out.push(format!("{file}: shown on {comment} of {item}: {what}{signs}"));
+ shown.insert(n.from.clone(), said);
}
Err(e) => {
out.push(format!("{file}: not posted: {e}"));
diff --git a/apps/notes/src/state.rs b/apps/notes/src/state.rs
new file mode 100644
index 00000000..5146afde
--- /dev/null
+++ b/apps/notes/src/state.rs
@@ -0,0 +1,191 @@
+//! What each ask has been through (docs/direction.feature DR6), kept in the project's .raea/notes-checks.json by its
+//! id (n3.2: note 3's second ask): its check and values as they first failed on the work, the run before that if it
+//! passed (refused: it wasn't measuring the ask), its last run, the clip cut for the person to sign and their sign.
+//! From these and the note, each ask reads to check, failing, to sign, passing or signed, and the note its worst.
+
+use std::collections::BTreeMap;
+use std::path::{Path, PathBuf};
+
+use raea_core_facts::{Ask, Note};
+use serde::{Deserialize, Serialize};
+use serde_json::{Map, Value};
+
+use crate::R;
+
+/// A run of an ask's check: when (UTC), the project's commit ("+" when not all of it was committed), what it found,
+/// and what it waited for instead, when it did.
+#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
+pub struct Run {
+ pub at: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub commit: Option<String>,
+ pub found: usize,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub waits: Option<String>,
+}
+
+/// An ask's check as it first failed: the check, its values, and that run.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Failed {
+ pub check: String,
+ #[serde(default, skip_serializing_if = "Map::is_empty")]
+ pub values: Map<String, Value>,
+ pub run: Run,
+}
+
+/// The clip cut for an ask the person signs: its file, the composition, the render it was cut from (its SHA-256),
+/// the frames, and whether the composition changed after that render.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Clip {
+ pub file: PathBuf,
+ pub of: String,
+ pub render: String,
+ pub frames: [i64; 2],
+ #[serde(default)]
+ pub stale: bool,
+}
+
+/// The person's sign on a clip: their name (none when the app had no account to name), the render they watched, and
+/// when.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Sign {
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub name: Option<String>,
+ pub render: String,
+ pub at: String,
+}
+
+/// What one ask has been through.
+#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
+pub struct Kept {
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub failed: Option<Failed>,
+ /// its check's first run, when it passed: refused, as it wasn't measuring the ask
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub refused: Option<Run>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub last: Option<Run>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub clip: Option<Clip>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub signed: Option<Sign>,
+}
+
+/// Every ask's, by its id.
+pub type State = BTreeMap<String, Kept>;
+
+fn path(project: &Path) -> PathBuf {
+ project.join(".raea/notes-checks.json")
+}
+
+pub fn read(project: &Path) -> State {
+ std::fs::read_to_string(path(project)).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default()
+}
+
+pub fn write(project: &Path, s: &State) -> R<()> {
+ let f = path(project);
+ if let Some(d) = f.parent() {
+ std::fs::create_dir_all(d).map_err(|e| format!("{}: {e}", d.display()))?;
+ }
+ let t = serde_json::to_string_pretty(s).map_err(|e| e.to_string())?;
+ std::fs::write(&f, t + "\n").map_err(|e| format!("{}: {e}", f.display()))
+}
+
+/// An ask's id: the note's number and the ask's (1 is the first).
+pub fn id(note: u32, ask: usize) -> String {
+ format!("n{note}.{ask}")
+}
+
+/// Where an ask stands, the word the app's badge shows, and why when that isn't plain.
+#[derive(Debug, Clone, PartialEq)]
+pub enum Standing {
+ ToRestate,
+ ToCheck(String),
+ Failing(usize),
+ ToSign(String),
+ Passing,
+ Signed(Option<String>),
+}
+
+impl Standing {
+ pub fn word(&self) -> &'static str {
+ match self {
+ Standing::ToRestate => "to restate",
+ Standing::ToCheck(_) => "to check",
+ Standing::Failing(_) => "failing",
+ Standing::ToSign(_) => "to sign",
+ Standing::Passing => "passing",
+ Standing::Signed(_) => "signed",
+ }
+ }
+
+ /// The word, and why or by whom.
+ pub fn said(&self) -> String {
+ match self {
+ Standing::ToCheck(why) | Standing::ToSign(why) => format!("{}: {why}", self.word()),
+ Standing::Failing(n) => format!("failing ({n} finding{})", if *n == 1 { "" } else { "s" }),
+ Standing::Signed(Some(name)) => format!("signed by {name}"),
+ Standing::Signed(None) => "signed (unnamed: the app had no account)".into(),
+ _ => self.word().into(),
+ }
+ }
+
+ /// How far it is from settled: the note reads its asks' worst.
+ fn rank(&self) -> u8 {
+ match self {
+ Standing::ToRestate => 5,
+ Standing::ToCheck(_) => 4,
+ Standing::Failing(_) => 3,
+ Standing::ToSign(_) => 2,
+ Standing::Passing => 1,
+ Standing::Signed(_) => 0,
+ }
+ }
+}
+
+/// Whether the check an ask names now is the one that failed first (its check and its values).
+pub fn same_check(a: &Ask, f: &Failed) -> bool {
+ a.check.as_deref() == Some(f.check.as_str()) && a.values.clone().unwrap_or_default() == f.values
+}
+
+/// Where an ask stands, from the ask and what it has been through.
+pub fn standing(a: &Ask, k: Option<&Kept>) -> Standing {
+ let sign = a.proof.as_ref().is_some_and(|p| p.sign);
+ if a.check.is_none() && !sign {
+ return Standing::ToCheck("no check, and no clip to sign".into());
+ }
+ if a.check.is_some() {
+ let failed = k.and_then(|k| k.failed.as_ref());
+ match (failed, k.and_then(|k| k.last.as_ref())) {
+ (Some(f), _) if !same_check(a, f) => return Standing::ToCheck("its check changed since it failed: show the new one failing (raea notes check)".into()),
+ (Some(_), Some(Run { waits: Some(w), .. })) => return Standing::ToCheck(format!("its check waits for {w}")),
+ (Some(_), Some(r)) if r.found > 0 => return Standing::Failing(r.found),
+ (Some(_), _) => {}
+ (None, _) if k.and_then(|k| k.refused.as_ref()).is_some() => return Standing::ToCheck("its check passed on its first run, so it isn't measuring the ask: write one that fails on the work as it stands".into()),
+ (None, Some(Run { waits: Some(w), .. })) => return Standing::ToCheck(format!("its check waits for {w}")),
+ (None, _) => return Standing::ToCheck("its check isn't shown failing on the work yet (raea notes check)".into()),
+ }
+ if !sign {
+ return Standing::Passing;
+ }
+ }
+ let clip = k.and_then(|k| k.clip.as_ref());
+ match (clip, k.and_then(|k| k.signed.as_ref())) {
+ // the agent's move until there's a clip of the work as it stands: to check, not the person's to sign
+ (None, _) => Standing::ToCheck("no clip yet: render, and raea notes check cuts it from the newest render".into()),
+ (Some(c), _) if c.stale => Standing::ToCheck(format!("{} changed after the render its clip is cut from: render it again", c.of)),
+ (Some(c), Some(s)) if s.render == c.render => Standing::Signed(s.name.clone()),
+ (Some(_), Some(s)) => Standing::ToSign(format!("{} signed an older render; its clip is new", s.name.as_deref().unwrap_or("the person"))),
+ (Some(_), None) => Standing::ToSign("its clip waits on the person (raea notes post shows it)".into()),
+ }
+}
+
+/// Each ask of a note with where it stands, and the note's: to restate, else its asks' worst.
+pub fn of_note(n: &Note, number: u32, s: &State) -> (Standing, Vec<Standing>) {
+ let asks: Vec<Standing> = n.asks.iter().enumerate().map(|(i, a)| standing(a, s.get(&id(number, i + 1)))).collect();
+ if n.state() == "to restate" {
+ return (Standing::ToRestate, asks);
+ }
+ let worst = asks.iter().max_by_key(|a| a.rank()).cloned().unwrap_or(Standing::ToRestate);
+ (worst, asks)
+}
diff --git a/apps/notes/src/take.rs b/apps/notes/src/take.rs
index 050eb981..f09ab777 100644
--- a/apps/notes/src/take.rs
+++ b/apps/notes/src/take.rs
@@ -1,13 +1,16 @@
//! `raea notes take`: what the person sent from the raea app to this project (the inbox lines it wrote: each edit
//! comment of a send, with its pin, or a note on an item) and what they said in a session (`--said`), each written
//! as a note file with their words verbatim and no asks, all in one new round. A note already taken isn't taken again.
+//! What the person sends back on a restated note comes the same way: a correction, written into its note (DR5), and
+//! a sign on an ask's clip, kept with what that ask has been through (state.rs, DR6).
+use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use raea_core_facts::{Pin, note};
use serde_json::Value;
-use crate::{R, files, place, quoted, values};
+use crate::{R, files, place, quoted, state, values};
/// What a note asks of the agent before anything changes, said where notes are taken and listed.
pub(crate) const RESTATE: &str = "restate each note before changing anything: one ask for each thing it asks for, the medium where its words name one (2D, 3D, flat, extruded, real, modelled, voxel), what it is about, and what it doesn't ask for (`not`), so a change keeps the rest";
@@ -115,6 +118,65 @@ pub(crate) fn corrected(t: &str, c: &Correction) -> Option<String> {
Some(out)
}
+/// The person's sign on an ask's clip in the app: the note (by where it came from), the ask (1 is the first), the
+/// render they watched (its SHA-256), their name (none when the app had no account) and when.
+pub(crate) struct Signed {
+ pub from: String,
+ pub ask: u32,
+ pub render: String,
+ pub name: Option<String>,
+ pub when: String,
+}
+
+/// The sign in one inbox line sent to `project`, if it is one.
+pub(crate) fn sign_of(v: &Value, project: &str) -> Option<Signed> {
+ if v["project"].as_str() != Some(project) || v["kind"].as_str() != Some("sign") {
+ return None;
+ }
+ let ask = v["ask"].as_u64().and_then(|n| u32::try_from(n).ok()).filter(|n| *n > 0)?;
+ let name = v["name"].as_str().map(str::trim).filter(|n| !n.is_empty()).map(String::from);
+ Some(Signed { from: format!("app {} {}", v["item"].as_str()?, v["comment"].as_str()?), ask, render: v["render"].as_str()?.into(), name, when: v["when"].as_str().unwrap_or("").into() })
+}
+
+/// Each ask's last sign kept with what it has been through (state.rs), once: what was signed, or why it wasn't.
+fn sign(project: &Path, kept: &[PathBuf], signs: Vec<Signed>) -> R<Vec<String>> {
+ // the last sign of each ask: a newer render's sign replaces an older one's
+ let mut last: BTreeMap<(String, u32), Signed> = BTreeMap::new();
+ for g in signs {
+ last.insert((g.from.clone(), g.ask), g);
+ }
+ let mut s = state::read(project);
+ let before = s.clone();
+ let mut out = Vec::new();
+ for g in last.into_values() {
+ let from = format!("from: {}", serde_json::to_string(&g.from).unwrap_or_default());
+ // the note whose file says it came from this comment
+ let note = kept.iter().find_map(|f| {
+ let said = std::fs::read_to_string(f).ok()?;
+ if said.contains(&from) { Some((f, place(project, f)?)) } else { None }
+ });
+ let Some((f, (_, number))) = note else {
+ out.push(format!("a sign for a note not in notes/ ({}, ask {})", g.from, g.ask));
+ continue;
+ };
+ let k = s.entry(state::id(number, g.ask as usize)).or_default();
+ let signed = state::Sign { name: g.name.clone(), render: g.render.clone(), at: g.when.clone() };
+ if k.signed.as_ref() == Some(&signed) {
+ continue;
+ }
+ let now = k.clip.as_ref().is_some_and(|c| c.render == g.render);
+ k.signed = Some(signed);
+ let rel = f.strip_prefix(project).unwrap_or(f).display();
+ let by = g.name.as_deref().unwrap_or("the person (unnamed: the app had no account)");
+ let short: String = g.render.chars().take(12).collect();
+ out.push(format!("{rel}: ask {} signed by {by}, on the render {short}…{}", g.ask, if now { "" } else { ", not the one its clip is cut from now: it is to sign again" }));
+ }
+ if s != before {
+ state::write(project, &s)?;
+ }
+ Ok(out)
+}
+
/// Each correction applied to its note's file, once: what was done, or why it wasn't.
fn apply(project: &Path, kept: &[PathBuf], corrections: &[Correction]) -> R<Vec<String>> {
let s = |v: &str| serde_json::to_string(v).unwrap_or_default();
@@ -178,12 +240,13 @@ pub(crate) fn take_from(dir: &Path, project: &Path, args: &[String]) -> R<String
v
}
};
- let (mut new, mut fixes): (Vec<New>, Vec<Correction>) = (Vec::new(), Vec::new());
+ let (mut new, mut fixes, mut signs): (Vec<New>, Vec<Correction>, Vec<Signed>) = (Vec::new(), Vec::new(), Vec::new());
for f in &inboxes {
let text = std::fs::read_to_string(f).map_err(|e| format!("{}: {e}", f.display()))?;
for v in text.lines().filter_map(|l| serde_json::from_str::<Value>(l).ok()) {
new.extend(of_line(&v, &name));
fixes.extend(correction_of(&v, &name));
+ signs.extend(sign_of(&v, &name));
}
}
new.extend(values(args, "--said").into_iter().map(str::trim).filter(|w| !w.is_empty()).map(|w| New { words: w.into(), from: "session".into(), pin: None, at: None }));
@@ -218,6 +281,7 @@ pub(crate) fn take_from(dir: &Path, project: &Path, args: &[String]) -> R<String
}
// corrections last, so one for a note taken just now finds its file
out.extend(apply(project, &files(project), &fixes)?);
+ out.extend(sign(project, &files(project), signs)?);
if out.is_empty() {
return Ok(format!("no new notes for {name}: what was sent to it from the raea app ({} inbox file{}) or said is in notes/ already (raea notes ls)", inboxes.len(), if inboxes.len() == 1 { "" } else { "s" }));
}
diff --git a/apps/notes/src/tests.rs b/apps/notes/src/tests.rs
index 32222aaa..f3c2f48d 100644
--- a/apps/notes/src/tests.rs
+++ b/apps/notes/src/tests.rs
@@ -1,5 +1,7 @@
use std::path::Path;
+use raea_core_facts::Finding;
+
use super::*;
use crate::take::take_from;
@@ -77,7 +79,7 @@ fn ls_says_where_each_note_stands_and_what_it_owes() {
std::fs::write(p.join("notes/1/n9.ts"), "export default 3;").unwrap();
let (out, code) = ls(&p, false, eval);
assert_eq!(code, 1, "a note that can't be read");
- assert!(out.contains("notes/1/n1.ts: round 1, to check: ") && out.contains(" - the lyric is flat type behind the singer"), "{out}");
+ assert!(out.contains("notes/1/n1.ts: round 1, to check: ") && out.contains(" n1.1 the lyric is flat type behind the singer: to check: no check, and no clip to sign"), "{out}");
assert!(out.contains(" ! one ask from 2 sentences: read it again for what else it asks"), "{out}");
assert!(out.contains(" ! its words say 2D and no ask says it, as its medium or in its `not`") && out.contains(" ! its words say 3D and no ask says it"), "{out}");
assert!(out.contains("notes/1/n9.ts: can't be read"), "{out}");
@@ -157,49 +159,193 @@ fn refused(_: &[String]) -> R<String> {
Err("the raea app isn't running".into())
}
+
+fn calls() -> Vec<Vec<String>> {
+ RAN.with(|r| r.borrow().clone())
+}
+
#[test]
-fn post_shows_each_restated_note_on_its_comment_once_and_none_still_owing() {
+fn post_shows_each_note_on_its_comment_as_it_stands_once() {
let (_tmp, p, inbox) = project();
let whole = r#"{"item":"i-show-2","project":"shop","kind":"note","text":"hold the end card longer","when":"2026-11-10T11:00:00Z"}"#;
std::fs::write(inbox.join("a.jsonl"), format!("{SENT}\n{whole}")).unwrap();
take_from(&inbox, &p, &[]).unwrap();
+ // taken and not restated: each comment's badge reads "to restate"
let (out, code) = post::post(&p, eval, refused);
- assert_eq!(code, 0, "nothing restated, nothing run: {out}");
- assert!(out.contains("notes/1/n1.ts: not posted: it's still to restate"), "{out}");
+ assert_eq!((code, out.contains("notes/1/n1.ts: not posted: the raea app isn't running")), (1, true), "{out}");
assert!(out.contains("notes/1/n3.ts: a note on its item as a whole has no comment to show its asks on"), "{out}");
+ let (out, code) = post::post(&p, eval, ran);
+ assert_eq!(code, 0, "{out}");
+ assert!(out.contains("notes/1/n1.ts: shown on cm-1 of i-show-1: to restate"), "{out}");
+ assert_eq!(calls()[0], args(&["show", "--on", "i-show-1", "--working", "cm-1", "--status", "to restate"]));
+ assert_eq!(calls().len(), 2, "cm-1 and cm-2");
- // one ask for two sentences still owes a reading: not posted
+ // one ask for two sentences still owes a reading: its asks aren't shown, and it still reads to restate
restate_n1(&p, r#"{ "text": "the lyric is flat type", "medium": "2D", "not": ["3D text"] }"#);
- let (out, _) = post::post(&p, eval, refused);
- assert!(out.contains("notes/1/n1.ts: not posted: its restatement still owes: one ask from 2 sentences"), "{out}");
+ let (out, _) = post::post(&p, eval, ran);
+ assert!(out.contains("notes/1/n1.ts: shown on cm-1 of i-show-1 as it stands already (to restate)"), "{out}");
+ assert_eq!(calls().len(), 2);
+ // whole: its asks, the note to check (no check yet) and each ask's state
restate_n1(&p, TWO);
- let (out, code) = post::post(&p, eval, refused);
- assert_eq!((code, out.contains("notes/1/n1.ts: not posted: the raea app isn't running")), (1, true), "{out}");
- let (out, code) = post::post(&p, eval, ran);
- assert_eq!(code, 0, "{out}");
- assert!(out.contains("notes/1/n1.ts: its 2 asks shown on cm-1 of i-show-1, where the person can correct one"), "{out}");
- let want = args(&["show", "--on", "i-show-1", "--working", "cm-1", "--ask", "the lyric is flat type the singer passes in front of", "--ask", "the words arrive as a lyric video's do"]);
- assert_eq!(RAN.with(|r| r.borrow().clone()), [want]);
-
- // shown already: not again (a comment settled since isn't marked working again), until its asks change
let (out, _) = post::post(&p, eval, ran);
- assert!(out.contains("notes/1/n1.ts: its asks are shown on cm-1 of i-show-1 already"), "{out}");
- assert_eq!(RAN.with(|r| r.borrow().len()), 1);
- restate_n1(&p, &TWO.replace("as a lyric video's do", "one by one on the beat"));
- post::post(&p, eval, ran);
- assert_eq!(RAN.with(|r| r.borrow().len()), 2);
+ assert!(out.contains("notes/1/n1.ts: shown on cm-1 of i-show-1: its 2 asks, to check"), "{out}");
+ let want = args(&["show", "--on", "i-show-1", "--working", "cm-1", "--ask", "the lyric is flat type the singer passes in front of", "--ask", "the words arrive as a lyric video's do", "--status", "to check", "--states", "to check,to check"]);
+ assert_eq!(calls()[2], want);
+ let (out, _) = post::post(&p, eval, ran);
+ assert!(out.contains("notes/1/n1.ts: shown on cm-1 of i-show-1 as it stands already (to check)"), "{out}");
+ assert_eq!(calls().len(), 3);
- // the person corrects ask 1; restated again in the same words, it's shown again, as the answer to their correction
+ // the person corrects ask 1: back to restate; restated again in the same words, it's shown again, as the answer
let fix = r#"{"kind":"correction","item":"i-show-1","project":"shop","title":"Spring ad","comment":"cm-1","ask":1,"text":"yes, that"}"#;
std::fs::write(inbox.join("a.jsonl"), format!("{SENT}\n{whole}\n{fix}")).unwrap();
take_from(&inbox, &p, &[]).unwrap();
- let f = p.join("notes/1/n1.ts");
let (out, _) = post::post(&p, eval, ran);
- assert!(out.contains("notes/1/n1.ts: not posted: its restatement still owes: the person corrected ask 1"), "{out}");
+ assert!(out.contains("notes/1/n1.ts: shown on cm-1 of i-show-1: to restate: its restatement still owes: the person corrected ask 1"), "{out}");
+ let f = p.join("notes/1/n1.ts");
std::fs::write(&f, std::fs::read_to_string(&f).unwrap().replace(" corrected: [1],\n", "")).unwrap();
+ post::post(&p, eval, ran);
+ assert_eq!(calls().last().unwrap(), &want);
+}
+
+/// A finding of the ask `id`'s check, as a run gives it.
+fn found(id: &str) -> Finding {
+ Finding::new("faces", raea_core_facts::Level::Error, "desk-3 is turned 180 degrees from facing chair-3", &check::by(id))
+}
+
+/// One composition's run that found `fs`.
+fn run_of(fs: Vec<Finding>) -> Vec<check::Ran> {
+ vec![check::Ran { of: "office.tsx".into(), found: fs, waits: vec![], render: None, shots: vec![], fps: 30.0 }]
+}
+
+/// A project with n1 restated as two asks that run one check with different values, the second on one composition.
+fn two_asks() -> (tempfile::TempDir, PathBuf) {
+ let (tmp, p, inbox) = project();
+ std::fs::write(inbox.join("a.jsonl"), SENT).unwrap();
+ take_from(&inbox, &p, &[]).unwrap();
+ restate_n1(&p, r#"{ "text": "every desk faces its chair", "medium": "2D", "not": ["3D"], "check": "../../checks/faces.ts", "values": { "what": "desk" } }, { "text": "every chair faces its desk", "medium": "2D", "not": [], "of": "office.tsx", "check": "../../checks/faces.ts", "values": { "what": "chair" } }"#);
+ (tmp, p)
+}
+
+#[test]
+fn an_asks_check_must_fail_first_and_one_that_passes_first_is_refused() {
+ let (_tmp, p) = two_asks();
+ let notes = read(&p, eval);
+ let (rules, bad) = check::rules(&p, &notes);
+ assert!(bad.is_empty());
+ assert_eq!(rules.iter().map(|r| (r.id.as_str(), r.by.as_str(), r.of.as_deref())).collect::<Vec<_>>(), [("n1.1", "note n1.1", None), ("n1.2", "note n1.2", Some("office.tsx"))]);
+ assert_eq!(rules[0].check, p.join("notes/1/../../checks/faces.ts").display().to_string(), "a check's path is from the note's folder");
+ let ask = |s: &state::State, i: usize| state::of_note(notes[0].note.as_ref().unwrap(), 1, s).1[i].clone();
+
+ // the first run passes n1.1 (refused) and fails n1.2; each counts only its own findings
+ let mut s = state::State::new();
+ let (lines, refused) = check::settle(&p, &notes, &rules, &run_of(vec![found("n1.2"), found("n1.2")]), "20261110-120000", &mut s);
+ assert!(refused);
+ assert!(lines[0].contains("n1.1 notes/1/n1.ts: \"every desk faces its chair\": refused: its check passes on the work as it stands"), "{lines:?}");
+ assert!(lines[1].contains("n1.2 notes/1/n1.ts: \"every chair faces its desk\": fails on the work as it stands (2 findings)"), "{lines:?}");
+ assert!(matches!(ask(&s, 0), state::Standing::ToCheck(why) if why.contains("passed on its first run")));
+ assert_eq!(ask(&s, 1), state::Standing::Failing(2));
+
+ // n1.1 shown failing later counts; the work changes and both pass
+ check::settle(&p, &notes, &rules, &run_of(vec![found("n1.1")]), "20261110-120100", &mut s);
+ assert_eq!((ask(&s, 0), ask(&s, 1)), (state::Standing::Failing(1), state::Standing::Passing));
+ let (lines, refused) = check::settle(&p, &notes, &rules, &run_of(vec![]), "20261110-120200", &mut s);
+ assert!(!refused && lines.iter().all(|l| l.ends_with(": passing")), "{lines:?}");
+
+ // --only runs one: the other isn't judged on a run it wasn't in
+ let (lines, _) = check::settle(&p, &notes, &rules[1..], &run_of(vec![found("n1.2")]), "20261110-120300", &mut s);
+ assert_eq!(lines.len(), 1);
+ assert_eq!((ask(&s, 0), ask(&s, 1)), (state::Standing::Passing, state::Standing::Failing(1)));
+
+ // a check changed after it failed is to be shown failing again; kept as written, ls says each ask's state
+ let f = p.join("notes/1/n1.ts");
+ std::fs::write(&f, std::fs::read_to_string(&f).unwrap().replace(r#""what": "desk""#, r#""what": "desk", "within": 90"#)).unwrap();
+ let notes = read(&p, eval);
+ assert!(matches!(state::of_note(notes[0].note.as_ref().unwrap(), 1, &s).1[0].clone(), state::Standing::ToCheck(why) if why.contains("changed since it failed")));
+ state::write(&p, &s).unwrap();
+ let (out, _) = ls(&p, false, eval);
+ assert!(out.contains(" n1.2 every chair faces its desk [2D]: failing (1 finding)"), "{out}");
+ assert!(out.contains("notes/1/n1.ts: round 1, to check: "), "{out}");
+}
+
+#[test]
+fn a_clip_is_signed_by_the_person_for_its_render_and_reopens_when_its_source_changes() {
+ let (_tmp, p, inbox) = project();
+ std::fs::write(inbox.join("a.jsonl"), SENT).unwrap();
+ take_from(&inbox, &p, &[]).unwrap();
+ restate_n1(&p, r#"{ "text": "the light turns on the cut", "medium": "2D", "not": ["3D"], "proof": { "shot": "reveal", "sign": true } }, { "text": "the lyric is flat type", "medium": "2D", "not": [] }"#);
+ let note = || read(&p, eval).remove(0).note.unwrap();
+ let ask = |s: &state::State| state::of_note(&note(), 1, s).1[0].clone();
+ let mut s = state::State::new();
+ assert!(matches!(ask(&s), state::Standing::ToCheck(why) if why.starts_with("no clip yet")), "the agent's move: render and cut it");
+ let clip = |render: &str, stale: bool| state::Clip { file: p.join(".raea/notes-clips/n1.1.mp4"), of: "edit.tsx".into(), render: render.into(), frames: [30, 150], stale };
+ s.insert("n1.1".into(), state::Kept { clip: Some(clip("aaa", false)), ..Default::default() });
+ state::write(&p, &s).unwrap();
+ assert!(matches!(ask(&s), state::Standing::ToSign(why) if why.contains("waits on the person")));
+
+ // posted under its ask, for the person to sign
let (out, _) = post::post(&p, eval, ran);
- assert!(out.contains("notes/1/n1.ts: its 2 asks shown on cm-1"), "{out}");
- assert_eq!(RAN.with(|r| r.borrow().len()), 3);
+ assert!(out.contains("notes/1/n1.ts: shown on cm-1 of i-show-1: its 2 asks, to check, with 1 clip to sign"), "{out}");
+ let file = p.join(".raea/notes-clips/n1.1.mp4").display().to_string();
+ assert_eq!(calls()[1], args(&["show", "--on", "i-show-1", "--working", "cm-1", "--sign", "1", "--clip", &file, "--render", "aaa"]), "after cm-1's asks, before cm-2");
+
+ // the person signs it in the app (a sign for a note not taken is said, not dropped); a second take changes nothing
+ let sign = |render: &str, name: &str| format!(r#"{{"kind":"sign","item":"i-show-1","project":"shop","comment":"cm-1","ask":1,"render":"{render}",{name}"when":"2026-11-10T12:00:00Z"}}"#);
+ let lost = r#"{"kind":"sign","item":"i-show-7","project":"shop","comment":"cm-1","ask":1,"render":"aaa","when":"x"}"#;
+ std::fs::write(inbox.join("a.jsonl"), [SENT.to_string(), sign("aaa", r#""name":"Sam","#), lost.to_string()].join("\n")).unwrap();
+ let out = take_from(&inbox, &p, &[]).unwrap();
+ assert!(out.contains("notes/1/n1.ts: ask 1 signed by Sam, on the render aaa…"), "{out}");
+ assert!(out.contains("a sign for a note not in notes/ (app i-show-7 cm-1, ask 1)"), "{out}");
+ let s = state::read(&p);
+ assert_eq!(ask(&s), state::Standing::Signed(Some("Sam".into())));
+ assert!(!take_from(&inbox, &p, &[]).unwrap().contains("signed"));
+
+ // its composition changed after the render: to sign again; a new render's clip: the old sign doesn't hold
+ let mut s = state::read(&p);
+ s.get_mut("n1.1").unwrap().clip = Some(clip("aaa", true));
+ assert!(matches!(ask(&s), state::Standing::ToCheck(why) if why.contains("changed after the render")), "the agent's move: render it again");
+ s.get_mut("n1.1").unwrap().clip = Some(clip("bbb", false));
+ assert!(matches!(ask(&s), state::Standing::ToSign(why) if why.starts_with("Sam signed an older render")));
+ state::write(&p, &s).unwrap();
+
+ // signed again for the new render, by a person the app had no account for: signed, unnamed
+ std::fs::write(inbox.join("a.jsonl"), [SENT.to_string(), sign("aaa", r#""name":"Sam","#), sign("bbb", "")].join("\n")).unwrap();
+ let out = take_from(&inbox, &p, &[]).unwrap();
+ assert!(out.contains("ask 1 signed by the person (unnamed: the app had no account), on the render bbb…"), "{out}");
+ assert_eq!(ask(&state::read(&p)), state::Standing::Signed(None));
+}
+
+#[test]
+fn an_ask_names_its_composition_by_file_or_by_file_and_id() {
+ assert!(check::is_of("hold.tsx", "hold.tsx#hold"), "a file alone is any composition in it");
+ assert!(check::is_of("hold.tsx", "hold.tsx"));
+ assert!(check::is_of("cuts.tsx#b", "cuts.tsx#b"));
+ assert!(!check::is_of("cuts.tsx#b", "cuts.tsx#a"));
+ assert!(!check::is_of("cuts.tsx#b", "cuts.tsx"), "an id the run doesn't name");
+ assert!(!check::is_of("hold.tsx", "scenes/hold.tsx#hold"), "its file from the project, not its name");
+}
+
+#[test]
+fn no_clip_is_cut_from_a_render_the_composition_changed_after() {
+ let (_tmp, p, inbox) = project();
+ std::fs::write(inbox.join("a.jsonl"), SENT).unwrap();
+ take_from(&inbox, &p, &[]).unwrap();
+ restate_n1(&p, r#"{ "text": "the light turns on the cut", "medium": "2D", "not": ["3D"], "of": "edit.tsx", "proof": { "shot": "reveal", "sign": true } }, { "text": "the lyric is flat type", "medium": "2D", "not": [] }"#);
+ let notes = read(&p, eval);
+ let mut s = state::State::new();
+ let clip = state::Clip { file: p.join(".raea/notes-clips/n1.1.mp4"), of: "edit.tsx#edit".into(), render: "aaa".into(), frames: [30, 150], stale: false };
+ s.insert("n1.1".into(), state::Kept { clip: Some(clip), ..Default::default() });
+ let run = |render: Option<check::Rendered>| vec![check::Ran { of: "edit.tsx#edit".into(), found: vec![], waits: vec![], render, shots: vec![("reveal".into(), 30, None)], fps: 30.0 }];
+
+ let stale = check::Rendered { out: p.join("out/edit.mp4"), stale: true, frames: 150 };
+ let lines = check::clips(&p, &notes, &run(Some(stale)), &mut s);
+ assert_eq!(lines, ["n1.1 notes/1/n1.ts: its clip waits for a render of edit.tsx#edit as it stands: it changed after its newest render"]);
+ assert!(s["n1.1"].clip.as_ref().unwrap().stale, "the clip kept from the render before is marked");
+ assert!(!p.join(".raea/notes-clips/n1.1.mp4").exists(), "nothing is cut from it");
+ let n = notes[0].note.as_ref().unwrap();
+ assert!(matches!(state::of_note(n, 1, &s).1[0].clone(), state::Standing::ToCheck(why) if why.contains("render it again")), "the agent's move");
+
+ // no render at all: said, and nothing is cut
+ assert_eq!(check::clips(&p, &notes, &run(None), &mut s), ["n1.1 notes/1/n1.ts: its clip waits for a render of edit.tsx#edit"]);
}
diff --git a/bench/direction/asks/asks.sh b/bench/direction/asks/asks.sh
new file mode 100644
index 00000000..ae25c4a3
--- /dev/null
+++ b/bench/direction/asks/asks.sh
@@ -0,0 +1,162 @@
+#!/usr/bin/env bash
+# DR6's proof (docs/direction.feature): a note's asks held by checks.
+# 1. The worked checks (sdk/guides/craft/checks, copied to checks/ as a project copies them), each named by an ask in
+# notes/1, run by `raea check FILE --only nX.Y` on a piece that holds the ask and on each cheat that must fail it.
+# 2. The notes' flow on a project of its own: a note said, restated as an ask about one composition, checked on the
+# work as it stands (it must fail first), the work changed until it passes; an ask whose check passes on its first
+# run is refused; an ask the person signs gets its clip cut from the newest render, and their sign from the app's
+# inbox is kept, until the composition changes.
+# Nothing is downloaded or generated; every case runs in a copy, so the bench folder stays clean.
+#
+# RAEA_BIN=path/to/raea bash bench/direction/asks/asks.sh
+set -uo pipefail
+here=$(cd "$(dirname "$0")" && pwd)
+root=$(cd "$here/../../.." && pwd)
+raea=${RAEA_BIN:-raea}
+work=$(mktemp -d "${TMPDIR:-/tmp}/raea-dr6-asks.XXXXXX")
+# KEEP=1 keeps the copy (its renders, logs, notes and state) and says where
+if [ -n "${KEEP:-}" ]; then trap 'echo "asks: kept $work"' EXIT; else trap 'rm -rf "$work"' EXIT; fi
+cp -R "$here/." "$work/"
+rm -f "$work/asks.sh"
+mkdir -p "$work/.raea" "$work/out" "$work/checks"
+: >"$work/.raea/project"
+cp "$root"/sdk/guides/craft/checks/*.ts "$work/checks/"
+cd "$work" || exit 2
+
+# the lyric's occlusion half reads who covers whom from a render's layers
+for p in lyric lyric-deep lyric-bare lyric-words; do "$raea" render "$p.tsx" -o "out/$p.mp4" --layers >"out/$p.log" 2>&1 || { echo "asks: raea render $p.tsx failed:"; tail -5 "out/$p.log"; exit 2; }; done
+
+bad=0
+# FILE ID WANT: `raea check FILE --only ID` finds nothing (WANT none) or something (WANT some), waits for nothing,
+# and every finding it prints is shown
+case_() {
+ local file=$1 id=$2 want=$3
+ local out
+ out=$("$raea" check "$file" --only "$id" --json 2>"out/$file.$id.err")
+ local code=$?
+ if [ $code -eq 2 ] || ! jq -e .compositions >/dev/null 2>&1 <<<"$out"; then
+ echo "FAIL $file --only $id: raea check couldn't check it (exit $code): $(tail -3 "out/$file.$id.err") $(head -c 300 <<<"$out")"
+ bad=$((bad + 1))
+ return
+ fi
+ local n waits
+ n=$(jq '[.compositions[].findings[]] | length' <<<"$out")
+ waits=$(jq -r '[.compositions[].waits[] | "\(.rule) waits for \(.for)"] | join("; ")' <<<"$out")
+ local ok=1
+ { [ "$want" = none ] && [ "$n" -ne 0 ]; } && ok=0
+ { [ "$want" = some ] && [ "$n" -eq 0 ]; } && ok=0
+ [ -n "$waits" ] && ok=0
+ [ $ok -eq 1 ] || bad=$((bad + 1))
+ printf '%s %s --only %s: %s finding(s)%s\n' "$([ $ok -eq 1 ] && echo "ok " || echo FAIL)" "$file" "$id" "$n" "${waits:+, $waits}"
+ jq -r '.compositions[].findings[] | " \(.level) \(.check) \(.frames // "" | tostring): \(.says)"' <<<"$out"
+}
+
+echo "1. the worked checks, each on a piece that holds its ask and on its cheats"
+case_ ride.tsx n1.1 none
+for c in ride-left ride-into ride-gone; do case_ "$c.tsx" n1.1 some; done
+case_ lyric.tsx n2.1 none
+for c in lyric-deep lyric-bare lyric-words; do case_ "$c.tsx" n2.1 some; done
+case_ office.tsx n3.1 none
+case_ office.tsx n3.2 none
+case_ office-turned.tsx n3.1 some
+case_ office-kettle.tsx n3.2 some
+case_ office-renamed.tsx n3.1 some
+case_ office-renamed.tsx n3.2 some
+case_ hold.tsx n4.1 none
+for c in hold-short hold-renamed; do case_ "$c.tsx" n4.1 some; done
+case_ office.tsx n5.1 none
+for c in orb orb-renamed orb-tiny; do case_ "$c.tsx" n5.1 some; done
+
+# 2. the flow, in a project of its own. The work as it stands: a desk turned from its chair with the kettle on it, and
+# the reveal held two seconds
+flow=$work/flow
+mkdir -p "$flow/.raea" "$flow/checks" "$flow/inbox"
+: >"$flow/.raea/project"
+cp set.tsx "$flow/"
+sed -e 's|<Office turned={3} />|<Office turned={3} kettle="desk" />|' -e 's|id="office-turned"|id="office"|' office-turned.tsx >"$flow/office.tsx"
+sed 's|id="hold-short"|id="hold"|' hold-short.tsx >"$flow/hold.tsx"
+cp checks/*.ts "$flow/checks/"
+export RAEA_INBOX_DIR=$flow/inbox
+cd "$flow" || exit 2
+# NAME WANT-CODE LINE...: what `cmd` prints has each line (a fixed string), and it exits WANT-CODE
+step() {
+ local name=$1 want=$2
+ shift 2
+ local out code
+ out=$("${cmd[@]}" 2>&1)
+ code=$?
+ local ok=1 l
+ [ "$code" -eq "$want" ] || ok=0
+ for l in "$@"; do grep -qF -- "$l" <<<"$out" || { ok=0; echo " missing: $l"; }; done
+ [ $ok -eq 1 ] || bad=$((bad + 1))
+ printf '%s %s (exit %s)\n' "$([ $ok -eq 1 ] && echo "ok " || echo FAIL)" "$name" "$code"
+ sed 's/^/ /' <<<"$out"
+}
+# FILE FROM TO: a note's file with FROM written as TO, as the agent edits it (FROM must be there)
+edit() {
+ bun -e 'const [f, a, b] = process.argv.slice(1); const t = await Bun.file(f).text(); if (!t.includes(a)) { console.error(`${f}: no ${a}`); process.exit(1); } await Bun.write(f, t.replace(a, b));' "$@" || { echo "asks: couldn't edit $1"; exit 2; }
+}
+take=("$raea" notes take "$flow")
+check=("$raea" notes check "$flow")
+ls_=("$raea" notes ls "$flow")
+
+echo "2. the notes' flow"
+cmd=("${take[@]}" --said "The desks face the wrong way." --said "Hold the reveal longer, and let me see it." --said "And why is there a kettle on a desk?")
+step "three notes said, taken to restate" 0 "notes/1/n1.ts: to restate" "notes/1/n3.ts: to restate" "round 1: 3 notes taken."
+cmd=("${check[@]}")
+step "nothing restated: nothing to check" 0 "no ask has a check or a clip to sign yet"
+# restated as asks, each about one composition; the kettle's check names a part the scene doesn't have, so it can't fail
+edit notes/1/n1.ts "asks: []," 'asks: [{ text: "every desk faces its chair", about: "desk", not: ["where the desks stand"], verb: "layout", of: "office.tsx", check: "../../checks/faces.ts", values: { what: "desk", toward: "chair" } }],'
+edit notes/1/n2.ts "asks: []," 'asks: [{ text: "the reveal holds four seconds", about: "reveal", not: ["the lead-in"], verb: "retime", of: "hold.tsx", check: "../../checks/shot-length.ts", values: { shot: "reveal", seconds: 4 } }, { text: "the person sees the longer reveal and signs it", about: "reveal", not: ["the other shots"], verb: "retime", of: "hold.tsx", proof: { shot: "reveal", sign: true } }],'
+edit notes/1/n3.ts "asks: []," 'asks: [{ text: "no kettle stands on a desk", about: "kettle, desk", not: ["the desks"], verb: "layout", of: "office.tsx", check: "../../checks/stands-on.ts", values: { what: "teapot", on: "desk" } }],'
+cmd=("${ls_[@]}")
+step "restated: where each ask stands" 0 " n1.1 every desk faces its chair; not: where the desks stand: to check: its check isn't shown failing on the work yet" " n2.2 the person sees the longer reveal and signs it; not: the other shots: to check: no clip yet"
+cmd=("${check[@]}" --no-render)
+step "checked on the work as it stands: two fail first; the kettle's passes, so it's refused" 1 \
+ "n1.1 notes/1/n1.ts: \"every desk faces its chair\": fails on the work as it stands (1 finding)" \
+ "n2.1 notes/1/n2.ts: \"the reveal holds four seconds\": fails on the work as it stands (1 finding)" \
+ "n3.1 notes/1/n3.ts: \"no kettle stands on a desk\": refused: its check passes on the work as it stands" \
+ "n2.2 notes/1/n2.ts: its clip waits for a render of hold.tsx"
+cmd=("${ls_[@]}")
+step "ls: failing, and the refused ask to check again" 0 " n1.1 every desk faces its chair; not: where the desks stand: failing (1 finding)" " n3.1 no kettle stands on a desk; not: the desks: to check: its check passed on its first run"
+# the refused ask's check made to measure it: the kettle by its name
+edit notes/1/n3.ts '"teapot"' '"kettle"'
+cmd=("${check[@]}" --no-render)
+step "the kettle's check, measuring it now, fails first" 0 "n3.1 notes/1/n3.ts: \"no kettle stands on a desk\": fails on the work as it stands (1 finding)" "n1.1 notes/1/n1.ts: \"every desk faces its chair\": failing (1 finding)"
+
+# the work changes as the notes ask, and the hold is rendered for its clip
+cp "$work/office.tsx" office.tsx
+cp "$work/hold.tsx" hold.tsx
+"$raea" render hold.tsx -o hold.mp4 >render.log 2>&1 || { echo "asks: raea render hold.tsx failed:"; tail -5 render.log; exit 2; }
+cmd=("${check[@]}")
+step "the work changed: every ask passes, and the reveal's clip is cut from the render" 0 \
+ "n1.1 notes/1/n1.ts: \"every desk faces its chair\": passing" \
+ "n2.1 notes/1/n2.ts: \"the reveal holds four seconds\": passing" \
+ "n3.1 notes/1/n3.ts: \"no kettle stands on a desk\": passing" \
+ "n2.2 notes/1/n2.ts: its clip, frames" "of hold.tsx#hold, cut from its newest render"
+if [ -s .raea/notes-clips/n2.2.mp4 ]; then echo "ok the clip: .raea/notes-clips/n2.2.mp4, $(ffprobe -v error -show_entries format=duration -of csv=p=0 .raea/notes-clips/n2.2.mp4) s"; else echo "FAIL no clip at .raea/notes-clips/n2.2.mp4"; bad=$((bad + 1)); fi
+cmd=("${ls_[@]}")
+step "ls: the clip waits on the person" 0 " n2.2 the person sees the longer reveal and signs it; not: the other shots: to sign: its clip waits on the person"
+
+# the person signs it in the app: the sign comes to the inbox, for the render the clip was cut from
+render=$(jq -r '."n2.2".clip.render' .raea/notes-checks.json)
+printf '{"kind":"sign","project":"flow","item":"i-show-1","comment":"cm-1","ask":2,"render":"%s","when":"2026-11-10T15:00:00Z"}\n' "$render" >inbox/a.jsonl
+cmd=("${take[@]}")
+step "a sign for a note that didn't come from that comment isn't kept" 0 "a sign for a note not in notes/ (app i-show-1 cm-1, ask 2)"
+edit notes/1/n2.ts 'from: "session"' 'from: "app i-show-1 cm-1"'
+cmd=("${take[@]}")
+step "the person's sign is kept" 0 "notes/1/n2.ts: ask 2 signed by the person (unnamed: the app had no account), on the render ${render:0:12}…"
+cmd=("${ls_[@]}")
+step "ls: signed" 0 " n2.2 the person sees the longer reveal and signs it; not: the other shots: signed (unnamed: the app had no account)"
+
+# the hold is shortened after its render: failing again, and the signed clip is no longer the work
+sed 's|id="hold-short"|id="hold"|' "$work/hold-short.tsx" >hold.tsx
+cmd=("${check[@]}")
+step "the hold shortened again: failing, and its clip from a render that is no longer the work" 0 \
+ "n2.1 notes/1/n2.ts: \"the reveal holds four seconds\": failing (1 finding)" \
+ "n2.2 notes/1/n2.ts: its clip waits for a render of hold.tsx#hold as it stands: it changed after its newest render"
+cmd=("${ls_[@]}")
+step "ls: the sign doesn't hold, and rendering again is the agent's move" 0 " n2.2 the person sees the longer reveal and signs it; not: the other shots: to check: hold.tsx#hold changed after the render its clip is cut from: render it again"
+
+if [ $bad -eq 0 ]; then echo "asks: every case as expected"; else echo "asks: $bad case(s) wrong"; fi
+exit $((bad > 0))
diff --git a/bench/direction/asks/hold-renamed.tsx b/bench/direction/asks/hold-renamed.tsx
new file mode 100644
index 00000000..f0607f1a
--- /dev/null
+++ b/bench/direction/asks/hold-renamed.tsx
@@ -0,0 +1,9 @@
+// Cheat: the reveal renamed, so no shot is the one asked about. shot-length must fail it.
+import { Composition, registerRoot } from "raea";
+import { Hold } from "./set";
+
+function Piece() {
+ return <Hold seconds={4} name="end" />;
+}
+
+registerRoot(() => <Composition id="hold-renamed" component={Piece} width={540} height={960} fps={30} durationInFrames={150} />);
diff --git a/bench/direction/asks/hold-short.tsx b/bench/direction/asks/hold-short.tsx
new file mode 100644
index 00000000..40be5f4c
--- /dev/null
+++ b/bench/direction/asks/hold-short.tsx
@@ -0,0 +1,9 @@
+// Cheat: the reveal left at two seconds. shot-length must fail it.
+import { Composition, registerRoot } from "raea";
+import { Hold } from "./set";
+
+function Piece() {
+ return <Hold seconds={2} />;
+}
+
+registerRoot(() => <Composition id="hold-short" component={Piece} width={540} height={960} fps={30} durationInFrames={90} />);
diff --git a/bench/direction/asks/hold.tsx b/bench/direction/asks/hold.tsx
new file mode 100644
index 00000000..0134e162
--- /dev/null
+++ b/bench/direction/asks/hold.tsx
@@ -0,0 +1,9 @@
+// DR6's cut as asked: the reveal held four seconds.
+import { Composition, registerRoot } from "raea";
+import { Hold } from "./set";
+
+function Piece() {
+ return <Hold seconds={4} />;
+}
+
+registerRoot(() => <Composition id="hold" component={Piece} width={540} height={960} fps={30} durationInFrames={150} />);
diff --git a/bench/direction/asks/lyric-bare.tsx b/bench/direction/asks/lyric-bare.tsx
new file mode 100644
index 00000000..2f9160bd
--- /dev/null
+++ b/bench/direction/asks/lyric-bare.tsx
@@ -0,0 +1,9 @@
+// Cheat: flat type with nothing in front of it. flat-type must fail it.
+import { Composition, registerRoot } from "raea";
+import { Lyric } from "./set";
+
+function Piece() {
+ return <Lyric bare />;
+}
+
+registerRoot(() => <Composition id="lyric-bare" component={Piece} width={540} height={960} fps={30} durationInFrames={30} />);
diff --git a/bench/direction/asks/lyric-deep.tsx b/bench/direction/asks/lyric-deep.tsx
new file mode 100644
index 00000000..c6e418b7
--- /dev/null
+++ b/bench/direction/asks/lyric-deep.tsx
@@ -0,0 +1,9 @@
+// Cheat: the line as 3D type 0.002 m deep, facing the camera so a frame reads flat. flat-type must fail it.
+import { Composition, registerRoot } from "raea";
+import { Lyric } from "./set";
+
+function Piece() {
+ return <Lyric deep />;
+}
+
+registerRoot(() => <Composition id="lyric-deep" component={Piece} width={540} height={960} fps={30} durationInFrames={30} />);
diff --git a/bench/direction/asks/lyric-words.tsx b/bench/direction/asks/lyric-words.tsx
new file mode 100644
index 00000000..63eb2fb9
--- /dev/null
+++ b/bench/direction/asks/lyric-words.tsx
@@ -0,0 +1,9 @@
+// Cheat: the line changed, so no text reads the words asked about. flat-type must fail it.
+import { Composition, registerRoot } from "raea";
+import { Lyric } from "./set";
+
+function Piece() {
+ return <Lyric words="INTO THE BLUE" />;
+}
+
+registerRoot(() => <Composition id="lyric-words" component={Piece} width={540} height={960} fps={30} durationInFrames={30} />);
diff --git a/bench/direction/asks/lyric.tsx b/bench/direction/asks/lyric.tsx
new file mode 100644
index 00000000..fa6bdf40
--- /dev/null
+++ b/bench/direction/asks/lyric.tsx
@@ -0,0 +1,9 @@
+// DR6's lyric as asked: the line as flat 2D type, the singer in front of it.
+import { Composition, registerRoot } from "raea";
+import { Lyric } from "./set";
+
+function Piece() {
+ return <Lyric />;
+}
+
+registerRoot(() => <Composition id="lyric" component={Piece} width={540} height={960} fps={30} durationInFrames={30} />);
diff --git a/bench/direction/asks/notes/1/n1.ts b/bench/direction/asks/notes/1/n1.ts
new file mode 100644
index 00000000..c053a919
--- /dev/null
+++ b/bench/direction/asks/notes/1/n1.ts
@@ -0,0 +1,19 @@
+// A note as the person said it, restated as asks (DR6's worked checks: sdk/guides/craft/checks, copied to checks/
+// by asks.sh as a project copies them).
+import { note } from "raea/note";
+
+export default note({
+ words: ["The seat turns with the computer, it's not on it."],
+ from: "session",
+ round: 1,
+ asks: [
+ {
+ text: "the computer rides the chair's seat as it swivels, clear of its back",
+ about: "computer, chair",
+ not: ["the chair's swivel", "the camera"],
+ verb: "animate",
+ check: "../../checks/rides.ts",
+ values: { rider: "computer", seat: "chair" },
+ },
+ ],
+});
diff --git a/bench/direction/asks/notes/1/n2.ts b/bench/direction/asks/notes/1/n2.ts
new file mode 100644
index 00000000..b338779d
--- /dev/null
+++ b/bench/direction/asks/notes/1/n2.ts
@@ -0,0 +1,20 @@
+// A note as the person said it, restated as asks (DR6's worked checks: sdk/guides/craft/checks, copied to checks/
+// by asks.sh as a project copies them).
+import { note } from "raea/note";
+
+export default note({
+ words: ["I want the lyric as 2D animated text with occlusion, not 3D text extrusion."],
+ from: "session",
+ round: 1,
+ asks: [
+ {
+ text: "the lyric is flat type, with the singer in front of it where they meet",
+ medium: "2D",
+ about: "OUT OF THE GREY",
+ not: ["3D type", "extruded letters"],
+ verb: "typeset",
+ check: "../../checks/flat-type.ts",
+ values: { words: "out of the grey", subject: "component:Singer" },
+ },
+ ],
+});
diff --git a/bench/direction/asks/notes/1/n3.ts b/bench/direction/asks/notes/1/n3.ts
new file mode 100644
index 00000000..ab1680d6
--- /dev/null
+++ b/bench/direction/asks/notes/1/n3.ts
@@ -0,0 +1,27 @@
+// A note as the person said it, restated as asks (DR6's worked checks: sdk/guides/craft/checks, copied to checks/
+// by asks.sh as a project copies them).
+import { note } from "raea/note";
+
+export default note({
+ words: ["The desks face the wrong way. And why are there kitchen props on them?"],
+ from: "session",
+ round: 1,
+ asks: [
+ {
+ text: "every desk faces its chair",
+ about: "desk",
+ not: ["where the desks stand"],
+ verb: "layout",
+ check: "../../checks/faces.ts",
+ values: { what: "desk", toward: "chair" },
+ },
+ {
+ text: "nothing from the kitchen stands on a desk",
+ about: "kettle, desk",
+ not: ["the kettle itself, on the counter"],
+ verb: "layout",
+ check: "../../checks/stands-on.ts",
+ values: { what: "kettle, mug", on: "desk" },
+ },
+ ],
+});
diff --git a/bench/direction/asks/notes/1/n4.ts b/bench/direction/asks/notes/1/n4.ts
new file mode 100644
index 00000000..8c79805b
--- /dev/null
+++ b/bench/direction/asks/notes/1/n4.ts
@@ -0,0 +1,19 @@
+// A note as the person said it, restated as asks (DR6's worked checks: sdk/guides/craft/checks, copied to checks/
+// by asks.sh as a project copies them).
+import { note } from "raea/note";
+
+export default note({
+ words: ["Hold the reveal longer."],
+ from: "session",
+ round: 1,
+ asks: [
+ {
+ text: "the reveal holds four seconds",
+ about: "reveal",
+ not: ["the lead-in"],
+ verb: "retime",
+ check: "../../checks/shot-length.ts",
+ values: { shot: "reveal", seconds: 4 },
+ },
+ ],
+});
diff --git a/bench/direction/asks/notes/1/n5.ts b/bench/direction/asks/notes/1/n5.ts
new file mode 100644
index 00000000..7a86bdf1
--- /dev/null
+++ b/bench/direction/asks/notes/1/n5.ts
@@ -0,0 +1,10 @@
+// A note as the person said it, restated as asks (DR6's worked checks: sdk/guides/craft/checks, copied to checks/
+// by asks.sh as a project copies them).
+import { note } from "raea/note";
+
+export default note({
+ words: ["No orbs anywhere."],
+ from: "session",
+ round: 1,
+ asks: [{ text: "no orb in any shot", about: "Orb", not: ["the lights"], verb: "distill", check: "../../checks/no-part.ts", values: { what: "component:Orb" } }],
+});
diff --git a/bench/direction/asks/office-kettle.tsx b/bench/direction/asks/office-kettle.tsx
new file mode 100644
index 00000000..bf64fd2d
--- /dev/null
+++ b/bench/direction/asks/office-kettle.tsx
@@ -0,0 +1,9 @@
+// Cheat: the kettle set on a desk. stands-on must fail it.
+import { Composition, registerRoot } from "raea";
+import { Office } from "./set";
+
+function Piece() {
+ return <Office kettle="desk" />;
+}
+
+registerRoot(() => <Composition id="office-kettle" component={Piece} width={960} height={540} fps={30} durationInFrames={30} />);
diff --git a/bench/direction/asks/office-renamed.tsx b/bench/direction/asks/office-renamed.tsx
new file mode 100644
index 00000000..24f946d1
--- /dev/null
+++ b/bench/direction/asks/office-renamed.tsx
@@ -0,0 +1,9 @@
+// Cheat: the desks renamed tables, so no desk is checked. faces and stands-on must fail it.
+import { Composition, registerRoot } from "raea";
+import { Office } from "./set";
+
+function Piece() {
+ return <Office desk="table" kettle="desk" />;
+}
+
+registerRoot(() => <Composition id="office-renamed" component={Piece} width={960} height={540} fps={30} durationInFrames={30} />);
diff --git a/bench/direction/asks/office-turned.tsx b/bench/direction/asks/office-turned.tsx
new file mode 100644
index 00000000..c4ead1a2
--- /dev/null
+++ b/bench/direction/asks/office-turned.tsx
@@ -0,0 +1,9 @@
+// Cheat: one desk turned round, its back to its chair. faces must fail it.
+import { Composition, registerRoot } from "raea";
+import { Office } from "./set";
+
+function Piece() {
+ return <Office turned={3} />;
+}
+
+registerRoot(() => <Composition id="office-turned" component={Piece} width={960} height={540} fps={30} durationInFrames={30} />);
diff --git a/bench/direction/asks/office.tsx b/bench/direction/asks/office.tsx
new file mode 100644
index 00000000..63ed0b14
--- /dev/null
+++ b/bench/direction/asks/office.tsx
@@ -0,0 +1,9 @@
+// DR6's office as asked: every desk faces its chair, the kettle is on the counter, no orb.
+import { Composition, registerRoot } from "raea";
+import { Office } from "./set";
+
+function Piece() {
+ return <Office />;
+}
+
+registerRoot(() => <Composition id="office" component={Piece} width={960} height={540} fps={30} durationInFrames={30} />);
diff --git a/bench/direction/asks/orb-renamed.tsx b/bench/direction/asks/orb-renamed.tsx
new file mode 100644
index 00000000..f56e06ee
--- /dev/null
+++ b/bench/direction/asks/orb-renamed.tsx
@@ -0,0 +1,9 @@
+// Cheat: the orb's mesh renamed lamp-glass; the Orb component still draws it. no-part must fail it.
+import { Composition, registerRoot } from "raea";
+import { Office } from "./set";
+
+function Piece() {
+ return <Office orb="renamed" />;
+}
+
+registerRoot(() => <Composition id="orb-renamed" component={Piece} width={960} height={540} fps={30} durationInFrames={30} />);
diff --git a/bench/direction/asks/orb-tiny.tsx b/bench/direction/asks/orb-tiny.tsx
new file mode 100644
index 00000000..962fee22
--- /dev/null
+++ b/bench/direction/asks/orb-tiny.tsx
@@ -0,0 +1,9 @@
+// Cheat: the orb scaled to nothing, still an orb. no-part must fail it.
+import { Composition, registerRoot } from "raea";
+import { Office } from "./set";
+
+function Piece() {
+ return <Office orb="tiny" />;
+}
+
+registerRoot(() => <Composition id="orb-tiny" component={Piece} width={960} height={540} fps={30} durationInFrames={30} />);
diff --git a/bench/direction/asks/orb.tsx b/bench/direction/asks/orb.tsx
new file mode 100644
index 00000000..bc59cc72
--- /dev/null
+++ b/bench/direction/asks/orb.tsx
@@ -0,0 +1,9 @@
+// Cheat: an orb in a corner of the office. no-part must fail it.
+import { Composition, registerRoot } from "raea";
+import { Office } from "./set";
+
+function Piece() {
+ return <Office orb="one" />;
+}
+
+registerRoot(() => <Composition id="orb" component={Piece} width={960} height={540} fps={30} durationInFrames={30} />);
diff --git a/bench/direction/asks/ride-gone.tsx b/bench/direction/asks/ride-gone.tsx
new file mode 100644
index 00000000..ca82a834
--- /dev/null
+++ b/bench/direction/asks/ride-gone.tsx
@@ -0,0 +1,9 @@
+// Cheat: the computer renamed box, so no frame has the rider. rides must fail it.
+import { Composition, registerRoot, useCurrentFrame } from "raea";
+import { Ride } from "./set";
+
+function Piece() {
+ return <Ride yaw={0.3 + useCurrentFrame() * 0.02} at={[0, 0.2, 0.05]} rider="box" />;
+}
+
+registerRoot(() => <Composition id="ride-gone" component={Piece} width={540} height={960} fps={30} durationInFrames={30} />);
diff --git a/bench/direction/asks/ride-into.tsx b/bench/direction/asks/ride-into.tsx
new file mode 100644
index 00000000..184e3b0a
--- /dev/null
+++ b/bench/direction/asks/ride-into.tsx
@@ -0,0 +1,9 @@
+// Cheat: the computer turns with the chair but sits 10 cm into its back. rides must fail it.
+import { Composition, registerRoot, useCurrentFrame } from "raea";
+import { Ride } from "./set";
+
+function Piece() {
+ return <Ride yaw={0.3 + useCurrentFrame() * 0.02} at={[0, 0.2, -0.15]} />;
+}
+
+registerRoot(() => <Composition id="ride-into" component={Piece} width={540} height={960} fps={30} durationInFrames={30} />);
diff --git a/bench/direction/asks/ride-left.tsx b/bench/direction/asks/ride-left.tsx
new file mode 100644
index 00000000..c89e8168
--- /dev/null
+++ b/bench/direction/asks/ride-left.tsx
@@ -0,0 +1,9 @@
+// Cheat: the computer left where it was as the chair turns under it. rides must fail it.
+import { Composition, registerRoot, useCurrentFrame } from "raea";
+import { Ride } from "./set";
+
+function Piece() {
+ return <Ride yaw={0.3 + useCurrentFrame() * 0.02} at={[0, 0.2, 0.05]} left />;
+}
+
+registerRoot(() => <Composition id="ride-left" component={Piece} width={540} height={960} fps={30} durationInFrames={30} />);
diff --git a/bench/direction/asks/ride.tsx b/bench/direction/asks/ride.tsx
new file mode 100644
index 00000000..718de0ea
--- /dev/null
+++ b/bench/direction/asks/ride.tsx
@@ -0,0 +1,9 @@
+// DR6's ride as asked: the computer on the chair's seat, clear of its back, turning with it.
+import { Composition, registerRoot, useCurrentFrame } from "raea";
+import { Ride } from "./set";
+
+function Piece() {
+ return <Ride yaw={0.3 + useCurrentFrame() * 0.02} at={[0, 0.2, 0.05]} />;
+}
+
+registerRoot(() => <Composition id="ride" component={Piece} width={540} height={960} fps={30} durationInFrames={30} />);
diff --git a/bench/direction/asks/set.tsx b/bench/direction/asks/set.tsx
new file mode 100644
index 00000000..9e2983ec
--- /dev/null
+++ b/bench/direction/asks/set.tsx
@@ -0,0 +1,121 @@
+// DR6's worked checks, the pieces they run on (docs/direction.feature DR6): an office (desks facing their chairs, a
+// kettle on the counter, and an orb where a cheat puts one), a computer riding a swivel chair, a lyric over a singer,
+// and a reveal held. Each composition beside this file is one of them as the notes ask, or a cheat that must fail.
+import { AbsoluteFill, Sequence } from "raea";
+import { Sphere, Text3D } from "raea/3d";
+import { Camera3d } from "raea/camera";
+import { DirectionalLight } from "raea/light";
+import { Cuboid, Mesh3d } from "raea/mesh";
+import { StandardMaterial } from "raea/pbr";
+import { Quat, Transform } from "raea/transform";
+
+const wood = "#8a5a3c";
+
+function Box({ name, at, half, yaw = 0, color = wood }: { name: string; at: number[]; half: [number, number, number]; yaw?: number; color?: string }) {
+ return (
+ <Mesh3d name={name} transform={Transform.fromXyz(at[0], at[1], at[2]).withRotation(Quat.fromEuler("XYZ", 0, yaw, 0))}>
+ <Cuboid half_size={half} />
+ <StandardMaterial base_color={color} />
+ </Mesh3d>
+ );
+}
+
+/** An orb, as a note means one: what the Orb component draws, whatever its mesh is called. */
+function Orb({ name = "orb", at, size = 1 }: { name?: string; at: number[]; size?: number }) {
+ return (
+ <Mesh3d name={name} transform={Transform.fromXyz(at[0], at[1], at[2]).withScale([size, size, size])}>
+ <Sphere radius={0.25} />
+ <StandardMaterial base_color="#9fd8ff" />
+ </Mesh3d>
+ );
+}
+
+/** Four desks in a row, each with its chair on its front (+z) side, and a counter with a kettle. `turned` turns one
+ * desk round; `kettle: "desk"` sets the kettle on a desk; `desk` names the desks; `orb` puts an orb in. */
+export function Office({ turned, kettle = "counter", desk = "desk", orb }: { turned?: number; kettle?: "counter" | "desk"; desk?: string; orb?: "one" | "renamed" | "tiny" }) {
+ return (
+ <AbsoluteFill style={{ background: "#202630" }}>
+ <Camera3d transform={Transform.fromXyz(0, 6, 9).lookingAt([0, 0, 0])} />
+ <DirectionalLight illuminance={9000} transform={Transform.fromXyz(3, 6, 5).lookingAt([0, 0, 0])} />
+ {[-3, -1, 1, 3].map((x, i) => (
+ <Box key={`d${i}`} name={`${desk}-${i + 1}`} at={[x, 0.375, 0]} half={[0.7, 0.375, 0.4]} yaw={turned === i + 1 ? Math.PI : 0} />
+ ))}
+ {[-3, -1, 1, 3].map((x, i) => (
+ <Box key={`c${i}`} name={`chair-${i + 1}`} at={[x, 0.25, 0.9]} half={[0.25, 0.25, 0.25]} color="#333a44" />
+ ))}
+ <Box name="counter" at={[0, 0.45, -3]} half={[1.5, 0.45, 0.35]} color="#c9c2b6" />
+ <Box name="kettle" at={kettle === "desk" ? [1, 0.875, 0] : [0.5, 1.025, -3]} half={[0.12, 0.125, 0.12]} color="#d33" />
+ {orb === "one" && <Orb at={[4.5, 2.5, -2]} />}
+ {orb === "renamed" && <Orb name="lamp-glass" at={[4.5, 2.5, -2]} />}
+ {orb === "tiny" && <Orb at={[4.5, 2.5, -2]} size={0.0001} />}
+ </AbsoluteFill>
+ );
+}
+
+/** A point `[x, y, z]` of the chair's own space, turned by `yaw` about its seat at (0, 0.5, 0). */
+const on = (yaw: number, [x, y, z]: number[]) => Transform.fromXyz(x * Math.cos(yaw) + z * Math.sin(yaw), 0.5 + y, -x * Math.sin(yaw) + z * Math.cos(yaw)).withRotation(Quat.fromEuler("XYZ", 0, yaw, 0));
+
+/** A swivel chair turned by `yaw`, its back behind, and a computer on its seat at `at` in the chair's space, turned
+ * with it; `left` leaves the computer where it was on frame 0 (yaw 0.3) as the chair turns; `rider` names it. */
+export function Ride({ yaw, at, left, rider = "computer" }: { yaw: number; at: number[]; left?: boolean; rider?: string }) {
+ return (
+ <AbsoluteFill style={{ background: "#1d2430" }}>
+ <Camera3d transform={Transform.fromXyz(2.5, 2, 4).lookingAt([0, 0.8, 0])} />
+ <DirectionalLight illuminance={9000} transform={Transform.fromXyz(2, 4, 6).lookingAt([0, 0, 0])} />
+ <Mesh3d name="chair" transform={on(yaw, [0, 0, 0])}>
+ <Cuboid half_size={[0.3, 0.05, 0.3]} />
+ <StandardMaterial base_color={wood} />
+ </Mesh3d>
+ <Mesh3d name="chair-back" transform={on(yaw, [0, 0.45, -0.25])}>
+ <Cuboid half_size={[0.3, 0.4, 0.05]} />
+ <StandardMaterial base_color={wood} />
+ </Mesh3d>
+ <Mesh3d name={rider} transform={on(left ? 0.3 : yaw, at)}>
+ <Cuboid half_size={[0.2, 0.15, 0.15]} />
+ <StandardMaterial base_color="#3fa7ff" />
+ </Mesh3d>
+ </AbsoluteFill>
+ );
+}
+
+/** The singer: a cutout standing in for a person, drawn after the line so it is in front of it. */
+function Singer() {
+ return <div style={{ position: "absolute", left: 220, top: 250, width: 180, height: 710, borderRadius: "90px 90px 0 0", background: "#2b2b2b" }} />;
+}
+
+/** The lyric over the singer as flat type; `deep` sets it as 3D type a hair deep, facing the camera; `bare` leaves
+ * the singer out; `words` changes the line. */
+export function Lyric({ deep, bare, words = "OUT OF THE GREY" }: { deep?: boolean; bare?: boolean; words?: string }) {
+ if (deep) {
+ return (
+ <AbsoluteFill style={{ background: "#16202e" }}>
+ <Camera3d transform={Transform.fromXyz(0, 0, 6).lookingAt([0, 0, 0])} />
+ <DirectionalLight illuminance={9000} transform={Transform.fromXyz(0, 2, 6).lookingAt([0, 0, 0])} />
+ <Mesh3d name="line" transform={Transform.fromXyz(0, 1, 0)}>
+ <Text3D size={0.25} depth={0.002}>{words}</Text3D>
+ <StandardMaterial base_color="#ffffff" />
+ </Mesh3d>
+ </AbsoluteFill>
+ );
+ }
+ return (
+ <AbsoluteFill style={{ background: "#3a4a5e" }}>
+ <div style={{ position: "absolute", left: 60, top: 300, width: 420, fontSize: 64, fontWeight: 800, color: "#ffffff", lineHeight: 1.1 }}>{words}</div>
+ {!bare && <Singer />}
+ </AbsoluteFill>
+ );
+}
+
+/** A cut: a lead-in, then the reveal for `seconds`, named `name`. */
+export function Hold({ seconds, name = "reveal" }: { seconds: number; name?: string }) {
+ return (
+ <AbsoluteFill style={{ background: "#111" }}>
+ <Sequence from={0} durationInFrames={30} name="lead-in">
+ <AbsoluteFill style={{ background: "#2a3340" }} />
+ </Sequence>
+ <Sequence from={30} durationInFrames={Math.round(seconds * 30)} name={name}>
+ <AbsoluteFill style={{ background: "#c8a24a" }} />
+ </Sequence>
+ </AbsoluteFill>
+ );
+}
diff --git a/bench/direction/proof/checks/rider.ts b/bench/direction/proof/checks/rider.ts
index 9d7a1be1..da8df1c9 100644
--- a/bench/direction/proof/checks/rider.ts
+++ b/bench/direction/proof/checks/rider.ts
@@ -1,48 +1,15 @@
// A rider turns with its seat and is in no part of it (DR4's fifth proof: a 3D scene). The parts are named in the
// rule's values (`rider`; `seat`, and every part whose name starts with it is the seat's); their rotations are
-// compared, and each part's own box, turned as it is, is tested against the rider's. That the rider rides the seat
-// is DR16's Rides; until then the rule names them.
-import { check, found, type Part } from "raea/check";
+// compared, and each part's own box, turned as it is, is tested against the rider's (raea/check's `inside`). That the
+// rider rides the seat is DR16's Rides; until then the rule names them. DR6's worked check for "the seat turns with
+// the computer" (sdk/guides/craft/checks/rides.ts) holds its place and turn on the seat as well.
+import { check, found, inside, type Part } from "raea/check";
type V = number[];
-const dot = (u: V, v: V) => u[0] * v[0] + u[1] * v[1] + u[2] * v[2];
-const cross = (u: V, v: V) => [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]];
/** The angle between two rotations (x, y, z, w), in degrees. */
const turn = (a: V, b: V) => (2 * Math.acos(Math.min(1, Math.abs(a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]))) * 180) / Math.PI;
-/** A part as a box turned as it is: its centre, its axes and its half sizes along them, in world metres. A part with
- * no box of its own is its world box. */
-function box(p: Part): { c: V; axes: V[]; half: V } | null {
- if (!p.own) return p.min && p.max ? { c: [0, 1, 2].map((k) => (p.min![k] + p.max![k]) / 2), axes: [[1, 0, 0], [0, 1, 0], [0, 0, 1]], half: [0, 1, 2].map((k) => (p.max![k] - p.min![k]) / 2) } : null;
- const [lo, hi] = p.own;
- const [x, y, z, w] = p.rotation;
- // v turned by the part's rotation
- const rot = (v: V) => {
- const t = [2 * (y * v[2] - z * v[1]), 2 * (z * v[0] - x * v[2]), 2 * (x * v[1] - y * v[0])];
- return [v[0] + w * t[0] + (y * t[2] - z * t[1]), v[1] + w * t[1] + (z * t[0] - x * t[2]), v[2] + w * t[2] + (x * t[1] - y * t[0])];
- };
- const c = rot([0, 1, 2].map((k) => ((lo[k] + hi[k]) / 2) * p.scale[k])).map((v, k) => v + p.at[k]);
- return { c, axes: [[1, 0, 0], [0, 1, 0], [0, 0, 1]].map(rot), half: [0, 1, 2].map((k) => (Math.abs(hi[k] - lo[k]) / 2) * Math.abs(p.scale[k])) };
-}
-
-/** How far two turned boxes are in each other: the least overlap along the axes that could part them (0: apart). */
-function depth(a: NonNullable<ReturnType<typeof box>>, b: NonNullable<ReturnType<typeof box>>): number {
- const d = [0, 1, 2].map((k) => b.c[k] - a.c[k]);
- const axes = [...a.axes, ...b.axes, ...a.axes.flatMap((u) => b.axes.map((v) => cross(u, v)))];
- let least = Infinity;
- for (const ax of axes) {
- const len = Math.hypot(ax[0], ax[1], ax[2]);
- if (len < 1e-9) continue;
- const n = ax.map((v) => v / len);
- const reach = (o: typeof a) => o.half.reduce((s, h, k) => s + h * Math.abs(dot(o.axes[k], n)), 0);
- const overlap = reach(a) + reach(b) - Math.abs(dot(d, n));
- if (overlap <= 0) return 0;
- least = Math.min(least, overlap);
- }
- return least;
-}
-
export default check({ id: "rider", text: "a rider turns with its seat and is in no part of it" }, (world, _frame, values) => {
const parts = world.find({ with: ["Part"] });
const part = (id: number) => world.component<Part>(id, "Part")!;
@@ -55,11 +22,8 @@ export default check({ id: "rider", text: "a rider turns with its seat and is in
const most = Number(values.turn ?? 0.5);
if (deg > most) found({ about: [rider, seat], says: `the rider is turned ${deg.toFixed(1)} degrees from its seat`, measure: { name: "turn", value: Math.round(deg * 10) / 10, unit: "deg", limit: most } });
const into = Number(values.into ?? 0.01);
- const r = box(part(rider));
for (const s of parts.filter((p) => p !== rider && part(p).name.startsWith(String(values.seat)))) {
- const q = box(part(s));
- if (!r || !q) continue;
- const cm = depth(r, q);
+ const cm = inside(part(rider), part(s));
if (cm > into) found({ about: [rider, s], says: `the rider is ${Math.round(cm * 100)} cm into ${part(s).name}`, measure: { name: "into", value: Math.round(cm * 100), unit: "cm", limit: Math.round(into * 100) } });
}
});
diff --git a/core/facts/src/note.rs b/core/facts/src/note.rs
index 4dea67a8..07587084 100644
--- a/core/facts/src/note.rs
+++ b/core/facts/src/note.rs
@@ -18,7 +18,8 @@ pub struct Pin {
pub part: Option<String>,
}
-/// Where an ask that can't be measured is shown, for the person to sign (DR6): a shot or a range of frames.
+/// Where an ask that can't be measured is shown, for the person to sign (DR6): a shot or a range of frames (the frame
+/// after its last ends it) of the ask's composition, cut from its newest render.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(optional_fields)]
pub struct Proof {
@@ -42,6 +43,9 @@ pub struct Ask {
pub not: Vec<String>,
/// the craft verb this ask is (skills/skills/raea/craft/verbs): one per ask, not one per note
pub verb: Option<String>,
+ /// the composition it is about, its file from the project (its id after a `#` where the file registers several):
+ /// where its check runs and its clip is cut from; none: every composition of the project
+ pub of: Option<String>,
/// the check that shows it met (DR6): one of raea's by name, or a .ts check by its path, as a rule names one
pub check: Option<String>,
/// the values its check is held to
@@ -147,7 +151,7 @@ mod tests {
use super::*;
fn ask(text: &str, medium: Option<&str>, not: &[&str]) -> Ask {
- Ask { text: text.into(), medium: medium.map(Into::into), about: None, not: not.iter().map(|s| s.to_string()).collect(), verb: None, check: None, values: None, proof: None }
+ Ask { text: text.into(), medium: medium.map(Into::into), about: None, not: not.iter().map(|s| s.to_string()).collect(), verb: None, of: None, check: None, values: None, proof: None }
}
fn note(words: &str, asks: Vec<Ask>) -> Note {
diff --git a/core/facts/src/record.rs b/core/facts/src/record.rs
index 4a32995f..75280cf7 100644
--- a/core/facts/src/record.rs
+++ b/core/facts/src/record.rs
@@ -67,8 +67,8 @@ pub fn rel(project: &Path, p: &Path) -> String {
full.strip_prefix(project).map(|r| r.display().to_string()).unwrap_or_else(|_| full.display().to_string())
}
-/// The project's commit, with "+" when `of` differs from it.
-fn commit(project: &Path, of: &str) -> Option<String> {
+/// The project's commit, with "+" when `of` (a path from the project; "." for all of it) differs from it.
+pub fn commit(project: &Path, of: &str) -> Option<String> {
let git = |a: &[&str]| {
let o = std::process::Command::new("git").arg("-C").arg(project).args(a).output().ok()?;
o.status.success().then_some(String::from_utf8_lossy(&o.stdout).trim().to_string())
diff --git a/core/facts/src/rule.rs b/core/facts/src/rule.rs
index 2b158427..2886d83b 100644
--- a/core/facts/src/rule.rs
+++ b/core/facts/src/rule.rs
@@ -25,14 +25,18 @@ pub struct Rule {
/// how bad what it finds is (None: the check's own level, else an error)
#[serde(default, skip_serializing_if = "Option::is_none")]
pub level: Option<Level>,
- /// where it was written: "raea", or "taste", "workspace" or "project" and the file
+ /// where it was written: "raea", or "taste", "workspace" or "project" and the file; "note" and the ask's id
pub by: String,
+ /// the one composition it runs on, its file from the project (its id after a `#`), as a note's ask names it;
+ /// none: every composition
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub of: Option<String>,
}
impl Rule {
/// One of raea's checks by `name`, held to `values`.
pub fn named(name: &str, text: &str, values: Map<String, Value>, level: Level, by: &str) -> Rule {
- Rule { id: name.into(), text: text.into(), check: name.into(), values, level: Some(level), by: by.into() }
+ Rule { id: name.into(), text: text.into(), check: name.into(), values, level: Some(level), by: by.into(), of: None }
}
/// The project's .ts check this rule runs, when it runs one.
@@ -68,7 +72,7 @@ impl Rule {
false => (check.clone(), check.clone()),
};
let level = level.as_deref().map(Level::of_word);
- out.push(Rule { id, text: f.label.clone(), check, values: values.clone().unwrap_or_default(), level, by: by.into() });
+ out.push(Rule { id, text: f.label.clone(), check, values: values.clone().unwrap_or_default(), level, by: by.into(), of: None });
}
out
}
diff --git a/docs/direction.feature b/docs/direction.feature
index b3d8a6f1..884889ac 100644
--- a/docs/direction.feature
+++ b/docs/direction.feature
@@ -477,8 +477,77 @@ Feature: Direction that holds: one world of facts, findings and rules, so a pers
And the restated asks are posted back on the note in the app before work starts, where the person can correct
one in a word; a correction is a new line of the note, kept
- @needs:DR5
+ @needs:DR5 @done
Scenario: DR6. Each ask gets a check that fails now, or a clip to sign
+ # Status 11-10: built. An ask names its check (one of raea's by name, or a .ts check by its path from the note's
+ # folder), its values, the composition it is about (`of`) and, where it can't be measured, its proof, a clip to
+ # sign. `raea notes check` runs each ask's check as a rule through `raea check`'s run (apps/direction, lent by the
+ # CLI), only on the composition the ask names (Rule.of), and keeps what each ask has been through in
+ # .raea/notes-checks.json: a check whose first run passes is refused (exit 1); one that fails is kept with its
+ # values, and the work may change; a check changed after it failed is to be shown failing again. Each finding's
+ # `by` is its ask (note n1.2), so two asks running one check are counted apart, and `raea check` runs the notes'
+ # checks beside the rules, marking their findings with the ask. A clip is cut with ffmpeg from the composition's
+ # newest render (the shot's frames, or the ask's), again only when the render or the frames change, and nothing
+ # is cut from a render the composition changed after. The person's sign comes from the app's inbox with the
+ # render's sha256 and their name when signed in; `raea notes take` keeps the last one per ask. An ask reads to
+ # check, failing, to sign, passing or signed, the note its worst (to restate before any); `raea notes ls` says
+ # each, and `raea notes post` sends the badge, each ask's state and each clip to sign (`raea show --working
+ # --status --states`, `--sign N --clip --render`). raea/check gained a per-rule memo, `after` (run once past the
+ # last frame), `named`, `turned` and `inside`; five worked checks ship in sdk/guides/craft/checks, copied into the
+ # skill as craft/checks: rides, flat-type, faces, stands-on, shot-length, no-part.
+ # Run on: bench/direction/asks/asks.sh with this commit's raea, every case as expected (35). Each worked check
+ # passes its piece and fails every cheat (ride turned 33.2 degrees and moved 29 mm, 10 cm into the chair's back,
+ # the rider gone; the lyric 2 mm deep, with nothing in front of it, its words changed; a desk turned 180 degrees,
+ # the kettle on a desk, the desks renamed so neither check has anything to measure; the reveal 2.0 s, the shot
+ # renamed; an orb, renamed to lamp-glass, scaled tiny). The notes' flow on a project of its own: three notes said,
+ # restated, two failing first and one refused (its check named a part the office hasn't), that check fixed and
+ # failing, the work changed until all pass, the reveal's clip cut (4.0 s, 120 frames), a sign kept, and the
+ # shortened hold reopening it. And end to end in a copy of the raea app (0.1.0-dev.1109.87, its own state; the
+ # app side is raea-feed 5fa93c7 and 1317a9d): the hold shown, "Hold the reveal longer, and let me see it."
+ # written and sent in the page, taken, posted as "to restate", restated as a check and a clip, checked failing
+ # and posted ("failing", ask 2 "to check"), the hold made 4 s and rendered, checked passing, the clip posted
+ # under ask 2 with "Sign: this is what I asked for", the agent's --done refused ("cm-1 is a note: it closes when
+ # the person retires it, not when the agent marks it done"), signed in the page (the inbox line's render matched
+ # the clip's), taken and posted as passing; the hold shortened again read to check, and its new render's clip
+ # came back unsigned. I looked at the page at each step and at the clip's frames: the reveal alone, no lead-in.
+ # Proved by tests in raea-core-facts (16), raea-app-notes (10: post with states and clips, an ask's check failing
+ # first, refused, counted apart and run alone with --only, a changed check; signs named and unnamed, a newer
+ # render and a changed composition; no clip from a stale render; how an ask names its composition),
+ # raea-app-direction (16), raea-runtime-world (15: an element that covers is named by its component) and
+ # engine/cli/conformance/show.test.ts (5: what --status, --states and --sign send, and what's refused first).
+ # Not seen, or left: an agent restating a note and choosing its check on its own (I wrote the asks); a sign with
+ # a name (the copy had no account signed in); the pieces are flat colour and boxes, so no clip had motion to
+ # judge; the five checks name things by name, model file or component until DR11 and DR16 give them kinds and
+ # relations; and a person retiring a note is DR7's.
+ Given the plan
+ | crate | file | lines | job |
+ | raea-app-notes | apps/notes/src/check.rs | 260 | `raea notes check`: each ask's check run as a rule on the work as it stands (the CLI lends apps/direction's run); a first run that passes is refused |
+ | raea-app-notes | apps/notes/src/state.rs | 220 | what each ask has been through, in .raea/notes-checks.json: its check as it first failed, its last run, its clip and the person's sign; to check, failing, passing, to sign, signed |
+ | raea-app-notes | apps/notes/src/post.rs | 220 | each note's state on its comment in the app, and each clip to sign |
+ | raea-app-notes | apps/notes/src/take.rs | 300 | the person's signs from the app: their name and the render's hash |
+ | raea-app-direction | apps/direction/src/check.rs | 400 | the notes' asks as rules beside the others, each finding's `by` its ask; the notes' rules alone, for `raea notes check` |
+ | raea-core-facts | core/facts/src/note.rs | 260 | an ask's composition (Ask.of): where its check runs and its clip is cut from |
+ | raea-core-facts | core/facts/src/rule.rs | 200 | a rule held to one composition (Rule.of), as an ask's is |
+ | raea-runtime-world | runtime/world/src/covers.rs | 180 | a plain element that covers another is named by the component it was drawn in |
+ | raea-runtime-world | runtime/world/src/renders.rs | 300 | the composition's folder kept with its render, for that element's Source |
+ | raea-cli | engine/cli/src/cli.rs | 380 | `raea notes` lent apps/direction's run |
+ And engine/cli/src/show.ts: `--status S --states S1,S2` with `--working` (the note's state for the badge, and each
+ ask's) and `--sign N --clip FILE --render HASH` (a clip for the person to sign under ask N); sdk/raea/src/check.ts: a check's memo, kept
+ across its frames, and its `after`, run once past its last frame (a shot that runs to its end is measured, and
+ a part the ask names that no frame has is found, not passed); `named(world, id, kinds)`, how a check names a
+ part, a shot or a layer until DR11's taxonomy; and the worked checks, each a .ts file in
+ sdk/guides/craft/checks (copied into the skill as craft/checks), with a piece that holds it and a cheat in
+ bench/direction/asks, run by its asks.sh
+ # Fixed in the code (DR6): the worked checks' table had two rows whose facts no world holds yet. "this is low
+ # poly" is DR14's detail floor, measured at a component's `seenFrom` (DR11's meta); "the light isn't timed to the
+ # cut" needs the subject's own pixels in the render, which for a 3D or footage subject is DR19's mask. Each row
+ # moves to that scenario and ships with its cheat there. The other five are built on the world as it is, the
+ # parts named in the ask's values (by name, model file or component) until DR11's taxonomy and DR16's relations
+ # say them: the rider's offset and turn are held to the seat's as on its first frame until DR16 gives it a
+ # socket, and no part of the rider is inside a part of the seat (box in box: a 3D part is in no Covers); a front
+ # is the model's own axis given in the values until DR11 measures it, and StandsOn is measured from the boxes (a
+ # bottom on a top, inside its footprint) until DR16 declares it; "occlusion" is a cover by the subject where the
+ # render has one (a page layer), and a 3D or footage subject is DR19's.
Then an ask's check is a system (DR4) written in the note's file or named from raea's, and `raea notes check`
must show it failing on the work as it stands before the work may change (a check that already passes is
refused: it isn't measuring the ask)
@@ -487,8 +556,14 @@ Feature: Direction that holds: one world of facts, findings and rules, so a pers
apart (the prototype counted both asks' findings against each until it did)
And where the ask can't be measured, its proof is a clip: `proof: { shot | frames, sign: true }`; it passes only
when the person marks it in the app (their name, the render's hash), and reopens when its source changes
- And the app's task badge (R3) reads: to restate, to check, failing, passing, signed; "done" is never typed by
- the agent
+ And the app's task badge (R3) reads: to restate, to check, failing, to sign, passing, signed; "done" is never
+ typed by the agent
+ # Fixed in the code (DR6): "to sign" is added: a clip waiting on the person is neither the agent's to check nor
+ # passing, and the badge says whose move it is: a clip not cut yet, or cut from a render that's no longer the
+ # work, is the agent's (to check), as the app copy showed when "yours to sign" sat on an ask with no clip. And an ask names its composition (Ask.of), not only its clip:
+ # a project holds several, and an ask about the office's desks run on the hold's shots finds nothing there to
+ # measure and passes, so it would be refused for the wrong reason. Its check runs only where it applies (Rule.of;
+ # a controller's rules leave it unset and run everywhere, as before), and its clip is cut from that composition's newest render.
And worked checks ship in the skill for the asks that recur, each with its cheat:
| the ask, as a person says it | the check |
| "the seat turns with the computer" | Rides: offset and turn from its socket every frame; no Covers of the rider by the seat's parts |
@@ -496,8 +571,6 @@ Feature: Direction that holds: one world of facts, findings and rules, so a pers
| "desks face the wrong way", "kitchen props on a desk" | every Part's `meta.front` toward what it serves; no Part of kind X StandsOn kind Y |
| "hold this longer" | the Shot is at least N seconds |
| "no orbs anywhere" | no Part of the named component in any frame |
- | "this is low poly", "more detail" | the component passes its detail floor at its nearest (DR14) |
- | "the light isn't timed to the cut" | the lit share of the subject crosses its half within a frame of the cut |
@needs:DR6
Scenario: DR7. Rounds hold
@@ -595,6 +668,8 @@ Feature: Direction that holds: one world of facts, findings and rules, so a pers
parts, its triangles and edge detail against that share, its surface detail (textures, or shader detail), and
whether it is one primitive or a few; under the floor is a finding, and the stage doesn't close
And the floor is a rule (DR8) a project can raise, never an agent
+ And the worked check for a note's "this is low poly", "more detail" ships in the skill with its cheat (moved
+ here from DR6, whose world had no `seenFrom`): the component passes its detail floor at its nearest
And how a component is made follows the skill's routing (built in code when exact, a permissive library, or
generated), and a spend or a download is the person's yes, asked once for the stage with its quote
And the stage's time is the largest in the plan the agent gives: a brief with twelve places says so before
@@ -671,6 +746,10 @@ Feature: Direction that holds: one world of facts, findings and rules, so a pers
And an element's medium is recorded on its Layer and its Text, so a note's ask (DR5) can check it: extruded
letters fail an ask that said 2D, flat ones fail an ask that said 3D
And the skill's core says: the scene being 3D decides nothing about a title, a lyric or a graphic
+ And with the subject's own pixels in the render, two of DR6's worked checks ship with their cheats (moved here
+ from DR6, whose render had no mask of a 3D or footage subject): "2D text with occlusion" MaskedBy a 3D or
+ footage subject where they meet, and "the light isn't timed to the cut": the lit share of the subject crosses
+ its half within a frame of the cut
# =====================================================================================================================
Rule: Part 8. Review in motion and in sound (finding 7)
diff --git a/docs/manual/reference/cli/notes.md b/docs/manual/reference/cli/notes.md
index 73e779aa..e1974a4e 100644
--- a/docs/manual/reference/cli/notes.md
+++ b/docs/manual/reference/cli/notes.md
@@ -2,7 +2,7 @@
title: "raea notes"
summary: "A person's notes as files the work is held to: each taken word for word, then restated as asks before anything changes."
order: 124
-sources: ["apps/notes/src/lib.rs", "apps/notes/src/take.rs", "apps/notes/src/post.rs", "core/facts/src/note.rs", "sdk/raea/src/note.ts"]
+sources: ["apps/notes/src/lib.rs", "apps/notes/src/take.rs", "apps/notes/src/post.rs", "apps/notes/src/check.rs", "apps/notes/src/state.rs", "core/facts/src/note.rs", "sdk/raea/src/note.ts"]
---
A note can hold several things, and a note that is only patched gets one of them answered. `raea notes take` writes
@@ -20,6 +20,7 @@ raea notes take
raea notes take --said "hold the end card a second longer"
raea notes ls
raea notes post
+raea notes check
```
```ts
@@ -32,27 +33,52 @@ export default note({
round: 1,
pin: { t: 12.4, x: 0.52, y: 0.31 },
asks: [
- { text: "each lyric line is flat type, masked by the singer where they meet", medium: "2D", about: "lyric", not: ["the camera"] },
- { text: "each lyric arrives word by word on its sung time", medium: "2D", about: "lyric", not: ["the font"] },
+ { text: "each lyric line is flat type, masked by the singer where they meet", medium: "2D", about: "lyric", not: ["the camera"],
+ of: "edit.tsx", check: "../../checks/flat-type.ts", values: { words: "out of the grey", subject: "component:Singer" } },
+ { text: "each lyric arrives word by word on its sung time", medium: "2D", about: "lyric", not: ["the font"],
+ of: "edit.tsx", proof: { shot: "chorus", sign: true } },
],
});
```
-`raea notes ls` says where each note stands (to restate; then to check, until each ask has a check that holds it)
-and what its restatement still owes: a second reading where several sentences became one ask, a medium its words name
-that no ask asks for or turns down, and what a redesign keeps. It exits 1 when a note's file can't be read.
+Each ask is then held by a check, or by a clip the person signs. A check is a system over the world, as a rule's is
+(`raea check`): one of raea's by name, or a `.ts` check by its path from the note's folder, with its `values`. The
+skill carries worked ones in `craft/checks` (a part that rides a seat, flat type with the subject in front of it, a
+part facing what it serves, nothing of one kind standing on another, a shot held N seconds, no part of a kind);
+copy one into the project's `checks/`. `of` names the composition the ask is about, its file from the project
+(`#ID` after it where the file registers several): its check runs only there. Where an ask can't be measured, its
+proof is a clip: `proof: { shot, sign: true }` (or `frames: [from, to]`).
-`raea notes post` shows each restated note's asks back on its comment in the raea app, before the work starts, and
-posts none whose restatement still owes something. The person reads them there and can correct one in a word. The
+`raea notes check` runs each ask's check on the work as it stands. A check must fail before the work changes: one that
+passes on its first run is refused, since it isn't measuring the ask, and the command exits 1. Once it has failed, the
+work may change until it passes. A check changed after it failed is to be shown failing again. The check also cuts
+each clip the person is to sign from its composition's newest render (`.raea/notes-clips/ID.mp4`, cut again only when
+the render or the frames change). `raea check` runs the notes' checks beside the project's rules, and each finding
+says which ask it is for (`[note n1.2]`), so two asks that use one check are told apart.
+
+`raea notes ls` says where each note and each of its asks stands, and what its restatement still owes: a second
+reading where several sentences became one ask, a medium its words name that no ask asks for or turns down, and what
+a redesign keeps. An ask is to check (no check or clip yet, its check not yet shown failing, or its clip from a
+render that's no longer the work: each the agent's move), failing, to sign (its clip waits on the person), passing
+or signed; a note reads its asks' worst, and to
+restate before any. What each ask has been through is kept in `.raea/notes-checks.json`. It exits 1 when a note's
+file can't be read.
+
+`raea notes post` shows each note on its comment in the raea app: its asks once it's restated with nothing owed, where
+it stands on the comment's badge (to restate, to check, failing, to sign, passing, signed) and each ask's, and each
+clip to sign under its ask. A note shown so already isn't shown again. The person can correct an ask in a word: the
next `raea notes take` writes their correction into the note as a new line of its words, kept, and lists the ask it
-corrected in `corrected`, so the note is to restate again until that ask is restated and taken off the list.
+corrected in `corrected`, so the note is to restate again until that ask is restated and taken off the list. They
+sign a clip in the app, and the next take keeps their sign with the render they watched; a newer render's clip is to
+sign again, and a composition changed after its render is to check until it's rendered again. A note is never marked done by the agent: it closes when the
+person retires it.
<!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions -->
## Usage
```sh
-raea notes take [PROJECT] [--inbox NAME] [--said WORDS]... | raea notes ls [PROJECT] [--json] | raea notes post [PROJECT] (a person's notes as files the work is held to: take writes each note sent from the raea app or said in a session to notes/ROUND/ID.ts, the words verbatim, to be restated as asks before anything changes, and writes in each correction the person made to a restatement; ls says where each note stands, to restate or to check, and what its restatement still owes; post shows each restated note's asks on its comment in the raea app, for the person to correct)
+raea notes take [PROJECT] [--inbox NAME] [--said WORDS]... | raea notes check [PROJECT] [--composition ID] [--render OUT | --no-render] | raea notes ls [PROJECT] [--json] | raea notes post [PROJECT] (a person's notes as files the work is held to: take writes each note sent from the raea app or said in a session to notes/ROUND/ID.ts, the words verbatim, to be restated as asks before anything changes, and writes in each correction and sign the person sent back; check runs each ask's check on the work as it stands, which must fail before the work changes (a check that passes first is refused), and cuts each clip the person is to sign from the newest render; ls says where each note and ask stands (to restate, to check, failing, to sign, passing, signed) and what its restatement still owes; post shows each note's asks and where they stand on its comment in the raea app, and each clip to sign)
```
Needs the raea app's host running on this machine (to show post's asks on the person's comments; take and ls run headless). Takes up to 2 arguments besides its flags.
@@ -61,8 +87,11 @@ Needs the raea app's host running on this machine (to show post's asks on the pe
| Flag | Takes | What it does |
| --- | --- | --- |
+| `--composition` | `ID` | With `check`: check one composition of the project instead of every one. |
| `--inbox` | `NAME` | With `take`: read only this inbox, `~/.raea/inbox/NAME.jsonl` (`RAEA_INBOX_DIR` moves the folder); every inbox when left out. |
| `--json` | – | With `ls`: each note as JSON, with its file, its state and what its restatement still owes. |
+| `--no-render` | – | With `check`: join no render, so the checks that need one wait and no clip is cut. |
+| `--render` | `OUT` | With `check`: join this render instead of the composition's newest in the project's record. |
| `--said` | `WORDS` | With `take`: a note the person said in this session, taken as written; give it once per note. |
<!-- generated:end -->
diff --git a/docs/manual/reference/cli/show.md b/docs/manual/reference/cli/show.md
index 999557b4..22dccb36 100644
--- a/docs/manual/reference/cli/show.md
+++ b/docs/manual/reference/cli/show.md
@@ -23,7 +23,11 @@ The person's edit comments are tasks they watch. The inbox line that carries the
--working ID` marks one as being worked (with `--sub NAME` when a subagent has it), and `--done ID` marks it settled,
or, with files and `--replaces`, settled by that version. Done stays in view, checked, until the person resolves it.
Each `--ask` with `--working` is one ask you read the comment as, shown on it so the person can correct your reading
-before the work starts; `raea notes post` sends a restated note's asks this way.
+before the work starts. `--status` is where the note stands, on the comment's badge, and `--states` each ask's, in
+order (to restate, to check, failing, to sign, passing, signed). `--sign N --clip FILE --render HASH` shows a clip
+under ask N for the person to sign, cut from the render whose sha256 is HASH; their sign comes back to the inbox. A
+comment read as asks is a note: it closes when the person retires it, and the app refuses `--done` on it.
+[`raea notes post`](notes.md) sends all of these from the project's notes.
```sh
raea show out/look-1.png out/look-2.png out/look-3.png --ask "Which of these three?"
@@ -32,6 +36,8 @@ raea show --question "Warmer or cooler grade?" --choice Warmer --choice Cooler
raea show --question "Which opening?" --choice Slam --preview out/slam.mp4 --choice Drift --preview out/drift.mp4 \
--question "Narrator speed?" --preview voice/take.mp3 --choice "As is" --choice Faster
raea show --on i-show-2f9c --working c-3 --sub "grade pass"
+raea show --on i-show-2f9c --working cm-4 --ask "the lyric is flat type" --ask "it arrives word by word" \
+ --status failing --states "failing,to check"
raea show out/cut-v2.mp4 --replaces i-show-2f9c --done c-3 --done c-4 --note "Warmer grade, title held a beat longer"
```
@@ -40,7 +46,7 @@ raea show out/cut-v2.mp4 --replaces i-show-2f9c --done c-3 --done c-4 --note "Wa
## Usage
```sh
-raea show FILE... [--title T] [--ask LINE] [--project P] [--replaces ITEM] [--as NAME] [--role ROLE] [--inbox NAME] [--open] | raea show --question Q --choice A --choice B [STILL...] | raea show [--title T] --question Q [--preview FILE] --choice A [--preview FILE] --choice B ... [--question Q2] ... | raea show --on ITEM [--working ID] [--ask TEXT] [--done ID] [--note LINE] [--sub NAME] (shown in the raea app as an item the person can use and answer, posted quietly with a notice, the window left where they are unless --open: stills (several, a storyboard), a video, a sound, a NAME.script.ts or .md, a .tsx (an interactive artifact; a project's composition opens in its editor), or questions, all of them one item, each question and choice with a --preview to play or read while answering (a still, a video, a sound, a script or .md; after a --choice that choice's, else the question's); what they send comes to ~/.raea/inbox/INBOX.jsonl; their edit comments are tasks: --working ID as you start one (each --ask with it one ask you read it as, for the person to correct), --done ID when it's settled, or with the version that settles it, FILE --replaces ITEM --done ID; never open media in Preview while the app is installed)
+raea show FILE... [--title T] [--ask LINE] [--project P] [--replaces ITEM] [--as NAME] [--role ROLE] [--inbox NAME] [--open] | raea show --question Q --choice A --choice B [STILL...] | raea show [--title T] --question Q [--preview FILE] --choice A [--preview FILE] --choice B ... [--question Q2] ... | raea show --on ITEM [--working ID] [--ask TEXT] [--status S] [--states S1,S2] [--sign N --clip FILE --render HASH] [--done ID] [--note LINE] [--sub NAME] (shown in the raea app as an item the person can use and answer, posted quietly with a notice, the window left where they are unless --open: stills (several, a storyboard), a video, a sound, a NAME.script.ts or .md, a .tsx (an interactive artifact; a project's composition opens in its editor), or questions, all of them one item, each question and choice with a --preview to play or read while answering (a still, a video, a sound, a script or .md; after a --choice that choice's, else the question's); what they send comes to ~/.raea/inbox/INBOX.jsonl; their edit comments are tasks: --working ID as you start one (each --ask with it one ask you read it as, for the person to correct; --status and --states where the note and each ask stand: to restate, to check, failing, to sign, passing, signed; --sign N --clip FILE --render HASH a clip under ask N for them to sign; a note closes when they retire it, never with --done), --done ID when it's settled, or with the version that settles it, FILE --replaces ITEM --done ID; never open media in Preview while the app is installed)
```
Needs the raea app's host running on this machine; then waits for a person's click in the raea app (to answer). Takes any number of arguments besides its flags.
@@ -52,6 +58,7 @@ Needs the raea app's host running on this machine; then waits for a person's cli
| `--as` | `NAME` | Who's showing it, as the feed names them (your harness's name when left out: Claude Code, Codex, Gemini). |
| `--ask` | `LINE` | What you want from the person, shown with the item. With `--on` and `--working`: one ask you read the comment as (give it once per ask), shown on the comment for the person to correct. |
| `--choice` | `A` | With `--question`: one answer to pick; give it once per answer. Stills given instead are the choices. |
+| `--clip` | `FILE` | With `--sign`: the clip the person is to sign, cut from the render (`raea notes check` cuts it). |
| `--done` | `ID` | Marks the person's edit comment done (give it once per comment), on the item named by `--on`, or with files on the item they `--replaces`. |
| `--inbox` | `NAME` | The inbox the answers go to, `~/.raea/inbox/NAME.jsonl` (one per session when left out). |
| `--note` | `LINE` | With `--done`: a line for the person on what settled it, shown under the comment. |
@@ -60,8 +67,12 @@ Needs the raea app's host running on this machine; then waits for a person's cli
| `--preview` | `FILE` | A still, video, sound, script or `.md` the person can play or read while answering. After a `--choice` it is that choice's preview, otherwise the question's. |
| `--project` | `P` | The project to post to: its id, title or `Workspace/project`. The project this folder is in when left out. |
| `--question` | `Q` | Ask the person this, with `--choice` answers or stills to pick from. |
+| `--render` | `HASH` | With `--sign`: the sha256 of the render the clip was cut from, which the person's sign names. |
| `--replaces` | `ITEM` | The item this is the next version of, so the feed shows it as that item's new version. |
| `--role` | `ROLE` | With `--as`: the role shown beside the name. |
+| `--sign` | `N` | With `--working` on one comment: shows a clip under ask N for the person to sign; give `--clip` and `--render` with it. |
+| `--states` | `S1,S2` | With `--working` and `--ask`: each ask's state, in order, one for each ask (to restate, to check, failing, to sign, passing, signed). |
+| `--status` | `S` | With `--working`: where the note stands, on the comment's badge: to restate, to check, failing, to sign, passing or signed. |
| `--sub` | `NAME` | With `--working` or `--done`: the subagent on those comments, shown beside your name when several split them. |
| `--title` | `T` | The item's title in the feed. |
| `--working` | `ID` | Marks the person's edit comment as being worked (give it once per comment), on the item named by `--on`. |
diff --git a/docs/manual/reference/sdk/check.md b/docs/manual/reference/sdk/check.md
index bff984df..935eeb35 100644
--- a/docs/manual/reference/sdk/check.md
+++ b/docs/manual/reference/sdk/check.md
@@ -31,22 +31,58 @@ export default check({ id: "caption", text: "a caption clears the platform's but
});
```
+A check keeps what it needs from frame to frame in its `memo` (empty on the first frame, and each rule's own, so two
+asks that run one check don't share it), and its `after` runs once past the last frame with that memo: for what only
+the whole run can say, such as how long a shot held, or that no frame had the part the check was about (a check that
+finds nothing to measure must say so, or it passes for the wrong reason). A finding from `after` names what it is
+about by name, since there is no world then. `named(world, id, kinds)` is how a check finds what its values name: a
+part's, shot's or layer's name or a model file's, as written or as its start, in any case (`desk` is `desk-3` and
+`Desk.glb`), `component:Orb` for what the Orb component drew, `file:props/orb.glb` for that model. `turned(q, v)`
+turns a vector by a part's rotation, and `inside(a, b)` says how far two parts are in each other, in metres, from
+their own boxes turned as they are. A note's ask names its check the same way a rule does
+([`raea notes`](../cli/notes.md)); the skill carries worked checks in `craft/checks`.
+
+```ts
+// checks/shot-length.ts (the skill's craft/checks has it in full): a shot held at least N seconds
+import { check, found, type Shot } from "raea/check";
+
+export default check(
+ { id: "shot-length", text: "the shot holds long enough" },
+ (world, frame, values, memo) => {
+ memo.fps ??= (world.resource("Frame") as { fps: number }).fps;
+ for (const s of world.find({ with: ["Shot"] })) {
+ const shot = world.component<Shot>(s, "Shot")!;
+ if (shot.name !== String(values.shot)) continue;
+ memo.shot ??= { from: shot.from, to: shot.to ?? null, last: frame };
+ memo.shot.last = frame;
+ }
+ },
+ (values, memo) => {
+ if (!memo.shot) return found({ says: `no shot is named ${values.shot}`, fix: "name the shot's Sequence as the ask does" });
+ const end = memo.shot.to ?? memo.shot.last + 1;
+ const secs = (end - memo.shot.from) / memo.fps;
+ if (secs < Number(values.seconds)) found({ about: [String(values.shot)], frames: [memo.shot.from, end], says: `the shot ${values.shot} is ${secs.toFixed(1)} s, under ${values.seconds} s` });
+ },
+);
+```
+
<!-- generated:begin by tools/manual-ref/sdk.ts from the SDK's exports and doc comments; edit outside this block -->
```ts
-import { check, declared, found, runChecks } from "raea/check"
+import { check, declared, found, inside } from "raea/check"
```
-`raea/check` exports 5 functions, 1 class, 36 types. Source: [sdk/raea/src/check.ts](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/src/check.ts).
+`raea/check` exports 8 functions, 1 class, 38 types. Source: [sdk/raea/src/check.ts](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/src/check.ts).
## Functions
### `check`
-A check: what it holds the work to, and the system that finds where the work doesn't hold.
+A check: what it holds the work to, the system that finds where the work doesn't hold, and what it says once the
+frames are run.
```ts
-function check(meta: CheckMeta, run: CheckFn): Check
+function check(meta: CheckMeta, run: CheckFn, after?: AfterFn): Check
```
### `declared`
@@ -65,6 +101,26 @@ Says what the running check found. Only inside a check's system, as raea check r
function found(f: Found): void
```
+### `inside`
+
+How far two parts are in each other, in metres: the least overlap of their own boxes, turned as they are, along
+the axes that could part them (0: apart, or a part with no box).
+
+```ts
+function inside(a: Part, b: Part): number
+```
+
+### `named`
+
+Whether entity `id` is one of `kinds` (a list, or one string of them split at commas): a bare kind is a part's,
+shot's or layer's name or a model file's, as written or as its start ("desk" is desk-3 and Desk.glb), any case;
+`component:Orb` is what the Orb component drew, and `file:props/orb.glb` what that model file is. Until a
+component's taxonomy says what a thing is, an ask's check names it this way.
+
+```ts
+function named(world: World, id: number, kinds: string | string[] | undefined): boolean
+```
+
### `runChecks`
Every planned check run on its frames' worlds: what they found, a run of frames finding the same thing as one
@@ -74,6 +130,14 @@ finding over those frames, and each check that threw, with what it threw.
function runChecks(checks: Check[], plan: Planned[], worlds: Facts[]): { findings: Finding[]; threw: { check: string; says: string; }[]; }
```
+### `turned`
+
+`v` turned by a rotation `q` (x, y, z, w), as a part's `rotation` turns its own space into the world's.
+
+```ts
+function turned(q: number[], v: number[]): number[]
+```
+
### `worldOf`
A frame's facts as a raea/ecs world: the same components, the frame's size and rate as the `Frame` resource, and
@@ -128,6 +192,15 @@ A world of entities: rows in tables by kind.
type About = { name: string, key?: string, }
```
+### `AfterFn`
+
+Run once after the last frame, with what the frames kept: for what only the whole run can say (how long a shot
+held, that no frame had the part an ask is about). A finding here has no frames unless it gives them.
+
+```ts
+type AfterFn = (values: Values, memo: Memo) => void
+```
+
### `Ask`
```ts
@@ -145,6 +218,7 @@ type Camera = { eye: [number, number, number], look: [number, number, number], /
| Field | Type | What it is |
| --- | --- | --- |
| `run` (required) | `CheckFn` | its system, run on each frame it ranges over |
+| `after` | `AfterFn` | run once past its last frame |
| `id` (required) | `string` | what `raea check --only` names, and its findings' check |
| `text` (required) | `string` | the line it holds the work to |
| `needs` | `"render"` | "render": it reads what only a render has (Contrast, Picture, Mix, Onset, Covers); with none, it waits for one |
@@ -153,10 +227,10 @@ type Camera = { eye: [number, number, number], look: [number, number, number], /
### `CheckFn`
-The system: a frame's world, the frame, and the rule's values.
+The system: a frame's world, the frame, the rule's values, and what this run has kept.
```ts
-type CheckFn = (world: World, frame: number, values: Values) => void
+type CheckFn = (world: World, frame: number, values: Values, memo: Memo) => void
```
### `CheckMeta`
@@ -226,7 +300,7 @@ are.
| Field | Type | What it is |
| --- | --- | --- |
-| `about` | `number[]` | the entities it is about, by their ids in this frame's world |
+| `about` | `(number \| string)[]` | the entities it is about, by their ids in this frame's world, or by name (a check's `after` has no world) |
| `says` (required) | `string` | what is wrong, in a line a person reads |
| `level` | `Level` | its level, where it isn't its rule's or its check's |
| `frames` | `[number, number]` | its first frame and the frame after its last (this frame alone when unset) |
@@ -272,6 +346,15 @@ type Measure = { name: string, value: number, unit: string, limit?: number, }
type Medium = "2d-type" | "2d-graphic" | "3d" | "footage" | "page"
```
+### `Memo`
+
+What one rule's run of a check keeps from frame to frame: empty on its first frame, its own (two asks that run
+one check each have theirs).
+
+```ts
+type Memo = Record<string, any>
+```
+
### `Mix`
```ts
@@ -359,7 +442,7 @@ type Text = { words: string, font?: string, /** * its letters' height in px of a
### `Values`
-A rule's values for its check (a controller's `values`).
+A rule's values for its check (a controller's `values`, an ask's).
```ts
type Values = Record<string, number | string | boolean>
diff --git a/docs/manual/reference/sdk/index.md b/docs/manual/reference/sdk/index.md
index 847b2129..98f3dbb2 100644
--- a/docs/manual/reference/sdk/index.md
+++ b/docs/manual/reference/sdk/index.md
@@ -93,7 +93,7 @@ Checks, lints and a headless App you can drive.
| Import | What it's for | Exports |
| --- | --- | --- |
-| [`raea/check`](check.md) | A check written as a system over a composition's world: what `raea check` runs for a rule a controller holds. | 5 functions, 1 class, 36 types |
+| [`raea/check`](check.md) | A check written as a system over a composition's world: what `raea check` runs for a rule a controller holds. | 8 functions, 1 class, 38 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 |
diff --git a/engine/cli/conformance/show.test.ts b/engine/cli/conformance/show.test.ts
new file mode 100644
index 00000000..1b5680c0
--- /dev/null
+++ b/engine/cli/conformance/show.test.ts
@@ -0,0 +1,56 @@
+// `raea show --on ITEM --working ID`: what a session sends the raea app's host for the person's comments (docs/review.feature
+// R3), and where a note read from one stands (docs/direction.feature DR5, DR6): its asks, its badge and each ask's,
+// and a clip under an ask for the person to sign. The host (apps/app/host/tasks.ts) is faked: this is the command's side.
+import { describe, expect, test } from "bun:test";
+import { showVerb } from "../src/show.ts";
+
+/** showVerb with a host that keeps each op it was asked, and answers a task as the host does. */
+function run(args: string[]) {
+ const ops: [string, Record<string, unknown>][] = [];
+ const ask = (op: string, b: Record<string, unknown>) => {
+ ops.push([op, b]);
+ if (op === "harness") return { name: "Claude Code", pid: 7 };
+ return { item: b.item, project: "shop", comments: b.comments, state: b.state };
+ };
+ const out = showVerb(ask, args, "/work/shop", { CLAUDECODE: "1", CLAUDE_CODE_SESSION_ID: "abcdef123" });
+ return { out, tasks: ops.filter(([op]) => op === "task").map(([, b]) => b) };
+}
+
+const HASH = "a".repeat(64);
+
+describe("raea show --working, for a note", () => {
+ test("a note to restate goes with its badge and no asks", () => {
+ const { out, tasks } = run(["--on", "i-show-1", "--working", "cm-1", "--status", "to restate"]);
+ expect(tasks).toHaveLength(1);
+ expect(tasks[0]).toMatchObject({ item: "i-show-1", comments: ["cm-1"], state: "working", status: "to restate" });
+ expect(tasks[0].asks).toBeUndefined();
+ expect(out).toBe(`Marked cm-1 working on i-show-1: the person sees Claude Code on them; it reads "to restate".\n`);
+ });
+
+ test("its asks go with the note's badge and each ask's", () => {
+ const { out, tasks } = run(["--on", "i-show-1", "--working", "cm-1", "--ask", "the lyric is flat type", "--ask", "it arrives as a lyric video's", "--status", "to check", "--states", "to check, failing"]);
+ expect(tasks[0]).toMatchObject({ asks: ["the lyric is flat type", "it arrives as a lyric video's"], status: "to check", states: ["to check", "failing"] });
+ expect(out).toContain(`it reads "to check" (its asks: to check, failing).`);
+ });
+
+ test("a clip to sign goes under its ask, its path made whole", () => {
+ const { out, tasks } = run(["--on", "i-show-1", "--working", "cm-1", "--sign", "2", "--clip", ".raea/notes-clips/n1.2.mp4", "--render", HASH]);
+ expect(tasks[0]).toMatchObject({ state: "working", sign: { ask: 2, clip: "/work/shop/.raea/notes-clips/n1.2.mp4", render: HASH } });
+ expect(out).toBe(`Shown ask 2's clip on cm-1 of i-show-1 for the person to sign (render aaaaaaaaaaaa…): their sign comes to the inbox, and raea notes take keeps it.\n`);
+ });
+
+ test("a mark without these sends none of them, as before", () => {
+ const { tasks } = run(["--on", "i-show-1", "--working", "cm-1", "--done", "cm-2"]);
+ expect(tasks.map((t) => [t.state, t.status, t.states, t.sign])).toEqual([["working", undefined, undefined, undefined], ["done", undefined, undefined, undefined]]);
+ });
+
+ test("what doesn't fit is said before anything reaches the app", () => {
+ const refused = (args: string[], says: string) => expect(() => run(["--on", "i-show-1", ...args])).toThrow(says);
+ refused(["--done", "cm-1", "--status", "passing"], "--status, --states and --sign go with --working");
+ refused(["--working", "cm-1", "--working", "cm-2", "--sign", "1", "--clip", "/c.mp4", "--render", HASH], "--sign N shows one comment's clip");
+ refused(["--working", "cm-1", "--sign", "1", "--clip", "/c.mp4"], "--sign N shows one comment's clip");
+ refused(["--working", "cm-1", "--sign", "1", "--clip", "/c.mp4", "--render", HASH, "--done", "cm-2"], "--sign N shows one comment's clip");
+ refused(["--working", "cm-1", "--clip", "/c.mp4"], "--clip and --render go with --sign N");
+ refused(["--working", "cm-1", "--ask", "one", "--states", "to check,failing"], "one state for each --ask: 1 asks, 2 states");
+ });
+});
diff --git a/engine/cli/src/cli.rs b/engine/cli/src/cli.rs
index c262c21f..c64eb1aa 100644
--- a/engine/cli/src/cli.rs
+++ b/engine/cli/src/cli.rs
@@ -101,6 +101,12 @@ pub fn traces(args: &[String]) -> R<String> {
Ok(out)
}
+/// `raea check`'s host (the TS evaluator, the bundle runner, taste's kinds), which runs the notes' asks too (DR6).
+const CHECK: raea_app_direction::check::Host = raea_app_direction::check::Host { ts: raea_app_direction::ts::Host { eval: spec::spec_json, run: run_bundle }, kinds: taste_kinds };
+fn notes_run(project: &Path, rules: &[raea_app_notes::check::Rule], args: &[String], whole: bool) -> R<Vec<raea_app_notes::check::Ran>> {
+ raea_app_direction::check::run(project, rules, args, whole, &CHECK)
+}
+
/// `raea run SCRIPT.ts`: a TypeScript program against the engine, headless (the native calls: solids, ECS
/// worlds, print). The script's default export, if a function, is called; what it prints goes to stdout; a throw
/// ends the run with exit 1.
@@ -127,7 +133,7 @@ pub fn run(args: &[String]) -> R<String> {
IN_HELP.set(was);
// `raea library` (engine/cli/src/library.ts) and `raea show` (show.ts: in the raea app, not Preview, Shane 11-09), under render's usage
let usage = format!("{usage}\n raea library [new NAME [--cloud] | add LIBRARY PATH | files LIBRARY | tag SHA TAGS | status | scan ...] | raea library search \"WORDS\" [--library LIBRARY] [--kind KIND] [--limit N] [--sound] (the person's libraries in the raea app: folders and drives indexed on this machine, searched by meaning; a folder an agent adds waits for the person's yes)");
- let usage = format!("{usage}\n raea show FILE... [--title T] [--ask LINE] [--project P] [--replaces ITEM] [--as NAME] [--role ROLE] [--inbox NAME] [--open] | raea show --question Q --choice A --choice B [STILL...] | raea show [--title T] --question Q [--preview FILE] --choice A [--preview FILE] --choice B ... [--question Q2] ... | raea show --on ITEM [--working ID] [--ask TEXT] [--done ID] [--note LINE] [--sub NAME] (shown in the raea app as an item the person can use and answer, posted quietly with a notice, the window left where they are unless --open: stills (several, a storyboard), a video, a sound, a NAME.script.ts or .md, a .tsx (an interactive artifact; a project's composition opens in its editor), or questions, all of them one item, each question and choice with a --preview to play or read while answering (a still, a video, a sound, a script or .md; after a --choice that choice's, else the question's); what they send comes to ~/.raea/inbox/INBOX.jsonl; their edit comments are tasks: --working ID as you start one (each --ask with it one ask you read it as, for the person to correct), --done ID when it's settled, or with the version that settles it, FILE --replaces ITEM --done ID; never open media in Preview while the app is installed)");
+ let usage = format!("{usage}\n raea show FILE... [--title T] [--ask LINE] [--project P] [--replaces ITEM] [--as NAME] [--role ROLE] [--inbox NAME] [--open] | raea show --question Q --choice A --choice B [STILL...] | raea show [--title T] --question Q [--preview FILE] --choice A [--preview FILE] --choice B ... [--question Q2] ... | raea show --on ITEM [--working ID] [--ask TEXT] [--status S] [--states S1,S2] [--sign N --clip FILE --render HASH] [--done ID] [--note LINE] [--sub NAME] (shown in the raea app as an item the person can use and answer, posted quietly with a notice, the window left where they are unless --open: stills (several, a storyboard), a video, a sound, a NAME.script.ts or .md, a .tsx (an interactive artifact; a project's composition opens in its editor), or questions, all of them one item, each question and choice with a --preview to play or read while answering (a still, a video, a sound, a script or .md; after a --choice that choice's, else the question's); what they send comes to ~/.raea/inbox/INBOX.jsonl; their edit comments are tasks: --working ID as you start one (each --ask with it one ask you read it as, for the person to correct; --status and --states where the note and each ask stand: to restate, to check, failing, to sign, passing, signed; --sign N --clip FILE --render HASH a clip under ask N for them to sign; a note closes when they retire it, never with --done), --done ID when it's settled, or with the version that settles it, FILE --replaces ITEM --done ID; never open media in Preview while the app is installed)");
// a workspace's files and specs (docs/projects.feature), listed under render's usage like library
let usage = format!("{usage}\n raea spec FILE.ts [--as brief|script|taste|plan|controller] (a spec's default export as JSON, checked against its schema: brief.ts, script.ts, taste.ts, plan.ts, controllers/ID.ts)\n raea workspace init [NAME] [--layout LAYOUT] | raea workspace adopt DIR [--name NAME] | raea workspace [--json] (a workspace: a git repo of projects and controllers under raea.root, ~/Documents/raea unless git config says)\n raea project new NAME [--storage inline|submodule] | raea project split NAME [--remote URL] | raea project join NAME | raea project [--json] (a project in the workspace: its folder, brief.ts, media/, out/; split and join keep its history)\n raea controller ls [--json] | raea controller get PATH [--json] | raea controller set PATH VALUE [--project] [--by NAME] | raea controller write FILE.ts [--by NAME] | raea controller rm ID [--by NAME] (the workspace's controllers, controllers/ID.ts; PATH is controller.group.field; every change a commit)\n 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)\n 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)\n raea next [DIR] (the two or three useful next steps for the project, from its brief, compositions, renders and checks)\n raea doctor [--fix] [DIR] (what doesn't match this raea: old brief files, an older workspace format, an agent's skill from another version)\n raea app run|check|bundle APP.tsx [--target web|native] [--size WxH] [--script steps.json] [--png DIR] [-o App.app] (a TSX app on @raea/ui: its window, the headless check, a Mac app; web is Blitz on Bevy, native is Rune; the app's `export const app` sets the target, web when it doesn't; raea rune ... is --target native)\n {}\n {}", skill::USAGE, tools::blender::USAGE);
let (export_game, scene, physics, splat) = (raea_app_game::USAGE, export::SCENE_USAGE, motion::physics::USAGE, tools::splat::USAGE);
@@ -200,16 +206,13 @@ pub fn run(args: &[String]) -> R<String> {
return raea_app_check::hook::hook(&args[1..]);
}
// `check PROJECT|EDIT.tsx`: every rule's check over the compositions' worlds (DR4); a video is the floor alone
- if args[0] == "check" && !raea_app_direction::check::of_video(&args[1..]) {
- let ts = raea_app_direction::ts::Host { eval: spec::spec_json, run: run_bundle };
- std::process::exit(raea_app_direction::check::cli(&args[1..], &raea_app_direction::check::Host { ts, kinds: taste_kinds }));
- }
+ if args[0] == "check" && !raea_app_direction::check::of_video(&args[1..]) { std::process::exit(raea_app_direction::check::cli(&args[1..], &CHECK)); }
if args[0] == "check" {
std::process::exit(raea_app_check::cli_with(&args[1..], spec::tastes_ts(args)?));
}
if args[0] == "world" { std::process::exit(raea_app_direction::cli(&args[1..])); } // a frame as one world of facts (docs/direction.feature DR1)
if args[0] == "findings" { return raea_app_direction::findings::cli(args); } // the project's record read back (DR3)
- if args[0] == "notes" { std::process::exit(raea_app_notes::cli(&args[1..], spec::spec_json)); } // a person's notes as files, restated as asks (DR5)
+ if args[0] == "notes" { std::process::exit(raea_app_notes::cli(&args[1..], spec::spec_json, notes_run)); } // a person's notes as files, restated as asks, each with a check (DR5, DR6)
if args[0] == "traces" { return traces(args); }
if args.first().map(String::as_str) == Some("play") {
return raea_app_play::play(args);
diff --git a/engine/cli/src/show.ts b/engine/cli/src/show.ts
index 1d3338b4..f2541471 100644
--- a/engine/cli/src/show.ts
+++ b/engine/cli/src/show.ts
@@ -24,14 +24,18 @@ raea show [--title T] --question Q1 [--preview FILE] --choice A [--preview FILE]
FILE: stills (several make a storyboard), a video, a sound, a NAME.script.ts or .md, or a .tsx (an interactive
artifact; one of the project's compositions opens in its editor). P: the project's id, title or Workspace/project;
else the one this folder is in. Who's showing it: --as NAME [--role ROLE] [--inbox NAME], else your harness's.
-raea show --on ITEM --working ID... [--ask TEXT]... | --done ID... [--note LINE] [--sub NAME]
+raea show --on ITEM --working ID... [--ask TEXT]... [--status S [--states S1,S2...]] | --done ID... [--note LINE] [--sub NAME]
+raea show --on ITEM --working ID --sign N --clip FILE --render HASH
raea show FILE... --replaces ITEM --done ID...
The person's edit comments are tasks they watch: mark each working as you start it and done when it's settled
(the version that settles them, with --replaces); --sub names a subagent when several split them. With --working,
- each --ask is one ask you read the comment as, shown on it for the person to correct (raea notes post).
+ each --ask is one ask you read the comment as, shown on it for the person to correct, --status where the note
+ stands on its badge and --states each ask's (to restate, to check, failing, to sign, passing, signed); --sign shows
+ ask N's clip, cut from the render whose sha256 is HASH, for the person to sign. A comment read as asks is a note: it
+ closes when the person retires it, never with --done. raea notes post sends all of these from the notes.
`;
-const WITH_VALUE = new Set(["--title", "--ask", "--project", "--replaces", "--as", "--role", "--inbox", "--question", "--choice", "--preview", "--on", "--working", "--done", "--note", "--sub"]);
+const WITH_VALUE = new Set(["--title", "--ask", "--project", "--replaces", "--as", "--role", "--inbox", "--question", "--choice", "--preview", "--on", "--working", "--done", "--note", "--sub", "--status", "--states", "--sign", "--clip", "--render"]);
const FLAGS = new Set(["--open"]);
/** The harness an agent runs in, named as the feed shows it, from the program that started this command (native.ts
@@ -87,7 +91,7 @@ export function parseShow(args: string[], cwd: string) {
// several questions, or any preview: one item with them all (host/show.ts questions); else the one question as before
const questions = asked.length > 1 || asked.some((q) => q.preview || q.choices.some((c) => c.preview)) ? asked : undefined;
if (questions && files.length) throw new Error(`with several questions or previews, each file is a --preview of the question or choice it shows\n${SHOW_USAGE}`);
- return { files, choices, questions, open: args.includes("--open"), title: one("--title"), ask: one("--ask"), asks: many("--ask"), project: one("--project"), replaces: one("--replaces"), question: questions ? undefined : one("--question"), as: one("--as"), role: one("--role"), inbox: one("--inbox"), on: one("--on"), working: many("--working"), done: many("--done"), note: one("--note"), sub: one("--sub") };
+ return { files, choices, questions, open: args.includes("--open"), title: one("--title"), ask: one("--ask"), asks: many("--ask"), project: one("--project"), replaces: one("--replaces"), question: questions ? undefined : one("--question"), as: one("--as"), role: one("--role"), inbox: one("--inbox"), on: one("--on"), working: many("--working"), done: many("--done"), note: one("--note"), sub: one("--sub"), status: one("--status"), states: one("--states")?.split(",").map((s) => s.trim()).filter(Boolean), sign: one("--sign"), clip: one("--clip"), render: one("--render") };
}
export function showVerb(ask: Ask, args: string[], cwd: string, env: Record<string, string | undefined>): string {
@@ -104,12 +108,23 @@ export function showVerb(ask: Ask, args: string[], cwd: string, env: Record<stri
// the person's edit comments as tasks (docs/review.feature R3): marked working or done on their item, or done by
// the version shown with --replaces; a working mark carries the asks the agent read the comments as (DR5), for the
// person to correct
+ // where a note stands (DR6): its badge and each ask's, and a clip under one of its asks for the person to sign
+ const noted = a.status !== undefined || a.states !== undefined || a.sign !== undefined;
+ if (noted && !a.working.length) throw new Error(`--status, --states and --sign go with --working: raea show --on ITEM --working ID --status S\n${SHOW_USAGE}`);
+ if (a.sign !== undefined && (a.working.length !== 1 || a.done.length || !a.clip || !a.render)) throw new Error(`--sign N shows one comment's clip: raea show --on ITEM --working ID --sign N --clip FILE --render HASH\n${SHOW_USAGE}`);
+ if ((a.clip || a.render) && a.sign === undefined) throw new Error(`--clip and --render go with --sign N, the ask the clip is for\n${SHOW_USAGE}`);
+ if (a.states && a.asks.length && a.states.length !== a.asks.length) throw new Error(`--states says one state for each --ask: ${a.asks.length} asks, ${a.states.length} states\n${SHOW_USAGE}`);
+ const sign = a.sign === undefined ? undefined : { ask: Number(a.sign), clip: a.clip!.startsWith("/") ? a.clip : `${cwd.replace(/\/$/, "")}/${a.clip}`, render: a.render };
const mark = (item: string, comments: string[], state: "working" | "done", version?: string) =>
- ask("task", { item, comments, state, by, sub: a.sub, note: state === "done" ? a.note : undefined, asks: state === "working" && a.asks.length ? a.asks : undefined, version }) as { item: string; comments: string[] };
- const said = (m: { item: string; comments: string[] }, state: string) => `Marked ${m.comments.join(", ")} ${state} on ${m.item}: the person sees ${a.sub ? `${by.name} · ${a.sub}` : by.name} ${state === "working" ? "on them" : "finished them"}.`;
+ ask("task", { item, comments, state, by, sub: a.sub, note: state === "done" ? a.note : undefined, asks: state === "working" && a.asks.length ? a.asks : undefined, version, ...(state === "working" ? { status: a.status, states: a.states, sign } : {}) }) as { item: string; comments: string[] };
+ const said = (m: { item: string; comments: string[] }, state: string) => `Marked ${m.comments.join(", ")} ${state} on ${m.item}: the person sees ${a.sub ? `${by.name} · ${a.sub}` : by.name} ${state === "working" ? "on them" : "finished them"}${state === "working" && a.status ? `; it reads "${a.status}"${a.states?.length ? ` (its asks: ${a.states.join(", ")})` : ""}` : ""}.`;
if (!a.files.length && !a.question && !a.questions && (a.working.length || a.done.length)) {
const item = a.on ?? a.replaces;
if (!item) throw new Error(`which item the comments are on: --on ITEM\n${SHOW_USAGE}`);
+ if (sign) {
+ const m = mark(item, a.working, "working");
+ return `Shown ask ${sign.ask}'s clip on ${m.comments[0]} of ${m.item} for the person to sign (render ${String(sign.render).slice(0, 12)}…): their sign comes to the inbox, and raea notes take keeps it.\n`;
+ }
const out = [...(a.working.length ? [said(mark(item, a.working, "working"), "working")] : []), ...(a.done.length ? [said(mark(item, a.done, "done"), "done")] : [])];
return `${out.join("\n")}\n`;
}
diff --git a/runtime/world/src/covers.rs b/runtime/world/src/covers.rs
index b3a3e274..c3d9a67b 100644
--- a/runtime/world/src/covers.rs
+++ b/runtime/world/src/covers.rs
@@ -96,8 +96,9 @@ impl Masks {
/// Each boxed layer of the world (`boxed`: its entity, key and box) and what covers it this frame, as Covers on the
/// covering layer's entity: the world's entity with that key, or a new one with only its Source when the page drew it
-/// but the world holds no entity of it (a plain element, a band).
-pub(crate) fn put(facts: &mut Facts, masks: &Masks, boxed: &[(u32, String, [f64; 4])], order: &HashMap<String, usize>) {
+/// but the world holds no entity of it (a plain element, a band): `source`'s for its key (the element's, with the
+/// component it was drawn in), else the key's file and line.
+pub(crate) fn put(facts: &mut Facts, masks: &Masks, boxed: &[(u32, String, [f64; 4])], order: &HashMap<String, usize>, source: &dyn Fn(&str) -> Option<Source>) {
let mut by: HashMap<String, Vec<Covered>> = HashMap::new();
for (e, key, bx) in boxed {
for (k, share) in masks.over(facts.frame, key, *bx, order) {
@@ -109,7 +110,7 @@ pub(crate) fn put(facts: &mut Facts, masks: &Masks, boxed: &[(u32, String, [f64;
for k in keys {
let id = keyed(facts, &k).unwrap_or_else(|| {
let id = facts.spawn(None);
- facts.put(id, &source_of(&k));
+ facts.put(id, &source(&k).unwrap_or_else(|| source_of(&k)));
id
});
facts.put(id, &Covers(by.remove(&k).unwrap_or_default()));
@@ -154,9 +155,15 @@ mod tests {
assert!(m.over(8, "bg.tsx:2:3", [0.0, 0.0, 1.0, 1.0], &order).is_empty(), "a frame not recorded");
let mut w = Facts::new(7, 4, 1, 30.0);
let caption = w.spawn(None);
- put(&mut w, &m, &[(caption, "bg.tsx:2:3".into(), [0.0, 0.0, 1.0, 1.0])], &order);
+ put(&mut w, &m, &[(caption, "bg.tsx:2:3".into(), [0.0, 0.0, 1.0, 1.0])], &order, &|_| None);
let band = w.find(&["Covers"])[0];
assert_eq!(band.components["Covers"], serde_json::json!([{"layer": caption, "share": 0.5}]));
assert_eq!((band.components["Source"]["file"].as_str(), band.components["Source"]["line"].as_u64()), (Some("bg.tsx"), Some(3)));
+ // where the element is known, it is named by the component it was drawn in, as every entity of the world is
+ let mut w = Facts::new(7, 4, 1, 30.0);
+ let caption = w.spawn(None);
+ let drawn = |k: &str| (k == "bg.tsx:3:3").then(|| Source { component: Some("Band".into()), key: Some(k.into()), ..Default::default() });
+ put(&mut w, &m, &[(caption, "bg.tsx:2:3".into(), [0.0, 0.0, 1.0, 1.0])], &order, &drawn);
+ assert_eq!(w.find(&["Covers"])[0].components["Source"]["component"], "Band");
}
}
diff --git a/runtime/world/src/renders.rs b/runtime/world/src/renders.rs
index 3812fd95..8826d499 100644
--- a/runtime/world/src/renders.rs
+++ b/runtime/world/src/renders.rs
@@ -45,6 +45,8 @@ pub(crate) struct Found {
masks: Option<Option<crate::covers::Masks>>,
/// its frames, decoded once as they're asked for (a text's contrast, what OCR reads)
pixels: crate::pixels::Pixels,
+ /// the composition's folder, where its source stamps' files are
+ dir: PathBuf,
}
fn secs(p: &Path) -> u64 {
@@ -76,7 +78,7 @@ pub(crate) fn find(how: &Render, tsx: &Path, size: (u32, u32, f64)) -> Option<Fo
// another composition of the file draws another size or rate
let same = m["width"] == size.0 && m["height"] == size.1 && m["fps"].as_f64() == Some(size.2);
let at = m["frames"].as_array()?.iter().enumerate().filter_map(|(k, f)| Some((f["frame"].as_i64()?, k))).collect();
- (same && out.exists()).then(|| Found { stale: secs(tsx) > made, out, path, m, record, at, dirty: false, env: None, masks: None, pixels: Default::default() })
+ (same && out.exists()).then(|| Found { stale: secs(tsx) > made, out, path, m, record, at, dirty: false, env: None, masks: None, pixels: Default::default(), dir: tsx.parent().map(Path::to_path_buf).unwrap_or_default() })
})
}
@@ -282,7 +284,9 @@ fn covers(facts: &mut Facts, r: &mut Found, laid: &Value, tree: &[El], mut boxed
}
}
let order: HashMap<String, usize> = tree.iter().enumerate().filter_map(|(i, el)| Some((raea_sys_layers::key_from_props(&el.props)?, i))).collect();
- crate::covers::put(facts, masks, &boxed, &order);
+ // a covering layer as the world has it when it holds the element: its Source, the component it was drawn in
+ let source = |k: &str| tree.iter().find(|el| raea_sys_layers::key_from_props(&el.props).as_deref() == Some(k)).and_then(|el| crate::source::of(&el.props, &r.dir));
+ crate::covers::put(facts, masks, &boxed, &order, &source);
}
#[cfg(test)]
diff --git a/sdk/guides/craft/ROUTER.md b/sdk/guides/craft/ROUTER.md
index 5ea45cbf..c16b1c1a 100644
--- a/sdk/guides/craft/ROUTER.md
+++ b/sdk/guides/craft/ROUTER.md
@@ -70,12 +70,22 @@ People write notes in their own words, and one note can hold several asks. Befor
1. `raea notes take` writes each note the person sent from the raea app, or said to you, to `notes/ROUND/ID.ts` in
the project, their words as written.
-2. Restate each note in its file as its asks: one for each separate thing it asks for; the medium where the words
- name one (2D means 2D: a 3D scene doesn't make a title 3D); what it is about; and what it doesn't ask for (`not`),
- so a change keeps the rest. A redesign's asks say what is kept.
+2. Restate each note in its file (`note({...})` from `raea/note`) as its asks: one for each separate thing it asks
+ for; the medium where the words name one (2D means 2D: a 3D scene doesn't make a title 3D); what it is about; and
+ what it doesn't ask for (`not`), so a change keeps the rest. A redesign's asks say what is kept.
3. `raea notes ls` says what each restatement still owes. Change nothing until it owes nothing.
4. `raea notes post` shows the asks on the person's comments in the raea app. A correction they make there comes back
with the next `raea notes take` as a new line of the note: restate that ask again before you go on.
+5. Give each ask a check that measures it, or a clip the person signs where it can't be measured. A check is a
+ `raea/check` system, as a rule's is: copy the worked one that fits from this skill's `craft/checks` (a part that
+ rides a seat, flat type with the subject in front, a part facing what it serves, nothing of one kind on another,
+ a shot held N seconds, no part of a kind) into the project's `checks/`, and name it in the ask with its `values`
+ and the composition it's about (`of`). A clip is `proof: { shot, sign: true }`.
+6. `raea notes check` must show each check failing on the work as it stands. A check that passes first is refused: it
+ isn't measuring the ask, so fix the check, not the work. Only then change the work, one move per ask, and run
+ `raea notes check` again until each passes; it also cuts each clip to sign from the newest render, so render first.
+ `raea notes post` again shows where each ask stands. A note closes when the person retires it, never when you mark
+ it done.
Each ask is one of a small set of moves: name it as the ask's `verb`, and do that move to the part or moment it
names. A note with three asks is three moves, not one:
diff --git a/sdk/guides/craft/checks/faces.ts b/sdk/guides/craft/checks/faces.ts
new file mode 100644
index 00000000..db92e088
--- /dev/null
+++ b/sdk/guides/craft/checks/faces.ts
@@ -0,0 +1,49 @@
+// A worked check for a note that says "the desks face the wrong way" (docs/direction.feature DR6): each part of a kind
+// faces what it serves, the nearest of it, on every frame.
+//
+// Its values, the kinds as raea/check's `named` reads them: `what`, the parts that face; `toward`, what they face (a
+// desk its chair), or `away`, what they turn their backs to (a desk the wall); `front`, the model's own front, "+z"
+// (the default), "-z", "+x" or "-x", until DR11 measures it from the model; `within`, how far off it may be, in
+// degrees (default 30). Only the turn about the up axis counts.
+//
+// asks: [{ text: "every desk faces its chair", check: "../../checks/faces.ts", values: { what: "desk", toward: "chair" } }]
+//
+// Its cheats, each failed: one desk turned round; the desks renamed, or the chairs gone, so there is nothing to face.
+import { check, found, named, turned, type Part } from "raea/check";
+
+const AXES: Record<string, number[]> = { "+z": [0, 0, 1], "-z": [0, 0, -1], "+x": [1, 0, 0], "-x": [-1, 0, 0] };
+const centre = (p: Part) => (p.min && p.max ? [0, 1, 2].map((k) => (p.min![k] + p.max![k]) / 2) : p.at);
+
+export default check(
+ { id: "faces", text: "each part faces what it serves" },
+ (world, _frame, values, memo) => {
+ const axis = AXES[String(values.front ?? "+z")];
+ if (!axis) throw new Error(`front is "+z", "-z", "+x" or "-x", not "${values.front}"`);
+ const away = values.toward == null;
+ const parts = world.find({ with: ["Part"] });
+ const part = (id: number) => world.component<Part>(id, "Part")!;
+ const what = parts.filter((p) => named(world, p, String(values.what)));
+ const goals = parts.filter((p) => !what.includes(p) && named(world, p, String(away ? values.away : values.toward)));
+ memo.what ||= what.length > 0;
+ memo.goals ||= goals.length > 0;
+ const within = Number(values.within ?? 30);
+ for (const p of what) {
+ const c = centre(part(p));
+ const dist = (g: number) => Math.hypot(...[0, 2].map((k) => centre(part(g))[k] - c[k]));
+ const goal = goals.reduce<number | null>((best, g) => (best == null || dist(g) < dist(best) ? g : best), null);
+ if (goal == null) continue;
+ const f = turned(part(p).rotation, axis);
+ const to = [0, 2].map((k) => (centre(part(goal))[k] - c[k]) * (away ? -1 : 1));
+ const len = Math.hypot(f[0], f[2]) * Math.hypot(to[0], to[1]);
+ if (len < 1e-9) continue;
+ const deg = (Math.acos(Math.max(-1, Math.min(1, (f[0] * to[0] + f[2] * to[1]) / len))) * 180) / Math.PI;
+ if (deg > within) {
+ found({ about: [p, goal], says: `${part(p).name} is turned ${Math.round(deg)} degrees from facing ${away ? "away from " : ""}${part(goal).name}`, measure: { name: "facing", value: Math.round(deg), unit: "deg", limit: within } });
+ }
+ }
+ },
+ (values, memo) => {
+ if (!memo.what) found({ says: `no part on any frame is ${values.what}: nothing to face` });
+ else if (!memo.goals) found({ says: `no part on any frame is ${values.toward ?? values.away}, for ${values.what} to face ${values.toward == null ? "away from" : ""}`.trim() });
+ },
+);
diff --git a/sdk/guides/craft/checks/flat-type.ts b/sdk/guides/craft/checks/flat-type.ts
new file mode 100644
index 00000000..f1ac52e1
--- /dev/null
+++ b/sdk/guides/craft/checks/flat-type.ts
@@ -0,0 +1,51 @@
+// A worked check for a note that says "2D text with occlusion" (docs/direction.feature DR6): the words are flat 2D
+// type (no depth, not a 3D part, on a layer whose medium is 2d-type) on every frame they're on, and the subject is in
+// front of them where they meet.
+//
+// Its values: `words`, the text it is about (any case, punctuation aside; unset: each line sung or said on the
+// frame); `subject`, what is to be in front of it, as raea/check's `named` reads it (unset: anything in front);
+// `occlusion: false` when the note asks for flat type alone. What covers what is a render's (raea render --layers),
+// so it waits for one. A page layer can cover type; a 3D or footage subject in front of 2D type is DR19's mask, and
+// until then the check says so, and the ask is a clip for the person to sign.
+//
+// asks: [{ text: "the lyric is flat type behind the singer", medium: "2D", check: "../../checks/flat-type.ts",
+// values: { words: "out of the grey", subject: "component:Singer" } }]
+//
+// Its cheats, each failed: 3D type a hair deep (0.002 m) facing the camera, so a frame of it reads as flat; flat type
+// with nothing in front of it; the words changed so no text reads them.
+import { check, found, named, type Covers, type Layer, type Line, type Text } from "raea/check";
+
+const plain = (s: string) => s.replace(/[^a-z0-9 ]/gi, " ").replace(/\s+/g, " ").trim().toLowerCase();
+
+export default check(
+ { id: "flat-type", text: "the words are flat 2D type, with the subject in front of them where they meet", needs: "render" },
+ (world, _frame, values, memo) => {
+ const want = values.words != null ? [plain(String(values.words))] : world.find({ with: ["Line"] }).map((l) => plain(world.component<Line>(l, "Line")!.text));
+ for (const t of world.find({ with: ["Text"] })) {
+ const text = world.component<Text>(t, "Text")!;
+ if (!want.some((w) => w && plain(text.words).includes(w))) continue;
+ memo.seen = true;
+ // its layer: its own, else the nearest one it is in
+ let at: number | null = t;
+ while (at != null && !world.component<Layer>(at, "Layer")) at = world.parent(at);
+ const medium = at == null ? "3d" : world.component<Layer>(at, "Layer")!.medium;
+ const part = !!world.components(t).Part;
+ if (part || text.extruded > 0 || medium !== "2d-type") {
+ found({ about: [t], says: `the words are ${part ? "3D" : medium} type${text.extruded > 0 ? `, ${text.extruded} m deep` : ""}: the note asks for flat 2D type`, fix: "set them as 2D type on the page, not Text3D" });
+ }
+ if (values.occlusion === false) continue;
+ const over = world.find({ with: ["Covers"] }).filter((c) => (world.component<Covers>(c, "Covers") ?? []).some((x) => x.layer === t && x.share > 0));
+ const subject = values.subject != null ? String(values.subject) : undefined;
+ if (over.some((c) => subject == null || named(world, c, subject))) continue;
+ const solid = subject != null && world.find({ with: ["Part"] }).some((p) => named(world, p, subject));
+ found({
+ about: [t],
+ says: solid ? `the subject (${subject}) is a 3D part: 2D type behind it is DR19's mask, which raea doesn't have yet` : `nothing${subject ? ` that is ${subject}` : ""} is in front of the words where they meet: the note asks for the subject to mask them`,
+ fix: solid ? "make the ask a clip for the person to sign (proof: { shot, sign: true }) until DR19" : undefined,
+ });
+ }
+ },
+ (values, memo) => {
+ if (!memo.seen) found({ says: values.words != null ? `no text on any frame reads "${values.words}"` : "no line sung or said is on screen as text on any frame" });
+ },
+);
diff --git a/sdk/guides/craft/checks/no-part.ts b/sdk/guides/craft/checks/no-part.ts
new file mode 100644
index 00000000..71967167
--- /dev/null
+++ b/sdk/guides/craft/checks/no-part.ts
@@ -0,0 +1,19 @@
+// A worked check for a note that says "no orbs anywhere" (docs/direction.feature DR6): no part of the named kind is
+// in the piece, on any frame, seen or not.
+//
+// Its values: `what`, the kind as raea/check's `named` reads it. A component the note means is best named by what
+// drew it (`component:Orb`), which renaming its parts doesn't change.
+//
+// asks: [{ text: "no orbs anywhere", check: "../../checks/no-part.ts", values: { what: "component:Orb" } }]
+//
+// Its cheats, each failed: one orb left in a corner of one shot; the orb's mesh renamed while the Orb component still
+// draws it; the orb scaled to nothing, which is still an orb.
+import { check, found, named, type Part } from "raea/check";
+
+export default check({ id: "no-part", text: "nothing of the kind is in the piece" }, (world, _frame, values) => {
+ // what the note calls it, as a person says it: "component:Orb" is an Orb
+ const label = String(values.what).replace(/\b(component|file):/g, "");
+ for (const p of world.find({ with: ["Part"] }).filter((p) => named(world, p, String(values.what)))) {
+ found({ about: [p], says: `${world.component<Part>(p, "Part")!.name} is there, and the note asks for no ${label}` });
+ }
+});
diff --git a/sdk/guides/craft/checks/rides.ts b/sdk/guides/craft/checks/rides.ts
new file mode 100644
index 00000000..b30d98c4
--- /dev/null
+++ b/sdk/guides/craft/checks/rides.ts
@@ -0,0 +1,72 @@
+// A worked check for a note that says "the seat turns with the computer" (docs/direction.feature DR6): the rider
+// holds its place and its turn on its seat on every frame, and no part of it is inside a part of the seat.
+//
+// Its values name the parts as raea/check's `named` reads them: `rider`, and `seat` (every part of the seat; the
+// first found is the one the rider's place is measured from). Until DR16 gives the seat a socket, the rider's place
+// and turn on the first frame that has both are what it is held to: `offset` (mm, default 10) and `turn` (degrees,
+// default 1) are how far they may drift, and `into` (m, default 0.01) how far the rider may be in a part of the seat.
+//
+// asks: [{ text: "the computer rides the chair as it swivels", check: "../../checks/rides.ts",
+// values: { rider: "computer", seat: "chair" } }]
+//
+// Its cheats, each failed: the rider set down beside the seat and left as the seat turns; the rider turned with the
+// seat but pushed into its back; the rider renamed or gone (no frame has it).
+import { check, found, inside, named, turned, type Part } from "raea/check";
+
+type V = number[];
+const conj = (q: V) => [-q[0], -q[1], -q[2], q[3]];
+const mul = (a: V, b: V) => [
+ a[3] * b[0] + a[0] * b[3] + a[1] * b[2] - a[2] * b[1],
+ a[3] * b[1] - a[0] * b[2] + a[1] * b[3] + a[2] * b[0],
+ a[3] * b[2] + a[0] * b[1] - a[1] * b[0] + a[2] * b[3],
+ a[3] * b[3] - a[0] * b[0] - a[1] * b[1] - a[2] * b[2],
+];
+const degrees = (a: V, b: V) => (2 * Math.acos(Math.min(1, Math.abs(a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]))) * 180) / Math.PI;
+
+/** The worst a measure got and the frames it was past its limit on, kept until the run ends. */
+type Bad = { from: number; to: number; worst: number; about: string[] };
+const worse = (memo: Record<string, Bad>, key: string, frame: number, value: number, about: string[]) => {
+ const b = memo[key];
+ if (!b) memo[key] = { from: frame, to: frame + 1, worst: value, about };
+ else Object.assign(b, { to: frame + 1, worst: Math.max(b.worst, value) });
+};
+
+export default check(
+ { id: "rides", text: "the rider holds its place and turn on its seat, and is in no part of it" },
+ (world, frame, values, memo) => {
+ const parts = world.find({ with: ["Part"] });
+ const part = (id: number) => world.component<Part>(id, "Part")!;
+ const riders = parts.filter((p) => named(world, p, String(values.rider)));
+ const seats = parts.filter((p) => !riders.includes(p) && named(world, p, String(values.seat)));
+ if (!riders.length && !seats.length) return;
+ memo.seen = true;
+ if (!riders.length || !seats.length) {
+ return found({ about: [...riders, ...seats], says: riders.length ? `the rider is here and no part is its seat (${values.seat})` : `the seat is here and no part is its rider (${values.rider})` });
+ }
+ const r = part(riders[0]);
+ const s = part(seats[0]);
+ // the rider's place and turn in the seat's own space
+ const at = turned(conj(s.rotation), [0, 1, 2].map((k) => r.at[k] - s.at[k]));
+ const q = mul(conj(s.rotation), r.rotation);
+ memo.bad ??= {};
+ if (!memo.at) Object.assign(memo, { at, q, first: frame });
+ const names = [r.name, s.name];
+ const mm = Math.hypot(...at.map((v, k) => v - memo.at[k])) * 1000;
+ if (mm > Number(values.offset ?? 10)) worse(memo.bad, "offset", frame, mm, names);
+ const deg = degrees(memo.q, q);
+ if (deg > Number(values.turn ?? 1)) worse(memo.bad, "turn", frame, deg, names);
+ for (const p of seats) {
+ const m = inside(r, part(p));
+ if (m > Number(values.into ?? 0.01)) worse(memo.bad, `into ${part(p).name}`, frame, m, [r.name, part(p).name]);
+ }
+ },
+ (values, memo) => {
+ if (!memo.seen) return found({ says: `no frame has the rider (${values.rider}) or its seat (${values.seat})`, fix: "name them in the ask's values as the scene does (raea world lists its parts)" });
+ for (const [key, b] of Object.entries((memo.bad ?? {}) as Record<string, Bad>)) {
+ const frames: [number, number] = [b.from, b.to];
+ if (key === "offset") found({ about: b.about, frames, says: `the rider moves up to ${Math.round(b.worst)} mm on its seat from where it sat on frame ${memo.first}`, measure: { name: "offset", value: Math.round(b.worst), unit: "mm", limit: Number(values.offset ?? 10) } });
+ else if (key === "turn") found({ about: b.about, frames, says: `the rider turns up to ${b.worst.toFixed(1)} degrees on its seat from how it sat on frame ${memo.first}`, measure: { name: "turn", value: Math.round(b.worst * 10) / 10, unit: "deg", limit: Number(values.turn ?? 1) } });
+ else found({ about: b.about, frames, says: `the rider is up to ${Math.round(b.worst * 100)} cm ${key}`, measure: { name: "into", value: Math.round(b.worst * 100), unit: "cm", limit: Math.round(Number(values.into ?? 0.01) * 100) } });
+ }
+ },
+);
diff --git a/sdk/guides/craft/checks/shot-length.ts b/sdk/guides/craft/checks/shot-length.ts
new file mode 100644
index 00000000..ea22c89d
--- /dev/null
+++ b/sdk/guides/craft/checks/shot-length.ts
@@ -0,0 +1,40 @@
+// A worked check for a note that says "hold this longer" (docs/direction.feature DR6): the shot is at least so many
+// seconds long.
+//
+// Its values: `shot`, the shot's name as its Sequence has it (`<Sequence name="hold">`), or "*" for every named shot;
+// `seconds`, the least it may run. A shot with no end runs to the piece's end, and is measured to its last frame.
+//
+// asks: [{ text: "hold the reveal for four seconds", check: "../../checks/shot-length.ts",
+// values: { shot: "reveal", seconds: 4 } }]
+//
+// Its cheats, each failed: the shot left as short as it was; the shot renamed, so no shot is the one asked about.
+import { check, found, type Shot } from "raea/check";
+
+export default check(
+ { id: "shot-length", text: "the shot holds long enough" },
+ (world, frame, values, memo) => {
+ memo.fps ??= (world.resource("Frame") as { fps: number }).fps;
+ memo.shots ??= {};
+ for (const s of world.find({ with: ["Shot"] })) {
+ const shot = world.component<Shot>(s, "Shot")!;
+ if (!shot.name || (values.shot !== "*" && shot.name !== String(values.shot))) continue;
+ const k = `${shot.name} ${shot.from}`;
+ memo.shots[k] ??= { name: shot.name, from: shot.from, to: shot.to ?? null, last: frame };
+ memo.shots[k].last = Math.max(memo.shots[k].last, frame);
+ }
+ },
+ (values, memo) => {
+ const shots = Object.values((memo.shots ?? {}) as Record<string, { name: string; from: number; to: number | null; last: number }>);
+ if (!shots.length) return found({ says: values.shot === "*" ? "no shot on any frame has a name" : `no shot is named ${values.shot}`, fix: "name the shot's Sequence as the ask does" });
+ const least = Number(values.seconds);
+ if (!(least > 0)) throw new Error(`seconds is the least the shot may run, more than 0, not ${values.seconds}`);
+ for (const s of shots) {
+ const end = s.to ?? s.last + 1;
+ const secs = (end - s.from) / memo.fps;
+ // half a frame's grace: a shot of 4 s at 30 fps is 120 frames
+ if (secs + 0.5 / memo.fps < least) {
+ found({ about: [s.name], frames: [s.from, end], says: `the shot ${s.name} is ${secs.toFixed(1)} s, under ${least} s`, measure: { name: "length", value: Math.round(secs * 10) / 10, unit: "s", limit: least } });
+ }
+ }
+ },
+);
diff --git a/sdk/guides/craft/checks/stands-on.ts b/sdk/guides/craft/checks/stands-on.ts
new file mode 100644
index 00000000..7a3986d9
--- /dev/null
+++ b/sdk/guides/craft/checks/stands-on.ts
@@ -0,0 +1,39 @@
+// A worked check for a note that says "there are kitchen props on a desk" (docs/direction.feature DR6): no part of
+// one kind stands on a part of another, on any frame.
+//
+// Its values, the kinds as raea/check's `named` reads them: `what`, what mustn't stand there (a list: "kettle, mug,
+// pan"); `on`, what it mustn't stand on ("desk"); `gap`, how near a bottom is to a top to stand on it, in metres
+// (default 0.02). One part stands on another when its bottom is within the gap of the other's top and its middle is
+// over the other's footprint, measured from their boxes until DR16 declares StandsOn. What floats or sinks is the
+// lint's (raea scene lint), not this.
+//
+// asks: [{ text: "nothing from the kitchen on the desks", check: "../../checks/stands-on.ts",
+// values: { what: "kettle, mug, pan", on: "desk" } }]
+//
+// Its cheats, each failed: a kettle set on a desk; the desks renamed or gone, so nothing is checked.
+import { check, found, named, type Part } from "raea/check";
+
+export default check(
+ { id: "stands-on", text: "nothing of one kind stands on another" },
+ (world, _frame, values, memo) => {
+ const parts = world.find({ with: ["Part"] });
+ const part = (id: number) => world.component<Part>(id, "Part")!;
+ const under = parts.filter((p) => named(world, p, String(values.on)));
+ memo.under ||= under.length > 0;
+ const gap = Number(values.gap ?? 0.02);
+ for (const a of parts.filter((p) => !under.includes(p) && named(world, p, String(values.what)))) {
+ const p = part(a);
+ if (!p.min || !p.max) continue;
+ const mid = [(p.min[0] + p.max[0]) / 2, (p.min[2] + p.max[2]) / 2];
+ for (const b of under) {
+ const q = part(b);
+ if (!q.min || !q.max) continue;
+ const over = mid[0] >= q.min[0] && mid[0] <= q.max[0] && mid[1] >= q.min[2] && mid[1] <= q.max[2];
+ if (over && Math.abs(p.min[1] - q.max[1]) <= gap) found({ about: [a, b], says: `${p.name} stands on ${q.name}` });
+ }
+ }
+ },
+ (values, memo) => {
+ if (!memo.under) found({ says: `no part on any frame is ${values.on}: nothing to keep ${values.what} off` });
+ },
+);
diff --git a/sdk/raea/src/check.ts b/sdk/raea/src/check.ts
index 08a41cdc..387e7d41 100644
--- a/sdk/raea/src/check.ts
+++ b/sdk/raea/src/check.ts
@@ -16,7 +16,7 @@
// });
import { createWorld, type World } from "@raea/app/ecs";
-import type { About, Finding, Level, Measure } from "./facts.gen";
+import type { About, Finding, Level, Measure, Part } from "./facts.gen";
export type * from "./facts.gen";
export type { World };
@@ -38,26 +38,101 @@ export interface CheckMeta {
frames?: Frames;
}
-/** A rule's values for its check (a controller's `values`). */
+/** A rule's values for its check (a controller's `values`, an ask's). */
export type Values = Record<string, number | string | boolean>;
-/** The system: a frame's world, the frame, and the rule's values. */
-export type CheckFn = (world: World, frame: number, values: Values) => void;
+/** What one rule's run of a check keeps from frame to frame: empty on its first frame, its own (two asks that run
+ * one check each have theirs). */
+export type Memo = Record<string, any>;
+/** The system: a frame's world, the frame, the rule's values, and what this run has kept. */
+export type CheckFn = (world: World, frame: number, values: Values, memo: Memo) => void;
+/** Run once after the last frame, with what the frames kept: for what only the whole run can say (how long a shot
+ * held, that no frame had the part an ask is about). A finding here has no frames unless it gives them. */
+export type AfterFn = (values: Values, memo: Memo) => void;
export interface Check extends CheckMeta {
/** its system, run on each frame it ranges over */
run: CheckFn;
+ /** run once past its last frame */
+ after?: AfterFn;
}
-/** A check: what it holds the work to, and the system that finds where the work doesn't hold. */
-export function check(meta: CheckMeta, run: CheckFn): Check {
- return { ...meta, run };
+/** A check: what it holds the work to, the system that finds where the work doesn't hold, and what it says once the
+ * frames are run. */
+export function check(meta: CheckMeta, run: CheckFn, after?: AfterFn): Check {
+ return { ...meta, run, after };
+}
+
+/** The names an entity goes by, as `named` matches them: its part's name, its model file's name (no folder, no
+ * extension), its shot's name and its layer key; and, each only by its prefix, the component that drew it
+ * (`component:Orb`) and its model file in full (`file:props/orb.glb`). */
+function names(world: World, id: number): { bare: string[]; component?: string; file?: string } {
+ const c = world.components(id) as Record<string, Record<string, unknown> | undefined>;
+ const str = (v: unknown) => (typeof v === "string" && v ? v : undefined);
+ const file = str(c.Part?.src);
+ const stem = file?.split("/").pop()?.replace(/\.[^.]+$/, "");
+ return { bare: [str(c.Part?.name), stem, str(c.Shot?.name), str(c.Source?.key)].filter((v): v is string => !!v), component: str(c.Source?.component), file };
+}
+
+/** Whether entity `id` is one of `kinds` (a list, or one string of them split at commas): a bare kind is a part's,
+ * shot's or layer's name or a model file's, as written or as its start ("desk" is desk-3 and Desk.glb), any case;
+ * `component:Orb` is what the Orb component drew, and `file:props/orb.glb` what that model file is. Until a
+ * component's taxonomy (DR11) says what a thing is, an ask's check names it this way. */
+export function named(world: World, id: number, kinds: string | string[] | undefined): boolean {
+ const ks = (Array.isArray(kinds) ? kinds : String(kinds ?? "").split(",")).map((k) => k.trim().toLowerCase()).filter(Boolean);
+ if (!ks.length) return false;
+ const n = names(world, id);
+ const starts = (v: string | undefined, k: string) => !!v && v.toLowerCase().startsWith(k);
+ return ks.some((k) => {
+ if (k.startsWith("component:")) return n.component?.toLowerCase() === k.slice(10);
+ if (k.startsWith("file:")) return !!n.file && n.file.toLowerCase().endsWith(k.slice(5));
+ return n.bare.some((v) => starts(v, k));
+ });
+}
+
+/** `v` turned by a rotation `q` (x, y, z, w), as a part's `rotation` turns its own space into the world's. */
+export function turned(q: number[], v: number[]): number[] {
+ const [x, y, z, w] = q;
+ const t = [2 * (y * v[2] - z * v[1]), 2 * (z * v[0] - x * v[2]), 2 * (x * v[1] - y * v[0])];
+ return [v[0] + w * t[0] + (y * t[2] - z * t[1]), v[1] + w * t[1] + (z * t[0] - x * t[2]), v[2] + w * t[2] + (x * t[1] - y * t[0])];
+}
+
+/** A part as a box turned as it is: its centre, its axes and its half sizes along them, in world metres. A part with
+ * no box of its own is its world box; one with neither has none. */
+function boxOf(p: Part): { c: number[]; axes: number[][]; half: number[] } | null {
+ const unit = [[1, 0, 0], [0, 1, 0], [0, 0, 1]];
+ if (!p.own) return p.min && p.max ? { c: [0, 1, 2].map((k) => (p.min![k] + p.max![k]) / 2), axes: unit, half: [0, 1, 2].map((k) => (p.max![k] - p.min![k]) / 2) } : null;
+ const [lo, hi] = p.own;
+ const c = turned(p.rotation, [0, 1, 2].map((k) => ((lo[k] + hi[k]) / 2) * p.scale[k])).map((v, k) => v + p.at[k]);
+ return { c, axes: unit.map((u) => turned(p.rotation, u)), half: [0, 1, 2].map((k) => (Math.abs(hi[k] - lo[k]) / 2) * Math.abs(p.scale[k])) };
+}
+
+/** How far two parts are in each other, in metres: the least overlap of their own boxes, turned as they are, along
+ * the axes that could part them (0: apart, or a part with no box). */
+export function inside(a: Part, b: Part): number {
+ const p = boxOf(a);
+ const q = boxOf(b);
+ if (!p || !q) return 0;
+ const dot = (u: number[], v: number[]) => u[0] * v[0] + u[1] * v[1] + u[2] * v[2];
+ const cross = (u: number[], v: number[]) => [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]];
+ const d = [0, 1, 2].map((k) => q.c[k] - p.c[k]);
+ let least = Infinity;
+ for (const ax of [...p.axes, ...q.axes, ...p.axes.flatMap((u) => q.axes.map((v) => cross(u, v)))]) {
+ const len = Math.hypot(ax[0], ax[1], ax[2]);
+ if (len < 1e-9) continue;
+ const n = ax.map((v) => v / len);
+ const reach = (o: NonNullable<typeof p>) => o.half.reduce((s, h, k) => s + h * Math.abs(dot(o.axes[k], n)), 0);
+ const overlap = reach(p) + reach(q) - Math.abs(dot(d, n));
+ if (overlap <= 0) return 0;
+ least = Math.min(least, overlap);
+ }
+ return least === Infinity ? 0 : least;
}
/** What a check found: the entities it is about, what it says, and, where they aren't the check's or the frame's,
* its level and frames (its first, and the frame after its last); the number it turns on and the fix, when there
* are. */
export interface Found {
- /** the entities it is about, by their ids in this frame's world */
- about?: number[];
+ /** the entities it is about, by their ids in this frame's world, or by name (a check's `after` has no world) */
+ about?: (number | string)[];
/** what is wrong, in a line a person reads */
says: string;
/** its level, where it isn't its rule's or its check's */
@@ -80,8 +155,9 @@ export function found(f: Found): void {
check: c.id,
// the finding's own level, else its rule's, else the check's
level: f.level ?? plan.level ?? c.level ?? "error",
- about: (f.about ?? []).map((id) => aboutOf(world, id)),
- frames: f.frames ?? [frame, frame + 1],
+ about: (f.about ?? []).map((id) => (typeof id === "string" ? ({ name: id } as About) : aboutOf(world, id))),
+ // past the last frame (a check's `after`), none unless it says
+ frames: f.frames ?? (frame < 0 ? null : [frame, frame + 1]),
says: f.says,
measure: f.measure ? { ...f.measure, limit: f.measure.limit ?? null } : null,
fix: f.fix ?? null,
@@ -161,22 +237,35 @@ export interface Planned {
export function runChecks(checks: Check[], plan: Planned[], worlds: Facts[]): { findings: Finding[]; threw: { check: string; says: string }[] } {
const out: Finding[] = [];
const threw: { check: string; says: string }[] = [];
+ // each planned run's memo, kept across its frames
+ const memos: Memo[] = plan.map(() => ({}));
+ const call = (c: Check, at: string, f: () => void) => {
+ try {
+ f();
+ } catch (e) {
+ if (!threw.some((t) => t.check === c.id)) threw.push({ check: c.id, says: `${at}: ${e instanceof Error ? e.message : String(e)}` });
+ } finally {
+ running = null;
+ }
+ };
for (const facts of worlds) {
- const here = plan.filter((p) => p.frames.includes(facts.frame));
- if (!here.length) continue;
+ if (!plan.some((p) => p.frames.includes(facts.frame))) continue;
const world = worldOf(facts);
- for (const p of here) {
+ plan.forEach((p, i) => {
+ if (!p.frames.includes(facts.frame)) return;
const c = checks[p.check];
running = { world, frame: facts.frame, check: c, plan: p, out };
- try {
- c.run(world, facts.frame, p.values);
- } catch (e) {
- if (!threw.some((t) => t.check === c.id)) threw.push({ check: c.id, says: `at frame ${facts.frame}: ${e instanceof Error ? e.message : String(e)}` });
- } finally {
- running = null;
- }
- }
+ call(c, `at frame ${facts.frame}`, () => c.run(world, facts.frame, p.values, memos[i]));
+ });
}
+ // what only the whole run can say, once, with no frame's world
+ const none = createWorld({ native: false });
+ plan.forEach((p, i) => {
+ const c = checks[p.check];
+ if (!c.after || threw.some((t) => t.check === c.id)) return;
+ running = { world: none, frame: -1, check: c, plan: p, out };
+ call(c, "after its frames", () => c.after!(p.values, memos[i]));
+ });
return { findings: joined(out), threw };
}
diff --git a/sdk/raea/src/facts.gen.ts b/sdk/raea/src/facts.gen.ts
index e110a5d9..1c8c1830 100644
--- a/sdk/raea/src/facts.gen.ts
+++ b/sdk/raea/src/facts.gen.ts
@@ -143,6 +143,11 @@ not: Array<string>,
* the craft verb this ask is (skills/skills/raea/craft/verbs): one per ask, not one per note
*/
verb?: string,
+/**
+ * the composition it is about, its file from the project (its id after a `#` where the file registers several):
+ * where its check runs and its clip is cut from; none: every composition of the project
+ */
+of?: string,
/**
* the check that shows it met (DR6): one of raea's by name, or a .ts check by its path, as a rule names one
*/
diff --git a/tools/skills.sh b/tools/skills.sh
index d7ef409e..c6c1d319 100755
--- a/tools/skills.sh
+++ b/tools/skills.sh
@@ -6,7 +6,7 @@
#
# tools/skills.sh gen write skills/skills/raea/reference/{cli,feed,files,sdk,app,platforms}.md, and copy the craft guides
# (sdk/guides/craft, what `raea guide` prints) into the skill (copies() below: bevy/ as 3d/,
-# motion.md and motion/, and the router, floor, rubric, modes/ and verbs/ under craft/), so a
+# motion.md and motion/, and the router, floor, rubric, modes/, verbs/ and checks/ under craft/), so a
# clone of raea-skills reads whole without raea; commit them in raea-skills, then the pointer here
# tools/skills.sh check the drift gate (SK3, in L0): fails on a stale reference, a retired word, a flag a verb
# doesn't take, a RAEA_* variable nothing reads, or a relative link that goes nowhere, each
@@ -49,9 +49,11 @@ copies() {
for g in ROUTER.md floor.md rubric.md NOTICE; do printf '%s\tcraft/%s\n' "sdk/guides/craft/$g" "$g"; done
for g in sdk/guides/craft/modes/*.md; do printf '%s\tcraft/modes/%s\n' "$g" "${g##*/}"; done
for g in sdk/guides/craft/verbs/*.md; do printf '%s\tcraft/verbs/%s\n' "$g" "${g##*/}"; done
+ # the worked checks a note's ask copies into its project (DR6): each a raea/check system with its values and cheats
+ for g in sdk/guides/craft/checks/*.ts; do printf '%s\tcraft/checks/%s\n' "$g" "${g##*/}"; done
}
# the folders whose every file is a copy (a file there with no source is one whose guide was removed or renamed)
-COPY_DIRS="3d motion craft craft/modes craft/verbs"
+COPY_DIRS="3d motion craft craft/modes craft/verbs craft/checks"
SKILL_ONLY="3d/plugins.md 3d/rows.md"
HEAD_LINE="<!-- generated by tools/skills.sh gen; do not edit -->"
APP=${RAEA_APP:-apps/app}