Compare commits

..
Author SHA1 Message Date
shaneandshinyobjectz c2e6e259d1 Skills pin: the skill regenerated from main for 0.1.17's next candidate (raea-skills #166) (#364)
Co-authored-by: shinyobjectz <[email protected]>
2026-12-06 06:13:05 -08:00
shaneandshinyobjectz 7f2585e8ec A goal without the floor pack keeps the render's own safe-area line (#363)
Co-authored-by: shinyobjectz <[email protected]>
2026-12-06 03:57:28 -08:00
shaneandshinyobjectz 8052626f20 Skills pin: no check --taste or --things, no montage pack, no rule_check (raea-skills #163-#165) (#362)
Co-authored-by: shinyobjectz <[email protected]>
2026-12-06 02:48:19 -08:00
shaneandshinyobjectz 6a058856ed The manifest records the colours a line's words are drawn in, and contrast measures each (#361)
Co-authored-by: shinyobjectz <[email protected]>
2026-12-06 02:24:06 -08:00
shaneandshinyobjectz 2c6d51ce66 Check: the montage pack, beats in brief.ts and the stale image critic are gone (#360)
* Check: the montage pack, beats in brief.ts and the stale image critic are gone

- sdk/goal: the montage pack is out (an agent's beats graded against themselves catch no fault); a brief that still names it is skipped, and the doctor says why (GONE_PACKS), never a crash
- guides: a cut's beats are the agent's plan in its notes, never brief.ts; Murch's order stays the editor's
- sdk/cloud/image: the stale overlay goal.ts (a raea ask critic for says rules) is deleted; the Dockerfile never copied it
- goal.feature MK41, MK47-MK51 say what is now true; the fingerprint manual no longer calls things a check

* Fingerprint usage and the brief's packs comment no longer name raea check --things or the montage pack

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-12-06 01:16:22 -08:00
shaneandshinyobjectz 00e1825cd6 Check: run 39 and 40's false errors (#359)
- sound: a cut with a pause between it and the word it names, on either side, is a warning (a sound the transcript missed); a cut between two words the take runs straight on between is a tight cut, a warning; past a dip to quiet, on the next word, it stays an error
- frames: a face at a side edge is cut only when more than 15% of its box is past it (the reader's box margin and a cheek aren't); a box held flush to the frame is cut when narrower than a whole face
- check: a placeholder brand kit is P2, a note for the person, never an error in the cut
- captions: white with a yellow lit word on the plate, never the website's text and accent colours (Dutch's kit is #000 for both, so the manifest said black words, and the contrast check measured black on the black plate)

Co-authored-by: shinyobjectz <[email protected]>
2026-12-05 23:44:55 -08:00
shaneandshinyobjectz f75335d6d1 Check: a cut past a pause after a whole word isn't the word's tail cut (#358)
The sound pack called any sound at a clip edge within 0.6 s of a word that word's tail or first
sound cut, an error. In Dutch run 38 an out point at 8.37 s came 70 ms after "$149." ended: the
take fell to its floor for 50 ms, then a sound the transcript missed started, and the cut took
20 ms of it. The word was whole. A clip edge with 30 ms of quiet between it and the word inside
the clip is now a warning that names what's cut (a breath, a noise or a missed word), with the same
gap to move to. A sound that runs on from the word to the cut is still the word's, an error.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-05 22:05:36 -08:00
shaneandshinyobjectz e6d739b16b Check: a face at the top edge that lost only its forehead isn't cut; place keeps out of the app's UI zones (#357)
frames.ts: a face box touching the top edge is cut only when it's under 0.9 as tall as
wide (a whole face reads 1.4; its eyes sit 40% down). Run 35's Dutch speaker, cut
above the brows at 1.05-1.07 with eyes, mouth and chin in the picture, was an ERROR.

place.ts: its safe margins are the app's UI zones from sdk/video zones.ts, the table the
floor and Region use. Its own 7% top told run 35's Elfster hook to move to top 134 px,
inside the floor's 220 px zone, where it was an ERROR.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-05 21:11:03 -08:00
shaneandshinyobjectz 1d90ea5743 Place: a face the reader doubts doesn't make text over it an error (#356)
frames.ts already holds a cut face under FACE_SURE (0.8) to a warning; place.ts
counted every face the reader gave. Run 34's Dutch caption over a speaker's
coat was an ERROR for a "face" at 0.675 on her gloves, beside her own at
0.947. Doubtful faces now count as the body they're on (a warning).

Co-authored-by: shinyobjectz <[email protected]>
2026-12-05 20:27:12 -08:00
shaneandshinyobjectz 7ef9e7d638 Brief guide: a playable's shape and networks, when the brief names them (#355)
playable() holds a game to both orientations and every network unless
brief.ts narrows it, and the guide never said how. Run 34's playable brief
asked for 9:16 only; the agent kept 9:16 in the aim, and the check called the
missing landscape composition an ERROR. The guide now names orientation and
networks.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-05 20:27:07 -08:00
shaneandshinyobjectz 6e8f16d849 raea check: no --taste or --things in help; --things refused (3D is checked from the manifest) (#354)
* raea help: check no longer lists --taste, which it refuses

raea check --taste is refused by name (a model's opinion is no check), yet
both of check's usage lines still offered it, and the raea skill's CLI
reference copied it from there. The flag ratchet lists --taste and --quick
as refused before any verb reads them.

* raea check --things is gone: 3D parts are checked from the render's manifest

check --things read a shot's things back off its frames (fingerprint things,
from the picture or an --aov depth pass). What raea drew is checked by the
stage and the render's own end checks, from its manifest. The skill told a
3D agent to render --aov and run it after every shot: in today's proof that
took ten minutes and never finished. gone() refuses it with the reason; help,
the manual and the bevy scenes guide drop it.

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-12-05 19:42:58 -08:00
shaneandshinyobjectz 84864ba4e7 Cut's hook keeps off the shot's faces; the caption plate is a colour (#353)
* Cut's hook keeps off the shot's faces; the caption plate is a colour

Run 31: hooks still drew across faces, because agents that skip raea
cut leave no perception.json and <Region> saw no face. Shot exports
facesOn (the take's faces, framed as a speaker shot frames them), and
<Title faces> puts a top title at the top when the room over the
highest face holds it, else under the lowest. <Cut> passes it the faces
of the shots under the hook.

The caption plate drew nothing as var(--brand-caption-plate, rgba(...)):
it's a plain colour now, restyled through Captions' style.

* Title: a dark plate behind the hook, as captions have

* brand.ts: the CTA's text reads on its button (white or black where the kit's is under 4.5:1)

Run 32: Elfster's end card, in its kit's button colours, read 2.5:1.

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-12-05 18:26:52 -08:00
shaneandshinyobjectz d80966354c Poteto audit: 4,478 lines, 34 files, 2 crates and 4 dead checks removed; 4 checks made to run (#351)
* A cloud render's check is proved by a test, and the old verb names are refused in one message or not at all

offload.ts's check step is checkRender(), exported and tested in sdk/cloud/test/units.ts against a stand-in raea: an ERROR in the cut fails the render with exit 1, and a check that can't run fails it with its own exit, never passing it unchecked. engine/cli's tests check the argv offload sends passes regroup() and gone() untouched.

regroup() answers `raea make check|seen|look|judge|gates` with one message naming `raea check`, instead of pointing at goal verbs gone() refuses. The part, next and make-plan arms, the controller tombstone and the craft alias of `raea guide` are deleted, with their tests and the docs that promised `raea part` still answers. The conformance test that ran `raea part add` now runs `raea make component add`, and its guide-name scan no longer accepts `raea craft`.

Poteto audit F01.

* The judge, make's gates and raea ask's verbs are deleted, since gone() already refused every way in

apps/judge, apps/make's gates and asked ledger, apps/ask's verbs, sdk/raea's raea/ask module and its drift test, and `scene faults --ask` (which spawned the refused `raea ask`) are deleted, with their Cargo edges, the lock, the layers entry and scene's now-unused image dependency. lod-plan's gate() and held() go with gates.rs, their only caller. why_refused moves into apps/make, its one reader.

In the CLI, gone() runs before the flag check, so `raea judge x` gets gone()'s reason and not a stray-flag error. Judge and ask leave the help, and a new test checks that no `raea X Y` form the help teaches is one gone() refuses. gone() names `--quick` and `--taste` apart.

core/brief's ROUNDS had no reader left and is deleted; the rounds field's doc says nothing reads it and that it stays so old briefs parse. The critic's comments name its one caller, `raea fingerprint read`. The manual and specs stop teaching the removed verbs and packs (seen, stills, critic, record, notes, and the surprise pack that was already gone), and the brief examples use montage instead.

Poteto audit F02.

* The three-stills quick check is deleted: a render checks its own output, and raea check OUT.mp4 checks it again

apps/check's quick.rs and the floor packs' stillsPack (never registered) are deleted; every helper quick.rs used has another caller. The `check EDIT.tsx --quick` help line and flag row are gone, and gone() still refuses --quick with where it went. Comments that cited the quick check's stills are rewritten, Grok Bot's preface tells the agent a render checks its own output, and the sizes test fixture no longer switches off the stills and seen packs, which no longer exist.

Poteto audit F03.

* Every description of raea's hooks says what they do: raea show for media, and raea check as a turn ends

The README, both plugin descriptions, the hook, index, skill, skills, goal and install pages, the CLI help, skill.rs and agent_hooks' module doc said a hook runs the quick check after a save. They now say what hook.rs does: before a shell command, media opened in the Mac's viewer goes to raea show; as a turn ends (Claude Code and Codex), `raea check --at done` holds the brief's goals; nothing is checked after a save, since a render checks its own output. goal.md's moments table says the edit moment is run by the agent or a person, and the raea/check and raea/brief doc comments no longer say a rule runs on every save.

Poteto audit F05.

* The critique guide holds the craft questions, and the floor says what raea check measures instead of repeating it

rubric.md is merged into verbs/critique.md, which now holds the questions in the same `- id (modes):` lines core/ask parses, the generated-music tells and the P0-P3 table. The model-judged pass, its level mapping and the gate's Passing section are dropped. floor.md's Verify list opens with one line naming what `raea check` measures and keeps only what no check holds. Everything that read rubric.md reads critique.md: core/ask, apps/ask's tests, the guide list and its test, and tools/skills.sh's copies.

The montage guide and pack header say who holds emotion and story (the person, in review), and the bevy NOTICE stops crediting the deleted gates and per-kind critic rubrics.

Poteto audit F06.

* The legacy-names gate catches the removed checks, and the manual renders first and checks the export

tools/legacy-names.sh has entries for `raea ask`, `raea judge`, `raea goal seen|judge|gates`, `check --quick`, the quick check, raea/ask and `raea controller`, each pointing at `raea check`. A word boundary is spelled as the characters around it, because a Mac's git grep -E has no \b and every entry with one matched nothing there. The script skips the check and ask specs, the refusals themselves and the cloud image's sdk-overlay.

The manual's quick-check steps now render, then run `raea check OUT.mp4`: first-video, agents (its step 4 is gone and the rest renumbered), rendering, check and findings. The specs that named the quick check, `raea judge` or `raea part` are updated, and the `says` field's doc says nothing checks it and to hold it with a `run` or `file` rule.

Poteto audit F04.

* The farm's volume gate is a module of its own, and its test exercises the real class

The Gate class moved out of farm.py's api() into deploy/modal/farm_gate.py, with the volume and the log as constructor arguments; nothing else in its body changed. farm.py builds farm_gate.Gate(vol), ships farm_gate with its other Python sources and drops the contextlib import only the Gate used. The moved comments say why the gate exists without dates or customer names.

test/farm_gate.py imports the module instead of slicing farm.py's source. Its stand-in volume records how many requests are inside the volume at every reload's start and end (always 0), and each request records whether a reload was running. The first case counts reloads and late entries rather than timing them, and a new case covers a refused reload tried again while requests are held back.

Poteto audit F14.

* The farm planner handles a run's answer, its budget check and its ending in one place each

spread() and hedged() each had a full copy of the code that takes a run's answer: log an exception, bill the run, send a failed or 3D run back for a GPU, keep it in got and log the result. That is now one helper, _landed(), which returns the run's code (1 for an exception), or None when the call goes back for a GPU. spread() keeps its map of calls still out, because a starmap exception doesn't say which call raised it; hedged() appends the call it already holds.

raea_render() and blender() each had their own max_usd check and their own join-or-keep ending; those are now over_budget() and finish(). blender()'s usage string sat after its first statement, so it was never the docstring; it is now.

Poteto audit F15.

* Every raea cloud deploy names the raea release it installs; none falls back to a stale default

image/Dockerfile's RAEA_VERSION has no default and its install step stops with --build-arg RAEA_VERSION when it is missing, as fly/Dockerfile already did. compose.yaml requires the variable, fly.toml drops its build arg (the deploy line passes one), the k8s files tag YOUR-RAEA-VERSION, and wrangler.jsonc passes image_vars so its build hits the same guard. raea_cloud.py stops at deploy time when RAEA_VERSION is unset. farm.py's RAEA_FALLBACK and its local parameter are gone: a deploy that can't read raea's newest release stops and asks for RAEA_VERSION. test/smoke.sh takes the release as its argument (or IMAGE for an image already built) instead of package.json's version.

bench/gpus.py defaulted to 0.1.6 and never passed the version into its containers, so every result file recorded 0.1.6 whatever was installed. A local run now stops without RAEA_VERSION, and the image carries it to the containers.

Poteto audit F09.

* The Sprite box scripts and box.sh move are deleted; box.sh list reads raea cloud's list itself

Every agent box is a Fly Machine now, so deploy/sprites/box.sh and setup.sh are deleted, and so is fly/box.sh's move, which copied a Sprite box onto Fly. box.sh list no longer runs the Sprite script: it reads raea cloud's admin list and prints the same lines, through a staff() helper it shares with register. Comments in the box image, start.sh, login.sh, org.sh, tools/linux-box.sh and the server, and the CL16 and rerender specs, no longer name the deleted scripts or move. org.sh and login.sh stay for the Linux test machine, which is still a Sprite.

The client's onSprite and spriteToken stay: raea-platform still passes spriteToken, so they go only after it stops.

Poteto audit F11.

* Deploying the farm again keeps its token, and box.sh up gives every box the farm's current settings

workspace.sh minted a new farm token on every run, which cut off every box that held the old one. It now keeps the token beside the farm's URL in modal-PROFILE.env (mode 600) and reuses it; a workspace deployed before that takes farm.env's token when farm.env points at this workspace's farm. A new token is made only on the first run or with the new workspace.sh rotate.

box.sh up now requires farm.env on every run and rewrites each box's RAEA_CLOUD_GPU_* settings from it, so a farm made again reaches every box, not only new ones. On an existing Machine it runs fly secrets deploy (one restart) only when those settings changed. box.sh key does nothing when the box already has that key, and writes the key to the local settings file only after Fly has taken it, so a failed import exits 1 and is tried again on the next run.

Poteto audit F10.

* Reading a job's files no longer removes the job; the client drops it once the files have arrived

GET /v1/jobs/ID/out removed the job before its answer was sent, so an answer lost on the way lost the render. It is now a plain read on both the farm and the single server, and a new DELETE /v1/jobs/ID removes a finished job (jobs.drop() and main.ts on the server; on the farm, under the volume gate with a commit, its logs popped after). The farm sweeps jobs whose changed.txt is more than an hour old on each POST /v1/jobs, inside the same gate use and commit, matching jobs.ts's KEEP_MS, so a job nobody drops still goes.

The client's jobFiles asks again on any failure but a final 4xx (408 and 429 are asked again), then sends DELETE and ignores the answer, so an older farm's 404 or 405 is harmless. The retry is one helper, again(), which jobMedia and sendMedia use too: the farm answers 503 to both while its volume is busy, and a job could fail after its render had finished. Sending media twice is safe, since each is a signed PUT that leaves the same object.

units.ts covers the server's read-twice-then-drop (with GNU tar) and the client against a stand-in that cuts its first answer off and answers 503 once to each media call. smoke.ts reads a real job's files twice, drops it, and then gets 404. Deploy the farm before the boxes.

Poteto audit F12.

* A box refuses to hand a render to a GPU worker on another raea version

offload.ts now asks the worker's health before it packs the project or sends any media, and compares the worker's raea with the box's own raea --version through a new otherRaea(). On a mismatch the render fails at once, naming both versions and the two ways out: deploy the farm with the box's RAEA_VERSION, or set RAEA_CLOUD_GPU_ANY_VERSION=1. A worker still reporting 'reading' or 'unknown' is let through. Before, a farm on a full release drew an rc box's compositions with another engine.

An rc box needs the farm deployed on the same rc, or the override, once boxes take an image with this.

Poteto audit F13.

* CI runs sdk/cloud's local tests on every pull request

sdk/cloud/package.json has a test script: units.ts, memguard.ts, unused-media.ts and farm-blobs.ts on node, then farm_plan.py, farm_media.py and farm_gate.py on python3, stopping at the first failure. ci.yml has a cloud job on ubuntu-24.04 (10 minutes): Node 24, the box image's, and ffmpeg from apt, since farm_plan's stand-in GPUs encode with libx264 and aac, then npm ci and npm test in sdk/cloud. The README's Test it section says what npm test covers.

Poteto audit F16.

* Kept buffers and shapes stay under 4 GB: the least recently used go, never one used in the last two hours

buffers/ (a BufferMesh's kept text) and shapes/ (kept solids' meshes) were never pruned, and an animated BufferMesh adds about 10 MB a frame. Each process's first write into either folder now removes its least recently used files while it holds more than 4 GB, stopping at the first file read or written in the last two hours. Every read touches its file, so a buffer a running scene names stays.

A test sets old file times and checks the order, the budget and the two-hour floor.

Poteto audit F51.

* A render's flags are carried by that render, so two renders in one process each keep their own

raea render's flags (--keys, --manifest, --stage, --10bit, --aov, --alpha, --kbps, --quality and the composition's --props/--scale/--hold) went through ten process globals, and what the end checks saw went through another. They are now one RenderArgs, read once in render() and owned by the render's Ctx; the end checks' seen parts are returned with their findings and written by write_manifest. render_bundle keeps its signature for the iPhone and render --bundle, as a wrapper over render_bundle_as. program, program_of and scene_program_checked take alpha. Live play's 3D no longer reads --aov: one live_frame helper in bevy_frame.rs turns it on for a render's game frames.

The same leak, in the same places:
- --clay is set for each render, so one with --clay no longer leaves every later render in the process clay.
- The bundled JS of render, review and world reads is named by process and thread, as the work folder is, so renders on two threads don't write and delete one file.
- The composition's folder is one global (ASSET_DIR), not two kept in sync: ml.rs's own copy is gone, and composition_dir answers in every build, so baked play and builds without ml find /media/ and the physics and contact files.

BEVY_3D_PROBE, LIVE_CLIPS and FED_CLIPPING stay globals.

Poteto audit F48.

* styles.gen is compiled into each bundle's own work folder, never written beside the edit

Every render wrote styles.gen.ts into the edit's folder when it looked older than the code, so renders of one folder side by side (a farm's parts on one volume) truncated the file under each other, and bundles in one process waited on one mutex for the process's one work folder. Each bundle_fresh now has its own work folder (raea-cli-b{pid}-{n}), and styles::module(dir) only reads the edit's folder and returns the module, which is written into the bundle's copy. A project's styles.gen.ts (the template's, pong's and seedling's) is now a declaration for the type-checker. The bundle cache's temp file is named per thread.

release-check proves the compile by the styled render drawing and nothing being written beside the edit. The guides and the P26 stub follow. A new test bundles eight folders on eight threads and finds only each one's own class in its bundle.

The same write-then-move rule, beside it: a baked solid's .obj is written to a .part file and renamed (a second thread could read half of it), and the bake cache's temp file is named per thread.

tools/dupes.max: one group moves from exact to near (292/58, the same 350 groups). The deleted file-time closure was half of an exact pair; the other half now matches by shape only.

The farm probe's vol.commit() in sdk/cloud/deploy/modal/farm.py stays until a farm render of 14 or more parts passes without it.

Poteto audit F49.

* RAEA_FRAME_LOG writes the four columns it measures: frame, react, sync and gpu

The frame log went through a process global and wrote four columns that have always been 0 since the bevy_ui page (draw3d, gpu3d, page, gpupage), with sync computed as the snapshot's time less those zeros. render_fed now keeps the rows in a local Vec and writes frame, react, sync and gpu. The readers follow: bench/rerender's bench.sh and ios/bench.sh read gpu from the fourth column, and sdk/cloud's gpus.py names three value columns. bench.ps1 reads by header name and fog-score.py sums every value column, so both were already right.

Poteto audit F50.

* Every bench script that scores two frames by SSIM sources one comparator, bench/lib/compare.sh

Twenty-six copies of the ffmpeg SSIM pipeline in 23 sh, bash and zsh scripts become calls to one POSIX-sh function, ssim A B [FILTER_A [FILTER_B]]: both sides read as 8-bit RGB with an optional crop each, the six-decimal All value printed, nothing when the frames can't be compared. Eleven local ssim() definitions are deleted. encode/check.sh's metric() keeps only its PSNR half. The header records what the number can and can't see. Left as they were: rr3.sh's per-frame stats from two MP4s, media-vs-ffmpeg.sh's four YUV video-to-video sites (moving them to RGB would move their numbers), and the three Python scorers.

The function gives the same value to six decimals as every old variant on 49 PNG pairs, sourced from sh, bash and zsh. Converted scripts run against their HEAD copies with the same raea give the same verdicts and numbers.

Poteto audit F21.

* P26 fails a frame under SSIM 0.999, between what a run repeats at and a one-frame slip

The bar was 0.98, which passed a frame drawn one frame late (0.986 in stage-guards SG0, 0.9985 on a slow 60 fps film). 0.999 sits above both and below the run-to-run floor (0.99998) and an incremental build's rounding (0.99997). The header says why, notes that a few-pixel fault such as SG0's cut glyph (0.9996) needs a pixel measure rather than a higher bar, names L2 instead of a CI gate that doesn't exist, and says a row that differs for a good reason is taken again with recapture.sh, which writes the reason into its row. capture.sh's header gives the same bar.

Against a stand-in raea serving real frames: frame N+1 scored against frame N's baseline (0.9985-0.9987) passed before and fails now, and still passes with MIN=0.98.

Poteto audit F19.

* bevy-parity times Bevy's example and raea's port with one estimator, the probe's steady median

The Bevy side took the last line at frame f, whose frame_ms was the mean since the line before and so held the load or a screenshot's readback, while the raea side took its own jq median after the first five. Both now read the probe's frame_ms (systems/parity), which records every update's time and reports the median after the App's first five updates. tools/bevy-parity's raea side reads the last line as the Bevy side does, and the report says how the time is measured. docs/bevy-parity.md keeps its old numbers until the next run rewrites it.

steady_median, compiled alone, keeps a load and a readback stall out, moves 4.0 to 6.0 ms when 2 ms is added to every update, and equals jq's median over .[5:]. With stand-in binaries a raea at 6 ms against an example at 4 ms turns the time column to false and the row to no.

Poteto audit F20.

* L2 runs every bench check, not a hand list of five

bench/l2-checks.txt named 5 checks; about 50 others were run by nothing. L2 now runs every tracked bench/**/check.sh and sdk/**/check.sh, plus tools/settle-nudge.sh and tools/frame-pure-3d.sh (60 on this tree), less what bench/l2-skip.txt names with a reason (none yet). Checks that run the plugin build go after that build; when it isn't made they are reported as not run and still count in the total. Each check runs in its own process group with L2_CHECK_SECONDS (default 1800): past it, the group is killed and the check is a miss, and anything a check leaves running is killed when it ends. "bench checks: ok/N" prints after the plugin step.

Four sdk/react checks (ml, speech, timelines, tone) looked for raea in sdk/react/target, which no longer exists; they now take RAEA_BIN, and settle-nudge reads it too, so L2 tests the candidate's raea. speech.md and stage-guards SG17 follow.

The bench block, run alone against stub checks: nested paths selected, a skip line honoured, the plugin check deferred, a hanging check stopped at its budget with its child gone, a passing check's leftover child killed, RAEA_BIN passed through. The next release candidate's L2 is the first full run; budget one round of triage for checks nobody has run since they landed.

Poteto audit F17.

* CI tests every crate that needs no GPU, listed from the lock file instead of by hand

The unit-test step named about 15 crates, so a new crate's tests ran only if someone added it, and runtime/live's stage_guards.rs never ran. The crate list now comes from cargo metadata and cargo tree: every workspace crate that links neither wgpu nor Rolldown (98 on macOS), less raea-sys-mlx (its tests need MLX's Metal device, which hosted runners lack), plus the six wgpu-linked crates whose tests need no GPU, now including raea-runtime-live. raea-bundle keeps its own call for Rolldown's feature unification. jsengine and io-assets leave the feature step, since the main step runs them, and ffmpeg is installed on both OSes for app-double's and app-ask's tests. All of wgpu's side can't join: its test binaries would fill the runner's disk (#90).

Locally the selection gives the same 98 crates as an independent cargo-metadata count, and cargo test on 96 of them passes 521 tests (17 ignored).

Poteto audit F18.

* The README stops claiming renders run faster than they play, and bench/speed measures it

bench/speed/run.sh renders each L2 composition whole to an MP4, one warm-up then RUNS=5 timed runs with the export cache off, and prints two speeds in seconds of video per wall second with their median and range: the frames alone (the render's own frame and encode time) and the whole command, spawn to exit. Measured here: 57 of 58 compositions make their frames faster than they play (median about 4x, 2.2x to 35x), bevy/volume-light at 0.51x, but the whole render is slower than playback for 43 of 58, held back by the 3.2 to 10 s spent outside the frames (bundle, page start, sound, end checks, signing). So the tagline now ends at "rendered on your own GPU". The script is a measurement, not a check: it is named run.sh so L2's check glob leaves it out, and one pass takes over an hour.

Poteto audit F22.

* raea-sys-foliage is removed until a verb, native call or SDK module calls it

systems/foliage (1,904 lines) had no Cargo dependent and no code caller: nothing in raea could grow a plant with it. The crate, its workspace member, its lock entry and its two tools/layers.toml entries go. docs/foliage.feature says how it comes back with FO10's caller (git checkout 02051ee9 -- systems/foliage). Its hash_str was the exact twin of tone's tonegraph hash, which now matches rune's fnv by shape only, so tools/dupes.max moves one group from exact to near (291/59, the same 350 groups).

tools/layers.sh, tools/dupes.sh and tools/size.sh pass; git grep finds no raea_sys_foliage. cargo build --workspace is CI's.

Poteto audit F23.

* Comments say what a crate or file holds, not that it was split out to stay under the size limit

Eleven clauses told the history of a split ("split out to keep this crate small", "split from lib.rs, which is at its 500-line limit", "split out at the crate limit", a dated "Split out of raea-sys-weathering"), which tools/size.sh already enforces and a reader doesn't need. They go from apps/check's Cargo.toml and flash crate, the goal CLI's module doc, runtime/look's cuts.rs, systems/frame's Cargo.toml, systems/atlas, and tools/skills-app.sh and skills-sections.sh. runtime/live's three test headers keep theirs: they say why the tests live there, which F56's move settles.

Poteto audit F38.

* tools/ensure.sh's install lock is freed with its holder, however the holder ends

The lock was a directory removed by an EXIT trap, so an install killed with -9 (or a crash) left it behind and every later install waited 10 minutes and then failed, asking a person to remove it. lock() now takes flock(2) on a file held open by the installing shell: the kernel drops it when that shell ends, however it ends. The wait is a blocking flock with a 10-minute alarm, not a poll. uv's install also clears a half-made uv.part first, as git's did.

With lock() taken from the file: after a holder is killed with -9, the next lock is taken in 0.02 s (HEAD's lock waits until its 10-minute limit); behind a live holder of 2 s, the next waits 2.01 s and then takes it.

Poteto audit F45.

* tools/size.sh leaves a crate's tests/ and benches/ out of its line cap, and bundle's key test goes home

A crate's integration tests and benches aren't built into it, but they counted toward its 2,000-line cap, so tests about one crate were parked in another that had room: runtime/bake held raea-runtime-bundle's cache-key test "tested here: that crate is at its size limit". size.sh now counts a crate's own .rs without its tests/ and benches/ (FILE_MAX still holds for each file), and the test moves to runtime/bundle/tests/bundle_key.rs unchanged. A 450-line file in runtime/react/tests/ fails HEAD's size.sh (2449 lines) and passes this one.

runtime/bake/tests/reads.rs (runtime/react's) and runtime/live's three tests (runtime/scene's) move after the runtime/kinds-into-scene merge, on a fresh count. CI builds the moved test (raea-runtime-bundle is bevy-bound).

Poteto audit F56 (part).

* <BlenderShot> needs a script or a .blend and <GodotShot> a script or a scene, by type

Both props had every field optional, so <BlenderShot /> type-checked and failed only when rendered. BlenderShotProps is now the options plus a union that requires script or file (or both), and GodotShotProps the same for script or scene. The runtime throw stays for untyped callers. sdk/blender/test/shot-props.ts and sdk/godot/test/shot-props.ts hold the type tests: each accepted form passes tsc, and a shot naming neither fails it (with HEAD's props the @ts-expect-error goes unused and tsc fails).

Poteto audit F35.

* raea gen's spending verbs refuse a flag they don't take and a cap that doesn't read

`--max-cents 2.50` didn't parse and silently fell back to the 100-cent cap, and a misspelt `--no-tripo` was ignored, so Tripo stayed allowed: both let a run spend past what was asked. run, plan and image|video|music|sfx|speech|mesh|text now check their flags against one table each (RUN_FLAGS, MAKE_FLAGS) before reading a flow, refusing an unknown flag or a flag missing its value, and --max-cents must be whole cents. Every flag the usage names for these verbs, and every one the repo's docs and guides pass, is in the tables.

cargo test -p raea-io-gen: 30 pass, including tests_flags (a dollar cap refused, three misspellings refused, every listed flag taken). HEAD's cli.rs fails two of the three.

Poteto audit F32.

* raea gen's flag tests run as an integration test, so the crate stays under its line cap

tests_flags.rs only calls the public cli::command, so it moves to io/gen/tests/flags.rs, which tools/size.sh doesn't count. With it in src/ raea-io-gen was 2019 lines, over the 2000 cap.

Poteto audit F32, F56.

* The legacy-names gate leaves raea-skills' upstream snapshot alone

upstream/raea/ is what a released raea printed, written by just sync-raea and never by hand, so the names a later raea removes stay in it until the next sync. The gate failed on it once it learned the removed checks.

Poteto audit F04.

* The platforms' text zones are written out in the placement guide, held there to the check's numbers

F06 cut the zone numbers from floor.md, since raea check measures them, which broke apps/check's test that held floor.md to zones(). The numbers now live in motion/placement.md, the guide that places text, and the test holds that file to every zone (9:16 unknown, TikTok, Reels, Shorts, 4:5, 1:1, 16:9). floor.md points at it, and zones() and sdk/video's table name it as their prose.

Poteto audit F06.

* CI's crate tests run to the end, so one run names every crate that fails

Without --no-fail-fast the run stopped at the first failing test binary, so a second failure only showed in the next run.

Poteto audit F18.

* Review fixes: clay held per render, the shape prune takes only its own files, every styles.gen import spelling

- --clay: a count of running clay renders (ClayRender) instead of a flag
  each render resets, so a colour render starting beside a clay one no
  longer turns it colour, and nothing stays clay after.
- The shape cache's prune takes only names it writes (.tris, 32-hex
  .json, their .part), never other files in a RAEA_SHAPE_CACHE folder.
- styles.gen is found however its import is spelt (either quote, .ts or
  .js), so no bundle goes without its CSS.
- The farm's sweep renames finished jobs aside under the volume gate and
  removes them after, so a download isn't held past Modal's 150 s.
- RAEA_CLOUD_GPU_FALLBACK=cpu renders here on a raea version mismatch too.
- GUIDE_NOTE no longer names the removed part verb; farm.py's probe
  commit comment says why it stays (rc4 still writes styles.gen.ts).

* skills: raea-skills main (#162: the poteto audit's skills changes)

* tools/rask: a crate's size leaves out its tests/ and benches/ (rask #1)

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-12-05 18:09:35 -08:00
shaneandshinyobjectz a9dd01b07c skills: raea-skills main (#161: no music where none can be made, the plugin directory's edition rebuilt and checked) (#352)
Co-authored-by: shinyobjectz <[email protected]>
2026-12-05 16:22:24 -08:00
shaneandshinyobjectz 364b06c094 Captions on a dark plate; a cut's take edges moved off words (#350)
* Captions on a dark plate, and a cut's take edges moved off words

raea's <Captions> draws each line on a 60% black plate (the brand's
--brand-caption-plate restyles it): a shadow alone darkened only the
letters' edges, and street cuts read 2.4-2.9:1 over bright walls.

Cut's saidOf moves each heard take's edges off any word they cut, in
place, so spans() and <Cut> see the same edges: a span typed from a
plan's in and out points landed inside words on six of six cuts.

* raea words: the aligner reads a minute at a time, and keeps only a word's time

Qwen3-ForcedAligner over a whole 10-minute piece drifted: a take came
back with "what's" from 1.8 s to 93 s, its words still matched by their
letters, and every cut from its first minutes went uncaptioned. Each
piece is now aligned in windows of at most 60 s cut in a pause, and an
aligned time is kept only where it's a word's length (2.5 s at most)
and within 1 s of where Parakeet heard it. Deployed (raea-words).

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-12-05 16:22:19 -08:00
shaneandshinyobjectz 768fb4fdc6 A render's manifest says has3d only when a frame drew 3D (#349)
has3d was true for every game, because a game's live scene exists from the start;
its engine opens only at the first frame with any 3D. A 2D playable was then
given 3D light's exposure advice on every frame ("8.6% of the pixels clip to
white" on its white type and brand yellow), which render's own rule keeps off
frames of the page's own fill when has3d is false.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-05 16:07:28 -08:00
shaneandshinyobjectz c7c8bdf655 Music guide: no music where none can be made, never one written by hand (#348)
A playable agent on raea cloud had no generate tool, raea gen music was refused
for a key, and it synthesized a bed in Python: a second way to make music. With
no way to make one, the piece has none and the report says so.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-05 16:07:24 -08:00
shaneandshinyobjectz 80b2138677 raea cloud's box on a Mac renders on its GPU, and says so (#347)
The desktop's local box runs raea cloud's box server on the Mac, where wgpu
reaches the GPU through Metal and no Vulkan loader lists it: the box said it
"renders on the CPU (llvmpipe)" on an M5 Pro. On a Mac it names the chip.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-05 16:07:18 -08:00
shaneandshinyobjectz 3e929cfee8 raea check: run-28 and local 3D noise fixes (doubtful face, line level, untold blotching) (#344)
* raea check: a doubtful face as tall as the faces beside it is still a face

#343 made a cut face the reader is under 80% sure of a warning, for Elfster's
hand at the edge. Body Shop's interviewer, cut by the frame's edge, read 0.74 and
0.61 too, and was demoted with it. The hand was 0.64 of the height of the faces
beside it, the interviewer 0.98: a doubtful face is now a warning only when it is
also under 0.75 of the other faces' height (or there's no other face).

* raea check: a line's level is read where it's said, not where its transcript put it

The levels check measured a line inside its words. Elfster's "Santa gift you've
ever gotten?" was timed 0.8 s late by its transcriber, in the silence after it,
and read -28 dB where the speech ran at -10: a line the mix had evened was called
19 dB under the others (12-05, run 28). A line's level is now the louder of its
in-words level and its whole clip's; a short word in a quiet clip keeps its own.

* raea check: blotching whose cause can't be told is an error only past an encoder's

A 3D shot rendered at master quality read 0.010 (BLOTCHY is 0.009) from its
shadows' own dithered edge, outside a raea project where the cause can't be
told, and was an error whose fix (master quality) it already had. VideoToolbox's
patches measured 0.012-0.014: under 0.012, an untold cause is a warning.

* raea check: no face, place or caption reading on a render that has no footage or sound

A local 3D shot's render check waited on a scene reader for faces and on a
transcript of a file with no audio track: the footage cut's rules, on a shot raea
drew whole. Its manifest says what it holds: with no video on any frame, frames
and place have nothing to read; with no sound clip, captions has nothing said.

* raea check: a file with no sound track says nothing

A silent shot's say, never and CTA rules waited on a transcript raea words
refused to make (no audio track). A file whose probe shows no sound track has
no words, so the brief's lines are read off the screen alone.

* raea check: a playable's missing orientation says what the brief's one shape means

A playable brief asking for 9:16 left orientation unset in brief.ts, the check
asked for a landscape composition, and the agent built a letterboxed stand-in.
The fix now says: one shape in the brief is its orientation, written in
brief.ts, never a stand-in of the other shape.

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-12-05 16:07:12 -08:00
shane 4b4ef8e57d skills: raea-skills #160 (#346)
Moves the skills pointer to raea-skills #160.
2026-12-05 14:14:58 -08:00
shane be812fc7ba Guides: one way to make music (a raea gen music bed), and framing without framing="face" (#345)
A piece's music is one instrumental bed from raea gen music (the same model as raea cloud's generate tool), ducked under the voice, its level set by what raea check says; Tone.js stays for a game's one-shots and the buses. The footage guide frames through FaceFrame, or Framed.tsx from footage/faces.json on raea cloud.
2026-12-05 13:59:30 -08:00
shane 2f1e10076a raea cut on boxes: jump cuts through ffmpeg, faces from footage/faces.json, a squeezed phrase dropped (#342)
Jump cuts read through the ffmpeg CLI (6-8 s per take on a box against 38-66 s); each clip's face for perception.json read from footage/faces.json, which prep makes; and a phrase the transcriber squeezed into one instant dropped from a take's words, so a line is found where it was said (Body Shop's CTA started inside "up").
2026-12-05 13:47:24 -08:00
shaneandshinyobjectz 1d51c09c0b raea check: four kinds of run 28's ERRORs that weren't faults (#343)
Each judged on the frame or the sound (12-05, proof run 28: Dutch, Elfster and
Body Shop through Brief-to-Video).

- frames: a face cut by the edge is an error only when the reader is at least
  80% sure, over its run, that it's a face. Elfster's "face cut by the left
  edge" was a hand at 0.79 then 0.65; the people in the shot read 0.92 and
  over. Below that it's a warning that says how sure the reader is.
- captions: a word said on an end card the render drew counts as captioned.
  captionsOf takes a frame full of text for a card, not captions, so the CTA
  read out over its own end card was "4.2 s of talking with no caption". Only
  the manifest's own texts count, never the footage's.
- place: a caption is over "words in the shot" only when it hides 30% of
  them or more. Over a sign's top edge, its words all read, it's a warning
  ("the edge of a sign"): Dutch's "Would" and "this.".
- contrast: the ratio to two places, rounded down, so 2.96 no longer reads
  "3.0:1 ... make it at least 3:1".

Co-authored-by: shinyobjectz <[email protected]>
2026-12-05 13:11:11 -08:00
shaneandshinyobjectz 02617df030 raea cloud: a named card reaches the farm, a job can ask for NVENC and NVDEC, and the CPU fallback's record is kept (#341)
offload passed RAEA_CLOUD_GPU_KIND as "gpu", which the client never read: it's the farm's card now. RAEA_CLOUD_NV=1|0
(Farm.nv, /v1/jobs nv=) turns NVIDIA's encoder and decoder on or off for a job, so a cut can be timed each way (on keeps
it on GPUs). local() counted a list's .size, so a CPU render never recorded its light copies; and farmInputs' type says
links.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-05 12:42:03 -08:00
shaneandshinyobjectz 12ad441266 Boxes edit on light copies; the farm renders from originals it fetches itself (#340)
* Boxes edit on light copies; the farm renders from originals it fetches from the library itself

A farm render now reads each light copy as its full-size original, resolved as it's sent (server/originals.ts):
by its link in .raea-cloud/originals.json, which the farm fetches from the library, checks by hash and keeps in
its cache; else by the original's file under footage/originals/, sent by its own hash. Nothing on the box ever
takes a light copy's place, and the box never downloads, hashes or sends a 4K original.

A light copy with neither is rendered as itself, printed as NO ORIGINAL, and recorded in the render's manifest
(originals.read / originals.light), so raea cloud never shows what was made from it.

footage/originals/ and the kept light copies (.raea-cloud/proxies/) no longer go in a render's tar: run 24's
Dutch box packed 179 MB of kept light copies into every render.

The farm takes an original of unknown size (0) when it comes with its link, checked by hash alone.

docs/cloud.feature CL17-CL20; test/originals.ts, test/farm_media.py.

* The farm's media list keeps each original by its link on every path; every render records what it read

Review of #340: on the default path (a farm with a media cache) offload set the list to what went into the cache
and dropped the originals' links, so the farm would have rendered the 540p light copies while the manifest said the
originals were read. The list is now decided once, after every path (withOriginals), and what a farm can't take
(an original by its file without the cache, one of unknown size on an older farm) is recorded light (settle).

The record goes into the manifest for every render, checked or not, and beside a still that has none. footage/
originals/ is no longer excluded outright: an original no source names already stays, and one a composition names
still goes. The by-name fallback matches only a light copy straight in footage/. An original of unknown size is
refused past 40 GB as it downloads.

* Originals by link: the farm says what it takes; a render's record holds only what it read

Second review of #340. /v1/blobs/have answers links: 1 when the farm fetches an original of unknown size, and settle
goes by that, not by the farm having a cache. The record goes into the --manifest and beside the output, narrowed to
the sources the manifest names; a clean render clears an old one; one that can't be written is said aloud. A CPU
render (no farm, or RAEA_CLOUD_GPU_FALLBACK=cpu) records every light copy as light and says NO ORIGINAL.
footage/originals/ stays out even when no source names any media. Farm temp files get a random suffix (PIDs repeat
across containers), and the size line counts what's fetched by link apart.

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-12-05 12:07:34 -08:00
shaneandshinyobjectz 8e7c5a13e7 raea cloud checks every render, the check stops reading reframes as edits, and farm renders frame people again (#339)
* raea cloud checks every render again: offload calls raea goal check, and a check that can't run fails the render

offload.ts ran the render's check as `raea make check`, which the CLI refuses (exit 2: make is the asset tools since
the goal/make split), and acted only on exit 1, so no cloud render had been checked: the agent saw a refusal line and
went on. It now calls `raea goal check OUT --at render`; exit 1 fails the render as before, and any other exit fails it
saying the check couldn't run. tools/legacy-names.sh now catches the old verb spawned as an argument list too.

* The check stops reading a reframe as an edit, and farm renders frame each person again

A take that plays straight on across two clips (a composition splits a clip when it reframes a shot mid-way) was read
by the sound rule as an edit point, so a word was "cut in two" where nothing was cut. sound.ts joins those clips first
(same source and level, touching in the cut and in the take, no fade between).

The farm linked each take sent by hash to its cache blob, named by its object id. A bundler follows the link, so a
composition that knows its takes by name (Framed's faces.json) found only a hash and framed every shot centred: faces
at the frame's edge in every farm-rendered cut. The link now ends at cache/named/OID/NAME, a hard link to the blob, and
the box maps that path back to the project's take as it did the blob's.

Tests: sdk/goal (72), test/farm_media.py (the link ends at the take's own name; fails on the old code), units.ts's
localSources case (units.ts's keep-alive case fails on main already).

* Captions keep a crisp dark edge under their soft shadow, so they read over white product shots and sky

A soft 24 px shadow alone left white and accent words at 2.2:1 over a white product screenshot (the check's contrast
rule wants 3:1). A 2 px and a 6 px dark edge go under it.

* The exposure check calls a pixel clipped white only when every channel is at the top

A flat 2D playable (pale sand, a yellow sun) was reported as 66% clipped to white: a pixel counted as clipped when its
brightest channel reached 254, so every saturated or pale colour did. White is all three channels at the top.

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-12-05 11:08:29 -08:00
shaneandshinyobjectz a380418ed5 Cuts timed by their sound and composed whole: paced raea cut, components/Cut.tsx, CTA takes, captions never dropped (#338)
* Cuts timed by their sound and composed whole: raea cut paces each clip, components/Cut.tsx lays a cut out

raea cut (engine/cli/src/pace.ts, cutplan.ts): each line cut in the quiet around its sound with a breath kept, long
pauses cut down (shorter in the hook), fillers and false starts with quiet both sides taken out, a line that stops
mid-sentence run on to its sentence's end (three words or fewer), a tight join at the quietest 10 ms and never inside
the transcript's own words (what the check reads), a run under 0.8 s of speech joined to its neighbour instead of
flicking by, each clip's gainDb evening the voices (measured on a second of speech or more, within 9 dB, a short clip
taking its own take's gain), and a jump cut marked for punchIn(i). It reads a take's light copy when raea cloud keeps
one. Tests: engine/cli/conformance/pace.test.ts.

The box image's components (sdk/cloud/image): Cut.tsx composes a cut from its moments (speaker, two, product, broll,
screen, wide, end) with Shot.tsx, crop.ts, Said.tsx, EndCard.tsx and brand.ts, beside Framed.tsx and Title.tsx and
faces.py (YuNet, MIT). Framed never swings to another person when the framed one goes undetected for a moment; a
split needs both people in 85% of its span; Title drops to the centre band when the top can't hold it above the
face; the end card's offer never shrinks under 56 px.

The check and captions: the CTA rule names the takes whose words say the brief's CTA, so the fix is one raea cut
away; <Captions> falls back to the bottom of the safe area when its band is refused, so no word goes uncaptioned;
Region's bands stop 1.2% short of the app's top and bottom zones, so descenders and shadows stay out of them.

Box: a Claude sign-in finds Claude Code in ~/.local/bin.

* Music goes under a cut through Cut's bed, at the level the check wants

A bed typed at volume 0.07 sat 28 dB under the voices once mastered and the check heard no music. Cut takes bed and
lays it at BED_DB (about 16 dB under the voices after <Mix>, inside the check's 12-20 dB) with short fades; the
instructions send music there and never to a typed volume.

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-12-05 10:11:15 -08:00
shaneandshinyobjectz 6e35267060 skills: one check (raea check is the only check in the raea skill) (#337)
Co-authored-by: shinyobjectz <[email protected]>
2026-12-05 09:40:02 -08:00
shaneandshinyobjectz 05f82ef572 raea cloud: a library proxy says it is one in its comment tag (#336)
Every 540p proxy proxy.py makes carries comment=raea-light-copy, and ffmpeg keeps the tag in what's made from it. raea
cloud's box reads it before a render is published or shown, so a file made from a proxy, wherever an agent put it, is
never handed to a person as a final. Proxies already kept by hash keep no tag until they're made again.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-05 09:39:58 -08:00
shaneandshinyobjectz 563f49a978 One check: raea check is the only way any agent's work is checked (#335)
* One check: raea check is the only way any agent's work is checked

docs/check.feature (CK0-CK6). Every rule lives in one of three places: a check, a component or the SDK,
or a skill or retrievable context; a rule that fits none is dropped.

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

* raea cut keeps a take's jump cuts: the second cut on a take doesn't decode it again

raea media cuts decodes every frame of a take (43 s for a 4-minute take on a box), and every raea cut ran it again,
so three cut lists on one take in a step ran past a box step's 3 minutes and the run stopped with nothing made.
The cuts are kept in raea's cache by the take's path, size and time: a second cut on the take took 0.5 s.

* The reading check reads the render's own texts from its manifest (Unrender J2)

What raea drew is checked from the render manifest, never by reading frames (docs/check.feature): the reading pack
takes each text's ink box from the manifest at the captions pack's step, a multi-line card sized by one line, and
reads the export's frames only when no manifest is beside it.

* raea/goal typechecks: a dead helper gone, shapeOf takes FileFacts' sizes, the montage test's beats are CutBeats

* raea goal check takes check's flags again: the old name runs, as CK0 says

The help lists check's flags under check alone, so a verb's flags read from it refused `raea goal check OUT --at
render` (raea cloud's render tool) for --at. goal check's arguments are now checked as check's.

* Farm: a volume reload goes next, shared and limited, so a busy farm never loses a finished render

With a dozen cuts in flight, blob uploads and other requests kept the farm API's volume in use without a break. A reload waited for none of them to be in it, and GET out sat behind it past Modal's 150 s web limit (408), losing a finished cut. Now a waiting reload holds new users back, a reload that starts after a request asked serves it too, and the wait is held to 100 s and answered with a 503 the box asks again on. test/farm_gate.py runs the class from farm.py: the old gate never reloads behind a stream of users; this one does in 0.16 s.

* Floor: blocky darks are an error only when the encode is measured to have added them

12-04, one-check proof: Body Shop's cut (17 Mbps) got an ERROR for blocky dark patches that its frame doesn't show at full size; the check couldn't tell the encode from the footage's own compression. Untraced, it's now a warning; the picture's own, no line.

* CTA and must-say read a frame's texts together

12-04, Elfster run 4: the end card drew the CTA as two texts ("Make your Wishlist and organize your Gift Exchange on Elfster." over "It's free."), each alone under the CTA's 85% share, and a cut ending on its CTA was failed for having none. A frame's texts are now read together, in the order drawn.

* Sound: a word timed longer than 2.5 s is a transcriber's slip, not a word cut in two

12-04, Elfster run 5: "secret" was timed 143.28-166.96 s, and a clip starting 15 s into it got an ERROR for cutting the word.

* One line a rule a file across levels, and no lines.txt note

12-05, run 5: a cut's ERROR and WARN from the same check each took a line, and Dutch's cuts listed 11-12 lines. The worst finding of a rule now leads its one line and the rest are counted under it. The "no lines.txt beside it" note is gone: a hint, not a fault in the cut.

* Farm: a composition's bundle cached on each container's own disk

12-05, run 6: a job's 32 CPU parts missed the shared bundle cache on the volume at once, each wrote the same file and committed it, and parts that read it mid-commit got zeros ("bundle.js: String contained internal null bytes"). Up to 23 of a cut's 32 parts went back to the 10 GPUs, and other jobs' frame-0 probes waited behind them.

* Words: Hear on up to 4 GPUs and Align on 3

12-05, run 8: three projects' transcriptions, 8 at a time each, queued on 2 of each class. Elfster's 51 takes took 6.5 minutes and its wait for them ran past the fetch step's 4. Seven of the account's 10 GPUs at a run's start leave 3 for the cuts' first frames; the cuts themselves draw on CPUs.

* Check: quotes cut by whole characters, and numbers said in words match digits

12-05, Dutch run 9: a caption quoted to 40 UTF-16 units split an emoji, and printing the report broke the check ("Conversion from string failed: invalid utf-8 sequence"). Quotes now cut by code point, and every finding is made well-formed before it's printed or saved. The same cut's caption "24-7" was called a word not said, against "twenty four seven" in the words file: the captions pack now reads numbers in words as digits on both sides.

* AGENTS.md: a take cropped to another shape goes through components/Framed.tsx, never a guessed objectPosition

12-05: agents guessed each 9:16 crop and cut the speaker off at the frame's edge.

* AGENTS.md: the brand paragraph in five lines

A box agent starts with at most 2,500 words (docs/check.feature); this paragraph was 150 of them.

* Check: a CTA said in part and shown in part lands; numbers said in words match the brief's digits

Dutch run 10: the host said "use code PETS60 for sixty dollars off your first" as the end card showed "Code PETS60: $60 off your first year". Heard alone was 79% of the line and shown alone 58%, so 5 of 6 cuts got a false CTA ERROR. The heard words now take numbers in digits (as the captions check does) and the CTA counts what is heard and shown together at the end.

* Check: "$60" reads as "60 dollars" in what's heard and what's captioned

Dutch run 10: the transcript wrote "sixty dollars" as "$60", the caption wrote it out, and the captions check called "dollars" a word the host never said.

* Captions check: the takes' own words where the edit placed them count as said

The check heard the export a second time, while captions are built from the takes' own transcripts. Run 11: a second hearing wrote the take's "he heard his label paw" as "he sleep with Paul", and "That's" and "take" otherwise, so right captions read as retyped or as dropping words (4 false ERRORs over Dutch's 6 cuts). A caption's letters now count as said when either hearing has them, and words heard but uncaptioned are a fault only when the take's own words there aren't captioned either. A retyped caption is still caught.

* One UI zone table for Region and the check; ERRORs only for the faults a cut's rules name

- sdk/video zones.ts: the app's UI zones, the same table as the floor's zones(). Region's edges and sides keep them,
  so a title or caption it places is never in the zone the check holds it to (Region kept 8% at the top against the
  check's 220 px, and every hook title it placed was an error).
- The right zone is the app's buttons, from 45% down the frame (RAIL), in the Rust floor and in the goal's floor pack
  for a raea from before it: a centred end card above the buttons is clear.
- place: an error over a face or a sign (words in the shot); over another thing the detector names, a warning with
  the clear place said.
- sound: a cut on sound more than 0.6 s from any word is a warning (a laugh, a noise, a missed word), not a word cut.

* Sound check: a clip with no well-timed word in it isn't a line held to the others' level

A take whose transcript has broken timing (a word 90 s long) made a 0.6 s pause read as a line 51 dB under the rest.

* Captions take a cut's own words; AGENTS.md: captions and titles through Captions and Region, never a typed top

An edit holding several cuts has one words.json, so Captions had no words for each cut and agents wrote their own
captions at a typed top, in the app's UI zones.

* AGENTS.md: shorter placement and Framed lines, back under the start-text limit

* Composition ids take underscores: a deliverable's name is its id

The naming rule names cuts client_concept_variant_v1, and registerRoot refused that id, so an agent that used the
deliverable's name lost a render pass (7 minutes in one run).

* Farm: the box image's SDK overlay on the release, so a render's Region keeps out of the app's zones

The farm bundles each composition with its own SDK; rc4's has no zones.ts, and titles placed by Region landed at
y=154, inside the top 220 px. Deployed (raea-farm, RAEA_VERSION=0.1.17-rc4).

* Farm: frame 0's run commits the work folder, so a render's parts don't each rewrite styles.gen.ts at once

Uncommitted, every part's container found styles.gen.ts older than the code and rewrote it on the shared volume,
truncating it under the others: 14 of one cut's parts refused with "couldn't bundle edit.tsx: Unterminated string"
and the cut was lost. Deployed (raea-farm, RAEA_VERSION=0.1.17-rc4).

* Farm: a piece whose runs draw only stills (a game's capture) is drawn as stills and encoded on the run's GPU

Every run of a playable's capture refused: the file extension .mp4 was not recognized as an image format.

* check.feature: name the retired frames command without its old name (the legacy-names gate)

* goal: the batch critic's test goes with the critic (one check removes raea ask)

* taxonomy: Captions is raea's own name (the one-line captions component)

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-12-05 08:49:49 -08:00
shaneandshinyobjectz 67277ab967 The farm joins a clip across a run's seam whatever its React key (#334)
Each run numbers its React nodes its own way, so one clip came back keyed n3 then n11 by turns, split at each seam, and
raea goal check's sound pack called every seam a cut inside a word: on two of round 22's cuts, 7 of 11 and 13 of 15 of
those errors (found by the pre-render check's engine work, raea #333). Pieces of the same source that meet in frames at
the source time they should now join whole. Deployed to raea-farm as v42 on 12-04.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-05 08:27:56 -08:00
shaneandshinyobjectz 4695f03650 raea goal check runs on raea's runtime again: no named import of spawn (#329)
* raea goal check runs on raea's own runtime again: no named import of spawn

#323 imported spawn from node:child_process for parallel raea ask; raea's runtime (engine/native/src/node.js) has
spawnSync and no spawn, and the named import failed the whole module, so every raea goal check on a box died before it
read a file (raea 0.1.17-rc4) and no StreetTalk cut could publish. A namespace import; spawn where it exists, spawnSync
one at a time where it doesn't. Checked on raea-5 against the installed runtime: the check runs and reports.

* Box image: overlay goal.ts (the spawn fix) on releases that still have the fault

The image installs raea from a release tarball, so the fix reaches boxes only with a new release. Until then the image
copies the fixed goal.ts over the installed one, and only while the installed file still has the named spawn import.

* raea goal check asks Clef six at a time on raea's own runtime too

With no async spawn (raea's runtime), clefVerdict's pool ran every raea ask one after another: StreetTalk round 18's
stop (12-04) spent 7.7 of its 10.5 minutes on 18 beats. askClefMany runs them all through one spawnSync'd shell,
CLEF_AT_ONCE at a time, each into its own file under review/. Measured on raea-4 with that project: the whole done check
in 157 s, the same verdict (14 of 18). The box image's overlay takes the same file.

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-12-05 08:27:49 -08:00
shaneandshinyobjectz 41fbcfc2ab A render sends the farm only the video and audio its source names (#326)
12-03: every StreetTalk run's first render, a few stills included, hashed and uploaded all of footage/ and
footage/originals/ (36-51 takes and several GB of full-size originals) to the farm's cache one file at a time, and
Elfster's stills render ran past its 5-minute step limit. Video and audio that no source file names, by path, file
name or stem with its folder, now stays on the box, out of the tar and the cache (media.ts unusedMedia); when none is
named, all of it goes, as before, and RAEA_CLOUD_GPU_ALL_MEDIA=1 sends it all regardless. The cache's uploads run four
at a time. Test: node sdk/cloud/test/unused-media.ts

Co-authored-by: shinyobjectz <[email protected]>
2026-12-05 08:27:43 -08:00
shane bec1ab1947 Merge pull request #325 from shinyobjectz/idle-real-path
A box's idle stop sees work by its folder's real path; box.sh holds the box while unpacking
2026-12-03 22:19:39 -08:00
shinyobjectz c261ecdfbc box.sh image on a clean tree: its label's dirty test ended the script under set -e, saying nothing 2026-12-03 21:18:41 -08:00
shinyobjectz 712e5ba3a0 A box's idle stop sees work in its folder by the folder's real path too; box.sh holds the box while it unpacks
On a Fly box the work folder is /home/sprite/work, a link to /home/raea/work, and /proc names a process's folder
without the link: a 64 GB unpack in it was taken for idle and the box stopped under it (12-03, raea-3).
2026-12-03 20:48:01 -08:00
shaneandshinyobjectz 51e2d87c76 HugText taught with captions (the skills gate rc3 failed on), a request counts as the box at work until it ends, and box.sh move resumes an arrived home and says what it unpacks (#324)
12-03: a box stopped as idle the moment a 19-minute upload ended (only its start counted), cutting off the unpack that
followed; an unpack of 26 GB said nothing for 3 minutes and was stopped as stalled.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-03 20:38:05 -08:00
shaneandshinyobjectz 9fed1783dc raea cloud's boxes as Fly Machines; 2D farm renders out at once, stragglers sent again (#323)
* raea cloud's boxes as Fly Machines, and a 2D render's runs out at once with stragglers sent again

Boxes: deploy/fly (image, start, box.sh up/move/latest), the server stops itself when idle (idle.ts), a file PUT
streams to disk, the client sends a Sprite's token only to a Sprite (CL16).
Farm: a video with no 3D goes out at once on up to the job's containers (no timed first run), a run hanging back is
sent again and the first answer kept, and containers with no GPU stay warm 180 s.

* The public guard passes raea cloud's box users' folders (/home/sprite, /home/raea); the Fly box scripts are executable

* A goal's says rules judged at once: up to 6 cuts heard by Clef together, and the critic reads while they're heard

One raea ask after another, a project's beats took 6-17 minutes of every goal check (12-03, StreetTalk).

* A box takes a request as long as its body takes (Node's 5 minutes cut a home's upload at 408); box.sh move stops when the home didn't arrive whole

* A box's files route in its own module, streamed both ways; box.sh move says what has arrived every 15 s and stops a copy that stops growing for 2 minutes

main.ts was 520 lines (tools/size.sh). Shane 12-03: fail fast at every step.

* farm: each step after the draw says how long it took when it took a second or more

A render whose every frame was kept took 64 s between "nothing to draw" and "joined" (12-03), and nothing said where.

* An agent socket whose caller answers no ping in 3 minutes is ended, and its agent with it; box.sh restarts a box only for a new image, and its copy reconnects to the Sprite

12-03: a stopped StreetTalk project's Gemini, busy so never idle, went on an hour running goal checks on raea-5: its caller
(the API, restarted) had gone with the box's half of the socket open. A Machine restarted by box.sh up after its health
check passed cut three homes' uploads off; and sprite exec lost all four copies' sessions at once, 6 minutes in, without
reconnecting while stdin was attached (--no-stdin).

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-12-03 20:02:40 -08:00
shaneandshinyobjectz 23918c2c23 Pin raea-skills at ff03a87: references for v0.1.17-rc3 (#322)
Co-authored-by: shinyobjectz <[email protected]>
2026-12-03 19:00:17 -08:00
shaneandshinyobjectz c5c87e2cfb raea guide brief: brief.ts's types and an example, and a cut's beats typed as they are (#321)
Dutch's plan turn (12-03) spent about 2 minutes looking for raea/brief's types: raea guide brief had no guide, so it
read sdk/raea/src under /opt/raea. And what it found was wrong: brief-goal.gen.ts imported the screenplay's Beat
(onScreen, lines, cues) for a cut's beats, while cut.rs's own Beat (at, feel, story, asl, tempo, MK48) is what raea
reads and validates. tsc refused a correct cut beat and accepted a wrong one.

- core/brief: a cut's beat is CutBeat in TypeScript and declared in brief-goal.gen.ts (regenerated); montage.ts uses it.
- sdk/guides/craft/motion/brief.md: the Brief fields, a cut goal's contract, rules and who judges a says rule (raea,
  never the agent), and a fictional example that type-checks against the SDK; the router points to it.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-03 17:50:07 -08:00
shaneandshinyobjectz 743b35677c Judges never pick a harness: a fresh session of the project's own agent, or Clef (#320)
Shane, 12-03: nothing judges or checks with another harness, and nothing the agent reads makes it choose a harness,
model or provider. Dutch's plan turn spent about 3 minutes on raea goal judge --by claude (not signed in on a box),
--by clef (no video at plan) and --by kimi (not on PATH), because sdk/goal spawned claude -p and kimi -p itself.

- sdk/cloud/server/critic.ts: each agent session the box server starts gets RAEA_JUDGE_URL and RAEA_JUDGE_TOKEN;
  POST /host/judge {cwd, prompt} starts a fresh session of that same agent (command, sign-in, environment) over ACP
  stdio, allows reads only, and returns what it says. The desktop's local cloud runs the same server.
- sdk/goal: judge() takes no critic. A rule with a piece to watch or hear goes to Clef-Omni, any other to the session's
  critic. raea goal check asks for a verdict itself when it's missing, stale or partial, so the check is the one
  command and the hooks judge with it. BY, critic() and --by are gone.
- raea judge and raea fingerprint read: the same critic through io/clef/src/critic.rs (one call for every caller);
  --by kimi|claude gone, judge eye --read in its place.
- Help, the manual and the Bevy guides name no harness.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-03 17:50:03 -08:00
shaneandshinyobjectz 80562f9ef7 skills pin: raea-skills fb72c5e for v0.1.17-rc2 (#318)
raea-skills #150-#153: raea show --choose and the workspace MCP line, the component library routing, the playable guide
on Bevy's PBR (#317), and the references regenerated with raea built at main 5f407a1c. SKILLS_STRICT=1
tools/skills.sh check passes on this tree with raea-feed main.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-03 13:43:14 -08:00
shaneandshinyobjectz 5f407a1cc2 A playable's 3D is drawn by Bevy's own PBR programs (PA11) (#317)
* A playable's 3D is drawn by Bevy's own PBR programs (PA11)

tools/bevy-glsl composes Bevy's mesh, pbr and prepass shaders with Bevy's ShaderCache for a WebGL2 device and
translates them with naga; sdk/playable/bevy/build.sh writes them, with each uniform block's field offsets, into
host/bevy/programs.ts, and apps/playable's test fails when Bevy's shaders or the translator change without a rebuild.
host/bevy.ts replaces three.js's renderer and the tone pass: it reads raea's three.js scene graph and fills Bevy's
blocks as Bevy's render world does (reverse Z, one light cluster, one directional shadow cascade, point and spot
lights, distance fog), draws into half float with 4x MSAA, and maps through TonyMcMapface's table.

A Plane3d now reaches three.js as its one face, not as a box with no depth whose top face three points down.

Against `raea render --frame`: brick-rush portrait frame 90 6.1 -> 4.3 / 255, landscape frame 300 9.8 -> 7.7; a
light test scene 0.7 to 1.3 with fog, point and spot lights and an orthographic camera. The page is about 100 KB
smaller and its first frame is as fast as before in WebKit.

* bevy-glsl gets its layer; one fewer helper and line for the gates

tools/layers.toml places bevy-glsl under tools. The translator's one-use int() helper is folded into its call (a
duplicate of uint()), so programs.from moves while programs.ts stays byte for byte. scene.ts asks geometry.ts's
planeOf for a Plane3d's face in one line, back to 500.

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-12-03 13:21:21 -08:00
shaneandshinyobjectz b0437d2d08 raea show --choose: pick one of 2 to 6 named options (#314)
* raea show --choose: the person picks one of 2 to 6 named options, each its files

raea-platform home.feature HM9. `raea show --choose "Warm grade" A.png B.png --choose "Cool grade" C.png
--recommend 2`: each --choose names an option and holds the files after it; --recommend N marks the one the agent
would pick (nothing is picked for the person). It goes to the app's host as intent "choose" with the options, and
the pick comes back to the inbox as {"kind":"answer","choice":"Cool grade"}. Refused: one option or more than six, an
option with no files, a file outside the options, --group, --question or --fyi with it, --recommend out of range.
Usage, the native help line and the manual page say so.

* raea show help: the pick's JSON braces escaped in the format string

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-12-03 12:47:53 -08:00
shaneandshinyobjectz 230f817543 raea check: contrast reads a text in the colour it has on the frame it's measured at (#316)
A text that keeps its words but changes colour (a step chip lighting up, grey on dark to dark on yellow) is one run,
and a run kept only its last frame's colour. Contrast measures at the run's middle frame, so the swipe-graph film's
chips were read as dark text on a dark chip: 1.2:1 where the pixels measure about 8:1. A run now keeps its colour on
each frame beside its box, and contrast uses the middle frame's (Run::middle_color).

Co-authored-by: shinyobjectz <[email protected]>
2026-12-03 12:47:46 -08:00
shaneandshinyobjectz 8dfd71eb92 The component library says when to use each piece: search by how people ask, show NAME, props and upstream names (#315)
An agent asked for "the effect template for composer animations with Claude" found nothing: the catalog had one thin
line per item and the search only read names and that line. Now:

- tools/library-meta.sh (enrich.ts, props.ts, upstream.ts, words.ts, hand.json) matches each of the 609 items by
  content to the upstream component it came from (all 609 match; snapcn's terminal-simulator and text-highlight are
  ui/terminal-session and text/highlight-sweep here) and writes into catalog.json: upstream (a search alias only),
  what (what it draws and how it moves), use_when and avoid_when (upstream's useWhen/avoidWhen in plain words, other
  libraries' names out, pointers rewritten to our category/name or dropped), asked_as (upstream's askedAs plus the
  words people use for its kind: template, effect, composer, chat input, AI prompt, terminal, Claude Code...), props
  (name, type, default and a line each, read from its Props type with the TypeScript parser), length, fps, size,
  aspect and vibe. snapcn's and React Video Editor's items have no when-to-use upstream: hand.json holds those, 134.
- raea make component list WORDS searches names, upstream names and asked_as heavily, what and use_when once; filler
  words are skipped and "template"/"effect"/"preset" alone list the items that are one with how to narrow it.
- raea make component show NAME prints one item in full; list/show --json give the same as JSON.
- sdk/guides/craft/components.md: a template, an effect or a branded screen goes to the library first.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-03 12:29:09 -08:00
shaneandshinyobjectz 2cbfa8c608 A playable carries Bevy's world as wasm for a game whose rules are raea/ecs systems (#313)
PA12: runtime/ecs builds as a cdylib for wasm32 (src/wasm.rs; sdk/playable/ecs/build.sh: 253 KB, 105 KB gzipped,
no imports) into sdk/playable/src/host/ecs.wasm, with the hash of what it was built from beside it, which apps/playable's
test checks. The lint's walk sees a World made; the export carries the module and its entry loads host/ecs.ts before
the game, so raea/ecs's calls (native.ts ecsCall: the engine's bridge, else the page's) reach Bevy's tables in the page
as they do in the engine. A page that can't make the module keeps raea/ecs's TypeScript tables.

World.copy() is a game's next state (copied with its systems, stepped on its own), and a native store nothing holds
frees its world, so a game's let-go states don't keep theirs. examples/playables/star-catch.tsx is a game whose rules
are three systems on a World; conformance/ecs-wasm.test.ts runs one world's life on the wasm and on the TypeScript
tables and finds them equal. The playable guide shows the pattern.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-03 12:23:00 -08:00
shaneandshinyobjectz c3765a13bb Playables play sound after the first touch: raea/tone through Tone.js, generated sounds made at export (#312)
PA6: the lint no longer refuses <Audio>. Its walk renders raea/tone's output beside each composition and lists every
generated sound the game describes (raea/asset now keeps them by src). The export makes each one with the asset store a
render uses, compresses it to 64 kb/s AAC, and carries it in the page. It bundles host/sound.ts only for a game with
sound, and Tone.js (the project's `raea add [email protected]`) only for a raea/tone graph, which host/tone.ts builds from
Tone's own classes and replays event by event. Sound starts in the first gesture, pauses while the ad is hidden and
fades at the end card. A frame stepped past on a slow phone still renders its page, so an <Sfx> on it sounds.

brick-rush gets a square-wave blip on the paddle and each brick and a generated crack under each brick (1,844 KB a
page). tools/check.ts reports what played and fails a page whose sound doesn't decode or never plays. The playable
guide covers sound, and that raea's bundled font families are now carried in the page.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-03 11:39:15 -08:00
shaneandshinyobjectz 5301beb62f Playables: a 2D page carries no three.js, fonts as the native render draws them, a playable goal, exact light rows (#311)
PA15: the host asks for its 3D through one interface (host/draw3d.ts). The export passes three.js's drawer to
start() only when the lint finds a 3D kind, so a 2D game's page drops from about 1,345 KB to 378 KB.

PA8: the page inlines core/fonts' faces under every family the game names that raea aliases, each weight drawn
by the face core/fonts picks. Inter is the page's default.

PA19: core/brief has a playable goal (game, name, networks, orientation, seconds, video). Its deliverables are what
`raea playable` writes, and raea goal's playable pack reads the export's new manifest. `raea playable --name`.
The generated declarations are split in two files to stay under 500 lines each.

PA18: the fast rows rounded a light's rotation to 6 decimals while the full rows wrote it exact, so
RAEA_LIVE3D_CHECK panicked on brick-rush. Rotation and colour columns now pass through exact, and the corpus
no longer skips brick-rush.

tools/check.ts plays with TAP_MS (0 is an instant tap). apps/make's step tests compile again.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-03 10:55:16 -08:00
shane 5c2a524369 Merge pull request #309 from shinyobjectz/cut-words-captions
Words timed to their sound, captions required, TikTok text boxes
2026-12-03 10:13:16 -08:00
shaneandshinyobjectz 4044e442c2 A playable keeps a tap until a step reads it (#310)
The host gave the game only what was held when a step read the input, so a tap
that went down and up between two steps (33 ms apart at 30 fps, longer on a phone
that drops frames) never reached the game. Found on the cloud's Nataly playable:
instant taps left the attract demo running; held 100 ms they played to the end
card. A press, a finger and a key now count as held for the step after they
went down, and the next step sees them let go.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-03 10:04:37 -08:00
shinyobjectz d4e39d41f0 taxonomy: HugText and EmojiText are raea's own 2026-12-03 09:50:14 -08:00
shinyobjectz c7e5534d38 Words timed to their sound, captions required, TikTok text boxes
- raea cloud's words (farm POST /v1/words) hear with raea-words on Modal: Parakeet TDT v3, Qwen3-ForcedAligner's
  times, each word widened onto the pauses beside it. On StreetTalk's takes: word ends early 15% (Whisper 57%),
  starts 30 ms median (70), a clipped word timed to where its sound stops (3/24 past it, Whisper 22/24).
  Whisper large-v3 on Groq is the fallback and hears languages Parakeet doesn't.
- The sound check checks a farm render's takes: its manifest names them by blob hash, and offload points them at the
  project's files (localSources). A voice clip it can't find is an error, not a skipped warning.
- The captions check fails a cut with talking and no captions, and a bare stretch of 3 s or more. A text hook may
  hold the opening (5 s) alone: a brief's "captions or a text hook, never both" means not in one frame.
- HugText: text in a box hugging each line, as TikTok draws it. EmojiText draws emoji in the colour emoji faces on
  any machine; the farm image gets fonts-noto-color-emoji.
2026-12-03 09:45:00 -08:00
shaneandshinyobjectz 788444e127 Videoform: its rules in a taste line's shape, and where to start (#208)
Controllers are gone (projects.feature PJ9, #209), so a videoform's mined rules go in its own `rules`, each in a taste
line's shape (words, a check, its values, a level), and `raea check PROJECT` holds a piece to the rules of the
fingerprint that judges it (VF8, a 15-line hook in apps/direction check.rs). docs/videoform.feature gains a short
"Start here": the order (VF1, VF2, VF3, then VF4 with VF12 as the gate before VF1b and VF9-VF11), the new crates, the
three hooks into what exists and the bench. docs/fingerprint.md records decision 6: Pro and Studio's monthly pool of
clef checks and content intelligence.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-03 08:07:40 -08:00
shaneandshinyobjectz 5b72d2e4dc raea cloud: a 540p proxy of every library video, made on Modal and kept by hash (IG14-IG16) (#306)
sdk/cloud/deploy/modal/proxy.py is raea cloud's proxy maker, its own Modal app (raea-proxy) beside the
indexer so it deploys without the indexer's bundle: a video fetched from the address its index job uses,
hashed as it comes, and made 540p H.264 (CRF 28, a keyframe a second, AAC 96k, faststart), then written
through the Worker's /u/<prefix>/<file-sha> with a ticket for the workspace's proxies alone. A hash already
kept isn't made again; an original that light is its own proxy. Deployed 12-02 as raea-proxy v1.

docs/cloud-ingest.feature IG14-IG16: the proxy made once from the index's download, people watch it, and
agents search by content, look and cut from proxies and fetch originals only for the master.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-02 22:43:25 -08:00
shaneandshinyobjectz 33d34e51b5 raea cloud's Sprite server asks raea's version once at start without blocking (#307)
It asked raea --version synchronously when it began listening, and on a
request when it hadn't yet: on a Sprite whose disk was cold that held every
request, health included, for about 6 s, and after the restarts of 12-02 up
to its 20 s timeout, which also left the version "unknown" for good. Now it
is asked once, off the event loop (2 min at most); /v1/health waits up to
3 s for it, then says "reading", and the start-up line comes once it's known.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-02 21:49:45 -08:00
shaneandshinyobjectz 7cd22cecfc raea-web in Safari: a let holding a texture or sampler is inlined before a shader module is made (#308)
Safari's WGSL holds to the spec (a let can't hold a texture or sampler; Chrome's Tint lets it through). Bevy's PBR
shaders do it in every mesh with UVs, so raea-web drew nothing in Safari: "Fragment module is invalid" for any
sphere or model. @raea/web's loadRaea now patches GPUDevice.createShaderModule once (sdk/web/src/wgsl.ts) to inline
those lets through the rest of their block, so the released engine (web-ad67361) draws in Safari 27: checked in
Ideate's 3D scene via safaridriver (spheres, shadows, fog, point lights). Unit tests: sdk/web/test/unit/wgsl.test.ts.
The vendored bevy_pbr shaders could be fixed at the source with the next web build (30 sites).

Co-authored-by: shinyobjectz <[email protected]>
2026-12-02 21:46:10 -08:00
shaneandshinyobjectz 76e6b00e04 Cloud: a turn's end is read from the agent's own session, not the newest one on its sign-in (#305)
Agents on one sign-in share a home on the Sprite. The watcher read the home's newest transcript, so one chat's last
message ended every other turn running beside it, with nothing said: three of ten chats run two at a time ended
mid-work. The transcript is now the one of the ACP session the socket is on, read off its own messages, and nothing is
said before a session is known. Claude's Stop hook file is shared the same way: while two agents on one sign-in are
open, it is not read.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-02 01:10:21 -08:00
shaneandshinyobjectz 88cacbe7f7 A cloud box comes with ffmpeg and the PDF tools (#304)
Every agent looked for them, searched the disk, then installed them with apt at each project's start; the montage check reads frames with ffmpeg too.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 23:20:54 -08:00
shaneandshinyobjectz 4fd7210cfe Farm: a job's files are listed 32 at a time, and a slow start says where it went (#303)
Each file's stat is a trip to the volume: one after another, 511 files took 9.7 s at each end of every job. A job that drew nothing took 46 s; it takes 16 s.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 23:05:49 -08:00
shaneandshinyobjectz 06a48730d1 A box says a Claude agent's turn has ended from its Stop hook (#302)
The hook is written into the socket's own settings and touches a file the box watches; as with a transcript's end, it's said only when nothing the agent started still runs.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 21:53:29 -08:00
shaneandshinyobjectz 28d89f8ffd Goal check: montage reads frames from a file, and keeps its findings beside the video (#301)
* The montage pack reads a video's frames from a file, not down a pipe

13 MB of small frames through the pipe took 9.7 s of a 35 s cut's read on a cloud box; into a file, 4.6 s.

* A video's montage findings are kept beside it, measured again when it or its beats change

Reading a 35 s cut's frames took 7 s each time the goal was checked, on files that hadn't changed.

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 21:40:48 -08:00
shaneandshinyobjectz 7b8317764a A made video's floor report is kept beside it, measured again only for cause (#300)
The measure took 26 s a cut and ran again on the same file at publish and at done. A kept report with an error is always measured again: what it names can be put right without the video changing.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 20:59:21 -08:00
shaneandshinyobjectz c69e28fac3 A box says when its agent's turn has ended: its transcript ended a step and nothing of its own still runs (#299)
Gemini wrote its last message without answering session/prompt, and the run stayed open 45 minutes until the idle agent was ended, read as cut off and started again. A step with no tool call is also how it waits on a job in the background (123 of 131 in one run), so the agent's processes are read with it.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 20:39:50 -08:00
shaneandshinyobjectz 83da71b62d A video's scene reading is kept beside it, and a kept reading isn't the work changing (#298)
A cut checked at its render was read again at publish and again at done, 30 s a file each time: a done check of 11 files took 334 s. And a done check that heard a cut's words wrote them beside it, so the critic's verdict of a minute before read as older than the work and every says rule failed again.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 19:01:29 -08:00
shaneandshinyobjectz 4d896d2b2f One size is one size however it's told: a name's 9x16, a 1080x1920 video, never a still (#297)
Told by pixels alone, an ad named _9x16 beside its own 1080x1920 renders and a 540x960 still read as three sizes, and an agent with one size made couldn't stop for its sign-off.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 18:43:59 -08:00
shaneandshinyobjectz d4d13925fa Farm: scene frames in parallel, 32 warm containers a video (#296)
* The farm reads a cut's scene frames on containers of their own, side by side

They went through the API's one core one after another inside its event loop: 70 frames of a 35 s ad took 37-47 s, and for that long every other call waited (a render's start 48 s, /v1/health 41 s, each job's follow). A whole goal check on a 35 s cut: 34 s, from 77-98.

* The farm draws a video on up to 32 containers, kept warm a minute, and says where a slow job's end went

A 35 s 1080x1920 cut: 80 s from the box's call to its file, from 104-160. At 8 containers its parts ran two after another on each; at 2 s idle every render's containers started cold.

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 18:22:58 -08:00
shaneandshinyobjectz a8d7263235 A caption over a person's body is a warning; over a face or what the shot shows it stays an error (#295)
Two people fill a 9:16 interview frame, and each caption's clearest place is a different one: an agent spent hours cropping shots and rendering again to clear errors that a steady caption position can't. The warning still names the clear place.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 18:22:53 -08:00
shaneandshinyobjectz d0f09511fe A file of another codec is refused from its moov box, not after the whole file is read (#294)
On Linux every open of an HEVC file tried the portable backend first, which read the whole file into memory to learn
it wasn't H.264 (0.1.16-rc4 on a Sprite: a cold probe of a 1.1 GB interview still took minutes, warm 1.8 s). The
sample entry is read from the moov box first. rotation_of read the whole file for a matrix: the moov box alone.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 12:38:36 -08:00
shaneandshinyobjectz 1a8a7df53d Opening a video, probing it and making its contact sheet no longer read the whole file (#293)
On a cloud Sprite one `raea media probe` of a 1.1 GB 4K interview took 112 s, and its 16-frame sheet 32 s where
ffmpeg alone takes 7 (12-01, measured). Three causes:

- The ffmpeg backend asked ffprobe for every packet's time on each open, and for MP4 and QuickTime ffprobe reads every
  packet to answer: 1 GB read per open, and a sheet opened its file once a frame. The times now come from the file's
  own sample tables (io/ffmpeg mov.rs; the same times as ffprobe's on 45 of 45 real client clips, up to one shift),
  and ffprobe is asked only for the stream's facts. Fragments, other containers and edit lists that do more than set
  a start are asked of ffprobe as before.
- `media probe` decoded the whole sound track to learn its rate, channels and length: read from the track's tables.
- A sheet's frames are read four at a time.

The Sprite's service sets its disks' read-ahead to 16 MB at each start: at the disk's own 256 KB, with each read
answered in about 26 ms, a pass over footage ran at 10 MB/s.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 11:22:11 -08:00
shaneandshinyobjectz ef8ea7563d On Windows a file asked for by its whole path is that file, not a package's name (#278) (#292)
0.1.16-rc2's Windows build failed its own new check: brief.ts importing react found the React raea ships, which was
then asked for again by its path (D:\..\react\index.js) and read as a package named that: "Cannot find package
'D:\...\index.js'". The resolver knew a whole path only by a leading slash.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 09:42:49 -08:00
shaneandshinyobjectz 6716b6b9f0 A Sprite's setup installs the open faces brands are closest to, and box.sh up builds a Sprite just made (#291)
A Sprite had Liberation and DejaVu alone, so every cut's type fell back to Liberation Sans. setup.sh now installs Inter,
Roboto, Open Sans, Lato, Montserrat, Noto, IBM Plex, Bebas Neue and the URW base 35, each when the Ubuntu has it.
box.sh up ended with curl's exit 7 on a Sprite just made (its wait for running agents asked a server that isn't there
yet).

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 09:12:06 -08:00
shaneandshinyobjectz 313ac8ab83 A project's file that imports react finds the React raea ships (#278) (#290)
* A project's file that imports react finds the React raea ships, as raea's own files do (#278)

0.1.15 let raea's own files (sdk/app) find react in the release's one node_modules. A project's file still could not:
brief.ts, or a scene it registers, imports its hooks from "react", a project has no package.json, and the render's
own checks load brief.ts. So a render was applied, then failed with "brief.ts doesn't run: Cannot find package
'react'" and "fix every ERROR above, then render again", on every release through 0.1.16-rc1.

Any file with no node_modules of its own above it now gets the package raea ships (the bundler gives a scene the same
React); a project's own copy still wins, and a package raea doesn't ship is still not found. The release's check of
the built archive renders beside such a brief.ts on every platform.

* The archive's check of a brief.ts that imports react runs on every build, not only on real machines

* node.rs back under the size limit

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 08:41:09 -08:00
shaneandshinyobjectz cdfb043026 clef's second opinion on a cut is a list of pointed picture and sound checks, the faults it found first (#289)
Asked "do the graphics look designed", clef graded Dutch's plain boxes "strong". Asked pointed yes/no checks of the
same cut it found three of them: three or more text boxes at once (0.93), captions, cards and badges all the same
plain box (0.57), the app shown only as a box of text (0.80). Shane, 12-01: "you just have to have them be more
specific or pointed like giving it some list of design checks to answer ... a few catch all checks on visual and
audio design"; "the agent itself is really responsible for design".

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 06:16:58 -08:00
shaneandshinyobjectz 35267727b8 raea goal seen judges a video's design at full size; a project's design is the agent's own (#288)
* raea goal seen judges a video's design at full size, with clef as a second opinion; a project's design is the agent's own within the brand's colours

A contact sheet's tiles show what happens in a cut, never whether its type, captions and cards look good, and it was
the only picture an agent looked at before sign-off. raea goal seen FILE now also writes six frames at full size
(FILE.looks/) and the seen pack holds a video until --look says how its design stands beside a reference. On raea
cloud it prints clef's grades of the whole cut, picture and sound, lowest first, as a second opinion.
A project's AGENTS.md no longer says "never a colour, font or size of your own": the brand's colours and faces are
the palette, and size, weight, shape, layout and motion are designed for the piece.

* skills: raea goal seen's frames at full size and --look (raea-skills #148)

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 06:02:21 -08:00
shaneandshinyobjectz c72717a635 RAEA_MEDIA=ffmpeg encodes with the system's H.264 encoder where ffmpeg has no libx264 (the LGPL build raea ships on Windows: h264_mf), at the bitrate (#279) (#287)
Co-authored-by: shinyobjectz <[email protected]>
2026-11-30 22:15:21 -08:00
shaneandshinyobjectz 0256cb9673 The AppImage's two pinned tools come from raea's own copy when GitHub's download fails (the runner got HTTP 618 three times for v0.1.15-rc1, and the Linux archive waits on it) (#286)
Co-authored-by: shinyobjectz <[email protected]>
2026-11-30 21:57:25 -08:00
shaneandshinyobjectz b9b0d76568 The sound guide says what the default mix ducks and how to cut air gaps (its lines reached the skill's copy and never main), and the skill's file list as main generates it (#285)
Co-authored-by: shinyobjectz <[email protected]>
2026-11-30 20:59:20 -08:00
shaneandshinyobjectz bda521b3ce goal judge --by clef (the critic on raea cloud), and the skill's references for 0.1.15 (#284)
* The raea skill's references say make component list WORDS and render --keys (raea-skills #145)

* raea goal judge --by clef: clef-omni judges says rules on the files they name, and is the critic where an agent key is set (a raea cloud box has no Claude sign-in in the agent's shell)

* raea's own files find the packages raea ships: a release's render no longer ends "Cannot find package 'react'" with exit 1, and raea goal check runs outside a build tree (#278)

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-11-30 20:15:26 -08:00
shaneandshinyobjectz 740f3c2cf4 Engine side of the render-cost work: clip decoding, frame keys, NVENC (#282)
* A page reads a clip on from where it stopped: up to 4 readers a file, so a clip shown twice at once isn't sought every frame

Where two elements showed one 4K clip, they shared one decoder and ffmpeg restarted every frame (31 starts in 30
frames). Each file now keeps up to 4 readers, each reading on from its last frame (the one behind within 60 frames,
else a new one, else the least used), and the frame it read last for a second ask. Those frames: 909 to 53 ms on the
Mac, SSIM 1.000000; a 30 s ad of 4K street-interview clips on the farm's GPUs 277 s and $0.106 to 153 s and $0.033.

* render --keys: each frame's key with nothing drawn, and the largest each clip is drawn

raea render EDIT --keys keys.json steps React through every frame and makes the page match it without reading a clip
or drawing: each frame's key (its elements' place, kind, props and text, each video's file and time, its 3D rows;
paths named from the composition's folder), has3d, the piece's sounds, and the largest each clip is drawn (box as
drawn, transforms and punch-in applied). A render farm keeps runs by these keys and reads clips from copies no larger
than they're drawn. On the ad: 6.7 s for 894 frames; a caption word changed 70 frames' keys, a sound 3 dB louder none
(CR32, CR36).

* RAEA_NV=1: NVENC and NVDEC in the ffmpeg backend, each after a one-frame try on the machine

The render farm sets it on a GPU's runs of a piece with 3D in it. h264_nvenc at libx264's CRF number as constant QP
(SSIM 0.9925 to libx264's 0.9924 on the ad) and clips through CUDA; where a try fails, libx264 and ffmpeg's own,
said once. The answer is kept for the machine's later runs (CR34).

* The face track and render --review's sheets are crates of their own (raea-sys-facetrack, raea-runtime-review): raea-runtime-page and raea-runtime-export are under 2000 lines again

* One opener for a video (raea_io_media::open_video) and one step of React to a frame (step_react), where the render-cost work had copied each

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-11-30 19:16:06 -08:00
460 changed files with 43153 additions and 9252 deletions

No files matched your search

+1 -1
View File
@@ -8,7 +8,7 @@
{
"name": "raea",
"source": { "source": "git-subdir", "url": "https://github.com/shinyobjectz/raea-skills.git", "path": "skills" },
"description": "Make video, motion graphics, games and 3D scenes with raea, the Render Anything Engine: the raea skill, and hooks that 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."
"description": "Make video, motion graphics, games and 3D scenes with raea, the Render Anything Engine: the raea skill, and hooks that show media in the raea app instead of the Mac's viewer and run raea check on the brief's goals as a turn ends (nothing is checked after a save: a render checks its own output)."
}
]
}
+37 -12
View File
@@ -1,7 +1,8 @@
# raea's public CI (docs/public-first.feature PF5), on GitHub's hosted runners only: it runs code from pull requests,
# so it never touches a self-hosted machine. What needs this Mac's GPU, VideoToolbox or audio (P26, UI parity, the
# sound gates) stays the maintainers' L1/L2 (docs/agents.md); this is the part anyone can read and rerun.
# every pull request and push to main guard (names and secrets), L0's repo-wide gates, cargo check of the engine
# every pull request and push to main guard (names and secrets), L0's repo-wide gates, sdk/cloud's local tests,
# cargo check of the engine, the tests of every crate that needs no GPU
name: ci
on:
@@ -93,6 +94,24 @@ jobs:
- name: taxonomy
run: bash tools/taxonomy.sh --check
cloud:
# sdk/cloud's tests that need no container or farm (its npm test): the box server's pure parts and memory guard,
# what a render sends the farm, and the farm's planner (its encode on ffmpeg), media and volume gate
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- uses: actions/checkout@v4
with:
lfs: false
- uses: actions/setup-node@v4
with:
node-version: 24
- name: ffmpeg
run: sudo apt-get update && sudo apt-get install -y ffmpeg
- name: sdk/cloud tests
working-directory: sdk/cloud
run: npm ci --no-fund --no-audit --loglevel=error && npm test
engine:
# a fresh clone builds as the README says (public #14): the toolchain from rust-toolchain.toml, --locked
strategy:
@@ -107,35 +126,41 @@ jobs:
lfs: false
- name: Linux libraries
if: runner.os == 'Linux'
run: sudo apt-get update && sudo apt-get install -y cmake ninja-build libasound2-dev libfontconfig1-dev libvulkan-dev libudev-dev nasm
run: sudo apt-get update && sudo apt-get install -y cmake ninja-build libasound2-dev libfontconfig1-dev libvulkan-dev libudev-dev nasm ffmpeg
- name: macOS tools
if: runner.os == 'macOS'
run: brew install cmake ninja nasm
run: brew install cmake ninja nasm ffmpeg
- uses: oven-sh/setup-bun@v2
with:
bun-version: 1.4.2
- uses: Swatinem/rust-cache@v2
- name: cargo check
run: cargo check --locked -p raea-cli --tests
- name: unit tests (the crates with no GPU or media device)
- name: unit tests (every crate with no GPU)
# debug info off: with it the test binaries of the app crates filled 27 GB of a runner's disk (#90)
env:
CARGO_PROFILE_TEST_DEBUG: "0"
# The crates come from the lock file, so a new crate's tests run without anyone naming it: every workspace crate
# that links neither wgpu nor Rolldown, then the few that link wgpu and whose tests need no GPU. All of wgpu's
# side can't join: its test binaries would fill the runner's disk (#90). Left out, with the reason:
# raea-sys-mlx its tests run on MLX's GPU device, and a hosted macOS runner has no Metal device
# raea-bundle in a call of its own: Rolldown's crates turn on serde_json's arbitrary_precision, features unify
# across one cargo call, and with it on an untagged enum can't read a number (raea-core-brief's make dials failed
# here from 11-23 while passing alone). raea itself never links Rolldown: it loads it as a library at run time
# here from 11-23 while passing alone). raea itself never links Rolldown: it loads it as a library at run time.
# --no-fail-fast: one run names every crate whose tests fail, not only the first
run: |
cargo test --locked -p raea-runtime-plugins -p raea-io-media -p raea-core-fonts -p raea-native -p raea-core-brief -p raea-core-k -p raea-app-check -p raea-app-check-flash -p raea-io-ffmpeg -p raea-app-workspace -p raea-app-tools -p raea-app-targets
ws=$(cargo metadata --locked --no-deps --format-version 1 | jq -r '.packages[].name' | sort)
linked=$(for k in wgpu rolldown; do cargo tree --locked --workspace -i "$k" -e normal,build,dev --prefix none --format '{p}'; done | grep -F "($PWD/" | sed 's/ v[0-9].*//' | sort -u)
light=$(comm -23 <(echo "$ws") <(echo "$linked") | grep -vx raea-sys-mlx | sed 's/^/-p /')
cargo test --locked --no-fail-fast $light -p raea-runtime-plugins -p raea-runtime-live -p raea-app-check -p raea-app-workspace -p raea-app-tools -p raea-app-targets
cargo test --locked -p raea-bundle
- name: Windows' and Linux's own (#169)
# what a Windows or Linux user meets that no other step ran: QuickJS's Intl (raea-runtime-jsengine's
# quickjs_formats_as_javascriptcore_does, on Linux), openh264 at --quality master (raea-io-soft), git found or
# fetched (raea-io-assets), and raea's Node core under the agent shell (raea-native's tests/node.rs: Node's names
# for the system, Windows' paths); tests/node.rs needs raea-native's modules feature and tests/quality.rs
# raea-io-soft's h264
# what a Windows or Linux user meets that needs a feature the step above doesn't turn on: openh264 at --quality
# master (raea-io-soft's tests/quality.rs, its h264 feature) and raea's Node core under the agent shell
# (raea-native's tests/node.rs, its modules feature: Node's names for the system, Windows' paths). QuickJS's
# Intl (raea-runtime-jsengine, on Linux) and git found or fetched (raea-io-assets) run in the step above
env:
CARGO_PROFILE_TEST_DEBUG: "0"
run: |
cargo test --locked -p raea-native --features modules --test node
cargo test --locked -p raea-io-soft --features h264
cargo test --locked -p raea-runtime-jsengine -p raea-io-assets
+2
View File
@@ -107,5 +107,7 @@ sdk/raea/.scratch-*/
# examples/materials/wear: its house is made by make-house.ts (media/) and baked at render time (assets/wear/)
/examples/materials/wear/media/
/examples/materials/wear/assets/
# a playable example's generated sounds, made beside it the first time it's rendered or exported (raea's asset store)
/examples/playables/assets/
# tools/bevy-parity links each example folder's assets/ to Bevy's checkout at run time (an absolute, per-machine path)
/sdk/raea/bench/bevy-parity/**/assets
Generated
+4 -34
View File
@@ -13820,6 +13820,7 @@ dependencies = [
"fastrand",
"raea-app-check",
"raea-app-double",
"raea-io-clef",
"raea-io-home",
"raea-sys-columns",
"raea-sys-fingerprint",
@@ -13862,19 +13863,6 @@ dependencies = [
"serde_json",
]
[[package]]
name = "raea-app-judge"
version = "0.1.0"
dependencies = [
"dunce",
"raea-core-ask",
"raea-core-facts",
"raea-io-clef",
"raea-io-home",
"raea-runtime-bundle",
"serde_json",
]
[[package]]
name = "raea-app-layers"
version = "0.1.0"
@@ -13907,13 +13895,9 @@ version = "0.1.0"
dependencies = [
"dunce",
"image",
"raea-app-judge",
"raea-core-ask",
"raea-core-brief",
"raea-core-facts",
"raea-core-review",
"raea-io-home",
"raea-runtime-lod-plan",
"resvg 0.48.1",
"serde_json",
]
@@ -13978,7 +13962,10 @@ dependencies = [
name = "raea-app-playable"
version = "0.1.0"
dependencies = [
"base64 0.22.1",
"dunce",
"raea-core-fonts",
"raea-io-assets",
"raea-io-home",
"raea-runtime-bundle",
"regex",
@@ -14003,7 +13990,6 @@ version = "0.1.0"
dependencies = [
"bevy",
"dunce",
"image",
"raea-core-facts",
"raea-core-scene",
"raea-runtime-bundle",
@@ -14023,8 +14009,6 @@ name = "raea-app-solid"
version = "0.1.0"
dependencies = [
"dunce",
"raea-app-ask",
"raea-app-judge",
"raea-app-make",
"raea-core-facts",
"raea-core-meshcheck",
@@ -14312,7 +14296,6 @@ version = "0.1.0"
dependencies = [
"bevy",
"dunce",
"raea-app-ask",
"raea-app-capcut",
"raea-app-check",
"raea-app-ci",
@@ -14320,7 +14303,6 @@ dependencies = [
"raea-app-engines",
"raea-app-fingerprint",
"raea-app-game",
"raea-app-judge",
"raea-app-layers",
"raea-app-lightbake",
"raea-app-make",
@@ -14407,7 +14389,6 @@ dependencies = [
"serde",
"serde_json",
"sha2 0.10.9",
"ts-rs",
]
[[package]]
@@ -16246,17 +16227,6 @@ dependencies = [
"wgpu",
]
[[package]]
name = "raea-sys-foliage"
version = "0.1.0"
dependencies = [
"image",
"parry3d",
"raea-core-ease",
"raea-sys-glb",
"serde_json",
]
[[package]]
name = "raea-sys-fonts"
version = "0.1.0"
-2
View File
@@ -148,7 +148,6 @@ members = [
"systems/matchmove",
"systems/grid",
"systems/lod",
"systems/foliage",
"systems/viewbox",
"systems/rendermap",
"systems/meshseq",
@@ -238,7 +237,6 @@ members = [
"apps/motion",
"apps/engines",
"apps/interchange",
"apps/judge",
"apps/make",
"apps/solid",
"apps/scene",
+5 -4
View File
@@ -11,7 +11,7 @@
<p align="center">
Tell your AI what to make. Videos, motion graphics, 3D and games, written as React and TypeScript<br>
(the code your AI already writes) and rendered on your own GPU, faster than they play.
(the code your AI already writes) and rendered on your own GPU.
</p>
<p align="center">
@@ -145,9 +145,10 @@ Apache-2.0, to read, render and take apart, and its models, textures and sound f
- **Agent skills.** They live in [raea-skills](https://github.com/shinyobjectz/raea-skills), pinned here as
[`skills/`](skills): `raea` teaches an agent to write, render and check raea compositions, 3D and games
included. The installer adds it to `~/.claude/skills`, and `raea skills install --agent NAME` to other agents.
- **Claude plugin.** The raea skill and 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.
- **Claude plugin.** The raea skill and its hooks: media an agent opens goes to the raea app, and `raea check` holds
the brief's goals as a turn ends. Nothing is checked after a save, since a render checks its own output. In Claude
Code: `/plugin install raea --marketplace shinyobjectz/raea-skills`. It's the `skills/` folder of raea-skills, and
`/plugin marketplace add shinyobjectz/raea` installs the same one.
- **Craft guides.** `raea guide` prints the floor every edit is held to and the guides for pitches, explainers, stories,
games, motion, music and layout. `raea context PROJECT` says what to read before working on a project.
- **Bug reports.** When an agent finds a bug in raea itself, `raea bug TITLE --text TEXT` sends it to raea's server
+1 -1
View File
@@ -4,7 +4,7 @@ version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "raea ask: questions about a piece's picture and sound, prepared from what raea knows of it, asked of clef in parallel from the person's plan, and every answer kept"
description = "Questions about a piece's picture and sound, prepared from what raea knows of it, asked of clef in parallel from the person's plan, and every answer kept"
[dependencies]
# the question format and the standard sets; the one clef client, routed to the person's plan first (docs/ask.feature)
+5 -5
View File
@@ -3,7 +3,7 @@
//! threshold, the problem score that flags 10% of the clean labels. The gates are the fingerprint's (16 labels of each
//! kind, from 3 projects, an AUC of 0.8). A question that passes is calibrated at its threshold: its answers are
//! findings, and the person's calibration replaces raea's shipped one. One under 0.6 after 32 labels doesn't separate,
//! and says which labels it missed, so its words can be fixed. `raea ask try` asks new words of the labelled clips and
//! and says which labels it missed, so its words can be fixed. `try_words` asks new words of the labelled clips and
//! sets both AUCs side by side.
use std::collections::{BTreeMap, BTreeSet, HashMap};
@@ -135,7 +135,7 @@ fn versions(only: Option<&str>, all: &[Label]) -> Vec<Question> {
out
}
/// `raea ask calibrate [ID]`: the feed's labels read again, then every labelled version held to them. The ones that
/// `calibrate(ID)`: the feed's labels read again, then every labelled version held to them. The ones that
/// pass are kept as the person's calibration; one that no longer passes loses it.
pub fn calibrate(only: Option<&str>) -> Result<(Vec<Standing>, (usize, usize)), String> {
let feed = labels::from_feed()?;
@@ -159,7 +159,7 @@ fn today() -> String {
raea_io_trace::utc(std::time::SystemTime::now()).0.chars().take(10).collect()
}
/// The groups `raea ask try` sends: the new question on each labelled clip set, with the state it was asked with.
/// The groups `try_words` sends: the new question on each labelled clip set, with the state it was asked with.
pub fn try_groups(like: &str, words: &str) -> Result<(Question, Question, Vec<Group>), String> {
let all = labels::all();
let standing = labels::standing(&all);
@@ -182,7 +182,7 @@ pub fn try_groups(like: &str, words: &str) -> Result<(Question, Question, Vec<Gr
groups.push(Group { piece, from, to, sees: new.sees, hears: new.hears, with: vec![], questions: vec![new.clone()], kept: Some(Arc::new(kept)) });
}
if groups.is_empty() {
return Err(format!("ask try: none of {like}'s labelled clips are still kept (raea ask calibrate lists its labels)"));
return Err(format!("ask try: none of {like}'s labelled clips are still kept (calibrate() lists its labels)"));
}
Ok((old, new, groups))
}
@@ -201,7 +201,7 @@ fn media(names: &[&str]) -> Option<Media> {
Some(m)
}
/// `raea ask try "WORDS" --like ID`: the new words asked of the old question's labelled clips, and both versions held to
/// `try_words(LIKE, WORDS)`: the new words asked of the old question's labelled clips, and both versions held to
/// the same labels.
pub fn try_words(like: &str, words: &str, o: &Opts, out: &mut dyn FnMut(Event)) -> Result<(Summary, Option<(Standing, Standing)>), String> {
let (old, new, groups) = try_groups(like, words)?;
+4 -4
View File
@@ -1,14 +1,14 @@
//! Labels (docs/ask.feature AK6): whether a question's problem was really there in what one call sent, so the question
//! can be calibrated on the person's own eye (calibrate.rs). A label belongs to a question and to the clips a call sent
//! (by their hashes), never to one answer: the same question reworded, asked again of the same clips, has the same
//! labels, which is what lets `raea ask try` measure new words.
//! labels, which is what lets `try_words` measure new words.
//!
//! Where labels come from:
//! - `raea ask verdict ANSWER WORD`: the person answers the question themselves, in its own terms (yes or no, an option,
//! - `verdict(ANSWER, WORD)`: the person answers the question themselves, in its own terms (yes or no, an option,
//! a level). Theirs counts first.
//! - The feed: a note of the person's on the render (its copy in the project's feed, known by `record::ident`), pinned
//! inside the window or not pinned at all, holding one of the question's label words, is a yes; an approved post (done)
//! with no such note is a no. Read again by every `raea ask calibrate`.
//! with no such note is a no. Read again by every `calibrate()`.
//! - Another eye (`verdict --eye agent`: an agent's own look) is kept as `eye:NAME` and never counted, as the
//! fingerprint keeps another eye's readings (FP6d).
@@ -149,7 +149,7 @@ fn label(q: &str, call: &Value, bad: bool, source: &str, note: Option<String>) -
}
}
/// `raea ask verdict ANSWER WORD [--eye NAME]`: the person's answer to the question on that answer's clips (or another
/// `verdict(ANSWER, WORD, EYE)`: the person's answer to the question on that answer's clips (or another
/// eye's, kept and never counted). A verdict given again replaces the last from the same source.
pub fn verdict(answer: &str, said: &str, eye: Option<&str>) -> Result<String, String> {
let row = record::rows("answers.jsonl").into_iter().find(|a| a["id"] == answer).ok_or_else(|| format!("ask verdict: no answer {answer} in {}", record::dir().display()))?;
+4 -8
View File
@@ -1,17 +1,13 @@
//! `raea ask` (docs/ask.feature AK2-AK3): questions about a piece's picture and sound. `prepare` reads what raea knows
//! of the piece and keeps the questions that apply; `runner` plans the calls, cuts each clip once and asks in parallel;
//! `record` keeps every call and answer; `labels` reads the person's verdicts, notes and approvals into labels, and
//! `calibrate` holds each question to them (AK6-AK7); `verbs` is the command. `raea check`, the app's critique and the
//! fingerprint's double-check go through the same runner.
//! Questions about a piece's picture and sound (docs/ask.feature AK2-AK3), asked for the fingerprint's double-check
//! (`raea fingerprint score --ask`, apps/double). `prepare` reads what raea knows of the piece and keeps the questions
//! that apply; `runner` plans the calls, cuts each clip once and asks in parallel; `record` keeps every call and answer;
//! `labels` reads the person's notes and approvals into labels, and `calibrate` holds each question to them (AK6-AK7).
pub mod calibrate;
pub mod labels;
pub mod prepare;
pub mod record;
pub mod runner;
pub mod verbs;
pub use verbs::{USAGE, cli};
#[cfg(test)]
mod tests;
+2 -2
View File
@@ -3,7 +3,7 @@
//! answer in answers.jsonl (the call, the question and its version, the reading). The clips themselves are kept by hash
//! in media/, at most 2 GB, the oldest out first, so new words can be asked of the same media. A call keeps what its
//! file was (`ident`), so a note on the render's copy in the feed labels it (labels.rs), and an answer keeps its whole
//! question, so a verdict reads in its terms and `raea ask try` can reword it.
//! question, so a verdict reads in its terms and `try_words` can reword it.
use std::io::Write as _;
use std::path::{Path, PathBuf};
@@ -49,7 +49,7 @@ fn hex(digest: &[u8]) -> String {
digest.iter().take(16).map(|b| format!("{b:02x}")).collect()
}
/// What a file is, cheaply, and the size an ident names (raea-core-ask, so `raea goal gates` reads the same).
/// What a file is, cheaply, and the size an ident names (raea-core-ask's).
pub use raea_core_ask::ident::{ident, ident_len};
/// One of the record's files written whole, through a temporary file, so a reader never sees half of it.
+4 -4
View File
@@ -3,7 +3,7 @@
//! call whose questions depend on whether anyone speaks when that isn't known), each clip cut once, the calls
//! made in parallel, the answers streamed back as they come and kept. A pool that's spent partway keeps what came and
//! reports the rest as waiting for it. `dry` cuts the media and says what would be sent, and spends nothing. A group can
//! carry clips kept from an earlier call instead of a file to cut (`raea ask try`), and every question goes out with the
//! carry clips kept from an earlier call instead of a file to cut (`try_words`), and every question goes out with the
//! person's own calibration when it has earned one (calibrate.rs).
use std::collections::{BTreeSet, HashMap};
@@ -50,10 +50,10 @@ pub struct Kept {
pub sound_seconds: f64,
}
/// One answer, or why a question wasn't asked or still waits: the line `raea ask --json` prints for each.
/// One answer, or why a question wasn't asked or still waits: one line of JSON each.
#[derive(Debug, Clone, Default, Serialize)]
pub struct Answer {
/// its id in the record (`raea ask verdict` takes it)
/// its id in the record (`labels::verdict` takes it)
pub answer: Option<String>,
pub file: String,
pub id: String,
@@ -285,7 +285,7 @@ pub fn run_groups(groups: Vec<Group>, unasked: Vec<Answer>, o: &Opts, out: &mut
sum
}
/// The clips a call sent, kept by hash for `raea ask try`.
/// The clips a call sent, kept by hash for `try_words`.
fn kept(m: &Media) -> Vec<String> {
let each = |v: &[Vec<u8>], ext: &str| v.iter().map(|b| record::keep_media(b, ext)).collect::<Vec<_>>();
[each(&m.videos, "mp4"), each(&m.stills, "jpg"), each(&m.sounds, "mp3")].concat()
+1 -7
View File
@@ -11,7 +11,7 @@ use crate::prepare::{self, Piece, VOICE};
use crate::runner::{self, Answer, Entry, Event, Opts};
fn rubric() -> String {
std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/../../sdk/guides/craft/rubric.md")).expect("the craft rubric")
std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/../../sdk/guides/craft/verbs/critique.md")).expect("the critique guide")
}
pub(crate) fn setup() {
@@ -166,9 +166,3 @@ fn a_pool_spent_partway_keeps_what_came_and_the_rest_waits() {
assert_eq!(got.iter().filter(|a| a.waits.as_deref().is_some_and(|w| w.contains("used up"))).count(), 2);
assert_eq!(CALLS.load(Ordering::SeqCst), 3, "nothing is sent after the pool is spent");
}
#[test]
fn own_words_keep_their_id() {
assert_eq!(crate::verbs::own_id("Does the music fight the voice?"), "own-does-the-music-fight-the-voice");
assert_eq!(crate::verbs::own_id("Does the music fight the voice?"), crate::verbs::own_id("does the MUSIC fight the voice"));
}
-385
View File
@@ -1,385 +0,0 @@
//! `raea ask` (docs/ask.feature AK3): questions about a piece's picture and sound, from the command line or a batch,
//! prepared (prepare.rs), asked in parallel (runner.rs) and kept (record.rs). It prints as answers come: words and a
//! probability a line, or with `--json` one JSON object a line (an answer, a call `--dry` would make, then the summary).
//! `--gate` exits 1 when a calibrated question flags (`--gate any`: when any does), for a pipeline. `verdict`,
//! `calibrate` and `try` label the answers, calibrate the questions on them and measure new words (labels.rs,
//! calibrate.rs; AK6-AK7).
use std::collections::{BTreeMap, HashMap};
use std::io::Read as _;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use raea_core_ask::{Kind, Question, Window, library};
use serde_json::{Value, json};
use crate::labels::{self, span};
use crate::prepare::{self, Piece};
use crate::runner::{self, Entry, Event, Opts};
use crate::{calibrate, record};
pub const USAGE: &str = "raea ask FILE [QUESTION...] [--choose A,B,C] [--grade] [--rate N] [--flag ANSWERS] [--set NAME] [--std ID] [--from S] [--to S] [--at S] [--with FILE2] [--brief brief.ts|none] [--words words.json] [--voice yes|no] [--state TEXT] [--dry] [--json] [--gate [any]] [--jobs N] | ask --batch FILE [--dry] [--json] [--gate [any]] [--jobs N] | ask list [SET] [--json] | ask verdict ANSWER WORD [--eye NAME] | ask calibrate [ID] [--json] | ask try WORDS --like ID [--dry] [--json] [--jobs N] (questions about a piece's picture and sound, answered by clef-omni and paid from your raea plan's pool when the app is signed in, else RAEA_AGENT_KEY's, else your own Cloudflare keys: your own words, or the standard sets (rubric, av, defects, platform, decide, make); every question about one clip goes in one call, --batch (a JSON list or JSON lines, - for stdin) asks many clips in parallel; --dry says what would be sent and spends nothing; answers are advice until a question is calibrated: verdict labels an answer, calibrate holds each question to your verdicts, notes and approvals, try asks new words of its labelled clips)";
const VALUED: [&str; 17] = ["--choose", "--rate", "--flag", "--set", "--std", "--from", "--to", "--at", "--with", "--brief", "--words", "--voice", "--state", "--jobs", "--batch", "--eye", "--like"];
const BARE: [&str; 4] = ["--grade", "--dry", "--json", "--gate"];
/// The arguments: the words that aren't flags, each flag's values, and whether `--gate` is `--gate any`.
#[derive(Default)]
struct Args {
words: Vec<String>,
flags: BTreeMap<String, Vec<String>>,
gate_any: bool,
}
impl Args {
fn parse(args: &[String]) -> Result<Args, String> {
let mut a = Args::default();
let mut i = 0;
while i < args.len() {
let s = args[i].as_str();
if VALUED.contains(&s) {
let v = args.get(i + 1).ok_or_else(|| format!("ask: {s} takes a value\nusage: {USAGE}"))?;
a.flags.entry(s.into()).or_default().push(v.clone());
i += 1;
} else if BARE.contains(&s) {
a.flags.entry(s.into()).or_default();
if s == "--gate" && args.get(i + 1).is_some_and(|v| v == "any") {
a.gate_any = true;
i += 1;
}
} else if s.starts_with("--") {
return Err(format!("ask doesn't take {s}\nusage: {USAGE}"));
} else {
a.words.push(s.into());
}
i += 1;
}
Ok(a)
}
fn has(&self, f: &str) -> bool {
self.flags.contains_key(f)
}
fn one(&self, f: &str) -> Option<&str> {
self.flags.get(f).and_then(|v| v.last()).map(String::as_str)
}
fn num(&self, f: &str) -> Result<Option<f64>, String> {
self.one(f).map(|v| v.parse::<f64>().map_err(|_| format!("ask: {f} takes seconds, got {v:?}"))).transpose()
}
fn list(&self, f: &str) -> Vec<String> {
self.flags.get(f).into_iter().flatten().flat_map(|v| v.split(',')).map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect()
}
}
/// The craft rubric's text, where the guides are installed, for the `rubric` set.
pub fn rubric_md() -> Option<String> {
std::fs::read_to_string(raea_io_home::home().join("sdk/guides/craft/rubric.md")).ok()
}
/// A question's id from its words: `own-` and its first words, so the same words keep their id.
pub fn own_id(words: &str) -> String {
let slug: Vec<String> = words.split(|c: char| !c.is_ascii_alphanumeric()).filter(|w| !w.is_empty()).take(6).map(str::to_lowercase).collect();
let mut id = format!("own-{}", slug.join("-"));
id.truncate(raea_core_ask::limits::ID_LEN);
id
}
/// The questions an entry names: its own words (shaped by the kind flags), its sets and its standard ids.
fn named(own: &[Question], sets: &[String], std: &[String], rubric: Option<&str>) -> Result<Vec<Question>, String> {
let mut qs = own.to_vec();
for s in sets {
qs.extend(library::set(s, rubric)?);
}
for id in std {
qs.push(library::find(id, rubric).ok_or_else(|| format!("ask: no standard question {id} (raea ask list)"))?);
}
Ok(qs)
}
fn shaped(words: &str, a: &Args) -> Result<Question, String> {
let mut q = Question::plain(&own_id(words), words);
if let Some(c) = a.one("--choose") {
q.kind = Kind::Choose;
q.options = c.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect();
} else if let Some(n) = a.one("--rate") {
let n: usize = n.parse().map_err(|_| format!("ask: --rate takes how many levels, got {n:?}"))?;
q.kind = Kind::Rate;
q.options = (1..=n).map(|i| i.to_string()).collect();
} else if a.has("--grade") {
q.kind = Kind::Grade;
}
q.flags = a.list("--flag");
if let Some(why) = raea_core_ask::limits::check(&q) {
return Err(format!("ask: {why}"));
}
Ok(q)
}
/// The window from --from, --to and --at (three seconds around it).
fn window(a: &Args) -> Result<Option<Window>, String> {
if let Some(at) = a.num("--at")? {
return Ok(Some(Window { from: Some((at - 1.5).max(0.0)), to: Some(at + 1.5) }));
}
let (from, to) = (a.num("--from")?, a.num("--to")?);
Ok((from.is_some() || to.is_some()).then_some(Window { from, to }))
}
fn voice(v: Option<&str>) -> Result<Option<bool>, String> {
match v {
None => Ok(None),
Some("yes" | "true") => Ok(Some(true)),
Some("no" | "false") => Ok(Some(false)),
Some(v) => Err(format!("ask: --voice takes yes or no, got {v:?}")),
}
}
/// Pieces read once a run, by what they were read with.
type Pieces = HashMap<String, Arc<Piece>>;
#[allow(clippy::too_many_arguments)]
fn piece(pieces: &mut Pieces, file: &str, brief: Option<&str>, words: Option<&str>, voice: Option<bool>, state: Option<String>) -> Result<Arc<Piece>, String> {
let key = format!("{file}\u{1f}{brief:?}\u{1f}{words:?}\u{1f}{voice:?}\u{1f}{state:?}");
if let Some(p) = pieces.get(&key) {
return Ok(p.clone());
}
let p = Arc::new(Piece::read(Path::new(file), brief.map(Path::new), words.map(Path::new), voice, state).map_err(|e| format!("ask: {e}"))?);
pieces.insert(key, p.clone());
Ok(p)
}
fn entry(p: Arc<Piece>, window: Option<Window>, qs: Vec<Question>, with: Vec<PathBuf>, rubric: Option<&str>) -> Entry {
let (questions, dropped) = prepare::keep(qs, &p.facts(), rubric);
Entry { piece: p, window, questions, dropped, with }
}
/// The command line's one entry.
fn from_args(a: &Args, rubric: Option<&str>, pieces: &mut Pieces) -> Result<Vec<Entry>, String> {
let Some((file, words)) = a.words.split_first() else { return Err(USAGE.into()) };
let own = words.iter().map(|w| shaped(w, a)).collect::<Result<Vec<_>, _>>()?;
let qs = named(&own, &a.list("--set"), &a.list("--std"), rubric)?;
if qs.is_empty() {
return Err(format!("ask: nothing to ask: give a question in words, --set or --std (raea ask list)\nusage: {USAGE}"));
}
let p = piece(pieces, file, a.one("--brief"), a.one("--words"), voice(a.one("--voice"))?, a.one("--state").map(str::to_string))?;
let with = a.flags.get("--with").into_iter().flatten().map(PathBuf::from).collect();
Ok(vec![entry(p, window(a)?, qs, with, rubric)])
}
/// A batch: a JSON list of entries or JSON lines, from a file or stdin (`-`). Each entry is {file, window?, questions?
/// (words or questions), set?, std?, with?, brief?, words?, voice?, state?}.
fn from_batch(path: &str, rubric: Option<&str>, pieces: &mut Pieces) -> Result<Vec<Entry>, String> {
let text = match path {
"-" => {
let mut s = String::new();
std::io::stdin().read_to_string(&mut s).map_err(|e| format!("ask: stdin: {e}"))?;
s
}
p => std::fs::read_to_string(p).map_err(|e| format!("ask: {p}: {e}"))?,
};
let rows: Vec<Value> = match serde_json::from_str::<Value>(text.trim()) {
Ok(Value::Array(a)) => a,
Ok(v @ Value::Object(_)) => vec![v],
_ => text.lines().filter(|l| !l.trim().is_empty()).enumerate().map(|(i, l)| serde_json::from_str(l).map_err(|e| format!("ask: {path} line {}: {e}", i + 1))).collect::<Result<_, _>>()?,
};
let strs = |v: &Value| -> Vec<String> {
match v {
Value::String(s) => s.split(',').map(|s| s.trim().to_string()).collect(),
Value::Array(a) => a.iter().filter_map(Value::as_str).map(str::to_string).collect(),
_ => vec![],
}
};
let mut out = Vec::new();
for (n, r) in rows.iter().enumerate() {
let at = |e: String| format!("ask: {path} entry {}: {e}", n + 1);
let file = r["file"].as_str().ok_or_else(|| at("it has no file".into()))?;
let own = r["questions"].as_array().into_iter().flatten().map(|q| match q {
Value::String(w) => Ok(Question::plain(&own_id(w), w)),
q => serde_json::from_value::<Question>(q.clone()).map_err(|e| e.to_string()),
});
let own = own.collect::<Result<Vec<_>, _>>().map_err(at)?;
let qs = named(&own, &strs(&r["set"]), &strs(&r["std"]), rubric).map_err(at)?;
let window: Option<Window> = serde_json::from_value(r["window"].clone()).ok();
let v = voice(r["voice"].as_str()).map_err(at)?.or(r["voice"].as_bool());
let p = piece(pieces, file, r["brief"].as_str(), r["words"].as_str(), v, r["state"].as_str().map(str::to_string)).map_err(at)?;
out.push(entry(p, window, qs, strs(&r["with"]).into_iter().map(PathBuf::from).collect(), rubric));
}
Ok(out)
}
/// `raea ask list [SET]`: the standard questions.
fn list(a: &Args, rubric: Option<&str>) -> Result<String, String> {
let sets: Vec<String> = match a.words.get(1) {
Some(s) => vec![s.clone()],
None => library::SETS.iter().map(|s| s.to_string()).collect(),
};
let mut out = Vec::new();
let mine = calibrate::local();
for s in &sets {
let mut qs = library::set(s, rubric)?;
qs.iter_mut().for_each(|q| calibrate::apply(q, &mine));
if a.has("--json") {
out.push(json!({"set": s, "questions": qs}).to_string());
continue;
}
out.push(format!("{s}:"));
for q in qs {
let how = if q.calibrated() { "calibrated" } else { "advice" };
out.push(format!(" {:<28} {:<6} {:<10} {}", q.id, format!("{:?}", q.kind).to_lowercase(), how, q.ask));
}
}
Ok(out.join("\n"))
}
/// An event as a line of text.
fn line(e: &Event, files: usize) -> String {
match e {
Event::Would(v) => {
let qs: Vec<&str> = v["questions"].as_array().into_iter().flatten().filter_map(|q| q["id"].as_str()).collect();
let m = &v["media"];
let kb = |k: &str| m[k].as_array().map(|a| a.iter().filter_map(Value::as_u64).map(|b| format!("{} KB", b / 1024)).collect::<Vec<_>>().join(", ")).unwrap_or_default();
format!(
"would ask {} ({}) about {}:\n {}\n videos [{}], stills [{}], sounds [{}], about ${:.4}\n state: {}",
qs.len(),
span(v["from"].as_f64().unwrap_or(0.0), v["to"].as_f64()),
v["file"].as_str().unwrap_or(""),
qs.join(", "),
kb("videos"),
kb("stills"),
kb("sounds"),
v["estimate_usd"].as_f64().unwrap_or(0.0),
v["state"].as_str().unwrap_or("")
)
}
Event::Answer(a) => {
let who = if files > 1 { format!("{}: ", a.file) } else { String::new() };
let what = match (&a.says, &a.not_asked, &a.waits) {
(Some(s), ..) => format!("{s} [{}]{}", span(a.from, a.to), if a.flagged && a.calibrated { " <- finding" } else if a.flagged { " <- flagged" } else { "" }),
(_, Some(n), _) => format!("not asked: {n}"),
(.., Some(w)) => w.clone(),
_ => "no answer".into(),
};
format!("{who}{:<34} {what}", a.id)
}
}
}
/// `raea ask ...` with its exit code: 0, or 1 when it couldn't ask or a gate failed.
pub fn cli(args: &[String]) -> i32 {
match run(args) {
Ok(code) => code,
Err(e) => {
eprintln!("{e}");
1
}
}
}
fn run(args: &[String]) -> Result<i32, String> {
let a = Args::parse(args)?;
let rubric = rubric_md();
let jobs = a.one("--jobs").map(|j| j.parse::<usize>().map_err(|_| format!("ask: --jobs takes a number, got {j:?}"))).transpose()?.unwrap_or(4);
let sub = a.words.first().map(String::as_str).filter(|w| !Path::new(w).exists());
match sub {
Some("list") => {
println!("{}", list(&a, rubric.as_deref())?);
return Ok(0);
}
Some("verdict") => {
let [_, answer, said] = a.words.as_slice() else { return Err(format!("ask verdict ANSWER WORD: the answer's id (from --json or {}) and your answer to its question", record::dir().join("answers.jsonl").display())) };
println!("{}", labels::verdict(answer, said, a.one("--eye"))?);
return Ok(0);
}
Some("calibrate") => return calibrated(&a),
Some("try") => return tried(&a, jobs),
_ => {}
}
let mut pieces = Pieces::new();
let entries = match a.one("--batch") {
Some(b) => from_batch(b, rubric.as_deref(), &mut pieces)?,
None => from_args(&a, rubric.as_deref(), &mut pieces)?,
};
let (json_out, dry) = (a.has("--json"), a.has("--dry"));
let files = pieces.len();
let sum = runner::run(entries, &Opts::new(jobs, dry), &mut |e| {
match (&e, json_out) {
(Event::Answer(r), true) => println!("{}", serde_json::to_string(r).unwrap_or_default()),
(Event::Would(v), true) => println!("{}", json!({"would": v})),
(e, false) => println!("{}", line(e, files)),
}
});
if json_out {
println!("{}", json!({"summary": sum}));
} else if dry {
println!("{} call{}, about ${:.4}; nothing was sent", sum.calls, if sum.calls == 1 { "" } else { "s" }, sum.estimate);
} else if sum.calls > 0 {
let routes: Vec<&str> = sum.routes.iter().map(String::as_str).collect();
let left = sum.pool_left.map(|l| format!(", ${l:.2} left this month")).unwrap_or_default();
let waiting = if sum.waiting > 0 { format!("; {} wait for the pool", sum.waiting) } else { String::new() };
println!(
"asked {} question{} in {} call{} through {}: ${:.4}{left}{waiting}. Answers are advice until a question is calibrated (docs/ask.feature AK7).",
sum.asked,
if sum.asked == 1 { "" } else { "s" },
sum.calls,
if sum.calls == 1 { "" } else { "s" },
routes.join(" and "),
sum.cost
);
}
if !dry && sum.calls == 0 {
return Err("ask: nothing was asked (each question's line says why)".into());
}
// a gate fails on a flag (a calibrated one, or with `any` any), and on questions still waiting for the pool
let flagged = if a.gate_any { sum.flagged } else { sum.flagged_calibrated };
Ok(i32::from(a.has("--gate") && (flagged > 0 || sum.waiting > 0)))
}
/// A version's standing as a line, with its misses below when it doesn't separate.
fn standing_line(s: &calibrate::Standing) -> String {
let auc = s.auc.map_or_else(|| "no AUC".to_string(), |a| format!("AUC {a:.2}"));
let mut out = format!("{} ({}) \"{}\": {}, {auc} on {} labels; {}", s.id, &s.version[..8.min(s.version.len())], s.ask, s.state, s.problems + s.clean, s.why);
if s.others > 0 {
out += &format!(" ({} from other eyes, not counted)", s.others);
}
for m in &s.misses {
let what = if m.bad { "a problem it scored" } else { "clean work it scored" };
out += &format!("\n {what} {:.2}: {} ({}){}", m.problem, m.file, m.span, m.note.as_ref().map(|n| format!(" \"{n}\"")).unwrap_or_default());
}
out
}
/// `raea ask calibrate [ID]`: the feed's labels read again and each labelled question held to its labels.
fn calibrated(a: &Args) -> Result<i32, String> {
let (all, (yes, no)) = calibrate::calibrate(a.words.get(1).map(String::as_str))?;
if a.has("--json") {
println!("{}", json!({"feed": {"problems": yes, "clean": no}}));
all.iter().for_each(|s| println!("{}", serde_json::to_string(s).unwrap_or_default()));
return Ok(0);
}
println!("from the feed: {yes} note{} that saw a problem, {no} approval{} without one", if yes == 1 { "" } else { "s" }, if no == 1 { "" } else { "s" });
if all.is_empty() {
println!("no labelled questions yet: raea ask verdict ANSWER WORD labels one, and your notes on a posted render do too");
}
all.iter().for_each(|s| println!("{}", standing_line(s)));
Ok(0)
}
/// `raea ask try WORDS --like ID`: new words asked of a question's labelled clips, both held to the same labels.
fn tried(a: &Args, jobs: usize) -> Result<i32, String> {
let words = a.words[1..].join(" ");
let like = a.one("--like").ok_or("ask try WORDS --like ID: the question whose labelled clips the new words are asked of")?;
if words.trim().is_empty() {
return Err("ask try WORDS --like ID: the new words".into());
}
let json_out = a.has("--json");
let (sum, both) = calibrate::try_words(like, &words, &Opts::new(jobs, a.has("--dry")), &mut |e| match (&e, json_out) {
(Event::Would(v), true) => println!("{}", json!({"would": v})),
(Event::Answer(r), true) => println!("{}", serde_json::to_string(r).unwrap_or_default()),
(e, false) => println!("{}", line(e, 2)),
})?;
match (both, json_out) {
(None, true) => println!("{}", json!({"summary": sum})),
(None, false) => println!("{} call{}, about ${:.4}; nothing was sent", sum.calls, if sum.calls == 1 { "" } else { "s" }, sum.estimate),
(Some((old, new)), true) => println!("{}", json!({"summary": sum, "old": old, "new": new})),
(Some((old, new)), false) => println!("${:.4} for {} calls\nold words: {}\nnew words: {}", sum.cost, sum.calls, standing_line(&old), standing_line(&new)),
}
Ok(i32::from(!a.has("--dry") && sum.calls == 0))
}
+4 -4
View File
@@ -20,14 +20,14 @@ raea-io-ffmpeg = { path = "../../io/ffmpeg" }
raea-sys-measure = { path = "../../systems/measure" }
# what it reads of a video, through FFmpeg or raea's own decoders where it isn't installed
raea-app-check-read = { path = "read" }
# who can fix what it finds: the encode's or the picture's own, carried, a source (split out to keep this crate small)
# who can fix what it finds: the encode's or the picture's own, carried, a source
raea-app-check-cause = { path = "cause" }
# the text rules on a render's manifest (split out: raea render holds its own text to them)
raea-app-check-text = { path = "text" }
# the flashing screen (WCAG 2.3.1), split out to keep this crate small
# the flashing screen (WCAG 2.3.1)
raea-app-check-flash = { path = "flash" }
# what the person sent from the raea app, handed to the agent (split out to keep this crate small)
# what the person sent from the raea app, handed to the agent
raea-app-check-inbox = { path = "inbox" }
# the Stop gate for a `make` job (docs/goal.feature MK2; split out to keep this crate small)
# the Stop gate for a `make` job (docs/goal.feature MK2)
raea-app-check-make = { path = "make" }
serde_json = "1"
+1 -1
View File
@@ -53,7 +53,7 @@ pub fn luma(rgba: &[u8], width: usize, w: usize, h: usize) -> Vec<u8> {
}
/// `frames` as `comp` draws them, never encoded, as luma `w` x `h` (top-left): `raea render COMP --at F,... -o DIR/`
/// (PNG) run by `raea` from the project, kept out of its record as the quick check's stills are
/// (PNG) run by `raea` from the project, kept out of its record (RAEA_RECORD=off)
pub fn unencoded(raea: &Path, project: &Path, comp: &Path, frames: &[i64], w: usize, h: usize) -> R<Vec<Vec<u8>>> {
let mut wanted: Vec<i64> = frames.to_vec();
wanted.sort_unstable();
+1 -2
View File
@@ -1,5 +1,4 @@
//! 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).
//! The flashing screen behind `raea check` (apps/check flash.rs feeds it the decoded frames): a pure measure of pixels.
/// 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
+2 -2
View File
@@ -52,7 +52,7 @@ pub fn stop(v: &Value) -> Option<String> {
let cwd = PathBuf::from(v["cwd"].as_str()?);
let brief = brief_with_job(&cwd)?;
let exe = std::env::current_exe().ok()?;
let out = std::process::Command::new(exe).args(["goal", "check", "--at", "done", "--json"]).current_dir(brief.parent()?).env("RAEA_RECORD", "off").output().ok()?;
let out = std::process::Command::new(exe).args(["check", "--at", "done", "--json"]).current_dir(brief.parent()?).env("RAEA_RECORD", "off").output().ok()?;
let r: Value = serde_json::from_slice(&out.stdout).ok()?;
let home = raea_io_home::user_home()?;
let session = v["session_id"].as_str().unwrap_or("");
@@ -67,7 +67,7 @@ pub fn stop(v: &Value) -> Option<String> {
}
let goals: Vec<String> = r["goals"].as_array().into_iter().flatten().filter(|g| g["passed"] != true).filter_map(|g| g["name"].as_str().map(String::from)).collect();
let open = if goals.is_empty() { String::new() } else { format!("goal {}, ", goals.join(", ")) };
Some(format!("Not done ({open}{}): {items}. Keep going: `raea goal check` lists each with its fix; review/goal.json holds them all.", brief.display()))
Some(format!("Not done ({open}{}): {items}. Fix each in its composition and render it again (its check runs at the render's end): `raea check --at done` lists them with their fixes, and review/goal.json holds them all.", brief.display()))
}
/// The open items, one line each: each error-level finding (its check and file), then each check that broke.
+6 -37
View File
@@ -3,10 +3,10 @@
//! --agent A` adds them, and they hold inside the raea app too, which leaves each agent its own shell). Before a shell
//! command: media opened in the Mac's viewer or a browser is stopped once while the raea app is installed, the reason
//! naming `raea show`; the same command tried again goes through, so an agent that means it says so twice. After a
//! file is saved: `raea goal check --at edit` on a composition, or on a file under a brief. As a turn ends: `raea
//! goal check --at done` on the brief's goals (apps/check/make). After any tool, and as a turn ends: what the person sent from
//! the raea app (inbox.rs). A stop is exit 2 with the reason on stderr, which every harness hands its agent; the edit
//! moment's findings go back in the shape each one reads.
//! file is saved: nothing (docs/check.feature: a render checks its own output at its end). As a turn ends: `raea check
//! --at done` on the brief's goals (apps/check/make), which reads each deliverable's kept check. After any tool, and as
//! a turn ends: what the person sent from the raea app (inbox.rs). A stop is exit 2 with the reason on stderr, which
//! every harness hands its agent; what was sent goes back in the shape each one reads.
use serde_json::{Value, json};
use std::path::{Path, PathBuf};
@@ -114,23 +114,6 @@ pub fn steer(files: &[String]) -> String {
format!("raea: the raea app is installed here, so show this in it, not the Mac's viewer: `raea show {list}` (several stills make a storyboard; add --ask \"what you want from the person\"; inside the raea app, feed_post does the same). It brings the app's window up on it as an item the person can answer, and their answer comes to the inbox file it prints. If the Mac's viewer really is what's wanted (the person asked for it, or raea show can't), run the same command again and it goes through.")
}
/// The files a tool call saved: `file_path` or `path` (Claude Code, Kimi Code, Gemini CLI), or the files an apply_patch
/// adds or updates (Codex).
fn saved(v: &Value) -> Vec<String> {
let i = &v["tool_input"];
if let Some(p) = i["file_path"].as_str().or(i["path"].as_str()).or(i["absolute_path"].as_str()) {
return vec![p.to_string()];
}
let patch = i["command"].as_str().or(i["input"].as_str()).unwrap_or("");
patch.lines().filter_map(|l| ["*** Add File: ", "*** Update File: "].iter().find_map(|head| l.strip_prefix(head))).map(str::trim).map(String::from).collect()
}
/// Whether a saved file is held at the edit moment: a composition (a .tsx that registers a root), or any file under a
/// brief.ts
fn held_at_edit(p: &Path) -> bool {
(p.extension().is_some_and(|e| e == "tsx") && std::fs::read_to_string(p).is_ok_and(|t| t.contains("registerRoot"))) || p.parent().is_some_and(|d| raea_app_check_make::brief_with_job(d).is_some())
}
/// Findings for the agent in the shape its harness reads after a tool: Gemini CLI's AfterTool context, Kimi Code's
/// plain stdout, Claude Code's and Codex's PostToolUse context.
fn after(agent: &str, text: &str) -> String {
@@ -178,20 +161,8 @@ pub fn hook(args: &[String]) -> R<String> {
}
return Ok(String::new());
}
// the edit moment of the loop (docs/goal.feature MK33): `raea goal check FILE --at edit` on a saved composition, or
// on any file under a brief; a save that passes says nothing
let me = std::env::current_exe().map_err(|e| e.to_string())?;
let mut found = Vec::new();
for path in saved(&v).iter().filter(|p| held_at_edit(Path::new(p))) {
let dir = Path::new(path).parent().filter(|d| d.is_dir()).map(Path::to_path_buf).unwrap_or_else(|| PathBuf::from(v["cwd"].as_str().unwrap_or(".")));
let Ok(out) = std::process::Command::new(&me).args(["goal", "check", "--at", "edit"]).arg(path).current_dir(dir).env("RAEA_RECORD", "off").output() else { continue };
if out.status.code() == Some(1) {
found.extend(String::from_utf8_lossy(&out.stdout).lines().filter(|l| !l.starts_with("PASSED")).map(String::from));
}
}
let edit = (!found.is_empty()).then(|| format!("raea goal check --at edit after this save:\n{}", found.join("\n")));
let text = [sent, edit].into_iter().flatten().collect::<Vec<_>>().join("\n\n");
Ok(if text.is_empty() { String::new() } else { after(agent, &text) })
// no check after a save (docs/check.feature CK1): a render checks its own output at its end, once
Ok(sent.map(|t| after(agent, &t)).unwrap_or_default())
}
#[cfg(test)]
@@ -217,8 +188,6 @@ mod tests {
assert_eq!(agent_of(&json!({"hook_event_name": "PreToolUse", "tool_name": "Bash"})), "claude");
assert_eq!(shell_command(&json!({"tool_name": "shell_command", "tool_input": {"command": "open a.png"}})), Some("open a.png"));
assert_eq!(shell_command(&json!({"tool_name": "apply_patch", "tool_input": {"command": "*** Begin Patch\n"}})), None);
assert_eq!(saved(&json!({"tool_input": {"command": "*** Begin Patch\n*** Update File: a/E.tsx\n@@\n*** Add File: b.ts\n"}})), ["a/E.tsx", "b.ts"]);
assert_eq!(saved(&json!({"tool_input": {"path": "E.tsx"}})), ["E.tsx"]);
assert_eq!(after("kimi", "x"), "x");
assert!(after("gemini", "x").contains("AfterTool") && after("codex", "x").contains("PostToolUse"));
assert!(steer(&["a b.png".into()]).contains("`raea show \"a b.png\"`"));
+3 -4
View File
@@ -1,4 +1,4 @@
//! `raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--things T.json] [--shape 9:16]
//! `raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--shape 9:16]
//! [--platform tiktok|reels|shorts] [-o check.json]`: the floor's measurable lines on an export (docs/craft-system.md, I; sdk/guides/craft/floor.md).
//! Each issue is ranked P0 (breaks the piece) to P3 (polish), with where it is and what to do. Rules on the file alone:
//! loudness and true peak, a steady sound that stops dead (a source run out, a cut with no fade), stretches where nothing
@@ -28,7 +28,6 @@ use raea_app_check_text::*;
use raea_app_check_cause as cause;
/// a video read through FFmpeg, or raea's own decoders where it isn't installed
use raea_app_check_read::{self as read, Probe};
pub mod quick;
pub mod hook;
pub use raea_app_check_inbox as inbox;
#[cfg(test)]
@@ -66,7 +65,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] [--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)";
pub const USAGE: &str = "raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--shape 16:9|9:16|4:5|1:1] [--platform tiktok|reels|shorts] [-o check.json] (an export against the floor: clipped text, contrast, safe areas, freezes, flashing, cues, loudness, blotching, a placeholder brand kit; its findings errors, warns and notes)";
/// 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)]
@@ -116,7 +115,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; 8] = ["--manifest", "--words", "--perception", "--things", "--shape", "--platform", "--taste", "-o"];
const TAKES: [&str; 6] = ["--manifest", "--words", "--perception", "--shape", "--platform", "-o"];
fn run(args: &[String], tastes: Vec<raea_core_brief::Taste>) -> R<(String, bool)> {
let (video, issues, passed, fps) = measured(args, taste_rules(&tastes))?;
+18 -5
View File
@@ -15,6 +15,16 @@ pub(crate) const MOST: f32 = 4.0;
pub(crate) const RUN: usize = 4;
pub(crate) const BACK: usize = 4;
pub(crate) const BLOTCHY: f64 = 0.009;
/// The least blotching an encoder's patches have been measured at (the VideoToolbox exports' 0.012): a score between
/// BLOTCHY and this, whose cause can't be told, is a warning, never an error (12-05: a 3D shot rendered at master
/// quality read 0.010, from its shadows' own dithered edge, and was an error whose fix, master quality, it already had)
pub(crate) const BLOTCHED: f64 = 0.012;
/// How a finding whose cause can't be told stands: an error when more than a fifth of the samples blotch and the worst
/// is past BLOTCHED, else a warning
pub(crate) fn untold_level(share: f64, worst: f64) -> u8 {
if share > 0.2 && worst >= BLOTCHED { 1 } else { 2 }
}
pub(crate) fn blotch_score(y: &[u8], w: usize, h: usize) -> Option<f64> {
let (bw, bh) = (w / 8, h / 8);
@@ -190,8 +200,8 @@ pub(crate) fn blotching_from(video: &str, probe: &Probe, scores: &[Option<f64>],
let own = if a.0.before > 0 { format!("; {} of the samples show the footage's own too, which stays", a.0.before) } else { String::new() };
(if a.0.worse as f64 / a.0.of.max(1) as f64 > 0.2 { 1 } else { 2 }, first.or(Some(at)), format!("the encode added blocky patches in dark areas: {} of {} samples are blotchier than the composition draws them unencoded; render with --quality master, which gives the darks the bits they need{own}", a.0.worse, a.0.of))
}
Some(Err(why)) => (if share > 0.2 { 1 } else { 2 }, Some(at), format!("{found}; whether the encode made them or the picture holds them couldn't be told ({why}): render with --quality master if the encode starved the darks")),
None => (if share > 0.2 { 1 } else { 2 }, Some(at), format!("{found}: the encode starved the near-blacks, or the footage holds them; render with --quality master, and check a render made in a raea project to tell which")),
Some(Err(why)) => (untold_level(share, worst), Some(at), format!("{found}; whether the encode made them or the picture holds them couldn't be told ({why}): render with --quality master if the encode starved the darks")),
None => (untold_level(share, worst), Some(at), format!("{found}: the encode starved the near-blacks, or the footage holds them; render with --quality master, and check a render made in a raea project to tell which")),
};
issues.push(Issue { rule: "blotching", p, at, says });
} else if seen > 0 {
@@ -213,12 +223,15 @@ pub(crate) fn contrast(video: &str, runs: &[Run], w: f64, h: f64, probe: &Probe,
continue;
}
// the same measure `raea world` joins to a text from its render (raea-sys-measure, DR2)
let ratio = if crate::read::native() { crate::read::contrast(video, t, crop, &r.color) } else { raea_sys_measure::contrast(std::path::Path::new(video), t, crop, &r.color) };
let Some(ratio) = ratio else { continue };
// each colour its words are drawn in (an accent word's beside the line's), held to the lowest
let measure = |color: &str| if crate::read::native() { crate::read::contrast(video, t, crop, color) } else { raea_sys_measure::contrast(std::path::Path::new(video), t, crop, color) };
let worst = r.middle_inks().into_iter().filter_map(|c| measure(c).map(|v| (v, c))).min_by(|a, b| a.0.total_cmp(&b.0));
let Some((ratio, color)) = worst else { continue };
let word = if color == r.middle_color() { String::new() } else { format!(" (its words in {color})") };
measured += 1;
if ratio < 3.0 {
low += 1;
issues.push(Issue { rule: "contrast", p: 1, at: Some(t), says: format!("{} is {ratio:.1}:1 against what's behind it; make it at least 3:1 (a band, a shadow for separation, or another colour)", quote(&r.text)) });
issues.push(Issue { rule: "contrast", p: 1, at: Some(t), says: format!("{}{word} is {:.2}:1 against what's behind it; make it at least 3:1 (a band, a shadow for separation, or another colour)", quote(&r.text), (ratio * 100.0).floor() / 100.0) });
}
}
if measured > 0 && low == 0 {
-75
View File
@@ -1,75 +0,0 @@
//! `raea check EDIT.tsx --quick` (docs/skills.feature SK10). The quick check renders three stills of a composition (a
//! quarter in, the middle, the last frame, of the length frame 0's render reports) with their manifest, and runs the text rules
//! and the person's text taste on it: clipped and cramped text, safe areas, sizes. Every agent's after-save hook runs
//! it (hook.rs): after a .tsx that registers a root is saved, its findings go back to the agent; a clean check says
//! nothing.
use super::*;
use std::path::Path;
/// The stills' frames: a quarter in, the middle and the last of the length a render reports (render.json's `length`,
/// the composition's own however it's written; #86 read its source's `durationInFrames={N}` and took 90 for a name).
fn samples(m: &Value) -> Option<[u64; 3]> {
let n = m["length"].as_u64()?.max(1);
Some([n / 4, n / 2, n - 1])
}
/// `raea check EDIT.tsx --quick [--shape S] [--platform P] [-o check.json]`: (report, P0 or P1 found). `tastes` are the
/// person's, evaluated by the raea CLI when --taste names them.
pub fn quick(args: &[String], tastes: Vec<raea_core_brief::Taste>) -> R<(String, bool)> {
let file = args.iter().find(|a| a.ends_with(".tsx")).ok_or("raea check --quick takes a composition: EDIT.tsx")?;
let tmp = std::env::temp_dir().join(format!("raea-quick-{}", std::process::id()));
std::fs::create_dir_all(&tmp).map_err(|e| format!("{}: {e}", tmp.display()))?;
let manifest = tmp.join("render.json");
let me = std::env::current_exe().map_err(|e| e.to_string())?;
// the stills are part of this check, which keeps the one entry in the project's record (DR3)
let render = |at: &str| std::process::Command::new(&me).arg("render").arg(file).args(["--at", at, "-o"]).arg(format!("{}/", tmp.display())).arg("--manifest").arg(&manifest).env("RAEA_RECORD", "off").output().map_err(|e| e.to_string());
// frame 0 first, for the length (its manifest's), then the three stills
let mut out = render("0")?;
let at = std::fs::read_to_string(&manifest).ok().and_then(|t| samples(&serde_json::from_str(&t).ok()?));
if let Some(at) = at {
let _ = std::fs::remove_file(&manifest);
out = render(&at.map(|f| f.to_string()).join(","))?;
}
// rendered when its manifest was written: a render whose stills clip exits 1 (DR3), and those findings are read here
let result = if let (Some(at), true) = (at, manifest.is_file()) {
on_manifest(file, &manifest, args, tastes, at)
} else {
// a render that fails is the finding: the agent sees why
let (err, out) = (String::from_utf8_lossy(&out.stderr), String::from_utf8_lossy(&out.stdout));
let why: Vec<&str> = err.lines().chain(out.lines()).filter(|l| l.contains("REFUSED") || l.contains("rror")).collect();
let f = raea_core_facts::Finding::new("render", raea_core_facts::Level::Error, why.join("\n"), "raea check --quick");
Ok((format!("raea check {file}: it doesn't render\n{}\nraea check: {}", f.line(), raea_core_facts::finding::count(&[f])), true))
};
let _ = std::fs::remove_dir_all(&tmp);
result
}
/// `raea check --quick`'s half (docs/skills.feature SK10): the text rules and the person's text taste on the manifest
/// of a few stills (`raea render EDIT.tsx --at ... --manifest`), no video. What it can't see (contrast, freezes,
/// sound, blotching) waits for the full check on the export.
fn on_manifest(file: &str, manifest: &Path, args: &[String], tastes: Vec<raea_core_brief::Taste>, [a, b, c]: [u64; 3]) -> R<(String, bool)> {
let at = manifest.display();
let m: Value = serde_json::from_str(&std::fs::read_to_string(manifest).map_err(|e| format!("{at}: {e}"))?).map_err(|e| format!("{at}: {e}"))?;
let (mut issues, mut passed) = (Vec::new(), vec![format!("looked at frames {a}, {b} and {c} of {}", c + 1)]);
let runs = text_runs(&m);
let (w, h) = (m["width"].as_f64().unwrap_or(1080.0), m["height"].as_f64().unwrap_or(1920.0));
text_rules(&runs, None, w, h, flag(args, "--shape"), flag(args, "--platform"), &mut issues, &mut passed);
taste_text(&taste_rules(&tastes), &runs, w, h, &mut issues, &mut passed);
// and what the render of the stills found (the 3D's clipping, DR3)
let more = serde_json::from_value(m["findings"].clone()).unwrap_or_default();
report(file, issues, more, passed, flag(args, "-o"), m["fps"].as_f64().unwrap_or(30.0))
}
#[cfg(test)]
mod tests {
use serde_json::json;
/// the length is the render's, so a `durationInFrames={DUR}` (#86: 300 frames, read as 90) is sampled to its end
#[test]
fn frames_come_from_the_render() {
assert_eq!(super::samples(&json!({"length": 240})), Some([60, 120, 239]));
assert_eq!(super::samples(&json!({"length": 300})), Some([75, 150, 299]));
assert_eq!(super::samples(&json!({"length": 1})), Some([0, 0, 0]));
// a render that reported no length: no stills to look at, so the frame-0 render's failure is the finding
assert_eq!(super::samples(&json!({"width": 640})), None);
}
}
+15 -13
View File
@@ -22,7 +22,7 @@ fn a_placeholder_brand_kit_is_flagged() {
brand_kit(&["", video.to_str().unwrap()], &mut issues, &mut passed);
(issues.iter().map(|i| i.p).collect::<Vec<_>>(), passed.len())
};
assert_eq!(rules(Some(r#"{"domain":"acme.test","source":{"thin":["no font-family in its CSS"]}}"#)), (vec![1], 0));
assert_eq!(rules(Some(r#"{"domain":"acme.test","source":{"thin":["no font-family in its CSS"]}}"#)), (vec![2], 0));
assert_eq!(rules(Some(r#"{"domain":"acme.test","source":{"thin":["x"],"by_hand":{"palette.accent":"hero button"}}}"#)), (vec![], 1));
assert_eq!(rules(Some(r#"{"domain":"acme.test","source":{"thin":[]}}"#)), (vec![], 1));
assert_eq!(rules(None), (vec![2], 0));
@@ -51,6 +51,10 @@ fn flat_dark_is_clean_and_stepped_dark_is_blotchy() {
(20.0 - (x * x + y * y).sqrt() / 24.0).max(6.0) as u8
}).collect();
assert!(blotch_score(&rings, w, h).unwrap() < BLOTCHY / 2.0);
// a cause that can't be told: an error only past an encoder's measured blotching, on more than a fifth of samples
assert_eq!(untold_level(1.0, 0.010), 2);
assert_eq!(untold_level(1.0, 0.09), 1);
assert_eq!(untold_level(0.1, 0.09), 2);
assert_eq!(x264_crf(b"..\x05x264 - core 165 r3222 - H.264/MPEG-4 AVC codec - options: cabac=1 rc=crf mbtree=1 crf=12.0 qcomp=0.60"), Some(12.0));
assert_eq!(x264_crf(b"Lavf61 VideoToolbox"), None);
}
@@ -67,8 +71,8 @@ fn taste_checks_hold_text_to_the_persons_line() {
Taste { form: "text-above", value: 62.0, line: "Captions sit clear of the bottom.".into() },
Taste { form: "text-hold", value: 2.0, line: "Text holds two seconds".into() },
]);
let low = Run { text: "Render anything.".into(), from: 1.0, to: 4.0, box_: [800.0, 800.0, 300.0, 60.0], boxes: vec![[800.0, 800.0, 300.0, 60.0]], color: String::new(), size: 48.0 };
let high = Run { text: "raea".into(), from: 5.0, to: 6.0, box_: [800.0, 300.0, 300.0, 60.0], boxes: vec![[800.0, 300.0, 300.0, 60.0]], color: String::new(), size: 48.0 };
let low = Run { text: "Render anything.".into(), from: 1.0, to: 4.0, box_: [800.0, 800.0, 300.0, 60.0], boxes: vec![[800.0, 800.0, 300.0, 60.0]], colors: vec![], inks: vec![], color: String::new(), size: 48.0 };
let high = Run { text: "raea".into(), from: 5.0, to: 6.0, box_: [800.0, 300.0, 300.0, 60.0], boxes: vec![[800.0, 300.0, 300.0, 60.0]], colors: vec![], inks: vec![], color: String::new(), size: 48.0 };
let (mut issues, mut passed) = (vec![], vec![]);
taste_text(&rules, &[low, high], 1920.0, 1080.0, &mut issues, &mut passed);
let says: Vec<_> = issues.iter().map(|i| (i.rule, i.p, i.at)).collect();
@@ -185,15 +189,14 @@ fn a_bed_close_under_the_voice_and_a_loud_stretch_without_it_are_found() {
}
#[test]
fn the_floor_and_placement_state_the_zones_check_measures() {
// zones() is where the numbers live; floor.md and placement.md say them in words, held to it here
fn placement_states_the_zones_check_measures() {
// zones() is where the numbers live; placement.md says them in words, held to it here
let words = |t: &str| t.split_whitespace().collect::<Vec<_>>().join(" ");
let floor = words(include_str!("../../../sdk/guides/craft/floor.md"));
let placement = words(include_str!("../../../sdk/guides/craft/motion/placement.md"));
let n = |v: f64| format!("{v:.0}");
let [t, r, b, l] = zones(1080.0, 1920.0, Some("9:16"), None);
let said = [
format!("keep the top {} px, the bottom {}, the right {} and the left {} clear", n(t), n(b), n(r), n(l)),
format!("that is top {}, bottom {}, right {} and left {} px at 1080 wide", n(t), n(b), n(r), n(l)),
["tiktok", "reels", "shorts"].map(|p| {
let [t, r, b, _] = zones(1080.0, 1920.0, Some("9:16"), Some(p));
let name = match p { "tiktok" => "TikTok", "reels" => "Reels", _ => "Shorts" };
@@ -204,10 +207,8 @@ fn the_floor_and_placement_state_the_zones_check_measures() {
{ let [t, r, b, l] = zones(1920.0, 1080.0, Some("16:9"), None); assert!(t == b && r == l); format!("16:9 top and bottom {}, sides {}", n(t), n(r)) },
];
for s in &said {
assert!(floor.contains(s.as_str()), "floor.md doesn't say {s:?}");
assert!(placement.contains(s.as_str()), "placement.md doesn't say {s:?}");
}
let s = format!("that is top {}, bottom {}, right {} and left {} px at 1080 wide", n(t), n(b), n(r), n(l));
assert!(placement.contains(&s), "placement.md doesn't say {s:?}");
}
#[test]
@@ -267,7 +268,7 @@ fn typing_is_one_run_and_cues_find_their_word() {
#[test]
fn a_caption_is_timed_from_the_first_word_it_shows() {
let run = |text: &str, from: f64| Run { text: text.into(), from, to: from + 1.0, box_: [0.0; 4], boxes: vec![], color: String::new(), size: 48.0 };
let run = |text: &str, from: f64| Run { text: text.into(), from, to: from + 1.0, box_: [0.0; 4], boxes: vec![], colors: vec![], inks: vec![], color: String::new(), size: 48.0 };
let words: Vec<Word> = [("half", 12.2), ("of", 12.66), ("the", 12.8), ("spend", 12.96)].iter().map(|(t, s)| Word { text: (*t).into(), start: *s, end: *s }).collect();
let (mut issues, mut passed) = (vec![], vec![]);
// on with "of": on time, though "spend" (its first word of weight) is said 0.3 s later
@@ -335,7 +336,7 @@ fn safe_area_tests_the_letters_not_the_box() {
#[test]
fn a_card_sharing_one_word_with_another_line_isnt_held_to_it() {
let run = |text: &str, from: f64| Run { text: text.into(), from, to: from + 2.0, box_: [0.0; 4], boxes: vec![], color: String::new(), size: 48.0 };
let run = |text: &str, from: f64| Run { text: text.into(), from, to: from + 2.0, box_: [0.0; 4], boxes: vec![], colors: vec![], inks: 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![]);
@@ -425,10 +426,11 @@ fn things_found_are_findings_and_an_unknown_rule_is_not() {
#[test]
fn a_moving_text_is_read_where_it_is() {
let ink = |f: usize| [56.7 + 4.0 * f as f64, 1000.0, 26.7, 40.0];
let run = Run { text: "E".into(), from: 0.0, to: 8.0, box_: [996.0, 1000.0, 60.0, 40.0], boxes: (0..240).map(ink).collect(), color: String::new(), size: 40.0 };
let run = Run { text: "E".into(), from: 0.0, to: 8.0, box_: [996.0, 1000.0, 60.0, 40.0], boxes: (0..240).map(ink).collect(), colors: vec![], inks: vec![], color: String::new(), size: 40.0 };
let (t, b) = run.middle(30.0);
assert_eq!(t, 4.0);
assert!((b[0] - 520.0).abs() < 1e-9 && b[1..] == [1000.0, 60.0, 40.0], "{b:?}");
let still = Run { boxes: vec![ink(0); 240], box_: [40.0, 1000.0, 60.0, 40.0], ..run };
assert_eq!(still.middle(30.0), (4.0, [40.0, 1000.0, 60.0, 40.0]));
}
+95 -7
View File
@@ -43,6 +43,13 @@ pub struct Run {
/// 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 boxes: Vec<[f64; 4]>,
/// its colour on each of those frames, beside `boxes`: a text can change colour while it reads the same (a step
/// chip lighting up, grey on dark to dark on yellow), and its contrast is its colour on the frame it's measured at
pub colors: Vec<String>,
/// the colours its words are drawn in on each of those frames, beside `colors`, when any differs from the line's (the
/// manifest's `inks`: a caption's accent word); empty when every word is in the line's colour
pub inks: Vec<Vec<String>>,
/// its colour on its last frame
pub color: String,
pub size: f64,
}
@@ -57,11 +64,36 @@ impl Run {
let (at, [x, y, w, h]) = (self.boxes[n / 2], self.box_);
(self.to - (n - n / 2) as f64 / fps, [x + at[0] - last[0], y + at[1] - last[1], w, h])
}
/// Its colour on the frame `middle` measures: the one it had there, not the one it ended with.
pub fn middle_color(&self) -> &str {
let n = self.boxes.len();
match self.colors.get(n / 2) {
Some(c) if n > 1 && self.colors.len() == n => c,
_ => &self.color,
}
}
/// Every colour its words are drawn in on that frame: the line's, and an accent span's beside it (12-06: a line
/// recorded only by its own colour hid a dark word on a dark plate)
pub fn middle_inks(&self) -> Vec<&str> {
let n = self.boxes.len();
let mut all = vec![self.middle_color()];
let at = if n > 1 && self.inks.len() == n { self.inks.get(n / 2) } else { self.inks.last() };
for i in at.into_iter().flatten() {
if !all.contains(&i.as_str()) {
all.push(i);
}
}
all
}
}
/// The brand kit the cut was styled from (brand/ at or above the manifest's or the video's folder, as render finds
/// brand.css): a kit `raea brand` read from a thin fetch that nobody corrected by hand is a placeholder, P1; a brand.css
/// with no brand.json beside it wasn't read from the brand at all, P2
/// brand.css): a kit `raea brand` read from a thin fetch that nobody corrected by hand is a placeholder, and a brand.css
/// with no brand.json beside it wasn't read from the brand at all, both P2: where a kit came from is a note for the person
/// at sign-off, not a fault in the cut (12-05, run 39: all four of Body Shop's cuts held an error for a fetch of the
/// brand's site that read 40 of its 95 colour and face variables)
pub fn brand_kit(near: &[&str], issues: &mut Vec<Issue>, passed: &mut Vec<String>) {
let mut seen = std::collections::HashSet::new();
for start in near.iter().filter(|p| !p.is_empty()) {
@@ -82,7 +114,7 @@ pub fn brand_kit(near: &[&str], issues: &mut Vec<Issue>, passed: &mut Vec<String
let thin: Vec<&str> = kit["source"]["thin"].as_array().map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default();
let by_hand = kit["source"]["by_hand"].as_object().is_some_and(|o| !o.is_empty());
if !thin.is_empty() && !by_hand {
issues.push(Issue { rule: "brand", p: 1, at: None, says: format!("styled from a placeholder kit: raea brand's fetch of {} was thin ({}) and nothing in brand.json's source.by_hand says it was checked; read the live site in a browser and fix the kit (raea guide brand, \"When the fetch was thin\")", kit["domain"].as_str().unwrap_or("the site"), thin.join("; ")) });
issues.push(Issue { rule: "brand", p: 2, at: None, says: format!("styled from a placeholder kit: raea brand's fetch of {} was thin ({}) and nothing in brand.json's source.by_hand says it was checked; read the live site in a browser and fix the kit (raea guide brand, \"When the fetch was thin\")", kit["domain"].as_str().unwrap_or("the site"), thin.join("; ")) });
} else {
passed.push(format!("brand: the cut is styled from {}'s kit{}", kit["domain"].as_str().unwrap_or("the brand"), if by_hand { ", checked by hand" } else { "" }));
}
@@ -114,18 +146,24 @@ pub fn text_runs(manifest: &Value) -> Vec<Run> {
});
let mut r = match found {
Some(i) => open.remove(i),
None => Run { text: text.clone(), from: t, to: t, box_: b, boxes: Vec::new(), color: String::new(), size: 0.0 },
None => Run { text: text.clone(), from: t, to: t, box_: b, boxes: Vec::new(), colors: Vec::new(), inks: Vec::new(), color: String::new(), size: 0.0 },
};
let color = x["color"].as_str().unwrap_or("rgb(255, 255, 255)").to_string();
let inks: Vec<String> = x["inks"].as_array().map(|a| a.iter().filter_map(Value::as_str).map(String::from).collect()).unwrap_or_default();
if text.len() > r.text.len() {
r.boxes.clear();
r.colors.clear();
r.inks.clear();
}
if text.len() >= r.text.len() {
r.text = text;
r.box_ = b;
r.boxes.push(ink.unwrap_or(b));
r.colors.push(color.clone());
r.inks.push(inks);
}
r.to = t + 1.0 / fps;
r.color = x["color"].as_str().unwrap_or("rgb(255, 255, 255)").to_string();
r.color = color;
r.size = x["size"].as_f64().unwrap_or(0.0);
next.push(r);
}
@@ -176,7 +214,11 @@ pub fn face_cover(runs: &[Run], faces: &[(f64, f64, [f64; 4])], issues: &mut Vec
}
}
/// the zones where text can't go, as [top, right, bottom, left] at 1080 wide (sdk/guides/craft/floor.md)
/// The app's right-hand buttons start this far down the frame (sdk/video/src/zones.ts RAIL): the right zone is under it.
/// 12-05: a centred end card at 35% down was an error for the right zone, where no app draws anything.
pub const RAIL: f64 = 0.45;
/// the zones where text can't go, as [top, right, bottom, left] at 1080 wide (sdk/guides/craft/motion/placement.md)
pub fn zones(w: f64, h: f64, shape: Option<&str>, platform: Option<&str>) -> [f64; 4] {
let r = w / h;
let shape = shape.unwrap_or(if r < 0.7 { "9:16" } else if r < 0.9 { "4:5" } else if r < 1.2 { "1:1" } else { "16:9" });
@@ -208,7 +250,8 @@ pub fn text_rules(runs: &[Run], heard: Option<&[Word]>, w: f64, h: f64, shape: O
let [x, y, bw, bh] = r.box_;
let q = quote(&r.text);
let off = |&[x, y, bw, bh]: &[f64; 4]| x < -1.0 || y < -1.0 || x + bw > w + 1.0 || y + bh > h + 1.0;
let zoned = |&[x, y, bw, bh]: &[f64; 4]| y < zt || x + bw > w - zr || y + bh > h - zb || x < zl;
// the right zone is the app's buttons, which start RAIL down the frame: above them the right edge is clear
let zoned = |&[x, y, bw, bh]: &[f64; 4]| y < zt || (x + bw > w - zr && y + bh > RAIL * h) || y + bh > h - zb || x < zl;
if r.boxes.iter().all(off) {
clipped += 1;
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") });
@@ -294,3 +337,48 @@ pub fn cues(runs: &[Run], words: &[Word], issues: &mut Vec<Issue>, passed: &mut
passed.push(format!("cues: {checked} texts land on their words"));
}
}
#[cfg(test)]
mod tests {
/// The right zone is the app's buttons, from RAIL down: a centred end card above them is clear (12-05, an end card 35%
/// down was an error); the same card over the buttons isn't.
#[test]
fn the_right_zone_starts_where_the_apps_buttons_do() {
let right = |y: f64| {
let m = serde_json::json!({"fps": 1.0, "frames": [{"frame": 0, "text": [{"text": "THE BODY SHOP", "box": [134.0, y, 812.0, 112.0]}]}]});
let (mut issues, mut passed) = (vec![], vec![]);
text_rules(&text_runs(&m), None, 1080.0, 1920.0, None, None, &mut issues, &mut passed);
issues.into_iter().filter(|i| i.rule == "safe-area").map(|i| i.says).collect::<String>()
};
assert_eq!(right(682.0), "");
assert!(right(1290.0).contains("at the right (keep 140 px clear)"), "{}", right(1290.0));
}
use super::*;
use serde_json::json;
#[test]
fn a_text_that_lights_up_is_measured_in_its_colour_at_the_middle() {
// a step chip: grey on dark for six frames, then dark on yellow for four (the same words)
let m = json!({"fps": 10.0, "frames": (0..10).map(|f| json!({"frame": f, "text": [
{"text": "03 MAP", "box": [500, 120, 130, 52], "size": 23, "color": if f < 6 { "rgb(169, 169, 174)" } else { "rgb(10, 10, 11)" }}
]})).collect::<Vec<_>>()});
let runs = text_runs(&m);
assert_eq!(runs.len(), 1);
assert_eq!(runs[0].color, "rgb(10, 10, 11)", "its last colour");
assert_eq!(runs[0].middle_color(), "rgb(169, 169, 174)", "the frame contrast measures is still grey");
}
#[test]
fn a_line_with_an_accent_word_is_measured_in_both_colours() {
// a white caption with one word in dark red: the manifest's line colour alone hid the red word
let m = json!({"fps": 10.0, "frames": (0..4).map(|f| json!({"frame": f, "text": [
{"text": "Stay out longer.", "box": [100, 1400, 880, 90], "size": 84, "color": "rgb(255, 255, 255)", "inks": ["rgb(255, 255, 255)", "rgb(120, 0, 0)"]}
]})).collect::<Vec<_>>()});
let runs = text_runs(&m);
assert_eq!(runs[0].middle_inks(), vec!["rgb(255, 255, 255)", "rgb(120, 0, 0)"]);
// a line drawn in its own colour only has no inks, and is measured in that colour alone
let plain = json!({"fps": 10.0, "frames": [{"frame": 0, "text": [{"text": "raea", "box": [0, 0, 10, 10], "size": 40, "color": "rgb(1, 2, 3)"}]}]});
assert_eq!(text_runs(&plain)[0].middle_inks(), vec!["rgb(1, 2, 3)"]);
}
}
+2 -2
View File
@@ -18,10 +18,10 @@ use crate::ts;
type R<T> = Result<T, String>;
pub const USAGE: &str = "raea check [PROJECT|EDIT.tsx] [--composition ID] [--only ID] [--taste T] [--render OUT | --no-render] [--json] (every check that applies to each composition, over its frames: raea's floor on its newest render, the person's, the workspace's and the project's taste.ts (each line's check: one of raea's forms or checks by name, or a project's .ts check); what needs a render and has none waits, and says so)";
pub const USAGE: &str = "raea check [PROJECT|EDIT.tsx] [--composition ID] [--only ID] [--render OUT | --no-render] [--json] (every check that applies to each composition, over its frames: raea's floor on its newest render, the person's, the workspace's and the project's taste.ts (each line's check: one of raea's forms or checks by name, or a project's .ts check); what needs a render and has none waits, and says so)";
/// The flags raea check takes with a value (its own, and the floor's on a video).
const TAKES: [&str; 10] = ["--composition", "--only", "--taste", "--render", "--manifest", "--words", "--perception", "--shape", "--platform", "-o"];
const TAKES: [&str; 9] = ["--composition", "--only", "--render", "--manifest", "--words", "--perception", "--shape", "--platform", "-o"];
/// What the CLI lends `raea check`: its TS evaluator and headless run, and the taste kinds a mode needs (as `raea
/// context` reads the person's taste).
+1 -1
View File
@@ -61,7 +61,7 @@ pub fn rendered(args: &[String]) -> i32 {
let _ = std::fs::write(&m, v.to_string());
}
}
// a render that is part of another (a review's tiles, a quick check's stills) leaves the entry to that one
// a render that is part of another (a review's tiles) leaves the entry to that one
let file = args.get(1).filter(|a| !a.starts_with('-') && std::env::var("RAEA_RECORD").as_deref() != Ok("off")).map(PathBuf::from);
if let Some(e) = file.and_then(|f| record::keep("raea render", &f, out.as_deref(), &found, excused, &raea_io_trace::utc(SystemTime::now()).1)) {
println!("raea render: kept in the project's record as {} (raea findings reads it)", e.id);
+1 -1
View File
@@ -35,7 +35,7 @@ pub struct Double {
pub problem: Option<f64>,
/// clef agrees: past even odds, or past the question's threshold once the person's labels calibrated it
pub agrees: Option<bool>,
/// its answer's id in raea ask's record, for `raea ask verdict`
/// its answer's id in the ask record (~/.raea/ask/answers.jsonl)
pub answer: Option<String>,
/// why it wasn't asked or still waits
pub not_asked: Option<String>,
+2
View File
@@ -15,6 +15,8 @@ raea-sys-fingerprint = { path = "../../systems/fingerprint" }
raea-sys-fingerprint-use = { path = "../../systems/fingerprint-use" }
# score --ask: each flag asked again of the decision model (docs/ask.feature AK8)
raea-app-double = { path = "../double" }
# the critic a note is read by: a fresh session of the project's own agent (critic.rs)
raea-io-clef = { path = "../../io/clef" }
raea-sys-fingerprint-things = { path = "../../systems/fingerprint-things" }
# the encoders and the columns they make
raea-sys-columns = { path = "../../systems/columns" }
+2 -3
View File
@@ -21,13 +21,13 @@ use std::path::Path;
pub use serve::serve;
pub const USAGE: &str = "raea fingerprint new NAME [--who W] [--about TEXT] [--extends FP] [--kinds K,K] [--tags T,T] | raea fingerprint bootstrap FILE... [--from LIST] [--per N] | raea fingerprint teach FILE --axis A --at T [--bad|--good] [--span S] [--box x0,y0,x1,y1] [--words W] [--project P] | raea fingerprint approve FILE... [--project P] | raea fingerprint pair WORSE BETTER --axis A [--at T] [--then T2] | raea fingerprint versions V1 V2... | raea fingerprint profile REFS... --as NAME [--against LIST] | raea fingerprint score FILE [--was OLD] [--ask flags|unsure] [--json] [--sheet out.png] [--timeline] [--profile NAME] | raea fingerprint report [--json] | raea fingerprint which [PATH] [--json] | raea fingerprint use NAME [--in project|workspace] [PATH] | raea fingerprint diff A B [--json] | raea fingerprint share NAME [--in project|workspace] [PATH] | raea fingerprint reembed PLACE... | raea fingerprint read PROJECT [--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), and with --ask flags each flag put to clef again on its own window, whether clef agrees said beside it and kept as clef's evidence (unsure: the moments it's unsure of too); profile takes the ranges of work you admire (loudness, tilt, cut rate, motion, brightness, contrast, saturation, sharpness), checked leave-one-out, and score --profile says what falls outside them, where and which way; report says each head's held-out score, labels, cheats, gate and what it can't judge; which says the one that judges a piece (its project's, its workspace's, then yours) and why, use pins one there, diff lists the axes two fingerprints rank the same evidence most differently on, and share copies one's taxonomy and evidence (no heads, no media) into a project or workspace for its team; reembed moves a fingerprint's evidence to this machine's encoders, re-embedding the rows whose media it finds; read has a fresh 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)";
pub const USAGE: &str = "raea fingerprint new NAME [--who W] [--about TEXT] [--extends FP] [--kinds K,K] [--tags T,T] | raea fingerprint bootstrap FILE... [--from LIST] [--per N] | raea fingerprint teach FILE --axis A --at T [--bad|--good] [--span S] [--box x0,y0,x1,y1] [--words W] [--project P] | raea fingerprint approve FILE... [--project P] | raea fingerprint pair WORSE BETTER --axis A [--at T] [--then T2] | raea fingerprint versions V1 V2... | raea fingerprint profile REFS... --as NAME [--against LIST] | raea fingerprint score FILE [--was OLD] [--ask flags|unsure] [--json] [--sheet out.png] [--timeline] [--profile NAME] | raea fingerprint report [--json] | raea fingerprint which [PATH] [--json] | raea fingerprint use NAME [--in project|workspace] [PATH] | raea fingerprint diff A B [--json] | raea fingerprint share NAME [--in project|workspace] [PATH] | raea fingerprint reembed PLACE... | raea fingerprint read PROJECT | raea fingerprint readings [PROJECT] [--ask N] [--tally] | raea fingerprint learn-notes [PROJECT] | raea fingerprint move [--fp CHILD] [--to PARENT] [--axis A] [--source S] [--project P] | raea fingerprint postmortem [PROJECT] [--ask N] [--tally] | raea fingerprint things FILE [--project P] [--json] | raea fingerprint stop [--fp NAME] (a person's sense of good work as axes with small heads over on-device encoders, docs/fingerprint.md: new makes ~/.raea/fingerprints/NAME with raea's base taxonomy in fingerprint.ts (or FP's axes with --extends), what it's for, the kinds of piece and project tags it judges, and every axis scoring from its words; bootstrap puts known defects into windows of real work and trains the mechanical axes, held out by source, and patch heads that say where in the frame a picture defect is; teach adds a label at a moment; approve makes approved work clean on every axis, away from its notes; pair says one moment is better than another on an axis (a pick, a hand edit); versions makes weak pairs of noted moments the next version changed; score prints the moments it expects a note on first (where in the frame, and the layers there, when its patch head points held out), then every axis per window with --json, a sheet PNG with --sheet, or the piece second by second in words with --timeline, and with --was OLD whether each of OLD's gating flags is fixed, still there, or looks disguised (nearer the axis's disguised defects than clean work), and with --ask flags each flag put to clef again on its own window, whether clef agrees said beside it and kept as clef's evidence (unsure: the moments it's unsure of too); profile takes the ranges of work you admire (loudness, tilt, cut rate, motion, brightness, contrast, saturation, sharpness), checked leave-one-out, and score --profile says what falls outside them, where and which way; report says each head's held-out score, labels, cheats, gate and what it can't judge; which says the one that judges a piece (its project's, its workspace's, then yours) and why, use pins one there, diff lists the axes two fingerprints rank the same evidence most differently on, and share copies one's taxonomy and evidence (no heads, no media) into a project or workspace for its team; reembed moves a fingerprint's evidence to this machine's encoders, re-embedding the rows whose media it finds; read has a fresh session of the project's own agent read its pinned notes into kinds and axes, readings puts them to you to check and tallies your answers, and learn-notes makes the defects and praise evidence once you've agreed with 45 kinds and 40 axes in 50, each project's in the fingerprint that judges it; move takes a child's own labels (by axis, source or project) up into a fingerprint it extends, which never reads them otherwise; postmortem scores every version in a project's feed and asks you at most ten yes/no questions in the app, each with its moment playing, where the fingerprint disagrees with your labels or is least sure, and --tally makes your answers evidence and says how each head's held-out score moved; things finds a piece's shots, its things (a render's layers, and the marks drawn on its notes) with their depth, and the camera's path, and says where a thing floats, two pass through each other, the camera lurches mid-move or nothing is on screen, for a person to look at; --json prints it as JSON)";
/// 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] = [
pub(crate) const FLAGS: [(&str, bool); 30] = [
("--fp", true),
("--was", true),
("--to", true),
@@ -51,7 +51,6 @@ pub(crate) const FLAGS: [(&str, bool); 31] = [
("--as", true),
("--against", true),
("--profile", true),
("--by", true),
("--ask", true),
("--tally", false),
("--bad", false),
+11 -32
View File
@@ -1,5 +1,5 @@
//! 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
//! Notes become evidence (docs/fingerprint.feature FP5a, FP5b). `raea fingerprint read PROJECT` has a fresh session of
//! the project's own agent (its host's critic, raea_io_clef::critic; never one raea or the agent picks) 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
@@ -99,30 +99,9 @@ pub fn fold(notes: &mut [Reading], fp: &Fingerprint, ans: &[Value], by: &str) {
}
}
/// 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)
/// One fresh session of the project's own agent, through its host (raea_io_clef::critic): its words
fn ask(cwd: &Path, p: &str) -> Result<String, String> {
raea_io_clef::critic::ask(cwd, p)
}
pub fn readings_of(dir: &Folder) -> Vec<Reading> {
@@ -133,12 +112,12 @@ 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]`
/// `raea fingerprint read PROJECT`
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 by = "agent";
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);
@@ -148,15 +127,15 @@ pub(crate) fn read_here(args: &[String], cwd: &Path) -> i32 {
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"))?;
let text = ask(&project, &prompt(&fp, chunk))?;
let ans = answer(&text).ok_or_else(|| "the critic answered no readings JSON".to_string())?;
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()))
Ok(format!("{read} notes read into labels by a fresh session of the project's agent, 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) => {
@@ -285,7 +264,7 @@ mod tests {
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");
fold(&mut n, &fp, &ans, "agent");
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");
-18
View File
@@ -1,18 +0,0 @@
[package]
name = "raea-app-judge"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "raea judge: a review's sheets judged by clef-omni on a frozen rubric, the pass decided in code, calibrated against the person's eye before it gates"
[dependencies]
dunce = "1"
raea-io-home = { path = "../../io/home" }
# what a judge saw, as raea's one Finding (docs/direction.feature DR3)
raea-core-facts = { path = "../../core/facts" }
serde_json = "1"
raea-runtime-bundle = { path = "../../runtime/bundle" }
# the one clef client: the question format and the call, routed to the person's plan first (docs/ask.feature AK1b)
raea-core-ask = { path = "../../core/ask" }
raea-io-clef = { path = "../../io/clef" }
-194
View File
@@ -1,194 +0,0 @@
//! A judge that is an agent CLI rather than clef-omni: `raea judge DIR --by kimi|claude` (Shane, 11-06: "use claude or
//! kimi cli as the judge"). Each call is a new session, run in DIR with only the sheets to look at (kimi's media tool;
//! claude with Read alone), given the fresh-context judge prompt (sdk/guides/craft/bevy/prompts.md section 3) and
//! never the code or the builder's notes. It answers JSON: the seven scores 0-10, the blind read and every defect named;
//! the pass, done and stall are still decided in code (rubric::pass, progress). `raea judge eye DIR --by kimi` records
//! its reading as the eye clef is calibrated against.
use std::path::Path;
use serde_json::{Map, Value, json};
use crate::rubric::{BAR, scores};
pub const BY: [&str; 2] = ["kimi", "claude"];
/// The judge prompt: the sheets by name, the brief's words, and the JSON to answer. A `raea make` job's kind asks its
/// own categories and the bar (docs/goal.feature MK5); none asks the rubric raea judge has always asked.
pub fn prompt(kind: Option<&str>, dir: &Path, brief: &Value, target: Option<&Path>) -> String {
match kind {
None => prompt_default(dir, brief, target),
Some(k) => prompt_kind(k, dir, brief, target),
}
}
fn brief_words(brief: &Value) -> String {
["look", "logline", "notDoing"].iter().filter_map(|k| brief.get(*k).map(|v| format!("{k}: {}", v.as_str().map(str::to_string).unwrap_or_else(|| v.to_string())))).collect::<Vec<_>>().join("; ")
}
fn prompt_kind(kind: &str, dir: &Path, brief: &Value, target: Option<&Path>) -> String {
let words = brief_words(brief);
let target = target.map(|t| format!(" The reference, what it must read as, is {}.", t.display())).unwrap_or_default();
let d = dir.display();
let sheets = match kind {
"shot" => format!("This round's sheet: {d}/framing.png. Each row is one shot: its first, middle and last frame, left to right, each stamped with its name and time. Open it."),
_ => format!(
"This round's sheets: {d}/colour.png and {d}/clay.png, each six tiles, left to right, top to bottom: hero, front, right, top, iso, low (0.3 m off the floor). Clay is every surface light grey and matte. Open both{}.",
if kind == "kit" { "; the scene is the kit's lineup, its props side by side with a scale bar" } else { "" }
),
};
let blind = if kind == "shot" {
String::new()
} else {
format!("PART 1, BLIND: open {d}/hero-colour.png first, one frame. In one sentence: what is this, what era? List five objects you can name. Is it a photograph or a render, and which three tells decided it?\n\n")
};
let cats: String = scores(Some(kind)).iter().map(|(k, on, ask)| format!("- {k}{}: {}\n", if *on == "clay" { " (judged on CLAY)" } else { "" }, ask.split_once(": ").map(|(_, r)| r).unwrap_or(ask))).collect();
let json_scores = scores(Some(kind)).iter().map(|(k, _, _)| format!("\"{k}\": 0")).collect::<Vec<_>>().join(", ");
format!(
"You review a {kind} from images only, as the person who will use it would. You have never seen how it was built and you never will. \
Judge what is in the pixels; do not guess at intentions. Only look at images; change no file.\n\n{blind}\
PART 2, SCORED. The brief: \"{words}\".{target} {sheets}\n\n\
Score each 0-10 (5 = a believable draft; 7 = a production base an artist would accept; 9 = indistinguishable from real). Halves are allowed.\n{cats}\n\
{BAR} Each defect field is one short sentence; \"blocking\" means someone using this would notice it where it will be seen. \
Name exactly what gives it away (not \"the phone looks fake\" but \"the handset is fused to the cradle with no gap\").\n\n\
End your answer with only this JSON, nothing after it:\n\
{{\"blind\": {{\"place\": \"\", \"objects\": [], \"photo\": \"yes|no\", \"tells\": []}}, \
\"scores\": {{{json_scores}}}, \
\"defects\": [{{\"tile\": \"\", \"where\": \"\", \"wrong\": \"\", \"real\": \"\", \"fix\": \"\", \"level\": \"blocking|detail\"}}], \
\"show_as_is\": \"\"}}"
)
}
fn prompt_default(dir: &Path, brief: &Value, target: Option<&Path>) -> String {
let words = brief_words(brief);
let target = target.map(|t| format!(" The target picture, what it must read as, is {}.", t.display())).unwrap_or_default();
format!(
"You review a 3D scene from images only, as the person who will use it would. You have never seen how it was built and you never will. \
Judge what is in the pixels; do not guess at intentions. Only look at images; change no file.\n\n\
PART 1, BLIND: open {d}/hero-colour.png first, one frame. In one sentence: what place is this, what time, what era? List five objects you can name. \
Is it a photograph or a render, and which three tells decided it?\n\n\
PART 2, SCORED. The brief: \"{words}\".{target} This round's sheets: {d}/colour.png and {d}/clay.png, each six tiles, left to right, top to bottom: \
hero, front, right, top, iso, low (0.3 m off the floor). Clay is every surface light grey and matte. Open both.\n\n\
Score each 0-10 (5 = a believable draft; 7 = a production base an artist would accept; 9 = indistinguishable from real). Halves are allowed.\n\
- composition: camera, framing, layout, the position and scale of every major object.\n\
- form, judged on CLAY: silhouettes read at a glance; parts have real thickness; nothing blobby, melted or a primitive standing in for a thing; repeated things vary.\n\
- assembly, judged on CLAY first: nothing floats, sinks, pokes through or rests on the wrong thing; joints touch; the low tile shows the feet.\n\
- materials: every surface reads as its real material, with wear where use puts it; nothing a flat default colour.\n\
- light: motivated by the place's own sources; exposure and contrast believable.\n\
- detail: close views hold real geometry or texture, not a smooth stand-in; printed matter reads.\n\
- world: one coherent real place; nothing off-era or invented beyond the brief.\n\n\
Then list the defects, most damaging first: at most 8, each field one short sentence. \"blocking\" means someone using this scene would notice it in the views it will be seen in. \
Name exactly what gives it away (not \"the dryer looks fake\" but \"the dryer door is a flat disc with no rim or glass depth\").\n\n\
End your answer with only this JSON, nothing after it:\n\
{{\"blind\": {{\"place\": \"\", \"objects\": [], \"photo\": \"yes|no\", \"tells\": []}}, \
\"scores\": {{\"composition\": 0, \"form\": 0, \"assembly\": 0, \"materials\": 0, \"light\": 0, \"detail\": 0, \"world\": 0}}, \
\"defects\": [{{\"tile\": \"\", \"where\": \"\", \"wrong\": \"\", \"real\": \"\", \"fix\": \"\", \"level\": \"blocking|detail\"}}], \
\"show_as_is\": \"\"}}",
d = dir.display()
)
}
/// The last JSON object in the text that has scores (an agent may think aloud, or draft the JSON twice).
pub fn last_verdict(text: &str) -> Option<Value> {
let starts: Vec<usize> = text.match_indices('{').map(|(i, _)| i).collect();
for &s in starts.iter().rev() {
let mut de = serde_json::Deserializer::from_str(&text[s..]).into_iter::<Value>();
if let Some(Ok(v)) = de.next()
&& v.get("scores").is_some_and(Value::is_object)
{
return Some(v);
}
}
None
}
/// The verdict read into the judge's own shape: scores (0-10, the kind's categories), defects (present, level, named
/// by what is wrong), the blind read's photo (1 a photo, 0 a render) and the agent's own words.
pub fn read(kind: Option<&str>, v: &Value) -> (Map<String, Value>, Vec<Value>, Value) {
let mut out = Map::new();
for &(k, _, _) in scores(kind) {
if let Some(x) = v["scores"][k].as_f64().filter(|x| (0.0..=10.0).contains(x)) {
out.insert(k.into(), json!(x));
}
}
let defects = v["defects"].as_array().into_iter().flatten().filter(|d| d["wrong"].as_str().is_some_and(|w| !w.trim().is_empty())).map(|d| {
let level = if d["level"].as_str().unwrap_or("").starts_with("block") { "blocking" } else { "detail" };
let wrong = d["wrong"].as_str().unwrap_or("");
json!({"defect": wrong.chars().take(80).collect::<String>(), "present": true, "level": level, "sheet": d["tile"], "asked": wrong,
"where": d["where"], "real": d["real"], "fix": d["fix"]})
}).collect();
let photo = match v["blind"]["photo"].as_str() {
Some(p) if p.starts_with('y') => json!(1.0),
Some(p) if p.starts_with('n') => json!(0.0),
_ => Value::Null,
};
(out, defects, photo)
}
/// One fresh judging session by `by` over DIR's sheets: its verdict JSON. Its steps stream (kimi's stream-json), each
/// said on stderr as it comes, so a watcher sees it working through a judgement that can take minutes.
pub fn ask(kind: Option<&str>, by: &str, dir: &Path, brief: &Value, target: Option<&Path>) -> Result<Value, String> {
use std::io::BufRead as _;
let dir = dunce::canonicalize(&dir).map_err(|e| format!("judge: {}: {e}", dir.display()))?;
let p = prompt(kind, &dir, brief, target);
let mut cmd = match by {
"kimi" => {
let mut c = std::process::Command::new("kimi");
c.args(["-p", &p, "--output-format", "stream-json"]);
c
}
"claude" => {
let mut c = std::process::Command::new("claude");
c.args(["-p", &p, "--allowedTools", "Read", "--output-format", "stream-json", "--verbose"]);
c
}
o => return Err(format!("judge: --by {o}: the judges are clef (the default), {}", BY.join(", "))),
};
let mut child = cmd.current_dir(&dir).stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped()).spawn()
.map_err(|e| format!("judge: couldn't run {by}: {e} (is the {by} CLI installed and signed in?)"))?;
let mut said = Vec::new();
let mut last = String::new();
for line in std::io::BufReader::new(child.stdout.take().ok_or("judge: no output pipe")?).lines().map_while(Result::ok) {
let Ok(v) = serde_json::from_str::<Value>(&line) else { continue };
said.extend(texts(&v));
let step = match (v["role"].as_str(), v["type"].as_str()) {
(Some("tool") | Some("user"), _) => "looked at a picture".to_string(),
(Some("assistant"), _) | (_, Some("assistant")) => texts(&v).last().map_or_else(|| "thinking".into(), |t| t[..t.floor_char_boundary(100)].to_string()),
_ => continue,
};
if step != last {
eprintln!("judge ({by}): {}", step.replace('\n', " "));
last = step;
}
}
let out = child.wait_with_output().map_err(|e| format!("judge: {by}: {e}"))?;
let text = said.join("\n");
if !out.status.success() && last_verdict(&text).is_none() {
return Err(format!("judge: {by} failed: {}", String::from_utf8_lossy(&out.stderr).lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("no output")));
}
last_verdict(&text).ok_or_else(|| format!("judge: {by} answered no verdict JSON: {}", text.trim().chars().rev().take(300).collect::<String>().chars().rev().collect::<String>()))
}
/// The words in one streamed line: kimi's {role: assistant, content: "..."}; claude's {type: assistant, message:
/// {content: [{type: text, text}]}} and its final {type: result, result}.
fn texts(v: &Value) -> Vec<String> {
let mut out = Vec::new();
if v["role"] == "assistant"
&& let Some(s) = v["content"].as_str()
{
out.push(s.to_string());
}
for c in v["message"]["content"].as_array().into_iter().flatten() {
if c["type"] == "text"
&& let Some(s) = c["text"].as_str()
{
out.push(s.to_string());
}
}
if v["type"] == "result"
&& let Some(s) = v["result"].as_str()
{
out.push(s.to_string());
}
out
}
-168
View File
@@ -1,168 +0,0 @@
//! Shane's eye, the judge's calibration. `raea judge eye DIR form=5 light=7 ... [--pass yes|no]` records his scores for a
//! round the judge has already judged (DIR/judge.json), with the judge's raw scores beside them, in
//! ~/.raea/judge/eye.jsonl. `raea judge calibrate` fits, per category, a line from the judge's score to his
//! (least squares), and says how often the mapped judge's pass agrees with his. The judge gates only once it has 10
//! rounds or more, some passed by the eye and some not, and agrees on 8 in 10 or better; until then `gating` is false and its verdict is advice
//! (clef has rated almost everything acceptable: docs/craft-system.md). `raea judge eye DIR --by kimi|claude` records a
//! fresh agent session's reading instead (Shane, 11-06), each row saying whose eye it is.
use std::path::PathBuf;
use serde_json::{Map, Value, json};
use crate::rubric::{pass_for, scores};
fn home() -> PathBuf {
raea_io_home::env_path("RAEA_JUDGE_DIR", ".raea/judge")
}
/// A kind's calibration file: calibration.json for the default rubric, calibration.KIND.json for a `raea make` kind's
/// (docs/goal.feature MK6), each fitted on that kind's rounds alone.
fn file_of(kind: Option<&str>) -> PathBuf {
home().join(kind.map_or_else(|| "calibration.json".to_string(), |k| format!("calibration.{k}.json")))
}
/// The calibration in force for a kind, if one was made.
pub fn calibration(kind: Option<&str>) -> Option<Value> {
serde_json::from_str(&std::fs::read_to_string(file_of(kind)).ok()?).ok()
}
/// A row's or a verdict's kind: none for the default rubric.
fn kind_in(v: &Value) -> Option<&str> {
v["kind"].as_str()
}
/// The judge's scores mapped through the calibration's lines, kept to 0-10.
pub fn apply(c: &Value, scores: &mut Map<String, Value>) {
for (k, v) in scores.iter_mut() {
if let (Some(x), Some(a), Some(b)) = (v.as_f64(), c["maps"][k]["a"].as_f64(), c["maps"][k]["b"].as_f64()) {
*v = json!(((a * x + b).clamp(0.0, 10.0) * 100.0).round() / 100.0);
}
}
}
pub fn record(args: &[String]) -> Result<String, String> {
let dir = args.get(2).map(PathBuf::from).ok_or("raea judge eye DIR CATEGORY=SCORE... [--pass yes|no]")?;
let verdict: Value = serde_json::from_str(&std::fs::read_to_string(dir.join("judge.json")).map_err(|_| format!("judge eye: no {}: judge the round first (raea judge {})", dir.join("judge.json").display(), dir.display()))?).map_err(|e| e.to_string())?;
let kind = kind_in(&verdict);
let cats = scores(kind);
// an agent's reading as the eye (`--by kimi`): a fresh session's scores, and its pass by the same rule in code
if let Some(by) = args.iter().position(|a| a == "--by").and_then(|i| args.get(i + 1)) {
let v = crate::agent::ask(kind, by, &dir, &json!({}), None)?;
let (eye, defects, _) = crate::agent::read(kind, &v);
if eye.len() < cats.len() {
return Err(format!("judge eye: {by} scored only {} of {} categories", eye.len(), cats.len()));
}
let eye_pass = pass_for(kind, &eye, &defects).0;
let row = json!({"dir": verdict["dir"], "kind": kind, "by": by, "judge": verdict["raw"], "judge_pass": verdict["pass"], "defects": verdict["defects"], "eye": eye, "eye_pass": eye_pass, "eye_defects": defects});
append(&row)?;
let shown: Vec<String> = eye.iter().map(|(k, v)| format!("{k} {v}")).collect();
return Ok(format!("APPLIED {by}'s eye on {} recorded ({}): {}; raea judge calibrate fits clef to it", dir.display(), if eye_pass { "a pass" } else { "not yet" }, shown.join(", ")));
}
let mut eye = Map::new();
let mut said_pass = None;
let mut i = 3;
while i < args.len() {
if args[i] == "--pass" {
said_pass = Some(matches!(args.get(i + 1).map(String::as_str), Some("yes" | "true" | "y")));
i += 2;
continue;
}
let (k, v) = args[i].split_once('=').ok_or_else(|| format!("judge eye: {:?} isn't CATEGORY=SCORE", args[i]))?;
if !cats.iter().any(|s| s.0 == k) {
return Err(format!("judge eye: no category {k}: {}", cats.iter().map(|s| s.0).collect::<Vec<_>>().join(", ")));
}
let x: f64 = v.parse().ok().filter(|x| (0.0..=10.0).contains(x)).ok_or_else(|| format!("judge eye: {k} is a score 0-10, got {v:?}"))?;
eye.insert(k.into(), json!(x));
i += 1;
}
if eye.is_empty() {
return Err("judge eye: give your scores, e.g. composition=6 form=5 assembly=7 materials=4 light=6 detail=5 world=6".into());
}
// his pass: as he says it, else the same rule on his scores with the judge's defects
let eye_pass = said_pass.unwrap_or_else(|| pass_for(kind, &eye, verdict["defects"].as_array().map(Vec::as_slice).unwrap_or(&[])).0);
let row = json!({"dir": verdict["dir"], "kind": kind, "by": "shane", "judge": verdict["raw"], "judge_pass": verdict["pass"], "defects": verdict["defects"], "eye": eye, "eye_pass": eye_pass});
append(&row)?;
Ok(format!("APPLIED your eye on {} recorded ({}): raea judge calibrate fits the judge to it", dir.display(), if eye_pass { "a pass" } else { "not yet" }))
}
/// One eye row onto ~/.raea/judge/eye.jsonl; a newer reading of the same round by the same eye replaces the older.
fn append(row: &Value) -> Result<(), String> {
std::fs::create_dir_all(home()).map_err(|e| e.to_string())?;
let path = home().join("eye.jsonl");
let mut rows: Vec<Value> = std::fs::read_to_string(&path).unwrap_or_default().lines().filter_map(|l| serde_json::from_str(l).ok()).filter(|r: &Value| !(r["dir"] == row["dir"] && whose(r) == whose(&row))).collect();
rows.push(row.clone());
std::fs::write(&path, rows.iter().map(Value::to_string).collect::<Vec<_>>().join("\n") + "\n").map_err(|e| e.to_string())
}
/// Least squares y = a x + b; flat x (one value) maps by the mean offset.
fn fit(xy: &[(f64, f64)]) -> (f64, f64) {
let n = xy.len() as f64;
let (mx, my) = (xy.iter().map(|p| p.0).sum::<f64>() / n, xy.iter().map(|p| p.1).sum::<f64>() / n);
let sxx: f64 = xy.iter().map(|p| (p.0 - mx).powi(2)).sum();
if sxx < 1e-9 {
return (1.0, my - mx);
}
let a = xy.iter().map(|p| (p.0 - mx) * (p.1 - my)).sum::<f64>() / sxx;
(a, my - a * mx)
}
/// The fit over a kind's rows of {judge, eye, defects, eye_pass} (none: the default rubric's): per-category maps and
/// errors, and the pass agreement.
pub fn fit_rows_for(kind: Option<&str>, rows: &[Value]) -> Value {
let mut maps = Map::new();
for &(k, _, _) in scores(kind) {
let xy: Vec<(f64, f64)> = rows.iter().filter_map(|r| Some((r["judge"][k].as_f64()?, r["eye"][k].as_f64()?))).collect();
if xy.len() < 2 {
continue;
}
let (a, b) = fit(&xy);
let mae = |f: &dyn Fn(f64) -> f64| xy.iter().map(|(x, y)| (f(*x) - y).abs()).sum::<f64>() / xy.len() as f64;
let r2 = |x: f64| (x * 1000.0).round() / 1000.0;
maps.insert(k.into(), json!({"a": r2(a), "b": r2(b), "n": xy.len(), "maeRaw": r2(mae(&|x| x)), "maeMapped": r2(mae(&|x| (a * x + b).clamp(0.0, 10.0)))}));
}
let cal = json!({"maps": maps});
let mut agree = 0;
for r in rows {
let mut s = r["judge"].as_object().cloned().unwrap_or_default();
apply(&cal, &mut s);
let p = pass_for(kind, &s, r["defects"].as_array().map(Vec::as_slice).unwrap_or(&[])).0;
if Value::Bool(p) == r["eye_pass"] {
agree += 1;
}
}
let n = rows.len();
let agreement = if n == 0 { 0.0 } else { agree as f64 / n as f64 };
// agreement means something only when the eye passed some rounds and failed others: all fails agree trivially
let passes = rows.iter().filter(|r| r["eye_pass"] == true).count();
let both = passes > 0 && passes < n;
json!({"maps": maps, "rounds": n, "eyePasses": passes, "agreement": (agreement * 1000.0).round() / 1000.0, "gate": n >= 10 && agreement >= 0.8 && both})
}
pub fn calibrate(args: &[String]) -> Result<String, String> {
let kind = crate::kind_of(args)?;
let kind = kind.as_deref();
let rows: Vec<Value> = std::fs::read_to_string(home().join("eye.jsonl")).unwrap_or_default().lines().filter_map(|l| serde_json::from_str(l).ok()).filter(|r: &Value| kind_in(r) == kind).collect();
if rows.is_empty() {
let k = kind.map(|k| format!(" of a {k}")).unwrap_or_default();
return Err(format!("judge calibrate: no rounds{k} with your eye yet (raea judge eye DIR form=5 ...)"));
}
let mut cal = fit_rows_for(kind, &rows);
cal["kind"] = json!(kind);
let mut eyes: Vec<String> = rows.iter().map(whose).map(str::to_string).collect();
eyes.sort();
eyes.dedup();
cal["eyes"] = json!(eyes);
std::fs::write(file_of(kind), serde_json::to_string_pretty(&cal).unwrap_or_default()).map_err(|e| e.to_string())?;
if args.iter().any(|a| a == "--json") {
return Ok(serde_json::to_string_pretty(&cal).unwrap_or_default());
}
let mut t: Vec<String> = cal["maps"].as_object().into_iter().flatten().map(|(k, m)| format!("{k:<12} eye = {} x judge {:+} (off by {} raw, {} mapped, {} rounds)", m["a"], m["b"], m["maeRaw"], m["maeMapped"], m["n"])).collect();
t.push(format!("agreement on the pass: {} over {} rounds (eyes: {}); {}", cal["agreement"], cal["rounds"], eyes.join(", "), if cal["gate"] == true { "the judge gates now".to_string() } else if cal["rounds"].as_u64() >= Some(10) && cal["agreement"].as_f64() >= Some(0.8) { format!("advice only: the eye passed {} of {} rounds, and agreement means something only with passes and fails both (judge a scene that is good)", cal["eyePasses"], cal["rounds"]) } else { "advice only until 10 rounds agree 8 in 10, with passes and fails both".to_string() }));
Ok(t.join("\n"))
}
/// Whose eye a row records: Shane's when it doesn't say.
fn whose(r: &Value) -> &str {
r["by"].as_str().unwrap_or("shane")
}
-235
View File
@@ -1,235 +0,0 @@
//! `raea judge`: a review's sheets (`raea render --review DIR`) judged by clef-omni on the frozen rubric (rubric.rs),
//! fresh every round and blind to the code, with the pass decided here in code. Until it is calibrated against Shane's
//! eye (`raea judge eye`, `raea judge calibrate`, eye.rs) its verdict is advice: `gating` says which.
//!
//! raea judge DIR [--kind scene|kit|shot] [--by clef|kimi|claude] [--brief brief.ts] [--target T.png] [--json] [--dry]
//! raea judge eye DIR composition=6 form=5 ... [--pass yes|no] (or --by kimi: an agent's reading as the eye)
//! raea judge calibrate [--kind scene|kit|shot] [--json]
//!
//! `--kind` asks a `raea make` job's own rubric (docs/goal.feature MK5): a scene's, a kit's or a shot list's categories,
//! with the bar AnyKit's critic is given; each kind is calibrated on its own rounds (MK6).
//!
//! DIR/judge.json is the verdict; DIR's parent's judge.log.jsonl holds every round's, so "done" (two passes in a row,
//! each a fresh call) and the stall (the mean up by less than a point over two rounds) are read from it.
mod agent;
mod eye;
/// Whether the judge's score gates a `raea make` kind's jobs: its calibration (`raea judge calibrate --kind KIND`)
/// agreed with the person's eye (docs/goal.feature MK6).
pub fn kind_gates(kind: &str) -> bool {
eye::calibration(Some(kind)).is_some_and(|c| c["gate"] == true)
}
pub mod rubric;
pub use agent::BY;
use std::path::{Path, PathBuf};
use raea_core_facts::{Finding, Level, finding};
use raea_runtime_bundle::flag;
use serde_json::{Value, json};
pub const USAGE: &str = "raea judge DIR [--kind scene|kit|shot] [--by clef|kimi|claude] [--brief brief.ts] [--target T.png] [--json] [--dry] | judge eye DIR (CATEGORY=SCORE ... [--pass yes|no] | --by kimi|claude) | judge calibrate [--kind scene|kit|shot] [--json] (a --review folder's sheets judged blind: clef-omni on the frozen rubric, or a fresh kimi or claude session on the judge prompt; --kind asks a scene, kit or shot goal's own rubric (a shot list's framing.png); the pass decided in code; clef advises until calibrated against your eye or an agent's, each kind on its own)";
/// `--kind`, checked: one of the rubric's kinds, or none (the default rubric).
pub fn kind_of(args: &[String]) -> Result<Option<String>, String> {
match flag(args, "--kind") {
None => Ok(None),
Some(k) if rubric::KINDS.contains(&k.as_str()) => Ok(Some(k)),
Some(k) => Err(format!("judge: --kind {k}: the kinds are {}", rubric::KINDS.join(", "))),
}
}
/// One call through raea's one clef client (raea-io-clef: the person's plan first, then their own Cloudflare keys),
/// with the rubric's questions as written and each sheet as a JPEG still.
fn ask(state: &str, questions: &Value, images: &[PathBuf]) -> Result<(Value, f64), String> {
let qs = questions.as_object().ok_or("judge: the questions aren't a map")?;
let questions = qs.iter().map(|(id, w)| raea_core_ask::Question::from_wire(id, w).ok_or(format!("judge: {id} isn't one of clef's question types"))).collect::<Result<_, _>>()?;
let stills = images.iter().map(|p| raea_io_clef::media::still(p, None)).collect::<Result<_, _>>()?;
let call = raea_io_clef::Call { state: state.into(), questions, media: raea_io_clef::Media { stills, ..Default::default() } };
let a = raea_io_clef::ask(&call).map_err(|f| f.to_string())?;
Ok((Value::Object(a.answers), a.cost))
}
/// The brief's words, from `raea spec brief.ts --as brief` (look, logline, notDoing), or nothing.
fn brief_of(path: Option<&str>) -> Result<Value, String> {
let Some(p) = path else { return Ok(json!({})) };
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
let out = std::process::Command::new(exe).args(["spec", p, "--as", "brief"]).output().map_err(|e| e.to_string())?;
let text = String::from_utf8_lossy(&out.stdout);
let start = text.find('{').ok_or_else(|| format!("judge: {p} didn't read as a brief: {}", why_refused(&out)))?;
let v: Value = serde_json::from_str(&text[start..]).map_err(|e| format!("judge: {p}: {e}"))?;
Ok(v.get("brief").cloned().unwrap_or(v))
}
/// The rounds judged so far beside this one (DIR's parent's judge.log.jsonl).
fn log_of(dir: &Path) -> PathBuf {
dir.parent().unwrap_or(dir).join("judge.log.jsonl")
}
/// Done and stall, from the log's rounds (oldest first), in code.
pub fn progress(rounds: &[Value]) -> Value {
let passes = rounds.iter().rev().take_while(|r| r["pass"] == true).count();
let means: Vec<f64> = rounds.iter().filter_map(|r| r["mean"].as_f64()).collect();
let stall = means.len() >= 3 && {
let best_before = means[..means.len() - 2].iter().cloned().fold(f64::MIN, f64::max);
let best_now = means[means.len() - 2..].iter().cloned().fold(f64::MIN, f64::max);
best_now - best_before < 1.0
};
// the same blocking defect present in the last two rounds
let named = |r: &Value| -> Vec<String> { rubric::blocking(r["defects"].as_array().map(Vec::as_slice).unwrap_or_default()).into_iter().map(str::to_string).collect() };
let again: Vec<String> = match rounds {
[.., a, b] => named(a).into_iter().filter(|d| named(b).contains(d)).collect(),
_ => Vec::new(),
};
json!({"rounds": rounds.len(), "passesInARow": passes, "done": passes >= 2, "stall": stall || !again.is_empty(), "again": again})
}
pub fn cli(args: &[String]) -> Result<String, String> {
match args.get(1).map(String::as_str) {
Some("eye") => return eye::record(args),
Some("calibrate") => return eye::calibrate(args),
Some(_) => {}
None => return Err(USAGE.into()),
}
let dir = PathBuf::from(&args[1]);
let kind = kind_of(args)?;
let kind = kind.as_deref();
let hero = dir.join("hero-colour.png");
let sheets: Vec<(&str, PathBuf)> = rubric::sheets(kind).iter().map(|(s, f)| (*s, dir.join(f))).collect();
for (_, f) in &sheets {
if !f.is_file() {
let make = if kind == Some("shot") { format!("raea make framing --out {}", dir.display()) } else { format!("raea render EDIT.tsx --review {}", dir.display()) };
return Err(format!("judge: no {} (make the sheets with {make})", f.display()));
}
}
let brief = brief_of(flag(args, "--brief").as_deref())?;
let target = flag(args, "--target").map(PathBuf::from);
let dry = args.iter().any(|a| a == "--dry");
let by = flag(args, "--by").unwrap_or_else(|| "clef".into());
if by != "clef" {
if dry {
return Ok(agent::prompt(kind, &dir, &brief, target.as_deref()));
}
let v = agent::ask(kind, &by, &dir, &brief, target.as_deref())?;
let (scores, defects, photo) = agent::read(kind, &v);
return finish(args, kind, &dir, scores.clone(), scores, defects, photo, 0.0, &by, false, json!({"blind": v["blind"], "show_as_is": v["show_as_is"]}));
}
let mut calls = Vec::new();
for (sheet, img) in &sheets {
let mut images = vec![img.clone()];
if *sheet == "colour" {
images.extend(target.clone());
}
calls.push((*sheet, rubric::state_for(kind, sheet, &brief), rubric::questions_for(kind, sheet), images));
}
if hero.is_file() && kind != Some("shot") {
calls.push(("blind", "One frame. Judge only what is in the pixels.".into(), rubric::blind(), vec![hero.clone()]));
}
if dry {
let shown: Vec<Value> = calls.iter().map(|(s, st, q, im)| json!({"sheet": s, "state": st, "questions": q, "images": im.iter().map(|p| p.display().to_string()).collect::<Vec<_>>()})).collect();
return Ok(serde_json::to_string_pretty(&json!({"would_ask": shown})).unwrap_or_default());
}
let mut scores = serde_json::Map::new();
let mut defects = Vec::new();
let mut photo = Value::Null;
let mut cost = 0.0;
for (sheet, st, q, images) in &calls {
let (answers, c) = ask(st, q, images)?;
cost += c;
if *sheet == "blind" {
photo = json!(answers["photo"]["noul"].as_f64().map(|p| (p * 1000.0).round() / 1000.0));
continue;
}
let (s, d) = rubric::read_for(kind, &answers);
scores.extend(s);
defects.extend(d.into_iter().map(|mut x| {
x["sheet"] = json!(sheet);
x
}));
}
let raw = scores.clone();
let cal = eye::calibration(kind);
if let Some(c) = &cal {
eye::apply(c, &mut scores);
}
let gating = cal.as_ref().is_some_and(|c| c["gate"] == true);
finish(args, kind, &dir, scores, raw, defects, photo, cost, "clef", !gating, json!({"calibrated": cal.is_some()}))
}
/// The defects a judge saw, as raea's one Finding (docs/direction.feature DR3): a blocking one an error and a detail a
/// warn, each a level lower from a judge that only advises. A judge sees pictures, not parts: a finding names its
/// sheet in its words and is about no entity.
pub fn findings(defects: &[Value], by: &str, advice: bool) -> Vec<Finding> {
let found = defects.iter().filter(|d| d["present"] == true).map(|d| {
let blocking = d["level"] == "blocking";
let level = match (blocking, advice) {
(true, false) => Level::Error,
(true, true) | (false, false) => Level::Warn,
(false, true) => Level::Note,
};
let sheet = d["sheet"].as_str().unwrap_or("");
let check = format!("judge.{}", if by == "clef" { d["defect"].as_str().unwrap_or("defect") } else { sheet });
let mut f = Finding::new(&check, level, format!("{sheet} sheet: {}", d["asked"].as_str().unwrap_or("")), &format!("raea judge ({by})"));
if let Some(p) = d["p"].as_f64() {
f = f.measure("p", p, "", Some(0.5));
}
match d["fix"].as_str() {
Some(x) if !x.is_empty() => f.fix(x),
_ => f,
}
});
finding::ranked(found.collect())
}
/// The verdict decided in code, written (DIR/judge.json for clef, DIR/judge.BY.json for an agent; every round in the
/// log), and said. `advice` marks a judge not yet trusted to gate (clef before calibration).
#[allow(clippy::too_many_arguments)]
fn finish(args: &[String], kind: Option<&str>, dir: &Path, scores: serde_json::Map<String, Value>, raw: serde_json::Map<String, Value>, defects: Vec<Value>, photo: Value, cost: f64, by: &str, advice: bool, extra: Value) -> Result<String, String> {
let (pass, why) = rubric::pass_for(kind, &scores, &defects);
let vals: Vec<f64> = scores.values().filter_map(Value::as_f64).collect();
let mean = if vals.is_empty() { 0.0 } else { (vals.iter().sum::<f64>() / vals.len() as f64 * 100.0).round() / 100.0 };
let model = if by == "clef" { "@cf/cloudflare/clef-omni".to_string() } else { format!("{by} cli") };
let found = findings(&defects, by, advice);
let mut verdict = json!({"dir": dir.display().to_string(), "kind": kind, "by": by, "scores": scores, "raw": raw, "mean": mean, "defects": defects, "photo": photo,
"pass": pass, "why": why, "gating": !advice, "cost": cost, "model": model, "findings": found, "count": finding::count(&found)});
if let (Some(v), Some(e)) = (verdict.as_object_mut(), extra.as_object()) {
v.extend(e.clone());
}
let log = log_of(dir);
let mut rounds: Vec<Value> = std::fs::read_to_string(&log).unwrap_or_default().lines().filter_map(|l| serde_json::from_str(l).ok()).filter(|r: &Value| r["dir"] != verdict["dir"]).collect();
rounds.push(verdict.clone());
verdict["progress"] = progress(&rounds);
let file = if by == "clef" { "judge.json".to_string() } else { format!("judge.{by}.json") };
std::fs::write(dir.join(file), serde_json::to_string_pretty(&verdict).unwrap_or_default()).map_err(|e| e.to_string())?;
let lines: Vec<String> = rounds.iter().map(|r| serde_json::to_string(&json!({"dir": r["dir"], "kind": r["kind"], "by": r["by"], "pass": r["pass"], "mean": r["mean"], "defects": r["defects"]})).unwrap_or_default()).collect();
std::fs::write(&log, lines.join("\n") + "\n").map_err(|e| e.to_string())?;
if cost > 0.0 {
let _ = std::process::Command::new("antsy").args(["spend", &format!("{cost:.6}"), "raea judge (clef-omni)"]).output();
}
if args.iter().any(|a| a == "--json") {
return Ok(serde_json::to_string_pretty(&verdict).unwrap_or_default());
}
let who = if by == "clef" { String::new() } else { format!("({by}) ") };
let mut t = vec![format!("{} {who}{}{}", if pass { "PASS" } else { "NOT YET" }, if advice { "(advice: the judge isn't calibrated against your eye yet) " } else { "" }, why.join("; "))];
t.push(format!("scores: {}", scores.iter().map(|(k, v)| format!("{k} {v}")).collect::<Vec<_>>().join(", ")));
for f in &found {
let p = f.measure.as_ref().map(|m| format!(" (p {})", m.value)).unwrap_or_default();
t.push(format!(" {}{p}", f.line()));
}
let p = &verdict["progress"];
t.push(format!("round {}: {} passes in a row{}{}; ${cost:.4}", p["rounds"], p["passesInARow"], if p["done"] == true { ", done" } else { "" }, if p["stall"] == true { ", stalled: change the approach for the part, not the dose" } else { "" }));
t.push(format!("raea judge: {}", finding::count(&found)));
Ok(t.join("\n"))
}
#[cfg(test)]
mod tests;
/// Why `raea spec` refused a brief, in its own words: its refusal is the last line it printed, on whichever stream
/// (a REFUSED line goes to stdout, a thrown module's error to stderr). Reading stderr alone left the reason empty.
pub fn why_refused(out: &std::process::Output) -> String {
let last = |b: &[u8]| String::from_utf8_lossy(b).lines().rev().find(|l| !l.trim().is_empty()).map(|l| l.trim().trim_start_matches("REFUSED").trim().to_string());
last(&out.stderr).or_else(|| last(&out.stdout)).unwrap_or_else(|| "raea spec printed nothing".into())
}
-229
View File
@@ -1,229 +0,0 @@
//! The frozen rubric (the 11-06 prompt pack, section 3, in clef-omni's native question types): a 0-10 score per category
//! as an ordered six-level rubric, and every named defect as a yes/no question, so a defect is a probability rather
//! than prose. clef-omni answers questions, not essays; the defects it can name are the ones asked. Nothing here says
//! where the pass line is (the loop decides, in code: `pass`).
use serde_json::{Value, json};
/// The six levels each category is scored on, lowest first (clef's `score`: the probability-weighted level), read as
/// 0, 2, 4, 6, 8, 10.
fn levels(what: &str) -> Value {
json!([
format!("0: no {what} to speak of; broken or missing"),
format!("2: {what} is crude: primitives and placeholders"),
format!("4: {what} is a rough draft, plainly unfinished"),
format!("6: {what} is a believable draft"),
format!("8: {what} is a production base an artist would accept"),
format!("10: {what} is indistinguishable from the real thing"),
])
}
/// A category: (id, the sheet it is judged on, the question).
pub type Score = (&'static str, &'static str, &'static str);
/// (id, the sheet it is judged on, the question): the rubric raea judge has always asked, when no `--kind` is given.
pub const SCORES: [Score; 7] = [
("composition", "colour", "Composition: the camera, framing and layout; every major object's position and scale against the brief's space."),
("form", "clay", "Form, judged on these grey clay tiles: silhouettes read at a glance, parts have real thickness, nothing blobby or melted, no primitive standing in for a thing, repeated things vary."),
("assembly", "clay", "Assembly, judged on these grey clay tiles: nothing floats, sinks, pokes through or rests on the wrong thing; joints touch; the low tile shows the feet resting."),
("materials", "colour", "Materials: every surface reads as its real material with wear where use puts it; nothing a flat default colour; glass is glass."),
("light", "colour", "Light: motivated by the place's own sources; exposure and contrast believable; no surface implausibly dark or bright."),
("detail", "colour", "Detail: close surfaces hold real geometry or texture at that distance, not smooth stand-ins; printed matter reads."),
("world", "colour", "World: one coherent real place matching the brief; nothing off-era, no real brands, nothing invented beyond the brief."),
];
/// The job kinds with a rubric of their own (docs/goal.feature MK5): `raea judge DIR --kind scene|kit|shot`.
pub const KINDS: [&str; 3] = ["scene", "kit", "shot"];
/// A scene made to a plan (AnyScene's categories): judged on the six-camera sheets.
pub const SCENE: [Score; 8] = [
("layout", "clay", "Layout, judged on these grey clay tiles: every major object where the plan and the reference put it, at its real size, with room to move between them."),
("props", "clay", "Props, judged on these grey clay tiles: each object's form reads at a glance, with real thickness; nothing blobby or a primitive standing in; nothing floats, sinks or pokes through."),
("signage", "colour", "Screens and signage: every screen, sign, label and printed thing reads, belongs to one invented world, and shows no real brand."),
("materials", "colour", "Materials: every surface reads as its real material with wear where use puts it; nothing a flat default colour; glass is glass."),
("light", "colour", "Light: motivated by the place's own sources; exposure and contrast believable; emissive things glow without lighting the room wrong."),
("atmosphere", "colour", "Atmosphere: the air, haze, dust or weather the place would have, matching the plan's dials; not empty and clinical."),
("plausibility", "colour", "Plausibility: one coherent real place a person could stand in; nothing off-era, nothing that couldn't be there."),
("composition", "colour", "Composition: the hero camera's framing and the place's layout read as the reference's."),
];
/// A kit (AnyKit's categories): judged on the six-camera sheets of its lineup.
pub const KIT: [Score; 8] = [
("cohesion", "colour", "Cohesion: every prop belongs to one set: the same era, palette, materials, wear and maker; none is an outlier."),
("fidelity", "colour", "Reference fidelity: the props read as the style references' world, at normal viewing distance."),
("brief", "colour", "Brief: the kit holds the props the brief asked for, each recognisable as what it is meant to be."),
("mesh", "clay", "Mesh, judged on these grey clay tiles: crisp silhouettes, real thickness, no melted or blobby forms, no holes or spikes."),
("texture", "colour", "Texture: real materials with wear where use puts it; no smeared, stretched or flat default surfaces; glass is glass."),
("assembly", "clay", "Assembly, judged on these grey clay tiles: every part of each prop is connected to its body; handles, legs and lids attached."),
("scale", "clay", "Scale, judged on these grey clay tiles: each prop's size is right beside the others and the scale bar."),
("labels", "colour", "Labels: printed text and logos read, belong to the one invented maker, and no real brand shows."),
];
/// A shot list (AnyShot's categories): judged on the framing sheet, each shot's first, middle and last frame.
pub const SHOT: [Score; 6] = [
("framing", "colour", "Framing: each shot frames its subject as its description says, at every one of its frames."),
("move", "colour", "Move: the camera's change from first to last frame is the move the description names, at a believable size."),
("focus", "colour", "Focus: what the description says is sharp is sharp; nothing important lost in blur."),
("clearance", "colour", "Clearance: the camera is never inside or against a wall or object; nothing blocks the frame."),
("continuity", "colour", "Continuity: the shots read as one place at one time: the same light, weather and dressing across them."),
("grade", "colour", "Grade: the look matches the plan's look dial, with believable exposure and colour."),
];
/// The categories asked for a kind: its own rubric, or the default one.
pub fn scores(kind: Option<&str>) -> &'static [Score] {
match kind {
Some("scene") => &SCENE,
Some("kit") => &KIT,
Some("shot") => &SHOT,
_ => &SCORES,
}
}
/// What a kind's critic is told the bar is (AnyKit's own words, docs/goal.feature MK5).
pub const BAR: &str = "The bar is a production base an artist then refines, judged at normal viewing distance: take no points off for choices that differ from the reference, don't nitpick, and name at most five fixes, most damaging first.";
/// The sheets a kind is judged on: the six-camera colour and clay sheets, or a shot list's framing sheet alone.
pub fn sheets(kind: Option<&str>) -> &'static [(&'static str, &'static str)] {
match kind {
Some("shot") => &[("colour", "framing.png")],
_ => &[("colour", "colour.png"), ("clay", "clay.png")],
}
}
/// (id, sheet, the yes/no question, blocking when yes)
pub const DEFECTS: [(&str, &str, &str, bool); 12] = [
("floating", "clay", "Does any object float above the surface it should rest on, with a visible gap under it?", true),
("intersecting", "clay", "Does any object pass through another object, a wall or the floor?", true),
("blobby", "clay", "Is any object a blobby, melted or lumpy shape where the real thing has crisp form?", true),
("stand_in", "clay", "Is any object just a plain box, ball or cylinder standing in for a more detailed real thing?", true),
("clones", "clay", "Are several copies of one thing identical and evenly spaced in an obviously artificial way?", false),
("flat_colour", "colour", "Is any large surface a flat, uniform default colour with no texture, variation or wear?", true),
("plastic", "colour", "Do the surfaces look like shiny uniform plastic or CG rather than their real materials?", true),
("garbled_text", "colour", "Is any visible text garbled, tiled or unreadable where it should read?", false),
("too_dark", "colour", "Is the scene so dark that important objects are hard to see?", true),
("too_bright", "colour", "Is the scene washed out, with large areas blown to white?", true),
("brands", "colour", "Is a real brand name or logo visible?", true),
("not_doing", "colour", "Does the scene show anything the brief says it must not contain?", true),
];
/// The paragraph clef reads before the sheet: what it is looking at, and the brief's words (no code, no log, no line).
pub fn state(sheet: &str, brief: &Value) -> String {
state_for(None, sheet, brief)
}
/// state, for a kind: a kind's critic also reads what it is looking at in its terms, and the bar.
pub fn state_for(kind: Option<&str>, sheet: &str, brief: &Value) -> String {
let what = match kind {
Some("shot") => "The image is a framing sheet: each row is one shot, its first, middle and last frame left to right, each stamped with the shot's name and time. Judge each shot as its description would.".to_string(),
_ => {
let tiles = "six tiles of one 3D scene, left to right and top to bottom: hero (the shot's own camera), front, right, top, iso, and low (a camera 0.3 m off the floor)";
let what = if sheet == "clay" { format!("The image is {tiles}, rendered in clay: every surface plain grey, so only form and assembly show.") } else { format!("The image is {tiles}, in full colour.") };
let target = if sheet == "colour" { " A second image, when given, is the target picture the scene should read as." } else { "" };
let kit = if kind == Some("kit") { " The scene is a kit: a lineup of props made to belong together, with a scale bar." } else { "" };
format!("{what}{target}{kit}")
}
};
// the default rubric's words stay as calibrated: "the scene"
let it = match kind { None | Some("scene") => "the scene", Some("kit") => "the kit", _ => "the shots" };
let mut s = format!("{what} Judge only what is in the pixels, as the person who will use {it} would.");
let look = brief["look"].as_str().unwrap_or("");
let logline = brief["logline"].as_str().unwrap_or("");
let not: Vec<&str> = brief["notDoing"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
if !logline.is_empty() || !look.is_empty() {
s.push_str(&format!(" The brief: {logline} Look: {look}."));
}
if !not.is_empty() {
let it = it[..1].to_uppercase() + &it[1..];
s.push_str(&format!(" {it} must not contain: {}.", not.join("; ")));
}
if kind.is_some() {
s.push(' ');
s.push_str(BAR);
}
s
}
/// The questions for one sheet, by id.
pub fn questions(sheet: &str) -> Value {
questions_for(None, sheet)
}
/// questions, for a kind's rubric.
pub fn questions_for(kind: Option<&str>, sheet: &str) -> Value {
let mut q = serde_json::Map::new();
for &(id, on, ask) in scores(kind) {
if on == sheet {
q.insert(format!("score_{id}"), json!({"type": "score", "instructions": ask, "criteria": levels(id)}));
}
}
for (id, on, ask, _) in DEFECTS {
if on == sheet {
q.insert(format!("defect_{id}"), json!({"type": "noul", "instructions": ask}));
}
}
Value::Object(q)
}
/// The blind read on the hero tile alone: is this a photograph (reported, never gated, until calibrated).
pub fn blind() -> Value {
json!({"photo": {"type": "noul", "instructions": "Is this a photograph of a real place, rather than a computer render?"}})
}
/// clef's answers read into scores (0-10) and defects (probability of yes, blocking ones flagged).
pub fn read(answers: &Value) -> (serde_json::Map<String, Value>, Vec<Value>) {
read_for(None, answers)
}
/// read, for a kind's rubric.
pub fn read_for(kind: Option<&str>, answers: &Value) -> (serde_json::Map<String, Value>, Vec<Value>) {
let mut scores = serde_json::Map::new();
let mut defects = Vec::new();
for &(id, _, _) in self::scores(kind) {
if let Some(a) = answers.get(format!("score_{id}")) {
let level = a["score"].as_f64().unwrap_or(0.0);
scores.insert(id.into(), json!((level * 2.0 * 100.0).round() / 100.0));
}
}
for (id, _, ask, blocking) in DEFECTS {
if let Some(a) = answers.get(format!("defect_{id}")) {
let p = a["noul"].as_f64().unwrap_or(0.0);
defects.push(json!({"defect": id, "p": (p * 1000.0).round() / 1000.0, "present": p >= 0.5, "level": if blocking { "blocking" } else { "detail" }, "asked": ask}));
}
}
(scores, defects)
}
/// The loop's pass, in code: no blocking defect present, the lowest score 6 or more and the mean 7 or more (raea's
/// 0-10 scale; the prompt pack's line). Scores mapped by a calibration first, when there is one.
pub fn pass(scores: &serde_json::Map<String, Value>, defects: &[Value]) -> (bool, Vec<String>) {
pass_for(None, scores, defects)
}
/// pass, for a kind's rubric: every one of its categories scored.
pub fn pass_for(kind: Option<&str>, scores: &serde_json::Map<String, Value>, defects: &[Value]) -> (bool, Vec<String>) {
let want = self::scores(kind).len();
let vals: Vec<f64> = scores.values().filter_map(Value::as_f64).collect();
let mut why = Vec::new();
let blocking = blocking(defects);
if !blocking.is_empty() {
why.push(format!("blocking: {}", blocking.join(", ")));
}
let min = vals.iter().cloned().fold(f64::INFINITY, f64::min);
let mean = if vals.is_empty() { 0.0 } else { vals.iter().sum::<f64>() / vals.len() as f64 };
if vals.len() < want {
why.push(format!("only {} of {want} categories scored", vals.len()));
}
if min < 6.0 {
let low: Vec<String> = scores.iter().filter(|(_, v)| v.as_f64().is_some_and(|x| x < 6.0)).map(|(k, _)| k.clone()).collect();
why.push(format!("below a draft: {}", low.join(", ")));
}
if mean < 7.0 {
why.push("the whole is under a production base".into());
}
(why.is_empty(), why)
}
/// The blocking defects present, by name.
pub fn blocking(defects: &[Value]) -> Vec<&str> {
defects.iter().filter(|d| d["present"] == true && d["level"] == "blocking").filter_map(|d| d["defect"].as_str()).collect()
}
-126
View File
@@ -1,126 +0,0 @@
use super::*;
use serde_json::json;
fn scores(v: f64) -> serde_json::Map<String, Value> {
rubric::SCORES.iter().map(|s| (s.0.to_string(), json!(v))).collect()
}
#[test]
fn the_pass_is_code_and_a_blocking_defect_holds_it() {
assert!(rubric::pass(&scores(7.5), &[]).0);
assert!(!rubric::pass(&scores(6.5), &[]).0, "mean under 7");
let mut s = scores(8.0);
s.insert("form".into(), json!(5.0));
let (ok, why) = rubric::pass(&s, &[]);
assert!(!ok && why.iter().any(|w| w.contains("form")));
let d = vec![json!({"defect": "floating", "present": true, "level": "blocking"})];
assert!(!rubric::pass(&scores(9.0), &d).0);
// the questions hold no pass line
let q = format!("{}{}", rubric::questions("colour"), rubric::questions("clay"));
assert!(!q.contains("mean") && !q.contains(">= 6"));
}
#[test]
fn answers_are_read_and_rounds_say_done_and_stall() {
let a = json!({"score_form": {"score": 3.5}, "defect_floating": {"noul": 0.8}});
let (s, d) = rubric::read(&a);
assert_eq!(s["form"], 7.0);
assert_eq!(d[0]["present"], true);
let r = |p: bool, m: f64| json!({"pass": p, "mean": m, "defects": []});
assert_eq!(progress(&[r(false, 5.0), r(true, 7.2), r(true, 7.4)])["done"], true);
assert_eq!(progress(&[r(false, 5.0), r(false, 5.3), r(false, 5.6)])["stall"], true);
assert_eq!(progress(&[r(false, 4.0), r(false, 5.3), r(false, 6.1)])["stall"], false);
}
#[test]
fn calibration_maps_a_lenient_judge_onto_the_eye() {
// the judge says 8 to everything the eye gives 5, and 9 to what the eye gives 8
let row = |j: f64, e: f64, p: bool| json!({"judge": scores(j), "eye": scores(e), "eye_pass": p, "defects": []});
let rows: Vec<Value> = (0..12).map(|i| if i % 2 == 0 { row(8.0, 5.0, false) } else { row(9.0, 8.0, true) }).collect();
let cal = eye::fit_rows_for(None, &rows);
assert_eq!(cal["agreement"], 1.0);
assert_eq!(cal["gate"], true);
assert!((cal["maps"]["form"]["a"].as_f64().unwrap() - 3.0).abs() < 1e-6);
let few = eye::fit_rows_for(None, &rows[..4]);
assert_eq!(few["gate"], false, "too few rounds to gate");
// an eye that failed everything agrees with a judge that fails everything, which proves nothing
let fails: Vec<Value> = (0..12).map(|_| row(3.0, 2.0, false)).collect();
let all_fail = eye::fit_rows_for(None, &fails);
assert_eq!(all_fail["agreement"], 1.0);
assert_eq!(all_fail["gate"], false, "no pass among the eye's rounds");
}
#[test]
fn an_agent_verdict_is_read_from_the_end_of_its_thinking() {
// an agent thinks aloud, may draft the JSON twice, and ends with the one it means
let text = r#"• Looking at the sheets... draft: {"scores": {"form": 1}} then the answer:
{"blind": {"place": "office", "objects": [], "photo": "no", "tells": []},
"scores": {"composition": 6, "form": 5.5, "assembly": 7, "materials": 4, "light": 6, "detail": 5, "world": 6, "vibes": 9},
"defects": [{"tile": "iso", "where": "left", "wrong": "the desks are plain boxes", "real": "a desk has legs", "fix": "model legs", "level": "blocking"},
{"tile": "low", "wrong": "", "level": "detail"}],
"show_as_is": "no"}"#;
let v = crate::agent::last_verdict(text).unwrap();
let (scores, defects, photo) = crate::agent::read(None, &v);
assert_eq!(scores.len(), 7, "only the seven categories, each 0-10");
assert_eq!(scores["form"], serde_json::json!(5.5));
assert_eq!(defects.len(), 1, "a defect with nothing wrong named is dropped");
assert_eq!(defects[0]["level"], "blocking");
assert_eq!(photo, serde_json::json!(0.0));
let (pass, why) = crate::rubric::pass(&scores, &defects);
assert!(!pass && why[0].starts_with("blocking"));
assert!(crate::agent::last_verdict("no json here").is_none());
// what it saw, as Findings (DR3): a gating judge's blocking defect is an error, an advising one's a warn
let f = &crate::findings(&defects, "kimi", false)[0];
assert_eq!((f.check.as_str(), f.level, f.fix.as_deref(), f.by.as_str()), ("judge.iso", raea_core_facts::Level::Error, Some("model legs"), "raea judge (kimi)"));
assert!(f.says.starts_with("iso sheet: "), "{}", f.says);
assert_eq!(crate::findings(&defects, "kimi", true)[0].level, raea_core_facts::Level::Warn);
}
#[test]
fn each_make_kind_has_its_own_rubric_and_the_default_is_unchanged() {
// docs/goal.feature MK5: a kit's categories, a shot list's on the framing sheet alone, the bar said to each
let kit = rubric::questions_for(Some("kit"), "clay");
for k in ["score_mesh", "score_assembly", "score_scale"] {
assert!(kit.get(k).is_some(), "{k} in {kit}");
}
assert!(kit.get("score_cohesion").is_none(), "cohesion is judged in colour");
assert_eq!(rubric::sheets(Some("shot")), &[("colour", "framing.png")]);
assert_eq!(rubric::sheets(None).len(), 2);
let shot = rubric::questions_for(Some("shot"), "colour");
assert!(shot.get("score_clearance").is_some() && shot.get("score_composition").is_none());
assert!(rubric::state_for(Some("kit"), "colour", &json!({})).contains(rubric::BAR));
assert!(rubric::state_for(Some("shot"), "colour", &json!({})).contains("framing sheet"));
// the default's words are what it was calibrated on
let d = rubric::state("clay", &json!({"notDoing": ["cats"]}));
assert!(d.contains("as the person who will use the scene would") && d.contains("The scene must not contain: cats.") && !d.contains(rubric::BAR), "{d}");
// every kind scored in full to pass
let all = |k: Option<&str>, v: f64| -> serde_json::Map<String, Value> { rubric::scores(k).iter().map(|s| (s.0.to_string(), json!(v))).collect() };
assert!(rubric::pass_for(Some("kit"), &all(Some("kit"), 8.0), &[]).0);
let (ok, why) = rubric::pass_for(Some("kit"), &all(None, 8.0), &[]);
assert!(!ok && why.iter().any(|w| w.contains("of 8 categories")), "{why:?}");
assert!(kind_of(&["judge".into(), "d".into(), "--kind".into(), "film".into()]).is_err());
assert_eq!(kind_of(&["judge".into(), "d".into(), "--kind".into(), "shot".into()]).unwrap().as_deref(), Some("shot"));
}
#[test]
fn an_agent_critic_is_asked_its_kinds_categories() {
let p = crate::agent::prompt(Some("shot"), std::path::Path::new("/r/r1"), &json!({"look": "dusk"}), None);
assert!(p.contains("/r/r1/framing.png") && p.contains("\"clearance\": 0") && p.contains(rubric::BAR) && !p.contains("PART 1, BLIND"), "{p}");
let k = crate::agent::prompt(Some("kit"), std::path::Path::new("/r/r1"), &json!({}), None);
assert!(k.contains("\"cohesion\": 0") && k.contains("scale bar") && k.contains("(judged on CLAY)"));
let d = crate::agent::prompt(None, std::path::Path::new("/r/r1"), &json!({}), None);
assert!(d.contains("\"composition\": 0") && !d.contains(rubric::BAR));
let v = json!({"scores": {"cohesion": 7, "fidelity": 8, "composition": 9}});
let (s, _, _) = crate::agent::read(Some("kit"), &v);
assert_eq!(s.len(), 2, "only the kit's categories");
}
#[test]
fn a_kind_is_calibrated_on_its_own_categories() {
// docs/goal.feature MK6
let s = |j: f64| -> serde_json::Map<String, Value> { rubric::KIT.iter().map(|c| (c.0.to_string(), json!(j))).collect() };
let rows: Vec<Value> = (0..12).map(|i| if i % 2 == 0 { json!({"kind": "kit", "judge": s(8.0), "eye": s(5.0), "eye_pass": false, "defects": []}) } else { json!({"kind": "kit", "judge": s(9.0), "eye": s(8.0), "eye_pass": true, "defects": []}) }).collect();
let cal = eye::fit_rows_for(Some("kit"), &rows);
assert_eq!(cal["gate"], true);
assert!(cal["maps"]["cohesion"].is_object() && cal["maps"]["form"].is_null());
}
+2 -10
View File
@@ -4,23 +4,15 @@ version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "raea make's Rust: a scene, kit or shot job's steps, and the record and critic gates raea/goal's packs read (docs/goal.feature)"
description = "raea make's Rust: a scene, kit or shot goal's asset steps (docs/goal.feature)"
[dependencies]
# the plan: `make` on brief.ts
raea-core-brief = { path = "../../core/brief" }
# the project's record of renders and checks, and the folder it lives in
# the folder a project lives in
raea-core-facts = { path = "../../core/facts" }
# the parts a render showed closer than their planned detail (MK24)
raea-runtime-lod-plan = { path = "../../runtime/lod-plan" }
# the judge's rounds, passes and blocking defects, read as it keeps them
raea-app-judge = { path = "../judge" }
# the make questions, their calibrations and a sheet's ident, as raea ask keeps them (MK4)
raea-core-ask = { path = "../../core/ask" }
# a lens's field of view (MK15's lens chart), as the review sheets work it out
raea-core-review = { path = "../../core/review" }
# raea ask's ledger folder
raea-io-home = { path = "../../io/home" }
# the contact sheets: tiles composited, labels drawn in the system's fonts
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
resvg = { version = "=0.48.1", default-features = false, features = ["text", "system-fonts"] }
-114
View File
@@ -1,114 +0,0 @@
//! The second tier of the gate (docs/goal.feature MK4): the `make` set of `raea ask` questions (core/ask
//! library/make.json), asked of the job's newest sheets. A question gates once it is calibrated on the person's labels
//! (`raea ask calibrate`: 16 problem, 16 clean, an AUC of 0.8); until then what it says is advice in the gates. An
//! answer counts for a sheet only when its call was about exactly that sheet's bytes (the ledger's `ident`), so a sheet
//! rendered again must be asked again.
use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};
use raea_core_ask::{Calibration, Question};
use serde_json::{Value, json};
/// The ledger as the gates read it: every call's ident by id, every answer, and the person's calibrations.
#[derive(Default)]
pub struct Ledger {
pub idents: HashMap<String, String>,
pub answers: Vec<Value>,
pub calibrations: BTreeMap<String, Calibration>,
}
impl Ledger {
/// `raea ask`'s record (RAEA_ASK_DIR, else ~/.raea/ask), read once.
pub fn read() -> Ledger {
let dir = raea_io_home::env_path("RAEA_ASK_DIR", ".raea/ask");
let rows = |f: &str| -> Vec<Value> { std::fs::read_to_string(dir.join(f)).unwrap_or_default().lines().filter_map(|l| serde_json::from_str(l).ok()).collect() };
let idents = rows("calls.jsonl").into_iter().filter_map(|c| Some((c["id"].as_str()?.to_string(), c["ident"].as_str()?.to_string()))).collect();
let answers = rows("answers.jsonl").into_iter().filter(|a| a["question"].as_str().is_some_and(|q| q.starts_with("make."))).collect();
let calibrations = std::fs::read_to_string(dir.join("calibration.json")).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default();
Ledger { idents, answers, calibrations }
}
}
/// The `make` set's questions with the person's calibrations in place of raea's (as `raea ask` applies them).
pub fn questions(ledger: &Ledger) -> Vec<Question> {
let mut qs = raea_core_ask::library::set("make", None).unwrap_or_default();
for q in &mut qs {
if let Some(c) = ledger.calibrations.get(&q.version()) {
q.calibration = Some(c.clone());
}
}
qs
}
/// The sheet a question is asked of: its id's second word (make.clay.floating is asked of a clay sheet).
pub fn sheet_of(q: &Question) -> &str {
match q.id.split('.').nth(1) {
Some(sheet) => sheet,
None => "",
}
}
/// The command that asks a sheet its questions.
pub fn command(sheet: &Path, qs: &[&Question]) -> String {
let std: Vec<String> = qs.iter().map(|q| format!("--std {}", q.id)).collect();
format!("raea ask {} {}", sheet.display(), std.join(" "))
}
/// Each sheet's gate, and the advice: what uncalibrated questions flagged. `sheets` are (kind, file): clay, colour,
/// refs, framing. `notes` is NOTES.md: a flagged question answered there by its id holds nothing.
pub fn gates(sheets: &[(&str, PathBuf)], ledger: &Ledger, notes: &str) -> (Vec<Value>, Vec<String>) {
let qs = questions(ledger);
let mut gates = Vec::new();
let mut advice = Vec::new();
for (kind, file) in sheets {
let mine: Vec<&Question> = qs.iter().filter(|q| sheet_of(q) == *kind).collect();
if mine.is_empty() {
continue;
}
let rel = file.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
let Some(ident) = raea_core_ask::ident::ident(file) else { continue };
// the newest answer to each question about these exact bytes
let mut latest: BTreeMap<&str, &Value> = BTreeMap::new();
for a in &ledger.answers {
let about = a["call"].as_str().and_then(|c| ledger.idents.get(c)).is_some_and(|i| *i == ident);
let Some(q) = a["question"].as_str() else { continue };
if about && latest.get(q).is_none_or(|b| at(a) >= at(b)) {
latest.insert(q, a);
}
}
let mut open = Vec::new();
let mut unasked = Vec::new();
for q in &mine {
let a = latest.get(q.id.as_str());
let flagged = a.is_some_and(|a| a["flagged"] == true);
let p = a.and_then(|a| a["problem"].as_f64()).map(|p| format!(" (p {p:.2})")).unwrap_or_default();
if q.calibrated() {
match a {
None => unasked.push(*q),
Some(_) if flagged && !notes.contains(&q.id) => open.push(format!("{} flagged{p}: {}", q.id, q.fix.as_deref().unwrap_or("fix it, or answer it in NOTES.md by its id"))),
_ => {}
}
} else if flagged {
advice.push(format!("{rel}: {} says yes{p}, advice until calibrated: {}", q.id, q.fix.as_deref().unwrap_or("")));
}
}
if !unasked.is_empty() {
open.push(format!("not asked of this {kind} sheet yet: {}", command(file, &unasked)));
}
let calibrated = mine.iter().filter(|q| q.calibrated()).count();
let says = match (open.is_empty(), calibrated) {
(true, 0) => format!("advice only: none of its {} questions is calibrated yet (raea ask calibrate)", mine.len()),
(true, n) => format!("{n} calibrated question{} clear", if n == 1 { "" } else { "s" }),
(false, _) => open.join("; "),
};
let mut g = json!({"gate": "ask", "of": rel, "clear": open.is_empty(), "says": says});
g["ask"] = json!(command(file, &mine));
gates.push(g);
}
(gates, advice)
}
fn at(a: &Value) -> u64 {
a["at"].as_str().and_then(|s| s.parse().ok()).or_else(|| a["at"].as_u64()).unwrap_or(0)
}
-202
View File
@@ -1,202 +0,0 @@
//! A scene, kit or shot job's record and critic gates (docs/goal.feature MK38), from what's on disk and nothing the agent
//! says: the record of renders and checks, the parts seen closer than planned, the judge's rounds on the kind's rubric
//! and the make questions asked of its sheets. `raea goal gates --json` prints them, and raea/goal's record and critic
//! packs hold the job to them (sdk/goal/src/packs/job.ts); deliverables and notes are packs of their own. Pure over a
//! `Job` so it is tested on fixtures.
use std::{path::{Path, PathBuf}, time::SystemTime};
use raea_core_brief::goal::{self, Goal};
use raea_core_facts::{Level, record::Entry};
use serde_json::{Value, json};
/// Everything the gates read, gathered by `lib.rs` (or a test).
pub struct Job<'a> {
pub make: &'a Goal,
/// the brief's folder: deliverables, NOTES.md and review/ are relative to it
pub dir: &'a Path,
/// the project's folder (record paths are relative to it), when it is a raea project
pub project: Option<&'a Path>,
pub record: &'a [Entry],
/// review/judge.log.jsonl's rounds, oldest first
pub rounds: &'a [Value],
/// the latest round's judge.json, when there is one
pub verdict: Option<&'a Value>,
/// when the judge last wrote its log
pub judged_at: Option<SystemTime>,
/// `raea ask`'s ledger, for the make questions' gate (asked.rs)
pub ledger: &'a crate::asked::Ledger,
/// `raea judge calibrate --kind KIND` agreed with the person's eye for this kind: its score gates too (MK6)
pub score_gates: bool,
}
/// A round's folder: as the judge wrote it when absolute, else the folder of that name beside the log (review/), since
/// `raea judge DIR` keeps its log in DIR's parent and DIR was written relative to wherever it ran.
pub fn round_dir(dir: &Path, round: &Value) -> Option<PathBuf> {
let d = Path::new(round["dir"].as_str()?);
if d.is_absolute() {
return Some(d.to_path_buf());
}
Some(dir.join("review").join(d.file_name()?))
}
/// The sheets the make questions are asked of: the newest round's (its framing sheet for a shot list, its colour and
/// clay sheets otherwise) and a kit's reference sheet.
pub fn sheets(job: &Job) -> Vec<(&'static str, PathBuf)> {
let mut out = Vec::new();
if let Some(r) = job.rounds.last().and_then(|r| round_dir(job.dir, r)) {
if job.make.kind == goal::Kind::Shot {
out.push(("framing", r.join("framing.png")));
} else {
out.push(("clay", r.join("clay.png")));
out.push(("colour", r.join("colour.png")));
}
}
if job.make.kind == goal::Kind::Kit {
out.push(("refs", job.dir.join("review/refs.png")));
}
out.into_iter().filter(|(_, f)| f.is_file()).collect()
}
/// When a file last changed, and that as seconds since 1970 (a record entry's clock).
fn mtime(p: &Path) -> Option<SystemTime> {
std::fs::metadata(p).ok()?.modified().ok()
}
fn mtime_secs(p: &Path) -> Option<u64> {
Some(mtime(p)?.duration_since(SystemTime::UNIX_EPOCH).ok()?.as_secs())
}
fn is_picture(p: &Path) -> bool {
matches!(p.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).as_deref(), Some("png" | "jpg" | "jpeg" | "exr"))
}
/// One deliverable: a file, `a|b` (either), or `dir/` (three or more pictures in it). Returns the files that answer it.
fn answered(dir: &Path, want: &str) -> Result<Vec<PathBuf>, String> {
if let Some(folder) = want.strip_suffix('/') {
let pics: Vec<PathBuf> = std::fs::read_dir(dir.join(folder)).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| is_picture(p)).collect();
return if pics.len() >= 3 { Ok(pics) } else { Err(format!("{want} holds {} picture{}; three or more", pics.len(), if pics.len() == 1 { "" } else { "s" })) };
}
let found: Vec<PathBuf> = want.split('|').map(|w| dir.join(w)).filter(|p| p.is_file()).collect();
if found.is_empty() { Err(want.replace('|', " or ")) } else { Ok(found) }
}
fn notes_text(dir: &Path) -> Option<String> {
std::fs::read_to_string(dir.join("NOTES.md")).ok()
}
/// AnyKit's stall: three rounds in a row without beating the best mean before them. Not the judge's own `stall`
/// (the same defect twice: change the approach), which is advice to the agent, not a reason to let it stop.
pub fn stalled(rounds: &[Value]) -> bool {
let means: Vec<f64> = rounds.iter().filter_map(|r| r["mean"].as_f64()).collect();
means.len() >= 4 && {
let (before, last) = means.split_at(means.len() - 3);
last.iter().cloned().fold(f64::MIN, f64::max) <= before.iter().cloned().fold(f64::MIN, f64::max)
}
}
fn gate(name: &str, of: Option<&str>, clear: bool, says: String) -> Value {
let mut g = json!({"gate": name, "clear": clear, "says": says});
if let Some(of) = of {
g["of"] = json!(of);
}
g
}
/// Tier 1: each composition the plan names has a render or check newer than it that found no error.
fn checks(job: &Job) -> Vec<Value> {
job.make
.compositions
.iter()
.map(|c| {
let file = job.dir.join(c);
let rel = job.project.map(|p| raea_core_facts::record::rel(p, &file)).unwrap_or_else(|| c.clone());
let Some(last) = job.record.iter().rev().find(|e| e.of == rel) else {
return gate("checks", Some(c), false, format!("never rendered or checked: raea render {c} (or raea scene lint {c})"));
};
let changed = mtime_secs(&file);
if changed.is_some_and(|t| t > last.at) {
return gate("checks", Some(c), false, format!("changed since its last {} ({}): run it again", last.by, last.id));
}
let errors: Vec<&str> = last.findings.iter().filter(|f| f.level == Level::Error).map(|f| f.says.as_str()).collect();
match errors.as_slice() {
[] => gate("checks", Some(c), true, format!("clean at {} ({})", last.id, last.by)),
[one] => gate("checks", Some(c), false, format!("{} found: {one}", last.id)),
many => gate("checks", Some(c), false, format!("{} found {} errors, first: {}", last.id, many.len(), many[0])),
}
})
.collect()
}
/// MK24: parts a composition's last render showed closer than planned, held until replanned or answered (raea-runtime-lod-plan)
fn lods(job: &Job, notes: &str) -> Vec<Value> {
let plans = job.make.objects.iter().any(|o| o.lod.is_some());
let last = |c: &String| job.record.iter().rev().find(|e| e.of == job.project.map(|p| raea_core_facts::record::rel(p, &job.dir.join(c))).unwrap_or_else(|| c.clone()));
job.make.compositions.iter().filter_map(|c| last(c).and_then(|l| raea_runtime_lod_plan::gate(c, &l.id, &l.findings, notes, plans)).map(|(clear, says)| gate("lod", Some(c), clear, says))).collect()
}
/// Tier 3: a fresh critic has judged a round newer than the newest deliverable, and each blocking defect it named is
/// fixed (the round passed) or answered in NOTES.md by its name. Its score gates once the judge is calibrated.
fn critic(job: &Job, newest: Option<SystemTime>, notes: &str) -> Vec<Value> {
let Some(last) = job.rounds.last() else {
let kind = job.make.kind.name();
let what = match job.make.kind {
goal::Kind::Kit => "raea render shared/components/KIT/lineup.tsx --review review/r1",
goal::Kind::Shot => "raea make framing --out review/r1",
goal::Kind::Scene | goal::Kind::Cut | goal::Kind::Rules => "raea render EDIT.tsx --review review/r1",
};
return vec![gate("critic", None, false, format!("no round yet: {what}, then raea judge review/r1 --kind {kind} --by claude --brief brief.ts"))];
};
let mut out = Vec::new();
let fresh = match (job.judged_at, newest) {
(Some(j), Some(n)) => j >= n,
(Some(_), None) => true,
_ => false,
};
out.push(gate("critic", None, fresh, if fresh { format!("round {} judged after the newest deliverable", job.rounds.len()) } else { "the newest deliverable came after the last round: review and judge it again".into() }));
// the kind's own rubric (MK5): a round judged on another's doesn't count
let kind = job.make.kind.name();
if last["kind"].as_str() != Some(kind) {
let dir = last["dir"].as_str().unwrap_or("review/rN");
out.push(gate("rubric", None, false, format!("the last round wasn't judged on the {kind} rubric: raea judge {dir} --kind {kind} --by claude")));
}
let blocking: Vec<&str> = raea_app_judge::rubric::blocking(last["defects"].as_array().map(Vec::as_slice).unwrap_or_default());
let open: Vec<&str> = if last["pass"] == true { Vec::new() } else { blocking.into_iter().filter(|d| !notes.contains(d)).collect() };
out.push(gate("defects", None, open.is_empty(), if open.is_empty() { "no blocking defect left unanswered".into() } else { format!("blocking, neither fixed nor answered in NOTES.md: {}", open.join(", ")) }));
// the score gates once the judge is calibrated for this kind; before that, fixed-or-answered is enough (MK6)
if job.score_gates {
let p = raea_app_judge::progress(job.rounds);
let done = p["done"] == true;
out.push(gate("score", None, done, format!("the calibrated judge: {} passes in a row, two needed", p["passesInARow"])));
}
out
}
/// The job's gates: each, whether all are clear, and why it's delivered short (out of rounds, or stalled) when it is.
pub fn gates(job: &Job) -> Value {
// the newest deliverable: a round judged before it is stale (the deliverables pack says what's missing)
let newest = goal::deliverables(job.make).iter().filter_map(|w| answered(job.dir, w).ok()).flatten().filter_map(|f| mtime(&f)).max();
let notes = notes_text(job.dir).unwrap_or_default();
let mut gates = checks(job);
gates.extend(lods(job, &notes));
gates.extend(critic(job, newest, &notes));
let (asks, said) = crate::asked::gates(&sheets(job), job.ledger, &notes);
gates.extend(asks);
let cap = job.make.rounds.unwrap_or(goal::ROUNDS) as usize;
let clear = gates.iter().all(|g| g["clear"] == true);
let mut short = Vec::new();
if job.rounds.len() >= cap && !clear {
short.push(format!("capped: {} critic rounds, the most this job gets; delivered with what's still open", job.rounds.len()));
}
if stalled(job.rounds) && !clear {
short.push("stalled: three rounds without beating the best before them; delivered with what's still open".to_string());
}
let advice = raea_app_judge::progress(job.rounds);
json!({
"kind": job.make.kind,
"clear": clear,
"short": short,
"gates": gates,
"judge": {"rounds": job.rounds.len(), "cap": cap, "passesInARow": advice["passesInARow"], "changeApproach": advice["stall"], "again": advice["again"]},
"advice": said,
})
}
+1 -1
View File
@@ -158,7 +158,7 @@ pub fn sheet_refs(dir: &Path, m: &Goal) -> Result<String, String> {
rows.extend(refs.chunks(4).map(|c| c.iter().map(|t| Tile { img: t.img.clone(), label: t.label.clone() }).collect()));
let file = dir.join("review/refs.png");
sheet("Reference sheet: the style, then every object's reference", &rows, 320, &file)?;
Ok(format!("wrote {}: regenerate an outlier before any 3D (raea make refs --only ID); ask it: raea ask {} --std make.refs.outlier --std make.refs.two_objects --std make.refs.brands", file.display(), file.display()))
Ok(format!("wrote {}: regenerate an outlier before any 3D (raea make refs --only ID)", file.display()))
}
/// The flow that sends one reference to both generators, each at its face limit.
+10 -43
View File
@@ -1,18 +1,14 @@
//! The asset tools for a scene, kit or shot goal (docs/goal.feature): `raea make blockout|refs|...` build to the goal's
//! frozen plan (`goal` on brief.ts, core/brief goal.rs), and `raea goal gates` gives the record and critic gates
//! raea/goal's packs read. The loop itself, every rule at its moments, is TypeScript: `raea goal check|tasks|seen|judge`
//! run sdk/goal/src/run.ts (engine/cli verbs.rs goal_ts).
//! frozen plan (`goal` on brief.ts, core/brief goal.rs). The loop itself, every rule at its moments, is TypeScript:
//! `raea check` and `raea goal tasks` run sdk/goal/src/run.ts (engine/cli verbs.rs goal_ts).
//!
//! raea goal gates [DIR] [--goal NAME] --json (the record and critic gates of a scene, kit or shot goal)
//! raea make blockout|refs|sheet refs|gen|pick-sheet|pick|prep|kit|framing|lenschart ... (the steps, USAGE)
pub mod asked;
pub mod floor;
pub mod kit;
pub mod kitout;
pub mod sheet;
pub mod shots;
pub mod gates;
use std::path::{Path, PathBuf};
@@ -20,7 +16,6 @@ use raea_core_brief::goal::Goal;
use serde_json::Value;
pub const USAGE: &str = "raea make place FILE [--at S[,S...]] [--box WxH] (the clearest places in a shot for a text box that size, in a 1080-wide frame)
raea goal gates [DIR] [--goal NAME] --json (a scene, kit or shot goal's record and critic gates, as raea/goal's packs read them)
raea make blockout [DIR] [--no-review] (a scene's blockout stop: review/plan/floor-plan.png, a grey-box blockout from the entrance and its review sheets, comparison.png beside reference 0)
raea make refs [DIR] [--only ID,...] [--model M] [--dry] (a kit: every object's reference from the style images, in the plan's style, then review/refs.png; --dry quotes it)
raea make sheet refs [DIR] (review/refs.png again: the style images, then every reference)
@@ -59,7 +54,7 @@ pub fn read_goals(brief: &Path) -> Result<Vec<Goal>, String> {
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
let out = std::process::Command::new(exe).arg("spec").arg(brief).args(["--as", "brief"]).env("RAEA_RECORD", "off").output().map_err(|e| e.to_string())?;
let text = String::from_utf8_lossy(&out.stdout);
let start = text.find('{').ok_or_else(|| format!("{} didn't read as a brief: {}", brief.display(), raea_app_judge::why_refused(&out)))?;
let start = text.find('{').ok_or_else(|| format!("{} didn't read as a brief: {}", brief.display(), why_refused(&out)))?;
let v: Value = serde_json::from_str(&text[start..]).map_err(|e| format!("{}: {e}", brief.display()))?;
let b = v.get("brief").cloned().unwrap_or(v);
match b.get("goal") {
@@ -71,6 +66,12 @@ pub fn read_goals(brief: &Path) -> Result<Vec<Goal>, String> {
}
}
/// Why a raea that ran printed no answer: its last line said (a refusal's word taken off), else that it printed nothing.
fn why_refused(out: &std::process::Output) -> String {
let last = |b: &[u8]| String::from_utf8_lossy(b).lines().rev().find(|l| !l.trim().is_empty()).map(|l| l.trim().trim_start_matches("REFUSED").trim().to_string());
last(&out.stderr).or_else(|| last(&out.stdout)).unwrap_or_else(|| "raea spec printed nothing".into())
}
/// The scene, kit or shot goal the asset tools build to: the one named, else the only one of those kinds.
pub fn read_goal(brief: &Path) -> Result<Option<Goal>, String> {
read_goal_named(brief, None)
@@ -90,35 +91,8 @@ pub fn read_goal_named(brief: &Path, name: Option<&str>) -> Result<Option<Goal>,
}
}
/// The judge's rounds beside the brief (review/judge.log.jsonl, as `raea judge` keeps them), the newest round's
/// verdict (judge.json, or judge.BY.json for an agent critic), and when the log was last written.
fn judged(dir: &Path) -> (Vec<Value>, Option<Value>, Option<std::time::SystemTime>) {
let log = dir.join("review").join("judge.log.jsonl");
let rounds: Vec<Value> = std::fs::read_to_string(&log).unwrap_or_default().lines().filter_map(|l| serde_json::from_str(l).ok()).collect();
let verdict = rounds.last().and_then(|r| {
let d = gates::round_dir(dir, r)?;
let file = r["by"].as_str().filter(|b| *b != "clef").map_or_else(|| "judge.json".to_string(), |b| format!("judge.{b}.json"));
serde_json::from_str(&std::fs::read_to_string(d.join(file)).ok()?).ok()
});
let at = std::fs::metadata(&log).and_then(|m| m.modified()).ok();
(rounds, verdict, at)
}
/// The record and critic gates of the job whose brief is at `brief`, with its plan already read.
pub fn gates_of(brief: &Path, make: &Goal) -> Value {
let dir = brief.parent().unwrap_or(Path::new("."));
let project = raea_core_facts::record::up(dir, ".raea/project");
let record = project.as_deref().map(raea_core_facts::record::read).unwrap_or_default();
let (rounds, verdict, judged_at) = judged(dir);
let ledger = asked::Ledger::read();
let job = gates::Job { make, dir, project: project.as_deref(), record: &record, rounds: &rounds, verdict: verdict.as_ref(), judged_at, ledger: &ledger, score_gates: raea_app_judge::kind_gates(make.kind.name()) };
let mut s = gates::gates(&job);
s["brief"] = Value::String(brief.display().to_string());
s
}
/// The flags that take a value: what follows them isn't a positional argument.
const VALUED: [&str; 9] = ["--only", "--model", "--tripo", "--meshy", "--name", "--to", "--out", "--by", "--goal"];
const VALUED: [&str; 8] = ["--only", "--model", "--tripo", "--meshy", "--name", "--to", "--out", "--goal"];
fn flag<'a>(args: &'a [String], k: &str) -> Option<&'a str> {
args.iter().position(|a| a == k).and_then(|i| args.get(i + 1)).map(String::as_str)
@@ -199,17 +173,10 @@ fn step(verb: &str, args: &[String]) -> Result<String, String> {
pub fn cli(args: &[String]) -> Result<String, String> {
match args.get(1).map(String::as_str) {
Some("gates") => {
let dir = positional(args, 2).first().map(PathBuf::from).unwrap_or_else(|| PathBuf::from("."));
let (brief, make) = job(&dir, flag(args, "--goal"))?;
Ok(serde_json::to_string_pretty(&gates_of(&brief, &make)).unwrap_or_default())
}
Some(v @ ("blockout" | "refs" | "sheet" | "gen" | "pick-sheet" | "pick" | "prep" | "kit" | "framing" | "lenschart")) => step(v, args),
_ => Err(USAGE.into()),
}
}
#[cfg(test)]
mod tests;
#[cfg(test)]
mod tests_steps;
+3 -3
View File
@@ -1,6 +1,6 @@
//! The contact sheets a gate looks at (docs/goal.feature MK10, MK11, MK15): pictures in rows, each labelled under it,
//! a title over them, on one PNG a person, `raea ask` and the critic read at once. Labels are drawn by resvg in the
//! system's own fonts; an SVG drawn whole (the floor plan, MK18) goes through `svg_png`.
//! The contact sheets a person looks at (docs/goal.feature MK10, MK11, MK15): pictures in rows, each labelled under it,
//! a title over them, on one PNG read at once. Labels are drawn by resvg in the system's own fonts; an SVG drawn whole
//! (the floor plan, MK18) goes through `svg_png`.
use std::path::{Path, PathBuf};
use std::sync::{Arc, OnceLock};
+4 -5
View File
@@ -1,8 +1,7 @@
//! Blocking a shot list (docs/goal.feature MK15): `raea make framing` renders each shot's first, middle and last
//! frame and puts them on one sheet, a row a shot, each stamped with its name and time, so the person, `raea ask`
//! (make.framing.*) and the critic (`raea judge --kind shot`) see every shot's start and end at once; `raea make
//! lenschart SHOT` renders a shot's first frame at 18, 24, 35, 50, 85 and 135 mm (RAEA_LENS, core/review) to choose its
//! lens before it's moved.
//! frame and puts them on one sheet, a row a shot, each stamped with its name and time, so the person sees every shot's
//! start and end at once; `raea make lenschart SHOT` renders a shot's first frame at 18, 24, 35, 50, 85 and 135 mm
//! (RAEA_LENS, core/review) to choose its lens before it's moved.
use std::path::{Path, PathBuf};
@@ -82,7 +81,7 @@ pub fn framing(dir: &Path, m: &Goal, only: &[String], out: &Path) -> Result<Stri
}
let file = out.join("framing.png");
sheet("Framing: each shot's first, middle and last frame", &rows, 480, &file)?;
Ok(format!("wrote {} ({} shot{}); ask it: raea ask {} --set make (the framing questions apply); judge it: raea judge {} --kind shot", file.display(), shots.len(), if shots.len() == 1 { "" } else { "s" }, file.display(), out.display()))
Ok(format!("wrote {} ({} shot{})", file.display(), shots.len(), if shots.len() == 1 { "" } else { "s" }))
}
/// One shot's first frame at every lens of the chart, on one sheet (OUT/lens-SHOT.png).
-196
View File
@@ -1,196 +0,0 @@
use std::path::PathBuf;
use std::time::{Duration, SystemTime};
use raea_core_brief::{goal::Goal, read};
use raea_core_facts::record::Entry;
use serde_json::{Value, json};
use crate::asked::Ledger;
use crate::gates::{Job, gates, stalled};
fn dir(name: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("raea-make-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
d
}
fn put(d: &PathBuf, rel: &str, text: &str) {
let p = d.join(rel);
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(p, text).unwrap();
}
fn kit() -> Goal {
read("make", r#"{"kind": "kit", "style": "1970s desk, maker Aurora", "objects": [{"id": "phone", "label": "Phone", "h": 0.12, "prompt": "a rotary phone"}]}"#).unwrap()
}
fn delivered(d: &PathBuf) {
for f in ["out/kit/phone/phone.glb", "out/kit/phone/phone_lod1.glb", "out/kit/thumbs/phone.png", "out/kit/lineup.png", "out/kit/kit.json", "review/refs.png"] {
put(d, f, "x");
}
put(d, "NOTES.md", "# Notes\n\n## What the skill got wrong\n- nothing yet\n");
}
fn round(pass: bool, mean: f64, defects: Value) -> Value {
json!({"dir": "review/r1", "kind": "kit", "pass": pass, "mean": mean, "defects": defects})
}
fn run(make: &Goal, d: &PathBuf, record: &[Entry], rounds: &[Value], judged_at: Option<SystemTime>) -> Value {
run_with(make, d, record, rounds, judged_at, &Ledger::default())
}
fn run_with(make: &Goal, d: &PathBuf, record: &[Entry], rounds: &[Value], judged_at: Option<SystemTime>, ledger: &Ledger) -> Value {
gates(&Job { make, dir: d, project: None, record, rounds, verdict: None, judged_at, ledger, score_gates: false })
}
fn later() -> Option<SystemTime> {
Some(SystemTime::now() + Duration::from_secs(5))
}
#[test]
fn delivered_and_judged_after_is_done() {
let d = dir("done");
delivered(&d);
let s = run(&kit(), &d, &[], &[round(true, 7.5, json!([]))], later());
assert_eq!(s["clear"], true, "{s:#}");
assert_eq!(s["short"], json!([]));
}
#[test]
fn a_round_older_than_the_newest_deliverable_is_stale() {
let d = dir("stale");
delivered(&d);
let s = run(&kit(), &d, &[], &[round(true, 7.5, json!([]))], Some(SystemTime::UNIX_EPOCH));
assert_eq!(s["clear"], false);
assert!(s["gates"].to_string().contains("came after the last round"), "{s:#}");
}
#[test]
fn a_blocking_defect_must_be_fixed_or_answered_in_the_notes() {
let d = dir("defect");
delivered(&d);
let defects = json!([{"defect": "floating", "present": true, "level": "blocking"}]);
let s = run(&kit(), &d, &[], &[round(false, 6.0, defects.clone())], later());
assert_eq!(s["clear"], false);
assert!(s["gates"].to_string().contains("floating"));
put(&d, "NOTES.md", "## What the skill got wrong\n- floating: the handset rests in its cradle; the judge read its shadow as a gap\n");
let s = run(&kit(), &d, &[], &[round(false, 6.0, defects.clone())], later());
assert_eq!(s["clear"], true, "{s:#}");
// once the judge is calibrated for kits, its score gates too: two passes in a row (MK6)
let (rounds, ledger) = ([round(false, 6.0, defects)], Ledger::default());
let s = gates(&Job { make: &kit(), dir: &d, project: None, record: &[], rounds: &rounds, verdict: None, judged_at: later(), ledger: &ledger, score_gates: true });
assert_eq!(s["clear"], false, "{s:#}");
assert!(s["gates"].to_string().contains("two needed"), "{s:#}");
}
#[test]
fn at_the_cap_it_is_delivered_short() {
let d = dir("cap");
// eight rounds, the last still blocked by a defect no one answered
let blocked = json!([{"defect": "floating", "present": true, "level": "blocking"}]);
let rounds: Vec<Value> = (0..8).map(|i| round(false, 5.0 + i as f64 * 0.5, blocked.clone())).collect();
let s = run(&kit(), &d, &[], &rounds, later());
assert_eq!(s["clear"], false, "{s:#}");
assert!(s["short"].to_string().contains("capped"), "{s:#}");
}
#[test]
fn three_rounds_without_beating_the_best_is_a_stall() {
let r = |m: f64| json!({"mean": m});
assert!(stalled(&[r(5.0), r(6.5), r(6.0), r(6.4), r(6.5)]));
assert!(!stalled(&[r(5.0), r(6.0), r(6.2), r(6.4), r(6.6)]));
assert!(!stalled(&[r(5.0), r(5.0), r(5.0)]), "too few rounds to call it");
}
#[test]
fn a_composition_needs_a_clean_check_newer_than_it() {
let d = dir("checks");
delivered(&d);
put(&d, "scene.tsx", "x");
let mut make = kit();
make.compositions = vec!["scene.tsx".into()];
let rounds = [round(true, 7.5, json!([]))];
let s = run(&make, &d, &[], &rounds, later());
assert!(s["gates"].to_string().contains("never rendered"), "{s:#}");
let entry = |at: u64, level: &str| -> Entry {
serde_json::from_value(json!({"id": "20261123-x", "at": at, "by": "raea render", "of": "scene.tsx",
"findings": [{"check": "float", "level": level, "says": "the mug floats 2 cm", "by": "raea scene lint"}]})).unwrap()
};
let future = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs() + 60;
let s = run(&make, &d, &[entry(future, "error")], &rounds, later());
assert!(s["gates"].to_string().contains("the mug floats"), "{s:#}");
let s = run(&make, &d, &[entry(future, "warn")], &rounds, later());
assert_eq!(s["clear"], true, "a warn doesn't block: {s:#}");
let s = run(&make, &d, &[entry(1, "warn")], &rounds, later());
assert!(s["gates"].to_string().contains("changed since"), "{s:#}");
}
// MK24: a part a render showed closer than planned holds the job until it's replanned or answered in the notes
#[test]
fn a_part_seen_closer_than_planned_holds_the_job() {
let d = dir("lod");
delivered(&d);
put(&d, "scene.tsx", "x");
let mut make = kit();
make.compositions = vec!["scene.tsx".into()];
let future = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs() + 60;
let entry: Entry = serde_json::from_value(json!({"id": "r1", "at": future, "by": "raea render", "of": "scene.tsx", "findings": [{"check": "lod-closer", "level": "warn", "about": [{"name": "kiosk"}], "says": "'kiosk' is planned at LOD 3", "by": "raea render"}]})).unwrap();
let s = run(&make, &d, &[entry.clone()], &[round(true, 7.5, json!([]))], later());
assert!(s["clear"] == false && s["gates"].to_string().contains("seen closer than planned at r1: kiosk"), "{s:#}");
put(&d, "NOTES.md", "- lod kiosk: one frame at the cut, left as a box\n## What the skill got wrong\n- nothing\n");
assert_eq!(run(&make, &d, &[entry], &[round(true, 7.5, json!([]))], later())["clear"], true);
}
#[test]
fn a_round_judged_on_another_kinds_rubric_does_not_count() {
// docs/goal.feature MK5: a kit is judged on the kit's rubric
let d = dir("rubric");
delivered(&d);
let old = json!({"dir": "review/r1", "pass": true, "mean": 8.0, "defects": []});
let s = run(&kit(), &d, &[], &[old], later());
assert_eq!(s["clear"], false);
assert!(s["gates"].to_string().contains("--kind kit"), "{s:#}");
}
#[test]
fn a_calibrated_ask_question_gates_and_an_uncalibrated_one_advises() {
// docs/goal.feature MK4
let d = dir("ask");
delivered(&d);
put(&d, "review/r1/clay.png", "clay sheet bytes");
put(&d, "review/r1/colour.png", "colour sheet bytes");
let rounds = [round(true, 7.5, json!([]))];
let floating = raea_core_ask::library::find("make.clay.floating", None).unwrap();
let mut ledger = Ledger::default();
// nothing calibrated: every question is advice, and the job is done
let s = run_with(&kit(), &d, &[], &rounds, later(), &ledger);
assert_eq!(s["clear"], true, "{s:#}");
assert!(s["gates"].to_string().contains("advice only"), "{s:#}");
// floating calibrated on the person's labels: it must be asked of this exact clay sheet
ledger.calibrations.insert(floating.version(), serde_json::from_value(json!({"auc": 0.9, "n": 40, "positives": 16, "threshold": 0.4, "date": "2026-11-23", "by": "you"})).unwrap());
let s = run_with(&kit(), &d, &[], &rounds, later(), &ledger);
assert_eq!(s["clear"], false);
let gates = s["gates"].to_string();
assert!(gates.contains("not asked of this clay sheet") && gates.contains("--std make.clay.floating"), "{gates}");
// asked, and it flagged: open until fixed or answered by its id in NOTES.md
let ident = raea_core_ask::ident::ident(&d.join("review/r1/clay.png")).unwrap();
ledger.idents.insert("c-1".into(), ident);
ledger.answers.push(json!({"id": "a-1", "at": "100", "call": "c-1", "question": "make.clay.floating", "flagged": true, "problem": 0.8}));
let s = run_with(&kit(), &d, &[], &rounds, later(), &ledger);
assert_eq!(s["clear"], false);
assert!(s["gates"].to_string().contains("make.clay.floating flagged (p 0.80)"), "{s:#}");
put(&d, "NOTES.md", "## What the skill got wrong\n- make.clay.floating: the handset's shadow, not a gap; checked on the low tile\n");
let s = run_with(&kit(), &d, &[], &rounds, later(), &ledger);
assert_eq!(s["clear"], true, "{s:#}");
// the sheet rendered again: the old answer was about other bytes, so it's asked again
put(&d, "review/r1/clay.png", "a new clay sheet");
let s = run_with(&kit(), &d, &[], &rounds, later(), &ledger);
assert!(s["gates"].to_string().contains("not asked of this clay sheet"), "{s:#}");
// an uncalibrated question that flags is said as advice, holding nothing
let ident = raea_core_ask::ident::ident(&d.join("review/r1/colour.png")).unwrap();
ledger.idents.insert("c-2".into(), ident);
ledger.answers.push(json!({"id": "a-2", "at": "101", "call": "c-2", "question": "make.colour.plastic", "flagged": true, "problem": 0.7}));
let s = run_with(&kit(), &d, &[], &rounds, later(), &ledger);
assert!(s["advice"].to_string().contains("make.colour.plastic says yes"), "{s:#}");
}
+3 -3
View File
@@ -3,7 +3,7 @@
use std::path::PathBuf;
use image::{Rgba, RgbaImage};
use raea_core_brief::{make::Make, read};
use raea_core_brief::{goal::Goal as Make, read};
use crate::sheet::{Tile, sheet};
@@ -148,7 +148,7 @@ fn a_shot_frames_its_start_middle_and_end() {
// a shot with no composition can't be framed, and says what's needed
let d = dir("framing");
assert!(crate::shots::framing(&d, &m, &["hold".to_string()], &d).unwrap_err().contains("no composition"));
assert!(raea_core_brief::make::doctor(&m).iter().any(|w| w.contains("shot `hold` has no composition")));
assert!(raea_core_brief::goal::doctor(&m).iter().any(|w| w.contains("shot `hold` has no composition")));
}
// MK18: the floor plan draws every placed footprint (invented ones dashed); the blockout boxes them from the entrance
@@ -193,7 +193,7 @@ fn a_quote_reads_as_one_line() {
#[test]
fn a_boxy_model_is_fitted_by_its_height_and_turned_to_lie_front_to_back() {
use raea_core_brief::make::Object;
use raea_core_brief::goal::Object;
let stapler: Object = serde_json::from_value(serde_json::json!({"id": "stapler", "label": "Stapler", "dims": [0.05, 0.17, 0.07]})).unwrap();
// long across (x) where the plan's is front to back (z): a quarter turn
assert_eq!(crate::kit::fit_args(&stapler, Some([1.9, 0.72, 0.58])), ["--dims", "0.05,0.17,0.07", "--h", "0.07", "--turn", "90"]);
+26 -4
View File
@@ -40,6 +40,29 @@ pub fn still(path: &Path, at: f64, out: &Path, width: Option<u32>) -> R<Value> {
Ok(json!({"wrote": out, "at": at, "width": img.width(), "height": img.height()}))
}
/// `f(0..n)`, up to four at a time, in order: a sheet's frames are each a seek and a decode of their own (16 of a 4K
/// interview: 7 s one after another, 4 s so).
fn at_once<T: Send>(n: usize, f: impl Fn(usize) -> R<T> + Sync) -> R<Vec<T>> {
use std::sync::{Mutex, atomic::{AtomicUsize, Ordering}};
let workers = std::thread::available_parallelism().map_or(2, |c| c.get()).clamp(1, 4).min(n.max(1));
let next = AtomicUsize::new(0);
let out: Vec<Mutex<Option<R<T>>>> = (0..n).map(|_| Mutex::new(None)).collect();
std::thread::scope(|s| {
for _ in 0..workers {
s.spawn(|| {
loop {
let i = next.fetch_add(1, Ordering::Relaxed);
if i >= n {
break;
}
*out[i].lock().unwrap() = Some(f(i));
}
});
}
});
out.into_iter().map(|m| m.into_inner().unwrap().unwrap_or_else(|| Err("a frame wasn't read".into()))).collect()
}
pub fn sheet(files: &[PathBuf], n: usize, w: u32, out: &Path) -> R<Value> {
if files.is_empty() {
return Err("raea media sheet FILE... -o OUT: which files?".into());
@@ -47,10 +70,9 @@ pub fn sheet(files: &[PathBuf], n: usize, w: u32, out: &Path) -> R<Value> {
let mut tiles = Vec::new();
if files.len() == 1 {
let p = probe_of(&files[0])?;
for i in 0..n.max(1) {
let t = (i as f64 + 0.5) / n.max(1) as f64 * p.duration;
tiles.push((t, frame(&files[0], t)?));
}
let at: Vec<f64> = (0..n.max(1)).map(|i| (i as f64 + 0.5) / n.max(1) as f64 * p.duration).collect();
let read = at_once(at.len(), |i| frame(&files[0], at[i]))?;
tiles.extend(at.into_iter().zip(read));
} else {
for f in files {
let p = probe_of(f)?;
+69 -62
View File
@@ -1,6 +1,7 @@
//! `media probe`: what a file is (duration, size, fps, codec, audio), with the MP4 boxes read directly for a track's own timing.
use super::*;
use raea_io_media::mp4box::{be32, be64, boxes, child, moov_of};
pub(crate) fn round3(x: f64) -> f64 {
(x * 1000.0).round() / 1000.0
@@ -38,7 +39,11 @@ pub fn probe_of(path: &Path) -> R<Probe> {
}
i
});
let audio = soft()?.decode_audio(path).ok().filter(|a| a.len() > 0).map(|a| (a.rate, a.channels.len(), a.duration()));
// what the file states, when it does; else the track decoded (WAV, MP3, a container read no other way)
let audio = match audio_track(path) {
Some(a) => Some(a),
None => soft()?.decode_audio(path).ok().filter(|a| a.len() > 0).map(|a| (a.rate, a.channels.len(), a.duration())),
};
if video.is_none() && audio.is_none() {
// what each backend said about the picture: a missing FFmpeg, a codec none of them reads
let why = why.map(|w| format!(" ({})", w.split_once(": no backend reads it (").map_or(w.as_str(), |(_, r)| r.trim_end_matches(')')).to_string())).unwrap_or_default();
@@ -124,74 +129,37 @@ impl Track {
}
}
/// The boxes inside `b` (a box's payload): (type, payload).
pub(crate) fn boxes(b: &[u8]) -> Vec<([u8; 4], &[u8])> {
let mut out = Vec::new();
let mut i = 0usize;
while i + 8 <= b.len() {
let mut size = u32::from_be_bytes(b[i..i + 4].try_into().unwrap()) as usize;
let kind: [u8; 4] = b[i + 4..i + 8].try_into().unwrap();
let mut hdr = 8;
if size == 1 && i + 16 <= b.len() {
size = u64::from_be_bytes(b[i + 8..i + 16].try_into().unwrap()) as usize;
hdr = 16;
} else if size == 0 {
size = b.len() - i;
/// The first sound track as the file states it (rate, channels, seconds), for MP4 and QuickTime files: `media probe`
/// decoded the whole track to learn these, which read every byte of a 1 GB interview (two minutes on a network disk).
pub fn audio_track(path: &Path) -> Option<(u32, usize, f64)> {
audio_in(&moov_of(path)?)
}
pub(crate) fn audio_in(moov: &[u8]) -> Option<(u32, usize, f64)> {
for (k, trak) in boxes(moov) {
if &k != b"trak" {
continue;
}
if size < hdr || i + size > b.len() {
break;
let Some(mdia) = child(trak, b"mdia") else { continue };
if child(mdia, b"hdlr").and_then(|h| h.get(8..12)) != Some(&b"soun"[..]) {
continue;
}
out.push((kind, &b[i + hdr..i + size]));
i += size;
let mdhd = child(mdia, b"mdhd")?;
let (scale, dur) = if mdhd.first() == Some(&1) { (be32(mdhd, 20)? as f64, be64(mdhd, 24)? as f64) } else { (be32(mdhd, 12)? as f64, be32(mdhd, 16)? as f64) };
// the first sample description: version at 24, channels at 32, rate (16.16) at 40; QuickTime's version 2 states
// them again as a double at 48 and a count at 56
let stsd = child(child(child(mdia, b"minf")?, b"stbl")?, b"stsd")?;
let v2 = stsd.get(24..26) == Some(&[0u8, 2][..]);
let rate = if v2 { f64::from_bits(be64(stsd, 48)?) } else { be32(stsd, 40)? as f64 / 65536.0 };
let channels = if v2 { be32(stsd, 56)? as usize } else { u16::from_be_bytes(stsd.get(32..34)?.try_into().ok()?) as usize };
return (scale > 0.0 && dur > 0.0 && rate >= 1.0 && (1..=64).contains(&channels)).then_some((rate.round() as u32, channels, dur / scale));
}
out
}
pub(crate) fn child<'a>(b: &'a [u8], kind: &[u8; 4]) -> Option<&'a [u8]> {
boxes(b).into_iter().find(|(k, _)| k == kind).map(|(_, p)| p)
}
pub(crate) fn be32(b: &[u8], at: usize) -> Option<u32> {
Some(u32::from_be_bytes(b.get(at..at + 4)?.try_into().ok()?))
}
pub(crate) fn be64(b: &[u8], at: usize) -> Option<u64> {
Some(u64::from_be_bytes(b.get(at..at + 8)?.try_into().ok()?))
None
}
/// The first video track's timing, for MP4 and QuickTime files.
pub fn video_track(path: &Path) -> Option<Track> {
use std::io::{Read, Seek, SeekFrom};
let mut f = std::fs::File::open(path).ok()?;
let len = f.metadata().ok()?.len();
// the top-level boxes, to moov (read alone: mdat can be gigabytes)
let mut at = 0u64;
let moov = loop {
if at + 8 > len {
return None;
}
let mut h = [0u8; 16];
f.seek(SeekFrom::Start(at)).ok()?;
f.read_exact(&mut h[..8]).ok()?;
let mut size = u32::from_be_bytes(h[..4].try_into().ok()?) as u64;
let mut hdr = 8u64;
if size == 1 {
f.read_exact(&mut h[8..]).ok()?;
size = u64::from_be_bytes(h[8..].try_into().ok()?);
hdr = 16;
} else if size == 0 {
size = len - at;
}
if size < hdr {
return None;
}
if &h[4..8] == b"moov" {
let mut m = vec![0u8; (size - hdr).min(256 << 20) as usize];
f.read_exact(&mut m).ok()?;
break m;
}
at += size;
};
let moov = moov_of(path)?;
for (k, trak) in boxes(&moov) {
if &k != b"trak" {
continue;
@@ -295,3 +263,42 @@ pub(crate) fn rate_fraction(fps: f64) -> String {
}
// ---- pictures
#[cfg(test)]
mod tests {
use super::*;
fn bx(kind: &[u8; 4], body: &[u8]) -> Vec<u8> {
let mut v = ((body.len() + 8) as u32).to_be_bytes().to_vec();
v.extend_from_slice(kind);
v.extend_from_slice(body);
v
}
#[test]
fn a_sound_track_is_read_from_the_file_s_own_tables() {
// mdhd v0: 48 kHz timescale, 10 s; stsd: one mp4a entry, 2 channels, 48000 Hz
let mut mdhd = vec![0u8; 24];
mdhd[12..16].copy_from_slice(&48000u32.to_be_bytes());
mdhd[16..20].copy_from_slice(&480000u32.to_be_bytes());
let mut hdlr = vec![0u8; 24];
hdlr[8..12].copy_from_slice(b"soun");
let mut stsd = vec![0u8; 44];
stsd[7] = 1;
stsd[12..16].copy_from_slice(b"mp4a");
stsd[32..34].copy_from_slice(&2u16.to_be_bytes());
stsd[40..44].copy_from_slice(&(48000u32 << 16).to_be_bytes());
let mdia = [bx(b"mdhd", &mdhd), bx(b"hdlr", &hdlr), bx(b"minf", &bx(b"stbl", &bx(b"stsd", &stsd)))].concat();
// a picture track ahead of it is passed over
let mut vh = vec![0u8; 24];
vh[8..12].copy_from_slice(b"vide");
let moov = [bx(b"trak", &bx(b"mdia", &bx(b"hdlr", &vh))), bx(b"trak", &bx(b"mdia", &mdia))].concat();
assert_eq!(audio_in(&moov), Some((48000, 2, 10.0)));
// no sound track, or one that states no rate: nothing (the track is decoded instead)
assert_eq!(audio_in(&bx(b"trak", &bx(b"mdia", &bx(b"hdlr", &vh)))), None);
let mut silent = stsd.clone();
silent[40..44].copy_from_slice(&0u32.to_be_bytes());
let mdia = [bx(b"mdhd", &mdhd), bx(b"hdlr", &hdlr), bx(b"minf", &bx(b"stbl", &bx(b"stsd", &silent)))].concat();
assert_eq!(audio_in(&bx(b"trak", &bx(b"mdia", &mdia))), None);
}
}
+5
View File
@@ -14,4 +14,9 @@ raea-runtime-bundle = { path = "../../runtime/bundle" }
raea-io-home = { path = "../../io/home" }
regex = "1"
serde_json = "1"
# the faces the native page draws with (core/fonts), inlined in the page under the families the game names (PA8)
raea-core-fonts = { path = "../../core/fonts" }
# a game's generated sounds made at export, as a render makes them, and FFmpeg to compress them (PA6)
raea-io-assets = { path = "../../io/assets" }
base64 = "0.22"
zip = { version = "9", default-features = false, features = ["deflate-flate2"] }
+127
View File
@@ -0,0 +1,127 @@
//! The page's fonts as the native render draws them (docs/playables.feature PA8). A composition's page draws with
//! raea's bundled faces (core/fonts: Fontsource latin subsets, a few weights a family), each family the page names
//! aliased onto one (Helvetica, Arial and SF Pro draw as Inter, Times as EB Garamond, ...) and each weight drawn by the
//! nearest face (core/fonts `face`). A phone has none of them, so brick-rush's Inter fell back to a serif. The export
//! inlines, for every family the game's script names that raea aliases, its faces as @font-face data URLs under that
//! name, each face's weight a range that makes the browser's choice the native one (Inter 400/700/900: 1-550, 551-800,
//! 801-1000; a weight halfway between two faces takes the lighter, as `face`'s first-found minimum does). The page's
//! own default family is Inter, the native page's.
use base64::Engine;
use std::collections::BTreeMap;
/// The family a page with no family of its own draws in
const DEFAULT: &str = "Inter";
/// Each family name the script writes (fontFamily values and CSS font-family declarations), as written, with the
/// bundled family raea draws it as; the default first
pub fn families(script: &str) -> Vec<(String, &'static str)> {
let mut out: Vec<(String, &'static str)> = vec![(DEFAULT.into(), "inter")];
let res = [
r#"fontFamily["']?\s*:\s*["'`]([^"'`]+)["'`]"#,
r#"font-family\s*:\s*([^;"'`}]+)"#,
];
for re in res {
let re = regex::Regex::new(re).expect("a valid pattern");
for cap in re.captures_iter(script) {
for name in cap[1].split(',') {
let name = name.trim().trim_matches(|c| c == '"' || c == '\'').trim();
if let Some(c) = raea_core_fonts::canonical(name) {
if !out.iter().any(|(n, _)| n.eq_ignore_ascii_case(name)) {
out.push((name.to_string(), c));
}
}
}
}
}
out
}
/// A bundled family's faces as (weight range, style, woff2): each style's weights split halfway between neighbours,
/// the halfway weight to the lighter face
pub fn faces(canonical: &str) -> Vec<((u16, u16), &'static str, &'static [u8])> {
let mut by_style: BTreeMap<&str, Vec<(u16, &'static [u8])>> = BTreeMap::new();
for (f, w, st, bytes) in raea_core_fonts::BUNDLED {
if *f == canonical {
by_style
.entry(st)
.or_default()
.push((w.parse().unwrap_or(400), bytes));
}
}
let mut out = Vec::new();
for (st, mut ws) in by_style {
ws.sort_by_key(|(w, _)| *w);
let mut lo = 1u16;
for (i, (w, bytes)) in ws.iter().enumerate() {
let hi = ws.get(i + 1).map_or(1000, |(next, _)| (w + next) / 2);
out.push(((lo, hi), st, *bytes));
lo = hi + 1;
}
}
out
}
/// The page's <style>: each family the script names that raea aliases, its faces inlined under that name, and the
/// page's default family
pub fn style(script: &str) -> String {
let b64 = base64::engine::general_purpose::STANDARD;
let mut css = String::from("<style>\n");
for (name, canonical) in families(script) {
for ((lo, hi), st, bytes) in faces(canonical) {
css.push_str(&format!(
"@font-face{{font-family:\"{}\";font-style:{st};font-weight:{lo} {hi};src:url(data:font/woff2;base64,{}) format(\"woff2\")}}\n",
name.replace('"', ""),
b64.encode(bytes)
));
}
}
css.push_str(&format!("html,body{{font-family:\"{DEFAULT}\"}}\n</style>"));
css
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn each_family_the_game_names_is_aliased_as_the_native_page_does() {
let script = r#"h("div",{style:{fontFamily:"Inter, system-ui, sans-serif",fontWeight:900}});x={fontFamily:'Helvetica Neue'};y="b{font-family: Georgia, serif;}""#;
let f = families(script);
assert_eq!(
f,
[
("Inter".to_string(), "inter"),
("Helvetica Neue".into(), "inter"),
("Georgia".into(), "eb-garamond")
]
);
}
#[test]
fn a_weight_takes_the_face_the_native_page_takes() {
let r: Vec<(u16, u16)> = faces("inter").iter().map(|(r, _, _)| *r).collect();
assert_eq!(r, [(1, 550), (551, 800), (801, 1000)]);
// the native pick for each weight is the face whose range holds it
for w in [100u16, 400, 550, 551, 700, 800, 801, 900] {
let native = raea_core_fonts::face("Inter", w, false).unwrap();
let ours = faces("inter")
.into_iter()
.find(|((lo, hi), _, _)| (*lo..=*hi).contains(&w))
.unwrap()
.2;
assert!(native == ours, "weight {w}");
}
}
#[test]
fn the_style_holds_inter_and_sets_the_default() {
let css = style("var x=1;");
assert_eq!(css.matches("@font-face").count(), 3);
assert!(
css.contains("font-weight:801 1000")
&& css.contains("html,body{font-family:\"Inter\"}")
);
assert!(css.len() < 110_000, "{} bytes", css.len());
}
}
+170 -18
View File
@@ -1,15 +1,19 @@
//! `raea playable GAME.tsx -o DIR`: a raea game exported as a playable ad (docs/playables.feature PA13). The same TSX
//! that renders with `raea render` as the video ad (it plays itself) is linted (lint.rs), bundled once with
//! sdk/playable's browser host by raea's own bundler (Rolldown, in process: minified, its pictures and tables carried
//! in the script, one three.js), and written as each network's page or ZIP (pages.rs), each checked against its cap.
//! in the script; three.js only when the lint found a 3D kind, PA15; a sound player only for a game with sound, Tone.js
//! only for a raea/tone graph, and its generated sounds made and carried in the page, PA6), and written as each
//! network's page or ZIP (pages.rs), each checked against its cap.
mod fonts;
mod lint;
mod pages;
mod sound;
use std::path::{Path, PathBuf};
type R<T> = Result<T, String>;
pub const USAGE: &str = "raea playable GAME.tsx -o DIR [--networks LIST] [--ios URL] [--android URL] [--title TEXT] [--cta TEXT] [--orientation portrait|landscape|both]";
pub const USAGE: &str = "raea playable GAME.tsx -o DIR [--name NAME] [--networks LIST] [--ios URL] [--android URL] [--title TEXT] [--cta TEXT] [--orientation portrait|landscape|both]";
pub const ABOUT: &str = "a game as a playable ad: one page or ZIP per network (applovin, unity, google, meta, moloco, mintegral, tiktok, liftoff, preview), each under its 5 MB cap, from the TSX that renders as the video ad";
/// A path as an import specifier (no Windows verbatim prefix, which Rolldown can't open): raea-bundle's own
@@ -19,12 +23,13 @@ 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)
}
/// The folder whose node_modules holds the three.js a playable draws with: the project's own (`raea add [email protected]`),
/// else the copy beside sdk/playable or sdk/r3f in raea's own files
fn three_dir(game: &Path, home: &Path) -> R<PathBuf> {
/// The folder whose node_modules holds a package the page carries (three.js to draw 3D, Tone.js to play a raea/tone
/// graph): the project's own (`raea add [email protected]`), else the copy beside sdk/playable or sdk/r3f in raea's own files
fn package_dir(game: &Path, home: &Path, name: &str, why: &str, add: &str) -> R<PathBuf> {
let has = |d: &Path| d.join("node_modules").join(name).join("package.json").is_file();
let mut d = game.parent();
while let Some(dir) = d {
if dir.join("node_modules/three/package.json").is_file() {
if has(dir) {
return Ok(dir.to_path_buf());
}
d = dir.parent();
@@ -32,21 +37,80 @@ fn three_dir(game: &Path, home: &Path) -> R<PathBuf> {
["sdk/playable", "sdk/r3f"]
.iter()
.map(|p| home.join(p))
.find(|d| d.join("node_modules/three/package.json").is_file())
.ok_or_else(|| "a playable draws its 3D with three.js, which this project doesn't have: `raea add [email protected]` in it".into())
.find(|d| has(d))
.ok_or_else(|| format!("a playable {why} with {name}, which this project doesn't have: `raea add {add}` in it"))
}
/// runtime/ecs as wasm (sdk/playable/ecs/build.sh), base64
fn ecs_wasm(home: &Path) -> R<String> {
use base64::Engine;
let f = home.join("sdk/playable/src/host/ecs.wasm");
let b = std::fs::read(&f).map_err(|e| format!("{}: raea/ecs's world as wasm isn't there ({e}): bash sdk/playable/ecs/build.sh", f.display()))?;
Ok(base64::engine::general_purpose::STANDARD.encode(b))
}
/// What sound a game makes, as the lint found it: none, media only (<Audio>, generated sounds) or a raea/tone graph
#[derive(Clone, Copy, PartialEq, Debug)]
enum Sounds {
None,
Media,
Tone,
}
/// What a page carries beside the game and the host, as the lint found the game needs it
#[derive(Clone, Copy, PartialEq, Debug)]
struct Carry {
/// a 3D drawer (Bevy's programs, its scene read by three.js), for a game with a 3D kind (PA11, PA15)
with_3d: bool,
sounds: Sounds,
/// Bevy's world as wasm, for a game that makes a raea/ecs World (PA12)
ecs: bool,
}
/// The bundle's entry: Bevy's world first for a game on raea/ecs (PA12: a World made as the game's module loads is
/// already Bevy's), the game, then the host started with Bevy's PBR programs as its 3D drawer (PA11) only for a game
/// with 3D (PA15: a 2D game's page carries no renderer) and a sound player only for a game with sound, Tone.js in it only for a
/// raea/tone graph (PA6)
fn entry(game: &Path, host: &Path, carry: Carry) -> String {
let Carry { with_3d, sounds, ecs } = carry;
let first = if ecs { format!("import {:?};\n", spec(&host.join("ecs.ts"))) } else { String::new() };
let mut e = format!("{first}import {:?};\nimport {{ start }} from {:?};\n", spec(game), spec(&host.join("main.tsx")));
if with_3d {
e.push_str(&format!("import {{ bevy3d }} from {:?};\n", spec(&host.join("bevy.ts"))));
}
if sounds != Sounds::None {
e.push_str(&format!("import {{ sound }} from {:?};\n", spec(&host.join("sound.ts"))));
}
if sounds == Sounds::Tone {
e.push_str(&format!("import {{ tone }} from {:?};\n", spec(&host.join("tone.ts"))));
}
let d3 = if with_3d { "bevy3d" } else { "undefined" };
e.push_str(&match sounds {
Sounds::None if with_3d => "start(bevy3d);\n".into(),
Sounds::None => "start();\n".into(),
Sounds::Media => format!("start({d3}, sound());\n"),
Sounds::Tone => format!("start({d3}, sound(tone));\n"),
});
e
}
/// The game and the host in one minified script that carries its files
fn bundle(game: &Path, home: &Path) -> R<String> {
let host = home.join("sdk/playable/src/host/main.tsx");
if !host.is_file() {
fn bundle(game: &Path, home: &Path, carry: Carry) -> R<String> {
let Carry { with_3d, sounds, .. } = carry;
let host = home.join("sdk/playable/src/host");
if !host.join("main.tsx").is_file() {
return Err(format!("{}: raea's playable host isn't there", host.display()));
}
let three = three_dir(game, home)?;
let out = std::env::temp_dir().join(format!("raea-playable-{}.js", std::process::id()));
let entry = format!("import {:?};\nimport {:?};\n", spec(game), spec(&host));
let alias = format!("three/={}", three.display());
let r = raea_runtime_bundle::bundle_entry(&entry, &out, &["--minify", "1", "--inline", "1", "--alias", &alias]);
let mut flags = vec!["--minify".to_string(), "1".into(), "--inline".into(), "1".into()];
if with_3d {
flags.extend(["--alias".into(), format!("three/={}", package_dir(game, home, "three", "draws its 3D", "[email protected]")?.display())]);
}
if sounds == Sounds::Tone {
flags.extend(["--alias".into(), format!("tone/={}", package_dir(game, home, "tone", "plays raea/tone", "[email protected]")?.display())]);
}
let flags: Vec<&str> = flags.iter().map(String::as_str).collect();
let r = raea_runtime_bundle::bundle_entry(&entry(game, &host, carry), &out, &flags);
let js = r.and_then(|_| std::fs::read_to_string(&out).map_err(|e| e.to_string()));
let _ = std::fs::remove_file(&out);
js
@@ -66,7 +130,12 @@ pub fn cli(args: &[String]) -> R<String> {
}
let store = serde_json::json!({"ios": flag(args, "--ios").unwrap_or(""), "android": flag(args, "--android").unwrap_or("")}).to_string();
let card = serde_json::json!({"title": flag(args, "--title").unwrap_or(""), "cta": flag(args, "--cta").unwrap_or("Play now")}).to_string();
let name = game.file_stem().and_then(|s| s.to_str()).unwrap_or("playable").to_string();
// the files' name: the brief's (`playable({ playable: { name } })`), else the game's file name
let stem = game.file_stem().map(|s| s.to_string_lossy().into_owned());
let name = flag(args, "--name").map(str::to_string).or(stem).unwrap_or_else(|| "playable".into());
if name.is_empty() || name.contains(['/', '\\']) {
return Err(format!("--name {name:?}: a file name, no folders"));
}
let mut report = Vec::new();
let found = lint::lint(&game)?;
@@ -83,16 +152,45 @@ pub fn cli(args: &[String]) -> R<String> {
return Err(why.join("\n"));
}
let js = bundle(&game, &raea_io_home::home())?;
let is = |k: &str| found.sound[k].as_bool() == Some(true);
let sounds = if is("tone") { Sounds::Tone } else if is("media") { Sounds::Media } else { Sounds::None };
let carry = Carry { with_3d: !found.kinds.is_empty(), sounds, ecs: found.ecs };
let home = raea_io_home::home();
let js = bundle(&game, &home, carry)?;
// its generated sounds, made (or found made) beside the game and carried in the page (PA6)
let assets = found.sound["assets"].as_array().cloned().unwrap_or_default();
let made = sound::make(&game, &assets)?;
report.push(match sounds {
Sounds::None => "sound: none".into(),
_ => format!("sound: {}{} generated ({} KB), played after the first touch", if sounds == Sounds::Tone { "a raea/tone graph, " } else { "" }, made.count, made.bytes / 1024),
});
// Bevy's world, for a game on raea/ecs (PA12): the wasm the host loads before the game
let ecs = if found.ecs { ecs_wasm(&home)? } else { String::new() };
report.push(if found.ecs { format!("ecs: Bevy's world as wasm ({} KB)", ecs.len() * 3 / 4 / 1024) } else { "ecs: none".into() });
let ecs = if ecs.is_empty() { ecs } else { format!("globalThis.__raeaEcsWasm={ecs:?};") };
let js = format!("{ecs}{}{js}", made.script);
// the faces the native page draws with, for the families the game names (PA8)
let style = fonts::style(&js);
std::fs::create_dir_all(&out).map_err(|e| format!("{}: {e}", out.display()))?;
let mut over = false;
let mut written = Vec::new();
for net in networks {
let script = format!("{}\n{js}", pages::preamble(net, &store, &card));
let w = pages::write(net, &name, &script, &out, orientation)?;
let w = pages::write(net, &name, &script, &out, orientation, &style)?;
let ok = w.bytes <= pages::CAP;
over |= !ok;
report.push(format!("{:<10} {:<40} {:>6} KB / {} KB {}", w.network, w.file.display(), w.bytes / 1024, pages::CAP / 1024, if ok { "ok" } else { "OVER" }));
written.push(w);
}
// what was written, for raea goal's playable pack (sdk/goal packs/playable.ts) and raea cloud's review
let manifest = serde_json::json!({
"name": name, "game": game.display().to_string(), "orientation": orientation, "kinds": found.kinds,
"compositions": found.comps.iter().map(|c| serde_json::json!({"id": c.id, "width": c.width, "height": c.height, "fps": c.fps, "frames": c.frames})).collect::<Vec<_>>(),
"pages": written.iter().map(|w| serde_json::json!({"network": w.network, "file": w.file.file_name().map(|f| f.to_string_lossy().to_string()).unwrap_or_default(), "bytes": w.bytes})).collect::<Vec<_>>(),
"cap": pages::CAP,
});
let mf = out.join(format!("{name}.playable.json"));
std::fs::write(&mf, serde_json::to_string_pretty(&manifest).unwrap_or_default()).map_err(|e| format!("{}: {e}", mf.display()))?;
if over {
report.insert(0, format!("a page is over its network's {} KB cap", pages::CAP / 1024));
return Err(report.join("\n"));
@@ -100,3 +198,57 @@ pub fn cli(args: &[String]) -> R<String> {
report.push(format!("APPLIED {name} exported as a playable to {}", out.display()));
Ok(report.join("\n"))
}
#[cfg(test)]
mod tests {
use super::{Carry, Sounds, entry};
use std::path::Path;
fn e(with_3d: bool, sounds: Sounds, ecs: bool) -> String {
entry(Path::new("/g/game.tsx"), Path::new("/h/host"), Carry { with_3d, sounds, ecs })
}
#[test]
fn a_2d_game_starts_with_no_drawer() {
let e = e(false, Sounds::None, false);
assert!(e.contains("start();") && !e.contains("three") && !e.contains("sound") && !e.contains("ecs"), "{e}");
}
#[test]
fn a_3d_game_starts_with_three() {
let e = e(true, Sounds::None, false);
assert!(e.contains("bevy3d } from \"/h/host/bevy.ts\"") && e.contains("start(bevy3d);"), "{e}");
}
#[test]
fn a_game_with_sound_starts_with_its_player_and_tone_only_for_a_graph() {
let media = e(false, Sounds::Media, false);
assert!(media.contains("start(undefined, sound());") && !media.contains("tone"), "{media}");
let tone = e(true, Sounds::Tone, false);
assert!(tone.contains("tone } from \"/h/host/tone.ts\"") && tone.contains("start(bevy3d, sound(tone));"), "{tone}");
}
#[test]
fn a_game_on_raea_ecs_loads_bevys_world_before_the_game() {
let e = e(false, Sounds::None, true);
assert!(e.starts_with("import \"/h/host/ecs.ts\";\nimport \"/g/game.tsx\";"), "{e}");
}
#[test]
fn the_carried_ecs_wasm_is_built_from_runtime_ecs_as_it_is() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
let out = std::process::Command::new("bash").arg(root.join("sdk/playable/ecs/from.sh")).output().expect("bash");
let now = String::from_utf8_lossy(&out.stdout).trim().to_string();
let built = std::fs::read_to_string(root.join("sdk/playable/src/host/ecs.wasm.from")).unwrap_or_default();
assert_eq!(built.trim(), now, "runtime/ecs changed since ecs.wasm was built: bash sdk/playable/ecs/build.sh");
}
#[test]
fn the_carried_bevy_programs_are_made_from_bevys_shaders_as_they_are() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
let out = std::process::Command::new("bash").arg(root.join("sdk/playable/bevy/from.sh")).output().expect("bash");
let now = String::from_utf8_lossy(&out.stdout).trim().to_string();
let built = std::fs::read_to_string(root.join("sdk/playable/src/host/bevy/programs.from")).unwrap_or_default();
assert_eq!(built.trim(), now, "Bevy's shaders or tools/bevy-glsl changed since programs.ts was made: bash sdk/playable/bevy/build.sh");
}
}
+7 -3
View File
@@ -20,6 +20,10 @@ pub struct Found {
pub kinds: Vec<String>,
pub notes: Vec<String>,
pub refusals: Vec<String>,
/// its sound (walk.ts): `tone` (a raea/tone graph), `media` (an <Audio>) and `assets` (each generated sound to make)
pub sound: Value,
/// whether it makes a raea/ecs World (walk.ts), whose page carries Bevy's world as wasm (PA12)
pub ecs: bool,
}
const SOURCE_RULES: &[(&str, &str)] = &[
@@ -27,7 +31,7 @@ const SOURCE_RULES: &[(&str, &str)] = &[
(r"https?://", "a URL in the source: a playable makes no network requests (every network refuses one)"),
(r"\bfetch\s*\(|XMLHttpRequest|WebSocket", "fetch/XHR/WebSocket: a playable makes no network requests"),
(r#"from\s+["']raea/(native|ml|character|physics|media|matchmove|modelling)["']"#, "a module that needs the native engine (native calls, models, physics, footage)"),
(r"<(Video|Audio)\b", "<Video>/<Audio> play through the native media stack; a playable's sound is PA6 (not yet)"),
(r"<(Video|OffthreadVideo)\b", "<Video> plays footage through the native media stack, which a playable doesn't carry: render the clip as frames or an image sequence"),
];
/// The game's source and its compositions, judged
@@ -48,7 +52,7 @@ pub fn lint(game: &Path) -> R<Found> {
let walked = match walk(game) {
Ok(w) => w,
// what the source can't have (a fetch, a URL) often stops the render too: the refusal says why, the render's end doesn't
Err(_) if !refusals.is_empty() => return Ok(Found { comps: vec![], kinds: vec![], notes, refusals }),
Err(_) if !refusals.is_empty() => return Ok(Found { comps: vec![], kinds: vec![], notes, refusals, sound: Value::Null, ecs: false }),
Err(e) => return Err(e),
};
let comps: Vec<Comp> = walked["comps"]
@@ -73,7 +77,7 @@ pub fn lint(game: &Path) -> R<Found> {
for k in strings("refused") {
refusals.push(format!("3D kind {k} isn't drawn in a playable"));
}
Ok(Found { comps, kinds: strings("kinds"), notes, refusals })
Ok(Found { comps, kinds: strings("kinds"), notes, refusals, sound: walked["sound"].clone(), ecs: walked["ecs"].as_bool() == Some(true) })
}
/// sdk/playable's walk run on the engine (`raea run`) after the game, in a process of its own so the game's React stays
+4 -3
View File
@@ -43,9 +43,10 @@ fn zip(file: &Path, entries: &[(String, String)]) -> R<()> {
Ok(())
}
/// `network`'s package of `script` (its preamble already first) written into `out` as NAME-NETWORK.html or .zip
pub fn write(network: &str, name: &str, script: &str, out: &Path, orientation: &str) -> R<Written> {
let html = |head: &str, body: &str| page(name, head, body, script);
/// `network`'s package of `script` (its preamble already first) written into `out` as NAME-NETWORK.html or .zip, its
/// `style` (the fonts, fonts.rs) first in the head
pub fn write(network: &str, name: &str, script: &str, out: &Path, orientation: &str, style: &str) -> R<Written> {
let html = |head: &str, body: &str| page(name, &format!("{style}\n{head}"), body, script);
let file = match network {
// a ZIP with index.html; exitapi.js and the orientation tag in the head (Google Ads help 9981650)
"google" => {
+89
View File
@@ -0,0 +1,89 @@
//! A playable's generated sounds (docs/playables.feature PA6). A game's `sao(...)` effects and TokenSynth notes are
//! made by the native renderer the first time a render meets them (runtime/sound: raea's asset store, beside the edit).
//! A playable makes no requests, so the export makes each one the game describes (sdk/playable walk.ts lists them,
//! each with its model, prompt, seed and params as the renderer passes them, so the store's cache is shared with
//! renders) and carries it in the page as a data URL under its src (`asset:sao/...`), AAC at 64 kb/s mono when FFmpeg
//! is there (a two-second effect is about 16 KB), else the file as made. The host plays it after the first touch.
use super::R;
use base64::Engine;
use serde_json::Value;
use std::path::Path;
/// The page's sounds: a script that sets `__raeaSounds` (src -> data URL), how many and their bytes
pub struct Made {
pub script: String,
pub count: usize,
pub bytes: usize,
}
/// Each generated sound the game describes, made (or found made) beside the game and inlined
pub fn make(game: &Path, assets: &[Value]) -> R<Made> {
let store = raea_io_assets::Store::beside(game);
let ffmpeg = raea_io_assets::ffmpeg_tool("ffmpeg", false).ok();
let mut out = serde_json::Map::new();
let mut bytes = 0;
for a in assets {
let (Some(src), Some(model), Some(prompt)) =
(a["src"].as_str(), a["model"].as_str(), a["prompt"].as_str())
else {
continue;
};
let seed = a["seed"].as_u64().unwrap_or(1);
let made = store
.make(model, prompt, seed, &a["params"])
.map_err(|e| format!("the sound {model} \"{prompt}\" couldn't be made: {e}"))?;
let file = store.path(&made);
let (mime, data) = match ffmpeg.as_deref().and_then(|f| aac(f, &file)) {
Some(d) => ("audio/mp4", d),
None => (
mime(&made.ext),
std::fs::read(&file).map_err(|e| format!("{}: {e}", file.display()))?,
),
};
bytes += data.len();
out.insert(
src.into(),
Value::from(format!(
"data:{mime};base64,{}",
base64::engine::general_purpose::STANDARD.encode(&data)
)),
);
}
let count = out.len();
let script = if count == 0 {
String::new()
} else {
format!("globalThis.__raeaSounds={};", Value::Object(out))
};
Ok(Made {
script,
count,
bytes,
})
}
/// The file as AAC in an MP4 (what WebKit and every other browser decode), mono at 64 kb/s
fn aac(ffmpeg: &Path, file: &Path) -> Option<Vec<u8>> {
let to = std::env::temp_dir().join(format!("raea-playable-sound-{}.m4a", std::process::id()));
let ok = std::process::Command::new(ffmpeg)
.args(["-v", "error", "-y", "-i"])
.arg(file)
.args(["-vn", "-ac", "1", "-c:a", "aac", "-b:a", "64k", "-f", "mp4"])
.arg(&to)
.status()
.is_ok_and(|s| s.success());
let data = if ok { std::fs::read(&to).ok() } else { None };
let _ = std::fs::remove_file(&to);
data
}
fn mime(ext: &str) -> &'static str {
match ext {
"mp3" => "audio/mpeg",
"ogg" => "audio/ogg",
"flac" => "audio/flac",
"m4a" | "mp4" | "aac" => "audio/mp4",
_ => "audio/wav",
}
}
-2
View File
@@ -25,6 +25,4 @@ raea-core-facts = { path = "../../core/facts" }
raea-core-scene = { path = "../../core/scene" }
bevy = { version = "=0.20.0", default-features = false, features = ["std"] }
dunce = "1"
# --ask: the fault ringed on its frame for the vision model
image = { version = "0.25", default-features = false, features = ["png"] }
serde_json = "1"
-109
View File
@@ -1,109 +0,0 @@
//! `raea scene faults EDIT.tsx --composition ID --ask N` (docs/notice.feature NT12): a vision model asked only what
//! geometry can't say, whether a likely fault is meant. The judge has already found it, measured it and found the
//! frame it shows largest on; that frame is rendered, the fault's spots ringed on it, and `raea ask` (clef-omni) is
//! handed the picture with the scene's own words for it: which part, what it's on or in, by how much. Its answer,
//! meant or a mistake, is kept as a verdict (`by: "ask"`) when it's SURE or more, and any person's verdict on the same
//! finding outranks it.
//! The ringed pictures stay in the project's review/faults-ask/ for a person to look at.
use std::path::Path;
use std::process::Command;
use serde_json::Value;
use raea_sys_notice::{FAULT, Judged, labels};
/// Rendered this wide (its height kept to the composition's shape).
const WIDE: u32 = 960;
/// An answer this sure or more is kept as a verdict; under it, said as unsure and kept out of training. On room
/// 106's shot-window (2026-11-27) the model was 0.52-0.65 sure on chair feet pressed into carpet and a leg through a
/// strap, and 0.72-0.78 on a sunk kit, a floating hat and a part sunk into a door.
const SURE: f64 = 0.7;
/// One ring around every spot of the fault on the picture, a little out from them, in red.
fn ring(png: &Path, marks: &[[f32; 2]]) -> Result<(), String> {
let mut img = image::open(png).map_err(|e| format!("{}: {e}", png.display()))?.to_rgb8();
let (w, h) = (img.width() as f32, img.height() as f32);
let pts: Vec<(f32, f32)> = marks.iter().map(|m| ((m[0] + 1.0) * 0.5 * w, (1.0 - m[1]) * 0.5 * h)).collect();
let (cx, cy) = (pts.iter().map(|p| p.0).sum::<f32>() / pts.len() as f32, pts.iter().map(|p| p.1).sum::<f32>() / pts.len() as f32);
let r = pts.iter().map(|p| (p.0 - cx).hypot(p.1 - cy)).fold(0.0f32, f32::max) + 0.03 * w;
for y in 0..img.height() {
for x in 0..img.width() {
let d = (x as f32 - cx).hypot(y as f32 - cy);
if (d - r).abs() <= 2.5 {
img.put_pixel(x, y, image::Rgb([255, 30, 30]));
}
}
}
img.save(png).map_err(|e| format!("{}: {e}", png.display()))
}
fn question(j: &Judged) -> String {
let f = &j.fault;
let what = match &f.into {
Some(into) => format!("{} (against {into})", f.part),
None => f.part.clone(),
};
format!(
"This is a frame of a 3D scene. Inside the red ring is {what}. A geometry check measured: {}. Judge only what is inside the ring. Is it meant to be like this (cloth draped over an edge, something hung, feet pressed into soft carpet, something set into a wall), or a mistake a viewer would notice (something floating, sunk into something, passing through something, faces flickering)?",
f.says
)
}
/// The likeliest `n` faults asked about, their answers kept as verdicts.
#[allow(clippy::too_many_arguments)]
pub fn run(tsx: &Path, shot: &str, judged: &[Judged], frames: &[i64], w: u32, h: u32, n: usize, dry: bool) -> Result<String, String> {
let project = labels::project_of(tsx);
let dir = project.join("review").join("faults-ask");
std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
let me = std::env::current_exe().map_err(|e| e.to_string())?;
let tall = ((WIDE as f32 * h as f32 / w as f32 / 2.0).round() as u32 * 2).max(2);
let (mut out, mut rows) = (Vec::new(), Vec::new());
for j in judged.iter().filter(|j| j.p >= FAULT && j.seen.best.is_some() && !j.seen.marks.is_empty()).take(n) {
let frame = frames[j.seen.best.unwrap()];
let name = format!("{shot}-{}", j.fault.key).replace(|c: char| !(c.is_ascii_alphanumeric() || c == '-'), "_");
let (png, mp4) = (dir.join(format!("{name}.png")), dir.join(format!("{name}.mp4")));
// the frame as the render draws it, its own end checks left out (they'd judge the scene again)
let drawn = Command::new(&me)
.args(["render", &tsx.to_string_lossy(), "--composition", shot, "--frame", &frame.to_string(), "--w", &WIDE.to_string(), "--h", &tall.to_string(), "-o", &png.to_string_lossy()])
.env("RAEA_FAULTS_CHECK", "0")
.env("RAEA_CLIP_CHECK", "0")
.output()
.map_err(|e| format!("raea render: {e}"))?;
if !drawn.status.success() {
return Err(format!("raea render frame {frame}: {}", String::from_utf8_lossy(&drawn.stderr).lines().last().unwrap_or("")));
}
ring(&png, &j.seen.marks)?;
// raea ask watches a picture move: the still as a second of video
let made = Command::new("ffmpeg").args(["-y", "-loglevel", "error", "-loop", "1", "-i", &png.to_string_lossy(), "-t", "1", "-r", "10", "-pix_fmt", "yuv420p", &mp4.to_string_lossy()]).status().map_err(|e| format!("ffmpeg: {e}"))?;
if !made.success() {
return Err(format!("ffmpeg couldn't make {}", mp4.display()));
}
let mut cmd = Command::new(&me);
cmd.args(["ask", &mp4.to_string_lossy(), &question(j), "--choose", "meant,mistake", "--brief", "none", "--json"]);
if dry {
cmd.arg("--dry");
}
let asked = cmd.output().map_err(|e| format!("raea ask: {e}"))?;
let text = String::from_utf8_lossy(&asked.stdout);
let first: Value = text.lines().find_map(|l| serde_json::from_str::<Value>(l).ok()).unwrap_or(Value::Null);
let choice = first["choice"].as_str().or_else(|| first["answer"].as_str()).map(str::to_lowercase);
let says = first["says"].as_str().unwrap_or("").to_string();
let sure = first["value"].as_f64().unwrap_or(0.0);
match choice.as_deref() {
Some(c) if (c.contains("mistake") || c.contains("meant")) && sure < SURE => {
out.push(format!("{:.2} {} -> unsure ({says}), not kept (frame {frame}, {})", j.p, j.fault.key, png.display()));
}
Some(c) if c.contains("mistake") || c.contains("meant") => {
let real = c.contains("mistake");
rows.push(labels::row(&j.fault.key, real, "ask", shot, &j.x, &j.toks));
out.push(format!("{:.2} {} -> {}{} (frame {frame}, {})", j.p, j.fault.key, if real { "a mistake" } else { "meant" }, if says.is_empty() { String::new() } else { format!(": {says}") }, png.display()));
}
_ if dry => out.push(format!("{:.2} {} would be asked on frame {frame} ({})", j.p, j.fault.key, png.display())),
_ => out.push(format!("{:.2} {} not answered: {}", j.p, j.fault.key, first["not_asked"].as_str().or(first["problem"].as_str()).unwrap_or(text.lines().next().unwrap_or("")))),
}
}
labels::append(&project, &rows)?;
out.push(format!("{} asked, {} answers kept as verdicts (by ask; a person's verdict outranks them) in {}", out.len(), rows.len(), project.join("review").join("faults.labels.jsonl").display()));
Ok(out.join("\n"))
}
+2 -10
View File
@@ -45,12 +45,10 @@ pub fn cli(args: &[String]) -> Result<String, String> {
let (found, _) = raea_sys_contact::lint(&now, &next);
// the cameras: the frame's own and evenly over the rest of the shot
let step = frames.len().div_ceil(CAMERAS).max(1);
// and each view's frame number, for the frame a fault shows largest on (--ask)
let (mut views, mut view_frames) = (vec![now.clone()], vec![frame]);
for (i, (f, fr)) in frames.iter().enumerate() {
let mut views = vec![now.clone()];
for (i, (_, fr)) in frames.iter().enumerate() {
if i != k && i % step == 0 {
views.push(items(fr));
view_frames.push(*f);
}
}
let model = Model::load();
@@ -61,12 +59,6 @@ pub fn cli(args: &[String]) -> Result<String, String> {
return Ok(crate::seed::run(&now, &next, &views, &found, w, h, &model, n));
}
// a vision model asked whether the likeliest faults are meant (ask.rs), its answers kept as verdicts
if let Some(n) = raea_runtime_bundle::flag(args, "--ask") {
let n = n.parse::<usize>().map_err(|_| "--ask takes how many of the likeliest faults to ask about")?;
return crate::ask::run(&tsx, &shot, &judged, &view_frames, w, h, n, args.iter().any(|a| a == "--dry"));
}
// what it learns from: this run against the last, and any verdict given now
let project = labels::project_of(&tsx);
let keys: Vec<String> = judged.iter().map(|j| j.fault.key.clone()).collect();
+1 -2
View File
@@ -11,7 +11,6 @@ use raea_runtime_export::{frame_of, items};
// how near the camera passes to each solid part, every frame (`--clearance M`, MK16)
pub mod clearance;
// the lint's findings judged as a viewer of the shot would see them, learning from verdicts (raea-sys-notice)
mod ask;
mod chars;
mod faults;
mod motion;
@@ -22,7 +21,7 @@ mod light;
pub mod lod;
mod stage;
pub const USAGE: &str = "raea scene lint|explain|faults|light|stage|lod EDIT.tsx [--composition ID] [--frame N] [--part NAME] [--from N] [--to N] [--clearance M] [--real KEY] [--fine KEY] [--seed N] [--ask N [--dry]] [--motion] [--json] | raea scene faults train [FOLDER] | raea scene faults --clip CLIP.json|FOLDER [--real KEY] [--fine KEY] [--fine-from N] [--fine-upto N] [--real-from N] [--real-upto N] [--by NAME] [--seed N] [--json]";
pub const USAGE: &str = "raea scene lint|explain|faults|light|stage|lod EDIT.tsx [--composition ID] [--frame N] [--part NAME] [--from N] [--to N] [--clearance M] [--real KEY] [--fine KEY] [--seed N] [--motion] [--json] | raea scene faults train [FOLDER] | raea scene faults --clip CLIP.json|FOLDER [--real KEY] [--fine KEY] [--fine-from N] [--fine-upto N] [--real-from N] [--real-upto N] [--by NAME] [--seed N] [--json]";
/// `raea scene lint|explain EDIT.tsx [--composition ID] [--frame N] [--json]`: the frame's parts measured
/// (frame 0 by default). `lint` says the faults (errors fail it: floating, sunk, clipping; warnings: in the air,
-3
View File
@@ -14,9 +14,6 @@ raea-core-facts = { path = "../../core/facts" }
serde_json = "1"
# --set's and the CLI's flags, read as the bundler reads them
raea-runtime-bundle = { path = "../../runtime/bundle" }
# `raea judge`, dispatched with `raea make solid` (verb())
raea-app-judge = { path = "../judge" }
raea-app-ask = { path = "../ask" }
# a scene, kit or shot held to its plan (docs/goal.feature)
raea-app-make = { path = "../make" }
# `raea make solid export`: the solid built, written as .glb and read back (core/shape), named and coloured (core/meshcheck)
+2 -4
View File
@@ -91,13 +91,11 @@ fn parse_set(s: &str) -> Result<Map<String, Value>, String> {
Ok(m)
}
/// `raea make solid ...`, `raea judge ...`, `raea make ...` (docs/goal.feature) and `raea ask ...` (docs/ask.feature AK3, which prints as it goes and exits with
/// its own code), the verbs that build and judge a piece (engine/cli hands them over), or None for another verb.
/// `raea make solid ...` and `raea make ...` (docs/goal.feature), the verbs that build a piece (engine/cli hands them
/// over), or None for another verb.
pub fn verb(args: &[String]) -> Option<Result<String, String>> {
match args.first().map(String::as_str) {
Some("solid") => Some(cli(args)),
Some("judge") => Some(raea_app_judge::cli(args)),
Some("ask") => std::process::exit(raea_app_ask::cli(&args[1..])),
Some("make") => Some(raea_app_make::cli(args)),
_ => None,
}
+1 -1
View File
@@ -55,7 +55,7 @@ pub fn with_preface(text: &str, dir: &Path) -> String {
return text.to_string();
}
let p = format!(
"> **On Grok Bot.** raea runs on the person's Mac, not on your computer. Run every `raea` command there, and read\n> every file this skill links (3d.md, reference/cli.md and the rest) from its copy there, in {}, both\n> with Run a command on your local computer (the person turns on Settings → Computer → Execution on this computer).\n> No raea MCP server or hook is set up for you: after saving a composition run `raea check EDIT.tsx --quick` yourself,\n> and `raea show FILE` puts media in front of the person.\n",
"> **On Grok Bot.** raea runs on the person's Mac, not on your computer. Run every `raea` command there, and read\n> every file this skill links (3d.md, reference/cli.md and the rest) from its copy there, in {}, both\n> with Run a command on your local computer (the person turns on Settings → Computer → Execution on this computer).\n> No raea MCP server or hook is set up for you: a render checks its own output at its end (`raea check OUT.mp4`\n> checks one again), and `raea show FILE` puts media in front of the person.\n",
dir.join("raea").display()
);
let Some(rest) = text.strip_prefix("---\n") else { return format!("{p}\n{text}") };
+4 -3
View File
@@ -1,8 +1,9 @@
//! The hooks `raea skills install` adds an agent (docs/agents.feature A5d, A5e; docs/skills.feature SK10), the same two
//! for every harness, each written where and how that harness reads hooks: before a shell command, `raea hook AGENT`
//! steers media opened in the Mac's viewer to `raea show`; after a file is saved, it runs the quick check on a
//! composition. Claude Code's run after every tool and as a turn ends too, to hand the session what the person sent from
//! the raea app (apps/check/src/inbox.rs). An event that already has a `raea hook` entry keeps it, its matcher widened
//! steers media opened in the Mac's viewer to `raea show`; after a file is saved, it checks nothing (a render checks its
//! own output, docs/check.feature CK1) and only hands the session what the person sent from the raea app
//! (apps/check/src/inbox.rs). Claude Code's run after every tool, and Claude Code's and Codex's as a turn ends too, where
//! `raea check --at done` holds the brief's goals. An event that already has a `raea hook` entry keeps it, its matcher widened
//! to this raea's when an older raea wrote a narrower one.
use crate::agent_mcp::user_home;
use serde_json::{Value, json};
+6 -6
View File
@@ -17,6 +17,7 @@
set -uo pipefail
ROOT=$(cd "$(dirname "$0")/../.." && pwd)
cd "$ROOT"
. bench/lib/compare.sh
# renders compared by their pixels are no exports: unsigned and unwatermarked (a TrustMark id differs per render; CI sets it too)
export RAEA_SIGN=0
PIXELS=0
@@ -75,8 +76,7 @@ if [ $PIXELS = 1 ]; then
case "$out" in *PASS*) line S2d PASS "a typed query on the host's World (HostWorld) in a plain App, a reflected component never shared: ${out#host_query: PASS }" ;; *) line S2d FAIL "a typed query on the host's World: ${out:-no result}" ;; esac
(cd "$WORK" && RAEA_PAGE=blitz "$MOTION" render edit.tsx --at 30 -o "$WORK/ref/") > "$WORK/render.log" 2>&1
target/release/examples/plain_page "$WORK/edit.js" "$WORK/plain.png" 1280 720 30 30 > "$WORK/plain.log" 2>&1
ssim() { ffmpeg -hide_banner -nostats -i "${REF:-$WORK/ref/frame-00000.png}" -i "${GOT:-$WORK/plain.png}" -lavfi "[0:v]format=rgb24${1}[a];[1:v]format=rgb24${1}[b];[a][b]ssim" -f null - 2>&1 | grep -o 'All:[0-9.]*' | cut -d: -f2; }
whole=$(ssim "") title=$(ssim ",crop=400:120:40:30")
whole=$(ssim "$WORK/ref/frame-00000.png" "$WORK/plain.png") title=$(ssim "$WORK/ref/frame-00000.png" "$WORK/plain.png" crop=400:120:40:30)
if [ -z "$whole" ]; then line H5 FAIL "the page over a plain App's scene: no frame (see plain_page, raea render)"
else
awk -v s="$whole" 'BEGIN { exit !(s >= 0.998) }' && line H5 PASS "the page over a plain App's scene (classbg frame 30, SSIM $whole against raea)" || line H5 FAIL "the page over a plain App's scene (classbg frame 30, SSIM $whole < 0.998)"
@@ -101,14 +101,14 @@ if [ $PIXELS = 1 ]; then
# would match too)
(cd "$WORK" && RAEA_PAGE=blitz "$MOTION" render video.tsx --at 30 -o "$WORK/vref/") > "$WORK/vrender.log" 2>&1
target/release/examples/plain_page "$WORK/video.js" "$WORK/video.png" 1280 720 30 30 > "$WORK/video.log" 2>&1
v=$(REF=$WORK/vref/frame-00000.png GOT=$WORK/video.png ssim ",crop=320:568:80:60")
v=$(ssim "$WORK/vref/frame-00000.png" "$WORK/video.png" crop=320:568:80:60)
mean=$(ffmpeg -v error -i "$WORK/video.png" -vf "crop=320:568:80:60,scale=1:1" -f rawvideo -pix_fmt rgb24 - 2>/dev/null | xxd -p)
if [ -n "$v" ] && [ "$mean" != 1b2230 ] && awk -v s="$v" 'BEGIN { exit !(s >= 0.999) }'; then line H11 PASS "a video playing inside a page in a plain App (its area SSIM $v against raea)"
else line H11 FAIL "a video playing inside a page in a plain App (SSIM ${v:-none}, mean ${mean:-none})"; fi
# a <Screen>: the frame against raea's, and its page on it: red at its middle, the card blue, black around
(cd "$WORK" && RAEA_PAGE=blitz "$MOTION" render screen.tsx --at 30 -o "$WORK/sref/") > "$WORK/srender.log" 2>&1
target/release/examples/plain_page "$WORK/screen.js" "$WORK/screen.png" 1280 720 30 30 > "$WORK/screen.log" 2>&1
sc=$(REF=$WORK/sref/frame-00000.png GOT=$WORK/screen.png ssim "")
sc=$(ssim "$WORK/sref/frame-00000.png" "$WORK/screen.png")
at() { ffmpeg -v error -i "$WORK/screen.png" -vf "crop=1:1:$1:$2" -f rawvideo -pix_fmt rgb24 - 2>/dev/null | xxd -p; }
if [ -n "$sc" ] && awk -v s="$sc" 'BEGIN { exit !(s >= 0.995) }' && [ "$(at 640 360)" = ff3030 ] && [ "$(at 794 424)" = 2040ff ] && [ "$(at 100 100)" = 000000 ]; then
line H5 PASS "a <Screen>'s nested composition on its screen in a plain App (SSIM $sc against raea)"
@@ -117,8 +117,8 @@ if [ $PIXELS = 1 ]; then
# the page under the sphere and over it
(cd "$WORK" && RAEA_PAGE=blitz "$MOTION" render layers.tsx --at 30 -o "$WORK/lref/") > "$WORK/lrender.log" 2>&1
target/release/examples/plain_page "$WORK/layers.js" "$WORK/layers.png" 960 540 30 30 > "$WORK/layers.log" 2>&1
L() { REF=$WORK/lref/frame-00000.png GOT=$WORK/layers.png ssim "$1"; }
lw=$(L "") lu=$(L ",crop=240:80:20:20") lo=$(L ",crop=900:40:0:250")
L() { ssim "$WORK/lref/frame-00000.png" "$WORK/layers.png" "$@"; }
lw=$(L) lu=$(L crop=240:80:20:20) lo=$(L crop=900:40:0:250)
if [ "$lw" = 1.000000 ] && [ "$lu" = 1.000000 ] && [ "$lo" = 1.000000 ]; then
line H5 PASS "a layered Canvas3D in a plain App: the page under and over its 3D as raea's (SSIM $lw; under $lu, over $lo)"
else line H5 FAIL "a layered Canvas3D in a plain App (SSIM ${lw:-none}; under ${lu:-none}, over ${lo:-none})"; fi
-11
View File
@@ -1,11 +0,0 @@
# The bench checks L2 runs on every release candidate (tools/l2.sh), each with that commit's raea as RAEA_BIN; each
# must exit 0. They hold what P26 can't: P26 compares with a baseline, and a baseline drawn by a raea with a fault
# carries the fault. These say what is right.
#
# A frame drawn alone or out of order (--at, --frame) agrees with the render of every frame (docs/stage-guards.feature
# SG17). 0.1.9 drew a CSS animation in a frame alone from the earliest <Sequence>'s start, or from the frame itself.
bench/at-0/check.sh
bench/at-time/check.sh
bench/at-3d/check.sh
bench/compute-frames/check.sh
sdk/react/bench/css/check.sh
+8
View File
@@ -0,0 +1,8 @@
# The bench checks L2 (tools/l2.sh) does not run. L2 runs every bench/**/check.sh and sdk/**/check.sh, and
# tools/settle-nudge.sh and tools/frame-pure-3d.sh, each with the release candidate's raea as RAEA_BIN; each must
# exit 0.
# They hold what P26 can't: P26 compares with a baseline, and a baseline drawn by a raea with a fault carries the fault.
# These say what is right.
#
# A check is left out only with its reason, one per line: PATH WHY (what it needs that L2 can't give, or the issue
# that tracks its failure). A check whose subject is gone is deleted, not listed here.
+27
View File
@@ -0,0 +1,27 @@
# shellcheck shell=sh disable=SC3043 # local: every shell that sources this has it
# The bench checks' frame comparison, sourced by every script that scores two frames by SSIM so that all of them
# measure the same thing. POSIX sh: sh, bash and zsh scripts source it alike.
#
# . "$ROOT/bench/lib/compare.sh"
# s=$(ssim A B [FILTER_A [FILTER_B]])
#
# ssim prints ffmpeg's SSIM of two images, both read as 8-bit RGB (an alpha channel is dropped, not blended): the
# "All" value to six decimals, 1.000000 for identical pixels. FILTER_A is an ffmpeg filter chain applied to A before
# the conversion (crop=400:120:40:30), FILTER_B the same for B (default: FILTER_A). It prints nothing when ffmpeg
# can't compare them (a file missing or unreadable, or the two sizes differ), so a caller's ${s:-none} or ${s:-0}
# says which.
#
# What the number can and can't see. The same binary rendering a frame twice repeats at 0.99998 or more
# (bench/p26-baseline), and a deband dither keyed to screen position, 2/255 at most, keeps 0.999 (sdk/raea/bench/bevy/
# view). But whole-frame SSIM forgives a small subject and a small slip: a sequence's frame 28 against frame 29 alone
# scored 0.986 (docs/stage-guards.feature SG0), a cut glyph 0.9996, a sprite on the wrong cell 0.989 (tools/
# bevy-parity). A bar under 0.999 passes a one-frame slip; a check that must catch a small subject measures it apart
# (a crop, a tile, a box).
ssim() {
local fa fb
fa=${3:+$3,}
fb=${4:-${3:-}}
fb=${fb:+$fb,}
ffmpeg -nostdin -hide_banner -nostats -i "$1" -i "$2" -lavfi "[0:v]${fa}format=rgb24[a];[1:v]${fb}format=rgb24[b];[a][b]ssim" \
-f null - 2>&1 | grep -o 'All:[0-9.]*' | tail -1 | cut -d: -f2
}
-1
View File
@@ -16,7 +16,6 @@ mkdir -p "$OUT"
export RAEA_SIGN=0 RAEA_MARK=0 RAEA_EXPORT_CACHE=0
expected() { case $1 in
examples/games/animated-character.tsx) echo "its media/RobotExpressive.glb was deleted" ;;
examples/playables/brick-rush.tsx) echo "RAEA_LIVE3D_CHECK panics on frame 1: the fast rows carry the sun's rotation and the full rows don't (runtime/scene/src/live.rs; docs/playables.feature PA18)" ;;
sdk/raea/bench/bevy-parity/3d/rotate_environment_map.tsx) echo "clearcoat textures need raea-sys-material's multi-layer feature, off by default (as bench/bevy-parity/runs.tsv leaves it out)" ;;
esac; }
SAME=0 DIFF=0 ERR=0 SKIP=0
+3 -2
View File
@@ -1,7 +1,8 @@
#!/bin/bash
# P26's baseline (docs/ts-native.feature P26a): frames of every composition in list.txt rendered by the published raea
# 0.1.9, the reference every later page must match (SSIM >= 0.98 per frame, fonts and brand styles included). It was
# the last Blitz build's until that build and its frames were lost (after 11-16); re-taken from 0.1.9 on 11-22.
# 0.1.9, the reference every later page must match (SSIM >= 0.999 per frame, compare.sh's bar, fonts and brand styles
# included). It was the last Blitz build's until that build and its frames were lost (after 11-16); re-taken from 0.1.9
# on 11-22.
#
# bench/p26-baseline/capture.sh [RAEA_BIN] (default: 0.1.9's raea, unpacked at
# ~/Library/Caches/raea/p26-baseline/bin-v0.1.9, P26_STORE to move it)
+17 -11
View File
@@ -1,30 +1,36 @@
#!/bin/bash
# P26's gate (docs/ts-native.feature P26a): each baseline frame (manifest.jsonl, the last Blitz build's) rendered again
# by raea on the Blitz page (the only page since B5d; P26_PAGE names it in results.jsonl,
# docs/blitz-bevy.feature B2b) and compared, SSIM >= 0.98 a frame.
# docs/blitz-bevy.feature B2b) and compared, SSIM >= 0.999 a frame.
#
# bench/p26-baseline/compare.sh [RAEA_BIN] (default: target/release/raea)
#
# The frames go to $P26_STORE/bevy/frames/<slug>/<frame>.png beside the baseline's ($P26_STORE: ~/Library/Caches/raea/
# p26-baseline), each frame's SSIM (ffmpeg's, over RGB) to $P26_STORE/bevy/results.jsonl; a composition that didn't
# render is a failure of all its frames. ONLY=substring limits the compositions. MIN=0.98 is the bar. Prints the pass
# rate and the worst frames, and exits 1 when any frame is under the bar (CI's p26 gate reads the exit). One render at
# a time (the GPU is shared).
# render is a failure of all its frames. ONLY=substring limits the compositions. MIN is the bar. Prints the pass rate
# and the worst frames, and exits 1 when any frame is under the bar (L2, tools/l2.sh, counts each row's pass). One
# render at a time (the GPU is shared).
#
# The floor (10-26, one binary, each row rendered twice): rows repeat at SSIM >= 0.99998 run to run. Most are
# byte-identical or 1/255 apart; look/town and kitchen/wreck differ in about 200 pixels, on house-kit's siding, where
# the outside and inside skins have coincident faces and which one draws on top follows Bevy's draw order for equal
# depths, likely the asset-load order (spawning the models' scenes in a fixed order didn't change it). Coincident faces
# z-fight in any engine: whoever next touches those houses, offset the inner skin.
# The bar, 0.999, sits between what a run repeats at and the smallest fault it must catch. The floor (one binary, each
# row rendered twice): rows repeat at SSIM >= 0.99998 run to run, and an incremental build's float rounding (Cargo.toml's
# [profile.release] note) at 0.99997. Most are byte-identical or 1/255 apart; look/town and kitchen/wreck differ in
# about 200 pixels, on house-kit's siding, where the outside and inside skins have coincident faces and which one draws
# on top follows Bevy's draw order for equal depths, likely the asset-load order (spawning the models' scenes in a fixed
# order didn't change it). Coincident faces z-fight in any engine: whoever next touches those houses, offset the inner
# skin. The fault: a frame drawn one frame late scores 0.986 (docs/stage-guards.feature SG0, frame 28 against 29), and
# 0.9985 on a slow film (a 60 fps launch film's frame N+1 against N), both of which 0.98 passed. Whole-frame SSIM can't
# see a fault of a few pixels (SG0's cut glyph scored 0.9996): that needs a pixel measure, not a higher bar. A row that
# differs from the baseline for a good reason is taken again with recapture.sh, which writes the reason into its row.
set -uo pipefail
HERE=$(cd "$(dirname "$0")" && pwd)
. "$HERE/lib.sh"
# pixel checks: no Content Credentials or TrustMark id in the frames (a still's mark changes its pixels each run)
export RAEA_SIGN=0 RAEA_MARK=0
ROOT=$(cd "$HERE/../.." && pwd)
. "$ROOT/bench/lib/compare.sh"
STORE=${P26_STORE:-$HOME/Library/Caches/raea/p26-baseline}
BIN=${1:-$ROOT/target/release/raea}
MIN=${MIN:-0.98}
MIN=${MIN:-0.999}
# a composition whose baseline came from a plugin build (raea-bevy-sdk: hanabi, avian) renders with one: P26_PLUGIN_BIN
# (default sdk/raea/bench/bevy-plugins/motion.sh; it must take `render` as raea does)
PLUGIN_BIN=${P26_PLUGIN_BIN:-$ROOT/sdk/raea/bench/bevy-plugins/motion.sh}
@@ -79,7 +85,7 @@ for rel in $(jq -r '.composition' "$HERE/manifest.jsonl" | awk '!seen[$0]++'); d
continue
fi
cp "$got" "$OUT/frames/$slug/$f.png"
s=$(ffmpeg -hide_banner -nostats -i "$ref" -i "$got" -lavfi "[0:v]format=rgb24[a];[1:v]format=rgb24[b];[a][b]ssim" -f null - 2>&1 | grep -o 'All:[0-9.]*' | cut -d: -f2)
s=$(ssim "$ref" "$got")
[ -n "$s" ] || s=0
pass=$(awk -v s="$s" -v m="$MIN" 'BEGIN { print (s >= m) ? "true" : "false" }')
jq -nc --arg c "$rel" --argjson f "$f" --argjson s "$s" --argjson p "$pass" '{composition: $c, frame: $f, ssim: $s, pass: $p}' >> "$RES"
+2 -2
View File
@@ -27,8 +27,8 @@ p26_src() {
if [ -f "$WORK/proj/wrap.tsx" ]; then
src=$WORK/proj/wrap.tsx
mkdir -p "$WORK/proj/brand" && cp "$HERE/props/brand.css" "$WORK/proj/brand/brand.css"
# a stub older than everything, so the probe can import it and the render compiles it
echo 'export const css = "";' > "$WORK/proj/styles.gen.ts" && touch -t 200001010000 "$WORK/proj/styles.gen.ts"
# a stub the probe can import; the render compiles its own into the bundle
echo 'export const css = "";' > "$WORK/proj/styles.gen.ts"
fi
fi
dir=$(dirname "$src")
+1 -1
View File
@@ -26,7 +26,7 @@ PORT=${RT_PORT:-7631}
OUT=${RT_OUT:-$(mktemp -d "${TMPDIR:-/tmp}/raea-rt-stage.XXXXXX")}
mkdir -p "$OUT"
bun "$ROOT/bench/realtime/stage/build.ts" "$OUT/page.js" || { echo "FAIL the stage page didn't build"; exit 1; }
ssim() { ffmpeg -nostdin -hide_banner -nostats -i "$1" -i "$2" -lavfi "[0:v]format=rgb24[a];[1:v]format=rgb24[b];[a][b]ssim" -f null - 2>&1 | grep -o 'All:[0-9.]*' | cut -d: -f2; }
. bench/lib/compare.sh
dim() { grep '<Composition' "$1" | head -1 | grep -oE "$2=\{[0-9]+\}" | head -1 | tr -dc 0-9; }
host=""
copies=()
+2 -2
View File
@@ -9,6 +9,7 @@
# A play keeps stepping to its snapshots' frames however loaded the machine (ovw), so an unreached frame is a failure.
cd "$(dirname "$0")/../.." || exit 2
ROOT=$PWD
. bench/lib/compare.sh
# pixel checks: no Content Credentials or TrustMark id in the frames (a still's mark moves its pixels)
export RAEA_SIGN=0 RAEA_MARK=0 RAEA_AUDIO_MUTE=1
BIN=${RAEA_BIN:-$ROOT/target/release/raea}
@@ -53,8 +54,7 @@ while IFS=$'\t' read -r path input secs why; do
if [ ! -f "$OUT/$slug-play-$s.png" ]; then line="$line $f:unreached"; broke=1; continue; fi
if [ ! -f "$OUT/$slug-render/$(printf 'frame-%05d.png' "$f")" ]; then line="$line $f:render-failed"; broke=1; continue; fi
cp "$OUT/$slug-render/$(printf 'frame-%05d.png' "$f")" "$OUT/$slug-render-$s.png"
v=$(ffmpeg -nostdin -hide_banner -nostats -i "$OUT/$slug-play-$s.png" -i "$OUT/$slug-render-$s.png" \
-lavfi "[0:v]format=rgb24[a];[1:v]format=rgb24[b];[a][b]ssim" -f null - 2>&1 | grep -o 'All:[0-9.]*' | cut -d: -f2)
v=$(ssim "$OUT/$slug-play-$s.png" "$OUT/$slug-render-$s.png")
line="$line $f:${v:-none}"
worst=$(awk -v w="$worst" -v v="${v:-0}" 'BEGIN { print (v + 0 < w + 0) ? v : w }')
done
+3 -3
View File
@@ -54,9 +54,9 @@ stats() {
times=$(grep -m1 '^{"direct"' "$OUT/$id.log" || echo '{}')
# the last "first frame" mark: a piece with 3D starts again once it meets its first 3D frame
first=$(grep "the fed render's first frame" "$OUT/$id.log" | tail -1 | awk '{print $3}')
# RAEA_FRAME_LOG: frame, react, sync, draw3d, gpu3d, page, gpupage, gpu (ms); frame 0 is the cold one
frames=$(awk -F'\t' 'NR == 2 { r0 = $2; s0 = $3; g0 = $8 }
NR > 2 { n++; r += $2; s += $3; g += $8 }
# RAEA_FRAME_LOG: frame, react, sync, gpu (ms); frame 0 is the cold one
frames=$(awk -F'\t' 'NR == 2 { r0 = $2; s0 = $3; g0 = $4 }
NR > 2 { n++; r += $2; s += $3; g += $4 }
END { printf "{\"first\":{\"react\":%.2f,\"sync\":%.2f,\"gpu\":%.2f},\"rest_mean\":{\"react\":%.2f,\"sync\":%.2f,\"gpu\":%.2f},\"rows\":%d}", r0, s0, g0, (n ? r / n : 0), (n ? s / n : 0), (n ? g / n : 0), n + 1 }' "$OUT/$id.tsv" 2> /dev/null || echo '{}')
jq -n --arg id "$id" --argjson wall "$(cat "$OUT/$id.wall")" --argjson first "${first:-null}" --argjson times "$times" --argjson log "$frames" \
'{id: $id, wall_s: $wall, first_frame_ms: $first, frames: $times.frames, encoder: $times.video,
+2 -2
View File
@@ -91,8 +91,8 @@ stats() {
local id=$1 times first frames
times=$(grep -m1 '^{.*"fps_incl_encode"' "$OUT/$id.log" 2> /dev/null || echo '{}')
first=$(grep "the fed render's first frame" "$OUT/$id.log" 2> /dev/null | tail -1 | awk '{print $3}')
frames=$(awk -F'\t' 'NR == 2 { r0 = $2; s0 = $3; g0 = $8 }
NR > 2 { n++; r += $2; s += $3; g += $8 }
frames=$(awk -F'\t' 'NR == 2 { r0 = $2; s0 = $3; g0 = $4 }
NR > 2 { n++; r += $2; s += $3; g += $4 }
END { printf "{\"first\":{\"react\":%.2f,\"sync\":%.2f,\"gpu\":%.2f},\"rest_mean\":{\"react\":%.2f,\"sync\":%.2f,\"gpu\":%.2f},\"rows\":%d}", r0, s0, g0, (n ? r / n : 0), (n ? s / n : 0), (n ? g / n : 0), n + 1 }' "$OUT/$id.tsv" 2> /dev/null || echo '{}')
jq -n --arg id "$id" --argjson app "$(cat "$OUT/$id.json" 2> /dev/null || echo '{}')" --argjson launch "$(cat "$OUT/$id.launch")" \
--argjson first "${first:-null}" --argjson times "$times" --argjson log "$frames" \
+1 -1
View File
@@ -25,7 +25,7 @@ export RAEA_SIGN=0 RAEA_MARK=0 RAEA_EXPORT_CACHE=0
mkdir -p "$OUT"
fail=0
ssim() { ffmpeg -hide_banner -nostats -i "$1" -i "$2" -lavfi ssim -f null - 2>&1 | sed -n 's/.*All:\([0-9.]*\).*/\1/p'; }
. bench/lib/compare.sh
# the box the two pictures' differing pixels lie in, "x1 x2 y1 y2", or nothing when every pixel is the same
box() { ffmpeg -hide_banner -i "$1" -i "$2" -lavfi "[0][1]blend=all_mode=difference,format=gray,bbox=min_val=1" -f null - 2>&1 | grep -o "x1:[0-9]* x2:[0-9]* y1:[0-9]* y2:[0-9]*" | tail -1 | sed 's/[a-z0-9]*://g'; }
lower() { echo "$1 $2" | awk '{print ($2 < $1) ? $2 : $1}'; }
+1 -1
View File
@@ -30,7 +30,7 @@ export RAEA_SIGN=0 RAEA_MARK=0 RAEA_EXPORT_CACHE=0
mkdir -p "$OUT"
fail=0
ssim() { ffmpeg -hide_banner -nostats -i "$1" -i "$2" -lavfi ssim -f null - 2>&1 | sed -n 's/.*All:\([0-9.]*\).*/\1/p'; }
. bench/lib/compare.sh
lower() { echo "$1 $2" | awk '{print ($2 < $1) ? $2 : $1}'; }
now() { perl -MTime::HiRes=time -e 'printf "%.3f", time'; }
png() { echo "$1/frame-$(printf %05d "$2").png"; }
+68
View File
@@ -0,0 +1,68 @@
#!/bin/bash
# How fast raea renders the L2 compositions (bench/p26-baseline/manifest.jsonl, resolved as P26 resolves them; the
# plugin build's rows left out). Each is rendered whole to an MP4, once to warm up and then RUNS times, the export
# cache off. Two speeds, each the video's seconds over wall seconds (2.0x: two seconds of video for each second waited):
# frames over the time spent making and encoding the frames (the render's own count: RAEA_RENDER_STATS'
# fps_incl_encode)
# render over the whole command, spawn to exit: what a person waits for. The frames plus the rest of the command
# (the bundle, the page's start, sound, the end checks, signing), which the "rest" column holds
# One line a composition: each speed's median and the range of its runs, the rest's median, and the load. SLOW marks a
# median frame speed under 1.0x. Then the slowest medians, and how many compositions render slower than they play.
# Each run prints its own line as it ends (a game's 36000-frame bound renders for minutes).
#
# bench/speed/run.sh [RAEA_BIN] (default target/release/raea; RUNS=5; ONLY=a grep -E pattern limits the
# compositions)
#
# A measurement, not a check: it exits 1 only when a composition makes no video. Run it under antsy with a memory cap
# (a whole render of the 1-frame sdk/react/bench/css/svg.tsx grows without bound after writing its frame). A loaded
# machine is slower: read the range before the median, and the load printed with each line.
set -uo pipefail
ROOT=$(cd "$(dirname "$0")/../.." && pwd)
HERE=$ROOT/bench/p26-baseline
# shellcheck source=bench/p26-baseline/lib.sh
. "$HERE/lib.sh"
BIN=${1:-${RAEA_BIN:-$ROOT/target/release/raea}}
RUNS=${RUNS:-5}
[ -x "$BIN" ] || { echo "speed: no raea at $BIN" >&2; exit 2; }
WORK=$(mktemp -d "${TMPDIR:-/tmp}/raea-speed.XXXXXX")
trap 'rm -rf "$WORK"' EXIT
now() { perl -MTime::HiRes=time -e 'printf "%.3f", time'; }
load() { sysctl -n vm.loadavg 2>/dev/null | awk '{ print $2 }' || cut -d' ' -f1 /proc/loadavg; }
range() { printf '%s\n' "$@" | sort -n | awk '{ v[NR] = $1 } END { print v[1], v[int((NR + 1) / 2)], v[NR] }'; }
fail=0 n=0 slow=0 under=0 worst='' wrel='' rworst='' rrel=''
for rel in $(jq -r 'select(.binary | test("bevy-plugins|bin-avian") | not) | .composition' "$HERE/manifest.jsonl" | awk '!seen[$0]++'); do
[ -n "${ONLY:-}" ] && ! grep -qE "$ONLY" <<< "$rel" && continue
p26_src "$rel"
speeds=() whole=() rest=() secs=
for i in $(seq 0 "$RUNS"); do
rm -f "$WORK/out.mp4"
t0=$(now)
# its exit isn't read: the end checks (raea check --at render) fail a composition on what it shows, after the MP4
# is written, and that's no slower render
(cd "$dir" && RAEA_EXPORT_CACHE=0 RAEA_RENDER_STATS=1 RAEA_DESPITE="all: speed times the render, not what its scene says" \
"$BIN" render "$src" ${copt[@]+"${copt[@]}"} -o "$WORK/out.mp4") > "$WORK/log" 2>&1
t1=$(now)
secs=$(ffprobe -v error -select_streams v:0 -show_entries stream=duration -of csv=p=0 "$WORK/out.mp4" 2>/dev/null)
[ -n "$secs" ] || { echo "FAIL $rel: no video came out: $(grep -m1 -E 'REFUSED|error|Error|panicked' "$WORK/log" | cut -c1-200)"; fail=1; continue 2; }
fps=$(grep '^{' "$WORK/log" | grep fps_incl_encode | tail -1 | jq -r '"\(.frames) \(.fps_incl_encode)"')
[ -n "$fps" ] || { echo "FAIL $rel: the render said no frame count (RAEA_RENDER_STATS)"; fail=1; continue 2; }
# run 0 warms the caches (the bundle, shaders, fonts); it isn't counted
[ "$i" = 0 ] && continue
read -r f w r <<< "$(awk -v s="$secs" -v a="$t0" -v b="$t1" -v fps="$fps" 'BEGIN { split(fps, x, " "); t = x[1] / x[2]
printf "%.2f %.2f %.2f", s / t, s / (b - a), (b - a) - t }')"
speeds+=("$f"); whole+=("$w"); rest+=("$r")
echo " run $i of $RUNS: frames ${f}x, render ${w}x, rest $r s $rel"
done
read -r lo med hi <<< "$(range "${speeds[@]}")"
read -r rlo rmed rhi <<< "$(range "${whole[@]}")"
read -r _ xmed _ <<< "$(range "${rest[@]}")"
n=$((n + 1)) ok=ok
awk -v m="$med" 'BEGIN { exit !(m < 1) }' && { slow=$((slow + 1)); ok=SLOW; }
awk -v m="$rmed" 'BEGIN { exit !(m < 1) }' && under=$((under + 1))
if [ -z "$worst" ] || awk -v m="$med" -v w="$worst" 'BEGIN { exit !(m < w) }'; then worst=$med wrel=$rel; fi
if [ -z "$rworst" ] || awk -v m="$rmed" -v w="$rworst" 'BEGIN { exit !(m < w) }'; then rworst=$rmed rrel=$rel; fi
printf '%-4s frames %6sx (%s-%s) render %5sx (%s-%s) rest %5s s %d runs %6.2f s of video load %s %s\n' \
"$ok" "$med" "$lo" "$hi" "$rmed" "$rlo" "$rhi" "$xmed" "${#speeds[@]}" "$secs" "$(load)" "$rel"
done
echo "speed: $n compositions; frames slower than they play in $slow (slowest ${worst:-none}x, $wrel); the whole render slower than they play in $under (slowest ${rworst:-none}x, $rrel)"
exit $fail
-2
View File
@@ -11,5 +11,3 @@ serde = { version = "1", features = ["derive"] }
serde_json = "1"
# a file's ident (ident.rs), the one the ledger keeps
sha2 = "0.10"
# the TypeScript declarations are generated from these types, so the two can't drift
ts-rs = "12"
+2 -2
View File
@@ -1,6 +1,6 @@
//! What a file is, cheaply: its size and a hash of its first and last MB. The ledger keeps it on every call
//! (apps/ask record.rs), so a render is known again by its copy in the feed, a later render to the same path isn't
//! taken for it, and `raea goal gates` knows an answer was about exactly the sheet on disk now (docs/goal.feature MK4).
//! (apps/ask record.rs), so a render is known again by its copy in the feed, and a later render to the same path isn't
//! taken for it.
use std::io::{Read as _, Seek as _, SeekFrom};
use std::path::Path;
+2 -18
View File
@@ -1,6 +1,5 @@
//! Questions for the decision model (clef-omni), as every caller of `raea ask` writes them (docs/ask.feature AK1): the
//! question and how its answer reads, the sets that come standard, and the model's limits. Its TypeScript declarations
//! are generated from these types (`declarations`): sdk/raea/src/ask.gen.ts, checked by a test.
//! Questions for the decision model (clef-omni), as every caller of apps/ask writes them (docs/ask.feature AK1): the
//! question and how its answer reads, the sets that come standard, and the model's limits.
pub mod ident;
pub mod library;
@@ -9,20 +8,5 @@ pub mod question;
pub use question::{Calibration, Facts, Kind, LEVELS, Picks, Question, Reading, Sees, When, Window};
use ts_rs::{Config, TS};
macro_rules! decls {
($cfg:ident; $($t:ty),* $(,)?) => { vec![$(format!("export {}", <$t as TS>::decl(&$cfg))),*] };
}
/// The TypeScript of every type, one file's worth: sdk/raea/src/ask.gen.ts is this, checked by a test.
pub fn declarations() -> String {
let cfg = Config::new();
let mut out = vec!["// Generated from raea-core-ask (core/ask) by its `declarations`; edit the Rust, not this.".to_string()];
out.extend(decls!(cfg; question::Question, question::Kind, question::Sees, question::Picks, question::When, question::Window, question::Calibration));
out.push(format!("export const SETS = {:?} as const;", library::SETS));
out.join("\n\n") + "\n"
}
#[cfg(test)]
mod tests;
+5 -5
View File
@@ -1,5 +1,5 @@
//! The questions that come standard (docs/ask.feature AK1), each set named: `rubric` (the craft rubric's own questions,
//! read from sdk/guides/craft/rubric.md, so there's one copy), `av` (picture with sound), `defects` (the fingerprint's
//! The questions that come standard (docs/ask.feature AK1), each set named: `rubric` (the critique guide's questions,
//! read from sdk/guides/craft/verbs/critique.md, so there's one copy), `av` (picture with sound), `defects` (the fingerprint's
//! axes with no labels yet), `platform` (the check packs' questions with their calibration), `decide` (picks and
//! comparisons) and `make` (the review loop's gate questions, asked of a job's sheets: docs/goal.feature MK4; each id
//! says its sheet, make.clay.*, make.colour.*, make.refs.*, make.framing.*). The JSON sets ship inside raea; the
@@ -7,7 +7,7 @@
use crate::question::{Kind, Question};
/// Every set, in the order `raea ask list` shows them.
/// Every set, in the order they're listed.
pub const SETS: [&str; 6] = ["rubric", "av", "defects", "platform", "decide", "make"];
fn embedded(name: &str) -> Option<&'static str> {
@@ -57,10 +57,10 @@ pub fn rubric(md: &str) -> Vec<Question> {
out
}
/// A set's questions. `rubric_md` is the rubric guide's text, needed only for `rubric`.
/// A set's questions. `rubric_md` is the critique guide's text, needed only for `rubric`.
pub fn set(name: &str, rubric_md: Option<&str>) -> Result<Vec<Question>, String> {
if name == "rubric" {
let md = rubric_md.ok_or("the rubric set is read from the rubric guide (raea guide rubric), which wasn't found")?;
let md = rubric_md.ok_or("the rubric set is read from the critique guide (raea guide critique), which wasn't found")?;
return Ok(rubric(md));
}
let text = embedded(name).ok_or_else(|| format!("no set named {name:?}: {}", SETS.join(", ")))?;
+7 -22
View File
@@ -5,13 +5,12 @@ use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use ts_rs::TS;
/// The five levels a `grade` reads over unless it names its own (the rubric's, and checks.rs's "score").
pub const LEVELS: [&str; 5] = ["poor", "weak", "acceptable", "strong", "excellent"];
/// clef's question types: `yes` is its noul, `choose` and `grade` its choice, `rate` its score.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, TS)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Kind {
/// the probability of yes
@@ -26,7 +25,7 @@ pub enum Kind {
}
/// What of the picture a question looks at.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, TS)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Sees {
/// the moving picture (2 frames a second, at most a minute)
@@ -39,7 +38,7 @@ pub enum Sees {
}
/// Its options are the files it's given, in order (first, second ...), or all but the first, which is the reference.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Picks {
All,
@@ -47,12 +46,10 @@ pub enum Picks {
}
/// What a piece must be for a question to be asked of it. Unset is any.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, TS)]
#[ts(optional_fields)]
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct When {
/// the brief's modes it's for (pitch, story, explain, play, tool); empty is every mode
#[serde(default, skip_serializing_if = "Vec::is_empty")]
#[ts(as = "Option<Vec<String>>", optional)]
pub modes: Vec<String>,
/// true: only when someone is heard speaking; false: only when no one is
#[serde(skip_serializing_if = "Option::is_none")]
@@ -63,8 +60,7 @@ pub struct When {
}
/// The seconds a question looks at; unset ends are the file's.
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize, TS)]
#[ts(optional_fields)]
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
pub struct Window {
#[serde(skip_serializing_if = "Option::is_none")]
pub from: Option<f64>,
@@ -73,8 +69,7 @@ pub struct Window {
}
/// How well a question's answers separate work with the problem from work without it, on labels (AK7).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[ts(optional_fields)]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Calibration {
pub auc: f64,
pub n: u32,
@@ -89,43 +84,34 @@ pub struct Calibration {
}
/// A question, as the standard sets, a taste line, a batch file or the command line write it.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[ts(optional_fields)]
pub struct Question {
/// letters, digits, `_`, `.` and `-`
pub id: String,
/// the question in words, as clef reads it
pub ask: String,
#[serde(rename = "type", default)]
#[ts(rename = "type", as = "Option<Kind>", optional)]
pub kind: Kind,
/// choose: its options; grade and rate: its levels, lowest first (a grade's are LEVELS unless given)
#[serde(default, skip_serializing_if = "Vec::is_empty")]
#[ts(as = "Option<Vec<String>>", optional)]
pub options: Vec<String>,
/// what an option (or yes and no) means, when its name alone doesn't say
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
#[ts(as = "Option<BTreeMap<String, String>>", optional)]
pub means: BTreeMap<String, String>,
/// the answers that mean a problem: yes's "yes" (the default) or "no"; choose's options (none: a pick, no problem)
#[serde(default, skip_serializing_if = "Vec::is_empty")]
#[ts(as = "Option<Vec<String>>", optional)]
pub flags: Vec<String>,
#[serde(default)]
#[ts(as = "Option<Sees>", optional)]
pub sees: Sees,
/// whether it listens to the sound (true unless set)
#[serde(default = "yes", skip_serializing_if = "is_true")]
#[ts(as = "Option<bool>", optional)]
pub hears: bool,
/// what the state tells clef beside the media: brief, words (heard), screen-words, measures, brand, platform; and
/// with: it compares the file with the files set beside it, so it isn't asked without them
#[serde(default, skip_serializing_if = "Vec::is_empty")]
#[ts(as = "Option<Vec<String>>", optional)]
pub uses: Vec<String>,
#[serde(default, skip_serializing_if = "When::is_any")]
#[ts(as = "Option<When>", optional)]
pub when: When,
/// the question asked in its place when `when` doesn't hold (sound -> sound-silent)
#[serde(skip_serializing_if = "Option::is_none")]
@@ -136,7 +122,6 @@ pub struct Question {
pub picks: Option<Picks>,
/// words in a person's note that mean they saw this problem (AK6)
#[serde(default, skip_serializing_if = "Vec::is_empty")]
#[ts(as = "Option<Vec<String>>", optional)]
pub label_words: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub calibration: Option<Calibration>,
+1 -12
View File
@@ -1,18 +1,7 @@
use super::*;
use serde_json::json;
const RUBRIC: &str = include_str!("../../../sdk/guides/craft/rubric.md");
#[test]
fn declarations_match_the_committed_file() {
let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../sdk/raea/src/ask.gen.ts");
let now = declarations();
if std::env::var_os("RAEA_WRITE").is_some() {
std::fs::write(path, &now).unwrap();
}
let committed = std::fs::read_to_string(path).unwrap_or_default();
assert!(committed == now, "sdk/raea/src/ask.gen.ts is out of date: RAEA_WRITE=1 cargo test -p raea-core-ask");
}
const RUBRIC: &str = include_str!("../../../sdk/guides/craft/verbs/critique.md");
#[test]
fn every_standard_question_reads_and_fits_the_limits() {
+1 -1
View File
@@ -83,7 +83,7 @@ pub struct CutPlan {
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(optional_fields)]
#[ts(rename = "Beat")]
#[ts(rename = "CutBeat")]
pub struct Beat {
/// where it starts, in seconds from the cut's start (0 for the first)
pub at: f64,
+21 -11
View File
@@ -1,8 +1,8 @@
//! A goal (docs/goal.feature): one step of the work, on a project's brief.ts as `goal:` (one, or several in order: a
//! workflow), written with `cut()`, `shot()`, `kit()`, `scene()` or `rules()` from "raea/brief" before anything is
//! built, and read here. Each kind turns its packs on: a scene (a dressed, lit place), a kit (props that belong
//! together), a shot (stills or camera moves of a built scene), a cut (ads from footage to a client's brief), and
//! rules (any other work: only its own rules). Any goal can carry `rules` and an `aim`. Every object carries its real
//! workflow), written with `cut()`, `shot()`, `kit()`, `scene()`, `playable()` or `rules()` from "raea/brief" before
//! anything is built, and read here. Each kind turns its packs on: a scene (a dressed, lit place), a kit (props that
//! belong together), a shot (stills or camera moves of a built scene), a cut (ads from footage to a client's brief), a
//! playable (a game exported as a playable ad, playable.rs), and rules (any other work: only its own rules). Any goal can carry `rules` and an `aim`. Every object carries its real
//! size and whether it came from the reference or was invented; every dial its value, where the value came from, and
//! what it meant here. `raea goal check` (sdk/goal) holds each goal to it.
@@ -25,6 +25,9 @@ pub enum Kind {
Cut,
/// any other work, held only to its rules: commands that must pass, files that must exist, words a critic judges
Rules,
/// a game exported as a playable ad by `raea playable`: each network's page, the preview, both orientations unless
/// the brief says one (playable.rs, docs/playables.feature PA19)
Playable,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
@@ -70,16 +73,18 @@ pub struct Goal {
#[serde(default)]
#[ts(as = "Option<Vec<String>>", optional)]
pub deliverables: Vec<String>,
/// the most critic rounds the job gets; at the cap it is delivered with what's still missing (8 by default)
/// read by nothing: the critic rounds it capped are gone (docs/check.feature); kept so a brief that sets it parses
pub rounds: Option<u32>,
/// a cut job's contract: the brief as rules (cut.rs)
pub cut: Option<crate::cut::Cut>,
/// a playable job's game, networks and orientation (playable.rs)
pub playable: Option<crate::playable::Playable>,
/// what the job shows but never delivers, relative to the brief (pictures, render tests, examples): each a file or a
/// `dir/` (review/ and previews/ when left out). Deliverables are what it hands over; previews are how it got there
#[serde(default)]
#[ts(as = "Option<Vec<String>>", optional)]
pub previews: Vec<String>,
/// raea's packs switched by name over the kind's defaults (`{ surprise: true, place: false }`): which of
/// raea's packs switched by name over the kind's defaults (`{ voice: true, place: false }`): which of
/// raea/goal's rules hold this goal (docs/goal.feature)
#[serde(default)]
#[ts(as = "Option<BTreeMap<String, bool>>", optional)]
@@ -224,10 +229,10 @@ pub struct Shot {
}
impl Kind {
/// as brief.ts writes it, and as raea judge's rubrics are named
/// as brief.ts writes it
pub fn name(self) -> &'static str {
// in the enum's order
["scene", "kit", "shot", "cut", "rules"][self as usize]
["scene", "kit", "shot", "cut", "rules", "playable"][self as usize]
}
}
@@ -239,12 +244,10 @@ pub fn dials(kind: Kind) -> &'static [&'static str] {
Kind::Shot => &["res", "seconds", "lens", "handheld", "look"],
Kind::Cut => &["look"],
Kind::Rules => &[],
Kind::Playable => &["look"],
}
}
/// The round cap when the plan names none: AnyKit's and raea judge's 8.
pub const ROUNDS: u32 = 8;
/// What must exist when the goal is done, relative to the brief's folder: its own list, else its kind's; and each of
/// its `file` rules.
pub fn deliverables(m: &Goal) -> Vec<String> {
@@ -276,6 +279,7 @@ fn by_kind(m: &Goal) -> Vec<String> {
Kind::Cut => m.cut.as_ref().map(crate::cut::deliverables).unwrap_or_default(),
// only its `file` rules, added above
Kind::Rules => vec![],
Kind::Playable => m.playable.as_ref().map(crate::playable::deliverables).unwrap_or_default(),
}
}
@@ -307,6 +311,12 @@ pub fn doctor(m: &Goal) -> Vec<String> {
(Some(_), k) => out.push(format!("`cut` is for a cut job, not a {k:?}: drop it, or make this `cut({{...}})`")),
_ => {}
}
match (&m.playable, m.kind) {
(Some(p), Kind::Playable) => out.extend(crate::playable::doctor(p)),
(None, Kind::Playable) => out.push("no `playable`: the game's TSX (`game`), and its networks and orientation when the brief names them".into()),
(Some(_), k) => out.push(format!("`playable` is for a playable job, not a {k:?}: drop it, or make this `playable({{...}})`")),
_ => {}
}
out.extend(crate::rules::doctor(&m.rules));
if m.kind == Kind::Rules {
if m.aim.as_deref().is_none_or(|a| a.trim().is_empty()) {
+22 -4
View File
@@ -7,6 +7,7 @@ pub mod brief;
pub mod cut;
pub mod goal;
pub mod parts;
pub mod playable;
pub mod rules;
pub mod script;
pub mod taste;
@@ -30,18 +31,35 @@ macro_rules! decls {
($cfg:ident; $($t:ty),* $(,)?) => { vec![$(format!("export {}", <$t as TS>::decl(&$cfg))),*] };
}
/// The TypeScript declarations of every schema, one file's worth: sdk/raea/src/brief.gen.ts is this, checked by a test, and
/// `raea/brief` (sdk/raea/src/brief.ts) types its builders with it, so the declarations ship with the SDK.
/// The file the goal's declarations are written to, beside brief.gen.ts (which re-exports them)
pub const GOAL_FILE: &str = "brief-goal.gen";
/// The TypeScript declarations of every schema, two files' worth (a file stays under 500 lines, tools/size.sh):
/// sdk/raea/src/brief.gen.ts is this, the goal's (`goal_declarations`) re-exported from it, each checked by a test,
/// and `raea/brief` (sdk/raea/src/brief.ts) types its builders with them, so the declarations ship with the SDK.
pub fn declarations() -> String {
let cfg = Config::new();
let mut out = vec!["// Generated from raea-core-brief (core/brief) by its `declarations`; edit the Rust, not this.".to_string()];
let mut out = vec![format!(
"// Generated from raea-core-brief (core/brief) by its `declarations`; edit the Rust, not this.\nimport type {{ Goals }} from \"./{GOAL_FILE}\";\nexport type * from \"./{GOAL_FILE}\";"
)];
out.extend(decls!(cfg;
brief::Brief, brief::Section, brief::Deliverable, brief::Reference, brief::Agent,
script::Script, script::Scene, script::Beat, script::Line,
taste::Taste, taste::TasteSection, taste::Rule, taste::RuleCheck, taste::RuleLevel, taste::Check,
parts::Parts, parts::Concept, parts::Level, parts::Count, parts::Part,
));
out.join("\n\n") + "\n"
}
/// The goal's declarations (what the work is held to: goal.rs, cut.rs, playable.rs, rules.rs): sdk/raea/src/brief-goal.gen.ts
pub fn goal_declarations() -> String {
let cfg = Config::new();
// a cut's beats are its own (cut.rs Beat, CutBeat in TypeScript: feel, story, asl, tempo), not a script's
let mut out = vec!["// Generated from raea-core-brief (core/brief) by its `goal_declarations`; edit the Rust, not this.".to_string()];
out.extend(decls!(cfg;
goal::Goal, goal::Kind, goal::Source, goal::DialValue, goal::Dial, goal::Route, goal::Origin, goal::Pick, goal::Object, goal::Shot, goal::Goals,
cut::Cut, cut::Quoted<u32>, cut::CutPlan, cut::Phrase, cut::Cta, cut::Open,
cut::Cut, cut::Quoted<u32>, cut::CutPlan, cut::Beat, cut::Phrase, cut::Cta, cut::Open,
playable::Playable, playable::Orientation,
rules::Rule,
));
out.join("\n\n") + "\n"
+125
View File
@@ -0,0 +1,125 @@
//! A playable goal (docs/playables.feature PA19): a raea game exported as a playable ad by `raea playable`, held to its
//! pages. The game is one TSX that renders as the video ad and exports for each network; the goal names it, the
//! networks it ships to and its orientation (both, unless the brief says one), and its deliverables are what the export
//! writes into out/playable/: each network's page or ZIP, the preview, and the export's manifest, which raea goal's
//! playable pack reads (sizes, compositions, when it was exported).
use serde::{Deserialize, Serialize};
use ts_rs::TS;
/// The networks `raea playable` writes for (apps/playable pages.rs NETWORKS, preview last)
pub const NETWORKS: &[&str] = &[
"applovin",
"unity",
"google",
"meta",
"moloco",
"mintegral",
"tiktok",
"liftoff",
];
/// The networks whose package is a ZIP (the rest are one HTML page)
const ZIPPED: &[&str] = &["google", "mintegral", "tiktok"];
/// Where the export writes, relative to the brief
pub const OUT: &str = "out/playable";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
#[serde(rename_all = "lowercase")]
#[ts(rename = "PlayableOrientation")]
pub enum Orientation {
/// a portrait and a landscape composition, the host playing the one nearest the screen
Both,
Portrait,
Landscape,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(optional_fields, rename = "PlayableGoal")]
pub struct Playable {
/// the game's TSX, relative to the brief: it renders as the video ad and exports as the playable
pub game: String,
/// the files' name ([a-z0-9_], `NAME-NETWORK.html`); the game's file name when left out
pub name: Option<String>,
/// the networks it ships to (applovin, unity, google, meta, moloco, mintegral, tiktok, liftoff); all of them when
/// left out. The preview page is always made: it's what the review plays
#[serde(default)]
#[ts(as = "Option<Vec<String>>", optional)]
pub networks: Vec<String>,
/// both unless the brief says one: Unity, AppLovin, Moloco and Mintegral want both
pub orientation: Option<Orientation>,
/// [least, most] seconds of play before the end card (15 to 60 by default)
pub seconds: Option<[f64; 2]>,
/// the same game rendered as the video ad too, as out/cuts/NAME_9x16.mp4 (PA17)
pub video: Option<bool>,
}
/// The name its files land as: its own, else the game's file name, as `raea playable` names them
pub fn name(p: &Playable) -> String {
p.name.clone().unwrap_or_else(|| {
std::path::Path::new(&p.game)
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("playable")
.to_string()
})
}
/// The networks it ships to, in raea's order
pub fn networks(p: &Playable) -> Vec<&'static str> {
NETWORKS
.iter()
.copied()
.filter(|n| p.networks.is_empty() || p.networks.iter().any(|m| m == n))
.collect()
}
/// What the export must have written: each network's page or ZIP, the preview and the manifest, and the video ad
pub fn deliverables(p: &Playable) -> Vec<String> {
let n = name(p);
let mut out: Vec<String> = networks(p)
.iter()
.map(|net| {
format!(
"{OUT}/{n}-{net}.{}",
if ZIPPED.contains(net) { "zip" } else { "html" }
)
})
.collect();
out.push(format!("{OUT}/{n}-preview.html"));
out.push(format!("{OUT}/{n}.playable.json"));
if p.video == Some(true) {
out.push(format!("out/cuts/{n}_9x16.mp4"));
}
out
}
/// What the playable still lacks before it can be built against
pub fn doctor(p: &Playable) -> Vec<String> {
let mut out = Vec::new();
if !p.game.ends_with(".tsx") {
out.push(format!(
"`game` {:?}: the game's TSX beside the brief (playable.tsx)",
p.game
));
}
if let Some(n) = p.name.as_deref().filter(|n| !crate::goal::is_name(n)) {
out.push(format!("playable name `{n}`: names are [a-z0-9_]"));
}
for n in p
.networks
.iter()
.filter(|n| !NETWORKS.contains(&n.as_str()))
{
out.push(format!(
"network `{n}` isn't one raea exports to ({})",
NETWORKS.join(", ")
));
}
if let Some([a, b]) = p.seconds {
if !(a > 0.0 && a <= b) {
out.push(format!("seconds [{a}, {b}]: least then most, both over 0"));
}
}
out
}
+1 -1
View File
@@ -22,7 +22,7 @@ pub struct Rule {
pub timeout: Option<u32>,
/// a file that must exist, relative to the brief (`a|b`: either; `dir/`: three or more pictures in it)
pub file: Option<String>,
/// words that must be true of the work, judged by a fresh critic (`raea goal judge`), never by the agent that did it
/// words the work should make true, which nothing checks (docs/check.feature): hold them with a `run` or `file` rule
pub says: Option<String>,
}
+45 -7
View File
@@ -1,14 +1,18 @@
use super::*;
#[test]
fn declarations_match_the_committed_file() {
let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../sdk/raea/src/brief.gen.ts");
let now = declarations();
if std::env::var_os("RAEA_WRITE").is_some() {
std::fs::write(path, &now).unwrap();
fn declarations_match_the_committed_files() {
let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/../../sdk/raea/src");
for (file, now) in [("brief.gen.ts".to_string(), declarations()), (format!("{GOAL_FILE}.ts"), goal_declarations())] {
let path = format!("{dir}/{file}");
if std::env::var_os("RAEA_WRITE").is_some() {
std::fs::write(&path, &now).unwrap();
}
let committed = std::fs::read_to_string(&path).unwrap_or_default();
assert!(committed == now, "sdk/raea/src/{file} is out of date: RAEA_WRITE=1 cargo test -p raea-core-brief");
let lines = now.lines().count();
assert!(lines <= 500, "sdk/raea/src/{file} is {lines} lines: split it (tools/size.sh)");
}
let committed = std::fs::read_to_string(path).unwrap_or_default();
assert!(committed == now, "sdk/raea/src/brief.gen.ts is out of date: RAEA_WRITE=1 cargo test -p raea-core-brief");
}
#[test]
@@ -153,3 +157,37 @@ fn several_goals_are_a_workflow_and_each_is_held_to_its_rules() {
let one: Brief = read("brief.ts", r#"{"title": "x", "goal": {"kind": "rules", "aim": "ship it", "rules": [{"id": "ok", "run": "true"}]}}"#).unwrap();
assert!(goal::doctor_all(one.goal.as_ref().unwrap()).is_empty());
}
#[test]
fn a_playable_goal_delivers_each_networks_page_the_preview_and_the_manifest() {
let g: crate::goal::Goal = serde_json::from_str(r#"{"kind":"playable","aim":"a runner for a tea brand","playable":{"game":"playable.tsx","networks":["applovin","google"],"video":true}}"#).unwrap();
assert_eq!(
crate::goal::deliverables(&g),
[
"out/playable/playable-applovin.html",
"out/playable/playable-google.zip",
"out/playable/playable-preview.html",
"out/playable/playable.playable.json",
"out/cuts/playable_9x16.mp4"
]
);
assert!(
crate::goal::doctor(&g).is_empty(),
"{:?}",
crate::goal::doctor(&g)
);
// both orientations unless the brief names one: `raea playable`'s own default
assert_eq!(g.playable.as_ref().unwrap().orientation, None);
let bad: crate::goal::Goal = serde_json::from_str(
r#"{"kind":"playable","aim":"x","playable":{"game":"game.ts","networks":["vungle"]}}"#,
)
.unwrap();
let d = crate::goal::doctor(&bad).join("\n");
assert!(d.contains("game.ts") && d.contains("vungle"), "{d}");
let none: crate::goal::Goal = serde_json::from_str(r#"{"kind":"playable","aim":"x"}"#).unwrap();
assert!(
crate::goal::doctor(&none)
.iter()
.any(|l| l.starts_with("no `playable`"))
);
}
+8 -3
View File
@@ -135,7 +135,7 @@ pub const KEEP_BUFFER_AT: usize = 1 << 16;
/// (buffers/NAME.json, NAME its content's BLAKE3), so what holds the shape holds 40 characters
/// (docs/render-memory.feature RM8). halcyon's palms were 263 MB of vertex arrays as text, held by the React scene,
/// every frame's program row, the store and the evaluator: two of them 51 MB each. None for a short one, one already
/// kept, or when the caches folder can't be written (the text then goes as it is).
/// kept, or when the caches folder can't be written (the text then goes as it is). The folder is pruned (kept.rs).
pub fn kept_buffer(expr: &str) -> Option<String> {
let json = expr.strip_prefix("buffer:")?;
if json.len() < KEEP_BUFFER_AT || json.starts_with('@') {
@@ -145,7 +145,10 @@ pub fn kept_buffer(expr: &str) -> Option<String> {
let name = &hex.as_str()[..32];
let dir = crate::kept::caches()?.join("buffers");
let p = dir.join(format!("{name}.json"));
if !p.exists() {
if p.exists() {
crate::kept::touch(&p);
} else {
crate::kept::prune_once(&dir);
let part = dir.join(format!(".{name}.{}.part", std::process::id()));
std::fs::create_dir_all(&dir).ok()?;
std::fs::write(&part, json).ok()?;
@@ -161,7 +164,9 @@ pub fn buffer_json(b: &str) -> Result<std::borrow::Cow<'_, str>, String> {
return Err(format!("buffer:@{name}: not a kept buffer's name"));
}
let p = crate::kept::caches().ok_or("no caches folder for a kept buffer")?.join("buffers").join(format!("{name}.json"));
std::fs::read_to_string(&p).map(std::borrow::Cow::Owned).map_err(|e| format!("buffer:@{name}: {}: {e}", p.display()))
let json = std::fs::read_to_string(&p).map_err(|e| format!("buffer:@{name}: {}: {e}", p.display()))?;
crate::kept::touch(&p);
Ok(std::borrow::Cow::Owned(json))
}
#[cfg(test)]
+77 -4
View File
@@ -4,9 +4,80 @@
//! program's size and time: another build may cut differently), and read back as the bytes that were written, so
//! what is drawn from it is what would have been made. RAEA_SHAPE_CACHE=0 turns it off, =DIR moves it from raea's
//! caches folder (shapes/ in it).
//!
//! The kept folders (shapes/ here, buffers/ for buffer.rs's kept BufferMesh text) are pruned once a process, at its
//! first write into each: the least recently used files go until the folder holds KEEP_BYTES, and none read or written
//! in the last IN_USE goes. Every read touches its file, so a buffer a running scene names stays. Unpruned, buffers/
//! grew by an animated BufferMesh's ~10 MB a frame and filled the disk.
use crate::Tris;
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime};
/// What each kept folder holds before its least recently used files go.
const KEEP_BYTES: u64 = 4 << 30;
/// A kept file read or written this recently stays, whatever its folder holds: a render reads its buffers as its frames
/// draw, and none may go mid-render. Two hours, as a render's work folder is kept (raea-runtime-bundle's sweep).
const IN_USE: Duration = Duration::from_secs(2 * 3600);
/// A kept file just used: its time moved on, so the prune takes the least recently used first.
pub(crate) fn touch(p: &Path) {
let _ = std::fs::File::options().append(true).open(p).and_then(|f| f.set_modified(SystemTime::now()));
}
/// `dir` pruned (prune), the first time this process writes into it.
pub(crate) fn prune_once(dir: &Path) {
static DONE: std::sync::Mutex<Vec<PathBuf>> = std::sync::Mutex::new(Vec::new());
{
let mut done = DONE.lock().unwrap_or_else(|e| e.into_inner());
if done.iter().any(|d| d == dir) {
return;
}
done.push(dir.to_path_buf());
}
prune(dir, KEEP_BYTES, SystemTime::now());
}
/// Whether a file's name is one this cache writes: a shape (`<hex>-<hex>.tris`), a buffer (`<32 hex>.json`), or either's
/// write cut short (`.<that>.<pid>.part`). RAEA_SHAPE_CACHE may name a folder that holds other files: the prune never
/// takes those.
pub(crate) fn ours(name: &str) -> bool {
let hex = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_hexdigit());
let kept = |n: &str| {
n.strip_suffix(".tris").and_then(|b| b.split_once('-')).is_some_and(|(a, b)| hex(a) && hex(b))
|| n.strip_suffix(".json").is_some_and(|b| b.len() == 32 && hex(b))
};
match name.strip_prefix('.').and_then(|n| n.strip_suffix(".part")).and_then(|n| n.rsplit_once('.')) {
Some((n, pid)) => pid.bytes().all(|b| b.is_ascii_digit()) && (kept(n) || hex(n)),
None => kept(name),
}
}
/// The cache's own files in `dir` (ours; a write cut short too) removed least recently used first while they hold more
/// than `keep` bytes, stopping at the first used within IN_USE of `now`.
pub(crate) fn prune(dir: &Path, keep: u64, now: SystemTime) {
let mut files: Vec<(SystemTime, u64, PathBuf)> = std::fs::read_dir(dir)
.into_iter()
.flatten()
.flatten()
.filter(|e| ours(&e.file_name().to_string_lossy()))
.filter_map(|e| {
let m = e.metadata().ok().filter(|m| m.is_file())?;
Some((m.modified().ok()?, m.len(), e.path()))
})
.collect();
files.sort();
let mut held: u64 = files.iter().map(|f| f.1).sum();
for (t, n, p) in files {
if held <= keep || !now.duration_since(t).is_ok_and(|age| age >= IN_USE) {
break;
}
if std::fs::remove_file(&p).is_ok() {
held -= n;
}
}
}
/// raea's caches folder, as raea-io-home names it (this crate is below it): ~/Library/Caches/raea on macOS,
/// %LOCALAPPDATA%\raea\cache on Windows, $XDG_CACHE_HOME/raea or ~/.cache/raea elsewhere.
@@ -75,13 +146,14 @@ pub(crate) fn files_read(expr: &str) -> Vec<u8> {
const MAGIC: &[u8; 8] = b"raeatri1";
/// The mesh kept at `p`: None when there is none or it isn't whole (a write that was cut short).
pub fn read(p: &std::path::Path) -> Option<Tris> {
/// The mesh kept at `p` (touched: used now): None when there is none or it isn't whole (a write that was cut short).
pub fn read(p: &Path) -> Option<Tris> {
let b = std::fs::read(p).ok()?;
let n = u64::from_le_bytes(b.get(8..16)?.try_into().ok()?) as usize;
if &b[..8] != MAGIC || b.len() != 16 + n * 24 {
return None;
}
touch(p);
let f = |at: usize| f32::from_le_bytes(b[at..at + 4].try_into().unwrap());
let run = |from: usize| (0..n).map(|i| [f(from + i * 12), f(from + i * 12 + 4), f(from + i * 12 + 8)]).collect::<Vec<_>>();
Some(Tris { positions: run(16), normals: run(16 + n * 12) })
@@ -89,7 +161,7 @@ pub fn read(p: &std::path::Path) -> Option<Tris> {
/// `t` kept at `p`, written beside it and moved into place so a reader never sees half of it. Failing is fine: the
/// mesh is made again next time.
pub fn write(p: &std::path::Path, t: &Tris) {
pub fn write(p: &Path, t: &Tris) {
if t.positions.len() != t.normals.len() {
return;
}
@@ -102,6 +174,7 @@ pub fn write(p: &std::path::Path, t: &Tris) {
}
}
let Some(dir) = p.parent() else { return };
prune_once(dir);
let part = dir.join(format!(".{}.{}.part", p.file_name().unwrap_or_default().to_string_lossy(), std::process::id()));
if std::fs::create_dir_all(dir).is_ok() && std::fs::write(&part, b).is_ok() && std::fs::rename(&part, p).is_err() {
let _ = std::fs::remove_file(&part);
+37
View File
@@ -270,6 +270,43 @@ mod tests {
std::fs::remove_dir_all(&dir).unwrap();
}
/// The prune with old times: the least recently used go first until the folder is under its budget, and a file used
/// within the last two hours stays even over it
#[test]
fn a_kept_folder_is_pruned_least_recently_used_first() {
let dir = std::env::temp_dir().join(format!("raea-shape-prune-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let now = std::time::SystemTime::now();
let hours = |h: u64| now - std::time::Duration::from_secs(h * 3600);
// 100 bytes each: three days, two days, a day, and one hour since last used
const A: &str = "00000000000000aa-10.tris";
const B: &str = "0123456789abcdef0123456789abcdef.json";
const C: &str = ".00000000000000cc-10.tris.4242.part";
const D: &str = "00000000000000dd-10.tris";
// a file of the person's own, in a folder RAEA_SHAPE_CACHE named: never the cache's to take, however old
const MINE: &str = "render.mp4";
let files = [(A, hours(72)), (B, hours(48)), (C, hours(24)), (D, hours(1)), (MINE, hours(500))];
for (name, t) in files {
std::fs::write(dir.join(name), [0u8; 100]).unwrap();
std::fs::File::options().append(true).open(dir.join(name)).unwrap().set_modified(t).unwrap();
}
let left = || [A, B, C, D].map(|n| dir.join(n).exists());
kept::prune(&dir, 400, now);
assert_eq!(left(), [true; 4], "under the budget (the four the cache wrote): nothing goes");
kept::prune(&dir, 250, now);
assert_eq!(left(), [false, false, true, true], "the two least recently used go");
kept::prune(&dir, 0, now);
assert_eq!(left(), [false, false, false, true], "one used in the last two hours stays, past the budget");
assert!(dir.join(MINE).exists(), "a file the cache didn't write stays");
assert!(!kept::ours("notes.json") && !kept::ours("abc.tris") && kept::ours(B), "only the cache's own names");
// a read is a use: it moves the file's time on
kept::touch(&dir.join(D));
let t = std::fs::metadata(dir.join(D)).unwrap().modified().unwrap();
assert!(t > hours(1), "touched");
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn a_mesh_file_written_again_is_kept_under_a_new_key() {
let dir = std::env::temp_dir().join(format!("raea-shape-files-{}", std::process::id()));
+5
View File
@@ -1,5 +1,10 @@
@spec
Feature: Ask: questions about a piece's picture and sound, answered by the decision model and paid from the person's plan
Superseded by docs/check.feature (CK0) for everything but AK8: `raea ask`, `raea judge`, sdk/raea's `raea/ask` and
apps/judge are gone, and a model's opinion is no check. What stays is what the fingerprint's double-check reads
(`raea fingerprint score --ask`, apps/double): core/ask's questions, io/clef, and apps/ask's runner, record and
calibration. The scenarios below are the record of what was built.
Shane, 2026-11-20: "a decision reviewer type api that calls and utilizes their raea subscription ... for checks and
things, or extending checks to be done quickly based on audio and video, maybe even being able to ask a question
about how does this sound based on the visuals". Planned "so that it sufficiently understands first what is
+60
View File
@@ -0,0 +1,60 @@
Feature: one check (12-04, Shane: "fix how every agent checks its work ... removing ask and judge completely and all
that exists is check as the overarching method")
Round 26's agents met about nine ways to check their work (raea goal check, goal seen, goal judge, raea ask, raea
check's taste, the old frames command, a lines.txt words check, raea cloud's stop critic and run eval, and the render and
publish tools' own copies), two of them broken on the boxes, and 183 findings on 10 cuts of which about 10 were real
faults. Every agent, on raea cloud, in the desktop app or with the raea skill, now has one: `raea check`.
Rule: every rule lives in one of three places, or nowhere (12-04, Shane)
Built in: a component or an SDK default that can't produce the fault (captions from the words file, in the safe area;
a Region that keeps text off faces and the app's buttons; raea cut, which cuts only in pauses). Its check is a
backstop that shouldn't fire.
A check, hard or soft: hard is an error (a fault in the deliverable), soft a warning (a note for the person, never a
reason to render again).
Context the agent retrieves while it makes the work: craft and taste (how captions read, pacing, a hook, a brand's
fingerprint, the person's past notes) live in the skill, the guides and memory. Nothing grades the work against them.
A rule that fits none of these isn't a rule: no ritual (the agent saying it looked: `seen`) and no model's opinion
of the work (taste, a critic, a judge, an ask).
Scenario: CK0 one verb
Given any project
When an agent or a person runs `raea check [FILE...] [--at edit|render|publish|done]`
Then it runs every rule the project's goal holds at that moment, and nothing else checks the work
And `raea goal check` still runs as `raea check`, for boxes and tools on an older raea
And `raea ask`, `raea goal judge`, `raea judge` and `raea goal seen` are gone: raea says so, and names `raea check`
Scenario: CK1 run once, after the render
Given a render that wrote OUT.mp4 (on this machine, or on raea cloud's farm and checked by the box that sent it)
When it ends
Then `raea check OUT.mp4 --at render` runs once and keeps OUT.check.json beside it
And publish and done read OUT.check.json while it's no older than OUT.mp4 or its manifest, and never run its rules again
Scenario: CK2 only real faults, one line a rule
Given a cut
Then it is held to: a word clipped or missing (words, sound), a face cut by the frame edge (frames), text over a face,
a sign or the app's buttons (place, floor), captions over talking (captions), the brief's must-say, never-say and
CTA (say, never, cta), its size, length and name (shape, sizes, naming), the brief's count and open items, and what
the render itself found (render)
And a 3D scene, kit or shot is held to its deliverables and what its render found: clipping, a part out of place or
under its detail, light that jumps
And each rule says at most one line a file: its first finding and how many more like it
Scenario: CK3 our own text from the manifest
Given a render manifest beside a video
Then captions, placement and size read the texts raea drew from it, never by reading the frames
And text in the source footage (a sign, a phone's screen) is never counted as the edit's
Scenario: CK4 no critic, no ritual in the loop
Then no check asks a model to judge the work, and no check waits for the agent to say it looked
And a check that can't run on a machine (Mac, Linux, Windows, a raea cloud box) is removed, not left waiting
Scenario: CK5 a brief that can't break the check
Given brief.ts with `goal: [steps, cut({...})]`, `goal: steps` or `goal: cut({...})`
Then `raea check` reads every goal in it, and never crashes on what an agent wrote
And a cut's beats are the agent's plan, never a rule it is checked against
Scenario: CK6 one set of instructions
Then raea's skill, its guides, `raea help`, the AGENTS.md raea writes, raea cloud's method, workflows and skills, and
the desktop app all name `raea check` as the one way to check, and none names ask, judge, seen, frames check or a
lines.txt words check
+26 -2
View File
@@ -52,8 +52,8 @@ Feature: raea cloud: a synced folder is pictured, understood, embedded and organ
9x16 or 16x9; its length), and for each tag who said it and why
Scenario: IG6. raea's model reads first; the workspace's agent when there's none
(built 11-24 with raea's model as a vision model on OpenRouter, tagger.ts: description, role, client, tags with
why, on the item and its turbopuffer rows; raea ask's clef model takes its place when it's deployed)
Given the workspace's plan has raea's ask model (raea ask, docs/ask.feature: clef-omni on the plan's pool)
why, on the item and its turbopuffer rows; the clef model (io/clef) takes its place when it's deployed)
Given the workspace's plan has raea's ask model (io/clef, docs/ask.feature: clef-omni on the plan's pool)
Then the files are read by it, batched, the spend on the pool
Otherwise they are read by the workspace's own connected agent on raea cloud's box (Claude Code on its Claude, or
Antigravity on its Google AI plan), as a background job that never takes a project's turn
@@ -99,3 +99,27 @@ Feature: raea cloud: a synced folder is pictured, understood, embedded and organ
When StreetTalk's four Drive syncs run from empty
Then every file has a picture, a description and tags; the three client folders are related to their client
libraries; a search for a shot finds it by what's in it; and the run says its time and what it cost
Rule: every video has a light copy to watch and cut from
Scenario: IG14. A video's proxy is made once, from the download its index already makes
(built 12-02: raea-platform index-run.ts submitProxy/proxyDue, sdk/cloud/deploy/modal/proxy.py)
Given a video in a library, uploaded or synced from Drive
Then raea makes a 540p proxy of it on Modal (540 lines on the short side and never more than the original,
H.264 CRF 28 with a keyframe every second, AAC 96 kbps, faststart) from the same address its index job
fetches, so a synced file is downloaded through its tool once for both
And the proxy is kept in R2 by the original's SHA-256, written through a ticket for the workspace's proxies
alone (the job holds no raea credential), so footage kept twice is made once
And an original already that light (H.264 in MP4, 540 lines or fewer, under 2.5 Mbps) is its own proxy
And a library indexed before proxies gets them a few at a time, 8 running a workspace
Scenario: IG15. People watch the proxy
When a person opens a video in the library
Then it plays from its proxy: no copy of a Drive original through its tool, and no 4K HEVC in the browser
And its original stays one click away (Open)
Scenario: IG16. Agents look and cut from proxies, and finish from originals
When an agent searches its libraries for footage
Then it finds videos by what's in them (what's seen, heard and said, with the seconds where) and by name
And each video comes with its proxy, whose times are the original's, to fetch, watch, transcribe and rough-cut
And the original (an upload's link, or a synced file through library_original) is fetched only for the master
And drafts on the farm read clip copies at the size they're drawn (CR36); masters read the originals
+51 -1
View File
@@ -91,7 +91,8 @@ Feature: raea cloud: raea and an ACP agent on a server of your own (sdk/cloud)
Scenario: CL14. A render job, and a GPU that sleeps when idle
Then POST /v1/jobs?args=JSON takes a project as a tar (zstd, gzip or none) and runs `raea ARGS` on it in a folder
of its own; GET /v1/jobs/ID?from=N follows its output in requests of 20 s at most (a serverless platform's
proxy cuts longer ones); GET /v1/jobs/ID/out returns the files it made or changed, and the job is dropped
proxy cuts longer ones); GET /v1/jobs/ID/out returns the files it made or changed, as often as asked, and
DELETE /v1/jobs/ID drops the job once they have arrived (one nobody drops goes an hour after it ends)
And deploy/modal/raea_cloud.py runs the image on a Modal GPU (an L4, else an A10G, else a T4, unless
RAEA_CLOUD_GPU names others or none), one container that starts on a request and stops after five idle
minutes, the token in a Modal secret
@@ -101,8 +102,23 @@ Feature: raea cloud: raea and an ACP agent on a server of your own (sdk/cloud)
job and lands what it made back in the project; its paths are made relative to the project, an output outside
it is moved to its place after, and an input outside it renders on the box with a line saying why
And a worker that can't be reached fails the render unless RAEA_CLOUD_GPU_FALLBACK=cpu
And a worker on another raea version than the box's fails the render before anything is sent, naming both,
unless RAEA_CLOUD_GPU_ANY_VERSION=1
And every other raea command runs on the box
Scenario: CL16. raea cloud's boxes are Fly Machines
Given the boxes were Sprites, which ran at most 10 at once, read their disk in about 26 ms a
read and stopped at 8 cores and 16 GB (12-03)
Then each box is a Fly app of its own (raea-box-N for the box raea-N) with one Machine of deploy/fly/Dockerfile,
8 dedicated cores and 16 GB, and a volume for its home folder: the agents' sign-ins, ~/.raea-cloud.env, ~/work
And its work folder is /home/sprite/work as on a Sprite (the image links /home/sprite to /home/raea), so a moved
project's folders and paths are the same
And the server exits when the box has been idle RAEA_CLOUD_IDLE_STOP_MIN minutes (no request, connection,
process working in ~/work, or hold file touched lately: server/idle.ts), the Machine stays stopped, and Fly's
proxy starts it again at the next request
And deploy/fly/box.sh makes a box (up), lists raea cloud's boxes (list) and puts every box on a release (latest)
And a file PUT to a box streams to disk and lands whole, never held in memory
Rule: it is proven end to end
Scenario: CL12. A stand-in agent, then a real one
Then test/smoke.sh builds the image, starts it, and checks CL4-CL7, CL14 and CL15 with test/echo-agent.mjs (a
@@ -110,3 +126,37 @@ Feature: raea cloud: raea and an ACP agent on a server of your own (sdk/cloud)
back, a second container handing its render to the first, an ACP turn round-tripped
And with Kimi Code signed in, one real turn renders a title card with raea in the container, and the file
comes back through /v1/files
Rule: a box edits on light copies, the farm renders from originals (12-05)
Scenario: CL17. Nothing on the box takes a light copy's place
Given raea cloud brought a run's footage as 540p light copies (footage/NAME.mp4, listed in .raea-cloud/light.txt)
Then every look the agent takes (a still, a frame, a probe, a check of its words) reads the light copy
And no file ever replaces footage/NAME.mp4 on the box, before a render or after one
Scenario: CL18. A farm render reads each light copy as its original, fetched by the farm
Given .raea-cloud/originals.json names a light copy's original: its hash, size and a link that hasn't ended
When a render that reads the light copy goes to the farm (server/offload.ts)
Then its media manifest names the original under the light copy's path, with its link, and the light copy's own
bytes go nowhere
And the farm fetches the original from the library into its cache, checks it against its hash, and keeps it for
every later render; the box never downloads it, hashes it or sends it
And a light copy the render doesn't read is left out, its original included
And a size raea cloud doesn't know goes as 0, which the farm takes with a link and never without one
Scenario: CL19. An original with no link goes from the box
Given a light copy whose original has no hash, or whose link ends within 5 minutes
When its original is in footage/originals/ under the light copy's name (any extension)
Then the render sends that file by its own hash, under the light copy's path
And only a farm with its media cache gets an original by its file (by LFS or in the tar it would go as the light
copy), and only that farm an original of unknown size: for any other the take is rendered as its light copy
And .raea-cloud/proxies/ never goes in a render's tar, and an original no source names stays on the box
Scenario: CL20. A render that read a light copy says so
Given a light copy with no original either way
Then the render prints NO ORIGINAL with its name, and is rendered from the light copy
And its manifest records {"originals": {"read": [...], "light": [...]}} (a still's in OUT.render.json beside it),
checked or not, from which raea cloud marks it a draft that is never shown or published
And the farm's media list holds each original by its link in its light copy's place, with everything else that
went (12-05 review: the farm-cache path dropped the links while the manifest said they were read)
And an original of unknown size over 40 GB is refused as it downloads, before it fills the farm's volume
And test/originals.ts and test/farm_media.py check CL17-CL20
+10 -11
View File
@@ -68,7 +68,7 @@ Feature: Direction that holds: one world of facts, findings and rules, so a pers
| an edit as rows and keyed columns | core/program (ir, eval, timeline) | the renderer's own; nothing queries it for checks |
| what each frame shows, as laid out | `raea render --manifest` (runtime/export/src/lib.rs write_manifest): each text's words and box, each video's source and time, the 3D's clipping, the sounds heard, the layers | written only when asked for; read by `raea check` alone; its clipping list is a second copy of what was printed |
| parts that clip, float, sink | systems/contact (every render), `raea scene lint` | findings are printed text or loose JSON `{check, level, says}` |
| an export's floor | apps/check (`raea check`: text, picture, flash, sound; `--quick`; `--taste`) | its own `Issue {rule, p, at, says}`; exports only |
| an export's floor | apps/check (`raea check`: text, picture, flash, sound; `--taste`) | its own `Issue {rule, p, at, says}`; exports only |
# `raea check` reads a video through FFmpeg where it's installed and through raea's own decoders where it isn't
# (apps/check/read; RAEA_CHECK_NATIVE=1 forces them): the same findings either way, held there by tests/parity.rs.
# 0.1.7 refused any video without FFmpeg, though `raea media probe` and `loudness` never needed it.
@@ -192,7 +192,7 @@ Feature: Direction that holds: one world of facts, findings and rules, so a pers
Then the frame is one world: its 3D items, timeline, clips and cues read as `raea scene lint` reads a 3D frame
today (React stepped, no engine, no GPU)
And the page's text and boxes come from the page's layout, which before this only a render did (the manifest's
"as laid out", which `raea check --quick` gets by rendering three stills): this scenario adds a layout-only
"as laid out"): this scenario adds a layout-only
pass (the render's own page synced and laid out by the main world's schedules, the render world's never run,
so nothing is drawn); with `--no-layout`, or where the page can't be made, its text carries `needs: "render"`
And its entities carry these components, each field measured, none typed by the author:
@@ -273,13 +273,13 @@ Feature: Direction that holds: one world of facts, findings and rules, so a pers
Scenario: DR3. One finding, for every command
# Status 11-10: built. One Finding (core/facts finding.rs: its check; error, warn or note; the entities it is
# about; frames; says; measure; fix; by) is all these write: the render's clipping (systems/contact found.rs) and
# exposure (light-meter), `raea scene lint|light`, `raea check` (--quick, --taste), `raea gen check`, `raea make solid
# info --expect`, `raea project scan`, raea/room's checkLayout and checkDecor, `raea judge`. Every render (a video,
# exposure (light-meter), `raea scene lint|light`, `raea check` (--taste), `raea gen check`, `raea make solid
# info --expect`, `raea project scan`, raea/room's checkLayout and checkDecor. Every render (a video,
# --at stills, a still, --review, a .wav) says them, writes them into its manifest and counts them on its last
# line; an error exits 1 unless `--despite CHECK WHY` (RAEA_DESPITE for harnesses that compare pixels). Each run of
# a file in a project keeps one entry in .raea/record/: what, what it wrote and its kind, the commit (+ when the
# file had changed), the findings, what was let through. A render that is part of another (a review's tiles, a
# quick check's stills, solid view's scene) keeps none. `raea findings` sets each thing's latest run against the
# file had changed), the findings, what was let through. A render that is part of another (a review's tiles,
# solid view's scene) keeps none. `raea findings` sets each thing's latest run against the
# one before of its kind and lists new, carried (since which run), renamed, fixed and let through; `raea goal next`
# steps by it: fix what the last render found, render the video, again once the composition changed, check it,
# polish what the check found, show it.
@@ -300,8 +300,7 @@ Feature: Direction that holds: one world of facts, findings and rules, so a pers
# frame; gen check's fitted fixes were JSON; a review kept 13 entries (one a tile) and was set against videos; a
# video copied from the export cache said nothing it had found; a review's right, top and iso cameras kept the
# scene camera's Transform rotation, so they faced its way and those tiles were empty.
# Not seen, or left: `raea judge` wasn't run on a real clip (a model call costs; its Findings are tested on
# fixtures). A part scaled to nothing or deleted reads as fixed (DR16's relations know what a part rests on);
# Not seen, or left: a part scaled to nothing or deleted reads as fixed (DR16's relations know what a part rests on);
# renamed and moved at once reads as fixed and new, though the error still stands in the count. The clipping
# check passes an overlap under 4% of the smaller part's diagonal (DEPTH_SHARE), so the render's own move left the
# crate 5.3 cm in the pillar, which the top view shows. The review's top tile has +x to the left.
@@ -319,8 +318,8 @@ Feature: Direction that holds: one world of facts, findings and rules, so a pers
# for Finding, holds it instead, and the registry's `up` (the nearest .raea/project) moved there with it.
| raea-app-direction | apps/direction/src/findings.rs | 160 | `raea findings` |
Then these write Findings and nothing else: the render's clipping check, `raea scene lint|light`, `raea check`
(and --quick, --taste), `raea gen check`, `raea make solid info --expect`, `raea project scan`, raea/room's
checkLayout and checkDecor, `raea judge`
(and --taste), `raea gen check`, `raea make solid info --expect`, `raea project scan`, raea/room's
checkLayout and checkDecor
And each finding names the entities it is about (the two parts that clip, the text that is cut off), so
"everything found about this part" is a query
And every render, video or `--at` stills, writes its findings into its manifest and prints their count last,
@@ -904,4 +903,4 @@ Feature: Direction that holds: one world of facts, findings and rules, so a pers
Scenario: DR27. Not in this plan
Then no film is repaired here: the abandoned one stays as it is
And no new kind of renderer, no new asset store, and no model or generation service is added
And judging taste by a model is as it is (`raea judge`); here taste is the person's signature on a clip
And no model judges taste (docs/check.feature); here taste is the person's signature on a clip
+11
View File
@@ -353,3 +353,14 @@ notes and is worth shipping without it: a person gets word scores, checks and bo
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.
6. **Pro and Studio include checks and content intelligence** (Shane, 11-20). Each month's pool (about 8,000 frames
checked on Pro, ten times that on Studio) stops when it's spent and is never billed past. It pays for two things:
- **clef-omni answering the fingerprint's questions** about a render's frames (`POST /v1/clef/ask`), so the agent
reads answers in words and opens only the frames they flag. Its verdicts are another eye's (FP6d), and it serves
the axes with no labels yet.
- **content intelligence for references** (`GET /v1/intel/...`): public posts, videos, transcripts and ads, to find
a videoform's references by what performs and keep them current (docs/videoform.md). A source's views and
engagement are another eye's evidence too, never the person's taste. A reference found this way is still read
once, as VF1 reads any link, and VF1's rights confirmation still applies.
Without a pool, everything here still works locally, and clef runs on the person's own Cloudflare account.
+4
View File
@@ -20,6 +20,10 @@ Feature: raea/foliage, plants grown from their species and drawn through the yea
Leaves and bark are made in code (a leaf's outline, teeth, veins and blotches from its shape's rules; bark's
fissures from noise in the shader), never photographed, so a species is a table of numbers and a seed.
The crate that grew them, raea-sys-foliage (systems/foliage), was removed while nothing called it: no verb, native
call or SDK module reached it. It comes back with FO10's caller, from the commit before its removal
(`git checkout 02051ee9 -- systems/foliage`, then its workspace member and its two tools/layers.toml entries).
Rule: 1. Plants
Scenario: FO1. A tree grown from its species
+41 -49
View File
@@ -218,7 +218,7 @@ Feature: Goal: the loop every piece of work runs, one goal or a workflow of them
And a part's plan is its own `lod` (Mesh3d, Model, and every part inside an Entity with a transform or a Group
that has one), else the `lod` of the plan's object of its name
When a frame shows a planned part at a finer level than its plan (raea-runtime-lod-plan)
Then the render's end checks, `raea scene stage` and `raea check --quick` say `lod-closer`: the part, its plan,
Then the render's end checks and `raea scene stage` say `lod-closer`: the part, its plan,
the level it is seen at, how much of the frame it spans at its largest and on which frame, how many frames it
is closer on, and the fix (build it for that level and plan it there, or keep the camera off it)
And one level finer is a warning, two or more an error, which fails the render as any error does
@@ -318,7 +318,7 @@ Feature: Goal: the loop every piece of work runs, one goal or a workflow of them
Given a goal job
Then `raea goal check` runs every `run` rule at every status, the Stop hook's included, and holds the job on one
that fails or outlives its timeout, with its exit code and last line ("run")
And a `says` rule is clear only when review/judge/NAME.json, written by `raea goal judge [DIR] [--by claude|kimi]`
And a `says` rule is clear only when review/judge/NAME.json, written by `raea goal judge [DIR] [--by claude|kimi|clef]`
(a fresh session that may only read: Read, Grep and Glob), found it true at a time no earlier than the work's
newest file, the job's own review/, .raea/, NOTES.md, .git and node_modules left out, compared at whole seconds
("says")
@@ -431,8 +431,8 @@ Feature: Goal: the loop every piece of work runs, one goal or a workflow of them
When it saves a composition, brief.ts or a check
Then the hook runs `raea goal check FILE --at edit` on a saved composition, or on any file under a brief with a
`make` job, and hands back what it found when it fails
And the quick check is the stills pack (`at: ["edit"]`), which reads apps/check's three-stills measure; the hook
has no path of its own to it
# Removed with the stills pack (docs/check.feature CK1): nothing is checked after a save; a render checks its
# own output at its end
@needs:MK32
Scenario: MK34. Render: every render ends with the render moment
@@ -456,6 +456,10 @@ Feature: Goal: the loop every piece of work runs, one goal or a workflow of them
And the seen pack holds it until its contact sheet has been shown since its last render (FILE.seen.json: the
render's time and size, what the agent said it sees and would change, at least 80 characters), and the
surprise pack, when on, until it names its moment in seconds and what it is
And it holds a video until its design is judged too, on its frames at full size (FILE.looks/, six through the
cut, made by `raea goal seen FILE`): `--look "..."`, at least 80 characters on its type, captions, cards and
end beside a reference and what was changed, since a sheet's tiles show what happens and never how it looks
(12-01, Shane on Dutch: "why do components not look good. is it even proofing or reviewing the work?")
And on a Mac the same packs hold through `raea goal seen FILE` (the sheet, shown in the raea app with
`raea show`) and `raea goal seen FILE "WHAT I SEE AND WOULD CHANGE"`, which write FILE.seen.json; raea cloud's
publish tool writes it through the same command
@@ -520,8 +524,8 @@ Feature: Goal: the loop every piece of work runs, one goal or a workflow of them
check`, `raea sound check`, `raea frames place`, `--plan`, plan.org, the hook's quick path, runtime/cut-plan and
runtime/goal-plan, sdk/cloud/server's check code, raea cloud's make-checks logic, publish gate, naming and count
checks, and the method paragraphs (RAEA, SOUND, CRAFT, NAMING, SIZES)
And `raea check` stays a top-level instrument (MK45): its VIDEO and --quick measures are what the floor and stills
packs read, and its taste lines are held by the taste pack (MK47); it never decides done
And `raea check` stays a top-level instrument (MK45): its VIDEO measures are what the floor pack reads (--quick and
--taste are gone, MK47); it never decides done
And every project's first message carries one paragraph on the loop: write the contract, work, run
`raea goal check`, fix what it names, until it says done
And `rg` over raea, raea-platform, raea-skills and raea-feed finds none of the gone names outside this file and
@@ -576,9 +580,8 @@ Feature: Goal: the loop every piece of work runs, one goal or a workflow of them
or shot goal's steps (`make blockout|refs|gen|pick-sheet|pick|prep|kit|framing|lenschart|place`)
And the instruments stay top-level, shared by every goal: `check`, `world`, `ask`, `judge`, `findings`, `scene`,
`media`, `words`, `song`, `track`; they measure and never decide done
And an old name is refused with where it went (`raea make check` is now `raea goal check`; `raea clothes` is now
`raea make clothes`; `raea make plan` is now `raea make blockout`; `raea next` is now `raea goal next`; `raea
part` is gone), never run under it
And an old name is refused with where it went (`raea make check` is gone, `raea check` is the one check; `raea
clothes` is now `raea make clothes`), never run under it; a name older than the release before is no verb at all
And docs/make.feature is this file, and the help, the manual, the guides and the skill teach only the new names
@needs:MK31
@@ -597,13 +600,12 @@ Feature: Goal: the loop every piece of work runs, one goal or a workflow of them
And core/brief's doctor says a name given twice and an `after` naming no goal
And core/brief tests and sdk/goal/test/contract.test.ts hold it
@needs:MK43 @needs:MK45
Scenario: MK47. Every rule a project registers runs inside the loop
Given taste lines (the person's, the workspace's, the project's) with checks, and a person's signed asks (raea notes)
Then the taste pack runs them through `raea check`'s rules at the moments they name, and their findings are the
goal check's, so no registered rule runs only when an agent remembers an instrument
And the story SDK's checks (raea/story `storyCheck`) are taste-line checks or a goal's `checks`, never a file of
their own that nothing runs
@done
Scenario: MK47. No rule a project registers runs inside an agent's loop
Given taste lines (the person's, the workspace's, the project's) and a person's signed asks
Then none runs inside an agent's loop: the taste pack is gone and `raea check --taste` is refused (engine/cli/goal
gone()), so the one check (check.feature) is the only check an agent's work meets
And the story SDK's checks are a goal's `checks`, never a file of their own
Rule: The cut, read as an editor reads it (Shane, 11-29: Kuleshov, Eisenstein's methods of montage, Murch's Rule of Six)
@@ -612,40 +614,30 @@ Feature: Goal: the loop every piece of work runs, one goal or a workflow of them
# in fMRI), Eisenstein's collision of shots, Murch's six reasons for a cut weighed emotion 51%, story 23%, rhythm
# 10%, eye trace 7%, the screen's plane 5%, its 3D space 4%, given up from the bottom. Murch's weights are his
# judgment, not measurements: raea uses them as an order, never as a score. The story SDK says what a piece is
# about; these say what each cut does to it. Status 11-29: built in raea #269 (sdk/goal packs/montage.ts,
# test/montage.test.ts; core/brief cut.rs Beat).
# about; these say what each cut does to it. Status 11-29: built in raea #269. 12-06: the montage pack and the beat
# critic are out (check.feature: one check, nothing grades an agent's plan); the craft stays in the guide.
Scenario: MK48. A cut plan's beats say what each part must make the viewer feel and understand, before it's cut
Given a cut goal's plan (`cut({ cuts: [{ id, beats: [...] }] })`)
Then each beat has `at` (seconds from the cut's start, the first at 0, in order) and `feel` in the person's words,
and may say `story` (what the viewer understands by its end), `asl` (its average shot length in seconds) and
`tempo` ("build": shots shorter as it goes, "release": longer, "hold": even)
And core/brief's doctor says a beat out of order, one with no feel, a tempo that isn't one of the three and an asl
that isn't above 0
And Dutch's cuts fail today: none says what any of its parts should make anyone feel
@done
Scenario: MK48. A cut's beats are the agent's plan, in its notes, never brief.ts
Given an agent planning a cut beat by beat (what each part makes the viewer feel and understand, and its pace)
Then the plan is in its notes, never in brief.ts, which holds only what the brief asks (check.feature), and the
guides say so (craft/story/montage.md, craft/motion/brief.md)
And a brief.ts that still has `beats` is read as before (core/brief keeps the field) and nothing grades them
Scenario: MK49. Emotion and story are judged on the cut in sequence, by a fresh critic
Given a cut goal whose plans have beats
Then each beat is a `says` rule (`beat_<cut>_<n>`, contract.ts saysOf): "in out/cuts/<cut>_<W>x<H>.mp4, from A s
to B s, watched in sequence as cut, the viewer feels <feel>, and by its end understands <story>", judged by
`raea goal judge` with the goal's own `says` rules and held by the says pack at done
And it's asked of the shots as cut, never one by one: what a shot means comes from its neighbours (Kuleshov)
And no measure stands in for them: they're Murch's top two, 74% of his weight
@done
Scenario: MK49. No critic judges a cut's emotion or story
Given a cut
Then no model is asked whether it makes the viewer feel its beats: `raea goal judge` is gone (engine/cli/goal
gone()), and emotion and story stay the editor's, from the guide, never a score
Scenario: MK50. Each beat's pace is its plan (Eisenstein's metric montage)
Given a delivered cut whose plan's beats say `asl` or `tempo`
Then the montage pack finds its hard cuts in its own frames (one ffmpeg pass, 48 pixels wide) and, for each beat,
its shots must average within a third of its asl, and a build's shot lengths must shorten (Kendall's tau under
-0.2), a release's lengthen (over 0.2), with three shots or more; each miss is an error naming the beat's feel,
the lengths it has and which way to go
And sdk/goal/test/montage.test.ts holds it
@done
Scenario: MK50. No pack measures a cut against the agent's own plan
Given a brief.ts that names the montage pack (`packs: { montage: true }`)
Then the pack is skipped and the check's doctor says it's gone and why (sdk/goal run.ts GONE_PACKS), never a crash
And sdk/goal/test/contract.test.ts holds it
Scenario: MK51. Eye trace, screen direction and tone across every cut, in Murch's order
Given any delivered cut (`packs: { montage: false }` switches it off)
Then at each cut: the focal point on the two sides (the largest face the scene reader finds, else where the
frame's contrast gathers) more than 0.4 of the frame's diagonal apart is an eye-trace warning; sideways motion
on both sides (over 0.15 widths a second) in opposite directions is a screen-direction warning; a jump in
brightness over 0.25 or warmth over 0.08 where no beat starts is a tonal warning
And each finding names its Murch weight, so a fix never gives up a higher reason for a lower one
And one of them broken at more than half a file's cuts is an error: a habit of the cut, not a choice
And a cut on a word stays the sound pack's (edit-on-sound), so no rule is held twice
@done
Scenario: MK51. Eye trace, screen direction and tone are the editor's, in Murch's order
Given any cut
Then the guide gives Murch's order for what to give up first (craft/story/montage.md), and no check measures eye
trace, screen direction or tone; a cut on a word stays the one check's (sound)
+2 -3
View File
@@ -19,7 +19,7 @@ Feature: One project layout: compositions, components, assets, artifacts; and th
Built 11-12 (lane layout): LY1 (raea project new and workspace init make the folders, .gitattributes, AGENTS.md
and the @shared/ tsconfig), LY2 (the loader resolves @shared/, PJ8's lint takes it), LY3's scan and lint and
controllers over shared/controllers/, and LY4's `raea make component` (`raea part` still answers). Still to do: LY3's
controllers over shared/controllers/, and LY4's `raea make component`. Still to do: LY3's
app pages (Compositions, Controllers, Source), LY4's examples/components rename and the guides and skill wording,
LY5 (`raea project tidy`), LY6.
@@ -77,7 +77,6 @@ Feature: One project layout: compositions, components, assets, artifacts; and th
When `raea make component list` or `raea make component add reel [--shared]` runs
Then it lists and copies raea's sets as `raea part` did, into components/<set>/ (or shared/components/<set>/)
And examples/parts is examples/components, and registry.gen.ts is packed from it
And `raea part ...` still works for this release, saying once that it's `raea make component` now
And the guides, the raea skill and AGENTS.md say components, never parts
Scenario: LY5. An existing project moves into the layout with one command
@@ -90,7 +89,7 @@ Feature: One project layout: compositions, components, assets, artifacts; and th
project's feed items, render manifests and checks name
And --dry-run prints the moves and rewrites and changes nothing
And it proves the move before it commits: the scan has no new lint, tsc passes if it passed before, and each
composition's first frame renders as it did (raea check --quick); a failure undoes the move
composition's first frame renders as it did (raea render --at 0); a failure undoes the move
And it is one commit per project, moves as renames (git mv), so history follows each file
And the workspace's root artifacts/ move to shared/ the same way (`raea workspace tidy`)
Loaded 100 of 460 files, more files were not shown because too many files have changed in this diff. Show more