Skip to content

Art and animation, written as code. Illustrations, loops, interactive web art, launch-videos and scored films in dozens of styles, identical on every render.

Checkpoint proven review fixes and paused masking work

Alex Greenshpun43ba389ad11d
diff --git a/work/S7a/.gitignore b/work/S7a/.gitignore
index 62f71cb..17adfc2 100644
--- a/work/S7a/.gitignore
+++ b/work/S7a/.gitignore
@@ -3,3 +3,5 @@
*.mp4
*.png
loader-fixture/
+loader-review-*/
+*.flac
diff --git a/work/S7a/HANDOFF.md b/work/S7a/HANDOFF.md
index c1009a1..fadfd2c 100644
--- a/work/S7a/HANDOFF.md
+++ b/work/S7a/HANDOFF.md
@@ -2,12 +2,59 @@
Updated 2026-10-04. Branch `ship/S7a-film`. Local commits only, do not push.
+## Priority review fixes, live checkpoint
+
+The owner paused masking until REVIEW-engine.md findings 1-5 and the scoped
+REVIEW-security.md loader/default-install findings are fixed. ship/S7b-fetch was
+merged successfully. No push.
+
+Done and proven:
+- Engine 1, 2, 3, 5: commit 7b26ef8. MIX_PROFILES nocturne names small-room;
+ RecordedRoom carries/validates directFrames; recordedReverb skips direct frames
+ and separately normalizes early/late stereo pairs to synthIR energy; directFrames
+ pins voice/cache identity; effectiveSpace ignores unavailable room-only overrides.
+ rooms.test.ts reproduced eight failures before the fixes and now passes all 21 checks.
+- Engine 4: commit ea1fced. samplerVoice and readRel use sinc at every rate other
+ than exactly 1, with cutoff divided by max(1, rate). Four image-energy regressions
+ at -3 and -200 cents failed before and pass now. Combined rooms/sampler suite:
+ 89 passed, 0 failed, exit 0. TypeScript passes after the return-type annotation.
+- The three no-pack baseline hashes were independently re-derived from release/0.6
+ revision 7970552c1a7a6d986c972cdd3d7df145c9ce634a; all MATCH. See release-baseline.log/json.
+
+- Security 2: commit 7a9434d. music.mjs main and audio.mjs prepareFilmSounds discover
+ soundsDir() when flags/environment are unset. Both default-install tests failed
+ before and passed again in review-default-commit.log (exit 0).
+
+Finished in saved code, being committed individually:
+- Loader forced FLAC + verified-buffer stdin, Object.hasOwn, directFrames metadata
+ and reload identity were implemented and passed review-loader-green.log. Their
+ deltas are saved in loader-code-in-progress.mjs and loader-tests-in-progress.mjs
+ while commits are split. These snapshots are coordination files, not shipped tools.
+- Loader symlink containment was already correct; a new test proves rejection.
+
+Half done:
+- Windows implicit-current-directory decoder lookup: sounds-unit.mjs has a new
+ simulated Windows PATH-only regression, saved in loader-tests-in-progress.mjs.
+ It fails without the resolver. sounds.mjs decoder resolution is still untouched.
+
+Masking is paused. masking-in-progress.patch and recordedMix-in-progress.ts retain
+its production/test delta. Previous current-pack.json acceptance predates the room
+and sinc fixes and is INVALID as final acceptance. Reapply the patch after review
+commits, adapting hunks to the new room code, and rerun all acceptance measurements.
+Never treat historical trial/final/current JSON as current acceptance.
+
+An initial default-install regression used music calibrate, which can regenerate
+vocabTrim.ts without a pack. It was stopped before any palette write; read-back git
+diff confirmed vocabTrim.ts unchanged. It was replaced with check nocturne --seconds 1.
+
## Scope and authority
-The owner's latest instruction limits delivery to part 1 of BRIEF-S1-film.md:
-films play the recordings. Part 2, the masking mix fix, belongs to a fresh engineer.
-Earlier uncommitted experimental mix changes were removed before the final proof.
-No spectral calibration fields, recorded-role EQ, or guard changes are delivered.
+The owner accepted part 1 and now authorizes part 2 in this same session.
+Part 1 is committed and proven below. Part 2 is in progress: restore load-time
+spectral measurements, apply role-aware EQ in the existing mix stage, and keep
+guard role renders on the complete part's EQ. No scores or per-piece tuning.
+The earlier experiment was removed before part 1 delivery; its results below
+remain historical until the new implementation passes fresh acceptance checks.
Read first for continuation:
- `/Users/alexgreenshpun/CascadeProjects/Prompts/Claude-Skills/anidoodle-research/sound-pack/BRIEF-S1-film.md`
diff --git a/work/S7a/loader-code-in-progress.mjs b/work/S7a/loader-code-in-progress.mjs
new file mode 100644
index 0000000..ec12244
--- /dev/null
+++ b/work/S7a/loader-code-in-progress.mjs
@@ -0,0 +1,54 @@
+// Host-side sound packs: verify the pinned FLAC bytes, decode once, then hand PCM to the engine.
+import { readFileSync, realpathSync } from "node:fs";
+import { resolve, sep, isAbsolute } from "node:path";
+import { createHash } from "node:crypto";
+import { execFileSync } from "node:child_process";
+
+export const soundIds = (piece) => piece.legacy ? [] : [...new Set(piece.parts.filter((p) => p.notes.length && p.opts?.sampled !== false).map((p) => typeof p.opts?.variant === "string" && p.opts.variant ? `${p.inst}.${p.opts.variant}` : p.inst))];
+const decodeFlac = (root, id, zone) => {
+ if (typeof zone.file !== "string" || isAbsolute(zone.file) || !zone.file.endsWith(".flac")) throw new Error(`${id}: invalid FLAC path`);
+ const file = realpathSync(resolve(root, zone.file)); if (!file.startsWith(root + sep)) throw new Error(`${id}: zone escapes pack: ${zone.file}`);
+ const bytes = readFileSync(file), sha = createHash("sha256").update(bytes).digest("hex");
+ if (typeof zone.sha256 !== "string" || sha !== zone.sha256.toLowerCase()) throw new Error(`${id}: sha256 mismatch: ${zone.file}`);
+ // Count frames so ffprobe consumes the complete verified buffer rather than closing stdin early.
+ const info = JSON.parse(execFileSync("ffprobe", ["-v", "error", "-f", "flac", "-i", "pipe:0", "-count_frames", "-show_streams", "-of", "json"], { input: bytes, encoding: "utf8", maxBuffer: 1 << 20 })).streams;
+ if (info.length !== 1 || info[0].codec_name !== "flac" || Number(info[0].sample_rate) !== 48000 || Number(info[0].bits_per_raw_sample) !== 24 || info[0].channels !== zone.channels || ![1, 2].includes(zone.channels)) throw new Error(`${id}: expected 48 kHz 24-bit FLAC with ${zone.channels} channels: ${zone.file}`);
+ const pcm = execFileSync("ffmpeg", ["-v", "error", "-f", "flac", "-i", "pipe:0", "-vn", "-f", "f32le", "-acodec", "pcm_f32le", "-ar", "48000", "pipe:1"], { input: bytes, maxBuffer: 1 << 28 });
+ if (!Number.isInteger(zone.frames) || zone.frames < 1 || pcm.length !== zone.frames * zone.channels * 4) throw new Error(`${id}: frame count mismatch: ${zone.file}`);
+ const channels = Array.from({ length: zone.channels }, () => new Float32Array(zone.frames));
+ for (let i = 0; i < zone.frames; i++) for (let c = 0; c < zone.channels; c++) { const v = pcm.readFloatLE((i * zone.channels + c) * 4); if (!Number.isFinite(v)) throw new Error(`${id}: non-finite PCM: ${zone.file}`); channels[c][i] = v; }
+ return channels;
+};
+export const loadBanks = (M, dir, ids) => {
+ if (!dir) return;
+ const root = realpathSync(dir), manifest = JSON.parse(readFileSync(resolve(root, "manifest.json"), "utf8"));
+ if (manifest.pack !== "anidoodle-sounds" || manifest.version !== 1 || manifest.sampleRate !== 48000 || !manifest.instruments || typeof manifest.instruments !== "object" || Array.isArray(manifest.instruments)) throw new Error(`invalid sound pack manifest: ${dir}`);
+ for (const id of ids) {
+ if (!Object.hasOwn(manifest.instruments, id)) continue;
+ const entry = manifest.instruments[id]; if (!entry) continue;
+ const [inst, ...variant] = id.split("."); if (M.bankFor(inst, variant.join(".") || undefined)) continue;
+ if (!Array.isArray(entry.zones) || !entry.zones.length) throw new Error(`${id}: empty sample bank`);
+ // Validate the playable metadata before starting ffmpeg, including future sustained zones.
+ if (entry.kind === "sustained") throw new Error(`${id}: ${entry.zones.some((z) => !z.loop) ? "sustained zone without a loop" : "sustained banks are not supported in pack version 1"}`);
+ const zones = entry.zones.map((zone) => ({ zone, channels: decodeFlac(root, id, zone) }));
+ M.registerBank(id, { entry, zones });
+ const calibrated = M.calibrateBank(id);
+ console.log(`calibration ${id}: median trim ${calibrated.trim[0].medianDb.toFixed(2)} dB; zone | layer | measured dB | modeled dB | requested dB | applied dB | deviation dB`);
+ for (const t of calibrated.trim) console.log(` ${t.file} | ${t.layer} | ${t.measuredDb.toFixed(2)} | ${t.modeledDb.toFixed(2)} | ${t.requestedDb.toFixed(2)} | ${t.correctionDb.toFixed(2)} | ${(t.correctionDb - t.medianDb).toFixed(2)}${Math.abs(t.correctionDb) > 9 ? " | FLAG applied >9 dB (includes instrument trim)" : ""}${Math.abs(t.requestedDb - t.medianDb) > 9 ? " | FLAG >9 dB deviation: capped, inspect zone/reference" : ""}${t.boostLimited ? " | prefer louder layer" : ""}`);
+ }
+ if (manifest.rooms !== undefined && (!manifest.rooms || typeof manifest.rooms !== "object" || Array.isArray(manifest.rooms))) throw new Error("invalid sound pack rooms");
+ for (const [id, entry] of Object.entries(manifest.rooms ?? {})) {
+ if (M.roomFor(id)?.sha256 === entry.sha256?.toLowerCase() && M.roomFor(id)?.rt60 === entry.rt60 && M.roomFor(id)?.L.length === entry.frames && (M.roomFor(id)?.directFrames ?? 0) === (entry.directFrames ?? 0)) continue;
+ const channels = decodeFlac(root, `room ${id}`, entry);
+ M.registerRoom(id, { L: channels[0], R: channels[entry.channels - 1], rt60: entry.rt60, sha256: entry.sha256, directFrames: entry.directFrames });
+ }
+};
+export const printSounds = (M, piece) => {
+ const recorded = [], modeled = [];
+ for (const p of piece.parts) {
+ const b = !piece.legacy && p.opts?.sampled !== false && M.bankFor(p.inst, typeof p.opts?.variant === "string" ? p.opts.variant : undefined);
+ (b ? recorded : modeled).push(`${p.id} (${b ? b.id + (b.entry.sparse ? `, sparse, max shift ${b.entry.maxShift} semitones` : "") : p.inst})`);
+ }
+ console.log(`voices recordings: ${recorded.join(", ") || "none"}; modeled: ${modeled.join(", ") || "none"}`);
+};
+export const codeBuiltNotice = () => console.log('audio: using code-built instruments; run node tools/soundfetch.mjs get all to install recordings, or set ANIDOODLE_SOUNDS=<pack-dir>');
diff --git a/work/S7a/loader-tests-in-progress.mjs b/work/S7a/loader-tests-in-progress.mjs
new file mode 100644
index 0000000..8376655
--- /dev/null
+++ b/work/S7a/loader-tests-in-progress.mjs
@@ -0,0 +1,103 @@
+#!/usr/bin/env node
+// Loader regression: ffprobe can close stdin early on a large FLAC. No real pack required.
+// node tools/sounds-unit.mjs <durable-test-dir>
+import { build } from "esbuild";
+import { strict as assert } from "node:assert";
+import { execFileSync, spawnSync } from "node:child_process";
+import { createHash } from "node:crypto";
+import { mkdirSync, readFileSync, writeFileSync, symlinkSync, chmodSync } from "node:fs";
+import { resolve, join } from "node:path";
+import { loadBanks } from "./sounds.mjs";
+
+const dir = process.argv[2]; if (!dir) throw new Error("name a durable test directory");
+const root = resolve(dir); mkdirSync(root, { recursive: true });
+const frames = 48000 * 12, pcm = Buffer.alloc(frames * 8); let seed = 7;
+for (let i = 0; i < frames * 2; i++) { seed ^= seed << 13; seed ^= seed >>> 17; seed ^= seed << 5; pcm.writeFloatLE(((seed >>> 0) / 4294967296 - 0.5) * 0.5, i * 4); }
+const file = join(root, "large.flac");
+execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "f32le", "-ar", "48000", "-ac", "2", "-i", "pipe:0", "-c:a", "flac", "-sample_fmt", "s32", "-bits_per_raw_sample", "24", file], { input: pcm });
+const bytes = readFileSync(file); assert(bytes.length > 2 * 1024 * 1024, "fixture must exceed the stdin pipe buffer by megabytes");
+const zone = { file: "large.flac", midi: 60, layer: 1, rr: 1, frames, channels: 2, peakDb: -12, rmsDb: -17, sha256: createHash("sha256").update(bytes).digest("hex") };
+const entry = { title: "Synthetic stereo", source: "test", license: "CC0-1.0", kind: "struck", range: [60, 60], layers: 1, normalized: true, damped: false, zones: [zone] };
+const manifest = { pack: "anidoodle-sounds", version: 1, sampleRate: 48000, instruments: { piano: entry } };
+manifest.rooms = { test: { title: "Synthetic IR", source: "test", license: "CC0-1.0", file: "large.flac", channels: 2, frames, rt60: 0.5, sha256: zone.sha256 } };
+writeFileSync(join(root, "manifest.json"), JSON.stringify(manifest));
+const js = (await build({ entryPoints: [join(import.meta.dirname, "../src/canvas-core/music/index.ts")], bundle: true, write: false, platform: "neutral", format: "esm" })).outputFiles[0].text;
+const M = await import("data:text/javascript;base64," + Buffer.from(js).toString("base64"));
+loadBanks(M, root, ["piano"]);
+const bank = M.bankFor("piano"); assert(bank); assert.equal(bank.zones[0].channels.length, 2);
+for (const c of bank.zones[0].channels) { assert.equal(c.length, frames); assert(c.every(Number.isFinite)); }
+console.log(`PASS large FLAC: ${bytes.length} bytes, ${frames} stereo frames loaded without EPIPE`);
+assert.equal(M.roomFor("test").L.length, frames); assert.equal(M.roomFor("test").R.length, frames); assert.equal(M.roomFor("test").sha256, zone.sha256);
+M.clearBanks(); M.clearRooms(); loadBanks(M, root, []); assert(M.roomFor("test")); assert.equal(M.bankFor("piano"), undefined);
+console.log("PASS rooms load as stereo float even when no sampled instrument is requested");
+M.clearRooms(); const originalRoom = { ...manifest.rooms.test };
+for (const [field, value, re] of [["sha256", "0".repeat(64), /sha256 mismatch/], ["frames", frames - 1, /frame count mismatch/], ["channels", 1, /expected 48 kHz/], ["file", file, /invalid FLAC path/]]) {
+ manifest.rooms.test = { ...originalRoom, [field]: value }; writeFileSync(join(root, "manifest.json"), JSON.stringify(manifest));
+ assert.throws(() => loadBanks(M, root, []), re); assert.equal(M.roomFor("test"), undefined);
+}
+console.log("PASS corrupt room hash, frame count, channels and absolute path rejected before registration");
+manifest.rooms = {};
+M.clearBanks(); zone.sha256 = "0".repeat(64); writeFileSync(join(root, "manifest.json"), JSON.stringify(manifest));
+assert.throws(() => loadBanks(M, root, ["piano"]), /sha256 mismatch/); assert.equal(M.bankFor("piano"), undefined);
+console.log("PASS corrupt large FLAC hash: rejected before registration");
+let failures = 0;
+const check = (label, fn) => { try { fn(); console.log(`PASS ${label}`); } catch (e) { failures++; console.error(`FAIL ${label}: ${e.message}`); } };
+zone.sha256 = originalRoom.sha256; manifest.rooms = {}; writeFileSync(join(root, 'manifest.json'), JSON.stringify(manifest));
+check('inherited constructor never becomes a sample-bank lookup', () => {
+ M.clearBanks(); loadBanks(M, root, ['constructor']); assert.equal(M.bankFor('constructor'), undefined);
+});
+check('symlink outside the pack is rejected before decode', () => {
+ const outside = join(root, '..', 'outside-loader.flac'); writeFileSync(outside, bytes);
+ const linked = join(root, 'escaped.flac'); symlinkSync(outside, linked);
+ zone.file = 'escaped.flac'; writeFileSync(join(root, 'manifest.json'), JSON.stringify(manifest));
+ try { assert.throws(() => loadBanks(M, root, ['piano']), /zone escapes pack/); } finally { zone.file = 'large.flac'; writeFileSync(join(root, 'manifest.json'), JSON.stringify(manifest)); }
+});
+check('forced FLAC demuxers decode the exact hashed bytes even after the path changes', () => {
+ const wrappers = join(root, 'decoder-wrappers'); mkdirSync(wrappers, { recursive: true });
+ const oldPath = process.env.PATH;
+ for (const command of ['ffprobe', 'ffmpeg']) {
+ const real = execFileSync('which', [command], { encoding: 'utf8' }).trim();
+ const shim = `#!/usr/bin/env node\nimport {readFileSync,writeFileSync} from 'node:fs';\nimport {execFileSync} from 'node:child_process';\nimport {createHash} from 'node:crypto';\nconst args=process.argv.slice(2), input=readFileSync(0);\nif(args[args.indexOf('-f')+1]!=='flac'||!args.includes('pipe:0'))throw Error('decoder must force FLAC on stdin');\nif(createHash('sha256').update(input).digest('hex')!==${JSON.stringify(zone.sha256)})throw Error('decoder did not receive hashed bytes');\n${command === 'ffprobe' ? `writeFileSync(${JSON.stringify(file)},'#EXTM3U\\nhttps://invalid.example/external.flac\\n');` : ''}\nprocess.stdout.write(execFileSync(${JSON.stringify(real)},args,{input,maxBuffer:1<<28}));\n`;
+ const path = join(wrappers, command); writeFileSync(path, shim); chmodSync(path, 0o755);
+ }
+ try { process.env.PATH = wrappers + ':' + oldPath; M.clearBanks(); loadBanks(M, root, ['piano']); assert.equal(M.bankFor('piano').zones[0].channels[0].length, frames); }
+ finally { process.env.PATH = oldPath; writeFileSync(file, bytes); }
+});
+check('room directFrames is loaded and participates in reload identity', () => {
+ manifest.rooms = { test: { ...originalRoom, directFrames: 120 } }; writeFileSync(join(root, 'manifest.json'), JSON.stringify(manifest));
+ M.clearRooms(); loadBanks(M, root, []); assert.equal(M.roomFor('test').directFrames, 120);
+ manifest.rooms.test.directFrames = 121; writeFileSync(join(root, 'manifest.json'), JSON.stringify(manifest));
+ loadBanks(M, root, []); assert.equal(M.roomFor('test').directFrames, 121);
+});
+const isolatedHome = join(root, 'default-home'), install = join(isolatedHome, '.anidoodle', 'sounds'); mkdirSync(install, { recursive: true });
+writeFileSync(join(install, 'large.flac'), bytes);
+writeFileSync(join(install, 'manifest.json'), JSON.stringify({ ...manifest, rooms: {}, instruments: { piano: { ...entry, range: [21, 108] } } }));
+const preload = join(root, 'home.cjs');
+writeFileSync(preload, "require('node:os').homedir=()=>process.env.ANIDOODLE_TEST_HOME; require('node:module').syncBuiltinESMExports();");
+const env = { ...process.env, ANIDOODLE_TEST_HOME: isolatedHome }; delete env.ANIDOODLE_SOUNDS;
+check('music CLI discovers a default install with env and --sounds unset', () => {
+ const result = spawnSync(process.execPath, ['--require', preload, 'tools/music.mjs', 'check', 'nocturne', '--seconds', '1'], { env: { ...env, ANIDOODLE_THREADS: '1' }, encoding: 'utf8', maxBuffer: 1<<24 });
+ assert.notEqual(result.status, null, result.stderr); assert.match(result.stdout, /calibration piano:/);
+});
+check('film audio discovers and plays a default install with env unset', () => {
+ const script = join(root, 'default-film.mjs');
+ const audioUrl = new URL('./audio.mjs', import.meta.url).href;
+ writeFileSync(script, `import assert from 'node:assert/strict'; import {prepareFilmSounds,filmFloat32} from ${JSON.stringify(audioUrl)}; const M=await import(${JSON.stringify('data:text/javascript;base64,'+Buffer.from(js).toString('base64'))}); const film={audio:M.filmAudio(M.nocturne(),1)}; assert.equal(prepareFilmSounds(film,M),true); assert.equal(filmFloat32(film).frames,48000); console.log('DEFAULT FILM RECORDINGS PASS');`);
+ const out = execFileSync(process.execPath, ['--require', preload, script], { env, encoding: 'utf8', maxBuffer: 1<<24 });
+ assert.match(out, /DEFAULT FILM RECORDINGS PASS/);
+});
+check('Windows decoder selection uses absolute PATH binaries, not implicit current-directory lookup', () => {
+ const windowsPath = join(root, 'windows-path'); mkdirSync(windowsPath, { recursive: true });
+ const marker = join(root, 'windows-decoder-marker');
+ for (const command of ['ffprobe', 'ffmpeg']) {
+ const real = execFileSync('which', [command], { encoding: 'utf8' }).trim();
+ writeFileSync(join(windowsPath, command + '.exe'), `#!${process.execPath}\nimport {readFileSync,writeFileSync} from 'node:fs'; import {execFileSync} from 'node:child_process'; writeFileSync(${JSON.stringify(marker)},'PATH binary'); process.stdout.write(execFileSync(${JSON.stringify(real)},process.argv.slice(2),{input:readFileSync(0),maxBuffer:1<<28}));`);
+ chmodSync(join(windowsPath, command + '.exe'), 0o755);
+ }
+ const script = join(root, 'windows-loader.mjs');
+ writeFileSync(script, `import {loadBanks} from ${JSON.stringify(new URL('./sounds.mjs', import.meta.url).href)}; const M=await import(${JSON.stringify('data:text/javascript;base64,'+Buffer.from(js).toString('base64'))}); Object.defineProperty(process,'platform',{value:'win32'}); loadBanks(M,${JSON.stringify(root)},['piano']);`);
+ execFileSync(process.execPath, [script], { env: { ...process.env, PATH: windowsPath, PATHEXT: '.exe' }, maxBuffer: 1<<24 });
+ assert.equal(readFileSync(marker, 'utf8'), 'PATH binary');
+});
+if (failures) process.exitCode = 1;
+else console.log('SOUNDS LOADER REVIEW PASS');
diff --git a/work/S7a/masking-in-progress.patch b/work/S7a/masking-in-progress.patch
new file mode 100644
index 0000000..08b1160
--- /dev/null
+++ b/work/S7a/masking-in-progress.patch
@@ -0,0 +1,156 @@
+diff --git a/skills/anidoodle/engine/src/canvas-core/music/guards.ts b/skills/anidoodle/engine/src/canvas-core/music/guards.ts
+index 667a2eb..41d9474 100644
+--- a/skills/anidoodle/engine/src/canvas-core/music/guards.ts
++++ b/skills/anidoodle/engine/src/canvas-core/music/guards.ts
+@@ -96,7 +96,7 @@ export const maskingPlan = (piece: Piece, o: { seconds?: number; tempo?: number;
+ const spans: [number, number][] = []; for (let b = 0; b < total; b += bpb) spans.push([perf.sec(b), perf.sec(b + bpb)]);
+ const melNotes = piece.parts.flatMap((p) => p.notes.filter((n) => n.role === "melody"));
+ const sounding = spans.map((_, i) => melNotes.some((n) => n.t < (i + 1) * bpb && n.t + n.d > i * bpb));
+- return { roles, spans, sounding, opts: (r: Role): RenderOpts => ({ seconds: o.seconds, tempo: o.tempo, master: "none", cache: o.cache, perf: played(r) }) };
++ return { roles, spans, sounding, opts: (r: Role): RenderOpts => ({ seconds: o.seconds, tempo: o.tempo, master: "none", cache: o.cache, perf: played(r), mixKeys: perf.parts.map(p => p.keys) }) };
+ };
+ export type MaskingPlan = NonNullable<ReturnType<typeof maskingPlan>>;
+ export const roleBandDb = (piece: Piece, sr: number, opts: RenderOpts, spans: [number, number][]) => { const x = renderPiece(piece, sr, opts); return bandDb(x.L, x.R, sr, spans); };
+diff --git a/skills/anidoodle/engine/src/canvas-core/music/mixProfiles.ts b/skills/anidoodle/engine/src/canvas-core/music/mixProfiles.ts
+index c1bebda..342e3a7 100644
+--- a/skills/anidoodle/engine/src/canvas-core/music/mixProfiles.ts
++++ b/skills/anidoodle/engine/src/canvas-core/music/mixProfiles.ts
+@@ -133,6 +133,14 @@ export const partEq = (prof: MixProfile, inst: InstId, role: Role): StemEq => {
+ if (role === "melody" && c !== "bass") e.bells = [...(e.bells ?? []), [2800, 1.1, 0.8 * k]];
+ return e;
+ };
++/** Leave the lead band open on recorded support parts, without changing faders or the voice. */
++export const recordedEq = (e: StemEq, role: Role, excessDb: number, fractionDb: number): StemEq => {
++ if (role !== "bass" && role !== "accomp") return e;
++ // A reference can itself be bright. Also limit absolute band occupancy toward 6% (-12 dB).
++ // One broad bell spans the guard's 500 Hz-4 kHz band; the existing makeup stage holds level.
++ const depth = Math.min(role === "bass" ? 12 : 6, Math.max(0, excessDb, fractionDb + 12) * (role === "bass" ? 0.8 : 0.6));
++ return depth > 0 ? { ...e, bells: [...(e.bells ?? []), [1400, 0.45, -depth]] } : e;
++};
+ /** A one-line summary for tools/music.mjs vocab. */
+ export const describeMix = (style: StyleId) => {
+ const p = MIX_PROFILES[style], s = p.space;
+diff --git a/skills/anidoodle/engine/src/canvas-core/music/render.ts b/skills/anidoodle/engine/src/canvas-core/music/render.ts
+index 7df5a87..f922008 100644
+--- a/skills/anidoodle/engine/src/canvas-core/music/render.ts
++++ b/skills/anidoodle/engine/src/canvas-core/music/render.ts
+@@ -6,7 +6,7 @@ import { type Piece, type Part, resequence, beatsPerBar } from "./plan";
+ import { perform, type Performance, type Played } from "./perform";
+ import { renderPiano, PIANO_REAL, type PianoOpts } from "./piano";
+ import { keysVoice, renderPianoV2 } from "./keys";
+-import { bankFor, samplerVoice, registerBank, type SampleBank, type SampleTrim } from "./sampler";
++import { bankFor, samplerVoice, sampleZones, registerBank, type SampleBank, type SampleTrim } from "./sampler";
+ import * as I from "./instruments";
+ import * as O from "./orchestra";
+ import { chokeTimes, type KitCtx } from "./drums";
+@@ -18,10 +18,11 @@ import { STYLES } from "./tables";
+ import { rng as mkRng } from "../core";
+ import { eqChain, runEq, stereoPan, compress, saturate, bandWidth, smoothLimiter, ampSim, transientGain } from "./mixDsp";
+ import { reverb, roomFor, type Space } from "./mixReverb";
+-import { mixProfile, partEq, ROLE_SEND, isStruck, TRANSIENT_DEFAULT, type MixProfile } from "./mixProfiles";
++import { mixProfile, partEq, recordedEq, ROLE_SEND, isStruck, TRANSIENT_DEFAULT, type MixProfile } from "./mixProfiles";
+
+ export type RenderOpts = { /** sound v2, gentle styles only: a <= 1 dB 2:1 glue on the mix bus (spec 08 forbids a compressor on gentle masters; Alex decides) */ gentleGlue?: boolean; expressive?: boolean; piano?: PianoOpts; flatVelocity?: number; seconds?: number; tempo?: number; master?: "auto" | "gentle" | "dense" | "none"; stems?: boolean; only?: (p: Part) => boolean;
+ /** play this performance instead of performing the piece (the guards render one role of the SAME performance the mix plays) */ perf?: Performance;
++ /** Complete part strikes keep recorded EQ fixed when a guard isolates one note role. */ mixKeys?: Played[][];
+ /** reuse synthesized voices by their exact inputs (tools/music.mjs check: each part is synthesized once for the mix, the guards and the stems); output is bit-identical */ cache?: VoiceCache };
+
+ /**
+@@ -142,16 +143,26 @@ export const calibrateBank = (id: string) => {
+ // Gated RMS would match the average tail instead of energy per strike, changing a fast
+ // arpeggio's balance when recorded and modeled decays differ. Use one fixed 12 s window.
+ const level = (r: VoiceOut) => { const mid = Float32Array.from(r.L, (x, i) => (x + r.R[i]) * 0.5); Biquad.make(sr, "hp", 30, 0.7071).run(mid); let energy = 0; for (const x of mid) energy += x * x; return 10 * Math.log10(energy / n); };
+- const references = new Map<string, number>();
++ const bandFraction = (r: VoiceOut) => {
++ const mid = Float32Array.from(r.L, (x, i) => (x + r.R[i]) * 0.5);
++ Biquad.make(sr, "hp", 40, Math.SQRT1_2).run(mid);
++ let total = 0; for (const x of mid) total += x * x;
++ Biquad.make(sr, "hp", 500, Math.SQRT1_2).run(mid); Biquad.make(sr, "lp", 4000, Math.SQRT1_2).run(mid);
++ let band = 0; for (const x of mid) band += x * x;
++ return 10 * Math.log10(Math.max(1e-15, band) / Math.max(1e-15, total));
++ };
++ const references = new Map<string, { level: number; band: number }>();
+ const trim: SampleTrim[] = bank.zones.filter(({ zone }) => zone.art !== "rel").map((z) => {
+ const p = z.zone.midi, v = bank.entry.layerVelocity?.[z.zone.layer - 1] ?? (z.zone.layer - 0.5) / bank.entry.layers;
+ const keys: Played[] = [{ p, v, tone: v, t: 0, off: 1, role: "melody", w: v }], one: SampleBank = { entry: { ...bare.entry, zones: [{ ...z.zone, art: undefined }] }, zones: [{ ...z, zone: { ...z.zone, art: undefined } }] }, recorded = samplerVoice(one, keys, [], sr, n, opts, 1);
+- const ref = `${p}:${v}`; let modeledDb = references.get(ref);
+- if (modeledDb === undefined) { const modeled = inst === "piano" ? renderPianoV2(keys, [], sr, n, opts, 1) : voice({ id: "ref", inst: inst as Part["inst"], role: "melody", notes: [], opts }, keys, sr, n, 1); modeledDb = level(modeled); references.set(ref, modeledDb); }
++ const ref = `${p}:${v}`; let modeled = references.get(ref);
++ if (modeled === undefined) { const r = inst === "piano" ? renderPianoV2(keys, [], sr, n, opts, 1) : voice({ id: "ref", inst: inst as Part["inst"], role: "melody", notes: [], opts }, keys, sr, n, 1); modeled = { level: level(r), band: bandFraction(r) }; references.set(ref, modeled); }
++ const modeledDb = modeled.level;
+ const measuredDb = level(recorded);
+ const correctionDb = modeledDb - measuredDb;
+ if (!Number.isFinite(correctionDb)) throw new Error(`${id}: silent calibration at MIDI ${p}`);
+- return { file: z.zone.file, midi: p, layer: z.zone.layer, measuredDb, modeledDb, correctionDb };
++ const bandFractionDb = bandFraction(recorded);
++ return { file: z.zone.file, midi: p, layer: z.zone.layer, measuredDb, modeledDb, correctionDb, bandFractionDb, bandExcessDb: bandFractionDb - modeled.band };
+ });
+ const sorted = trim.map((t) => t.correctionDb).sort((a, b) => a - b), middle = Math.floor(sorted.length / 2), medianDb = sorted.length % 2 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2;
+ return registerBank(id, { ...bare, trim: trim.map((t) => ({ ...t, requestedDb: t.correctionDb, medianDb, correctionDb: medianDb + Math.max(-9, Math.min(9, t.correctionDb - medianDb)), boostLimited: t.correctionDb > medianDb + 9 })) });
+@@ -245,7 +256,16 @@ const renderV2 = (piece: Piece, sr: number, o: RenderOpts = {}): Rendered => {
+ // corrective EQ, then match the stem's RMS back (+-3 dB cap): EQ shapes the tone, the fader keeps the calibrated balance
+ // the stem meter reads the part as the fader set it (pre-EQ, after its pan): the EQ is energy-neutral in the audible band
+ const pre = o.stems ? [Float32Array.from(sL), Float32Array.from(sR)] as [Float32Array, Float32Array] : null;
+- const before = audible(sL, sR, sr), e = partEq(prof, pt.inst, pt.role); runEq(sL, eqChain(sr, e)); runEq(sR, eqChain(sr, e));
++ const before = audible(sL, sR, sr);
++ let e = partEq(prof, pt.inst, pt.role);
++ if (job.kind === "sampled" && (pt.role === "bass" || pt.role === "accomp")) {
++ const bank = bankFor(pt.inst, typeof pt.opts?.variant === "string" ? pt.opts.variant : undefined)!;
++ const selected = sampleZones(bank, (o.mixKeys?.[pi] ?? keys).slice().sort((a, b) => a.t - b.t || a.p - b.p), job.seed, pt.opts?.pedal === false ? [] : perf.pedal);
++ const spectra = selected.map(z => bank.trim?.find(t => t.file === z.zone.file));
++ const median = (xs: number[], fallback: number) => xs.length ? xs.sort((a, b) => a - b)[Math.floor(xs.length / 2)] : fallback;
++ e = recordedEq(e, pt.role, median(spectra.map(t => t?.bandExcessDb ?? 0), 0), median(spectra.map(t => t?.bandFractionDb ?? -Infinity), -Infinity));
++ }
++ runEq(sL, eqChain(sr, e)); runEq(sR, eqChain(sr, e));
+ const after = audible(sL, sR, sr), mk = after > 0 && before > 0 ? Math.min(db(3), Math.max(db(-3), Math.sqrt(before / after))) : 1;
+ const g = db(pt.gainDb ?? 0) * mk;
+ for (let i = 0; i < n; i++) { sL[i] *= g; sR[i] *= g; }
+diff --git a/skills/anidoodle/engine/src/canvas-core/music/sampler.ts b/skills/anidoodle/engine/src/canvas-core/music/sampler.ts
+index a4c4570..3b97f52 100644
+--- a/skills/anidoodle/engine/src/canvas-core/music/sampler.ts
++++ b/skills/anidoodle/engine/src/canvas-core/music/sampler.ts
+@@ -9,7 +9,9 @@ import { pianoVelocity } from "./keysPiano";
+
+ export type SampleZone = { file: string; midi: number; layer: number; rr: number; frames: number; channels: number; peakDb: number; rmsDb: number; sha256: string; art?: "sus" | "rel"; unpitched?: boolean; measuredHz?: number; loop?: [number, number] };
+ export type SampleEntry = { title: string; source: string; license: string; kind: "struck" | "sustained"; range: [number, number]; layers: number; layerVelocity?: number[]; sparse?: boolean; maxShift?: number; damped: boolean; normalized?: boolean; zones: SampleZone[] };
+-export type SampleTrim = { file: string; midi: number; layer: number; measuredDb: number; modeledDb: number; correctionDb: number; requestedDb?: number; medianDb?: number; boostLimited?: boolean };
++export type SampleTrim = { file: string; midi: number; layer: number; measuredDb: number; modeledDb: number; correctionDb: number; requestedDb?: number; medianDb?: number; boostLimited?: boolean;
++ /** 500 Hz-4 kHz energy as a fraction of audible energy, and its excess over the modeled reference. */
++ bandFractionDb?: number; bandExcessDb?: number };
+ export type SampleBank = { entry: SampleEntry; zones: { zone: SampleZone; channels: Float32Array[] }[]; /** fixed modeled references at each recording's pitch and layer centre */ trim?: SampleTrim[] };
+ export type RegisteredBank = SampleBank & { id: string; hash: string };
+ const banks = new Map<string, RegisteredBank>();
+@@ -46,7 +48,7 @@ export const registerBank = (id: string, bank: SampleBank): RegisteredBank => {
+ if (JSON.stringify(z) !== JSON.stringify(e.zones[i]) || !Number.isInteger(z.midi) || z.midi < e.range[0] || z.midi > e.range[1] || !Number.isInteger(z.layer) || z.layer < 1 || z.layer > e.layers || !Number.isInteger(z.rr) || z.rr < 1 || !Number.isInteger(z.frames) || z.frames < 1 || ![1, 2].includes(z.channels) || !/^[a-f0-9]{64}$/i.test(z.sha256) || channels.length !== z.channels || channels.some((c) => !(c instanceof Float32Array) || c.length !== z.frames)) throw new Error(`${id}: invalid zone or PCM ${z.file}`);
+ });
+ if (!e.zones.some((z) => !z.art)) throw new Error(`${id}: no ordinary sample zones`);
+- if (bank.trim && (new Set(bank.trim.map((t) => t.file)).size !== bank.trim.length || bank.trim.some((t) => !e.zones.some((z) => z.file === t.file && z.midi === t.midi && z.layer === t.layer) || ![t.measuredDb, t.modeledDb, t.correctionDb, t.requestedDb ?? 0, t.medianDb ?? 0].every(Number.isFinite) || (t.medianDb !== undefined && Math.abs(t.correctionDb - t.medianDb) > 9.000001) || (t.boostLimited !== undefined && typeof t.boostLimited !== "boolean")))) throw new Error(`${id}: invalid sampled calibration`);
++ if (bank.trim && (new Set(bank.trim.map((t) => t.file)).size !== bank.trim.length || bank.trim.some((t) => !e.zones.some((z) => z.file === t.file && z.midi === t.midi && z.layer === t.layer) || ![t.measuredDb, t.modeledDb, t.correctionDb, t.requestedDb ?? 0, t.medianDb ?? 0, t.bandFractionDb ?? 0, t.bandExcessDb ?? 0].every(Number.isFinite) || (t.medianDb !== undefined && Math.abs(t.correctionDb - t.medianDb) > 9.000001) || (t.boostLimited !== undefined && typeof t.boostLimited !== "boolean")))) throw new Error(`${id}: invalid sampled calibration`);
+ const identity = bankIdentity(e), b = { ...bank, id, hash: bank.trim ? hash(JSON.stringify([identity, bank.trim])) : identity }; banks.set(id, b); return b;
+ };
+
+diff --git a/skills/anidoodle/engine/test/sampler.test.ts b/skills/anidoodle/engine/test/sampler.test.ts
+index 93eeb13..3323e18 100644
+--- a/skills/anidoodle/engine/test/sampler.test.ts
++++ b/skills/anidoodle/engine/test/sampler.test.ts
+@@ -114,6 +114,7 @@ export const run = (ok: (cond: boolean, label: string) => void) => {
+ const original = calibration.zones.map((z) => Float32Array.from(z.channels[0])); registerBank("piano", calibration);
+ const calibrated = calibrateBank("piano"), redo = calibrateBank("piano");
+ ok(calibrated.hash === redo.hash && JSON.stringify(calibrated.trim) === JSON.stringify(redo.trim), "pitch/layer calibration is deterministic from PCM and fixed modeled references");
++ ok(calibrated.trim!.every(t => Number.isFinite(t.bandFractionDb) && Number.isFinite(t.bandExcessDb)), "load calibration measures every zone's masking-band fraction and excess over its modeled reference");
+ ok(calibrated.zones.every((z, i) => same(z.channels[0], original[i])), "calibration never changes recording PCM or tone");
+ const measured = (x: Float32Array, y: Float32Array) => { const mid = Float32Array.from(x, (v, i) => (v + y[i]) * 0.5); Biquad.make(SR, "hp", 30, 0.7071).run(mid); let energy = 0; for (const v of mid) energy += v * v; return 10 * Math.log10(energy / (SR * 12)); };
+ const levels = [1, 2, 3].map((layer) => { const v = (layer - 0.5) / 3, r = render(calibrated, [{ ...key(60, v, 0, 1), tone: v }], SR, [], { pedal: false }); return measured(r.L, r.R); });
+diff --git a/skills/anidoodle/engine/tools/sounds.mjs b/skills/anidoodle/engine/tools/sounds.mjs
+index 8b50676..1b7686d 100644
+--- a/skills/anidoodle/engine/tools/sounds.mjs
++++ b/skills/anidoodle/engine/tools/sounds.mjs
+@@ -32,6 +32,8 @@ export const loadBanks = (M, dir, ids) => {
+ const zones = entry.zones.map((zone) => ({ zone, channels: decodeFlac(root, id, zone) }));
+ M.registerBank(id, { entry, zones });
+ const calibrated = M.calibrateBank(id);
++ console.log(`spectrum ${id}: zone | 500 Hz-4 kHz fraction dB | excess over modeled dB`);
++ for (const t of calibrated.trim) console.log(` ${t.file} | ${t.bandFractionDb.toFixed(2)} | ${t.bandExcessDb.toFixed(2)}`);
+ console.log(`calibration ${id}: median trim ${calibrated.trim[0].medianDb.toFixed(2)} dB; zone | layer | measured dB | modeled dB | requested dB | applied dB | deviation dB`);
+ for (const t of calibrated.trim) console.log(` ${t.file} | ${t.layer} | ${t.measuredDb.toFixed(2)} | ${t.modeledDb.toFixed(2)} | ${t.requestedDb.toFixed(2)} | ${t.correctionDb.toFixed(2)} | ${(t.correctionDb - t.medianDb).toFixed(2)}${Math.abs(t.correctionDb) > 9 ? " | FLAG applied >9 dB (includes instrument trim)" : ""}${Math.abs(t.requestedDb - t.medianDb) > 9 ? " | FLAG >9 dB deviation: capped, inspect zone/reference" : ""}${t.boostLimited ? " | prefer louder layer" : ""}`);
+ }
diff --git a/work/S7a/recordedMix-in-progress.ts b/work/S7a/recordedMix-in-progress.ts
new file mode 100644
index 0000000..aa03cff
--- /dev/null
+++ b/work/S7a/recordedMix-in-progress.ts
@@ -0,0 +1,54 @@
+import { registerBank, clearBanks, type SampleBank } from '../src/canvas-core/music/sampler';
+import { calibrateBank, renderPiece } from '../src/canvas-core/music/render';
+import { maskingPlan, roleBandDb } from '../src/canvas-core/music/guards';
+import { perform } from '../src/canvas-core/music/perform';
+import { Biquad } from '../src/canvas-core/music/dsp';
+import { hz } from '../src/canvas-core/music/theory';
+import { marimbaCurious } from '../src/canvas-core/music/pieces/families';
+import type { Piece, Role } from '../src/canvas-core/music/plan';
+
+export const name = 'recorded support mix';
+export const run = (ok: (cond: boolean, label: string) => void) => {
+ const sr = 24000, frames = 48000, pitches = [48, 60, 72];
+ const zones = pitches.map((midi, i) => {
+ const pcm = Float32Array.from({ length: frames }, (_, n) => {
+ const t = n / 48000, f = hz(midi);
+ return 0.2 * Math.exp(-t * 3) * (Math.sin(2 * Math.PI * f * t) + (i < 2 ? 0.8 * Math.sin(2 * Math.PI * f * 5 * t) : 0));
+ });
+ return { zone: { file: `${midi}.flac`, midi, layer: 1, rr: 1, frames, channels: 1, peakDb: -6, rmsDb: -18, sha256: String(i + 1).repeat(64) }, channels: [pcm] };
+ });
+ const bank: SampleBank = { entry: { title: 'spectral fixture', source: 'synthetic', license: 'CC0-1.0', kind: 'struck', range: [48, 72], layers: 1, damped: false, normalized: false, zones: zones.map(z => z.zone) }, zones };
+ const source = marimbaCurious();
+ const part = source.parts[0];
+ const piece = (role: Role, mixed = false): Piece => ({ ...source, tail: 0.2,
+ plan: { ...source.plan, space: undefined }, mix: { ...source.mix, eq: 0, transient: null, space: null, drumRoom: null, tilt: 0, busDrive: 0, glue: null, width: { mid: 1, high: 1, monoHz: 0, splitHz: 800 } },
+ parts: [{ ...part, inst: 'marimba', role, pan: 0, gainDb: 0, notes: mixed
+ ? [{ t: 0, d: 0.4, p: 48, v: 0.5, role: 'bass' }, { t: 0.5, d: 0.4, p: 72, v: 0.5, role: 'accomp' }, { t: 1, d: 0.4, p: 72, v: 0.5, role: 'accomp' }]
+ : [{ t: 0, d: 0.4, p: role === 'bass' ? 48 : 60, v: 0.5, role }] }] });
+ const fraction = (a: Float32Array) => {
+ const x = Biquad.make(sr, 'hp', 40, Math.SQRT1_2).run(Float32Array.from(a));
+ const total = x.reduce((s, v) => s + v * v, 0);
+ Biquad.make(sr, 'hp', 500, Math.SQRT1_2).run(x); Biquad.make(sr, 'lp', 4000, Math.SQRT1_2).run(x);
+ return 10 * Math.log10(x.reduce((s, v) => s + v * v, 0) / total);
+ };
+ const rms = (a: Float32Array) => Math.sqrt(a.reduce((s, v) => s + v * v, 0) / a.length);
+ clearBanks();
+ try {
+ registerBank('marimba', bank); const calibrated = calibrateBank('marimba');
+ const neutral = { ...calibrated, trim: calibrated.trim!.map(t => ({ ...t, bandFractionDb: -40, bandExcessDb: 0 })) };
+ const render = (role: Role) => renderPiece(piece(role), sr, { seconds: 2, master: 'none', expressive: false }).dry[0];
+ registerBank('marimba', neutral); const unchanged = render('melody'), bassBefore = render('bass'), accompBefore = render('accomp');
+ registerBank('marimba', calibrated); const lead = render('melody'), bass = render('bass'), accomp = render('accomp');
+ ok(lead.every((v, i) => v === unchanged[i]), 'recorded melody keeps every sample when support EQ measurements change');
+ ok(fraction(bass) < fraction(bassBefore) - 2 && fraction(accomp) < fraction(accompBefore) - 1, 'load-measured recorded bass and accompaniment lose masking-band energy');
+ ok(Math.abs(20 * Math.log10(rms(bass) / rms(bassBefore))) < 2.5 && Math.abs(20 * Math.log10(rms(accomp) / rms(accompBefore))) < 2.5, 'support EQ retains broadband balance through the existing makeup stage');
+ const p = piece('accomp', true);
+ // Include one melody note so the guard has a melody role; keep the complete accompaniment context.
+ p.parts[0].notes[2].role = 'melody';
+ const complete = perform(p, p.plan.tempo, { expressive: false }), plan = maskingPlan(p, { seconds: 2, perf: complete })!;
+ const isolated = { ...complete, parts: complete.parts.map(q => ({ ...q, keys: q.keys.filter(k => k.role === 'bass') })) };
+ const expected = roleBandDb(p, sr, { seconds: 2, master: 'none', perf: isolated, mixKeys: complete.parts.map(q => q.keys) }, plan.spans);
+ const actual = roleBandDb(p, sr, plan.opts('bass'), plan.spans);
+ ok(actual.every((v, i) => Math.abs(v - expected[i]) < 1e-8), 'role-isolated guard uses the complete part spectral choice, including mixed-role parts');
+ } finally { clearBanks(); }
+};
diff --git a/work/S7a/release-baseline.json b/work/S7a/release-baseline.json
new file mode 100644
index 0000000..9fc5a8e
--- /dev/null
+++ b/work/S7a/release-baseline.json
@@ -0,0 +1,17 @@
+{
+ "revision": "7970552c1a7a6d986c972cdd3d7df145c9ce634a",
+ "rows": [
+ {
+ "name": "marimbaCurious",
+ "md5": "d787a58c5704cf940a4404281e33d07a"
+ },
+ {
+ "name": "harpTender",
+ "md5": "f71a7e20d442d77462ef0b94e4ca8824"
+ },
+ {
+ "name": "nocturne",
+ "md5": "acd240c8adffd25d00ee5279f2c72d3e"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/work/S7a/release-baseline.mjs b/work/S7a/release-baseline.mjs
new file mode 100644
index 0000000..253ef3b
--- /dev/null
+++ b/work/S7a/release-baseline.mjs
@@ -0,0 +1,18 @@
+import { build } from '../../skills/anidoodle/engine/node_modules/esbuild/lib/main.js';
+import { execFileSync } from 'node:child_process';
+import { createHash } from 'node:crypto';
+import { readFileSync, writeFileSync } from 'node:fs';
+import assert from 'node:assert/strict';
+const prefix = 'skills/anidoodle/engine/', root = new URL('../../', import.meta.url).pathname;
+const revision = execFileSync('git', ['rev-parse', 'release/0.6'], { encoding: 'utf8' }).trim();
+const originalSources = { name: 'release-source', setup(b) { b.onLoad({ filter: /\.ts$/ }, a => ({ contents: execFileSync('git', ['show', `${revision}:${a.path.slice(root.length)}`], { encoding: 'utf8' }), loader: 'ts' })); } };
+const js = (await build({ entryPoints: [root + prefix + 'src/canvas-core/music/index.ts'], plugins: [originalSources], bundle: true, format: 'esm', write: false })).outputFiles[0].text;
+const M = await import('data:text/javascript;base64,' + Buffer.from(js).toString('base64'));
+const before = JSON.parse(readFileSync(new URL('baseline.json', import.meta.url))), rows = [];
+for (const name of ['marimbaCurious', 'harpTender', 'nocturne']) {
+ const r = M.renderPiece(M.DEMOS[name](), 48000), md5 = createHash('md5').update(Buffer.from(r.L.buffer)).update(Buffer.from(r.R.buffer)).digest('hex');
+ assert.equal(md5, before[name].md5, `${name}: release-derived baseline`);
+ rows.push({ name, md5 }); console.log(`release/0.6 ${name}: ${md5} MATCH`);
+}
+writeFileSync(new URL('release-baseline.json', import.meta.url), JSON.stringify({ revision, rows }, null, 2));
+console.log('RELEASE BASELINE PASS');