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.

FP9a, FP7a: a fix checked against the flag it claims to fix, and a postmortem. `raea fingerprint score NEW --was OLD` says whether each of OLD's gating flags is fixed, still there, or looks disguised (nearer the axis's disguised defects than its clean work), and exits 1 unless all are fixed (fixed.rs). `raea fingerprint postmortem [PROJECT] [--ask N] [--tally]` scores every version in the project's feed, asks at most ten yes/no questions in the app where a head goes against the person's labels or is least sure, each with its moment as a clip, and --tally makes the answers evidence and prints each head's held-out AUC before and after (postmortem.rs)

shinyobjectze367fe8190fb
diff --git a/Cargo.lock b/Cargo.lock
index fc1126b6..ef82b54a 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -15487,6 +15487,7 @@ dependencies = [
"raea-sys-columns",
"raea-sys-fingerprint",
"serde",
+ "serde_json",
]
[[package]]
diff --git a/apps/fingerprint/src/lib.rs b/apps/fingerprint/src/lib.rs
index 50f8edbc..dd5e21b5 100644
--- a/apps/fingerprint/src/lib.rs
+++ b/apps/fingerprint/src/lib.rs
@@ -10,6 +10,7 @@ mod moving;
mod notes;
mod pairing;
mod pick;
+mod postmortem;
mod profiles;
mod reembed;
mod serve;
@@ -19,14 +20,15 @@ use std::path::Path;
pub use serve::serve;
-pub const USAGE: &str = "raea fingerprint new NAME [--who W] [--about TEXT] [--extends FP] [--kinds K,K] [--tags T,T] | raea fingerprint bootstrap FILE... [--from LIST] [--per N] | raea fingerprint teach FILE --axis A --at T [--bad|--good] [--span S] [--box x0,y0,x1,y1] [--words W] [--project P] | raea fingerprint approve FILE... [--project P] | raea fingerprint pair WORSE BETTER --axis A [--at T] [--then T2] | raea fingerprint versions V1 V2... | raea fingerprint profile REFS... --as NAME [--against LIST] | raea fingerprint score FILE [--json] [--sheet out.png] [--timeline] [--profile NAME] | raea fingerprint report [--json] | raea fingerprint which [PATH] [--json] | raea fingerprint use NAME [--in project|workspace] [PATH] | raea fingerprint diff A B [--json] | raea fingerprint share NAME [--in project|workspace] [PATH] | raea fingerprint reembed PLACE... | raea fingerprint read PROJECT [--by kimi|claude] | raea fingerprint readings [PROJECT] [--ask N] [--tally] | raea fingerprint learn-notes [PROJECT] | raea fingerprint move [--fp CHILD] [--to PARENT] [--axis A] [--source S] [--project P] | raea fingerprint stop [--fp NAME] (a person's sense of good work as axes with small heads over on-device encoders, docs/fingerprint.md: new makes ~/.raea/fingerprints/NAME with raea's base taxonomy in fingerprint.ts (or FP's axes with --extends), what it's for, the kinds of piece and project tags it judges, and every axis scoring from its words; bootstrap puts known defects into windows of real work and trains the mechanical axes, held out by source; teach adds a label at a moment; approve makes approved work clean on every axis, away from its notes; pair says one moment is better than another on an axis (a pick, a hand edit); versions makes weak pairs of noted moments the next version changed; score prints the moments it expects a note on first, then every axis per window with --json, a sheet PNG with --sheet, or the piece second by second in words with --timeline; profile takes the ranges of work you admire (loudness, tilt, cut rate, motion, brightness, contrast, saturation, sharpness), checked leave-one-out, and score --profile says what falls outside them, where and which way; report says each head's held-out score, labels, cheats, gate and what it can't judge; which says the one that judges a piece (its project's, its workspace's, then yours) and why, use pins one there, diff lists the axes two fingerprints rank the same evidence most differently on, and share copies one's taxonomy and evidence (no heads, no media) into a project or workspace for its team; reembed moves a fingerprint's evidence to this machine's encoders, re-embedding the rows whose media it finds; read has a fresh kimi or claude session read a project's pinned notes into kinds and axes, readings puts them to you to check and tallies your answers, and learn-notes makes the defects and praise evidence once you've agreed with 45 kinds and 40 axes in 50, each project's in the fingerprint that judges it; move takes a child's own labels (by axis, source or project) up into a fingerprint it extends, which never reads them otherwise)";
+pub const USAGE: &str = "raea fingerprint new NAME [--who W] [--about TEXT] [--extends FP] [--kinds K,K] [--tags T,T] | raea fingerprint bootstrap FILE... [--from LIST] [--per N] | raea fingerprint teach FILE --axis A --at T [--bad|--good] [--span S] [--box x0,y0,x1,y1] [--words W] [--project P] | raea fingerprint approve FILE... [--project P] | raea fingerprint pair WORSE BETTER --axis A [--at T] [--then T2] | raea fingerprint versions V1 V2... | raea fingerprint profile REFS... --as NAME [--against LIST] | raea fingerprint score FILE [--was OLD] [--json] [--sheet out.png] [--timeline] [--profile NAME] | raea fingerprint report [--json] | raea fingerprint which [PATH] [--json] | raea fingerprint use NAME [--in project|workspace] [PATH] | raea fingerprint diff A B [--json] | raea fingerprint share NAME [--in project|workspace] [PATH] | raea fingerprint reembed PLACE... | raea fingerprint read PROJECT [--by kimi|claude] | raea fingerprint readings [PROJECT] [--ask N] [--tally] | raea fingerprint learn-notes [PROJECT] | raea fingerprint move [--fp CHILD] [--to PARENT] [--axis A] [--source S] [--project P] | raea fingerprint postmortem [PROJECT] [--ask N] [--tally] | raea fingerprint stop [--fp NAME] (a person's sense of good work as axes with small heads over on-device encoders, docs/fingerprint.md: new makes ~/.raea/fingerprints/NAME with raea's base taxonomy in fingerprint.ts (or FP's axes with --extends), what it's for, the kinds of piece and project tags it judges, and every axis scoring from its words; bootstrap puts known defects into windows of real work and trains the mechanical axes, held out by source; teach adds a label at a moment; approve makes approved work clean on every axis, away from its notes; pair says one moment is better than another on an axis (a pick, a hand edit); versions makes weak pairs of noted moments the next version changed; score prints the moments it expects a note on first, then every axis per window with --json, a sheet PNG with --sheet, or the piece second by second in words with --timeline, and with --was OLD whether each of OLD's gating flags is fixed, still there, or looks disguised (nearer the axis's disguised defects than clean work); profile takes the ranges of work you admire (loudness, tilt, cut rate, motion, brightness, contrast, saturation, sharpness), checked leave-one-out, and score --profile says what falls outside them, where and which way; report says each head's held-out score, labels, cheats, gate and what it can't judge; which says the one that judges a piece (its project's, its workspace's, then yours) and why, use pins one there, diff lists the axes two fingerprints rank the same evidence most differently on, and share copies one's taxonomy and evidence (no heads, no media) into a project or workspace for its team; reembed moves a fingerprint's evidence to this machine's encoders, re-embedding the rows whose media it finds; read has a fresh kimi or claude session read a project's pinned notes into kinds and axes, readings puts them to you to check and tallies your answers, and learn-notes makes the defects and praise evidence once you've agreed with 45 kinds and 40 axes in 50, each project's in the fingerprint that judges it; move takes a child's own labels (by axis, source or project) up into a fingerprint it extends, which never reads them otherwise; postmortem scores every version in a project's feed and asks you at most ten yes/no questions in the app, each with its moment playing, where the fingerprint disagrees with your labels or is least sure, and --tally makes your answers evidence and says how each head's held-out score moved)";
/// Evaluates a .ts file's default export to its JSON (the CLI's spec host)
pub type Eval = fn(&Path) -> Result<String, String>;
/// The flags each verb takes, and whether each takes a value
-pub(crate) const FLAGS: [(&str, bool); 30] = [
+pub(crate) const FLAGS: [(&str, bool); 31] = [
("--fp", true),
+ ("--was", true),
("--to", true),
("--source", true),
("--kinds", true),
@@ -131,7 +133,7 @@ pub fn cli(args: &[String], eval: Eval) -> i32 {
"readings" => notes::readings_here(&args[1..], &std::env::current_dir().unwrap_or_default()),
"share" => pick::share_here(&args[1..], &std::env::current_dir().unwrap_or_default()),
"use" => pick::use_here(&args[1..], &std::env::current_dir().unwrap_or_default()),
- "new" | "bootstrap" | "teach" | "approve" | "pair" | "versions" | "learn-notes" | "move" | "reembed" | "profile" | "score" | "stop" => {
+ "new" | "bootstrap" | "teach" | "approve" | "pair" | "versions" | "learn-notes" | "move" | "postmortem" | "reembed" | "profile" | "score" | "stop" => {
let cwd = std::env::current_dir().unwrap_or_default();
let here = has(args, "--here") || std::env::var_os("RAEA_FINGERPRINT_HERE").is_some();
let (out, code) = if here { serve::here(args, &cwd, eval) } else { serve::call(args, &cwd) };
diff --git a/apps/fingerprint/src/notes.rs b/apps/fingerprint/src/notes.rs
index a71627f7..c2d37bfe 100644
--- a/apps/fingerprint/src/notes.rs
+++ b/apps/fingerprint/src/notes.rs
@@ -76,6 +76,21 @@ fn media(project: &Path, m: &Value) -> Option<PathBuf> {
[home.join(".raea/feed/media").join(p), project.join(p)].into_iter().find(|f| f.is_file())
}
+/// Every video in the project's feed, each version's, found on this machine (FP7a's postmortem looks back on them)
+pub fn videos(project: &Path) -> Vec<PathBuf> {
+ let mut out: Vec<PathBuf> = Vec::new();
+ for e in std::fs::read_dir(project.join(".raea/feed")).into_iter().flatten().flatten() {
+ let Some(post) = std::fs::read_to_string(e.path()).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok()) else { continue };
+ for m in post["media"].as_array().into_iter().flatten().filter(|m| m["kind"] == "video") {
+ if let Some(v) = media(project, m).filter(|v| !out.contains(v)) {
+ out.push(v);
+ }
+ }
+ }
+ out.sort();
+ out
+}
+
/// Every person's pinned note on a video in the project's feed
pub fn pinned(project: &Path) -> Vec<Reading> {
let name = project.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
diff --git a/apps/fingerprint/src/postmortem.rs b/apps/fingerprint/src/postmortem.rs
new file mode 100644
index 00000000..5b204e4e
--- /dev/null
+++ b/apps/fingerprint/src/postmortem.rs
@@ -0,0 +1,58 @@
+//! `raea fingerprint postmortem [PROJECT] [--ask N] [--tally]` (docs/fingerprint.feature FP7a; the picking, the clips
+//! and the questions are raea-sys-fingerprint-use's postmortem.rs). It scores every version of the project's pieces with
+//! the fingerprint that judges the project and asks at most ten yes/no questions in the app; `--tally` makes each answer
+//! an evidence row, retrains, and says how each head's held-out score moved.
+
+use crate::{Eval, flag, has};
+use anyhow::{Result, anyhow, bail};
+use raea_sys_columns::Encoders;
+use raea_sys_fingerprint::evidence::{Row, features};
+use raea_sys_fingerprint::retrain;
+use raea_sys_fingerprint_use::postmortem::{self as pm, MOST};
+use raea_sys_fingerprint_use::score::{Scored, score};
+use std::path::{Path, PathBuf};
+
+pub(crate) fn run(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval) -> Result<(String, i32)> {
+ let project = crate::pick::piece_in(args, cwd).parent().map(Path::to_path_buf).unwrap_or_else(|| cwd.to_path_buf());
+ let name = project.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
+ let (dir, fp, w) = crate::verbs::open(enc, args, eval, Some(&crate::pick::piece_in(args, cwd)))?;
+ let before = dir.trained()?.map(|t| t.0).ok_or_else(|| anyhow!("{} has no trained heads yet: `raea fingerprint bootstrap` or teach it first", fp.name))?;
+ if has(args, "--tally") {
+ let inbox = std::fs::read_to_string(PathBuf::from(std::env::var("HOME").unwrap_or_default()).join(format!(".raea/inbox/{}.jsonl", pm::INBOX))).unwrap_or_default();
+ let answers = pm::answered(&dir.dir, &inbox);
+ let mut l = dir.ledger()?;
+ // every tally adds every answer again, so tallying twice is safe
+ l.retain(|r| r.source != "postmortem");
+ for (x, yes) in &answers {
+ let c = enc.columns(&x.file)?;
+ let (a, b) = (x.a.min(c.dur), x.b.min(c.dur));
+ if b - a < 0.5 {
+ continue;
+ }
+ let who = fp.who.clone().unwrap_or_else(|| "me".into());
+ let row = Row { media: c.media.clone(), a, b, axis: x.axis.clone(), bad: *yes, weight: 1.0, who, source: "postmortem".into(), project: name.clone(), kind: None, region: None, words: Some(x.words.clone()), at: 0, pin: None };
+ l.push(row, &features(&c, a, b));
+ }
+ dir.write_ledger(&l)?;
+ let after = retrain(&dir, &fp, &w, &l, None)?;
+ let f = |v: Option<f64>| v.map_or("-".into(), |v| format!("{v:.2}"));
+ let mut out = format!("{} answers are evidence now\n", answers.len());
+ for (axis, was, now) in pm::moved(&before, &after) {
+ out += &format!(" {axis}: held out {} -> {}\n", f(was), f(now));
+ }
+ return Ok((out, 0));
+ }
+ let n = flag(args, "--ask").map_or(Ok(MOST), str::parse).map_err(|_| anyhow!("--ask takes a count"))?.min(MOST);
+ let files = crate::notes::videos(&project);
+ if files.is_empty() {
+ bail!("{} has no videos in its feed to look back on", project.display());
+ }
+ let scored = files.iter().map(|f| -> Result<Scored> { Ok(score(&fp, Some(&w), Some(&before), &enc.columns(f)?, &f.display().to_string())) }).collect::<Result<Vec<_>>>()?;
+ let asks = pm::picks(&scored, &before, &fp, &dir.ledger()?, n);
+ if asks.is_empty() {
+ return Ok((format!("nothing to ask: on {} versions, no head disagrees with you or sits near its flag\n", files.len()), 0));
+ }
+ let item = pm::ask(&std::env::current_exe()?, &dir.dir, &name, &asks)?;
+ let against = asks.iter().filter(|x| x.why == "disagrees with you").count();
+ Ok((format!("{} questions on {} versions put to you in the app ({item}): {against} where it disagrees with you, the rest where it's least sure; `raea fingerprint postmortem --tally` adds your answers\n", asks.len(), files.len()), 0))
+}
diff --git a/apps/fingerprint/src/verbs.rs b/apps/fingerprint/src/verbs.rs
index 83e33fc7..d52fd1d1 100644
--- a/apps/fingerprint/src/verbs.rs
+++ b/apps/fingerprint/src/verbs.rs
@@ -29,6 +29,7 @@ pub(crate) fn run(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval, s
"pair" | "versions" => paired(enc, args[0].as_str(), rest, cwd, eval),
"learn-notes" => learned(enc, rest, cwd, eval),
"move" => moved(enc, rest, eval),
+ "postmortem" => crate::postmortem::run(enc, rest, cwd, eval),
"profile" => {
let dir = crate::pick::chosen(rest, None).0;
crate::profiles::make(enc, &dir, rest, cwd).map(|o| (o, 0))
@@ -89,7 +90,7 @@ fn new(enc: &mut Encoders, args: &[String]) -> Result<(String, i32)> {
/// The fingerprint, its encoders checked against this machine's, and its words, made again when they changed
/// The fingerprint a verb uses (pick.rs: --fp, else the one that judges the file), its axes with its parents', and its
/// words
-fn open(enc: &mut Encoders, args: &[String], eval: Eval, file: Option<&Path>) -> Result<(Folder, Fingerprint, Words)> {
+pub(crate) fn open(enc: &mut Encoders, args: &[String], eval: Eval, file: Option<&Path>) -> Result<(Folder, Fingerprint, Words)> {
let dir = crate::pick::chosen(args, file).0;
let mut raw = dir.read(Some(eval))?;
let here = enc.pins();
@@ -294,8 +295,23 @@ fn scored(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval) -> Result
let mut s = score(&fp, Some(&w), trained.as_ref(), &c, &file.display().to_string());
let found = checks(&file);
arbitrate(&mut s, &fp, &found);
+ // FP9a: each gating flag on the cut before, judged on this one, and its axis's disguises rerun on the fix
+ let fixes = match flag(args, "--was") {
+ Some(old) => {
+ let was = at(cwd, old);
+ let mut ws = score(&fp, Some(&w), trained.as_ref(), &enc.columns(&was)?, &was.display().to_string());
+ arbitrate(&mut ws, &fp, &checks(&was));
+ Some(raea_sys_fingerprint_use::fixed::fixes(&ws, &s, &fp, &dir.ledger()?, &c))
+ }
+ None => None,
+ };
let mut out = if has(args, "--json") {
- serde_json::to_string_pretty(&json!({"fingerprint": {"name": fp.name, "about": fp.about, "why": why}, "scored": s, "checks": found.iter().map(|(r, a, b, says)| json!({"check": r, "a": a, "b": b, "says": says})).collect::<Vec<_>>()}))?
+ serde_json::to_string_pretty(&json!({"fingerprint": {"name": fp.name, "about": fp.about, "why": why}, "scored": s, "checks": found.iter().map(|(r, a, b, says)| json!({"check": r, "a": a, "b": b, "says": says})).collect::<Vec<_>>(), "fixes": fixes}))?
+ } else if let Some(f) = &fixes {
+ let mut t = format!("judged by {}: {why}\n", fp.name);
+ t += &raea_sys_fingerprint_use::fixed::said(f);
+ t += &summary(&s);
+ t
} else {
let mut t = format!("judged by {}: {why}\n", fp.name);
t += &summary(&s);
@@ -319,7 +335,8 @@ fn scored(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval) -> Result
sheet(&s, &frames, &pcm, &ticks, &|axis| fp.axis(axis).map(|a| a.modality), &png)?;
out += &format!("sheet: {}\n", png.display());
}
- Ok((out, i32::from(s.moments.iter().any(|m| m.gating))))
+ let unfixed = fixes.iter().flatten().any(|f| f.verdict != "fixed");
+ Ok((out, i32::from(unfixed || s.moments.iter().any(|m| m.gating))))
}
/// `raea fingerprint report`: report.json, read; no encoders needed
diff --git a/docs/fingerprint.feature b/docs/fingerprint.feature
index 53c852bf..edfdcabf 100644
--- a/docs/fingerprint.feature
+++ b/docs/fingerprint.feature
@@ -395,6 +395,11 @@ Feature: Fingerprint: a person's or a team's sense of good work, learned on thei
the person's history, and asks at most ten yes/no questions on them with `raea show --question`, each with the
moment playing
And each answer is an evidence row, and the report says how each head's held-out score moved
+ And so far (11-12): `raea fingerprint postmortem [PROJECT] [--ask N]` scores every video version in the project's
+ feed with the fingerprint that judges it, asks first where a head goes against the person's own label on that
+ moment, then where a head sits nearest its flag, one per axis and piece within 4 s, at most ten, as Yes/No
+ questions in one `raea show` item with the moment cut to a clip; `--tally` makes each answer a "postmortem" row,
+ retrains and prints each head's held-out AUC before and after. Not yet: running on its own when a project closes
Rule: FP8. Teams
@needs:FP2d @done
@@ -512,6 +517,11 @@ Feature: Fingerprint: a person's or a team's sense of good work, learned on thei
why not
And the agent is told the axis and the moment in the person's words, never a score or a threshold
And a fix is checked against the flag it claims to fix, and the axis's cheats are rerun on it
+ And so far (11-12): `raea fingerprint score NEW --was OLD` judges each of OLD's gating flags on NEW: still there
+ (the axis flags within a second of it), looks disguised (the moment is nearer the axis's disguised defects, its
+ cheat rows, than its clean work, so the fix hid the defect), or fixed; it exits 1 unless every flag is fixed.
+ The raea skill tells agents to score before posting, fix or say why, name the axis and moment and never a score,
+ and to check each fix with --was (raea-skills fingerprint-fix f6d6654)
Rule: FP11. Markup: the player asks for a mark that means "this thing"
@needs:FP5a
diff --git a/systems/fingerprint-use/Cargo.toml b/systems/fingerprint-use/Cargo.toml
index 017e674b..a2a340c5 100644
--- a/systems/fingerprint-use/Cargo.toml
+++ b/systems/fingerprint-use/Cargo.toml
@@ -13,5 +13,7 @@ raea-sys-fingerprint = { path = "../fingerprint" }
raea-sys-columns = { path = "../columns" }
serde = { version = "1", features = ["derive"] }
anyhow = "1"
+# a postmortem's asks kept beside the fingerprint, and the answers read from the inbox (postmortem.rs)
+serde_json = "1"
# the sheet (sheet.rs) is a PNG; a mark grown by EdgeTAM writes its frames and reads its mattes (grow.rs)
image = { version = "0.25", default-features = false, features = ["png"] }
diff --git a/systems/fingerprint-use/src/fixed.rs b/systems/fingerprint-use/src/fixed.rs
new file mode 100644
index 00000000..de947f10
--- /dev/null
+++ b/systems/fingerprint-use/src/fixed.rs
@@ -0,0 +1,114 @@
+//! A fix checked against the flag it claims to fix (docs/fingerprint.feature FP9a). An agent that changes a cut
+//! because of a gating flag scores the new cut with `--was OLD`: each of the old cut's gating moments is still there
+//! (the same axis flags near it), looks disguised, or is fixed. "Looks disguised" reruns the axis's cheats on the fix:
+//! the fixed moment is nearer the axis's disguised defects (a blur sharpened afterwards, a freeze under a slow zoom)
+//! than its clean work, so the head may have been fooled rather than the defect fixed. The times are the old cut's,
+//! matched within a second either way, so a fix that moves the moment far is read as fixed only by the head.
+
+use crate::score::{Moment, Scored};
+use raea_sys_columns::Columns;
+use raea_sys_fingerprint::evidence::{Ledger, features, slice};
+use raea_sys_fingerprint::taxonomy::Fingerprint;
+use serde::Serialize;
+use std::collections::BTreeMap;
+
+/// How far either way a flag in the new cut still counts as the old one, seconds
+const NEAR: f64 = 1.0;
+
+#[derive(Clone, Debug, Serialize)]
+pub struct Fix {
+ pub axis: String,
+ pub a: f64,
+ pub b: f64,
+ pub words: String,
+ /// "still there", "looks disguised" or "fixed"
+ pub verdict: &'static str,
+ pub why: String,
+}
+
+fn mean(rows: &[&[f32]]) -> Option<Vec<f32>> {
+ let n = rows.len();
+ (n > 0).then(|| (0..rows[0].len()).map(|j| rows.iter().map(|r| r[j]).sum::<f32>() / n as f32).collect())
+}
+
+fn cos(a: &[f32], b: &[f32]) -> f32 {
+ let (d, na, nb) = a.iter().zip(b).fold((0.0, 0.0, 0.0), |(d, na, nb), (x, y)| (d + x * y, na + x * x, nb + y * y));
+ d / (na.sqrt() * nb.sqrt()).max(1e-9)
+}
+
+/// The disguise a moment is nearest, when it is nearer one of the axis's disguised defects than its clean work
+pub fn disguised(l: &Ledger, axis: &str, m: raea_sys_columns::window::Modality, row: &[f32]) -> Option<String> {
+ let mut kinds: BTreeMap<String, Vec<&[f32]>> = BTreeMap::new();
+ let mut clean = Vec::new();
+ for (i, r) in l.rows.iter().enumerate() {
+ if r.source == "cheat" && r.axis == axis {
+ kinds.entry(r.kind.clone().unwrap_or_else(|| "disguised".into())).or_default().push(l.modality(i, m));
+ } else if r.source != "cheat" && !r.bad && (r.axis == axis || r.axis == "*") {
+ clean.push(l.modality(i, m));
+ }
+ }
+ let clean = cos(row, &mean(&clean)?);
+ kinds.into_iter().filter_map(|(k, rows)| Some((k, cos(row, &mean(&rows)?)))).filter(|(_, s)| *s > clean).max_by(|a, b| a.1.total_cmp(&b.1)).map(|(k, _)| k)
+}
+
+/// Each of `was`'s gating moments, judged on `now` (whose columns are `c`)
+pub fn fixes(was: &Scored, now: &Scored, fp: &Fingerprint, l: &Ledger, c: &Columns) -> Vec<Fix> {
+ let still = |m: &Moment| now.moments.iter().any(|n| n.axis == m.axis && n.a <= m.b + NEAR && n.b >= m.a - NEAR);
+ was.moments
+ .iter()
+ .filter(|m| m.gating)
+ .map(|m| {
+ let base = |verdict, why: String| Fix { axis: m.axis.clone(), a: m.a, b: m.b, words: m.words.clone(), verdict, why };
+ if still(m) {
+ return base("still there", format!("the new cut still flags {} here", m.axis));
+ }
+ let (a, b) = (m.a.min(c.dur), m.b.min(c.dur));
+ let looks = fp.axis(&m.axis).filter(|_| b > a).and_then(|x| disguised(l, &m.axis, x.modality, &features(c, a, b)[slice(x.modality)]));
+ match looks {
+ Some(k) => base("looks disguised", format!("nearer its disguised version ({k}) than clean work: fix the cause, not how it reads")),
+ None => base("fixed", format!("no {} flag near it now", m.axis)),
+ }
+ })
+ .collect()
+}
+
+/// The fixes as lines for the agent, in the person's words
+pub fn said(f: &[Fix]) -> String {
+ let fixed = f.iter().filter(|x| x.verdict == "fixed").count();
+ let mut t = format!("against the cut before: {fixed} of {} flags fixed\n", f.len());
+ for x in f {
+ t += &format!(" {} {} ({}): {}, {}\n", crate::score::clock(x.a), x.axis, x.words, x.verdict, x.why);
+ }
+ t
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use raea_sys_columns::window::Modality;
+ use raea_sys_fingerprint::evidence::{Row, width};
+
+ fn row(axis: &str, source: &str, bad: bool, kind: Option<&str>) -> Row {
+ Row { media: "m".into(), a: 0.0, b: 2.0, axis: axis.into(), bad, weight: 1.0, who: "me".into(), source: source.into(), project: "p".into(), kind: kind.map(Into::into), region: None, words: None, at: 0, pin: None }
+ }
+
+ #[test]
+ fn a_fix_nearer_a_disguise_than_clean_work_looks_disguised() {
+ let m = Modality::ALL[0];
+ let s = slice(m);
+ let at = |v: &[f32]| {
+ let mut f = vec![0.0; width()];
+ f[s.start..s.start + v.len()].copy_from_slice(v);
+ f
+ };
+ let mut l = Ledger::default();
+ l.push(row("blur", "damage", false, None), &at(&[1.0, 0.0, 0.0]));
+ l.push(row("*", "approval", false, None), &at(&[0.9, 0.1, 0.0]));
+ l.push(row("blur", "cheat", true, Some("sharpened")), &at(&[0.0, 1.0, 0.0]));
+ let fooled = &at(&[0.1, 1.0, 0.0])[s.clone()];
+ let clean = &at(&[1.0, 0.05, 0.0])[s.clone()];
+ assert_eq!(disguised(&l, "blur", m, fooled).as_deref(), Some("sharpened"));
+ assert_eq!(disguised(&l, "blur", m, clean), None);
+ assert_eq!(disguised(&l, "glow", m, fooled), None, "an axis with no disguises can't look disguised");
+ }
+}
diff --git a/systems/fingerprint-use/src/lib.rs b/systems/fingerprint-use/src/lib.rs
index 6725b911..7215d82a 100644
--- a/systems/fingerprint-use/src/lib.rs
+++ b/systems/fingerprint-use/src/lib.rs
@@ -5,10 +5,14 @@
//! - which.rs: which fingerprint judges a piece: its project's, its workspace's, then the person's (FP14c)
//! - diff.rs: where two fingerprints rank the same evidence differently (FP8b)
//! - profile.rs: ranges from work the person admires, and a piece critiqued against them (FP6e)
+//! - fixed.rs: a fix checked against the flag it claims to fix, and against the axis's disguises (FP9a)
+//! - postmortem.rs: a project looked back on, its least sure moments asked as yes/no questions (FP7a)
//! - grow.rs: a note's mark grown into its thing and tracked over its label by EdgeTAM (FP11b)
pub mod diff;
+pub mod fixed;
pub mod grow;
+pub mod postmortem;
pub mod profile;
pub mod score;
pub mod sheet;
diff --git a/systems/fingerprint-use/src/postmortem.rs b/systems/fingerprint-use/src/postmortem.rs
new file mode 100644
index 00000000..3ae20a38
--- /dev/null
+++ b/systems/fingerprint-use/src/postmortem.rs
@@ -0,0 +1,169 @@
+//! A postmortem (docs/fingerprint.feature FP7a): when a project closes, or on `raea fingerprint postmortem PROJECT`,
+//! every version of every piece is scored, and the moments where the fingerprint disagrees with the person's own
+//! labels, then those where its heads are least sure, become at most ten yes/no questions in the app, each with its
+//! moment playing. Each answer is an evidence row (source "postmortem"); `postmortem --tally` adds them and the report
+//! says how each head's held-out score moved.
+
+use crate::score::Scored;
+use anyhow::{Result, anyhow};
+use raea_sys_fingerprint::evidence::Ledger;
+use raea_sys_fingerprint::taxonomy::Fingerprint;
+use raea_sys_fingerprint::train::Trained;
+use serde::{Deserialize, Serialize};
+use std::collections::BTreeMap;
+use std::path::{Path, PathBuf};
+
+/// At most this many questions a postmortem
+pub const MOST: usize = 10;
+/// The inbox a postmortem's answers come to
+pub const INBOX: &str = "fingerprint";
+/// Two asks on one axis of one piece closer than this are one
+const APART: f64 = 4.0;
+
+#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
+pub struct Ask {
+ pub file: PathBuf,
+ pub media: String,
+ pub a: f64,
+ pub b: f64,
+ pub axis: String,
+ pub words: String,
+ /// "disagrees with you" or "least sure"
+ pub why: String,
+ /// lower is asked first
+ pub rank: f32,
+}
+
+/// The moments to ask about: where a head's flag goes against a label the person gave on that moment, then where a
+/// head is nearest its flag, in units of its flag-to-strong spread; one per axis and piece within APART seconds
+pub fn picks(scored: &[Scored], trained: &Trained, fp: &Fingerprint, l: &Ledger, most: usize) -> Vec<Ask> {
+ let mut all = Vec::new();
+ for s in scored {
+ for w in &s.windows {
+ for x in w.axes.iter().filter(|x| x.by == "head") {
+ let Some(h) = trained.heads.iter().find(|h| h.axis == x.axis) else { continue };
+ let Some(t) = h.flag else { continue };
+ let said = l.rows.iter().find(|r| r.media == s.media && r.a < w.b && r.b > w.a && !matches!(r.source.as_str(), "cheat" | "damage" | "pair") && (r.axis == x.axis || (r.axis == "*" && !r.bad)));
+ let (why, rank) = match said {
+ Some(r) if r.bad != x.flagged => ("disagrees with you", -1.0),
+ Some(_) => continue,
+ None => ("least sure", (x.value - t).abs() / (h.strong.unwrap_or(t + 1.0) - t).abs().max(1e-3)),
+ };
+ let words = fp.axis(&x.axis).and_then(|a| a.words.first().cloned()).unwrap_or_else(|| x.axis.clone());
+ all.push(Ask { file: PathBuf::from(&s.file), media: s.media.clone(), a: w.a, b: w.b, axis: x.axis.clone(), words, why: why.into(), rank });
+ }
+ }
+ }
+ all.sort_by(|a, b| a.rank.total_cmp(&b.rank));
+ let mut out: Vec<Ask> = Vec::new();
+ for x in all {
+ if out.len() >= most {
+ break;
+ }
+ if !out.iter().any(|o| o.media == x.media && o.axis == x.axis && (o.a - x.a).abs() < APART) {
+ out.push(x);
+ }
+ }
+ out
+}
+
+/// The moment cut to a clip to play beside its question (ffmpeg), else None and the whole piece plays
+pub fn clip(x: &Ask, out: &Path) -> Option<PathBuf> {
+ std::fs::create_dir_all(out.parent()?).ok()?;
+ let ok = std::process::Command::new("ffmpeg")
+ .args(["-y", "-loglevel", "error", "-ss", &format!("{:.2}", (x.a - 0.5).max(0.0)), "-t", &format!("{:.2}", x.b - x.a + 1.0), "-i"])
+ .arg(&x.file)
+ .args(["-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac"])
+ .arg(out)
+ .status()
+ .is_ok_and(|s| s.success());
+ ok.then(|| out.to_path_buf())
+}
+
+/// The asks put to the person through `raea` show, one item; returns the item and keeps the asks under it in
+/// DIR/postmortem.json, so the answers can be matched in order
+pub fn ask(raea: &Path, dir: &Path, project: &str, asks: &[Ask]) -> Result<String> {
+ let mut cmd = std::process::Command::new(raea);
+ cmd.args(["show", "--title", &format!("What raea isn't sure of in {project}"), "--inbox", INBOX]);
+ for (i, x) in asks.iter().enumerate() {
+ let play = clip(x, &dir.join(format!("postmortem/{i}.mp4"))).unwrap_or_else(|| x.file.clone());
+ let q = format!("{} at {}: is there {} here?", x.file.file_stem().map(|s| s.to_string_lossy()).unwrap_or_default(), crate::score::clock(x.a), x.words);
+ cmd.args(["--question", &q, "--preview"]).arg(&play).args(["--choice", "Yes", "--choice", "No"]);
+ }
+ let out = cmd.output()?;
+ let said = String::from_utf8_lossy(&out.stdout).into_owned();
+ let item = said.split(|c: char| c.is_whitespace() || "(),".contains(c)).find(|w| w.starts_with("i-show-")).ok_or_else(|| anyhow!("raea show didn't say its item: {said}{}", String::from_utf8_lossy(&out.stderr)))?;
+ let mut kept: BTreeMap<String, Vec<Ask>> = std::fs::read(dir.join("postmortem.json")).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default();
+ kept.insert(item.to_string(), asks.to_vec());
+ std::fs::write(dir.join("postmortem.json"), serde_json::to_vec_pretty(&kept)?)?;
+ Ok(item.to_string())
+}
+
+/// Every answered ask: the asks kept under each item, matched in order to the answers in the inbox
+pub fn answered(dir: &Path, inbox: &str) -> Vec<(Ask, bool)> {
+ let kept: BTreeMap<String, Vec<Ask>> = std::fs::read(dir.join("postmortem.json")).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default();
+ let mut out = Vec::new();
+ for line in inbox.lines() {
+ let Ok(v) = serde_json::from_str::<serde_json::Value>(line) else { continue };
+ let Some(asks) = v["item"].as_str().and_then(|i| kept.get(i)) else { continue };
+ for (k, x) in asks.iter().enumerate() {
+ match v["answers"][format!("q{}", k + 1)].as_str() {
+ Some("Yes") => out.push((x.clone(), true)),
+ Some("No") => out.push((x.clone(), false)),
+ _ => {}
+ }
+ }
+ }
+ out
+}
+
+/// Each head's held-out AUC before and after, for the axes that moved
+pub fn moved(before: &Trained, after: &Trained) -> Vec<(String, Option<f64>, Option<f64>)> {
+ after
+ .heads
+ .iter()
+ .filter_map(|h| {
+ let was = before.heads.iter().find(|b| b.axis == h.axis).and_then(|b| b.held_out);
+ (was != h.held_out).then(|| (h.axis.clone(), was, h.held_out))
+ })
+ .collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::score::{AxisScore, Window};
+ use raea_sys_fingerprint::evidence::{Row, width};
+ use raea_sys_fingerprint::train::AxisHead;
+
+ fn win(a: f64, value: f32, flagged: bool) -> Window {
+ Window { a, b: a + 2.0, axes: vec![AxisScore { axis: "blur".into(), value, by: "head", state: "advice".into(), band: Some("weak"), flagged, gating: false }], seen: None, heard: None, level: -20.0, overall: None }
+ }
+
+ #[test]
+ fn a_disagreement_comes_first_then_the_least_sure() {
+ let fp = raea_sys_fingerprint::taxonomy::base("me");
+ let trained = Trained { heads: vec![AxisHead { axis: "blur".into(), flag: Some(0.0), strong: Some(2.0), ..Default::default() }], weighting: None };
+ let s = Scored { file: "v1.mp4".into(), media: "h1".into(), dur: 30.0, fingerprint: "me".into(), moments: vec![], windows: vec![win(0.0, 1.5, true), win(10.0, 0.1, true), win(20.0, -1.9, false), win(11.0, 0.15, true)] };
+ let mut l = Ledger::default();
+ // the person approved the first moment: a flag there disagrees with them
+ let r = Row { media: "h1".into(), a: 0.0, b: 2.0, axis: "*".into(), bad: false, weight: 1.0, who: "me".into(), source: "approval".into(), project: "p".into(), kind: None, region: None, words: None, at: 0, pin: None };
+ l.push(r, &vec![0.0; width()]);
+ let p = picks(&[s], &trained, &fp, &l, 10);
+ assert_eq!(p.iter().map(|x| (x.a, x.why.as_str())).collect::<Vec<_>>(), [(0.0, "disagrees with you"), (10.0, "least sure"), (20.0, "least sure")], "11 s is the same moment as 10 s");
+ assert_eq!(picks(&[], &trained, &fp, &l, 10), []);
+ }
+
+ #[test]
+ fn answers_match_their_asks_in_order() {
+ let dir = std::env::temp_dir().join(format!("raea-pm-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let x = |a: f64| Ask { file: "v.mp4".into(), media: "h".into(), a, b: a + 2.0, axis: "blur".into(), words: "soft".into(), why: "least sure".into(), rank: 0.0 };
+ let kept = BTreeMap::from([("i-show-1".to_string(), vec![x(0.0), x(5.0), x(9.0)])]);
+ std::fs::write(dir.join("postmortem.json"), serde_json::to_vec(&kept).unwrap()).unwrap();
+ let inbox = "{\"item\": \"i-show-1\", \"answers\": {\"q1\": \"Yes\", \"q3\": \"No\"}}\n{\"item\": \"i-show-other\", \"answers\": {\"q1\": \"Yes\"}}";
+ let a = answered(&dir, inbox);
+ let _ = std::fs::remove_dir_all(&dir);
+ assert_eq!(a, [(x(0.0), true), (x(9.0), false)]);
+ }
+}