mirror of
https://github.com/shinyobjectz/raea.git
synced 2026-12-01 06:53:19 -10:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f2d0e0335c | ||
|
|
b4fa9ae676 | ||
|
|
5aa6c4cd36 | ||
|
|
ad8187aefd | ||
|
|
1bfd0388b0 | ||
|
|
cbd7649e02 | ||
|
|
fc83cf7446 | ||
|
|
2bbf0179fc | ||
|
|
dcd1107a9f | ||
|
|
bf07a473ae | ||
|
|
f9b6f22ecf | ||
|
|
fcd6e12c03 | ||
|
|
d7a755c08b | ||
|
|
b776edd026 | ||
|
|
9a289e072c | ||
|
|
4bc503d81d | ||
|
|
4e252226a6 | ||
|
|
ca184a08c9 | ||
|
|
cceec65c38 | ||
|
|
fac78b331b | ||
|
|
ae49b9f3c9 | ||
|
|
edf25e43c0 | ||
|
|
4a563b9cf6 | ||
|
|
ea5e9015e7 | ||
|
|
d8c392b69a | ||
|
|
035783ae0c | ||
|
|
08a3904127 | ||
|
|
cae6d2201c | ||
|
|
b8d38aa2c0 | ||
|
|
d685762382 | ||
|
|
c96de52402 | ||
|
|
b4e6f54d55 | ||
|
|
d145985058 | ||
|
|
03685d6139 | ||
|
|
620c796095 | ||
|
|
37846080a7 | ||
|
|
e24034ee10 | ||
|
|
9f4990cd90 | ||
|
|
7026280df3 | ||
|
|
df9d1d11d5 | ||
|
|
e60a8bc5fe | ||
|
|
1496780fa4 | ||
|
|
2cb2136348 | ||
|
|
e368a5dbcb | ||
|
|
e3dfcb96d1 | ||
|
|
f845ef0add | ||
|
|
cb01f542c0 | ||
|
|
054738329d | ||
|
|
e85de83289 | ||
|
|
06090e06cd | ||
|
|
7729997d96 | ||
|
|
8818eaa2ec | ||
|
|
b715d70366 | ||
|
|
2c6132a460 | ||
|
|
1be8199c85 | ||
|
|
3599e18b6f | ||
|
|
923163e7b9 | ||
|
|
691673f616 | ||
|
|
edd00ee9ca | ||
|
|
23f5a5ce53 | ||
|
|
a5a81f22b8 | ||
|
|
e05cee0c73 | ||
|
|
50a695f0fb | ||
|
|
c65baf2c81 | ||
|
|
d679fa1cc4 | ||
|
|
bf74492d50 | ||
|
|
43cfe87121 | ||
|
|
a2477cd71e | ||
|
|
33896c4518 | ||
|
|
c7d7b59dfb | ||
|
|
33380411d8 | ||
|
|
b537bcfffd | ||
|
|
af293fcc35 | ||
|
|
e81d06dd8b | ||
|
|
96d2820589 | ||
|
|
09eeb21fe9 | ||
|
|
ea5fc2e5ef | ||
|
|
d415e0c59d | ||
|
|
7452b0d90c | ||
|
|
d6d97c3b8d | ||
|
|
6c106fb8f4 | ||
|
|
869318073a | ||
|
|
cd268ef764 | ||
|
|
b8d21bf712 | ||
|
|
e652168202 | ||
|
|
6abeb6ed43 | ||
|
|
3dc3096963 | ||
|
|
55d9eeaa50 | ||
|
|
bf984d4656 | ||
|
|
0902d43201 | ||
|
|
5189132ef8 | ||
|
|
0f9da00368 | ||
|
|
9632d542cd | ||
|
|
d9a5296796 | ||
|
|
53d5f94888 | ||
|
|
a504787ad3 | ||
|
|
05fb89ab72 | ||
|
|
44ca3f16d6 | ||
|
|
8a51aa0433 | ||
|
|
677ca278ba | ||
|
|
9eb649bf98 | ||
|
|
1e8c404738 | ||
|
|
535acb5a4f | ||
|
|
8579b43228 | ||
|
|
e367fe8190 | ||
|
|
c6acc16633 | ||
|
|
6c7889dbf7 | ||
|
|
620ccb4093 | ||
|
|
aca025d343 | ||
|
|
e4b607e7f8 | ||
|
|
0226baca9a | ||
|
|
760fcc9ec8 | ||
|
|
4dcfa760b1 | ||
|
|
85b877f06b | ||
|
|
28fd448ea2 | ||
|
|
db58ead2c9 | ||
|
|
6f253b3fe5 | ||
|
|
64dfd63cd7 | ||
|
|
fb11b58f6f | ||
|
|
f89873c1df | ||
|
|
853b6ab3dc | ||
|
|
a983349265 | ||
|
|
ea741f6bef | ||
|
|
5d181dae28 | ||
|
|
bb7e6716b4 | ||
|
|
6cb250a531 | ||
|
|
99e3fe0751 | ||
|
|
ebff73dbc6 | ||
|
|
734b172d34 | ||
|
|
b30eb6aa88 | ||
|
|
fb4572f284 | ||
|
|
eb8d3ad795 | ||
|
|
203c26621c | ||
|
|
a5d89e95c1 | ||
|
|
37fc50782d | ||
|
|
34629d33b8 | ||
|
|
6da2995575 | ||
|
|
c7e857b243 | ||
|
|
657664d7d9 | ||
|
|
cb87e0cd59 | ||
|
|
b3fe2699d0 | ||
|
|
8a2f9c78ab | ||
|
|
2d869d719b | ||
|
|
272b94e765 | ||
|
|
ee171c4f85 | ||
|
|
7fb2194503 | ||
|
|
fc7bfa3a0c | ||
|
|
593ebb5226 | ||
|
|
97e03e7447 | ||
|
|
559d8274e0 | ||
|
|
645b0853cc | ||
|
|
e165d0c4a8 | ||
|
|
d1e61bee2b | ||
|
|
875006089f | ||
|
|
163f0b9e00 | ||
|
|
76a4ef7885 | ||
|
|
a185361869 | ||
|
|
e90d70f0dc | ||
|
|
6d8623ca9b | ||
|
|
2b8b43a420 | ||
|
|
ab0babcce7 | ||
|
|
09ee785138 | ||
|
|
6f88437dc1 | ||
|
|
6e79971b12 | ||
|
|
11dab02b51 | ||
|
|
6177e27d51 | ||
|
|
a78fb95e75 | ||
|
|
be220a6064 | ||
|
|
7fb6251bf9 | ||
|
|
5d320bc96e | ||
|
|
3de2c63bab | ||
|
|
c89de2a778 | ||
|
|
d70c8e6604 | ||
|
|
dfca0bcf12 | ||
|
|
14870df064 | ||
|
|
6ba881cf0f | ||
|
|
de994972cd | ||
|
|
13daeb9976 |
No files matched your search
@@ -3,6 +3,15 @@
|
||||
[target.aarch64-apple-darwin]
|
||||
linker = "tools/link-jit.sh"
|
||||
|
||||
# every Windows executable's main thread gets 8 MB of stack, as on macOS and Linux (Windows' default is 1 MB). The
|
||||
# desktop app's raea-page-host overflowed 1 MB inside a window callback (#112); engine/cli/build.rs did this for raea
|
||||
# alone. A DLL's link ignores /STACK.
|
||||
[target.x86_64-pc-windows-msvc]
|
||||
rustflags = ["-C", "link-arg=/STACK:8388608"]
|
||||
|
||||
[target.aarch64-pc-windows-msvc]
|
||||
rustflags = ["-C", "link-arg=/STACK:8388608"]
|
||||
|
||||
# no strip after linking: rustc's strip pass re-signs the binary and drops the entitlement (release has no debug info
|
||||
# of its own; std's stays)
|
||||
[profile.release]
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
{
|
||||
"name": "raea",
|
||||
"owner": { "name": "Shane Murphy", "url": "https://raea.io" },
|
||||
"owner": { "name": "raea", "url": "https://raea.io" },
|
||||
"metadata": {
|
||||
"description": "raea's plugin for Claude, from the skills/ folder of shinyobjectz/raea-skills: the raea skill and its hooks."
|
||||
},
|
||||
"plugins": [
|
||||
{
|
||||
"name": "raea",
|
||||
"source": "./",
|
||||
"description": "Make video, motion graphics, games and 3D with raea, the Render Anything Engine."
|
||||
"source": { "source": "git-subdir", "url": "https://github.com/shinyobjectz/raea-skills.git", "path": "skills" },
|
||||
"description": "Make video, motion graphics, games and 3D scenes with raea, the Render Anything Engine: the raea skill, and hooks that run raea's quick check on a composition after it's saved and show media in the raea app instead of the Mac's viewer."
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
{
|
||||
"name": "raea",
|
||||
"version": "0.1.0",
|
||||
"description": "Make video, motion graphics, games and 3D with raea, the Render Anything Engine: write raea compositions, render them on the GPU, check the frames.",
|
||||
"author": { "name": "Shane Murphy", "url": "https://raea.io" },
|
||||
"homepage": "https://raea.io",
|
||||
"repository": "https://github.com/shinyobjectz/raea",
|
||||
"license": "FSL-1.1-ALv2",
|
||||
"skills": ["./skills/skills/raea"],
|
||||
"keywords": ["video", "motion-graphics", "game-development", "rendering", "bevy", "react", "agent-skills"]
|
||||
}
|
||||
@@ -61,7 +61,9 @@ jobs:
|
||||
run: |
|
||||
rustup show active-toolchain
|
||||
sudo apt-get update && sudo apt-get install -y ripgrep
|
||||
cargo install --locked cargo-shear cargo-dupes
|
||||
# the versions L0 runs on the Mac, so a new release can't change the verdict (cargo-shear 1.14.1 calls
|
||||
# engine/cli's feature-only ignores redundant, which 1.14.0 needs; both ran red on main 11-13)
|
||||
cargo install --locked [email protected] [email protected]
|
||||
- name: layers
|
||||
run: bash tools/layers.sh
|
||||
- name: names
|
||||
@@ -113,4 +115,7 @@ jobs:
|
||||
- name: cargo check
|
||||
run: cargo check --locked -p raea-cli --tests
|
||||
- name: unit tests (the crates with no GPU or media device)
|
||||
run: cargo test --locked -p raea-io-media -p raea-core-fonts -p raea-native
|
||||
# debug info off: with it the test binaries of the app crates filled 27 GB of a runner's disk (#90)
|
||||
env:
|
||||
CARGO_PROFILE_TEST_DEBUG: "0"
|
||||
run: cargo test --locked -p raea-io-media -p raea-core-fonts -p raea-native -p raea-core-brief -p raea-core-k -p raea-bundle -p raea-app-check -p raea-app-check-flash -p raea-io-ffmpeg -p raea-app-workspace -p raea-app-tools -p raea-app-targets
|
||||
+101
-11
@@ -60,9 +60,17 @@ jobs:
|
||||
- os: ubuntu-24.04
|
||||
lib: libraea_bundle.so
|
||||
extra: raea-perceive
|
||||
runs-on: ${{ matrix.os }}
|
||||
# a faster runner when the repo names one: vars RELEASE_MAC_RUNNER, RELEASE_LINUX_RUNNER, RELEASE_WINDOWS_RUNNER hold
|
||||
# a JSON list of runs-on labels (Namespace's: a machine and a cache volume); else GitHub's
|
||||
# own, a 3-core M1 with 7 GB on the Mac, where a cold build took 3 hours
|
||||
runs-on: ${{ (matrix.os == 'macos-15' && vars.RELEASE_MAC_RUNNER && fromJSON(vars.RELEASE_MAC_RUNNER)) || (matrix.os == 'ubuntu-24.04' && vars.RELEASE_LINUX_RUNNER && fromJSON(vars.RELEASE_LINUX_RUNNER)) || matrix.os }}
|
||||
# a cold thin-LTO build of raea-cli with the plugin catalog is the long part; GitHub's own limit is 6 hours
|
||||
timeout-minutes: 340
|
||||
env:
|
||||
# the compile cache (the "Compile cache" step): an R2 bucket, read and written by every build
|
||||
RELEASE_CACHE_ENDPOINT: ${{ secrets.RELEASE_CACHE_ENDPOINT }}
|
||||
AWS_ACCESS_KEY_ID: ${{ secrets.RELEASE_CACHE_KEY_ID }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ secrets.RELEASE_CACHE_SECRET }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
@@ -95,7 +103,7 @@ jobs:
|
||||
# rc3's build left 576 MB of macos-15's 320 GB free, and rc4's dSYMs (#88) ran it out linking raea-page-host
|
||||
# (ld: write() failed, errno=28): the image's other Xcodes and the Android and .NET SDKs go first
|
||||
- name: Room for the build
|
||||
if: runner.os == 'macOS' && env.RAEA_PROMOTED_FROM == ''
|
||||
if: runner.os == 'macOS' && env.RAEA_PROMOTED_FROM == '' && vars.RELEASE_MAC_RUNNER == ''
|
||||
run: |
|
||||
df -h . | tail -1
|
||||
keep=$(cd "$(xcode-select -p)/../.." && pwd -P)
|
||||
@@ -104,14 +112,48 @@ jobs:
|
||||
wait
|
||||
echo "kept $keep"
|
||||
df -h . | tail -1
|
||||
# The compile cache: sccache on an R2 bucket. GitHub's own cache can't carry a release build: a tag's run reads
|
||||
# only its own tag's caches and the default branch's (so rc3's never reached rc4), and the repo's 10 GB are CI's.
|
||||
# A bucket is read by every tag. A cold build fills it; a candidate after a small change compiles only the crates
|
||||
# that changed and the ones above them. Linking (thin LTO) and build scripts' runs aren't cached. With no secrets
|
||||
# (a fork) the build runs as before, uncached.
|
||||
# the build folder and cargo's downloads kept between runs on the runner's cache volume (a Namespace runner,
|
||||
# whose labels attach one), so a candidate rebuilds only what changed and links;
|
||||
# sccache below still serves the workspace's own crates, which a fresh checkout's file times mark as changed
|
||||
- name: The build folder, kept on the runner's cache volume
|
||||
if: env.RAEA_PROMOTED_FROM == '' && startsWith(runner.name, 'nsc-')
|
||||
uses: namespacelabs/nscloud-cache-action@v1
|
||||
with:
|
||||
path: |
|
||||
${{ github.workspace }}/target
|
||||
~/.cargo/registry
|
||||
~/.cargo/git
|
||||
- name: Compile cache (sccache)
|
||||
if: env.RAEA_PROMOTED_FROM == '' && env.AWS_ACCESS_KEY_ID != ''
|
||||
uses: mozilla-actions/[email protected]
|
||||
# the script from this workflow's own commit: a dispatched run (a dry run that fills the cache) builds an older
|
||||
# tag, whose tree may not have it
|
||||
- name: The compile cache's script
|
||||
if: env.RAEA_PROMOTED_FROM == '' && env.AWS_ACCESS_KEY_ID != ''
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.sha }}
|
||||
path: .workflow
|
||||
sparse-checkout: tools/release/compile-cache.sh
|
||||
sparse-checkout-cone-mode: false
|
||||
- name: Use the compile cache
|
||||
if: env.RAEA_PROMOTED_FROM == '' && env.AWS_ACCESS_KEY_ID != ''
|
||||
run: bash .workflow/tools/release/compile-cache.sh
|
||||
- name: Build
|
||||
if: env.RAEA_PROMOTED_FROM == ''
|
||||
run: |
|
||||
feat=$(bash tools/bevy-plugins.sh features sdk/raea/bench/bevy-plugins)
|
||||
cargo build --profile dist --locked -p raea-cli --bin raea --no-default-features --features "$feat"
|
||||
cargo build --profile dist --locked -p raea-rune-host
|
||||
cargo build --profile dist --locked -p raea-page-host --features window
|
||||
if [ -n "${{ matrix.extra }}" ]; then cargo build --profile dist --locked -p ${{ matrix.extra }}; fi
|
||||
t() { s=$SECONDS; "$@"; echo "::notice::${{ runner.os }} $(( (SECONDS - s) / 60 )) min: ${*:7}"; }
|
||||
t cargo build --profile dist --locked -p raea-cli --bin raea --no-default-features --features "$feat"
|
||||
t cargo build --profile dist --locked -p raea-rune-host
|
||||
t cargo build --profile dist --locked -p raea-page-host --features window
|
||||
if [ -n "${{ matrix.extra }}" ]; then t cargo build --profile dist --locked -p ${{ matrix.extra }}; fi
|
||||
if [ -n "${RUSTC_WRAPPER:-}" ]; then sccache --show-stats; fi
|
||||
mkdir ship
|
||||
cp target/dist/raea target/dist/${{ matrix.lib }} target/dist/raea-rune-host target/dist/raea-page-host ship/
|
||||
if [ -n "${{ matrix.extra }}" ]; then cp target/dist/${{ matrix.extra }} ship/; fi
|
||||
@@ -124,6 +166,8 @@ jobs:
|
||||
run: bash tools/release/promoted-bins.sh "$RAEA_PROMOTED_FROM" ship
|
||||
# the packing and its checks need only ship/, and macos-15's disk ran out packing rc1 with target/ kept
|
||||
- name: Free the build's disk
|
||||
# not the cache volume's build folder, which the next candidate starts from (a bind mount on Linux)
|
||||
if: ${{ !startsWith(runner.name, 'nsc-') }}
|
||||
run: |
|
||||
df -h . | tail -1
|
||||
rm -rf target
|
||||
@@ -177,8 +221,13 @@ jobs:
|
||||
# accept no licence and download no Microsoft files). The C runtime is the DLL one (the VC++ redistributable): ort's
|
||||
# prebuilt ONNX Runtime is built against it, so crt-static doesn't link (LNK2019 on __imp_ symbols, 10-29).
|
||||
windows:
|
||||
runs-on: windows-latest
|
||||
runs-on: ${{ (vars.RELEASE_WINDOWS_RUNNER && fromJSON(vars.RELEASE_WINDOWS_RUNNER)) || 'windows-latest' }}
|
||||
timeout-minutes: 350
|
||||
env:
|
||||
# the compile cache, as build's
|
||||
RELEASE_CACHE_ENDPOINT: ${{ secrets.RELEASE_CACHE_ENDPOINT }}
|
||||
AWS_ACCESS_KEY_ID: ${{ secrets.RELEASE_CACHE_KEY_ID }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ secrets.RELEASE_CACHE_SECRET }}
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
@@ -195,6 +244,21 @@ jobs:
|
||||
- name: Toolchain (rust-toolchain.toml's pin)
|
||||
if: env.RAEA_PROMOTED_FROM == ''
|
||||
run: rustup show active-toolchain || rustup toolchain install
|
||||
# nasm, which rav1d's and openh264-sys2's build scripts run: GitHub's Windows image has 2.16, Namespace's has none
|
||||
# (rc3's dry run there stopped at "Unable to run nasm: program not found"). Always NASM's own 2.16.03 zip, never
|
||||
# Chocolatey's: rc4 took Chocolatey's newest, and raea.exe failed to link 135 of openh264's SIMD routines
|
||||
# (WelsSampleSad16x8_sse2 and the rest unresolved) though openh264's C++ was built to call them
|
||||
- name: nasm
|
||||
if: env.RAEA_PROMOTED_FROM == ''
|
||||
run: |
|
||||
v=2.16.03
|
||||
curl -fsSL --retry 3 -o "$RUNNER_TEMP/nasm.zip" "https://www.nasm.us/pub/nasm/releasebuilds/$v/win64/nasm-$v-win64.zip"
|
||||
unzip -q "$RUNNER_TEMP/nasm.zip" -d "$RUNNER_TEMP"
|
||||
# Git Bash on Windows has no /dev/stderr (rc5 stopped here): capture, print, then match
|
||||
out=$("$RUNNER_TEMP/nasm-$v/nasm.exe" -v)
|
||||
echo "$out"
|
||||
case $out in *"version $v"*) ;; *) echo "::error::expected NASM $v, got: $out"; exit 1 ;; esac
|
||||
echo "$RUNNER_TEMP/nasm-$v" >> "$GITHUB_PATH"
|
||||
# jq for Windows ends -r lines with CRLF, so tools/bevy-plugins.sh read "ahoy\r" and lost its Bevy 0.20 block
|
||||
# (feature `ahoy` not found, 11-04); -b writes LF
|
||||
- name: jq that writes LF
|
||||
@@ -219,14 +283,40 @@ jobs:
|
||||
done < <(tr -d '\r' < tools/release/models.tsv)
|
||||
# the app targets' hosts a cargo call each: with raea-cli's crates in one call taffy's features unify and
|
||||
# rune-taffy doesn't build; raea-perceive (`raea song`'s map, #43) a call of its own too
|
||||
- name: The build folder, kept on the runner's cache volume (as build's)
|
||||
if: env.RAEA_PROMOTED_FROM == '' && startsWith(runner.name, 'nsc-')
|
||||
uses: namespacelabs/nscloud-cache-action@v1
|
||||
with:
|
||||
path: |
|
||||
${{ github.workspace }}/target
|
||||
~/.cargo/registry
|
||||
~/.cargo/git
|
||||
- name: Compile cache (sccache, as build's)
|
||||
if: env.RAEA_PROMOTED_FROM == '' && env.AWS_ACCESS_KEY_ID != ''
|
||||
uses: mozilla-actions/[email protected]
|
||||
# the script from this workflow's own commit: a dispatched run (a dry run that fills the cache) builds an older
|
||||
# tag, whose tree may not have it
|
||||
- name: The compile cache's script
|
||||
if: env.RAEA_PROMOTED_FROM == '' && env.AWS_ACCESS_KEY_ID != ''
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.sha }}
|
||||
path: .workflow
|
||||
sparse-checkout: tools/release/compile-cache.sh
|
||||
sparse-checkout-cone-mode: false
|
||||
- name: Use the compile cache
|
||||
if: env.RAEA_PROMOTED_FROM == '' && env.AWS_ACCESS_KEY_ID != ''
|
||||
run: bash .workflow/tools/release/compile-cache.sh
|
||||
- name: Build
|
||||
if: env.RAEA_PROMOTED_FROM == ''
|
||||
run: |
|
||||
feat=$(bash tools/bevy-plugins.sh features sdk/raea/bench/bevy-plugins)
|
||||
cargo build --profile dist --locked -p raea-cli --bin raea --no-default-features --features "$feat"
|
||||
cargo build --profile dist --locked -p raea-rune-host
|
||||
cargo build --profile dist --locked -p raea-page-host --features window
|
||||
cargo build --profile dist --locked -p raea-perceive
|
||||
t() { s=$SECONDS; "$@"; echo "::notice::Windows $(( (SECONDS - s) / 60 )) min: ${*:7}"; }
|
||||
t cargo build --profile dist --locked -p raea-cli --bin raea --no-default-features --features "$feat"
|
||||
t cargo build --profile dist --locked -p raea-rune-host
|
||||
t cargo build --profile dist --locked -p raea-page-host --features window
|
||||
t cargo build --profile dist --locked -p raea-perceive
|
||||
if [ -n "${RUSTC_WRAPPER:-}" ]; then sccache --show-stats; fi
|
||||
- name: The candidate's binaries (tools/release/promoted-bins.sh)
|
||||
if: env.RAEA_PROMOTED_FROM != ''
|
||||
env:
|
||||
|
||||
Generated
+264
-11
@@ -4165,6 +4165,8 @@ dependencies = [
|
||||
"cexpr",
|
||||
"clang-sys",
|
||||
"itertools 0.13.0",
|
||||
"log",
|
||||
"prettyplease",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"regex",
|
||||
@@ -5677,8 +5679,18 @@ version = "0.20.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee"
|
||||
dependencies = [
|
||||
"darling_core",
|
||||
"darling_macro",
|
||||
"darling_core 0.20.11",
|
||||
"darling_macro 0.20.11",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "darling"
|
||||
version = "0.24.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec"
|
||||
dependencies = [
|
||||
"darling_core 0.24.1",
|
||||
"darling_macro 0.24.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5695,17 +5707,41 @@ dependencies = [
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "darling_core"
|
||||
version = "0.24.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff"
|
||||
dependencies = [
|
||||
"ident_case",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"strsim 0.11.1",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "darling_macro"
|
||||
version = "0.20.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead"
|
||||
dependencies = [
|
||||
"darling_core",
|
||||
"darling_core 0.20.11",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "darling_macro"
|
||||
version = "0.24.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785"
|
||||
dependencies = [
|
||||
"darling_core 0.24.1",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dary_heap"
|
||||
version = "0.3.9"
|
||||
@@ -5858,7 +5894,7 @@ version = "0.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e0df63c21a4383f94bd5388564829423f35c316aed85dc4f8427aded372c7c0d"
|
||||
dependencies = [
|
||||
"darling",
|
||||
"darling 0.20.11",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
@@ -6171,7 +6207,7 @@ version = "0.20.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2d5bcf7b024d6835cfb3d473887cd966994907effbe9227e8c8219824d06c4e8"
|
||||
dependencies = [
|
||||
"darling",
|
||||
"darling 0.20.11",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
@@ -10117,6 +10153,15 @@ version = "0.15.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e20f57f9918e5bd7bc58c22cdd70a6afc7375d4dd9683af5f2b34bd3d2bba619"
|
||||
|
||||
[[package]]
|
||||
name = "mach-sys"
|
||||
version = "0.5.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "48460c2e82a3a0de197152fdf8d2c2d5e43adc501501553e439bf2156e6f87c7"
|
||||
dependencies = [
|
||||
"fastrand",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mach2"
|
||||
version = "0.4.3"
|
||||
@@ -10415,6 +10460,66 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mlx-internal-macros"
|
||||
version = "0.34.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f11a82b6a4730c2c3778469d186cc3ee9585a5b27a8ffcdfd3c96179b76a895d"
|
||||
dependencies = [
|
||||
"darling 0.24.1",
|
||||
"itertools 0.15.0",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mlx-macros"
|
||||
version = "0.34.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32fc73395b87b961f5556e10104e7c08ed72c500765f44d38e320a6ac83977ed"
|
||||
dependencies = [
|
||||
"darling 0.24.1",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mlx-rs"
|
||||
version = "0.34.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2f0d7721525b23f77bc38d7757e6c17ea7c925cd2b2889ce86965a17b5e85e86"
|
||||
dependencies = [
|
||||
"dyn-clone",
|
||||
"half",
|
||||
"itertools 0.15.0",
|
||||
"libc",
|
||||
"mach-sys",
|
||||
"mlx-internal-macros",
|
||||
"mlx-macros",
|
||||
"mlx-sys",
|
||||
"num-complex",
|
||||
"num-traits",
|
||||
"num_enum",
|
||||
"parking_lot",
|
||||
"paste",
|
||||
"smallvec",
|
||||
"strum 0.28.0",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mlx-sys"
|
||||
version = "0.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "da965f83ce211b80f9b681d9bbd6fa625fe6bb2e659ba7bc55dd95eea8d3b028"
|
||||
dependencies = [
|
||||
"bindgen",
|
||||
"cc",
|
||||
"cmake",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mock_instant"
|
||||
version = "0.6.1"
|
||||
@@ -13214,6 +13319,16 @@ version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa"
|
||||
|
||||
[[package]]
|
||||
name = "prettyplease"
|
||||
version = "0.2.37"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "primal-check"
|
||||
version = "0.3.4"
|
||||
@@ -13615,13 +13730,19 @@ dependencies = [
|
||||
name = "raea-app-check"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"raea-app-check-flash",
|
||||
"raea-core-brief",
|
||||
"raea-core-facts",
|
||||
"raea-io-ffmpeg",
|
||||
"raea-io-trace",
|
||||
"raea-sys-measure",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-app-check-flash"
|
||||
version = "0.1.0"
|
||||
|
||||
[[package]]
|
||||
name = "raea-app-ci"
|
||||
version = "0.1.0"
|
||||
@@ -13662,6 +13783,21 @@ dependencies = [
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-app-fingerprint"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"fastrand",
|
||||
"raea-app-check",
|
||||
"raea-sys-columns",
|
||||
"raea-sys-fingerprint",
|
||||
"raea-sys-fingerprint-things",
|
||||
"raea-sys-fingerprint-use",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-app-game"
|
||||
version = "0.1.0"
|
||||
@@ -14030,6 +14166,7 @@ dependencies = [
|
||||
"raea-app-ci",
|
||||
"raea-app-direction",
|
||||
"raea-app-engines",
|
||||
"raea-app-fingerprint",
|
||||
"raea-app-game",
|
||||
"raea-app-judge",
|
||||
"raea-app-media",
|
||||
@@ -14504,6 +14641,7 @@ dependencies = [
|
||||
"blitz-dom",
|
||||
"blitz-html",
|
||||
"image",
|
||||
"parley",
|
||||
"raea-core-wire",
|
||||
"raea-gpu-device",
|
||||
"raea-io-media",
|
||||
@@ -14519,6 +14657,7 @@ dependencies = [
|
||||
"serde_json",
|
||||
"stylo",
|
||||
"url",
|
||||
"usvg 0.48.1",
|
||||
"vello",
|
||||
"wgpu",
|
||||
]
|
||||
@@ -14628,6 +14767,7 @@ dependencies = [
|
||||
"raea-sys-framepass",
|
||||
"raea-sys-grass",
|
||||
"raea-sys-grid",
|
||||
"raea-sys-hold",
|
||||
"raea-sys-look",
|
||||
"raea-sys-matchmove",
|
||||
"raea-sys-material",
|
||||
@@ -14802,6 +14942,7 @@ dependencies = [
|
||||
"raea-io-media",
|
||||
"raea-native",
|
||||
"raea-runtime-bundle-lib",
|
||||
"raea-runtime-cssurls",
|
||||
"raea-sys-layers",
|
||||
"regex",
|
||||
"serde_json",
|
||||
@@ -14840,6 +14981,25 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-canvas"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"blitz-dom",
|
||||
"raea-native",
|
||||
"raea-sys-canvas",
|
||||
"raea-sys-fonts",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-cssurls"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"raea-core-scene",
|
||||
"raea-io-home",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-dom"
|
||||
version = "0.1.0"
|
||||
@@ -14926,6 +15086,7 @@ dependencies = [
|
||||
"raea-runtime-bake",
|
||||
"raea-runtime-encode",
|
||||
"raea-runtime-page",
|
||||
"raea-runtime-pagestore",
|
||||
"raea-runtime-react",
|
||||
"raea-runtime-scene",
|
||||
"raea-runtime-scene3d",
|
||||
@@ -14938,7 +15099,6 @@ dependencies = [
|
||||
"raea-sys-mix",
|
||||
"raea-sys-page",
|
||||
"serde_json",
|
||||
"twox-hash",
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
@@ -15019,6 +15179,7 @@ dependencies = [
|
||||
"raea-runtime-react",
|
||||
"raea-runtime-sound",
|
||||
"raea-sys-frame",
|
||||
"raea-sys-hold",
|
||||
"raea-sys-mix",
|
||||
"serde_json",
|
||||
"twox-hash",
|
||||
@@ -15065,6 +15226,14 @@ dependencies = [
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-pagestore"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"twox-hash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-plugins"
|
||||
version = "0.1.0"
|
||||
@@ -15099,12 +15268,14 @@ dependencies = [
|
||||
"raea-render",
|
||||
"raea-runtime-bundle",
|
||||
"raea-runtime-calls",
|
||||
"raea-runtime-canvas",
|
||||
"raea-runtime-input",
|
||||
"raea-runtime-jsengine",
|
||||
"raea-runtime-plugins",
|
||||
"raea-runtime-scene",
|
||||
"raea-runtime-shared",
|
||||
"raea-runtime-shots",
|
||||
"raea-runtime-track",
|
||||
"raea-runtime-twins",
|
||||
"raea-runtime-view",
|
||||
"raea-sys-animate",
|
||||
@@ -15196,6 +15367,18 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-track"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"raea-io-assets",
|
||||
"raea-native",
|
||||
"raea-runtime-bundle",
|
||||
"raea-runtime-calls",
|
||||
"raea-sys-bake",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-twins"
|
||||
version = "0.1.0"
|
||||
@@ -15241,7 +15424,6 @@ name = "raea-runtime-world"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"flate2",
|
||||
"image",
|
||||
"raea-core-facts",
|
||||
"raea-core-scene",
|
||||
@@ -15327,6 +15509,24 @@ dependencies = [
|
||||
"usvg 0.48.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-columns"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"fastrand",
|
||||
"half",
|
||||
"image",
|
||||
"ort",
|
||||
"raea-io-media",
|
||||
"raea-sys-ml",
|
||||
"rustfft",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
"tokenizers",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-compose"
|
||||
version = "0.1.0"
|
||||
@@ -15386,6 +15586,42 @@ dependencies = [
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-fingerprint"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"raea-sys-columns",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-fingerprint-things"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"fastrand",
|
||||
"raea-sys-columns",
|
||||
"raea-sys-fingerprint-use",
|
||||
"raea-sys-layers",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-fingerprint-use"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"fastrand",
|
||||
"image",
|
||||
"raea-sys-columns",
|
||||
"raea-sys-fingerprint",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-fog"
|
||||
version = "0.1.0"
|
||||
@@ -15485,6 +15721,14 @@ dependencies = [
|
||||
"raea-sys-frame",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-hold"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-sys-frame",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-image"
|
||||
version = "0.1.0"
|
||||
@@ -15622,6 +15866,14 @@ dependencies = [
|
||||
"ureq 2.12.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-mlx"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"mlx-rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-page"
|
||||
version = "0.1.0"
|
||||
@@ -18565,6 +18817,9 @@ name = "strum"
|
||||
version = "0.28.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd"
|
||||
dependencies = [
|
||||
"strum_macros 0.28.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "strum_macros"
|
||||
@@ -18674,7 +18929,7 @@ version = "0.22.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4ee5c550c2e00a0b3c046bef84a9ee217e04e7c014142eeb96f9e48781c5cfd3"
|
||||
dependencies = [
|
||||
"darling",
|
||||
"darling 0.20.11",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
@@ -19861,7 +20116,7 @@ version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0f8e91a023810fd2019648410d00eea13a71f21d849e71d6d9ed936fb8061174"
|
||||
dependencies = [
|
||||
"darling",
|
||||
"darling 0.20.11",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
@@ -20754,8 +21009,6 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "usvg"
|
||||
version = "0.48.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "977d0a4abdef933f424a99fe09f95576e089b90aebc6f016a3bc813762493e91"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"data-url 0.3.2",
|
||||
|
||||
+14
@@ -78,9 +78,14 @@ members = [
|
||||
"systems/tone",
|
||||
"systems/mix",
|
||||
"systems/ml",
|
||||
"systems/mlx",
|
||||
"systems/speech",
|
||||
"systems/layout",
|
||||
"systems/vision",
|
||||
"systems/columns",
|
||||
"systems/fingerprint",
|
||||
"systems/fingerprint-use",
|
||||
"systems/fingerprint-things",
|
||||
"systems/song",
|
||||
"systems/perceive",
|
||||
"systems/footage",
|
||||
@@ -98,6 +103,7 @@ members = [
|
||||
"systems/page-net",
|
||||
"systems/page-ops",
|
||||
"systems/frame",
|
||||
"systems/hold",
|
||||
"systems/layers",
|
||||
"systems/splat",
|
||||
"systems/sprite",
|
||||
@@ -136,6 +142,9 @@ members = [
|
||||
"engine/seedling",
|
||||
"engine/web",
|
||||
"runtime/react",
|
||||
"runtime/track",
|
||||
"runtime/pagestore",
|
||||
"runtime/cssurls",
|
||||
"bench/bridge",
|
||||
"bench/bevy-parity",
|
||||
"bench/bridge/swatch",
|
||||
@@ -147,6 +156,7 @@ members = [
|
||||
"engine/shape-web",
|
||||
"runtime/calls",
|
||||
"runtime/shots",
|
||||
"runtime/canvas",
|
||||
"runtime/export",
|
||||
"runtime/live",
|
||||
"runtime/page",
|
||||
@@ -156,8 +166,10 @@ members = [
|
||||
"runtime/scene2d",
|
||||
"runtime/shared",
|
||||
"apps/check",
|
||||
"apps/check/flash",
|
||||
"apps/direction",
|
||||
"apps/notes",
|
||||
"apps/fingerprint",
|
||||
"apps/sound",
|
||||
"apps/workspace",
|
||||
"apps/workspace/registry",
|
||||
@@ -279,6 +291,8 @@ split-debuginfo = "packed"
|
||||
[patch.crates-io]
|
||||
# the MP4 muxer, vendored
|
||||
muxide = { path = "vendor/muxide" }
|
||||
# usvg 0.48.1 spacing a chunk's last letter as Chrome does (changes marked "raea:", docs/layout-reads.feature LR10)
|
||||
usvg = { path = "vendor/usvg" }
|
||||
# bevy_seedling 0.8.0 without its cpal 0.18 paths, ported to Bevy 0.20 (changes marked "raea:")
|
||||
bevy_seedling = { path = "vendor/bevy_seedling" }
|
||||
# bevy_text 0.20.0 on parley 0.12, so one parley builds (changes marked "raea:", docs/bevy-upgrade.md)
|
||||
|
||||
@@ -103,7 +103,9 @@ floor (`raea check hello.mp4`). `raea init` starts a project, and `raea --help`
|
||||
- **Agent skills.** They live in [raea-skills](https://github.com/shinyobjectz/raea-skills), pinned here as
|
||||
[`skills/`](skills): `raea` teaches an agent to write, render and check raea compositions, 3D and games
|
||||
included. The installer adds it to `~/.claude/skills`, and `raea skills install --agent NAME` to other agents.
|
||||
- **Claude Code plugin.** `/plugin marketplace add shinyobjectz/raea`, then `/plugin install raea@raea`.
|
||||
- **Claude plugin.** The raea skill and two hooks (raea's quick check after a composition is saved, and media shown in
|
||||
the raea app). In Claude Code: `/plugin install raea --marketplace shinyobjectz/raea-skills`. It's the `skills/`
|
||||
folder of raea-skills, and `/plugin marketplace add shinyobjectz/raea` installs the same one.
|
||||
- **Craft guides.** `raea guide` prints the floor every edit is held to and the guides for pitches, explainers, stories,
|
||||
games, motion, music and layout. `raea context PROJECT` says what to read before working on a project.
|
||||
|
||||
|
||||
@@ -13,6 +13,10 @@ raea-core-brief = { path = "../../core/brief" }
|
||||
raea-core-facts = { path = "../../core/facts" }
|
||||
# a check's record named by when it was (UTC, DR3)
|
||||
raea-io-trace = { path = "../../io/trace" }
|
||||
# ffmpeg's flag for every decoded frame, by its version
|
||||
raea-io-ffmpeg = { path = "../../io/ffmpeg" }
|
||||
# caption contrast and loudness, measured as `raea world` measures a render (DR2)
|
||||
raea-sys-measure = { path = "../../systems/measure" }
|
||||
# the flashing screen (WCAG 2.3.1), split out to keep this crate small
|
||||
raea-app-check-flash = { path = "flash" }
|
||||
serde_json = "1"
|
||||
@@ -0,0 +1,7 @@
|
||||
[package]
|
||||
name = "raea-app-check-flash"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "`raea check`'s flashing screen (WCAG 2.3.1): opposing swings in a frame's windows, from decoded RGB"
|
||||
@@ -0,0 +1,232 @@
|
||||
//! The flashing screen behind `raea check` (apps/check flash.rs feeds it the decoded frames): a pure measure of pixels,
|
||||
//! in a crate of its own so the check stays small (tools/size.sh).
|
||||
|
||||
/// Flashing past WCAG 2.3.1: more than three flashes in any one second, over enough of the frame to matter. A flash is a
|
||||
/// pair of opposing changes in the same pixels, so a shape sliding past isn't one. Each window, a third of the frame wide
|
||||
/// and high, stands in for WCAG's quarter of a 10-degree field (the real area depends on the screen and how far away it
|
||||
/// is, which a file doesn't say), and a quarter of its pixels must swing together: by 0.10 relative luminance with the
|
||||
/// darker end under 0.80, or by 20 of saturated red ((R-G-B)*320, where R/(R+G+B) is at least 0.8). Every decoded frame
|
||||
/// counts, on its own timestamp, and the picture is sampled twice, by area and by point, so fine patterns don't average
|
||||
/// away. A screen for review, not a Harding or PEAT certification; an interlaced picture isn't split into its fields.
|
||||
const FLASH_MOST: usize = 6;
|
||||
const FLASH_PAIR_S: f64 = 1.0 + 1e-9;
|
||||
|
||||
/// A pixel in one measure: its value, and whether it can count. Red's value runs on through the saturation line, and a change
|
||||
/// counts when either end of it is saturated; a one-level step across the line isn't a jump from zero.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Px {
|
||||
value: f32,
|
||||
counts: bool,
|
||||
}
|
||||
|
||||
struct Swing {
|
||||
at: f64,
|
||||
direction: f32,
|
||||
moved: Vec<bool>,
|
||||
plain: bool,
|
||||
kept: bool,
|
||||
}
|
||||
|
||||
/// One window's swings in one measure: the ones an opposite swing within a second moves back in the same pixels. The
|
||||
/// general measure leaves out swings where another quarter of the window moved the other way at once (a moving pattern).
|
||||
struct Swings {
|
||||
by: f32,
|
||||
under: f32,
|
||||
mixed_counts: bool,
|
||||
pivot: Vec<Px>,
|
||||
extreme: Vec<Px>,
|
||||
at: f64,
|
||||
direction: f32,
|
||||
recent: std::collections::VecDeque<Swing>,
|
||||
ends: Vec<f64>,
|
||||
}
|
||||
|
||||
impl Swings {
|
||||
fn new(by: f32, under: f32, mixed_counts: bool) -> Swings {
|
||||
Swings { by, under, mixed_counts, pivot: Vec::new(), extreme: Vec::new(), at: 0.0, direction: 0.0, recent: Default::default(), ends: Vec::new() }
|
||||
}
|
||||
|
||||
fn moves(&self, a: Px, b: Px, direction: f32) -> bool {
|
||||
(b.value - a.value) * direction >= self.by && a.value.min(b.value) < self.under && (a.counts || b.counts)
|
||||
}
|
||||
|
||||
fn changed(&self, earlier: &[Px], later: &[Px], direction: f32) -> bool {
|
||||
earlier.iter().zip(later).filter(|(a, b)| self.moves(**a, **b, direction)).count() * 4 >= earlier.len()
|
||||
}
|
||||
|
||||
fn push(&mut self, t: f64, px: &[Px]) {
|
||||
if self.pivot.is_empty() {
|
||||
self.pivot = px.to_vec();
|
||||
self.extreme = px.to_vec();
|
||||
self.at = t;
|
||||
return;
|
||||
}
|
||||
if self.direction == 0.0 {
|
||||
for direction in [1.0, -1.0] {
|
||||
if self.changed(&self.pivot, px, direction) {
|
||||
self.direction = direction;
|
||||
self.extreme = px.to_vec();
|
||||
self.at = t;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if self.changed(&self.extreme, px, -self.direction) {
|
||||
self.record();
|
||||
self.pivot = std::mem::replace(&mut self.extreme, px.to_vec());
|
||||
self.at = t;
|
||||
self.direction = -self.direction;
|
||||
} else if self.changed(&self.pivot, px, self.direction) && self.went_further(px) {
|
||||
self.extreme = px.to_vec();
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the pixels swinging from the pivot went further than the saved extreme, judged on those pixels alone: the
|
||||
/// rest of the window can dim by less than counts and still outweigh a patch that's flashing.
|
||||
fn went_further(&self, px: &[Px]) -> bool {
|
||||
let further: f32 = self.pivot.iter().zip(px).zip(&self.extreme).filter(|((p, n), _)| self.moves(**p, **n, self.direction)).map(|((_, n), e)| (n.value - e.value) * self.direction).sum();
|
||||
further > 0.0
|
||||
}
|
||||
|
||||
fn record(&mut self) {
|
||||
if !self.changed(&self.pivot, &self.extreme, self.direction) {
|
||||
return;
|
||||
}
|
||||
let moved: Vec<bool> = self.pivot.iter().zip(&self.extreme).map(|(a, b)| self.moves(*a, *b, self.direction)).collect();
|
||||
let plain = self.mixed_counts || !self.changed(&self.pivot, &self.extreme, -self.direction);
|
||||
let (at, direction) = (self.at, self.direction);
|
||||
let mut kept = false;
|
||||
for other in self.recent.iter_mut().rev() {
|
||||
if at - other.at > FLASH_PAIR_S {
|
||||
break;
|
||||
}
|
||||
let same = moved.iter().zip(&other.moved).filter(|(x, y)| **x && **y).count();
|
||||
if other.direction == -direction && same * 4 >= moved.len() {
|
||||
other.kept = true;
|
||||
kept = true;
|
||||
}
|
||||
}
|
||||
self.recent.push_back(Swing { at, direction, moved, plain, kept });
|
||||
while self.recent.front().is_some_and(|s| at - s.at > FLASH_PAIR_S) {
|
||||
self.retire();
|
||||
}
|
||||
}
|
||||
|
||||
/// The oldest swing leaves the second it could still pair within; only the seconds' ends are kept for good.
|
||||
fn retire(&mut self) {
|
||||
if let Some(s) = self.recent.pop_front()
|
||||
&& s.plain
|
||||
&& s.kept
|
||||
{
|
||||
self.ends.push(s.at);
|
||||
}
|
||||
}
|
||||
|
||||
/// The most swings in any one second, and when that second starts.
|
||||
fn busiest(&mut self) -> (usize, f64) {
|
||||
if self.direction != 0.0 {
|
||||
self.record();
|
||||
self.direction = 0.0;
|
||||
}
|
||||
while !self.recent.is_empty() {
|
||||
self.retire();
|
||||
}
|
||||
self.ends.sort_by(f64::total_cmp);
|
||||
let (mut best, mut from, mut j) = (0, 0.0, 0);
|
||||
for i in 0..self.ends.len() {
|
||||
while self.ends[i] - self.ends[j] >= 1.0 - 1e-9 {
|
||||
j += 1;
|
||||
}
|
||||
if i - j + 1 > best {
|
||||
(best, from) = (i - j + 1, self.ends[j]);
|
||||
}
|
||||
}
|
||||
(best, from)
|
||||
}
|
||||
}
|
||||
|
||||
/// Frames of two pictures side by side, each `w` by `h` RGB: the area sample and the point sample of one frame.
|
||||
pub struct FlashScreen {
|
||||
w: usize,
|
||||
h: usize,
|
||||
last: Vec<u8>,
|
||||
linear: Vec<f32>,
|
||||
luma: Vec<Px>,
|
||||
red: Vec<Px>,
|
||||
cut: Vec<Px>,
|
||||
windows: Vec<(usize, usize, Swings, Swings)>,
|
||||
}
|
||||
|
||||
impl FlashScreen {
|
||||
pub fn new(w: usize, h: usize) -> FlashScreen {
|
||||
let (ww, wh) = (w / 3, h / 3);
|
||||
let places = |size: usize, window: usize| {
|
||||
let mut at: Vec<usize> = (0..=size - window).step_by((size / 6).max(1)).collect();
|
||||
at.push(size - window);
|
||||
at.dedup();
|
||||
at
|
||||
};
|
||||
let mut windows = Vec::new();
|
||||
for sample in 0..2 {
|
||||
for &y in &places(h, wh) {
|
||||
for &x in &places(w, ww) {
|
||||
windows.push((x + sample * w, y, Swings::new(0.10, 0.80, false), Swings::new(20.0, f32::INFINITY, true)));
|
||||
}
|
||||
}
|
||||
}
|
||||
let linear = (0..=255u32)
|
||||
.map(|c| {
|
||||
let c = c as f32 / 255.0;
|
||||
if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) }
|
||||
})
|
||||
.collect();
|
||||
FlashScreen { w, h, last: Vec::new(), linear, luma: Vec::new(), red: Vec::new(), cut: Vec::new(), windows }
|
||||
}
|
||||
|
||||
pub fn push(&mut self, rgb: &[u8], t: f64) {
|
||||
if rgb == self.last {
|
||||
return;
|
||||
}
|
||||
self.luma.clear();
|
||||
self.red.clear();
|
||||
for px in rgb.chunks_exact(3) {
|
||||
let (r, g, b) = (self.linear[px[0] as usize], self.linear[px[1] as usize], self.linear[px[2] as usize]);
|
||||
self.luma.push(Px { value: 0.2126 * r + 0.7152 * g + 0.0722 * b, counts: true });
|
||||
let sum = r + g + b + 1e-9;
|
||||
self.red.push(Px { value: ((r - g - b) * 320.0).max(0.0), counts: r / sum >= 0.8 });
|
||||
}
|
||||
let (stride, ww, wh) = (self.w * 2, self.w / 3, self.h / 3);
|
||||
for (x, y, general, saturated) in &mut self.windows {
|
||||
self.cut.clear();
|
||||
for r in 0..wh {
|
||||
self.cut.extend_from_slice(&self.luma[(*y + r) * stride + *x..][..ww]);
|
||||
}
|
||||
general.push(t, &self.cut);
|
||||
self.cut.clear();
|
||||
for r in 0..wh {
|
||||
self.cut.extend_from_slice(&self.red[(*y + r) * stride + *x..][..ww]);
|
||||
}
|
||||
saturated.push(t, &self.cut);
|
||||
}
|
||||
self.last.clear();
|
||||
self.last.extend_from_slice(rgb);
|
||||
}
|
||||
|
||||
/// (swings in the worst second, when it starts, which measure) when past the limit
|
||||
pub fn finish(mut self) -> Option<(usize, f64, &'static str)> {
|
||||
let mut worst: Option<(usize, f64, &'static str)> = None;
|
||||
for (_, _, general, saturated) in &mut self.windows {
|
||||
for (swings, kind) in [(general, "general"), (saturated, "red")] {
|
||||
let (n, from) = swings.busiest();
|
||||
if n > FLASH_MOST && worst.is_none_or(|w| n > w.0) {
|
||||
worst = Some((n, from, kind));
|
||||
}
|
||||
}
|
||||
}
|
||||
worst
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,100 @@
|
||||
use super::*;
|
||||
|
||||
/// a 96x54 picture drawn by `paint(frame index, sample, x, y)`, sample 0 the area sample and 1 the point sample, for
|
||||
/// `frames` frames at `fps`
|
||||
fn flash_samples(frames: usize, fps: f64, paint: impl Fn(usize, usize, usize, usize) -> [u8; 3]) -> Option<(usize, f64, &'static str)> {
|
||||
let (w, h) = (96, 54);
|
||||
let mut screen = FlashScreen::new(w, h);
|
||||
for f in 0..frames {
|
||||
let mut rgb = Vec::with_capacity(w * 2 * h * 3);
|
||||
for y in 0..h {
|
||||
for sample in 0..2 {
|
||||
for x in 0..w {
|
||||
rgb.extend_from_slice(&paint(f, sample, x, y));
|
||||
}
|
||||
}
|
||||
}
|
||||
screen.push(&rgb, f as f64 / fps);
|
||||
}
|
||||
screen.finish()
|
||||
}
|
||||
|
||||
fn flash_of(seconds: usize, paint: impl Fn(usize, usize, usize) -> [u8; 3]) -> Option<(usize, f64, &'static str)> {
|
||||
flash_samples(seconds * 60, 60.0, move |f, _, x, y| paint(f, x, y))
|
||||
}
|
||||
|
||||
/// two colours taking turns `hz` times a second, over a box of the frame
|
||||
fn turns(hz: usize, on: [u8; 3], off: [u8; 3], bx: (usize, usize, usize, usize)) -> Option<(usize, f64, &'static str)> {
|
||||
flash_of(3, move |f, x, y| {
|
||||
let inside = x >= bx.0 && x < bx.0 + bx.2 && y >= bx.1 && y < bx.1 + bx.3;
|
||||
if inside && f * hz * 2 / 60 % 2 == 0 { on } else { off }
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flashing_is_found_past_three_a_second_and_not_at_it() {
|
||||
let (white, black) = ([255, 255, 255], [0, 0, 0]);
|
||||
let all = (0, 0, 96, 54);
|
||||
assert_eq!(turns(3, white, black, all), None, "three a second is the limit, not past it");
|
||||
let (swings, _, kind) = turns(4, white, black, all).expect("four a second");
|
||||
assert_eq!((swings / 2, kind), (4, "general"));
|
||||
// a small box: under a quarter of any window, and then over it
|
||||
assert_eq!(turns(5, white, black, (40, 20, 10, 10)), None);
|
||||
assert!(turns(5, white, black, (30, 18, 32, 18)).is_some());
|
||||
// too small a change, and both ends too bright for WCAG to count it
|
||||
assert_eq!(turns(5, [60, 60, 60], [30, 30, 30], all), None);
|
||||
assert_eq!(turns(5, [255, 255, 255], [235, 235, 235], all), None);
|
||||
// a dark saturated red: too dim to count as a general flash, past the limit as a red one
|
||||
assert_eq!(turns(5, [150, 0, 0], black, all).map(|t| t.2), Some("red"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_flash_of_single_frames_counts_at_any_frame_rate() {
|
||||
// 120 fps with one white frame in every 30: four flashes a second, each gone within a sixtieth of a second
|
||||
let found = flash_samples(360, 120.0, |f, _, _, _| if f % 30 == 1 { [255, 255, 255] } else { [0, 0, 0] });
|
||||
assert_eq!(found.map(|(swings, _, kind)| (swings / 2, kind)), Some((4, "general")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_flash_the_area_sample_averages_away_is_found_in_the_point_sample() {
|
||||
let found = flash_samples(180, 60.0, |f, sample, _, _| {
|
||||
if sample == 0 {
|
||||
return [128, 128, 128];
|
||||
}
|
||||
if f * 5 * 2 / 60 % 2 == 0 { [255, 255, 255] } else { [0, 0, 0] }
|
||||
});
|
||||
assert!(found.is_some(), "the same flash in the point sample alone");
|
||||
}
|
||||
|
||||
|
||||
#[test]
|
||||
fn a_shape_sliding_past_and_ordinary_cuts_are_not_flashing() {
|
||||
let (white, black) = ([255, 255, 255], [0, 0, 0]);
|
||||
assert_eq!(flash_of(3, move |f, x, _| if x < f { white } else { black }), None, "one wipe across the frame");
|
||||
assert_eq!(flash_of(4, move |f, _, _| if (f / 30) % 2 == 0 { white } else { black }), None, "a cut every half second");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_patch_strobing_while_its_background_dims_is_still_found() {
|
||||
// a third of a window: 0 then 124 on a 148 background, then the background settles at 124 and the patch cycles 124 and 160.
|
||||
// The background's drop is under the 0.10 that counts, but it outweighs the patch in the window's mean.
|
||||
let found = flash_samples(180, 60.0, |f, _, x, y| {
|
||||
let patch = x < 16 && y < 12;
|
||||
let level = match (patch, f) {
|
||||
(true, 0) => 0,
|
||||
(true, 1) => 124,
|
||||
(true, _) => if (f - 2) * 5 * 2 / 60 % 2 == 0 { 160 } else { 124 },
|
||||
(false, 0 | 1) => 148,
|
||||
(false, _) => 124,
|
||||
};
|
||||
[level, level, level]
|
||||
});
|
||||
assert!(found.is_some(), "the patch flashes five times a second");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_colour_crossing_the_saturation_line_is_not_a_red_flash() {
|
||||
// one level of green moves the pixel across R/(R+G+B) = 0.8 and hardly changes its red at all
|
||||
let found = flash_samples(180, 60.0, |f, _, _, _| if f * 5 * 2 / 60 % 2 == 0 { [100, 49, 0] } else { [100, 50, 0] });
|
||||
assert_eq!(found, None);
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
use super::*;
|
||||
|
||||
/// The defects Fingerprint's axes map to that a measure finds exactly (docs/fingerprint.feature FP4c), so the check
|
||||
/// wins over a head: clipping, a dropout, and a flash frame. Each on the same decoded sound or a small grey picture;
|
||||
/// each with red-team cases in tests.rs (a loud clean tone, a faded pause, a cut).
|
||||
///
|
||||
/// Clipping: a run of 3 samples or more at full scale (|x| 0.999 or more), or a flat top: 4 or more samples the same
|
||||
/// to the bit at a level a sound rarely holds still at (0.05 or more), as a hard limiter or a clamp leaves them.
|
||||
/// Counted per second; a second with CLIP_RUNS runs or more is a finding.
|
||||
pub(crate) const FULL: f32 = 0.999;
|
||||
pub(crate) const FLAT_LEVEL: f32 = 0.05;
|
||||
pub(crate) const CLIP_RUNS: usize = 3;
|
||||
|
||||
pub(crate) fn clipped(x: &[f32]) -> Vec<(f64, String)> {
|
||||
let mut per: Vec<usize> = vec![0; x.len() / SR + 1];
|
||||
let mut i = 0;
|
||||
while i < x.len() {
|
||||
let v = x[i];
|
||||
let mut j = i + 1;
|
||||
if v.abs() >= FULL {
|
||||
while j < x.len() && x[j].abs() >= FULL && x[j].signum() == v.signum() {
|
||||
j += 1;
|
||||
}
|
||||
if j - i >= 3 {
|
||||
per[i / SR] += 1;
|
||||
}
|
||||
} else if v.abs() >= FLAT_LEVEL {
|
||||
while j < x.len() && x[j].to_bits() == v.to_bits() {
|
||||
j += 1;
|
||||
}
|
||||
if j - i >= 4 {
|
||||
per[i / SR] += 1;
|
||||
}
|
||||
}
|
||||
i = j;
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
let mut s = 0;
|
||||
while s < per.len() {
|
||||
if per[s] < CLIP_RUNS {
|
||||
s += 1;
|
||||
continue;
|
||||
}
|
||||
let mut e = s;
|
||||
while e + 1 < per.len() && per[e + 1] >= CLIP_RUNS {
|
||||
e += 1;
|
||||
}
|
||||
let runs: usize = per[s..=e].iter().sum();
|
||||
out.push((s as f64, format!("the sound clips: {runs} flat-topped runs over {} s; bring the level down before it hits the ceiling", e - s + 1)));
|
||||
s = e + 1;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A dropout: the sound falls from level (-45 dBFS or more) to digital silence (under -80 dBFS) in one 10 ms step and
|
||||
/// comes back within two, to within 10 dB of where it was, 50 ms to 3 s later. A pause that fades out or in isn't one.
|
||||
pub(crate) const SILENT: f64 = -80.0;
|
||||
pub(crate) const HAD_LEVEL: f64 = -45.0;
|
||||
|
||||
pub(crate) fn dropouts(x: &[f32]) -> Vec<(f64, String)> {
|
||||
let rms: Vec<f64> = x.as_chunks::<HOP>().0.iter().map(|f| crate::sound::db(f)).collect();
|
||||
let step = HOP as f64 / SR as f64;
|
||||
let mut out = Vec::new();
|
||||
let mut i = 1;
|
||||
while i < rms.len() {
|
||||
// a step that is silent, or nearly (the source cut partway through it), after one with level
|
||||
if !(rms[i] < HAD_LEVEL - 20.0 && rms[i - 1] >= HAD_LEVEL) {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let mut j = i + 1;
|
||||
while j < rms.len() && rms[j] < SILENT {
|
||||
j += 1;
|
||||
}
|
||||
let gap = (j - i) as f64 * step;
|
||||
let silent_inside = j > i + 1;
|
||||
// back at once: within two steps, to within 10 dB of the level before the gap (a fade in takes longer)
|
||||
let before = rms[i - 1];
|
||||
let back = rms[j.min(rms.len())..(j + 2).min(rms.len())].iter().any(|l| *l >= HAD_LEVEL.max(before - 10.0));
|
||||
if silent_inside && back && (0.05..=3.0).contains(&gap) {
|
||||
out.push((i as f64 * step, format!("the sound drops out for {:.2} s and comes back; a dropout, not a pause (no fade either side)", gap)));
|
||||
}
|
||||
i = j.max(i + 1);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A flash frame: one or two frames whose mean brightness differs from the frames either side by FLASH_STEP or more
|
||||
/// (0-1), while those two agree within FLASH_SAME: a black or white frame dropped into a shot. A cut (the brightness
|
||||
/// moves and stays) and a fade aren't flash frames.
|
||||
pub(crate) const FLASH_STEP: f32 = 0.25;
|
||||
pub(crate) const FLASH_SAME: f32 = 0.08;
|
||||
|
||||
pub(crate) fn flash_frames(luma: &[f32], fps: f64) -> Vec<(f64, String)> {
|
||||
let mut out = Vec::new();
|
||||
let mut i = 1;
|
||||
while i + 1 < luma.len() {
|
||||
let found = (1..=2).find(|&k| {
|
||||
let (before, after) = (luma[i - 1], luma.get(i + k - 1 + 1).copied());
|
||||
let Some(after) = after else { return false };
|
||||
(before - after).abs() <= FLASH_SAME && luma[i..i + k].iter().all(|&l| (l - before).abs() >= FLASH_STEP && (l - after).abs() >= FLASH_STEP)
|
||||
});
|
||||
match found {
|
||||
Some(k) => {
|
||||
out.push((i as f64 / fps, format!("{k} frame{} flash{} {} in the middle of a shot; a dropped or stray frame", if k == 1 { "" } else { "s" }, if k == 1 { "es" } else { "" }, if luma[i] < luma[i - 1] { "dark" } else { "bright" })));
|
||||
i += k + 1;
|
||||
}
|
||||
None => i += 1,
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Each frame's mean brightness (0-1), decoded small and grey
|
||||
fn lumas(video: &str) -> R<(Vec<f32>, f64)> {
|
||||
let out = Command::new("ffmpeg")
|
||||
.args(["-v", "error", "-nostdin", "-i", video, "-map", "0:v:0", "-vf", "scale=32:18:flags=area,format=gray", "-f", "rawvideo", "-"])
|
||||
.output()
|
||||
.map_err(|e| format!("ffmpeg: {e}"))?;
|
||||
if !out.status.success() {
|
||||
return Err(format!("ffmpeg couldn't read the picture of {video}: {}", String::from_utf8_lossy(&out.stderr).trim()));
|
||||
}
|
||||
let l = out.stdout.as_chunks::<{ 32 * 18 }>().0.iter().map(|f| f.iter().map(|&p| p as f32).sum::<f32>() / (32.0 * 18.0 * 255.0)).collect();
|
||||
let rate = ffmpeg_stderr(&["-hide_banner", "-i", video])?;
|
||||
let fps = rate.split(" fps").next().and_then(|s| s.rsplit(", ").next()).and_then(|s| s.trim().parse().ok()).unwrap_or(30.0);
|
||||
Ok((l, fps))
|
||||
}
|
||||
|
||||
pub(crate) fn flash_frame_rule(video: &str, issues: &mut Vec<Issue>, passed: &mut Vec<String>) -> R<()> {
|
||||
let (l, fps) = lumas(video)?;
|
||||
let found = flash_frames(&l, fps);
|
||||
if found.is_empty() {
|
||||
passed.push("flash-frame: no stray black or white frame".into());
|
||||
}
|
||||
issues.extend(moments("flash-frame", 1, found));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Each moment a rule found, as an issue of that priority
|
||||
pub(crate) fn moments(rule: &'static str, p: u8, found: Vec<(f64, String)>) -> impl Iterator<Item = Issue> {
|
||||
found.into_iter().map(move |(at, says)| Issue { rule, p, at: Some(at), says })
|
||||
}
|
||||
|
||||
/// The sound's defects on the decoded mix (sound.rs decodes it once)
|
||||
pub(crate) fn sound_defects(x: &[f32], issues: &mut Vec<Issue>, passed: &mut Vec<String>) {
|
||||
for (rule, found, ok) in [("clipping", clipped(x), "clipping: no flat-topped runs"), ("dropout", dropouts(x), "dropout: the sound never drops to silence and back")] {
|
||||
if found.is_empty() {
|
||||
passed.push(ok.into());
|
||||
}
|
||||
issues.extend(moments(rule, 1, found));
|
||||
}
|
||||
}
|
||||
+4
-238
@@ -1,243 +1,9 @@
|
||||
use super::*;
|
||||
use raea_app_check_flash::FlashScreen;
|
||||
|
||||
/// Flashing past WCAG 2.3.1: more than three flashes in any one second, over enough of the frame to matter. A flash is a
|
||||
/// pair of opposing changes in the same pixels, so a shape sliding past isn't one. Each window, a third of the frame wide
|
||||
/// and high, stands in for WCAG's quarter of a 10-degree field (the real area depends on the screen and how far away it
|
||||
/// is, which a file doesn't say), and a quarter of its pixels must swing together: by 0.10 relative luminance with the
|
||||
/// darker end under 0.80, or by 20 of saturated red ((R-G-B)*320, where R/(R+G+B) is at least 0.8). Every decoded frame
|
||||
/// counts, on its own timestamp, and the picture is sampled twice, by area and by point, so fine patterns don't average
|
||||
/// away. A screen for review, not a Harding or PEAT certification; an interlaced picture isn't split into its fields.
|
||||
/// The width each frame is decoded at for the flashing screen (raea-app-check-flash: its rule and its windows), twice over:
|
||||
/// the area sample and the point sample side by side
|
||||
const FLASH_W: usize = 192;
|
||||
const FLASH_MOST: usize = 6;
|
||||
const FLASH_PAIR_S: f64 = 1.0 + 1e-9;
|
||||
|
||||
/// A pixel in one measure: its value, and whether it can count. Red's value runs on through the saturation line, and a change
|
||||
/// counts when either end of it is saturated; a one-level step across the line isn't a jump from zero.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Px {
|
||||
value: f32,
|
||||
counts: bool,
|
||||
}
|
||||
|
||||
struct Swing {
|
||||
at: f64,
|
||||
direction: f32,
|
||||
moved: Vec<bool>,
|
||||
plain: bool,
|
||||
kept: bool,
|
||||
}
|
||||
|
||||
/// One window's swings in one measure: the ones an opposite swing within a second moves back in the same pixels. The
|
||||
/// general measure leaves out swings where another quarter of the window moved the other way at once (a moving pattern).
|
||||
struct Swings {
|
||||
by: f32,
|
||||
under: f32,
|
||||
mixed_counts: bool,
|
||||
pivot: Vec<Px>,
|
||||
extreme: Vec<Px>,
|
||||
at: f64,
|
||||
direction: f32,
|
||||
recent: std::collections::VecDeque<Swing>,
|
||||
ends: Vec<f64>,
|
||||
}
|
||||
|
||||
impl Swings {
|
||||
fn new(by: f32, under: f32, mixed_counts: bool) -> Swings {
|
||||
Swings { by, under, mixed_counts, pivot: Vec::new(), extreme: Vec::new(), at: 0.0, direction: 0.0, recent: Default::default(), ends: Vec::new() }
|
||||
}
|
||||
|
||||
fn moves(&self, a: Px, b: Px, direction: f32) -> bool {
|
||||
(b.value - a.value) * direction >= self.by && a.value.min(b.value) < self.under && (a.counts || b.counts)
|
||||
}
|
||||
|
||||
fn changed(&self, earlier: &[Px], later: &[Px], direction: f32) -> bool {
|
||||
earlier.iter().zip(later).filter(|(a, b)| self.moves(**a, **b, direction)).count() * 4 >= earlier.len()
|
||||
}
|
||||
|
||||
fn push(&mut self, t: f64, px: &[Px]) {
|
||||
if self.pivot.is_empty() {
|
||||
self.pivot = px.to_vec();
|
||||
self.extreme = px.to_vec();
|
||||
self.at = t;
|
||||
return;
|
||||
}
|
||||
if self.direction == 0.0 {
|
||||
for direction in [1.0, -1.0] {
|
||||
if self.changed(&self.pivot, px, direction) {
|
||||
self.direction = direction;
|
||||
self.extreme = px.to_vec();
|
||||
self.at = t;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if self.changed(&self.extreme, px, -self.direction) {
|
||||
self.record();
|
||||
self.pivot = std::mem::replace(&mut self.extreme, px.to_vec());
|
||||
self.at = t;
|
||||
self.direction = -self.direction;
|
||||
} else if self.changed(&self.pivot, px, self.direction) && self.went_further(px) {
|
||||
self.extreme = px.to_vec();
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the pixels swinging from the pivot went further than the saved extreme, judged on those pixels alone: the
|
||||
/// rest of the window can dim by less than counts and still outweigh a patch that's flashing.
|
||||
fn went_further(&self, px: &[Px]) -> bool {
|
||||
let further: f32 = self.pivot.iter().zip(px).zip(&self.extreme).filter(|((p, n), _)| self.moves(**p, **n, self.direction)).map(|((_, n), e)| (n.value - e.value) * self.direction).sum();
|
||||
further > 0.0
|
||||
}
|
||||
|
||||
fn record(&mut self) {
|
||||
if !self.changed(&self.pivot, &self.extreme, self.direction) {
|
||||
return;
|
||||
}
|
||||
let moved: Vec<bool> = self.pivot.iter().zip(&self.extreme).map(|(a, b)| self.moves(*a, *b, self.direction)).collect();
|
||||
let plain = self.mixed_counts || !self.changed(&self.pivot, &self.extreme, -self.direction);
|
||||
let (at, direction) = (self.at, self.direction);
|
||||
let mut kept = false;
|
||||
for other in self.recent.iter_mut().rev() {
|
||||
if at - other.at > FLASH_PAIR_S {
|
||||
break;
|
||||
}
|
||||
let same = moved.iter().zip(&other.moved).filter(|(x, y)| **x && **y).count();
|
||||
if other.direction == -direction && same * 4 >= moved.len() {
|
||||
other.kept = true;
|
||||
kept = true;
|
||||
}
|
||||
}
|
||||
self.recent.push_back(Swing { at, direction, moved, plain, kept });
|
||||
while self.recent.front().is_some_and(|s| at - s.at > FLASH_PAIR_S) {
|
||||
self.retire();
|
||||
}
|
||||
}
|
||||
|
||||
/// The oldest swing leaves the second it could still pair within; only the seconds' ends are kept for good.
|
||||
fn retire(&mut self) {
|
||||
if let Some(s) = self.recent.pop_front()
|
||||
&& s.plain
|
||||
&& s.kept
|
||||
{
|
||||
self.ends.push(s.at);
|
||||
}
|
||||
}
|
||||
|
||||
/// The most swings in any one second, and when that second starts.
|
||||
fn busiest(&mut self) -> (usize, f64) {
|
||||
if self.direction != 0.0 {
|
||||
self.record();
|
||||
self.direction = 0.0;
|
||||
}
|
||||
while !self.recent.is_empty() {
|
||||
self.retire();
|
||||
}
|
||||
self.ends.sort_by(f64::total_cmp);
|
||||
let (mut best, mut from, mut j) = (0, 0.0, 0);
|
||||
for i in 0..self.ends.len() {
|
||||
while self.ends[i] - self.ends[j] >= 1.0 - 1e-9 {
|
||||
j += 1;
|
||||
}
|
||||
if i - j + 1 > best {
|
||||
(best, from) = (i - j + 1, self.ends[j]);
|
||||
}
|
||||
}
|
||||
(best, from)
|
||||
}
|
||||
}
|
||||
|
||||
/// Frames of two pictures side by side, each `w` by `h` RGB: the area sample and the point sample of one frame.
|
||||
pub(crate) struct FlashScreen {
|
||||
w: usize,
|
||||
h: usize,
|
||||
last: Vec<u8>,
|
||||
linear: Vec<f32>,
|
||||
luma: Vec<Px>,
|
||||
red: Vec<Px>,
|
||||
cut: Vec<Px>,
|
||||
windows: Vec<(usize, usize, Swings, Swings)>,
|
||||
}
|
||||
|
||||
impl FlashScreen {
|
||||
pub(crate) fn new(w: usize, h: usize) -> FlashScreen {
|
||||
let (ww, wh) = (w / 3, h / 3);
|
||||
let places = |size: usize, window: usize| {
|
||||
let mut at: Vec<usize> = (0..=size - window).step_by((size / 6).max(1)).collect();
|
||||
at.push(size - window);
|
||||
at.dedup();
|
||||
at
|
||||
};
|
||||
let mut windows = Vec::new();
|
||||
for sample in 0..2 {
|
||||
for &y in &places(h, wh) {
|
||||
for &x in &places(w, ww) {
|
||||
windows.push((x + sample * w, y, Swings::new(0.10, 0.80, false), Swings::new(20.0, f32::INFINITY, true)));
|
||||
}
|
||||
}
|
||||
}
|
||||
let linear = (0..=255u32)
|
||||
.map(|c| {
|
||||
let c = c as f32 / 255.0;
|
||||
if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) }
|
||||
})
|
||||
.collect();
|
||||
FlashScreen { w, h, last: Vec::new(), linear, luma: Vec::new(), red: Vec::new(), cut: Vec::new(), windows }
|
||||
}
|
||||
|
||||
pub(crate) fn push(&mut self, rgb: &[u8], t: f64) {
|
||||
if rgb == self.last {
|
||||
return;
|
||||
}
|
||||
self.luma.clear();
|
||||
self.red.clear();
|
||||
for px in rgb.chunks_exact(3) {
|
||||
let (r, g, b) = (self.linear[px[0] as usize], self.linear[px[1] as usize], self.linear[px[2] as usize]);
|
||||
self.luma.push(Px { value: 0.2126 * r + 0.7152 * g + 0.0722 * b, counts: true });
|
||||
let sum = r + g + b + 1e-9;
|
||||
self.red.push(Px { value: ((r - g - b) * 320.0).max(0.0), counts: r / sum >= 0.8 });
|
||||
}
|
||||
let (stride, ww, wh) = (self.w * 2, self.w / 3, self.h / 3);
|
||||
for (x, y, general, saturated) in &mut self.windows {
|
||||
self.cut.clear();
|
||||
for r in 0..wh {
|
||||
self.cut.extend_from_slice(&self.luma[(*y + r) * stride + *x..][..ww]);
|
||||
}
|
||||
general.push(t, &self.cut);
|
||||
self.cut.clear();
|
||||
for r in 0..wh {
|
||||
self.cut.extend_from_slice(&self.red[(*y + r) * stride + *x..][..ww]);
|
||||
}
|
||||
saturated.push(t, &self.cut);
|
||||
}
|
||||
self.last.clear();
|
||||
self.last.extend_from_slice(rgb);
|
||||
}
|
||||
|
||||
/// (swings in the worst second, when it starts, which measure) when past the limit
|
||||
pub(crate) fn finish(mut self) -> Option<(usize, f64, &'static str)> {
|
||||
let mut worst: Option<(usize, f64, &'static str)> = None;
|
||||
for (_, _, general, saturated) in &mut self.windows {
|
||||
for (swings, kind) in [(general, "general"), (saturated, "red")] {
|
||||
let (n, from) = swings.busiest();
|
||||
if n > FLASH_MOST && worst.is_none_or(|w| n > w.0) {
|
||||
worst = Some((n, from, kind));
|
||||
}
|
||||
}
|
||||
}
|
||||
worst
|
||||
}
|
||||
}
|
||||
|
||||
/// Every decoded frame, once: -fps_mode from FFmpeg 5.1 on, -vsync before it.
|
||||
fn passthrough() -> [&'static str; 2] {
|
||||
let out = Command::new("ffmpeg").args(["-hide_banner", "-version"]).output().map(|o| o.stdout).unwrap_or_default();
|
||||
let head = String::from_utf8_lossy(&out);
|
||||
let version = head.split("version ").nth(1).and_then(|v| {
|
||||
let mut parts = v.trim_start_matches('n').split(|c: char| !c.is_ascii_digit());
|
||||
Some((parts.next()?.parse::<u32>().ok()?, parts.next()?.parse::<u32>().ok()?))
|
||||
});
|
||||
[if version.is_some_and(|v| v < (5, 1)) { "-vsync" } else { "-fps_mode" }, "passthrough"]
|
||||
}
|
||||
|
||||
/// A frame's number and time from showinfo's log, exact: its `pts` in ticks of the time base. `pts_time` is rounded to six
|
||||
/// significant digits, which is enough to push a legal third flash across the one-second line.
|
||||
@@ -269,7 +35,7 @@ pub(crate) fn flashing(video: &str, probe: &Probe, issues: &mut Vec<Issue>, pass
|
||||
let w = FLASH_W;
|
||||
let h = (((w as f64 * probe.h / probe.w.max(1.0)) / 2.0).round() as usize * 2).max(6);
|
||||
let graph = format!("showinfo,split=2[area][point];[area]scale={w}:{h}:flags=area[a];[point]scale={w}:{h}:flags=neighbor[b];[a][b]hstack=inputs=2,format=rgb24");
|
||||
let sync = passthrough();
|
||||
let sync = raea_io_ffmpeg::passthrough();
|
||||
let mut child = Command::new("ffmpeg")
|
||||
.args(["-hide_banner", "-nostats", "-nostdin", "-loglevel", "level+info", "-i", video, "-map", "0:v:0", "-vf", &graph, sync[0], sync[1], "-f", "rawvideo", "-"])
|
||||
.stdin(std::process::Stdio::null())
|
||||
|
||||
+37
-33
@@ -1,4 +1,4 @@
|
||||
//! `raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--shape 9:16]
|
||||
//! `raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--things T.json] [--shape 9:16]
|
||||
//! [--platform tiktok|reels|shorts] [-o check.json]`: the floor's measurable lines on an export (docs/craft-system.md, I; sdk/guides/craft/floor.md).
|
||||
//! Each issue is ranked P0 (breaks the piece) to P3 (polish), with where it is and what to do. Rules on the file alone:
|
||||
//! loudness and true peak, a steady sound that stops dead (a source run out, a cut with no fade), stretches where nothing
|
||||
@@ -20,6 +20,8 @@ mod picture;
|
||||
use picture::*;
|
||||
mod flash;
|
||||
use flash::*;
|
||||
mod defects;
|
||||
use defects::*;
|
||||
mod text;
|
||||
use text::*;
|
||||
pub mod quick;
|
||||
@@ -68,7 +70,7 @@ fn flag<'a>(args: &'a [String], name: &str) -> Option<&'a str> {
|
||||
args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).map(String::as_str)
|
||||
}
|
||||
|
||||
pub const USAGE: &str = "raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--shape 16:9|9:16|4:5|1:1] [--platform tiktok|reels|shorts] [--taste taste.ts|DIR] [-o check.json] (an export against the floor: clipped text, contrast, safe areas, freezes, flashing, cues, loudness, blotching, a placeholder brand kit; its findings errors, warns and notes)";
|
||||
pub const USAGE: &str = "raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--things T.json] [--shape 16:9|9:16|4:5|1:1] [--platform tiktok|reels|shorts] [--taste taste.ts|DIR] [-o check.json] (an export against the floor: clipped text, contrast, safe areas, freezes, flashing, cues, loudness, blotching, a placeholder brand kit, and with --things what `raea fingerprint things --json` found: a thing floating or passing through another, the camera lurching mid-move, an empty frame; its findings errors, warns and notes)";
|
||||
|
||||
/// A rule from the person's taste: a form raea can measure, its value, and the taste line it stands for.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
@@ -117,7 +119,7 @@ fn taste_text(rules: &[Taste], runs: &[Run], w: f64, h: f64, issues: &mut Vec<Is
|
||||
}
|
||||
|
||||
/// the flags `raea check` takes, each with a value
|
||||
const TAKES: [&str; 7] = ["--manifest", "--words", "--perception", "--shape", "--platform", "--taste", "-o"];
|
||||
const TAKES: [&str; 8] = ["--manifest", "--words", "--perception", "--things", "--shape", "--platform", "--taste", "-o"];
|
||||
|
||||
fn run(args: &[String], tastes: Vec<raea_core_brief::Taste>) -> R<(String, bool)> {
|
||||
let (video, issues, passed, fps) = measured(args, taste_rules(&tastes))?;
|
||||
@@ -143,8 +145,7 @@ fn measured(args: &[String], taste: Vec<Taste>) -> R<(String, Vec<Issue>, Vec<St
|
||||
return Err(format!("no file at {video}\n{USAGE}"));
|
||||
}
|
||||
let probe = Probe::of(&video)?;
|
||||
let mut issues = Vec::new();
|
||||
let mut passed = Vec::new();
|
||||
let (mut issues, mut passed) = (Vec::new(), Vec::new());
|
||||
let manifest: Option<Value> = match flag(args, "--manifest") {
|
||||
Some(m) => Some(serde_json::from_str(&std::fs::read_to_string(m).map_err(|e| format!("{m}: {e}"))?).map_err(|e| format!("{m}: {e}"))?),
|
||||
None => None,
|
||||
@@ -157,8 +158,12 @@ fn measured(args: &[String], taste: Vec<Taste>) -> R<(String, Vec<Issue>, Vec<St
|
||||
}
|
||||
freezes(&video, &probe, taste_of(&taste, "still-max"), &mut issues, &mut passed)?;
|
||||
flashing(&video, &probe, &mut issues, &mut passed)?;
|
||||
flash_frame_rule(&video, &mut issues, &mut passed)?;
|
||||
blotching(&video, &probe, &mut issues, &mut passed)?;
|
||||
brand_kit(&[flag(args, "--manifest").unwrap_or(""), video.as_str()], &mut issues, &mut passed);
|
||||
if let Some(p) = flag(args, "--things") {
|
||||
things(p, &mut issues, &mut passed)?;
|
||||
}
|
||||
if let Some(manifest) = &manifest {
|
||||
let runs = text_runs(manifest);
|
||||
let (w, h) = (manifest["width"].as_f64().unwrap_or(probe.w), manifest["height"].as_f64().unwrap_or(probe.h));
|
||||
@@ -176,27 +181,33 @@ fn measured(args: &[String], taste: Vec<Taste>) -> R<(String, Vec<Issue>, Vec<St
|
||||
Ok((video, issues, passed, fps))
|
||||
}
|
||||
|
||||
/// What `raea fingerprint things FILE --json` found (docs/fingerprint.feature FP13c): a thing floating, two passing
|
||||
/// through each other, the camera lurching mid-move, an empty frame; measured there, from depth, masks and the camera's
|
||||
/// path, never by a head
|
||||
fn things(p: &str, issues: &mut Vec<Issue>, passed: &mut Vec<String>) -> R<()> {
|
||||
let v: Value = serde_json::from_str(&std::fs::read_to_string(p).map_err(|e| format!("{p}: {e}"))?).map_err(|e| format!("{p}: {e}"))?;
|
||||
let before = issues.len();
|
||||
for i in v["issues"].as_array().into_iter().flatten() {
|
||||
let Some(rule) = ["floating", "passing-through", "camera-speed", "empty-frame"].into_iter().find(|r| i["rule"] == *r) else { continue };
|
||||
issues.push(Issue { rule, p: i["p"].as_u64().unwrap_or(2).min(3) as u8, at: i["at"].as_f64(), says: i["says"].as_str().unwrap_or_default().into() });
|
||||
}
|
||||
if issues.len() == before {
|
||||
passed.push("things: nothing floats, passes through, lurches or is empty".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The issues as Findings (docs/direction.feature DR3: P0 and P1 errors, P2 a warn, P3 a note; a time is its frame at
|
||||
/// `fps`), with `more` (a render's own), worst first then by time.
|
||||
fn findings_of(mut issues: Vec<Issue>, more: Vec<Finding>, fps: f64) -> Vec<Finding> {
|
||||
issues.sort_by(|a, b| a.p.cmp(&b.p).then(a.at.unwrap_or(0.0).total_cmp(&b.at.unwrap_or(0.0))));
|
||||
finding::ranked(
|
||||
issues
|
||||
.iter()
|
||||
.map(|i| {
|
||||
let f = Finding::new(i.rule, Level::of_rank(i.p), &i.says, "raea check");
|
||||
// an issue at a second is about the frame it falls on
|
||||
match i.at {
|
||||
Some(t) => {
|
||||
let fr = (t * fps).round() as i64;
|
||||
f.frames(fr, fr + 1)
|
||||
}
|
||||
None => f,
|
||||
}
|
||||
})
|
||||
.chain(more)
|
||||
.collect(),
|
||||
)
|
||||
let mut found = Vec::new();
|
||||
for i in &issues {
|
||||
// an issue at a second is about the frame it falls on
|
||||
let (f, fr) = (Finding::new(i.rule, Level::of_rank(i.p), &i.says, "raea check"), (i.at.unwrap_or(0.0) * fps).round() as i64);
|
||||
found.push(if i.at.is_some() { f.frames(fr, fr + 1) } else { f });
|
||||
}
|
||||
finding::ranked(found.into_iter().chain(more).collect())
|
||||
}
|
||||
|
||||
/// The findings (`findings_of`), written to -o as JSON when asked, and the report's text with the count last. True
|
||||
@@ -244,10 +255,8 @@ fn last_packet_end(video: &str) -> Option<f64> {
|
||||
|
||||
impl Probe {
|
||||
fn of(video: &str) -> R<Probe> {
|
||||
let out = Command::new("ffprobe")
|
||||
.args(["-v", "error", "-show_entries", "stream=codec_type,width,height,r_frame_rate,duration,start_time:format=duration,start_time", "-of", "json", video])
|
||||
.output()
|
||||
.map_err(|e| format!("ffprobe: {e}"))?;
|
||||
let entries = "stream=codec_type,width,height,r_frame_rate,duration,start_time:format=duration,start_time";
|
||||
let out = Command::new("ffprobe").args(["-v", "error", "-show_entries", entries, "-of", "json", video]).output().map_err(|e| format!("ffprobe: {e}"))?;
|
||||
let v: Value = serde_json::from_slice(&out.stdout).map_err(|e| format!("ffprobe: {e}"))?;
|
||||
let streams = v["streams"].as_array().cloned().unwrap_or_default();
|
||||
let vid = streams.iter().find(|s| s["codec_type"] == "video").ok_or("no video stream")?;
|
||||
@@ -258,12 +267,7 @@ impl Probe {
|
||||
Some(length) => seconds(&vid["start_time"]).unwrap_or(origin) - origin + length,
|
||||
None => last_packet_end(video).map_or(duration, |end| end - origin),
|
||||
};
|
||||
Ok(Probe {
|
||||
w: vid["width"].as_f64().unwrap_or(1920.0),
|
||||
h: vid["height"].as_f64().unwrap_or(1080.0),
|
||||
duration,
|
||||
picture,
|
||||
audio: streams.iter().any(|s| s["codec_type"] == "audio"),
|
||||
})
|
||||
let audio = streams.iter().any(|s| s["codec_type"] == "audio");
|
||||
Ok(Probe { w: vid["width"].as_f64().unwrap_or(1920.0), h: vid["height"].as_f64().unwrap_or(1080.0), duration, picture, audio })
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,12 @@ pub(crate) fn pct(v: &[f64], q: f64) -> f64 {
|
||||
/// a bed that stops under a voice shows in the band the voice doesn't fill (a projector's clatter in the highs). A band's
|
||||
/// level is its share of the step's mean square (Parseval, undoing the Hann window's power), so a tone reads the same in
|
||||
/// its band as in the mix
|
||||
/// A stretch of sound's level in dB (its RMS)
|
||||
pub(crate) fn db(f: &[f32]) -> f64 {
|
||||
let ms = f.iter().map(|&v| (v as f64).powi(2)).sum::<f64>() / f.len().max(1) as f64;
|
||||
20.0 * (ms.sqrt() + 1e-9).log10()
|
||||
}
|
||||
|
||||
pub(crate) fn levels(x: &[f32]) -> (Vec<f64>, [Vec<f64>; 3]) {
|
||||
use std::f64::consts::PI;
|
||||
let n = x.len() / HOP;
|
||||
@@ -44,8 +50,7 @@ pub(crate) fn levels(x: &[f32]) -> (Vec<f64>, [Vec<f64>; 3]) {
|
||||
let scale = 2.0 / (HOP * HOP) as f64 / (hann.iter().map(|h| h * h).sum::<f64>() / HOP as f64);
|
||||
let (mut rms, mut bands) = (Vec::with_capacity(n), [Vec::with_capacity(n), Vec::with_capacity(n), Vec::with_capacity(n)]);
|
||||
for f in x.chunks_exact(HOP) {
|
||||
let ms = f.iter().map(|&v| (v as f64).powi(2)).sum::<f64>() / HOP as f64;
|
||||
rms.push(20.0 * (ms.sqrt() + 1e-9).log10());
|
||||
rms.push(db(f));
|
||||
let w: Vec<f64> = f.iter().zip(&hann).map(|(&v, h)| v as f64 * h).collect();
|
||||
let mut e = [0.0; 3];
|
||||
for (b, tw) in &bins {
|
||||
@@ -163,7 +168,8 @@ pub(crate) fn sound(video: &str, words: Option<&[Word]>, issues: &mut Vec<Issue>
|
||||
}
|
||||
let x: Vec<f32> = out.stdout.chunks_exact(4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect();
|
||||
let (rms, bands) = levels(&x);
|
||||
let found = |list: Vec<(f64, String)>, p: u8| list.into_iter().map(move |(at, says)| Issue { rule: "sound", p, at: Some(at), says });
|
||||
sound_defects(&x, issues, passed);
|
||||
let found = |list: Vec<(f64, String)>, p: u8| crate::defects::moments("sound", p, list);
|
||||
let stops = dead_stops(&rms, &bands);
|
||||
if stops.is_empty() {
|
||||
passed.push("sound: no steady sound stops dead".into());
|
||||
|
||||
+88
-89
@@ -292,72 +292,6 @@ fn a_sign_the_camera_carries_off_isnt_clipped_but_a_title_held_off_is() {
|
||||
assert_eq!(rules, vec![("safe-area", "THE NIGHT MARKET".to_string()), ("clipped", "WIDE".to_string())]);
|
||||
}
|
||||
|
||||
/// a 96x54 picture drawn by `paint(frame index, sample, x, y)`, sample 0 the area sample and 1 the point sample, for
|
||||
/// `frames` frames at `fps`
|
||||
fn flash_samples(frames: usize, fps: f64, paint: impl Fn(usize, usize, usize, usize) -> [u8; 3]) -> Option<(usize, f64, &'static str)> {
|
||||
let (w, h) = (96, 54);
|
||||
let mut screen = FlashScreen::new(w, h);
|
||||
for f in 0..frames {
|
||||
let mut rgb = Vec::with_capacity(w * 2 * h * 3);
|
||||
for y in 0..h {
|
||||
for sample in 0..2 {
|
||||
for x in 0..w {
|
||||
rgb.extend_from_slice(&paint(f, sample, x, y));
|
||||
}
|
||||
}
|
||||
}
|
||||
screen.push(&rgb, f as f64 / fps);
|
||||
}
|
||||
screen.finish()
|
||||
}
|
||||
|
||||
fn flash_of(seconds: usize, paint: impl Fn(usize, usize, usize) -> [u8; 3]) -> Option<(usize, f64, &'static str)> {
|
||||
flash_samples(seconds * 60, 60.0, move |f, _, x, y| paint(f, x, y))
|
||||
}
|
||||
|
||||
/// two colours taking turns `hz` times a second, over a box of the frame
|
||||
fn turns(hz: usize, on: [u8; 3], off: [u8; 3], bx: (usize, usize, usize, usize)) -> Option<(usize, f64, &'static str)> {
|
||||
flash_of(3, move |f, x, y| {
|
||||
let inside = x >= bx.0 && x < bx.0 + bx.2 && y >= bx.1 && y < bx.1 + bx.3;
|
||||
if inside && f * hz * 2 / 60 % 2 == 0 { on } else { off }
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flashing_is_found_past_three_a_second_and_not_at_it() {
|
||||
let (white, black) = ([255, 255, 255], [0, 0, 0]);
|
||||
let all = (0, 0, 96, 54);
|
||||
assert_eq!(turns(3, white, black, all), None, "three a second is the limit, not past it");
|
||||
let (swings, _, kind) = turns(4, white, black, all).expect("four a second");
|
||||
assert_eq!((swings / 2, kind), (4, "general"));
|
||||
// a small box: under a quarter of any window, and then over it
|
||||
assert_eq!(turns(5, white, black, (40, 20, 10, 10)), None);
|
||||
assert!(turns(5, white, black, (30, 18, 32, 18)).is_some());
|
||||
// too small a change, and both ends too bright for WCAG to count it
|
||||
assert_eq!(turns(5, [60, 60, 60], [30, 30, 30], all), None);
|
||||
assert_eq!(turns(5, [255, 255, 255], [235, 235, 235], all), None);
|
||||
// a dark saturated red: too dim to count as a general flash, past the limit as a red one
|
||||
assert_eq!(turns(5, [150, 0, 0], black, all).map(|t| t.2), Some("red"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_flash_of_single_frames_counts_at_any_frame_rate() {
|
||||
// 120 fps with one white frame in every 30: four flashes a second, each gone within a sixtieth of a second
|
||||
let found = flash_samples(360, 120.0, |f, _, _, _| if f % 30 == 1 { [255, 255, 255] } else { [0, 0, 0] });
|
||||
assert_eq!(found.map(|(swings, _, kind)| (swings / 2, kind)), Some((4, "general")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_flash_the_area_sample_averages_away_is_found_in_the_point_sample() {
|
||||
let found = flash_samples(180, 60.0, |f, sample, _, _| {
|
||||
if sample == 0 {
|
||||
return [128, 128, 128];
|
||||
}
|
||||
if f * 5 * 2 / 60 % 2 == 0 { [255, 255, 255] } else { [0, 0, 0] }
|
||||
});
|
||||
assert!(found.is_some(), "the same flash in the point sample alone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_frame_gets_its_exact_time_from_the_log() {
|
||||
// lines FFmpeg 9.0.2 logged with -loglevel level+info
|
||||
@@ -382,34 +316,99 @@ fn only_a_lines_own_severity_counts_as_an_error() {
|
||||
assert_eq!(log_level("frame= 300 fps=0.0"), None);
|
||||
}
|
||||
|
||||
|
||||
/// A centred line in a left: 0; right: 0 box isn't in the left zone: its letters are tested where the render recorded
|
||||
/// them (#89); a left-aligned one is, the finding naming the edge, and a manifest without ink is tested by the box.
|
||||
#[test]
|
||||
fn a_shape_sliding_past_and_ordinary_cuts_are_not_flashing() {
|
||||
let (white, black) = ([255, 255, 255], [0, 0, 0]);
|
||||
assert_eq!(flash_of(3, move |f, x, _| if x < f { white } else { black }), None, "one wipe across the frame");
|
||||
assert_eq!(flash_of(4, move |f, _, _| if (f / 30) % 2 == 0 { white } else { black }), None, "a cut every half second");
|
||||
fn safe_area_tests_the_letters_not_the_box() {
|
||||
let safe_area = |ink: Value| {
|
||||
let m = json!({"fps": 1.0, "frames": [{"frame": 0, "text": [{"text": "centred", "box": [0, 160, 640, 40], "ink": ink}]}]});
|
||||
let (mut issues, mut passed) = (vec![], vec![]);
|
||||
text_rules(&text_runs(&m), None, 640.0, 360.0, None, None, &mut issues, &mut passed);
|
||||
issues.into_iter().filter(|i| i.rule == "safe-area").map(|i| i.says).collect::<String>()
|
||||
};
|
||||
assert_eq!(safe_area(json!([250, 160, 140, 40])), "");
|
||||
let left = safe_area(json!([0, 160, 140, 40]));
|
||||
assert!(left.contains("at the left") && left.contains("its letters 0,160 140x40"), "{left}");
|
||||
assert!(safe_area(Value::Null).contains("its box 0,160 640x40"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_patch_strobing_while_its_background_dims_is_still_found() {
|
||||
// a third of a window: 0 then 124 on a 148 background, then the background settles at 124 and the patch cycles 124 and 160.
|
||||
// The background's drop is under the 0.10 that counts, but it outweighs the patch in the window's mean.
|
||||
let found = flash_samples(180, 60.0, |f, _, x, y| {
|
||||
let patch = x < 16 && y < 12;
|
||||
let level = match (patch, f) {
|
||||
(true, 0) => 0,
|
||||
(true, 1) => 124,
|
||||
(true, _) => if (f - 2) * 5 * 2 / 60 % 2 == 0 { 160 } else { 124 },
|
||||
(false, 0 | 1) => 148,
|
||||
(false, _) => 124,
|
||||
};
|
||||
[level, level, level]
|
||||
});
|
||||
assert!(found.is_some(), "the patch flashes five times a second");
|
||||
fn a_card_sharing_one_word_with_another_line_isnt_held_to_it() {
|
||||
let run = |text: &str, from: f64| Run { text: text.into(), from, to: from + 2.0, box_: [0.0; 4], boxes: vec![], color: String::new(), size: 48.0 };
|
||||
let said = |ws: &[(&str, f64)]| ws.iter().map(|(t, s)| Word { text: (*t).into(), start: *s, end: *s }).collect::<Vec<Word>>();
|
||||
let words = said(&[("at", 37.9), ("wirestock", 38.2), ("i", 38.9), ("worked", 39.0), ("on", 39.2), ("a", 39.3), ("sora", 39.5), ("campaign", 40.2)]);
|
||||
let (mut issues, mut passed) = (vec![], vec![]);
|
||||
// one word of three shared with the line, said 1.35 s before: not a caption of it (the film's false P1)
|
||||
cues(&[run("Wirestock × OpenAI Sora", 39.55)], &words, &mut issues, &mut passed);
|
||||
// one word of four, "campaign": the same
|
||||
cues(&[run("Classroom of Tomorrow campaign", 39.55)], &words, &mut issues, &mut passed);
|
||||
assert!(issues.is_empty(), "{:?}", issues.iter().map(|i| &i.says).collect::<Vec<_>>());
|
||||
// a one-word card is held only to the word said right by it: "wirestock" 1.35 s earlier is another moment
|
||||
cues(&[run("Wirestock", 39.55)], &words, &mut issues, &mut passed);
|
||||
assert!(issues.is_empty(), "{:?}", issues.iter().map(|i| &i.says).collect::<Vec<_>>());
|
||||
// a real caption late by 0.4 s is still found
|
||||
cues(&[run("a Sora campaign", 39.7)], &words, &mut issues, &mut passed);
|
||||
assert_eq!(issues.len(), 1, "{:?}", issues.iter().map(|i| &i.says).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_colour_crossing_the_saturation_line_is_not_a_red_flash() {
|
||||
// one level of green moves the pixel across R/(R+G+B) = 0.8 and hardly changes its red at all
|
||||
let found = flash_samples(180, 60.0, |f, _, _, _| if f * 5 * 2 / 60 % 2 == 0 { [100, 49, 0] } else { [100, 50, 0] });
|
||||
assert_eq!(found, None);
|
||||
fn clipping_is_found_and_a_loud_clean_tone_isnt() {
|
||||
// a clean tone near full scale, then the same tone clamped (a limiter's flat tops), then pushed past full scale
|
||||
let loud = tone(3.0, &[(0.0, 3.0, -1.0)]);
|
||||
assert!(clipped(&loud).is_empty(), "{:?}", clipped(&loud));
|
||||
let clamped: Vec<f32> = loud.iter().map(|v| (v * 10.0).clamp(-0.3, 0.3)).collect();
|
||||
assert_eq!(clipped(&clamped).len(), 1);
|
||||
let over: Vec<f32> = loud.iter().map(|v| (v * 2.0).clamp(-1.0, 1.0)).collect();
|
||||
assert_eq!(clipped(&over).len(), 1);
|
||||
// one transient hitting full scale once isn't clipping
|
||||
let mut once = tone(3.0, &[(0.0, 3.0, -20.0)]);
|
||||
once[SR] = 1.0;
|
||||
assert!(clipped(&once).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dropout_is_found_and_a_faded_pause_isnt() {
|
||||
// a bed at -20 dBFS with 0.6 s cut out of it, as the bootstrap's dropout does
|
||||
let mut cut = tone(4.0, &[(0.0, 4.0, -20.0)]);
|
||||
cut[(1.7 * SR as f64) as usize..(2.3 * SR as f64) as usize].iter_mut().for_each(|v| *v = 0.0);
|
||||
let found = dropouts(&cut);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert!((found[0].0 - 1.7).abs() < 0.02, "{found:?}");
|
||||
// a pause that fades out over 300 ms and back in isn't one, nor a sound that stops and stays stopped
|
||||
let gain = |t: f32| ((1.7 - t) / 0.3).max((t - 2.3) / 0.3).clamp(0.0, 1.0);
|
||||
let paused: Vec<f32> = tone(4.0, &[(0.0, 4.0, -20.0)]).into_iter().enumerate().map(|(i, v)| v * gain(i as f32 / SR as f32)).collect();
|
||||
assert!(dropouts(&paused).is_empty(), "{:?}", dropouts(&paused));
|
||||
assert!(dropouts(&tone(4.0, &[(0.0, 2.0, -20.0)])).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_flash_frame_is_found_and_a_cut_or_a_fade_isnt() {
|
||||
let mut shot = vec![0.5f32; 60];
|
||||
shot[30] = 0.0;
|
||||
assert_eq!(flash_frames(&shot, 30.0).len(), 1);
|
||||
shot[31] = 0.0;
|
||||
assert_eq!(flash_frames(&shot, 30.0).len(), 1, "two frames are one flash");
|
||||
let cut: Vec<f32> = (0..60).map(|i| if i < 30 { 0.6 } else { 0.1 }).collect();
|
||||
assert!(flash_frames(&cut, 30.0).is_empty());
|
||||
let fade: Vec<f32> = (0..60).map(|i| 0.6 * (1.0 - i as f32 / 59.0)).collect();
|
||||
assert!(flash_frames(&fade, 30.0).is_empty());
|
||||
// a white frame, too
|
||||
let mut white = vec![0.3f32; 20];
|
||||
white[10] = 1.0;
|
||||
assert_eq!(flash_frames(&white, 30.0)[0].0, 10.0 / 30.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn things_found_are_findings_and_an_unknown_rule_is_not() {
|
||||
let p = std::env::temp_dir().join(format!("raea-check-things-{}.json", std::process::id()));
|
||||
let found = r#"{"issues": [{"rule": "floating", "p": 2, "at": 1.5, "to": 3.0, "says": "cup floats"}, {"rule": "made-up", "p": 0, "at": 0.0, "says": "x"}]}"#;
|
||||
std::fs::write(&p, found).unwrap();
|
||||
let (mut issues, mut passed) = (Vec::new(), Vec::new());
|
||||
things(p.to_str().unwrap(), &mut issues, &mut passed).unwrap();
|
||||
assert_eq!(issues.iter().map(|i| (i.rule, i.p, i.at)).collect::<Vec<_>>(), [("floating", 2, Some(1.5))]);
|
||||
std::fs::write(&p, r#"{"issues": []}"#).unwrap();
|
||||
things(p.to_str().unwrap(), &mut Vec::new(), &mut passed).unwrap();
|
||||
let _ = std::fs::remove_file(&p);
|
||||
assert_eq!(passed.len(), 1, "nothing found is a pass");
|
||||
}
|
||||
+18
-5
@@ -8,7 +8,8 @@ pub(crate) struct Run {
|
||||
pub(crate) from: f64,
|
||||
pub(crate) to: f64,
|
||||
pub(crate) box_: [f64; 4],
|
||||
/// its box on every frame it shows its whole text: a text the camera carries (a sign on a panning street) moves
|
||||
/// where its letters are on every frame it shows its whole text (the manifest's `ink`, else its box: a centred line in
|
||||
/// a full-width box is nowhere near x = 0, #89): a text the camera carries (a sign on a panning street) moves
|
||||
/// through the frame's edges and zones, which only counts against it when no frame shows it clear
|
||||
pub(crate) boxes: Vec<[f64; 4]>,
|
||||
pub(crate) color: String,
|
||||
@@ -61,7 +62,8 @@ pub(crate) fn text_runs(manifest: &Value) -> Vec<Run> {
|
||||
let mut next = Vec::new();
|
||||
for x in shown {
|
||||
let text = x["text"].as_str().unwrap_or("").trim().to_string();
|
||||
let b = x["box"].as_array().map(|b| [0, 1, 2, 3].map(|i| b.get(i).and_then(Value::as_f64).unwrap_or(0.0))).unwrap_or([0.0; 4]);
|
||||
let quad = |k: &str| x[k].as_array().map(|b| [0, 1, 2, 3].map(|i| b.get(i).and_then(Value::as_f64).unwrap_or(0.0)));
|
||||
let (b, ink) = (quad("box").unwrap_or([0.0; 4]), quad("ink"));
|
||||
let k = key(&text);
|
||||
let found = open.iter().position(|r| {
|
||||
let rk = key(&r.text);
|
||||
@@ -77,7 +79,7 @@ pub(crate) fn text_runs(manifest: &Value) -> Vec<Run> {
|
||||
if text.len() >= r.text.len() {
|
||||
r.text = text;
|
||||
r.box_ = b;
|
||||
r.boxes.push(b);
|
||||
r.boxes.push(ink.unwrap_or(b));
|
||||
}
|
||||
r.to = t + 1.0 / fps;
|
||||
r.color = x["color"].as_str().unwrap_or("rgb(255, 255, 255)").to_string();
|
||||
@@ -169,7 +171,9 @@ pub(crate) fn text_rules(runs: &[Run], heard: Option<&[Word]>, w: f64, h: f64, s
|
||||
issues.push(Issue { rule: "clipped", p: 0, at: Some(r.from), says: format!("{q} runs off the frame (box {x:.0},{y:.0} {bw:.0}x{bh:.0} in {w:.0}x{h:.0}); fit it or break the line") });
|
||||
} else if r.boxes.iter().all(zoned) {
|
||||
unsafe_ += 1;
|
||||
issues.push(Issue { rule: "safe-area", p: 1, at: Some(r.from), says: format!("{q} sits in the app's UI zone (keep {zt:.0} px top, {zb:.0} bottom, {zl:.0} left, {zr:.0} right clear)") });
|
||||
let [ix, iy, iw, ih] = *r.boxes.last().unwrap_or(&r.box_);
|
||||
let edge = if iy < zt { format!("the top (keep {zt:.0} px clear)") } else if iy + ih > h - zb { format!("the bottom (keep {zb:.0} px clear)") } else if ix < zl { format!("the left (keep {zl:.0} px clear)") } else { format!("the right (keep {zr:.0} px clear)") };
|
||||
issues.push(Issue { rule: "safe-area", p: 1, at: Some(r.from), says: format!("{q} sits in the app's UI zone at {edge}: its {} {ix:.0},{iy:.0} {iw:.0}x{ih:.0} in {w:.0}x{h:.0}", if r.boxes.last() == Some(&r.box_) { "box" } else { "letters" }) });
|
||||
}
|
||||
let words = r.text.split_whitespace().count() as f64;
|
||||
let need = (0.3 * words).max(1.0);
|
||||
@@ -244,12 +248,21 @@ pub(crate) fn cues(runs: &[Run], words: &[Word], issues: &mut Vec<Issue>, passed
|
||||
for r in runs {
|
||||
let shown: Vec<String> = r.text.split_whitespace().map(norm).filter(|t| !t.is_empty()).collect();
|
||||
let Some((k, i)) = shown.iter().enumerate().filter(|(_, t)| t.len() >= 3 && !SMALL.contains(&t.as_str())).find_map(|(k, t)| {
|
||||
words.iter().enumerate().filter(|(_, w)| norm(&w.text) == *t && (w.start - r.from).abs() <= 2.0).min_by(|(_, a), (_, b)| (a.start - r.from).abs().total_cmp(&(b.start - r.from).abs())).map(|(i, _)| (k, i))
|
||||
// a one-word card matches only a word said right by it: the same word said 2 s earlier is another moment
|
||||
let near = if shown.len() == 1 { 0.75 } else { 2.0 };
|
||||
words.iter().enumerate().filter(|(_, w)| norm(&w.text) == *t && (w.start - r.from).abs() <= near).min_by(|(_, a), (_, b)| (a.start - r.from).abs().total_cmp(&(b.start - r.from).abs())).map(|(i, _)| (k, i))
|
||||
}) else {
|
||||
continue;
|
||||
};
|
||||
// back over the words the text shows before it, while the voice says them in the same order just before
|
||||
let back = (1..=k.min(i)).take_while(|&n| norm(&words[i - n].text) == shown[k - n]).last().unwrap_or(0);
|
||||
// a caption says what the voice says: at least half its words, in order, around the anchor. A card that only
|
||||
// shares one word with another line ("Wirestock x OpenAI Sora" against "At Wirestock, I worked on...") isn't
|
||||
// a caption of it, and holding it to that word's time was a false P1
|
||||
let fwd = (1..).take_while(|&n| k + n < shown.len() && i + n < words.len() && norm(&words[i + n].text) == shown[k + n]).last().unwrap_or(0);
|
||||
if (back + 1 + fwd) * 2 < shown.len() {
|
||||
continue;
|
||||
}
|
||||
let w = &words[i - back];
|
||||
let tok = norm(&w.text);
|
||||
checked += 1;
|
||||
|
||||
@@ -35,10 +35,17 @@ pub fn taste_dir() -> Option<PathBuf> {
|
||||
std::env::var_os("RAEA_TASTE").map(PathBuf::from).or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".raea/taste")))
|
||||
}
|
||||
|
||||
/// The .ts files `--taste` names: the file, or every .ts in the folder.
|
||||
/// The .ts files `--taste` names: the file, or every .ts in the folder. A file named under the person's taste folder
|
||||
/// that isn't there yet is a note, not a refusal: the skill prescribes --taste on that folder's own taste file, and a
|
||||
/// machine with none yet should still check (#89); any other missing path is left to the reader to refuse.
|
||||
pub fn taste_files(args: &[String]) -> Vec<PathBuf> {
|
||||
let Some(t) = flag(args, "--taste").map(PathBuf::from) else { return vec![] };
|
||||
if t.extension().is_some_and(|x| x == "ts") {
|
||||
let home = taste_dir().map(std::path::absolute).and_then(Result::ok);
|
||||
if !t.is_file() && t.parent().map(std::path::absolute).and_then(Result::ok) == home {
|
||||
eprintln!("note: no taste yet ({} isn't there); checking without it", t.display());
|
||||
return vec![];
|
||||
}
|
||||
return vec![t];
|
||||
}
|
||||
let mut v: Vec<PathBuf> = std::fs::read_dir(&t).into_iter().flatten().filter_map(|e| e.ok().map(|e| e.path())).filter(|f| f.extension().is_some_and(|x| x == "ts")).collect();
|
||||
@@ -106,7 +113,7 @@ fn held(project: &Path, given: Vec<PathBuf>, host: &Host) -> (Vec<Rule>, Vec<Fin
|
||||
}
|
||||
}
|
||||
let ws = record::up(project, ".raea/workspace");
|
||||
for (dir, scope) in ws.iter().map(|w| (w.join("controllers"), "workspace")).chain([(project.join("controllers"), "project")]) {
|
||||
for (dir, scope) in ws.iter().map(|w| (raea_app_registry::shared_dir(w, "controllers"), "workspace")).chain([(project.join("controllers"), "project")]) {
|
||||
// a workspace's own folder is its project's too: read once
|
||||
if scope == "project" && ws.as_deref() == Some(project) {
|
||||
continue;
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
[package]
|
||||
name = "raea-app-fingerprint"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "`raea fingerprint` (docs/fingerprint.feature FP3a): new, bootstrap, teach, score and report, run by a resident service on localhost that keeps the encoders loaded"
|
||||
|
||||
[dependencies]
|
||||
# the taxonomy, evidence and heads
|
||||
raea-sys-fingerprint = { path = "../../systems/fingerprint" }
|
||||
# scoring and the sheet, which one judges a piece, diff and profiles
|
||||
raea-sys-fingerprint-use = { path = "../../systems/fingerprint-use" }
|
||||
raea-sys-fingerprint-things = { path = "../../systems/fingerprint-things" }
|
||||
# the encoders and the columns they make
|
||||
raea-sys-columns = { path = "../../systems/columns" }
|
||||
# raea check's floor on the file: its findings go in the summary, and a check wins over a head (FP4c)
|
||||
raea-app-check = { path = "../check" }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
anyhow = "1"
|
||||
# the draws of FP0b's few-shot curves, seeded (bootstrap.rs)
|
||||
fastrand = "2"
|
||||
@@ -0,0 +1,87 @@
|
||||
//! Approvals are positives (docs/fingerprint.feature FP6a): an approved cut, a picture lock, a publish or a golden
|
||||
//! reference says every moment of it is clean on every axis, except where the person left a note. `raea fingerprint
|
||||
//! approve FILE... [--project P]` adds a clean row on every axis ("*") for each 2 s window of each file, skipping the
|
||||
//! windows within 2 s of a pinned note on that file in its project's feed (.raea/feed/*.json), since a note there may
|
||||
//! name a defect. Notes aren't read into labels here; that is FP5a.
|
||||
|
||||
use crate::bootstrap::WIN;
|
||||
use crate::flag;
|
||||
use anyhow::{Result, anyhow};
|
||||
use raea_sys_columns::Encoders;
|
||||
use raea_sys_fingerprint::evidence::{Row, features};
|
||||
use raea_sys_fingerprint::folder::Folder;
|
||||
use raea_sys_fingerprint::taxonomy::Fingerprint;
|
||||
use std::path::Path;
|
||||
|
||||
/// The seconds a note was pinned at on `file`, from every post in its project's feed that shows a file of that name
|
||||
pub(crate) fn noted(file: &Path) -> Vec<f64> {
|
||||
let Some(name) = file.file_name().and_then(|n| n.to_str()) else { return Vec::new() };
|
||||
let Some(feed) = file.ancestors().map(|d| d.join(".raea/feed")).find(|d| d.is_dir()) else { return Vec::new() };
|
||||
let mut at = Vec::new();
|
||||
for e in std::fs::read_dir(feed).into_iter().flatten().flatten() {
|
||||
let Ok(text) = std::fs::read_to_string(e.path()) else { continue };
|
||||
let Ok(post) = serde_json::from_str::<serde_json::Value>(&text) else { continue };
|
||||
let shows = post["media"].as_array().into_iter().flatten().any(|m| m["path"].as_str().is_some_and(|p| p.ends_with(name)));
|
||||
if shows {
|
||||
at.extend(post["notes"].as_array().into_iter().flatten().filter_map(|n| n["pin"]["t"].as_f64()));
|
||||
}
|
||||
}
|
||||
at
|
||||
}
|
||||
|
||||
/// The windows an approval labels clean: every WIN seconds of the piece, away from its notes
|
||||
pub(crate) fn windows(dur: f64, notes: &[f64]) -> Vec<(f64, f64)> {
|
||||
let n = (dur / WIN).floor() as usize;
|
||||
(0..n).map(|i| (i as f64 * WIN, (i + 1) as f64 * WIN)).filter(|(a, b)| !notes.iter().any(|t| *t > a - WIN && *t < b + WIN)).collect()
|
||||
}
|
||||
|
||||
pub(crate) fn approve(enc: &mut Encoders, dir: &Folder, fp: &Fingerprint, args: &[String], cwd: &Path, project: impl Fn(&Path) -> String) -> Result<(String, usize)> {
|
||||
let files = crate::named(args, cwd)?;
|
||||
if files.is_empty() {
|
||||
return Err(anyhow!("which approved work? raea fingerprint approve FILE..."));
|
||||
}
|
||||
let mut l = dir.ledger()?;
|
||||
let mut out = String::new();
|
||||
let mut added = 0;
|
||||
for file in &files {
|
||||
let c = enc.columns(file)?;
|
||||
// an approval given again replaces the last one for that media
|
||||
l.retain(|r| !(r.source == "approval" && r.media == c.media));
|
||||
let notes = noted(file);
|
||||
let w = windows(c.dur, ¬es);
|
||||
for (a, b) in &w {
|
||||
let row = Row {
|
||||
media: c.media.clone(),
|
||||
a: *a,
|
||||
b: *b,
|
||||
axis: "*".into(),
|
||||
bad: false,
|
||||
weight: 1.0,
|
||||
who: fp.who.clone().unwrap_or_else(|| "me".into()),
|
||||
source: "approval".into(),
|
||||
project: flag(args, "--project").map_or_else(|| project(file), str::to_string),
|
||||
kind: None,
|
||||
region: None,
|
||||
words: None,
|
||||
at: 0,
|
||||
pin: None,
|
||||
band: None,
|
||||
};
|
||||
l.push(row, &features(&c, *a, *b));
|
||||
}
|
||||
added += w.len();
|
||||
out += &format!("approved {}: {} clean windows on every axis{}\n", file.display(), w.len(), if notes.is_empty() { String::new() } else { format!(", {} noted moments left out", notes.len()) });
|
||||
}
|
||||
dir.write_ledger(&l)?;
|
||||
Ok((out, added))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn an_approval_leaves_out_the_windows_near_a_note() {
|
||||
assert_eq!(super::windows(9.0, &[]), vec![(0.0, 2.0), (2.0, 4.0), (4.0, 6.0), (6.0, 8.0)]);
|
||||
// a note at 5 s: the windows within 2 s of it go
|
||||
assert_eq!(super::windows(12.0, &[5.0]), vec![(0.0, 2.0), (8.0, 10.0), (10.0, 12.0)]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
//! The bootstrap (FP4a, FP4b): known defects put into windows of the person's own real work, so the mechanical axes
|
||||
//! learn from labels by construction, and the cheats each must still catch. Each source gives `per` 2 s windows
|
||||
//! from 0.5 s to its end less 2.5 s (FP0b's protocol); each window gives a clean row ("*"), a row per picture and
|
||||
//! sound defect, and a row per cheat. Only what the damage changed is embedded again: a freeze reuses the first
|
||||
//! frame's vector, a flash re-embeds one frame, a sound defect leaves the picture alone.
|
||||
//!
|
||||
//! Then it measures what FP0b measured, in Rust: each axis's AUC from k = 4, 16 and 32 labelled windows a class, held
|
||||
//! out by source (5 folds x 5 draws, the scaler fit on every plain row of the training sources), on its own
|
||||
//! modality and on the one FP0b used; and each word head's AUC and catch rate with no labels (FP0g).
|
||||
|
||||
use raea_sys_fingerprint::evidence::{Ledger, Row, features, slice};
|
||||
use raea_sys_fingerprint::head::{Logistic, Scaler, auc, quantile, share_over};
|
||||
use raea_sys_fingerprint::taxonomy::Fingerprint;
|
||||
use raea_sys_fingerprint::train::{C, folds};
|
||||
use raea_sys_fingerprint::words::Words;
|
||||
use anyhow::Result;
|
||||
use raea_sys_columns::damage::{self, CHEATS, Noise, PICTURE, SOUND};
|
||||
use raea_sys_columns::media::{self, Rgb};
|
||||
use raea_sys_columns::window::Modality;
|
||||
use raea_sys_columns::{Columns, Encoders, FPS};
|
||||
use serde::Serialize;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// The window, seconds
|
||||
pub const WIN: f64 = 2.0;
|
||||
/// Sources shorter than this are skipped (FP0b's)
|
||||
pub const SHORTEST: f64 = 6.0;
|
||||
pub const KS: [usize; 3] = [4, 16, 32];
|
||||
|
||||
/// FP0b's AUC at k = 32 for each axis, on the modality it was measured on (docs/fingerprint.md FP0b, FP0g)
|
||||
pub const FP0B: [(&str, Modality, f64); 11] = [
|
||||
("blur", Modality::Picture, 1.00),
|
||||
("dark", Modality::Picture, 0.95),
|
||||
("glow", Modality::Picture, 0.80),
|
||||
("flash", Modality::Change, 0.97),
|
||||
("freeze", Modality::Change, 1.00),
|
||||
("noise", Modality::Events, 1.00),
|
||||
("dropout", Modality::Events, 0.97),
|
||||
("clip", Modality::Events, 0.98),
|
||||
("noise", Modality::Sound, 1.00),
|
||||
("dropout", Modality::Sound, 0.99),
|
||||
("clip", Modality::Sound, 1.00),
|
||||
];
|
||||
|
||||
#[derive(Debug, Default, Serialize)]
|
||||
pub struct Made {
|
||||
pub sources: usize,
|
||||
pub windows: usize,
|
||||
pub rows: usize,
|
||||
/// windows too quiet for a gap or clipping to change them, which get only the noise damage
|
||||
pub quiet: usize,
|
||||
pub skipped: Vec<String>,
|
||||
}
|
||||
|
||||
/// The rows a bootstrap makes, which the next bootstrap replaces
|
||||
fn made_here(r: &Row) -> bool {
|
||||
matches!(r.source.as_str(), "damage" | "cheat")
|
||||
}
|
||||
|
||||
/// A plain damage row on `axis` ("*" for the clean windows)
|
||||
fn damage_on(r: &Row, axis: &str) -> bool {
|
||||
r.source == "damage" && r.axis == axis
|
||||
}
|
||||
|
||||
/// The plain damage rows on `axis`
|
||||
fn damage_rows(l: &Ledger, axis: &str) -> Vec<usize> {
|
||||
(0..l.rows.len()).filter(|&i| damage_on(&l.rows[i], axis)).collect()
|
||||
}
|
||||
|
||||
/// Each defect of a sense as (kind, axis, source): the plain ones, then their disguises
|
||||
fn damages(sense: &[&'static str]) -> Vec<(&'static str, &'static str, &'static str)> {
|
||||
sense.iter().map(|k| (*k, *k, "damage")).chain(CHEATS.iter().filter(|c| sense.contains(&c.1)).map(|c| (c.0, c.1, "cheat"))).collect()
|
||||
}
|
||||
|
||||
/// Below this a window is near silence: a gap or clipping changes nothing, and a row saying it does teaches noise
|
||||
const QUIET_DB: f32 = -45.0;
|
||||
|
||||
/// The window's loudness in dB over all of it
|
||||
fn loudness(pcm: &[f32]) -> f32 {
|
||||
if pcm.is_empty() {
|
||||
return -100.0;
|
||||
}
|
||||
(10.0 * (pcm.iter().map(|x| x * x).sum::<f32>() / pcm.len() as f32).max(1e-10).log10()).max(-100.0)
|
||||
}
|
||||
|
||||
fn zeros_to(mut v: Vec<f32>, n: usize) -> Vec<f32> {
|
||||
v.resize(n, 0.0);
|
||||
v
|
||||
}
|
||||
|
||||
/// The picture columns of damaged frames, embedding only frames the damage changed
|
||||
fn picture_of(enc: &mut Encoders, clean: &[Rgb], sig: &[f32], look: &[f32], d: &[Rgb]) -> Result<(Vec<f32>, Vec<f32>)> {
|
||||
let (sd, ld) = (sig.len() / clean.len().max(1), look.len() / clean.len().max(1));
|
||||
let mut fresh: Vec<Rgb> = Vec::new();
|
||||
let mut from: Vec<Result<usize, usize>> = Vec::new();
|
||||
for f in d {
|
||||
match clean.iter().position(|c| c == f) {
|
||||
Some(j) => from.push(Ok(j)),
|
||||
None => {
|
||||
fresh.push(f.clone());
|
||||
from.push(Err(fresh.len() - 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
let (fs, fl) = if fresh.is_empty() { (Vec::new(), Vec::new()) } else { enc.picture(&fresh)? };
|
||||
let (mut s, mut l) = (Vec::with_capacity(sig.len()), Vec::with_capacity(look.len()));
|
||||
for f in from {
|
||||
let (ss, ll, j) = match f {
|
||||
Ok(j) => (sig, look, j),
|
||||
Err(k) => (&fs[..], &fl[..], k),
|
||||
};
|
||||
s.extend_from_slice(&ss[j * sd..(j + 1) * sd]);
|
||||
l.extend_from_slice(&ll[j * ld..(j + 1) * ld]);
|
||||
}
|
||||
Ok((s, l))
|
||||
}
|
||||
|
||||
/// The bootstrap's rows for `files` into the ledger, replacing any it made before. `say` hears each source's progress.
|
||||
pub fn rows(enc: &mut Encoders, who: &str, files: &[PathBuf], per: usize, l: &mut Ledger, say: &mut dyn FnMut(String)) -> Result<Made> {
|
||||
l.retain(|r| !made_here(r));
|
||||
let mut made = Made::default();
|
||||
let mut noise = Noise::new(0);
|
||||
for (n, file) in files.iter().enumerate() {
|
||||
let dur = media::duration(file).unwrap_or(0.0);
|
||||
if dur < SHORTEST {
|
||||
made.skipped.push(format!("{} ({dur:.1} s, under {SHORTEST} s)", file.display()));
|
||||
continue;
|
||||
}
|
||||
let sha = media::sha256(file)?;
|
||||
let frames = media::frames(file, FPS, 0.0, dur)?;
|
||||
let (p16, p48) = (media::sound(file, 16_000)?, media::sound(file, 48_000)?);
|
||||
made.sources += 1;
|
||||
for w in 0..per {
|
||||
let t = 0.5 + (dur - 3.0) * w as f64 / (per - 1).max(1) as f64;
|
||||
let i0 = (t * FPS).round() as usize;
|
||||
let Some(fr) = frames.get(i0..i0 + (WIN * FPS) as usize) else { continue };
|
||||
let cut = |p: &[f32], rate: f64| zeros_to(p.get((t * rate) as usize..).unwrap_or(&[]).iter().take((WIN * rate) as usize).copied().collect(), (WIN * rate) as usize);
|
||||
let (w16, w48) = (cut(&p16, 16_000.0), cut(&p48, 48_000.0));
|
||||
let (sig, look) = enc.picture(fr)?;
|
||||
let (clap, yam) = enc.sound(&w16, &w48)?;
|
||||
let clean = Columns { media: sha.clone(), dur: WIN, sig, look, clap, yam, level: media::levels(&w16, 16_000), text: Vec::new() };
|
||||
let push = |l: &mut Ledger, c: &Columns, axis: &str, kind: &str, source: &str| {
|
||||
let r = Row {
|
||||
media: sha.clone(),
|
||||
a: t,
|
||||
b: t + WIN,
|
||||
axis: axis.into(),
|
||||
bad: axis != "*",
|
||||
weight: 1.0,
|
||||
who: who.into(),
|
||||
source: source.into(),
|
||||
project: sha[..12].to_string(),
|
||||
kind: Some(kind.into()),
|
||||
region: None,
|
||||
words: None,
|
||||
at: 0,
|
||||
pin: None,
|
||||
band: None,
|
||||
};
|
||||
l.push(r, &features(c, 0.0, WIN));
|
||||
};
|
||||
push(l, &clean, "*", "clean", "damage");
|
||||
for (kind, axis, source) in damages(&PICTURE) {
|
||||
let (sig, look) = picture_of(enc, fr, &clean.sig, &clean.look, &damage::picture(fr, kind))?;
|
||||
push(l, &Columns { sig, look, ..clean.clone() }, axis, kind, source);
|
||||
}
|
||||
let quiet = loudness(&w16) < QUIET_DB;
|
||||
made.quiet += quiet as usize;
|
||||
for (kind, axis, source) in damages(&SOUND).into_iter().filter(|s| !quiet || s.1 == "noise") {
|
||||
let (d16, d48) = (damage::sound(&w16, kind, 16_000, &mut noise), damage::sound(&w48, kind, 48_000, &mut noise));
|
||||
let (clap, yam) = enc.sound(&d16, &d48)?;
|
||||
push(l, &Columns { clap, yam, level: media::levels(&d16, 16_000), ..clean.clone() }, axis, kind, source);
|
||||
}
|
||||
made.windows += 1;
|
||||
}
|
||||
say(format!("source {}/{} {}: {} windows so far", n + 1, files.len(), file.display(), made.windows));
|
||||
}
|
||||
made.rows = l.rows.iter().filter(|r| made_here(r)).count();
|
||||
Ok(made)
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct Curve {
|
||||
pub axis: String,
|
||||
pub modality: Modality,
|
||||
/// AUC at each k
|
||||
pub k: BTreeMap<usize, f64>,
|
||||
/// FP0b's at k = 32 on this modality, and whether this run came within 0.03 of it or beat it
|
||||
pub fp0b: Option<f64>,
|
||||
pub holds: Option<bool>,
|
||||
}
|
||||
|
||||
fn sample(rng: &mut fastrand::Rng, from: &[usize], k: usize) -> Vec<usize> {
|
||||
let mut v = from.to_vec();
|
||||
rng.shuffle(&mut v);
|
||||
v.truncate(k);
|
||||
v
|
||||
}
|
||||
|
||||
/// FP0b's few-shot curve for one axis on one modality, from the bootstrap's rows
|
||||
pub fn curve(l: &Ledger, axis: &str, m: Modality, rng: &mut fastrand::Rng) -> Curve {
|
||||
let s = slice(m);
|
||||
let row = |i: usize| &l.features(i)[s.clone()];
|
||||
let plain = |i: &usize| l.rows[*i].source == "damage";
|
||||
let (clean, bad) = (damage_rows(l, "*"), damage_rows(l, axis));
|
||||
let projects = l.projects(&clean);
|
||||
let mut k_auc = BTreeMap::new();
|
||||
for k in KS {
|
||||
let mut aucs = Vec::new();
|
||||
for fold in folds(&projects) {
|
||||
let held = |i: &usize| fold.contains(&l.rows[*i].project);
|
||||
let base: Vec<&[f32]> = (0..l.rows.len()).filter(|i| plain(i) && !held(i)).map(row).collect();
|
||||
let sc = Scaler::fit(&base);
|
||||
let (tc, tb): (Vec<usize>, Vec<usize>) = (clean.iter().copied().filter(|i| !held(i)).collect(), bad.iter().copied().filter(|i| !held(i)).collect());
|
||||
if tc.len() < k || tb.len() < k {
|
||||
continue;
|
||||
}
|
||||
for _ in 0..5 {
|
||||
let (a, b) = (sample(rng, &tc, k), sample(rng, &tb, k));
|
||||
let x: Vec<&[f32]> = a.iter().chain(&b).map(|&i| row(i)).collect();
|
||||
let y: Vec<bool> = (0..2 * k).map(|i| i >= k).collect();
|
||||
let f = Logistic::fit(sc.clone(), &x, &y, None, C, true);
|
||||
let score = |v: &Vec<usize>| -> Vec<f32> { v.iter().filter(|i| held(i)).map(|&i| f.score(row(i))).collect() };
|
||||
aucs.push(auc(&score(&bad), &score(&clean)));
|
||||
}
|
||||
}
|
||||
let ok: Vec<f64> = aucs.into_iter().filter(|a| a.is_finite()).collect();
|
||||
if !ok.is_empty() {
|
||||
k_auc.insert(k, ok.iter().sum::<f64>() / ok.len() as f64);
|
||||
}
|
||||
}
|
||||
let fp0b = FP0B.iter().find(|(a, mm, _)| *a == axis && *mm == m).map(|x| x.2);
|
||||
let holds = fp0b.zip(k_auc.get(&32)).map(|(want, got)| *got >= want - 0.03);
|
||||
Curve { axis: axis.into(), modality: m, k: k_auc, fp0b, holds }
|
||||
}
|
||||
|
||||
/// Every mechanical axis's curve on its own modality and on FP0b's
|
||||
pub fn curves(fp: &Fingerprint, l: &Ledger) -> Vec<Curve> {
|
||||
let mut rng = fastrand::Rng::with_seed(1);
|
||||
let mut out = Vec::new();
|
||||
for axis in PICTURE.iter().chain(&SOUND) {
|
||||
let own = fp.axis(axis).map(|a| a.modality);
|
||||
let mut ms: Vec<Modality> = own.into_iter().chain(FP0B.iter().filter(|x| x.0 == *axis).map(|x| x.1)).collect();
|
||||
ms.dedup();
|
||||
for m in ms.into_iter().collect::<BTreeSet<_>>() {
|
||||
out.push(curve(l, axis, m, &mut rng));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct WordScore {
|
||||
pub axis: String,
|
||||
/// AUC, damaged against clean windows, with no labels
|
||||
pub auc: f64,
|
||||
/// the share of damaged windows over the score that flags 10% of clean ones
|
||||
pub caught: f64,
|
||||
/// each cheat's share over that same score
|
||||
pub cheats: BTreeMap<String, f64>,
|
||||
}
|
||||
|
||||
/// Each word head on the bootstrap's windows (FP0g)
|
||||
pub fn word_scores(l: &Ledger, words: &Words) -> Vec<WordScore> {
|
||||
let z = |i: usize, axis: &str| words.z(axis, l.features(i));
|
||||
let of = |axis: &str, pick: &dyn Fn(&Row) -> bool| -> Vec<f32> { l.rows.iter().enumerate().filter(|(_, r)| pick(r)).filter_map(|(i, _)| z(i, axis)).collect() };
|
||||
let mut out = Vec::new();
|
||||
for axis in PICTURE.iter().chain(&SOUND) {
|
||||
if !words.axes.iter().any(|w| w.0 == *axis) {
|
||||
continue;
|
||||
}
|
||||
let clean = of(axis, &|r| damage_on(r, "*"));
|
||||
let bad = of(axis, &|r| damage_on(r, axis));
|
||||
let thr = quantile(&clean, 0.9);
|
||||
let share = |v: &[f32]| share_over(v, thr);
|
||||
let cheats = CHEATS.iter().filter(|c| c.1 == *axis).map(|c| (c.0.to_string(), share(&of(axis, &|r| r.source == "cheat" && r.kind.as_deref() == Some(c.0))))).collect();
|
||||
out.push(WordScore { axis: axis.to_string(), auc: auc(&bad, &clean), caught: share(&bad), cheats });
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
//! `raea fingerprint` (docs/fingerprint.feature FP3a): a person's fingerprint made, bootstrapped, taught and used to
|
||||
//! score a piece. The encoders take seconds to load, so the verbs run in a resident service (`raea fingerprint
|
||||
//! serve`, serve.rs) that keeps them loaded: the first verb starts it, on localhost, and later verbs reach it in
|
||||
//! milliseconds (earshot's CLI reloads its models on every call, 20-40 s). It leaves after 30 idle minutes, or on
|
||||
//! `raea fingerprint stop`. RAEA_FINGERPRINT_HERE=1 runs a verb in this process instead.
|
||||
|
||||
mod approve;
|
||||
mod bootstrap;
|
||||
mod moving;
|
||||
mod notes;
|
||||
mod pairing;
|
||||
mod pick;
|
||||
mod postmortem;
|
||||
mod profiles;
|
||||
mod reembed;
|
||||
mod serve;
|
||||
mod things;
|
||||
mod verbs;
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
pub use serve::serve;
|
||||
|
||||
pub const USAGE: &str = "raea fingerprint new NAME [--who W] [--about TEXT] [--extends FP] [--kinds K,K] [--tags T,T] | raea fingerprint bootstrap FILE... [--from LIST] [--per N] | raea fingerprint teach FILE --axis A --at T [--bad|--good] [--span S] [--box x0,y0,x1,y1] [--words W] [--project P] | raea fingerprint approve FILE... [--project P] | raea fingerprint pair WORSE BETTER --axis A [--at T] [--then T2] | raea fingerprint versions V1 V2... | raea fingerprint profile REFS... --as NAME [--against LIST] | raea fingerprint score FILE [--was OLD] [--json] [--sheet out.png] [--timeline] [--profile NAME] | raea fingerprint report [--json] | raea fingerprint which [PATH] [--json] | raea fingerprint use NAME [--in project|workspace] [PATH] | raea fingerprint diff A B [--json] | raea fingerprint share NAME [--in project|workspace] [PATH] | raea fingerprint reembed PLACE... | raea fingerprint read PROJECT [--by kimi|claude] | raea fingerprint readings [PROJECT] [--ask N] [--tally] | raea fingerprint learn-notes [PROJECT] | raea fingerprint move [--fp CHILD] [--to PARENT] [--axis A] [--source S] [--project P] | raea fingerprint postmortem [PROJECT] [--ask N] [--tally] | raea fingerprint things FILE [--project P] [--json] | raea fingerprint stop [--fp NAME] (a person's sense of good work as axes with small heads over on-device encoders, docs/fingerprint.md: new makes ~/.raea/fingerprints/NAME with raea's base taxonomy in fingerprint.ts (or FP's axes with --extends), what it's for, the kinds of piece and project tags it judges, and every axis scoring from its words; bootstrap puts known defects into windows of real work and trains the mechanical axes, held out by source, and patch heads that say where in the frame a picture defect is; teach adds a label at a moment; approve makes approved work clean on every axis, away from its notes; pair says one moment is better than another on an axis (a pick, a hand edit); versions makes weak pairs of noted moments the next version changed; score prints the moments it expects a note on first (where in the frame, and the layers there, when its patch head points held out), then every axis per window with --json, a sheet PNG with --sheet, or the piece second by second in words with --timeline, and with --was OLD whether each of OLD's gating flags is fixed, still there, or looks disguised (nearer the axis's disguised defects than clean work); profile takes the ranges of work you admire (loudness, tilt, cut rate, motion, brightness, contrast, saturation, sharpness), checked leave-one-out, and score --profile says what falls outside them, where and which way; report says each head's held-out score, labels, cheats, gate and what it can't judge; which says the one that judges a piece (its project's, its workspace's, then yours) and why, use pins one there, diff lists the axes two fingerprints rank the same evidence most differently on, and share copies one's taxonomy and evidence (no heads, no media) into a project or workspace for its team; reembed moves a fingerprint's evidence to this machine's encoders, re-embedding the rows whose media it finds; read has a fresh kimi or claude session read a project's pinned notes into kinds and axes, readings puts them to you to check and tallies your answers, and learn-notes makes the defects and praise evidence once you've agreed with 45 kinds and 40 axes in 50, each project's in the fingerprint that judges it; move takes a child's own labels (by axis, source or project) up into a fingerprint it extends, which never reads them otherwise; postmortem scores every version in a project's feed and asks you at most ten yes/no questions in the app, each with its moment playing, where the fingerprint disagrees with your labels or is least sure, and --tally makes your answers evidence and says how each head's held-out score moved; things finds a piece's shots, its things (a render's layers, and the marks drawn on its notes) with their depth, and the camera's path, and says where a thing floats, two pass through each other, the camera lurches mid-move or nothing is on screen, as JSON for `raea check --things` with --json)";
|
||||
|
||||
/// 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); 31] = [
|
||||
("--fp", true),
|
||||
("--was", true),
|
||||
("--to", true),
|
||||
("--source", true),
|
||||
("--kinds", true),
|
||||
("--tags", true),
|
||||
("--who", true),
|
||||
("--about", true),
|
||||
("--extends", true),
|
||||
("--from", true),
|
||||
("--per", true),
|
||||
("--axis", true),
|
||||
("--at", true),
|
||||
("--then", true),
|
||||
("--span", true),
|
||||
("--box", true),
|
||||
("--words", true),
|
||||
("--project", true),
|
||||
("--sheet", true),
|
||||
("--in", true),
|
||||
("--as", true),
|
||||
("--against", true),
|
||||
("--profile", true),
|
||||
("--by", true),
|
||||
("--ask", true),
|
||||
("--tally", false),
|
||||
("--bad", false),
|
||||
("--good", false),
|
||||
("--json", false),
|
||||
("--timeline", false),
|
||||
("--here", false),
|
||||
];
|
||||
|
||||
/// A flag's value
|
||||
pub(crate) fn flag<'a>(args: &'a [String], name: &str) -> Option<&'a str> {
|
||||
args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).map(String::as_str)
|
||||
}
|
||||
|
||||
pub(crate) fn has(args: &[String], name: &str) -> bool {
|
||||
args.iter().any(|a| a == name)
|
||||
}
|
||||
|
||||
/// A path as given, against the folder the verb ran in (an absolute one stays itself)
|
||||
pub(crate) fn at(cwd: &Path, p: &str) -> std::path::PathBuf {
|
||||
cwd.join(p)
|
||||
}
|
||||
|
||||
/// The files a verb names, against the folder it ran in
|
||||
pub(crate) fn named(args: &[String], cwd: &Path) -> anyhow::Result<Vec<std::path::PathBuf>> {
|
||||
Ok(words(args).map_err(anyhow::Error::msg)?.iter().map(|f| at(cwd, f)).collect())
|
||||
}
|
||||
|
||||
/// The files a list names, one a line against the list's own folder; blank lines and # lines are skipped
|
||||
pub(crate) fn listed(cwd: &Path, list: &str) -> anyhow::Result<Vec<std::path::PathBuf>> {
|
||||
use anyhow::Context;
|
||||
let list = at(cwd, list);
|
||||
let text = std::fs::read_to_string(&list).with_context(|| list.display().to_string())?;
|
||||
let base = list.parent().unwrap_or(cwd);
|
||||
Ok(text.lines().map(str::trim).filter(|l| !(l.is_empty() || l.starts_with('#'))).map(|l| at(base, l)).collect())
|
||||
}
|
||||
|
||||
/// The words that aren't flags or their values; an unknown flag is an error
|
||||
pub(crate) fn words(args: &[String]) -> Result<Vec<&str>, String> {
|
||||
let mut out = Vec::new();
|
||||
let mut it = args.iter();
|
||||
while let Some(a) = it.next() {
|
||||
match FLAGS.iter().find(|(f, _)| f == a) {
|
||||
Some((_, true)) => {
|
||||
it.next().ok_or_else(|| format!("{a} takes a value"))?;
|
||||
}
|
||||
Some(_) => {}
|
||||
None if a.starts_with("--") => return Err(format!("no flag {a}")),
|
||||
None => out.push(a.as_str()),
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// `raea fingerprint VERB ...`, printed; its exit code (1: the verb failed, 2: the command was wrong)
|
||||
pub fn cli(args: &[String], eval: Eval) -> i32 {
|
||||
let verb = match args.first().map(String::as_str) {
|
||||
None | Some("--help" | "-h" | "help") => {
|
||||
println!("{USAGE}");
|
||||
return 0;
|
||||
}
|
||||
Some(v) => v,
|
||||
};
|
||||
if let Err(e) = words(&args[1..]) {
|
||||
eprintln!("raea fingerprint: {e}\n{USAGE}");
|
||||
return 2;
|
||||
}
|
||||
match verb {
|
||||
"serve" => match serve(eval) {
|
||||
Ok(()) => 0,
|
||||
Err(e) => {
|
||||
eprintln!("raea fingerprint serve: {e:#}");
|
||||
1
|
||||
}
|
||||
},
|
||||
"report" => verbs::report_here(args),
|
||||
"which" => pick::which_here(&args[1..], &std::env::current_dir().unwrap_or_default()),
|
||||
"diff" => pick::diff_here(&args[1..]),
|
||||
"read" => notes::read_here(&args[1..], &std::env::current_dir().unwrap_or_default()),
|
||||
"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" | "postmortem" | "things" | "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) };
|
||||
if !out.is_empty() {
|
||||
println!("{}", out.trim_end());
|
||||
}
|
||||
code
|
||||
}
|
||||
v => {
|
||||
eprintln!("raea fingerprint: no verb {v}\n{USAGE}");
|
||||
2
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn the_usage_names_every_flag() {
|
||||
let missing: Vec<_> = super::FLAGS.iter().filter(|(f, _)| *f != "--here" && !super::USAGE.contains(f)).collect();
|
||||
assert!(missing.is_empty(), "raea fingerprint takes flags its usage doesn't name: {missing:?}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
//! `raea fingerprint move [--fp CHILD] [--to PARENT] [--axis A] [--source S] [--project P]` (docs/fingerprint.feature
|
||||
//! FP14d). A note or mark teaches the fingerprint that judged the piece, and a parent never reads a child's evidence
|
||||
//! (inherit.rs), so one client's taste doesn't move the person's own. Moving labels up is the person's call: the
|
||||
//! child's own rows that match leave its ledger for a fingerprint it extends (its nearest unless --to names one). A
|
||||
//! row on an axis the parent hasn't, or on one the child says otherwise, stays: in the parent it would mean something
|
||||
//! else.
|
||||
|
||||
use crate::{Eval, flag};
|
||||
use anyhow::{Result, anyhow, bail};
|
||||
use raea_sys_fingerprint::evidence::{Ledger, Row};
|
||||
use raea_sys_fingerprint::folder::Folder;
|
||||
use raea_sys_fingerprint::inherit;
|
||||
use raea_sys_fingerprint::taxonomy::Fingerprint;
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
/// The rows `pick` takes from `child` into `parent`; returns how many moved
|
||||
pub fn rows(child: &mut Ledger, parent: &mut Ledger, pick: &dyn Fn(&Row) -> bool) -> usize {
|
||||
let mut n = 0;
|
||||
for i in 0..child.rows.len() {
|
||||
if pick(&child.rows[i]) {
|
||||
parent.push(child.rows[i].clone(), child.features(i));
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
child.retain(|r| !pick(r));
|
||||
n
|
||||
}
|
||||
|
||||
/// The axes a row may carry into `parent`: the parent's own and inherited ones, less those the child overrides
|
||||
pub fn carried(parent: &Fingerprint, eval: Eval, over: &BTreeSet<String>) -> BTreeSet<String> {
|
||||
let full = inherit::axes(parent, &inherit::parents(parent, Some(eval)));
|
||||
full.axes.iter().map(|a| a.name.clone()).filter(|a| !over.contains(a)).chain(["*".to_string()]).collect()
|
||||
}
|
||||
|
||||
/// Moves the child's matching rows up and writes both ledgers; returns the parent's name and what it did
|
||||
pub(crate) fn up(dir: &Folder, child: &Fingerprint, args: &[String], eval: Eval) -> Result<(String, String)> {
|
||||
let (axis, source, project) = (flag(args, "--axis"), flag(args, "--source"), flag(args, "--project"));
|
||||
if axis.is_none() && source.is_none() && project.is_none() {
|
||||
bail!("say which labels: --axis A, --source S (note, teach, approval, pair, damage) or --project P");
|
||||
}
|
||||
let parents = inherit::parents(child, Some(eval));
|
||||
let (pdir, parent) = match flag(args, "--to") {
|
||||
Some(n) => parents.iter().find(|(_, p)| p.name == n).ok_or_else(|| anyhow!("{} doesn't extend {n}: labels only move up", child.name))?,
|
||||
None => parents.first().ok_or_else(|| anyhow!("{} extends nothing, so its labels have nowhere to move up to", child.name))?,
|
||||
};
|
||||
let keep = carried(parent, eval, &inherit::overrides(child, &parents));
|
||||
let wanted = |r: &Row| axis.is_none_or(|a| r.axis == a) && source.is_none_or(|s| r.source == s) && project.is_none_or(|p| r.project == p);
|
||||
let (mut lc, mut lp) = (dir.ledger()?, pdir.ledger()?);
|
||||
let stay = lc.rows.iter().filter(|r| wanted(r) && !keep.contains(&r.axis)).count();
|
||||
let n = rows(&mut lc, &mut lp, &|r| wanted(r) && keep.contains(&r.axis));
|
||||
if n == 0 && stay == 0 {
|
||||
bail!("none of {}'s own labels match", child.name);
|
||||
}
|
||||
pdir.write_ledger(&lp)?;
|
||||
dir.write_ledger(&lc)?;
|
||||
let mut out = format!("{n} labels moved from {} up to {}\n", child.name, parent.name);
|
||||
if stay > 0 {
|
||||
out += &format!("{stay} stay: their axes are {}'s own, and would mean something else in {}\n", child.name, parent.name);
|
||||
}
|
||||
Ok((parent.name.clone(), out))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn row(axis: &str, source: &str) -> Row {
|
||||
Row { media: "m".into(), a: 0.0, b: 2.0, axis: axis.into(), bad: true, weight: 1.0, who: "me".into(), source: source.into(), project: "p".into(), kind: None, region: None, words: None, at: 0, pin: None, band: None }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_picked_rows_move_and_keep_their_features() {
|
||||
let w = raea_sys_fingerprint::evidence::width();
|
||||
let (mut c, mut p) = (Ledger::default(), Ledger::default());
|
||||
c.push(row("blur", "note"), &vec![1.0; w]);
|
||||
c.push(row("glow", "note"), &vec![2.0; w]);
|
||||
c.push(row("blur", "damage"), &vec![3.0; w]);
|
||||
p.push(row("hiss", "teach"), &vec![4.0; w]);
|
||||
let n = rows(&mut c, &mut p, &|r| r.source == "note" && r.axis == "blur");
|
||||
assert_eq!(n, 1);
|
||||
assert_eq!(c.rows.iter().map(|r| r.axis.as_str()).collect::<Vec<_>>(), ["glow", "blur"]);
|
||||
assert_eq!((c.features(0)[0], c.features(1)[0]), (2.0, 3.0), "the child's rows keep their own features");
|
||||
assert_eq!(p.rows.len(), 2);
|
||||
assert_eq!(p.features(1)[0], 1.0, "a moved row carries its features");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
//! Notes become evidence (docs/fingerprint.feature FP5a, FP5b). `raea fingerprint read PROJECT [--by kimi|claude]`
|
||||
//! has a fresh agent session read each pinned note on the project's videos into a kind (defect, direction, praise or
|
||||
//! both) and an axis from the fingerprint's own axes, kept in the fingerprint's readings.jsonl. Nothing trains on them
|
||||
//! yet: `raea fingerprint readings --ask N` puts N readings to the person as questions in the app (`raea show
|
||||
//! --question`, answers to the "fingerprint" inbox), `readings --tally` counts how often the person agreed, and only
|
||||
//! once the kind is right 45 times in 50 and the axis 40 (FP5b) does `raea fingerprint learn-notes` make each defect
|
||||
//! or praise an evidence row over its span (1.5 s before the pin to 0.5 s after). A direction goes to the brief and the
|
||||
//! agent, never into a head. A note's marks (FP11b) make its row a region label: the box around its marks, boxes and
|
||||
//! lassos; a span pin sets the row's time. On a render with a layer pass, a reading keeps the layers under its pin,
|
||||
//! and the reader is told them.
|
||||
|
||||
use crate::{flag, has, words};
|
||||
use raea_sys_fingerprint::folder::Folder;
|
||||
use raea_sys_fingerprint::taxonomy::Fingerprint;
|
||||
pub use raea_sys_fingerprint_use::reading::{Reading, agreement, earned};
|
||||
use raea_sys_fingerprint_use::reading::span;
|
||||
use serde_json::{Value, json};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub const INBOX: &str = "fingerprint";
|
||||
|
||||
|
||||
/// A post's video on this machine: the renders library, else the project's own folder
|
||||
fn media(project: &Path, m: &Value) -> Option<PathBuf> {
|
||||
let p = m["path"].as_str()?;
|
||||
let home = PathBuf::from(std::env::var("HOME").unwrap_or_default());
|
||||
[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();
|
||||
let mut out = Vec::new();
|
||||
for e in std::fs::read_dir(project.join(".raea/feed")).into_iter().flatten().flatten() {
|
||||
let Ok(post) = std::fs::read_to_string(e.path()).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok()).ok_or(()) else { continue };
|
||||
let Some(video) = post["media"].as_array().into_iter().flatten().find(|m| m["kind"] == "video").and_then(|m| media(project, m)) else { continue };
|
||||
for n in post["notes"].as_array().into_iter().flatten() {
|
||||
let (Some(t), Some(text)) = (n["pin"]["t"].as_f64(), n["text"].as_str()) else { continue };
|
||||
if n["author"]["kind"] != "person" {
|
||||
continue;
|
||||
}
|
||||
let to = n["pin"]["to"].as_f64().filter(|&to| to > t);
|
||||
let at = n["pin"]["x"].as_f64().zip(n["pin"]["y"].as_f64()).map(|(x, y)| [x - 0.01, y - 0.01, x + 0.01, y + 0.01].map(|v| v.clamp(0.0, 1.0)));
|
||||
let layers = at.map(|b| raea_sys_fingerprint_things::located::layers(&video, t, b)).unwrap_or_default();
|
||||
out.push(Reading { note: n["id"].as_str().unwrap_or("").into(), text: text.into(), who: n["author"]["name"].as_str().unwrap_or("me").into(), media: video.clone(), t, project: name.clone(), to, region: raea_sys_fingerprint_use::grow::marked(&n["pin"]), layers, band: raea_sys_fingerprint_use::grow::sound_band(&n["pin"]), ..Default::default() });
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The reading prompt: the axes with their words, then the notes, and the JSON to answer
|
||||
pub fn prompt(fp: &Fingerprint, notes: &[Reading]) -> String {
|
||||
let axes = fp.axes.iter().map(|a| format!("- {}: {}", a.name, a.words.join("; "))).collect::<Vec<_>>().join("\n");
|
||||
let on = |n: &Reading| if n.layers.is_empty() { String::new() } else { format!(" (pinned on {})", n.layers.join(", ")) };
|
||||
let list = notes.iter().map(|n| format!("{}: {}{}", n.note, n.text.replace('\n', " "), on(n))).collect::<Vec<_>>().join("\n");
|
||||
format!(
|
||||
"You read a person's review notes on their videos. Read each note only; open no file and change nothing.\n\
|
||||
For each note say its kind: \"defect\" (it names something wrong at that moment), \"direction\" (it asks for a creative change, \
|
||||
not a fault), \"praise\" (it says something is good) or \"both\" (a defect and a direction). Then the axis it is about, from \
|
||||
these and only these, or null when none fits:\n{axes}\n\nThe notes, one a line, id first:\n{list}\n\n\
|
||||
End with only this JSON, nothing after it: [{{\"id\": \"\", \"kind\": \"defect|direction|praise|both\", \"axis\": \"name or null\"}}]"
|
||||
)
|
||||
}
|
||||
|
||||
/// The JSON array an answer ends with
|
||||
pub fn answer(text: &str) -> Option<Vec<Value>> {
|
||||
let end = text.rfind(']')?;
|
||||
let start = text[..end].rfind("[{").or_else(|| text[..end].rfind('['))?;
|
||||
serde_json::from_str(&text[start..=end]).ok()
|
||||
}
|
||||
|
||||
/// Fold an answer into the notes: a kind it doesn't know or an axis not in the fingerprint is dropped
|
||||
pub fn fold(notes: &mut [Reading], fp: &Fingerprint, ans: &[Value], by: &str) {
|
||||
for a in ans {
|
||||
let Some(id) = a["id"].as_str() else { continue };
|
||||
let Some(n) = notes.iter_mut().find(|n| n.note == id) else { continue };
|
||||
let kind = a["kind"].as_str().unwrap_or("");
|
||||
if !matches!(kind, "defect" | "direction" | "praise" | "both") {
|
||||
continue;
|
||||
}
|
||||
n.kind = kind.into();
|
||||
n.axis = a["axis"].as_str().filter(|x| fp.axis(x).is_some()).map(str::to_string);
|
||||
n.by = by.into();
|
||||
}
|
||||
}
|
||||
|
||||
/// One fresh session's words: kimi's or claude's stream, the assistant's text joined
|
||||
fn ask(by: &str, p: &str) -> Result<String, String> {
|
||||
let mut c = std::process::Command::new(by);
|
||||
match by {
|
||||
"kimi" => c.args(["-p", p, "--output-format", "stream-json"]),
|
||||
"claude" => c.args(["-p", p, "--output-format", "stream-json", "--verbose", "--allowedTools", ""]),
|
||||
o => return Err(format!("--by {o}: kimi or claude")),
|
||||
};
|
||||
let out = c.output().map_err(|e| format!("couldn't run {by}: {e}"))?;
|
||||
let mut text = String::new();
|
||||
for line in String::from_utf8_lossy(&out.stdout).lines() {
|
||||
let Ok(v) = serde_json::from_str::<Value>(line) else { continue };
|
||||
let content = if v["role"] == "assistant" { &v["content"] } else if v["type"] == "assistant" { &v["message"]["content"] } else if v["type"] == "result" { &v["result"] } else { continue };
|
||||
match content {
|
||||
Value::String(s) => text += s,
|
||||
Value::Array(a) => a.iter().filter_map(|p| p["text"].as_str()).for_each(|s| text += s),
|
||||
_ => {}
|
||||
}
|
||||
text.push('\n');
|
||||
}
|
||||
if text.trim().is_empty() {
|
||||
return Err(format!("{by} said nothing: {}", String::from_utf8_lossy(&out.stderr).lines().last().unwrap_or("")));
|
||||
}
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
pub fn readings_of(dir: &Folder) -> Vec<Reading> {
|
||||
std::fs::read_to_string(dir.dir.join("readings.jsonl")).unwrap_or_default().lines().filter_map(|l| serde_json::from_str(l).ok()).collect()
|
||||
}
|
||||
|
||||
pub fn write_readings(dir: &Folder, r: &[Reading]) -> std::io::Result<()> {
|
||||
std::fs::write(dir.dir.join("readings.jsonl"), r.iter().filter_map(|x| serde_json::to_string(x).ok()).map(|l| l + "\n").collect::<String>())
|
||||
}
|
||||
|
||||
/// `raea fingerprint read PROJECT [--by kimi|claude]`
|
||||
pub(crate) fn read_here(args: &[String], cwd: &Path) -> i32 {
|
||||
let run = || -> Result<String, String> {
|
||||
let w = words(args)?;
|
||||
let project = w.first().map_or(cwd.to_path_buf(), |p| cwd.join(p));
|
||||
let by = flag(args, "--by").unwrap_or("kimi");
|
||||
let dir = crate::pick::chosen(args, Some(&crate::pick::piece_in(args, cwd))).0;
|
||||
let fp = dir.read(None).map_err(|e| e.to_string())?;
|
||||
let mut notes = pinned(&project);
|
||||
let mut kept = readings_of(&dir);
|
||||
notes.retain(|n| !kept.iter().any(|k| k.note == n.note && k.media == n.media));
|
||||
if notes.is_empty() {
|
||||
return Ok(format!("no new pinned notes in {}", project.display()));
|
||||
}
|
||||
for chunk in notes.chunks_mut(40) {
|
||||
let text = ask(by, &prompt(&fp, chunk))?;
|
||||
let ans = answer(&text).ok_or_else(|| format!("{by} answered no readings JSON"))?;
|
||||
fold(chunk, &fp, &ans, by);
|
||||
eprintln!("read {} notes", chunk.len());
|
||||
}
|
||||
let read = notes.iter().filter(|n| !n.kind.is_empty()).count();
|
||||
kept.extend(notes.into_iter().filter(|n| !n.kind.is_empty()));
|
||||
write_readings(&dir, &kept).map_err(|e| e.to_string())?;
|
||||
Ok(format!("{read} notes read into labels by {by}, kept in {}; none trains a head until you've checked them: raea fingerprint readings --ask 50", dir.dir.join("readings.jsonl").display()))
|
||||
};
|
||||
match run() {
|
||||
Ok(o) => {
|
||||
println!("{o}");
|
||||
0
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("raea fingerprint read: {e}");
|
||||
1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The choices a reading is checked with, and what each says about kind and axis
|
||||
pub const CHOICES: [(&str, bool, bool); 4] = [("Right", true, true), ("Right kind, wrong axis", true, false), ("Wrong kind", false, false), ("Right axis, wrong kind", false, true)];
|
||||
|
||||
/// `raea fingerprint readings [PROJECT] [--ask N] [--tally]`: the readings kept in the fingerprint that judges PROJECT
|
||||
pub(crate) fn readings_here(args: &[String], cwd: &Path) -> i32 {
|
||||
let dir = crate::pick::chosen(args, Some(&crate::pick::piece_in(args, cwd))).0;
|
||||
let mut r = readings_of(&dir);
|
||||
if let Some(n) = flag(args, "--ask").and_then(|n| n.parse::<usize>().ok()) {
|
||||
let todo: Vec<usize> = r.iter().enumerate().filter(|(_, x)| x.kind_ok.is_none()).map(|(i, _)| i).take(n).collect();
|
||||
let mut cmd = std::process::Command::new(std::env::current_exe().unwrap_or_else(|_| "raea".into()));
|
||||
cmd.args(["show", "--title", "Check how raea read your notes", "--inbox", INBOX]);
|
||||
for &i in &todo {
|
||||
let x = &r[i];
|
||||
let q = format!("[{}] \"{}\" read as {} on {}", x.note, x.text.replace('\n', " "), x.kind, x.axis.as_deref().unwrap_or("no axis"));
|
||||
cmd.args(["--question", &q, "--preview", &x.media.display().to_string()]);
|
||||
for (c, _, _) in CHOICES {
|
||||
cmd.args(["--choice", c]);
|
||||
}
|
||||
}
|
||||
if todo.is_empty() {
|
||||
println!("every reading is checked");
|
||||
return 0;
|
||||
}
|
||||
let Ok(out) = cmd.output() else { return 1 };
|
||||
let said = String::from_utf8_lossy(&out.stdout).into_owned();
|
||||
// the item raea show made, so the answers can be matched to the notes asked, in order
|
||||
let Some(item) = said.split(|c: char| c.is_whitespace() || c == '(' || c == ')' || c == ',').find(|w| w.starts_with("i-show-")) else {
|
||||
eprintln!("raea fingerprint readings: raea show didn't say its item: {said}{}", String::from_utf8_lossy(&out.stderr));
|
||||
return 1;
|
||||
};
|
||||
let mut asked: serde_json::Map<String, Value> = std::fs::read(dir.dir.join("asked.json")).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default();
|
||||
asked.insert(item.to_string(), json!(todo.iter().map(|&i| [r[i].note.clone(), r[i].media.display().to_string()]).collect::<Vec<_>>()));
|
||||
let _ = std::fs::write(dir.dir.join("asked.json"), serde_json::to_vec_pretty(&asked).unwrap_or_default());
|
||||
println!("{} readings put to you in the app ({item}); `raea fingerprint readings --tally` counts your answers", todo.len());
|
||||
return 0;
|
||||
}
|
||||
if has(args, "--tally") {
|
||||
let asked: serde_json::Map<String, Value> = std::fs::read(dir.dir.join("asked.json")).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default();
|
||||
let inbox = PathBuf::from(std::env::var("HOME").unwrap_or_default()).join(format!(".raea/inbox/{INBOX}.jsonl"));
|
||||
for line in std::fs::read_to_string(inbox).unwrap_or_default().lines() {
|
||||
let Ok(v) = serde_json::from_str::<Value>(line) else { continue };
|
||||
let Some(batch) = v["item"].as_str().and_then(|i| asked.get(i)).and_then(Value::as_array) else { continue };
|
||||
for (k, who) in batch.iter().enumerate() {
|
||||
let Some(a) = v["answers"][format!("q{}", k + 1)].as_str() else { continue };
|
||||
let Some((_, ok_kind, ok_axis)) = CHOICES.iter().find(|c| c.0 == a) else { continue };
|
||||
if let Some(x) = r.iter_mut().find(|x| who[0].as_str() == Some(x.note.as_str()) && who[1].as_str() == Some(&x.media.display().to_string())) {
|
||||
(x.kind_ok, x.axis_ok) = (Some(*ok_kind), Some(*ok_axis));
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = write_readings(&dir, &r);
|
||||
}
|
||||
let (k, a, n) = agreement(&r);
|
||||
let f = |x: Option<f64>| x.map_or("-".into(), |v| format!("{:.0}%", v * 100.0));
|
||||
println!("{} readings, {n} checked: kind right {}, axis right {} (FP5b needs 50 checked, 90% and 80%): {}", r.len(), f(k), f(a), if earned(&r) { "notes may train" } else { "notes don't train yet" });
|
||||
println!("{}", json!({"readings": r.len(), "checked": n, "kind": k, "axis": a, "earned": earned(&r)}));
|
||||
0
|
||||
}
|
||||
|
||||
/// `learn-notes`: each checked-off reading's defect or praise as an evidence row over its span, once the readings
|
||||
/// have earned it; a reading already learned is replaced, so learning again is safe
|
||||
pub(crate) fn learn(enc: &mut raea_sys_columns::Encoders, dir: &Folder, l: &mut raea_sys_fingerprint::evidence::Ledger) -> anyhow::Result<String> {
|
||||
let r = readings_of(dir);
|
||||
if !earned(&r) {
|
||||
let (k, a, n) = agreement(&r);
|
||||
anyhow::bail!("notes don't train yet: {n} readings checked, kind right {:?}, axis right {:?} (FP5b needs 50 checked, 90% and 80%: raea fingerprint readings --ask 50)", k, a);
|
||||
}
|
||||
// only these readings' rows are remade: notes another fingerprint's person moved up here (FP14d) stay
|
||||
let ids: std::collections::BTreeSet<&str> = r.iter().map(|x| x.note.as_str()).collect();
|
||||
l.retain(|x| x.source != "note" || !x.kind.as_deref().is_some_and(|k| ids.contains(k)));
|
||||
let mut made = 0;
|
||||
for x in r.iter().filter(|x| x.kind_ok != Some(false) && x.axis_ok != Some(false)) {
|
||||
let bad = match x.kind.as_str() {
|
||||
"defect" | "both" => true,
|
||||
"praise" => false,
|
||||
_ => continue,
|
||||
};
|
||||
let axis = match (&x.axis, bad) {
|
||||
(Some(a), _) => a.clone(),
|
||||
(None, false) => "*".into(),
|
||||
(None, true) => continue,
|
||||
};
|
||||
let c = enc.columns(&x.media)?;
|
||||
// a span is the label's time (a scene's, a box's on the sound: FP11c), half a second at least; a moment, 1.5 s
|
||||
// before the pin to 0.5 s after (FP11b)
|
||||
let (a, b) = x.to.map_or(((x.t - 1.5).max(0.0), (x.t + 0.5).min(c.dur)), |to| span(x.t, to, c.dur));
|
||||
if b - a < 0.5 {
|
||||
continue;
|
||||
}
|
||||
// a defect's marks, grown into the thing by EdgeTAM and followed through its shot: a row for each 2 s it stays
|
||||
// in, with its box there (grow.rs through); else the mark's own box over the label
|
||||
let seed = x.region.filter(|_| bad);
|
||||
let shot = seed.and_then(|s| raea_sys_fingerprint_use::grow::through(&x.media, x.t, c.dur, s, 2.0).ok().flatten()).filter(|w| !w.is_empty());
|
||||
for (a, b, region) in shot.map_or_else(|| vec![(a, b, seed)], |w| w.into_iter().map(|(a, b, r)| (a, b, Some(r))).collect()) {
|
||||
let (media, axis, who, project, kind, words) = (c.media.clone(), axis.clone(), x.who.clone(), x.project.clone(), Some(x.note.clone()), Some(x.text.clone()));
|
||||
// a defect's box on the sound keeps its pitch band (FP11c)
|
||||
let band = x.band.filter(|_| bad);
|
||||
let row = raea_sys_fingerprint::evidence::Row { media, a, b, axis, bad, weight: 1.0, who, source: "note".into(), project, kind, region, words, at: 0, pin: None, band };
|
||||
l.push(row, &raea_sys_fingerprint::evidence::features(&c, a, b));
|
||||
}
|
||||
made += 1;
|
||||
}
|
||||
Ok(format!("{made} notes are evidence now (defects and praise; directions stay with the brief)\n"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
|
||||
#[test]
|
||||
fn a_reading_keeps_only_kinds_and_axes_it_knows() {
|
||||
let fp = raea_sys_fingerprint::taxonomy::base("me");
|
||||
let mut n = vec![Reading { note: "n1".into(), ..Default::default() }, Reading { note: "n2".into(), ..Default::default() }, Reading { note: "n3".into(), ..Default::default() }];
|
||||
let ans = answer("I read them.\n[{\"id\": \"n1\", \"kind\": \"defect\", \"axis\": \"glitch\"}, {\"id\": \"n2\", \"kind\": \"direction\", \"axis\": \"made up\"}, {\"id\": \"n3\", \"kind\": \"rant\", \"axis\": null}]").unwrap();
|
||||
fold(&mut n, &fp, &ans, "kimi");
|
||||
assert_eq!((n[0].kind.as_str(), n[0].axis.as_deref()), ("defect", Some("glitch")));
|
||||
assert_eq!((n[1].kind.as_str(), n[1].axis.as_deref()), ("direction", None), "an axis the fingerprint hasn't is dropped");
|
||||
assert_eq!(n[2].kind, "", "a kind it doesn't know is no reading");
|
||||
n[0].layers = vec!["Floor".into()];
|
||||
assert!(prompt(&fp, &n).contains("n1: ") && prompt(&fp, &n).contains("(pinned on Floor)"), "the reader is told the layer");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_box_on_the_sound_is_a_reading_s_span_and_band_not_a_region() {
|
||||
let dir = std::env::temp_dir().join(format!("fp11c-{}", std::process::id()));
|
||||
std::fs::create_dir_all(dir.join(".raea/feed")).unwrap();
|
||||
std::fs::write(dir.join("a.mp4"), b"").unwrap();
|
||||
let note = json!({"id": "n1", "text": "that hiss", "author": {"kind": "person", "name": "me"}, "pin": {"kind": "time", "t": 2.0, "to": 4.0, "marks": [{"kind": "box", "on": "sound", "points": [[0.2, 0.9], [0.4, 0.6]]}]}});
|
||||
std::fs::write(dir.join(".raea/feed/p.json"), json!({"media": [{"kind": "video", "path": "a.mp4"}], "notes": [note]}).to_string()).unwrap();
|
||||
let r = pinned(&dir);
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
assert_eq!(r.len(), 1);
|
||||
assert_eq!((r[0].t, r[0].to, r[0].band, r[0].region), (2.0, Some(4.0), Some([0.6, 0.9]), None));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
//! Pairs from what the person already does (docs/fingerprint.feature FP6b, FP6c). `raea fingerprint pair WORSE BETTER
|
||||
//! --axis A [--at T] [--then T2]` records a pick between real options or a hand edit's before and after: the better
|
||||
//! window against the worse on that axis. `raea fingerprint versions V1 V2...` (the files in version order) makes a
|
||||
//! weak pair (weight 0.5, every axis) of each noted moment whose picture or sound changed in the next version (cosine
|
||||
//! distance 0.01 or more) and wasn't noted again within 1 s there.
|
||||
|
||||
use crate::approve::noted;
|
||||
use crate::flag;
|
||||
use anyhow::{Context, Result, anyhow, bail};
|
||||
use raea_sys_columns::Encoders;
|
||||
use raea_sys_columns::window::Modality;
|
||||
use raea_sys_fingerprint::evidence::{Ledger, Row, features, slice};
|
||||
use raea_sys_fingerprint::pairs::difference;
|
||||
use std::path::Path;
|
||||
|
||||
fn row(media: &str, a: f64, b: f64, axis: &str, weight: f32, who: &str, project: String, words: Option<String>) -> Row {
|
||||
Row { media: media.into(), a, b, axis: axis.into(), bad: true, weight, who: who.into(), source: "pair".into(), project, kind: None, region: None, words, at: 0, pin: None, band: None }
|
||||
}
|
||||
|
||||
|
||||
/// `pair`: one row, the worse window's features minus the better one's
|
||||
pub(crate) fn pair(enc: &mut Encoders, l: &mut Ledger, who: &str, args: &[String], cwd: &Path, project: impl Fn(&Path) -> String) -> Result<String> {
|
||||
let f = crate::named(args, cwd)?;
|
||||
let [worse, better] = f.as_slice() else { bail!("raea fingerprint pair WORSE BETTER --axis A [--at T] [--then T2]") };
|
||||
let axis = flag(args, "--axis").ok_or_else(|| anyhow!("--axis A: the axis the better one is better on"))?;
|
||||
let span: f64 = flag(args, "--span").map_or(Ok(2.0), str::parse).context("--span takes seconds")?;
|
||||
let t: f64 = flag(args, "--at").map_or(Ok(span / 2.0), str::parse).context("--at takes seconds")?;
|
||||
let t2: f64 = flag(args, "--then").map_or(Ok(t), str::parse).context("--then takes seconds")?;
|
||||
let (cw, cb) = (enc.columns(worse)?, enc.columns(better)?);
|
||||
let win = |dur: f64, t: f64| {
|
||||
let a = (t - span / 2.0).clamp(0.0, (dur - span).max(0.0));
|
||||
(a, (a + span).min(dur))
|
||||
};
|
||||
let ((a, b), (a2, b2)) = (win(cw.dur, t), win(cb.dur, t2));
|
||||
let d = difference(&features(&cw, a, b), &features(&cb, a2, b2));
|
||||
l.push(row(&cw.media, a, b, axis, 1.0, who, flag(args, "--project").map_or_else(|| project(worse), str::to_string), flag(args, "--words").map(str::to_string)), &d);
|
||||
Ok(format!("paired on {axis}: {} at {a:.1} s is worse than {} at {a2:.1} s\n", worse.display(), better.display()))
|
||||
}
|
||||
|
||||
fn distance(x: &[f32], y: &[f32]) -> f32 {
|
||||
let d: f32 = x.iter().zip(y).map(|(a, b)| a * b).sum();
|
||||
1.0 - d / (x.iter().map(|a| a * a).sum::<f32>().sqrt() * y.iter().map(|b| b * b).sum::<f32>().sqrt()).max(1e-9)
|
||||
}
|
||||
|
||||
/// Whether a noted moment changed in the next version and wasn't noted there again
|
||||
pub(crate) fn weak(before: &[f32], after: &[f32], t: f64, next_notes: &[f64]) -> bool {
|
||||
let changed = [Modality::Picture, Modality::Sound].iter().any(|&m| distance(&before[slice(m)], &after[slice(m)]) >= 0.01);
|
||||
changed && !next_notes.iter().any(|n| (n - t).abs() <= 1.0)
|
||||
}
|
||||
|
||||
/// `versions`: weak pairs along a chain of versions
|
||||
pub(crate) fn versions(enc: &mut Encoders, l: &mut Ledger, who: &str, args: &[String], cwd: &Path, project: impl Fn(&Path) -> String) -> Result<String> {
|
||||
let f = crate::named(args, cwd)?;
|
||||
if f.len() < 2 {
|
||||
bail!("raea fingerprint versions V1 V2... takes the versions in order");
|
||||
}
|
||||
let mut made = 0;
|
||||
for w in f.windows(2) {
|
||||
let (now, next) = (&w[0], &w[1]);
|
||||
let (cn, cx) = (enc.columns(now)?, enc.columns(next)?);
|
||||
let next_notes = noted(next);
|
||||
for t in noted(now) {
|
||||
let (a, b) = ((t - 1.5).max(0.0), (t + 0.5).min(cn.dur.min(cx.dur)));
|
||||
if b - a < 1.0 {
|
||||
continue;
|
||||
}
|
||||
let (fb, fa) = (features(&cn, a, b), features(&cx, a, b));
|
||||
if weak(&fb, &fa, t, &next_notes) {
|
||||
l.push(row(&cn.media, a, b, "*", 0.5, who, flag(args, "--project").map_or_else(|| project(now), str::to_string), None), &difference(&fb, &fa));
|
||||
made += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(format!("{made} weak pairs from {} versions: noted moments the next version changed and nobody noted again\n", f.len()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use raea_sys_fingerprint::evidence::width;
|
||||
|
||||
#[test]
|
||||
fn a_changed_moment_not_noted_again_is_a_weak_pair() {
|
||||
let a = vec![1.0; width()];
|
||||
let mut b = a.clone();
|
||||
assert!(!super::weak(&a, &b, 5.0, &[]), "unchanged: no pair");
|
||||
b.iter_mut().enumerate().for_each(|(i, x)| *x = if i % 2 == 0 { 1.0 } else { -1.0 });
|
||||
assert!(super::weak(&a, &b, 5.0, &[]));
|
||||
assert!(!super::weak(&a, &b, 5.0, &[5.6]), "noted again within 1 s: no pair");
|
||||
assert!(super::weak(&a, &b, 5.0, &[7.0]));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
//! Which fingerprint judges a piece (docs/fingerprint.feature FP14c): `raea fingerprint which PATH` says the one
|
||||
//! chosen, what it's for and why; `raea fingerprint use NAME [--in project|workspace] [PATH]` pins one by writing that
|
||||
//! level's `default`. score and teach use the chosen one unless --fp names another. No encoders are needed.
|
||||
|
||||
use crate::{flag, has, words};
|
||||
use raea_sys_fingerprint::folder::{Folder, root};
|
||||
use raea_sys_fingerprint_use::which::{Choice, default_file, levels, piece, which};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// The fingerprint a verb uses: --fp, else the one that judges `file`, else the account's default, else "me"
|
||||
pub(crate) fn chosen(args: &[String], file: Option<&Path>) -> (Folder, Option<Choice>) {
|
||||
if let Some(n) = flag(args, "--fp") {
|
||||
return (Folder::named(n), None);
|
||||
}
|
||||
if let Some(c) = file.and_then(which) {
|
||||
return (Folder { dir: c.dir.clone() }, Some(c));
|
||||
}
|
||||
let n = std::fs::read_to_string(root().join("default")).ok().map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).unwrap_or_else(|| "me".into());
|
||||
(Folder::named(&n), None)
|
||||
}
|
||||
|
||||
/// A piece in the project a verb names (its first word, else the current folder), so `read`, `readings` and
|
||||
/// `learn-notes` keep a project's notes in the fingerprint that judges it (FP14d)
|
||||
pub(crate) fn piece_in(args: &[String], cwd: &Path) -> PathBuf {
|
||||
here(cwd, args, 0).join("piece.mp4")
|
||||
}
|
||||
|
||||
fn here(cwd: &Path, args: &[String], at: usize) -> PathBuf {
|
||||
let w = words(args).unwrap_or_default();
|
||||
w.get(at).map_or_else(|| cwd.to_path_buf(), |p| cwd.join(p))
|
||||
}
|
||||
|
||||
pub(crate) fn which_here(args: &[String], cwd: &Path) -> i32 {
|
||||
let path = here(cwd, args, 0);
|
||||
let Some(c) = which(&path) else {
|
||||
eprintln!("raea fingerprint which: you have no fingerprint yet (`raea fingerprint new me` makes one)");
|
||||
return 1;
|
||||
};
|
||||
if has(args, "--json") {
|
||||
let p = piece(&path);
|
||||
println!("{}", serde_json::json!({"chosen": c, "piece": p, "looked_in": levels(&p).iter().map(|(l, d)| serde_json::json!({"level": l, "dir": d})).collect::<Vec<_>>()}));
|
||||
} else {
|
||||
println!("{} {}", c.name, c.about.as_deref().unwrap_or(""));
|
||||
println!(" why: {}", c.why);
|
||||
println!(" at: {}", c.dir.display());
|
||||
}
|
||||
0
|
||||
}
|
||||
|
||||
pub(crate) fn use_here(args: &[String], cwd: &Path) -> i32 {
|
||||
let Some(name) = words(args).ok().and_then(|w| w.first().map(|s| s.to_string())) else {
|
||||
eprintln!("raea fingerprint use: which one? raea fingerprint use NAME [--in project|workspace] [PATH]");
|
||||
return 2;
|
||||
};
|
||||
let level = flag(args, "--in").unwrap_or("account");
|
||||
if !matches!(level, "project" | "workspace" | "account") {
|
||||
eprintln!("raea fingerprint use: --in takes project or workspace, not {level}");
|
||||
return 2;
|
||||
}
|
||||
let path = here(cwd, args, 1);
|
||||
let Some(file) = default_file(&path, level) else {
|
||||
eprintln!("raea fingerprint use: {} isn't in a {level} (no .raea/{level} above it)", path.display());
|
||||
return 1;
|
||||
};
|
||||
let p = piece(&path);
|
||||
let all = levels(&p);
|
||||
let from = all.iter().position(|(l, _)| *l == level).unwrap_or(0);
|
||||
if !all[from..].iter().any(|(_, d)| Folder { dir: d.join(&name) }.exists()) {
|
||||
eprintln!("raea fingerprint use: no fingerprint {name} at the {level} or above it");
|
||||
return 1;
|
||||
}
|
||||
let wrote = std::fs::create_dir_all(file.parent().unwrap_or(cwd)).and(std::fs::write(&file, &name));
|
||||
if let Err(e) = wrote {
|
||||
eprintln!("raea fingerprint use: {}: {e}", file.display());
|
||||
return 1;
|
||||
}
|
||||
println!("{name} judges this {level}'s pieces now ({})", file.display());
|
||||
0
|
||||
}
|
||||
|
||||
/// `raea fingerprint diff A B [--json]` (FP8b): the axes two fingerprints rank the same evidence most differently on
|
||||
pub(crate) fn diff_here(args: &[String]) -> i32 {
|
||||
let w = words(args).unwrap_or_default();
|
||||
let [a, b] = w.as_slice() else {
|
||||
eprintln!("raea fingerprint diff: which two? raea fingerprint diff A B");
|
||||
return 2;
|
||||
};
|
||||
match raea_sys_fingerprint_use::diff::diff(&Folder::named(a), &Folder::named(b), 3) {
|
||||
Ok(d) if has(args, "--json") => {
|
||||
println!("{}", serde_json::to_string_pretty(&d).unwrap_or_default());
|
||||
0
|
||||
}
|
||||
Ok(d) => {
|
||||
println!("where {a} and {b} differ, most apart first (0 agree, 1 unrelated, 2 opposed):");
|
||||
for x in &d {
|
||||
println!(" {:16} {:.2} over {} windows", x.axis, x.apart, x.windows);
|
||||
for m in &x.moments {
|
||||
println!(" {} {:.1}-{:.1}s: {a} ranks it {:.0}%, {b} {:.0}%", &m.media[..m.media.len().min(12)], m.a, m.b, m.rank_a * 100.0, m.rank_b * 100.0);
|
||||
}
|
||||
}
|
||||
0
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("raea fingerprint diff: {e:#}");
|
||||
1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `raea fingerprint share NAME --in project|workspace [PATH]` (FP8a): the fingerprint's taxonomy, words and evidence
|
||||
/// copied into that level's .raea/fingerprints, to travel with its repo; never its heads (each machine retrains them)
|
||||
/// and never media (the rows hold embeddings, spans and labels)
|
||||
pub(crate) fn share_here(args: &[String], cwd: &Path) -> i32 {
|
||||
let Some(name) = words(args).ok().and_then(|w| w.first().map(|s| s.to_string())) else {
|
||||
eprintln!("raea fingerprint share: which one? raea fingerprint share NAME --in project|workspace [PATH]");
|
||||
return 2;
|
||||
};
|
||||
let level = flag(args, "--in").unwrap_or("project");
|
||||
let path = here(cwd, args, 1);
|
||||
let Some(to) = default_file(&path, level).and_then(|f| f.parent().map(|d| d.join(&name))) else {
|
||||
eprintln!("raea fingerprint share: {} isn't in a {level} (no .raea/{level} above it)", path.display());
|
||||
return 1;
|
||||
};
|
||||
let from = Folder::named(&name);
|
||||
let run = || -> anyhow::Result<usize> {
|
||||
from.read(None)?;
|
||||
let dest = Folder { dir: to.clone() };
|
||||
if dest.exists() {
|
||||
anyhow::bail!("{} has a fingerprint {name} already", to.display());
|
||||
}
|
||||
std::fs::create_dir_all(&to)?;
|
||||
for f in ["fingerprint.ts", "fingerprint.json", "words.json", "words.f16"] {
|
||||
if from.dir.join(f).is_file() {
|
||||
std::fs::copy(from.dir.join(f), to.join(f))?;
|
||||
}
|
||||
}
|
||||
let l = from.ledger()?;
|
||||
dest.write_ledger(&l)?;
|
||||
Ok(l.rows.len())
|
||||
};
|
||||
match run() {
|
||||
Ok(n) => {
|
||||
println!("shared {name} into {} with {n} evidence rows, no heads and no media; commit it with the {level}", to.display());
|
||||
0
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("raea fingerprint share: {e:#}");
|
||||
1
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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, band: 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))
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
//! `raea fingerprint profile REFS... --as NAME [--against LIST]` and `score FILE --profile NAME` (docs/fingerprint.feature
|
||||
//! FP6e): a profile's measures taken from work the person admires, kept in the fingerprint's profiles/NAME.json, and a
|
||||
//! piece critiqued against it, measure by measure, with where and which way to move.
|
||||
|
||||
use crate::{flag, listed, named};
|
||||
use anyhow::{Context, Result, anyhow, bail};
|
||||
use raea_sys_columns::{Encoders, media};
|
||||
use raea_sys_fingerprint::folder::Folder;
|
||||
use raea_sys_fingerprint_use::profile::{Measures, NAMES, Out, Profile, critique, measures, profile};
|
||||
use raea_sys_fingerprint_use::score::clock;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
const BINS: usize = 12;
|
||||
/// The windows the critique says "where" with, seconds
|
||||
const WIN: f64 = 4.0;
|
||||
|
||||
/// A piece's measures, whole and in windows
|
||||
pub(crate) fn measured(enc: &mut Encoders, file: &Path) -> Result<(Measures, Vec<((f64, f64), Measures)>)> {
|
||||
let c = enc.columns(file)?;
|
||||
let pcm = media::sound(file, 16_000).unwrap_or_default();
|
||||
let cols = ((c.dur * 10.0) as usize).max(1);
|
||||
let spec = media::spectrogram(&pcm, 16_000, cols, BINS);
|
||||
let whole = measures(&c, &spec, BINS, 0.0, c.dur);
|
||||
let n = (c.dur / WIN).ceil() as usize;
|
||||
let windows = (0..n).map(|i| {
|
||||
let (a, b) = (i as f64 * WIN, ((i + 1) as f64 * WIN).min(c.dur));
|
||||
((a, b), measures(&c, &spec, BINS, a, b))
|
||||
}).collect();
|
||||
Ok((whole, windows))
|
||||
}
|
||||
|
||||
fn path(dir: &Folder, name: &str) -> PathBuf {
|
||||
dir.dir.join("profiles").join(format!("{name}.json"))
|
||||
}
|
||||
|
||||
pub(crate) fn make(enc: &mut Encoders, dir: &Folder, args: &[String], cwd: &Path) -> Result<String> {
|
||||
let name = flag(args, "--as").ok_or_else(|| anyhow!("name it: raea fingerprint profile REFS... --as NAME"))?;
|
||||
let refs = named(args, cwd)?;
|
||||
if refs.len() < 2 {
|
||||
bail!("a profile needs two references or more (three for its leave-one-out check)");
|
||||
}
|
||||
let mut r = Vec::new();
|
||||
for f in &refs {
|
||||
r.push((f.display().to_string(), measured(enc, f)?.0));
|
||||
}
|
||||
let mut other = Vec::new();
|
||||
if let Some(list) = flag(args, "--against") {
|
||||
for f in listed(cwd, list)? {
|
||||
other.push(measured(enc, &f)?.0);
|
||||
}
|
||||
}
|
||||
let p = profile(name, r, &other);
|
||||
std::fs::create_dir_all(dir.dir.join("profiles"))?;
|
||||
std::fs::write(path(dir, name), serde_json::to_vec_pretty(&p)?)?;
|
||||
let mut out = format!("profile {name} from {} references:\n", p.refs.len());
|
||||
for (k, words) in NAMES {
|
||||
if let Some((lo, hi)) = p.ranges.get(k) {
|
||||
out += &format!(" {words:40} {lo:.2} to {hi:.2}\n");
|
||||
}
|
||||
}
|
||||
out += &match (p.inside_own, p.inside_other) {
|
||||
(Some(o), Some(x)) => format!("leave-one-out: a reference falls in the others' ranges {:.0}% of the time, unrelated work {:.0}%: {}\n", o * 100.0, x * 100.0, if p.tells == Some(true) { "it tells this taste apart" } else { "it does NOT tell this taste apart" }),
|
||||
(Some(o), None) => format!("leave-one-out: a reference falls in the others' ranges {:.0}% of the time (give --against LIST to compare with unrelated work)\n", o * 100.0),
|
||||
_ => "leave-one-out needs three references\n".into(),
|
||||
};
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The critique of a piece against a saved profile, as lines
|
||||
pub(crate) fn against(enc: &mut Encoders, dir: &Folder, name: &str, file: &Path) -> Result<(String, Vec<Out>)> {
|
||||
let p: Profile = serde_json::from_slice(&std::fs::read(path(dir, name)).with_context(|| format!("no profile {name} (raea fingerprint profile REFS... --as {name})"))?)?;
|
||||
let (whole, windows) = measured(enc, file)?;
|
||||
let out = critique(&p, &whole, &windows);
|
||||
let words = |k: &str| NAMES.iter().find(|n| n.0 == k).map_or(k.to_string(), |n| n.1.to_string());
|
||||
let mut t = format!("against the {name} profile: {}\n", if out.is_empty() { "every measure in range".to_string() } else { format!("{} out of range", out.len()) });
|
||||
for o in &out {
|
||||
t += &format!(" {} {:.2} is outside {:.2} to {:.2}: {} it{}\n", words(&o.measure), o.value, o.range.0, o.range.1, o.move_, o.at.map_or(String::new(), |(a, _)| format!(", most at {}", clock(a))));
|
||||
}
|
||||
Ok((t, out))
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
//! Encoder upgrades keep the evidence (docs/fingerprint.feature FP8c). When this machine's encoders aren't the ones a
|
||||
//! fingerprint was trained on, `raea fingerprint reembed PLACE...` re-embeds every row whose media it finds under
|
||||
//! those files and folders (matched by content hash), moves the fingerprint to the new encoders and retrains. A row
|
||||
//! whose media isn't found keeps its old pin and trains no head until it's re-embedded or labelled again; a bootstrap's
|
||||
//! damaged rows are remade by running the bootstrap again.
|
||||
|
||||
use crate::words;
|
||||
use anyhow::{Result, anyhow};
|
||||
use raea_sys_columns::{Encoders, media};
|
||||
use raea_sys_fingerprint::evidence::features;
|
||||
use raea_sys_fingerprint::folder::Folder;
|
||||
use raea_sys_fingerprint::taxonomy::Fingerprint;
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
const MEDIA: [&str; 9] = ["mp4", "mov", "m4v", "webm", "mkv", "wav", "mp3", "m4a", "flac"];
|
||||
|
||||
/// An encoder set's short name, as a row's pin
|
||||
pub(crate) fn pin_of(p: &BTreeMap<String, String>) -> String {
|
||||
p.iter().map(|(k, v)| format!("{k}:{}", &v[..v.len().min(8)])).collect::<Vec<_>>().join(",")
|
||||
}
|
||||
|
||||
/// The media files under each place, two folders deep
|
||||
fn files(places: &[PathBuf]) -> Vec<PathBuf> {
|
||||
fn walk(d: &Path, depth: usize, out: &mut Vec<PathBuf>) {
|
||||
for e in std::fs::read_dir(d).into_iter().flatten().flatten() {
|
||||
let p = e.path();
|
||||
if p.is_dir() && depth > 0 {
|
||||
walk(&p, depth - 1, out);
|
||||
} else if MEDIA.iter().any(|m| p.extension().is_some_and(|x| x.eq_ignore_ascii_case(m))) {
|
||||
out.push(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for p in places {
|
||||
if p.is_dir() { walk(p, 2, &mut out) } else { out.push(p.clone()) }
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Rows moved to `here`'s encoders where their media is found; returns the fingerprint as it is now and what happened
|
||||
pub(crate) fn reembed(enc: &mut Encoders, dir: &Folder, mut fp: Fingerprint, here: BTreeMap<String, String>, args: &[String], cwd: &Path) -> Result<(Fingerprint, String)> {
|
||||
let places: Vec<PathBuf> = words(args).map_err(|e| anyhow!(e))?.iter().map(|f| cwd.join(f)).collect();
|
||||
let mut l = dir.ledger()?;
|
||||
if fp.encoders != here {
|
||||
let old = pin_of(&fp.encoders);
|
||||
l.rows.iter_mut().filter(|r| r.pin.is_none()).for_each(|r| r.pin = Some(old.clone()));
|
||||
fp.encoders = here;
|
||||
dir.rewrite(&fp)?;
|
||||
}
|
||||
let waiting: std::collections::BTreeSet<String> = l.rows.iter().filter(|r| r.pin.is_some() && !matches!(r.source.as_str(), "damage" | "cheat")).map(|r| r.media.clone()).collect();
|
||||
let mut done = 0;
|
||||
for f in files(&places) {
|
||||
if waiting.is_empty() {
|
||||
break;
|
||||
}
|
||||
let Ok(sha) = media::sha256(&f) else { continue };
|
||||
if !waiting.contains(&sha) {
|
||||
continue;
|
||||
}
|
||||
let c = enc.columns(&f)?;
|
||||
for i in 0..l.rows.len() {
|
||||
let r = &l.rows[i];
|
||||
if r.media == sha && r.pin.is_some() && !matches!(r.source.as_str(), "damage" | "cheat") {
|
||||
let x = features(&c, r.a, r.b);
|
||||
l.set_features(i, &x);
|
||||
l.rows[i].pin = None;
|
||||
done += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
dir.write_ledger(&l)?;
|
||||
let left = l.rows.iter().filter(|r| r.pin.is_some()).count();
|
||||
let damage = l.rows.iter().filter(|r| r.pin.is_some() && matches!(r.source.as_str(), "damage" | "cheat")).count();
|
||||
let mut out = format!("re-embedded {done} rows on this machine's encoders; {left} wait on their old ones");
|
||||
if damage > 0 {
|
||||
out += &format!(" ({damage} from a bootstrap: run raea fingerprint bootstrap again to remake them)");
|
||||
}
|
||||
Ok((fp, out + "\n"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn a_pin_names_each_encoder_and_its_hash() {
|
||||
let p = std::collections::BTreeMap::from([("clap".to_string(), "0123456789abcdef".to_string()), ("siglip".to_string(), "fedcba".to_string())]);
|
||||
assert_eq!(super::pin_of(&p), "clap:01234567,siglip:fedcba");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
//! The resident service: the encoders loaded once, on 127.0.0.1 at a port the host file names
|
||||
//! (~/.raea/fingerprints/.serve.json). A request is one JSON line, {"args": [...], "cwd": "..."}; the answer is
|
||||
//! progress lines, {"say": "..."}, then {"out": "...", "code": N}. One request at a time, in order.
|
||||
|
||||
use crate::{Eval, verbs};
|
||||
use anyhow::{Context, Result};
|
||||
use raea_sys_columns::Encoders;
|
||||
use raea_sys_fingerprint::folder::root;
|
||||
use serde_json::{Value, json};
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::net::{TcpListener, TcpStream};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
/// The service leaves after this long with no request
|
||||
const IDLE: Duration = Duration::from_secs(30 * 60);
|
||||
/// How long a verb waits for a service it started to come up (the first run fetches the models)
|
||||
const UP: Duration = Duration::from_secs(900);
|
||||
|
||||
fn host() -> PathBuf {
|
||||
root().join(".serve.json")
|
||||
}
|
||||
|
||||
fn now() -> u64 {
|
||||
SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// `raea fingerprint serve`: load the encoders, listen, answer until idle or stopped
|
||||
pub fn serve(eval: Eval) -> Result<()> {
|
||||
let started = Instant::now();
|
||||
let mut enc = Encoders::load().context("loading the encoders")?;
|
||||
let listener = TcpListener::bind("127.0.0.1:0")?;
|
||||
let port = listener.local_addr()?.port();
|
||||
std::fs::create_dir_all(root())?;
|
||||
std::fs::write(host(), json!({"port": port, "pid": std::process::id()}).to_string())?;
|
||||
eprintln!("raea fingerprint serve: encoders loaded in {:.1} s, on 127.0.0.1:{port}", started.elapsed().as_secs_f64());
|
||||
let last = Arc::new(AtomicU64::new(now()));
|
||||
let seen = last.clone();
|
||||
std::thread::spawn(move || {
|
||||
loop {
|
||||
std::thread::sleep(Duration::from_secs(60));
|
||||
if now().saturating_sub(seen.load(Ordering::Relaxed)) > IDLE.as_secs() {
|
||||
let _ = std::fs::remove_file(host());
|
||||
eprintln!("raea fingerprint serve: idle for {} min, leaving", IDLE.as_secs() / 60);
|
||||
std::process::exit(0);
|
||||
}
|
||||
}
|
||||
});
|
||||
for stream in listener.incoming() {
|
||||
let Ok(mut s) = stream else { continue };
|
||||
last.store(now(), Ordering::Relaxed);
|
||||
let mut line = String::new();
|
||||
if BufReader::new(&s).read_line(&mut line).is_err() {
|
||||
continue;
|
||||
}
|
||||
let req: Value = serde_json::from_str(&line).unwrap_or_default();
|
||||
let args: Vec<String> = serde_json::from_value(req["args"].clone()).unwrap_or_default();
|
||||
let cwd = PathBuf::from(req["cwd"].as_str().unwrap_or("."));
|
||||
if args.first().is_some_and(|v| v == "stop") {
|
||||
let _ = writeln!(s, "{}", json!({"out": "raea fingerprint serve: stopped", "code": 0}));
|
||||
let _ = std::fs::remove_file(host());
|
||||
return Ok(());
|
||||
}
|
||||
let mut say = |m: String| {
|
||||
let _ = writeln!(s, "{}", json!({ "say": m }));
|
||||
};
|
||||
let (out, code) = verbs::run(&mut enc, &args, &cwd, eval, &mut say);
|
||||
let _ = writeln!(s, "{}", json!({"out": out, "code": code}));
|
||||
last.store(now(), Ordering::Relaxed);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A verb run in this process, with the encoders loaded for it
|
||||
pub(crate) fn here(args: &[String], cwd: &Path, eval: Eval) -> (String, i32) {
|
||||
match Encoders::load() {
|
||||
Ok(mut enc) => verbs::run(&mut enc, args, cwd, eval, &mut |m| eprintln!("{m}")),
|
||||
Err(e) => (format!("raea fingerprint: loading the encoders: {e:#}"), 1),
|
||||
}
|
||||
}
|
||||
|
||||
fn reach() -> Option<TcpStream> {
|
||||
let h: Value = serde_json::from_slice(&std::fs::read(host()).ok()?).ok()?;
|
||||
TcpStream::connect(("127.0.0.1", h["port"].as_u64()? as u16)).ok()
|
||||
}
|
||||
|
||||
/// The service started in the background, its output in ~/.raea/fingerprints/.serve.log; its stream once it's up
|
||||
fn start() -> Result<TcpStream, String> {
|
||||
let _ = std::fs::remove_file(host());
|
||||
std::fs::create_dir_all(root()).map_err(|e| e.to_string())?;
|
||||
let log = root().join(".serve.log");
|
||||
let file = std::fs::File::create(&log).map_err(|e| e.to_string())?;
|
||||
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
|
||||
let mut cmd = std::process::Command::new(exe);
|
||||
cmd.args(["fingerprint", "serve"]).stdin(std::process::Stdio::null()).stdout(file.try_clone().map_err(|e| e.to_string())?).stderr(file);
|
||||
#[cfg(unix)]
|
||||
std::os::unix::process::CommandExt::process_group(&mut cmd, 0);
|
||||
let mut child = cmd.spawn().map_err(|e| format!("starting the service: {e}"))?;
|
||||
eprintln!("raea fingerprint: starting the service (loading the encoders once; its log is {})", log.display());
|
||||
let t = Instant::now();
|
||||
while t.elapsed() < UP {
|
||||
if let Some(s) = reach() {
|
||||
return Ok(s);
|
||||
}
|
||||
if let Ok(Some(status)) = child.try_wait() {
|
||||
let tail = std::fs::read_to_string(&log).unwrap_or_default();
|
||||
return Err(format!("the service stopped ({status}):\n{}", tail.lines().rev().take(12).collect::<Vec<_>>().into_iter().rev().collect::<Vec<_>>().join("\n")));
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
}
|
||||
let _ = child.kill();
|
||||
Err(format!("the service didn't come up in {} s (see {})", UP.as_secs(), log.display()))
|
||||
}
|
||||
|
||||
/// A verb sent to the service, started if it isn't running; its progress printed as it comes
|
||||
pub(crate) fn call(args: &[String], cwd: &Path) -> (String, i32) {
|
||||
let stream = match reach() {
|
||||
Some(s) => Ok(s),
|
||||
None if args.first().is_some_and(|v| v == "stop") => return ("raea fingerprint: no service running".into(), 0),
|
||||
None => start(),
|
||||
};
|
||||
let mut s = match stream {
|
||||
Ok(s) => s,
|
||||
Err(e) => return (format!("raea fingerprint: {e}"), 1),
|
||||
};
|
||||
if writeln!(s, "{}", json!({"args": args, "cwd": cwd})).is_err() {
|
||||
return ("raea fingerprint: the service closed the connection".into(), 1);
|
||||
}
|
||||
for line in BufReader::new(s).lines() {
|
||||
let Ok(line) = line else { break };
|
||||
let v: Value = serde_json::from_str(&line).unwrap_or_default();
|
||||
if let Some(m) = v["say"].as_str() {
|
||||
eprintln!("{m}");
|
||||
} else if v.get("code").is_some() {
|
||||
return (v["out"].as_str().unwrap_or("").to_string(), v["code"].as_i64().unwrap_or(1) as i32);
|
||||
}
|
||||
}
|
||||
("raea fingerprint: the service ended without an answer (see ~/.raea/fingerprints/.serve.log)".into(), 1)
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
//! `raea fingerprint things FILE [--project P] [--json]` (docs/fingerprint.feature FP13a, FP13c): a piece's shots,
|
||||
//! their things (a render's layers, and every mark a person drew on a note of it in P's feed, P the folder it runs in
|
||||
//! by default) and the camera's path, with what floats, passes through, lurches or is empty
|
||||
//! (raea-sys-fingerprint-things). `--json` prints it all for `raea check --things`.
|
||||
|
||||
use crate::{flag, has};
|
||||
use anyhow::Result;
|
||||
use raea_sys_columns::Encoders;
|
||||
use raea_sys_fingerprint_things::things::{Mark, things};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub(crate) fn run(enc: &mut Encoders, args: &[String], cwd: &Path) -> Result<(String, i32)> {
|
||||
let file = cwd.join(args.first().filter(|a| !a.starts_with("--")).ok_or_else(|| anyhow::anyhow!("things FILE"))?);
|
||||
let project = flag(args, "--project").map_or_else(|| cwd.to_path_buf(), |p| cwd.join(p));
|
||||
let me = file.canonicalize().ok();
|
||||
let marks: Vec<Mark> = crate::notes::pinned(&project)
|
||||
.into_iter()
|
||||
.filter(|r| r.media.canonicalize().ok() == me)
|
||||
.filter_map(|r| Some(Mark { name: r.text.chars().take(40).collect(), t: r.t, a: (r.t - 1.0).max(0.0), b: r.to.unwrap_or(r.t + 1.0), region: r.region? }))
|
||||
.collect();
|
||||
let t = things(enc, &file, &marks)?;
|
||||
if has(args, "--json") {
|
||||
return Ok((serde_json::to_string_pretty(&t)?, 0));
|
||||
}
|
||||
let n: usize = t.shots.iter().map(|s| s.things.len()).sum();
|
||||
let mut out = format!("{}: {} shots, {n} things seen ({} marked), {} findings\n", PathBuf::from(&t.file).display(), t.shots.len(), marks.len(), t.issues.len());
|
||||
for i in &t.issues {
|
||||
out += &format!(" {:>6.1} s {} {}\n", i.at, i.rule, i.says);
|
||||
}
|
||||
Ok((out, 0))
|
||||
}
|
||||
@@ -0,0 +1,398 @@
|
||||
//! The verbs, run with the encoders loaded: new, bootstrap, teach and score; and report, which needs no encoders.
|
||||
|
||||
use crate::{Eval, at, flag, has, listed, named, words};
|
||||
use anyhow::{Context, Result, anyhow, bail};
|
||||
use raea_sys_columns::{Encoders, FPS, media};
|
||||
use raea_sys_fingerprint::evidence::{Ledger, Row, features};
|
||||
use raea_sys_fingerprint::folder::{Folder, root};
|
||||
use raea_sys_fingerprint::inherit;
|
||||
use raea_sys_fingerprint_use::score::{Scored, clock, score, summary, timeline};
|
||||
use raea_sys_fingerprint_use::sheet::{Tick, sheet};
|
||||
use raea_sys_fingerprint::taxonomy::{Applies, Fingerprint, base, words_of};
|
||||
use raea_sys_fingerprint::words::Words;
|
||||
use crate::bootstrap;
|
||||
use raea_sys_fingerprint::{report_text, retrain};
|
||||
use serde_json::json;
|
||||
use std::path::Path;
|
||||
|
||||
/// The fingerprint a verb is about: --fp, else the one `new` made first, else "me"
|
||||
|
||||
/// A verb's answer and exit code
|
||||
pub(crate) fn run(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval, say: &mut dyn FnMut(String)) -> (String, i32) {
|
||||
let rest = &args[1..];
|
||||
let ran = match args[0].as_str() {
|
||||
"new" => new(enc, rest),
|
||||
"bootstrap" => boot(enc, rest, cwd, eval, say),
|
||||
"teach" => teach(enc, rest, cwd, eval),
|
||||
"approve" => approved(enc, rest, cwd, eval),
|
||||
"reembed" => reembedded(enc, rest, cwd, eval),
|
||||
"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),
|
||||
"things" => crate::things::run(enc, rest, cwd),
|
||||
"profile" => {
|
||||
let dir = crate::pick::chosen(rest, None).0;
|
||||
crate::profiles::make(enc, &dir, rest, cwd).map(|o| (o, 0))
|
||||
}
|
||||
"score" => scored(enc, rest, cwd, eval),
|
||||
v => Err(anyhow!("no verb {v}")),
|
||||
};
|
||||
ran.unwrap_or_else(|e| (format!("raea fingerprint {}: {e:#}", args[0]), 1))
|
||||
}
|
||||
|
||||
/// A new fingerprint as `new` makes it: raea's base axes, or the axes of the one it --extends, with --who and --about,
|
||||
/// and the kinds of piece and project tags it judges (--kinds, --tags, each comma-separated)
|
||||
pub(crate) fn shaped(short: &str, args: &[String], parent: Option<Fingerprint>) -> Fingerprint {
|
||||
let mut fp = base(short);
|
||||
if let Some(p) = parent {
|
||||
fp.axes = p.axes;
|
||||
fp.extends = Some(p.name);
|
||||
}
|
||||
fp.who = flag(args, "--who").map(str::to_string).or_else(|| std::env::var("USER").ok());
|
||||
fp.about = flag(args, "--about").map(str::trim).filter(|a| !a.is_empty()).map(str::to_string);
|
||||
let (kinds, tags) = (flag(args, "--kinds").map(words_of).unwrap_or_default(), flag(args, "--tags").map(words_of).unwrap_or_default());
|
||||
if !kinds.is_empty() || !tags.is_empty() {
|
||||
fp.applies = Some(Applies { kinds, tags });
|
||||
}
|
||||
fp
|
||||
}
|
||||
|
||||
fn new(enc: &mut Encoders, args: &[String]) -> Result<(String, i32)> {
|
||||
let n = *words(args).map_err(|e| anyhow!(e))?.first().ok_or_else(|| anyhow!("name it: raea fingerprint new NAME"))?;
|
||||
let dir = Folder::named(n);
|
||||
let short = dir.dir.file_name().map(|s| s.to_string_lossy().into_owned()).unwrap_or_else(|| n.into());
|
||||
let parent = match flag(args, "--extends") {
|
||||
Some(p) => Some(Folder::named(p).read(None).with_context(|| format!("--extends {p}"))?),
|
||||
None => None,
|
||||
};
|
||||
let from = parent.as_ref().map(|p| format!("{}'s axes", p.name)).unwrap_or_else(|| "raea's base taxonomy".into());
|
||||
let mut fp = shaped(&short, args, parent);
|
||||
fp.encoders = enc.pins();
|
||||
dir.create(&fp)?;
|
||||
let w = Words::build(enc, &fp)?;
|
||||
dir.write_words(&w)?;
|
||||
retrain(&dir, &fp, &w, &Ledger::default(), None)?;
|
||||
if !root().join("default").exists() && dir.dir.parent() == Some(root().as_path()) {
|
||||
std::fs::write(root().join("default"), &short)?;
|
||||
}
|
||||
Ok((
|
||||
format!(
|
||||
"made {}: {} axes from {from}, {} scoring from their words today (advice until they earn a gate)\n edit {} to add, remove or reword axes\n next: raea fingerprint bootstrap FILE... with your own finished work trains the mechanical axes",
|
||||
dir.dir.display(),
|
||||
fp.axes.len(),
|
||||
w.axes.len(),
|
||||
dir.ts().display()
|
||||
),
|
||||
0,
|
||||
))
|
||||
}
|
||||
|
||||
/// 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
|
||||
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();
|
||||
if raw.encoders.is_empty() {
|
||||
raw.encoders = here;
|
||||
dir.rewrite(&raw)?;
|
||||
} else if here.iter().filter(|(k, v)| raw.encoders.get(*k) == Some(*v)).count() == raw.encoders.len() && raw.encoders != here {
|
||||
// an encoder added since (EmbeddingGemma 2, FP1b) doesn't change the ones it was trained on
|
||||
raw.encoders = here;
|
||||
dir.rewrite(&raw)?;
|
||||
} else if raw.encoders != here {
|
||||
bail!(
|
||||
"{} was trained on other encoders ({:?}) than this machine has ({:?}); its heads refuse these columns. `raea fingerprint reembed FOLDER...` moves its evidence to these, re-embedding the rows whose media it finds",
|
||||
dir.ts().display(),
|
||||
raw.encoders,
|
||||
here
|
||||
);
|
||||
}
|
||||
// a fingerprint that extends another judges with its parents' axes too (FP14b)
|
||||
let fp = inherit::axes(&raw, &inherit::parents(&raw, Some(eval)));
|
||||
let w = match dir.words().filter(|w| !w.stale(&fp)) {
|
||||
Some(w) => w,
|
||||
None => {
|
||||
let w = Words::build(enc, &fp)?;
|
||||
dir.write_words(&w)?;
|
||||
w
|
||||
}
|
||||
};
|
||||
// a shared fingerprint arrives with evidence and no heads: this machine trains its own (FP8a)
|
||||
if !dir.dir.join("heads.safetensors").is_file() {
|
||||
let l = dir.ledger()?;
|
||||
if !l.rows.is_empty() {
|
||||
retrain(&dir, &fp, &w, &l, None)?;
|
||||
}
|
||||
}
|
||||
Ok((dir, fp, w))
|
||||
}
|
||||
|
||||
fn boot(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval, say: &mut dyn FnMut(String)) -> Result<(String, i32)> {
|
||||
let (dir, fp, w) = open(enc, args, eval, None)?;
|
||||
let mut files = named(args, cwd)?;
|
||||
if let Some(list) = flag(args, "--from") {
|
||||
files.extend(listed(cwd, list)?);
|
||||
}
|
||||
if files.is_empty() {
|
||||
bail!("give it real finished work: raea fingerprint bootstrap FILE... or --from LIST (no placeholder footage)");
|
||||
}
|
||||
let per: usize = flag(args, "--per").map_or(Ok(10), str::parse).context("--per takes a count")?;
|
||||
let mut l = dir.ledger()?;
|
||||
let who = fp.who.clone().unwrap_or_else(|| "me".into());
|
||||
let made = bootstrap::rows(enc, &who, &files, per, &mut l, say)?;
|
||||
dir.write_ledger(&l)?;
|
||||
say(format!("{} windows from {} sources; measuring held out by source", made.windows, made.sources));
|
||||
let curves = bootstrap::curves(&fp, &l);
|
||||
let ws = bootstrap::word_scores(&l, &w);
|
||||
let patches = raea_sys_fingerprint_things::located::bootstrap(enc, &dir.dir, &files, per, say)?;
|
||||
let b = json!({"made": made, "per": per, "sources": files, "curves": curves, "words": ws, "patches": patches});
|
||||
retrain(&dir, &fp, &w, &l, Some(b))?;
|
||||
Ok((report_text(&dir.report().unwrap_or_default()), 0))
|
||||
}
|
||||
|
||||
/// The project a file belongs to: the folder holding .raea/project above it, else the folder it's in
|
||||
fn project_of(file: &Path) -> String {
|
||||
let mut d = file.parent();
|
||||
while let Some(p) = d {
|
||||
if p.join(".raea/project").exists() {
|
||||
return p.file_name().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
}
|
||||
d = p.parent();
|
||||
}
|
||||
file.parent().and_then(|p| p.file_name()).map(|s| s.to_string_lossy().into_owned()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// `approve`: approved work as clean rows on every axis (approve.rs, FP6a), then the heads retrained
|
||||
fn approved(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval) -> Result<(String, i32)> {
|
||||
let first = words(args).map_err(|e| anyhow!(e))?.first().map(|f| at(cwd, f));
|
||||
let (dir, fp, w) = open(enc, args, eval, first.as_deref())?;
|
||||
let (mut out, _) = crate::approve::approve(enc, &dir, &fp, args, cwd, project_of)?;
|
||||
let tr = retrain(&dir, &fp, &w, &dir.ledger()?, None)?;
|
||||
out += &format!("{} axes gating\n", tr.heads.iter().filter(|h| h.state == "gating").count());
|
||||
Ok((out, 0))
|
||||
}
|
||||
|
||||
/// `reembed`: the evidence moved to this machine's encoders (reembed.rs, FP8c), the words remade and the heads retrained
|
||||
fn reembedded(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval) -> Result<(String, i32)> {
|
||||
let dir = crate::pick::chosen(args, None).0;
|
||||
let raw = dir.read(Some(eval))?;
|
||||
let (fp, out) = crate::reembed::reembed(enc, &dir, raw, enc.pins(), args, cwd)?;
|
||||
let fp = inherit::axes(&fp, &inherit::parents(&fp, Some(eval)));
|
||||
let w = Words::build(enc, &fp)?;
|
||||
dir.write_words(&w)?;
|
||||
retrain(&dir, &fp, &w, &dir.ledger()?, None)?;
|
||||
Ok((out, 0))
|
||||
}
|
||||
|
||||
/// `pair` and `versions` (pairing.rs, FP6b, FP6c), then the heads retrained
|
||||
fn paired(enc: &mut Encoders, verb: &str, args: &[String], cwd: &Path, eval: Eval) -> Result<(String, i32)> {
|
||||
let first = words(args).map_err(|e| anyhow!(e))?.first().map(|f| at(cwd, f));
|
||||
let (dir, fp, w) = open(enc, args, eval, first.as_deref())?;
|
||||
let who = fp.who.clone().unwrap_or_else(|| "me".into());
|
||||
let mut l = dir.ledger()?;
|
||||
let out = if verb == "pair" { crate::pairing::pair(enc, &mut l, &who, args, cwd, project_of)? } else { crate::pairing::versions(enc, &mut l, &who, args, cwd, project_of)? };
|
||||
dir.write_ledger(&l)?;
|
||||
retrain(&dir, &fp, &w, &l, None)?;
|
||||
Ok((out, 0))
|
||||
}
|
||||
|
||||
/// `learn-notes [PROJECT]` (notes.rs, FP5a): checked readings as evidence in the fingerprint that judges the project
|
||||
/// (FP14d), then its heads retrained
|
||||
fn learned(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval) -> Result<(String, i32)> {
|
||||
let (dir, fp, w) = open(enc, args, eval, Some(&crate::pick::piece_in(args, cwd)))?;
|
||||
let mut l = dir.ledger()?;
|
||||
let out = crate::notes::learn(enc, &dir, &mut l)?;
|
||||
dir.write_ledger(&l)?;
|
||||
retrain(&dir, &fp, &w, &l, None)?;
|
||||
Ok((out, 0))
|
||||
}
|
||||
|
||||
/// `move` (moving.rs, FP14d): a child's own labels up into a fingerprint it extends, then both retrained
|
||||
fn moved(enc: &mut Encoders, args: &[String], eval: Eval) -> Result<(String, i32)> {
|
||||
let (dir, fp, w) = open(enc, args, eval, None)?;
|
||||
let (to, out) = crate::moving::up(&dir, &dir.read(Some(eval))?, args, eval)?;
|
||||
retrain(&dir, &fp, &w, &dir.ledger()?, None)?;
|
||||
let (pd, pfp, pw) = open(enc, &["--fp".into(), to], eval, None)?;
|
||||
retrain(&pd, &pfp, &pw, &pd.ledger()?, None)?;
|
||||
Ok((out, 0))
|
||||
}
|
||||
|
||||
fn teach(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval) -> Result<(String, i32)> {
|
||||
let file = at(cwd, words(args).map_err(|e| anyhow!(e))?.first().ok_or_else(|| anyhow!("which file?"))?);
|
||||
let (dir, fp, w) = open(enc, args, eval, Some(&file))?;
|
||||
let axis = flag(args, "--axis").ok_or_else(|| anyhow!("--axis A (or \"*\" for every axis)"))?;
|
||||
if axis != "*" && fp.axis(axis).is_none() {
|
||||
bail!("no axis {axis:?} in {}: its axes are {}", dir.ts().display(), fp.axes.iter().map(|a| a.name.as_str()).collect::<Vec<_>>().join(", "));
|
||||
}
|
||||
let t: f64 = flag(args, "--at").ok_or_else(|| anyhow!("--at SECONDS"))?.parse().context("--at takes seconds")?;
|
||||
let span: f64 = flag(args, "--span").map_or(Ok(2.0), str::parse).context("--span takes seconds")?;
|
||||
let region = flag(args, "--box").map(|b| -> Result<[f32; 4]> {
|
||||
let v: Vec<f32> = b.split(',').map(str::parse).collect::<Result<_, _>>().context("--box takes x0,y0,x1,y1 in 0-1")?;
|
||||
v.try_into().map_err(|_| anyhow!("--box takes four numbers"))
|
||||
});
|
||||
let c = enc.columns(&file)?;
|
||||
let a = (t - span / 2.0).clamp(0.0, (c.dur - span).max(0.0));
|
||||
let b = (a + span).min(c.dur);
|
||||
let bad = !has(args, "--good");
|
||||
let row = Row {
|
||||
media: c.media.clone(),
|
||||
a,
|
||||
b,
|
||||
axis: axis.into(),
|
||||
bad,
|
||||
weight: 1.0,
|
||||
who: fp.who.clone().unwrap_or_else(|| "me".into()),
|
||||
source: "teach".into(),
|
||||
project: flag(args, "--project").map_or_else(|| project_of(&file), str::to_string),
|
||||
kind: None,
|
||||
region: region.transpose()?,
|
||||
words: flag(args, "--words").map(str::to_string),
|
||||
at: 0,
|
||||
pin: None,
|
||||
band: None,
|
||||
};
|
||||
let mut l = dir.ledger()?;
|
||||
l.push(row, &features(&c, a, b));
|
||||
dir.write_ledger(&l)?;
|
||||
let tr = retrain(&dir, &fp, &w, &l, None)?;
|
||||
let h = tr.heads.iter().find(|h| h.axis == axis);
|
||||
let (p, n) = l.for_axis(axis).iter().fold((0, 0), |(p, n), &i| if l.rows[i].bad { (p + 1, n) } else { (p, n + 1) });
|
||||
Ok((
|
||||
format!(
|
||||
"taught {axis}: {} at {} in {}\n {axis} has {p} defect and {n} clean labels; its head: {}",
|
||||
if bad { "the defect" } else { "clean" },
|
||||
clock(t),
|
||||
file.display(),
|
||||
h.map_or("every axis's clean labels grew".to_string(), |h| format!("{} ({})", h.state, h.why))
|
||||
),
|
||||
0,
|
||||
))
|
||||
}
|
||||
|
||||
/// raea check's findings on the file, in seconds: (rule, from, to, what)
|
||||
fn checks(file: &Path) -> Vec<(String, f64, f64, String)> {
|
||||
let Ok(found) = raea_app_check::floor(&[file.display().to_string()], &[], &[]) else { return Vec::new() };
|
||||
found.into_iter().map(|f| {
|
||||
let (a, b) = f.frames.map_or((0.0, 0.0), |[a, b]| (a as f64 / 30.0, b as f64 / 30.0));
|
||||
(f.check, a, b, f.says)
|
||||
}).collect()
|
||||
}
|
||||
|
||||
/// A check wins over a head (FP4c): a moment on an axis a check measures is no gate unless the check found it too
|
||||
fn arbitrate(s: &mut Scored, fp: &Fingerprint, found: &[(String, f64, f64, String)]) {
|
||||
for m in &mut s.moments {
|
||||
let Some(rule) = fp.axis(&m.axis).and_then(|a| a.check.as_deref()) else { continue };
|
||||
let agrees = found.iter().any(|(r, a, b, _)| r == rule && *a <= m.b + 1.0 && *b >= m.a - 1.0);
|
||||
if !agrees {
|
||||
m.gating = false;
|
||||
m.state = format!("{}; the {rule} check found none", m.state);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn scored(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval) -> Result<(String, i32)> {
|
||||
let file = at(cwd, words(args).map_err(|e| anyhow!(e))?.first().ok_or_else(|| anyhow!("which file?"))?);
|
||||
let (dir, fp, w) = open(enc, args, eval, Some(&file))?;
|
||||
let why = crate::pick::chosen(args, Some(&file)).1.map_or_else(|| "named with --fp, or the account's default".to_string(), |c| c.why);
|
||||
let c = enc.columns(&file)?;
|
||||
let trained = dir.trained()?.map(|(t, _)| t);
|
||||
let mut s = score(&fp, Some(&w), trained.as_ref(), &c, &file.display().to_string());
|
||||
let found = checks(&file);
|
||||
arbitrate(&mut s, &fp, &found);
|
||||
raea_sys_fingerprint_things::located::locate(enc, &file, &raea_sys_fingerprint_use::patch::load(&dir.dir), &mut s)?;
|
||||
// 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<_>>(), "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);
|
||||
t += &format!("checks: {}\n", if found.is_empty() { "no findings".to_string() } else { format!("{} findings", found.len()) });
|
||||
for (r, a, _, says) in &found {
|
||||
t += &format!(" {} {r}: {says}\n", clock(*a));
|
||||
}
|
||||
t
|
||||
};
|
||||
if has(args, "--timeline") {
|
||||
out += &timeline(&s);
|
||||
}
|
||||
if let Some(p) = flag(args, "--profile") {
|
||||
out += &crate::profiles::against(enc, &dir, p, &file)?.0;
|
||||
}
|
||||
if let Some(png) = flag(args, "--sheet") {
|
||||
let png = at(cwd, png);
|
||||
let frames: Vec<media::Rgb> = (0..12).filter_map(|i| media::frames(&file, FPS, c.dur * (i as f64 + 0.5) / 12.0, 0.25).ok()?.into_iter().next()).collect();
|
||||
let pcm = media::sound(&file, 16_000)?;
|
||||
let ticks: Vec<Tick> = found.iter().map(|(r, a, b, _)| Tick { a: *a, b: *b, what: r.clone() }).collect();
|
||||
sheet(&s, &frames, &pcm, &ticks, &|axis| fp.axis(axis).map(|a| a.modality), &png)?;
|
||||
out += &format!("sheet: {}\n", png.display());
|
||||
}
|
||||
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
|
||||
pub(crate) fn report_here(args: &[String]) -> i32 {
|
||||
let dir = crate::pick::chosen(args, None).0;
|
||||
match dir.report() {
|
||||
Some(r) if has(args, "--json") => {
|
||||
println!("{}", serde_json::to_string_pretty(&r).unwrap_or_default());
|
||||
0
|
||||
}
|
||||
Some(r) => {
|
||||
println!("{}", report_text(&r).trim_end());
|
||||
0
|
||||
}
|
||||
None => {
|
||||
eprintln!("raea fingerprint report: no report at {} (`raea fingerprint new NAME` makes one)", dir.dir.display());
|
||||
1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::shaped;
|
||||
use raea_sys_fingerprint::taxonomy::{Applies, base};
|
||||
|
||||
fn args(xs: &[&str]) -> Vec<String> {
|
||||
xs.iter().map(|x| x.to_string()).collect()
|
||||
}
|
||||
|
||||
/// FP14a: a new fingerprint says what it's for, and one that extends another starts from its axes
|
||||
#[test]
|
||||
fn a_new_fingerprint_says_what_its_for_and_what_it_builds_on() {
|
||||
let own = shaped("me", &args(&["me", "--who", "w"]), None);
|
||||
assert_eq!((own.about.as_deref(), own.extends.as_deref(), own.who.as_deref()), (None, None, Some("w")));
|
||||
assert_eq!(own.axes, base("me").axes);
|
||||
|
||||
let mut parent = base("me");
|
||||
parent.axes.truncate(2);
|
||||
parent.axes[0].words = vec!["a soft picture".into()];
|
||||
let ads = shaped("ads", &args(&["ads", "--about", " Short ads for one brand ", "--extends", "me"]), Some(parent.clone()));
|
||||
assert_eq!(ads.name, "ads");
|
||||
assert_eq!(ads.about.as_deref(), Some("Short ads for one brand"));
|
||||
assert_eq!(ads.extends.as_deref(), Some("me"));
|
||||
assert_eq!(ads.axes, parent.axes);
|
||||
assert_eq!(shaped("x", &args(&["x", "--about", " "]), None).about, None);
|
||||
assert_eq!(own.applies, None);
|
||||
let judged = shaped("ads", &args(&["ads", "--kinds", "ad, Playable", "--tags", "brand,"]), None);
|
||||
assert_eq!(judged.applies, Some(Applies { kinds: vec!["ad".into(), "playable".into()], tags: vec!["brand".into()] }));
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,17 @@ pub use read::{Facts, Prop};
|
||||
/// The nearest folder at or above a path that holds a marker (.raea/workspace, .raea/project), as the record finds it.
|
||||
pub use raea_core_facts::record::up;
|
||||
|
||||
/// The workspace's shared folder of one kind (docs/layout.feature: shared/compositions, components, controllers, assets,
|
||||
/// artifacts), which every project can call on as @shared/<kind>/. A workspace from before shared/ keeps that kind at
|
||||
/// its root (controllers/, artifacts/) until `raea workspace tidy` moves it, and it's read there meanwhile.
|
||||
pub fn shared_dir(ws: &Path, kind: &str) -> PathBuf {
|
||||
let old = ws.join(kind);
|
||||
if !ws.join("shared").is_dir() && old.is_dir() {
|
||||
return old;
|
||||
}
|
||||
ws.join("shared").join(kind)
|
||||
}
|
||||
|
||||
/// A name as a folder: lowercase, dashes. A controller's id from its title is this (core/brief fills it the same way).
|
||||
pub fn slug(s: &str) -> String {
|
||||
let mut out = String::new();
|
||||
@@ -131,7 +142,14 @@ pub fn stem(file: &str) -> String {
|
||||
/// The file a relative or absolute import names: as written, or with .tsx, .ts, .jsx or .js (in place of an extension
|
||||
/// or after the name), or its folder's index.
|
||||
pub(crate) fn resolve(from: &Path, spec: &str) -> Option<PathBuf> {
|
||||
let base = if spec.starts_with('/') { PathBuf::from(spec) } else { from.parent()?.join(spec) };
|
||||
// @shared/<kind>/<name>: the workspace's shared/ (docs/layout.feature LY2), as the engine's loader resolves it
|
||||
let base = if let Some(rest) = spec.strip_prefix(SHARED) {
|
||||
up(from.parent()?, ".raea/workspace")?.join("shared").join(rest)
|
||||
} else if spec.starts_with('/') {
|
||||
PathBuf::from(spec)
|
||||
} else {
|
||||
from.parent()?.join(spec)
|
||||
};
|
||||
let mut tries = vec![base.clone()];
|
||||
for ext in ["tsx", "ts", "jsx", "js"] {
|
||||
tries.push(base.with_extension(ext));
|
||||
@@ -142,11 +160,14 @@ pub(crate) fn resolve(from: &Path, spec: &str) -> Option<PathBuf> {
|
||||
Some(std::fs::canonicalize(&found).unwrap_or(found))
|
||||
}
|
||||
|
||||
/// An import of a file (not a package): relative or absolute.
|
||||
/// An import of a file (not a package): relative, absolute, or the workspace's shared/ (@shared/...).
|
||||
pub(crate) fn is_path(spec: &str) -> bool {
|
||||
spec.starts_with("./") || spec.starts_with("../") || spec.starts_with('/')
|
||||
spec.starts_with("./") || spec.starts_with("../") || spec.starts_with('/') || spec.starts_with(SHARED)
|
||||
}
|
||||
|
||||
/// The prefix a project imports its workspace's shared files by: @shared/components/desk (docs/layout.feature LY2).
|
||||
pub const SHARED: &str = "@shared/";
|
||||
|
||||
/// A version's newest render manifest: NAME[-vN][.play].render.json beside it, or the folder's render.json for edit.tsx.
|
||||
fn manifest(path: &Path) -> Option<Value> {
|
||||
let dir = path.parent()?;
|
||||
|
||||
@@ -73,6 +73,8 @@ pub(super) fn lint(reg: &Registry, files: &[File], used_by: &BTreeMap<String, BT
|
||||
}
|
||||
let comp_files: BTreeSet<&str> = reg.compositions.iter().map(|c| c.file.as_str()).collect();
|
||||
let controller_files: BTreeSet<&str> = reg.controllers.iter().map(|c| c.file.as_str()).collect();
|
||||
// the workspace's shared/, which a project reaches as @shared/
|
||||
let shared = super::up(®.dir, ".raea/workspace").map(|w| w.join("shared")).map(|s| s.canonicalize().unwrap_or(s));
|
||||
|
||||
for f in files {
|
||||
if let Some(why) = &f.facts.broken {
|
||||
@@ -90,18 +92,47 @@ pub(super) fn lint(reg: &Registry, files: &[File], used_by: &BTreeMap<String, BT
|
||||
for (spec, line) in f.facts.imports.iter().filter(|(s, _)| is_path(s)) {
|
||||
match resolve(&f.path, spec) {
|
||||
None => out.push(warn(&f.rel, *line, "unresolved", format!("imports {spec}, which isn't there"), "fix the path, or add the file")),
|
||||
Some(to) if !to.starts_with(®.dir) => out.push(warn(
|
||||
&f.rel,
|
||||
*line,
|
||||
"outside",
|
||||
format!("imports {} from outside the project", tilde(&to)),
|
||||
"copy it into the project (raea part add, for raea's parts), so the project renders on its own",
|
||||
)),
|
||||
// the workspace's shared/ by its name is how a project reaches it (docs/layout.feature LY2)
|
||||
Some(_) if spec.starts_with(super::SHARED) => {}
|
||||
Some(to) if !to.starts_with(®.dir) => {
|
||||
let in_shared = shared.as_ref().and_then(|s| to.strip_prefix(s).ok());
|
||||
out.push(warn(
|
||||
&f.rel,
|
||||
*line,
|
||||
"outside",
|
||||
format!("imports {} from outside the project", tilde(&to)),
|
||||
&match in_shared {
|
||||
Some(r) => format!("import it by the workspace's name for it: \"@shared/{}\"", r.with_extension("").display()),
|
||||
None => "move it to the workspace's shared/ and import it as @shared/<kind>/<name>, or copy it into the project (raea component add, for raea's sets)".into(),
|
||||
},
|
||||
))
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// where each kind is kept (docs/layout.feature LY3): a project in the layout has a folder per kind, and a file
|
||||
// elsewhere is said once with the folder it belongs in; a project from before the layout is said once, as a whole
|
||||
if reg.project && reg.dir.join(".raea/project").is_file() {
|
||||
let laid = reg.dir.join("compositions").is_dir() || reg.dir.join("components").is_dir();
|
||||
let home = |rel: &str, kind: &str| rel.starts_with(&format!("{kind}/"));
|
||||
let components: BTreeSet<&str> = used_by.keys().map(String::as_str).filter(|f| f.ends_with(".tsx") && !comp_files.contains(f)).collect();
|
||||
let stray: Vec<(&str, &str)> = comp_files
|
||||
.iter()
|
||||
.filter(|f| !home(f, "compositions"))
|
||||
.map(|f| (*f, "compositions"))
|
||||
.chain(components.iter().filter(|f| !home(f, "components")).map(|f| (*f, "components")))
|
||||
.collect();
|
||||
if !laid && !stray.is_empty() {
|
||||
out.push(Lint { file: String::new(), line: 0, rule: "old-layout", level: Level::Info, says: format!("keeps {} files loose, from before compositions/ and components/", stray.len()), fix: "`raea project tidy --dry-run` shows where each goes, then `raea project tidy` moves them".into(), action: None });
|
||||
} else {
|
||||
for (f, kind) in stray {
|
||||
out.push(Lint { file: f.to_string(), line: 1, rule: "misplaced", level: Level::Info, says: format!("a {} outside {kind}/", &kind[..kind.len() - 1]), fix: format!("move it into {kind}/ (`raea project tidy` moves it and its imports)"), action: None });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// one id, two compositions (a composition's versions share theirs)
|
||||
let mut by_id: BTreeMap<&str, BTreeSet<String>> = BTreeMap::new();
|
||||
for c in ®.compositions {
|
||||
@@ -165,7 +196,12 @@ pub(super) fn lint(reg: &Registry, files: &[File], used_by: &BTreeMap<String, BT
|
||||
|
||||
// controllers: where they're kept, one id each, and every override naming one that's there
|
||||
let ws = super::up(®.dir, ".raea/workspace");
|
||||
let home = ws.clone().unwrap_or_else(|| reg.dir.clone()).join("controllers");
|
||||
// a project keeps its own (its controllers/); the workspace's own folder keeps the shared ones (docs/layout.feature LY3)
|
||||
let home = match &ws {
|
||||
Some(w) if w != ®.dir => reg.dir.join("controllers"),
|
||||
Some(w) => super::shared_dir(w, "controllers"),
|
||||
None => reg.dir.join("controllers"),
|
||||
};
|
||||
let mut ids: BTreeMap<String, Vec<&str>> = BTreeMap::new();
|
||||
for c in ®.controllers {
|
||||
let f = files.iter().find(|f| f.rel == c.file).expect("a controller's file was read");
|
||||
|
||||
@@ -148,3 +148,37 @@ fn real_folder() {
|
||||
let r = scan(Path::new(&dir), &[]);
|
||||
println!("{}\n({} ms)", r.text(), t.elapsed().as_millis());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_project_in_the_layout_reaches_shared_and_says_whats_out_of_place() {
|
||||
// docs/layout.feature LY2, LY3: @shared/ resolves and isn't "outside"; a relative climb into shared/ is told its
|
||||
// @shared/ name; a composition outside compositions/ is misplaced; a project from before the layout is said once
|
||||
let t = tempdir::Dir::new();
|
||||
let w = |rel: &str, text: &str| {
|
||||
let f = t.0.join(rel);
|
||||
std::fs::create_dir_all(f.parent().unwrap()).unwrap();
|
||||
std::fs::write(f, text).unwrap();
|
||||
};
|
||||
w(".raea/workspace", "[workspace]\n\tname = W\n");
|
||||
w("shared/components/desk.tsx", "export function Desk() { return <div />; }\n");
|
||||
w("projects/a/.raea/project", "[project]\n\tid = pj-a\n");
|
||||
w("projects/a/compositions/main.tsx", "import { Desk } from \"@shared/components/desk\";\nimport { Leg } from \"../components/leg\";\nimport { Desk as D2 } from \"../../../shared/components/desk\";\nexport default () => <><Desk /><Leg /><D2 /></>;\n");
|
||||
w("projects/a/components/leg.tsx", "export function Leg() { return <i />; }\n");
|
||||
w("projects/a/loose.tsx", "export default () => <b />;\n");
|
||||
let r = scan(&t.0.join("projects/a"), &[]);
|
||||
let says = |rule: &str| r.lint.iter().filter(|l| l.rule == rule).map(|l| format!("{} {}: {}", l.file, l.says, l.fix)).collect::<Vec<_>>();
|
||||
assert!(says("unresolved").is_empty(), "{:?}", says("unresolved"));
|
||||
let outside = says("outside");
|
||||
assert_eq!(outside.len(), 1, "{outside:?}");
|
||||
assert!(outside[0].contains("\"@shared/components/desk\""), "{outside:?}");
|
||||
assert_eq!(says("misplaced"), ["loose.tsx a composition outside compositions/: move it into compositions/ (`raea project tidy` moves it and its imports)"]);
|
||||
assert!(!r.lint.iter().any(|l| l.rule == "orphan" && l.file == "components/leg.tsx"));
|
||||
|
||||
w("projects/old/.raea/project", "[project]\n\tid = pj-old\n");
|
||||
w("projects/old/promo.tsx", "import { Card } from \"./card\";\nexport default () => <Card />;\n");
|
||||
w("projects/old/card.tsx", "export function Card() { return <i />; }\n");
|
||||
let r = scan(&t.0.join("projects/old"), &[]);
|
||||
let old: Vec<_> = r.lint.iter().filter(|l| l.rule == "old-layout").collect();
|
||||
assert!(old.len() == 1 && old[0].says.contains("2 files loose") && old[0].fix.contains("raea project tidy"), "{:?}", r.lint);
|
||||
assert!(!r.lint.iter().any(|l| l.rule == "misplaced"));
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
//! A workspace's controllers on disk (docs/projects.feature PJ2): controllers/<id>.ts, each `export default
|
||||
//! A workspace's controllers on disk (docs/projects.feature PJ2): shared/controllers/<id>.ts (docs/layout.feature; a
|
||||
//! workspace from before shared/ keeps controllers/ at its root), each `export default
|
||||
//! controller({...})` from "raea/brief", checked by core/brief's normalize. A project overrides a field's value in its
|
||||
//! .raea/project (`[controller "delivery.format"] aspect-ratio = 16:9`), so the project's value wins, as git config's
|
||||
//! own scopes do. Every change is a commit by who made it ("you", or the agent's name with --by).
|
||||
@@ -16,7 +17,7 @@ fn workspace_dir() -> R<PathBuf> {
|
||||
|
||||
/// Every controller in the workspace, checked, in file order.
|
||||
pub fn load(ws: &Path, eval: Eval) -> R<Vec<(PathBuf, Controller)>> {
|
||||
let mut files: Vec<PathBuf> = std::fs::read_dir(ws.join("controllers")).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "ts")).collect();
|
||||
let mut files: Vec<PathBuf> = std::fs::read_dir(raea_app_registry::shared_dir(ws, "controllers")).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "ts")).collect();
|
||||
files.sort();
|
||||
files.into_iter().map(|f| read(&f, eval).map(|c| (f, c))).collect()
|
||||
}
|
||||
@@ -188,9 +189,9 @@ fn set(ws: &Path, path: &str, value: &str, project: bool, by: &str, eval: Eval)
|
||||
|
||||
fn write(ws: &Path, file: &Path, by: &str, eval: Eval) -> R<String> {
|
||||
let c = read(file, eval)?;
|
||||
let to = ws.join("controllers").join(format!("{}.ts", c.id));
|
||||
let to = raea_app_registry::shared_dir(ws, "controllers").join(format!("{}.ts", c.id));
|
||||
let new = !to.exists();
|
||||
std::fs::create_dir_all(ws.join("controllers")).map_err(|e| e.to_string())?;
|
||||
std::fs::create_dir_all(raea_app_registry::shared_dir(ws, "controllers")).map_err(|e| e.to_string())?;
|
||||
std::fs::write(&to, module(&c)).map_err(|e| format!("{}: {e}", to.display()))?;
|
||||
commit(ws, &[&to], &format!("{} controller {}", if new { "add" } else { "rewrite" }, c.id), by)?;
|
||||
let n = |k: usize, what: &str| format!("{k} {what}{}", if k == 1 { "" } else { "s" });
|
||||
@@ -198,7 +199,7 @@ fn write(ws: &Path, file: &Path, by: &str, eval: Eval) -> R<String> {
|
||||
}
|
||||
|
||||
fn rm(ws: &Path, id: &str, by: &str) -> R<String> {
|
||||
let file = ws.join("controllers").join(format!("{id}.ts"));
|
||||
let file = raea_app_registry::shared_dir(ws, "controllers").join(format!("{id}.ts"));
|
||||
if !file.is_file() {
|
||||
return Err(format!("no controller {id}: raea controller ls lists them"));
|
||||
}
|
||||
|
||||
@@ -10,7 +10,14 @@ fn a_name_is_its_folder() {
|
||||
fn a_spec_module_is_tidy_typescript() {
|
||||
// keys unquoted where they can be, nulls and empty lists left out, whole numbers whole, short string lists inline
|
||||
let v = json!({"id": "delivery", "help": null, "tags": [], "n": 45.0, "options": ["9:16", "16:9"], "odd-key": 1});
|
||||
assert_eq!(ts_literal(&v, 0), "{\n id: \"delivery\",\n n: 45,\n \"odd-key\": 1,\n options: [\"9:16\", \"16:9\"],\n}");
|
||||
// the keys' order is serde_json's: sorted on its own, as written when a crate built alongside turns on
|
||||
// preserve_order (raea-cli does), so the lines are held as a set (#90)
|
||||
fn lines(s: &str) -> Vec<&str> {
|
||||
let mut l: Vec<&str> = s.lines().collect();
|
||||
l.sort_unstable();
|
||||
l
|
||||
}
|
||||
assert_eq!(lines(&ts_literal(&v, 0)), lines("{\n id: \"delivery\",\n n: 45,\n \"odd-key\": 1,\n options: [\"9:16\", \"16:9\"],\n}"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -133,3 +140,31 @@ fn the_root_with_none_set() {
|
||||
std::fs::create_dir_all(synced.join("Library/Mobile Documents/com~apple~CloudDocs/Documents")).unwrap();
|
||||
assert_eq!(default_root(&synced), synced.join("raea"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_workspace_and_project_have_the_layout() {
|
||||
// docs/layout.feature LY1: a folder per kind in the project and in the workspace's shared/, no media/ brand/ parts/
|
||||
let ws = scratch("layout");
|
||||
crate::workspace::make_workspace(&ws, "Layout", "monorepo").unwrap();
|
||||
for k in crate::workspace::KINDS {
|
||||
assert!(ws.join("shared").join(k).join(".gitkeep").is_file(), "shared/{k}");
|
||||
}
|
||||
assert!(!ws.join("controllers").exists() && !ws.join("artifacts").exists());
|
||||
let attrs = std::fs::read_to_string(ws.join(".gitattributes")).unwrap();
|
||||
assert!(attrs.contains("**/assets/** filter=lfs"), "{attrs}");
|
||||
crate::workspace::new_project_in(&ws, "Desk Test", None).unwrap();
|
||||
let p = ws.join("projects/desk-test");
|
||||
for k in crate::workspace::KINDS.iter().chain(["out"].iter()) {
|
||||
assert!(p.join(k).join(".gitkeep").is_file(), "{k}");
|
||||
}
|
||||
for gone in ["media", "brand", "parts"] {
|
||||
assert!(!p.join(gone).exists(), "{gone}");
|
||||
}
|
||||
assert!(std::fs::read_to_string(p.join("tsconfig.json")).unwrap().contains("\"@shared/*\": [\"../../shared/*\"]"));
|
||||
assert!(std::fs::read_to_string(p.join("AGENTS.md")).unwrap().contains("@shared/components/desk"));
|
||||
// committed: the workspace's repo has every kept folder
|
||||
let tracked = std::process::Command::new("git").args(["ls-files"]).current_dir(&ws).output().unwrap();
|
||||
let tracked = String::from_utf8_lossy(&tracked.stdout);
|
||||
assert!(tracked.contains("projects/desk-test/components/.gitkeep") && tracked.contains("shared/assets/.gitkeep"), "{tracked}");
|
||||
let _ = std::fs::remove_dir_all(&ws);
|
||||
}
|
||||
@@ -9,16 +9,27 @@ const USAGE: &str = "usage: raea workspace [--json] | raea workspace init [NAME]
|
||||
|
||||
/// git for raea's own commits. A new Mac has no user.email and a hostname git can't make one from, so every commit
|
||||
/// failed with "Author identity unknown" and the person's first project was never made. git reads $EMAIL only when
|
||||
/// user.email isn't set, so this gives a fresh Mac an address without overriding anyone's own.
|
||||
/// user.email isn't set, so this gives a fresh Mac an address without overriding anyone's own. A Linux account with no
|
||||
/// full name (a CI runner's, a container's) has no name either ("empty ident name ... not allowed"), and git has no
|
||||
/// fallback below user.name to give it, so when no user.name is set the author and committer are named for the account.
|
||||
pub(crate) fn git_cmd() -> Command {
|
||||
let mut c = Command::new("git");
|
||||
let user = std::env::var("USER").unwrap_or_else(|_| "raea".into());
|
||||
if std::env::var_os("EMAIL").is_none() {
|
||||
let user = std::env::var("USER").unwrap_or_else(|_| "raea".into());
|
||||
c.env("EMAIL", format!("{user}@raea.local"));
|
||||
}
|
||||
if !has_name() {
|
||||
c.env("GIT_AUTHOR_NAME", &user).env("GIT_COMMITTER_NAME", &user);
|
||||
}
|
||||
c
|
||||
}
|
||||
|
||||
/// Whether git has a user.name to sign commits with (asked once a process).
|
||||
fn has_name() -> bool {
|
||||
static HAS: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
*HAS.get_or_init(|| Command::new("git").args(["config", "--get", "user.name"]).output().is_ok_and(|o| o.status.success() && !o.stdout.trim_ascii().is_empty()))
|
||||
}
|
||||
|
||||
pub(crate) fn git(dir: &Path, args: &[&str]) -> R<String> {
|
||||
let out = git_cmd().arg("-C").arg(dir).args(args).output().map_err(|e| format!("git: {e}"))?;
|
||||
if !out.status.success() {
|
||||
@@ -156,7 +167,17 @@ pub(crate) fn commit(repo: &Path, paths: &[&str], what: &str) -> R<()> {
|
||||
git(repo, &["commit", "-q", "-m", &format!("raea: {what}"), "--"]).map(|_| ())
|
||||
}
|
||||
|
||||
const AGENTS_PROJECT: &str = "# Agents\n\nRun `raea context .` here before any work: the taste, this project's brief.ts and script.ts, its look and the guides\nits modes need, in the order to read them. Specs are TypeScript (`export default brief({...})` from \"raea/brief\").\n";
|
||||
const AGENTS_PROJECT: &str = "# Agents\n\nRun `raea context .` here before any work: the taste, this project's brief.ts and script.ts, its look and the guides\nits modes need, in the order to read them. Specs are TypeScript (`export default brief({...})` from \"raea/brief\").\n\nWhere files go (docs/layout.feature):\n\n- compositions/: what renders, a registerRoot <Composition> or a default export; versions are NAME-v2.tsx\n- components/: what compositions import; every prop is a component whose props animate it\n- controllers/: this project's controllers, over the workspace's shared ones by id\n- assets/: media in (footage, stills, audio, models, fonts) and the brand kit in assets/brand/\n- artifacts/: the small React apps posted to the feed\n- out/: renders\n\nThe workspace's shared/ holds the same five folders for every project: import them as\n`@shared/components/desk`, never by a relative path out of this folder.\n";
|
||||
|
||||
/// The kinds of file a project, and the workspace's shared/, keep a folder each for (docs/layout.feature).
|
||||
pub const KINDS: [&str; 5] = ["compositions", "components", "controllers", "assets", "artifacts"];
|
||||
|
||||
/// LFS for media in and renders out, at any depth: in each project and in shared/ (a pattern with a slash is anchored to
|
||||
/// the workspace root, so the old media/** never matched a project's media/)
|
||||
const GITATTRIBUTES: &str = "**/assets/** filter=lfs diff=lfs merge=lfs -text\n**/out/** filter=lfs diff=lfs merge=lfs -text\n**/media/** filter=lfs diff=lfs merge=lfs -text\n";
|
||||
|
||||
/// A project's tsconfig: @shared/ resolves to the workspace's shared/ for an editor and tsc, as the engine resolves it.
|
||||
const TSCONFIG_PROJECT: &str = "{\n \"compilerOptions\": {\n \"jsx\": \"react-jsx\",\n \"module\": \"esnext\",\n \"moduleResolution\": \"bundler\",\n \"target\": \"es2022\",\n \"strict\": true,\n \"noEmit\": true,\n \"baseUrl\": \".\",\n \"paths\": { \"@shared/*\": [\"../../shared/*\"] }\n }\n}\n";
|
||||
|
||||
/// `raea workspace …`
|
||||
pub fn workspace(args: &[String]) -> R<String> {
|
||||
@@ -229,7 +250,7 @@ fn count(n: usize) -> String {
|
||||
if n == 1 { "1 project".into() } else { format!("{n} projects") }
|
||||
}
|
||||
|
||||
fn make_workspace(dir: &Path, name: &str, layout: &str) -> R<()> {
|
||||
pub(crate) fn make_workspace(dir: &Path, name: &str, layout: &str) -> R<()> {
|
||||
// never a workspace in another repo's own folder (on a case-insensitive disk ~/Raea is ~/raea, raea's checkout); a
|
||||
// repo further up, as a home folder kept in git, is fine: the workspace is a repo of its own inside it
|
||||
let parent = dir.parent().unwrap_or(Path::new("/"));
|
||||
@@ -250,11 +271,17 @@ fn make_workspace(dir: &Path, name: &str, layout: &str) -> R<()> {
|
||||
set(&file, "workspace.name", name)?;
|
||||
set(&file, "workspace.layout", layout)?;
|
||||
include(dir, &file)?;
|
||||
write_new(&dir.join("controllers/.gitkeep"), "")?;
|
||||
// what every project here can call on (docs/layout.feature LY1, LY2): imported as @shared/<kind>/...
|
||||
for k in KINDS {
|
||||
write_new(&dir.join("shared").join(k).join(".gitkeep"), "")?;
|
||||
}
|
||||
write_new(&dir.join("projects/.gitkeep"), "")?;
|
||||
write_new(&dir.join("taste.ts"), &format!("import {{ taste }} from \"raea/brief\";\n\n// {name}'s house rules: every project here follows them, after the person's own taste.\nexport default taste({{\n title: {:?},\n sections: [],\n}});\n", format!("{name}: house rules")))?;
|
||||
write_new(&dir.join(".gitattributes"), "media/** filter=lfs diff=lfs merge=lfs -text\nout/** filter=lfs diff=lfs merge=lfs -text\n")?;
|
||||
commit(dir, &[".raea/workspace", "controllers/.gitkeep", "projects/.gitkeep", "taste.ts", ".gitattributes"], &format!("workspace {name}"))
|
||||
write_new(&dir.join(".gitattributes"), GITATTRIBUTES)?;
|
||||
let kept: Vec<String> = KINDS.iter().map(|k| format!("shared/{k}/.gitkeep")).collect();
|
||||
let mut files: Vec<&str> = vec![".raea/workspace", "projects/.gitkeep", "taste.ts", ".gitattributes"];
|
||||
files.extend(kept.iter().map(String::as_str));
|
||||
commit(dir, &files, &format!("workspace {name}"))
|
||||
}
|
||||
|
||||
/// The workspace's projects: (name, path, storage), from .raea/workspace.
|
||||
@@ -327,6 +354,12 @@ pub fn project(args: &[String]) -> R<String> {
|
||||
fn new_project(name: &str, storage: Option<&str>) -> R<String> {
|
||||
let here = std::env::current_dir().map_err(|e| e.to_string())?;
|
||||
let ws = up(&here, ".raea/workspace").ok_or("not in a workspace: raea workspace init NAME makes one")?;
|
||||
new_project_in(&ws, name, storage)
|
||||
}
|
||||
|
||||
/// A new project in the workspace at `ws` (the folder holding .raea/workspace).
|
||||
pub(crate) fn new_project_in(ws: &Path, name: &str, storage: Option<&str>) -> R<String> {
|
||||
let ws = ws.to_path_buf();
|
||||
let slugged = slug(name);
|
||||
if slugged.is_empty() {
|
||||
return Err(format!("{name:?} has no letters or digits to name a folder by"));
|
||||
@@ -344,11 +377,15 @@ fn new_project(name: &str, storage: Option<&str>) -> R<String> {
|
||||
std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
write_new(&dir.join("brief.ts"), &format!("import {{ brief }} from \"raea/brief\";\n\nexport default brief({{\n title: {name:?},\n}});\n"))?;
|
||||
write_new(&dir.join("AGENTS.md"), AGENTS_PROJECT)?;
|
||||
for d in ["media", "brand", "out"] {
|
||||
write_new(&dir.join("tsconfig.json"), TSCONFIG_PROJECT)?;
|
||||
// the project's layout (docs/layout.feature LY1): a folder for each kind of file, and its renders
|
||||
for d in KINDS.iter().chain(["out"].iter()) {
|
||||
write_new(&dir.join(d).join(".gitkeep"), "")?;
|
||||
}
|
||||
let id = register(&ws, &dir, &rel, storage)?;
|
||||
let files = [".raea/project", "brief.ts", "AGENTS.md", "media/.gitkeep", "brand/.gitkeep", "out/.gitkeep"];
|
||||
let kept: Vec<String> = KINDS.iter().chain(["out"].iter()).map(|d| format!("{d}/.gitkeep")).collect();
|
||||
let mut files: Vec<&str> = vec![".raea/project", "brief.ts", "AGENTS.md", "tsconfig.json"];
|
||||
files.extend(kept.iter().map(String::as_str));
|
||||
if storage == "submodule" {
|
||||
git(&dir, &["init", "-q"])?;
|
||||
commit(&dir, &files, &format!("project {name}"))?;
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
# the entries check.sh makes beside each module of a corpus
|
||||
lr/
|
||||
*.raea.tsx
|
||||
@@ -0,0 +1,59 @@
|
||||
// The page's text runs in Chrome, made the way raea's render manifest makes them (engine/page/src/motion/manifest.rs),
|
||||
// so the two can be compared run by run. A run is the words of the text nodes owned by one element: the nearest
|
||||
// ancestor that isn't inline and has a box. Its box is that element's bounding rect, and its ink spans where its
|
||||
// letters are. Text under opacity 0.01 or less is skipped, as the manifest skips it.
|
||||
export type Run = { text: string; box: number[]; ink?: number[] };
|
||||
|
||||
const r = (v: number) => Math.round(v * 10) / 10;
|
||||
|
||||
function alpha(el: Element | null): number {
|
||||
let a = 1;
|
||||
for (let e = el; e; e = e.parentElement) a *= Number(getComputedStyle(e).opacity);
|
||||
return a;
|
||||
}
|
||||
|
||||
function sized(el: Element): DOMRect | null {
|
||||
const b = el.getBoundingClientRect();
|
||||
return b.width > 0 && b.height > 0 ? b : null;
|
||||
}
|
||||
|
||||
export function runs(root: Element): Run[] {
|
||||
const owned = new Map<Element, Text[]>();
|
||||
const walk = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
|
||||
for (let n = walk.nextNode() as Text | null; n; n = walk.nextNode() as Text | null) {
|
||||
if (!n.data || !n.parentElement) continue;
|
||||
// (an svg's <title> and <desc> are never drawn: they name the picture for a screen reader)
|
||||
if (n.parentElement.closest("style, script, svg title, svg desc")) continue;
|
||||
// an svg's words belong to their <text>, as the manifest has them (the page draws an svg as one picture, usvg's)
|
||||
const svgText = n.parentElement.closest("svg text");
|
||||
let up: Element | null = svgText ?? n.parentElement;
|
||||
if (svgText && !sized(svgText)) continue;
|
||||
while (!svgText && up && (getComputedStyle(up).display.startsWith("inline") || !sized(up))) up = up.parentElement;
|
||||
// hidden words (a measuring copy under opacity 0 or visibility: hidden) aren't on the frame, as the manifest has it
|
||||
if (!up || alpha(n.parentElement) <= 0.01 || getComputedStyle(n.parentElement).visibility !== "visible") continue;
|
||||
owned.set(up, [...(owned.get(up) ?? []), n]);
|
||||
}
|
||||
const out: Run[] = [];
|
||||
for (const [owner, texts] of owned) {
|
||||
// run_text's join: the trimmed pieces with a space between, or letters set one a span read back as their words
|
||||
const words = texts.map((t) => t.data.trim()).filter(Boolean);
|
||||
const text = words.length && words.every((w) => [...w].length === 1) ? texts.map((t) => t.data).join("").split(/\s+/).filter(Boolean).join(" ") : words.join(" ");
|
||||
const b = sized(owner);
|
||||
if (!text || !b) continue;
|
||||
let x0 = Infinity, x1 = -Infinity;
|
||||
for (const t of texts) {
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(t);
|
||||
for (const q of range.getClientRects()) {
|
||||
if (q.width <= 0) continue;
|
||||
x0 = Math.min(x0, q.left);
|
||||
x1 = Math.max(x1, q.right);
|
||||
}
|
||||
}
|
||||
const run: Run = { text, box: [r(b.x), r(b.y), r(b.width), r(b.height)] };
|
||||
if (owner.closest("svg")) run.ink = run.box;
|
||||
else if (x1 > x0) run.ink = [r(x0), r(b.y), r(x1 - x0), r(b.height)];
|
||||
out.push(run);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
Executable
+126
@@ -0,0 +1,126 @@
|
||||
#!/bin/bash
|
||||
# Layout reads against Chrome (docs/layout-reads.feature LR0, #54): compositions that measure their text and layout,
|
||||
# rendered by raea and by headless Chrome at their first, middle and last frames.
|
||||
# - A corpus is a folder of modules, each exporting `Comp` (the component), `conf` ({ width, height, fps,
|
||||
# durationInFrames }) and `props`. Its list.txt names the ones to run (the first word of each line), else every
|
||||
# .tsx. Each gets two entries made beside it: NAME.raea.tsx for raea, lr/NAME.chrome.tsx for Chrome. The default corpus is probes/, raea's own: each reads one part of the DOM a web component reads. Another is
|
||||
# named by LAYOUT_READS_CORPUS; Chrome resolves its imports through the nearest tsconfig.json above it.
|
||||
# - raea renders each with `raea render --at`. Its manifest's text runs are the words, box and ink as raea laid them out.
|
||||
# - Chrome runs the same module under React DOM, in raea's Clock at the same frame, mounted once the fonts it asked
|
||||
# for are in, and boxes.ts lists its text runs the way the manifest does.
|
||||
# - compare.jq pairs the runs by their words. A frame passes when every run pairs, and box and ink are within 1 px.
|
||||
# - The frames' dissimilarity (1 - SSIM, ImageMagick 7's SSIM metric) is printed too, for information.
|
||||
# A composition passes when raea renders it without throwing, and all three frames pass.
|
||||
# bench/layout-reads/check.sh [NAME ...] (RAEA_BIN: the raea to run, default target/release/raea;
|
||||
# KEEP=DIR keeps the frames and logs there)
|
||||
# Prints one line per composition, then the count. Exits 1 when one fails.
|
||||
cd "$(dirname "$0")/../.." || exit 2
|
||||
RAEA=$PWD
|
||||
BENCH=$RAEA/bench/layout-reads
|
||||
BIN=${RAEA_BIN:-$RAEA/target/release/raea}
|
||||
C=$(cd "${LAYOUT_READS_CORPUS:-$BENCH/probes}" && pwd) || exit 2
|
||||
export RAEA_SIGN=0 RAEA_MARK=0 RAEA_EXPORT_CACHE=0
|
||||
for t in bun jq magick python3; do command -v $t > /dev/null || { echo "layout-reads: needs $t" >&2; exit 2; }; done
|
||||
CH=$(bash "$RAEA/sdk/ui/parity/chrome.sh") || exit 2
|
||||
|
||||
# the corpus's tsconfig (the nearest above it), and Chrome's: its paths, raea's SDK paths made absolute, and one React
|
||||
TS=$C
|
||||
while [ "$TS" != / ] && [ ! -f "$TS/tsconfig.json" ]; do TS=$(dirname "$TS"); done
|
||||
L=$C/lr
|
||||
mkdir -p "$L"
|
||||
jq -n --slurpfile base "$RAEA/sdk/tsconfig.base.json" --arg sdk "$RAEA/sdk" --arg root "$TS" \
|
||||
--argjson own "$([ -f "$TS/tsconfig.json" ] && jq -c '.compilerOptions.paths // {}' "$TS/tsconfig.json" || echo '{}')" '
|
||||
{compilerOptions: {jsx: "react-jsx", module: "esnext", target: "es2022", moduleResolution: "bundler", baseUrl: $root,
|
||||
paths: (([$base[0].compilerOptions.paths | to_entries[] | select(.key | test("^react") | not)
|
||||
| .value |= map($sdk + "/" + ltrimstr("./"))] | from_entries) + $own
|
||||
# each SDK package has its own node_modules/react, and two copies break hooks
|
||||
+ ({"react": "react/index.js", "react/jsx-runtime": "react/jsx-runtime.js", "react/jsx-dev-runtime": "react/jsx-dev-runtime.js",
|
||||
"react-dom": "react-dom/index.js", "react-dom/client": "react-dom/client.js", "scheduler": "scheduler/index.js"}
|
||||
| map_values([$sdk + "/raea/node_modules/" + .])))}}' > "$L/tsconfig.chrome.json" || exit 2
|
||||
|
||||
names=("$@")
|
||||
if [ ${#names[@]} -eq 0 ]; then
|
||||
if [ -f "$C/list.txt" ]; then
|
||||
while read -r n _; do names+=("$n"); done < <(grep -vE '^(#|$)' "$C/list.txt")
|
||||
else
|
||||
for f in "$C"/*.tsx; do case $f in *.raea.tsx) ;; *) names+=("$(basename "$f" .tsx)") ;; esac; done
|
||||
fi
|
||||
fi
|
||||
|
||||
O=${KEEP:-$(mktemp -d "${TMPDIR:-/tmp}/raea-layout-reads.XXXXXX")}
|
||||
mkdir -p "$O"
|
||||
PORT=$((20000 + RANDOM % 20000))
|
||||
python3 -m http.server $PORT --bind 127.0.0.1 --directory "$C" > /dev/null 2>&1 &
|
||||
SRV=$!
|
||||
disown $SRV 2> /dev/null # (its kill at the end says nothing)
|
||||
if [ -n "${KEEP:-}" ]; then trap 'kill $SRV 2> /dev/null' EXIT; else trap 'kill $SRV 2> /dev/null; rm -rf "$O"' EXIT; fi
|
||||
|
||||
pass=0 fail=0
|
||||
for n in "${names[@]}"; do
|
||||
[ -f "$C/$n.tsx" ] || { echo "$n FAIL no $n.tsx in the corpus"; fail=$((fail + 1)); continue; }
|
||||
D=$O/$n && rm -rf "$D" && mkdir -p "$D"
|
||||
# raea's entry beside the module (raea resolves an edit's imports through the tsconfig of its own folder)
|
||||
cat > "$C/$n.raea.tsx" <<EOF
|
||||
import { Composition, registerRoot } from "raea";
|
||||
import { Comp, conf, props } from "./$n";
|
||||
const Main = () => <Comp {...props} />;
|
||||
registerRoot(() => <Composition id="$n" component={Main} {...conf} />);
|
||||
EOF
|
||||
cat > "$L/$n.chrome.tsx" <<EOF
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { Clock } from "raea/clock";
|
||||
import { Comp, conf, props } from "../$n";
|
||||
import { runs } from "$BENCH/boxes";
|
||||
const [frame, dump] = location.hash.slice(1).split(",");
|
||||
document.body.style.margin = "0";
|
||||
const el = document.getElementById("root")!;
|
||||
el.style.cssText = \`position:relative;width:\${conf.width}px;height:\${conf.height}px;overflow:hidden\`;
|
||||
// mounted once the fonts it asked for (loadFont's stylesheets) are in, as a render holds for them
|
||||
const sheets = [...document.querySelectorAll<HTMLLinkElement>("link[rel=stylesheet]")].map((l) => (l.sheet ? Promise.resolve() : new Promise((ok) => { l.onload = l.onerror = ok; })));
|
||||
await Promise.all(sheets);
|
||||
await Promise.all([...document.fonts].map((f) => f.load().catch(() => {})));
|
||||
createRoot(el).render(<Clock frame={Number(frame)} {...conf}><Comp {...props} /></Clock>);
|
||||
if (dump) document.fonts.ready.then(() => setTimeout(() => {
|
||||
const s = document.createElement("script");
|
||||
s.type = "application/json";
|
||||
s.id = "lr-runs";
|
||||
s.textContent = JSON.stringify(runs(el));
|
||||
document.body.appendChild(s);
|
||||
}, 1000));
|
||||
EOF
|
||||
# its size and length, from frame 0's render
|
||||
(cd "$C" && "$BIN" render "$n.raea.tsx" --at 0 -o "$D/first/" --manifest "$D/first.json") > "$D/first.log" 2>&1
|
||||
read -r width height dur < <(jq -r '[.width, .height, .length] | @tsv' "$D/first.json" 2> /dev/null)
|
||||
if [ -z "$dur" ]; then
|
||||
echo "$n FAIL raea: $(grep -m1 -E 'threw|Error:|panicked|REFUSED' "$D/first.log" | sed -E 's/\x1b\[[0-9;]*m//g' | cut -c1-200)"
|
||||
fail=$((fail + 1)); continue
|
||||
fi
|
||||
frames=(0 $((dur / 2)) $((dur - 1)))
|
||||
(cd "$C" && RUST_LOG=info "$BIN" render "$n.raea.tsx" --at "$(IFS=,; echo "${frames[*]}")" -o "$D/raea/" --manifest "$D/manifest.json") > "$D/raea.log" 2>&1
|
||||
rr=$?
|
||||
threw=$(grep -m1 -E 'threw|Error:|panicked|REFUSED' "$D/raea.log" | sed -E 's/\x1b\[[0-9;]*m//g' | cut -c1-200)
|
||||
(cd "$L" && bun build "$n.chrome.tsx" --tsconfig-override tsconfig.chrome.json --target browser --outfile "$n.js" \
|
||||
--define 'process.env.NODE_ENV="production"') > "$D/bun.log" 2>&1 || { echo "$n FAIL Chrome's bundle: $(grep -m1 -i error "$D/bun.log" | cut -c1-150)"; fail=$((fail + 1)); continue; }
|
||||
printf '<!doctype html><meta charset=utf-8><body style="background:#000"><div id=root></div><script type=module src="/lr/%s.js"></script>' "$n" > "$L/$n.html"
|
||||
line="" ok=1
|
||||
[ $rr = 0 ] && [ -z "$threw" ] || ok=0
|
||||
# Chrome renders each frame in real time (chrome.ts), so its requestAnimationFrame and ResizeObserver run
|
||||
bun "$BENCH/chrome.ts" "$CH" "http://127.0.0.1:$PORT/lr/$n.html" "$width" "$height" "$D" "${frames[@]}" > "$D/chrome.log" 2>&1
|
||||
for i in 0 1 2; do
|
||||
f=${frames[$i]}
|
||||
r=$D/raea/frame-0000$i.png
|
||||
if [ $rr != 0 ] || [ ! -f "$r" ]; then line="$line @$f no frame"; ok=0; continue; fi
|
||||
[ -s "$D/chrome-$f.json" ] || { line="$line @$f no Chrome runs"; ok=0; continue; }
|
||||
# the manifest's entry for frame f, by its number (a frame drawn twice has one entry, the last)
|
||||
cmp=$(jq -c -n --slurpfile m "$D/manifest.json" --slurpfile c "$D/chrome-$f.json" --argjson f "$f" \
|
||||
"([\$m[0].frames[] | select(.frame == \$f)] | last | .text // []) as \$r | \$c[0] as \$c | $(cat "$BENCH/compare.jq")")
|
||||
echo "$cmp" > "$D/compare-$f.json"
|
||||
dssim=$(magick compare -metric SSIM <(magick "$r" -background black -alpha remove png:-) <(magick "$D/chrome-$f.png" -background black -alpha remove png:-) null: 2>&1 | grep -oE '\(([0-9.e-]+)\)' | tr -d '()')
|
||||
read -r paired alone box ink < <(echo "$cmp" | jq -r '[.paired, (.raea_only + .chrome_only | length), (.box * 10 | round / 10), (.ink * 10 | round / 10)] | @tsv')
|
||||
if [ "$alone" = 0 ] && awk "BEGIN { exit !($box <= 1 && $ink <= 1) }"; then mark=ok; else mark=off; ok=0; fi
|
||||
line="$line @$f $mark runs $paired+$alone box $box ink $ink dssim ${dssim:-?}"
|
||||
done
|
||||
if [ $ok = 1 ]; then pass=$((pass + 1)); echo "$n PASS$line"; else fail=$((fail + 1)); echo "$n FAIL$line${threw:+ $threw}"; fi
|
||||
done
|
||||
echo "layout-reads: $pass passed, $fail failed (of ${#names[@]})"
|
||||
[ $fail = 0 ]
|
||||
@@ -0,0 +1,28 @@
|
||||
// The Chrome side's frames (check.sh): the pinned Chrome for Testing, driven by Playwright, renders the composition's
|
||||
// page at each frame in real time, so requestAnimationFrame and ResizeObserver run as they do in a browser (a headless
|
||||
// --dump-dom under --virtual-time-budget runs neither: no rendering step ever comes). Each frame's page is loaded with
|
||||
// `#FRAME,dump`; once boxes.ts's runs are on it (the page adds them a second after its fonts are ready), they're written
|
||||
// to OUT/chrome-FRAME.json and the page to OUT/chrome-FRAME.png.
|
||||
// bun bench/layout-reads/chrome.ts CHROME URL WIDTH HEIGHT OUT FRAME...
|
||||
|
||||
import { writeFileSync } from "node:fs";
|
||||
import { chromium } from "../../apps/app/node_modules/@playwright/test";
|
||||
|
||||
const [exe, url, w, h, out, ...frames] = process.argv.slice(2);
|
||||
if (!exe || !url || !out || !frames.length) {
|
||||
console.error("usage: chrome.ts CHROME URL WIDTH HEIGHT OUT FRAME...");
|
||||
process.exit(2);
|
||||
}
|
||||
const browser = await chromium.launch({ executablePath: exe, args: ["--hide-scrollbars"] });
|
||||
try {
|
||||
for (const f of frames) {
|
||||
const page = await browser.newPage({ viewport: { width: Number(w), height: Number(h) } });
|
||||
await page.goto(`${url}#${f},dump`);
|
||||
const runs = await page.waitForSelector("#lr-runs", { state: "attached", timeout: 30000 }).then((s) => s.textContent());
|
||||
writeFileSync(`${out}/chrome-${f}.json`, runs ?? "");
|
||||
await page.screenshot({ path: `${out}/chrome-${f}.png` });
|
||||
await page.close();
|
||||
}
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
# One frame's text runs, raea's ($r, the render manifest's) against Chrome's ($c, boxes.ts): each raea run is paired
|
||||
# with the first unpaired Chrome run of the same words, in order. Says how many paired, the words each side has alone,
|
||||
# and the largest differences in px: box (x, y, width, height) and ink (x and width).
|
||||
def gap(a; b; at): [at[] | ((a[.] // 0) - (b[.] // 0)) | fabs] | max // 0;
|
||||
reduce $r[] as $x ({used: [], pairs: [], alone: []};
|
||||
. as $s
|
||||
| ([$c | to_entries[] | select(.value.text == $x.text) | .key | select(. as $k | $s.used | any(.[]; . == $k) | not)]) as $k
|
||||
| if ($k | length) > 0 then
|
||||
.used += [$k[0]]
|
||||
| .pairs += [{text: $x.text, box: gap($x.box; $c[$k[0]].box; [0, 1, 2, 3]),
|
||||
ink: (if $x.ink and $c[$k[0]].ink then gap($x.ink; $c[$k[0]].ink; [0, 2]) else 0 end)}]
|
||||
else .alone += [$x.text] end)
|
||||
| . as $s
|
||||
| {paired: ($s.pairs | length),
|
||||
raea_only: $s.alone,
|
||||
chrome_only: [$c | to_entries[] | select(.key as $k | $s.used | any(.[]; . == $k) | not) | .value.text],
|
||||
box: ([$s.pairs[].box] | max // 0),
|
||||
ink: ([$s.pairs[].ink] | max // 0),
|
||||
worst: (($s.pairs | max_by([.box, .ink] | max)) // null)}
|
||||
@@ -0,0 +1,91 @@
|
||||
// LR5 and LR7's reads as a probe (docs/layout-reads.feature): getComputedStyle, an svg <text>'s measures, a Range over a
|
||||
// text node, and a node made with document.createElement and measured. Each length read places a word (its left at the
|
||||
// value), so the harness's 1 px box check holds it to Chrome's; a computed value is printed as words, which must match.
|
||||
import { AbsoluteFill } from "raea";
|
||||
import { loadFont } from "raea/text";
|
||||
import { useLayoutEffect, useRef, useState } from "react";
|
||||
|
||||
const { fontFamily } = loadFont("Inter");
|
||||
|
||||
export const conf = { width: 640, height: 360, fps: 30, durationInFrames: 3 };
|
||||
export const props = {};
|
||||
|
||||
type Read = { size: string; weight: string; color: string; len: number; tracked: number; third: number; range: number; prefix: number; made: number };
|
||||
|
||||
export function Comp() {
|
||||
const styled = useRef<HTMLDivElement>(null);
|
||||
const svg = useRef<SVGTextElement>(null);
|
||||
const tracked = useRef<SVGTextElement>(null);
|
||||
const span = useRef<HTMLSpanElement>(null);
|
||||
const [r, setR] = useState<Read | null>(null);
|
||||
useLayoutEffect(() => {
|
||||
const cs = getComputedStyle(styled.current!);
|
||||
const t = svg.current!;
|
||||
const node = span.current!.firstChild!;
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(node);
|
||||
const whole = range.getBoundingClientRect().width;
|
||||
range.setStart(node, 0);
|
||||
range.setEnd(node, 5);
|
||||
const prefix = range.getBoundingClientRect().width;
|
||||
// a hidden copy made, measured and removed
|
||||
const m = document.createElement("span");
|
||||
m.style.fontFamily = fontFamily;
|
||||
m.style.fontSize = "40px";
|
||||
m.style.position = "absolute";
|
||||
m.textContent = "measured copy";
|
||||
document.body.appendChild(m);
|
||||
const made = m.getBoundingClientRect().width;
|
||||
m.remove();
|
||||
setR({
|
||||
size: cs.fontSize,
|
||||
weight: cs.getPropertyValue("font-weight"),
|
||||
color: cs.color,
|
||||
len: t.getComputedTextLength(),
|
||||
tracked: tracked.current!.getComputedTextLength(),
|
||||
third: t.getStartPositionOfChar(3).x,
|
||||
range: whole,
|
||||
prefix,
|
||||
made,
|
||||
});
|
||||
}, []);
|
||||
const at = (left: number, top: number, word: string) => (
|
||||
<div style={{ position: "absolute", left, top, fontSize: 16, lineHeight: "20px" }}>{word}</div>
|
||||
);
|
||||
return (
|
||||
<AbsoluteFill style={{ background: "#fff", color: "#111", fontFamily }}>
|
||||
<div ref={styled} style={{ position: "absolute", left: 20, top: 300, fontSize: 18, fontWeight: 600, color: "#3355aa" }}>
|
||||
styled
|
||||
</div>
|
||||
<svg width={640} height={360} style={{ position: "absolute", left: 0, top: 0 }}>
|
||||
<g opacity={0}>
|
||||
<text ref={svg} x={10} y={40} style={{ fontFamily, fontSize: 36 }}>
|
||||
Hidden width
|
||||
</text>
|
||||
<text ref={tracked} x={10} y={80} style={{ fontFamily, fontSize: 36, letterSpacing: 4 }}>
|
||||
Tracked
|
||||
</text>
|
||||
</g>
|
||||
</svg>
|
||||
{/* spacing as text-select sets its line: ink across the words, against Chrome's */}
|
||||
<div style={{ position: "absolute", left: 200, top: 230, fontSize: 32, wordSpacing: "-0.07em" }}>word gaps tight here</div>
|
||||
<div style={{ position: "absolute", left: 200, top: 270, fontSize: 32, wordSpacing: "-0.07em", letterSpacing: "-0.012em" }}>
|
||||
tracked and tight
|
||||
</div>
|
||||
<span ref={span} style={{ position: "absolute", left: 20, top: 330, fontSize: 24, whiteSpace: "pre" }}>
|
||||
Range over words
|
||||
</span>
|
||||
{r && (
|
||||
<>
|
||||
{at(r.len, 10, "svglength")}
|
||||
{at(r.tracked, 40, "tracked")}
|
||||
{at(r.third, 70, "third")}
|
||||
{at(r.range, 100, "range")}
|
||||
{at(r.prefix, 130, "prefix")}
|
||||
{at(r.made, 160, "made")}
|
||||
{at(20, 200, `computed ${r.size} ${r.weight} ${r.color}`)}
|
||||
</>
|
||||
)}
|
||||
</AbsoluteFill>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
// LR3's reads as a probe (docs/layout-reads.feature): each value a ref reads is printed as words, so the harness's
|
||||
// pairing by words fails on any value that differs from Chrome's. Covers getBoundingClientRect under a transform,
|
||||
// offset* (untransformed, from the positioned offsetParent's padding edge), client* (padding box, 0 for an inline
|
||||
// span) and scroll* of a scroller.
|
||||
import { AbsoluteFill } from "raea";
|
||||
import { loadFont } from "raea/text";
|
||||
import { useLayoutEffect, useRef, useState } from "react";
|
||||
|
||||
const { fontFamily } = loadFont("Inter");
|
||||
|
||||
export const conf = { width: 640, height: 360, fps: 30, durationInFrames: 3 };
|
||||
export const props = {};
|
||||
|
||||
const r = (v: number) => Math.round(v * 10) / 10;
|
||||
|
||||
export function Comp() {
|
||||
const card = useRef<HTMLDivElement>(null);
|
||||
const turned = useRef<HTMLDivElement>(null);
|
||||
const word = useRef<HTMLSpanElement>(null);
|
||||
const scroller = useRef<HTMLDivElement>(null);
|
||||
const [lines, setLines] = useState<string[]>([]);
|
||||
useLayoutEffect(() => {
|
||||
const c = card.current!, t = turned.current!, w = word.current!, s = scroller.current!;
|
||||
const b = t.getBoundingClientRect();
|
||||
setLines([
|
||||
`card offset ${c.offsetLeft} ${c.offsetTop} ${c.offsetWidth} ${c.offsetHeight}`,
|
||||
`card client ${c.clientLeft} ${c.clientTop} ${c.clientWidth} ${c.clientHeight}`,
|
||||
`turned rect ${r(b.x)} ${r(b.y)} ${r(b.width)} ${r(b.height)}`,
|
||||
`turned offset ${t.offsetLeft} ${t.offsetTop} ${t.offsetWidth} ${t.offsetHeight} parent ${t.offsetParent === c ? "card" : "other"}`,
|
||||
`word offset ${w.offsetWidth} ${w.offsetHeight} client ${w.clientWidth}`,
|
||||
`scroller ${s.scrollWidth} ${s.scrollHeight} ${s.clientHeight}`,
|
||||
]);
|
||||
}, []);
|
||||
return (
|
||||
<AbsoluteFill style={{ background: "#fff", color: "#111", fontFamily, fontSize: 14 }}>
|
||||
<div ref={card} style={{ position: "absolute", left: 24, top: 20, width: 260, height: 120, padding: 10, border: "3px solid #333" }}>
|
||||
<div ref={turned} style={{ position: "absolute", left: 40, top: 30, width: 100, height: 40, background: "#c33", transform: "rotate(30deg)" }} />
|
||||
<span ref={word} style={{ fontSize: 22 }}>
|
||||
measure me
|
||||
</span>
|
||||
</div>
|
||||
<div ref={scroller} style={{ position: "absolute", left: 340, top: 20, width: 200, height: 80, overflow: "hidden" }}>
|
||||
<div style={{ width: 300, height: 260, background: "#ddd" }} />
|
||||
</div>
|
||||
<div style={{ position: "absolute", left: 24, top: 180 }}>
|
||||
{lines.map((l) => (
|
||||
<div key={l}>{l}</div>
|
||||
))}
|
||||
</div>
|
||||
</AbsoluteFill>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
// LR9's hold as a probe (docs/layout-reads.feature): the composition holds its frame, sets its words after a timer
|
||||
// (as it would after a font or a fetch), and continues. The frame taken is the one with the words; a frame taken
|
||||
// before the hold was released would show "waiting" where Chrome, which dumps a second later, shows the words.
|
||||
import { AbsoluteFill, continueRender, delayRender } from "raea";
|
||||
import { loadFont } from "raea/text";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
|
||||
const { fontFamily } = loadFont("Inter");
|
||||
|
||||
export const conf = { width: 640, height: 200, fps: 30, durationInFrames: 3 };
|
||||
export const props = {};
|
||||
|
||||
export function Comp() {
|
||||
const [handle] = useState(() => delayRender("words after a timer"));
|
||||
const [words, setWords] = useState("waiting");
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => {
|
||||
const t = setTimeout(() => {
|
||||
setWords("held until the words came");
|
||||
continueRender(handle);
|
||||
}, 300);
|
||||
return () => clearTimeout(t);
|
||||
}, [handle]);
|
||||
return (
|
||||
<AbsoluteFill style={{ background: "#fff", color: "#111", fontFamily, fontSize: 32 }}>
|
||||
<div ref={ref} style={{ position: "absolute", left: 32, top: 70 }}>
|
||||
{words}
|
||||
</div>
|
||||
</AbsoluteFill>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
// LR6's reads as a probe (docs/layout-reads.feature): a 2D context's measureText and its image data. Each measure
|
||||
// places a word (its left or top at the value read), so the harness's 1 px box check holds it to Chrome's; the pixels
|
||||
// read back are printed as words, which must match exactly.
|
||||
import { AbsoluteFill } from "raea";
|
||||
import { loadFont } from "raea/text";
|
||||
import { useLayoutEffect, useState } from "react";
|
||||
|
||||
const { fontFamily } = loadFont("Inter");
|
||||
|
||||
export const conf = { width: 640, height: 360, fps: 30, durationInFrames: 3 };
|
||||
export const props = {};
|
||||
|
||||
type Read = { w: number; inkL: number; inkR: number; asc: number; desc: number; fasc: number; pixels: string; put: string };
|
||||
|
||||
function read(): Read {
|
||||
const c = new OffscreenCanvas(64, 64);
|
||||
const ctx = c.getContext("2d")!;
|
||||
ctx.font = `48px ${fontFamily}`;
|
||||
const hello = ctx.measureText("Hello, measured");
|
||||
const g = ctx.measureText("g");
|
||||
ctx.textAlign = "center";
|
||||
const mid = ctx.measureText("Wide");
|
||||
ctx.textAlign = "left";
|
||||
// what was drawn, read back: a red square on clear, the middle of it and a corner outside it
|
||||
ctx.fillStyle = "#f00";
|
||||
ctx.fillRect(8, 8, 16, 16);
|
||||
const px = (x: number, y: number) => [...ctx.getImageData(x, y, 1, 1).data].join(" ");
|
||||
// putImageData writes its pixels as they are: half-transparent green, no blending with the red under it
|
||||
const img = ctx.createImageData(2, 2);
|
||||
for (let i = 0; i < img.data.length; i += 4) img.data.set([0, 255, 0, 128], i);
|
||||
ctx.globalAlpha = 0.25;
|
||||
ctx.putImageData(img, 10, 10);
|
||||
return {
|
||||
w: hello.width,
|
||||
inkL: mid.actualBoundingBoxLeft,
|
||||
inkR: mid.actualBoundingBoxRight,
|
||||
asc: hello.actualBoundingBoxAscent,
|
||||
desc: g.actualBoundingBoxDescent,
|
||||
fasc: hello.fontBoundingBoxAscent,
|
||||
pixels: `${px(16, 16)} and ${px(40, 40)}`,
|
||||
put: px(11, 11),
|
||||
};
|
||||
}
|
||||
|
||||
export function Comp() {
|
||||
const [r, setR] = useState<Read | null>(null);
|
||||
useLayoutEffect(() => setR(read()), []);
|
||||
if (!r) return <AbsoluteFill style={{ background: "#fff" }} />;
|
||||
const at = (left: number, top: number, word: string) => (
|
||||
<div style={{ position: "absolute", left, top, fontSize: 16, lineHeight: "20px" }}>{word}</div>
|
||||
);
|
||||
return (
|
||||
<AbsoluteFill style={{ background: "#fff", color: "#111", fontFamily }}>
|
||||
{at(r.w, 10, "width")}
|
||||
{at(320 - r.inkL, 40, "inkleft")}
|
||||
{at(320 + r.inkR, 70, "inkright")}
|
||||
{at(20, 100 + r.asc, "ascent")}
|
||||
{at(20 + r.desc * 10, 160, "descent")}
|
||||
{at(20, 180 + r.fasc, "fontascent")}
|
||||
{at(20, 260, `red ${r.pixels}`)}
|
||||
{at(20, 290, `put ${r.put}`)}
|
||||
</AbsoluteFill>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
// LR8's ResizeObserver as a probe (docs/layout-reads.feature): a box observed while its words change size. The
|
||||
// observer's first call (on observe) and its call after the words grow each place a word at the width they report, so
|
||||
// the harness's 1 px box check holds them to Chrome's; the frame is held until the second call, so both sides compare
|
||||
// the frame after it. MutationObserver and IntersectionObserver are made, and must not throw.
|
||||
import { AbsoluteFill, continueRender, delayRender } from "raea";
|
||||
import { loadFont } from "raea/text";
|
||||
import { useEffect, useLayoutEffect, useRef, useState } from "react";
|
||||
|
||||
const { fontFamily } = loadFont("Inter");
|
||||
|
||||
export const conf = { width: 640, height: 240, fps: 30, durationInFrames: 3 };
|
||||
export const props = {};
|
||||
|
||||
type Seen = { content: number; border: number; height: number };
|
||||
|
||||
export function Comp() {
|
||||
const [handle] = useState(() => delayRender("resize observed"));
|
||||
const [words, setWords] = useState("short");
|
||||
const [seen, setSeen] = useState<Seen[]>([]);
|
||||
const box = useRef<HTMLDivElement>(null);
|
||||
useLayoutEffect(() => {
|
||||
const ro = new ResizeObserver((entries) => {
|
||||
const e = entries[0]!;
|
||||
setSeen((s) => [...s, { content: e.contentRect.width, border: e.borderBoxSize[0]!.inlineSize, height: e.contentBoxSize[0]!.blockSize }]);
|
||||
});
|
||||
ro.observe(box.current!);
|
||||
new MutationObserver(() => {}).observe(box.current!, { childList: true });
|
||||
new IntersectionObserver(() => {}).observe(box.current!);
|
||||
return () => ro.disconnect();
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
if (seen.length === 1) setWords("a good deal longer now");
|
||||
if (seen.length >= 2) continueRender(handle);
|
||||
}, [seen, handle]);
|
||||
const at = (left: number, top: number, word: string) => (
|
||||
<div style={{ position: "absolute", left, top, fontSize: 16, lineHeight: "20px" }}>{word}</div>
|
||||
);
|
||||
const [a, b] = [seen[0], seen[1]];
|
||||
return (
|
||||
<AbsoluteFill style={{ background: "#fff", color: "#111", fontFamily }}>
|
||||
<div ref={box} style={{ position: "absolute", left: 20, top: 20, padding: 8, border: "3px solid #888", fontSize: 28 }}>
|
||||
{words}
|
||||
</div>
|
||||
{a && at(a.content, 100, "first")}
|
||||
{a && at(a.border, 130, "firstborder")}
|
||||
{b && at(b.content, 160, "second")}
|
||||
{b && at(b.height * 4, 190, "height")}
|
||||
</AbsoluteFill>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// #54's repro as a probe (docs/layout-reads.feature LR0, LR3): a span's offsetWidth, read in an effect, places the
|
||||
// word under it. In Chrome "Hello world" at 64 px is 335 px wide, so "here" starts at x 335; with no width to read it
|
||||
// starts at 0.
|
||||
import { AbsoluteFill } from "raea";
|
||||
import { loadFont } from "raea/text";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
|
||||
const { fontFamily } = loadFont("Inter");
|
||||
|
||||
export const conf = { width: 640, height: 240, fps: 30, durationInFrames: 3 };
|
||||
export const props = {};
|
||||
|
||||
export function Comp() {
|
||||
const ref = useRef<HTMLSpanElement>(null);
|
||||
const [w, setW] = useState(0);
|
||||
useEffect(() => setW(Number(ref.current?.offsetWidth) || 0), []);
|
||||
return (
|
||||
<AbsoluteFill style={{ background: "#fff", color: "#111", fontFamily }}>
|
||||
<div style={{ position: "absolute", top: 0, left: 0 }}>
|
||||
<span ref={ref} style={{ fontSize: 64 }}>
|
||||
Hello world
|
||||
</span>
|
||||
</div>
|
||||
<div style={{ position: "absolute", top: 120, left: w, fontSize: 32 }}>here</div>
|
||||
</AbsoluteFill>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
// LR4's reads as a probe (docs/layout-reads.feature): a ref walked and queried as a web component does, each answer
|
||||
// printed as words, so the harness's pairing by words fails on any answer that differs from Chrome's.
|
||||
import { AbsoluteFill } from "raea";
|
||||
import { loadFont } from "raea/text";
|
||||
import { useLayoutEffect, useRef, useState } from "react";
|
||||
|
||||
const { fontFamily } = loadFont("Inter");
|
||||
|
||||
export const conf = { width: 640, height: 360, fps: 30, durationInFrames: 3 };
|
||||
export const props = {};
|
||||
|
||||
export function Comp() {
|
||||
const list = useRef<HTMLUListElement>(null);
|
||||
const [lines, setLines] = useState<string[]>([]);
|
||||
useLayoutEffect(() => {
|
||||
const l = list.current!;
|
||||
const items = l.querySelectorAll("li");
|
||||
const second = l.querySelector("li:nth-child(2)") as HTMLElement;
|
||||
const word = l.querySelector(".word[data-w='b']") as HTMLElement;
|
||||
let bad = "no throw";
|
||||
try {
|
||||
l.querySelector("li[");
|
||||
} catch (e) {
|
||||
bad = (e as Error).name;
|
||||
}
|
||||
setLines([
|
||||
`tag ${l.tagName} kids ${l.children.length} items ${items.length} first ${l.firstElementChild?.textContent} last ${l.lastElementChild?.textContent}`,
|
||||
`second ${second.textContent} next ${second.nextElementSibling?.textContent} prev ${second.previousElementSibling?.textContent}`,
|
||||
`word ${word.textContent} closest ${word.closest("li")?.id} parent ${word.parentElement?.tagName} data ${word.dataset.w}`,
|
||||
`matches ${second.matches("ul > li.item:not(.off)")} odd ${l.querySelectorAll("li:nth-child(odd)").length} last ${l.querySelectorAll("li:last-child").length}`,
|
||||
`class ${word.className} list ${word.classList.length} has ${word.classList.contains("word")} attr ${word.getAttribute("data-w")} ${word.hasAttribute("title")}`,
|
||||
`contains ${l.contains(word)} ${word.contains(l)} text ${l.textContent?.replace(/\s+/g, "-")} bad ${bad}`,
|
||||
]);
|
||||
}, []);
|
||||
return (
|
||||
<AbsoluteFill style={{ background: "#fff", color: "#111", fontFamily, fontSize: 16 }}>
|
||||
<ul ref={list} style={{ position: "absolute", left: 24, top: 10, margin: 0 }}>
|
||||
<li id="one" className="item">
|
||||
one
|
||||
</li>
|
||||
<li id="two" className="item">
|
||||
two <span className="word" data-w="b">bee</span>
|
||||
</li>
|
||||
<li id="three" className="item off">
|
||||
three
|
||||
</li>
|
||||
</ul>
|
||||
<div style={{ position: "absolute", left: 24, top: 140 }}>
|
||||
{lines.map((t) => (
|
||||
<div key={t}>{t}</div>
|
||||
))}
|
||||
</div>
|
||||
</AbsoluteFill>
|
||||
);
|
||||
}
|
||||
@@ -154,12 +154,28 @@ impl Finding {
|
||||
}
|
||||
|
||||
static SAID: std::sync::Mutex<Vec<Finding>> = std::sync::Mutex::new(Vec::new());
|
||||
/// Held by a test that says and takes, so two such tests don't take each other's findings
|
||||
#[cfg(test)]
|
||||
pub(crate) static SAYING: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
|
||||
/// Findings a command has said as it went (a render's clipping, from its own thread), kept for its count at the end.
|
||||
pub fn said(fs: &[Finding]) {
|
||||
SAID.lock().unwrap_or_else(|e| e.into_inner()).extend(fs.iter().cloned());
|
||||
}
|
||||
|
||||
/// A finding about frame `f` alone, said: printed and kept, unless the same finding is running on the frames just before
|
||||
/// it, which it then joins (a render's black frames with paint on them say one line a run, and count once: #96).
|
||||
pub fn said_frame(found: Finding, f: i64) {
|
||||
let mut all = SAID.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(run) = all.iter_mut().rev().find(|x| x.check == found.check && x.says == found.says && x.frames.is_some_and(|[_, b]| b == f)) {
|
||||
run.frames = run.frames.map(|[a, _]| [a, f + 1]);
|
||||
return;
|
||||
}
|
||||
let found = found.frames(f, f + 1);
|
||||
eprintln!("raea: {}", found.line());
|
||||
all.push(found);
|
||||
}
|
||||
|
||||
/// Every finding said so far, taken: what the command ends by counting.
|
||||
pub fn taken() -> Vec<Finding> {
|
||||
std::mem::take(&mut *SAID.lock().unwrap_or_else(|e| e.into_inner()))
|
||||
@@ -199,6 +215,19 @@ pub fn count(fs: &[Finding]) -> String {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_finding_on_frames_in_a_row_is_one_finding_over_them() {
|
||||
let _held = SAYING.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let _ = taken();
|
||||
let lost = || Finding::new("black-frame", Level::Warn, "drew all black", "raea render");
|
||||
for f in [22, 23, 24, 30] {
|
||||
said_frame(lost(), f);
|
||||
}
|
||||
said_frame(Finding::new("black-frame", Level::Warn, "other", "raea render"), 25);
|
||||
let got: Vec<_> = taken().into_iter().map(|x| (x.says, x.frames)).collect();
|
||||
assert_eq!(got, vec![("drew all black".to_string(), Some([22, 25])), ("drew all black".into(), Some([30, 31])), ("other".into(), Some([25, 26]))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_old_ranks_and_words_map_onto_three_levels() {
|
||||
assert_eq!([0, 1, 2, 3].map(Level::of_rank), [Level::Error, Level::Error, Level::Warn, Level::Note]);
|
||||
|
||||
@@ -186,6 +186,7 @@ mod tests {
|
||||
// outside a project, nothing is kept
|
||||
assert!(keep("raea render", &std::env::temp_dir().join("loose.tsx"), None, &[], vec![], "x").is_none());
|
||||
// a video copied from the export cache says what was found when it was drawn (finding::keep_to, replay)
|
||||
let _held = crate::finding::SAYING.lock().unwrap_or_else(|e| e.into_inner());
|
||||
crate::finding::said(std::slice::from_ref(&tilt));
|
||||
assert!(crate::finding::keep_to(&root.join("cached.findings")));
|
||||
let _ = crate::finding::taken();
|
||||
|
||||
+24
-8
@@ -1,6 +1,10 @@
|
||||
/ RGBA (texture T, w x h, plus a frame-tag texel at (8, h)) to NV12, BT.709 limited range in 8.8 fixed point.
|
||||
/ One output word per thread: four luma bytes, or two interleaved chroma pairs (each the mean of a 2x2 block),
|
||||
/ or, last, the tag texel. Coordinates are clamped so the branch not taken stays in bounds.
|
||||
/ Each sample is rounded through a 4x4 Bayer threshold of its pixel (a chroma pair's, of its block's top-left pixel) in
|
||||
/ place of half-up rounding, so a slow dark gradient steps every pixel instead of every band (#87): the same
|
||||
/ threshold in play and render, and in nv12_cpu (core/k/src/native.rs), which stays bit-equal. Samples are clamped to the
|
||||
/ nominal range (luma 16..235, chroma 16..240): 220/256 overshoots 219/255, and the dither would put some white on 236.
|
||||
ny:(w*h)%4
|
||||
nuv:(w*h)%8
|
||||
/ luma: pixels 4i..4i+3
|
||||
@@ -8,13 +12,21 @@ p:(4*i)&(w*h)-4
|
||||
ly:p%w
|
||||
lx:p!w
|
||||
c0:tex[T;lx+0;ly]
|
||||
y0:clamp[16+shr[(47*and[c0;255])+(157*and[shr[c0;8];255])+(16*and[shr[c0;16];255])+128;8];0;255]
|
||||
a0:xor[lx+0;ly]
|
||||
d0:or[or[shl[and[a0;1];3];shl[and[ly;1];2]];or[and[a0;2];shr[and[ly;2];1]]]
|
||||
y0:clamp[16+shr[(47*and[c0;255])+(157*and[shr[c0;8];255])+(16*and[shr[c0;16];255])+8+(16*d0);8];16;235]
|
||||
c1:tex[T;lx+1;ly]
|
||||
y1:clamp[16+shr[(47*and[c1;255])+(157*and[shr[c1;8];255])+(16*and[shr[c1;16];255])+128;8];0;255]
|
||||
a1:xor[lx+1;ly]
|
||||
d1:or[or[shl[and[a1;1];3];shl[and[ly;1];2]];or[and[a1;2];shr[and[ly;2];1]]]
|
||||
y1:clamp[16+shr[(47*and[c1;255])+(157*and[shr[c1;8];255])+(16*and[shr[c1;16];255])+8+(16*d1);8];16;235]
|
||||
c2:tex[T;lx+2;ly]
|
||||
y2:clamp[16+shr[(47*and[c2;255])+(157*and[shr[c2;8];255])+(16*and[shr[c2;16];255])+128;8];0;255]
|
||||
a2:xor[lx+2;ly]
|
||||
d2:or[or[shl[and[a2;1];3];shl[and[ly;1];2]];or[and[a2;2];shr[and[ly;2];1]]]
|
||||
y2:clamp[16+shr[(47*and[c2;255])+(157*and[shr[c2;8];255])+(16*and[shr[c2;16];255])+8+(16*d2);8];16;235]
|
||||
c3:tex[T;lx+3;ly]
|
||||
y3:clamp[16+shr[(47*and[c3;255])+(157*and[shr[c3;8];255])+(16*and[shr[c3;16];255])+128;8];0;255]
|
||||
a3:xor[lx+3;ly]
|
||||
d3:or[or[shl[and[a3;1];3];shl[and[ly;1];2]];or[and[a3;2];shr[and[ly;2];1]]]
|
||||
y3:clamp[16+shr[(47*and[c3;255])+(157*and[shr[c3;8];255])+(16*and[shr[c3;16];255])+8+(16*d3);8];16;235]
|
||||
yw:or[or[y0;shl[y1;8]];or[shl[y2;16];shl[y3;24]]]
|
||||
/ chroma: samples 2j and 2j+1 of the (w/2) x (h/2) grid, j counting from the first chroma word
|
||||
j:0|(i-ny)&nuv-1
|
||||
@@ -29,8 +41,10 @@ t03:tex[T;x0+1;(2*cr)+1]
|
||||
r0:and[t00;255]+and[t01;255]+and[t02;255]+and[t03;255]
|
||||
g0:and[shr[t00;8];255]+and[shr[t01;8];255]+and[shr[t02;8];255]+and[shr[t03;8];255]
|
||||
b0:and[shr[t00;16];255]+and[shr[t01;16];255]+and[shr[t02;16];255]+and[shr[t03;16];255]
|
||||
u0:clamp[128+shr[(-26*r0)+(-87*g0)+(112*b0)+512;10];0;255]
|
||||
v0:clamp[128+shr[(112*r0)+(-102*g0)+(-10*b0)+512;10];0;255]
|
||||
aq0:xor[x0;2*cr]
|
||||
dq0:or[or[shl[and[aq0;1];3];shl[and[2*cr;1];2]];or[and[aq0;2];shr[and[2*cr;2];1]]]
|
||||
u0:clamp[128+shr[(-26*r0)+(-87*g0)+(112*b0)+32+(64*dq0);10];16;240]
|
||||
v0:clamp[128+shr[(112*r0)+(-102*g0)+(-10*b0)+32+(64*dq0);10];16;240]
|
||||
x1:2*cc+1
|
||||
t10:tex[T;x1;2*cr]
|
||||
t11:tex[T;x1+1;2*cr]
|
||||
@@ -39,7 +53,9 @@ t13:tex[T;x1+1;(2*cr)+1]
|
||||
r1:and[t10;255]+and[t11;255]+and[t12;255]+and[t13;255]
|
||||
g1:and[shr[t10;8];255]+and[shr[t11;8];255]+and[shr[t12;8];255]+and[shr[t13;8];255]
|
||||
b1:and[shr[t10;16];255]+and[shr[t11;16];255]+and[shr[t12;16];255]+and[shr[t13;16];255]
|
||||
u1:clamp[128+shr[(-26*r1)+(-87*g1)+(112*b1)+512;10];0;255]
|
||||
v1:clamp[128+shr[(112*r1)+(-102*g1)+(-10*b1)+512;10];0;255]
|
||||
aq1:xor[x1;2*cr]
|
||||
dq1:or[or[shl[and[aq1;1];3];shl[and[2*cr;1];2]];or[and[aq1;2];shr[and[2*cr;2];1]]]
|
||||
u1:clamp[128+shr[(-26*r1)+(-87*g1)+(112*b1)+32+(64*dq1);10];16;240]
|
||||
v1:clamp[128+shr[(112*r1)+(-102*g1)+(-10*b1)+32+(64*dq1);10];16;240]
|
||||
uvw:or[or[u0;shl[v0;8]];or[shl[u1;16];shl[v1;24]]]
|
||||
px:sel[i<ny;yw;sel[i<ny+nuv;uvw;tex[T;8;h]]]
|
||||
@@ -1,6 +1,10 @@
|
||||
/ RGBA (buffer F, w x h words; the frame tag is texel (8, h) of texture T; w x h, plus a frame-tag texel at (8, h)) to NV12, BT.709 limited range in 8.8 fixed point.
|
||||
/ One output word per thread: four luma bytes, or two interleaved chroma pairs (each the mean of a 2x2 block),
|
||||
/ or, last, the tag texel. Coordinates are clamped so the branch not taken stays in bounds.
|
||||
/ Each sample is rounded through a 4x4 Bayer threshold of its pixel (a chroma pair's, of its block's top-left pixel) in
|
||||
/ place of half-up rounding, so a slow dark gradient steps every pixel instead of every band (#87): the same
|
||||
/ threshold in play and render, and in nv12_cpu (core/k/src/native.rs), which stays bit-equal. Samples are clamped to the
|
||||
/ nominal range (luma 16..235, chroma 16..240): 220/256 overshoots 219/255, and the dither would put some white on 236.
|
||||
ny:(w*h)%4
|
||||
nuv:(w*h)%8
|
||||
/ luma: pixels 4i..4i+3
|
||||
@@ -8,13 +12,21 @@ p:(4*i)&(w*h)-4
|
||||
ly:p%w
|
||||
lx:p!w
|
||||
c0:word[F;((ly)*w)+lx+0]
|
||||
y0:clamp[16+shr[(47*and[c0;255])+(157*and[shr[c0;8];255])+(16*and[shr[c0;16];255])+128;8];0;255]
|
||||
a0:xor[lx+0;ly]
|
||||
d0:or[or[shl[and[a0;1];3];shl[and[ly;1];2]];or[and[a0;2];shr[and[ly;2];1]]]
|
||||
y0:clamp[16+shr[(47*and[c0;255])+(157*and[shr[c0;8];255])+(16*and[shr[c0;16];255])+8+(16*d0);8];16;235]
|
||||
c1:word[F;((ly)*w)+lx+1]
|
||||
y1:clamp[16+shr[(47*and[c1;255])+(157*and[shr[c1;8];255])+(16*and[shr[c1;16];255])+128;8];0;255]
|
||||
a1:xor[lx+1;ly]
|
||||
d1:or[or[shl[and[a1;1];3];shl[and[ly;1];2]];or[and[a1;2];shr[and[ly;2];1]]]
|
||||
y1:clamp[16+shr[(47*and[c1;255])+(157*and[shr[c1;8];255])+(16*and[shr[c1;16];255])+8+(16*d1);8];16;235]
|
||||
c2:word[F;((ly)*w)+lx+2]
|
||||
y2:clamp[16+shr[(47*and[c2;255])+(157*and[shr[c2;8];255])+(16*and[shr[c2;16];255])+128;8];0;255]
|
||||
a2:xor[lx+2;ly]
|
||||
d2:or[or[shl[and[a2;1];3];shl[and[ly;1];2]];or[and[a2;2];shr[and[ly;2];1]]]
|
||||
y2:clamp[16+shr[(47*and[c2;255])+(157*and[shr[c2;8];255])+(16*and[shr[c2;16];255])+8+(16*d2);8];16;235]
|
||||
c3:word[F;((ly)*w)+lx+3]
|
||||
y3:clamp[16+shr[(47*and[c3;255])+(157*and[shr[c3;8];255])+(16*and[shr[c3;16];255])+128;8];0;255]
|
||||
a3:xor[lx+3;ly]
|
||||
d3:or[or[shl[and[a3;1];3];shl[and[ly;1];2]];or[and[a3;2];shr[and[ly;2];1]]]
|
||||
y3:clamp[16+shr[(47*and[c3;255])+(157*and[shr[c3;8];255])+(16*and[shr[c3;16];255])+8+(16*d3);8];16;235]
|
||||
yw:or[or[y0;shl[y1;8]];or[shl[y2;16];shl[y3;24]]]
|
||||
/ chroma: samples 2j and 2j+1 of the (w/2) x (h/2) grid, j counting from the first chroma word
|
||||
j:0|(i-ny)&nuv-1
|
||||
@@ -29,8 +41,10 @@ t03:word[F;(((2*cr)+1)*w)+x0+1]
|
||||
r0:and[t00;255]+and[t01;255]+and[t02;255]+and[t03;255]
|
||||
g0:and[shr[t00;8];255]+and[shr[t01;8];255]+and[shr[t02;8];255]+and[shr[t03;8];255]
|
||||
b0:and[shr[t00;16];255]+and[shr[t01;16];255]+and[shr[t02;16];255]+and[shr[t03;16];255]
|
||||
u0:clamp[128+shr[(-26*r0)+(-87*g0)+(112*b0)+512;10];0;255]
|
||||
v0:clamp[128+shr[(112*r0)+(-102*g0)+(-10*b0)+512;10];0;255]
|
||||
aq0:xor[x0;2*cr]
|
||||
dq0:or[or[shl[and[aq0;1];3];shl[and[2*cr;1];2]];or[and[aq0;2];shr[and[2*cr;2];1]]]
|
||||
u0:clamp[128+shr[(-26*r0)+(-87*g0)+(112*b0)+32+(64*dq0);10];16;240]
|
||||
v0:clamp[128+shr[(112*r0)+(-102*g0)+(-10*b0)+32+(64*dq0);10];16;240]
|
||||
x1:2*cc+1
|
||||
t10:word[F;((2*cr)*w)+x1]
|
||||
t11:word[F;((2*cr)*w)+x1+1]
|
||||
@@ -39,7 +53,9 @@ t13:word[F;(((2*cr)+1)*w)+x1+1]
|
||||
r1:and[t10;255]+and[t11;255]+and[t12;255]+and[t13;255]
|
||||
g1:and[shr[t10;8];255]+and[shr[t11;8];255]+and[shr[t12;8];255]+and[shr[t13;8];255]
|
||||
b1:and[shr[t10;16];255]+and[shr[t11;16];255]+and[shr[t12;16];255]+and[shr[t13;16];255]
|
||||
u1:clamp[128+shr[(-26*r1)+(-87*g1)+(112*b1)+512;10];0;255]
|
||||
v1:clamp[128+shr[(112*r1)+(-102*g1)+(-10*b1)+512;10];0;255]
|
||||
aq1:xor[x1;2*cr]
|
||||
dq1:or[or[shl[and[aq1;1];3];shl[and[2*cr;1];2]];or[and[aq1;2];shr[and[2*cr;2];1]]]
|
||||
u1:clamp[128+shr[(-26*r1)+(-87*g1)+(112*b1)+32+(64*dq1);10];16;240]
|
||||
v1:clamp[128+shr[(112*r1)+(-102*g1)+(-10*b1)+32+(64*dq1);10];16;240]
|
||||
uvw:or[or[u0;shl[v0;8]];or[shl[u1;16];shl[v1;24]]]
|
||||
px:sel[i<ny;yw;sel[i<ny+nuv;uvw;tex[T;8;h]]]
|
||||
+10
-4
@@ -4,7 +4,12 @@
|
||||
/// formula per output word, the words split into bands; bit-equal.
|
||||
pub fn nv12_cpu(rgba: &[u32], w: usize, h: usize, threads: usize) -> Vec<u32> {
|
||||
let ch = |c: u32, s: u32| ((c >> s) & 255) as i32;
|
||||
let luma = |c: u32| (16 + ((47 * ch(c, 0) + 157 * ch(c, 8) + 16 * ch(c, 16) + 128) >> 8)).clamp(0, 255) as u32;
|
||||
// the 4x4 Bayer threshold of pixel (x, y): 0..15, in place of half-up rounding (nv12.k's d0..d3, dq0, dq1; #87)
|
||||
let bayer = |x: usize, y: usize| -> i32 {
|
||||
let (a, y) = ((x ^ y) as i32, y as i32);
|
||||
(a & 1) << 3 | (y & 1) << 2 | (a & 2) | (y & 2) >> 1
|
||||
};
|
||||
let luma = |c: u32, x: usize, y: usize| (16 + ((47 * ch(c, 0) + 157 * ch(c, 8) + 16 * ch(c, 16) + 8 + 16 * bayer(x, y)) >> 8)).clamp(16, 235) as u32;
|
||||
let (ny, nuv) = (w * h / 4, w * h / 8);
|
||||
let mut out = vec![0u32; ny + nuv + 1];
|
||||
let cw = w / 2;
|
||||
@@ -13,7 +18,7 @@ pub fn nv12_cpu(rgba: &[u32], w: usize, h: usize, threads: usize) -> Vec<u32> {
|
||||
let p = 4 * j;
|
||||
let (y, x) = (p / w, p % w);
|
||||
let px = |d: usize| rgba[y * w + x + d];
|
||||
return luma(px(0)) | luma(px(1)) << 8 | luma(px(2)) << 16 | luma(px(3)) << 24;
|
||||
return luma(px(0), x, y) | luma(px(1), x + 1, y) << 8 | luma(px(2), x + 2, y) << 16 | luma(px(3), x + 3, y) << 24;
|
||||
}
|
||||
let j = j - ny;
|
||||
let mut wd = 0u32;
|
||||
@@ -23,8 +28,9 @@ pub fn nv12_cpu(rgba: &[u32], w: usize, h: usize, threads: usize) -> Vec<u32> {
|
||||
let t = [rgba[2 * cr * w + 2 * cc], rgba[2 * cr * w + 2 * cc + 1], rgba[(2 * cr + 1) * w + 2 * cc], rgba[(2 * cr + 1) * w + 2 * cc + 1]];
|
||||
let sum = |sh: u32| t.iter().map(|c| ch(*c, sh)).sum::<i32>();
|
||||
let (r, g, b) = (sum(0), sum(8), sum(16));
|
||||
let u = (128 + ((-26 * r - 87 * g + 112 * b + 512) >> 10)).clamp(0, 255) as u32;
|
||||
let v = (128 + ((112 * r - 102 * g - 10 * b + 512) >> 10)).clamp(0, 255) as u32;
|
||||
let d = 32 + 64 * bayer(2 * cc, 2 * cr);
|
||||
let u = (128 + ((-26 * r - 87 * g + 112 * b + d) >> 10)).clamp(16, 240) as u32;
|
||||
let v = (128 + ((112 * r - 102 * g - 10 * b + d) >> 10)).clamp(16, 240) as u32;
|
||||
wd |= (u | v << 8) << (16 * k);
|
||||
}
|
||||
wd
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
//! The RGB to NV12 kernels round each sample through a 4x4 Bayer threshold of its pixel (#87: half-up rounding into
|
||||
//! limited range banded every slow dark gradient), and nv12_cpu (the CPU render's twin) stays bit-equal to both the
|
||||
//! texture kernel (nv12.k) and the buffer kernel (nv12buf.k), run here through the K interpreter.
|
||||
use std::collections::HashMap;
|
||||
|
||||
use raea_core_k::{Cpu, nv12_cpu, parse};
|
||||
|
||||
const NV12_K: &str = include_str!("../kernels/nv12.k");
|
||||
const NV12BUF_K: &str = include_str!("../kernels/nv12buf.k");
|
||||
|
||||
/// a w x (h + 1) frame of packed RGBA words from a small generator, the last row the frame tag's
|
||||
fn frame(w: usize, h: usize, seed: u32) -> Vec<u32> {
|
||||
let mut s = seed;
|
||||
(0..w * (h + 1))
|
||||
.map(|_| {
|
||||
s ^= s << 13;
|
||||
s ^= s >> 17;
|
||||
s ^= s << 5;
|
||||
s
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn through(k: &str, rgba: &[u32], w: usize, h: usize) -> Vec<u32> {
|
||||
let k = parse(k).unwrap();
|
||||
let cpu = Cpu { buffers: HashMap::from([("T", rgba), ("F", rgba)]), scalars: HashMap::from([("w", w as i32), ("h", h as i32), ("T_w", w as i32)]) };
|
||||
cpu.run(&k, w * h / 4 + w * h / 8 + 1, &["px"]).unwrap().remove(0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_kernels_match_the_cpu_twin_bit_for_bit() {
|
||||
for (w, h, seed) in [(16, 8, 1u32), (24, 12, 7), (64, 36, 99)] {
|
||||
let rgba = frame(w, h, seed);
|
||||
let want = nv12_cpu(&rgba, w, h, 3);
|
||||
assert_eq!(through(NV12_K, &rgba, w, h), want, "nv12.k at {w}x{h}");
|
||||
assert_eq!(through(NV12BUF_K, &rgba, w, h), want, "nv12buf.k at {w}x{h}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A flat dark grey keeps its mean through the dither: the luma of RGB 10 is 24.63 in limited range, so a 4x4 block
|
||||
/// lands on 24 and 25 in a ratio that averages to it, not on one band.
|
||||
#[test]
|
||||
fn a_flat_dark_grey_keeps_its_mean_and_spans_two_levels() {
|
||||
let (w, h) = (16, 8);
|
||||
let rgba = vec![0xff0a0a0au32; w * (h + 1)];
|
||||
let out = nv12_cpu(&rgba, w, h, 1);
|
||||
let luma: Vec<u32> = out[..w * h / 4].iter().flat_map(|wd| [wd & 255, wd >> 8 & 255, wd >> 16 & 255, wd >> 24]).collect();
|
||||
let mean = luma.iter().sum::<u32>() as f64 / luma.len() as f64;
|
||||
assert!((mean - 24.627).abs() < 0.1, "mean {mean}");
|
||||
let mut levels: Vec<u32> = luma.clone();
|
||||
levels.sort_unstable();
|
||||
levels.dedup();
|
||||
assert_eq!(levels, [24, 25]);
|
||||
// and black stays black, white stays white: the dither never lifts the ends of the range
|
||||
let black = nv12_cpu(&vec![0xff000000u32; w * (h + 1)], w, h, 1);
|
||||
assert!(black[..w * h / 4].iter().all(|wd| *wd == 0x10101010), "black luma");
|
||||
let white = nv12_cpu(&vec![0xffffffffu32; w * (h + 1)], w, h, 1);
|
||||
assert!(white[..w * h / 4].iter().all(|wd| *wd == 0xebebebeb), "white luma");
|
||||
}
|
||||
+79
-1
@@ -27,6 +27,9 @@ Feature: Agents in the raea app: chats run on a provider, agents are optional te
|
||||
3. Whoever posts an item is its subscriber: what the person sends on it reaches that session, inside raea or out.
|
||||
4. A session states its own role. One started from a template in raea gets the template's role without asking;
|
||||
one started outside raea says who it is when it posts, and may change it.
|
||||
5. There's no Director. The workspace has one primary: the harness that runs at its root (its own chats) and
|
||||
whatever the person doesn't pick for. It's a provider on a model, or one of the person's agents; making an agent
|
||||
the primary is how someone gets an orchestrator, and it's still only that choice (A6, Shane 11-12).
|
||||
|
||||
Background:
|
||||
Given the app is apps/app (raea-feed): src/chat, src/agent, src/model/agents.ts, host/acp, host/feed-items.ts
|
||||
@@ -48,9 +51,24 @@ Feature: Agents in the raea app: chats run on a provider, agents are optional te
|
||||
|
||||
Scenario: A1b. A template is a choice, never a requirement
|
||||
Given a workspace with no agents
|
||||
Then New chat, the feed's composer and a project's chat all work, each on the workspace's default provider
|
||||
Then New chat, the feed's composer and a project's chat all work, each on the workspace's primary
|
||||
|
||||
Scenario: A1c. One menu picks the AI, its model or an agent
|
||||
# Shane 11-12: "when I go to composer and I select a model, I could pick a model provider that I have, only show
|
||||
# the ones that are connected ... groups with those model providers at the top of the dropdown, and then we
|
||||
# could scroll down and look at our agents or type to search and select an agent"
|
||||
# Status 11-12: built (raea-feed primary-agents: src/chat/RunsOn.tsx; e2e "New chat runs on a provider",
|
||||
# "an agent is a provider on a model").
|
||||
When I open what a chat runs on, under New chat's box
|
||||
Then the AIs signed in on this Mac come first, Kimi first, each a group of its models; one that isn't signed in
|
||||
or isn't on this Mac isn't offered (Settings → Plugins connects it)
|
||||
And the person's agents come under them, each with its square mark and what it runs on
|
||||
And typing searches both, and Enter picks the first match
|
||||
And the pick is that chat's: the next New chat starts on the primary again
|
||||
|
||||
Rule: A2. raea ships no agent types
|
||||
# Status 11-12: the dev page's sample agents (Planner, Builder, Cutter, ...) are authors only too: they keep their
|
||||
# recorded sessions for the e2e suite, and no list offers them (raea-feed primary-agents, model/data.ts).
|
||||
# Status 11-09: built (raea-feed 601d4ae). No Director or Critic is made; the planner and critique post as raea
|
||||
# (raeaAgent, provider "raea"), tasks for it say @raea and an old brief's @director reads as raea. The built app's
|
||||
# sample world keeps its agents as `by` authors only (model/data.ts sampleAuthors); the dev page keeps them as
|
||||
@@ -139,3 +157,63 @@ Feature: Agents in the raea app: chats run on a provider, agents are optional te
|
||||
And the hooks hold inside the raea app too, which runs each ACP agent with its own shell and config
|
||||
And `raea show` names its poster from the harness that started it, found up its parent processes when the
|
||||
harness doesn't mark its shell, so Kimi, OpenCode and the rest post as themselves with an inbox per session
|
||||
|
||||
Rule: A6. One primary, and agents are providers with more on top
|
||||
# Shane 11-12: "in our docs we say like there's a director and the director owns everything. That's not really
|
||||
# true. All we have is a primary agent harness that runs in the global root of the workspace ... I could assign an
|
||||
# agent to be that level, that orchestrator or that like director, but it's really just a primary harness choice
|
||||
# or model choice." And: "the ability to create an agent that is something beyond calling the model harness ...
|
||||
# those agents ... are in fact just the model provider with all the same bells and whistles".
|
||||
# Status 11-12: built (raea-feed primary-agents). The primary is settings.chatOn + chatModel (chat/provider.ts
|
||||
# primaryOf); Settings → Agents sets it. Agents are kept as agents/<id>.json in the workspace's folder
|
||||
# (host/agents.ts, POST /host/agents) with launch.model.
|
||||
|
||||
Scenario: A6a. The primary runs the workspace
|
||||
Given Settings → Agents, whose first row is the primary, Kimi on its own default model until changed
|
||||
When I pick an AI's model or one of my agents there
|
||||
Then the workspace's own chats (New chat with no project, the Inbox's composer, the Controllers page's bar) run on
|
||||
it at the workspace's root, and so does every chat, feed message and task where nothing else is picked or named
|
||||
And no page calls it a Director: an agent made the primary is an orchestrator only because it's there
|
||||
|
||||
Scenario: A6b. An agent is a provider on a model, with its own name, instructions and tools
|
||||
When I make an agent in Settings → Agents (New agent)
|
||||
Then I pick what it runs on (Kimi, Claude, ChatGPT, Gemini, OpenCode, or a command of my own) and, for a provider,
|
||||
one of its models, beside its name, colour, instructions, tools and approvals
|
||||
And it's kept in the workspace's folder as agents/<id>.json, so it's there after a restart and travels with the
|
||||
workspace's repo
|
||||
And chats on it run its model with its instructions, as a chat on the bare provider would with none
|
||||
|
||||
Rule: A7. Each AI's own settings, for the AI and for an agent on it
|
||||
# Shane 11-12: "acp allows us to adjust provider/harness specific options?" and "selecting a harness for a custom
|
||||
# agent ... we would need the same settings and options once we select what we pick".
|
||||
# An ACP session reports its config options (session/new configOptions): each has a category (mode, model,
|
||||
# thought_level, model_config, or the AI's own) and is a select or a switch. Claude's: mode, model, effort, fast,
|
||||
# ultracode. Kimi's: model, thinking, mode. raea draws them as reported, so no AI needs code of its own.
|
||||
# Status 11-12: built (raea-feed primary-agents). Page: agent/AgentOptions.tsx, settings/AIOptions.tsx and the
|
||||
# agent editor; host: app-prefs providers (POST /host/onboard ai-prefs), host/acp/hub.ts optionsFor, bridge.ts
|
||||
# useOptions.
|
||||
|
||||
Scenario: A7a. An AI's defaults on this Mac
|
||||
Given Settings → Agents, whose Your AIs lists every AI signed in on this Mac, each saying what's set for it
|
||||
When I open an AI's Options
|
||||
Then I see every setting it reports but its model, grouped as Thinking, Mode and More, each on Default, which names
|
||||
the AI's own value
|
||||
And I can give it environment variables (NAME=value) and extra arguments to start with
|
||||
And what I save is kept on this Mac and reaches every chat on that AI started afterwards: the primary, a chat
|
||||
picked in New chat, and an agent on it that doesn't set its own
|
||||
|
||||
Scenario: A7b. An agent on an AI has the same settings
|
||||
When I pick what an agent runs on in its editor
|
||||
Then the same settings show for that AI, each on Default, which names the value I gave the AI ("Claude's: High")
|
||||
or else the AI's own
|
||||
And what I set is the agent's (launch.options, launch.env, launch.extraArgs), and picking another AI starts them
|
||||
over
|
||||
And a command of my own has no settings to show; only its environment is kept
|
||||
|
||||
Scenario: A7c. Settings layer, and one that no longer applies says so
|
||||
Given the AI's own default, then my defaults for the AI, then the agent's settings, then the chat's model
|
||||
When a session starts
|
||||
Then each setting is the last of those that sets it, applied with session/set_config_option
|
||||
And one the AI no longer reports, or a value it refuses, is skipped with a notice in the chat, never a failure
|
||||
And raea changes no mode for me: Approve everything (Settings → General) already answers the AI's permission asks,
|
||||
so its own bypass or yolo mode, or a plan-only mode, is on only if I pick it
|
||||
@@ -0,0 +1,340 @@
|
||||
Feature: Email: sign-in codes, invites, two-factor and notices, sent by raea-api through Resend
|
||||
Shane, 11-12: "build resend tooling for raea.io so that for collaborations and invites and other things we have a
|
||||
highly sophisticated build out of invite links, forgot passwords, 2fa etc."
|
||||
|
||||
What exists (11-12):
|
||||
- Accounts have no passwords. People sign in with GitHub (device and web flow, auth.ts, web.ts), Google (CN9) or
|
||||
Apple (CN10), and identities (0003) join them on a verified email onto users (0001: id, email). A web session and
|
||||
a computer are both device rows holding a hashed token (the web's cookie lasts 90 days). Email links were
|
||||
planned in CN10 and never built.
|
||||
- Team invites (account.ts, org_invites 0019) and project invites (collaborators.ts, project_collaborators, R5)
|
||||
reach only people who already have a raea account. Anyone else gets 404 no_user ("hasn't signed in to raea
|
||||
yet"). Nothing is emailed: the person finds the invite on raea.io/account or in the Library's Shared with you.
|
||||
- Review links (review.ts, R4) take guests' comments and approvals, and the owner sees them only in the app.
|
||||
- raea-api sends no email. hello@raea.io is a Cloudflare Email Routing forward.
|
||||
- Resend: the account has no domains (checked through its API on 11-12). The key Shane pasted on 11-12 has full
|
||||
access (it can list API keys).
|
||||
- raea.io's mail DNS (11-12): MX is Email Routing (route1-3.mx.cloudflare.net), SPF is
|
||||
"v=spf1 include:_spf.mx.cloudflare.net ~all", DMARC is "v=DMARC1; p=reject;". Because of p=reject, every mail
|
||||
raea sends must carry a DKIM signature aligned with raea.io, or Gmail and the rest drop it.
|
||||
- Resend's terms (11-12): Free sends 100 mails a day and 3,000 a month; Pro is $20 a month for 50,000, with no
|
||||
daily limit. The API takes 10 requests a second per team on every plan, shared by all its keys.
|
||||
|
||||
The approach: raea stays passwordless. "Forgot password" becomes "email me a code", which is the same email
|
||||
without a password table to protect. Two-factor is passkeys and authenticator apps on top of any way in. Invites go
|
||||
to an email address whether or not the person has an account yet. Every mail goes through one module in raea-api
|
||||
(src/mail/): templates in git drawn by its own small layout (EM2b), a send log, suppressions fed by Resend's
|
||||
webhooks, and a fake Resend for the tests. Shane, later on 11-12: "finish email work and make it fully live ... and
|
||||
we have a place to collect emails and build a proper email list, including any checkmarks we need to process to
|
||||
allow them to opt in or out at any time" (EM10).
|
||||
|
||||
Rule: EM0. Decisions (Shane, 11-12: "no passwords, and ill upgrade to pro. team only. but anyone who has review
|
||||
links like on pro can send emails to review something")
|
||||
Scenario: EM0a. No passwords
|
||||
Then raea keeps no passwords: a six-digit code or a link by email signs in, a passkey signs in with one touch,
|
||||
and there is no "Forgot password?" because there is nothing to forget
|
||||
And (why, for the record) passwords would mean a hash table to protect, reset by email, breach checks and
|
||||
lockouts, and Workers' WebCrypto caps PBKDF2 at 100,000 iterations (review.ts already hits this) against
|
||||
OWASP's 600,000 for SHA-256
|
||||
Scenario: EM0b. Resend Pro ($20 a month), done 11-12
|
||||
Then the Free plan's 100 a day runs out at about thirty sign-ins plus their invites, and a sign-in code refused
|
||||
at quota locks people out, so the account is on Pro before EM3 ships
|
||||
Scenario: EM0c. Keys (done 11-12)
|
||||
Then the full-access key from 11-12 is kept outside the repository for setup only (domains, webhooks, keys),
|
||||
and is rotated once setup is done, since it has been in a chat transcript
|
||||
And the Worker's key is sending-only and limited to raea.io; it is raea-api's RESEND_API_KEY. The list needs a
|
||||
second, full-access key (RESEND_CONTACTS_KEY), since a sending-only key can't touch contacts
|
||||
Scenario: EM0d. Team invites and project invites to people without an account: Team only
|
||||
Then Team accounts invite anyone by email; Pro and Free invite only people who already have an account, as today
|
||||
Scenario: EM0e. Review links by email: Pro and Team (EM5h)
|
||||
Then anyone who can make review links (Pro and Team, R4) can also email one to people to review it
|
||||
Scenario: EM0f. Two-factor for teams: optional, with a team setting to require it (EM4d)
|
||||
|
||||
Rule: EM1. Sending from raea.io, set up once
|
||||
Scenario: EM1a. raea.io is a Resend domain
|
||||
Then raea.io is added in Resend (region us-east-1) and its records go on Cloudflare: DKIM at
|
||||
resend._domainkey.raea.io, and the return path on send.raea.io (MX to Amazon SES's feedback host and
|
||||
"v=spf1 include:amazonses.com ~all"), exactly as Resend lists them
|
||||
And the root's MX, SPF and DMARC stay as they are: Email Routing keeps hello@raea.io, and DKIM (d=raea.io) aligns
|
||||
for p=reject
|
||||
And DMARC gains rua=mailto:dmarc@raea.io (an Email Routing address), so failing mail shows up in the reports
|
||||
And open and click tracking are off for the domain. Click tracking rewrites links, which breaks one-time links
|
||||
and puts a third party between people and raea's sign-in; open tracking is a pixel the privacy policy doesn't
|
||||
allow
|
||||
Scenario: EM1b. One sender
|
||||
Then every mail comes from "raea <[email protected]>", so a reply reaches a person through Email Routing
|
||||
And an invite never carries the inviter's address (review.ts already keeps owners' emails private)
|
||||
Scenario: EM1c. Apple's private relay delivers to people who signed in with Apple
|
||||
Then raea.io and send.raea.io are registered under Sign in with Apple for Email Communication on team
|
||||
BJJZ79J5NL (done 11-12; a domain covers every address at it, hello@raea.io included), and both pass Apple's
|
||||
SPF check there: send.raea.io is the envelope sender, and raea.io signs with DKIM
|
||||
And without that, every mail to a privaterelay.appleid.com or private.icloud.com address bounces
|
||||
And each relay address takes at most 100 mails a day (Apple's limit), which is far past raea's use
|
||||
Scenario: EM1d. Secrets
|
||||
Then RESEND_API_KEY (sending-only) and RESEND_WEBHOOK_SECRET are Worker secrets, and RESEND_API is a var that the
|
||||
tests point at the fake
|
||||
And without the key, routes that must send mail answer 503 mail_unavailable and every other route is unaffected
|
||||
|
||||
Rule: EM2. The mail module (raea-api src/mail/)
|
||||
Scenario: EM2a. One send()
|
||||
Then send(env, {to, kind, data, user?}) renders the kind's template and POSTs to Resend's /emails with an
|
||||
Idempotency-Key, so a retried request never sends twice, a tag naming the kind, and a row in mail_log
|
||||
And a 429 rate answer is retried after its retry-after, up to three times; a quota 429 or a 5xx is a failure the
|
||||
caller sees: sign-in and security mail answer 503 "We couldn't send the email. Try again in a minute", and
|
||||
notices wait for the next cron
|
||||
And batches (digests, reminders) go out from the hourly cron at under 8 a second, inside Resend's 10 a second
|
||||
shared by every key
|
||||
And it uses fetch, as the rest of raea-api does, rather than Resend's Node SDK
|
||||
Scenario: EM2b. Templates in git
|
||||
Then each kind is a function in src/mail/templates.ts that returns a subject and a list of blocks (heading,
|
||||
paragraph, button, code, note); src/mail/layout.ts draws the blocks as table-based HTML (one layout that
|
||||
matches raea.io: the lockup, black, hairlines; it reads in light and dark mail clients) and as the plain-text
|
||||
part, so the two never disagree. Every value is HTML-escaped there
|
||||
And not React Email (checked 11-12): its component packages (@react-email/components and each @react-email/*)
|
||||
are deprecated, folded into the `react-email` CLI package, which brings Tailwind, Babel, socket.io and esbuild
|
||||
with it. One layout of raea's own is smaller than that
|
||||
And every link is absolute to raea.io, test/mail-preview.sh writes each kind to an HTML file to look at, and the
|
||||
copy is checked by copymatter
|
||||
And the kinds: sign_in, email_change, email_changed, invite_team, invite_project, invite_reminder,
|
||||
invite_answered, review_request, security_sign_in, security_factor, security_recovery, review_digest,
|
||||
review_approved,
|
||||
welcome, storage_limit, access_ended, account_deleted
|
||||
Scenario: EM2c. A log, suppressions and Resend's webhooks
|
||||
Then mail_log keeps (id, user_id, to_sha256, to_domain, kind, resend_id, status, created_at, updated_at): no
|
||||
bodies and no address in the clear, enough for support to answer "did my code go out?", pruned after 90 days
|
||||
And POST /hooks/resend checks the Svix signature (svix-id, svix-timestamp, svix-signature, five minutes' leeway)
|
||||
and moves the status: delivered, delivery_delayed, bounced, complained
|
||||
And a hard bounce suppresses the address; a complaint suppresses everything except security mail
|
||||
And send() skips suppressed addresses, and raea.io/account shows "We can't reach you at a•••@x.com" with a fix
|
||||
Scenario: EM2d. Preferences and one-click unsubscribe
|
||||
Then mail falls in categories: security (always on), invites, activity (review comments, people joining) and
|
||||
product news (off unless ticked; Resend Broadcasts, later)
|
||||
And every mail outside security carries List-Unsubscribe with a one-click POST URL (RFC 8058) and a footer link;
|
||||
its token is an HMAC of the address and category, so unsubscribing needs no sign-in
|
||||
And someone without an account who gets an invite can choose "Don't send me raea invites" (invite_blocks keeps
|
||||
the address's SHA-256)
|
||||
|
||||
Rule: EM3. Signing in by email (CN10's email links), and getting back in
|
||||
Scenario: EM3a. One mail holds a code and a link
|
||||
When someone types their email on raea.io's sign-in (a fourth way, under GitHub, Google and Apple) or on the
|
||||
link page a computer opens (OB-L)
|
||||
Then POST /auth/email/start {email, return?} gives the same {sent} answer whether or not the address has an
|
||||
account, so nobody can test which addresses are raea's
|
||||
And the mail holds a six-digit code and a link, each good once and for 10 minutes; only HMACs of both are stored
|
||||
And the code works only in the browser that asked (a short HttpOnly cookie carries the request's nonce), and the
|
||||
request dies after five wrong codes; codes compare in constant time
|
||||
And opening the link never spends it: mail scanners (Outlook Safe Links, Mimecast, Proofpoint) open every link,
|
||||
so the page asks for one press, which POSTs
|
||||
And an address gets 5 requests an hour and 20 a day, OPEN_LIMIT throttles by IP, and MAIL_DAILY is a ceiling
|
||||
across everyone that guards the bill (as CHECKS_DAILY_USD does)
|
||||
Scenario: EM3b. Who it signs in
|
||||
Then identityUser(env, "email", address, null, () => address) finds the user with that email (owning the
|
||||
mailbox proves it) or makes one unless SIGNUPS_CLOSED, and a computer gets its token through the link code as
|
||||
with Google and Apple
|
||||
And with two-factor on, the code is the first step only (EM4b)
|
||||
Scenario: EM3c. "Can't sign in?" replaces "Forgot password?"
|
||||
Then someone who lost their GitHub, Google or Apple account signs in with a code sent to the account's email
|
||||
And accounts whose email can't take mail (GitHub's users.noreply.github.com fallback in auth.ts) are asked on
|
||||
raea.io/account to add a reachable address, verified by code, before they need it; count them at rollout
|
||||
Scenario: EM3d. Changing the account's email
|
||||
Then the new address is verified by a code, after step-up (EM4c)
|
||||
And the old address is told "Your raea email is now n•••@y.com", with "This wasn't me" good for 7 days, which
|
||||
puts the old address back and signs out every device
|
||||
Scenario: EM3e. Lost both the mailbox and the second factor
|
||||
Then hello@raea.io handles it by hand, from a computer still signed in or the account's Stripe details
|
||||
And a recovery takes 7 days, with a mail to the address on file each day, so nobody takes an account quietly
|
||||
|
||||
Rule: EM4. Two-factor and step-up
|
||||
Scenario: EM4a. The factors
|
||||
Then passkeys (WebAuthn, RP ID raea.io, so raea.io and app.raea.io share them), authenticator apps (TOTP per
|
||||
RFC 6238: SHA-1, 30 s, one step either side, a used step never accepted twice, the secret sealed with
|
||||
TOKEN_KEY by connect/crypt.ts), and 10 recovery codes shown once and stored hashed
|
||||
And no SMS: SIM swaps, cost, and carriers' filtering
|
||||
And a passkey can be the whole sign-in ("Sign in with a passkey", a discoverable credential), counting as both
|
||||
factors
|
||||
And check @simplewebauthn/server in workerd before choosing it; the fallback is verifying ES256 and RS256
|
||||
assertions with WebCrypto directly
|
||||
Scenario: EM4b. Where the second step is asked
|
||||
Then after any first step (GitHub, Google, Apple, an email code), on raea.io and on the link page a computer
|
||||
opens; the device row and its token are made only after the second step
|
||||
And a token keeps working until it expires or is revoked, so two-factor is asked at sign-in, not per request
|
||||
Scenario: EM4c. Step-up for what can't be undone
|
||||
Then changing the email, removing a factor or turning two-factor off, new recovery codes, deleting the account,
|
||||
making an agent key (agent-keys.ts), and removing a team member ask for a fresh factor (a passkey, TOTP, or an
|
||||
email code when two-factor is off) within the last 10 minutes, kept as step_up_at on the device row
|
||||
Scenario: EM4d. A team can require two-factor
|
||||
Then a team admin's require_2fa gives members without it 7 days with a banner and a mail, after which the team's
|
||||
storage (Git LFS, libraries) answers 403 2fa_required until they add one
|
||||
Scenario: EM4e. Security mail
|
||||
Then a new sign-in (the device's name, city and country from Cloudflare's request.cf, the time, and "Not you?"
|
||||
leading to Sign out everywhere), a factor added or removed, a recovery code used and an email changed each
|
||||
send a mail
|
||||
And security mail ignores preferences; only a hard bounce stops it
|
||||
|
||||
Rule: EM5. Invites by email, with or without an account
|
||||
Scenario: EM5a. Invite anyone by email, to a team or a project
|
||||
When a team admin (account.ts) or a project's owner on Team (collaborators.ts) types an email with no account
|
||||
Then raea-api keeps an email invite (email_invites: id, kind, org_id or owner and repo, email, invited_by,
|
||||
token_sha256, created_at, expires_at, reminded_at), counted in TEAM_MEMBERS or COLLABORATORS_MAX like today's,
|
||||
and mails it
|
||||
And on Accept it becomes an org_invites or project_collaborators row for the person who accepted and is
|
||||
answered at once, so the existing accept, headcount and access paths stay as they are
|
||||
And someone who already has an account gets the same mail beside the in-app invite, and 404 no_user goes away
|
||||
Scenario: EM5b. The invite's mail and page
|
||||
Then the mail says "<the inviter's GitHub login or name> invited you to <team or project> on raea", what that
|
||||
means in one line (a team: the team's plan covers you; a project: you work in it from your own raea, and its
|
||||
storage is the owner's), when it expires, and an Accept button to raea.io/invite/<token>
|
||||
And the page shows who and what; signed out, it offers the four ways in with the email filled; then Accept or
|
||||
Decline, never on a GET
|
||||
And the token is 128 bits, stored as a SHA-256, and good once
|
||||
Scenario: EM5c. Accepting with another address
|
||||
Then accepting while signed in under another address asks "This invite went to a•••@x.com. Join as b@y.com?",
|
||||
and the inviter sees who joined
|
||||
And a team admin can lock the team's invites to the exact address
|
||||
Scenario: EM5d. Reminders, expiry, taking back, sending again
|
||||
Then an invite left unanswered gets one reminder at 3 days and expires at 14, which frees its place
|
||||
And the inviter can send it again once a day; taking it back makes the link 404 at once, as review links do
|
||||
And the inviter gets a mail when it is accepted or declined (activity)
|
||||
Scenario: EM5e. Invite links, with no email
|
||||
Then a team admin makes raea.io/join/<token> with a number of uses (at most the free seats), an expiry (at most
|
||||
30 days), an optional email domain (only @agency.com addresses join; anyone else asks the admin), and
|
||||
"Approve each" on or off; it can be revoked, and every join is mailed to the admins
|
||||
And projects have no invite links: a project spends its owner's storage, so each collaborator is named
|
||||
Scenario: EM5f. Abuse
|
||||
Then only Team accounts invite people without accounts into a team or project (EM0d), at most 20 such invites a
|
||||
day within the existing 100, and 5 an hour to one domain; review requests have their own limits (EM5h)
|
||||
And an invite carries no free text from the inviter (later: up to 280 characters, plain, no links, from
|
||||
accounts older than 7 days)
|
||||
And a complaint on an invite stops that account's invites to people without accounts until the admin agent
|
||||
(admin.raea.io) or Shane looks
|
||||
Scenario: EM5g. Project invites and GitHub
|
||||
Then a project's history is on GitHub (R5a), so someone who joined by email without GitHub is asked to connect it
|
||||
when they Open in raea, and the owner's app sends GitHub's repo invite then rather than at invite time
|
||||
Scenario: EM5h. Send a review link by email (Pro and Team)
|
||||
When the owner of a review link (R4), or their agent with the "share" scope, adds email addresses in the Share
|
||||
panel or calls POST /v1/review-links/:id/send {to: [emails], note?}
|
||||
Then each address gets "<the owner's GitHub login or name> sent you <title> to review", a still of the current
|
||||
version, when the link expires, and a Review button to raea.io/r/<token>; a link with a password says so and
|
||||
never carries the password
|
||||
And each recipient's mail carries their own ?by= tag, so the page fills their name and the owner sees who
|
||||
watched, commented and approved; a recipient needs no account
|
||||
And a new version on the link (R4d) offers "Tell reviewers" to the same people, never sent on its own
|
||||
And the limits: 25 addresses a send, 100 recipients a day for Pro and 300 for Team, a link's sends counted in its
|
||||
own row, suppressions and "Don't send me raea review requests" honoured, and a complaint pauses the account's
|
||||
sends until the admin agent or Shane looks
|
||||
And the note is plain text, up to 280 characters, with links shown as text, from accounts older than 7 days
|
||||
|
||||
Scenario: EM5i. Status (11-12)
|
||||
Then built and live: EM5a for teams (email_invites, D1 0045; src/mail/invites.ts), EM5b (the page is
|
||||
raea.io/account/?invite=<token>, beside ?signin=), EM5c's "Join as" notice, EM5d (reminder at 3 days, expiry
|
||||
at 14, take back, send again once a day, the inviter mailed on accept or decline), EM5f's Team-only rule and
|
||||
its limits (20 a day, 5 an hour to one domain), and EM5h's route, POST /v1/review-links/:id/send
|
||||
And raea.io's invite page, sign-in banner and the Team page's invites by email are live, and the app's Share
|
||||
panel sends a live link by email (EM5h's field, raea-feed PR #4: up to 25 addresses and a note, never an
|
||||
agent's to send)
|
||||
And not built yet: project invites by email (EM5a's project half, with EM5g), locking a team's invites to the
|
||||
exact address (EM5c), invite links (EM5e), pausing invites after a complaint (EM5f), and for EM5h the still,
|
||||
per-recipient ?by= tags and "Tell reviewers"
|
||||
And tests: test/invites.sh (offline, 11 checks), test/mail-web.sh's invite path in Chrome, and the app's
|
||||
host/share.test.ts, src/share/share.test.ts and e2e/share-email.spec.ts
|
||||
|
||||
Rule: EM6. Activity mail (after EM5)
|
||||
Scenario: EM6a. Review links as a digest
|
||||
Then comments on a person's review links come as one digest per link at most every 15 minutes, and an approval
|
||||
comes at once
|
||||
And a reviewer without an account can leave an email to hear of new versions and replies; it is confirmed by a
|
||||
code first and leaves with one click
|
||||
Scenario: EM6b. Reply by email (later)
|
||||
Then a digest's Reply-To is a per-thread address (r+<HMAC>@reply.raea.io) received by Resend's inbound on
|
||||
reply.raea.io (the root's MX stays with Email Routing), posted as the owner's comment once the sender matches,
|
||||
with the quoted text stripped
|
||||
And each received mail counts against Resend's monthly quota
|
||||
Scenario: EM6c. Account and plan notices
|
||||
Then one welcome mail (no drip), storage at 80% and 100% of the allowance, a plan ending that cut off a team's
|
||||
or collaborators' access, and the account deleted
|
||||
And Stripe and Link send receipts and failed payments; raea doesn't repeat them
|
||||
|
||||
Rule: EM7. Privacy and law
|
||||
Scenario: EM7a. The privacy policy names Resend
|
||||
Then /privacy/'s processors (legal.ts, beside Cloudflare) add that Resend sends raea's email and sees each
|
||||
address and message, and Resend's DPA is accepted in its dashboard. Done 11-12: the processors list and a new
|
||||
Email section (/privacy/#mail) saying what's sent, the consent kept for raea news and how to stop each kind
|
||||
And an invited person's address is kept only while the invite lives; an opt-out keeps only its SHA-256
|
||||
And mail has no tracking pixels and no rewritten links
|
||||
Scenario: EM7b. Product news
|
||||
Then product news goes only to people who ticked it (EM10), through Resend Broadcasts, with Shinyobjectz LLC's
|
||||
postal address in the footer (CAN-SPAM); the D1 raea-waitlist is not mailed news without that consent
|
||||
And an issue starts as a Resend draft made by raea-api's news-draft.mts from a short Markdown file: raea's mail
|
||||
layout, the raea news segment and topic, from hello@raea.io (replies reach the team through Email Routing),
|
||||
Resend's per-recipient unsubscribe link and the postal address in the footer; it is read, tested and sent from
|
||||
Resend's dashboard. The first draft waits there (11-12)
|
||||
|
||||
Rule: EM8. Tests, cheapest first
|
||||
Scenario: EM8a. Offline against a fake Resend
|
||||
Then test/fake-resend.mts (like fake-github.mts) records each POST /emails, can be told to answer 429 or 500,
|
||||
and signs webhooks with a test secret
|
||||
And test/mail.sh covers: an email sign-in (start, the code read from the fake, five wrong codes end it, a GET of
|
||||
the link doesn't spend it, the press signs in), the same answer for an unknown address, two-factor (a TOTP
|
||||
code computed in the test, a recovery code, step-up expiring), invites (a person with no account invited,
|
||||
signing up through the link, accepted, the headcount, taken back to 404, the 3-day reminder and the expiry on
|
||||
a clock override), suppression (a bounce webhook, then a notice skipped and security mail still sent), and
|
||||
one-click unsubscribe
|
||||
And test/auth.sh, apple.sh, connections.sh and account.sh still pass
|
||||
Scenario: EM8b. Live, after EM1 (cents)
|
||||
Then production sends to Resend's test addresses delivered@resend.dev, bounced@resend.dev and
|
||||
complained@resend.dev, and the webhooks land
|
||||
And one real mail each to Gmail, Outlook and an Apple relay address shows DKIM pass and reads in light and dark
|
||||
Scenario: EM8c. The pages
|
||||
Then the sign-in's email field, /invite/, /join/ and the account's Security tab pass the site's headless page
|
||||
checks at desktop and phone width, in both themes
|
||||
|
||||
Rule: EM9. Order of work
|
||||
Scenario: EM9a. Steps
|
||||
Then 1. EM1's setup. Done 11-12: raea.io added to Resend (domain 961880ce, us-east-1, tracking off), the
|
||||
Worker's sending key and a contacts key made, the four DNS records added through Cloudflare's dashboard in
|
||||
Shane's browser, and the domain verified; a test mail from hello@raea.io delivered. Resend is on Pro and
|
||||
Apple's relay sources are registered (both 11-12)
|
||||
And 2. EM2, the module, the fake, the log, suppressions and the webhook, in D1 migration 0044 onward
|
||||
And 3. EM3, email sign-in, finishing CN10. It comes first because it gives every account a way back in
|
||||
And 4. EM5, invites by email, invite links and review links by email (EM5h): the collaboration ask
|
||||
And 5. EM4, two-factor, step-up and security mail
|
||||
And 6. EM6 and EM7b; EM6b's reply by email last
|
||||
And EM10, the list, went with EM3 (11-12), since the site's sign-up and the account's switches need only EM2
|
||||
And each API deploy goes from private HEAD with Shane's go, as review-api deploys do
|
||||
|
||||
Rule: EM10. raea news, the list (11-12)
|
||||
Background:
|
||||
Given the list is D1's mail_list (0044), one row per address: pending, subscribed or unsubscribed, the exact
|
||||
words the person agreed to, where (site, account, or Resend's own page) and their country, and when they asked,
|
||||
confirmed and unsubscribed. That row is the consent record
|
||||
And Resend holds the same list as contacts on the "raea news" topic (opt-out by default, public, so Resend's
|
||||
unsubscribe page shows it) and segment, written through by src/mail/list.ts with a full-access key
|
||||
(RESEND_CONTACTS_KEY; the sending key can't touch contacts). Broadcasts go to that segment and topic
|
||||
Scenario: EM10a. Nobody is on it without asking
|
||||
Then the box by the sign-up is never ticked for anyone, and raea-api refuses a sign-up without consent: true
|
||||
(400 consent_required)
|
||||
And the words by the box are list.ts CONSENT, kept with each row: "Send me raea news: new releases and what's
|
||||
new, about once a month. I can unsubscribe at any time."
|
||||
And the GitHub-noreply address of an account is never put on it (it reads no mail)
|
||||
Scenario: EM10b. The site's sign-up confirms by mail (double opt-in)
|
||||
When someone enters an address and ticks the box in raea.io's footer (news-signup.tsx)
|
||||
Then raea-api answers the same whatever the address, keeps a pending row, and mails a confirmation (at most 3 a
|
||||
day to one address); the address goes on the list, and to Resend, only when that mail's button is pressed
|
||||
(GET /mail/confirm shows the button, POST confirms, so a mail scanner opening the link does nothing)
|
||||
And a pending row is deleted after 7 days by the cron
|
||||
Scenario: EM10c. The account's switches
|
||||
Then the Overview's Email card (email-prefs.tsx) shows raea news (off until turned on, with CONSENT's words),
|
||||
invites, review requests and activity (on, each can be turned off), and sign-in and security (always on,
|
||||
locked), saved as each changes through GET/PUT /v1/mail/prefs
|
||||
And a signed-in person turning news on needs no confirming mail: the address is the account's own
|
||||
And an address raea can't mail (GitHub's private one, or one that bounced) says so and locks the switches
|
||||
Scenario: EM10d. Out at any time, from anywhere
|
||||
Then turning it off in the account, Resend's unsubscribe link in a broadcast ({{{RESEND_UNSUBSCRIBE_URL}}}) and
|
||||
Resend's dashboard all end in the same row: the account writes through to Resend, and Resend's
|
||||
contact.updated and contact.topics.updated webhooks write back to D1 (never back to Resend again)
|
||||
And an address that unsubscribed stays unsubscribed until that person turns it on again themselves
|
||||
And if Resend is down when a change is made, D1 keeps it and the hourly cron writes it through (synced_at)
|
||||
Scenario: EM10e. Tests
|
||||
Then test/mail.sh covers double opt-in, Resend's unsubscribe writing back, the account's prefs and an outage
|
||||
caught up by the cron; test/mail-web.sh covers the footer's sign-up, signing in with an emailed code and the
|
||||
Email card in Chrome at desktop and phone widths
|
||||
@@ -0,0 +1,129 @@
|
||||
@spec
|
||||
Feature: Feed tasks: the graph view's layering, the to-do list, and sessions started outside the app
|
||||
Shane, 2026-11-13: "note to ship with this next batch for release is that in the react graph view when i zoom in it
|
||||
ends up obstructing other buttons and gui outside of the stage and across the app, so we need to make sure layering
|
||||
works there and remove the agents button in the top right of feed and inbox for a checkbox and this is a editable
|
||||
todolist built to look minimal, skimmable and easy to read with the ability to click into a task to see more
|
||||
details. the other note to add is in the timeline if an agent is currently running even if i have initiated the
|
||||
session myself in terminal or an app and it is still claimed or working on it without being terminated, meaning its
|
||||
still open or the session is active, we should see it in the feed and see updates from it. this should help tie
|
||||
into the todolist stuff too."
|
||||
|
||||
Three parts. Each is done when it works in raea's window (not only in Chrome) and has its tests.
|
||||
|
||||
Background:
|
||||
Given the app's code is apps/app (raea-feed); its branch for parts 2 and 3 is feed-tasks, part 1 is on its main
|
||||
And a window check is a headless raea window of the session's own: `node blitz/pw-run.mjs SPEC` on the BLITZ_E2E
|
||||
bundle, RAEA_PAGE_HOST_BIN a copy of the page host, a fresh raea.root each run
|
||||
|
||||
Rule: FT1. The graph view stays in its own box
|
||||
# Status 11-13: built, in 0.1.3. Engine 37846080a (vendor/blitz-dom/src/node/node.rs, sdk/ui/src/dom/input.ts, a unit test
|
||||
# in sdk/ui/test/dom.test.tsx); app raea-feed #11 (AskCanvas clipped at its box, e2e/canvas-layer.spec.ts).
|
||||
# Cause: Chrome never showed it. In raea's window the canvas was DRAWN clipped, but neither hit test honoured an
|
||||
# overflow clip: blitz-dom's hit_inner tested a clipping box's children wherever they overflowed to, and sdk/ui's
|
||||
# hit dropped the inherited clip at a child with its own z-index and replaced it at a child that clips (a card is
|
||||
# overflow-hidden). Both halves are needed: with only sdk/ui fixed, elementFromPoint is right and a real press
|
||||
# still lands on the canvas (the host's target wins). Checked: the spec in Chrome and in the window; the app's
|
||||
# whole window smoke 28 passed, 49 failed, 4 skipped of 81 before and after, the same tests; sdk/ui 60 tests.
|
||||
# Not read by the hit tests: a transform on a box between a z-indexed child and its stacking-context root (the
|
||||
# painter's clips don't read it either); in sdk/ui, an absolute box whose containing block is above the clipper.
|
||||
|
||||
@done
|
||||
Scenario: FT1a. A press outside the canvas never reaches it, at any zoom
|
||||
Given an ask with four pictures open on its canvas (React Flow), zoomed all the way in (scale 2)
|
||||
Then no point outside the canvas's box finds a piece of the canvas (document.elementFromPoint)
|
||||
And a press on the sidebar, the workspace picker or the header goes to what is drawn there
|
||||
And the canvas clips what it draws at its own box
|
||||
|
||||
@done
|
||||
Scenario: FT1b. A box that clips takes no pointer for what it cuts away, anywhere in the window
|
||||
Given a box with overflow other than visible, and a child that overflows it, with or without its own z-index
|
||||
Then a point outside the box's padding box never hits the child or anything in it
|
||||
But a fixed box, and a box whose containing blocks are above the clipping box, are not cut by it
|
||||
|
||||
Rule: FT2. The agents button is a checkbox that opens the to-do list
|
||||
# Status 11-13: built, in 0.1.3: raea-feed #12, merged ab68f0d (3b2353b, a2dc439). src/feed/todo.ts (the rows),
|
||||
# src/feed/TodoPanel.tsx, brief/format.ts removeTask and moveTask. The Agents panel and its menu surface are gone.
|
||||
# Checked: e2e/todo.spec.ts 4 of 4 in Chrome and 4 of 4 in the window; vitest (todo.test.ts, format.test.ts).
|
||||
# Decisions made here, each open to Shane's word:
|
||||
# - It is the tasks the app already has, not a second list: the project's brief's tasks (## Tasks in brief.md:
|
||||
# what the composer, the Board and agents write) and the edits sent on its items (comment tasks). Nothing is
|
||||
# kept by the list.
|
||||
# - Words are changed in a task's details (one click away, in the same column), not in the list's line: a click
|
||||
# on a line opens it, so the line itself stays a single target.
|
||||
# - A task's comments: an edit's replies; a brief task's are its linked item's open comments. A brief's task has
|
||||
# nowhere of its own to keep a comment yet.
|
||||
# - In the Inbox a new task goes to the project picked beside the line (the first, until picked).
|
||||
# - Reorder is within a project's brief tasks; an edit keeps its place by when it was sent.
|
||||
# Left: no keyboard shortcut opens the list; the Board's card sheet still edits a task's agents, due date and tags.
|
||||
|
||||
@done
|
||||
Scenario: FT2a. Where the agents button was, in a feed and in the Inbox
|
||||
Then a feed's header has no agents button; a checkbox there opens the to-do list in a column on the right
|
||||
And in a project's feed it is the project's list; in the Inbox the workspace's, each project's tasks under its name
|
||||
And its tooltip says what it is; the column closes from its own button and is as it was left next time
|
||||
|
||||
@done
|
||||
Scenario: FT2b. Minimal, skimmable
|
||||
Then a task is one line: a checkbox, its words, and who has it when someone does
|
||||
And its handle and Remove show only on the line pointed at or focused
|
||||
And done tasks are folded away under a count ("2 done"), opened by a click
|
||||
|
||||
@done
|
||||
Scenario: FT2c. Edited where it is read, written at once, with Undo
|
||||
When I type a line and press Enter, check a task off, change its words, drag it by its handle (or Alt+Up/Down),
|
||||
or remove it
|
||||
Then the change is written at once to where the task lives (the brief; a linked item's status; the comment)
|
||||
And Undo at the column's foot, or Cmd+Z, takes the last change back
|
||||
But a brief's change is undone only while the brief is still as that change left it
|
||||
|
||||
@done
|
||||
Scenario: FT2d. A click opens a task's details; Esc goes back
|
||||
Then the details show its words, who is on it and what they last did, the feed item it is linked to, its comments
|
||||
And an agent at work on it in one of the app's own sessions can be stopped there, with its subagents listed
|
||||
And Esc goes back to the list, not out of the feed
|
||||
|
||||
Rule: FT3. A session started outside the app is in the feed while it is open
|
||||
# Status 11-13: built, in 0.1.3: raea-feed #12, merged ab68f0d (7e90a7c, a2dc439). host/outside.ts (POST
|
||||
# /host/outside), src/feed/outside.ts, OutsideKeeper.tsx, OutsideBubble.tsx. No feed tool was added or changed.
|
||||
# Checked: e2e/outside.spec.ts 2 of 2 in Chrome and in the window (the host's list given by the spec);
|
||||
# host/outside.test.ts on files written as Claude Code writes them; the reader run against this Mac's six real
|
||||
# sessions. Not checked: a real session ending while the app's own window is watched by a person.
|
||||
# The signal, the smallest honest one: what the harness already keeps. Nothing new is asked of any session.
|
||||
# - Claude Code keeps ~/.claude/sessions/<pid>.json for each open session ({pid, sessionId, cwd, name, status})
|
||||
# and its transcript, <sessionId>.jsonl in its projects folder.
|
||||
# - active: its file is there, its process is alive, and a person runs it (kind "interactive"). Holding a claim
|
||||
# alone is not active: a task a session has that has ended still names it, without a live mark.
|
||||
# - working: the file says "busy"; otherwise it is open and waiting at its prompt.
|
||||
# - an update: its last words, the tool call at hand, its plan (the last TodoWrite), read from the transcript's
|
||||
# end; an item it posts and a task it marks are already in the feed and on the task.
|
||||
# - ended: the host no longer lists it.
|
||||
# Left: Codex, Gemini, Kimi and the rest keep no file that says a session is open, so they are in the feed only
|
||||
# by what they post; a session working in a folder that is no project's and that has posted nothing is in no
|
||||
# feed (Shane's own lanes in ~/raea are this case until they `raea show` something); rask claims and the lanes
|
||||
# board are not read.
|
||||
|
||||
@done
|
||||
Scenario: FT3a. One bubble a session, in the projects it is in
|
||||
Given a Claude Code session open on this Mac
|
||||
Then it has one bubble in the feed of each project whose folder it works in or that it has posted to
|
||||
(its posts carry its inbox, claude-code-<the first 8 of its id>, as `raea show` names it), and in the Inbox
|
||||
And a session that is in no project's folder and has posted nothing is in no feed
|
||||
|
||||
@done
|
||||
Scenario: FT3b. It reads as the app's own sessions do, without a Stop
|
||||
Then the bubble says its name and harness, that it is working (and for how long) or waiting at its prompt,
|
||||
the step at hand, its last words, and its plan
|
||||
And there is no Stop: a mark beside its status says where it runs and that it is stopped there
|
||||
|
||||
@done
|
||||
Scenario: FT3c. Its updates come as it goes, and it ends when the session does
|
||||
When it says something new or starts another step
|
||||
Then the same bubble shows it within a few seconds, written only when what it shows has changed
|
||||
When the session is no longer open
|
||||
Then the bubble ends, its last words kept; a session that comes back opens it again
|
||||
|
||||
@done
|
||||
Scenario: FT3d. It ties to the to-do list
|
||||
Then a brief's task that @names the session, and an edit on an item it posted, are its tasks
|
||||
And the bubble names them, and the to-do list shows the session on them with what it last did
|
||||
@@ -0,0 +1,723 @@
|
||||
@spec
|
||||
Feature: Fingerprint: a person's or a team's sense of good work, learned on their own device from their own notes
|
||||
Shane, 2026-11-12: "build a framework within raea called Fingerprint ... some kind of taxonomy data structure and an
|
||||
embedding model that can run on a personal device that could be easily trained on device to best understand if a
|
||||
video, both its audio and video and whatever else we can put together into this ... is good or not ... train through
|
||||
all these comments or notes or through post mortem process that the agent can run ... and if you have a team, you can
|
||||
distribute those embedding models." The plan, its measurements and the reference design (earshot,
|
||||
github.com/Leonxlnx/earshot, MIT: its methods, not its code): docs/fingerprint.md.
|
||||
|
||||
The model this file sets:
|
||||
1. A fingerprint is a taxonomy of axes, one small head per axis over frozen, pinned on-device encoders, a person's
|
||||
weighting over the axes, and the evidence the heads learned from. Encoders are not fine-tuned until an axis is
|
||||
measured stuck (FP10).
|
||||
2. Everything trains on the device in milliseconds, after every new label. Nothing leaves the device unless the
|
||||
person shares the fingerprint, and then it's evidence (embeddings and labels), never media.
|
||||
3. A note is not a label until it's read into one: its axis, polarity, span and layer. Creative directions go to
|
||||
the brief, never into a head.
|
||||
4. Every score is held out by project before it's trusted, and every axis has cheats that must still be caught.
|
||||
5. Agents get the axis and the moment, never the number.
|
||||
|
||||
Background:
|
||||
Given the spike of 11-12 (~/films/fingerprint-spike: Python in a scratch venv, not repo code): Shane's 205 pinned
|
||||
notes on 17 feed renders (Stay assemblies 18-23, the launch film's passes b-l), the five golden references and
|
||||
11 other renders, 33 videos and 34 minutes
|
||||
And the encoders on disk: SigLIP 2 base p16-224 and YAMNet (~/.local/share/raea-models), EmbeddingGemma 2 q8
|
||||
(~/.raea/models, the Library's model through apps/app host/library/embed.ts), CLAP htsat-unfused (Xenova's
|
||||
ONNX, fp32: audio 117 MB, text 502 MB; q8 copies at 34 MB and 127 MB are off by default)
|
||||
And every encoder runs locally on consumer hardware or isn't used (Shane, 11-12, dropping PE-AV: "if it cant run
|
||||
locally on consumer hardware its not usable"); the smallest PE-AV is a ViT-L/14 at 336 px per frame, 3.4 GB
|
||||
And Rust goes through the lanes' build rules, new code in small files and a small crate (systems/fingerprint),
|
||||
repo scripts in bash, any heavy maths a Rust subcommand
|
||||
|
||||
Rule: FP0. Measure before building (the spike)
|
||||
@done
|
||||
Scenario: FP0a. Notes alone don't say where the next note goes
|
||||
Then 11-12, on the 9 renders with 8 or more notes (197 noted 2 s windows, 263 windows 3 s or more from any note),
|
||||
a logistic head ranks noted above un-noted at AUC 0.64 on SigLIP 2 held out by video, and 0.40 held out by
|
||||
film; YAMNet 0.54 / 0.46, all of them together 0.55 / 0.42, cheap columns 0.53 / 0.51, position 0.41 / 0.40;
|
||||
EmbeddingGemma 2's picture, sound and both 0.65 / 0.38, 0.66 / 0.47, 0.64 / 0.53 (2.3 s a window on the CPU)
|
||||
And the kind of note (10 axes read from its words) is predicted from its window 0.150 of the time, against 0.130
|
||||
for the commonest kind
|
||||
And the reason is in the notes: of 205, about 98 name a defect, about 74 are directions (23 are both), and 3 are
|
||||
approvals; one note every 3-4 s of film; a noted moment is noted again within 1 s in the next version 0.25-0.62
|
||||
of the time, against 0.26-0.45 for any moment; 21 of 143 noted moments make a version pair, too few to score
|
||||
|
||||
@done
|
||||
Scenario: FP0b. A named axis is learned from 4 to 32 examples
|
||||
Then 11-12, defects put into 270 windows of 27 real renders, held out by source, on standardised features of the
|
||||
axis's own modality (AUC at 4 / 16 / 32 labelled windows a class):
|
||||
| axis | features | k=4 | k=16 | k=32 |
|
||||
| blur | picture | 1.00 | 1.00 | 1.00 |
|
||||
| dark | picture | 0.72 | 0.90 | 0.95 |
|
||||
| glow | picture | 0.55 | 0.69 | 0.80 |
|
||||
| flash | change | 0.97 | 0.97 | 0.97 |
|
||||
| freeze | change | 1.00 | 1.00 | 1.00 |
|
||||
| noise | sound | 0.99 | 1.00 | 1.00 |
|
||||
| dropout | sound | 0.79 | 0.94 | 0.97 |
|
||||
| clip | sound | 0.91 | 0.97 | 0.98 |
|
||||
And without standardising, SigLIP hides behind YAMNet's larger values (blur 0.75 at 32); with both modalities
|
||||
a head is worse at small k (blur 0.97, dropout 0.68 at 4)
|
||||
|
||||
@done
|
||||
Scenario: FP0c. Taxonomy first, then a person's weighting
|
||||
Then 11-12, eight shared axis heads and a person's 9 weights over their scores, from 32 of that person's labels,
|
||||
give AUC 0.84, 0.73 and 0.95 for three made-up tastes, against 0.73 and 0.64 for one head straight on the
|
||||
embeddings from the same labels
|
||||
And two opposed tastes stay apart: each head ranks the other person's labels at 0.38 and 0.39
|
||||
And three teammates' 16 labels each: one alone 0.66, heads averaged 0.74, evidence pooled and retrained 0.76
|
||||
|
||||
@done
|
||||
Scenario: FP0d. Cost and cheats
|
||||
Then a head fits in 3.9 ms on 32 windows and 81 ms on 2,430, scores 2,430 in 1.6 ms, and is 7 KB in fp32;
|
||||
SigLIP 2 costs 47 ms a frame on the CPU, so a 90 s render at 4 fps takes 17 s
|
||||
And at the threshold that flags 10% of clean work, a de-rez sharpened afterwards is still caught 0.99 and noise
|
||||
at a third of the level 0.85, but glow only 0.33 (half strength 0.20): SigLIP's pooled vector ignores a
|
||||
picture's look, so look axes need their own columns
|
||||
|
||||
@done
|
||||
Scenario: FP0e. EmbeddingGemma 2 on the same windows
|
||||
Then 11-12, the Library's EmbeddingGemma 2 vectors (q8 on the CPU, 2.3 s a window: 2 frames at 1 fps and 2 s of
|
||||
sound) on FP0a's windows: picture 0.65 / 0.38, sound 0.66 / 0.47, both 0.64 / 0.53 (by video / by film), no
|
||||
better than SigLIP 2
|
||||
And on FP0b's axes (135 windows, held out by source, k = 4 / 16 / 32): blur 0.70 / 0.90 / 0.96, glow 0.54 / 0.65 /
|
||||
0.73, dark 0.58 / 0.74 / 0.85, freeze (2 frames) 0.56 / 0.66 / 0.77, noise 0.82 / 0.92 / 0.97, dropout 0.68 /
|
||||
0.88 / 0.94, clip 0.80 / 0.92 / 0.96: it learns them, more slowly than SigLIP 2, change and YAMNet
|
||||
And so video and sound axes read SigLIP 2, change, look and YAMNet; EmbeddingGemma 2 carries words, scripts,
|
||||
boards and stills, and the Library's rows; PE-AV was dropped untested (it can't run on consumer hardware)
|
||||
|
||||
@done
|
||||
Scenario: FP0f. Marks teach where; today's pins don't
|
||||
Then 11-12, five local defects in a random 64-80 px box of 290 real frames, linear heads on SigLIP 2's 14 x 14
|
||||
patch tokens, held out by source: the head's top patch falls in the box (chance 0.10) 0.85-0.96 of the time from
|
||||
8 frames marked with a click on the defect, 0.89-0.99 with a box, and 0.23-0.62 with only "this frame is bad",
|
||||
for blur, a hole, a flat grey surface and noise; local glow 0.44-0.62
|
||||
And on Shane's 203 pinned notes, a head trained on other videos' clicks ranks 35% of a frame's patches above the
|
||||
clicked one (44% by film), and his average click position 16%: pins sit near the middle (x 0.50 sd 0.14, y 0.52
|
||||
sd 0.18), also on the 89 that name a defect, so a pin anchors a note and isn't a mark of the thing
|
||||
|
||||
@done
|
||||
Scenario: FP0g. CLAP: sound axes from words alone, and heads at least as good as YAMNet's
|
||||
Then 11-12, CLAP htsat-unfused on FP0b's sound defects (130 windows of 2 s from 26 sources, held out by source):
|
||||
an axis prompt's similarity as a z against 40 background descriptions (earshot's calibration), with no labels,
|
||||
scores noise 0.97, clipping 0.98 and dropout 0.66 (AUC damaged against clean); at the threshold that flags 10%
|
||||
of clean windows it catches 0.94, 0.95 and 0.12
|
||||
And a head on CLAP's audio vectors scores, at k = 4 / 16 / 32: noise 0.94 / 1.00 / 1.00, dropout 0.86 / 0.99 /
|
||||
0.99, clipping 0.94 / 0.99 / 1.00, at or above YAMNet's (FP0b) on every axis from k = 16
|
||||
And noise at a third of the level (the cheat) is caught 0.48 from words alone (0.78 on 5 s windows), so a word
|
||||
head is advice; silence matches no description, so dropout is a check and a head, never a word head
|
||||
And 5 s windows change little; q8 keeps the numbers (words 0.99 / 0.67 / 0.97) at cosine 0.9975 to fp32; a 2 s
|
||||
clip costs 33 ms on the CPU (spike: ~/films/fingerprint-spike/clap, results/fp0g-clap*.txt)
|
||||
|
||||
Rule: FP1. Columns are made once at ingest and read by every fingerprint
|
||||
@needs:FP0b @done
|
||||
Scenario: FP1a. Each video gets its fingerprint columns
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| raea-sys-columns | systems/columns/src/lib.rs | 180 | the crate's surface: the encoders loaded once, a file in, its columns out |
|
||||
| raea-sys-columns | systems/columns/src/models.rs | 120 | where each encoder's files are (RAEA_MODELS), fetched once, pinned by sha256 |
|
||||
| raea-sys-columns | systems/columns/src/media.rs | 110 | a file's frames at 4 fps and its sound at 16 and 48 kHz (raea-io-media), its levels |
|
||||
| raea-sys-columns | systems/columns/src/siglip.rs | 120 | SigLIP 2's image and text towers on ort (ONNX fp32 image tower) |
|
||||
| raea-sys-columns | systems/columns/src/clap.rs | 150 | CLAP's audio tower on ort (raea-sys-ml): the 48 kHz log-mel front end and the session, checked against the spike's vectors at cosine 0.999 |
|
||||
| raea-sys-columns | systems/columns/src/clap_text.rs | 50 | CLAP's text tower on ort with its tokenizer (the tokenizers crate), for axis words only |
|
||||
| raea-sys-columns | systems/columns/src/yamnet.rs | 40 | YAMNet's embeddings on ort, when its model is here |
|
||||
| raea-sys-columns | systems/columns/src/look.rs | 60 | luminance histogram, saturation, local contrast and sharpness per frame |
|
||||
| raea-sys-columns | systems/columns/src/window.rs | 120 | a span's features from the columns (mean, change, look), as the heads read them |
|
||||
| raea-sys-columns | systems/columns/src/cache.rs | 80 | columns cached by the file's sha256 and step version, fp16 |
|
||||
| raea-sys-columns | systems/columns/src/damage.rs | 110 | the bootstrap's damage and cheats on frames and sound (FP2b) |
|
||||
| raea-sys-columns | systems/columns/src/tests.rs | 130 | parity with the spike: CLAP audio and text, SigLIP 2 against ONNX fp32 |
|
||||
When a video is ingested or rendered
|
||||
Then it gets SigLIP 2 per frame at 4 fps (the pooled vector, fp16), CLAP per 2 s window with a 1 s hop, YAMNet per
|
||||
0.48 s, change (frame-to-frame SigLIP distance) and look (luminance histogram, saturation, local contrast,
|
||||
sharpness) columns, stored under the file's content hash and each step's version (platform.feature: derived
|
||||
files are a cache)
|
||||
And SigLIP 2's 14 x 14 patch tokens (300 KB a frame) are kept only for flagged or marked frames, and remade on demand
|
||||
And the columns are made inside the feed host, which keeps the models loaded (earshot's CLI pays 20-40 s a call)
|
||||
And the Library's EmbeddingGemma 2 rows (v, a, t a segment) are read where they exist, never remade
|
||||
And every encoder runs on ort (raea-sys-ml) everywhere; on the Mac SigLIP 2 moves to MLX (raea-sys-mlx) once
|
||||
docs/mlx.feature MX5 gives it a path, never Core ML's GPU, and any new runtime path is checked against ONNX fp32
|
||||
at cosine 0.999 or better before its columns are kept
|
||||
And no encoder runs through transformers.js or Python; the spike's transformers.js vectors are only the reference
|
||||
And 11-12: raea-sys-columns makes every column above but the patch tokens (FP12a) and the Library's EmbeddingGemma 2
|
||||
rows (FP1b), in the resident service `raea fingerprint serve` rather than the feed host; on ort, SigLIP on the
|
||||
CPU. Parity with the spike (`cargo test -p raea-sys-columns -- --ignored`): CLAP audio on 260 clips mean and
|
||||
worst cosine 1.00000, CLAP text on 40 descriptions 1.00000, SigLIP 2 against Python onnxruntime on 16 frames
|
||||
1.000000
|
||||
|
||||
@needs:FP1a @done
|
||||
Scenario: FP1b. Not only video
|
||||
Then scripts, briefs, storyboards, stills, pages and sounds get EmbeddingGemma 2 rows the same way, so a
|
||||
fingerprint can hold axes about them (a script that reads the buttons aloud, a board with wide empty shots)
|
||||
And 11-12, so far: a script, brief or page (.md, .txt, .fountain, .html, .brief, .script.ts) is read as passages,
|
||||
each an EmbeddingGemma 2 row (systems/columns gemma.rs, the q8 export the app's library keeps in ~/.raea/models,
|
||||
fetched once otherwise; the Rust path gives transformers.js's vectors to the fifth decimal), a passage a step
|
||||
on its timeline; an axis with modality "text" scores its words as EmbeddingGemma 2 queries against 24 ordinary
|
||||
passages. A still or storyboard frame (.png, .jpg, .webp) is one frame through SigLIP 2 and a sound file goes
|
||||
through CLAP and YAMNet, the encoders picture and sound axes already read, rather than EmbeddingGemma 2's own
|
||||
image and audio encoders (a port of their preprocessing that buys nothing a head can use yet). Evidence rows
|
||||
written before the text column read as the same rows with no text; a fingerprint pinned before EmbeddingGemma 2
|
||||
was on the machine keeps working. a_script_and_a_still_get_rows (ignored, real models): the call to action is
|
||||
nearest "a call to action", the scene heading nearest "a scene heading"
|
||||
|
||||
Rule: FP2. The fingerprint is a folder, its taxonomy is TypeScript
|
||||
@needs:FP1a @done
|
||||
Scenario: FP2a. What's in it
|
||||
Then a fingerprint is ~/.raea/fingerprints/NAME/ (a person's), or PROJECT/.raea/fingerprints/NAME/ (a project's
|
||||
or team's), holding fingerprint.ts (`export default fingerprint({...})` from "raea/brief"), heads.safetensors,
|
||||
evidence.jsonl with evidence.f16 beside it, and report.json
|
||||
And fingerprint.ts names its encoders by id and hash, and a head refuses columns from any other
|
||||
And 11-12: the folder is as above, with fingerprint.json beside fingerprint.ts (what it last evaluated to, for
|
||||
hosts without a TS evaluator) and words.json beside words.f16; a fingerprint pins its encoders by id and sha256
|
||||
and a verb refuses columns from others (`reembed` moves it, FP8c)
|
||||
|
||||
@needs:FP2a @done
|
||||
Scenario: FP2b. An axis
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| raea-sys-fingerprint | systems/fingerprint/src/taxonomy.rs| 140 | an axis, a fingerprint, raea's base taxonomy and the background vocabularies |
|
||||
Then an axis has a name, the words people use for it, a modality (picture, change, look, sound, words), a scope
|
||||
(moment, shot, whole piece), a polarity, and optionally the taste check it maps to (text-hold, loudness...)
|
||||
And raea's base taxonomy is drawn from Shane's notes: glitch and continuity, sound, pace, camera, cut, light and
|
||||
look, realism and detail, interaction, design and type, story
|
||||
And a person or team adds axes in their fingerprint.ts; directions are never axes
|
||||
And 11-12: taxonomy.rs's Axis and raea's base taxonomy (15 axes: 8 mechanical, 7 taste axes from words); sdk/raea's
|
||||
`fingerprint({...})` types it
|
||||
|
||||
@needs:FP2b,FP1a @done
|
||||
Scenario: FP2e. Every axis scores from its words on day one
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| raea-sys-fingerprint | systems/fingerprint/src/words.rs | 100 | word heads: an axis's words against the background vocabulary as a z, per window |
|
||||
Then each axis's words are embedded when they change (CLAP's text tower for sound, SigLIP 2's for picture, on ort) and stored in the fingerprint as words.f16, with a background vocabulary of about 40 ordinary
|
||||
descriptions; the text towers never run at score time
|
||||
And a word head is always advice, and hands over to the learned head once that beats it on held-out evidence
|
||||
And on FP0g's defects the base taxonomy's words score noise and clipping at 0.97 or better with no labels
|
||||
And 11-12, word_heads_score_noise_and_clipping_from_words_alone on the spike's 130 two-second windows: noise 0.987,
|
||||
clipping 0.975 from their words alone; on 40 of Shane's renders (FP4b's bootstrap) noise 1.00, clip 0.90, blur
|
||||
0.87, dark 0.74, glow 0.61
|
||||
|
||||
@needs:FP1a,FP2c
|
||||
Scenario: FP2f. Realness, measured before it ships
|
||||
Then a realness axis for sound is trained from labels by construction: raea's own generated sound (TokenSynth,
|
||||
Stable Audio Open, Fish) against recorded foley and footage, held out by generator and by category, as earshot
|
||||
holds its out by engine and category (its grouped CV AUC 0.92)
|
||||
And it ships as an axis only at 0.85 or better held out by generator; it's a taste check ("real material only"),
|
||||
never a claim that a sound is or isn't AI-made
|
||||
And 11-12, measured, not shipped: raea-sys-fingerprint-use realness.rs, a logistic head on a sound's CLAP and
|
||||
YAMNet means (realness_on_this_machine, ignored, RAEA_REALNESS=~/.raea/evals/realness). Made: 60 SAO foley clips
|
||||
(15 categories, 4 seeds), 45 TokenSynth notes (9 timbres, C3-G4) and 40 Fish lines (two voices, $0.05).
|
||||
Recorded, each clip's source and licence kept beside it: 40 LibriSpeech test-clean speakers (CC BY 4.0), 42
|
||||
NSynth test acoustic notes in 7 families (CC BY 4.0) and 70 Clotho v2.1 evaluation clips in 14 of the 15
|
||||
categories, CC0 or CC BY 3.0 only (the NC and Sampling+ clips dropped). TokenSynth's bass and organ and SAO's
|
||||
typing have no recording and sit out (283 sounds measured). Held out by generator: TokenSynth 0.90, Fish
|
||||
0.80, SAO 0.57, so the axis doesn't ship (it needs 0.85 on all three). Held out by category it averages 0.85
|
||||
over 22 categories (about 5 recordings each; dishes and engine 0.40, traffic 0.60). Foley is where it fails:
|
||||
trained on notes and speech it can't tell SAO from recorded foley
|
||||
|
||||
@needs:FP2a @done
|
||||
Scenario: FP2c. Heads train in milliseconds, on the device
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| raea-sys-fingerprint | systems/fingerprint/src/lib.rs | 120 | the crate's surface: columns and evidence in, scores out; retraining and report.json |
|
||||
| raea-sys-fingerprint | systems/fingerprint/src/folder.rs | 250 | the fingerprint folder read and written: fingerprint.ts, words.f16, heads.safetensors, evidence.jsonl and .f16, report.json |
|
||||
| raea-sys-fingerprint | systems/fingerprint/src/evidence.rs| 140 | an evidence row (hash, span, axis, polarity, weight, who, source, columns) |
|
||||
| raea-sys-fingerprint | systems/fingerprint/src/head.rs | 210 | logistic and Bradley-Terry heads on standardised columns, their encoder pin |
|
||||
| raea-sys-fingerprint | systems/fingerprint/src/train.rs | 210 | fitting (L-BFGS), the person's weighting, held-out by project scores, the gate |
|
||||
| raea-sys-fingerprint | systems/fingerprint/src/tests.rs | 120 | a head learns, the folder round-trips, a ledger drops rows, a gate needs projects |
|
||||
| raea | sdk/raea/src/fingerprint.ts | 40 | `fingerprint({...})` and the Axis type, re-exported from raea/brief beside `taste` |
|
||||
Then each axis's head is a logistic fit on its modality's columns, standardised with the encoder's shipped
|
||||
statistics; an axis with pairs adds a Bradley-Terry fit on their differences; a person's weighting is a
|
||||
logistic fit over the axis scores
|
||||
And a retrain runs after every new evidence row and takes under a second for 10,000 rows on the CPU
|
||||
And the trainer is a Rust crate (systems/fingerprint), with no Python at run time
|
||||
And 11-12: head.rs (logistic and Bradley-Terry by L-BFGS), train.rs and folder.rs as planned; every verb that adds
|
||||
evidence retrains every head; no Python at run time. Tests: a_head_learns_a_separable_axis,
|
||||
the_folder_keeps_heads_words_and_evidence, a_ledger_keeps_features_when_it_drops_rows
|
||||
|
||||
@needs:FP2c @done
|
||||
Scenario: FP2d. A head is advice until it's earned its place
|
||||
Then a head gates only once it has 16 labels of each polarity or more, from 3 projects or more, and a held-out
|
||||
by project AUC of 0.8 or better; until then `raea fingerprint score` marks it advice
|
||||
And a gated head reports strong, plausible or weak, each band with the precision measured on its own held-out
|
||||
evidence (earshot's verdict bands)
|
||||
And report.json gives each head's held-out score, its labels by source, its red-team results, and what it can't
|
||||
judge (earshot's LIMITS.md)
|
||||
And 11-12: the gate is 16 labels of each kind from 3 projects, held-out AUC 0.8 and every cheat caught 0.8; a head
|
||||
reports its strong (precision 0.9) and plausible (0.7) thresholds and report.json says each head's why and what
|
||||
it can't judge. Test: a_gate_needs_projects
|
||||
|
||||
Rule: FP3. Scoring a piece
|
||||
@needs:FP2c @done
|
||||
Scenario: FP3a. raea fingerprint score
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| raea-sys-fingerprint-use | systems/fingerprint-use/src/score.rs | 220 | per-window axis scores, the moments a note is expected on, the summary and the timeline |
|
||||
| raea-app-fingerprint | apps/fingerprint/src/lib.rs | 120 | `raea fingerprint`: its usage, flags and the verbs' dispatch (raea-cli is at its 2,000-line limit, so the verbs are their own crate) |
|
||||
| raea-app-fingerprint | apps/fingerprint/src/verbs.rs | 260 | new, bootstrap, teach, score (with raea check's findings, the check winning) and report |
|
||||
| raea-app-fingerprint | apps/fingerprint/src/serve.rs | 150 | the resident service that keeps the encoders loaded, on localhost; the verbs start it on demand |
|
||||
When I run `raea fingerprint score FILE [--fp NAME]`
|
||||
Then it prints a summary first: the moments the fingerprint expects a note on, each with its axis named in the
|
||||
person's words and the checks' findings; every axis's score per window with --json
|
||||
And it runs in the feed host with the models already loaded
|
||||
And `raea fingerprint teach FILE --axis A --at T [--bad|--good] [--span S] [--box x0,y0,x1,y1]` adds an evidence
|
||||
row from the CLI or an agent
|
||||
And the watch timeline shows the same as a lane (the player's lane plugins)
|
||||
And 11-12: `raea fingerprint score` prints which fingerprint judged and why (FP14c), the moments first, raea check's
|
||||
findings beside them; a check wins over a head on an axis it measures. The watch timeline's lane is FP11's
|
||||
|
||||
@needs:FP3a @done
|
||||
Scenario: FP3c. A sheet and a timeline an agent can read
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| raea-sys-fingerprint-use | systems/fingerprint-use/src/sheet.rs | 180 | one PNG: frames (heatmaps with FP12), axis lanes, the level, the spectrogram with flagged sounds boxed, check findings |
|
||||
When I run `raea fingerprint score FILE --sheet out.png` or `--timeline`
|
||||
Then the sheet shows the whole piece in one picture (earshot's `sheet`), and the timeline reads it second by
|
||||
second in words: what is seen, what is heard, which axes flag (earshot's `timeline`)
|
||||
And `raea show` opens the sheet for a person
|
||||
And 11-12: `--sheet` writes the PNG (frames, axis lanes, the level, the spectrogram, the checks' ticks) and
|
||||
`--timeline` the piece second by second, the nearest vocabulary words for what is seen and heard
|
||||
|
||||
@needs:FP3a,FP4a
|
||||
Scenario: FP3b. The golden references stay clean, and a known bad cut doesn't
|
||||
Then the five golden references' approved.mp4 raise no gating flag
|
||||
And the cut Shane called "explicitly a bad one" raises more flags, on the same axes, than the approved reel
|
||||
made from the same footage (both in the golden references' private media, never in git)
|
||||
And 11-12, scored with a scratch copy of FP4b's 40-render fingerprint: the five golden references raise no gating
|
||||
flag (advice only: 9, 9, 6, 9 and 7 moments, mostly noise under music beds, blur and flash); the Kimi cut raises
|
||||
no gating flag either and fewer advice moments than the approved reel from the same footage (4 against 9),
|
||||
though raea check finds more in it (4 findings against 1). What makes that cut bad isn't a mechanical defect, so
|
||||
this waits on taste axes trained from Shane's notes (FP5) before it can pass
|
||||
And decided 11-12 for 0.1.2: FP3b closes on its first clause, which holds; its second moves to FP5c, the proof
|
||||
on his own notes, because no mechanical axis can tell that cut apart and none should be tuned until it does.
|
||||
Until FP5c passes, `score` makes no claim to rank a cut's taste, and nothing gates on taste axes with only words
|
||||
|
||||
Rule: FP4. Damage variants bootstrap the axes
|
||||
@needs:FP2c @done
|
||||
Scenario: FP4a. Labels by construction, on real work
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| raea-app-fingerprint | apps/fingerprint/src/bootstrap.rs | 250 | damaged windows of real work as evidence, FP0b's few-shot curves held out by source, word heads' AUCs and cheats |
|
||||
Then for each mechanical axis (blur, dark, glow, flash, freeze, noise, dropout, clip, and the ones added later)
|
||||
`raea fingerprint bootstrap` makes damaged windows of the person's own approved work and trains the axis head,
|
||||
held out by source, to FP0b's numbers or better
|
||||
And no placeholder footage: the sources are real renders and footage
|
||||
And 11-12, `raea fingerprint bootstrap` on 40 of Shane's renders (28 long enough, 280 windows, 4,760 rows), held
|
||||
out by source at k = 4 / 16 / 32: blur 0.99 / 1.00 / 1.00, dark 0.78 / 0.97 / 0.99, glow (picture) 0.58 / 0.73 /
|
||||
0.84, flash 0.96 / 0.97 / 0.97, freeze 1.00, noise 0.99 / 1.00 / 1.00; dropout 0.70 / 0.88 / 0.93 and clip 0.84 /
|
||||
0.94 / 0.95 fall under FP0g's CLAP numbers (0.99, 1.00) on these renders, many of them quiet
|
||||
|
||||
@needs:FP4a @done
|
||||
Scenario: FP4b. Every axis has cheats that must still be caught
|
||||
Then each axis carries a red-team set (sharpened after a de-rez, half-strength glow, quieter noise, a one-frame
|
||||
flash, a freeze with a slow zoom on it), and report.json shows each cheat's catch rate at the threshold that
|
||||
flags 10% of clean work
|
||||
And a cheat caught under 0.8 holds that axis at advice
|
||||
And glow gates only once the look columns exist and its cheats pass
|
||||
And 11-12: damage.rs's cheats are sharpblur, glow_half, noise_low, freeze_zoom, dark_half (darkened half as much),
|
||||
flash_white, dropout_short (0.2 s) and clip_soft; on FP4a's 40 renders sharpblur, noise_low and flash_white are
|
||||
caught 1.00 and dark_half 0.80, and glow_half 0.50, freeze_zoom 0.27, dropout_short 0.60 and clip_soft 0.61 hold
|
||||
glow, freeze, dropout and clip at advice
|
||||
|
||||
@needs:FP1a @done
|
||||
Scenario: FP4c. What can be measured is a check, and the arbiter
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| raea-app-check | apps/check/src/defects.rs | 150 | clipping, a dropout and a flash frame as raea check rules, with red-team tests |
|
||||
Then dropout (a silence gap in a sound that had level), clipping (samples at full scale), loudness, a flash frame
|
||||
and a freeze are measured from the columns and the sound as `raea check` findings, each with red-team cases
|
||||
And where a check and a head disagree, the check wins: earshot's search fooled its learned critics while its
|
||||
measurements held, and FP0g shows silence matching no words
|
||||
And 11-12: defects.rs (clipping, dropout, flash frames) beside raea check's loudness, peak and freeze rules, with
|
||||
red-team tests (clipping_is_found_and_a_loud_clean_tone_isnt, a_dropout_is_found_and_a_faded_pause_isnt,
|
||||
a_flash_frame_is_found_and_a_cut_or_a_fade_isnt); flash, freeze, dropout and clip name their check, and a moment on
|
||||
one isn't a gate unless its check found it too
|
||||
|
||||
Rule: FP5. Notes become evidence
|
||||
@needs:FP2b @done
|
||||
Scenario: FP5a. A pinned note is read into a label
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| raea-app-fingerprint | apps/fingerprint/src/notes.rs | 320 | notes read by a fresh session, checked by the person, then evidence |
|
||||
When a person pins a note on a video (docs/review.feature R1)
|
||||
Then the Director reads it into: defect, direction or praise; the axis, from the fingerprint's own axes and their
|
||||
words; the span (by default the 1.5 s before the pin to 0.5 s after); and the layer under the pin's x,y
|
||||
through the layer pass (review.feature R2), when the video has one
|
||||
And a defect or praise becomes an evidence row with the note's words, its id and who wrote it; a direction goes to
|
||||
the brief and the agent only
|
||||
And 11-12: `raea fingerprint read PROJECT [--by kimi|claude]` (notes.rs) has a fresh session read each person's
|
||||
pinned note on the project's videos into a kind and one of the fingerprint's axes (an axis it hasn't, or a kind
|
||||
it doesn't know, is dropped), kept in readings.jsonl with the note's id, words, author, its moment or span and the
|
||||
region its marks name. On a render with a layer pass the reading keeps the layers under the pin (a pin on a
|
||||
things red-team block reads "Box", one on the empty sky none), and the reader is told them ("pinned on Box").
|
||||
`learn-notes` makes a defect or praise an evidence row over 1.5 s before the pin to 0.5 s after, with the note's
|
||||
words, id and author; a direction stays with the brief. It trains only past FP5b's gate
|
||||
|
||||
@needs:FP5a
|
||||
Scenario: FP5b. The reading is checked against the person
|
||||
Then on 50 of Shane's real notes read by the Director, he agrees with the kind (defect, direction, praise) on 45
|
||||
or more and with the axis on 40 or more, before notes train any head
|
||||
And decided 11-12 for 0.1.2: the check is built and the gate stays where it is. `raea fingerprint read` has a
|
||||
fresh session read a project's pinned notes, `readings --ask 50` puts them to the person in the app,
|
||||
`readings --tally` counts the answers, and `learn-notes` refuses until 50 are checked with 45 kinds and 40 axes
|
||||
agreed. On 11-12 no readings exist yet and none is checked, so notes train nothing in 0.1.2. Reading starts
|
||||
when Shane runs `read` himself, since it sends his note texts to an outside model; his answers are the
|
||||
measure, so none is assumed
|
||||
|
||||
@needs:FP5b,FP6a
|
||||
Scenario: FP5c. The proof that matters
|
||||
Then a fingerprint built from Shane's evidence on Stay assemblies 18-22 ranks the moments he noted on assembly 23
|
||||
above the rest by AUC 0.70 or better on its gating axes, held out by film as well as by version, and beats the
|
||||
previous version's note times as a predictor (0.60 in FP0)
|
||||
And decided 11-12 for 0.1.2: not measured. Its evidence is FP5b's checked readings, and there are none yet; a
|
||||
number from unchecked readings would measure the reader, not the fingerprint. It is measured once FP5b's
|
||||
gate passes, and FP3b's second clause (the bad cut ranked below its approved reel) is measured with it
|
||||
|
||||
Rule: FP6. Positives and pairs come from what the person already does
|
||||
@needs:FP2c @done
|
||||
Scenario: FP6a. Approvals
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| raea-app-fingerprint | apps/fingerprint/src/approve.rs | 90 | approved work as clean rows on every axis, away from its notes |
|
||||
Then an approval, a picture lock, a publish or a golden reference is a positive on every axis over every span with
|
||||
no defect note
|
||||
And 11-12: `raea fingerprint approve FILE... [--project P]` adds a clean row on every axis for each 2 s window,
|
||||
leaving out windows within 2 s of a note pinned on that file in its project's feed. Test:
|
||||
an_approval_leaves_out_the_windows_near_a_note
|
||||
@needs:FP6a @done
|
||||
Scenario: FP6b. Picks and hand edits
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| raea-sys-fingerprint | systems/fingerprint/src/pairs.rs | 70 | Bradley-Terry fits on pairs, held out by project |
|
||||
| raea-app-fingerprint | apps/fingerprint/src/pairing.rs | 130 | pair and versions |
|
||||
Then a pick between real options (docs/craft-system.md F) is a pair on the axes the options differ on, and a hand
|
||||
edit's before and after (~/.raea/taste/corrections.jsonl) is a pair on the axis the edit touched
|
||||
And 11-12: `raea fingerprint pair WORSE BETTER --axis A [--at T] [--then T2]` records either one: the worse
|
||||
window's columns minus the better one's, fit Bradley-Terry with no intercept, held out by project; an axis with
|
||||
4 or more pairs and no labels of each kind is ranked by its pairs alone, as advice. corrections.jsonl's rows say
|
||||
what was said, not which files came before and after, so an edit is recorded with `pair` rather than read from
|
||||
it. Tests: pairs_alone_rank
|
||||
@needs:FP6a @done
|
||||
Scenario: FP6c. Version pairs
|
||||
Then a noted moment whose picture or sound changed in the next version (cosine distance 0.01 or more) and that
|
||||
isn't noted again within 1 s is a weak pair (weight 0.5)
|
||||
And 11-12: `raea fingerprint versions V1 V2...` (apps/fingerprint/src/pairing.rs). Test:
|
||||
a_changed_moment_not_noted_again_is_a_weak_pair
|
||||
@needs:FP6a @done
|
||||
Scenario: FP6d. Another eye stays another eye
|
||||
Then clef's or Kimi's readings are evidence from that eye, with their source, and never count as the person's
|
||||
And 11-12: rows with source eye:NAME train a head but are left out of the gate's label and project counts, which
|
||||
say "labels of yours". Test: another_eye_stays_another_eye
|
||||
|
||||
@needs:FP2c,FP4c @done
|
||||
Scenario: FP6e. Profiles: ranges from work the person admires
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| raea-sys-fingerprint-use | systems/fingerprint-use/src/profile.rs | 180 | a profile's ranges over measures and axis scores, the leave-one-out check, critique against it |
|
||||
When I run `raea fingerprint profile REFS... --as NAME`
|
||||
Then each measure (loudness, spectral balance, cut rate, motion, brightness and contrast) and each axis score gets
|
||||
the range the references span, and `raea fingerprint score --profile NAME` says which fall outside it, where,
|
||||
and which way to move (earshot's `profile` and `critique`)
|
||||
And the profile is checked leave-one-out: each reference against a profile of the others must fall in range more
|
||||
often than against a profile of unrelated work (earshot's 86% against 71%), or it's reported as not telling
|
||||
this taste apart
|
||||
And the golden references and approved cuts are the first profiles, and give the positives notes don't (3
|
||||
approvals in 205 notes)
|
||||
And 11-12: measures are loudness, loudness range, tilt (bass against treble), cuts a minute, motion, brightness,
|
||||
contrast, saturation and sharpness, each range widened 10%; the profile says when it doesn't tell its taste
|
||||
apart. Test: a_profile_critiques_a_piece
|
||||
|
||||
Rule: FP7. The post-mortem
|
||||
@needs:FP5a,FP6a
|
||||
Scenario: FP7a. The agent asks what it's least sure of
|
||||
When a project is closed, or on `raea fingerprint postmortem PROJECT`
|
||||
Then the agent scores every version, finds the moments where the fingerprint is least sure or disagrees most with
|
||||
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. Archiving a project runs it in the background (raea-feed #5, in the 0.1.2 app)
|
||||
|
||||
Rule: FP8. Teams
|
||||
@needs:FP2d @done
|
||||
Scenario: FP8a. Sharing is evidence, not weights
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| raea-sys-fingerprint | systems/fingerprint/src/share.rs | 60 | a shared folder's evidence a folder a person, its heads kept off the repo |
|
||||
Then sharing a fingerprint shares fingerprint.ts and the evidence rows (embeddings, spans, labels, who), through
|
||||
the project's repo (Git + LFS) or raea's API, under the project's permissions; never media
|
||||
And each teammate's machine retrains the shared heads from the pooled evidence (FP0c: pooled 0.76 against
|
||||
averaged heads 0.74 and one person's 0.66)
|
||||
And each person's weighting stays their own; a team fingerprint's weighting is fit on everyone's labels
|
||||
And 11-12: `raea fingerprint share NAME --in project|workspace` copies fingerprint.ts and the evidence into
|
||||
PLACE/.raea/fingerprints/NAME, a folder a person (evidence/<who>/), with heads and the report git-ignored; a
|
||||
shared one with no heads trains on open. Test: a_shared_fingerprint_keeps_evidence_a_person
|
||||
|
||||
@needs:FP8a @done
|
||||
Scenario: FP8b. Where tastes differ
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| raea-sys-fingerprint-use | systems/fingerprint-use/src/diff.rs | 110 | two fingerprints' heads on the same evidence: the axes most apart and their moments |
|
||||
Then `raea fingerprint diff A B` lists the axes where two fingerprints disagree most on the same evidence, with
|
||||
the moments that show it
|
||||
And 11-12: rows are counted once by media, span, axis and kind. Test: diff_finds_where_two_tastes_differ
|
||||
|
||||
@needs:FP8a @done
|
||||
Scenario: FP8c. Encoder upgrades keep the evidence
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| raea-app-fingerprint | apps/fingerprint/src/reembed.rs | 110 | rows moved to this machine's encoders where their media is found |
|
||||
Then when an encoder is replaced, rows whose media is present are re-embedded and the heads retrained; rows
|
||||
without media keep the old pin until re-labelled
|
||||
And 11-12: `raea fingerprint reembed PLACE...`; each row carries the pin it was embedded on, and a scoring
|
||||
fingerprint on other encoders refuses and names reembed. Tests: a_row_on_old_encoders_waits,
|
||||
a_pin_names_each_encoder_and_its_hash
|
||||
|
||||
Rule: FP14. Many fingerprints: one person's evidence, a fingerprint for each kind of work
|
||||
# Separate fingerprints that each start from nothing split a person's labels, and their labels are the scarce part.
|
||||
# So a fingerprint isn't a silo: it extends another and inherits its axes and evidence, and adds or overrides only
|
||||
# where its kind of work differs (a client's ads cut fast, a film holds). Which one judges a piece is decided by
|
||||
# where the piece lives, as .editorconfig is, not picked each time; the person can always see why.
|
||||
@needs:FP2a @done
|
||||
Scenario: FP14a. Each says what it is for
|
||||
Then fingerprint.ts has `about`, one line naming what it tracks and when it judges ("Short ads for one brand:
|
||||
pace, type on screen, the brand's colours"), shown wherever the fingerprint is named and given to agents
|
||||
And it may have `extends` (another fingerprint by name, the person's own or one in a parent folder) and
|
||||
`applies` ({ kinds?: film, ad, game, playable, still, sound; tags?: the project's }), both optional
|
||||
And 11-12: `raea fingerprint new NAME --about TEXT --extends FP` writes them (raea-sys-fingerprint Fingerprint
|
||||
about/extends/applies, sdk/raea fingerprint.ts Applies); --extends starts from FP's axes and its evidence is
|
||||
FP14b's; the app shows `about` in its switcher, the card and Settings. Tests: about_extends_and_applies_round_trip,
|
||||
a_new_fingerprint_says_what_its_for_and_what_it_builds_on, raea-cli a_verb_refuses_what_it_doesnt_take (bootstrap
|
||||
takes many files: the usage named each sub-verb with `raea fingerprint`, or the arity check held them all to new's 2)
|
||||
|
||||
@needs:FP14a @done
|
||||
Scenario: FP14b. A child inherits, and its own labels count more
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| raea-sys-fingerprint | systems/fingerprint/src/inherit.rs | 160 | a child's parents, its axes with theirs, its evidence with theirs (its own 2x), overrides, the measure |
|
||||
When a fingerprint extends another
|
||||
Then it has its parent's axes plus its own; an axis of its own with the parent's name overrides that axis's words,
|
||||
polarity or check, and an override's evidence starts from its own labels only
|
||||
And its heads train on its parent's evidence and its own, its own weighted up (2x, then measured: held out by
|
||||
project, the child's own projects, against training on its own labels alone and on the parent's alone)
|
||||
And the parent never trains on a child's evidence, so one client's taste doesn't move the person's own
|
||||
And 11-12: the report's `inherits` gives own and inherited rows, the overrides and each axis's measure. Test:
|
||||
a_child_inherits_and_its_own_labels_count_more
|
||||
|
||||
@needs:FP14a @done
|
||||
Scenario: FP14c. Which one judges a piece
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| raea-sys-fingerprint-use | systems/fingerprint-use/src/which.rs | 160 | the levels, a piece's kind and tags, the one chosen and why |
|
||||
| raea-app-fingerprint | apps/fingerprint/src/pick.rs | 170 | which, use, share and diff, and the fingerprint a verb uses |
|
||||
Given a piece in PROJECT, inside a WORKSPACE folder, on a person's account
|
||||
Then the fingerprints are looked for in PROJECT/.raea/fingerprints, then WORKSPACE/.raea/fingerprints, then
|
||||
~/.raea/fingerprints; at each level the one whose `applies` matches the piece's kind and tags most closely
|
||||
wins, else that level's `default` file, else the next level up; the account's default always matches
|
||||
And `raea fingerprint which PATH` prints the one chosen, its `about`, and why (the level and the rule that matched)
|
||||
And a project or workspace can pin one with `raea fingerprint use NAME [--project|--workspace]`, which writes that
|
||||
level's `default`
|
||||
And the agent scores with the chosen one only, and says its name when it reports a flag
|
||||
And 11-12: `raea fingerprint which PATH [--json]`, `use NAME --in project|workspace`, and `new --kinds --tags`
|
||||
for `applies`; a piece's kind is .raea/project's `kind =`, else its file type, its tags `tags =`; score prints
|
||||
"judged by NAME: why". Tests: which_one_judges_a_piece, a_new_fingerprint_says_what_its_for_and_what_it_builds_on
|
||||
|
||||
@needs:FP14b,FP5a @done
|
||||
Scenario: FP14d. A note teaches the one that judged
|
||||
Then a note or mark on a piece is evidence in the fingerprint that judged that piece, so labels land where the
|
||||
taste they express applies, and a parent sees them only if the person moves them up (`raea fingerprint move`)
|
||||
And so far (11-12): teach, approve and pair label the fingerprint `which` picks for the file; read, readings and
|
||||
learn-notes keep a project's notes in the one that judges the project, and learning again remakes only those
|
||||
notes' rows. `move [--fp CHILD] [--to PARENT] --axis/--source/--project` takes the child's own matching rows up
|
||||
into a fingerprint it extends and retrains both; rows on an axis the parent lacks or the child overrides stay
|
||||
|
||||
@needs:FP14c @done
|
||||
Scenario: FP14e. Managing them in the app
|
||||
Then the fingerprint page lists the person's fingerprints as a tree by `extends`, each with its `about`, where it
|
||||
applies, its labels and what it knows; one is shown at a time, and a project's page names the one judging it
|
||||
And "New fingerprint" asks for a name, what it's for, what it builds on (the account default by default) and
|
||||
where it applies (this project, this workspace, or kinds of work), and writes fingerprint.ts there
|
||||
And a fingerprint kept in a project or workspace folder travels with that folder's repo and is shared as FP8a
|
||||
says; one in ~/.raea is the person's own
|
||||
And so far (11-12, raea-feed fingerprint-page): the page's title has a switcher of ~/.raea/fingerprints with each
|
||||
one's `about` and how many axes it knows, "New fingerprint" asks for a name, what it's for and what it builds on,
|
||||
Settings makes one the default and trains it; headless, the app made client-ads from me in 34 s and trained it
|
||||
from 12 renders in 3m54s (910 rows, 6 axes gating). Since: the switcher is a tree by `extends`, each saying
|
||||
which kinds and tags it judges; "New fingerprint" asks which it judges (`new --kinds --tags`); a project's header
|
||||
names the one `raea fingerprint which` picks, why in its tooltip. 11-13 (raea-feed #8): that name is a menu
|
||||
saying who judges and why, with Keep with this project and Keep with the workspace listing the person's
|
||||
fingerprints; the host runs `share` and `use` there and commits the folder in the repo that holds it.
|
||||
Tests: host/fingerprint-keep.test.ts (the real raea in a throwaway home), e2e/fingerprint-keep.spec.ts
|
||||
|
||||
Rule: FP9. Agents use it, and can't game it
|
||||
@needs:FP3a,FP4b,FP5c
|
||||
Scenario: FP9a. Before posting a cut
|
||||
Then the feed's agent runs `raea fingerprint score` on a cut before posting it and fixes each gating flag, or says
|
||||
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 @done
|
||||
Scenario: FP11a. Marks beside the pin
|
||||
Given the review player (docs/review.feature R1), where a pin places a note
|
||||
Then a note can carry marks: mark (a click on the thing), box, lasso, arrow (from a thing to a place), strike (a
|
||||
stroke through a thing) and span (a drag along the timeline); on sound, a box on the spectrogram is FP11c
|
||||
And each mark is stored with the note, in the frame's 0-1 coordinates, with its frame or span and the layer keys
|
||||
under it from the layer pass when the video has one
|
||||
And a note without a mark keeps its pin, which is never read as a mark (FP0f)
|
||||
And so far (11-12, raea-feed fingerprint-page 2265d91): a pin dropped on the picture opens its composer with mark,
|
||||
box, lasso, arrow and strike tools; the next drag draws one, kept in pin.marks in 0-1 with its frame (`t`) and
|
||||
the layer keys under it on a render with a layer pass, and an opened note draws them again (e2e/marks.spec.ts).
|
||||
A span is the time pin's `to` (MomentComposer)
|
||||
|
||||
@needs:FP11a @done
|
||||
Scenario: FP11b. What each mark teaches
|
||||
Then a mark or a box on a defect note is a region label for that axis on those frames; an arrow is a direction
|
||||
(the layer and its displacement) and goes to the agent as an instruction; a strike is "remove this layer" for
|
||||
the agent; a span sets the label's time
|
||||
And a click is grown into a region by EdgeTAM and tracked through its shot, so one mark labels every frame of it,
|
||||
with the frames EdgeTAM loses dropped
|
||||
And so far (11-12): the agent reads arrows, strikes and the marked thing as lines in the note's prompt and on a
|
||||
poster's line (raea-feed 02fc49a, model/pin.ts marksLines); `learn-notes` makes a defect note's mark, box and
|
||||
lasso its row's region and a span pin its time. The mark is followed through its whole shot (grow.rs through:
|
||||
raea-perceive cuts for the shot, at most 8 s either side, then EdgeTAM forward and back at 4 frames a second),
|
||||
and the note becomes one row for each 2 s window of the shot where EdgeTAM kept the thing on half its frames or
|
||||
more, at the box around it there. The note's own window is always a row, at the mark. Without raea-perceive it
|
||||
is one row over the label's span. On the things red-team renders (3 s shots), a mark on a still block kept both
|
||||
windows, the second at the block's own box (overlap 0.97 of its layer-pass box), and a mark on a moving block
|
||||
followed it left across the frame, a looser box (overlap 0.41). A blind seed in the middle of an app render
|
||||
kept only the note's frame, so only its own window
|
||||
|
||||
@needs:FP11b @done
|
||||
Scenario: FP11c. Marks on the sound
|
||||
Given the review player shows a sound's spectrogram under its picture (or in its place, for sound alone)
|
||||
Then a box drawn on it is a note's mark there, kept in 0-1 of the span shown (time) and of the frequencies (mel)
|
||||
And on a defect note on a sound axis, `learn-notes` makes its time the label's span and keeps its band in the row
|
||||
And decided 11-12: not in 0.1.2; built 11-13 for 0.1.3 (raea-feed #9). The host draws a mel
|
||||
spectrogram (host/spectrum.ts: 22.05 kHz, 64 bands to 11.025 kHz, a column every 25 ms, the loudest 80 dB),
|
||||
the timeline's sound track offers it as Spectrogram (opened tall), and Listen shows it under the waveform.
|
||||
A box dragged on it (with the Comment tool on the timeline, any drag in Listen) opens the moment card naming
|
||||
its span and band in Hz; the note's pin is a time pin over the box's span with one mark {kind: "box", on:
|
||||
"sound", points: [[time, mel], [time, mel]]} in 0-1 of the piece and of the mel scale, drawn again on the
|
||||
spectrogram in its author's hue, and the agent reads it as "Marked on the sound (box, T0 to T1, LO to HI)"
|
||||
(e2e/sound-marks.spec.ts, src/detail/marks.test.ts, host/spectrum.test.ts). `marked` ignores a sound box (it
|
||||
is no place in the frame); `sound_band` reads its band into the reading, and `learn-notes` labels t..to
|
||||
(widened to half a second about its middle when shorter) and keeps a defect's band in the evidence row's
|
||||
`band`. The sound heads are still per window, so the band is kept but not yet learned from
|
||||
|
||||
Rule: FP12. Heatmaps: a picture axis says where, not only whether
|
||||
@needs:FP11b,FP2c @done
|
||||
Scenario: FP12a. Patch heads
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| raea-sys-fingerprint-use | systems/fingerprint-use/src/patch.rs | 260 | patch heads: fit from region labels, pointing held out by source, the region and its place in words |
|
||||
| raea-sys-fingerprint-things | systems/fingerprint-things/src/located.rs | 180 | the bootstrap's frames with local defects, and a scored moment placed in the frame and its layers |
|
||||
Then each picture axis also has a patch head on SigLIP 2's patch tokens, trained from region labels (marked
|
||||
patches positive, clean frames' patches and a box's outside negative), and `raea fingerprint score` gives a
|
||||
heatmap for each flagged moment
|
||||
And on raea's renders the heatmap is read through the layer pass into the layers it covers, so a flag names the
|
||||
mesh, the text or the component
|
||||
And on FP0f's local defects, pointing is 0.85 or better from 8 marked frames for blur, holes, flat surfaces and
|
||||
noise, held out by source, and glow gates only once the look columns lift it to 0.8
|
||||
And 11-12: `raea fingerprint bootstrap` also makes patch heads (located.rs, patch.rs). From up to 6 frames of each
|
||||
source it makes FP0f's five local defects in a random 64-80 px box (columns damage.rs LOCAL): a blurred patch for
|
||||
blur, a black hole and heavy grain for glitch, a flat grey surface for barren, a local glow for glow. A defect
|
||||
that changes its box by under 6 levels in 255 (blur on a clear sky) is left out, since it isn't one. Each head
|
||||
is a logistic over the 196 patch tokens (siglip.rs patches, last_hidden_state): the box's cells positive (a
|
||||
cell half inside or more), the rest and every other frame negative. Held out by source, trained on 8 of the
|
||||
axis's frames from the other sources and tested on the held-out source's, on 27 of the "me" fingerprint's
|
||||
renders: barren (flat) 0.92, glitch 0.90 (grain 0.91, hole 0.89), blur 0.88, glow 0.49. Without the visible
|
||||
rule blur was 0.79. A head says where only at 0.85 or better (POINTS), so glow doesn't
|
||||
And `score` gives each flagged moment on an axis whose head points a box, the top patch and the patches joined
|
||||
to it within 1 of it in log-odds, at the moment's middle frame. It's printed as its place ("top right") and,
|
||||
when NAME.layers is beside the piece, the layers under a tenth of the box or more, by name ("on Floor"), in
|
||||
--json as `at` {t, region, layers}. The sheet boxes it in amber. On a render with a black hole drawn top
|
||||
right, glitch said "top right on Floor"
|
||||
And not yet: a heatmap image (the region is a box), and the person's marks training patch heads (FP12b)
|
||||
|
||||
@needs:FP12a
|
||||
Scenario: FP12b. Pointing on real marks
|
||||
Then once Shane has made 50 marks on defect notes, a patch head trained on the other projects' marks puts his mark
|
||||
in its top 10% of patches on half of them or more, against his own centre prior, held out by project
|
||||
And decided 11-12 for 0.1.2: waits on his marks. Patch heads train only on local defects (FP12a), and a mark on
|
||||
a note doesn't train one yet. Marks join them once he has made 50, when this is measured, so nothing claims
|
||||
to point at his marks before it has been tested on them
|
||||
|
||||
Rule: FP13. Things, not only pixels: depth, masks and words for footage raea didn't make
|
||||
@needs:FP11b
|
||||
Scenario: FP13a. A shot's things
|
||||
Then footage gets, per shot, its things: masks from EdgeTAM (from marks, and from words below), depth and the
|
||||
camera's path from Depth Anything 3 Small (both already in perception), and one embedding per thing (SigLIP 2's
|
||||
patch tokens pooled in its mask)
|
||||
And on raea's renders the same things come from the layer pass, the depth and motion passes and the scene's
|
||||
camera, with no model run
|
||||
And 11-12, so far: `raea fingerprint things FILE [--json]` (raea-sys-fingerprint-things things.rs): the shots
|
||||
(raea-perceive cuts), each thing's box, the median 1/depth of it, of its base and of the ground under it every
|
||||
half second, and one SigLIP 2 vector where it's largest: its frame's patch tokens (FP12a) averaged over the cells
|
||||
its mask covers half of or more, the one it covers most for a thing under a cell (on the floating red-team
|
||||
render the two boxes from one component are the nearest pair, 0.77, and the two end posts the next, 0.61);
|
||||
and the camera's path (raea-perceive flow, Lucas-Kanade at 512: Vision's flow read a pan over plain ground at a
|
||||
quarter of its speed). A thing comes from each mark drawn on the piece's notes, followed by EdgeTAM (grow.rs
|
||||
follow), or on a render from NAME.layers beside it (the reader moved from runtime/world into raea-sys-layers
|
||||
read.rs, both use it). Depth is the render's own reverse Z when NAME.aov (`raea render EDIT --aov -o NAME.aov`)
|
||||
is beside it, else Depth Anything 3 Small (depth-values now takes many frames to one model load). A render's
|
||||
camera path is its own, from the same pass's motion vectors (NAME.aov/motion): the median move of every pixel as
|
||||
the pan and the median move out from the middle, after the pan, as the zoom, eight times a second, with no
|
||||
model run; footage keeps the flow's. On the lurch red-team render (the camera trucks 0.02 a frame, then 0.06
|
||||
from 1.5 s) the pass reads -0.063 frames a second, then -0.190, three times as fast, where flow read -0.015,
|
||||
then -0.066; on the two renders whose camera holds still it reads 0 where flow read moves up to 0.1. Not yet:
|
||||
footage's camera path from Depth Anything 3 Small. raea-perceive's port gives depth only (depth-values), not the
|
||||
model's camera head, so footage's path is still the flow's, which reads a pan over plain ground slow
|
||||
|
||||
@needs:FP13a,FP5a
|
||||
Scenario: FP13b. A note's words find its thing (the test that decides whether a grounder ships)
|
||||
Then an open-vocabulary detector that runs on consumer hardware under a commercial licence (Grounding DINO or
|
||||
Florence-2 base, measured first; nothing AGPL) finds a defect note's nouns within 20% of the frame of its pin
|
||||
And on 30 of Shane's defect notes that he also marks (FP11a), the grown region covers his mark on 24 or more;
|
||||
below that, notes stay frame labels and the detector isn't shipped
|
||||
And decided 11-12 for 0.1.2: not shipped. The test needs 30 of Shane's own defect notes with his marks on them,
|
||||
and they don't exist yet, so 0.1.2 has no grounder: a note stays a label on its frame, and its thing comes only
|
||||
from a mark drawn on it (FP13a)
|
||||
|
||||
@needs:FP13a
|
||||
Scenario: FP13c. Geometry axes are checks, not heads
|
||||
Then floating (a gap under a thing that should rest), passing through (two things' masks and depths crossing),
|
||||
a camera that changes speed mid-move, and a frame with nothing on it are measured from depth, masks and the
|
||||
camera's path as `raea check` findings, each with red-team cases, and never trained as heads
|
||||
And 11-12, so far: geometry.rs measures the four on things.rs's output and `raea check --things T.json` reports
|
||||
them (floating and a camera that changes speed as warns, passing through and an empty frame as errors); each has
|
||||
red-team cases offline (a resting thing, a base out of frame, one bad depth; one thing walking in front of
|
||||
another, two that part and come back; a steady pan, an ease, a start; a fade at either end, a dark frame with
|
||||
something in it), and on four renders made for it (scratch geom.tsx, 960 x 540, 3 s each) passing through,
|
||||
the camera tripling its speed at 1.5 s and a blank second are found where they are, with nothing found on the
|
||||
clean things in those scenes; with the floating scene's AOV pass beside it, the hanging box floats from 0 s and
|
||||
neither the resting box nor the 12 posts do. Floating needs true depth: on Depth Anything's the hanging box's
|
||||
base and the floor under it read 0.71 and 0.73 (the floor is about 30% farther), so on footage it's found only
|
||||
where the model sees the gap
|
||||
|
||||
Rule: FP10. A fine-tuned or other device-sized encoder, only on evidence
|
||||
@needs:FP4b @done
|
||||
Scenario: FP10a. When an axis stays stuck
|
||||
Then an axis under its bar with 300 labels or more, after its own columns were added, may try a LoRA adapter on
|
||||
SigLIP 2's last blocks trained on the device through raea-sys-mlx with a heatmap loss as well as the axis's own
|
||||
(checked against PyTorch to cosine 0.999), or another encoder that runs locally on consumer hardware
|
||||
And the trainer for that adapter is chosen then, between MLX's autograd and Burn (a Rust training framework with
|
||||
Metal, CUDA and CPU backends), on which matches PyTorch and runs on the person's device; the heads never need
|
||||
either, since a head is a logistic fit by L-BFGS in plain Rust (head.rs) in milliseconds
|
||||
And either is kept only if it raises that axis's held-out by project AUC by 0.05 or more, at a cost the person's
|
||||
device can pay, and the result is recorded here with the date
|
||||
And 11-12, so far: report.json and `raea fingerprint report` name the stuck axes (raea-sys-fingerprint
|
||||
`stuck`: 300 labels or more, cheats not counted, and a held-out score under the gate's 0.8), the only axes that
|
||||
may try an adapter or another encoder. On this machine's fingerprints one is: glow in "me" (580 labels, all
|
||||
bootstrap damage; held out 0.79 on its look columns). Another encoder already on the device was tried first
|
||||
(a_stuck_axis_on_another_encoder, ignored, on "me"'s own evidence): on SigLIP 2's picture columns glow holds
|
||||
out 0.90, 0.11 better, on the change columns 0.52. So raea's base taxonomy reads glow from pictures (as
|
||||
FP4b's bootstrap curve already measured it); no adapter was needed, and the trainer for one isn't chosen
|
||||
@@ -0,0 +1,349 @@
|
||||
# Fingerprint: the plan
|
||||
|
||||
Shane, 2026-11-12: "build a framework within raea called Fingerprint ... a taxonomy data structure and an embedding
|
||||
model that can run on a personal device, that could be easily trained on device, to best understand if a video (its
|
||||
audio and video and whatever else we can put together into this) is good or not ... train through comments or notes
|
||||
or a post-mortem process the agent can run ... and if you have a team, you can distribute those embedding models."
|
||||
|
||||
This is the one plan for Fingerprint: what it is, the stack, how it trains, how people and agents use it, the
|
||||
measurements behind each part, and the build order with a confidence for each step. The rask tasks are in
|
||||
[fingerprint.feature](fingerprint.feature) (FP0-FP13). The reference design is
|
||||
[earshot](https://github.com/Leonxlnx/earshot) (MIT), a local sound critic for agents. It is the closest working
|
||||
system to what Fingerprint does for sound. We take its methods, not its code (see "earshot, the reference").
|
||||
|
||||
## What a fingerprint is
|
||||
|
||||
A fingerprint is not a fine-tuned embedding model. It is a **taxonomy of axes**: the things that can be good or wrong
|
||||
about a piece, such as a soft picture, dead motion, noise under the voice or a cut that drags. Each axis has the
|
||||
**words** people use for it and **one small head** over **frozen, pinned encoders that run on the person's own
|
||||
device**. On top of the axes sit the person's **weighting** across them, an optional **profile** (ranges taken from
|
||||
work they admire) and the **evidence ledger** that every head was trained from.
|
||||
|
||||
On day one, an axis's words already give it a zero-shot score. Each label the person adds retrains its head in
|
||||
milliseconds. Whatever can be measured exactly, such as loudness, silence gaps, frozen frames or one thing passing
|
||||
through another, is a check rather than a learned head. A team shares evidence, never media, and each machine
|
||||
retrains from it.
|
||||
|
||||
The hard part is turning notes into labels, not the model. On Shane's real notes, picture and sound alone can't
|
||||
predict where he will leave a note. They do learn a named axis from 4 to 32 examples, and some axes from no examples
|
||||
at all.
|
||||
|
||||
## The stack
|
||||
|
||||
```
|
||||
media ─► columns (once, at ingest, cached by content hash)
|
||||
picture: SigLIP 2 per frame at 4 fps (pooled vector; 14x14 patch grid for flagged or marked frames)
|
||||
change: frame-to-frame SigLIP distance look: luminance histogram, saturation, contrast, sharpness
|
||||
sound: CLAP audio, 2 s windows, 1 s hop YAMNet, 0.48 s frames (event classes and timing)
|
||||
text: EmbeddingGemma 2 for scripts, briefs and other text (a still gets the picture columns)
|
||||
things: a render's layers or EdgeTAM masks, depth from its AOV or Depth Anything 3, and the camera
|
||||
─► checks (no model): loudness, silence gaps, clipping, flash, freeze, sync to cut, floating, passing through
|
||||
─► axis heads: word head (zero-shot) → learned head (logistic / Bradley-Terry) → patch head (heatmap)
|
||||
─► person's weighting over axis scores ─► profile ranges from reference work
|
||||
─► summary · JSON · sheet PNG · timeline · watch lane
|
||||
```
|
||||
|
||||
| part | model | size on disk | runs at score time | cost for a 90 s render |
|
||||
|---|---|---|---|---|
|
||||
| picture columns | SigLIP 2 base p16-224 (image tower) | 95 MB int8, 372 MB fp32 | yes | 17 s on ort's CPU path (47 ms a frame); MLX on the Mac once MX5 lands; never Core ML's GPU |
|
||||
| sound columns | CLAP htsat-unfused (audio tower) | 117 MB fp32 (34 MB q8 copy, off by default) | yes | about 3 s (33 ms a 2 s clip) |
|
||||
| sound events | YAMNet | 16 MB | yes | under 1 s |
|
||||
| change and look | none | none | yes | negligible |
|
||||
| words, scripts, briefs | EmbeddingGemma 2 | 841 MB q8, the Library's copy when it has one | only for text files; a still gets the picture columns | 2.3 s a window |
|
||||
| axis words → vectors | CLAP text tower (502 MB fp32), SigLIP 2 text tower | | **no**: only when an axis's words change; the vectors are stored in the fingerprint | |
|
||||
| heads, weighting, profile | ours | 7 KB a head | yes | milliseconds |
|
||||
| things | EdgeTAM, Depth Anything 3 Small | 37 MB, 51 MB (both already in perception) | only for thing-level axes and checks | about 86 ms a frame for EdgeTAM |
|
||||
|
||||
Only CLAP is a new download. Its fp32 audio and text towers come to 619 MB. The q8 copies (161 MB) match fp32 only to
|
||||
cosine 0.998, and differ between ONNX Runtime builds, so fp32 is the default (RAEA_CLAP_DTYPE=q8 picks the copies). Every encoder runs in Rust:
|
||||
- **ONNX Runtime** (ort, through raea-sys-ml) is the path on every platform and the reference. YAMNet already runs on
|
||||
it, CLAP's audio and text towers join it, and CLAP's tokenizer is the `tokenizers` crate raea-sys-speech already
|
||||
uses.
|
||||
- **MLX** (raea-sys-mlx) is for SigLIP 2 on the Mac, the one heavy column. On this Mac, ort's CPU path costs 47 ms a
|
||||
frame and Core ML's GPU computes SigLIP wrong. SigLIP is already a named candidate for mlx.feature MX5, and it moves
|
||||
there once its MLX path matches ONNX fp32.
|
||||
- **CLAP stays on ort.** At 33 ms a clip on the CPU there's nothing to gain from rewriting its HTSAT network in MLX.
|
||||
|
||||
transformers.js (onnxruntime-node underneath, the same .onnx files) was used only to measure. Everything runs inside
|
||||
the feed host, which stays alive, so the models load once.
|
||||
earshot's CLI reloads its models on every call (20-40 s) and has to steer agents to its MCP server for that reason.
|
||||
`raea fingerprint` talks to the running host instead. Columns are cached by content hash and step version, which is
|
||||
safer than earshot's cache key of path, size, modification time and sampled blocks.
|
||||
|
||||
**Used only for labelling and training, never at score time:** the Director reading notes into labels, EdgeTAM
|
||||
growing a click into a region, the open-vocabulary grounder (gated, FP13b), the damage and red-team generators, the
|
||||
text towers, and the gated LoRA trainer (FP10).
|
||||
|
||||
**Training stays plain Rust until FP10.** The encoders are frozen and inference only, so they stay on ort. A head is
|
||||
a logistic fit on a few hundred to a few thousand rows of at most 1,024 values; L-BFGS in plain Rust fits one in
|
||||
milliseconds and needs no framework. A training framework earns its place only with FP10's adapter, which back-propagates
|
||||
through SigLIP 2; then MLX's autograd and Burn (Metal, CUDA and CPU backends) are compared on PyTorch parity and on
|
||||
what the person's device can run.
|
||||
|
||||
### Axes and their heads
|
||||
|
||||
An axis is declared in TypeScript beside `taste` (`fingerprint({...})` from "raea/brief"). It has:
|
||||
- a name and the words people use for it;
|
||||
- a modality: picture, change, look, sound, events or text (a script's, brief's or page's words);
|
||||
- a scope: moment, shot or the whole piece;
|
||||
- a polarity;
|
||||
- optionally, the check it maps to.
|
||||
|
||||
raea ships a base taxonomy drawn from Shane's notes: glitch and continuity, sound, pace, camera, cut, light and look,
|
||||
realism and detail, interaction, design and type, story. A person or team adds axes. Creative directions ("could be a
|
||||
garden door") are not axes. They go to the brief and the agent, never into a head.
|
||||
|
||||
Each axis uses the best head it has earned:
|
||||
1. **A word head** (from day one): the similarity between the window and the axis's words, as a z-score against a
|
||||
background vocabulary of about 40 ordinary descriptions. This is earshot's calibration. CLAP serves sound axes,
|
||||
SigLIP 2's text tower serves picture axes and EmbeddingGemma 2 serves text axes. A word head is always advice: it never gates.
|
||||
2. **A learned head**: logistic on the axis's own modality columns, standardised with the encoder's shipped
|
||||
statistics, plus Bradley-Terry when the axis has pairs. It takes over from the word head once it beats it on
|
||||
held-out evidence.
|
||||
3. **A patch head** (picture axes): logistic on SigLIP 2's patch tokens, trained from local defects (FP12a) and,
|
||||
once there are enough, marks (FP12b). It says *where* in the frame.
|
||||
|
||||
An axis that a check measures exactly, such as dropout or loudness, reports the check, and its head only adds what
|
||||
the check can't see.
|
||||
|
||||
## How it trains
|
||||
|
||||
1. **Day 0.** The base taxonomy's words give every axis an advisory score. `raea fingerprint bootstrap` damages
|
||||
windows of the person's own approved work (blur, dark, glow, flash, freeze, noise, dropout, clipping) and trains
|
||||
the mechanical axes from those labels by construction (FP0b). No placeholder footage is used.
|
||||
2. **Every label is an evidence row**: the media's content hash and span, the region or layer, axis, polarity,
|
||||
weight, who gave it, its source, and the window's columns (fp16, about 4 KB). The heads retrain after each row,
|
||||
in milliseconds.
|
||||
3. **Sources, strongest first:**
|
||||
1. a mark or box on a defect note (FP11);
|
||||
2. a pinned defect note, read by the Director into {kind, axis, span, layer};
|
||||
3. an approval, a picture lock, a publish or a golden reference: positives over every un-noted span;
|
||||
4. a pick between real options, or a hand edit's before and after: pairs;
|
||||
5. reference work the person admires, as a profile (FP6e);
|
||||
6. version pairs (a noted moment that changed and wasn't noted again): weak pairs;
|
||||
7. damage variants (bootstrap);
|
||||
8. the post-mortem's answers;
|
||||
9. clef's or Kimi's readings, kept as another eye's labels and never counted as the person's.
|
||||
4. **The gate.** A head is advice until it has 16 labels of each polarity from 3 or more projects, a held-out by
|
||||
project AUC of 0.8 or better, and a catch rate of 0.8 or better on its red-team cheats. A gated head reports
|
||||
bands, as earshot's verdicts do: strong, plausible or weak, each with the precision measured on that head's own
|
||||
held-out evidence.
|
||||
5. **The person's weighting** is a logistic fit over the axis scores, from their own labels (FP0c).
|
||||
6. **The post-mortem.** At a project's end, the agent scores every version, finds where the fingerprint is least sure
|
||||
or disagrees most with the person's history, and asks at most ten yes/no questions with the moment playing
|
||||
(`raea show --question`). Each answer is an evidence row.
|
||||
7. **Encoder upgrades.** A row whose media is present is re-embedded and its head retrained. A row without media keeps
|
||||
the old pin until it's labelled again.
|
||||
8. **Fine-tuning the encoder** is gated. It is tried only for an axis still under its bar with 300 labels or more after
|
||||
its own columns were added (glow is the likely first), as a LoRA adapter on SigLIP 2 trained on the device through
|
||||
MLX. It is kept only if it raises held-out AUC by 0.05.
|
||||
|
||||
## The CLI
|
||||
|
||||
```
|
||||
raea fingerprint new NAME [--team PROJECT] a fingerprint from the base taxonomy (~/.raea/fingerprints/NAME or the project's)
|
||||
raea fingerprint score FILE [--fp NAME] summary first: the moments it expects a note on, each axis in the person's words
|
||||
[--json] [--sheet out.png] [--timeline] full scores; an annotated sheet; a second-by-second reading
|
||||
raea fingerprint teach FILE --axis A --at T a label from the CLI or an agent: --bad/--good, --span, --box x0,y0,x1,y1
|
||||
raea fingerprint bootstrap [--from DIR] damage variants of approved work train the mechanical axes
|
||||
raea fingerprint profile REFS... --as NAME reference ranges from work the person admires, checked leave-one-out
|
||||
raea fingerprint report each head: labels by source, held-out score, cheats caught, gate state
|
||||
raea fingerprint postmortem PROJECT the ten questions, then the report's change
|
||||
raea fingerprint diff A B the axes two fingerprints disagree on most, with the moments
|
||||
```
|
||||
|
||||
The sheet is one PNG an agent or a person reads at a glance. It holds frames with the patch heatmaps over them, the
|
||||
axis lanes, the spectrogram with flagged sounds boxed, and the checks' findings. In the app, the same scores are a lane
|
||||
on the watch timeline. Agents get the axis, the moment and the person's words, never a number or a threshold.
|
||||
|
||||
## Teams
|
||||
|
||||
A fingerprint is a folder with these files:
|
||||
- `fingerprint.ts` (axes, words, encoder pins);
|
||||
- `words.f16` (the axis words' vectors);
|
||||
- `heads.safetensors`;
|
||||
- `evidence.jsonl` with `evidence.f16`;
|
||||
- `profiles/`;
|
||||
- `report.json`.
|
||||
|
||||
It travels with the project (Git + LFS, or raea's API) under the project's permissions. Teammates share evidence rows
|
||||
and each machine retrains: pooling beat averaging the heads (FP0c). Each person's weighting stays their own.
|
||||
Embeddings partly reveal content, so evidence never leaves the project's permissions, and media never travels at all.
|
||||
|
||||
## Agents, and keeping them honest
|
||||
|
||||
The feed's agent runs `raea fingerprint score` on a cut before posting it, and either fixes each gating flag or says
|
||||
why not. A fix is checked against the flag it claims to fix, and the axis's cheats are rerun.
|
||||
|
||||
earshot found the risk the hard way. Once a sound-making search optimised against its learned critics, those critics
|
||||
stopped telling made sounds from real ones, while its model-free measurements still could. Our own cheats agree:
|
||||
glow at half strength is caught only 0.20. So:
|
||||
- measured checks are the arbiter wherever a thing can be measured;
|
||||
- every learned axis carries red-team cheats;
|
||||
- agents never see scores;
|
||||
- like earshot's LIMITS.md, `report.json` says what each head can't judge.
|
||||
|
||||
## earshot, the reference
|
||||
|
||||
earshot is a CPU-only Python toolkit that gives agents ears. It runs CLAP (laion/larger_clap_general, Apache-2.0) and
|
||||
AST (BSD-3) over a film's sound and returns a timeline, sync checks, a critique against reference films and a
|
||||
realness score. It's honest about its measured limits. It covers sound only, and its runtime is Python and PyTorch,
|
||||
which raea doesn't ship. We take six ideas:
|
||||
|
||||
| earshot | Fingerprint | spec |
|
||||
|---|---|---|
|
||||
| text-audio match calibrated as a z against a 322-term vocabulary, with verdict bands whose precision is measured on held-out recordings | word heads from the axis words, for sound (CLAP) and picture (SigLIP 2); bands on gated heads | FP2e, FP2d |
|
||||
| `profile` reference films, `critique` against their ranges with timestamped fixes, checked leave-one-out (86% in range against a 71% baseline) | profiles from golden references and approved work: the positives that notes don't give (3 approvals in 205 notes) | FP6e |
|
||||
| realness: real against code-synthesised sound, a small head on CLAP vectors, grouped CV AUC 0.92 held out by category and engine | measured, not shipped: a head on CLAP and YAMNet means, labelled by construction from raea's own generators (TokenSynth, SAO, Fish) against recordings under CC0 and CC BY, scored 0.90, 0.80 and 0.57 held out by generator, under the 0.85 it needed on all three, so there is no realness axis | FP2f |
|
||||
| summary first, `--json`, an annotated `sheet` PNG, a `timeline` transcript | the same outputs from `raea fingerprint score` | FP3a, FP3c |
|
||||
| a resident MCP server, because loading the models costs 20-40 s | everything in the feed host, models loaded once | FP3a |
|
||||
| "model critics stop discriminating after search; model-free measurements still do"; a "cannot judge" list | checks as arbiter, red-team cheats per axis, limits in report.json | FP4b, FP4c, FP9a |
|
||||
|
||||
We don't take:
|
||||
- its Python and PyTorch runtime;
|
||||
- AST: YAMNet already serves event classes, and CLAP's heads match or beat YAMNet's on our defects;
|
||||
- its larger CLAP checkpoint (larger_clap_general), until htsat-unfused falls short on a measured axis;
|
||||
- its optional Gemini critique, which breaks the two-API-models rule;
|
||||
- its cache key.
|
||||
|
||||
Its results are not ours to quote as Fingerprint's. Our numbers for the same ideas are FP0g below.
|
||||
|
||||
## What was measured (11-12, this Mac; spike in ~/films/fingerprint-spike)
|
||||
|
||||
The data:
|
||||
- **Notes:** Shane's 205 pinned notes, with time and place, on 17 feed renders (Stay assemblies 18-23 and the launch
|
||||
film's passes b-l).
|
||||
- **Videos:** those 17 renders, the five golden references and 11 other renders: 33 videos, 34 minutes.
|
||||
- **Encoders:** SigLIP 2 base (ONNX fp32), YAMNet, EmbeddingGemma 2 (q8, through apps/app host/library/embed.ts) and
|
||||
CLAP htsat-unfused (Xenova's ONNX through the same transformers.js).
|
||||
|
||||
**FP0a. Notes alone don't say where the next note goes.** A logistic head scored 197 noted 2 s windows against 263
|
||||
windows at least 3 s from any note:
|
||||
|
||||
| features | AUC held out by video | AUC held out by film |
|
||||
|---|---|---|
|
||||
| position in the video | 0.41 | 0.40 |
|
||||
| cheap columns (brightness, contrast, motion, loudness) | 0.53 | 0.51 |
|
||||
| SigLIP 2 | 0.64 | 0.40 |
|
||||
| YAMNet | 0.54 | 0.46 |
|
||||
| EmbeddingGemma 2, picture and sound | 0.64 | 0.53 |
|
||||
|
||||
Within a film, the heads score above chance because the same scenes recur across versions. Across films they're at
|
||||
or below chance whichever encoder reads the windows, so the encoder isn't what's missing. The notes aren't good/bad
|
||||
labels:
|
||||
- about 98 name a defect, about 74 are directions (23 are both), and 3 are approvals;
|
||||
- there is one note every 3-4 s of film;
|
||||
- only 21 of 143 noted moments make a version pair.
|
||||
|
||||
**FP0b. A named axis is learned from a few examples.** Defects were put into real renders and the heads held out by
|
||||
source. Each cell is AUC at k = 4 / 16 / 32 labelled windows a class:
|
||||
|
||||
| axis | own columns (SigLIP 2, change, YAMNet) | CLAP head | CLAP words only, no labels | EmbeddingGemma 2 |
|
||||
|---|---|---|---|---|
|
||||
| blur | 1.00 / 1.00 / 1.00 | | | 0.70 / 0.90 / 0.96 |
|
||||
| too dark | 0.72 / 0.90 / 0.95 | | | 0.58 / 0.74 / 0.85 |
|
||||
| glow | 0.55 / 0.69 / 0.80 | | | 0.54 / 0.65 / 0.73 |
|
||||
| flash frame | 0.97 / 0.97 / 0.97 | | | |
|
||||
| freeze | 1.00 / 1.00 / 1.00 | | | 0.56 / 0.66 / 0.77 |
|
||||
| noise under the sound | 0.99 / 1.00 / 1.00 | 0.94 / 1.00 / 1.00 | **0.97** | 0.82 / 0.92 / 0.97 |
|
||||
| sound drops out | 0.79 / 0.94 / 0.97 | 0.86 / 0.99 / 0.99 | 0.66 | 0.68 / 0.88 / 0.94 |
|
||||
| clipped sound | 0.91 / 0.97 / 0.98 | 0.94 / 0.99 / 1.00 | **0.98** | 0.80 / 0.92 / 0.96 |
|
||||
|
||||
**FP0g. CLAP, measured 11-12.** CLAP ran on 2 s windows, 130 windows from 26 sources.
|
||||
- **Words alone.** With no labels at all, the words catch noise and clipping at AUC 0.97 and 0.98. At the threshold
|
||||
that flags 10% of clean windows, they catch 0.94 and 0.95 of the damaged ones.
|
||||
- **Dropout fails from words** (0.66): silence isn't a sound a description matches. So dropout is a check (a silence
|
||||
gap) plus a head, never a word head.
|
||||
- **Cheats.** Noise at a third of the level is caught 0.48 from words (0.78 on 5 s windows), so word heads stay
|
||||
advice.
|
||||
- **Learned heads.** CLAP heads match or beat YAMNet on every sound axis, most at k = 4.
|
||||
- **Window length.** 5 s windows change little: words 0.99 / 0.60 / 0.98; heads at k = 4 0.98 / 0.76 / 0.98.
|
||||
- **q8 copy.** It holds the numbers (words 0.99 / 0.67 / 0.97), with audio vectors at cosine 0.9975 to fp32.
|
||||
- **Cost.** 33 ms a clip on the CPU.
|
||||
|
||||
**FP1a. The Rust columns match, measured 11-12.** raea-sys-columns runs every encoder on ONNX Runtime's CPU kernels
|
||||
(raea-sys-ml), and its tests check it against the spike (systems/columns/src/tests.rs, run with --ignored):
|
||||
- **SigLIP 2's image tower** against ONNX fp32 in Python on the same frames: cosine 1.000000.
|
||||
- **CLAP's audio tower**, fp32, its log-mel front end in Rust: mean and worst cosine 1.00000 over 260 clips. The q8
|
||||
copy came to a worst cosine of 0.9978, a difference between ONNX Runtime builds rather than the front end (fp32
|
||||
against fp32 matches), so fp32 is the default.
|
||||
- **CLAP's text tower**: 1.00000 over the 40 vocabulary descriptions, once padded as transformers.js padded the
|
||||
batch. The export takes no attention mask, so raea embeds each text alone, unpadded.
|
||||
|
||||
**FP0b's lessons on method.**
|
||||
- Standardise columns. Unstandardised, SigLIP hid behind YAMNet's larger values: blur scored 0.75 at k = 32.
|
||||
- Keep each axis on its own modality. A head given both modalities was worse at small k: dropout scored 0.68 at k = 4.
|
||||
|
||||
**FP0c. Taxonomy first, then the person.** Eight shared axis heads, followed by a person's 9 weights fit from 32 of
|
||||
their labels, scored 0.84, 0.73 and 0.95 on three made-up tastes. One head fit straight on the embeddings from the
|
||||
same labels scored 0.73 and 0.64. Two opposed tastes stayed apart (each ranks the other's labels 0.38 and 0.39). Three
|
||||
teammates with 16 labels each scored 0.66 alone, 0.74 with their heads averaged, and 0.76 with their evidence pooled
|
||||
and retrained.
|
||||
|
||||
**FP0d. Cost and cheats.**
|
||||
- **Cost.** A head fits in 3.9 ms on 32 windows and 81 ms on 2,430, scores 2,430 windows in 1.6 ms, and takes 7 KB.
|
||||
- **Cheats**, at the threshold that flags 10% of clean work:
|
||||
- a de-rez sharpened afterwards is still caught 0.99;
|
||||
- noise at a third of the level 0.85;
|
||||
- glow only 0.33, and 0.20 at half strength.
|
||||
|
||||
SigLIP's pooled vector ignores a picture's look, so look axes get their own columns.
|
||||
|
||||
**FP0f. Marks teach where; pins don't.** A linear head on SigLIP 2's 14 x 14 patch tokens put local defects in real
|
||||
frames. Its top patch fell inside the defect box (chance 0.10):
|
||||
- 0.85-0.96 of the time from 8 frames marked with a click;
|
||||
- 0.89-0.99 from 8 frames marked with a box;
|
||||
- 0.23-0.62 with only "this frame is bad";
|
||||
- local glow 0.44-0.62.
|
||||
|
||||
On Shane's 203 pinned notes, a head ranks 35% of a frame's patches above the one he clicked, while his average click
|
||||
position ranks 16% above it. His pins sit near the middle of the frame (x 0.50, y 0.52). A pin anchors a note where
|
||||
it's easy to read; it doesn't mark the thing.
|
||||
|
||||
**Encoders ruled out.**
|
||||
- **PE-AV small** (Meta) is a ViT-L/14 at 336 px per frame and 3.4 GB. Shane, 11-12: "if it cant run locally on
|
||||
consumer hardware its not usable."
|
||||
- **V-JEPA 2** carries a research licence.
|
||||
- **7B grounded vision-language critics** (Q-Insight, VisualQuality-R1) fail both the consumer-hardware rule and the
|
||||
two-API-models rule.
|
||||
- **YOLOE** is AGPL.
|
||||
|
||||
The literature agrees with FP0b and FP0c. Personal aesthetics work finds per-user linear heads on frozen
|
||||
vision-language features better than prompting or LoRA (arXiv 2604.11374). Video aesthetics work keeps the encoder
|
||||
frozen (VADB, arXiv 2510.25238). Rich Human Feedback (CVPR 2024) learns heatmaps from people's points, as FP12 will.
|
||||
|
||||
## Build order, with confidence
|
||||
|
||||
| phase | step | what | confidence | why |
|
||||
|---|---|---|---|---|
|
||||
| 1, foundation | FP1 | columns at ingest: SigLIP 2, change, look, CLAP, YAMNet; EmbeddingGemma 2 rows for text files | high | every model is measured; only the look columns and CLAP's Rust front end are new |
|
||||
| | FP2 | the folder, the base taxonomy, word heads, learned heads, the trainer and the gate, in Rust | high | FP0b-d and FP0g: heads learn from 4-32 labels in milliseconds, and words already score noise and clipping at 0.97-0.98 |
|
||||
| | FP3 | `raea fingerprint score` through the feed host: summary, JSON, sheet, timeline, watch lane | high | plumbing over FP1-2; earshot shows the outputs agents can use |
|
||||
| | FP4 | bootstrap from damage variants; red-team cheats; measured checks for dropout, clipping, loudness, flash, freeze | high; glow was low on the look columns and holds out 0.90 on SigLIP 2 pictures (FP10a, 11-12) | FP0b, FP0d, FP0g |
|
||||
| 2, learning from people | FP5 | notes into evidence: the Director reads each note, checked against Shane on 50 notes (45 right on kind, 40 on axis) | medium | FP0a: notes don't label themselves |
|
||||
| | FP6 | approvals, picks, hand edits, version pairs, reference profiles | medium; profiles medium-high | the sources exist; profiles are earshot's measured method and fill the missing positives |
|
||||
| | FP7 | the person's weighting and the post-mortem | medium | FP0c works on made-up tastes; a real one needs FP5-6's labels |
|
||||
| 3, where | FP11 | markup in the review player: mark, box, lasso, arrow, strike, span, sound box | high to build, medium for uptake | FP0f: a pin isn't a mark |
|
||||
| | FP12 | patch heads and heatmaps from marks, grown by EdgeTAM | high for blur, holes, flat surfaces, noise; low for glow | FP0f |
|
||||
| | FP13 | things per shot (EdgeTAM, DA3); geometry checks; a note's nouns grounded near its pin | high, high, gated | both models are in perception; the grounder ships only if FP13b passes |
|
||||
| 4, share and use | FP8 | teams: shared evidence, retrain, diff | medium-high | FP0c measured pooling; the transport is the project |
|
||||
| | FP9 | the agent scores before posting and can't game it | medium | needs FP5-7 and red-team sets |
|
||||
| measured | FP2f | realness axis for sound | not shipped | held out by generator, SAO foley scored 0.57 against a bar of 0.85 (TokenSynth 0.90, Fish 0.80) |
|
||||
| | FP10 | a LoRA adapter on SigLIP 2, or another device-sized encoder | low | only for an axis stuck after its own columns |
|
||||
|
||||
**The first proof that matters is FP5c.** A fingerprint built from Shane's evidence on Stay assemblies 18-22 has to
|
||||
rank the moments he noted on assembly 23 above the rest at AUC 0.70 or better, held out by film. The axis it names
|
||||
has to match his words. The spike couldn't reach that bar with raw notes, and the plan stands on it. Phase 1 needs no
|
||||
notes and is worth shipping without it: a person gets word scores, checks and bootstrapped heads the day they install.
|
||||
|
||||
## Decisions taken by default (Shane can overrule any)
|
||||
|
||||
1. **Patch grid storage.** Every frame stores its pooled vector. The 14 x 14 grid (300 KB a frame, about 108 MB for a
|
||||
90 s render) is kept only for flagged or marked frames and recomputed on demand.
|
||||
2. **The note reader is the Director (Kimi).** It is checked on 50 of Shane's notes before notes train any head.
|
||||
3. **Markup tools live in apps/app's review player.** The work is coordinated with the player's owner through the
|
||||
orchestrator.
|
||||
4. **Teams share evidence rows, not heads.**
|
||||
5. **CLAP joins the stack** (Shane, 11-12: "include clap if we can if its not too much work"). It is about 300 lines
|
||||
of Rust on ort: the 48 kHz log-mel front end and the audio session (200), and the text tower with its tokenizer
|
||||
(100), run only when an axis's words change. Both are checked against the spike's vectors at cosine 0.999.
|
||||
@@ -0,0 +1,393 @@
|
||||
@spec
|
||||
Feature: Layout reads: a composition measures its text and layout as Chrome does (#54)
|
||||
Public #54 (from #13, @kevinschaich): a composition can't measure anything before it draws. snapcn's 61 free
|
||||
components (MIT) were run through raea, and 27 of them measure:
|
||||
- In 5 of them, `document.createElement("canvas").getContext("2d").measureText()` throws, because a composition has
|
||||
no `document`. `document.fonts.ready` and `document.fonts.load` are missing too.
|
||||
- In 6 of them, a ref read in an effect has no geometry and no DOM API. `getBoundingClientRect`, `offset*`,
|
||||
`children`, `querySelectorAll` and `style` are all missing.
|
||||
- The others guard with `typeof document` and fall back to guessed widths, so their layout drifts from Chrome's.
|
||||
They measure inside an effect while the first frame is held, so the read must be synchronous and the frame taken
|
||||
must be the measured one.
|
||||
|
||||
Shane, 2026-11-12, asked for the future-proof answer, and took this one: real layout reads, answered from the same
|
||||
Blitz layout that draws the frame. "lets do that ... so we do the big job completely and dont miss anything", aimed
|
||||
at 0.1.3.
|
||||
|
||||
Why this design and not the others:
|
||||
- Chrome is the bar (docs/blitz-bevy.feature). Estimated widths drift, which is the bug in the report.
|
||||
- One bridge, no parallel paths (B3). Putting compositions on @raea/ui's DOM would run a second runtime beside
|
||||
bevy-react, which also carries the 3D parts.
|
||||
- The Blitz page that draws the frame already has every box and every font, and `raea check`'s manifest reads that
|
||||
same layout. A ref then reads what the render and the checks read.
|
||||
|
||||
How it works today, which the design has to fit:
|
||||
- A composition's JS runs on its own thread (runtime/react/src/thread.rs). bevy-react sends each commit's ops as one
|
||||
JSON batch from `resetAfterCommit`, which is before React runs the layout effects. `__raea_flush` puts the batch on
|
||||
a channel and counts it (FLUSHED).
|
||||
- On the main thread, `settle` (runtime/react/src/scene/settle.rs) steps the React App: `apply_commits` turns the
|
||||
batches into entities, and settle waits on FLUSHED until the frame's marker lands. The marker is held while
|
||||
`__raeaHold.n` > 0.
|
||||
- Only after that does the host sync its BevyPage from the React World and lay it out (runtime/export/src/
|
||||
bevy_frame.rs; runtime/live/src/draw.rs; runtime/world/src/page.rs). `BevyPage::client_box(id)` already reads one
|
||||
element's box by React id.
|
||||
- `__raea_call` handlers have no World and no page. `page.viewBox` answers from a static the last layout wrote.
|
||||
- The ref handle is bevy-react's, `{ id, type, kind }`, or BevyCanvasElement for a `<canvas>`. sdk/raea/src/
|
||||
canvas2d.ts already installs the web's 2D context on it from the entry (#55), and this plan extends handles the
|
||||
same way.
|
||||
|
||||
Background:
|
||||
Given the bar is headless Chrome at deviceScaleFactor 1, with the composition's size as its viewport and the same
|
||||
font files
|
||||
And a composition that reads no layout pays nothing for this: no snapshot is made unless something asks for one
|
||||
|
||||
Rule: it is measured against Chrome from the start
|
||||
|
||||
@done
|
||||
Scenario: LR0. A harness runs snapcn's measuring components in raea and in Chrome
|
||||
Given bench/layout-reads/check.sh runs a corpus: a folder of modules each exporting Comp, conf and props
|
||||
And its own corpus, bench/layout-reads/probes, is raea's: a composition per DOM read, #54's repro first
|
||||
And snapcn's components (MIT, pinned at 18b973d7) are a corpus the private tree's adapter makes, pointing their
|
||||
imports of the package they're written for at raea's own API, a name the public tree doesn't hold
|
||||
Then each composition renders at its first, middle and last frames, in raea (`raea render --at`, with its
|
||||
manifest) and in headless Chrome (React DOM in raea's Clock, Chrome for Testing pinned by
|
||||
sdk/ui/parity/chrome.sh, mounted once its fonts are in)
|
||||
And compare.jq pairs the text runs by their words: raea's from the render manifest, Chrome's from boxes.ts,
|
||||
which makes runs the way the manifest does
|
||||
And a frame passes when every run pairs and each run's box and ink are within 1 px of Chrome's; a component
|
||||
passes when it renders without throwing and all three frames pass. 1 - SSIM of the two frames is printed too,
|
||||
for information
|
||||
And snapcn's list holds 33 components: the 27 that measure, and 6 that only hold a frame (LR9)
|
||||
And the repro probe fails today as #54 says: "here" sits at x 0, where Chrome puts it at 342
|
||||
And 11-12, the baseline (raea from the 11-12 tree, before any LR work), 3 of 33 pass:
|
||||
| outcome | components |
|
||||
| throws: no `document` | bloom-lockup, hello-zoom, sky-lockup, spec-sweep, title-sweep |
|
||||
| throws: refs have no DOM | karaoke-captions, word-captions (getBoundingClientRect), text-reveal (NaN |
|
||||
| | from offsetWidth), text-rewrite (querySelectorAll), type-morph (children), |
|
||||
| | search-typing (style) |
|
||||
| throws: canvas | orb-swarm (putImageData) |
|
||||
| panicked | text-build, text-swell: the black-frame warning read a text node's box |
|
||||
| | (559d8274e, #96), fixed on its own lane. Both now render, and drift |
|
||||
| drifts | announce-title (to 72 px), block-wordmark, capture-reveal, check-cycle, |
|
||||
| | drop-line, font-shuffle, portal-intro (13.5), prompt-send (87), punch-lines |
|
||||
| | (30), status-cycle, text-select, word-flip (37), word-gather (16) |
|
||||
| hold only, drift | card-rail (161), hero-launch (5), wordmark-cut (47) |
|
||||
| hold only, pass | channel-thread, logo-collapse, pulsing-border |
|
||||
And "drifts" with no number means raea's words have no box of their own and fall to an ancestor's (check-cycle's
|
||||
all go to the frame's), or are missing from raea's frame
|
||||
And 11-12, after LR1-LR10, 23 of 33 pass. The gap left, each with its cause, is LR10's "Still off" list:
|
||||
announce-title, capture-reveal, font-shuffle, portal-intro, prompt-send, search-typing, status-cycle,
|
||||
text-build, word-gather and card-rail
|
||||
|
||||
Rule: a read gets the layout that draws the frame, synchronously
|
||||
|
||||
@needs:LR0 @done
|
||||
Scenario: LR1. A synchronous layout call answered by the page
|
||||
Given the composition's JS asks `page.layout` while an effect runs
|
||||
Then the JS thread blocks until the main thread answers
|
||||
And the main thread answers from inside settle's wait, without waiting for the frame's marker. It applies the
|
||||
batches in the inbox, syncs the BevyPage from the React World, lays it out, and returns the boxes of every
|
||||
element at once, keyed by React id
|
||||
And that wait wakes on a layout request, as it wakes on a flush (the FLUSHED condvar)
|
||||
And the JS caches the answer until its next op_flush, so a burst of reads costs one layout
|
||||
And a request that gets no answer within HANG_SECS fails the render, saying which call hung
|
||||
And the page the host owns is lent to settle for the wait, on the main thread (BevyPage isn't Send): a
|
||||
scoped thread-local, or a parameter, chosen when it's built
|
||||
And with no page to answer (a host that lays nothing out), the call says so, and the ref's reads throw an error
|
||||
that names the host, instead of returning guesses
|
||||
And 11-12, built:
|
||||
- The page is a parameter: `settle_with(app, want, secs, answer)`, where `answer` lays the host's page out
|
||||
from the World. Plain `settle` answers "this host lays no page out", so every host is still a choice
|
||||
LR2 makes.
|
||||
- Each runtime has its own ask (runtime/react/src/layout.rs: a LayoutAsk resource in its App, the same Arc
|
||||
on its JS thread). One process runs several runtimes: a render's 3D-rows pre-pass, and a bake's workers
|
||||
on threads. A shared ask would let one runtime's page answer another's read.
|
||||
- The answer is raea-sys-page's snapshot, the one an app page's DOM already reads (runtime/dom now uses
|
||||
it too). With offsets it adds `o`, from blitz-dom's offset_rect and offsetParent: offsetLeft, offsetTop,
|
||||
offsetWidth, offsetHeight, the offsetParent's React id, and whether the element is a non-atomic inline.
|
||||
- The render and export answer from their frame's page: the still loop, the 3D loop and the fed render.
|
||||
bevy_frame.rs's layout_answer syncs the page at the frame's time, lays it out, and snapshots it. Passes
|
||||
that draw no page get an answer with no boxes, where every read is 0. Those are the sound pass and the
|
||||
3D-rows pre-pass (raea-bake's step_frames).
|
||||
- sdk/raea/src/page-layout.ts parses the answer once and keeps it until the next op_flush or raea-frame.
|
||||
A composition that never reads makes no snapshot.
|
||||
- With LR3's getters, bench/layout-reads/probes pass against Chrome. In repro, "here" is at x 342 as in
|
||||
Chrome (Inter at 64 px). geometry prints each value it read, and all match Chrome's words.
|
||||
|
||||
@needs:LR1
|
||||
@done
|
||||
Scenario: LR2. Every host that runs a composition answers
|
||||
Then each host below answers LR1's call, or states plainly why it can't:
|
||||
| host | where |
|
||||
| render and export | runtime/export/src/bevy_frame.rs |
|
||||
| preview and live play | runtime/live/src/draw.rs |
|
||||
| the world's page | runtime/world/src/page.rs |
|
||||
| bake | runtime/bake |
|
||||
| the lite entry | runtime/bundle/src/entry.rs |
|
||||
| the portable bundle | the iPhone's player |
|
||||
| an exported game | raea-app-game's player |
|
||||
And in live play a read costs at most one frame's wait, which is stated with its measurement
|
||||
And 11-12, built:
|
||||
- Render and export, a bundle drawn by render_bundle (the portable bundle's player) and the fed render answer
|
||||
from their frame's page (LR1). The sound pass and the 3D rows' pre-pass draw no page and answer with no
|
||||
boxes (layout::nothing_drawn).
|
||||
- Live play (preview, raea play, the app's stage and an exported game, all runtime/live step_inner) answers
|
||||
from its live page: settle_with syncs the page to the World mid-settle, lays it out and snapshots it.
|
||||
- Live play runs on raea's lite runtime (sdk/react/js/lite), which set no refs, so a ref was null there and
|
||||
a canvas drawn through one drew nothing. Lite's hosts now keep bevy-react's nodes (BevyElement,
|
||||
BevyCanvasElement, BevyTextNode) linked as React's tree is, and set a ref when its host is made and clear it
|
||||
when it's dropped. entry_lite installs canvas2d and the DOM reads as React's entry does.
|
||||
- raea world answers from the page it lays its frames out with (made for a read even under --no-layout).
|
||||
- A baked timeline (raea play --baked) lays no page out while it bakes: a read is refused with "a baked timeline
|
||||
(raea play --baked; play it without --baked) lays no page out", not baked as 0.
|
||||
- #54's repro played live puts "here" at x 342, as the render and Chrome do (x 0 before). Every probe
|
||||
(geometry, tree, document, measure, observe, hold) played live is the render's frame (SSIM 1.000), and
|
||||
sdk/react/bench/games/replay.sh (pong, platformer: lite against React) stays at SSIM 1.000.
|
||||
- The cost, measured on a 640x720 page of 40 lines, one getBoundingClientRect a frame at 60 fps (raea play
|
||||
--offscreen --no-vsync, 5 s, twice): a frame's step p50 0.39-0.41 ms without the read, 1.8-2.0 ms with it;
|
||||
work p50 3.8-4.2 ms against 4.3-5.0 ms. Under a tenth of a 60 fps frame.
|
||||
|
||||
Rule: a ref has the DOM a web component reads
|
||||
|
||||
@needs:LR1 @done
|
||||
Scenario: LR3. Geometry on refs
|
||||
Then a ref's element has getBoundingClientRect() (a DOMRect: x, y, width, height, top, left, right, bottom and
|
||||
toJSON) and getClientRects()
|
||||
And it has offsetWidth, offsetHeight, offsetLeft, offsetTop and offsetParent; clientWidth, clientHeight,
|
||||
clientLeft and clientTop; scrollWidth, scrollHeight, scrollLeft and scrollTop
|
||||
And each value means what it means in Chrome: getBoundingClientRect includes transforms, offset* doesn't, and
|
||||
both are in the composition's CSS px
|
||||
And #54's repro measures its span as Chrome does (the issue's `335` was its own font; with the harness's Inter
|
||||
both put "here" at x 342)
|
||||
And 11-12, built:
|
||||
- bevy-react 0.8.1 gets a patch (sdk/react/js/patches, applied by bun install). Its instances become a tree:
|
||||
BevyElement and BevyTextNode, with parentNode, childNodes, props and text as React last committed them.
|
||||
That gives refs a class to carry the DOM, and it's LR4's tree.
|
||||
- sdk/raea/src/dom-reads.ts puts the reads on BevyElement's prototype, from the entry, as canvas2d.ts
|
||||
installs the 2D context. The values are Chrome's: offset*, client* and scroll* are whole px, a
|
||||
non-atomic inline's client* and scroll* are 0, an element that isn't displayed reads 0 with a null
|
||||
offsetParent, and offsetParent is the nearest positioned ancestor or the composition's root for the body.
|
||||
- getClientRects answers one rect, so an inline element's line fragments come joined. Per-line rects come
|
||||
with LR7's Range.
|
||||
- bench/layout-reads/probes/geometry.tsx prints every read as words, and they match Chrome's: offset, client
|
||||
and border of a padded, bordered box; the bounds of a rotated box; the offsets and offsetParent of a box
|
||||
inside it; a span's offsets with client 0; and a scroller's scroll sizes.
|
||||
- The bundle crate was at its 2000-line limit: the stylesheet url() rewriter moved to raea-runtime-cssurls.
|
||||
|
||||
@done
|
||||
Scenario: LR4. The tree on refs
|
||||
Then a ref's element has children, childNodes, firstChild, lastChild, firstElementChild, lastElementChild,
|
||||
nextSibling, previousSibling, nextElementSibling, previousElementSibling, parentNode and parentElement,
|
||||
tagName, nodeName and nodeType, id, className, classList, dataset, getAttribute and hasAttribute,
|
||||
textContent, contains, matches, closest, querySelector and querySelectorAll
|
||||
And these are answered in JS from the bridge's own instances, which hold the tree as React last committed it,
|
||||
with no call to Rust
|
||||
And the selectors cover tag, #id, .class, [attr], [attr=v], descendant, child, :first-child, :last-child,
|
||||
:nth-child() and :not(), and an unsupported selector throws a SyntaxError, as Chrome's does
|
||||
And 11-12, built:
|
||||
- sdk/raea/src/dom-tree.ts installs these from the entry, with dom-reads. Text nodes also get nodeType,
|
||||
nodeName, textContent, the siblings and parentElement. Elements also get localName, childElementCount,
|
||||
innerText, hasChildNodes, getElementsByTagName and getElementsByClassName. The selectors also cover *,
|
||||
:only-child and [attr~= ^= $= *=], and comma lists.
|
||||
- An attribute is read from the committed props: class from className, for from htmlFor, style as text.
|
||||
A <text> holding a single string keeps it in its props, and textContent reads it there.
|
||||
- `el.id` is the element's id attribute, as on the web. bevy-react kept its reconciler id in `id`, which
|
||||
hid that, so the patch renames it `nodeId`. raea's own readers of it (canvas2d, dom-reads, useEntity)
|
||||
read nodeId, and fall back to id on an unpatched bridge.
|
||||
- classList reads only: add, remove and toggle change the class, which is LR5's writing to an element.
|
||||
- bench/layout-reads/probes/tree.tsx walks and queries a list and prints each answer, and the words match
|
||||
Chrome's: children and querySelectorAll counts, siblings, closest's id, matches with a child combinator
|
||||
and :not, nth-child(odd), classList, dataset, getAttribute, contains, textContent, and the SyntaxError.
|
||||
|
||||
@needs:LR1 @done
|
||||
Scenario: LR5. style and getComputedStyle
|
||||
Then el.style reads the element's style prop, and writing it (a property, setProperty or cssText) sends an
|
||||
update op, as canvas2d.ts sends a canvas's draws. React's next commit to the same key wins, as in Chrome
|
||||
And getComputedStyle(el) answers from the page's computed style, carried in the LR1 snapshot only when it's
|
||||
asked for
|
||||
And 11-12, built:
|
||||
- sdk/raea/src/dom-style.ts. el.style is a CSSStyleDeclaration over the style React committed, with the
|
||||
composition's writes over it. A write sends an update op (style, styleUnset) at once. React's own update
|
||||
to a property the composition wrote takes it back.
|
||||
- page.layout takes { styles: [ids] }. The snapshot then carries s: {id: {property: value}}, from stylo's
|
||||
computed values (engine/page read.rs computed_style: display, position, fonts, spacing, box sizes,
|
||||
transform and the rest), serialized as Chrome serializes them (18px, rgb(51, 85, 170)).
|
||||
getComputedStyle reads it once per element per commit (page-layout.ts computedOf). A property the page
|
||||
doesn't answer falls back to the element's own style.
|
||||
- probes/document.tsx prints a computed font-size, weight and colour, and they match Chrome's words.
|
||||
|
||||
Rule: the composition has a document
|
||||
|
||||
@done
|
||||
Scenario: LR6. measureText measures with the real fonts
|
||||
Then `document.createElement("canvas").getContext("2d")` is @raea/ui's 2D context, the one canvas2d.ts installs
|
||||
And its measureText returns TextMetrics (width, actualBoundingBoxLeft, actualBoundingBoxRight,
|
||||
actualBoundingBoxAscent, actualBoundingBoxDescent, fontBoundingBoxAscent and fontBoundingBoxDescent)
|
||||
shaped from the font files the page draws with, through a synchronous native call
|
||||
And a composition's <canvas> ref measures the same way, so canvas text no longer depends on the `fonts` event's
|
||||
estimates
|
||||
And the 2D context has putImageData and getImageData that read back what it drew (orb-swarm throws without
|
||||
putImageData)
|
||||
And with the same font, the width is within 0.5 px of Chrome's
|
||||
And 11-12, built:
|
||||
- systems/canvas measure.rs: measureText is the text shaped by usvg as the canvas draws it (canvas.measure),
|
||||
its advance and font box usvg's layout box, its ink the glyphs' outlines. getImageData draws the context's
|
||||
list on a bitmap of its own and reads it back (canvas.read); putImageData writes its pixels as they are.
|
||||
raea-runtime-canvas serves them as natives, reached through @raea/ui's wire (canvas2d.ts __ui_sync).
|
||||
- raea's bundled faces (Inter and the rest) now reach usvg's font database too (systems/fonts), so a canvas
|
||||
measures and draws in them, not a fallback: the probe's width had been 314.6 against Chrome's 368.8.
|
||||
- probes/measure.tsx matches Chrome: the width exactly, ink and font box within 0.8 px, the pixels read back
|
||||
equal. orb-swarm (putImageData) passes.
|
||||
|
||||
@needs:LR1 @done
|
||||
Scenario: LR7. document's other parts
|
||||
Then document.fonts has ready, load(font) and check(font). ready and load resolve once the faces the composition
|
||||
asked for (loadFont, @font-face, packaged fonts) are in the page
|
||||
And document has body, documentElement, getElementById, querySelector and querySelectorAll over the
|
||||
composition's tree, plus createElement, createTextNode and createRange (a Range's getBoundingClientRect and
|
||||
getClientRects over text: search-typing places its caret by one)
|
||||
And an element made with createElement and appended into the composition is laid out and measurable, then
|
||||
drawn or removed as in Chrome. Components measure that way: they append a hidden copy, read it, and remove it
|
||||
And window has innerWidth, innerHeight and devicePixelRatio for the composition's size, and getComputedStyle
|
||||
And 11-12, built:
|
||||
- sdk/raea/src/dom-document.ts. document.body is the composition's surface, the element the page draws from
|
||||
(React's root container sits above it, and a node appended there was never laid out). createElement makes a
|
||||
node of the page: appended it's laid out and measured, removed it's despawned, appended again it's made
|
||||
again. A canvas made there is an OffscreenCanvas.
|
||||
- document.fonts.load and a family-named FontFace load a family the composition asked for (fonts.load). A
|
||||
FontFace given by URL is fetched through raea's cache into the faces an svg's and a canvas's text are set
|
||||
in (fonts.face); one that doesn't load rejects, so the text falls back, as in Chrome. ready is settled: the
|
||||
page's own text has its faces before the frame is taken.
|
||||
- dom-range.ts. A Range over a text node is its characters laid out in the parent's computed font, placed
|
||||
where the parent's line starts (an inline parent's box, or a block's content box as its text-align sets
|
||||
the line). One line only: a range across wrapped lines gets one rect, the width of its characters. A range
|
||||
over elements is their boxes.
|
||||
- dom-svgtext.ts. An svg <text> has getComputedTextLength, getNumberOfChars, getStartPositionOfChar,
|
||||
getEndPositionOfChar and getSubStringLength. Components read them off hidden text (an opacity-0 group),
|
||||
which the page's svg never lays out, so the words are laid out on their own by usvg (canvas.svgText), in
|
||||
the element's computed font, letter- and word-spacing and font-variation-settings included. Chrome's length
|
||||
tracks the last character too; usvg's box doesn't, so the tracking is added back.
|
||||
- probes/document.tsx matches Chrome within 1 px: an svg text's length (tracked and not) and a character's
|
||||
start, a Range's width and a prefix's, a node made, measured and removed, and lines set with word- and
|
||||
letter-spacing. capture-reveal and font-shuffle (svg text in URL faces) and search-typing (a Range) no
|
||||
longer throw or hang.
|
||||
|
||||
@done
|
||||
Scenario: LR8. Observers, from the same layout
|
||||
Then ResizeObserver calls back after a layout in which an observed element's size changed, with
|
||||
contentRect, borderBoxSize and contentBoxSize
|
||||
And MutationObserver and IntersectionObserver are present. Each calls back if the harness shows a component needs
|
||||
it, and otherwise exists but never fires, which is stated in the manual
|
||||
And 11-12, built:
|
||||
- sdk/raea/src/dom-observers.ts. ResizeObserver calls back once on observe and after any commit whose layout
|
||||
changed an observed element's size. While a delayRender hold is open it checks every 16 ms, as a browser
|
||||
goes on rendering while a page waits. It reads the layout only while something is observed.
|
||||
- No snapcn component makes an observer, so MutationObserver and IntersectionObserver exist and never call
|
||||
back (LR11's manual page says so).
|
||||
- A pass that draws no page (the sound pass, the 3D rows' pre-pass) answers every read with a 0 x 0 page.
|
||||
A hold waiting on a size there could never end, so on that answer the pass's holds are released and later
|
||||
ones don't hold (hold.ts noPage).
|
||||
- The harness's Chrome ran no rendering step: a headless --dump-dom under --virtual-time-budget fires neither
|
||||
requestAnimationFrame nor ResizeObserver. bench/layout-reads/chrome.ts drives the same Chrome through
|
||||
Playwright in real time. probes/observe.tsx then matches Chrome (0.1 px).
|
||||
|
||||
Rule: the frame waits for the measure
|
||||
|
||||
@done
|
||||
Scenario: LR9. delayRender and continueRender
|
||||
Then "raea" exports delayRender(label?), continueRender(handle) and cancelRender(error) on the hold that @raea/r3f
|
||||
already uses (__raeaHold)
|
||||
And a frame is taken only after every handle is continued
|
||||
And a handle still open after the hold's timeout fails the render, naming its label
|
||||
And a component written for this pattern (measure in an effect, then continue) draws its measured layout on the
|
||||
held frame itself, not the frame after
|
||||
And 11-12, built:
|
||||
- sdk/raea/src/hold.ts. delayRender(label?, { timeoutInMilliseconds }) opens a hold. Its timer (30 s,
|
||||
HOLD_TIMEOUT_MS) fails the render as `cancelRender: "LABEL" was held for N ms and never continued`.
|
||||
continueRender releases it, and the last release wakes the frame. A handle released twice does nothing.
|
||||
cancelRender sends a data-raea-error, which the render reports as a composition's throw.
|
||||
- Settle's guard against a stalled frame (20 s with nothing moving) would have failed a held frame before
|
||||
the hold's own timeout. A frame whose marker is at the frame but not done now waits up to HOLD_SECS
|
||||
(120 s), then fails saying it was held. The same applies to <R3F> scenes that never finish loading,
|
||||
which used to fail at 20 s.
|
||||
- bench/layout-reads/probes/hold.tsx holds its frame, sets its words after a 300 ms timer, and continues.
|
||||
The frames match Chrome's words. A composition whose hold is never continued fails in 2.6 s with its
|
||||
label (timeout 2000 ms).
|
||||
- The manual has a page for it, docs/manual/reference/sdk/hold.md.
|
||||
|
||||
Rule: it's finished when the harness passes, nothing got slower, and users can read about it
|
||||
|
||||
@needs:LR3,LR4,LR5,LR6,LR7,LR8,LR9 @done
|
||||
Scenario: LR10. The harness passes, and no render got slower
|
||||
Then LR0's harness passes, with any remaining gap listed in LR0
|
||||
And a composition that doesn't read layout renders exactly as before: identical frames on the P26 set, and no
|
||||
more time than before
|
||||
And a composition that measures every frame (karaoke-captions, 300 frames) has its cost per read and per frame
|
||||
measured and written here
|
||||
And sdk/raea/conformance covers the JS side, and Rust tests cover the call, the wait and the hang guard
|
||||
And 11-12, in progress (snapcn: 3 of 33 before LR work, 7 after LR1-LR9, 12 after the usvg and font fixes, 17 with kerning and the manifest, 21 with the fonts, 23 now):
|
||||
- Kerning across spans. blitz-dom gave every composition span a border edge: with `border-style: none` (the
|
||||
initial style) a border's computed width is still `medium`, and inline_edges read the width alone, so each
|
||||
plain span got a zero-width spacer box at both ends and parley split its shaping there. "AVAWATAVAWAT" in a
|
||||
span a letter was 632 px against 578 written once; Chrome draws both at 578. An app page never showed it
|
||||
(Tailwind's preflight sets border-width: 0). sdk/ui/parity's p13-text/kerning-spans holds it. word-flip
|
||||
(its typed letters a span each, 5.6 px wide) passes.
|
||||
- A visibility: hidden inline element's text isn't drawn (blitz-paint drew every glyph run; only boxes were
|
||||
hidden), though it keeps its place: #13's word-flip strut showed as a fake "features".
|
||||
- A render manifest's frames: a still that drew all black and was drawn again listed the frame twice (the fed
|
||||
render popped the first draw's entry, the still loop didn't), so every later frame was read one place late.
|
||||
check.sh now finds each frame by its number. text-reveal and text-swell pass.
|
||||
- A manifest text's ink spans its glyph runs and inline-blocks, not the line's whole advance: an inline
|
||||
element's padding at a line's end (a caption's word pill) isn't ink. karaoke-captions and word-captions
|
||||
pass.
|
||||
- A canvas's `system-ui` and `BlinkMacSystemFont` are macOS's SF ("System Font", variable in weight and optical
|
||||
size), as Chrome's canvas takes them: fontdb knew neither, so a list headed by them was measured in
|
||||
Helvetica, about 10% wider at 72px. text-build, which places its words from measureText, went from 9 px off
|
||||
to 1.3: what's left is SF's `trak` table (CoreText tracks SF about 0.12 px a letter at 72px; usvg doesn't).
|
||||
- A Google family from raea/text's loadFont is fetched when loadFont is called, and a canvas and svg text have
|
||||
it too. The page fetched it at the first layout that named it, after a component's first effect had measured
|
||||
(its canvas found the fallback), and a family the page fetched first never reached the canvas's faces at all.
|
||||
Figtree's "scene" at 600 64px measured 145.72 against Chrome's 171.25, now 171.26. An app-bundled face of a
|
||||
family the page already gave is left out (Geist fetched at import came before the bundled Geist).
|
||||
bloom-lockup passes (40.8 px off before), word-gather is 1.2 px off (25.5 before).
|
||||
- A loadFont family's faces are the page's even where raea bundles faces of that name, as a linked
|
||||
stylesheet's @font-face shadows a local font. Inter is bundled (static 400 and 700), so it was never missing
|
||||
and Google's never came: raea drew 300, 400 and 500 alike (345.45 px at 100px for "snapcn"; Chrome 340.39,
|
||||
345.47, 350.45) and 600 as 700. Now 340.33, 345.45, 350.48, 355.38, 360.45. wordmark-cut (22 px narrow at 500),
|
||||
text-select and hero-launch pass; punch-lines 18.1 -> 0.9, text-rewrite 7.4 -> 0.2 (box; ink 1.9).
|
||||
- getBoundingClientRect through a perspective is the box of the four corners as drawn (blitz-dom's
|
||||
transformed_bounds took only the affine part, so a card turned under a perspective read at its flat size
|
||||
and place); one in a preserve-3d context is mapped from its context root's parent. Chrome's numbers for a
|
||||
400x200 card under a 1000px perspective, flat and in a turned world, are a blitz-dom test. A manifest text's
|
||||
ink goes through the same transforms. card-rail 161.4 px off -> 0.6 (ink 1.7), announce-title 11504 -> 43.5;
|
||||
punch-lines and text-rewrite pass.
|
||||
- Still off (10): announce-title (frame 0's runs), capture-reveal (3 runs only raea has), font-shuffle,
|
||||
portal-intro, prompt-send (ink 1.8), search-typing (1.5), status-cycle, text-build (SF's trak),
|
||||
word-gather and card-rail (ink 1.7).
|
||||
- The cost, measured 11-12 on the M5 Pro (300 frames, 1280x720, 40 inline-blocks of Inter whose text changes
|
||||
every frame, rendered to hashes, median of 6): no reads 2.034 s, one getBoundingClientRect a frame 2.151 s,
|
||||
ten a frame 2.180 s. The first read in a frame costs about 0.39 ms (one layout synced); each further read in
|
||||
that frame about 0.01 ms (the answer is cached until the next flush). snapcn's karaoke-captions (150 frames at
|
||||
its defaults) reads two rects when a card mounts and once more when Montserrat is ready, not every frame:
|
||||
0.74 s with its reads, 0.75 to 0.77 s with them replaced by 0, the same frames, so its reads cost less than
|
||||
the run's noise.
|
||||
- P26 with these: 185 of 215 frames at the bar, the same frames at the same SSIM (to six places) as a binary
|
||||
before them. The 12 compositions under it are all 3D (classbg, datamaps, paint, planes, texmaps, the four
|
||||
volumetric benches, box3d, arena3d) plus css/edit.tsx, which throws before its first commit; the volumetric
|
||||
three draw no page text, so the shared tree's 3D work moved them, not this.
|
||||
|
||||
@needs:LR10 @done
|
||||
Scenario: LR11. Docs, skills, and the issues
|
||||
Then the manual and the skills' sdk reference say what a composition's DOM has, and what it lacks
|
||||
And #54 is answered with the harness's before and after, and closed
|
||||
And #13 is answered with what now matches Chrome
|
||||
And 11-12, done:
|
||||
- docs/manual/guides/web-components.md: measuring then letting the frame be taken (delayRender, loadFont),
|
||||
what a ref, document and window answer, and what's missing (MutationObserver and IntersectionObserver never
|
||||
call back, an img's onError never fires, a wrapped Range is one rect, a pass with no page reads 0, no
|
||||
innerHTML or outerHTML).
|
||||
- The skills: the motion router's rule 2 names the web APIs and the modules that install them (raea-skills
|
||||
#50). It merges into raea-skills main when 0.1.2 is published (it is on fingerprint-docs, the skills
|
||||
0.1.2 pins), because raea-skills main is what the Claude plugin serves to people on 0.1.1.
|
||||
- #54 is closed with the harness's 3 of 33 before and 23 of 33 after, and the cost per read; #13 is answered
|
||||
with what now matches Chrome and what's left.
|
||||
@@ -0,0 +1,97 @@
|
||||
Feature: One project layout: compositions, components, controllers, assets, artifacts; and the workspace's shared/
|
||||
Shane, 11-12: "reorganize the default project organization to remove "parts" and really align around the folders of
|
||||
compositions, components, controllers, assets, artifacts. this should be the default, and at the workspace level
|
||||
having a library that any project can call upon from those global folders." On naming: "just make sure it doesn't
|
||||
get confused with our other concept of libraries" (docs/libraries.feature: indexed media, `raea library`), so the
|
||||
workspace's folder is shared/ and its import prefix @shared/. Existing projects move with a command, reviewed
|
||||
before they land; `raea part` becomes `raea component`.
|
||||
|
||||
Read 11-12, before any change:
|
||||
- `raea project new` (apps/workspace/src/workspace.rs new_project) makes brief.ts, AGENTS.md, media/, brand/, out/.
|
||||
Compositions and components are loose .tsx at the project's root, told apart by `raea project scan` (PJ8).
|
||||
- Agents made parts/ by hand in stay and orientation (scene pieces); nothing scaffolds it. "Parts" is otherwise
|
||||
raea's own sets: `raea part add reel` copies examples/parts/reel into components/reel/ (engine/cli index.ts,
|
||||
registry.gen.ts from tools/pack.ts).
|
||||
- The workspace root has controllers/ (PJ2) and artifacts/; 11-07 (docs/organize.md) made controllers per project.
|
||||
- The engine's loader (engine/modules resolve) takes relative imports inside the space and prebuilt libraries by
|
||||
name; anything else is refused (UnknownLibrary, OutsideSpace). PJ8's lint flags a component imported from
|
||||
outside the project's folder.
|
||||
|
||||
Built 11-12 (lane layout): LY1 (raea project new and workspace init make the folders, .gitattributes, AGENTS.md
|
||||
and the @shared/ tsconfig), LY2 (the loader resolves @shared/, PJ8's lint takes it), LY3's scan and lint and
|
||||
controllers over shared/controllers/, and LY4's `raea component` (`raea part` still answers). Still to do: LY3's
|
||||
app pages (Compositions, Controllers, Source), LY4's examples/components rename and the guides and skill wording,
|
||||
LY5 (`raea project tidy`), LY6.
|
||||
|
||||
The layout:
|
||||
|
||||
<workspace>/
|
||||
.raea/workspace, taste.ts, projects/, attachments/ as now
|
||||
shared/ what every project in the workspace can call on
|
||||
compositions/ components/ controllers/ assets/ artifacts/
|
||||
<workspace>/projects/<name>/
|
||||
.raea/project, brief.ts, <name>.script.ts, AGENTS.md what the project is (as now, at its root)
|
||||
compositions/ what renders: a registerRoot <Composition>, or a default export; versions NAME-v2.tsx
|
||||
components/ what compositions import: props as rigs (component-library-first), raea's sets
|
||||
controllers/ the project's controllers (PJ2), over shared/controllers/ by id
|
||||
assets/ media in: footage, stills, audio, models, fonts, the brand kit (assets/brand/)
|
||||
artifacts/ the small React apps agents post to the feed
|
||||
out/ renders (LFS, as now)
|
||||
|
||||
Scenario: LY1. A new project and a new workspace have the layout
|
||||
When `raea project new NAME` makes a project
|
||||
Then its folder has compositions/, components/, controllers/, assets/ and artifacts/ (each kept with a .gitkeep),
|
||||
out/, brief.ts and AGENTS.md, and no media/, brand/ or parts/
|
||||
And `raea workspace init` makes shared/ with the same five folders, and no root controllers/ or artifacts/
|
||||
And .gitattributes keeps assets/** and out/** in LFS (shared/assets/** too)
|
||||
And AGENTS.md says where each kind of file goes, in a line each, and that @shared/ is the workspace's
|
||||
And `raea init` in a loose folder makes compositions/edit.tsx and components/, not edit.tsx at the root
|
||||
|
||||
Scenario: LY2. A project imports from the workspace's shared/ by @shared/
|
||||
Given shared/components/desk.tsx in the workspace
|
||||
When a project's composition imports "@shared/components/desk"
|
||||
Then the engine's loader resolves it to the workspace's shared/components/desk.tsx (walking up to .raea/workspace),
|
||||
as it resolves a relative import, with the same extensions and index files
|
||||
And a render, `raea check`, `raea context` and the app's Compositions page all read it the same way
|
||||
And TypeScript resolves it too: the project's tsconfig (made by `raea project new`, kept by `raea doctor --fix`)
|
||||
maps @shared/* to ../../shared/*, so an editor and tsc follow the import
|
||||
And @shared/ outside a workspace is refused with what to do (UnknownLibrary's message names shared/)
|
||||
And PJ8's lint no longer flags an @shared/ import; a relative import that climbs out of the project still is,
|
||||
with @shared/ as the fix when the file is in shared/
|
||||
|
||||
Scenario: LY3. One reading of the layout, everywhere
|
||||
When `raea project scan`, the app's Compositions, Controllers and Source pages, and `raea context` read a project
|
||||
Then compositions come from compositions/ and components from components/, each also from shared/ (marked shared)
|
||||
And a .tsx elsewhere in the project is still read by what it is (PJ8), and linted as out of place with the folder
|
||||
it belongs in as the fix
|
||||
And controllers are the project's controllers/ over shared/controllers/ by id (a project's own wins), so the 11-07
|
||||
per-project copy is no longer needed: `raea controller ls` says which are shared
|
||||
And Source's Assets tab lists assets/ (and shared/assets/), and its Artifacts tab artifacts/ (and shared/artifacts/)
|
||||
And an agent's feed_post of an artifact writes it to the project's artifacts/
|
||||
|
||||
Scenario: LY4. `raea component` replaces `raea part`
|
||||
When `raea component list` or `raea component add reel [--shared]` runs
|
||||
Then it lists and copies raea's sets as `raea part` did, into components/<set>/ (or shared/components/<set>/)
|
||||
And examples/parts is examples/components, and registry.gen.ts is packed from it
|
||||
And `raea part ...` still works for this release, saying once that it's `raea component` now
|
||||
And the guides, the raea skill and AGENTS.md say components, never parts
|
||||
|
||||
Scenario: LY5. An existing project moves into the layout with one command
|
||||
When `raea project tidy [NAME] [--dry-run]` runs on a project in the old layout
|
||||
Then each file goes where its kind belongs, as the scan reads it: compositions (and their versions) to
|
||||
compositions/, the .tsx they import to components/ (parts/ and its subfolders as components/<same path>),
|
||||
controllers to controllers/, media/ and brand/ to assets/ (assets/brand/), artifacts to artifacts/
|
||||
And brief.ts, scripts, notes (.md) and out/ stay where they are; anything it can't place is listed, not moved
|
||||
And every import that names a moved file is rewritten (relative paths, media imports), and so are the paths the
|
||||
project's feed items, render manifests and checks name
|
||||
And --dry-run prints the moves and rewrites and changes nothing
|
||||
And it proves the move before it commits: the scan has no new lint, tsc passes if it passed before, and each
|
||||
composition's first frame renders as it did (raea check --quick); a failure undoes the move
|
||||
And it is one commit per project, moves as renames (git mv), so history follows each file
|
||||
And the workspace's root controllers/ and artifacts/ move to shared/ the same way (`raea workspace tidy`)
|
||||
|
||||
Scenario: LY6. The Raea workspace is tidied
|
||||
Given the Raea workspace (~/Documents/raea/raea): stay, orientation, v0-1-launch and two untitled projects
|
||||
When each is tidied, its --dry-run read by Shane first
|
||||
Then each project's feed still opens with its items playing, its compositions render, and nothing is lost
|
||||
And `raea doctor` in an old-layout project says to run `raea project tidy`
|
||||
@@ -31,6 +31,95 @@ Feature: Lightspeed: raea as fast as anything could be, with the best quality, m
|
||||
And it updates the row here (value, date, commit) and appends a line to the log at the bottom
|
||||
And when an experiment doesn't pay, it records the numbers and reverts the change. A measured no is a result
|
||||
|
||||
Rule: 0.1.4, the performance release (set 2026-11-13: "the v0.1.4 update will be completely performance based")
|
||||
# Seven areas, each with a measured baseline before anything changes. Measured on a clone of a real workspace (9
|
||||
# projects, 21,713 files, a 19 GB media library), the built app headless, a Mac with 64 GB.
|
||||
Scenario: PF1. App start and data loading: seconds if not milliseconds
|
||||
Then the baseline, warm, headless: projects listed 0.61 to 0.67 s after the app is spawned (its host up at
|
||||
0.45 to 0.5 s); a project's feed shown 136 ms after the click with 6 cards, 260 to 282 ms with 41 (about 6 ms
|
||||
a card)
|
||||
And the largest real project's feed (93 cards): its first card 215 ms after the click, settled at 320 ms
|
||||
And the first launch after a new binary: 3.7 s to the projects listed (0.6 s warm)
|
||||
And open: a cold start after a reboot, the window on screen, and a feed of several hundred cards
|
||||
|
||||
Scenario: PF2. Thumbnails: feed items, the library, a project's Source
|
||||
Then a composition's still is `raea play FILE --offscreen --seek N` in a process of its own, two at a time:
|
||||
1.4 s, 1.9 s and 5.0 s for three real compositions (a ray-traced set is the 5 s one)
|
||||
And fixed (raea #141): beside a tsconfig.json, which raea writes into every new project, that play threw before
|
||||
its first frame, so every still there was a failed play and then a render (as slow, and the app's stage and
|
||||
`raea play` did not work at all in such a folder)
|
||||
And faster with PF4's start (raea #147): the same three stills 0.5 s, 1.2 s and 1.2 s warm, and one of the
|
||||
largest project that took 4.05 s as a one-frame render 0.63 s played
|
||||
And open: stills drawn in one long-lived process instead of one each (each pays the engine's start), and the
|
||||
library's tiles on a real library (the test copy has none)
|
||||
|
||||
Scenario: PF3. Video takes the space it needs, no more
|
||||
Then the baseline: 38 GB of video in 1,010 files on this Mac, most at 90 to 100 Mbit/s for 1080p, because every
|
||||
review version and every shot to be joined was rendered at `--quality master`
|
||||
And measured on 1080p24 film footage: default 16 Mbit/s, high 30, master 87; against the master encode the
|
||||
default scores VMAF 99.5 (worst frame 95.8) and high 99.7
|
||||
And fixed in the guides and the skill (raea #143, raea-skills #59, pinned 16ed215): a version made for notes
|
||||
takes no --quality flag, a film delivers at high, master is for delivered motion graphics and type, a
|
||||
replaced version is deleted
|
||||
And open: the app saying what renders take and offering to make old versions smaller; whether the library's
|
||||
copy of a render posted from a project is a clone of it or a second file
|
||||
|
||||
Scenario: PF4. Renders two to three times faster
|
||||
Then the baseline on a real ray-traced film at 1080p: a 61-frame shot is 5.2 to 5.8 s, of which the frames are
|
||||
about 2.2 s (25 to 30 a second: 18 to 20 ms waiting on the GPU and 14 to 22 ms making the frame's rows in
|
||||
JavaScript, one after the other) and the rest is the process starting; the whole 1,666-frame film is 53 s
|
||||
And the two levers that follow from it: a frame's rows made while the GPU draws the one before (they are
|
||||
independent: about 1.5 to 2 times on the frames), and every composition of a file rendered in one process (a
|
||||
film made a shot at a time pays about 3.3 s a shot for nothing: 33 shots, 110 s)
|
||||
And fixed (raea #144): a ray-traced camera's MSAA was turned on again every frame and off again by Bevy with a
|
||||
warning, a line a frame in the render's log
|
||||
And fixed (raea #147), the start: before its first frame a render read the first and last MiB of every picture,
|
||||
sound and video under the edit's folder (to ask for an optimized copy only a video has) and walked the whole
|
||||
folder, .git and node_modules included, for imports from outside it. Time to the first frame of an .mp4, bundle
|
||||
cached: 2.0 s to 0.35 s in a project of 1,234 files, 7.4 s to 0.62 s in one of 10,226; a 60-frame shot 4.7 s
|
||||
to 3.0 s end to end
|
||||
And measured since, what the frames themselves are: flat 2D at 1080p is 254 frames a second with no wait on the
|
||||
GPU; a ray-traced 1080p frame is 18 to 20 ms of GPU and about 5 ms of the scene's sync, so a long ray-traced
|
||||
render is the GPU's. Four ray-traced shots side by side take 7.4 s where in turn they take 11.3 (1.5 times),
|
||||
each frame two to three times slower: the GPU is one, and the window and every other render wait on it, so
|
||||
it is not a default. Two to three times on ray-traced frames is a cheaper trace (fewer pixels or samples
|
||||
traced, then upscaled), which changes the picture and is a rendering decision, not plumbing
|
||||
|
||||
Scenario: PF5. What agents lose time on
|
||||
Then fixed in the lane check (tools/agents/check, on this Mac): the CLI surface step tests the raea it rebuilds
|
||||
(it tested an older build on PATH, and stayed failing after its own rebuild), and the skills step reads the feed
|
||||
app at raea-feed's main (it read whatever branch the shared checkout had out): a lane's check now passes with
|
||||
no variables set
|
||||
And fixed (raea #141, in 0.1.3): `raea play` beside a tsconfig.json, which every new project has
|
||||
And fixed in the app (raea-feed #13, not merged): a review sent on an item whose author is named over a
|
||||
connection went to an inbox it doesn't have, so its edits waited for good; and an agent whose session isn't
|
||||
open is started again by the send
|
||||
And open, each seen on 2026-11-13: a render with <Audio> that reaches no sound is refused only after every frame
|
||||
is drawn (53 s on a film; what sounds are known only once the frames are made); `-o DIR` writes every frame
|
||||
as a PNG (4.9 GB for a film) with nothing said of its size; `but commit` with a long message commits nothing
|
||||
and says so only in a hint; main can fail its own L1 after a GitHub merge (two stale generated pages blocked
|
||||
every lane for a morning)
|
||||
And a release's builds, about three hours each and run many times, moved to larger runners with a cache volume
|
||||
and a compile cache: a candidate after a small change should take minutes (the release lane's; rc4 and rc5
|
||||
are the first measured)
|
||||
|
||||
Scenario: PF6. Video playback and looking around a scene
|
||||
Then video (raea #137): frames decoded a quarter second ahead and shown when due, a faster pixel conversion, a
|
||||
small-drawn video drawn from a halving made off the page's thread: 4K30's worst wait between frames 76 ms to
|
||||
39, 4K60 on a page drawing 120 times a second 0 of 1,214 frames passed over
|
||||
And the app's player (raea-feed #13, not merged): the detail view's clock is outside React state, so a playing
|
||||
video's ticks render only what shows the time: the seconds of 60 fps play with a wait of 26 ms or more
|
||||
between frames go from nearly all to about half
|
||||
And open: frames still go through the CPU; the scene inspector's frame rate while orbiting is not measured
|
||||
|
||||
Scenario: PF8. Pages and assets from this Mac open at once
|
||||
Then covered so far by PF1 (a feed) and PF2 (stills)
|
||||
And a project's Source view (50 compositions, 71 components): its list is there 0.18 s after the click when
|
||||
its thumbnails are in the proxy store, and 2.4 to 3.8 s when the store is empty and the feed's own are still
|
||||
being made. Not explained: the host answers in 0.25 to 0.33 s, the window draws 47 to 91 frames a second
|
||||
throughout, holding still-drawing at the click changes nothing, and so does asking for no row thumbnails
|
||||
And open: that first visit; an asset's preview, a model's, and the library on a real library
|
||||
|
||||
Rule: Lightspeed's goals (set 2026-10-19, after the four multi-day levers; the user: "just focus on lightspeed work")
|
||||
Scenario: Who owns what now
|
||||
Then lightspeed owns performance and optimization end to end: it builds its levers itself, not only measures them
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
@spec
|
||||
Feature: The Linux engine, as fast as it can be in the cloud
|
||||
Shane, 2026-11-11: "lets pinpoint and build a plan to test, validate and improve the linux engine for raea so that it
|
||||
can become more performant and as performant as possible in the cloud". It follows the raea cloud talk the same day:
|
||||
Mac minis are out (macOS's licence allows two VMs a Mac and no time-sharing), so cloud raea is Linux on NVIDIA
|
||||
graphics cards, the sdk/cloud image (docs/cloud.feature) on Modal first.
|
||||
|
||||
Where the time goes today, measured 11-11 (raea 0.1.1-rc3 in sdk/cloud's image on Modal, bench/rerender's film as one
|
||||
render: 900 frames at 1920x1080 with six looks, openh264, 8 cores; ms a frame, steady frames):
|
||||
|
||||
| GPU (Modal $/h) | wall | a frame | GPU wait | React | sync | first frame | GPU $ a film |
|
||||
| A10G ($1.10) | 46.0 s | 41.6 | 0.06 | 11.6 | 23.3 | 7.0 s | 0.014 |
|
||||
| L40S ($1.95) | 38.2 s | 34.4 | 0.01 | 9.5 | 19.2 | 6.0 s | 0.021 |
|
||||
| L4 ($0.80) | 72.0 s | 66.1 | 0.05 | 17.5 | 38.9 | 10.3 s | 0.016 |
|
||||
| H100 ($3.95) | 133.8 s | 137.7 | 74.6 | 12.7 | 43.0 | 7.9 s | 0.147 |
|
||||
| H200 ($4.54) | 127.0 s | 128.5 | 76.6 | 9.9 | 35.6 | 9.8 s | 0.160 |
|
||||
|
||||
What that says:
|
||||
- On a graphics card the GPU is idle (a wait of 0.01-0.06 ms): a frame is all CPU. React on QuickJS (no JIT; the Mac
|
||||
runs JavaScriptCore at 1.0-1.7 ms for the same frames, docs/rerender.feature RR0) and sync (the page synced and
|
||||
drawn and the 3D prepared: runtime/export/src/fed.rs's FrameLog) are 83-85% of it, the rest more of the main
|
||||
thread's own work (RAEA_TIMES' fed is 98% of the frame on the A10G).
|
||||
- So the host's CPU sets the speed, not the card: the L4 loses to the A10G on the CPU side alone, with the same idle
|
||||
GPU. Hosts under one GPU kind differ too: A10G hosts ran 1.52-2.11 s on one single-thread probe (Intel with AVX-512
|
||||
and AMD without; this Mac 0.81 s), and the same film took 46.0 s on one A10G host and 62.5 s on another. Every A/B
|
||||
here runs both builds on one host (LX1).
|
||||
- Compute cards are the wrong kind: an H100 or H200 has a small graphics part, so it's the one place raea waits on the
|
||||
GPU (75 ms a frame), 3x slower than an A10G at 10x the cost a film, and no NVENC.
|
||||
- More cores don't speed one render (4, 8 and 16 cores: 61.6, 62.5, 62.7 s on one host): a render is bound by its
|
||||
main thread and its render thread. Renders share a GPU well enough to fill a box: four at once on 16 cores made
|
||||
35 fps against one render's 14.4 (2.4x), but each frame's time outside the main thread grew from 17 to 60 ms.
|
||||
- The first frame takes 6-10 s: 0.4 s installing Bevy's plugins, 3.8 s of a page-only start thrown away when frame 0
|
||||
holds 3D (runtime/export/src/render.rs, FED_3D), then 3 s starting again with the 3D.
|
||||
- The clipping check can be most of a render: test/gpu/edit.tsx (576 blocks changing shape every frame, 90 frames)
|
||||
took 132.6 s, 96.1 s of it the check (systems/contact voxelizes every part every frame on one thread). So the
|
||||
"1229 ms a frame on an A10" recorded for that scene was mostly the check, not the GPU.
|
||||
- Agents' chunked renders cost double on Linux: six shot renders 3 at a time took 53.7 s plus a 56.6 s join (no ffmpeg
|
||||
in the image, so raea media concat re-encodes), each chunk's first frame 6.6-10.1 s.
|
||||
- A cold worker answers in 8.1 s (a T4: about 6 s Modal placing the container, 2 s our entrypoint).
|
||||
|
||||
Bars for every scenario: the numbers come from bench/linux (LX0) on Modal; a change is judged by LX1's paired A/B (old
|
||||
and new builds interleaved on one host, at least two rounds each), never by runs on different hosts; the picture is
|
||||
unchanged (SSIM 1.000000 on decoded frames) unless a scenario says otherwise; a gate that can't be met goes to Shane with
|
||||
its measurements, never loosened in place; spend is logged with antsy (each round so far cost under $1).
|
||||
|
||||
Rule: Measure on Linux, on the cloud's own machines
|
||||
|
||||
Scenario: LX0. bench/linux: the rows, on any GPU kind and core count
|
||||
# Status 11-11: measured with a scratch version of bench.py (the table above and the findings); to commit.
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| - | bench/linux/bench.py | 220 | a Modal app on sdk/cloud's image: per GPU kind and core count it runs the rows below and prints one JSON line each; each GPU kind's result is printed as it ends (a kind out of capacity mustn't hold the others) |
|
||||
| - | bench/linux/rows.sh | 160 | the rows inside the container: the RR0 film as one render (bench/rerender/bench.sh MODES=one), N renders at once, the chunked film, test/gpu/edit.tsx, and a GPU-heavy scene; each with RAEA_TIMES, RAEA_FRAME_LOG, RAEA_STARTUP_TRACE, the clipping check's time, nvidia-smi's GPU and encoder use, and a single-thread probe of the host |
|
||||
Then `modal run bench/linux/bench.py --gpus A10G,L40S,L4 --cores 8 --rows film,x4,edit,chunked` prints a row per
|
||||
GPU kind and row with: wall, first frame, ms a frame split into React, sync, render thread, GPU wait, readback
|
||||
and encode, the clipping check, GPU and encoder use, the host's CPU (vendor, AVX-512, single-thread time)
|
||||
And a GPU-heavy row (bench/linux/heavy.tsx: ray-traced light, volumetric fog, 4K) shows the card's share, so the
|
||||
GPU kind is chosen on both a CPU-bound and a GPU-bound scene
|
||||
|
||||
@needs:LX0
|
||||
Scenario: LX1. A paired A/B of any two raea builds on one host, and a Linux build of any commit
|
||||
# Status 11-11: the paired run is proven (rc3 against rc5 interleaved on one A10G host); the builder isn't.
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| - | bench/linux/pair.sh | 120 | two raea builds, A and B, run A B A B ... on one host, each row at least twice, and the median of each with its spread; a B that differs by less than the spread says "no change" |
|
||||
| - | bench/linux/build.py | 160 | raea for x86_64 Linux built at any commit in a Modal CPU container, its cargo target on a Modal Volume (an incremental build after the first), the tarball kept on the Volume for pair.sh |
|
||||
Then `bench/linux/pair.sh A=0.1.1-rc5 B=<commit>` builds B if needed and prints both builds' rows side by side from
|
||||
one host, with the host's single-thread time
|
||||
And every gate below is read from pair.sh, never from two separate runs
|
||||
|
||||
@needs:LX0
|
||||
Scenario: LX2. Where a frame's milliseconds go, named
|
||||
# Modal runs containers under gVisor, where perf can't sample, so the split comes from raea's own spans.
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| raea-io-trace | io/trace/src/spans.rs | 140 | RAEA_SPANS=FILE: a Chrome trace of each frame's main thread (React's commit, the page's sync, each Bevy system over 0.2 ms) and render thread (extract, prepare, queue, each render graph node, submit), from Bevy's own spans plus raea's, written by the flight recorder |
|
||||
| - | bench/linux/spans.ts | 120 | the trace folded into a table: each span's mean ms a frame, ranked, and its share of the frame (bun) |
|
||||
Then on the LX1 host the table names at least 90% of the main thread's and the render thread's ms a frame for the
|
||||
RR0 film and edit.tsx
|
||||
And the same trace taken on the Windows PC (the same portable path: QuickJS, Vulkan) agrees on the top five spans,
|
||||
so a fix can be found on a machine with a sampling profiler (samply) and proven on Linux
|
||||
|
||||
Rule: The CPU side of a frame
|
||||
|
||||
@needs:LX1
|
||||
Scenario: LX3. JavaScriptCore on Linux
|
||||
# QuickJS has no JIT: React is 11.6-17.5 ms a frame on Linux, 1.0-1.7 ms on the Mac's JavaScriptCore.
|
||||
# docs/ports.feature left "whether Linux needs another engine" to a number; this is the number.
|
||||
# Checked 11-11: Debian's libjavascriptcoregtk-6.0-1 and -4.1-0 (WebKitGTK 2.50.6, 31 MB each) both export the C
|
||||
# API (JSGlobalContextCreate, JSEvaluateScript, JSObjectMakeFunctionWithCallback, JSValueToNumber,
|
||||
# JSStringCreateWithUTF8CString) beside the GLib one; their licences are LGPL-2+ and LGPL-2.1.
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| raea-runtime-jsengine | runtime/jsengine/src/jsc_c.rs | 380 | JavaScriptCore through its C API (JSContextRef, JSEvaluateScript, JSObjectMakeFunctionWithCallback) from libjavascriptcoregtk, loaded at run time, as Engine::Jsc off Apple |
|
||||
| raea-runtime-jsengine | runtime/jsengine/src/lib.rs | 240 | Engine::default() on Linux: JavaScriptCore when the library loads, QuickJS when it doesn't (said once); BEVY_TSX_ENGINE still picks |
|
||||
| - | sdk/cloud/image/Dockerfile | 75 | libjavascriptcoregtk-6.0-1 in the image |
|
||||
Then the licence is cleared first: libjavascriptcoregtk is LGPL-2.1, linked at run time and not shipped in raea's
|
||||
tarball; Shane decides whether that fits before any code
|
||||
And the conformance suite passes 19/19 on it on Linux, and the RR0 film's frames are identical to QuickJS's
|
||||
And on the LX1 host React is at most 3 ms a frame on the RR0 film and edit.tsx's React at most a quarter of today's
|
||||
And ES modules stay where they are: React's thread runs one bundled script; what needs the module loader keeps QuickJS
|
||||
|
||||
@needs:LX2
|
||||
Scenario: LX4. The main thread's sync, cut where LX2 points
|
||||
# sync is 19-43 ms a frame on Linux against 6-15 ms on the Mac; LX2's table picks the work. Its plan table is
|
||||
# written when that table is in: no code is planned against a cost nobody has measured.
|
||||
Then on the LX1 host the RR0 film's sync is at most 10 ms a frame, with identical frames
|
||||
And each change lands with its pair.sh rows in its commit message
|
||||
|
||||
@needs:LX2
|
||||
Scenario: LX5. The render thread off the critical path
|
||||
# One render on a slower A10G host spent 17 ms a frame outside its main thread, and four renders sharing the GPU
|
||||
# 60 ms: the render thread (raea_sys_frame::pipe) or the driver behind it. LX2's render-thread spans name the
|
||||
# files: what Bevy prepares again each frame for a scene that hasn't changed, and what four processes on one GPU
|
||||
# wait for.
|
||||
Then on the LX1 host a frame's wall is within 1 ms of its main thread's time, alone and with four renders at once
|
||||
And four renders on one A10G make at least 3.5x one render's frames a second
|
||||
|
||||
@needs:LX1
|
||||
Scenario: LX6. No start thrown away
|
||||
# 3.8 s of the RR0 film's 7 s first frame is a page-only start that ends at frame 0's 3D (FED_3D) and is redone.
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| raea-runtime-export | runtime/export/src/render.rs | 413 | a video whose first frame holds 3D starts with its 3D (frames_hold_3d on frame 0 first), so the page-only start and its FED_3D restart only happen for a piece whose 3D comes later; within the file's size today, as the crate is at its 2,000 lines |
|
||||
Then on the LX1 host the RR0 film's first frame comes at least 3.5 s sooner, with identical frames
|
||||
And a piece whose 3D starts later (bench/rerender's shot 3 alone) renders as before
|
||||
|
||||
@needs:LX6,RR10
|
||||
Scenario: LX6b. The cloud keeps its pipeline cache, and the first frame comes in under 1.5 s
|
||||
# RR10 owns the cache (gpu/device's pipelines.rs, Vulkan through wgpu's PipelineCache); this keeps it across the
|
||||
# cloud's containers, whose home folder starts empty each time.
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| - | sdk/cloud/deploy/modal/raea_cloud.py | 90 | a Modal Volume as the pipeline cache's folder, one folder per GPU kind and driver version |
|
||||
Then on the LX1 host the RR0 film's first frame comes at most 1.5 s after the spawn with a warm cache and 3 s cold
|
||||
And the six-chunk row's start-ups sum to at most a third of today's 50.4 s
|
||||
|
||||
@needs:LX1
|
||||
Scenario: LX7. The clipping check never makes a render wait
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| raea-sys-contact | systems/contact/src/broad.rs | 160 | a broad phase before the voxels: parts whose boxes don't touch on a frame are never voxelized or tested; a part's voxels kept by its shape and scale, so an unchanged part is voxelized once a render |
|
||||
| raea-sys-contact | systems/contact/src/lib.rs | 500 | the frames checked in parallel (frames are pure), on the cores the render leaves idle |
|
||||
Then edit.tsx's clipping check takes at most its frames' own time (from 96.1 s), and RR0's film's at most 300 ms
|
||||
And a render's wall with the check on is within 3% of RAEA_CLIP_CHECK=0
|
||||
And the findings are identical on the RR0 film, edit.tsx and the contact fixtures (systems/contact's tests)
|
||||
|
||||
@needs:LX1
|
||||
Scenario: LX8. A raea built for the cloud's CPUs
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| - | bench/linux/build.py | 160 | the builder's variants: x86-64-v3 (every host measured has AVX2), fat LTO, and profile-guided (cargo-pgo, trained on the RR0 film and edit.tsx) |
|
||||
Then each variant is paired against the release build on one host, and a variant ships (as the image's raea, or
|
||||
as the Linux tarball) only where it's at least 10% faster a frame with identical frames
|
||||
|
||||
Rule: Encode and join without the CPU
|
||||
|
||||
@needs:LX0,RR3,RR8b
|
||||
Scenario: LX9. NVENC and a join that doesn't re-encode, measured in the cloud
|
||||
# docs/rerender.feature owns the code (RR3's segments, RR8b's NVENC); this is their cloud gate.
|
||||
Then with four renders on one A10G the encoder is NVENC and the frames' CPU time drops by openh264's share
|
||||
And the chunked row's join takes at most 1 s (from 56.6 s), without ffmpeg in the image
|
||||
|
||||
Rule: The cloud worker
|
||||
|
||||
@needs:LX0
|
||||
Scenario: LX10. The GPU kinds, chosen by what a finished film costs
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| - | sdk/cloud/deploy/modal/raea_cloud.py | 90 | the default list ordered by LX0's cost a film (A10G, L40S, L4 on 11-11's numbers, replacing L4, A10G, T4), and a compute card (H100, H200, B200, A100) refused with the measured reason unless RAEA_CLOUD_GPU_ANY=1 |
|
||||
Then LX0's table for the RR0 film and the GPU-heavy row is in this scenario, with each kind's cost a film
|
||||
And the list is re-chosen whenever LX3-LX7 change where a frame's time goes
|
||||
|
||||
Scenario: LX11. The image runs the raea it was asked for
|
||||
# 11-11: RAEA_VERSION=0.1.1-rc5 built an image whose raea said 0.1.1-rc3: Modal reused its cached layer.
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| - | sdk/cloud/deploy/modal/raea_cloud.py | 90 | the version made part of the image's identity (a layer built from it, so a new version builds a new layer) |
|
||||
| - | sdk/cloud/image/entrypoint.sh | 110 | RAEA_EXPECT_VERSION checked against `raea --version` at start: a mismatch is an error, never a quiet older raea |
|
||||
Then deploying with a new RAEA_VERSION serves that version (/v1/health says it) on its first request
|
||||
|
||||
@needs:LX1
|
||||
Scenario: LX12. A cold worker in under 4 s, and hidden from the agent
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| - | sdk/cloud/image/entrypoint.sh | 110 | a render worker (RAEA_CLOUD_ROLE=worker) skips agents and skills, and checks the GPU beside the server's start, not before it |
|
||||
| - | sdk/cloud/src/index.ts | 220 | the client wakes the GPU worker (GET /healthz) when an agent session opens, so the first render meets a warm worker |
|
||||
Then ten cold starts on Modal answer /healthz in at most 4 s at the median (8.1 s on 11-11)
|
||||
And in CL12's smoke test the agent's first render never waits for a worker to start
|
||||
|
||||
@needs:LX5
|
||||
Scenario: LX13. As many renders a GPU as it holds
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| - | sdk/cloud/server/jobs.ts | 200 | the worker's jobs run N at a time (RAEA_CLOUD_SLOTS, by default the number LX0 measures best for the GPU kind and cores), queued past that |
|
||||
Then on one A10G with 16 cores the worker's frames a second at its default N are at least 3x one render's
|
||||
And RR5's workers inside one render (a long video's segments) take the same slots
|
||||
|
||||
Rule: Keep it fast
|
||||
|
||||
@needs:LX1
|
||||
Scenario: LX14. Every release candidate is paired against the last release
|
||||
Then before a release's notes are written, pair.sh runs LX0's rows for the candidate against the previous release
|
||||
on one A10G host, and a row more than 5% slower a frame or at its first frame fails the release pass with the
|
||||
rows (by hand in the release lane while CI is on hold)
|
||||
@@ -0,0 +1,95 @@
|
||||
Feature: The raea manual: one set of docs for agents first and developers second
|
||||
The manual is raea's documentation: how to install it, what it is made of, how to make each kind of thing with it,
|
||||
every verb and import, and what changed in each release. Agents read it more than people do, so every page has to
|
||||
work as plain Markdown an agent fetches or a CLI prints, and as a page a developer reads on raea.io. It lives in
|
||||
this repository beside the code it describes, it is checked by the same CI, it ships inside each release so an
|
||||
agent reads the version it runs, and the skill in raea-skills carries it.
|
||||
|
||||
Background:
|
||||
Given the manual's source is docs/manual/ in this repository: one Markdown file a page, with front matter
|
||||
And raea.io/docs/ renders it (apps/site), and every page has a Markdown twin at the same path ending .md
|
||||
And the raea skill (skills/skills/raea, the raea-skills submodule) is the short, task-ordered entry point an agent
|
||||
loads first; the manual is the full text it links to
|
||||
|
||||
Scenario: DM0. The decisions (Shane, 2026-11-08)
|
||||
Then the source of truth is this repository's docs/manual/, not raea-skills: the code and its docs change in the
|
||||
same commit, and raea-skills receives a copy from the gen step (DM5)
|
||||
And it is served at raea.io/docs/, in the site, with the site's nav
|
||||
And "What's new" is built from each release's approved notes (docs/release.feature RL4), one file a version
|
||||
And the primary reader is an agent and the second is a developer; both get the same pages
|
||||
And every page is written in complete English sentences, says what to do before why, and shows an example for
|
||||
each thing it teaches
|
||||
|
||||
Scenario: DM1. A page's form
|
||||
Then a page is docs/manual/<section>/<name>.md with front matter: `title`, `summary` (one sentence, used in the
|
||||
sidebar's tooltip, llms.txt and search), `order` (its place in the section), and `sources` (the paths whose
|
||||
change can make it wrong, as SK4 reads `<!-- sources: -->`)
|
||||
And it opens with what the reader can do after reading it, then the shortest working example, then the details
|
||||
And each section is a heading an agent can link to: `/docs/<section>/<name>#<heading-slug>`
|
||||
And examples are fenced with their language; a TSX example that is a whole file names it: ```tsx file=hello.tsx
|
||||
means docs/manual/examples/hello.tsx holds the same text, and DM4 renders it
|
||||
And commands are shown as the reader types them, one per line, with a comment saying what each does when that
|
||||
isn't obvious; output is shown in a separate block marked `text`
|
||||
And no page names another product as a foil (sdk/raea/README.md rule 3); a page may name a tool raea works with
|
||||
(Blender, ffmpeg, Claude Code) by its name
|
||||
And words follow the skill's vocabulary (docs/skills.glossary.md) and its retired list (SK3)
|
||||
|
||||
Scenario: DM2. The sections, in reading order
|
||||
Then the sections are:
|
||||
| section | holds |
|
||||
| start | what raea is, install, the first video, the first game, how an agent should use raea |
|
||||
| concepts | compositions and frames, rendering and playing, workspaces and specs, checks |
|
||||
| guides | one page a kind of work: footage cut by words, captions, motion, music, sound, 3D, |
|
||||
| | games, apps, HTML pages, R3F and three.js, generated media, the raea app for agents |
|
||||
| reference | the CLI, the SDK's imports, files and specs (generated, DM3), settings and variables |
|
||||
| whats-new | one page a release, newest first (DM7) |
|
||||
And docs/manual/index.md is the map: one line a page, so an agent reading only it knows where everything is
|
||||
|
||||
Scenario: DM3. References come from the code
|
||||
Then reference/cli, reference/sdk and reference/files are the skill's generated references
|
||||
(skills/skills/raea/reference/{cli,sdk,files}.md, written by tools/skills.sh gen from `raea help --json`, the
|
||||
SDK's exports and a scratch workspace): the site renders those files, so the manual and the skill can't differ
|
||||
And a hand-written page never repeats a flag list; it links the reference
|
||||
|
||||
Scenario: DM4. Every example works (tools/manual.sh check, in L0 and public CI)
|
||||
Then every ```tsx file=NAME block matches docs/manual/examples/NAME byte for byte
|
||||
And every file in docs/manual/examples/ renders with this tree's `raea render NAME --frame F -o OUT.png` (F is the
|
||||
file's `// check: frames A,B` line, else 0), or plays with `raea play --seconds 1 --offscreen` when it is a game
|
||||
And every `raea VERB` in a page's commands is a verb `raea help --json` lists, with flags that verb takes (the
|
||||
check tools/skills.sh check already runs on the skill, run on the manual)
|
||||
And every relative link and `#heading` resolves to a page and a heading that exist
|
||||
And each failure names its page, line and fix
|
||||
|
||||
Scenario: DM5. The skill carries the manual (raea-skills)
|
||||
Then tools/skills.sh gen copies docs/manual/ into skills/skills/raea/manual/ with its examples, as it copies the 3D
|
||||
guides into 3d/, so a clone of raea-skills reads whole without raea
|
||||
And the skill's SKILL.md links the manual's pages for depth instead of repeating them
|
||||
And raea-skills' CI (skillcheck) checks the copy's links and front matter, and its `upstream_drift` feature fails
|
||||
when the copy is older than the raea it's tested against
|
||||
|
||||
Scenario: DM6. The binary serves the manual for its own version
|
||||
Then `raea docs` prints the map, `raea docs PAGE` prints one page (`raea docs guides/games`), and
|
||||
`raea docs search "WORDS"` lists pages and headings that match, each with its path
|
||||
And the text is embedded in the binary at build time, so it matches `raea --version` and works offline
|
||||
And `raea skill`'s output names `raea docs` as where depth lives
|
||||
|
||||
Scenario: DM7. What's new, from the release notes
|
||||
Given a release's notes are approved (RL4)
|
||||
Then tools/release.sh writes them to docs/manual/whats-new/<VERSION>.md with front matter (`title`, `version`,
|
||||
`date`, `summary`: the notes' first sentence) in the release commit, and the GitHub release body is the same text
|
||||
And raea.io/docs/whats-new/ lists every release newest first, with each one's headings as its contents
|
||||
And `raea whats-new` prints the entries since the version the person last ran (kept in ~/.raea/last-version), and
|
||||
`raea whats-new --all` all of them
|
||||
And the installer prints the new version's headlines after it updates an existing install
|
||||
And past releases (0.1.0-canary.1 to canary.3) are back-filled from their published notes
|
||||
|
||||
Scenario: DM8. Agents can find and fetch it
|
||||
Then raea.io/llms.txt lists every page as `- [title](https://raea.io/docs/<path>.md): summary`, grouped by
|
||||
section, and raea.io/llms-full.txt is every page's Markdown in reading order
|
||||
And each page's HTML links its Markdown twin (`<link rel="alternate" type="text/markdown">`)
|
||||
And the twin is the source file with its front matter turned into a title line and a summary line
|
||||
|
||||
Scenario: DM9. Coverage
|
||||
Then every verb in `raea help --json` and every import path in sdk/raea's package exports has a reference entry
|
||||
(DM3) and at least one page that shows it in use, or is listed in docs/manual/uncovered.txt with a reason
|
||||
And tools/manual.sh coverage prints what isn't covered yet, so the gap is a list, not a guess
|
||||
@@ -0,0 +1,110 @@
|
||||
---
|
||||
title: "Compositions and frames"
|
||||
summary: "A composition is a function of the frame: what that means, the core APIs (Composition, Sequence, interpolate, spring), and the rules that keep every render the same."
|
||||
order: 1
|
||||
sources: ["sdk/raea/src/index.tsx", "sdk/math/src/spring.ts", "sdk/guides/craft/motion.md"]
|
||||
---
|
||||
|
||||
A composition is a React component that raea calls once for every frame. Give it frame N and it draws frame N. It
|
||||
doesn't remember the frame before, and it doesn't wait for anything. That one rule is why raea can render any frame on
|
||||
its own, play the same file live, and promise that the same code always renders the same pixels.
|
||||
|
||||
## The smallest composition
|
||||
|
||||
```tsx
|
||||
import { AbsoluteFill, Composition, registerRoot, useCurrentFrame } from "raea";
|
||||
|
||||
function Counter() {
|
||||
const frame = useCurrentFrame();
|
||||
return <AbsoluteFill style={{ background: "#000", color: "#fff", fontSize: 200, justifyContent: "center", alignItems: "center" }}>{frame}</AbsoluteFill>;
|
||||
}
|
||||
|
||||
registerRoot(() => <Composition id="counter" component={Counter} width={1080} height={1080} fps={30} durationInFrames={60} />);
|
||||
```
|
||||
|
||||
- `registerRoot` names what the file contains. A file can register several compositions; `raea render FILE
|
||||
--composition ID` picks one.
|
||||
- `Composition` sets the size in pixels, the frame rate and the length in frames.
|
||||
- `useCurrentFrame()` is the frame being drawn. Everything that moves is computed from it.
|
||||
- `AbsoluteFill` is a `div` that fills its parent, laid out as a flex column.
|
||||
|
||||
Layout and styling are the web's: `div`, `span` and `img` elements, inline `style` objects or Tailwind classes in
|
||||
`className`, flexbox and grid. raea draws them on the GPU itself; there is no browser.
|
||||
|
||||
## Moving things: interpolate and spring
|
||||
|
||||
`interpolate` maps a range of frames onto a range of values:
|
||||
|
||||
```tsx
|
||||
const x = interpolate(frame, [0, 30], [-400, 0], { extrapolateLeft: "clamp", extrapolateRight: "clamp" });
|
||||
```
|
||||
|
||||
Frames 0 to 30 move `x` from -400 to 0. Without the `clamp` options the line keeps going past its ends, so at frame 60
|
||||
`x` would be 400. Clamp every `interpolate` unless you want that. Add `easing: Easing.out(Easing.cubic)` to ease it.
|
||||
|
||||
`spring` gives the motion of a physical spring, from 0 to 1, and settles by itself:
|
||||
|
||||
```tsx file=title.tsx
|
||||
// check: frames 0,12,40
|
||||
import { AbsoluteFill, Composition, registerRoot, spring, useCurrentFrame, useVideoConfig } from "raea";
|
||||
|
||||
const WORDS = ["Make", "what", "you", "imagine."];
|
||||
|
||||
// Each word springs up into place, four frames after the one before it.
|
||||
function Title() {
|
||||
const frame = useCurrentFrame();
|
||||
const { fps } = useVideoConfig();
|
||||
return (
|
||||
<AbsoluteFill style={{ background: "#0f1115", justifyContent: "center", alignItems: "center", flexDirection: "row", gap: 28 }}>
|
||||
{WORDS.map((word, i) => {
|
||||
const p = spring({ frame, fps, delay: i * 4, config: { damping: 14, stiffness: 160 } });
|
||||
return (
|
||||
<span key={word} style={{ color: "#ffffff", fontSize: 110, fontWeight: 700, opacity: p, transform: `translateY(${(1 - p) * 80}px)` }}>
|
||||
{word}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</AbsoluteFill>
|
||||
);
|
||||
}
|
||||
|
||||
registerRoot(() => <Composition id="title" component={Title} width={1920} height={1080} fps={30} durationInFrames={60} />);
|
||||
```
|
||||
|
||||
`spring({ frame, fps })` is 0 at frame 0 and settles at 1. `delay` starts it later; `config` sets its `mass`,
|
||||
`damping` and `stiffness` (defaults 1, 10 and 100: lower damping bounces more). `from` and `to` change the range, and
|
||||
`durationInFrames` stretches it to settle in exactly that many frames.
|
||||
|
||||
## Placing things in time: Sequence and Series
|
||||
|
||||
`Sequence` shows its children from one frame for a number of frames, and restarts their clock:
|
||||
|
||||
```tsx
|
||||
<Sequence from={30} durationInFrames={60}>
|
||||
<Card text="Hello" />
|
||||
</Sequence>
|
||||
```
|
||||
|
||||
Inside, `useCurrentFrame()` is 0 at composition frame 30. A component written to animate from frame 0 works anywhere
|
||||
you place it. `Series` places Sequences one after another without adding up the frames yourself.
|
||||
|
||||
## The rules
|
||||
|
||||
1. **Everything that moves reads the frame.** `useState`, `useEffect`, refs and timers don't animate a render. A value
|
||||
that changes over time is a function of `useCurrentFrame()`.
|
||||
2. **Random is seeded per frame.** `Math.random()` returns new numbers every frame, so something placed with it
|
||||
jumps. Seed what should hold still from an index, or decide it once in a game's `step`.
|
||||
3. **Clamp interpolations.** An unclamped value runs off and can turn into NaN, which fails the render and names
|
||||
the line.
|
||||
4. **Cue on words or events, not on frame numbers you guessed.** `word("phrase")` and `useGameEvents` stay right when
|
||||
the cut or the rules change. A typed frame number drifts.
|
||||
5. **Media comes from files.** `<Video>`, `<Audio>` and `<Img>` take a path (use `staticFile("name")` for the
|
||||
project's `media/` folder) or an `https://` URL, which raea fetches once into its cache.
|
||||
|
||||
`raea guide motion` has the full list of core rules with the reasoning behind each.
|
||||
|
||||
## Where to go next
|
||||
|
||||
- [Rendering and checking](rendering.md): stills, exports and the checks.
|
||||
- [Captions and cues on words](../guides/words.md): timing to speech.
|
||||
- [The SDK reference](../reference/sdk.md): every import.
|
||||
@@ -0,0 +1,117 @@
|
||||
---
|
||||
title: "Rendering and checking"
|
||||
summary: "How to render stills, transparent frames and videos, set quality and bitrate, and check an export against the floor before anyone sees it."
|
||||
order: 2
|
||||
sources: ["engine/cli/src/usage.rs", "sdk/guides/craft/motion/rendering.md", "runtime/export/src"]
|
||||
---
|
||||
|
||||
raea renders the same tree the viewer gets, so a still from it is the truth about layout: fonts, footage, 3D and text
|
||||
overflow only show up in pixels. `raea check` then measures what a still can't, such as a word clipped for three
|
||||
frames, a stretch of black or a voice buried under music. This page covers both.
|
||||
|
||||
## Stills
|
||||
|
||||
Render the frames you want to look at as PNGs:
|
||||
|
||||
```sh
|
||||
raea render piece.tsx --at 15,63,144,270 -o stills/ # four frames, as stills/frame-00000.png and on
|
||||
raea render piece.tsx --frame 120 -o frame-120.png # one frame, to one file
|
||||
raea render piece.tsx --alpha -o frames/ # every frame as a transparent PNG, for another editor
|
||||
```
|
||||
|
||||
Pick the moments that matter, look at all of them at once, fix everything they show, and look again. A contact sheet
|
||||
of a finished video shows the whole piece in one image:
|
||||
|
||||
```sh
|
||||
raea media sheet piece.mp4 -o sheet.png
|
||||
```
|
||||
|
||||
## Video
|
||||
|
||||
```sh
|
||||
raea render piece.tsx -o piece.mp4
|
||||
raea render piece.tsx --composition wide -o wide.mp4 # one of several compositions in the file
|
||||
```
|
||||
|
||||
An MP4 from raea is H.264 in yuv420p. On a Mac it is encoded with VideoToolbox (H.264 High, AAC audio); on Linux and
|
||||
Windows with openh264 (H.264 Constrained Baseline, Opus audio).
|
||||
|
||||
The output's folder must exist: `-o out/piece.mp4` needs `out/` already there.
|
||||
|
||||
## Quality and bitrate
|
||||
|
||||
By default the bitrate follows the size and frame rate: about 20 Mbit/s at 1080p30 and 80 at 4K30.
|
||||
|
||||
| Flag | Use it for |
|
||||
|---|---|
|
||||
| `--quality draft` | Fast previews |
|
||||
| `--quality high` | Most deliveries |
|
||||
| `--quality master` | Final exports of motion graphics and type: keeps thin type and hard edges clean |
|
||||
| `--quality 0.85` | A constant quality from 0 to 1, if the presets don't fit |
|
||||
| `--kbps 12000` | A fixed bitrate |
|
||||
| `--10bit` | 10-bit output |
|
||||
|
||||
`--quality` asks for constant quality: each frame gets the bits it needs, so a flat motion graphic stays small and a
|
||||
busy one stays clean.
|
||||
|
||||
Blotchy dark areas come from the encoder, not the composition. Export dark material as PNG frames and encode them
|
||||
with more bits for the darks:
|
||||
|
||||
```sh
|
||||
RAEA_READBACK=rgba raea render piece.tsx -o frames/
|
||||
```
|
||||
|
||||
## A share copy
|
||||
|
||||
A raea MP4 is standard but large. For a copy any player and any upload takes, re-encode it with ffmpeg:
|
||||
|
||||
```sh
|
||||
ffmpeg -i film.mp4 -c:v libx264 -preset slow -crf 23 -maxrate 2600k -bufsize 5200k -pix_fmt yuv420p -c:a aac -b:a 128k -movflags +faststart film-share.mp4
|
||||
```
|
||||
|
||||
## The quick check
|
||||
|
||||
```sh
|
||||
raea check piece.tsx --quick
|
||||
```
|
||||
|
||||
The quick check renders three stills of a composition and measures its text: clipped, cramped, inside the safe areas
|
||||
and large enough to read. It takes about a second. Run it after every save. Add `--platform tiktok` (or `reels`,
|
||||
`shorts`) to check against that platform's buttons and captions.
|
||||
|
||||
## The full check
|
||||
|
||||
Render with a manifest, then check the export:
|
||||
|
||||
```sh
|
||||
raea render piece.tsx -o piece.mp4 --manifest render.json
|
||||
raea check piece.mp4 --manifest render.json --words words.json --platform tiktok -o check.json
|
||||
```
|
||||
|
||||
The manifest records where every element was on every frame, so the check can say which element a problem belongs
|
||||
to. The full check measures:
|
||||
|
||||
- clipped text, text under the platform's buttons, and text over a face
|
||||
- captions on screen too briefly to read, and caption contrast against the pixels behind them
|
||||
- frozen stretches and flashing past the safe limit
|
||||
- cues that miss the word they were tied to (with `--words`)
|
||||
- loudness, sound that stops dead, and sound that fights the voice
|
||||
- blotching in dark areas
|
||||
|
||||
Each finding is ranked P0 (broken) to P3 (polish) and comes with its fix. The command exits 1 while any P0 or P1
|
||||
stands, so a script or an agent can stop on it. `-o check.json` writes the findings for a later review.
|
||||
|
||||
An exception in the composition fails the render itself and names the line: a value that turned into NaN, keyframes
|
||||
out of order, a phrase `word()` can't find, or a missing prop.
|
||||
|
||||
## Loudness
|
||||
|
||||
When the composition has a `<Mix>`, the export comes out at -14 LUFS integrated (within 1) with true peak at or below
|
||||
-1 dBTP, which is what the major platforms play back at.
|
||||
|
||||
## Mistakes to avoid
|
||||
|
||||
- Judging layout from the code. Text overflow and contrast against footage only show in pixels.
|
||||
- Checking frame 0 only. Most problems are at cues and joins.
|
||||
- Calling it done without listening. The voice must stay clear over the music, and every sound should land.
|
||||
- Rendering a new version over the old one. Render `piece-v2.mp4` beside `piece.mp4`.
|
||||
@@ -0,0 +1,102 @@
|
||||
---
|
||||
title: "Workspaces and projects"
|
||||
summary: "Where work lives in raea: a workspace is a git repository of projects and controllers, and each project has a brief and folders for media and renders."
|
||||
order: 3
|
||||
sources: ["apps/workspace/src", "core/brief/src", "skills/skills/raea/reference/files.md"]
|
||||
---
|
||||
|
||||
You can render a single `.tsx` file from any folder, and for a quick piece that's all you need. For ongoing work,
|
||||
raea keeps things in workspaces and projects, so an agent always knows what the work is for, what the person likes,
|
||||
and where the files go.
|
||||
|
||||
## A workspace
|
||||
|
||||
A workspace is a git repository, one per studio or client, that holds projects and controllers. Workspaces live under
|
||||
your raea root, which is `~/Studio` unless you set another:
|
||||
|
||||
```sh
|
||||
git config --global raea.root ~/Work # optional: put workspaces somewhere else
|
||||
raea workspace init acme # makes ~/Studio/acme
|
||||
raea workspace adopt ~/clients/acme # or makes an existing folder a workspace
|
||||
raea workspace # shows the current one (--json for its projects and paths)
|
||||
```
|
||||
|
||||
## A project
|
||||
|
||||
A project is one piece of work inside a workspace. In the raea app it shows as a channel.
|
||||
|
||||
```sh
|
||||
cd ~/Studio/acme
|
||||
raea project new spring-launch
|
||||
```
|
||||
|
||||
That makes the project's folder:
|
||||
|
||||
| Path | Holds |
|
||||
|---|---|
|
||||
| `brief.ts` | What the work is: who it's for, the one thing they should believe, its modes, its deliverables |
|
||||
| `media/` | Footage, music and other source files |
|
||||
| `out/` | Renders |
|
||||
| `brand/` | The brand kit: `brand.css`, `brand.json`, logos |
|
||||
|
||||
A project can live inline in the workspace or as a repository of its own; both keep its history:
|
||||
|
||||
```sh
|
||||
raea project split spring-launch # its own repository
|
||||
raea project join spring-launch # back inline
|
||||
```
|
||||
|
||||
## The spec files
|
||||
|
||||
raea's specs are TypeScript files whose default export is checked against a schema:
|
||||
|
||||
| File | What it says |
|
||||
|---|---|
|
||||
| `brief.ts` | The project's brief |
|
||||
| `NAME.script.ts` | A storyboard: scenes of beats, what's on screen, what each scene must land |
|
||||
| `~/.raea/taste/taste.ts` | The person's taste, which beats any guide's default |
|
||||
| `plan.ts` | A frozen plan for a build, checked by raea |
|
||||
| `controllers/ID.ts` | The workspace's settings and workflows |
|
||||
|
||||
```sh
|
||||
raea spec brief.ts # prints the brief as JSON, checked against its schema
|
||||
```
|
||||
|
||||
A brief, written with the `brief` helper from `raea/brief`. Only `title` is required; `believe` (the one thing the
|
||||
audience should think afterwards) and `mode` are what an agent needs most:
|
||||
|
||||
```ts
|
||||
import { brief } from "raea/brief";
|
||||
|
||||
export default brief({
|
||||
title: "Spring launch",
|
||||
for: "Acme Running",
|
||||
audience: "runners who already own our shoes, on their phones",
|
||||
believe: "the new sole makes an easy run feel easier",
|
||||
mode: ["pitch"],
|
||||
deliver: [{ name: "launch-9x16", specs: ["30 s", "9:16", "with sound"] }],
|
||||
});
|
||||
```
|
||||
|
||||
The full list of each spec's fields is in [Files and specs](../reference/files.md).
|
||||
|
||||
## Controllers
|
||||
|
||||
Controllers are the workspace's settings and workflows: delivery specs, who reviews what, the tools every agent gets.
|
||||
Every change to one is a git commit.
|
||||
|
||||
```sh
|
||||
raea controller ls # every controller, with its groups and fields
|
||||
raea controller get CONTROLLER.GROUP.FIELD # one value
|
||||
raea controller set CONTROLLER.GROUP.FIELD VALUE # change it, as a commit
|
||||
```
|
||||
|
||||
## Reading a project before working on it
|
||||
|
||||
```sh
|
||||
raea context .
|
||||
```
|
||||
|
||||
prints, in order, everything an agent should read before making anything in the project: the person's taste, the
|
||||
workspace's taste, the brief, the look, the controllers, the craft floor and the guides for the brief's modes. See
|
||||
[How an agent should use raea](../start/agents.md).
|
||||
@@ -0,0 +1,34 @@
|
||||
// check: frames 0,30,89
|
||||
import { AbsoluteFill, Composition, Sequence, interpolate, registerRoot, useCurrentFrame } from "raea";
|
||||
|
||||
// One card: its text fades in over the first 12 frames of its Sequence.
|
||||
function Card({ text }: { text: string }) {
|
||||
const frame = useCurrentFrame();
|
||||
const opacity = interpolate(frame, [0, 12], [0, 1], { extrapolateLeft: "clamp", extrapolateRight: "clamp" });
|
||||
return (
|
||||
<AbsoluteFill style={{ background: "#000", color: "#fff", justifyContent: "center", alignItems: "center", fontSize: 120 }}>
|
||||
<span style={{ opacity }}>{text}</span>
|
||||
</AbsoluteFill>
|
||||
);
|
||||
}
|
||||
|
||||
// Three seconds at 30 fps, vertical: "Hello" for the first half, "world" for the second.
|
||||
registerRoot(() => (
|
||||
<Composition
|
||||
id="hello"
|
||||
width={1080}
|
||||
height={1920}
|
||||
fps={30}
|
||||
durationInFrames={90}
|
||||
component={() => (
|
||||
<>
|
||||
<Sequence from={0} durationInFrames={45}>
|
||||
<Card text="Hello" />
|
||||
</Sequence>
|
||||
<Sequence from={45} durationInFrames={45}>
|
||||
<Card text="world" />
|
||||
</Sequence>
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
));
|
||||
@@ -0,0 +1,57 @@
|
||||
// check: frames 0,90,240
|
||||
import { Composition, registerRoot, useGameState, type Playtest } from "raea";
|
||||
import { Arena, Banner, Hint, Score } from "raea/arena";
|
||||
|
||||
// The field's own units: everything below is drawn in a 1600 by 900 field, and the Arena scales it to the stage.
|
||||
const W = 1600, H = 900, PADDLE = 160, BALL = 24, SPEED = 14;
|
||||
|
||||
type State = { y: number; bx: number; by: number; vx: number; vy: number; returns: number; misses: number };
|
||||
const initial: State = { y: H / 2, bx: W / 2, by: H / 3, vx: -SPEED, vy: SPEED * 0.6, returns: 0, misses: 0 };
|
||||
|
||||
// The rules, as a pure function: the next state from this one and this frame's keys. It never changes `s`.
|
||||
function step(s: State, input: { keys: string[] }): State {
|
||||
const up = input.keys.includes("ArrowUp"), down = input.keys.includes("ArrowDown");
|
||||
// Nobody at the keys (a render, or live before a key is pressed): the paddle follows the ball by itself.
|
||||
const aim = up || down ? s.y + (down ? 18 : -18) : s.y + Math.sign(s.by - s.y) * Math.min(12, Math.abs(s.by - s.y));
|
||||
const y = Math.max(PADDLE / 2, Math.min(H - PADDLE / 2, aim));
|
||||
let { bx, by, vx, vy, returns, misses } = s;
|
||||
bx += vx;
|
||||
by += vy;
|
||||
if (by < BALL / 2 || by > H - BALL / 2) vy = -vy; // top and bottom walls
|
||||
if (bx > W - BALL / 2) vx = -Math.abs(vx); // the far wall
|
||||
if (bx < 60 && vx < 0) {
|
||||
if (Math.abs(by - y) < PADDLE / 2 + BALL / 2) { vx = Math.abs(vx); returns += 1; } // a return
|
||||
else if (bx < 0) { bx = W / 2; by = H / 3; misses += 1; } // a miss: serve again
|
||||
}
|
||||
return { y, bx, by, vx, vy, returns, misses };
|
||||
}
|
||||
|
||||
function Squash() {
|
||||
const g = useGameState(initial, step);
|
||||
return (
|
||||
<Arena
|
||||
width={W}
|
||||
height={H}
|
||||
score={<Score items={[{ label: "returns", value: g.returns, accent: true }, { label: "misses", value: g.misses }]} />}
|
||||
banner={g.returns === 0 && g.misses === 0 && g.bx > W / 2 ? <Banner text="squash" sub="keep the ball in play" /> : null}
|
||||
hint={<Hint keys={[{ keys: "↑ ↓", does: "move" }]} />}
|
||||
>
|
||||
<div style={{ position: "absolute", inset: 0, background: "#1b1f2a", borderRadius: 24 }} />
|
||||
<div style={{ position: "absolute", left: 30, top: g.y - PADDLE / 2, width: 24, height: PADDLE, borderRadius: 12, background: "#ff5a36" }} />
|
||||
<div style={{ position: "absolute", left: g.bx - BALL / 2, top: g.by - BALL / 2, width: BALL, height: BALL, borderRadius: BALL, background: "#ffffff" }} />
|
||||
</Arena>
|
||||
);
|
||||
}
|
||||
|
||||
// What the playtest's bots need to check the game can be played: the same state and step, and the keys a player uses.
|
||||
export const playtest: Playtest<State> = {
|
||||
initial,
|
||||
step,
|
||||
actions: [[], ["ArrowUp"], ["ArrowDown"]],
|
||||
observe: (s) => ({ paddle: s.y, ball: [s.bx, s.by] }),
|
||||
progress: (s) => Math.min(1, s.returns / 10),
|
||||
outcome: (s) => (s.returns >= 10 ? "won" : s.misses >= 3 ? "lost" : null),
|
||||
};
|
||||
|
||||
// Games render landscape at 60 fps: ten seconds here.
|
||||
registerRoot(() => <Composition id="squash" width={1920} height={1080} fps={60} durationInFrames={600} component={Squash} />);
|
||||
@@ -0,0 +1,24 @@
|
||||
// check: frames 0,12,40
|
||||
import { AbsoluteFill, Composition, registerRoot, spring, useCurrentFrame, useVideoConfig } from "raea";
|
||||
|
||||
const WORDS = ["Make", "what", "you", "imagine."];
|
||||
|
||||
// Each word springs up into place, four frames after the one before it.
|
||||
function Title() {
|
||||
const frame = useCurrentFrame();
|
||||
const { fps } = useVideoConfig();
|
||||
return (
|
||||
<AbsoluteFill style={{ background: "#0f1115", justifyContent: "center", alignItems: "center", flexDirection: "row", gap: 28 }}>
|
||||
{WORDS.map((word, i) => {
|
||||
const p = spring({ frame, fps, delay: i * 4, config: { damping: 14, stiffness: 160 } });
|
||||
return (
|
||||
<span key={word} style={{ color: "#ffffff", fontSize: 110, fontWeight: 700, opacity: p, transform: `translateY(${(1 - p) * 80}px)` }}>
|
||||
{word}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</AbsoluteFill>
|
||||
);
|
||||
}
|
||||
|
||||
registerRoot(() => <Composition id="title" component={Title} width={1920} height={1080} fps={30} durationInFrames={60} />);
|
||||
@@ -0,0 +1,37 @@
|
||||
// check: frames 0,45,89
|
||||
import { AbsoluteFill, Composition, Easing, interpolate, registerRoot, useCurrentFrame, useVideoConfig } from "raea";
|
||||
import { Cylinder, Entity } from "raea/3d";
|
||||
import { StandardMaterial } from "raea/pbr";
|
||||
import { Cuboid, Mesh3d } from "raea/mesh";
|
||||
import { AmbientLight, DirectionalLight } from "raea/light";
|
||||
import { Quat, Transform } from "raea/transform";
|
||||
import { Camera3d } from "raea/camera";
|
||||
|
||||
function Turntable() {
|
||||
const f = useCurrentFrame();
|
||||
const { fps, durationInFrames } = useVideoConfig();
|
||||
const turn = (f / fps) * (Math.PI / 3); // a sixth of a turn a second
|
||||
const z = interpolate(f, [0, durationInFrames - 1], [7, 5], { easing: Easing.out(Easing.cubic), extrapolateLeft: "clamp", extrapolateRight: "clamp" });
|
||||
return (
|
||||
<AbsoluteFill style={{ background: "#14161c" }}>
|
||||
<Camera3d transform={Transform.fromXyz(0, 1.6, z).lookingAt([0, 0.5, 0])} projection={{ Perspective: { fov: (40 * Math.PI) / 180 } }} />
|
||||
<AmbientLight brightness={160} />
|
||||
<DirectionalLight transform={Transform.fromXyz(3, 5, 4).lookingAt([0, 0, 0])} illuminance={11200} shadow_maps_enabled />
|
||||
<Entity transform={Transform.IDENTITY.withRotation(Quat.fromEuler("XYZ", 0, turn, 0))}>
|
||||
<Mesh3d transform={Transform.fromXyz(0, -0.1, 0)}>
|
||||
<Cylinder radius={1.4} half_height={0.1} />
|
||||
<StandardMaterial base_color="#2b2f3a" perceptual_roughness={0.6} />
|
||||
</Mesh3d>
|
||||
<Mesh3d transform={Transform.fromXyz(0, 0.6, 0)}>
|
||||
<Cuboid half_size={[0.45, 0.6, 0.45]} />
|
||||
<StandardMaterial base_color="#e8b04a" perceptual_roughness={0.35} metallic={0.2} />
|
||||
</Mesh3d>
|
||||
</Entity>
|
||||
<div style={{ position: "absolute", top: 80, width: "100%", textAlign: "center", fontFamily: "Inter", fontWeight: 800, fontSize: 72, color: "#ffffff" }}>
|
||||
Made to be seen
|
||||
</div>
|
||||
</AbsoluteFill>
|
||||
);
|
||||
}
|
||||
|
||||
registerRoot(() => <Composition id="turntable" component={Turntable} width={1080} height={1080} fps={30} durationInFrames={90} />);
|
||||
@@ -0,0 +1,67 @@
|
||||
---
|
||||
title: "Check a cut with it"
|
||||
summary: "Score a cut with your fingerprint before it's posted, check that a fix removed a flag instead of hiding it, judge scripts and stills, find things floating in a 3D shot, and compare a cut with work you admire."
|
||||
order: 2
|
||||
sources: ["docs/fingerprint.feature", "apps/fingerprint/src", "systems/fingerprint-use/src", "systems/fingerprint-things/src"]
|
||||
---
|
||||
|
||||
## Score a cut
|
||||
|
||||
```sh
|
||||
raea fingerprint score out/cut.mp4 # the moments it expects a note on, first
|
||||
raea fingerprint score out/cut.mp4 --sheet cut.png # the same on a sheet of frames, with where boxed
|
||||
raea fingerprint score out/cut.mp4 --timeline # the piece second by second, in words
|
||||
raea fingerprint which out/cut.mp4 # which fingerprint judged it, and why
|
||||
```
|
||||
|
||||
`score` names which fingerprint judged the piece, then lists the moments it expects a note on, each in your words. On
|
||||
a picture axis that has learned where, a moment also says where in the frame and, on a render with a layer pass, the
|
||||
layers there ("top right on Floor"). `--json` gives every axis for every window, for a script.
|
||||
|
||||
An axis that **knows** can hold a post back until you've looked. One that is **learning** only advises. Your agents
|
||||
run `score` before they post, fix each moment that holds the cut back, or tell you why they didn't.
|
||||
|
||||
## Check a fix
|
||||
|
||||
```sh
|
||||
raea fingerprint score out/v2.mp4 --was out/v1.mp4
|
||||
```
|
||||
|
||||
For each moment that held v1 back, this says whether v2 fixed it, still has it, or looks **disguised**: nearer the
|
||||
axis's disguised defects than clean work, so the fix hid the defect instead of removing its cause. Only a fixed flag
|
||||
counts as fixed.
|
||||
|
||||
## Scripts, briefs and stills
|
||||
|
||||
A fingerprint reads more than video. A script, a brief or another text file gets EmbeddingGemma 2 rows, one per
|
||||
paragraph, and a still gets the picture columns. Each axis judges only what the file has, so a script is never called
|
||||
blurry. raea's own axes judge pictures, sound and motion. To judge writing, add an axis that reads text to your
|
||||
fingerprint.ts and teach it like any other.
|
||||
|
||||
## Things in a shot
|
||||
|
||||
```sh
|
||||
raea render shot.tsx --layers -o shot.mp4 # the video and its layers (shot.layers)
|
||||
raea render shot.tsx --aov -o shot.aov # its depth, beside it
|
||||
raea fingerprint things shot.mp4 --json > things.json
|
||||
raea check shot.mp4 --things things.json
|
||||
```
|
||||
|
||||
`things` finds a piece's shots, the things in each (a render's layers, and anything marked on its notes) with their
|
||||
depth, and the camera's path. It says where a thing floats, where two pass through each other, where the camera lurches
|
||||
in the middle of a move, and where nothing is on screen. `raea check --things` turns those into findings beside the
|
||||
rest. Floating needs real depth: with the render's `--aov` pass beside it (`shot.aov` for `shot.mp4`) it uses the
|
||||
render's own depth, and without one it estimates depth from the picture, which can't always tell a hanging box from
|
||||
one on the floor.
|
||||
|
||||
## Profiles of work you admire
|
||||
|
||||
```sh
|
||||
raea fingerprint profile golden/*.mp4 --as reels --against others.txt
|
||||
raea fingerprint score cut.mp4 --profile reels
|
||||
```
|
||||
|
||||
A profile takes the ranges your references span: loudness, bass against treble, cuts a minute, motion, brightness,
|
||||
contrast, saturation and sharpness. A cut scored against it hears which measures fall outside, where, and which way
|
||||
to move. The profile checks itself: each reference has to fit the others' ranges more often than unrelated work does,
|
||||
or raea says it doesn't tell this taste apart.
|
||||
@@ -0,0 +1,47 @@
|
||||
---
|
||||
title: "Fingerprint: teach raea your eye"
|
||||
summary: "What raea learns about good work from your notes, marks and approvals, on your Mac: the axes it judges, the Fingerprint page, and what it can't judge yet."
|
||||
order: 0
|
||||
sources: ["docs/fingerprint.feature", "docs/fingerprint.md", "apps/fingerprint/src", "systems/fingerprint/src", "systems/fingerprint-use/src", "apps/app/src/fingerprint"]
|
||||
---
|
||||
|
||||
A fingerprint is your sense of good work, as raea has learned it on your Mac. It's a list of axes, the things you
|
||||
notice: blur, a black frame, hiss, clipping, a glow over everything, a frozen picture, and taste axes such as fake,
|
||||
barren or unreadable text. Each axis has a small model over encoders that run on your Mac (SigLIP 2 for pictures, CLAP
|
||||
for sound, YAMNet for sound events, EmbeddingGemma 2 for scripts and other text), so nothing leaves the machine unless
|
||||
you share it.
|
||||
|
||||
Your agents use it before they post a cut: `raea fingerprint score` lists the moments your fingerprint expects a note
|
||||
on, each named in your words, and the agent fixes them or tells you why it didn't. It tells you the axis and the
|
||||
moment, never a number.
|
||||
|
||||
## In this section
|
||||
|
||||
- [Train your fingerprint](train.md): learning from your own renders, your notes and marks, a box on the part of a
|
||||
sound you mean, and a post-mortem when a project is done.
|
||||
- [Check a cut with it](check.md): scoring a cut, checking a fix, scripts and stills, things in a shot, and profiles
|
||||
of work you admire.
|
||||
- [Projects and teams](projects.md): one fingerprint for each kind of work, which one judges a project, keeping one
|
||||
with a project or workspace, and sharing with a team.
|
||||
|
||||
## The Fingerprint page
|
||||
|
||||
Open **Fingerprint** in the sidebar. The card at the top is your mark, one column of bits for each axis, grouped by
|
||||
sense: pictures, sound and motion. Point at a sense to see its axes and how well each one judges. Below it, every axis
|
||||
says whether it **knows** (it's trusted, and can hold a post back until you've looked), is **learning** (it gives
|
||||
advice), or is still **to learn** (it only has its words). **Can't judge yet** lists what no axis can see, such as
|
||||
whether a piece works as a whole.
|
||||
|
||||
The name in the page's title is a menu of your fingerprints. **Settings** holds what one is for, what it builds on,
|
||||
whether it's your default, and **Learn from renders**.
|
||||
|
||||
A fingerprint's axes are a file you can read and edit, `~/.raea/fingerprints/NAME/fingerprint.ts`, typed by
|
||||
`raea/fingerprint` ([the SDK page](../reference/sdk/fingerprint.md)). Add, remove or reword an axis there; its
|
||||
evidence is raea's to keep. Every command is on [the CLI page](../reference/cli/fingerprint.md).
|
||||
|
||||
## What it can't do yet
|
||||
|
||||
Axes judge two-second moments, so a fingerprint can't say whether a piece works as a whole, or judge story and pace
|
||||
across shots. It can say where in the frame only for blur, glitches and flat, barren surfaces; glow it can only
|
||||
flag. Sound axes judge the whole sound in each moment, so a box's pitch band is kept but not yet learned from. A
|
||||
stylised look or a held shot can read as a defect. And taste axes with only words never hold a post back.
|
||||
@@ -0,0 +1,67 @@
|
||||
---
|
||||
title: "Projects and teams"
|
||||
summary: "One fingerprint for each kind of work, which one judges a project and why, keeping one with a project or its workspace from the app, and sharing one with a team."
|
||||
order: 3
|
||||
sources: ["docs/fingerprint.feature", "apps/fingerprint/src", "apps/app/src/fingerprint", "apps/app/host/fingerprint.ts"]
|
||||
---
|
||||
|
||||
## One for each kind of work
|
||||
|
||||
You can keep several fingerprints, each saying what it's for. One can build on another: a client's ads can start from
|
||||
your own and add what that client cares about. It inherits your axes and evidence, counts its own labels twice, and
|
||||
never changes yours.
|
||||
|
||||
```sh
|
||||
raea fingerprint new client-ads --about "Short ads for one brand: pace, type on screen" --extends me
|
||||
```
|
||||
|
||||
## Which one judges a project
|
||||
|
||||
Which one judges a piece is decided by where it lives: the project's fingerprints first, then the workspace's, then
|
||||
your own. At each level, the one whose `applies` matches the piece's kind wins, else that level's default.
|
||||
|
||||
In the app, a project's feed names it beside the project's name at the top: the fingerprint chip. Open it to see which
|
||||
fingerprint judges the project and why. When it's one of yours, **Open** takes you to its Fingerprint page. The chip
|
||||
shows once you have a fingerprint.
|
||||
|
||||
From a terminal:
|
||||
|
||||
```sh
|
||||
raea fingerprint which projects/brand/out/cut.mp4 # which one judges this, and why
|
||||
```
|
||||
|
||||
## Keep one with a project
|
||||
|
||||
The chip's menu has **Keep with this project** and **Keep with the workspace**. Pick one of your fingerprints under
|
||||
either and raea copies it into that folder and commits it, so it travels with the folder's repository: everyone on
|
||||
the team judges the project with the same taste, and the chip names it from then on.
|
||||
|
||||
The same from a terminal:
|
||||
|
||||
```sh
|
||||
raea fingerprint share client-ads --in project projects/brand # copy it into the project
|
||||
raea fingerprint use client-ads --in project projects/brand # and make it the one that judges there
|
||||
```
|
||||
|
||||
Use `--in workspace` for every project in the workspace.
|
||||
|
||||
## Sharing with a team
|
||||
|
||||
Sharing copies the axes and the evidence (embeddings, spans and labels) into the workspace or project, to travel with
|
||||
its repository. It never shares media or trained weights: each teammate's Mac trains its own from everyone's
|
||||
evidence, and each person's evidence sits in its own folder so two people labelling at once never edit the same
|
||||
file. When raea's encoders change, `raea fingerprint reembed FOLDER` moves the evidence to the new ones wherever it
|
||||
finds the media.
|
||||
|
||||
```sh
|
||||
raea fingerprint diff me ana # where two tastes differ, and the moments that show it
|
||||
```
|
||||
|
||||
## Notes teach the one that judged
|
||||
|
||||
Your notes and marks on a piece teach the fingerprint that judged it, so a client's notes stay with the client's
|
||||
fingerprint. When one of its lessons is really yours, move it up:
|
||||
|
||||
```sh
|
||||
raea fingerprint move --fp client-ads --axis glow # its glow labels become yours (me)
|
||||
```
|
||||
@@ -0,0 +1,73 @@
|
||||
---
|
||||
title: "Train your fingerprint"
|
||||
summary: "Teach a fingerprint from your own renders, your notes, marks and approvals, a box on the part of a sound you mean, and a post-mortem when a project is done; and when it trusts an axis."
|
||||
order: 1
|
||||
sources: ["docs/fingerprint.feature", "apps/fingerprint/src", "systems/fingerprint/src", "apps/app/src/fingerprint"]
|
||||
---
|
||||
|
||||
A new fingerprint judges from the words for each axis on day one. Everything after that is evidence: your own work,
|
||||
and what you say about it.
|
||||
|
||||
## From your renders
|
||||
|
||||
To train the mechanical axes, choose **Learn from renders** in the Fingerprint page's Settings, or run:
|
||||
|
||||
```sh
|
||||
raea fingerprint bootstrap ~/renders/*.mp4
|
||||
```
|
||||
|
||||
raea damages moments of your own finished work on purpose (a blur, a black frame, a gap in the sound) and learns the
|
||||
difference, held out by source, so it can't learn a shortcut. Each axis also has disguised versions of its defect, such
|
||||
as a blur that was sharpened afterwards or a freeze hidden under a slow zoom. An axis that misses its disguises stays
|
||||
advice.
|
||||
|
||||
The same run teaches picture axes where a defect sits. It blurs, punches a hole in, greys out or glows one patch of a
|
||||
frame, and learns to find the patch. An axis that finds it 85 times in 100 on renders it didn't learn from says where:
|
||||
`score` then gives the moment's place in the frame, such as "top right", and on a render with a layer pass the layers
|
||||
there, such as "on Floor", and `--sheet` boxes it on the frame.
|
||||
|
||||
## From your reviewing
|
||||
|
||||
Your own reviewing teaches it the rest:
|
||||
|
||||
```sh
|
||||
raea fingerprint teach cut.mp4 --axis blur --at 4.2 --bad # a moment you marked
|
||||
raea fingerprint approve final.mp4 # approved work is clean, except where you left a note
|
||||
raea fingerprint pair v1.mp4 v2.mp4 --axis glow # v2 is better on glow
|
||||
raea fingerprint read projects/stay # read your pinned notes into labels
|
||||
raea fingerprint readings --ask 50 # check 50 of those readings in the app
|
||||
raea fingerprint learn-notes projects/stay # once they read right, your notes become evidence
|
||||
```
|
||||
|
||||
Notes become evidence only after you've checked how they were read: the kind right 45 times in 50 and the axis 40. A
|
||||
note that asks for a creative change goes to the brief, never into an axis. Each project's notes teach the
|
||||
fingerprint that judges that project ([Projects and teams](projects.md)).
|
||||
|
||||
## Point at what you mean
|
||||
|
||||
A note can say exactly what it's about. On the picture, drop a pin and mark, box or lasso the thing you mean.
|
||||
|
||||
On the sound, choose **Spectrogram** on the timeline's sound track (or open the sound in Listen) and, with the Comment
|
||||
tool, drag a box around the part you mean, such as a hiss up high or a hum down low. A sound on its own shows its
|
||||
spectrogram under the waveform, where any drag draws a box. The note keeps the box's time as its span and its pitch
|
||||
band, your agent reads both with the note, and `learn-notes` labels that span and keeps the band in the label. Sound
|
||||
axes still judge the whole sound in each moment, so the band is kept but not yet learned from.
|
||||
|
||||
## When an axis is trusted
|
||||
|
||||
An axis is trusted once it has 16 labels of each kind from 3 projects, ranks real defects above clean work on
|
||||
projects it never saw, and catches its disguises. `raea fingerprint report` says where each one stands. An axis that is
|
||||
still under its bar with 300 labels is **stuck**: more labels won't help it, so `report` names it as one to try on
|
||||
another encoder.
|
||||
|
||||
## Looking back on a project
|
||||
|
||||
When a project is done, a post-mortem asks you what the fingerprint is least sure of:
|
||||
|
||||
```sh
|
||||
raea fingerprint postmortem projects/film # at most ten yes/no questions in the app, each with its moment
|
||||
raea fingerprint postmortem projects/film --tally # your answers become evidence; each head's score before and after
|
||||
```
|
||||
|
||||
It scores every version in the project's feed and first asks where a head disagrees with a label you gave on that
|
||||
moment, then where a head is nearest its flag, one question per axis within four seconds.
|
||||
@@ -0,0 +1,120 @@
|
||||
---
|
||||
title: "3D scenes"
|
||||
summary: "Write 3D in TSX with Bevy's names: a camera, lights, meshes and materials, moved by the frame, with 2D titles over them in the same composition."
|
||||
order: 2
|
||||
sources: ["sdk/raea/src/3d.tsx", "sdk/raea/src/mesh.ts", "sdk/raea/src/pbr.ts", "sdk/raea/src/light.ts", "sdk/raea/src/camera.ts", "sdk/guides/craft/bevy.md"]
|
||||
---
|
||||
|
||||
You write 3D the way you write the rest of a composition: components whose props are computed from the frame. raea
|
||||
turns them into Bevy entities (meshes, lights, cameras, glTF models, post-processing) and draws them under the page,
|
||||
so titles, captions and a score sit over the 3D in the same file. You never write Rust or a render loop. A render and
|
||||
a live play of the same file draw the same thing, so what you check in a render is what plays.
|
||||
|
||||
## A turntable
|
||||
|
||||
```tsx file=turntable.tsx
|
||||
// check: frames 0,45,89
|
||||
import { AbsoluteFill, Composition, Easing, interpolate, registerRoot, useCurrentFrame, useVideoConfig } from "raea";
|
||||
import { Cylinder, Entity } from "raea/3d";
|
||||
import { StandardMaterial } from "raea/pbr";
|
||||
import { Cuboid, Mesh3d } from "raea/mesh";
|
||||
import { AmbientLight, DirectionalLight } from "raea/light";
|
||||
import { Quat, Transform } from "raea/transform";
|
||||
import { Camera3d } from "raea/camera";
|
||||
|
||||
function Turntable() {
|
||||
const f = useCurrentFrame();
|
||||
const { fps, durationInFrames } = useVideoConfig();
|
||||
const turn = (f / fps) * (Math.PI / 3); // a sixth of a turn a second
|
||||
const z = interpolate(f, [0, durationInFrames - 1], [7, 5], { easing: Easing.out(Easing.cubic), extrapolateLeft: "clamp", extrapolateRight: "clamp" });
|
||||
return (
|
||||
<AbsoluteFill style={{ background: "#14161c" }}>
|
||||
<Camera3d transform={Transform.fromXyz(0, 1.6, z).lookingAt([0, 0.5, 0])} projection={{ Perspective: { fov: (40 * Math.PI) / 180 } }} />
|
||||
<AmbientLight brightness={160} />
|
||||
<DirectionalLight transform={Transform.fromXyz(3, 5, 4).lookingAt([0, 0, 0])} illuminance={11200} shadow_maps_enabled />
|
||||
<Entity transform={Transform.IDENTITY.withRotation(Quat.fromEuler("XYZ", 0, turn, 0))}>
|
||||
<Mesh3d transform={Transform.fromXyz(0, -0.1, 0)}>
|
||||
<Cylinder radius={1.4} half_height={0.1} />
|
||||
<StandardMaterial base_color="#2b2f3a" perceptual_roughness={0.6} />
|
||||
</Mesh3d>
|
||||
<Mesh3d transform={Transform.fromXyz(0, 0.6, 0)}>
|
||||
<Cuboid half_size={[0.45, 0.6, 0.45]} />
|
||||
<StandardMaterial base_color="#e8b04a" perceptual_roughness={0.35} metallic={0.2} />
|
||||
</Mesh3d>
|
||||
</Entity>
|
||||
<div style={{ position: "absolute", top: 80, width: "100%", textAlign: "center", fontFamily: "Inter", fontWeight: 800, fontSize: 72, color: "#ffffff" }}>
|
||||
Made to be seen
|
||||
</div>
|
||||
</AbsoluteFill>
|
||||
);
|
||||
}
|
||||
|
||||
registerRoot(() => <Composition id="turntable" component={Turntable} width={1080} height={1080} fps={30} durationInFrames={90} />);
|
||||
```
|
||||
|
||||
```sh
|
||||
raea render turntable.tsx --at 0,45,89 -o frames/
|
||||
raea render turntable.tsx -o turntable.mp4
|
||||
```
|
||||
|
||||
What each part does:
|
||||
|
||||
- **`Camera3d`** is the camera: where it is (`transform`) and its lens (`projection`, with the field of view in
|
||||
radians). The first camera in the tree is the one that renders.
|
||||
- **Lights**: `AmbientLight` fills the shadows, `DirectionalLight` is a sun (its brightness in lux, here 11,200),
|
||||
`shadow_maps_enabled` turns its shadows on.
|
||||
- **`Entity`** groups parts so they move together. Turning the group turns the plinth and the box on it.
|
||||
- **`Mesh3d`** is a visible thing: a shape (`Cylinder`, `Cuboid`, `Sphere`, `Torus` and others from `raea/mesh`) and
|
||||
a material (`StandardMaterial` from `raea/pbr`, with `base_color`, `perceptual_roughness` and `metallic`).
|
||||
- **`Transform`** places things: `Transform.fromXyz(x, y, z)`, `.lookingAt([x, y, z])`, and rotations from
|
||||
`Quat.fromEuler`. Y is up and units are metres, as in Bevy.
|
||||
- **The `div` after the 3D** is ordinary 2D layout, drawn over the scene.
|
||||
|
||||
## The rules for 3D
|
||||
|
||||
1. **Every value comes from the frame.** A spin is `(frame / fps) * speed`, not a value kept between frames. That is
|
||||
what keeps a render and a live play the same.
|
||||
2. **Rotations are in radians.** `Quat.fromEuler("XYZ", 0, Math.PI / 2, 0)` is a quarter turn about Y.
|
||||
3. **Colours are hex strings.** CSS variables don't reach the 3D.
|
||||
4. **Name parts that come and go** (`<Mesh3d name="lid">`), so raea matches them across frames.
|
||||
5. **A part's shape is fixed for its life.** Animate its transform, colour, opacity, emission, roughness or metalness;
|
||||
to change its shape, swap in another named part.
|
||||
|
||||
## Checking a scene
|
||||
|
||||
```sh
|
||||
raea scene lint turntable.tsx # parts floating, sunk into the floor, or clipping each other
|
||||
raea scene light turntable.tsx # how the scene is lit, and whether the subject is exposed well
|
||||
raea render turntable.tsx --review review/ # fixed cameras (hero, front, right, top, iso, low) in colour and clay
|
||||
```
|
||||
|
||||
`--review` writes the same scene from six fixed cameras, in colour and as untextured clay, so you can see the shapes
|
||||
and the light without the materials getting in the way.
|
||||
|
||||
## The 3D guides
|
||||
|
||||
The 3D guides go topic by topic, each with a complete composition to start from. Read one or two at a time:
|
||||
|
||||
```sh
|
||||
raea guide bevy # the map of 3D topics
|
||||
raea guide bevy/lights # one topic
|
||||
```
|
||||
|
||||
| Topic | Covers |
|
||||
|---|---|
|
||||
| `bevy/scene` | The camera, camera moves, groups, 2D under and over 3D |
|
||||
| `bevy/lights` | Sun, bulbs, spots, ambient light, shadows, brightness |
|
||||
| `bevy/materials` | Colour, metal, glass, glow, clearcoat, textures, toon shading and outlines, decals |
|
||||
| `bevy/meshes` | Primitives, modelled solids, blended organic shapes, trees, terrain, rocks, 3D text |
|
||||
| `bevy/animation` | Spins, springs, reveals, model animation clips |
|
||||
| `bevy/characters` | Bodies posed by goals, motion capture, walking to a spot |
|
||||
| `bevy/rooms` | Interiors, furniture along walls, windows, daylight, sound placed in the scene |
|
||||
| `bevy/games` | 3D games: state, input, many entities, collisions, state machines |
|
||||
| `bevy/assets` | glTF models, pictures in space, where files go |
|
||||
| `bevy/blender` | Fixing an asset in Blender first: scale, pivot, heavy meshes, FBX to glTF |
|
||||
| `bevy/splats` | Gaussian splats trained from footage, and animating them |
|
||||
| `bevy/liquids` | Liquids and goo, simulated and baked |
|
||||
| `bevy/post` | Bloom, fog, tone mapping, exposure, lens effects, motion blur |
|
||||
| `bevy/limits` | How much a scene can hold, and what isn't there yet |
|
||||
|
||||
The same topics ship in the raea skill as `3d/*.md`.
|
||||
@@ -0,0 +1,173 @@
|
||||
---
|
||||
title: "The storage, search and review API"
|
||||
summary: "Who can call raea's API (anyone on Pro or Team, on their own or in a team), how an agent key is made and scoped, and the calls for cloud libraries, search by meaning, files and review links."
|
||||
order: 5
|
||||
sources: ["docs/libraries.feature", "docs/review.feature", "apps/site/api/src/agent-keys.ts", "apps/site/api/src/library/routes.ts", "apps/site/api/src/library/search.ts", "apps/site/api/src/storage.ts", "apps/site/api/src/review.ts"]
|
||||
---
|
||||
|
||||
Your cloud libraries, their search and your review links are reachable over HTTP at `https://api.raea.io`, so an
|
||||
agent, a script or your own tool can find a shot, fetch it, add files, and share them for review. The raea app uses
|
||||
the same calls.
|
||||
|
||||
## Who can use it
|
||||
|
||||
Anyone on **Pro** or **Team** can, a person on their own included: there's no separate developer plan and no
|
||||
per-call price. The API reaches what lives in raea's cloud, so it comes with the plans that have cloud storage.
|
||||
|
||||
On **Free**, libraries stay on your Mac, and so does their search. Search them from the app, or from a terminal or an
|
||||
agent on the same Mac with [`raea library`](../reference/cli/library.md), which needs no key. Asking for an agent key
|
||||
on Free answers `402 agent_keys_paid`.
|
||||
|
||||
## Make an agent key
|
||||
|
||||
On [raea.io/account](https://raea.io/account), open Storage, then Agent access. Name the key after the agent that will
|
||||
use it, tick what it may do, and pick which libraries it reaches (all of them, or some). The key, `raea_ak_` and 64
|
||||
hex characters, is shown once with a ready-made example: copy it then. raea keeps only its hash.
|
||||
|
||||
A key lasts 90 days unless you choose otherwise (365 at most), up to 50 at once. Revoking one stops it on its next
|
||||
request. Every change made with a key goes in your storage log, with the key's name.
|
||||
|
||||
Send it as a bearer header on every call. Nothing else works with it: no cookie, no basic auth.
|
||||
|
||||
```sh
|
||||
curl https://api.raea.io/v1/libraries -H "authorization: Bearer raea_ak_..."
|
||||
```
|
||||
|
||||
## What a key may do
|
||||
|
||||
| Scope | Reaches |
|
||||
| --- | --- |
|
||||
| `files:read` | your libraries and their files, search, a file's download URL, storage used |
|
||||
| `files:write` | uploads, naming files in a cloud library, tags, new libraries and cloud sources |
|
||||
| `files:delete` | moving stored files to the trash, the trash, restoring from it |
|
||||
| `share` | review links: making, changing and stopping them, their comments; a project's collaborators |
|
||||
|
||||
A key reaches only those. Billing, connections, publishing, your computers, devices, Git LFS and the keys themselves
|
||||
answer `403 agent_scope`, whatever the key's scopes. A key limited to some libraries sees only their files (any other
|
||||
is `404`) and the files it uploaded itself; making a library, the trash and collaborators need a key for all of them.
|
||||
|
||||
## Find your libraries
|
||||
|
||||
```sh
|
||||
curl https://api.raea.io/v1/libraries -H "authorization: Bearer $RAEA_KEY"
|
||||
```
|
||||
|
||||
Each library comes with its `id`, `name`, `workspace`, `sources` (each with its `kind`: a `folder` or `volume` on one of
|
||||
your computers, `cloud`, or `drive` for Google Drive), and how many `files` it holds and has `indexed`. A library on
|
||||
your Mac only isn't here: it never leaves the Mac.
|
||||
|
||||
List a library's files, 200 at a time (up to 500), each with its `path`, `sha256`, `kind` and thumbnail:
|
||||
|
||||
```sh
|
||||
curl "https://api.raea.io/v1/libraries/lib_.../files?limit=200" -H "authorization: Bearer $RAEA_KEY"
|
||||
```
|
||||
|
||||
Pass the last `path` you got as `after=` for the next page.
|
||||
|
||||
## Search
|
||||
|
||||
```sh
|
||||
curl https://api.raea.io/v1/libraries/search \
|
||||
-H "authorization: Bearer $RAEA_KEY" -H "content-type: application/json" \
|
||||
-d '{"workspace": "<a library'\''s workspace>", "words": "a chip pulled apart, cheese stretching", "limit": 10}'
|
||||
```
|
||||
|
||||
| Field | |
|
||||
| --- | --- |
|
||||
| `workspace` | required: the workspace the libraries are in, as the list names it |
|
||||
| `words` | what you're looking for, as you'd describe it |
|
||||
| `vector` | the words' embedding, to search by meaning (below) |
|
||||
| `libraries` | a list: only these library ids |
|
||||
| `kind` | a list of any of `video`, `image` and `audio` |
|
||||
| `tags` | a list: only files with any of these tags |
|
||||
| `path` | a glob over the files' paths, like `cuts/**` |
|
||||
| `limit` | how many hits |
|
||||
| `sound` | `true` to rank by how things sound, for a described sound effect |
|
||||
|
||||
Each hit is a moment: the file's `sha256`, the segment's `t0` and `t1` in seconds, a `score`, what `matched` (its
|
||||
`picture`, `sound` or `words` by meaning, its `text` or `sound labels` by keyword), any `text` read or heard in it, its
|
||||
`labels`, a `thumb_url`, and the `file` with every place it's kept. The answer's `by` says how it searched.
|
||||
|
||||
**By meaning, or by words.** With `vector`, raea compares it with every shot's picture, sound and words, and matches
|
||||
your words as keywords too: `"by": "meaning"`. Without one, it searches by keywords alone: `"by": "words"`. The vector
|
||||
is EmbeddingGemma 2's (`onnx-community/embeddinggemma-2-ONNX`, 768 numbers) for the text
|
||||
`task: search result | query: ` followed by your words. raea never runs a model in its cloud for you: the app embeds
|
||||
your words on your Mac, which is what `raea library search` and the app's Search do, and raea.io's Storage page
|
||||
borrows one of your computers that's online.
|
||||
|
||||
## Get a file
|
||||
|
||||
```sh
|
||||
curl https://api.raea.io/v1/storage/blobs/<sha256> -H "authorization: Bearer $RAEA_KEY"
|
||||
```
|
||||
|
||||
The answer is a `url` good for an hour, and the file's `size`. Fetch the bytes from it directly. A file in a folder
|
||||
on one of your computers is in storage only once something has uploaded it (sharing it does); until then the hit's
|
||||
`file` says which computer has it.
|
||||
|
||||
## Add a file
|
||||
|
||||
Files go straight to storage, never through the API. Ask with the file's SHA-256 and size:
|
||||
|
||||
```sh
|
||||
curl https://api.raea.io/v1/storage/uploads -H "authorization: Bearer $RAEA_KEY" \
|
||||
-H "content-type: application/json" -d '{"sha256": "<sha256>", "size": 1048576}'
|
||||
```
|
||||
|
||||
The answer is `{"exists": true}` when raea has the file already, a `url` to `PUT` it to, or for a big file an
|
||||
`upload_id` with a URL for each part. Then `POST /v1/storage/uploads/complete` with `{sha256, upload_id, parts}` (each
|
||||
part's `n` and `etag`). An upload past your plan's storage is refused before it starts.
|
||||
|
||||
To put it in a cloud library, name it in one of the library's `cloud` sources:
|
||||
|
||||
```sh
|
||||
curl https://api.raea.io/v1/libraries/sources/<source id>/files -H "authorization: Bearer $RAEA_KEY" \
|
||||
-H "content-type: application/json" \
|
||||
-d '{"upsert": [{"path": "cuts/teaser.mp4", "sha256": "<sha256>", "size": 1048576, "mtime": 1794400000000, "kind": "video"}]}'
|
||||
```
|
||||
|
||||
raea doesn't index files on its own servers: one of your linked computers indexes it the next time it's online with
|
||||
raea open, and then it turns up in search. The same call takes `rename:
|
||||
[{from, to}]`, and `remove: [path]` with `files:delete`. Tags go on with `POST /v1/libraries/media/<sha256>/tags`
|
||||
`{"tags": [...]}`.
|
||||
|
||||
## Delete, with a way back
|
||||
|
||||
`DELETE /v1/storage/blobs/<sha256>` moves a file to the trash. It's refused (`409 in_use`, saying where) while a
|
||||
library still names it or a post is going out with it. `GET /v1/storage/trash` lists the trash, and
|
||||
`POST /v1/storage/trash/<sha256>/restore` brings a file back. raea deletes it for good after 30 days, and only you, on
|
||||
raea.io, can empty the trash sooner.
|
||||
|
||||
## Share for review
|
||||
|
||||
With the `share` scope, a key can send a stored file on a review link. Giving a key that scope is your say-so; Let
|
||||
agents share, in the app's Settings, is the same choice for agents working inside the app.
|
||||
|
||||
```sh
|
||||
curl https://api.raea.io/v1/review-links -H "authorization: Bearer $RAEA_KEY" \
|
||||
-H "content-type: application/json" \
|
||||
-d '{"sha256": "<sha256>", "type": "video/mp4", "title": "Teaser, cut 3", "days": 30}'
|
||||
```
|
||||
|
||||
The answer has the link's `id` and its `url` (raea.io/r/...) to hand on. `days` is 1 to 365 (30 if left out),
|
||||
`download` lets reviewers download the file, and `password` sets one. The file must be in your storage first:
|
||||
`409 not_stored` says to upload it.
|
||||
|
||||
| Call | |
|
||||
| --- | --- |
|
||||
| `GET /v1/review-links` | every link, newest first |
|
||||
| `GET /v1/review-links/<id>` | one link with its versions, comments and viewers |
|
||||
| `POST /v1/review-links/<id>/versions` | `{sha256, type}`: the next version, on the same link |
|
||||
| `POST /v1/review-links/<id>/comments` | `{body, version?, parent?}`: your answer to a reviewer |
|
||||
| `PATCH /v1/review-links/<id>/comments/<comment id>` | `{"resolved": true}` |
|
||||
| `PATCH /v1/review-links/<id>` | `{title?, days?, download?, password?}` |
|
||||
| `DELETE /v1/review-links/<id>` | stop sharing: the link stops working for everyone at once |
|
||||
|
||||
A link of several files is made in the app for now (the Library's Share for review bar); a key can't make one yet.
|
||||
|
||||
## Errors
|
||||
|
||||
A missing, unknown, revoked or expired key gets a plain-text `401`. Every other refusal is JSON with an `error` code
|
||||
and a `message` saying what to do: `402` for a plan without the feature, `403 agent_scope` for a call outside the key's scopes, `404` for
|
||||
anything that isn't yours (raea never says whether it exists), `409` for a conflict, and `413` when storage or the
|
||||
search index is full.
|
||||
@@ -0,0 +1,131 @@
|
||||
---
|
||||
title: "Apps on the web target or native"
|
||||
summary: "Write a desktop app as one React file, pick the web target (Blitz) or the native target (Rune), check it headless with scripted steps, and bundle it as a Mac app."
|
||||
order: 3
|
||||
sources: ["docs/targets.feature", "apps/targets/src", "sdk/ui/src/app.ts", "sdk/rune/src", "sdk/rune/examples"]
|
||||
---
|
||||
|
||||
An app is a React file with a default export: DOM elements, with inline `style` or Tailwind `className`, on raea's
|
||||
UI layer. One setting picks the host that draws it. Neither uses the operating system's widgets or a browser; both draw
|
||||
every pixel themselves on the GPU.
|
||||
|
||||
| | web (the default) | native |
|
||||
|---|---|---|
|
||||
| Engine | Blitz on Bevy, a browser engine | Rune, an app UI framework |
|
||||
| CSS | All of it, grid included | A subset: flex, no grid |
|
||||
| npm UI packages | Web ones work | Those that stay in the subset |
|
||||
| 3D | Yes | Not yet |
|
||||
| Motion | CSS transitions | Springs on every change, GPU effects |
|
||||
| Accessibility tree | | AccessKit, for screen readers |
|
||||
| Host size | about 175 MB | about 27 MB |
|
||||
|
||||
Pick native for a small, motion-heavy app with no 3D that passes its check. Anything else stays on web. A video or a
|
||||
game is a composition, not an app.
|
||||
|
||||
## A sign-in card
|
||||
|
||||
This app ships with raea as `sdk/rune/examples/signin.tsx` and passes the check on both targets. It uses only
|
||||
Tailwind classes:
|
||||
|
||||
```tsx
|
||||
import { useState } from "react";
|
||||
import { rune } from "@raea/rune";
|
||||
|
||||
export default function SignIn() {
|
||||
const [email, setEmail] = useState("");
|
||||
const [code, setCode] = useState("");
|
||||
const ready = email.includes("@") && code.length === 6;
|
||||
return (
|
||||
<div data-testid="page" className="flex min-h-screen flex-col items-center bg-zinc-50 p-6">
|
||||
<div className="flex w-full max-w-lg flex-col gap-5 rounded-xl border border-zinc-200 bg-white p-6 shadow-sm">
|
||||
<span className="text-lg font-semibold text-zinc-900">Sign in</span>
|
||||
<input data-testid="email" value={email} onChange={(e) => setEmail((e.target as HTMLInputElement).value)}
|
||||
className="h-9 rounded-md border border-zinc-300 px-3 text-sm focus:ring-2 focus:ring-blue-500/30" />
|
||||
<input data-testid="code" value={code} onChange={(e) => setCode((e.target as HTMLInputElement).value)}
|
||||
className="h-9 rounded-md border border-zinc-300 px-3 text-sm focus:ring-2 focus:ring-blue-500/30" />
|
||||
<button data-testid="submit" disabled={!ready}
|
||||
className="h-9 rounded-md bg-zinc-900 px-4 text-sm font-medium text-white disabled:opacity-50"
|
||||
{...rune({ motion: "snap" })}>
|
||||
Sign in
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
(This is a shortened copy; the shipped file adds a "remember this device" checkbox, a side-by-side layout from `md:`
|
||||
up, and dark mode.)
|
||||
|
||||
Unlike a composition, an app is interactive, so `useState` and event handlers work as in any React app.
|
||||
|
||||
## Pick the target
|
||||
|
||||
Say the target in the app's own file, as a literal:
|
||||
|
||||
```tsx
|
||||
export const app = { target: "native", title: "Notes", size: [480, 640], minSize: [360, 480] };
|
||||
```
|
||||
|
||||
With no `app` export, or no `target` in it, the target is `"web"`. `--target web` or `--target native` on the command
|
||||
line overrides it.
|
||||
|
||||
## Run, check and bundle
|
||||
|
||||
```sh
|
||||
raea app run signin.tsx # opens it in a window
|
||||
raea app check signin.tsx --png out/ # runs it headless and writes a PNG after each step
|
||||
raea app bundle signin.tsx -o SignIn.app # makes a Mac app
|
||||
```
|
||||
|
||||
Give the check its input as steps in the app's file, finding elements by `data-testid`:
|
||||
|
||||
```tsx
|
||||
export const steps = [{ press: "email" }, { type: "ada@example.com", into: "email" }, { type: "123456", into: "code" }, { press: "submit" }];
|
||||
```
|
||||
|
||||
or as `--script steps.json`. The check writes `00-mount.png`, then a PNG after each step, and `tree.json` with each
|
||||
element's role, label, text and box. Read the PNGs. When the app should run on both targets, check both:
|
||||
|
||||
```sh
|
||||
raea app check signin.tsx --target web --png out/web/
|
||||
raea app check signin.tsx --target native --png out/native/
|
||||
```
|
||||
|
||||
What each target is held to:
|
||||
|
||||
- **native** fails on any prop Rune doesn't map and any host call it doesn't answer, naming each with its element's
|
||||
path in `unmapped.json` and `unanswered.json`. Change the prop, or keep the app on web.
|
||||
- **web** passes when it draws, and lists what native wouldn't draw.
|
||||
|
||||
On a native app, `raea app check --video out/app.mp4` films the steps at 60 fps, with a cursor gliding to each element
|
||||
it presses.
|
||||
|
||||
## Signing
|
||||
|
||||
`raea app bundle` signs ad hoc unless you give it your own identity:
|
||||
|
||||
```sh
|
||||
raea app bundle signin.tsx -o SignIn.app --identity "Developer ID Application: Your Name (TEAMID)" --notarize PROFILE
|
||||
```
|
||||
|
||||
`PROFILE` is a `notarytool` keychain profile. raea always signs with your identity, never its own.
|
||||
|
||||
## What only Rune does
|
||||
|
||||
Typed props from `@raea/rune` add Rune's motion and effects:
|
||||
|
||||
```tsx
|
||||
<div {...rune({ motion: "pop", transition: { effect: { push: "top" }, enter: "pop" } })}>...</div>
|
||||
```
|
||||
|
||||
There are also `lead`, `instant`, `blur`, `backdropBlur` and `glass`, and the components `Badge`, `Spinner`,
|
||||
`Progress`, `RollingText` and `Switch`. On the web target a preset motion becomes a CSS transition, blur and glass
|
||||
become filters, and the rest is ignored and listed by the check.
|
||||
|
||||
## Host calls
|
||||
|
||||
`call` and `callSync` from `@raea/ui/wire` reach the host on both targets: `net.fetch`, `net.ws.*`, `net.storage.*`,
|
||||
`net.clipboard.*`, `os.open` (http, https and mailto), `fs.pick`, `fs.save`, `fs.read`, `fs.write` and
|
||||
`dialog.message`. In a headless check, a step answers a dialog: `{ pick: ["a.txt"] }`, `{ save: "out.txt" }`,
|
||||
`{ dialog: 0 }`.
|
||||
@@ -0,0 +1,86 @@
|
||||
---
|
||||
title: "Web components that measure"
|
||||
summary: "What a composition's DOM answers, as Chrome does: refs' geometry, style and tree, document and window, canvas and svg text measures, Range, ResizeObserver, and the frame held until a measure lands. And what it lacks."
|
||||
order: 4
|
||||
sources: ["docs/layout-reads.feature", "sdk/raea/src/dom-reads.ts", "sdk/raea/src/dom-tree.ts", "sdk/raea/src/dom-style.ts", "sdk/raea/src/dom-document.ts", "sdk/raea/src/dom-range.ts", "sdk/raea/src/dom-svgtext.ts", "sdk/raea/src/dom-observers.ts", "sdk/raea/src/dom-load.ts", "sdk/raea/src/canvas2d.ts", "sdk/raea/src/frame-globals.ts", "sdk/raea/src/hold.ts"]
|
||||
---
|
||||
|
||||
Many components written for a web page measure before they draw: a title sized to fit its box, captions that wrap at
|
||||
the width a line really takes, a caret placed after the last typed letter. In a composition those reads answer as they
|
||||
do in Chrome, from the same layout and the same font files that draw the frame. Nothing needs importing: the entry
|
||||
installs them on every ref and on `document` and `window`.
|
||||
|
||||
## Measure, then let the frame be taken
|
||||
|
||||
A measure runs in an effect, after the first commit. Hold the frame until it's done, so the frame taken is the measured
|
||||
one:
|
||||
|
||||
```tsx
|
||||
import { continueRender, delayRender } from "raea";
|
||||
import { loadFont } from "raea/text";
|
||||
|
||||
loadFont("Inter");
|
||||
|
||||
export const Fit = ({ text }: { text: string }) => {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const [scale, setScale] = useState(1);
|
||||
const [handle] = useState(() => delayRender("fit the title"));
|
||||
useEffect(() => {
|
||||
document.fonts.ready.then(() => {
|
||||
setScale(1080 / ref.current!.getBoundingClientRect().width);
|
||||
continueRender(handle);
|
||||
});
|
||||
}, []);
|
||||
return <div ref={ref} style={{ display: "inline-block", fontFamily: "Inter", transform: `scale(${scale})` }}>{text}</div>;
|
||||
};
|
||||
```
|
||||
|
||||
A hold never released fails the render after 30 s, naming its label ([raea/hold](../reference/sdk/hold.md)). Load a
|
||||
web font with `loadFont` so the measure uses its own faces; a family you never asked for is measured in raea's bundled
|
||||
faces, as a browser falls back.
|
||||
|
||||
## What a ref answers
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Geometry | `getBoundingClientRect()` (transforms included), `getClientRects()`, `offsetWidth`, `offsetHeight`, `offsetLeft`, `offsetTop`, `offsetParent`, `client*`, `scroll*`. Values are Chrome's, in the composition's CSS px. |
|
||||
| Style | `el.style` reads what React committed. Writing it (a property, `setProperty`, `cssText`) restyles the element at once; React's next commit to the same property wins. `getComputedStyle(el)` answers from the page's computed style. |
|
||||
| The tree | `children`, `childNodes`, the sibling and parent links, `tagName`, `id`, `className`, `classList`, `dataset`, `getAttribute`, `textContent`, `contains`, `matches`, `closest`, `querySelector` and `querySelectorAll`. |
|
||||
| svg text | `getComputedTextLength`, `getNumberOfChars`, `getStartPositionOfChar`, `getEndPositionOfChar` and `getSubStringLength`, in the element's computed font, letter- and word-spacing and font-variation-settings included, hidden text too. |
|
||||
| canvas | `getContext("2d")` with `measureText` (width, the ink's and the font's boxes, shaped from the faces the canvas draws with), `letterSpacing` and `wordSpacing`, `getImageData` and `putImageData`. |
|
||||
| images | An `<img>`'s `onLoad` fires once it's made or its `src` changes; the frame still waits for the picture itself. |
|
||||
|
||||
Selectors cover tag, `*`, `#id`, `.class`, `[attr]` and `[attr=v]` (and `~=`, `^=`, `$=`, `*=`), the descendant and
|
||||
child combinators, comma lists, `:first-child`, `:last-child`, `:only-child`, `:nth-child()` and `:not()`. Anything
|
||||
else throws a SyntaxError, as Chrome's does.
|
||||
|
||||
## document and window
|
||||
|
||||
- `document.body` is the composition's root. `getElementById`, `querySelector` and `querySelectorAll` search it.
|
||||
- `document.createElement` makes an element of the page: appended into the composition it's laid out, measured and
|
||||
drawn, and removed it's gone. That's how a component measures a hidden copy. A canvas made there is an
|
||||
OffscreenCanvas with the same 2D context.
|
||||
- `document.createRange()` over a text node gives the rect of its characters, placed where the line starts. One line
|
||||
only: a range across wrapped lines gets one rect, the width of its characters.
|
||||
- `document.fonts` has `ready`, `load` and `check`; a `FontFace` given by URL is fetched and its text set in it. One
|
||||
that doesn't load rejects, and the text falls back.
|
||||
- `window` has `innerWidth`, `innerHeight` and `devicePixelRatio` for the composition's size, and `getComputedStyle`.
|
||||
- `requestAnimationFrame` calls back once per frame drawn, given that frame's time, so a frame drawn again gets the
|
||||
same calls. `new Image()` fires `load` when its `src` is set, with no pixel size.
|
||||
- `ResizeObserver` calls back once when it starts observing, then after any layout that changed an observed element's
|
||||
size, with `contentRect`, `borderBoxSize` and `contentBoxSize`.
|
||||
|
||||
## What it lacks
|
||||
|
||||
- `MutationObserver` and `IntersectionObserver` exist, so a component that makes one doesn't throw, but they never
|
||||
call back.
|
||||
- An `<img>`'s `onError` never fires: an image that doesn't load fails the render, naming its src.
|
||||
- `new Image()` has no `naturalWidth` or `naturalHeight` (they stay 0).
|
||||
- An element has no `innerHTML` or `outerHTML`: read `textContent`, or walk `children` and `childNodes`.
|
||||
- A Range across wrapped lines is one rect, not one per line, and an inline element's `getClientRects()` is one rect
|
||||
too.
|
||||
- In a pass that draws no page (the sound pass, a 3D pre-pass) every read answers 0, and holds there are released.
|
||||
- Inside a `RuneLayer` in an app, `getBoundingClientRect` is zero.
|
||||
|
||||
Measured against Chrome on snapcn's measuring components, `bench/layout-reads/` in the repository is the harness that
|
||||
holds these to it ([#54](https://github.com/shinyobjectz/raea/issues/54)).
|
||||
@@ -0,0 +1,97 @@
|
||||
---
|
||||
title: "Captions and cues on words"
|
||||
summary: "Cut footage by what was said, cue any part on the moment a phrase is spoken with word(), and build captions from useWords() so they follow every re-cut."
|
||||
order: 1
|
||||
sources: ["sdk/guides/craft/motion/words.md", "engine/cli/src/usage.rs"]
|
||||
---
|
||||
|
||||
Most videos people make are someone talking. raea times an edit by its words instead of its seconds: a title lands
|
||||
when the line is said, wherever that line ends up after the next trim. This page shows how to cut a take by its
|
||||
lines, cue parts on phrases, and build captions that follow the cut.
|
||||
|
||||
## 1. Cut a take by its lines
|
||||
|
||||
Put the take under the project's `media/` folder and cut it to the lines you want:
|
||||
|
||||
```sh
|
||||
raea cut interview.mp4 "We started in a garage" "Now we ship to forty countries"
|
||||
```
|
||||
|
||||
raea transcribes the take first if it has no `interview.words.json`, then cuts it in the pauses around each line it
|
||||
says. It writes `cuts.ts` (the cut) and `words.json` (every word kept, with its timing) beside the edit. `--at 12.4-18.9`
|
||||
cuts at seconds instead, and `--append` adds to the existing cut.
|
||||
|
||||
`raea render` reads `words.json` from beside the edit, so the words reach the composition without any wiring.
|
||||
|
||||
## 2. Cue a part on a phrase
|
||||
|
||||
```tsx
|
||||
import { Sequence, word } from "raea";
|
||||
|
||||
function Title() {
|
||||
// the frame where "forty countries" starts, wherever the cut puts it
|
||||
const at = word("forty countries");
|
||||
return (
|
||||
<Sequence from={at} durationInFrames={60}>
|
||||
<h1 style={{ fontSize: 96, color: "#fff" }}>40 countries</h1>
|
||||
</Sequence>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
- `word(phrase)` returns the frame where the phrase starts. `word(phrase, { edge: "end" })` is the frame after it
|
||||
ends, and `word(phrase, { occurrence: 2 })` is the second time it's said.
|
||||
- Matching ignores case and punctuation, so `word("forty countries")` finds "forty countries."
|
||||
- If the phrase is never said, `word()` throws and names it. Treat that as a check: the line isn't in the cut.
|
||||
- Call `word()` inside a component, while rendering, not at the top of the file. It reads the clock.
|
||||
- Inside a `Sequence`, `word()` is still a composition frame. Subtract the Sequence's `from` to use it locally.
|
||||
|
||||
## 3. Build captions
|
||||
|
||||
`useWords()` returns every word heard on the timeline as `{ text, from, to }` in the frames of the nearest Sequence
|
||||
(`to` is exclusive). Words cut out of the edit aren't there, so captions follow the cut by themselves.
|
||||
|
||||
```tsx
|
||||
import { useCurrentFrame, useWords } from "raea";
|
||||
|
||||
function Captions() {
|
||||
const frame = useCurrentFrame();
|
||||
const words = useWords();
|
||||
// the words said in the last second, up to the current one
|
||||
const shown = words.filter((w) => w.from <= frame && frame < w.to + 30).slice(-3);
|
||||
return (
|
||||
<div style={{ position: "absolute", bottom: 360, width: "100%", textAlign: "center", fontSize: 84, fontWeight: 800, color: "#fff" }}>
|
||||
{shown.map((w) => (
|
||||
<span key={w.from} style={{ color: frame < w.to ? "#ffd84a" : "#fff" }}>{w.text} </span>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
Rules for captions that read well:
|
||||
|
||||
- **Group the words**: start a new group after three words, after punctuation, or after a pause of more than eight
|
||||
frames. Show a group from its first word until the next group starts.
|
||||
- **Size them** at 60 pixels or more at 1080 wide, with at least 3:1 contrast against what's behind them.
|
||||
- **Keep them in one place**, off the face, off logos and off burned-in text.
|
||||
- **Fix names.** Speech-to-text mishears names. Map each wrong spelling to the right one before it reaches the screen.
|
||||
|
||||
`raea guide words` has a complete karaoke-caption composition with grouping and a lit current word.
|
||||
|
||||
## 4. Check the cues
|
||||
|
||||
```sh
|
||||
raea render edit.tsx -o edit.mp4 --manifest render.json
|
||||
raea check edit.mp4 --manifest render.json --words words.json
|
||||
```
|
||||
|
||||
With `--words`, the check finds cues that miss the word they were tied to, captions on screen too briefly to read,
|
||||
and caption contrast against the footage.
|
||||
|
||||
## Mistakes to avoid
|
||||
|
||||
- Typing cue frames by ear. Every trim moves them. Use `word()`.
|
||||
- Calling `word()` at the top level of the file. There is no clock there, and it throws.
|
||||
- Captions wider than the frame. Fix a width, centre them, and keep groups short.
|
||||
- Showing the transcript's spelling of a brand or a person's name.
|
||||
@@ -0,0 +1,63 @@
|
||||
---
|
||||
title: "raea docs"
|
||||
summary: "What raea is, and a map of every page in these docs, so an agent reading only this page knows where everything is."
|
||||
order: 0
|
||||
sources: ["docs/manual"]
|
||||
---
|
||||
|
||||
raea is the Render Anything Engine. You describe a video, a motion graphic, a 3D scene, a game or an app in
|
||||
TypeScript and React, and raea draws it on the GPU with its own engine, built on the Bevy game engine. The same file
|
||||
renders to an MP4, plays live as a game, or renders single frames for you to look at. It runs on your own computer
|
||||
and needs no account.
|
||||
|
||||
These docs are written for coding agents first and for developers second. Every page is plain Markdown: add `.md` to
|
||||
any page's address to get its source, or read [llms.txt](https://raea.io/llms.txt) for the list of pages. Offline,
|
||||
`raea skill` and `raea guide` print the skill and the craft guides that match the raea you have installed.
|
||||
|
||||
```sh
|
||||
curl -fsSL https://raea.io/install | sh # macOS (Apple Silicon) or Linux (x86_64)
|
||||
raea --version # the version these docs should match
|
||||
```
|
||||
|
||||
## If you are an agent
|
||||
|
||||
Read [How an agent should use raea](start/agents.md) first. It gives the order of work: read the project, write the
|
||||
composition, check it in a second, render stills and look at them, render the export and check it, then hand it over.
|
||||
The raea skill (`raea skill` prints it) is the short version of the same loop; these docs are the long version.
|
||||
|
||||
## Start
|
||||
|
||||
- [Install raea](start/install.md): install, update, pick a version, and what goes where.
|
||||
- [Your first video](start/first-video.md): a composition from an empty folder to an MP4, in five minutes.
|
||||
- [Your first game](start/first-game.md): a game that plays live and renders the same every time.
|
||||
- [How an agent should use raea](start/agents.md): the loop, what runs headless, and what waits on a person.
|
||||
|
||||
## Concepts
|
||||
|
||||
- [Compositions and frames](concepts/compositions.md): a composition is a function of the frame, and why that matters.
|
||||
- [Rendering and checking](concepts/rendering.md): stills, exports, quality, and the checks that catch defects.
|
||||
- [Workspaces and projects](concepts/workspaces.md): where work lives, and the spec files an agent reads first.
|
||||
|
||||
## Guides
|
||||
|
||||
- [Captions and cues on words](guides/words.md): cue anything on the moment a phrase is said, and build captions.
|
||||
- [3D scenes](guides/3d.md): cameras, lights, meshes and materials in TSX, drawn by Bevy.
|
||||
- [Apps on the web target or native](guides/apps.md): a React file that runs as a desktop app.
|
||||
|
||||
## Fingerprint
|
||||
|
||||
- [Fingerprint: teach raea your eye](fingerprint/index.md): what raea learns about good work from your notes, on your Mac.
|
||||
- [Train your fingerprint](fingerprint/train.md): your renders, notes and marks, and a box on the part of a sound you mean.
|
||||
- [Check a cut with it](fingerprint/check.md): score a cut before it's posted, and check that a fix really fixed it.
|
||||
- [Projects and teams](fingerprint/projects.md): which fingerprint judges a project, and keeping one with it for the team.
|
||||
|
||||
## Reference
|
||||
|
||||
- [The CLI](reference/cli.md): a page for each of the 43 `raea` verbs, with its forms, where it runs and what each flag does.
|
||||
- [The SDK](reference/sdk.md): a page for each `raea` import path, with every export's signature, props and examples.
|
||||
- [Files and specs](reference/files.md): a workspace's and a project's files, and each spec's fields.
|
||||
- [Settings](reference/settings.md): every setting raea reads from the environment or `~/.raea/env`.
|
||||
|
||||
## What's new
|
||||
|
||||
- [What's new](whats-new/index.md): every release, newest first, with what changed and what is still missing.
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
title: "raea add"
|
||||
summary: "Add, remove and install npm packages for a project, with no Node or npm: raea.lock and node_modules."
|
||||
order: 28
|
||||
order: 29
|
||||
sources: ["io/npm/src/lib.rs"]
|
||||
---
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
title: "raea brand"
|
||||
summary: "Read a brand kit from a website on this machine: colours, fonts and logos into brand/ and BRAND.md."
|
||||
order: 29
|
||||
order: 30
|
||||
sources: ["engine/cli/src/brand.ts", "engine/cli/src/scrape.ts"]
|
||||
---
|
||||
|
||||
|
||||
@@ -73,7 +73,7 @@ last change is still joined, with a note that what it measured may have moved.
|
||||
```sh
|
||||
raea check EDIT.tsx --quick [--shape S] [--platform P] [--taste T] [-o check.json] (three stills of a composition checked for text: clipped, cramped, safe areas, sizes; about a second)
|
||||
raea check [PROJECT|EDIT.tsx] [--composition ID] [--only ID] [--taste T] [--render OUT | --no-render] [--json] (every check that applies to each composition, over its frames: raea's floor on its newest render, the person's taste, the workspace's and the project's rules (a controller's rule fields: one of raea's checks by name, or a project's .ts check); what needs a render and has none waits, and says so)
|
||||
raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--shape 16:9|9:16|4:5|1:1] [--platform tiktok|reels|shorts] [--taste taste.ts|DIR] [-o check.json] (an export against the floor: clipped text, contrast, safe areas, freezes, flashing, cues, loudness, blotching, a placeholder brand kit; its findings errors, warns and notes)
|
||||
raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--things T.json] [--shape 16:9|9:16|4:5|1:1] [--platform tiktok|reels|shorts] [--taste taste.ts|DIR] [-o check.json] (an export against the floor: clipped text, contrast, safe areas, freezes, flashing, cues, loudness, blotching, a placeholder brand kit, and with --things what `raea fingerprint things --json` found: a thing floating or passing through another, the camera lurching mid-move, an empty frame; its findings errors, warns and notes)
|
||||
```
|
||||
|
||||
Headless: it needs nothing running and opens no window. Takes up to 1 argument besides its flags.
|
||||
@@ -93,6 +93,7 @@ Headless: it needs nothing running and opens no window. Takes up to 1 argument b
|
||||
| `--render` | `OUT` | Join this render instead of the composition's newest in the project's record. |
|
||||
| `--shape` | `S` | The delivery's aspect ratio, for its safe areas. |
|
||||
| `--taste` | `T` | The person's taste files: the rules in them that carry a `check` are applied too. |
|
||||
| `--things` | `T.json` | what `raea fingerprint things FILE --json` found in the video (a thing floating or passing through another, the camera lurching mid-move, an empty frame), as findings |
|
||||
| `--words` | `W.json` | The transcript, to check cues against their words and the voice against the music. |
|
||||
| `-o` | `check.json` | Write the findings as JSON, for a later review or for `raea next`. |
|
||||
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
---
|
||||
title: "raea component"
|
||||
summary: "Copy a ready-made component or set into the project's components/, or the workspace's shared/components/, to use and change as your own."
|
||||
order: 27
|
||||
sources: ["engine/cli/src/index.ts", "engine/cli/src/registry.gen.ts"]
|
||||
---
|
||||
|
||||
Components are ready-made pieces of a composition (captions, lower thirds, end cards and the like) and sets of them.
|
||||
`raea component list` shows them; `raea component add` copies one into `components/NAME/`, where it's yours: raea
|
||||
never updates or overwrites it unasked. With `--shared` it goes into the workspace's `shared/components/` instead, for
|
||||
every project to import as `@shared/components/NAME`. `raea part` is the old name and still works.
|
||||
|
||||
```sh
|
||||
raea component list
|
||||
raea component add captions end-card
|
||||
raea component add reel --shared
|
||||
```
|
||||
|
||||
<!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions -->
|
||||
|
||||
## Usage
|
||||
|
||||
```sh
|
||||
raea component list | raea component add NAME ... [--shared] [--force] | raea part list | raea part add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; raea part is its old name)
|
||||
```
|
||||
|
||||
Headless: it needs nothing running and opens no window. Takes any number of arguments besides its flags.
|
||||
|
||||
## Flags
|
||||
|
||||
| Flag | Takes | What it does |
|
||||
| --- | --- | --- |
|
||||
| `--force` | – | Replace a component's files that are already there. Without it, an existing component is left alone and the command stops. |
|
||||
| `--shared` | – | Copy into the workspace's `shared/components/` instead, where every project in the workspace imports it as `/components/NAME`. |
|
||||
|
||||
<!-- generated:end -->
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
title: "raea doctor"
|
||||
summary: "Find what doesn't match this version of raea: old brief files, an older workspace format, an agent's stale skill."
|
||||
order: 49
|
||||
order: 50
|
||||
sources: ["apps/workspace/src/doctor.rs"]
|
||||
---
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
title: "raea findings"
|
||||
summary: "What each render and check found, read back from the project's record: fixed, new and carried since the one before."
|
||||
order: 44
|
||||
order: 45
|
||||
sources: ["apps/direction/src/findings.rs", "core/facts/src/record.rs"]
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
---
|
||||
title: "raea fingerprint"
|
||||
summary: "A person's sense of good work, learned on this Mac: axes with small heads over on-device encoders that score a render moment by moment and say what they can't judge yet."
|
||||
order: 44
|
||||
sources: ["apps/fingerprint/src/lib.rs", "systems/fingerprint/src/taxonomy.rs", "systems/fingerprint-things/src/things.rs"]
|
||||
---
|
||||
|
||||
A fingerprint is one person's sense of good work, kept in `~/.raea/fingerprints/NAME`. It is a list of axes (blur,
|
||||
flash, clipping, pace, a brand's colours) with a small head for each over encoders that run on this Mac: SigLIP for
|
||||
pictures, CLAP for sound, YAMNet for sound events and EmbeddingGemma 2 for scripts and other text; each axis judges
|
||||
only what a file has. A new axis judges from its words until it has been trained;
|
||||
`bootstrap` trains the mechanical axes by damaging moments of your own renders, and `teach` adds a label at a moment
|
||||
you point at. A person can keep several, each saying what it's for, and one can build on another with `--extends`.
|
||||
The app's Fingerprint page shows the same thing: what each one knows, what it's still learning, and what it can't
|
||||
judge yet. `postmortem` looks back on a finished project with at most ten questions, and `things` says where a
|
||||
thing floats or passes through another, the camera lurches or the frame is empty, for `raea check --things`. See
|
||||
[docs/fingerprint.md](https://github.com/shinyobjectz/raea/blob/main/docs/fingerprint.md) for the plan.
|
||||
|
||||
```sh
|
||||
raea fingerprint new me
|
||||
raea fingerprint new client-ads --about "Short ads for one brand" --extends me
|
||||
raea fingerprint bootstrap renders/*.mp4 --fp client-ads
|
||||
raea fingerprint score cut.mp4 --timeline
|
||||
raea fingerprint teach cut.mp4 --axis blur --at 4.2 --bad
|
||||
raea fingerprint report
|
||||
raea fingerprint postmortem projects/film
|
||||
raea fingerprint things shot.mp4 --json > things.json
|
||||
```
|
||||
|
||||
<!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions -->
|
||||
|
||||
## Usage
|
||||
|
||||
```sh
|
||||
raea fingerprint new NAME [--who W] [--about TEXT] [--extends FP] [--kinds K,K] [--tags T,T] | raea fingerprint bootstrap FILE... [--from LIST] [--per N] | raea fingerprint teach FILE --axis A --at T [--bad|--good] [--span S] [--box x0,y0,x1,y1] [--words W] [--project P] | raea fingerprint approve FILE... [--project P] | raea fingerprint pair WORSE BETTER --axis A [--at T] [--then T2] | raea fingerprint versions V1 V2... | raea fingerprint profile REFS... --as NAME [--against LIST] | raea fingerprint score FILE [--was OLD] [--json] [--sheet out.png] [--timeline] [--profile NAME] | raea fingerprint report [--json] | raea fingerprint which [PATH] [--json] | raea fingerprint use NAME [--in project|workspace] [PATH] | raea fingerprint diff A B [--json] | raea fingerprint share NAME [--in project|workspace] [PATH] | raea fingerprint reembed PLACE... | raea fingerprint read PROJECT [--by kimi|claude] | raea fingerprint readings [PROJECT] [--ask N] [--tally] | raea fingerprint learn-notes [PROJECT] | raea fingerprint move [--fp CHILD] [--to PARENT] [--axis A] [--source S] [--project P] | raea fingerprint postmortem [PROJECT] [--ask N] [--tally] | raea fingerprint things FILE [--project P] [--json] | raea fingerprint stop [--fp NAME] (a person's sense of good work as axes with small heads over on-device encoders, docs/fingerprint.md: new makes ~/.raea/fingerprints/NAME with raea's base taxonomy in fingerprint.ts (or FP's axes with --extends), what it's for, the kinds of piece and project tags it judges, and every axis scoring from its words; bootstrap puts known defects into windows of real work and trains the mechanical axes, held out by source, and patch heads that say where in the frame a picture defect is; teach adds a label at a moment; approve makes approved work clean on every axis, away from its notes; pair says one moment is better than another on an axis (a pick, a hand edit); versions makes weak pairs of noted moments the next version changed; score prints the moments it expects a note on first (where in the frame, and the layers there, when its patch head points held out), then every axis per window with --json, a sheet PNG with --sheet, or the piece second by second in words with --timeline, and with --was OLD whether each of OLD's gating flags is fixed, still there, or looks disguised (nearer the axis's disguised defects than clean work); profile takes the ranges of work you admire (loudness, tilt, cut rate, motion, brightness, contrast, saturation, sharpness), checked leave-one-out, and score --profile says what falls outside them, where and which way; report says each head's held-out score, labels, cheats, gate and what it can't judge; which says the one that judges a piece (its project's, its workspace's, then yours) and why, use pins one there, diff lists the axes two fingerprints rank the same evidence most differently on, and share copies one's taxonomy and evidence (no heads, no media) into a project or workspace for its team; reembed moves a fingerprint's evidence to this machine's encoders, re-embedding the rows whose media it finds; read has a fresh kimi or claude session read a project's pinned notes into kinds and axes, readings puts them to you to check and tallies your answers, and learn-notes makes the defects and praise evidence once you've agreed with 45 kinds and 40 axes in 50, each project's in the fingerprint that judges it; move takes a child's own labels (by axis, source or project) up into a fingerprint it extends, which never reads them otherwise; postmortem scores every version in a project's feed and asks you at most ten yes/no questions in the app, each with its moment playing, where the fingerprint disagrees with your labels or is least sure, and --tally makes your answers evidence and says how each head's held-out score moved; things finds a piece's shots, its things (a render's layers, and the marks drawn on its notes) with their depth, and the camera's path, and says where a thing floats, two pass through each other, the camera lurches mid-move or nothing is on screen, as JSON for `raea check --things` with --json)
|
||||
```
|
||||
|
||||
Headless: it needs nothing running and opens no window. Takes any number of arguments besides its flags.
|
||||
|
||||
## Flags
|
||||
|
||||
| Flag | Takes | What it does |
|
||||
| --- | --- | --- |
|
||||
| `--about` | `TEXT` | What this fingerprint is for, in a sentence, shown beside its name in the app |
|
||||
| `--against` | `LIST` | With profile: a file listing unrelated work, one path a line, that the references must fit their own ranges better than |
|
||||
| `--as` | `NAME` | With profile: the name the profile is kept under, for score --profile |
|
||||
| `--ask` | `N` | With readings: put N of the readings to you in the app, one question each, to check before notes train; with postmortem: ask at most N (10 at most) |
|
||||
| `--at` | `T` | The moment a label is for, in seconds |
|
||||
| `--axis` | `A` | The axis a label is for, by name, such as blur or clip |
|
||||
| `--bad` | – | The moment has the problem the axis names (the default) |
|
||||
| `--box` | `x0,y0,x1,y1` | Where in the frame the label is, as fractions of the width and height |
|
||||
| `--by` | `kimi\|claude` | With read: which fresh session reads your notes, kimi (the default) or claude |
|
||||
| `--extends` | `FP` | Another of your fingerprints to start from: the new one takes its axes and adds its own |
|
||||
| `--fp` | `CHILD` | Which fingerprint to use, by name; without it, the default |
|
||||
| `--from` | `LIST` | A file listing the renders to learn from, one path a line, relative to the file; lines starting with # are skipped |
|
||||
| `--good` | – | The moment is fine on that axis |
|
||||
| `--in` | `project\|workspace` | With use or share: the level the fingerprint is pinned or copied to, the project's or the workspace's folder |
|
||||
| `--json` | – | Print the result as JSON |
|
||||
| `--kinds` | `K,K` | With new: the kinds of piece it judges (film, ad, game, playable, still, sound), comma-separated |
|
||||
| `--per` | `N` | How many moments to take from each render (10 if not given) |
|
||||
| `--profile` | `NAME` | With score: also say which measures fall outside this profile's ranges, where, and which way to move |
|
||||
| `--project` | `P` | The project the label came from, so evidence is held out by project; with move, only that project's labels |
|
||||
| `--sheet` | `out.png` | Also write a contact sheet PNG of the moments it expects a note on |
|
||||
| `--source` | `S` | With move: only labels from this source (note, teach, approval, pair, damage) |
|
||||
| `--span` | `S` | How long the labelled moment lasts, in seconds |
|
||||
| `--tags` | `T,T` | With new: the project tags it judges, comma-separated; a project picks the one matching its kind and tags best |
|
||||
| `--tally` | – | With readings: count your answers so far against the readings asked, and say whether notes have earned training; with postmortem: make your answers evidence and say how each head moved |
|
||||
| `--then` | `T2` | With pair: the moment in BETTER, when it isn't at the same time as --at in WORSE |
|
||||
| `--timeline` | – | Describe the piece second by second in words |
|
||||
| `--to` | `PARENT` | With move: the fingerprint the labels move up to, one this one extends (its nearest by default) |
|
||||
| `--was` | `OLD` | With score: whether each of the earlier cut's gating flags is fixed, still there, or looks disguised (nearer the axis's disguised defects than clean work); exits 1 unless all are fixed |
|
||||
| `--who` | `W` | Whose fingerprint it is, shown on its card |
|
||||
| `--words` | `W` | The label's own words, as the note said them |
|
||||
|
||||
<!-- generated:end -->
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
title: "raea hook"
|
||||
summary: "Every agent's tool hooks: media opened in the Mac's viewer goes to raea show, and the quick check after a composition is saved."
|
||||
order: 50
|
||||
order: 51
|
||||
sources: ["apps/check/src/hook.rs", "apps/tools/src/agent_hooks.rs"]
|
||||
---
|
||||
|
||||
|
||||
@@ -51,7 +51,8 @@ The workspace, its projects and what a project holds.
|
||||
| [`raea project`](project.md) | Make a project in the workspace, list them, or move one between inline and a repository of its own. |
|
||||
| [`raea controller`](controller.md) | Read and change the workspace's controllers: its settings and workflows, each a TypeScript file. |
|
||||
| [`raea spec`](spec.md) | Print a spec file's default export as JSON, checked against its schema: briefs, scripts, taste, plans and controllers. |
|
||||
| [`raea part`](part.md) | Copy a ready-made part into the project's components/, to use and change as your own. |
|
||||
| [`raea component`](component.md) | Copy a ready-made component or set into the project's components/, or the workspace's shared/components/, to use and change as your own. |
|
||||
| [`raea part`](part.md) | The old name of raea component: copy a ready-made component into the project's components/, to use and change as your own. |
|
||||
| [`raea add`](add.md) | Add, remove and install npm packages for a project, with no Node or npm: raea.lock and node_modules. |
|
||||
| [`raea brand`](brand.md) | Read a brand kit from a website on this machine: colours, fonts and logos into brand/ and BRAND.md. |
|
||||
| [`raea library`](library.md) | Search and manage the person's media libraries in the raea app: folders and drives indexed on this machine, searched by meaning. |
|
||||
@@ -64,6 +65,7 @@ What's wrong before anyone watches it.
|
||||
| --- | --- |
|
||||
| [`raea check`](check.md) | Check a composition's text in a second, a project against every rule it holds, or an export against the floor: text, contrast, safe areas, freezes, flashing, cues and loudness. |
|
||||
| [`raea judge`](judge.md) | Judge a 3D scene's review sheets blind, by a model on a frozen rubric or a fresh agent session, with the pass decided in code. |
|
||||
| [`raea fingerprint`](fingerprint.md) | A person's sense of good work, learned on this Mac: axes with small heads over on-device encoders that score a render moment by moment and say what they can't judge yet. |
|
||||
| [`raea findings`](findings.md) | What each render and check found, read back from the project's record: fixed, new and carried since the one before. |
|
||||
| [`raea scene`](scene.md) | Find floating, sunk and clipping 3D parts, say what each part rests on, and meter a shot's light. |
|
||||
| [`raea world`](world.md) | A frame as one world: its layers, text, 3D parts, camera, shots, clips, cues and lines as entities, queried across media. |
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
title: "raea library"
|
||||
summary: "Search and manage the person's media libraries in the raea app: folders and drives indexed on this machine, searched by meaning."
|
||||
order: 30
|
||||
order: 31
|
||||
sources: ["engine/cli/src/library.ts"]
|
||||
---
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
title: "raea next"
|
||||
summary: "The two or three most useful next steps for a project, read from its brief, compositions, renders and checks."
|
||||
order: 48
|
||||
order: 49
|
||||
sources: ["apps/workspace/src/next.rs", "core/facts/src/record.rs"]
|
||||
---
|
||||
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
---
|
||||
title: "raea part"
|
||||
summary: "Copy a ready-made part into the project's components/, to use and change as your own."
|
||||
order: 27
|
||||
summary: "The old name of raea component: copy a ready-made component into the project's components/, to use and change as your own."
|
||||
order: 28
|
||||
sources: ["engine/cli/src/index.ts", "engine/cli/src/registry.gen.ts"]
|
||||
---
|
||||
|
||||
Parts are ready-made components (captions, lower thirds, end cards and the like). `raea part list` shows them;
|
||||
`raea part add` copies one into `components/NAME/`, where it's yours: raea never updates or overwrites it unasked.
|
||||
`raea part` is the old name of [`raea component`](component.md), and still works the same. `raea part list` shows
|
||||
the ready-made components; `raea part add` copies one into `components/NAME/`, where it's yours: raea never updates
|
||||
or overwrites it unasked.
|
||||
|
||||
```sh
|
||||
raea part list
|
||||
@@ -18,7 +19,7 @@ raea part add captions end-card
|
||||
## Usage
|
||||
|
||||
```sh
|
||||
raea part list | raea part add NAME ... [--force] (a ready part copied into components/, yours to change)
|
||||
raea component list | raea component add NAME ... [--shared] [--force] | raea part list | raea part add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; raea part is its old name)
|
||||
```
|
||||
|
||||
Headless: it needs nothing running and opens no window. Takes any number of arguments besides its flags.
|
||||
@@ -28,5 +29,6 @@ Headless: it needs nothing running and opens no window. Takes any number of argu
|
||||
| Flag | Takes | What it does |
|
||||
| --- | --- | --- |
|
||||
| `--force` | – | Replace a part's files that are already in `components/`. Without it, an existing part is left alone and the command stops. |
|
||||
| `--shared` | – | Copy into the workspace's `shared/components/` instead, where every project in the workspace imports it as `/components/NAME`. |
|
||||
|
||||
<!-- generated:end -->
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
title: "raea scene"
|
||||
summary: "Find floating, sunk and clipping 3D parts, say what each part rests on, and meter a shot's light."
|
||||
order: 45
|
||||
order: 46
|
||||
sources: ["runtime/export/src/scene.rs"]
|
||||
---
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
title: "raea solid"
|
||||
summary: "Measure, view and export a solid: parts built from code with exact volumes, joints and parameters."
|
||||
order: 47
|
||||
order: 48
|
||||
sources: ["apps/solid/src/lib.rs", "apps/solid/src/export.rs"]
|
||||
---
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
title: "raea traces"
|
||||
summary: "List the sessions raea apps left, newest first, with how each ended and its glitches, or tell one in full."
|
||||
order: 51
|
||||
order: 52
|
||||
sources: ["engine/cli/src/cli.rs", "io/trace/src"]
|
||||
---
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
title: "raea world"
|
||||
summary: "A frame as one world: its layers, text, 3D parts, camera, shots, clips, cues and lines as entities, queried across media."
|
||||
order: 46
|
||||
order: 47
|
||||
sources: ["apps/direction/src/world.rs", "runtime/world/src/lib.rs", "core/facts/src/components.rs"]
|
||||
---
|
||||
|
||||
|
||||
Loaded 100 of 427 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user