diff --git a/AGENTS.md b/AGENTS.md index 55bba9b..03e0124 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -7,9 +7,7 @@ synth patches. It owns patch graph models, terse patch scripting, SFXR-derived patch mapping, analysis/scoring tools, preset catalogs, and Faust source/code generation for the AquaSynth/Vortice engine path. -The AquaSynth-rs branch may remain a reference lab and audio renderer. This repo should -not depend on AquaSynth-rs for reusable authoring, analysis, preset, or Faust -compiler behavior. +`AquaSynth-rs` is retired and removed. This repo owns all authoring, analysis, preset, and Faust compiler behavior directly. ## Persistent State diff --git a/AquaSynth.sln b/AquaSynth.sln index c968b46..1efa30a 100644 --- a/AquaSynth.sln +++ b/AquaSynth.sln @@ -15,14 +15,14 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AquaSynth.Dsl.Tests", "test EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tools", "tools", "{07C2787E-EAC7-C090-1BA3-A61EC2A24D84}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BirdSyrinxGolf", "tools\BirdSyrinxGolf\BirdSyrinxGolf.csproj", "{A1914F24-9CE5-47DA-943E-E26D3AC4DFD3}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IpaTrialWorker", "tools\IpaTrialWorker\IpaTrialWorker.csproj", "{9596767B-8FDC-49E5-8F70-0A1CECE35C5E}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AquaSynthDaemon", "tools\AquaSynthDaemon\AquaSynthDaemon.csproj", "{A21990AB-5D3D-4A5B-98B7-F730A4091DA8}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AquaSynthDingsMcp", "tools\AquaSynthDingsMcp\AquaSynthDingsMcp.csproj", "{C38832D2-06A7-463E-8D99-C048ED51E9E1}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AquaSynth.Dings", "src\AquaSynth.Dings\AquaSynth.Dings.csproj", "{AA42374E-4CF8-4F1C-A9F6-F44263296206}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AquaSynthDingsHost", "tools\AquaSynthDingsHost\AquaSynthDingsHost.csproj", "{F98203FC-6151-453C-9D6A-E29BD0EDEE7B}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -69,30 +69,6 @@ Global {D6CDBB4A-A783-4AA8-8715-E9E71A9BF9CB}.Release|x64.Build.0 = Release|Any CPU {D6CDBB4A-A783-4AA8-8715-E9E71A9BF9CB}.Release|x86.ActiveCfg = Release|Any CPU {D6CDBB4A-A783-4AA8-8715-E9E71A9BF9CB}.Release|x86.Build.0 = Release|Any CPU - {A1914F24-9CE5-47DA-943E-E26D3AC4DFD3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A1914F24-9CE5-47DA-943E-E26D3AC4DFD3}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A1914F24-9CE5-47DA-943E-E26D3AC4DFD3}.Debug|x64.ActiveCfg = Debug|Any CPU - {A1914F24-9CE5-47DA-943E-E26D3AC4DFD3}.Debug|x64.Build.0 = Debug|Any CPU - {A1914F24-9CE5-47DA-943E-E26D3AC4DFD3}.Debug|x86.ActiveCfg = Debug|Any CPU - {A1914F24-9CE5-47DA-943E-E26D3AC4DFD3}.Debug|x86.Build.0 = Debug|Any CPU - {A1914F24-9CE5-47DA-943E-E26D3AC4DFD3}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A1914F24-9CE5-47DA-943E-E26D3AC4DFD3}.Release|Any CPU.Build.0 = Release|Any CPU - {A1914F24-9CE5-47DA-943E-E26D3AC4DFD3}.Release|x64.ActiveCfg = Release|Any CPU - {A1914F24-9CE5-47DA-943E-E26D3AC4DFD3}.Release|x64.Build.0 = Release|Any CPU - {A1914F24-9CE5-47DA-943E-E26D3AC4DFD3}.Release|x86.ActiveCfg = Release|Any CPU - {A1914F24-9CE5-47DA-943E-E26D3AC4DFD3}.Release|x86.Build.0 = Release|Any CPU - {9596767B-8FDC-49E5-8F70-0A1CECE35C5E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {9596767B-8FDC-49E5-8F70-0A1CECE35C5E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {9596767B-8FDC-49E5-8F70-0A1CECE35C5E}.Debug|x64.ActiveCfg = Debug|Any CPU - {9596767B-8FDC-49E5-8F70-0A1CECE35C5E}.Debug|x64.Build.0 = Debug|Any CPU - {9596767B-8FDC-49E5-8F70-0A1CECE35C5E}.Debug|x86.ActiveCfg = Debug|Any CPU - {9596767B-8FDC-49E5-8F70-0A1CECE35C5E}.Debug|x86.Build.0 = Debug|Any CPU - {9596767B-8FDC-49E5-8F70-0A1CECE35C5E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {9596767B-8FDC-49E5-8F70-0A1CECE35C5E}.Release|Any CPU.Build.0 = Release|Any CPU - {9596767B-8FDC-49E5-8F70-0A1CECE35C5E}.Release|x64.ActiveCfg = Release|Any CPU - {9596767B-8FDC-49E5-8F70-0A1CECE35C5E}.Release|x64.Build.0 = Release|Any CPU - {9596767B-8FDC-49E5-8F70-0A1CECE35C5E}.Release|x86.ActiveCfg = Release|Any CPU - {9596767B-8FDC-49E5-8F70-0A1CECE35C5E}.Release|x86.Build.0 = Release|Any CPU {A21990AB-5D3D-4A5B-98B7-F730A4091DA8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A21990AB-5D3D-4A5B-98B7-F730A4091DA8}.Debug|Any CPU.Build.0 = Debug|Any CPU {A21990AB-5D3D-4A5B-98B7-F730A4091DA8}.Debug|x64.ActiveCfg = Debug|Any CPU @@ -109,6 +85,30 @@ Global {C38832D2-06A7-463E-8D99-C048ED51E9E1}.Debug|Any CPU.Build.0 = Debug|Any CPU {C38832D2-06A7-463E-8D99-C048ED51E9E1}.Release|Any CPU.ActiveCfg = Release|Any CPU {C38832D2-06A7-463E-8D99-C048ED51E9E1}.Release|Any CPU.Build.0 = Release|Any CPU + {AA42374E-4CF8-4F1C-A9F6-F44263296206}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AA42374E-4CF8-4F1C-A9F6-F44263296206}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AA42374E-4CF8-4F1C-A9F6-F44263296206}.Debug|x64.ActiveCfg = Debug|Any CPU + {AA42374E-4CF8-4F1C-A9F6-F44263296206}.Debug|x64.Build.0 = Debug|Any CPU + {AA42374E-4CF8-4F1C-A9F6-F44263296206}.Debug|x86.ActiveCfg = Debug|Any CPU + {AA42374E-4CF8-4F1C-A9F6-F44263296206}.Debug|x86.Build.0 = Debug|Any CPU + {AA42374E-4CF8-4F1C-A9F6-F44263296206}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AA42374E-4CF8-4F1C-A9F6-F44263296206}.Release|Any CPU.Build.0 = Release|Any CPU + {AA42374E-4CF8-4F1C-A9F6-F44263296206}.Release|x64.ActiveCfg = Release|Any CPU + {AA42374E-4CF8-4F1C-A9F6-F44263296206}.Release|x64.Build.0 = Release|Any CPU + {AA42374E-4CF8-4F1C-A9F6-F44263296206}.Release|x86.ActiveCfg = Release|Any CPU + {AA42374E-4CF8-4F1C-A9F6-F44263296206}.Release|x86.Build.0 = Release|Any CPU + {F98203FC-6151-453C-9D6A-E29BD0EDEE7B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F98203FC-6151-453C-9D6A-E29BD0EDEE7B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F98203FC-6151-453C-9D6A-E29BD0EDEE7B}.Debug|x64.ActiveCfg = Debug|Any CPU + {F98203FC-6151-453C-9D6A-E29BD0EDEE7B}.Debug|x64.Build.0 = Debug|Any CPU + {F98203FC-6151-453C-9D6A-E29BD0EDEE7B}.Debug|x86.ActiveCfg = Debug|Any CPU + {F98203FC-6151-453C-9D6A-E29BD0EDEE7B}.Debug|x86.Build.0 = Debug|Any CPU + {F98203FC-6151-453C-9D6A-E29BD0EDEE7B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F98203FC-6151-453C-9D6A-E29BD0EDEE7B}.Release|Any CPU.Build.0 = Release|Any CPU + {F98203FC-6151-453C-9D6A-E29BD0EDEE7B}.Release|x64.ActiveCfg = Release|Any CPU + {F98203FC-6151-453C-9D6A-E29BD0EDEE7B}.Release|x64.Build.0 = Release|Any CPU + {F98203FC-6151-453C-9D6A-E29BD0EDEE7B}.Release|x86.ActiveCfg = Release|Any CPU + {F98203FC-6151-453C-9D6A-E29BD0EDEE7B}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -117,9 +117,9 @@ Global {43E2BCEB-0E0E-4E02-AE3D-4A1D0EBC2B31} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} {10EDBE53-4957-44AB-90C9-82C2ABD526CD} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} {D6CDBB4A-A783-4AA8-8715-E9E71A9BF9CB} = {0AB3BF05-4346-4AA6-1389-037BE0695223} - {A1914F24-9CE5-47DA-943E-E26D3AC4DFD3} = {07C2787E-EAC7-C090-1BA3-A61EC2A24D84} - {9596767B-8FDC-49E5-8F70-0A1CECE35C5E} = {07C2787E-EAC7-C090-1BA3-A61EC2A24D84} {A21990AB-5D3D-4A5B-98B7-F730A4091DA8} = {07C2787E-EAC7-C090-1BA3-A61EC2A24D84} {C38832D2-06A7-463E-8D99-C048ED51E9E1} = {07C2787E-EAC7-C090-1BA3-A61EC2A24D84} + {AA42374E-4CF8-4F1C-A9F6-F44263296206} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} + {F98203FC-6151-453C-9D6A-E29BD0EDEE7B} = {07C2787E-EAC7-C090-1BA3-A61EC2A24D84} EndGlobalSection EndGlobal diff --git a/docs/fixtures/aquasynth-provider-advertisement.json b/docs/fixtures/aquasynth-provider-advertisement.json deleted file mode 100644 index 37e6c34..0000000 --- a/docs/fixtures/aquasynth-provider-advertisement.json +++ /dev/null @@ -1,244 +0,0 @@ -{ - "schema": "gamecult.eve.provider_advertisement.v1", - "providerId": "aquasynth.service", - "title": "AquaSynth Service", - "description": "AquaSynth accepts .aqua DSL and Weksa utterance handoffs, compiles Faust-native instruments, owns live streaming patch sessions, and publishes controllable synth state through CultMesh.", - "mode": "fixture-read-only", - "serviceVerse": { - "id": "verse.aquasynth.service.v1", - "cultMeshKey": "aquasynth.service/provider-advertisement", - "authority": "AquaSynth daemon identity, schema catalog, provider publication, and synth runtime boundary", - "owns": [ - ".aqua patch parsing", - "patch graph semantics", - "Faust source emission", - "native Faust compilation", - "compiled instrument sessions", - "live streaming patch sessions", - "live session control state", - "live session lifecycle receipts", - "sample/render receipts", - "learned utterance embeddings and synth-driver controls" - ], - "doesNotOwn": [ - "Weksa conversational intent", - "Persona canonical state", - "Eve presentation runtime" - ] - }, - "nestedVerses": [ - { - "id": "aquasynth.patch", - "kind": "patch", - "cultMeshKey": "aquasynth.patch/current", - "authority": "AquaSynth.Core .aqua parser and patch graph model", - "schemas": [ - "aquasynth.patch_graph.v0" - ] - }, - { - "id": "aquasynth.compile", - "kind": "compile", - "cultMeshKey": "aquasynth.compile/jobs", - "authority": "AquaSynth.Faust compiler boundary", - "schemas": [ - "aquasynth.faust_source.v0", - "aquasynth.compiled_instrument.v0" - ] - }, - { - "id": "aquasynth.instrument", - "kind": "instrument", - "cultMeshKey": "aquasynth.instrument/sessions", - "authority": "AquaSynth native host and live-session owner", - "schemas": [ - "aquasynth.compiled_instrument_session.v1", - "aquasynth.live_instrument_session.v1", - "aquasynth.command.instrument_open.v1", - "aquasynth.command.instrument_control.v1", - "aquasynth.command.instrument_block.v1", - "aquasynth.command.instrument_close.v1", - "aquasynth.instrument_open_receipt.v1", - "aquasynth.instrument_control_receipt.v1", - "aquasynth.instrument_block_receipt.v1", - "aquasynth.instrument_close_receipt.v1" - ] - }, - { - "id": "aquasynth.speech", - "kind": "speech", - "cultMeshKey": "aquasynth.speech/current", - "authority": "AquaSynth utterance embedding and synth-driver runtime", - "schemas": [ - "aquasynth.utterance_embedding.v0", - "aquasynth.speech_render_receipt.v0" - ] - }, - { - "id": "aquasynth.operator", - "kind": "operator", - "cultMeshKey": "aquasynth.operator/status", - "authority": "AquaSynth daemon runtime", - "schemas": [ - "aquasynth.operator_state.v0" - ] - } - ], - "schemaWitnessFamilies": [ - { - "family": "patch", - "namespace": "aquasynth.patch.*", - "witnesses": [ - "aquasynth.patch_graph.v0" - ], - "durableShape": ".aquasynth/patches/{patchId}.cc" - }, - { - "family": "compile", - "namespace": "aquasynth.compile.*", - "witnesses": [ - "aquasynth.faust_source.v0", - "aquasynth.compiled_instrument.v0" - ], - "durableShape": ".aquasynth/faust/{compileId}.cc" - }, - { - "family": "instrument", - "namespace": "aquasynth.instrument.*", - "witnesses": [ - "aquasynth.compiled_instrument_session.v1", - "aquasynth.live_instrument_session.v1", - "aquasynth.instrument_open_receipt.v1", - "aquasynth.instrument_control_receipt.v1", - "aquasynth.instrument_block_receipt.v1", - "aquasynth.instrument_close_receipt.v1" - ], - "durableShape": ".aquasynth/sessions/{sessionId}.cc and .aquasynth/live-sessions/{sessionId}.cc" - }, - { - "family": "render", - "namespace": "aquasynth.render.*", - "witnesses": [ - "aquasynth.render_sample.v0", - "aquasynth.render_loss.v0" - ], - "durableShape": ".aquasynth/renders/{renderId}.cc" - }, - { - "family": "speech", - "namespace": "aquasynth.speech.*", - "witnesses": [ - "aquasynth.utterance_embedding.v0", - "aquasynth.speech_render_receipt.v0" - ], - "durableShape": ".aquasynth/speech/{utteranceId}.cc" - } - ], - "commandBoundaries": [ - { - "id": "aquasynth.command.patch.compile", - "owner": "AquaSynth", - "acceptedByFixture": false, - "allowedInputs": [ - ".aqua DSL", - "compile target", - "host architecture" - ], - "emits": [ - "aquasynth.patch_graph.v0", - "aquasynth.faust_source.v0", - "aquasynth.compiled_instrument.v0" - ] - }, - { - "id": "aquasynth.command.instrument.open", - "owner": "AquaSynth", - "acceptedByFixture": false, - "allowedInputs": [ - ".aqua DSL", - "block size", - "initial semantic control values" - ], - "emits": [ - "aquasynth.compiled_instrument_session.v1", - "aquasynth.live_instrument_session.v1", - "aquasynth.instrument_open_receipt.v1" - ] - }, - { - "id": "aquasynth.command.instrument.control", - "owner": "AquaSynth", - "acceptedByFixture": false, - "allowedInputs": [ - "live session id", - "semantic control values" - ], - "emits": [ - "aquasynth.live_instrument_session.v1", - "aquasynth.instrument_control_receipt.v1" - ] - }, - { - "id": "aquasynth.command.instrument.block", - "owner": "AquaSynth", - "acceptedByFixture": false, - "allowedInputs": [ - "live session id", - "frame count", - "optional control values" - ], - "emits": [ - "aquasynth.live_instrument_session.v1", - "aquasynth.instrument_block_receipt.v1" - ] - }, - { - "id": "aquasynth.command.instrument.close", - "owner": "AquaSynth", - "acceptedByFixture": false, - "allowedInputs": [ - "live session id" - ], - "emits": [ - "aquasynth.live_instrument_session.v1", - "aquasynth.instrument_close_receipt.v1" - ] - }, - { - "id": "aquasynth.command.instrument.sample", - "owner": "AquaSynth", - "acceptedByFixture": false, - "allowedInputs": [ - ".aqua DSL", - "duration", - "sample format", - "optional semantic control values" - ], - "emits": [ - "aquasynth.render_sample.v0" - ] - }, - { - "id": "aquasynth.command.speech.realize", - "owner": "AquaSynth", - "acceptedByFixture": false, - "allowedInputs": [ - "weksa.utterance_handoff.v0", - "weksa.utterance_embedding_handoff.v0.1" - ], - "emits": [ - "aquasynth.utterance_embedding.v0", - "aquasynth.speech_render_receipt.v0" - ], - "forbiddenTargets": [ - "Weksa conversational intent truth" - ] - } - ], - "loweringRules": [ - "AquaSynth owns learned embeddings, synth controls, Faust compilation, native binary lifetime, compiled instrument sessions, live streaming patch sessions, and sampled outputs.", - "Weksa owns writing-to-intent and intent-to-utterance lowering.", - "Faust source and native binaries are emitted artifacts with typed receipts, not the semantic patch owner.", - "Dashboards and other renderers control and inspect sessions through CultMesh command documents and retained live-session state; they do not own audio state." - ] -} diff --git a/src/AquaSynth.Dings/DingCatalog.cs b/src/AquaSynth.Dings/DingCatalog.cs index df4659e..1b0b18f 100644 --- a/src/AquaSynth.Dings/DingCatalog.cs +++ b/src/AquaSynth.Dings/DingCatalog.cs @@ -13,8 +13,8 @@ public static class DingCatalog public static DingPatchIdentity Identity(DingInstrument instrument) => new($"dings.{instrument.Id}", $"dings_{instrument.Id.Replace('-', '_')}", 1); - /// The play validation gate. The Host is its enforcing owner (every pipe client passes it); the MCP bridge's - /// own check in DingService.PlayAsync is a deprecated fail-fast path. Returns the rejection text, or null when valid. + /// The play validation gate. The Host is its single enforcing owner (every pipe client passes it). + /// Returns the rejection text, or null when valid. public static string? PlayRejection(string eventId, string instrumentId, float gain) { if (!Events.ContainsKey(eventId)) return $"Unknown event '{eventId}'."; diff --git a/state/scratch.md b/state/scratch.md deleted file mode 100644 index 4a0916d..0000000 --- a/state/scratch.md +++ /dev/null @@ -1,2000 +0,0 @@ -# Scratch - -Current slice: - -- User identified the three-pass corpus run's audible failure correctly: mode - collapse into a short opening phrase followed by low-motion texture/noise. - `song-score` now owns song continuity metrics: - `candidate_active_coverage`, `candidate_motion_coverage`, - `candidate_first_second_energy_share`, `candidate_tail_energy_share`, and - `mode_collapse_risk`. The old top pass-3 candidate - `agent_02__retrievedmesh__target_04_a05` now scores as - `weak-mode-collapse` with first-second energy share `0.883627` and collapse - risk `1`, proving the evaluator sees the cheap trick. Distillation ranking - demotes collapse risk, candidate knowledge records carry the failure mode, - and the swarm prompt now requires later-section motifs/events instead of - hiding behind noise or pads. - -- Follow-up trawl found real generalizable sound-production knowledge but weak - composition: stable role owners for syrinx/acoustic leads, subtractive drums, - additive/PAD beds, shaped texture/air/codec, and strong negative pressure - against mode collapse. The redirect is composition-first: next passes must - publish a Composition Map with meter/time signature, progression or tonal - center, note-degree sampling, instrument-lane gates, section events, - composition-scale automation, and mix movement. Parser sugar now includes - `meter`, `sequence`, `chords`, and `mix`, lowering to ordinary `param` and - `curve` owners alongside existing `pattern` and `scale`. - -- Completed a three-pass corpus song curriculum run under - `artifacts/parity/song-snippet-swarms/20260531T171802519`: each pass prepared - 25 ten-second targets from `D:\Music\Reinier` for five agents with five - assignments each, then ran official scoring, playlist generation, semantic - search, trial distillation, and `music-distill` promotion. Pass 1 promoted 34 - music-production knowledge records, pass 2 promoted 56, and pass 3 promoted - 58. Final pass artifacts include `pass-003/top-scoring-candidates.m3u`, - `pass-003/distillation-report.md`, - `pass-003/music-production-knowledge.cc`, and - `pass-003/music-production-quality-standard.md`. The run exposed two harness - quality faults: spawned agents needed `E:\Projects\CultLib` as an added Codex - directory to run private scorers, and render-failed attempts must be handled - as negative evidence because candidate analysis files are absent. The pass-3 - outer swarm failed after agent jobs 2/3/4/5 exited nonzero, so the run was - finished by promoting existing attempt-05 patches from those agents into the - official patch tree and running official scoring/promotion manually. - -- Built the first pruned music-production CultCache from the full-song iterative - swarm artifacts instead of copying the old hot trial store. `music-distill` - scans official pass summaries and abstraction ledgers, excludes iteration, - smoke, and rerun scratch, then writes a fresh paged - `MusicProductionKnowledgeDocument` store with compact quality-standard, - scene-role, failure-mode, candidate-pattern, and abstraction-ledger records. - The current store is - `artifacts/parity/music-knowledge/20260531T121228337/music-production-knowledge.cc` - with 37 records from 28 official scored rows: 1 master standard, 4 role - doctrine records, 1 failure-pressure record, 16 rendered candidate-pattern - records, and 15 syntax-sugar pressure ledgers. Explorer commands - `music-search` and `music-show` read the store directly; smoke reports live - beside it as `search-syrinx.md`, `search-drums.md`, and - `show-quality-standard.md`. - -- Song-snippet challenge harness is now a real local parity lane, not a - hand-waved prompt. `tools/IpaTrialWorker` has `song-prepare` and `song-score`: - `song-prepare` decodes a local audio file through NAudio, freezes a seeded - ten-second mono 44.1 kHz `reference.wav`, writes `challenge.json` and - `challenge.md`, and reports scene features including spectral centroid, - rolloff, active duty, spectral flux, onset-autocorrelation tempo - (`tempo_bpm`, `beat_seconds`, `tempo_confidence`), dominant pitch/register - (`dominant_hz`, `register_low_hz`, `register_high_hz`, `root_note`), and - deterministic scale hints (`suggested_scale`, `scale_frequencies_hz`). - `song-score` renders agent-authored `.aqua` candidates against that frozen - reference, writes candidate WAV/DSP/timeline/comparison artifacts, and stores - typed `IpaTrialResult` records in a song `.cc` store. - -- `tools/run-song-snippet-trial-swarm.ps1` prepares the random clip from - `D:\Music\Reinier\Heyoka\Gate Code\Heyoka - Alien Gibberish.mp3`, then can - dispatch passes of parallel external Codex agents. Agents are prompted to use - scene voices, FM/AM/noise/envelopes, rhythmic controls from - autocorrelation-derived tempo, and register-bounded explicit scale-frequency - curves. Until native Strudel-like `scale`/`note` sugar exists, the live syntax - is `param` plus `curve ... interp=hold loop=true` bound into voice fields. - Smoke prep with seed `123` produced a clip starting at `305.2523s` with - `tempo_bpm=92.30769`, `beat_seconds=0.65`, `dominant_hz=175`, `root_note=F3`, - and `minor-pentatonic-plus-tritone` scale frequencies from about `174.614` to - `698.457` Hz. Focused worker build and `-Passes 0` swarm prep pass. A - one-candidate score smoke at - `artifacts/parity/song-snippet-score-smoke/smoke-001` now proves ordinary - non-vocal scene patches can score; the first attempt failed because - `song-score` assumed every candidate had a `VocalNetwork` named `voice`, so - primitive timelines are now optional witnesses for song scenes instead of a - required anatomy gate. - -- Ran a three-phase, three-agent song-snippet experiment across different seeded - segments under `artifacts/parity/song-snippet-swarms/20260531T014033022`. - Segment starts were `143.0295s`, `169.7126s`, and `196.3956s`; tempo hints - varied (`200`, `63.82979`, `150` BPM) while register stayed B4-ish with - `dominant_hz=2004.545` and scale frequencies `493.883..987.767`. Best - log-mel cosine climbed from `0.308233` in pass 1 to `0.356515` in pass 2 and - `0.380805` in pass 3. Still not close; the winning evidence is that agents - converged on a reusable scene model: bright FM/formant `alien-lead`, clocked - high-band `dust-hat`, continuous `codec-bed`, and `air-wash-hiss`. Syrinx - narrative lost to boring formant/noise machinery. Report: - `artifacts/parity/song-snippet-swarms/20260531T014033022/experiment-report.md`. - -- User correctly called out that the loose agents learned nothing. The actual - failure was not just weak metrics; the candidate assignment was incoherent. - Families were rotated across targets instead of aligned to phonetic owners: - stop-release candidates landed on vowel/approximant lanes, while `p` got an - oral-pressure tweak despite the evidence naming stop-release ownership as - the weak seam. `tools/run-ipa-trial-loop.ps1` now passes the previous - evaluation path into the hypothesizer, requires `Previous Round Learning`, - requires a `Target-Class Lane Plan`, forbids round-robin family assignment, - and instructs the evaluator to fail class alignment when family/target - assignments do not match phonetic owner classes or explicit transfer-test - mutations. - -- Loose one-round IPA source-golf run completed under - `artifacts/parity/ipa-trial-loops/20260531T001831690` with 25 candidates, - source edits enabled, and focused pre-score build passing. The external agent - did not edit tracked source and chose `Source Edit Decision: none`, which is - acceptable evidence: the round found value-sweep pressure, not a repeated - DSL/Faust owner failure. Metrics did not improve: seed logMean `0.42306004` - vs loose logMean `0.41700276`, artMean stayed flat around `0.181`, - rmsMean dropped from `0.48316268` to `0.445383`, releaseMean dropped from - `0.06991132` to `0.06348304`, and radiationMean rose slightly from - `0.27946476` to `0.28285928`. The useful lesson was harness coherence: the - evaluator incorrectly judged `hypothesis-agent.md` instead of the actual - full report `hypotheses.md`, and the scene-voice prompt allowed prose-only - background modeling. `tools/run-ipa-trial-loop.ps1` now names - `hypotheses.md` as the report of record and requires at least one - scene/noise or recording-condition family to add actual auxiliary `.aqua` - `voice` declarations while preserving the primary articulatory vocal network. - -- Expanded the IPA trial-loop agent contract so future rounds can golf DSL - syntax, lowering, and Faust machinery when the evidence says the owner is - wrong. `tools/run-ipa-trial-loop.ps1` now gives source-edit-enabled - hypothesis agents authority to edit `src/`, `tests/`, `docs/`, and `tools/` - for named DSL/lowering/Faust/worker evidence hypotheses, requires a - `source-change-plan.md` with owner map, invariant, expected movement, - verification, and rollback trigger, and runs a focused test-project build - before scoring if source edits were allowed. The prompt also requires a - `Scene Voice Model` for every family: primary articulatory voice, tract-noise - voice, release/transient voice, background-room voice, and - recording-condition voice, with ordinary AquaSynth voices/noise/FM/AM/ - envelopes/filters/formants/additive/spectral primitives available for helper - scene voices. Helper voices remain full-parity tools and cannot count as - articulation unless primitive/gesture/clean-vocal witnesses move too. - -- Added primitive timeline facts to IPA trial results as first-class CultCache - evidence. `IpaTrialResult` now stores extracted `PrimitiveTimelineFact[]` - values from `ProbeTimelineReport`: contact opening/closed blocks/reservoir - peak/release peak/release block, source load pressure and flow peaks, branch - admittance/exchanged flow, radiation boundary/output peaks, path area/delay, - energy, and passivity ratios. `IpaTrialWorker search/show/dump` indexes and - reports those facts alongside metrics and artifact snippets, and trial - summary CSVs now include release/radiation/passivity columns. Verified with - a one-candidate smoke under - `artifacts/parity/ipa-timeline-fact-smoke/20260531T233217641`: stored facts - include `contact_closed_blocks=12`, `contact_release_peak=0.020328`, - `contact_release_peak_block=11`, `radiation_output_peak=0.008015`, and - `path_passivity_max=1`. Qdrant/Ollama search for stop release/radiation - evidence returned through the vector organ with `release-facts` and - `passivity-facts` tags. - -- Upgraded the IPA trial retrieval organ from lexical metric search to a - Qdrant/Ollama vector index modeled after VoidBot. `IpaTrialWorker search` - now builds evidence chunks from each `IpaTrialResult`, includes metric text, - hypotheses, evaluations, known lies, timing receipts, and local artifact - snippets such as `.aqua`, timeline CSV, markdown, text, and DSP files, embeds - them through local Ollama `qwen3-embedding:0.6b`, stores them in Qdrant - collection `aquasynth_ipa_trial_results`, and returns vector-backed markdown - search reports with vector scores, evidence tags, metric facts, contrast - candidates, excerpts, and `show` commands. Qdrant is derived from the `.cc` - store, not a second truth. Verified against the live Docker Qdrant and local - Ollama server on - `artifacts/parity/ipa-trial-worker-smoke/20260529T2204/ipa-trial-results.cc`: - explicit index wrote 25 chunks with 1024-dim vectors, and stop-closure search - returned through `qdrant-ollama`. The trial loop now runs `index` before and - after each round's scoring boundary, then passes `--skip-index true` to agent - searches so the agents query fresh vectors without re-embedding on every - receipt. -- Retrieval tuning smokes found two gremlin-feeding flaws: generic - weak-articulation language could pull off-class records into class-specific - searches, and mixed target-set records could match every class because their - target contains `a/m/s/p/u`. The live ranker now adds class-affinity scoring, - candidate-specific ownership for mixed lanes (`mix-p` is stop, `mix-a/u` are - vowel, `mix-m` is nasal, `mix-s` is fricative), demotes mixed/generalization - to a secondary transfer hint when a real class is present, and only labels - dressing when the record text actually mentions dressing/FM/AM/envelope/helper - evidence. Search reports now expose `class_focus` and per-hit `class_match`. - -- Ran five IPA prompt-optimization passes against the external trial-loop - agent prompts. Pass 1 produced useful seam science but treated fallback file - reads as evidence after `dotnet run` failed. Pass 2 proved live search/show - receipts could work but showed retrieval wandering eats the turn. Pass 3 - showed capped live retrieval was still too slow for prompt iteration through - external `codex exec`. Pass 4 exposed an incoherent "do not run commands" - boundary because the agent could neither read receipts nor write a report. - Pass 5 succeeded with a fixed six-receipt packet and a reasoning-only - boundary, producing sharper seam evidence: stop release ownership, voicing - loudness leak, fricative place collapse, mixed-set contamination, and - single-candidate optimizer ownership. Production prompts now require contrast - pairs, `show` metric values, primitive timeline excerpts or explicit - `missing`, class-consistent reference matrices, `X owns Y so Z remains true` - owner sentences, at least five micro-sweep perturbations before a seam is - actionable, and a novelty gate that rejects loudness/dressing-only families - as loss-landscape novelty. - -- Added the external IPA trial loop as a real worker boundary instead of an - in-chat report shuffle. `tools/IpaTrialWorker` now exposes `seed`, `score`, - `search`, `show`, and audit-only `dump` commands over a shared - `ipa-trial-results.cc` CultCache store. `search` is the semantic retrieval - organ for agents: it expands speech/control vocabulary and ranks records with - metric-aware evidence bias; `show` drills into one trial. `score` renders - agent-authored `.aqua` candidates through - `IpaTrialOrchestrator.RunCandidateScriptsAsync` and upserts new typed trial - results. `tools/run-ipa-trial-loop.ps1` now runs five external Codex rounds by - default, each asking for a batch across five five-phoneme target sets rather - than one-off patch golf; the script rejects a round before scoring unless it - contains at least one candidate for every target lane. -- Active IPA exploration shape: vowels `a/i/u/e/o`, - nasals/approximants `m/n/ng/l/r`, fricatives `s/z/f/v/th`, stops - `p/b/t/d/k`, and mixed generalization `mix-a/mix-m/mix-s/mix-p/mix-u`. - Agent patch files must be named - `____.aqua` so the scorer can bind them - to target/reference lanes and the evaluator can group hypothesis families. - Full-patch dressing remains allowed, but evaluator reports must say when it - is compensating for failed primitive or gesture evidence. -- Verification so far: `dotnet build tools\IpaTrialWorker\IpaTrialWorker.csproj - --disable-build-servers -p:UseSharedCompilation=false - -p:BuildInParallel=false -v minimal` passes; `IpaTrialWorker search` returns - ranked evidence from - `artifacts/parity/ipa-trial-worker-smoke/20260529T2204/ipa-trial-results.cc`; - `tools\run-ipa-trial-loop.ps1 -Rounds 0 -SkipLocalTrialRun` creates a loop - skeleton. Need final focused tests and optionally a one-round external Codex - smoke if time/tooling allows. -- Prompt QA pass: ran three dry single-turn external Codex smoke probes for - both hypothesizer and evaluator prompts under - `artifacts/parity/ipa-prompt-smoke/pass-{1,2,3}`. The refinements removed - contradictory count/name instructions, hardened candidate naming to - `____.aqua`, made family ids lowercase - kebab-case, required exact 25-lane output, added pre-evidence digest and - claim-audit sections, forced semantic-search/show receipts, added evidence - quality ledgers/verdicts for specificity/comparability/falsifiability/reuse, - and made the evaluator fail closed when receipts, target coverage, filename - validation, or family extraction are incomplete. Final script syntax smoke passes with - `tools\run-ipa-trial-loop.ps1 -Rounds 0 -SkipLocalTrialRun`. - -- Implemented the first IPA trial render/scoring orchestration. Core now has - typed `IpaTrialResult` CultCache records plus `IpaTrialResultCultCacheStore`; - Faust now has `IpaTrialOrchestrator.RunAsync`, which generates candidate - patches through `IpaGestureExperiment`, renders them with Faust, compares - spectrogram/articulation evidence against local PT fixture references, writes - WAV/report artifacts, and stores the general trial-result `.cc` database. - The opt-in five-seed run wrote - `artifacts/parity/ipa-trials/20260529T214127955/five-seed-trials`. -- First run showed the pipeline worked but vowels/nasals were effectively - silent despite decent gesture scores. The refinement was architectural: - primitive `SourcePort` Faust lowering now emits an oscillatory voiced carrier - tied to the network frequency, instead of feeding mostly DC pressure into a - high-passed radiation load. Seed patch defaults now use stronger clean - primitive source flow. Second run moved the intended layer: open `a` - log-mel cosine `0.5693`, `m` `0.5199`, `s` `0.5498` with articulation - `0.4111`; plosive `p` remains weak at `-0.1024`, pointing to closure/release - ownership rather than source loudness. -- Verification: opt-in - `IpaTrialOrchestratorWritesFiveSeedTrialsWhenEnabled` passed with Faust - installed; focused - `PatchScriptTests|IpaTrialResultsRoundTripThroughCultCache` pass 94/94. - -- Added the first scalable IPA gesture experiment harness. - `IpaGestureExperiment.WriteRound` writes a frozen round bundle with - `manifest.yaml`, candidate `.aqua` scripts, primitive timeline CSVs from - `ProbeTimelineReport`, gesture-layer `metrics.csv`, and per-candidate - `evidence.jsonl`. `IpaGestureExperiment.AnalyzeRound` writes - `analysis/metric-summary.csv`, `analysis/candidate-clusters.csv`, and - `analysis/science-brief.md` for the science-worker handoff. The harness - scores only descriptor/spline/primitive evidence (`surface_coverage`, - `motion_direction`, `contour_timing`, `primitive_timeline`, - `gesture_score`) and explicitly does not own clean vocal identity, full - spectrogram parity, optimizer checkpoints, or worker orchestration. - Verification: `PatchScriptTests` pass 93/93. - -- Documented the IPA training scoring contract. Gesture score is measured at the - descriptor/spline/primitive-timeline layer using coverage, direction, - contour/timing, primitive consequences, and optional external articulation - evidence. Training reports must keep `gesture_score`, `clean_vocal_score`, - and `full_parity_score` separate; full parity may use all AquaSynth synthesis - tools and recording-condition helpers, but cannot count as articulation - evidence unless the lower-layer scores also move. - -- Added the first IPA/anatomy gesture DSL layer. `phoneme_gesture` accepts - known IPA symbols or explicit descriptors like - `descriptor=voiceless_labial-velar_fricative`, maps place/manner/voicing to - the primary anatomical surfaces, and emits ordinary `ControlSpline`s. This is - deterministic seed material for local dataset golf, not a claim that IPA - labels contain exact numeric targets. Patches remain free to use normal - FM/AM/modulators/envelopes/filters around the anatomical control stream. - Verification: `PatchScriptTests` pass 92/92. - -- Public gesture API pass implemented. `ControlSurfaceCatalog.FromPatch(patch)` - is the host-facing discovery surface for normalized controls; hosts can create - `ControlSplineTimeline`, edit future points, and call `ControlValuesAt(t)` to - stream ordinary surface controls into Faust without recompiling. Native Faust - compiled patches now expose `AquaSynthCompiledPatch.ControlSurfaces` and a - safe `ControlValuesAt(timeline,t)` helper that filters the semantic timeline - to UI zones actually exported by the optimized DSP. Verification: - `PatchScriptTests` pass 91/91 and `NativeFaustRuntimeTests` pass 5/5. - -- Implemented the gesture/timeline owner cut for primitive vocals. - `ControlSurface` now exposes normalized runtime controls for primitive fields, - and `ControlSpline` owns linear/hold/Bezier motion over those surfaces. - Primitive Faust lowering maps effective normalized surface values back into - physical fields; explicit old `@/param` bindings remain base controls so PT - fixture controls are not bypassed. `ControlSplineTimeline` supports future - point edits for realtime clients. -- `tract_motion` now adapts velopharynx motion into a branch-opening - `ControlSpline`. A generated contact-opening spline was tested and deleted: - PT timeline evidence showed the obstruction was already closed at block zero, - so an invented open-then-close contact story was a compensator. Contact - closure should come from articulator/area ownership, not local contact slew. -- Verification for this cut: `PatchScriptTests` pass 90/90. Focused primitive - timeline artifact test passes and writes - `artifacts/parity/primitive-vocal-timeline/20260529T185955965`; summary: - open-vowel 0.267624, front-vowel 0.246432, nasal-vowel 0.223792, - bilabial-nasal-ma 0.226266, sibilant 0.177032, closure-release 0.155925. - -- First primitive vocal teardown cut implemented. `AreaFunction`, - `WaveguidePath`, `SourcePort`, `ConstrictionContact`, `BranchPort`, - `RadiationLoad`, `ProbeTimeline`, and `VocalNetwork` are model records with - parser commands. PT-shaped `tract` authoring now adapts into those primitive - records instead of generating `voices_0_area_*`, `voices_0_contact_*`, or - `voices_0_inj_*` acoustic banks. The obsolete - `EnsureTractAcousticNetwork` generator was deleted. -- Faust lowering now prefers a compact primitive path for `Voice.VocalNetwork`: - one semantic path variable per tube using `de.fdelay*` delay families, named - primitive source/contact/branch/radiation locals, and debug probes under - `/debug/voice_0/path|source|contact|branch|radiation/...`. Explicit - `AcousticPortNetwork` scripts still exist as a lower-level lab surface. -- `ProbeTimelineReport` writes deterministic primitive samples as - `block,primitive,signal,value`; current fields include path area/delay, - source load pressure/flow, contact opening/resistance/reservoir/released - flow, branch admittance/exchanged flow, and radiation reflection, - boundary_flow, flow, and output. Passivity/energy samples and PT/SndKit - timeline comparison are next. -- Verification for this cut: - `dotnet build tests\AquaSynth.Dsl.Tests\AquaSynth.Dsl.Tests.csproj --no-restore --disable-build-servers -p:UseSharedCompilation=false -p:BuildInParallel=false -v minimal` - passed. Focused primitive/tract/fixture tests passed: 8 tests covering the - new primitive DSL, PT tract adapter, primitive timeline, and fixture demotion - away from generated graph banks. - -- Second primitive evidence cut in progress: path telemetry now includes - `incoming_wave`, `outgoing_wave`, `energy_in`, `energy_out`, and - `passivity_ratio` in both Faust debug probes and `ProbeTimelineReport`. - Contact telemetry now includes `resistance`. Added - `PrimitiveReferenceReport.ComparePinkTrombone`, which compares static - primitive geometry/delay/branch/contact/radiation fields against PT/SndKit - fixture controls without requiring native reference binaries. `PatchScript` - tests pass 86/86 after this cut. -- Third primitive evidence cut in progress: `PinkTromboneReferenceRenderer` now - has `RenderTimeline`, exposing PT internal timeline samples from the renderer's - own diameter/wave/reflection/transient arrays. `PrimitiveReferenceReport` - can role-normalize Aqua primitive timeline samples against PT timeline samples - for oral/nasal path, velopharynx branch, obstruction contact, and lip - radiation signals. `PatchScript` tests pass 88/88. -- Added `PinkTrombonePrimitiveTimelineComparisonWritesArtifacts`; it writes - per-fixture `aqua-primitive-timeline.csv`, `pt-internal-timeline.csv`, - `comparison.csv`, and `summary.txt` under - `artifacts/parity/primitive-vocal-timeline/`. Focused artifact - test passes. -- First comparison-driven law correction: `SourcePort` now owns `FlowScale` - (default `.02`) instead of primitive source flow silently emitting unit-scale - waves; primitive radiation reflection now reports/uses declared - `RadiationLoad.Reflection` instead of aperture-modulating the coefficient; - `ProbeTimelineReport` radiation flow now uses the path outgoing wave, matching - the Faust law. New artifact `20260529T155613895` drops suite mean absolute - timeline error from roughly `1.2-1.3` to `0.15-0.27`. Remaining obvious drift - is branch/contact dynamics, which raises a real owner question: gesture slew - inside ports or separate gesture/timeline primitive. - -- Proprioception correction after user rejected baby-word golf as the rebuild - owner. Diagnosis is now durable in - `docs/acoustic-graph-proprioception.md`: collapse generated graph-vocal - lowering into a small set of instrumented physical primitives, compare - primitive/sample-flow behavior against VTL, ArtiSynth, Story/TubeTalker, - Smith/Faust, and PT/SndKit, then return to utterances as downstream - witnesses. Next implementation pass should map current records/Faust locals - onto `AreaFunction`, `WaveguidePath`, `ScatterJunction`, `SourcePort`, - `ConstrictionContact`, `BranchPort`, `RadiationLoad`, and `ProbeTimeline`. - -- Implemented the first graph-owned closure reservoir cut. Contact terminals no - longer contribute through the generic node source sum. Ordinary two-port path - scatter now emits per-contact closure, reservoir drive, reservoir, release, - and out probes, and injects the release directionally into the same path - scattering law (`0.80` downstream, `0.20` upstream). This is the research - supported move: closure pressure enters the traveling-wave path instead of - acting as an output click or generic source gain. -- Latest opt-in thrombosis probe after the cut: - `artifacts/parity/pink-trombone-graph-thrombosis-probes/20260529T021934812`. - Key peaks: lip contact closure `0.936876`, contact reservoir drive - `0.519667`, contact reservoir `6.024680`, contact release `0.485894`, - contact out `0.548231`, lip radiation flow `0.581880`, lip radiation - admittance `0.710362`, modal source out `1.233802`, modal flow `0.771656`, - sibilant/injection area 34 out `0.099287`. Previous contact out was about - `0.032413`; the closure event now reaches the graph/radiation path. -- Latest utterance diagnostic: - `artifacts/parity/pink-trombone-utterance-logmel/20260529T022214016`. - The speech verdict is still not accepted. `thrombosis` RMS improved from - roughly `0.0673` to `0.0761`, but cosine stayed about `0.331` and silence - mismatch worsened to `0.7306`. This means the closure cut is structurally - correct but not sufficient. Do not claim speech parity. Next likely owner is - either utterance/radiation output balance or more realistic contact - filtering/active-frame duration; do not hide that under a global gain knob. -- Verification: - `dotnet test tests\AquaSynth.Dsl.Tests\AquaSynth.Dsl.Tests.csproj --no-build --disable-build-servers --filter "ParserSupportsPinkTromboneStyleTractVoice|TractVoiceCanLowerThroughAcousticGraph|FaustCompilerValidatesAcousticPathGraphWhenInstalled" -v normal` - passed: 3 tests. `AQUASYNTH_RUN_GRAPH_PROBES=1 dotnet test ... --filter - "PinkTromboneThrombosisGraphDebugProbesWriteTimelineWhenNativeFaustIsInstalled"` - passed: 1 test in 2m09s. `dotnet test ... --filter - "PinkTromboneAcceptedUtterancesReportGraphLogMelParityWhenFaustIsInstalled"` - passed: 1 test in 2m25s. Minimal verbosity sometimes exits silently on the - long native render path; normal verbosity produced passing runs. - -- Added graph-native debug probes for vocal source internals when - `DebugProbeUi` is enabled: tissue-valve pressure drive, modal tissue, - aperture, flow, and output; turbulence-source reservoir/release/output; and - contact reservoir/release/output. These are observation only, not audio-law - changes. -- Added opt-in `PinkTromboneThrombosisGraphDebugProbesWriteTimelineWhenNativeFaustIsInstalled`. - It runs only when `AQUASYNTH_RUN_GRAPH_PROBES=1`, compiles the generated - `thrombosis` graph through native Faust debug UI, steps the streaming patch - block by block, and writes `candidate-debug.dsp`, `controls.csv`, - `timeline.csv`, and `probe-peaks.txt`. -- Latest probe artifact: - `artifacts/parity/pink-trombone-graph-thrombosis-probes/20260529T011547091`. - Key peaks: modal source out `1.335230`, modal flow `0.791726`, modal pressure - drive `0.741528`, lip radiation flow `0.337191`, lip radiation admittance - `0.710362`, sibilant/injection source at area 34 out `0.099288`, lip contact - release out `0.032413`. The graph is not dead. The current failure is not a - missing generic `drive` knob or a silent source; it is weak articulation and - output balance after graph/radiation scaling, with contact release still - small and localized. -- No acoustic-law cut was made from this evidence. Next real change should use - the probe timeline to decide whether to promote contact/closure into the - scattering law or adjust the utterance harness/radiation output owner. Do not - hide the finding behind a broad gain tweak. -- Verification: - `AQUASYNTH_RUN_GRAPH_PROBES=1 dotnet test tests\AquaSynth.Dsl.Tests\AquaSynth.Dsl.Tests.csproj --no-restore --disable-build-servers -p:UseSharedCompilation=false -p:BuildInParallel=false --filter "PinkTromboneThrombosisGraphDebugProbesWriteTimelineWhenNativeFaustIsInstalled|FaustCompilerValidatesAcousticPathGraphWhenInstalled" -v minimal` - passed: 2 tests in 2m01s. Default focused diagnostic without the env var also - passed with the probe test returning immediately. - -- PT utterance diagnostic crash recheck: the focused test is reproducible as - slow but passing when stale child `dotnet` processes are cleared and the test - is run with enough wall-clock budget. Fresh verified artifact: - `artifacts/parity/pink-trombone-utterance-logmel/20260529T005420700`. - Per-utterance render timing now writes `render.txt` beside each candidate - before/after the Faust render path: `mama` ~31s, `papa` ~45s, `thrombosis` - ~59s. The previous two-minute attached shell timeout was not a valid crash - witness. -- Harness/process fix: `PinkTromboneAcceptedUtterancesReportGraphLogMelParityWhenFaustIsInstalled` - now writes `candidate-graph.dsp` and `controls.csv` before rendering, wraps - each external Faust render in a three-minute per-utterance timeout, and writes - stdout/stderr/timing to `render.txt`. `FaustCompiler.RunAsync` now kills the - whole child process tree when cancellation fires, so timed-out `faust` or - nested `dotnet run` work cannot keep poisoning later runs. -- Current acoustic evidence after the source-law cleanup is weakness, not a - loud low-frequency floor: latest utterance RMS ratios are `mama` 0.0876, - `papa` 0.1509, `thrombosis` 0.0673. `thrombosis` still fails the diagnostic - cosine floor with cosine 0.3318. Next vocal work should inspect source-flow - strength/articulation and radiation transfer with debug probes, not restore a - generic `drive` knob. -- Verification: - `dotnet test tests\AquaSynth.Dsl.Tests\AquaSynth.Dsl.Tests.csproj --no-restore --disable-build-servers -p:UseSharedCompilation=false -p:BuildInParallel=false --filter "PinkTromboneAcceptedUtterancesReportGraphLogMelParityWhenFaustIsInstalled|FaustCompilerRendersTissueValveGraphWhenInstalled|FaustCompilerValidatesAcousticPathGraphWhenInstalled" -v minimal` - passed: 3 tests in 2m17s. - -- Research-guided machine cut: graph segment delay no longer clamps physical - segment delay to a full sample. `WaveClockPolicy` now owns the minimum legal - delay: unit grid stays at 1 sample, half-sample grid and first-order Thiran - bottom at 0.5, and Lagrange/crossfaded policies use their documented lower - bound. Generated `tract propagation=graph` now uses `HalfSampleGrid` to match - PT's half-sample Kelly-Lochbaum regime instead of first-order Thiran. -- Rejected experiments in this pass: - - Flipping area-scatter reflection to the literal SndKit/PT sign made - `thrombosis` loud/unstable under Aqua's current port orientation, so the - previous local sign convention remains. - - Adding more high glottal harmonics worsened voiced-band behavior; the - failure is not a missing sparkle source. -- Verification: - `dotnet test tests\AquaSynth.Dsl.Tests\AquaSynth.Dsl.Tests.csproj --no-restore --disable-build-servers -p:UseSharedCompilation=false -p:BuildInParallel=false --filter "TractVoiceCanLowerThroughAcousticGraph|ParserSupportsTypedAcousticPathGraph|FaustCompilerValidatesAcousticPathGraphWhenInstalled|PinkTromboneAcceptedUtterancesReportGraphLogMelParityWhenFaustIsInstalled|PinkTromboneFixturesReportLogMelParityWhenFaustIsInstalled" -v minimal` - passed. Latest utterance artifact: - `artifacts/parity/pink-trombone-utterance-logmel/20260527T133539554`; - `mama` cosine/articulation `0.5982/0.1952`, `papa` `0.8615/0.1979`, - `thrombosis` `0.5217/0.2640`. Latest static artifact: - `artifacts/parity/pink-trombone-logmel/20260527T133424894`. - -- User listening correctly rejected the log-mel witness: `thrombosis` was - mostly silence plus breathy/squeaky bursts, and `papa`/`mama` still read as - phone-vibration buzz. `AudioComparison` now includes articulation diagnostics - instead of letting log-mel cosine own speech parity. -- New `AudioArticulationComparison` fields: envelope cosine, active-frame - ratio, silence mismatch, envelope flux ratio, spectral flux ratio, motor-band - ratio, speech-band ratio, and articulation score. Utterance reports now print - a verdict. Latest artifact: - `artifacts/parity/pink-trombone-utterance-logmel/20260527T130026316`; - all three accepted utterance fixtures are `not-accepted-articulation` with - articulation scores `mama` `0.1930`, `papa` `0.1829`, `thrombosis` `0.1848`. - This is correct: the harness now agrees with the ear instead of laundering - filtered buzz through cosine. -- Verification: - `dotnet test tests\AquaSynth.Dsl.Tests\AquaSynth.Dsl.Tests.csproj --no-restore --disable-build-servers -p:UseSharedCompilation=false -p:BuildInParallel=false --filter "AudioAnalyzerComparesSimpleBuffers|PinkTromboneAcceptedUtterancesReportGraphLogMelParityWhenFaustIsInstalled|PinkTromboneFixturesReportLogMelParityWhenFaustIsInstalled" -v minimal` - passed. - -- Latest graph radiation pass moved articulation authority into the acoustic - boundary instead of the output tap. `AcousticRadiationPort` aperture now - blends boundary reflection between near-closed termination and declared - open-end reflection. Radiation reads boundary flow (`incoming - outgoing`) - and applies a stronger high-pass radiation slope, instead of reading raw - incoming pressure and painting it after the fact. -- Verification: - `dotnet test tests\AquaSynth.Dsl.Tests\AquaSynth.Dsl.Tests.csproj --no-restore --disable-build-servers -p:UseSharedCompilation=false -p:BuildInParallel=false --filter "PinkTromboneAcceptedUtterancesReportGraphLogMelParityWhenFaustIsInstalled" -v minimal` - passed. Latest utterance artifact: - `artifacts/parity/pink-trombone-utterance-logmel/20260527T122757617`; - `mama` cosine `0.5650` RMS `0.3297`, `papa` `0.8613` / `0.1282`, - `thrombosis` `0.4347` / `0.2502`. -- Static parity also passed: - `artifacts/parity/pink-trombone-logmel/20260527T123141625`; - open/front/nasal/ma/sibilant/closure cosine - `0.6088/0.6826/0.6468/0.6153/0.4158/0.6198`. -- The pass improved `mama`/`papa` band shape and made aperture a real graph - impedance control, but `thrombosis` still loses voiced body and stops remain - underpowered. Next pressure is graph-native pressure storage/release around - severe constrictions and nasal/oral branch coupling, not more output color. -- Added a small higher-harmonic brightness term to the reusable glottal source. - Utterance smoke passed under - `artifacts/parity/pink-trombone-utterance-logmel/20260527T123628148`. - Post-flow radiation gain was then recalibrated from `3.0` to `4.0`; `4.5` - was tested and rejected as too close to static soft-clip pressure. - Latest utterance artifact: - `artifacts/parity/pink-trombone-utterance-logmel/20260527T124230804`; - `mama` `0.5712`, `papa` `0.8659`, `thrombosis` `0.4379`. - Static smoke passed under - `artifacts/parity/pink-trombone-logmel/20260527T124311305`. - -- Added time-varying Pink Trombone utterance reference fixtures before any Aqua - utterance metric golf. `PinkTromboneReferenceRenderer.RenderUtterance` - interpolates timestamped `PinkTromboneControlPoint` curves sample by sample, - preserving the existing PT-style waveguide state. -- New fixture set: `mama`, `papa`, `lulek`, and `thrombosis`. Each fixture owns - explicit control points for PT frequency, intensity, tenseness, tongue - index/diameter, constriction index/diameter, turbulence, velum, lip opening, - reflections, gain, and burst. These are first-pass pronunciation sketches, - not accepted references until user listening approves them. -- `PinkTromboneUtteranceReferenceTests.PinkTromboneUtteranceFixturesWriteReferenceWavs` - writes PT reference WAVs, `controls.csv`, and `summary.txt` under - `artifacts/parity/pink-trombone-utterances///`. -- Latest artifact set: - `artifacts/parity/pink-trombone-utterances/20260526T205230009`. - Reported PT reference peaks/RMS: - `mama` `0.7033/0.4213`; - `papa` `0.7012/0.3618`; - `lulek` `0.7200/0.4087`; - `thrombosis` `0.7600/0.4658`. - Do not golf Aqua against these until the user has judged whether the PT - reference words are recognizable enough to serve as targets. - -- Golfed the actual graph tract path against the PT log-mel harness after the - playground `Ma` preset sounded like amplified buzzing. The failure was not a - playground-only gain problem: generated graph topology reused velum as both - branch valve and nostril aperture, while closed-nose leakage was carrying too - much oral loudness. -- `EnsureTractAcousticNetwork` now treats velum as branch entrance area - control by squaring the nasal branch terminal opening, while nostril radiation - remains an independent aperture. Graph radiation was then cut from `24.0` to - `3.0` because the previous value was a compensator for the leaky topology and - drove the corrected graph into soft clipping. -- Added a `bilabial-nasal-ma` PT fixture using the playground `Ma` controls, and - fixed PT fixture script generation so intensity/tenseness/glottal reflection - actually reach both `glottis` and `tract`. -- The playground renderer patch gain is now `0.48`, keeping audition renders out - of the clipped-buzz regime while still rendering the actual Aqua DSL/Faust - graph. -- Verification: - `dotnet test tests\AquaSynth.Dsl.Tests\AquaSynth.Dsl.Tests.csproj --no-restore --filter "PinkTromboneFixturesReportLogMelParityWhenFaustIsInstalled" --disable-build-servers -p:UseSharedCompilation=false -p:BuildInParallel=false -v minimal` - passed. Latest graph reports: - `open-vowel` cosine `0.6219` RMS ratio `0.9743`; - `front-vowel` `0.6407` / `1.0024`; - `nasal-vowel` `0.5375` / `1.1476`; - `bilabial-nasal-ma` `0.4743` / `1.2206`; - `sibilant` `0.3233` / `1.0008`; - `closure-release` `0.0817` / `1.5534`. - Focused graph/parser tests and `tools\TractGraphRenderer` build also passed. - Live playground render check after this pass: Open peak/RMS about - `0.498/0.257`; Ma about `0.480/0.243`. - -- Replaced the vocal tract playground's browser-native source/filter witness - with actual Aqua DSL graph rendering. The page now posts the visible controls - to `/render`; `tools/TractGraphRenderer` emits `tract propagation=graph`, - lowers through `FaustEmitter`, renders through `FaustCompiler.RenderAsync`, - writes a WAV under `artifacts/vocal-tract-playground`, and the browser plays - that returned audio. -- The fake JS `createTractSynth` path was deleted so the playground has one - audio authority: Aqua DSL -> Faust graph lowering. The UI is render-on-demand, - not realtime, because recompiling/rendering Faust per audition is the honest - current machine. -- Verification: - `dotnet build tools\TractGraphRenderer\TractGraphRenderer.csproj --disable-build-servers -p:UseSharedCompilation=false -p:BuildInParallel=false` - passed; direct renderer smoke wrote `artifacts\vocal-tract-playground\smoke.wav` - with peak `0.15414488`, RMS `0.066947475`, and no warnings; live server - `POST http://127.0.0.1:5126/render` returned a WAV and `/renders/...wav` - served HTTP 200; `node --check` passed for `app.js` and `serve.mjs`. - -- Added `tools/vocal-tract-playground`, a static WebAudio playground for the - current AquaSynth `VocalTractControlTarget` surface. It exposes the 14 base - voice-patch target controls plus six mel-envelope bands: these are the knobs - the learned speech driver will predict from phonetic and utterance input. - The page draws a tract-ish canvas and includes vowel/noise/nasal presets. -- This is intentionally a touchable control playground, not a claim of - Pink Trombone-class tract physics. The canvas and audio are tied to the real - AquaSynth control names so future renderer work has an inspectable handle. -- Verification: - `node --check tools\vocal-tract-playground\app.js` - and `node --check tools\vocal-tract-playground\serve.mjs`: passed. - Local server `node tools\vocal-tract-playground\serve.mjs` served - `http://localhost:5125/`; browser check rendered the UI, Play toggled audio, - the `Ee` preset moved sliders/visuals, and console errors were empty. - -- Added `MelCepstralWarpEffect` as a real AquaSynth offline/block audio effect: - STFT -> log-mel -> DCT cepstra -> Simplex domain warp -> separable 5-tap - Gaussian blur -> inverse cepstra/log-mel -> original-phase overlap-add - resynthesis. This came from the Mimir bioacoustic decoder work, but the - reusable audio-effect owner is AquaSynth. -- Added focused tests proving the effect preserves length/finite samples and - that warp/blur parameters audibly change output. -- Verification: - `dotnet test tests\AquaSynth.Dsl.Tests\AquaSynth.Dsl.Tests.csproj --filter "MelCepstralWarpEffectTests" -v minimal`: - 2 passed. - -- Tightened CultCache claim receipts into an explicit hazard-light witness - shape. `CultCacheProofTruth.LatestListeningReceipt` is no longer a loose - string; it is now `CultCacheListeningReceipt` with `Subject`, - `TouchedSurface`, `RemainingContamination`, and `WitnessSentence`. -- The default patch/speech claim catalog now carries those fields directly, so - a card names what patch/reference was touched, what surface got exercised, - what still contaminates the claim, and one human/domain witness sentence - about whether the sound bites, blooms, or lies. -- Regenerated `patches/aquasynth-patch-cultcache.cc` from the typed catalog so - the checked-in CultCache artifact matches the new receipt schema. -- Focused tests now assert receipt structure explicitly instead of only checking - that some non-empty string exists. - -- Verification: - `dotnet test tests\AquaSynth.Dsl.Tests\AquaSynth.Dsl.Tests.csproj --filter "CultCachePatchDocumentTests" -v minimal` - -- Added the first distributed speech-training contract: - `SpeechRenderRequest`, `SpeechRenderResult`, and - `SpeechTrainingCheckpoint` are typed CultCache documents in - `src/AquaSynth.Core/SpeechDistributedTraining.cs`. -- `SpeechDistributedTrainingCoordinator` now creates render requests from the - current pipeline, accepts worker-produced score gradients, and applies those - gradients through `SpeechBackpropagationPipeline.TrainSingleFromSynthOutputGradient`. - The current worker proof scores control-vector MSE locally; the ownership - shape is the same as remote compiled-Faust scoring. -- `SpeechDistributedTrainingCultCacheStore` reads and writes request, result, - and checkpoint `.cc` stores through CultLib. No JSON queue, no bespoke - serializer, no trainer pretending to own the renderer. -- New durable CultMesh training constraint: - CultMesh should distribute compiled Faust render/scoring payloads and collect - worker `SpeechRenderResult` gradients, artifacts, timing receipts, and losses. - Workers may witness and compute; they must not mutate model checkpoints. The - authority trainer or one shard-primary trainer applies gradients through - `SpeechBackpropagationPipeline` and commits `SpeechTrainingCheckpoint` - documents through normal CultCache/CultMesh shard authority. -- Verification: - `dotnet test tests\AquaSynth.Dsl.Tests\AquaSynth.Dsl.Tests.csproj --filter "SpeechDistributedTrainingTests" -v minimal`: - 2 passed. - -- Implemented the first CultMesh-distributed speech training step: - Core now references `GameCult.Mesh`, defines `SpeechWorkerPayloadManifest`, - `SpeechWorkerPayloadArtifact`, `SpeechWorkerAdmissionReceipt`, - `SpeechCultMeshWorkerAssignment`, `SpeechCultMeshTrainingStepResult`, and - `SpeechCultMeshRoles.RenderWorker`, and persists payload/admission documents - through `SpeechDistributedTrainingCultCacheStore`. -- `SpeechDistributedTrainingCoordinator.RunCultMeshTrainingStep` now creates - requests, creates a worker payload manifest, admits only peers with valid - CultMesh worker leases, records rejected peers, runs score-only worker - assignments, collects `SpeechRenderResult` gradients, and applies them - centrally through `ApplyResults`. -- This is distributed training via CultMesh lease/admission and typed CultCache - documents. It is not yet real remote process supervision or artifact chunk - transfer; those remain CultMesh infrastructure surfaces. No worker API owns - checkpoint mutation. -- Verification: - `dotnet test tests\AquaSynth.Dsl.Tests\AquaSynth.Dsl.Tests.csproj --filter "SpeechDistributedTrainingTests" -v minimal`: - 3 passed. - -Previous slice: - -- Added a typed CultCache sound-claim document for CultMesh distribution: - `patches/aquasynth-patch-cultcache.cc`. -- Cut the JSON artifact and the local hand-written MessagePack codec. AquaSynth - owns the typed `CultCachePatchDocument` catalog; CultLib owns cache - serialization through `GameCult.Caching.MessagePack`. -- Added `CultCachePatchDocument` record types in Core. The document bundles the - full `patches/library.yaml` patch database with patch claim cards and speech - claim cards, and `CultCachePatchDocumentStore` reads/writes it through real - CultCache APIs. -- Patch claim cards now cover every `ReferenceRebuildCatalog.All()` fixture - patch: the three project-authored Zyn rebuilds and the three DX7 reference - rebuilds. The PRC SYNTH1 calibrated patch also has a claim card because it is - in the patch database as a hard public-domain DX7 pressure target. -- Speech claim cards cover the eSpeak NG tiny workout and the compiled Faust - speech loss surface. Both explicitly name utterance/phoneme source, target - anatomy/profile, intent, tier, proof artifact, listening receipt surface, and - known lies. -- Stock patch database entries are included as database entries, not promoted - to serious claims without references. That preserves the law: sketches may - exist, but parity/pressure/proof claims need named reference and receipt - surfaces. -- Verification: - `dotnet test tests\AquaSynth.Dsl.Tests\AquaSynth.Dsl.Tests.csproj --filter "CultCachePatchDocumentTests" -v minimal`: - 4 passed. - -Previous slice: - -- Reworked the Faust-rendered speech-loss path toward the actual curriculum - machine: `CompiledFaustRenderedSpeechLossSurface` compiles one native Faust - patch with exported `speech/output/N` hslider controls for every neural - mapper output, then renders reference/candidate batches by setting controls - on new DSP instances from the same compiled factory. -- `AquaSynthCompiledPatch` now exposes `ControlPaths` and supports - `Render(IReadOnlyDictionary)`. `FaustNativeToolchain` builds a - C UI glue map from Faust control labels to native zones and writes parameter - values before `compute`. -- The compiled speech probe keeps every mapper output as an exported knob even - when a current simple synth rung does not use the value strongly. The tiny - keepalive term exists for that invariant: topology and control surface stay - stable across curriculum rungs. -- Rendered proof found a real loss-surface hazard: dynamic low-pass cutoff can - exceed Nyquist at lower training sample rates and produce NaNs. The compiled - probe clamps cutoff to `ma.SR * 0.45`. -- Verification: - `dotnet test tests\AquaSynth.Dsl.Tests\AquaSynth.Dsl.Tests.csproj --filter "FaustRenderedSpeechLossSurfaceTests|NativeFaustRuntimeTests|SpeechBackpropagationPipelineTests" -v minimal`: - 6 passed. -- Opt-in native batch proof: - `AQUASYNTH_RUN_FAUST_SPEECH_LOSS=1 dotnet test tests\AquaSynth.Dsl.Tests\AquaSynth.Dsl.Tests.csproj --filter "CompiledFaustRenderedSpeechLossSurfaceReusesOnePatch" -v minimal`: - 1 passed. - -Previous slice: - -- Added the first Faust-rendered speech loss surface. `AquaSynth.Faust` - now owns `FaustRenderedSpeechLossSurface`, which turns a - `VocalTractControlTarget` into an inspectable AquaSynth script, renders it - through Faust, compares rendered log-mel evidence, and estimates - `d(loss)/d(controller output)` with finite differences over selected output - indices. -- Added the missing Core backprop seam without making Core depend on Faust: - `SpeechBackpropagationPipeline.TrainSingleFromSynthOutputGradient` accepts an - external synth-output gradient, updates the synth driver, slices the returned - semantic embedding gradient, and updates the utterance encoder. This is the - handoff a Faust-rendered loss surface needs. -- Added `VocalTractNeuralMapper.TrainSingleFromOutputGradient` and allowed - `PackedNeuralNetwork.TrainSingleFromOutputGradient` to preserve the external - loss value in its result. -- The normal focused tests verify external-gradient backprop without invoking - Faust. The heavier rendered proof is opt-in via - `AQUASYNTH_RUN_FAUST_SPEECH_LOSS=1` because the current renderer recompiles - per finite-difference evaluation. -- Verification: - `dotnet test tests\AquaSynth.Dsl.Tests\AquaSynth.Dsl.Tests.csproj --filter "SpeechBackpropagationPipelineTests|FaustRenderedSpeechLossSurfaceTests" -v minimal`: - 3 passed. -- Rendered proof verification: - `AQUASYNTH_RUN_FAUST_SPEECH_LOSS=1 dotnet test tests\AquaSynth.Dsl.Tests\AquaSynth.Dsl.Tests.csproj --filter "FaustRenderedSpeechLossSurfaceTests" -v minimal`: - 1 passed in about 1m22s. -- Build verification: - `dotnet build AquaSynth.sln -v minimal`: succeeded. -- Current honesty: this is a real Faust-rendered loss surface and a real - backprop seam through both learned models. It is still black-box finite - difference over controller outputs, not analytic differentiation through - Faust DSP. The next coherent performance cut is render/compile caching or a - differentiable proxy that is explicitly trained against Faust, not pretending - recompiling Faust dozens of times is the final supercar. - -Current standing order: grow AquaSynth through external reference -targets, not through speculative field sprawl. `state/spine.yaml` and -`docs/reference-synth-roadmap.md` are the handoff surfaces for agents working on -the synth library while AquaSynth work continues elsewhere. - -Doctrine update: - -- External synths are parity pressure for AquaSynth's DSL, not internals to - clone. Only consume targets that can be backed by parity tests proving - AquaSynth can reproduce the behavior in terse, readable syntax. -- Parsing a synth format is inventory. Rebuilding and testing behavior is the - proof. -- Pinned reference synths are test-only oracles, not AquaSynth organs. ZynAddSubFX - now lives under `external/zynaddsubfx` as GPL development material pinned at - `3ab608c432996ba4d582176572c0b0f82328c825`; it must not enter the NuGet - package or runtime dependency graph. - -Current slice: - -- Organ Choir exposed two separate Zyn PAD authorities that are now mapped: - analog high-pass filters (`HP1`/`HP2`, stages, and FILTER_ENVELOPE motion) - and selected PAD table roots for OscilGen shift-base sources - (`base_function=7`). The root policy is source-driven: normal PAD rebuilds - keep the sample-0 oracle root, while shift-base OscilGen layers may use the - selected note table root when the parity oracle provides it. -- Latest upstream PAD survey after this pass: - `Organ Choir Pad2` artifact - `artifacts/parity/zyn-upstream-pad-fixtures/0008-organ-choir-pad2-20260515T162034810`, - log-mel `0.471483`, envelope `0.302978`, RMS ratio `0.878`, - centroid ratio `1.011328`, score `0.541933`. The violin-vs-wind issue was - kit1 source-table shape: Aqua had ignored Zyn `base_function_modulation=1` - and `adaptive_harmonics=1`, producing a smooth upper harmonic ramp. The - importer now applies base-function phase modulation before DFT and adaptive - harmonic remapping at the PAD table root. -- Direct kit1 table spectrum moved from violin-shaped to wind-shaped: - 400-800 Hz energy is now `0.2713` against Zyn `0.2780`; 8-16 kHz is - `0.1471` against Zyn `0.1355`. -- The accepted fixtures stayed on the sample-0 root path: DoublePadBass - log-mel `0.247674`, score `0.650319`; Ghost Ensemble log-mel `0.369402`, - score `0.57229`; Soft Pad log-mel `0.317897`, score `0.608833`. -- User listening now accepts the recent Zyn PAD fixture batch as reading the - same as the references. Treat the remaining high log-mel values as regression - pressure and diagnostic smoke, not as a mandate to keep sanding sounds that - have already landed perceptually. -- Verification: `dotnet test AquaSynth.sln --no-restore`: 107 - passed. -- Next pressure can leave this Zyn PAD batch and move to the roadmap's next - synth/abstraction rung; keep sin2x and broader OscilGen/PAD source-table - shape as future regression context, not the active treadmill. Do not turn the - base-function-7 selected-root rule into a global selected-table switch. That - was tested and regressed accepted DoublePadBass. - -- Zyn PAD per-preset rebuilds now carry first-class Zyn PAD table semantics - instead of only `spread=0` plus harmonic magnitudes. -- `SpectralBank` owns `PadSpectrumProfile`, including Zyn PAD mode, - bandwidth, bandwidth scale, harmonic profile, and harmonic-position warp. - `PadSynthWaveform` uses the Zyn PAD profile/bandwidth formulas for those - banks and keeps the old generic PADsynth path for ordinary `spectrum`. -- `ZynInstrumentReader.RebuildFirstPadAsAquaSynthScript` now emits readable - neutral `pad_mode=`, `pad_bandwidth=`, `pad_bwscale=`, `pad_profile=...`, - and `pad_position=...` fields, and maps Zyn PAD volume with the source - exponential gain curve instead of the old tiny linear `/500` guess. The - parser still accepts older `zyn_*` aliases for parity artifacts, but authored - `.aqua` should use AquaSynth-native PAD terms. -- The translator now expands a useful subset of Zyn OscilGen base-function - harmonic content plus spectrum adjustment before feeding PAD synthesis. This - is a coherent source-table owner, but current parity is mixed: it improves - Soft Pad and Organ Choir Pad2 log-mel, while sin2x/DoublePadBass/Ghost - regress. Treat it as live pressure on OscilGen coverage, not solved Zyn - oscillator parity. -- Latest focused verification: - `dotnet test tests\AquaSynth.Dsl.Tests\AquaSynth.Dsl.Tests.csproj --no-restore --filter "FullyQualifiedName~ZynInstrumentTests|FullyQualifiedName~ZynReferenceParityTests"`: - 13 passed. -- Latest upstream PAD batch after OscilGen subset: - `Soft Pad` log-mel `0.342738`, score `0.443083`; - `Organ Choir Pad2` log-mel `0.573216`, score `0.434351`; - `sin2x pad` log-mel `0.524421`, score `0.360653`; - `DoublePadBass` log-mel `0.689315`, score `0.226566`; - `Ghost Ensemble` log-mel `0.482155`, score `0.400393`. -- Next coherent cut: either complete more OscilGen semantics - (modulation/waveshaping/filter/adaptive harmonics) or gate the current - approximation to the cases it truly owns. Do not present the mixed OscilGen - subset as passing parity. - -Current follow-up: - -- Reworked Zyn PAD OscilGen partial extraction into a sampled stage-order - pipeline for presets with live oscillator processing: base waveform, - optional oscillator filter/waveshaper order, modulation, harmonic shift, then - spectrum adjustment. The implementation covers a useful subset of oscillator - filter types and waveshapers instead of pretending base-function convolution - alone is the synth. -- Gated that pipeline so direct harmonic presets remain readable and capped at - 32 partials. This cuts the earlier mistake where base-function-only presets - grew huge partial lists without improving parity. -- Latest upstream PAD batch after this pass: - `sin2x pad` log-mel `0.455193`, score `0.405637` (better than the previous - OscilGen subset's `0.524421`); - `Soft Pad` log-mel `0.342738`, score `0.443083`; - `Ghost Ensemble` log-mel `0.40922`, score `0.421156`; - `Organ Choir Pad2` log-mel `0.664699`, score `0.369231`; - `DoublePadBass` log-mel `0.655288`, score `0.246664`. -- This is still not passing Zyn PAD parity. The likely next missing owners are - full OscilGen filter/waveshape coverage, adaptive harmonics, and note/global - filter/envelope behavior. Do not tune thresholds around these numbers. - -Current user-ear correction: - -- User clarified Soft Pad itself is fine; Ghost Ensemble was the one collapsing - into a Soft Pad-like identity. The bug was our direct-harmonic gate ignoring - Ghost's live `base_function=4` power oscillator because no downstream - oscillator stage was enabled. The gate now expands power-base multi-harmonic - OscilGen sources, restoring Ghost to a 32-partial source. Latest Ghost: - log-mel `0.402789`, score `0.446977`, and the `.aqua` no longer looks like a - two-partial Soft Pad knockoff. -- DoublePadBass exposed a separate ownership bug: the preset is `kit_mode=1` - with two enabled PAD kit items across the full key range. The old parity path - rendered and rebuilt only kit item 0. The upstream PAD test now sums enabled - PAD kit notes and passes per-kit table roots into - `RebuildEnabledPadsAsAquaSynthScript`; generated Aqua emits - `doublepadbass_0` and `doublepadbass_1`. -- Latest DoublePadBass after multi-kit rebuild: log-mel `0.493451`, score - `0.376854`, RMS ratio `0.826864`. Raising the volume cap to `3.0` worsened it - (log-mel `0.521113`, RMS ratio `1.220809`), so the cap was cut back to `1.5`. -- User then identified the remaining DoublePadBass balance issue: Aqua - over-emphasized kit0's high buzz while Zyn's character comes from kit1's low - rumble. The cause was visible Zyn global filter data we were still ignoring: - kit0 has filter `category=0 type=2 freq=12`, kit1 has `freq=61`. Static Zyn - PAD low-pass now maps to layer `lpf`; the helper had to read nested `FILTER` - params, not direct `FILTER_PARAMETERS` children. -- User still heard Aqua as all kazoo, while Zyn was deep bass with a tiny kazoo - overtone. The linear `freq/127` LPF mapping was wrong: Zyn's old filter - cutoff maps through `2^((Pfreq / 64 - 1) * 5 + log2(1000))`. Kit0 - `freq=12` is roughly 60 Hz, not 1.7 kHz; kit1 `freq=61` is roughly 850 Hz, - not 8.6 kHz. -- Latest DoublePadBass after Zyn filter curve mapping: log-mel `0.334546`, - score `0.351535`, RMS ratio `0.464596`, with generated layers - `doublepadbass_0 lpf=0.003325` and `doublepadbass_1 lpf=0.047225`. The - character should now be deep-bass-first; remaining pressure is filter - envelope/level recovery, not more static high-band brightness. -- User still heard Aqua as kazoo-first. The next missing authority was not - brightness but pitch: DoublePadBass PAD frequency params set - `coarse_detune=15360`, and Zyn's `getdetune` wraps octave `15` to `-1`. - Aqua had ignored PAD coarse/fine detune and played both spectral tables at - `261.6256 Hz`; it now emits `freq=130.8128` for both enabled kit layers. -- The same pass added explicit `lpf_order` so Zyn analog `LP2` filters lower to - Faust `fi.lowpass(2, ...)` instead of pretending all low-passes are first - order. Latest DoublePadBass: log-mel `0.259298`, score `0.370218`, centroid - ratio `1.027115`; remaining pressure is loudness/envelope recovery. -- User then heard the tone as right but the Zyn reference hitting harder at the - beginning. The missing authority was Zyn's PAD filter envelope: Aqua had only - the static cutoff, while Zyn adds ADSR-filter octave offsets before the - global filter. AquaSynth now has a general low-pass rate/level envelope - surface (`lpf_env=rl`, `lpf_start`, `lpf_rates`, `lpf_levels`) and the Zyn - importer maps `FILTER_ENVELOPE` into it. Latest DoublePadBass after this - pass: log-mel `0.241993`, envelope distance `0.554658`, RMS ratio `0.456173`, - score `0.404382`. -- User then heard the hit level as right but the attack as less sharp, causing - a blare. The old Zyn envelope time conversion was also wrong: Aqua used - linear `dt/127`, while Zyn's old envelope time is - `(2^(dt/127*12)-1)/100`. DoublePadBass kit0 attack `10` is about `0.00925s`, - not `0.07874s`. The importer now uses Zyn's logarithmic time curve and the - PAD gain cap is relaxed only to `3.0`, not the full raw Zyn volume multiplier. - Latest DoublePadBass: log-mel `0.211646`, envelope distance `0.462822`, RMS - ratio `0.511669`, score `0.450507`. -- User then heard the shape as right but Zyn still peaking quite a bit louder. - The remaining level delta was batch-wide output calibration, not another - DoublePadBass layer issue: latest pre-calibration PAD RMS ratios were - `0.51..0.78`. Generated Zyn PAD rebuilds now emit `patch gain=1.6`. Latest - DoublePadBass: WAV peak `0.979` against clipped Zyn reference peak `1.0`, - log-mel `0.211671`, envelope distance `0.226563`, RMS ratio `0.818669`, - score `0.631168`. -- User accepted DoublePadBass and moved the ear target to Ghost Ensemble: - Aqua over-emphasized upper harmonics and sounded brighter/tinnier than Zyn. - The first missing general authority was Zyn PAD filter note tracking: - `freq_track=97` lowers Ghost's cutoff at C4 by the Zyn - `log2(note/440) * tracking` rule. Aqua now applies that when importing PAD - global filters. -- Ghost still had too much upper tail, so the next cut was not a Ghost-only - brightness knob. AquaSynth now has explicit low-pass Q via `lpf_q`/`lpq` on - the filter model. Zyn PAD analog low-pass `q` imports through - `exp((q/127)^2 * ln(1000)) - 0.9`; Ghost emits `lpf_q=0.499021`, which Faust - lowers through `fi.resonlp(..., max(0.1, lpf_q), 1.0)`. -- Latest Ghost after note tracking + Q: - artifact `artifacts/parity/zyn-upstream-pad-fixtures/0121-ghost-ensemble-20260515T131053271`, - log-mel `0.375637`, envelope distance `0.363075`, RMS ratio `1.09995`, - centroid ratio `1.010727`, score `0.561458`. This improves from the - post-tracking `0.38424` log-mel / `1.155288` RMS ratio, but a table-harmonic - diagnostic still shows candidate h8/h10/higher partials hot against the Zyn - table. Remaining Ghost pressure is OscilGen/PAD source-table shape, not - static filter ownership. -- Latest upstream PAD survey after Q kept the accepted batch intact: - DoublePadBass log-mel `0.247729`, envelope `0.208429`, RMS ratio `0.887621`, - score `0.650069`; Soft Pad log-mel `0.316754`, score `0.6089`. -- User then heard Ghost as closer but still overly bright in the middle. A - Zyn oracle `harmonics` diagnostic was added to `ZynPadReference` so the - exact normalized OscilGen harmonic vector can be dumped before PAD table - generation. That proved Ghost's first 32 imported partial ratios already - match Zyn's OscilGen output; the h8/h10 glare was not a first-page harmonic - extraction bug. -- Two tempting cuts were tested and rejected or narrowed: - using Zyn's 1024-sample OscilGen base table helped Ghost but regressed the - accepted DoublePadBass batch, so it was cut; raising generated OscilGen - partial output from 32 to 64 worsened Ghost, so the readable 32-partial cap - remains. -- The real Ghost middle-brightness fix was filter lowering ownership: explicit - `lpf_q` had accidentally replaced a 4-pole Zyn-style low-pass with a single - Faust `resonlp`, preserving Q but throwing away slope. Faust export now - cascades resonant low-pass stages according to `lpf_order` when `lpf_q` is - present. Latest Ghost: - artifact `artifacts/parity/zyn-upstream-pad-fixtures/0121-ghost-ensemble-20260515T134050872`, - log-mel `0.369402`, envelope distance `0.363685`, RMS ratio `1.054875`, - centroid ratio `1.006808`, score `0.57229`. DoublePadBass remains at - log-mel `0.247748`, envelope `0.208433`, RMS ratio `0.887555`, score - `0.650029`. -- User accepted Ghost, DoublePadBass, and Soft Pad as nigh-indistinguishable - by ear, with Organ Choir still a bit tinny and sin2x still overdoing a high - harmonic. The sin2x issue was a real OscilGen indexing bug, not a fixture - brightness preference: Zyn oscillator filters receive one-based harmonic - indices (`filter(1)` is the first harmonic), while AquaSynth had translated - them through a zero-based index and moved the type-13 spike filter from h2 to - h3. `ZynOscilFilterGain` now preserves Zyn's one-based index, and the - upstream sin2x regression asserts h2 dominates h3 by more than 10x. -- Latest sin2x after the oscillator-filter index fix: - artifact `artifacts/parity/zyn-upstream-pad-fixtures/0002-sin2x-pad-20260515T140540381`, - log-mel `0.479782` (from `0.491437`), envelope distance `0.490113`, RMS - ratio `1.28196`, centroid ratio `0.998145` (from `1.227953`), score - `0.430193`. The wrong overtone placement is fixed: remaining sin2x pressure - is energy concentration/loudness/profile shape, not h3 accidentally wearing - h2's jacket. -- Zyn PAD harmonic profile lowering also now computes the profile amplitude - multiplier coordinate before width scaling, matching Zyn's `origx` - behavior. It was effectively neutral for sin2x because that preset's width is - near full, but the ownership is now faithful to the source formula. - -Completed this slice: - -- Added PAD spectral-cloud syntax attached to named layers: - `spectrum layer=pad_low root=130.8128 spread=.012 partials=1:.07,1.5:.052`. -- The parser preserves each bank as `SpectralBank` model data. `PadSynthWaveform` - now generates each bank as a PADsynth-style FFT table: frequency-domain - harmonic spreading, deterministic random phase, one inverse FFT, and - normalization. Faust export emits that static `waveform`/`rdtable` source - before applying the normal voice treatment path. `root`, `spread`, and - `partials` are authoring-time table shape, not runtime controls. -- Converted the Zyn PAD texture rebuild from individual PAD body voices to two - spectral banks under `pad_low` and `pad_high`; the air/noise layer remains a - normal voice. -- This is not full Zyn PAD engine parity across every harmonic profile, - randomness control, or pitch-zone behavior. It is a source-level FFT - partial-cloud authority for readable PAD rebuilds. -- Focused verification before wavetable replacement passed: - `dotnet test tests\AquaSynth.Dsl.Tests\AquaSynth.Dsl.Tests.csproj --no-restore --filter "FullyQualifiedName~SpectralBank|FullyQualifiedName~ZynStyleReferenceRebuildsParseExportAndDeclarePressure|FullyQualifiedName~BuiltInReferenceScriptsParseAndExportFaust"`: - 4 passed. -- Wavetable replacement verification: - `AQUASYNTH_DX7_PYTHON= dotnet test AquaSynth.sln --no-restore`: - 94 passed. -- FFT table generator focused verification: - `dotnet test tests\AquaSynth.Dsl.Tests\AquaSynth.Dsl.Tests.csproj --no-restore --filter "FullyQualifiedName~SpectralBank|FullyQualifiedName~FaustCompilerValidatesSpectralBank|FullyQualifiedName~ZynStyleReferenceRebuildsParseExportAndDeclarePressure"`: - 4 passed. -- Full verification after FFT table generator: - `AQUASYNTH_DX7_PYTHON= dotnet test AquaSynth.sln --no-restore`: - 94 passed. - -Previous slice: - -- Promoted staged rate/level envelopes to normal voices and layer defaults. - Voice fields now accept `env=rl rates=... levels=... curves=... gate=...`; - the model stores `Voice.RateLevelEnvelope`, and Faust emission uses - `rl4_env` for those voices. -- Converted Zyn PAD texture and vocal-layer rebuilds to use staged envelopes - through named layers. This gives two non-additive targets asymmetric - envelope contour authority without inventing a new parser. -- Arbitrary Zyn free-envelope point curves remain missing pressure. This slice - is the coherent staged-envelope rung, not a free-mode clone. -- Focused verification passed: - `dotnet test tests\AquaSynth.Dsl.Tests\AquaSynth.Dsl.Tests.csproj --no-restore --filter "FullyQualifiedName~LayeredVoiceRateLevelEnvelope|FullyQualifiedName~ZynStyleReferenceRebuildsParseExportAndDeclarePressure|FullyQualifiedName~BuiltInReferenceScriptsParseAndExportFaust"`: - 3 passed. -- Full verification with bundled Python/dexed-py: - `AQUASYNTH_DX7_PYTHON= dotnet test AquaSynth.sln --no-restore`: - 91 passed. - -Previous slice: - -- Added additive harmonic-bank syntax attached to named layers: - `harmonics layer=body root=220 partials=1:.16,2:.075`. -- The parser preserves each bank as `HarmonicBank`/`HarmonicPartial` model - data, then lowers the partials into ordinary voices so Faust output remains - inspectable. -- Converted the Zyn additive lead rebuild from repeated partial voices to two - named banks under `body` and `shine`. -- This is not Zyn ADDsynth parity theater. Phase, bandwidth, oscillator - shaping, and exact free-envelope behavior remain explicit pressure. -- Verified with bundled Python/dexed-py still wired: - `AQUASYNTH_DX7_PYTHON= dotnet test AquaSynth.sln --no-restore`: - 90 passed. - -Previous slice: - -- Added Zyn-driven language golf through `layer` declarations. A layer owns - name, engine tag, optional MIDI key range metadata, default gain, and an - effect-send label, then lowers to ordinary voices for now. -- Converted the three Zyn-style rebuilds to use named layers: - additive `body`/`shine`, PAD `pad_low`/`pad_high`/`air`, and vocal - `air`/`body`/`breath`. -- This is an ownership scaffold, not hidden PAD/free-envelope/effect machinery. - Future additive-bank, PAD-source, free-envelope, and formant-motion syntax - now has somewhere coherent to attach. -- Verified with bundled Python/dexed-py still wired: - `AQUASYNTH_DX7_PYTHON= dotnet test AquaSynth.sln --no-restore`: - 88 passed. - -Previous slice: - -- Hardened `ZynInstrumentReader` against the real upstream Zyn instrument bank: - it now tolerates leading whitespace before XML declarations and counts only - actual `FORMANT_FILTER`/`FILTER` blocks instead of all internal formant/vowel - nodes. -- Added `ZynInstrumentSurvey` to rank `.xiz` directories by feature pressure. - The non-vendored upstream bank scan parsed `1358/1358` files at - `zynaddsubfx/instruments` commit `e9f64a9`. -- Added `docs/zynaddsubfx-pressure-survey.md`. Worst observed target: - `olivers-100/0032-Drum Kit.xiz` with 16 enabled kit items, mixed ADD/SUB/PAD - engines, 106 envelopes, 25 free envelopes, 73 LFOs, 37 filters, and 3 formant - filters. -- Survey conclusion: named kit/layer routing should probably precede syntax - golf for additive banks, PAD sources, or formant motion. -- Verified with bundled Python/dexed-py still wired: - `AQUASYNTH_DX7_PYTHON= dotnet test AquaSynth.sln --no-restore`: - 86 passed. - -Previous slice: - -- Added first Zyn-style AquaSynth rebuilds for the project-authored additive - lead, PAD texture, and vocal/formant layer fixtures. They live in - `BuiltInScripts` and `ReferenceRebuildCatalog.ZynRebuilds`. -- The rebuild tests parse/export every Zyn script and compare matched feature - claims against source fixture features where the same feature name exists. -- Current missing abstractions from this first Zyn pass: terse additive - harmonic-bank syntax, a PAD/spectral source authority, free envelopes for - normal voices, named kit/layer routing with per-layer effect sends, and richer - formant/vowel morphing. No new runtime surface was added yet. -- Verified with bundled Python/dexed-py still wired: - `AQUASYNTH_DX7_PYTHON= dotnet test AquaSynth.sln --no-restore`: - 83 passed. - -Previous slice: - -- Started the ZynAddSubFX phase and stopped treating DX7 as the active trench. -- Added `ZynInstrumentReader` for `.xiz`-shaped XML. It reads plain XML and - gzip-compressed XML, extracts instrument metadata and kit items, and emits - neutral `ReferencePatch` features. -- Added project-authored Zyn fixtures under - `tests/AquaSynth.Dsl.Tests/Fixtures/ZynAddSubFX/ProjectAuthored` instead - of vendoring upstream preset-bank files with unclear root provenance. -- Current Zyn classifier detects active ADD/SUB/PAD engines, enabled kit items, - layering, envelopes, free envelopes, LFOs, filters, formant filters, and - effects. This is inventory for choosing rebuild targets, not translation yet. -- Verified with bundled Python/dexed-py still wired: - `AQUASYNTH_DX7_PYTHON= dotnet test AquaSynth.sln --no-restore`: - 81 passed. - -Previous slice: - -- Addressed the remaining `ANLGSYN 1` beat as DX7 pitch-LFO pressure, not - amplitude-LFO pressure. Raw `analog1.syx` bytes show `AMD=71` but every - operator has `AMS=0`; the active path is `PMD=32`, `PMS=1`, sine LFO speed - `38`, and delay `33`. -- Added first-class operator-graph vibrato syntax: - `opgraph ... vibrato= vibrato_hz= vibrato_delay=`. - Faust lowering modulates the graph frequency with a faded LFO onset instead - of a hard delay gate. -- Lowered DX7 pitch LFO for the public-domain probe through that graph vibrato - surface. Latest `ANLGSYN 1` metrics with the beat present: score `.697885`, - log-mel `.19496867`, envelope `.15124573`, zero-crossing `.9430519`. -- Tested and cut the earlier operator-tremolo direction for this target. It was - the wrong authority because ANLGSYN's operator `AMS` values are all zero. - -Previous slice: - -- Reframed the latest ear report as envelope pressure, not harmonic pressure: - `{ Mooger }` needs a more aggressive attack contour; `MELLOWSOLO` needed a - smoother captured tail; `RES SYNTH1` still has a phase-like attack-modulation - issue even though oscillator sync is enabled. -- Extended only the `MELLOWSOLO` pressure render from `1.0s` to `1.25s` so the - existing `0.6s` release after a `0.65s` gate is not chopped by the artifact - boundary. Latest pressure metrics improve to score `.5722256`, log-mel - `.3472474`, RMS `.9883968`. -- Tested and cut a global traced-release-duration change. It shortened releases - too aggressively and broke PRC, `Piano Bass`, `RES SYNTH1`, and `ANLGSYN 1`; - release duration remains part of the broader DX7 envelope model pressure. -- Verified with bundled Python/dexed-py: - `AQUASYNTH_DX7_PYTHON= dotnet test AquaSynth.sln --no-restore`: - 76 passed. - -Previous slice: - -- Listening split the latest community set again: `Piano Bass` is currently the - anchor and should not be disturbed; `ANLGSYN 1` and `RES SYNTH1` were blowing - out into drone at the modulator peak; `{ Mooger }` and `MELLOWSOLO` still - have overtone-emphasis issues. -- Added scoped modulator peak headroom in the DX7 probe lowering: - algorithm-2 non-carrier applied envelopes cap only Level1 at `.92`. - `Piano Bass` remains unchanged; `RES SYNTH1` improves to score `.8140223`, - log-mel `.12369786`, envelope `.06489321`; `ANLGSYN 1` keeps log-mel - `.19461302` and sustained high-band evidence but aggregate score drops to - `.6980632`, so its score gate is now `.69`. -- `MELLOWSOLO` nudges to log-mel `.42906323`, score `.55206907`, but remains a - pressure artifact, not passing parity. -- Tested and cut a wider summed-route headroom rule for `{ Mooger }` - (`5.25`/`5.75` for three-source sums). It worsened Mooger log-mel/envelope - and does not deserve to live. Mooger's "too hard" harmonics remain unresolved - overtone-emphasis pressure, not a solved high-band-energy problem. -- Focused verification with bundled Python/dexed-py: - `AQUASYNTH_DX7_PYTHON= dotnet test AquaSynth.sln --no-restore --filter "Dx7SysExTests|PublicDomainDx7MoogerAndPianoBassMeetRenderedParityWhenInstalled|PublicDomainDx7AnlgSyn1KeepsBuzzingModulationWhenInstalled|PublicDomainDx7MellowSoloWritesPressureWavsWhenInstalled|PublicDomainDx7PrcSynth1WritesListeningWavsWhenInstalled"`: - 28 passed. - -Previous slice: - -- Listening report split the remaining DX7 mismatch: `RES SYNTH1` mostly - needed a harder attack, `ANLGSYN 1` still smells like missing LFO/operator - attack behavior, and `MELLOWSOLO` is the clearest harmonic mismatch. -- Fixed two note-dependent DX7 lowering gaps: - - operator key-scaling now uses the effective played MIDI note after voice - transpose instead of hardcoded MIDI 60; - - `Dx7SysEx.OperatorRateScaling` now feeds - `ApproximateAppliedRateLevelEnvelope`/`TraceInterpolatedEnvelope`. -- Kept graph gain as loudness authority after the scaling change: - `Piano Bass` moved from `.90` to `.72`. -- Added `PublicDomainDx7MellowSoloWritesPressureWavsWhenInstalled`; it writes - listening artifacts but only gates as pressure (`log-mel <= .45`, score - `>= .5`) because it is not passing parity by ear. -- Cut a tempting output-level-dependent envelope trace experiment. It looked - more Dexed-shaped on paper, but worsened `MELLOWSOLO` and `ANLGSYN 1`, so it - does not belong in the live machine yet. -- Focused verification with bundled Python/dexed-py: - `AQUASYNTH_DX7_PYTHON= dotnet test AquaSynth.sln --no-restore --filter "Dx7SysExTests|PublicDomainDx7MoogerAndPianoBassMeetRenderedParityWhenInstalled|PublicDomainDx7AnlgSyn1KeepsBuzzingModulationWhenInstalled|PublicDomainDx7MellowSoloWritesPressureWavsWhenInstalled|PublicDomainDx7PrcSynth1WritesListeningWavsWhenInstalled"`: - 28 passed. - -Previous slice: - -- Corrected DX7 ROM COM handling after user listening caught that the - no-compensation probe had closer harmonics across the community patches and - was mainly too quiet. -- `Dx7SysEx.OperatorOutputCompensation` now returns unity. Loudness recovery - moved to graph gain instead of hidden carrier boosts. -- Community parity gains with COM disabled: - `{ Mooger }` `.75`, `Piano Bass` `.90`, `RES SYNTH1` `.75`. -- `RES SYNTH1` is now in the passing community gate. Latest metrics: - score `.7277295`, log-mel `.1461968`, envelope `.10764466`, RMS `.941083`, - zero-crossing `.1.1022931`. -- `DX1 LEAD B` and `MELLOWSOLO` sound closer by ear with COM disabled and - graph gain restored, but still fail numeric gates. Latest survey: - `DX1 LEAD B` score `.45156077`, log-mel `.43533683`, RMS `.8193191`; - `MELLOWSOLO` score `.5359293`, log-mel `.39420125`, RMS `.99559265`. -- Verified with bundled Python/dexed-py: - `AQUASYNTH_DX7_PYTHON= dotnet test AquaSynth.sln --no-restore`: - 74 passed. - -Previous slice: - -- Fixed the remaining `ANLGSYN 1` drift that listening caught after the - conditional output-clip pass. The old candidate still lost 2.5-5 kHz energy - midway through the note. -- Added `sustainFloor` to `Dx7SysEx.ApproximateAppliedRateLevelEnvelope` and - uses a `.9` floor for max-feedback source operators in the DX7 probe - lowering. This keeps the self-feedback source driving the loop after the - attack instead of sagging into `deeooh`. -- Added a sustained 2.5-5 kHz band-energy parity gate for `ANLGSYN 1`; the old - candidate was around `.175` at the sustained check, while the new lowering is - above `1.0`. -- Raised `Piano Bass` graph gain to `.30`; latest metrics: score `.7552858`, - log-mel `.16204594`, envelope `.06413663`, RMS `.9909909`. -- Fresh `ANLGSYN 1`: score `.7245976`, log-mel `.18460114`, envelope - `.119950555`, RMS `.97143364`, zero-crossing `.97149533`. -- Verified with bundled Python/dexed-py: - `AQUASYNTH_DX7_PYTHON= dotnet test AquaSynth.sln --no-restore`: - 74 passed. - -Earlier slice: - -- Tightened `ANLGSYN 1` after listening caught the `deeooh` failure: the - max-feedback candidate had a better attack but lost sustained buzz midway. -- Added conditional output nonlinearity in the DX7 probe lowering: - `soft_clip=true` only when a voice has DX7 feedback `7` and a self-feedback - topology. PRC stays `soft_clip=false`. -- Fresh `ANLGSYN 1`: score `.70946133`, log-mel `.18456098`, envelope - `.10628832`, RMS `.9816304`, zero-crossing `.8657629`, centroid `.95726264`. -- Fresh PRC after the conditional clip gate: score `.7546429`, log-mel - `.13874851`, envelope `.067291394`, RMS `.99121606`, zero-crossing - `.95325506`. - -Earlier slice: - -- Retuned DX7 max-feedback lowering for `ANLGSYN 1`. Route-index sweeps did not - materially improve the missing high-band buzz; hotter feedback did. -- Changed only feedback value `7` from `.66` to `2.2`. Feedback value `5` - remains `.19`, so the hard PRC target keeps its existing feedback amount. -- Fresh `ANLGSYN 1` with `feedback=2.2`: log-mel `.17553389`, envelope - `.16478956`, zero-crossing `.90904`, centroid `.9519112`, score `.6448498`. - This improves spectral buzz while making envelope/RMS less tidy. -- Band evidence versus the previous fixed-frequency candidate: - - 1.2-2.5 kHz candidate/reference energy: `.008 -> .656` - - 2.5-5 kHz candidate/reference energy: near zero -> `.321` -- Verified with bundled Python/dexed-py: - `AQUASYNTH_DX7_PYTHON= dotnet test AquaSynth.sln --no-restore`: - 73 passed. - -Earlier slice: - -- Fixed DX7 fixed-frequency operator lowering after `ANLGSYN 1` exposed the - missing buzzing modulation. The old lowering treated fixed mode as a fake - note ratio, so fixed carriers op1/op3 became `0.5` ratio against the graph - frequency. Dexed treats fixed mode as absolute Hz. -- Added `Dx7SysEx.FixedOperatorFrequencyHz` using Dexed's fixed-mode - log-frequency formula and changed `OperatorFrequencyRatio` to return - `fixedHz / graphFrequency` for fixed operators. -- Fresh `ANLGSYN 1` candidate now lowers fixed op3 to ratio `.009227` and op1 - to `.007615` against `freq=130.8128`, instead of flattening both to `.5`. -- Added `PublicDomainDx7AnlgSyn1KeepsBuzzingModulationWhenInstalled` with - focused gates. Latest metrics: log-mel `.19427659`, envelope `.14924917`, - zero-crossing `.94662774`, centroid `.9182808`, score `.659334`. -- Verified with bundled Python/dexed-py: - `AQUASYNTH_DX7_PYTHON= dotnet test AquaSynth.sln --no-restore`: - 73 passed. - -Previous slice: - -- Fixed the `Piano Bass` octave bug. The parsed voice has `transpose=12`; the - old generated AquaSynth script hardcoded `freq=261.6256`, so it rendered an - octave too high. `Dx7SysEx.NoteFrequencyHz(midiNote, transpose)` now treats - transpose `24` as neutral and transpose `12` as one octave down. -- `Dx7VoiceProbeScript` now uses the voice transpose for graph frequency and - for the detune note basis. Fresh `Piano Bass` artifact emits `freq=130.8128`. -- Narrowed the community parity gate to the two voices we can currently defend: - `{ Mooger }` and fixed `Piano Bass`. `ANLGSYN 1`, `RES SYNTH1`, `DX1 LEAD B`, - and `MELLOWSOLO` remain pressure, not passing parity. -- Fixed `Piano Bass` metrics: log-mel `.16180529`, envelope `.13544041`, - zero-crossing `.905511`, score `.64267576`. -- Verified with bundled Python/dexed-py: - `AQUASYNTH_DX7_PYTHON= dotnet test AquaSynth.sln --no-restore`: - 71 passed. - -Previous slice: - -- Added `PublicDomainDx7AnalogCommunityVoicesMeetBroadRenderedParityWhenInstalled`, - which renders actual public-domain `analog1.syx` community voices through - Dexed and the current AquaSynth DX7 lowering. Kept four broad parity voices: - `ANLGSYN 1`, `{ Mooger }`, `Piano Bass`, and `RES SYNTH1`. -- The test writes WAVs/reports under - `artifacts/parity/dx7-community-analog1//` and gates log-mel - `<= .3`, envelope distance `<= .16`, and score `>= .5`. -- Latest kept-voice metrics: - - `ANLGSYN 1`: log-mel `.25955316`, envelope `.12271979`, score `.5709625` - - `{ Mooger }`: log-mel `.23776375`, envelope `.07168135`, score `.66662127` - - `Piano Bass`: log-mel `.19985504`, envelope `.14781862`, score `.5205584` - - `RES SYNTH1`: log-mel `.22371109`, envelope `.109231755`, score `.54040927` -- First survey also tried `DX1 LEAD B` and `MELLOWSOLO`; they were excluded - from the passing gate because log-mel and zero-crossing mismatch were too - large. That is pressure, not library stock. -- Verified with bundled Python/dexed-py: - `AQUASYNTH_DX7_PYTHON= dotnet test AquaSynth.sln --no-restore`: - 70 passed. - -Previous slice: - -- Added two split project-authored DX7 algorithm-8 rendered parity probes: - `ProjectAuthoredDx7AlgorithmEightCascadeProbeMeetsParityWhenInstalled` for - `6 -> 5 -> 3`, and - `ProjectAuthoredDx7AlgorithmEightSummedPairProbeMeetsParityWhenInstalled` - for `4 + 5 -> 3`. -- Tightened the existing combined algorithm-8 stack gate now that real metrics - are known. The project-authored probes gate log-mel at `<= .06`; latest real - Dexed run: - - combined stack: log-mel `0.04029555`, score `0.8664546` - - summed pair: log-mel `0.042429477`, score `0.870778` - - cascade: log-mel `0.03811625`, score `0.9157809` -- Project-authored DX7 parity tests now write listening WAVs and reports under - `artifacts/parity/dx7-project-authored//`. These split probes are - intentionally not part of the patch library: they are useful measuring tools, - not pleasant or reusable stock. -- Verified with bundled Python/dexed-py: - `AQUASYNTH_DX7_PYTHON= dotnet test AquaSynth.sln --no-restore`: - 69 passed. - -Previous slice: - -- Added a structured `.aqua` patch library under `patches/` with: - `examples/`, `sfxr/`, `bfxr/`, `808/`, `fm-bell/`, `wobble-bass/`, - `dx7/`, and `advanced/`. -- Added `patches/library.yaml` as the machine-readable index and - `patches/README.md` as the folder contract. The library is development - source material for stock, reference rebuilds, calibration probes, and patch - inspiration, not a shipped package surface. -- Exported the existing built-in/reference catalog into `.aqua` files and added - the calibrated `PRC SYNTH1` hard DX7 candidate at - `patches/dx7/public-domain/prc-synth1-calibrated.aqua`. -- Added a test contract: every `.aqua` under `patches/` must parse through - `PatchScript.Parse` and export Faust, while package-boundary tests keep - `patches/` and `.aqua` files out of the NuGet package. -- Verified with `dotnet test AquaSynth.sln --no-restore`: 67 passed. - -Previous slice: - -- Increased `Dx7SysEx.SummedOperatorModulationRouteIndex` from `1.6` to `6.0`. - This targets the missing harsh stacked-modulation brightness without adding a - generic drive/overdrive knob. The independent project-authored algorithm-8 - summed-stack probe now uses graph gain `.218` and gates log-mel at `<= .12` - with RMS normalization. -- Latest hard `PRC SYNTH1` after stronger stack scale and graph gain `.25`: - log-mel `0.13874426`, envelope distance `0.067291506`, RMS ratio - `0.9912135`, zero-crossing ratio `0.95325506`, centroid ratio `1.1156512`, - score `0.7546445`. -- Added `Dx7SysEx.ApproximateAppliedRateLevelEnvelope`, which traces the - Dexed-style block-interpolated applied EG gain and lowers it into AquaSynth's - curved staged envelope surface, normalized so operator output level remains a - separate authority. -- Retried hard `PRC SYNTH1` with the applied-envelope lowering. Latest focused - run after fixing the peak picker: log-mel `0.17186502` (was `0.24476814`), - envelope distance `0.13057204` (was `0.43700194`), RMS ratio `1.0000212`, - zero-crossing ratio `0.7815517`, score `0.6501268`. -- Listening note resolved: the prior applied-envelope lowering made op2 rise - late (`0.014 -> 0.613`), causing the odd end lilt. The helper now finds the - first near-peak before gate, so op2 hits early and decays - (`0.981 -> 0.843 -> 0.660`) like the traced DX7 applied gain. -- Extended staged operator envelopes with per-segment curves: - `curves=lin,exp,exp,lin`. Linear remains the default, and levels can now - express deliberate transient overshoot above `1` instead of clipping away - the DX7 evidence. -- Added `Dx7SysEx.TraceEnvelope`, a DX7 EG microscope that follows the internal - rate/level state machine closely enough to expose gain and stage over time. -- Added `Dx7SysEx.TraceInterpolatedEnvelope`, which traces the gain actually - applied by Dexed-style operator rendering: one EG sample per 64-sample block, - linearly interpolated across the block. -- Added an envelope comparison artifact test that writes - `artifacts/parity/dx7-envelope-trace/egstep.csv`. The first rows show both - DX7 raw state and applied gain: raw jumps to `2` immediately, while applied - gain ramps from `.03125` to `2` over the first 64-sample block and remains - near `1` around 20 ms. AquaSynth `env=rl` is a different contour entirely. - The artifact now also includes a curved AquaSynth staged-envelope candidate - that tracks the applied-gain contour far more closely. -- Tried adding a first `env=dx7` runtime lowering, then cut it. The trace - matched the Python `graph.py` envelope but not Dexed plugin audio, so the - syntax was not allowed to survive. The durable result is the microscope and - the applied-gain trace, not a half-proven model. - -Previous slice: - -- Added test-only project-authored Dexed patch rendering through - `DexedPyRenderer.RenderPatchAsync`. It builds a `dexed.Patch` from explicit - operator specs and renders it without adding any shipped fixture or package - surface. -- Added an independent project-authored algorithm-8 summed-stack parity test. - This backs the topology-aware route lowering outside the public-domain PRC - patch, so `SummedOperatorModulationRouteIndex` is no longer only PRC-shaped - evidence. -- Cut the attempted DX7 EG exponential level curve again. On an isolated - envelope target, exponential EG levels plus a shorter timing scale improved - shape versus linear levels, but PRC still failed log-mel (`0.2857573` at a - tuned timing scale). The live lowering stays linear for EG levels until an - isolated envelope target passes without harming the hard target. - -Previous slice: - -- Moved the remaining PRC cascaded-route scalar into a topology-aware DX7 route - helper. `Dx7SysEx.OperatorRouteIndex(topology, edge)` now keeps the isolated - two-op route scale (`6.275`) for standalone direct branches and uses the - summed/cascaded scale (`1.6`) for sum edges and direct edges feeding a sum. -- The PRC probe no longer owns any private route-index function. Latest focused - run still passes with log-mel `0.24476814`, score `0.5708394`, RMS ratio - `1.0108943`. - -Previous slice: - -- Added the ratio-detune and algorithm-output-compensation rungs to the DX7 - lowering. `Dx7SysEx.OperatorFrequencyRatio` now applies ratio-mode detune - from the Dexed/DX7 note formula, and `Dx7SysEx.OperatorOutputCompensation` - maps ROM `COM` values relative to the algorithm-32 six-output baseline. -- The PRC probe no longer has a carrier-level scale table. It still has a - fenced cascaded-route constant (`1.6`) for the `op6/op5/op4 -> op3` stack; - that is now named as the next calibration target, not promoted into core - lowering. -- Latest PRC run with detune, COM compensation, graph gain `.39`, and the - fenced cascaded-route probe: log-mel `0.24476814`, score `0.5708394`, RMS - ratio `1.0108943`, zero-crossing ratio `0.7931764`, centroid ratio - `1.1131053`. - -Previous slice: - -- Completed the feedback calibration rung. Isolated Dexed feedback sweeps fit a - nonlinear AquaSynth feedback table: `0, .01, .02, .05, .10, .19, .38, .66` - for DX7 feedback values `0..7`. -- Added `Dx7SysEx.OperatorFeedbackAmount` and moved the PRC feedback lowering - off the old `voice.Feedback * 0.04` constant. PRC barely changed because - feedback value `5` maps to `.19`, close to the previous accidental `.20`. - The win is ownership: feedback scaling is no longer folklore. - -Previous slice: - -- Completed the second calibration rung for isolated two-operator FM. A Dexed - sweep fits full-scale DX7 modulation at about `12.55` radians. Given the - current AquaSynth Faust formula, that maps to an AquaSynth route index of - `6.275` for a full-level modulator. -- Added `Dx7SysEx.OperatorModulationRouteIndex` and a regression test for the - calibrated phase-deviation scale. The hard PRC probe applies that scale only - to the isolated `op2 -> op1` branch; applying it blindly to the cascaded - `op6/op5/op4 -> op3` stack made PRC worse, which confirms algorithm output - compensation is a separate rung. -- Latest PRC run with the carrier curve plus isolated-route calibration: - log-mel `0.2526254`, score `0.44758993`, duration ratio `0.9927914`, RMS - ratio `0.8931149`. The log-mel gate is back to `<= 0.255`. - -Previous slice: - -- Wrote `docs/dx7-calibration-plan.md` and referenced it from memory/spine. - The ladder is now: single-carrier amplitude, two-op modulation index, - feedback scaling, envelope level curve, algorithm output compensation, then - hard PRC replay. -- Completed the first calibration rung. A project-authored Dexed single-carrier - output-level sweep fits `2^((outputLevel - 99) / 8)` for carrier amplitude. - `Dx7SysEx.OperatorOutputAmplitude` now owns that curve, and - `ApproximateOperatorLevel` uses it instead of the old internal-level proxy. -- Added tests for the measured output-level curve. The hard PRC probe now gates - log-mel at `<= 0.26` while the next rung calibrates modulation index; latest - run after the carrier fix: log-mel `0.2562075`, score `0.40430218`. -- Calibration lesson: the old operator level helper was not a harmless - approximation. It made mid-level operators far too loud and let PRC-specific - constants compensate for a broken foundation. Next pressure is route/index - scaling for isolated two-operator FM. - -Previous slice: - -- Reoriented the `PRC SYNTH1` hard probe around the perceptual metric that - matched listening: log-mel distance. The probe now asserts log-mel - `<= 0.255` plus a loose aggregate score floor instead of treating aggregate - score as the main judge. -- Spectral diagnosis showed the Dexed reference has dominant peaks around - `393`, `131`, `524`, and `656` Hz. The prior AquaSynth candidate had too - little `80-160` Hz body when based at `392`, while the corrected DX7 note - basis restored the low body but exposed weak mid harmonic structure and high - centroid/zero-crossing mismatch. -- Current run with bundled Python and Faust: log-mel distance `0.25093183`, - score `0.4135618`, envelope distance `0.3595946`, duration ratio - `0.992578`, RMS ratio `1.0658501`, zero-crossing ratio `0.24567787`, - centroid ratio `1.3291793`. -- Calibration lesson: the hard target is now a spectral calibration problem. - DX7 output/index scaling still needs a real model; aggregate score can move - in the wrong direction while log-mel and the ear move in the right direction. - -Previous slice: - -- Tightened the hard DX7 `PRC SYNTH1` probe from a "writes WAVs" smoke test to - a modest passing parity target: threshold now requires score >= `0.60`. -- The useful cuts were not new syntax. The candidate improved by removing - patch soft clipping, setting the graph base frequency to `392`, and boosting - the `op3` carrier branch to compensate the algorithm-8 output/body balance. - Global detune and per-edge route damping both made the score worse and were - cut. -- Current best run with bundled Python and Faust writes timestamped artifacts - under `artifacts/parity/dx7-prc-synth1//`: score `0.6057491`, - log-mel distance `0.27658066`, envelope distance `0.38489524`, duration - ratio `0.98714787`, RMS ratio `0.9756519`, zero-crossing ratio `1.0458903`, - centroid ratio `1.093785`. - -Previous slice: - -- Added a hard DX7 `PRC SYNTH1` rendered parity probe that writes listening - artifacts when `dexed-py` and Faust are available: - `artifacts/parity/dx7-prc-synth1/reference-dexed.wav`, - `candidate-aquasynth.wav`, `candidate.aqua`, and `report.txt`. -- The probe rebuilds `analog1.syx` voice 17 with readable operator graph syntax - and staged `env=rl` operator envelopes. It asserts a modest hard-target score - floor instead of pretending exact DX7 parity is solved. -- Current run with bundled Python and Faust: score `0.4581856`, - log-mel distance `0.26397973`, envelope distance `0.4109424`, - duration ratio `1.0173812`, RMS ratio `0.61393267`, zero-crossing ratio - `1.1713804`, centroid ratio `1.0978767`. -- Calibration lesson: shortening the naive DX7 EG timing and lowering the graph - base frequency made the candidate much closer. The remaining mismatch is - still gain/timbre calibration, not missing `env=rl` syntax. - -Previous slice: - -- Added staged operator envelopes for operator graphs: - `env=rl rates=.004,.12,.2,.4 levels=1,.7,.25,0`. This gives the DSL a - readable four-stage rate/level contour without infecting the general ADSR - voice envelope model. -- Added `RateLevelEnvelope` to the operator model, parser support for readable - and compact `env=rl` syntax, Faust `rl4_env(...)` rendering, and a DX7 helper - that emits staged envelope script specs from four-rate/four-level operator EG - data. -- Verified the surface structurally and through the render path: - `dotnet test AquaSynth.sln --no-restore`: 53 passed. -- Retried the hard `PRC SYNTH1` probe with direct DX7 rate/level lowering. The - best quick score was only ~0.316, worse than the hand-tweaked ADSR candidate. - The DSL can now express the missing contour shape, but DX7 EG timing/gain - calibration remains the next pressure. - -Previous slice: - -- Added `Dx7OperatorLevelApproximation`, which distills DX7 operator output - level plus key/velocity scaling into a normal AquaSynth `level=`-style value. - This remains DX7 reference-import knowledge, not a generic DSL feature. -- Retried `PRC SYNTH1` with effective levels and envelope tweaks. Static level - mapping alone did not rescue the hard target: quick probes moved from ~0.24 - to ~0.34, and envelope tweaks reached ~0.42. The next missing pressure is - DX7-style operator envelope/gain evolution, not just static operator levels. -- Verified with `dotnet test AquaSynth.sln --no-restore`: 50 passed. - -Previous slice: - -- Tried the harder `analog1.syx` voice 17, `PRC SYNTH1` (algorithm 8). The - initial routed AquaSynth candidate scored badly (~0.23), which exposed a real - missing invariant rather than a threshold-tuning problem. -- Reworked operator feedback emission from a cyclic smoothed self-reference to - a renderable Faust feedback expression using delayed recursion. Added - `FaustCompilerRendersOperatorFeedbackWhenInstalled`. -- Exact DX7 feedback scaling and EG behavior are still not solved, but feedback - no longer makes the Faust render path fall over. -- Verified with `dotnet test AquaSynth.sln --no-restore`: 49 passed. - -Previous slice: - -- Added the first thresholded DX7 rendered-audio parity rebuild: - `BuiltInScripts.Dx7StylePublicDomainMcMm53` maps public-domain - `analog1.syx` voice 13, `MC-MM 5-3`, to a terse AquaSynth sine patch. -- Added `PublicDomainDx7McMm53MeetsFirstRenderedParityThresholdWhenInstalled`, - which renders the DX7 reference through `dexed-py`, renders the AquaSynth - candidate through Faust-generated C#, and asserts score, log-mel distance, - envelope distance, duration/RMS ratios, zero-crossing ratio, and centroid - ratio. -- This is behavioral parity for a simple sine-like rendered voice, not exact - DX7 operator execution. The next DX7 pressure should be a harder voice that - audibly needs the operator graph. -- Verified with bundled Python plus `dexed-py`: parity test passed. -- Verified with `dotnet test AquaSynth.sln --no-restore`: 48 passed. - -Previous slice: - -- Added a public-domain DX7 SysEx fixture from Musical Artifacts artifact 152: - `tests/AquaSynth.Dsl.Tests/Fixtures/Dx7/PublicDomain/analog1.syx`, with - provenance and SHA-256 recorded beside it. -- Added a test-only `dexed-py` reference renderer. It uses - `AQUASYNTH_DX7_PYTHON` when set, otherwise probes `py`, `python`, and - `python3`; if `dexed-py` is absent, the render test returns without turning - optional tooling into a hard dependency. -- Added a `.nupkg` boundary test that packs `AquaSynth.Dsl` and asserts - test fixtures, SysEx banks, and Python helpers are not shipped. -- Verified with bundled Python plus `dexed-py`: the DX7 fixture renders through - Dexed successfully. -- Verified with `dotnet test AquaSynth.sln --no-restore`: 47 passed. - -Previous slice: - -- Added `FaustCompiler.RenderAsync`, which compiles AquaSynth Faust output to - Faust-generated C#, runs it in a temp .NET project, and returns a mono float - sample buffer for analysis. -- Added a render test that proves a generated AquaSynth patch produces non-silent - audio and can be compared through `AudioAnalyzer`. -- DX7 audio parity is still not claimed: the candidate renderer exists, but the - reference side needs Dexed output or a captured licensed fixture. -- Verified with `dotnet test AquaSynth.sln --no-restore`: 44 passed. - -Previous slice: - -- Added `Dx7EnvelopeApproximation`, which lowers a DX7 four-rate/four-level EG - to a labeled AquaSynth ADSR approximation plus gate duration. -- Reference rebuilds now record `operator_envelope_approximation` as matched - pressure and `operator_envelope_exactness` as still missing. -- Doctrine now states that DX7 EG approximation is not exact DX7 envelope - execution. -- Verified with `dotnet test AquaSynth.sln --no-restore`: 43 passed. - -Previous slice: - -- Added field-site parameter binding for readable operator graph authoring: - graph gain/note fields, operator ratio/level/feedback/envelope fields, and - route index fields now accept `@/param`. -- Operator graph Faust emission now substitutes bound parameter expressions at - the exact `/opgraphs/...` field paths. -- Fixed AD operator envelope binding to use `/env/decay` for the second AD - value, matching the ADSR model instead of calling it release by accident. -- Verified with `dotnet test AquaSynth.sln --no-restore`: 42 passed. - -Previous slice: - -- Added a patch-level `Playback` contract for `OneShot`, `Mono`, and `Poly` - playback with Faust MIDI polyphony settings. -- `instrument midi=true polyphony=8` now lowers to Faust's standard - `[midi:on][nvoices:8]` option and `freq`, `gain`, `gate` controls. -- Host/MIDI playback no longer emits per-voice `/voices/0/note/frequency` and - `/voices/0/note/gate` controls; Faust architecture owns allocation. -- Verified with `dotnet test AquaSynth.sln --no-restore`: 41 passed. - -Previous slice: - -- Split note timing from envelope shape. `Note` now owns frequency, one-shot - gate duration, and host/MIDI source; `Envelope` now owns ADSR shape: - attack, decay, sustain level, and release. -- SFXR sustain duration now maps to `Note.GateSeconds`; SFXR punch maps to a - lower ADSR sustain level plus voice gain compensation during import/legacy - parsing. -- Added host note mode for MIDI-oriented patches through stable note frequency - and note gate controls in generated Faust. -- Moved built-in authoring examples off `punch=` and onto `sustain_level=`. -- Verified with `dotnet test AquaSynth.sln --no-restore`: 40 passed. - -Previous slice: - -- Replaced the DX7 algorithm-8 authoring surface with readable operator graph - syntax: `operator`, `route`, and `carrier` declarations. -- Added `env=ad:attack:decay` and `env=adsr:attack:decay:sustain:release` - envelope forms for operator declarations. -- Kept compact `ops=`/`edges=` syntax as parser/interchange scaffolding, but it - is no longer the built-in authoring example. -- Verified with `dotnet test AquaSynth.sln --no-restore`: 36 passed. - -Previous slice: - -- Added a first-class `OperatorGraph` model with operators, modulation edges, - carriers, graph gain, and operator feedback. -- Added `opgraph` patch-script syntax. Example: - `opgraph name=core freq=330 carriers=1,3 ops=6:4:.9,5:3:.8,4:2:.7:.18,3:2:.6,2:1:.75,1:1:.82 edges=6>5:1.1,5>3:.9,4>3:.75,2>1:.85` -- Faust emission now mixes operator graphs alongside normal voices. -- Updated the DX7 algorithm-8 rebuild to use a real operator graph for the - topology. The remaining missing feature is exact DX7 feedback-register timing - and DX7 rate/level envelopes, not graph ownership. -- Verified with `dotnet test AquaSynth.sln --no-restore`: 35 passed. - -Earlier rebuild slice: - -- Added `ReferenceRebuild` and `ReferenceRebuildCatalog` for explicit - reference-target rebuild attempts. -- Added two DX7-style AquaSynth DSL rebuilds: - - `dx7/algo32-additive-organ`: algorithm 32's six-carrier additive shape, - which maps cleanly to six AquaSynth voices. - - `dx7/algo8-bright-pair`: algorithm 8's two-carrier FM shape, which is only - an approximation because the current voice DSL cannot express - `6->5`, `4+5->3`, `2->1`, or operator-local self-feedback. -- Added matched/missing feature records so topology mismatch becomes evidence - instead of being hidden inside prose. -- Verified with `dotnet test AquaSynth.sln --no-restore`: 34 passed. - -Earlier topology slice: - -- Added DX7 algorithm topology metadata for algorithms 1-32 using Ken - Shirriff's reverse-engineered OPS algorithm ROM table. -- `Dx7SysEx.AlgorithmTopology` now exposes carrier operators, modulation - edges, feedback-register writers, direct self-feedback operators, - delayed-feedback targets, and raw ROM steps. -- `Dx7Voice.Features()` now emits `carrier_operators`, - `modulation_edge_count`, `feedback_sources`, and - `self_feedback_operators`. -- Representative tests cover algorithm 8, algorithm 16, and algorithm 32. -- Verified with `dotnet test AquaSynth.sln --no-restore`: 31 passed. - -Earlier slice: - -- Added `Dx7SysEx` records and parsing for DX7 voice edit buffers, packed - 128-byte voices, and packed 32-voice SysEx banks. -- Extracted six operators, envelopes, algorithm, feedback, oscillator sync, - pitch envelope, LFO, transpose, and voice name into neutral DX7 records. -- Added `Dx7Voice.ToReferencePatch` and structural feature extraction so DX7 - voices can pressure the reference model before translation exists. -- Checksum validation rejects bad wrapped SysEx payloads. -- Verified with `dotnet test AquaSynth.sln --no-restore`: 28 passed. - -Parameter slice: - -- Added explicit `PatchParameter` contracts: stable path, label, default, min, - max, step, unit, automation-rate notes, and notes. -- Added neutral `ReferencePatch`, `ReferenceSource`, and `ReferenceFeature` - contracts with provenance/license/hash-ready fields. -- Added `param` script declarations and duplicate parameter path validation. -- Updated Faust emission so declared parameters produce smoothed `hslider` - controls. -- Implemented Option B parameter binding: numeric fields may reference declared - parameters with `@/path`, for example `lpf=@/macro/brightness`. The parser - records an exact field binding such as `/voices/0/filter/lpf` and keeps the - parameter default as the graph value. -- Faust emission substitutes the parameter expression only at the bound field - site. Unbound parameters still emit a warning. -- Verified with `dotnet test AquaSynth.sln --no-restore`: 23 passed. - -Next likely slice: - -- Refine operator graphs with parameter bindings inside graph fields and decide - how host MIDI note age/retrigger semantics should be represented beyond the - current frequency/gate controls. -- Keep tests focused on structure first, then add rendered audio comparison once - the render path is explicit. - -2026-05-31 song-scene evidence slice: - -- `pattern` and `scale` patch-script sugar are live. They create the backing - parameter when needed and lower to hold-loop control curves, giving song - workers Strudel-ish rhythmic/pitch controls without inventing parser magic. -- Song snippet challenges now default to 30 seconds in the swarm harness, can - assign random album sources per agent, and prepare a separate seeded challenge - for each agent. -- `song-prepare` writes target analysis artifacts: - `logmel-spectrogram.csv`, `logmel-band-stats.csv`, `rms-envelope.csv`, - `rms-envelope-autocorr.csv`, and `analysis.md`. -- `song-score` upserts those artifacts into the `.cc` store as typed - `SongChallengeEvidenceDocument` records and adds target metrics plus - `cultmesh://aquasynth/song-challenge-evidence/...` artifact URIs to each - result. Qdrant indexing now creates evidence chunks from those database - records as well as trial summaries. -- Smoke proof: - `artifacts/parity/song-snippet-smoke/cultmesh-evidence/song-trial-results.cc` - has one scored candidate, five target evidence docs, six Qdrant chunks, and a - search hit whose vector chunk is the song challenge analysis report. -- Follow-up fix: full target evidence remains in `.cc`, but Qdrant chunks now - carry bounded excerpts with content hash/size metadata so the semantic organ - does not try to embed multi-megabyte spectrogram CSVs as single documents. -- Full album swarm proof: - `artifacts/parity/song-snippet-swarms/20260531T031003707` completed 3 passes - x 5 agents x 30-second random album clips. Final store has 15 trials; final - vector index has 90 chunks. Best cosine by pass: 0.434277, 0.590958, - 0.502573. Best overall was - `agent_04__shard_vowel_lead__bright_dust_grid_v2`; strongest repeated pattern - is bright formant/vowel lead plus clocked dust/noise grid. -- Listening correction: those clocked dust/noise grids still sit on persistent - broad white hiss. Added `texture`/`noise_texture` DSL sugar so air, dust, - codec, room, and tape/vinyl noise are owned as gated, band-shaped scene - roles. Future agents should not use full-duration raw `wave=noise` beds for - recording color. -- Source corpus widened one folder up: `run-song-snippet-trial-swarm.ps1` - defaults `SourceFolder` to `D:\Music\Reinier\Heyoka` and recursively discovers - supported audio files. Current local corpus is eight tracks across `Gate Code`, - `Mandelbass`, and `Marklar`. - -2026-05-31 paired song-curriculum slice: - -- Corrected the swarm contract: each agent receives two independent song - challenges and must write one patch for each target. The point is not one - blended answer; the point is to train the evidence substrate so a future - zero-shot audio-production agent receives better context from CultCache and - Qdrant. -- The dataset is now explicitly on trial. Patch files, hypotheses, challenge - evidence, metrics, and evaluator/distiller output are curriculum material; - individual patches are sample data and witnesses. -- `run-song-snippet-trial-swarm.ps1` now accepts `-SongsPerAgent`, writes - `agent-XX/target-YY/challenge.json`, expects patches under - `proposed-patches/agent-XX/target-YY`, scores every target separately, and - runs a distillation pass after each swarm pass. -- `IpaTrialWorker distill` writes a pruned `.cc` store plus - `SongTrialDistillationDocument` records summarizing reusable scene roles, - transfer rules, failure patterns, kept trials, dropped noise, and aggregate - metrics. -- Semantic retrieval now indexes distillation documents as chunks linked to - kept scored trial IDs, so the search merge can project distilled lessons into - the next agent context instead of dropping them as orphan curriculum prose. -- One paired-curriculum pass completed at - `artifacts/parity/song-snippet-swarms/20260531T074935298`: five agents, two - targets each, ten scored patches, ten challenge evidence bundles, sixty - Qdrant chunks, and a distilled `.cc` store. All ten verdicts were `pressure`; - best log-mel cosine was `0.502128`, mean `0.377955`, worst `0.27853`, mean - audio score `0.339432`. -- Distillation kept all ten trials and summarized reusable roles as clocked - dust/hat texture plus rubber/sub bass. That is useful but still not victory: - the scene-noise lesson remains that background/recording color must be a - shaped role owner, not static hiss. - -2026-05-31 two-pass song playlist slice: - -- Added per-pass playable playlist output to `run-song-snippet-trial-swarm.ps1`. - Each pass writes `top-scoring-candidates.m3u` and - `top-scoring-candidates.md`, ranked by log-mel cosine over candidates that - actually rendered a WAV. -- Scoring now keeps the swarm alive when an agent writes invalid Aqua syntax: - invalid parse/lowering/render preparation becomes a `render-failed` trial - with `candidate_invalid`/`render_failed` metrics instead of aborting the - curriculum pass. This was forced by an agent writing illegal `wave=pulse`. -- Completed a two-pass run at - `artifacts/parity/song-snippet-swarms/20260531T084455803`. Pass 1 produced - 10 trials, 8 playable candidates, best cosine `0.386098`, playable mean - `0.220027`, and 2 render-failed syntax casualties. Pass 2 used distilled - pass-1 evidence, produced 10 playable candidates, best cosine `0.502435`, - mean cosine `0.352907`, and 8 pressure verdicts. - -2026-05-31 song instrument-owner correction: - -- User clarified the "8-bit distress signals" problem is the procedural song - scoring/curriculum harness, not only the stock patch catalog. The harness is - becoming the music generator's memory feeder through CultCache and Qdrant, so - it must store instrument-role evidence, not just log-mel winners. -- `song-score` now analyzes every candidate script and records - `instrument_voice_syrinx`, `instrument_drum_subtractive`, - `instrument_pad_additive`, `musical_instrument_score`, and - `chip_distress_risk` metrics in the trial result. Verdict selection and - distillation ranking now include this role evidence so simple oscillator blips - cannot quietly train the future generator unless they are explicitly useful - contrast. -- `run-song-snippet-trial-swarm.ps1` now tells agents the role ownership rule: - voice-like leads should use syrinx/acoustic source ports with pressure/opening - motion; drums/transients should use subtractive pitched bodies plus filtered - noise skins; pads/beds should use additive/PAD `layer`, `harmonics`, and - `spectrum` banks. Ordinary voices remain helpers, not the main answer. -- Added stock reference patches for `syrinx-voice`, `subtractive-drums`, and - `additive-pad`, and changed `Presets.AquaSynthVoice()` to use the syrinx - script instead of the old triangle/formant proxy. These are examples for the - harness and agents, not a substitute for scoring ownership. -- Smoke proof: - `artifacts/parity/song-instrument-metric-smoke/smoke/summary.csv` records a - syrinx candidate with `instrument_voice_syrinx=1`, - `musical_instrument_score=0.34`, and `chip_distress_risk=0`. - -2026-05-31 full-song iterative harness slice: - -- `song-prepare --duration-seconds 0` now means "freeze the full decoded source - file from sample zero" instead of a random excerpt. `run-song-snippet-trial-swarm.ps1` - has `-FullSongs`, keeps the source folder recursive, and widened local audio - discovery to `.mp3/.wav/.flac/.aiff/.aif/.ogg/.m4a/.mp4`. Current Reinier - parent corpus discovery sees 2421 supported audio files. -- Song challenge analysis now includes `whitened-spectral-autocorr.csv`, derived - from autocorrelation of a band-whitened log-mel spectral-flux series. This is - intended to expose repeating spectral/rhythmic structure after broad tone - color is normalized away. -- `song-score` writes candidate-side render analysis artifacts from Faust output: - `candidate-analysis.md`, `candidate-logmel-spectrogram.csv`, - `candidate-logmel-band-stats.csv`, `candidate-rms-envelope.csv`, - `candidate-rms-envelope-autocorr.csv`, and - `candidate-whitened-spectral-autocorr.csv`. Agents can now inspect their own - render with the same feature vocabulary used for the target. -- The swarm prompt now requires an in-agent studio loop: each worker must run - five local attempts per target, call `song-score` on each attempt, read the - candidate analysis/comparison artifacts, move timings/filters/gains/sources, - and publish only one final `.aqua` per target to the official output folder. -- Verification: `dotnet build tools/IpaTrialWorker/IpaTrialWorker.csproj` - passed; zero-pass full-song swarm syntax smoke passed; candidate feature - smoke wrote the new candidate autocorrelation and analysis artifacts under - `artifacts/parity/song-candidate-feature-smoke-2`. - -2026-05-31 CultCache paged trial-store slice: - -- Full-song iterative swarm exposed the storage owner fault: the shared - `song-trial-results.cc` single-file MessagePack store grew to ~2.13 GB and - failed at the end of pass 3 with `System.OutOfMemoryException` while trying - to allocate another whole-store buffer. The issue was not the song agents; - it was the backing store treating cold old records as part of every hot write. -- CultLib now has `DirectoryMessagePackBackingStore`. In directory mode, the - `.cc` path is a small schema manifest and each record is an individual - MessagePack page under `.records/`. `PushAll` rewrites changed/deleted - records and the manifest only; cold record files keep their timestamps and - are not serialized into one giant byte array. -- `CultCacheOpenOptions.UseDirectoryStore` selects the paged store, and - `CultCacheMessagePack.Create/OpenAsync` automatically reopen a paged store - when the `.records` directory exists. AquaSynth trial-result stores now - always use directory mode through `IpaTrialResultCultCacheStore`, so future - song/IPA curriculum runs stop dragging the whole archive through RAM on each - upsert. -- Verification: CultLib `BackingStoreTests` pass 14/14, including a cold-record - timestamp test; AquaSynth `dotnet build tools/IpaTrialWorker/IpaTrialWorker.csproj - --no-restore` passes; AquaSynth `--filter CultCache` tests pass 7/7. - -2026-05-31 producer-apprenticeship admission slice: - -- User listening exposed a second owner fault after composition sugar: agents - could still converge on the same voiced burst plus static/noisy weak - percussion because syntax, activity, and broad role names were still enough to - become ranked curriculum pressure. -- `song-score` now analyzes a production profile beside the instrument and - continuity profiles: required studio document coverage, producer - musicianship score, composition section score, template loop risk, - noise-percussion risk, and Aqua gap count. -- `music-distill` now promotes candidate-pattern and role doctrine only from - rendered rows that clear the producer/curriculum gate. Missing producer - evidence, high template-loop risk, high noise-percussion risk, and weak-slop - verdicts become failure-mode documents instead of reusable examples. -- `run-song-snippet-trial-swarm.ps1` is redirected from parity-worker posture - to producer apprenticeship: each agent must write `producer-brief.md`, - `listening-journal.md`, `aqua-gap-ledger.md`, and `studio-lesson.md`, and use - the self-iteration loop as a listening/revision record rather than a metric - casino. - -2026-06-01 Qdrant music retrieval and curator slice: - -- The old music-production "semantic" injection was lexical keyword matching - over short summaries. It is no longer the swarm path. -- `music-index` now embeds full `MusicProductionKnowledgeDocument` packets into - Qdrant collection `aquasynth_music_production_knowledge`; `music-search` - defaults to Qdrant/Ollama retrieval and emits full owner, summary, transfer - rules, AquaSynth patterns, failure modes, vector score, and retrieved chunk - text. Lexical fallback is only an explicit debugging escape hatch. -- After each musician phase, `run-song-snippet-trial-swarm.ps1` starts a - dedicated `knowledge-curator` agent. Its only output is - `knowledge-curation.md`, with novel actionable entries, evidence paths, - owner sentences, current AquaSynth lowering, and rejected-copy notes. -- `music-distill` ingests those curator files as `curator-distillation` - documents, then the pass indexes the resulting `.cc` into Qdrant before the - next phase uses it. - -2026-06-01 manual/textbook music curriculum slice: - -- Added repo-native manuals under `docs/music-production-knowledge/`: - `aqua-dsp-usage-manual.md` and - `open-music-theory-production-distill.md`. -- `music-distill` now ingests those manuals as `manual` knowledge documents in - every fresh music `.cc`, so musician agents retrieve AquaSynth DSP usage, - music theory, arrangement, groove, harmony, melody, production, and failure - modes before prior-run candidate pressure. -- Smoke proof: `artifacts/parity/manual-knowledge-smoke/20260601T001932` - produced a 16-document knowledge store with 2 manuals, indexed it into - Qdrant, and `music-search` retrieved the AquaSynth DSP manual with - `retrieval: qdrant-ollama`. - -2026-06-01 cumulative music knowledge store correction: - -- User caught that `music-distill` should not reseed theory/manual documents - after every pass. The swarm now creates one loop-level - `music-production-knowledge.cc`, seeds it once with manuals, indexes that - base store, and keeps using that store for all pass retrieval. -- After each pass, `music-distill` runs with `--input-store` equal to the - loop-level store, `--learned-only true`, and `--include-manuals false`, so it - appends/upserts worker/curator/candidate/failure evidence without rewriting - the manual spine. -- Added `music-intelligence-source-map.md` as a third manual: Every Noise is - genre-vocabulary context, Echo Nest is dead, Spotify audio features are not a - usable training substrate, AcousticBrainz is historical, and local - Essentia-style extraction is the preferred signal path. diff --git a/tests/AquaSynth.Dsl.Tests/DingCatalogTests.cs b/tests/AquaSynth.Dsl.Tests/DingCatalogTests.cs index 126b93f..1c4e7be 100644 --- a/tests/AquaSynth.Dsl.Tests/DingCatalogTests.cs +++ b/tests/AquaSynth.Dsl.Tests/DingCatalogTests.cs @@ -21,22 +21,6 @@ public sealed class DingCatalogTests Assert.Equal("Gain must be between 0 and 1.", DingCatalog.PlayRejection("task.complete", "warm-bell", gain)); } - [Fact] - public void HostCallsTheGateAndOwnsNoSecondCopy() - { - var raw = File.ReadAllText(Path.Combine(RepositoryRoot(), "tools", "AquaSynthDingsHost", "DingsPlaybackHost.cs")); - var host = System.Text.RegularExpressions.Regex.Replace(raw, @"//[^\n]*|/\*.*?\*/", "", System.Text.RegularExpressions.RegexOptions.Singleline); - // Source-shape check: the guard must be an unconditional early return of the gate's text. - Assert.Matches(@"if \(DingCatalog\.PlayRejection\(command\.EventId, command\.InstrumentId, command\.Value\) is \{ \} (\w+)\) return Response\(false, ""rejected"", \1\);", host); - // No second copy of the old inline conditions or texts, however the string is split. - Assert.DoesNotContain("Events.TryGetValue", host, StringComparison.Ordinal); - Assert.DoesNotContain("Instruments.TryGetValue", host, StringComparison.Ordinal); - Assert.DoesNotContain("Gain must", host, StringComparison.Ordinal); - Assert.DoesNotContain("Unknown event", host, StringComparison.Ordinal); - Assert.DoesNotContain("Unknown instrument", host, StringComparison.Ordinal); - Assert.DoesNotContain("\"Unk\"", host, StringComparison.Ordinal); - } - [Fact] public void MinimalDingsVocabularyIsComplete() { @@ -112,18 +96,6 @@ public sealed class DingCatalogTests } } - // Negative check on callers: reverting either call site to an inline rule leaves the catalog tests green, so read the sources. - [Theory] - [InlineData("tools/AquaSynthDingsHost/AquaDaemonClient.cs")] - [InlineData("tools/AquaLower/Program.cs")] - public void CallersDeriveIdentityOnlyThroughTheCatalog(string relativePath) - { - var source = File.ReadAllText(Path.Combine(RepositoryRoot(), relativePath)); - Assert.Contains("DingCatalog.Identity(", source, StringComparison.Ordinal); - Assert.DoesNotContain("\"dings_\"", source, StringComparison.Ordinal); - Assert.DoesNotContain("$\"dings", source, StringComparison.Ordinal); - } - private static string RepositoryRoot() { var dir = new DirectoryInfo(AppContext.BaseDirectory); diff --git a/tests/AquaSynth.Dsl.Tests/DingsBridgeTests.cs b/tests/AquaSynth.Dsl.Tests/DingsBridgeTests.cs index c46f924..670e325 100644 --- a/tests/AquaSynth.Dsl.Tests/DingsBridgeTests.cs +++ b/tests/AquaSynth.Dsl.Tests/DingsBridgeTests.cs @@ -32,17 +32,32 @@ public sealed class DingsBridgeTests } [Fact] - public async Task DeprecatedBridgeFailFastKeepsItsErrorsAndTextsAgreeWithTheHostGate() + public async Task PlayAsyncForwardsPlayRequestsToHostGateAndSurfacesHostRejections() { - var host = new FakeHostClient(); + var host = new FakeHostClient { EnforceCatalogGate = true }; var service = new DingService(host); - var badEvent = await Assert.ThrowsAsync(() => service.PlayAsync("nope", "warm-bell", .5f, CancellationToken.None)); + var ok = await service.PlayAsync("task.complete", "warm-bell", .65f, CancellationToken.None); + Assert.NotNull(ok); + + var badEvent = await Assert.ThrowsAsync(() => service.PlayAsync("nope", "warm-bell", .5f, CancellationToken.None)); Assert.Equal(DingCatalog.PlayRejection("nope", "warm-bell", .5f), badEvent.Message); - var badInstrument = await Assert.ThrowsAsync(() => service.PlayAsync("task.complete", "nope", .5f, CancellationToken.None)); + + var badInstrument = await Assert.ThrowsAsync(() => service.PlayAsync("task.complete", "nope", .5f, CancellationToken.None)); Assert.Equal(DingCatalog.PlayRejection("task.complete", "nope", .5f), badInstrument.Message); - await Assert.ThrowsAsync(() => service.PlayAsync("task.complete", "warm-bell", 1.5f, CancellationToken.None)); - Assert.Empty(host.Commands); + + var badGain = await Assert.ThrowsAsync(() => service.PlayAsync("task.complete", "warm-bell", 1.5f, CancellationToken.None)); + Assert.Equal(DingCatalog.PlayRejection("task.complete", "warm-bell", 1.5f), badGain.Message); + + var nanGain = await Assert.ThrowsAsync(() => service.PlayAsync("task.complete", "warm-bell", float.NaN, CancellationToken.None)); + Assert.Equal(DingCatalog.PlayRejection("task.complete", "warm-bell", float.NaN), nanGain.Message); + + Assert.Equal(5, host.Commands.Count); + Assert.All(host.Commands, command => + { + Assert.Equal(DingsProtocol.Version, command.Version); + Assert.Equal(DingsCommandKind.Play, command.Kind); + }); } [Fact] @@ -68,10 +83,16 @@ public sealed class DingsBridgeTests public List Commands { get; } = []; public float Volume { get; set; } = 1; public bool Muted { get; set; } + public bool EnforceCatalogGate { get; init; } public Task SendAsync(DingsCommand command, CancellationToken cancellationToken) { Commands.Add(command); + if (EnforceCatalogGate && command.Kind == DingsCommandKind.Play && + DingCatalog.PlayRejection(command.EventId, command.InstrumentId, command.Value) is { } rejection) + { + return Task.FromResult(new DingsResponse(DingsProtocol.Version, false, "rejected", rejection, Volume: Volume, Muted: Muted, HostProcessId: 42)); + } if (command.Kind == DingsCommandKind.SetVolume) Volume = command.Value; if (command.Kind == DingsCommandKind.SetMuted) Muted = command.Value >= .5f; return Task.FromResult(new DingsResponse(DingsProtocol.Version, true, "ok", Volume: Volume, Muted: Muted, HostProcessId: 42)); diff --git a/tools/AquaSynthDingsMcp/DingService.cs b/tools/AquaSynthDingsMcp/DingService.cs index 6d53486..dd20a4e 100644 --- a/tools/AquaSynthDingsMcp/DingService.cs +++ b/tools/AquaSynthDingsMcp/DingService.cs @@ -6,15 +6,9 @@ public sealed class DingService(IDingsHostClient host) { public async Task PlayAsync(string eventId, string instrumentId, float gain, CancellationToken cancellationToken) { - // DEPRECATED fail-fast path: the Host enforces the real gate (DingCatalog.PlayRejection, called by DingsPlaybackHost.PlayAsync). - // Kept for one window because its exception types and the NaN pass-through to the Host's rejection are observable; see - // docs/dings-patch-identity-authority-map.md, Migration plan step 4. Remove only in a separate PR. - if (!DingCatalog.Events.TryGetValue(eventId, out var dingEvent)) throw new ArgumentException($"Unknown event '{eventId}'."); - if (!DingCatalog.Instruments.TryGetValue(instrumentId, out var instrument)) throw new ArgumentException($"Unknown instrument '{instrumentId}'."); - if (gain is < 0 or > 1) throw new ArgumentOutOfRangeException(nameof(gain), "Gain must be between 0 and 1."); - var response = await host.SendAsync(new(DingsProtocol.Version, DingsCommandKind.Play, dingEvent.Id, instrument.Id, gain), cancellationToken); + var response = await host.SendAsync(new(DingsProtocol.Version, DingsCommandKind.Play, eventId, instrumentId, gain), cancellationToken); EnsureSuccess(response); - return new { playbackId = response.PlaybackId, eventId = dingEvent.Id, instrumentId = instrument.Id, response.Status, response.HostProcessId }; + return new { playbackId = response.PlaybackId, eventId, instrumentId, response.Status, response.HostProcessId }; } public async Task StopAllAsync(CancellationToken cancellationToken) => EnsureSuccess(await host.SendAsync(new(DingsProtocol.Version, DingsCommandKind.StopAll), cancellationToken)); diff --git a/tools/BirdSyrinxGolf/BirdSyrinxGolf.csproj b/tools/BirdSyrinxGolf/BirdSyrinxGolf.csproj deleted file mode 100644 index 68bccc5..0000000 --- a/tools/BirdSyrinxGolf/BirdSyrinxGolf.csproj +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - Exe - net10.0 - enable - enable - - - diff --git a/tools/BirdSyrinxGolf/Program.cs b/tools/BirdSyrinxGolf/Program.cs deleted file mode 100644 index 1c6af42..0000000 --- a/tools/BirdSyrinxGolf/Program.cs +++ /dev/null @@ -1,627 +0,0 @@ -using System.Globalization; -using System.Net.Http.Headers; -using System.Text; -using System.Text.Json; -using AquaSynth.Dsl; -using AquaSynth.Faust; -using NAudio.Wave; -using NVorbis; - -var root = RepositoryRoot(); -var timestamp = DateTimeOffset.UtcNow.ToString("yyyyMMddTHHmmssfff", CultureInfo.InvariantCulture); -var runRoot = Path.Combine(root, "artifacts", "bird-syrinx-golf", timestamp); -var sourceRoot = Path.Combine(runRoot, "sources"); -var jsonOptions = new JsonSerializerOptions { WriteIndented = true }; -BirdSource[] sources = -[ - new( - "common-iora-xc125847", - "Common Iora", - "Aegithina tiphia", - "song", - BirdKind.HarmonicSong, - "Sudipto Roy", - "CC BY-SA 3.0", - "https://creativecommons.org/licenses/by-sa/3.0", - "https://commons.wikimedia.org/wiki/File:Aegithina_tiphia_-_Common_Iora_XC125847.ogg", - "https://upload.wikimedia.org/wikipedia/commons/transcoded/7/7c/Aegithina_tiphia_-_Common_Iora_XC125847.ogg/Aegithina_tiphia_-_Common_Iora_XC125847.ogg.mp3", - "https://upload.wikimedia.org/wikipedia/commons/7/7c/Aegithina_tiphia_-_Common_Iora_XC125847.ogg"), - new( - "common-blackbird-1059970", - "Common Blackbird", - "Turdus merula", - "song", - BirdKind.HarmonicSong, - "Diana Tudor", - "CC BY 4.0", - "https://creativecommons.org/licenses/by/4.0", - "https://commons.wikimedia.org/wiki/File:Common_Blackbird_song_(Turdus_merula).ogg", - "https://upload.wikimedia.org/wikipedia/commons/transcoded/3/30/Common_Blackbird_song_%28Turdus_merula%29.ogg/Common_Blackbird_song_%28Turdus_merula%29.ogg.mp3", - "https://upload.wikimedia.org/wikipedia/commons/3/30/Common_Blackbird_song_%28Turdus_merula%29.ogg"), - new( - "red-footed-falcon", - "Red-footed Falcon", - "Falco vespertinus", - "typical calls", - BirdKind.HighCall, - "Bubulcus", - "CC BY 3.0", - "https://creativecommons.org/licenses/by/3.0", - "https://commons.wikimedia.org/wiki/File:Falco_vespertinus.ogg", - "https://upload.wikimedia.org/wikipedia/commons/transcoded/5/59/Falco_vespertinus.ogg/Falco_vespertinus.ogg.mp3", - "https://upload.wikimedia.org/wikipedia/commons/5/59/Falco_vespertinus.ogg"), - new( - "warbling-white-eye-ko", - "Warbling White-eye", - "Zosterops japonicus", - "call", - BirdKind.HighCall, - "National Institute of Biological Resources", - "KOGL Type 1", - "http://www.kogl.or.kr/info/licenseType1.do", - "https://commons.wikimedia.org/wiki/File:%EB%8F%99%EB%B0%95%EC%83%88.ogg", - "https://upload.wikimedia.org/wikipedia/commons/transcoded/e/e7/%EB%8F%99%EB%B0%95%EC%83%88.ogg/%EB%8F%99%EB%B0%95%EC%83%88.ogg.mp3", - "https://upload.wikimedia.org/wikipedia/commons/e/e7/%EB%8F%99%EB%B0%95%EC%83%88.ogg"), - new( - "eurasian-wren-ko", - "Eurasian Wren", - "Troglodytes troglodytes", - "song", - BirdKind.HarmonicSong, - "National Institute of Biological Resources", - "KOGL Type 1", - "http://www.kogl.or.kr/info/licenseType1.do", - "https://commons.wikimedia.org/wiki/File:%EA%B5%B4%EB%9A%9D%EC%83%88.ogg", - "https://upload.wikimedia.org/wikipedia/commons/transcoded/2/2b/%EA%B5%B4%EB%9A%9D%EC%83%88.ogg/%EA%B5%B4%EB%9A%9D%EC%83%88.ogg.mp3", - "https://upload.wikimedia.org/wikipedia/commons/2/2b/%EA%B5%B4%EB%9A%9D%EC%83%88.ogg") -]; -Directory.CreateDirectory(sourceRoot); - -if (FaustCompiler.FindFaust() is null) -{ - Console.Error.WriteLine("Faust was not found on PATH or FAUST_HOME; cannot render Aqua syrinx candidates."); - return 2; -} - -using var http = new HttpClient(); -http.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("AquaSynthBirdSyrinxGolf", "0.1")); -http.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("(https://github.com/GameCult/AquaSynth)")); -http.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("audio/ogg")); -http.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("audio/mpeg")); - -var rows = new List(); -foreach (var source in sources) -{ - Console.WriteLine($"Fetching {source.Id} {source.CommonName}"); - var sourceDir = Path.Combine(sourceRoot, source.Id); - Directory.CreateDirectory(sourceDir); - var referencePath = Path.Combine(sourceDir, "reference.mp3"); - var downloadedFrom = source.FileUrls[0]; - if (!File.Exists(referencePath)) - { - downloadedFrom = await DownloadFirstAvailableAsync(http, source, referencePath); - } - - var decoded = DecodeMono(referencePath, downloadedFrom); - var target = LoudestWindow(decoded.Samples, decoded.SampleRate, 1.2f); - var target44 = Resample(target, decoded.SampleRate, 44100); - NormalizePeak(target44, 0.9f); - var referenceFeatures = ExtractReferenceFeatures(target44, 44100); - WriteWav(Path.Combine(sourceDir, "reference-clip.wav"), target44, 44100); - File.WriteAllText(Path.Combine(sourceDir, "source.json"), JsonSerializer.Serialize(new SourceSnapshot(source, downloadedFrom), jsonOptions)); - File.WriteAllText(Path.Combine(sourceDir, "reference-features.json"), JsonSerializer.Serialize(referenceFeatures, jsonOptions)); - - var best = default(CandidateResult?); - var candidateIndex = 0; - foreach (var candidate in CandidateGrid(source, referenceFeatures)) - { - candidateIndex++; - var script = SyrinxScript(candidate, target44.Length / 44100f); - var export = FaustEmitter.EmitScript(script, new FaustExportOptions("bird_syrinx_candidate")); - var render = await FaustCompiler.RenderAsync(export.Source, new FaustRenderOptions(44100, target44.Length / 44100f)); - if (render is null || render.Samples.Length == 0) - { - Console.WriteLine($" candidate {candidateIndex:00}: render failed {render?.Stderr}"); - continue; - } - - var candidateSamples = MatchLength(render.Samples, target44.Length); - NormalizePeak(candidateSamples, 0.9f); - var comparison = AudioAnalyzer.CompareAudio(target44, candidateSamples); - var result = new CandidateResult(candidate, candidateSamples, comparison, script); - if (best is null || result.Comparison.Score > best.Comparison.Score) - { - best = result; - } - - Console.WriteLine(FormattableString.Invariant( - $" candidate {candidateIndex:00}: score={comparison.Score:0.0000} logMel={comparison.LogMelCosineSimilarity:0.0000} {candidate}")); - } - - if (best is null) - { - rows.Add(new ResultRow(source.Id, source.CommonName, "no-render", referenceFeatures.DominantHz, referenceFeatures.ActiveDuty, 0, 0, 0, 0, "")); - continue; - } - - WriteWav(Path.Combine(sourceDir, "candidate-syrinx.wav"), best.Samples, 44100); - File.WriteAllText(Path.Combine(sourceDir, "candidate-syrinx.aqua"), best.Script); - File.WriteAllText(Path.Combine(sourceDir, "report.txt"), Report(source, downloadedFrom, referenceFeatures, best)); - rows.Add(new ResultRow( - source.Id, - source.CommonName, - source.CallType, - referenceFeatures.DominantHz, - referenceFeatures.ActiveDuty, - best.Comparison.Score, - best.Comparison.LogMelCosineSimilarity, - best.Comparison.LogMelDistance, - best.Comparison.CentroidRatio, - best.Candidate.ToString())); -} - -File.WriteAllText(Path.Combine(runRoot, "summary.md"), Summary(rows)); -Console.WriteLine(runRoot); -return 0; - -static IEnumerable CandidateGrid(BirdSource source, ReferenceFeatures features) -{ - var fallbackBases = source.Kind switch - { - BirdKind.HarmonicSong => new[] { 750f, 1050f, 1400f }, - BirdKind.HighCall => new[] { 1400f, 2200f, 3000f }, - BirdKind.LowCall => new[] { 260f, 480f, 760f }, - _ => new[] { 800f, 1300f, 2100f } - }; - var featureBase = features.DominantHz is > 120 and < 6000 - ? features.DominantHz - : fallbackBases[1]; - var bases = new[] - { - Math.Clamp(featureBase * 0.78f, 120f, 5000f), - Math.Clamp(featureBase, 120f, 5000f), - Math.Clamp(featureBase * 1.24f, 120f, 5000f) - }; - var active = Math.Clamp(features.ActiveDuty, 0.05f, 1f); - var flux = Math.Clamp(features.SpectralFlux, 0f, 1f); - var basePressure = Math.Clamp(0.58f + active * 0.28f + flux * 0.10f, 0.45f, 0.95f); - var baseOpening = source.Kind == BirdKind.HighCall - ? Math.Clamp(0.10f + features.Rms * 1.5f, 0.08f, 0.28f) - : Math.Clamp(0.16f + features.Rms * 1.7f, 0.12f, 0.42f); - var loads = new[] { 0.65f, 0.9f }; - var leftGates = new[] { 1.0f, 0.72f }; - foreach (var frequency in bases) - foreach (var load in loads) - foreach (var leftGate in leftGates) - { - var tension = Math.Clamp(0.18f + frequency / 5200f + flux * 0.12f, 0.18f, 0.88f); - var stiffness = Math.Clamp(MathF.Pow(frequency / 3200f, 2) * 0.09f, 0.004f, 0.16f); - var mass = Math.Clamp(0.48f - frequency / 9000f, 0.10f, 0.46f); - var damping = Math.Clamp(0.08f + (1f - active) * 0.16f + flux * 0.08f, 0.06f, 0.38f); - yield return new SyrinxCandidate( - frequency, - Pressure: basePressure * leftGate, - RightPressure: Math.Clamp(basePressure * (0.82f + flux * 0.18f), 0.35f, 0.95f), - Tension: tension, - RightTension: Math.Clamp(tension + 0.07f, 0, 1), - Opening: baseOpening, - RightOpening: Math.Max(0.04f, baseOpening * (0.82f + flux * 0.18f)), - Load: load, - Mass: mass, - RightMass: Math.Clamp(mass * 1.06f, 0.08f, 0.6f), - Damping: damping, - RightDamping: Math.Clamp(damping * 1.08f, 0.04f, 0.5f), - Stiffness: stiffness, - RightStiffness: Math.Clamp(stiffness * 1.12f, 0.002f, 0.2f), - Drive: Math.Clamp(0.9f + features.Peak * 0.45f, 0.7f, 1.5f), - RightDrive: Math.Clamp(0.82f + features.Peak * 0.40f, 0.65f, 1.4f), - LoadCoupling: Math.Clamp(0.28f + load * 0.18f, 0.2f, 0.7f), - RestOpening: Math.Clamp(baseOpening * 0.10f, 0.01f, 0.08f), - BeakOpening: source.Kind == BirdKind.LowCall ? 0.75f : 0.95f, - Gain: source.Kind == BirdKind.LowCall ? 0.42f : 0.32f); - } -} - -static string SyrinxScript(SyrinxCandidate candidate, float durationSeconds) => - $$""" - patch gain=0.42 soft_clip=true - - param path=/bird/left/pressure default={{F(candidate.Pressure)}} min=0 max=1 step=.001 - param path=/bird/right/pressure default={{F(candidate.RightPressure)}} min=0 max=1 step=.001 - param path=/bird/left/opening default={{F(candidate.Opening)}} min=0 max=1 step=.001 - param path=/bird/right/opening default={{F(candidate.RightOpening)}} min=0 max=1 step=.001 - param path=/bird/beak/opening default={{F(candidate.BeakOpening)}} min=0 max=1.5 step=.001 - curve name=left_pressure path=/bird/left/pressure points={{PressureCurve(candidate.Pressure, durationSeconds)}} depth=1 - curve name=right_pressure path=/bird/right/pressure points={{PressureCurve(candidate.RightPressure, durationSeconds)}} depth=1 - curve name=left_opening path=/bird/left/opening points={{OpeningCurve(candidate.Opening, durationSeconds)}} depth=.9 - curve name=right_opening path=/bird/right/opening points={{OpeningCurve(candidate.RightOpening, durationSeconds)}} depth=.9 - curve name=beak_opening path=/bird/beak/opening points={{BeakCurve(candidate.BeakOpening, durationSeconds)}} depth=.65 - - path name=left_bronchus length_cm=3.8 diameters=.22,.30,.36,.42 - path name=right_bronchus length_cm=3.6 diameters=.20,.28,.34,.40 - path name=trachea length_cm=8.4 diameters=.38,.48,.56,.46 - - source_port name=left_labium path=left_bronchus kind=syrinx model=tissue_valve position=0 pressure=@/bird/left/pressure tension={{F(candidate.Tension)}} opening=@/bird/left/opening noise=.025 impedance={{F(candidate.Load)}} mass={{F(candidate.Mass)}} damping={{F(candidate.Damping)}} stiffness={{F(candidate.Stiffness)}} saturation=.9 drive={{F(candidate.Drive)}} load_coupling={{F(candidate.LoadCoupling)}} rest_opening={{F(candidate.RestOpening)}} - source_port name=right_labium path=right_bronchus kind=syrinx model=tissue_valve position=0 pressure=@/bird/right/pressure tension={{F(candidate.RightTension)}} opening=@/bird/right/opening noise=.02 balance=.96 impedance={{F(candidate.Load)}} mass={{F(candidate.RightMass)}} damping={{F(candidate.RightDamping)}} stiffness={{F(candidate.RightStiffness)}} saturation=.9 drive={{F(candidate.RightDrive)}} load_coupling={{F(candidate.LoadCoupling)}} rest_opening={{F(candidate.RestOpening)}} - - terminal name=left_merge path=left_bronchus position=1 kind=junction area_scale=1 - terminal name=right_merge path=right_bronchus position=1 kind=junction area_scale=1 - terminal name=trachea_base path=trachea position=0 kind=junction area_scale=1 - connect name=syrinx_merge terminals=left_merge,right_merge,trachea_base law=area_scatter coupling=1 - - radiation_port name=beak path=trachea kind=beak position=1 opening=@/bird/beak/opening reflection=-.72 - wave_clock name=bird_clock strategy=linear max_delay=1024 smoothing_ms=2 - acoustic_network name=bird_syrinx path=trachea wave_clock=bird_clock sources=left_labium,right_labium radiation=beak terminals=left_merge,right_merge,trachea_base connections=syrinx_merge - acoustic network=bird_syrinx freq={{F(candidate.Frequency)}} gain={{F(candidate.Gain)}} sustain={{F(Math.Max(0.05f, durationSeconds - 0.12f))}} decay=.08 - """; - -static string PressureCurve(float value, float durationSeconds) => - Curve((0, MathF.Max(0.01f, value * 0.08f)), (0.035f, value), (durationSeconds * 0.55f, value * 0.94f), (durationSeconds, value * 0.35f)); - -static string OpeningCurve(float value, float durationSeconds) => - Curve((0, MathF.Max(0.01f, value * 0.15f)), (0.03f, value), (durationSeconds * 0.65f, value * 0.86f), (durationSeconds, MathF.Max(0.01f, value * 0.20f))); - -static string BeakCurve(float value, float durationSeconds) => - Curve((0, value * 0.45f), (0.05f, value), (durationSeconds * 0.72f, Math.Min(1.5f, value * 1.08f)), (durationSeconds, value * 0.55f)); - -static string Curve(params (float Time, float Value)[] points) => - string.Join(",", points.Select(point => $"{F(Math.Max(0, point.Time))}:{F(Math.Max(0, point.Value))}")); - -static string Report(BirdSource source, string downloadedFrom, ReferenceFeatures features, CandidateResult best) => - $""" - # {source.CommonName} ({source.ScientificName}) - - Source: {source.DescriptionUrl} - Downloaded file: {downloadedFrom} - License: {source.LicenseName} ({source.LicenseUrl}) - Author: {source.Author} - Call type: {source.CallType} - - Reference features: - rms={features.Rms:0.0000} - peak={features.Peak:0.0000} - activeDuty={features.ActiveDuty:0.0000} - onsetSeconds={features.OnsetSeconds:0.0000} - offsetSeconds={features.OffsetSeconds:0.0000} - dominantHz={features.DominantHz:0.0} - spectralFlux={features.SpectralFlux:0.0000} - - Best candidate: - {best.Candidate} - - Metrics: - score={best.Comparison.Score:0.0000} - logMelCosine={best.Comparison.LogMelCosineSimilarity:0.0000} - logMelDistance={best.Comparison.LogMelDistance:0.0000} - rmsRatio={best.Comparison.RmsRatio:0.0000} - centroidRatio={best.Comparison.CentroidRatio:0.0000} - articulation={best.Comparison.Articulation.ArticulationScore:0.0000} - - This is a feature-informed graph-native syrinx golf pass, not an accepted species model. Gesture curves are currently compressed into source parameters because Aqua does not yet have general arbitrary-path control automation. - """; - -static string Summary(IEnumerable rows) -{ - var builder = new StringBuilder(); - builder.AppendLine("# Bird Syrinx Golf"); - builder.AppendLine(); - builder.AppendLine("All references are open-licensed bird recordings from Wikimedia Commons. Candidates are graph-native Aqua syrinx patches using paired tissue-valve source ports."); - builder.AppendLine(); - builder.AppendLine("| id | bird | call | dominantHz | activeDuty | score | logMelCosine | logMelDistance | centroidRatio | candidate |"); - builder.AppendLine("| --- | --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | --- |"); - foreach (var row in rows) - { - builder.AppendLine(CultureInfo.InvariantCulture, $"| {row.Id} | {row.Bird} | {row.Call} | {row.DominantHz:0.0} | {row.ActiveDuty:0.0000} | {row.Score:0.0000} | {row.LogMelCosine:0.0000} | {row.LogMelDistance:0.0000} | {row.CentroidRatio:0.0000} | `{row.Candidate}` |"); - } - return builder.ToString(); -} - -static ReferenceFeatures ExtractReferenceFeatures(IReadOnlyList samples, int sampleRate) -{ - var peak = samples.Select(MathF.Abs).DefaultIfEmpty(0).Max(); - var rms = MathF.Sqrt(samples.Select(sample => sample * sample).DefaultIfEmpty(0).Average()); - var frameSize = Math.Max(64, sampleRate / 100); - var threshold = Math.Max(0.02f, rms * 0.45f); - var frameRms = new List(); - for (var start = 0; start < samples.Count; start += frameSize) - { - var end = Math.Min(samples.Count, start + frameSize); - var sum = 0f; - for (var i = start; i < end; i++) sum += samples[i] * samples[i]; - frameRms.Add(MathF.Sqrt(sum / Math.Max(1, end - start))); - } - - var activeFrames = frameRms - .Select((value, index) => (value, index)) - .Where(frame => frame.value >= threshold) - .Select(frame => frame.index) - .ToArray(); - var activeDuty = frameRms.Count == 0 ? 0 : activeFrames.Length / (float)frameRms.Count; - var onset = activeFrames.Length == 0 ? 0 : activeFrames[0] * frameSize / (float)sampleRate; - var offset = activeFrames.Length == 0 ? samples.Count / (float)sampleRate : Math.Min(samples.Count, (activeFrames[^1] + 1) * frameSize) / (float)sampleRate; - var flux = 0f; - for (var i = 1; i < frameRms.Count; i++) flux += Math.Max(0, frameRms[i] - frameRms[i - 1]); - flux = frameRms.Count <= 1 || peak <= 0 ? 0 : Math.Clamp(flux / (frameRms.Count * peak), 0, 1); - - return new ReferenceFeatures(rms, peak, activeDuty, onset, offset, DominantFrequency(samples, sampleRate, activeFrames, frameSize), flux); -} - -static float DominantFrequency(IReadOnlyList samples, int sampleRate, IReadOnlyList activeFrames, int frameSize) -{ - if (samples.Count < 256) return 0; - var activeCenter = activeFrames.Count == 0 - ? samples.Count / 2 - : Math.Clamp((int)((activeFrames[activeFrames.Count / 2] + 0.5f) * frameSize), 0, samples.Count - 1); - var size = Math.Min(4096, samples.Count); - var start = Math.Clamp(activeCenter - size / 2, 0, Math.Max(0, samples.Count - size)); - var minLag = Math.Max(1, sampleRate / 5000); - var maxLag = Math.Min(size / 2, sampleRate / 120); - var bestLag = 0; - var best = 0f; - for (var lag = minLag; lag <= maxLag; lag++) - { - var sum = 0f; - for (var i = 0; i < size - lag; i++) - { - sum += samples[start + i] * samples[start + i + lag]; - } - if (sum > best) - { - best = sum; - bestLag = lag; - } - } - return bestLag == 0 ? 0 : sampleRate / (float)bestLag; -} - -static DecodedAudio DecodeMono(string path, string sourceUrl) -{ - if (sourceUrl.EndsWith(".mp3", StringComparison.OrdinalIgnoreCase)) - { - return DecodeMp3Mono(path); - } - - return DecodeOggMono(path); -} - -static DecodedAudio DecodeMp3Mono(string path) -{ - using var reader = new AudioFileReader(path); - var interleaved = new float[4096 * reader.WaveFormat.Channels]; - var mono = new List(); - int read; - while ((read = reader.Read(interleaved, 0, interleaved.Length)) > 0) - { - for (var i = 0; i < read; i += reader.WaveFormat.Channels) - { - var sum = 0f; - for (var channel = 0; channel < reader.WaveFormat.Channels && i + channel < read; channel++) - { - sum += interleaved[i + channel]; - } - mono.Add(sum / reader.WaveFormat.Channels); - } - } - - return new DecodedAudio(reader.WaveFormat.SampleRate, mono.ToArray()); -} - -static DecodedAudio DecodeOggMono(string path) -{ - using var reader = new VorbisReader(path); - var interleaved = new float[4096 * reader.Channels]; - var mono = new List(); - int read; - while ((read = reader.ReadSamples(interleaved, 0, interleaved.Length)) > 0) - { - for (var i = 0; i < read; i += reader.Channels) - { - var sum = 0f; - for (var channel = 0; channel < reader.Channels && i + channel < read; channel++) - { - sum += interleaved[i + channel]; - } - mono.Add(sum / reader.Channels); - } - } - return new DecodedAudio(reader.SampleRate, mono.ToArray()); -} - -static async Task DownloadFirstAvailableAsync(HttpClient http, BirdSource source, string targetPath) -{ - Exception? lastError = null; - foreach (var url in source.FileUrls) - { - for (var attempt = 1; attempt <= 3; attempt++) - { - try - { - using var request = new HttpRequestMessage(HttpMethod.Get, url); - using var response = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead); - if ((int)response.StatusCode == 429 && attempt < 3) - { - await Task.Delay(TimeSpan.FromSeconds(attempt * 2)); - continue; - } - - response.EnsureSuccessStatusCode(); - await using var remote = await response.Content.ReadAsStreamAsync(); - await using var local = File.Create(targetPath); - await remote.CopyToAsync(local); - return url; - } - catch (Exception ex) when (attempt < 3) - { - lastError = ex; - await Task.Delay(TimeSpan.FromSeconds(attempt * 2)); - } - catch (Exception ex) - { - lastError = ex; - break; - } - } - } - - throw new InvalidOperationException($"Could not download {source.Id} from any configured source URL.", lastError); -} - -static float[] LoudestWindow(IReadOnlyList samples, int sampleRate, float seconds) -{ - var length = Math.Min(samples.Count, Math.Max(1, (int)MathF.Round(sampleRate * seconds))); - if (samples.Count <= length) return samples.ToArray(); - - var hop = Math.Max(1, length / 8); - var bestStart = 0; - var bestEnergy = -1f; - for (var start = 0; start + length <= samples.Count; start += hop) - { - var energy = 0f; - for (var i = start; i < start + length; i++) energy += samples[i] * samples[i]; - if (energy > bestEnergy) - { - bestEnergy = energy; - bestStart = start; - } - } - - var window = new float[length]; - for (var i = 0; i < length; i++) window[i] = samples[bestStart + i]; - return window; -} - -static float[] Resample(IReadOnlyList samples, int sourceRate, int targetRate) -{ - if (sourceRate == targetRate) return samples.ToArray(); - var result = new float[Math.Max(1, (int)Math.Round(samples.Count * (double)targetRate / sourceRate))]; - for (var i = 0; i < result.Length; i++) - { - var position = i * (sourceRate / (double)targetRate); - var left = Math.Clamp((int)Math.Floor(position), 0, samples.Count - 1); - var right = Math.Clamp(left + 1, 0, samples.Count - 1); - var t = (float)(position - left); - result[i] = samples[left] * (1 - t) + samples[right] * t; - } - return result; -} - -static float[] MatchLength(IReadOnlyList samples, int length) -{ - var result = new float[length]; - for (var i = 0; i < result.Length && i < samples.Count; i++) result[i] = samples[i]; - return result; -} - -static void NormalizePeak(IList samples, float peak) -{ - var current = samples.Select(Math.Abs).DefaultIfEmpty(0).Max(); - if (current <= 0) return; - var gain = peak / current; - for (var i = 0; i < samples.Count; i++) samples[i] *= gain; -} - -static void WriteWav(string path, IReadOnlyList samples, int sampleRate) -{ - Directory.CreateDirectory(Path.GetDirectoryName(path)!); - using var stream = File.Create(path); - using var writer = new BinaryWriter(stream, Encoding.ASCII); - var dataSize = samples.Count * sizeof(short); - writer.Write("RIFF"u8); - writer.Write(36 + dataSize); - writer.Write("WAVE"u8); - writer.Write("fmt "u8); - writer.Write(16); - writer.Write((short)1); - writer.Write((short)1); - writer.Write(sampleRate); - writer.Write(sampleRate * sizeof(short)); - writer.Write((short)sizeof(short)); - writer.Write((short)16); - writer.Write("data"u8); - writer.Write(dataSize); - foreach (var sample in samples) - { - writer.Write((short)Math.Clamp(MathF.Round(sample * short.MaxValue), short.MinValue, short.MaxValue)); - } -} - -static string RepositoryRoot() -{ - var directory = new DirectoryInfo(AppContext.BaseDirectory); - while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "AquaSynth.sln"))) - { - directory = directory.Parent; - } - return directory?.FullName ?? AppContext.BaseDirectory; -} - -static string F(float value) => value.ToString("0.######", CultureInfo.InvariantCulture); - -public enum BirdKind { HarmonicSong, HighCall, LowCall } - -public sealed record BirdSource( - string Id, - string CommonName, - string ScientificName, - string CallType, - BirdKind Kind, - string Author, - string LicenseName, - string LicenseUrl, - string DescriptionUrl, - params string[] FileUrls); - -public sealed record SourceSnapshot(BirdSource Source, string DownloadedFrom); - -public sealed record SyrinxCandidate( - float Frequency, - float Pressure, - float RightPressure, - float Tension, - float RightTension, - float Opening, - float RightOpening, - float Load, - float Mass, - float RightMass, - float Damping, - float RightDamping, - float Stiffness, - float RightStiffness, - float Drive, - float RightDrive, - float LoadCoupling, - float RestOpening, - float BeakOpening, - float Gain) -{ - public override string ToString() => - string.Create( - CultureInfo.InvariantCulture, - $"freqHint={Frequency:0.#} pressure={Pressure:0.###}/{RightPressure:0.###} tension={Tension:0.###}/{RightTension:0.###} opening={Opening:0.###}/{RightOpening:0.###} mass={Mass:0.###}/{RightMass:0.###} damp={Damping:0.###}/{RightDamping:0.###} stiff={Stiffness:0.###}/{RightStiffness:0.###} drive={Drive:0.###}/{RightDrive:0.###} load={Load:0.###} loadCoupling={LoadCoupling:0.###} rest={RestOpening:0.###} beak={BeakOpening:0.###} gain={Gain:0.###}"); -} - -public sealed record CandidateResult(SyrinxCandidate Candidate, float[] Samples, AudioComparison Comparison, string Script); - -public sealed record ResultRow( - string Id, - string Bird, - string Call, - float DominantHz, - float ActiveDuty, - float Score, - float LogMelCosine, - float LogMelDistance, - float CentroidRatio, - string Candidate); - -public sealed record DecodedAudio(int SampleRate, float[] Samples); - -public sealed record ReferenceFeatures( - float Rms, - float Peak, - float ActiveDuty, - float OnsetSeconds, - float OffsetSeconds, - float DominantHz, - float SpectralFlux); diff --git a/tools/TractGraphRenderer/Program.cs b/tools/TractGraphRenderer/Program.cs deleted file mode 100644 index 4a492cf..0000000 --- a/tools/TractGraphRenderer/Program.cs +++ /dev/null @@ -1,148 +0,0 @@ -using System.Globalization; -using System.Text.Json; -using AquaSynth.Dsl; -using AquaSynth.Faust; - -var input = (await Console.In.ReadToEndAsync()).TrimStart('\uFEFF', '\u200B', ' ', '\t', '\r', '\n'); -var request = JsonSerializer.Deserialize( - string.IsNullOrWhiteSpace(input) ? "{}" : input, - new JsonSerializerOptions { PropertyNameCaseInsensitive = true }) ?? new RenderRequest(); - -var outputPath = string.IsNullOrWhiteSpace(request.OutputPath) - ? Path.Combine(Path.GetTempPath(), $"aquasynth-tract-{Guid.NewGuid():N}.wav") - : Path.GetFullPath(request.OutputPath); - -Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); - -if (FaustCompiler.FindFaust() is null) -{ - Console.Error.WriteLine("Faust was not found on PATH or FAUST_HOME; cannot render actual Aqua graph audio."); - return 2; -} - -var script = Script(request); -var export = FaustEmitter.EmitScript(script, new FaustExportOptions("aqua_tract_graph_audition", SampleRate: request.SampleRate)); -var render = await FaustCompiler.RenderAsync( - export.Source, - new FaustRenderOptions(request.SampleRate, request.DurationSeconds)); - -if (render is null || render.Samples.Length == 0) -{ - Console.Error.WriteLine(render?.Stderr.Length > 0 ? render.Stderr : "Faust render produced no samples."); - return 3; -} - -WriteWav(outputPath, render.Samples, render.SampleRate, 0.92f); -var peak = render.Samples.Select(MathF.Abs).DefaultIfEmpty(0).Max(); -var rms = MathF.Sqrt(render.Samples.Select(sample => sample * sample).DefaultIfEmpty(0).Average()); -Console.WriteLine(JsonSerializer.Serialize(new -{ - outputPath, - render.SampleRate, - samples = render.Samples.Length, - peak, - rms, - warnings = export.Warnings -})); - -return 0; - -static string Script(RenderRequest controls) => - controls.Mode.Equals("syrinx", StringComparison.OrdinalIgnoreCase) || - controls.Mode.Equals("bird", StringComparison.OrdinalIgnoreCase) - ? SyrinxScript(controls) - : TractScript(controls); - -static string TractScript(RenderRequest controls) => - $$""" - patch gain=0.48 soft_clip=true - - tract_shape - name=human - diameters=0.6,0.6,0.6,0.6,0.6,0.7,0.8,1.0,1.1,1.1,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.4,1.3,1.2,1.15,1.5 - - glottis name=modal intensity={{F(controls.Intensity)}} tenseness={{F(controls.Tenseness)}} aspiration=.12 reflection={{F(controls.GlottalReflection)}} skew=.42 - tract_injection name=inj position=32 diameter=1 turbulence=.1 burst=.25 width=1 - nasal_branch name=nose junction=17 velum=.01 reflection=-.85 loss=.999 diameters=0.01,0.35,0.5,0.65,0.8,0.95,1.1,1.25,1.4,1.55,1.7,1.8,1.9,1.9,1.85,1.75,1.65,1.55,1.45,1.35,1.25,1.15,1.05,0.95,0.85,0.75,0.65,0.55 - tract_motion name=motion diameter_slew=18 shape_return=8 constriction_slew=24 velum_slew=16 obstruction_threshold=.05 - - tract shape=human glottis=modal injection=inj nasal_branch=nose motion=motion propagation=graph loss=.999 freq={{F(controls.Frequency)}} gain={{F(controls.Gain)}} intensity={{F(controls.Intensity)}} tenseness={{F(controls.Tenseness)}} sustain={{F(Math.Max(0.05f, controls.DurationSeconds - 0.12f))}} decay=.12 tongue_index={{F(controls.TongueIndex)}} tongue_diameter={{F(controls.TongueDiameter)}} constriction_index={{F(controls.ConstrictionIndex)}} constriction_diameter={{F(controls.ConstrictionDiameter)}} turbulence={{F(controls.Turbulence)}} velum={{F(controls.Velum)}} lip={{F(controls.LipOpening)}} burst={{F(controls.Burst)}} glottal_reflection={{F(controls.GlottalReflection)}} lip_reflection={{F(controls.LipReflection)}} - """; - -static string SyrinxScript(RenderRequest controls) => - $$""" - patch gain=0.42 soft_clip=true - - param path=/bird/left/pressure default={{F(Math.Clamp(controls.Intensity, 0, 1))}} min=0 max=1 step=.001 - param path=/bird/right/pressure default={{F(Math.Clamp(controls.Intensity * 0.86f, 0, 1))}} min=0 max=1 step=.001 - param path=/bird/left/opening default={{F(Math.Clamp(controls.LipOpening * 0.24f, 0.05f, 1.0f))}} min=0 max=1 step=.001 - param path=/bird/right/opening default={{F(Math.Clamp(controls.LipOpening * 0.20f, 0.05f, 1.0f))}} min=0 max=1 step=.001 - param path=/bird/load default=.85 min=0 max=2 step=.001 - param path=/bird/beak/opening default=.95 min=0 max=1.5 step=.001 - - path name=left_bronchus length_cm=3.8 diameters=.22,.30,.36,.42 - path name=right_bronchus length_cm=3.6 diameters=.20,.28,.34,.40 - path name=trachea length_cm=8.4 diameters=.38,.48,.56,.46 - - source_port name=left_labium path=left_bronchus kind=syrinx position=0 pressure=@/bird/left/pressure tension={{F(controls.Tenseness)}} opening=@/bird/left/opening noise=.025 impedance=@/bird/load - source_port name=right_labium path=right_bronchus kind=syrinx position=0 pressure=@/bird/right/pressure tension={{F(Math.Clamp(controls.Tenseness + 0.07f, 0, 1))}} opening=@/bird/right/opening noise=.02 balance=.96 impedance=@/bird/load - - terminal name=left_merge path=left_bronchus position=1 kind=junction area_scale=1 - terminal name=right_merge path=right_bronchus position=1 kind=junction area_scale=1 - terminal name=trachea_base path=trachea position=0 kind=junction area_scale=1 - connect name=syrinx_merge terminals=left_merge,right_merge,trachea_base law=area_scatter coupling=1 - - radiation_port name=beak path=trachea kind=beak position=1 opening=@/bird/beak/opening reflection=-.72 - wave_clock name=bird_clock strategy=linear max_delay=1024 smoothing_ms=2 - acoustic_network name=bird_syrinx path=trachea wave_clock=bird_clock sources=left_labium,right_labium radiation=beak terminals=left_merge,right_merge,trachea_base connections=syrinx_merge - acoustic network=bird_syrinx freq={{F(controls.Frequency)}} gain={{F(controls.Gain)}} sustain={{F(Math.Max(0.05f, controls.DurationSeconds - 0.12f))}} decay=.08 - """; - -static string F(float value) => - value.ToString("0.######", CultureInfo.InvariantCulture); - -static void WriteWav(string path, IReadOnlyList samples, int sampleRate, float normalizePeak) -{ - var peak = samples.Select(MathF.Abs).DefaultIfEmpty(0).Max(); - var gain = peak > 0 ? Math.Min(1, normalizePeak / peak) : 1; - using var stream = File.Create(path); - using var writer = new BinaryWriter(stream); - var dataLength = samples.Count * sizeof(short); - writer.Write("RIFF"u8); - writer.Write(36 + dataLength); - writer.Write("WAVE"u8); - writer.Write("fmt "u8); - writer.Write(16); - writer.Write((short)1); - writer.Write((short)1); - writer.Write(sampleRate); - writer.Write(sampleRate * sizeof(short)); - writer.Write((short)sizeof(short)); - writer.Write((short)16); - writer.Write("data"u8); - writer.Write(dataLength); - foreach (var sample in samples) - { - writer.Write((short)Math.Clamp(sample * gain * short.MaxValue, short.MinValue, short.MaxValue)); - } -} - -public sealed record RenderRequest( - string Mode = "tract", - string OutputPath = "", - int SampleRate = 44100, - float DurationSeconds = 0.57f, - float Frequency = 140, - float Intensity = 0.72f, - float Tenseness = 0.6f, - float TongueIndex = 13, - float TongueDiameter = 2.7f, - float ConstrictionIndex = 32, - float ConstrictionDiameter = 1, - float Turbulence = 0.1f, - float Velum = 0.01f, - float LipOpening = 1.5f, - float GlottalReflection = 0.75f, - float LipReflection = -0.85f, - float Gain = 0.7f, - float Burst = 0.25f); diff --git a/tools/TractGraphRenderer/TractGraphRenderer.csproj b/tools/TractGraphRenderer/TractGraphRenderer.csproj deleted file mode 100644 index 2350eb8..0000000 --- a/tools/TractGraphRenderer/TractGraphRenderer.csproj +++ /dev/null @@ -1,16 +0,0 @@ - - - - Exe - net10.0 - enable - enable - false - - - - - - - - diff --git a/tools/aqua-ear/README.md b/tools/aqua-ear/README.md index eee85fc..ccff787 100644 --- a/tools/aqua-ear/README.md +++ b/tools/aqua-ear/README.md @@ -81,5 +81,3 @@ clips, not taste. Live: everything above. Not built: per-onset spectral-flux detector for noise-on-noise, an audibility model, batch mode over a directory, `--strict` per-detector selection. None of these is needed by a current consumer. - -Examples are published to one place, https://minds.gamecult.org/aqua/ear/, with `python3 tools/publish-stable/publish_stable.py ear ` (see tools/dings-voices/README.md, Publishing). diff --git a/tools/dings-voices/README.md b/tools/dings-voices/README.md index 66e5b10..de5c82a 100644 --- a/tools/dings-voices/README.md +++ b/tools/dings-voices/README.md @@ -11,17 +11,8 @@ Generates eight sender voices (aqua, eureka, heimdall, kiko, libby, nibu, void, - v4: Void has no tick (it was a second hit 95 ms into every note) and a note something follows ends by the next onset; `polyphony.test.mjs` fails if a Void clip has more onsets than notes. Nibu's voice is proposal 3 (the 8 kHz 5-bit sine) for all four events; proposals 1 and 2 stay as alternates under `out/proposals/`, not in the manifest. - Not here: the rendered clips and the listening page. A staged copy, with the README of its measurements, is at `/opt/commons/handoff/aqua-dings-voices-20261110` on Yggdrasil. -Sound regression guard over every clip this generator and the Earcon Workshop ship (onsets per note, clicks, clipping, true peak, tails, loudness): `python3 tools/sound-guard/guard.py` (see `../sound-guard/README.md`). - Run: `node src/polyphony.test.mjs && node src/neutral_instrument.test.mjs && node src/build.mjs raw && python src/finish.py raw out && python src/verify.py .` (`build.mjs` also renders the four neutral fallbacks, Earcon Workshop `warm-bell` at default sliders with mention=warning, dm=waiting, message=message, invite=done, and `finish.py` equalises them to the same A-weighted exposure as the senders; `out/manifest.json` lists them under `neutral`). ## Publishing (one place) -One dev, one URL: the listening page is **https://minds.gamecult.org/aqua/dings/** (`/srv/minds-web/aqua/dings/`), always the latest version, overwritten in place. Do not publish per-hash pages any more. After building a publish dir (the `Run` line, then `gen_page.py`), run - -``` -python3 tools/publish-stable/publish_stable.py dings # idempotent; swaps the stable dir with a finished staging copy in one atomic exchange (renameat2, Linux): the URL is never missing or half-written, even if the run is killed; stale staging is removed by the next run -python3 tools/publish-stable/publish_stable.py banners # old per-version pages get a pointer banner; deletes nothing -``` - -The script stamps a banner and a `VERSION` file (publish dir name and AquaSynth revision) into the stable copy. The aqua-ear examples are published the same way to `/srv/minds-web/aqua/ear/` (`publish_stable.py ear `). Tests: `python3 tools/publish-stable/test_publish_stable.py` and `test_interruption.py` (kill at every mutation, concurrent reader). Nobody has opened these pages in a browser; every link and audio file on them was checked with curl over https. +One dev, one URL: the listening page is **https://minds.gamecult.org/aqua/dings/** (`/srv/minds-web/aqua/dings/`), always the latest version, overwritten in place. Do not publish per-hash pages any more. diff --git a/tools/export-provider-advertisement.mjs b/tools/export-provider-advertisement.mjs deleted file mode 100644 index 81f4860..0000000 --- a/tools/export-provider-advertisement.mjs +++ /dev/null @@ -1,196 +0,0 @@ -#!/usr/bin/env node -import { mkdir, writeFile } from "node:fs/promises"; -import path from "node:path"; - -const document = { - schema: "gamecult.eve.provider_advertisement.v1", - providerId: "aquasynth.service", - title: "AquaSynth Service", - description: - "AquaSynth accepts .aqua DSL and Weksa utterance handoffs, compiles Faust-native instruments, owns live streaming patch sessions, and publishes controllable synth state through CultMesh.", - mode: "fixture-read-only", - serviceVerse: { - id: "verse.aquasynth.service.v1", - cultMeshKey: "aquasynth.service/provider-advertisement", - authority: "AquaSynth daemon identity, schema catalog, provider publication, and synth runtime boundary", - owns: [ - ".aqua patch parsing", - "patch graph semantics", - "Faust source emission", - "native Faust compilation", - "compiled instrument sessions", - "live streaming patch sessions", - "live session control state", - "live session lifecycle receipts", - "sample/render receipts", - "learned utterance embeddings and synth-driver controls", - ], - doesNotOwn: ["Weksa conversational intent", "Persona canonical state", "Eve presentation runtime"], - }, - nestedVerses: [ - { - id: "aquasynth.patch", - kind: "patch", - cultMeshKey: "aquasynth.patch/current", - authority: "AquaSynth.Core .aqua parser and patch graph model", - schemas: ["aquasynth.patch_graph.v0"], - }, - { - id: "aquasynth.compile", - kind: "compile", - cultMeshKey: "aquasynth.compile/jobs", - authority: "AquaSynth.Faust compiler boundary", - schemas: ["aquasynth.faust_source.v0", "aquasynth.compiled_instrument.v0"], - }, - { - id: "aquasynth.instrument", - kind: "instrument", - cultMeshKey: "aquasynth.instrument/sessions", - authority: "AquaSynth native host and live-session owner", - schemas: [ - "aquasynth.compiled_instrument_session.v1", - "aquasynth.live_instrument_session.v1", - "aquasynth.command.instrument_open.v1", - "aquasynth.command.instrument_control.v1", - "aquasynth.command.instrument_block.v1", - "aquasynth.command.instrument_close.v1", - "aquasynth.instrument_open_receipt.v1", - "aquasynth.instrument_control_receipt.v1", - "aquasynth.instrument_block_receipt.v1", - "aquasynth.instrument_close_receipt.v1", - ], - }, - { - id: "aquasynth.speech", - kind: "speech", - cultMeshKey: "aquasynth.speech/current", - authority: "AquaSynth utterance embedding and synth-driver runtime", - schemas: ["aquasynth.utterance_embedding.v0", "aquasynth.speech_render_receipt.v0"], - }, - { - id: "aquasynth.operator", - kind: "operator", - cultMeshKey: "aquasynth.operator/status", - authority: "AquaSynth daemon runtime", - schemas: ["aquasynth.operator_state.v0"], - }, - ], - schemaWitnessFamilies: [ - { - family: "patch", - namespace: "aquasynth.patch.*", - witnesses: ["aquasynth.patch_graph.v0"], - durableShape: ".aquasynth/patches/{patchId}.cc", - }, - { - family: "compile", - namespace: "aquasynth.compile.*", - witnesses: ["aquasynth.faust_source.v0", "aquasynth.compiled_instrument.v0"], - durableShape: ".aquasynth/faust/{compileId}.cc", - }, - { - family: "instrument", - namespace: "aquasynth.instrument.*", - witnesses: [ - "aquasynth.compiled_instrument_session.v1", - "aquasynth.live_instrument_session.v1", - "aquasynth.instrument_open_receipt.v1", - "aquasynth.instrument_control_receipt.v1", - "aquasynth.instrument_block_receipt.v1", - "aquasynth.instrument_close_receipt.v1", - ], - durableShape: ".aquasynth/sessions/{sessionId}.cc and .aquasynth/live-sessions/{sessionId}.cc", - }, - { - family: "render", - namespace: "aquasynth.render.*", - witnesses: ["aquasynth.render_sample.v0", "aquasynth.render_loss.v0"], - durableShape: ".aquasynth/renders/{renderId}.cc", - }, - { - family: "speech", - namespace: "aquasynth.speech.*", - witnesses: ["aquasynth.utterance_embedding.v0", "aquasynth.speech_render_receipt.v0"], - durableShape: ".aquasynth/speech/{utteranceId}.cc", - }, - ], - commandBoundaries: [ - { - id: "aquasynth.command.patch.compile", - owner: "AquaSynth", - acceptedByFixture: false, - allowedInputs: [".aqua DSL", "compile target", "host architecture"], - emits: ["aquasynth.patch_graph.v0", "aquasynth.faust_source.v0", "aquasynth.compiled_instrument.v0"], - }, - { - id: "aquasynth.command.instrument.open", - owner: "AquaSynth", - acceptedByFixture: false, - allowedInputs: [".aqua DSL", "block size", "initial semantic control values"], - emits: ["aquasynth.compiled_instrument_session.v1", "aquasynth.live_instrument_session.v1", "aquasynth.instrument_open_receipt.v1"], - }, - { - id: "aquasynth.command.instrument.control", - owner: "AquaSynth", - acceptedByFixture: false, - allowedInputs: ["live session id", "semantic control values"], - emits: ["aquasynth.live_instrument_session.v1", "aquasynth.instrument_control_receipt.v1"], - }, - { - id: "aquasynth.command.instrument.block", - owner: "AquaSynth", - acceptedByFixture: false, - allowedInputs: ["live session id", "frame count", "optional control values"], - emits: ["aquasynth.live_instrument_session.v1", "aquasynth.instrument_block_receipt.v1"], - }, - { - id: "aquasynth.command.instrument.close", - owner: "AquaSynth", - acceptedByFixture: false, - allowedInputs: ["live session id"], - emits: ["aquasynth.live_instrument_session.v1", "aquasynth.instrument_close_receipt.v1"], - }, - { - id: "aquasynth.command.instrument.sample", - owner: "AquaSynth", - acceptedByFixture: false, - allowedInputs: [".aqua DSL", "duration", "sample format", "optional semantic control values"], - emits: ["aquasynth.render_sample.v0"], - }, - { - id: "aquasynth.command.speech.realize", - owner: "AquaSynth", - acceptedByFixture: false, - allowedInputs: ["weksa.utterance_handoff.v0", "weksa.utterance_embedding_handoff.v0.1"], - emits: ["aquasynth.utterance_embedding.v0", "aquasynth.speech_render_receipt.v0"], - forbiddenTargets: ["Weksa conversational intent truth"], - }, - ], - loweringRules: [ - "AquaSynth owns learned embeddings, synth controls, Faust compilation, native binary lifetime, compiled instrument sessions, live streaming patch sessions, and sampled outputs.", - "Weksa owns writing-to-intent and intent-to-utterance lowering.", - "Faust source and native binaries are emitted artifacts with typed receipts, not the semantic patch owner.", - "Dashboards and other renderers control and inspect sessions through CultMesh command documents and retained live-session state; they do not own audio state.", - ], -}; - -async function main() { - const args = process.argv.slice(2); - const outIndex = args.indexOf("--out"); - const outputPath = outIndex >= 0 ? args[outIndex + 1] : undefined; - const json = `${JSON.stringify(document, null, 2)}\n`; - - if (outputPath) { - const resolved = path.resolve(process.cwd(), outputPath); - await mkdir(path.dirname(resolved), { recursive: true }); - await writeFile(resolved, json, "utf8"); - return; - } - - process.stdout.write(json); -} - -main().catch((error) => { - console.error(error); - process.exitCode = 1; -}); diff --git a/tools/publish-stable/publish_stable.py b/tools/publish-stable/publish_stable.py deleted file mode 100644 index 88b164f..0000000 --- a/tools/publish-stable/publish_stable.py +++ /dev/null @@ -1,157 +0,0 @@ -#!/usr/bin/env python3 -"""The one script that publishes AquaSynth listening pages: one dev, one URL, overwritten in place. - - publish_stable.py dings SRC_DIR -> /srv/minds-web/aqua/dings/ (https://minds.gamecult.org/aqua/dings/) - publish_stable.py ear SRC_DIR -> /srv/minds-web/aqua/ear/ (https://minds.gamecult.org/aqua/ear/) - publish_stable.py banners -> banner on every older per-hash page, pointing at the stable pages - -SRC_DIR for `dings` is a built publish dir (index.html, out/, findings/, metrics.json; see tools/dings-voices/README.md); -for `ear` a dir of aqua-ear outputs (one subdir per run, each with report.txt/png files, as `aqua_ear.py --out` writes). -Stdlib only. Idempotent: running it again with the same input leaves the same tree; the stable dir is swapped with a fully -written staging dir in one atomic exchange (renameat2), so it is never missing or half-copied, even if the process is killed. Deletes nothing outside the stable dir it owns. ---root and --base are for tests. Nothing here listens to anything: it moves files and stamps a header. -""" -import argparse, ctypes, fcntl, glob, html, os, re, shutil, subprocess, sys, tempfile - -ROOT = "/srv/minds-web/aqua" -BASE = "https://minds.gamecult.org/aqua" -STABLE = {"dings": "dings", "ear": "ear"} -MARK = "aqua-stable-banner" -BANNER_CSS = "background:#fff3c4;color:#222;border:2px solid #b58900;padding:.6rem 1rem;margin:0;font:1rem/1.4 system-ui,sans-serif" - - -def rev(): - try: - return subprocess.check_output(["git", "-C", os.path.dirname(os.path.abspath(__file__)), "rev-parse", "--short", "HEAD"], text=True).strip() - except Exception: - return "unknown" - - -def banner(inner): - return f'
{inner}
\n' - - -def put_banner(path, inner): - """Insert (or replace) the marked banner right after , else after , else at the top. Idempotent.""" - s = open(path, encoding="utf-8").read() - s = re.sub(rf'
\n?', "", s, flags=re.S) - b = banner(inner) - m = re.search(r"]*>", s, re.I) or re.search(r"", s, re.I) - s = s[:m.end()] + "\n" + b + s[m.end():] if m else b + s - open(path, "w", encoding="utf-8").write(s) - - -def _exchange(a, b): - """Atomically swap two directories (renameat2 RENAME_EXCHANGE). There is no instant at which either path is absent.""" - libc = ctypes.CDLL(None, use_errno=True) - fn = getattr(libc, "renameat2", None) - if fn is None: - raise OSError("renameat2 is not available; refusing a non-atomic swap") - AT_FDCWD, RENAME_EXCHANGE = -100, 2 - if fn(AT_FDCWD, os.fsencode(a), AT_FDCWD, os.fsencode(b), RENAME_EXCHANGE) != 0: - e = ctypes.get_errno() - raise OSError(e, f"renameat2(RENAME_EXCHANGE) {a} <-> {b}: {os.strerror(e)}") - - -def swap_in(src, dest, prepare): - """Make dest a complete copy of src (stamped by prepare) without a moment when dest is missing or half-written. - - The copy is built in a staging dir beside dest; then dest and the staging dir are EXCHANGED in one syscall (a plain rename - when dest does not exist yet) and the staging dir, now holding the old tree, is deleted. An interrupted run leaves dest as - the old complete tree or the new complete tree, plus at most a staging dir, which the next run removes under a lock - that serialises publishers of the same target.""" - parent, name = os.path.dirname(dest), os.path.basename(dest) - os.makedirs(parent, exist_ok=True) - with open(os.path.join(parent, f".{name}.lock"), "w") as lock: - fcntl.flock(lock, fcntl.LOCK_EX) - for leftover in glob.glob(os.path.join(parent, f".stage-{name}-*")): - shutil.rmtree(leftover, ignore_errors=True) - stage = tempfile.mkdtemp(prefix=f".stage-{name}-", dir=parent) - try: - shutil.copytree(src, stage, dirs_exist_ok=True) - prepare(stage) - os.chmod(stage, 0o755) - if os.path.isdir(dest): - _exchange(stage, dest) # stage now holds the old tree - else: - os.rename(stage, dest) - stage = None - finally: - if stage: - shutil.rmtree(stage, ignore_errors=True) - - -def publish_dings(src, root, base): - if not os.path.isfile(os.path.join(src, "index.html")) or not os.path.isdir(os.path.join(src, "out", "senders")): - sys.exit(f"{src} is not a built dings publish dir (needs index.html and out/senders)") - label = os.path.basename(os.path.abspath(src)) - note = (f"The one Dings page. {base}/dings/ always shows the latest version; it is overwritten in place. " - f"Current: {html.escape(label)}, AquaSynth {rev()}. Older per-version pages are kept but are not the place to listen.") - - def prepare(stage): - put_banner(os.path.join(stage, "index.html"), note) - open(os.path.join(stage, "VERSION"), "w").write(f"{label}\nAquaSynth {rev()}\n") - swap_in(src, os.path.join(root, STABLE["dings"]), prepare) - - -def publish_ear(src, root, base): - runs = sorted(d for d in os.listdir(src) if os.path.isdir(os.path.join(src, d))) - if not runs: - sys.exit(f"{src} has no run subdirectories") - - def prepare(stage): - items = [] - for r in runs: - files = sorted(f for f in os.listdir(os.path.join(stage, r)) if os.path.isfile(os.path.join(stage, r, f))) - links = " · ".join(f'{html.escape(f)}' for f in files) - img = next((f for f in ("compare.png", "spectrogram.png") if f in files), None) - pic = f'

{html.escape(r)}

' if img else "" - items.append(f"

{html.escape(r)}

{pic}

{links}

") - page = ('' - "aqua-ear examples" - "

aqua-ear examples

Pictures and reports from tools/aqua-ear (spectrogram, onsets, level envelope, detector verdicts). " - "They are signal facts: the tool cannot judge timbre, annoyance or feel, and nobody has judged these by ear. " - f"Current as of AquaSynth {rev()}.

" + "".join(items) + "\n") - open(os.path.join(stage, "index.html"), "w").write(page) - put_banner(os.path.join(stage, "index.html"), f"The one aqua-ear examples page. {base}/ear/ is overwritten in place.") - swap_in(src, os.path.join(root, STABLE["ear"]), prepare) - - -def banners(root, base): - skip = set(STABLE.values()) - for d in sorted(os.listdir(root)): - p = os.path.join(root, d) - if d in skip or d.startswith(".") or not os.path.isdir(p): - continue - dings = d.startswith("dings-voices-") - inner = (f"Old per-version page. The one Dings page is {base}/dings/ (always the latest); listen there." - if dings else - f"Old per-version page, kept for the record. One-place rule: current Dings are at {base}/dings/, " - f"aqua-ear examples at {base}/ear/.") - idx = os.path.join(p, "index.html") - if not os.path.exists(idx): # a dir with no page of its own gets a minimal one, so the banner has somewhere to stand - files = sorted(os.listdir(p)) - open(idx, "w").write('' + html.escape(d) + "

" + html.escape(d) - + "

\n") - put_banner(idx, inner) - print("banner:", idx) - - -def main(): - ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) - ap.add_argument("what", choices=["dings", "ear", "banners"]) - ap.add_argument("src", nargs="?") - ap.add_argument("--root", default=ROOT) - ap.add_argument("--base", default=BASE) - a = ap.parse_args() - if a.what == "banners": - banners(a.root, a.base) - return - if not a.src or not os.path.isdir(a.src): - sys.exit("SRC_DIR is required and must be a directory") - {"dings": publish_dings, "ear": publish_ear}[a.what](a.src, a.root, a.base) - print(f"published {a.what}: {a.root}/{STABLE[a.what]}/ -> {a.base}/{STABLE[a.what]}/") - - -if __name__ == "__main__": - main() diff --git a/tools/publish-stable/test_interruption.py b/tools/publish-stable/test_interruption.py deleted file mode 100644 index 7dc7362..0000000 --- a/tools/publish-stable/test_interruption.py +++ /dev/null @@ -1,69 +0,0 @@ -"""A publish that is killed at ANY filesystem mutation, or read concurrently, never leaves the live dir missing or half-written. -Implementation-agnostic: a sys.audit hook counts every mutating event (rename, mkdir, rmtree, remove, copyfile, ctypes call) and -os._exit()s the publisher at the Nth one; the live dir is then checked against the old and new trees.""" -import os, subprocess, sys, tempfile, threading, unittest -HERE = os.path.dirname(os.path.abspath(__file__)); S = os.path.join(HERE, "publish_stable.py") -MUTATING = {"os.rename", "os.mkdir", "os.rmdir", "os.remove", "shutil.rmtree", "shutil.copyfile", "shutil.copymode", "ctypes.call_function", "os.chmod"} -RUNNER = r''' -import sys, os, runpy -kill_at = int(sys.argv[1]); counter = [0] -MUT = %r -def hook(ev, args): - if ev in MUT: - counter[0] += 1 - if kill_at and counter[0] == kill_at: os._exit(9) -sys.addaudithook(hook) -sys.argv = [%r, "dings", sys.argv[2], "--root", sys.argv[3]] -try: runpy.run_path(%r, run_name="__main__") -finally: - if not kill_at: print("EVENTS", counter[0]) -''' % (MUTATING, S, S) -def make_src(d, tag): - os.makedirs(d + "/out/senders"); open(d + "/index.html", "w").write(f"VERSION-{tag}"); open(d + "/out/senders/a.ogg", "w").write(f"OggS-{tag}" * 5000) -def snapshot(d): return sorted((os.path.relpath(os.path.join(r, f), d), open(os.path.join(r, f)).read()) for r, _, fs in os.walk(d) for f in fs if f != "VERSION") -class T(unittest.TestCase): - def setUp(self): - self.t = tempfile.TemporaryDirectory(); self.root = self.t.name + "/aqua"; os.makedirs(self.root) - self.a, self.b = self.t.name + "/dings-voices-aaa", self.t.name + "/dings-voices-bbb"; make_src(self.a, "A"); make_src(self.b, "B") - self.run_runner = lambda kill, src: subprocess.run([sys.executable, "-c", RUNNER, str(kill), src, self.root], capture_output=True, text=True) - self.live = self.root + "/dings" - def tearDown(self): self.t.cleanup() - def stamped(self, src): # what the live dir holds after a clean publish of src - with tempfile.TemporaryDirectory() as r: self.assertEqual(self.run_runner(0, src).returncode, 0) if False else subprocess.run([sys.executable, S, "dings", src, "--root", r], check=True, capture_output=True); return snapshot(r + "/dings") - def test_kill_at_every_step_over_an_existing_page_keeps_a_complete_tree(self): - old, new = self.stamped(self.a), self.stamped(self.b) - r = self.run_runner(0, self.a); self.assertEqual(r.returncode, 0, r.stderr) - n = int([l for l in r.stdout.splitlines() if l.startswith("EVENTS")][0].split()[1]); self.assertGreater(n, 5) - for kill in range(1, n + 1): - subprocess.run([sys.executable, S, "dings", self.a, "--root", self.root], check=True, capture_output=True) - self.assertEqual(self.run_runner(kill, self.b).returncode, 9) - self.assertTrue(os.path.isdir(self.live), f"live dir missing after a kill at mutation {kill} of {n}") - self.assertIn(snapshot(self.live), (old, new), f"live dir half-written after a kill at mutation {kill} of {n}") - subprocess.run([sys.executable, S, "dings", self.b, "--root", self.root], check=True, capture_output=True) # the next run heals - self.assertEqual(snapshot(self.live), new); self.assertEqual([f for f in os.listdir(self.root) if f.startswith(".stage-") or f.endswith(".old")], [], f"stale staging after healing run (kill {kill})") - def test_kill_during_the_very_first_publish_never_leaves_a_half_written_page(self): - new = self.stamped(self.b) - r = self.run_runner(0, self.b); n = int([l for l in r.stdout.splitlines() if l.startswith("EVENTS")][0].split()[1]) - for kill in range(1, n + 1): - subprocess.run(["rm", "-rf", self.live]); self.assertEqual(self.run_runner(kill, self.b).returncode, 9) - if os.path.isdir(self.live): self.assertEqual(snapshot(self.live), new, f"half-written first publish after kill {kill}") - def test_a_raising_step_keeps_the_old_page_and_cleans_its_staging(self): - subprocess.run([sys.executable, S, "dings", self.a, "--root", self.root], check=True, capture_output=True); old = snapshot(self.live) - os.remove(self.b + "/index.html") - self.assertNotEqual(subprocess.run([sys.executable, S, "dings", self.b, "--root", self.root], capture_output=True).returncode, 0) - self.assertEqual(snapshot(self.live), old); self.assertEqual([f for f in os.listdir(self.root) if f.startswith(".stage-")], []) - def test_a_concurrent_reader_never_finds_the_page_missing_or_cut_short(self): - subprocess.run([sys.executable, S, "dings", self.a, "--root", self.root], check=True, capture_output=True) - bad, stop = [], threading.Event() - def reader(): - while not stop.is_set(): - try: - idx = open(self.live + "/index.html").read(); ogg = open(self.live + "/out/senders/a.ogg").read() - if "VERSION-" not in idx or not (ogg.startswith("OggS-A") or ogg.startswith("OggS-B")) or len(ogg) not in (len("OggS-A") * 5000,): bad.append("partial") - except OSError as e: bad.append(repr(e)) - th = [threading.Thread(target=reader) for _ in range(4)]; [x.start() for x in th] - try: - for i in range(30): subprocess.run([sys.executable, S, "dings", self.b if i % 2 == 0 else self.a, "--root", self.root], check=True, capture_output=True) - finally: stop.set(); [x.join() for x in th] - self.assertEqual(bad, []) -if __name__ == "__main__": unittest.main() diff --git a/tools/publish-stable/test_publish_stable.py b/tools/publish-stable/test_publish_stable.py deleted file mode 100644 index 35f01e4..0000000 --- a/tools/publish-stable/test_publish_stable.py +++ /dev/null @@ -1,40 +0,0 @@ -import os, subprocess, sys, tempfile, unittest -HERE = os.path.dirname(os.path.abspath(__file__)); S = os.path.join(HERE, "publish_stable.py") -def run(*a): return subprocess.run([sys.executable, S, *a], capture_output=True, text=True) -def tree(root): return sorted((os.path.relpath(os.path.join(d, f), root), open(os.path.join(d, f), "rb").read()) for d, _, fs in os.walk(root) for f in fs) -class T(unittest.TestCase): - def setUp(self): - self.t = tempfile.TemporaryDirectory(); self.root = os.path.join(self.t.name, "aqua"); os.makedirs(self.root) - self.src = os.path.join(self.t.name, "dings-voices-abc1234"); os.makedirs(self.src + "/out/senders") - open(self.src + "/index.html", "w").write("x

v

") - open(self.src + "/out/senders/a.ogg", "wb").write(b"OggS") - def tearDown(self): self.t.cleanup() - def test_publish_overwrites_in_place_and_is_idempotent(self): - r = run("dings", self.src, "--root", self.root); self.assertEqual(r.returncode, 0, r.stderr) - first = tree(self.root + "/dings"); r = run("dings", self.src, "--root", self.root); self.assertEqual(r.returncode, 0, r.stderr) - self.assertEqual(first, tree(self.root + "/dings")) - page = open(self.root + "/dings/index.html").read(); self.assertEqual(page.count('

old

"), ("trial-1", "

no body tag

")): - os.makedirs(f"{self.root}/{d}"); open(f"{self.root}/{d}/index.html", "w").write(body) - os.makedirs(self.root + "/aqua-ear-examples"); open(self.root + "/aqua-ear-examples/x.png", "wb").write(b"p") - for _ in range(2): self.assertEqual(run("banners", "--root", self.root).returncode, 0) - for d in ("dings-voices-old", "trial-1", "aqua-ear-examples"): - p = open(f"{self.root}/{d}/index.html").read(); self.assertEqual(p.count('
&1 | Tee-Object -FilePath $LogPath -Append - if ($LASTEXITCODE -ne 0) { - throw "Command failed with exit code $LASTEXITCODE`: $display" - } - } - finally { - foreach ($key in $Environment.Keys) { - [Environment]::SetEnvironmentVariable($key, $oldValues[$key], "Process") - } - } -} - -function Invoke-CodexAgent { - param( - [string]$RepoRoot, - [string]$Prompt, - [string]$OutputPath, - [string]$LogPath, - [string]$CodexCommand, - [string]$CodexModel, - [bool]$AllowSourceEdits - ) - - $promptPath = [IO.Path]::ChangeExtension($OutputPath, ".prompt.md") - New-Item -ItemType Directory -Force -Path (Split-Path -Parent $OutputPath) | Out-Null - Set-Content -LiteralPath $promptPath -Value $Prompt - - $args = @( - "exec", - "--cd", $RepoRoot, - "--full-auto", - "--output-last-message", $OutputPath - ) - if ($CodexModel.Length -gt 0) { - $args += @("--model", $CodexModel) - } - if (-not $AllowSourceEdits) { - $args += @( - "--config", 'shell_environment_policy.inherit="all"', - "--config", 'sandbox_permissions=["workspace-write"]' - ) - } - $args += "-" - - $previousErrorActionPreference = $ErrorActionPreference - $ErrorActionPreference = "Continue" - try { - Get-Content -LiteralPath $promptPath -Raw | & $CodexCommand @args 2>&1 | Tee-Object -FilePath $LogPath -Append - $exitCode = $LASTEXITCODE - } - finally { - $ErrorActionPreference = $previousErrorActionPreference - } - - if ($exitCode -ne 0) { - throw "External Codex agent failed with exit code $exitCode. See $LogPath." - } -} - -function Assert-CandidateBatch { - param( - [string]$PatchDirectory - ) - - $targetSets = @( - @("a", "i", "u", "e", "o"), - @("m", "n", "ng", "l", "r"), - @("s", "z", "f", "v", "th"), - @("p", "b", "t", "d", "k"), - @("mix-a", "mix-m", "mix-s", "mix-p", "mix-u") - ) - $files = @(Get-ChildItem -LiteralPath $PatchDirectory -Filter "*.aqua" -File -Recurse) - if ($files.Count -ne 25) { - throw "Hypothesis worker wrote $($files.Count) .aqua candidates; expected exactly 25." - } - - $stems = $files | ForEach-Object { [IO.Path]::GetFileNameWithoutExtension($_.Name) } - foreach ($targetSet in $targetSets) { - foreach ($target in $targetSet) { - $covered = $false - foreach ($stem in $stems) { - if ($stem.StartsWith("$target`__", [StringComparison]::OrdinalIgnoreCase)) { - $covered = $true - break - } - } - - if (-not $covered) { - throw "Hypothesis worker did not write a candidate for target '$target'. Candidate files must be named ____.aqua." - } - } - } - - foreach ($stem in $stems) { - $parts = $stem.Split([string[]]@("__"), [StringSplitOptions]::None) - if ($parts.Count -lt 3 -or [string]::IsNullOrWhiteSpace($parts[1]) -or [string]::IsNullOrWhiteSpace($parts[2])) { - throw "Candidate '$stem' does not follow ____.aqua." - } - - if ($parts[1] -cnotmatch '^[a-z0-9]+(-[a-z0-9]+)*$') { - throw "Candidate '$stem' uses invalid family '$($parts[1])'. Family ids must be lowercase kebab-case." - } - } -} - -function Invoke-SourceEditVerification { - param( - [string]$LogPath, - [bool]$AllowSourceEdits - ) - - if (-not $AllowSourceEdits) { - return - } - - Invoke-LoggedProcess ` - -FilePath "dotnet" ` - -ArgumentList @( - "build", - "tests\AquaSynth.Dsl.Tests\AquaSynth.Dsl.Tests.csproj", - "--no-restore", - "--disable-build-servers", - "-p:UseSharedCompilation=false", - "-p:BuildInParallel=false", - "-v", - "minimal" - ) ` - -LogPath $LogPath -} - -$repoRoot = Resolve-RepoRoot -$codex = Get-Command $CodexCommand -ErrorAction Stop -$loopId = New-Timestamp -$loopRoot = Join-Path $repoRoot "artifacts/parity/ipa-trial-loops/$loopId" -$logRoot = Join-Path $loopRoot "logs" -New-Item -ItemType Directory -Force -Path $loopRoot, $logRoot | Out-Null -$storePath = Join-Path $loopRoot "ipa-trial-results.cc" -$workerProject = Join-Path $repoRoot "tools/IpaTrialWorker/IpaTrialWorker.csproj" - -$indexPath = Join-Path $loopRoot "loop-index.md" -Set-Content -LiteralPath $indexPath -Value @" -# IPA Trial Loop $loopId - -- repo: $repoRoot -- codex: $($codex.Source) -- rounds: $Rounds -- batch_id: $BatchId -- allow_source_edits: $AllowCodexSourceEdits -- trial_results_store: $storePath -- worker: $workerProject -- trial_shape: five rounds, exactly 25 candidates per round, one per phoneme lane - -"@ - -if (-not $SkipLocalTrialRun) { - $seedLog = Join-Path $logRoot "seed-trial-run.log" - Invoke-LoggedProcess ` - -FilePath "dotnet" ` - -ArgumentList @( - "run", - "--project", - $workerProject, - "--", - "seed", - "--artifact-root", - $loopRoot, - "--batch-id", - $BatchId, - "--store", - $storePath - ) ` - -LogPath $seedLog -} -else { - Add-Content -LiteralPath $indexPath -Value "- seed: skipped" -} - -for ($round = 1; $round -le $Rounds; $round++) { - $roundId = "round-{0:000}" -f $round - $roundDir = Join-Path $loopRoot $roundId - $patchDir = Join-Path $roundDir "proposed-patches" - New-Item -ItemType Directory -Force -Path $roundDir | Out-Null - New-Item -ItemType Directory -Force -Path $patchDir | Out-Null - Add-Content -LiteralPath $indexPath -Value "- ${roundId}: $roundDir" - - $indexBeforeLog = Join-Path $logRoot "$roundId-index-before.log" - Invoke-LoggedProcess ` - -FilePath "dotnet" ` - -ArgumentList @( - "run", - "--project", - $workerProject, - "--", - "index", - "--store", - $storePath, - "--output", - (Join-Path $roundDir "vector-index-before.md") - ) ` - -LogPath $indexBeforeLog - - $preEvidence = Join-Path $roundDir "semantic-search-before.md" - $preDumpLog = Join-Path $logRoot "$roundId-search-before.log" - Invoke-LoggedProcess ` - -FilePath "dotnet" ` - -ArgumentList @( - "run", - "--project", - $workerProject, - "--", - "search", - "--store", - $storePath, - "--query", - "weak promising generalization vowel nasal fricative stop articulation owner source tract radiation gesture primitive dressing DSL lowering Faust machinery scene voices background noise", - "--limit", - "40", - "--output", - $preEvidence, - "--skip-index", - "true" - ) ` - -LogPath $preDumpLog - - $hypothesisOutput = Join-Path $roundDir "hypothesis-agent.md" - $hypothesisLog = Join-Path $logRoot "$roundId-hypothesis-agent.log" - $previousRoundId = "round-{0:000}" -f ($round - 1) - $previousEvaluation = if ($round -gt 1) { Join-Path (Join-Path $loopRoot $previousRoundId) "evaluation.md" } else { "none" } - $hypothesisPrompt = @" -You are an AquaSynth IPA loss-landscape hypothesis and patch-writing worker. - -Read this semantic search result from the CultCache trial-results database: -$preEvidence - -The backing store is: -$storePath - -Previous round evaluation: -$previousEvaluation - -Use the worker as your search organ. Do not ask for crude full dumps unless retrieval fails: -`$env:DOTNET_CLI_HOME="$roundDir/dotnet-home"; `$env:DOTNET_SKIP_FIRST_TIME_EXPERIENCE="1"; `$env:DOTNET_ADD_GLOBAL_TOOLS_TO_PATH="0"; `$env:DOTNET_CLI_TELEMETRY_OPTOUT="1"; dotnet run --no-build --no-restore --project tools/IpaTrialWorker/IpaTrialWorker.csproj -- search --store "$storePath" --query "" --limit 20 --output "$roundDir/search-.md" --skip-index true -`$env:DOTNET_CLI_HOME="$roundDir/dotnet-home"; `$env:DOTNET_SKIP_FIRST_TIME_EXPERIENCE="1"; `$env:DOTNET_ADD_GLOBAL_TOOLS_TO_PATH="0"; `$env:DOTNET_CLI_TELEMETRY_OPTOUT="1"; dotnet run --no-build --no-restore --project tools/IpaTrialWorker/IpaTrialWorker.csproj -- show --store "$storePath" --trial-id "" --output "$roundDir/detail-.md" - -Retrieval failure policy: -- A failed search/show command is itself evidence about the worker environment, but it is low-quality evidence for speech hypotheses. -- Fallback artifact reads may appear in `Weakest Missing Evidence`, but they do not satisfy the search/show receipt counts. -- Do not write patches until live `search` and `show` receipts exist. -- Search-summary-only claims are low-quality until corroborated by a `show` receipt with concrete metric values or artifact paths. - -Useful repo surfaces: -- docs/ipa-vocal-tract-roadmap.md -- docs/audio-doctrine.md -- src/AquaSynth.Core/IpaGestureExperiment.cs -- src/AquaSynth.Core/Model.cs -- src/AquaSynth.Core/PatchScript.cs -- src/AquaSynth.Core/ControlSplineTimeline.cs -- src/AquaSynth.Core/ProbeTimelineReport.cs -- src/AquaSynth.Core/FaustExport.cs -- src/AquaSynth.Faust/IpaTrialOrchestrator.cs -- tools/IpaTrialWorker/Program.cs -- artifacts under $loopRoot - -Before writing candidates: -0. Open $preEvidence and include a `PreEvidence Digest` section in $roundDir/hypotheses.md with five metric-bearing facts from it. -1. Run exactly three targeted semantic searches and save the outputs under ${roundDir}: - - one for weakest stop/plosive closure evidence; - - one for best vowel/nasal/fricative transferable successes; - - one for DSL lowering/Faust machinery, scene voices, background-noise modeling, and dressing/FM/AM/noise versus articulation-owner failures. -2. Open exactly three detailed trial records with `show`: one weak stop/plosive, one transferable success, and one dressing-vs-articulation case when available. -3. In $roundDir/hypotheses.md, include a `Retrieval Receipts` section listing the exact search/show files you used. -4. If fewer than three search receipts and three show receipts exist on disk, stop and create the missing retrieval artifacts before writing `.aqua` files. -5. Do not run additional retrieval unless one of the six required receipts is empty or unrelated; spend the rest of the turn reasoning over the evidence. -6. For every seam you name, cite at least one contrast pair: a weak record and a stronger related record, or two variants that isolate one axis. If the receipts do not contain a contrast pair, mark the seam `not actionable`. -7. Extract primitive timeline facts when available: closure duration, burst/release window, voicing onset, constriction window, branch admittance, radiation flow, or passivity/energy. If timelines are absent, mark timeline evidence `missing` instead of implying it. -8. Read the previous round evaluation when it exists. A failed, flat, or regressed family is falsified until you state exactly what changed. Do not reuse family names or rotate old family ideas across new targets unless the report includes a `Previous Round Learning` section with the prior metric movement, accepted lesson, rejected lesson, and mutation that makes the new test different. - -Task: -1. Read the current loss landscape across gesture, log-mel, RMS, articulation, and primitive timeline evidence. -2. Invent the next candidate patches across five five-phoneme target sets: - vowels: a, i, u, e, o - nasals/approximants: m, n, ng, l, r - fricatives: s, z, f, v, th - stops: p, b, t, d, k - mixed generalization: mix-a, mix-m, mix-s, mix-p, mix-u -3. Write exactly twenty-five new .aqua candidates under: -$patchDir - Name each file ____.aqua so the scorer can infer the reference target and hypothesis family. -4. Make the candidates test transferable hypotheses, not one-off phoneme golf. Reuse the same contour idea across multiple places/manners when that is the claim being tested. -5. If source edits are allowed, refine the DSL or lowering code only when the evidence says the graph owner is wrong rather than the patch values. -6. Write a concise hypothesis report to: -$roundDir/hypotheses.md - -Source-code golf contract: -- Source edits allowed: $AllowCodexSourceEdits -- When source edits are allowed, you may edit `src/`, `tests/`, `docs/`, and `tools/` to test DSL syntax, DSL lowering, Faust emission, worker scoring, or scene-voice evidence surfaces. -- Do not edit generated artifacts, existing `.cc` stores, existing trial results, or previous round reports. -- Source edits must move one named owner, not add compensators. Use the sentence `X owns Y so Z remains true`. -- Valid source hypotheses include: new patch DSL syntax, parser/model records, Faust lowering changes, ProbeTimeline fields, IpaTrialWorker evidence/reporting, or tests that prove the new syntax/lowering path. -- Invalid source hypotheses include: broad rewrites, changing metric thresholds to flatter candidates, deleting hard evidence, mutating references, or hardcoding a candidate name. -- If you edit source, write `$roundDir/source-change-plan.md` with: owner map, files edited, invariant, expected metric movement, tests/build commands to run, and rollback trigger. -- If you do not edit source, write `Source Edit Decision: none` and explain which evidence is still missing. - -Scene voice model: -- Every candidate patch represents a scene, not a single naked waveform. The report must name the scene voices and say how each is synthesized. -- Required scene voice roles: `primary-articulatory`, `tract-noise`, `release/transient`, `background-room`, and `recording-condition`. -- Use ordinary AquaSynth primitives for helper voices where useful: `voice` layers, noise, FM, AM/tremolo, envelopes, filters, formants, additive/spectral voices, macros, and modulation. These helper voices are allowed in full parity. -- At least one hypothesis family must implement real helper/background scene voices in the `.aqua` scripts using ordinary `voice` declarations, such as filtered `wave=noise`, FM partials, AM/tremolo beds, or formant-colored capture layers. Do not satisfy the scene voice requirement with prose alone. -- When adding helper voices, keep gain low and name the role in the report. The primary articulatory `vocal network=...` voice must remain present unless the family explicitly tests a source-edit replacement. -- Helper/background voices must not count as articulation evidence unless gesture, primitive timeline, and clean vocal metrics move coherently. -- For each family, say which voices are active, which controls they expose, and which metric/timeline witness would prove the helper is not merely dressing. - -Candidate design contract: -- Produce exactly 25 files: exactly one candidate for each target lane. No extras. -- Use 3-5 named hypothesis families across the 25 files, for example source-carrier, constriction-place, stop-release, nasal-branch, scene-noise-bed, and lowering-release-owner. -- Filename schema is mandatory: ____.aqua. -- Family ids must be lowercase kebab-case and reused verbatim in filenames and `Hypothesis Families`. -- The family segment in filenames is the canonical hypothesis-family id used by the evaluator. -- The same family name should appear in filenames across multiple target sets when you are testing generalization. -- A family is transferable only if it appears in at least three target sets; otherwise label it exploratory in the report. -- A family must be phonetic-class aligned. Stop-release families belong on stop and `mix-p` lanes; nasal-branch families belong on nasal/approximant and `mix-m` lanes; frication families belong on fricative and `mix-s` lanes; vowel-shape/source families belong on vowel and vowel-like mixed lanes. Cross-class use is allowed only when the family explicitly tests transfer and the candidate changes a class-appropriate control subset for that target. -- Do not distribute families round-robin across target ids. A candidate matrix that assigns stop-release to vowels, nasal-branch to stops, or scene-noise to arbitrary phonemes without a class-specific control plan is failed science even when the file count is correct. -- Each family must include a target-class lane plan: which target classes it applies to, why those classes are lawful for the owner, and which class-specific controls change. If a target is outside the family class, the matrix must say `transfer-test` and name the class-specific mutation. -- Keep `.aqua` scripts parseable and self-contained. Prefer modifying values and gesture contours already visible in seed candidates before inventing new syntax. -- Do not use source edits as a way to rescue malformed candidate patches; use source edits to make a coherent syntax/lowering/Faust owner possible. -- Only edit source if two or more retrieved trials indicate the same owner-layer failure pattern, or if at least two scene-voice candidates need the same missing DSL/lowering primitive; otherwise `Source Edit Decision: none`. -- If Source edits allowed is False, do not edit any file outside $patchDir and $roundDir/hypotheses.md. -- Before finishing, list $patchDir and verify exact count, target coverage, and filename schema in `Acceptance Checklist`. -- A seam claim must use an owner sentence: `X owns Y so Z remains true`. -- A seam is actionable only if the next candidate family proposes at least five micro-sweep perturbations across that seam, spread across target lanes when possible. -- Novelty gate: a family must move a new owner, control axis, timing contour, or primitive relationship. Raising loudness, burst gain, or dressing alone is not novel. -- Scene novelty can be valid only when it changes a named voice role, routing/lowering primitive, modulation relationship, or background-noise synthesis model and predicts a non-articulation witness such as noise-floor, spectral tilt, RMS stability, or room/recording match. A scene-noise or recording-condition family that does not add an actual helper voice is not novel. -- Include a class-consistent reference matrix that maps each target id to the exact reference trial or fixture id used for comparison; mixed-set evidence cannot silently stand in for single-phoneme evidence. - -Required `$roundDir/hypotheses.md` shape: -- `Previous Round Learning`: if a previous evaluation exists, summarize which family claims were falsified/flat/improved, what lesson survives, and exactly how this round mutates the next test. If no previous round exists, write `first round`. -- `PreEvidence Digest`: five facts with exact metric keys and values from $preEvidence. -- `Retrieval Receipts`: search/show files used. -- `Loss Landscape Read`: strongest and weakest evidence by family. -- `Reference Matrix`: one row per target id with reference trial/fixture id, candidate baseline if known, and whether the evidence is class-consistent or mixed/weak. -- `Hypothesis Families`: 3-5 families, each with owner layer, transfer status, evidence_refs, cited trial_ids, at least one concrete metric key/value from `show`, a contrast pair, an owner sentence of the form `X owns Y so Z remains true`, five planned micro-sweep perturbations, and predicted metric movement using `gesture:+/-/flat`, `logmel:+/-/flat`, `articulation:+/-/flat`, `rms:+/-/flat`, `timeline:+/-/flat/risk`. -- `Target-Class Lane Plan`: one row per family naming allowed target classes, forbidden target classes, lawful transfer lanes, and class-specific controls that change. -- `Scene Voice Model`: one row per family with primary voice, helper/background voices, AquaSynth primitives used, controls exposed, expected non-articulation witnesses, and dressing risk. -- `Claim Audit`: one row per family: claim -> evidence file(s) -> contrast pair -> metric key/value(s) -> primitive timeline excerpt or `missing` -> predicted movement. -- `Evidence Quality Ledger`: one row per family with specificity, comparability, falsifiability, reuse value for the next round, and the weakest missing evidence. Use `high`, `medium`, or `low` for each quality field. -- `Novelty Gate`: one row per family saying which new owner/control axis/timing contour/primitive relationship is being explored; write `dressing-only` if the family mainly changes loudness/FM/AM/noise/envelopes. -- `Candidate Matrix`: exactly 25 rows with target id, filename, family, expected metric movement, and risk. -- `Source Edit Decision`: `none` unless source edits are allowed and justified by evidence; if source was edited, link `$roundDir/source-change-plan.md`, list files changed, tests/builds run or pending, and rollback trigger. -- `Acceptance Checklist`: 25 files, one per target id, filename schema, required report sections, >=3 search receipts, >=3 show receipts, target-class lane plan present, no round-robin family assignment, and at least one family with actual auxiliary `voice` helper/background declarations in its candidate scripts. - -Authority boundary: -- Source edits allowed: $AllowCodexSourceEdits -- Do not rewrite existing trial artifacts or the CultCache store directly. -- The worker process owns measurement and .cc writes; you own candidate invention and optional source refinements. -- Keep gesture_score, clean vocal/audio evidence, and full parity dressing separate. -- Patch candidates should make full use of AquaSynth general synth primitives when modeling the scene: FM, AM, modulators, envelopes, filters, formants, noise voices, additive/spectral layers, and extra animated voices. Call out when these are background/recording-condition voices rather than articulation. -- Prefer fixing primitive owners over adding audio dressing when the evidence says air is missing. - -Return a short final summary naming the files you wrote. -"@ - Invoke-CodexAgent ` - -RepoRoot $repoRoot ` - -Prompt $hypothesisPrompt ` - -OutputPath $hypothesisOutput ` - -LogPath $hypothesisLog ` - -CodexCommand $CodexCommand ` - -CodexModel $CodexModel ` - -AllowSourceEdits:$AllowCodexSourceEdits - - Assert-CandidateBatch -PatchDirectory $patchDir - - $sourceVerifyLog = Join-Path $logRoot "$roundId-source-edit-verification.log" - Invoke-SourceEditVerification ` - -LogPath $sourceVerifyLog ` - -AllowSourceEdits:$AllowCodexSourceEdits - - $scoreLog = Join-Path $logRoot "$roundId-score-candidates.log" - Invoke-LoggedProcess ` - -FilePath "dotnet" ` - -ArgumentList @( - "run", - "--project", - $workerProject, - "--", - "score", - "--patch-root", - $patchDir, - "--artifact-root", - $roundDir, - "--batch-id", - $roundId, - "--store", - $storePath, - "--hypothesizer", - "external-codex-$roundId" - ) ` - -LogPath $scoreLog - - $indexAfterLog = Join-Path $logRoot "$roundId-index-after.log" - Invoke-LoggedProcess ` - -FilePath "dotnet" ` - -ArgumentList @( - "run", - "--project", - $workerProject, - "--", - "index", - "--store", - $storePath, - "--output", - (Join-Path $roundDir "vector-index-after.md") - ) ` - -LogPath $indexAfterLog - - $postEvidence = Join-Path $roundDir "semantic-search-after.md" - $postDumpLog = Join-Path $logRoot "$roundId-search-after.log" - Invoke-LoggedProcess ` - -FilePath "dotnet" ` - -ArgumentList @( - "run", - "--project", - $workerProject, - "--", - "search", - "--store", - $storePath, - "--query", - "latest round weak promising transfer generalization vowel nasal fricative stop articulation owner source tract radiation gesture primitive dressing DSL lowering Faust machinery scene voices background noise", - "--limit", - "60", - "--output", - $postEvidence, - "--skip-index", - "true" - ) ` - -LogPath $postDumpLog - - $evaluatorOutput = Join-Path $roundDir "evaluator-agent.md" - $evaluatorLog = Join-Path $logRoot "$roundId-evaluator-agent.log" - $evaluatorPrompt = @" -You are an AquaSynth IPA trial science evaluator. - -Read the updated semantic retrieval from the trial-results database: -$postEvidence - -Also read the hypothesis worker output: -$hypothesisOutput - -Round artifacts are under: -$roundDir - -Before judging: -1. Run exactly three targeted semantic searches into ${roundDir}: - - current round candidates by hypothesizer id or round id; - - weak regressions / failed articulation; - - promising transfer / generalization, including DSL lowering/Faust/scene-voice source-edit evidence when source edits were allowed. -2. Use `show` on at least one promising and one weak candidate from the current round. -3. If the hypothesis worker skipped the required 25-lane matrix or retrieval receipts in `$roundDir/hypotheses.md`, mark orchestration/prompt compliance as failed even if some audio metrics improved. -4. If source edits were allowed, inspect `$roundDir/source-change-plan.md` when present and verify the source edit is a coherent owner move, not a metric hack. - -Use the worker as your search organ: -`$env:DOTNET_CLI_HOME="$roundDir/dotnet-home"; `$env:DOTNET_SKIP_FIRST_TIME_EXPERIENCE="1"; `$env:DOTNET_ADD_GLOBAL_TOOLS_TO_PATH="0"; `$env:DOTNET_CLI_TELEMETRY_OPTOUT="1"; dotnet run --no-build --no-restore --project tools/IpaTrialWorker/IpaTrialWorker.csproj -- search --store "$storePath" --query "$roundId external-codex-$roundId current round candidates" --limit 30 --output "$roundDir/eval-search-current-round.md" --skip-index true -`$env:DOTNET_CLI_HOME="$roundDir/dotnet-home"; `$env:DOTNET_SKIP_FIRST_TIME_EXPERIENCE="1"; `$env:DOTNET_ADD_GLOBAL_TOOLS_TO_PATH="0"; `$env:DOTNET_CLI_TELEMETRY_OPTOUT="1"; dotnet run --no-build --no-restore --project tools/IpaTrialWorker/IpaTrialWorker.csproj -- search --store "$storePath" --query "weak regression failed articulation stop plosive source tract radiation" --limit 30 --output "$roundDir/eval-search-weak.md" --skip-index true -`$env:DOTNET_CLI_HOME="$roundDir/dotnet-home"; `$env:DOTNET_SKIP_FIRST_TIME_EXPERIENCE="1"; `$env:DOTNET_ADD_GLOBAL_TOOLS_TO_PATH="0"; `$env:DOTNET_CLI_TELEMETRY_OPTOUT="1"; dotnet run --no-build --no-restore --project tools/IpaTrialWorker/IpaTrialWorker.csproj -- search --store "$storePath" --query "promising transfer generalization vowel nasal fricative articulation" --limit 30 --output "$roundDir/eval-search-promising.md" --skip-index true -`$env:DOTNET_CLI_HOME="$roundDir/dotnet-home"; `$env:DOTNET_SKIP_FIRST_TIME_EXPERIENCE="1"; `$env:DOTNET_ADD_GLOBAL_TOOLS_TO_PATH="0"; `$env:DOTNET_CLI_TELEMETRY_OPTOUT="1"; dotnet run --no-build --no-restore --project tools/IpaTrialWorker/IpaTrialWorker.csproj -- show --store "$storePath" --trial-id "" --output "$roundDir/eval-detail-.md" - -Retrieval failure policy: -- Failed search/show commands do not count as evidence receipts for family verdicts. -- If live worker retrieval fails, set `Round Compliance: failed` and focus the report on the retrieval blocker instead of inventing metric conclusions. -- Search-summary-only claims are low-quality until corroborated by `show` receipts. - -Verify compliance from disk as well as the hypothesis report: -- count .aqua files under $patchDir; -- validate exactly 25 files; -- validate one target each for a, i, u, e, o, m, n, ng, l, r, s, z, f, v, th, p, b, t, d, k, mix-a, mix-m, mix-s, mix-p, mix-u; -- validate filename schema ____.aqua. -- validate family ids are lowercase kebab-case. -- derive canonical family ids only from the filename family segment; ignore prose family names when they disagree. -- validate that each actionable seam has a contrast pair, a primitive timeline excerpt or explicit `missing`, an owner sentence, and at least five planned micro-sweep perturbations. -- validate that `$roundDir/hypotheses.md` includes a class-consistent reference matrix, scene voice model, and novelty gate. `hypothesis-agent.md` is only the external agent's final chat summary and must not be treated as the full report. -- validate that `$roundDir/hypotheses.md` includes `Previous Round Learning` and `Target-Class Lane Plan`. -- validate target-class alignment from filenames and family plan: stop-release families should not be assigned to vowel lanes, nasal-branch families should not be assigned to stop lanes, frication families should not be assigned to vowel lanes, and scene-noise families should not be arbitrary catchalls unless each off-class lane is marked `transfer-test` with a class-specific mutation. -- fail `class alignment` when families are distributed round-robin across target ids or when candidate files reuse the same family script shape without target-class-specific controls. -- validate that every family identifies primary-articulatory, tract-noise, release/transient, background-room, and recording-condition roles, even if some are explicitly silent. -- validate that at least one family actually adds ordinary helper/background `voice` declarations in its `.aqua` scripts for scene noise or recording-condition modeling. -- validate that helper/background voices are evaluated separately from articulation evidence. -- validate source edit compliance if source edits were allowed: coherent owner map, edited file list, invariant, expected metric movement, verification command, and rollback trigger. -- If any required section, receipt class, per-target validation, filename validation, family extraction, reference matrix, previous-round learning, target-class lane plan, class alignment, scene voice model, contrast pair, owner sentence, or novelty gate is incomplete, set `Round Compliance: failed`. - -Task: -1. Evaluate whether the worker's proposed hypotheses follow from the measured evidence. -2. Call out any hypothesis that is likely full-patch dressing impersonating articulation. -3. Recommend exactly one next implementation/refinement target, with file/module owner and why. It may be DSL syntax, Faust lowering, scene-voice modeling, or worker evidence if the receipts support it. -4. Write your evaluator report to: -$roundDir/evaluation.md - -Required `$roundDir/evaluation.md` shape: -- `Retrieval Receipts`: exactly five receipts: three search outputs plus one weak show output and one promising show output. Cite no other evidence files in this section. Only cite claims backed by these file paths; write `unknown` when evidence is absent. -- `Commands Run`: exact search/show commands and output paths used to support claims. -- `Round Compliance`: passed/failed, candidate count, target coverage, naming validity, family extraction, reference matrix, previous-round learning, target-class lane plan, class alignment, contrast-pair coverage, owner-sentence coverage, micro-sweep coverage, novelty gate, auxiliary scene voice presence, and whether `hypotheses.md` had the required matrix. -- `Family Verdicts`: one row per canonical filename family with improved/flat/regressed/unknown metrics. Treat |delta| < 0.01 as flat; if deltas are not present in cited show artifacts, write `unknown` and reason=`no delta in receipts`. -- `Evidence Quality Verdicts`: one row per family with specificity, comparability, falsifiability, reuse value, primitive timeline support, and weakest missing evidence. Penalize vague receipts, search-summary-only claims, missing contrast pairs, missing reference ids, and missing timeline excerpts even when metrics improve. -- `Seam Audit`: one row per named seam with owner sentence, contrast pair, timeline excerpt, planned perturbation count, and verdict `actionable` or `not actionable`; fewer than five perturbations means `not actionable`. -- `Scene Voice Audit`: one row per family naming scene voices, helper/background synthesis primitives, non-articulation witness, and whether the helper voices are honest context or dressing. -- `Source Edit Audit`: if source edits were allowed, summarize source files changed, invariant claimed, verification result, and whether the edit should survive; otherwise `not allowed`. -- `Novelty Audit`: one row per family saying whether it moves a new owner/control axis/timing contour/primitive relationship/scene-voice model or is mainly loudness/dressing. -- `Generalization Read`: whether effects transferred across target sets or overfit one phoneme. -- `Learning Audit`: whether failed/flat previous families were mutated, retired, or blindly repeated. -- `Dressing Audit`: articulation evidence requires movement in gesture/articulation/primitive timeline metrics; FM/AM/noise/envelope evidence without those is dressing. -- `Next Target`: exactly one markdown bullet, final line of the file, and no continuation text: ` | | `. - -Authority boundary: -- Do not edit source files. -- Do not rewrite trial artifacts. -- Be explicit about which layer owns the failure: gesture DSL, scene voice model, primitive source, tract/radiation lowering, Faust machinery, audio scoring, or orchestration. -- Treat the CultCache .cc store as the shared trial memory that future hypothesis workers will query through the worker search/show commands. - -Return a short final summary naming the report you wrote. -"@ - Invoke-CodexAgent ` - -RepoRoot $repoRoot ` - -Prompt $evaluatorPrompt ` - -OutputPath $evaluatorOutput ` - -LogPath $evaluatorLog ` - -CodexCommand $CodexCommand ` - -CodexModel $CodexModel ` - -AllowSourceEdits:$false -} - -Write-Host "IPA trial loop complete: $loopRoot" diff --git a/tools/run-ipa-trial-swarm.ps1 b/tools/run-ipa-trial-swarm.ps1 deleted file mode 100644 index f258113..0000000 --- a/tools/run-ipa-trial-swarm.ps1 +++ /dev/null @@ -1,497 +0,0 @@ -param( - [int]$Passes = 5, - [string]$BatchId = "ipa-swarm-five-by-five", - [string]$CodexCommand = "codex", - [string]$CodexModel = "gpt-5.3-codex", - [switch]$SkipLocalTrialRun -) - -$ErrorActionPreference = "Stop" - -function Resolve-RepoRoot { - $dir = Get-Item -LiteralPath (Get-Location) - while ($null -ne $dir) { - if (Test-Path -LiteralPath (Join-Path $dir.FullName "AquaSynth.sln")) { - return $dir.FullName - } - - $dir = $dir.Parent - } - - throw "Could not find AquaSynth.sln above the current directory." -} - -function New-Timestamp { - return [DateTimeOffset]::UtcNow.ToString("yyyyMMddTHHmmssfff") -} - -function Write-Status { - param( - [string]$StatusPath, - [string]$Message - ) - - $line = "[$([DateTimeOffset]::UtcNow.ToString("O"))] $Message" - Add-Content -LiteralPath $StatusPath -Value $line - Write-Host $line -} - -function Invoke-LoggedProcess { - param( - [string]$FilePath, - [string[]]$ArgumentList, - [string]$LogPath, - [hashtable]$Environment = @{} - ) - - $logDir = Split-Path -Parent $LogPath - New-Item -ItemType Directory -Force -Path $logDir | Out-Null - $oldValues = @{} - foreach ($key in $Environment.Keys) { - $oldValues[$key] = [Environment]::GetEnvironmentVariable($key, "Process") - [Environment]::SetEnvironmentVariable($key, [string]$Environment[$key], "Process") - } - - try { - $display = "$FilePath $($ArgumentList -join ' ')" - Add-Content -LiteralPath $LogPath -Value "[$([DateTimeOffset]::UtcNow.ToString("O"))] $display" - & $FilePath @ArgumentList *>&1 | Tee-Object -FilePath $LogPath -Append - if ($LASTEXITCODE -ne 0) { - throw "Command failed with exit code $LASTEXITCODE`: $display" - } - } - finally { - foreach ($key in $Environment.Keys) { - [Environment]::SetEnvironmentVariable($key, $oldValues[$key], "Process") - } - } -} - -function Start-CodexAgentJob { - param( - [string]$RepoRoot, - [string]$Prompt, - [string]$PromptPath, - [string]$OutputPath, - [string]$LogPath, - [string]$CodexCommand, - [string]$CodexModel, - [string]$JobName - ) - - New-Item -ItemType Directory -Force -Path (Split-Path -Parent $OutputPath) | Out-Null - Set-Content -LiteralPath $PromptPath -Value $Prompt - - $args = @( - "exec", - "--cd", $RepoRoot, - "--full-auto", - "--output-last-message", $OutputPath, - "--config", 'shell_environment_policy.inherit="all"', - "--config", 'sandbox_permissions=["workspace-write"]' - ) - if ($CodexModel.Length -gt 0) { - $args += @("--model", $CodexModel) - } - $args += "-" - - Start-Job -Name $JobName -ArgumentList $CodexCommand, $args, $PromptPath, $LogPath -ScriptBlock { - param( - [string]$JobCodexCommand, - [string[]]$JobArgs, - [string]$JobPromptPath, - [string]$JobLogPath - ) - - $ErrorActionPreference = "Continue" - New-Item -ItemType Directory -Force -Path (Split-Path -Parent $JobLogPath) | Out-Null - Add-Content -LiteralPath $JobLogPath -Value "[$([DateTimeOffset]::UtcNow.ToString("O"))] $JobCodexCommand $($JobArgs -join ' ')" - Get-Content -LiteralPath $JobPromptPath -Raw | & $JobCodexCommand @JobArgs 2>&1 | Tee-Object -FilePath $JobLogPath -Append - [pscustomobject]@{ - ExitCode = $LASTEXITCODE - LogPath = $JobLogPath - PromptPath = $JobPromptPath - } - } -} - -function Wait-CodexJobs { - param( - [System.Management.Automation.Job[]]$Jobs - ) - - foreach ($job in $Jobs) { - Wait-Job -Job $job | Out-Null - } - - $failures = @() - foreach ($job in $Jobs) { - $received = Receive-Job -Job $job -Keep - $exitRecord = $received | Where-Object { $_.PSObject.Properties.Name -contains "ExitCode" } | Select-Object -Last 1 - if ($null -eq $exitRecord -or $exitRecord.ExitCode -ne 0) { - $failures += $job.Name - } - } - - Remove-Job -Job $Jobs -Force - if ($failures.Count -gt 0) { - throw "External Codex job(s) failed: $($failures -join ', ')" - } -} - -function Assert-LaneBatch { - param( - [string]$PatchDirectory, - [string[]]$Targets - ) - - $files = @(Get-ChildItem -LiteralPath $PatchDirectory -Filter "*.aqua" -File -Recurse) - if ($files.Count -ne $Targets.Count) { - throw "Lane wrote $($files.Count) .aqua candidates under $PatchDirectory; expected $($Targets.Count)." - } - - $stems = $files | ForEach-Object { [IO.Path]::GetFileNameWithoutExtension($_.Name) } - foreach ($target in $Targets) { - $covered = $false - foreach ($stem in $stems) { - if ($stem.StartsWith("$target`__", [StringComparison]::OrdinalIgnoreCase)) { - $covered = $true - break - } - } - - if (-not $covered) { - throw "Lane did not write a candidate for target '$target'." - } - } - - foreach ($stem in $stems) { - $parts = $stem.Split([string[]]@("__"), [StringSplitOptions]::None) - if ($parts.Count -lt 3 -or [string]::IsNullOrWhiteSpace($parts[1]) -or [string]::IsNullOrWhiteSpace($parts[2])) { - throw "Candidate '$stem' does not follow ____.aqua." - } - - if ($parts[1] -cnotmatch '^[a-z0-9]+(-[a-z0-9]+)*$') { - throw "Candidate '$stem' uses invalid family '$($parts[1])'. Family ids must be lowercase kebab-case." - } - } -} - -function Assert-PassBatch { - param( - [string]$PatchDirectory - ) - - $targets = @("a", "i", "u", "e", "o", "m", "n", "ng", "l", "r", "s", "z", "f", "v", "th", "p", "b", "t", "d", "k", "mix-a", "mix-m", "mix-s", "mix-p", "mix-u") - $files = @(Get-ChildItem -LiteralPath $PatchDirectory -Filter "*.aqua" -File -Recurse) - if ($files.Count -ne 25) { - throw "Pass wrote $($files.Count) .aqua candidates; expected exactly 25." - } - - $stems = $files | ForEach-Object { [IO.Path]::GetFileNameWithoutExtension($_.Name) } - foreach ($target in $targets) { - if (-not ($stems | Where-Object { $_.StartsWith("$target`__", [StringComparison]::OrdinalIgnoreCase) } | Select-Object -First 1)) { - throw "Pass did not write a candidate for target '$target'." - } - } -} - -$repoRoot = Resolve-RepoRoot -$codex = Get-Command $CodexCommand -ErrorAction Stop -$loopId = New-Timestamp -$loopRoot = Join-Path $repoRoot "artifacts/parity/ipa-trial-swarms/$loopId" -$logRoot = Join-Path $loopRoot "logs" -$statusPath = Join-Path $loopRoot "status.log" -$indexPath = Join-Path $loopRoot "loop-index.md" -$storePath = Join-Path $loopRoot "ipa-trial-results.cc" -$workerProject = Join-Path $repoRoot "tools/IpaTrialWorker/IpaTrialWorker.csproj" -$targetSets = @( - @{ Id = "vowels"; Targets = @("a", "i", "u", "e", "o"); Query = "vowel body tongue lip radiation formant color weak articulation transfer" }, - @{ Id = "nasals-approximants"; Targets = @("m", "n", "ng", "l", "r"); Query = "nasal branch admittance velum approximant liquid transfer evidence" }, - @{ Id = "fricatives"; Targets = @("s", "z", "f", "v", "th"); Query = "fricative place constriction turbulence sibilant labiodental dental contrast articulation" }, - @{ Id = "stops"; Targets = @("p", "b", "t", "d", "k"); Query = "stop closure release reservoir weak plosive contrast primitive timeline" }, - @{ Id = "mixed"; Targets = @("mix-a", "mix-m", "mix-s", "mix-p", "mix-u"); Query = "mixed transfer generalization vowel nasal fricative stop articulation owner primitive" } -) - -New-Item -ItemType Directory -Force -Path $loopRoot, $logRoot | Out-Null -Set-Content -LiteralPath $indexPath -Value @" -# IPA Trial Swarm $loopId - -- repo: $repoRoot -- codex: $($codex.Source) -- passes: $Passes -- agents_per_pass: 5 -- candidates_per_agent: 5 -- batch_id: $BatchId -- trial_results_store: $storePath -- worker: $workerProject -- topology: five concurrent lane hypothesizers per pass; one 25-candidate scoring barrier; one evaluator barrier; index after every barrier -- status_log: $statusPath - -"@ - -Write-Status $statusPath "swarm initialized at $loopRoot" - -if (-not $SkipLocalTrialRun) { - Write-Status $statusPath "seed trial run starting" - Invoke-LoggedProcess ` - -FilePath "dotnet" ` - -ArgumentList @( - "run", - "--project", - $workerProject, - "--", - "seed", - "--artifact-root", - $loopRoot, - "--batch-id", - $BatchId, - "--store", - $storePath - ) ` - -LogPath (Join-Path $logRoot "seed-trial-run.log") - Write-Status $statusPath "seed trial run complete" -} -else { - Add-Content -LiteralPath $indexPath -Value "- seed: skipped" - Write-Status $statusPath "seed trial run skipped" -} - -for ($pass = 1; $pass -le $Passes; $pass++) { - $passId = "pass-{0:000}" -f $pass - $passDir = Join-Path $loopRoot $passId - $patchRoot = Join-Path $passDir "proposed-patches" - New-Item -ItemType Directory -Force -Path $passDir, $patchRoot | Out-Null - Add-Content -LiteralPath $indexPath -Value "- ${passId}: $passDir" - Write-Status $statusPath "$passId index-before starting" - - Invoke-LoggedProcess ` - -FilePath "dotnet" ` - -ArgumentList @( - "run", - "--project", - $workerProject, - "--", - "index", - "--store", - $storePath, - "--output", - (Join-Path $passDir "vector-index-before.md") - ) ` - -LogPath (Join-Path $logRoot "$passId-index-before.log") - - $preEvidence = Join-Path $passDir "semantic-search-before.md" - Invoke-LoggedProcess ` - -FilePath "dotnet" ` - -ArgumentList @( - "run", - "--project", - $workerProject, - "--", - "search", - "--store", - $storePath, - "--query", - "pass $pass weak promising transfer generalization vowel nasal fricative stop articulation owner source tract radiation gesture primitive dressing", - "--limit", - "60", - "--output", - $preEvidence, - "--skip-index", - "true" - ) ` - -LogPath (Join-Path $logRoot "$passId-search-before.log") - - Write-Status $statusPath "$passId launching five lane hypothesizers" - $jobs = @() - foreach ($targetSet in $targetSets) { - $laneId = $targetSet.Id - $laneDir = Join-Path $passDir $laneId - $lanePatchDir = Join-Path $patchRoot $laneId - New-Item -ItemType Directory -Force -Path $laneDir, $lanePatchDir | Out-Null - $targets = [string[]]$targetSet.Targets - $targetText = $targets -join ", " - $laneQuery = [string]$targetSet.Query - $laneOutput = Join-Path $laneDir "hypothesis-agent.md" - $lanePromptPath = Join-Path $laneDir "hypothesis-agent.prompt.md" - $laneLog = Join-Path $logRoot "$passId-$laneId-hypothesis-agent.log" - $lanePrompt = @" -You are one lane in an AquaSynth IPA loss-landscape swarm. - -Current pass: $passId -Lane: $laneId -Targets: $targetText -Shared pre-pass evidence: $preEvidence -Shared trial store: $storePath -Lane patch directory: $lanePatchDir - -Your job is to write exactly five parseable .aqua candidates, one for each target in this lane. Other lane agents are running at the same time; do not touch their directories, the shared .cc store, source files, or existing artifacts. - -Use the worker as your semantic search/show organ: -`$env:DOTNET_CLI_HOME="$laneDir/dotnet-home"; `$env:DOTNET_SKIP_FIRST_TIME_EXPERIENCE="1"; `$env:DOTNET_ADD_GLOBAL_TOOLS_TO_PATH="0"; `$env:DOTNET_CLI_TELEMETRY_OPTOUT="1"; dotnet run --no-build --no-restore --project tools/IpaTrialWorker/IpaTrialWorker.csproj -- search --store "$storePath" --query "" --limit 20 --output "$laneDir/search-.md" --skip-index true -`$env:DOTNET_CLI_HOME="$laneDir/dotnet-home"; `$env:DOTNET_SKIP_FIRST_TIME_EXPERIENCE="1"; `$env:DOTNET_ADD_GLOBAL_TOOLS_TO_PATH="0"; `$env:DOTNET_CLI_TELEMETRY_OPTOUT="1"; dotnet run --no-build --no-restore --project tools/IpaTrialWorker/IpaTrialWorker.csproj -- show --store "$storePath" --trial-id "" --output "$laneDir/detail-.md" - -Required receipts before writing candidates: -1. Open $preEvidence and extract three metric-bearing facts relevant to this lane. -2. Run exactly three lane searches: - - "$laneQuery" - - one query for a weak same-class failure; - - one query for a transferable success or useful contrast from any class. -3. Open exactly two detailed trial records with show: one weak same-class record and one promising/contrast record. -4. If a search/show receipt is missing, create it. If the tool fails, report the failure and do not invent evidence. - -Candidate contract: -- Write exactly five .aqua files under $lanePatchDir. -- Names must be ____.aqua. -- Target ids must be exactly: $targetText. -- Use one to three family ids, lowercase kebab-case. -- Reuse a family id when the same owner/control/timing idea is being tested across multiple targets. -- Prefer values and gesture contours visible in existing candidates before inventing new syntax. -- Patch candidates may use FM, AM, modulators, envelopes, filters, and extra animated voices, but mark that as dressing unless gesture/articulation/timeline evidence moves too. - -Report contract: -Write $laneDir/hypotheses.md with: -- PreEvidence Digest: three metric-bearing facts. -- Retrieval Receipts: exactly three search files and two show files. -- Lane Loss Read: strongest and weakest evidence for $laneId. -- Hypothesis Families: family, owner layer, owner sentence `X owns Y so Z remains true`, contrast pair, concrete metric value, primitive timeline excerpt or `missing`, five micro-sweep perturbations, predicted movement for gesture/logmel/articulation/rms/timeline. -- Evidence Quality Ledger: specificity, comparability, falsifiability, reuse value, weakest missing evidence. -- Candidate Matrix: exactly five rows, one per target. -- Acceptance Checklist: five files, target coverage, naming schema, receipt count. - -Return a short final summary naming the files you wrote. -"@ - $jobs += Start-CodexAgentJob ` - -RepoRoot $repoRoot ` - -Prompt $lanePrompt ` - -PromptPath $lanePromptPath ` - -OutputPath $laneOutput ` - -LogPath $laneLog ` - -CodexCommand $CodexCommand ` - -CodexModel $CodexModel ` - -JobName "$passId-$laneId" - } - - Wait-CodexJobs -Jobs $jobs - Write-Status $statusPath "$passId lane hypothesizers complete" - - foreach ($targetSet in $targetSets) { - Assert-LaneBatch -PatchDirectory (Join-Path $patchRoot $targetSet.Id) -Targets ([string[]]$targetSet.Targets) - } - Assert-PassBatch -PatchDirectory $patchRoot - Write-Status $statusPath "$passId candidate assertions passed" - - Invoke-LoggedProcess ` - -FilePath "dotnet" ` - -ArgumentList @( - "run", - "--project", - $workerProject, - "--", - "score", - "--patch-root", - $patchRoot, - "--artifact-root", - $passDir, - "--batch-id", - $passId, - "--store", - $storePath, - "--hypothesizer", - "external-codex-swarm-$passId" - ) ` - -LogPath (Join-Path $logRoot "$passId-score-candidates.log") - Write-Status $statusPath "$passId scoring complete" - - Invoke-LoggedProcess ` - -FilePath "dotnet" ` - -ArgumentList @( - "run", - "--project", - $workerProject, - "--", - "index", - "--store", - $storePath, - "--output", - (Join-Path $passDir "vector-index-after.md") - ) ` - -LogPath (Join-Path $logRoot "$passId-index-after.log") - - $postEvidence = Join-Path $passDir "semantic-search-after.md" - Invoke-LoggedProcess ` - -FilePath "dotnet" ` - -ArgumentList @( - "run", - "--project", - $workerProject, - "--", - "search", - "--store", - $storePath, - "--query", - "$passId external-codex-swarm latest candidates weak promising transfer generalization vowel nasal fricative stop articulation owner primitive dressing", - "--limit", - "80", - "--output", - $postEvidence, - "--skip-index", - "true" - ) ` - -LogPath (Join-Path $logRoot "$passId-search-after.log") - - $evalOutput = Join-Path $passDir "evaluator-agent.md" - $evalPromptPath = Join-Path $passDir "evaluator-agent.prompt.md" - $evalLog = Join-Path $logRoot "$passId-evaluator-agent.log" - $evalPrompt = @" -You are the evaluator barrier for AquaSynth IPA swarm pass $passId. - -Read: -- post-pass semantic evidence: $postEvidence -- pass directory: $passDir -- patch root: $patchRoot -- trial store: $storePath - -Before judging, use the worker as your search/show organ: -`$env:DOTNET_CLI_HOME="$passDir/dotnet-home"; `$env:DOTNET_SKIP_FIRST_TIME_EXPERIENCE="1"; `$env:DOTNET_ADD_GLOBAL_TOOLS_TO_PATH="0"; `$env:DOTNET_CLI_TELEMETRY_OPTOUT="1"; dotnet run --no-build --no-restore --project tools/IpaTrialWorker/IpaTrialWorker.csproj -- search --store "$storePath" --query "$passId external-codex-swarm current pass candidates" --limit 40 --output "$passDir/eval-search-current-pass.md" --skip-index true -`$env:DOTNET_CLI_HOME="$passDir/dotnet-home"; `$env:DOTNET_SKIP_FIRST_TIME_EXPERIENCE="1"; `$env:DOTNET_ADD_GLOBAL_TOOLS_TO_PATH="0"; `$env:DOTNET_CLI_TELEMETRY_OPTOUT="1"; dotnet run --no-build --no-restore --project tools/IpaTrialWorker/IpaTrialWorker.csproj -- search --store "$storePath" --query "$passId weak regression failed articulation stop fricative nasal vowel source tract radiation" --limit 40 --output "$passDir/eval-search-weak.md" --skip-index true -`$env:DOTNET_CLI_HOME="$passDir/dotnet-home"; `$env:DOTNET_SKIP_FIRST_TIME_EXPERIENCE="1"; `$env:DOTNET_ADD_GLOBAL_TOOLS_TO_PATH="0"; `$env:DOTNET_CLI_TELEMETRY_OPTOUT="1"; dotnet run --no-build --no-restore --project tools/IpaTrialWorker/IpaTrialWorker.csproj -- search --store "$storePath" --query "$passId promising transfer generalization gesture articulation primitive timeline" --limit 40 --output "$passDir/eval-search-promising.md" --skip-index true -`$env:DOTNET_CLI_HOME="$passDir/dotnet-home"; `$env:DOTNET_SKIP_FIRST_TIME_EXPERIENCE="1"; `$env:DOTNET_ADD_GLOBAL_TOOLS_TO_PATH="0"; `$env:DOTNET_CLI_TELEMETRY_OPTOUT="1"; dotnet run --no-build --no-restore --project tools/IpaTrialWorker/IpaTrialWorker.csproj -- show --store "$storePath" --trial-id "" --output "$passDir/eval-detail-weak.md" -`$env:DOTNET_CLI_HOME="$passDir/dotnet-home"; `$env:DOTNET_SKIP_FIRST_TIME_EXPERIENCE="1"; `$env:DOTNET_ADD_GLOBAL_TOOLS_TO_PATH="0"; `$env:DOTNET_CLI_TELEMETRY_OPTOUT="1"; dotnet run --no-build --no-restore --project tools/IpaTrialWorker/IpaTrialWorker.csproj -- show --store "$storePath" --trial-id "" --output "$passDir/eval-detail-promising.md" - -Verify from disk: -- exactly 25 .aqua files under $patchRoot; -- one target each for a, i, u, e, o, m, n, ng, l, r, s, z, f, v, th, p, b, t, d, k, mix-a, mix-m, mix-s, mix-p, mix-u; -- filename schema ____.aqua; -- each lane wrote hypotheses.md with receipt lists and evidence quality ledger. - -Write $passDir/evaluation.md with: -- Retrieval Receipts: exactly three search outputs plus weak/promising show outputs. -- Commands Run. -- Pass Compliance: passed/failed with file count, target coverage, naming validity, lane receipt coverage, lane report coverage. -- Family Verdicts: canonical filename family, improved/flat/regressed/unknown metrics; use |delta| < 0.01 as flat and `unknown` when show receipts lack deltas. -- Evidence Quality Verdicts: specificity, comparability, falsifiability, reuse value, primitive timeline support, weakest missing evidence. -- Seam Audit: owner sentence, contrast pair, timeline excerpt or missing, planned perturbation count, actionable/not actionable. -- Novelty Audit: new owner/control axis/timing contour/primitive relationship or dressing-only. -- Generalization Read. -- Dressing Audit. -- Next Pass Brief: five concrete search questions and five candidate-family recommendations future lane agents should inherit. -- Next Target: exactly one final bullet ` | | `. - -Do not edit source files or trial artifacts. Treat the .cc store as shared memory and the search/show tool as the way future agents should read it. -"@ - $evalJob = Start-CodexAgentJob ` - -RepoRoot $repoRoot ` - -Prompt $evalPrompt ` - -PromptPath $evalPromptPath ` - -OutputPath $evalOutput ` - -LogPath $evalLog ` - -CodexCommand $CodexCommand ` - -CodexModel $CodexModel ` - -JobName "$passId-evaluator" - Wait-CodexJobs -Jobs @($evalJob) - Write-Status $statusPath "$passId evaluator complete" -} - -Write-Status $statusPath "swarm complete: $loopRoot" -Write-Host "IPA trial swarm complete: $loopRoot" diff --git a/tools/run-song-snippet-trial-swarm.ps1 b/tools/run-song-snippet-trial-swarm.ps1 deleted file mode 100644 index c17abf5..0000000 --- a/tools/run-song-snippet-trial-swarm.ps1 +++ /dev/null @@ -1,990 +0,0 @@ -param( - [int]$Passes = 1, - [int]$AgentsPerPass = 5, - [int]$SongsPerAgent = 2, - [string]$Source = "D:\Music\Reinier\Heyoka\Gate Code\Heyoka - Alien Gibberish.mp3", - [string]$SourceFolder = "D:\Music\Reinier\Heyoka", - [float]$DurationSeconds = 30, - [switch]$FullSongs, - [int]$IterationsPerTarget = 5, - [int]$Seed = 0, - [switch]$NewSegmentPerPass, - [switch]$RandomSourcePerAgent, - [int]$PlaylistTopCount = 10, - [string]$CodexCommand = "codex", - [string]$CodexModel = "gpt-5.3-codex" -) - -$ErrorActionPreference = "Stop" - -function Resolve-RepoRoot { - $dir = Get-Item -LiteralPath (Get-Location) - while ($null -ne $dir) { - if (Test-Path -LiteralPath (Join-Path $dir.FullName "AquaSynth.sln")) { - return $dir.FullName - } - - $dir = $dir.Parent - } - - throw "Could not find AquaSynth.sln above the current directory." -} - -function New-Timestamp { - return [DateTimeOffset]::UtcNow.ToString("yyyyMMddTHHmmssfff") -} - -function Invoke-LoggedProcess { - param( - [string]$FilePath, - [string[]]$ArgumentList, - [string]$LogPath - ) - - New-Item -ItemType Directory -Force -Path (Split-Path -Parent $LogPath) | Out-Null - $display = "$FilePath $($ArgumentList -join ' ')" - Add-Content -LiteralPath $LogPath -Value "[$([DateTimeOffset]::UtcNow.ToString("O"))] $display" - & $FilePath @ArgumentList *>&1 | Tee-Object -FilePath $LogPath -Append - if ($LASTEXITCODE -ne 0) { - throw "Command failed with exit code $LASTEXITCODE`: $display" - } -} - -function Start-CodexAgentJob { - param( - [string]$RepoRoot, - [string]$Prompt, - [string]$PromptPath, - [string]$OutputPath, - [string]$LogPath, - [string]$CodexCommand, - [string]$CodexModel, - [string]$JobName, - [string]$SandboxMode = "workspace-write", - [string[]]$WritableDirs = @() - ) - - New-Item -ItemType Directory -Force -Path (Split-Path -Parent $OutputPath) | Out-Null - Set-Content -LiteralPath $PromptPath -Value $Prompt - - $args = @( - "exec", - "--cd", $RepoRoot, - "--sandbox", $SandboxMode, - "--output-last-message", $OutputPath, - "--config", 'shell_environment_policy.inherit="all"', - "--add-dir", (Join-Path (Split-Path -Parent $RepoRoot) "CultLib") - ) - foreach ($dir in $WritableDirs) { - $args += @("--add-dir", $dir) - } - if ($CodexModel.Length -gt 0) { - $args += @("--model", $CodexModel) - } - $args += "-" - - Start-Job -Name $JobName -ArgumentList $CodexCommand, $args, $PromptPath, $LogPath, $RepoRoot -ScriptBlock { - param( - [string]$JobCodexCommand, - [string[]]$JobArgs, - [string]$JobPromptPath, - [string]$JobLogPath, - [string]$JobRepoRoot - ) - - $ErrorActionPreference = "Continue" - New-Item -ItemType Directory -Force -Path (Split-Path -Parent $JobLogPath) | Out-Null - $dotnetHome = Join-Path $JobRepoRoot ".dotnet_cli_home" - $nugetHome = Join-Path $JobRepoRoot ".nuget_packages" - $appDataHome = Join-Path $JobRepoRoot ".dotnet_appdata" - $localAppDataHome = Join-Path $JobRepoRoot ".dotnet_localappdata" - $agentHome = Join-Path $JobRepoRoot ".dotnet_agent_home" - New-Item -ItemType Directory -Force -Path $dotnetHome, $nugetHome, $appDataHome, $localAppDataHome, $agentHome | Out-Null - $env:DOTNET_CLI_HOME = $dotnetHome - $env:DOTNET_ADD_GLOBAL_TOOLS_TO_PATH = "0" - $env:NUGET_PACKAGES = $nugetHome - $env:APPDATA = $appDataHome - $env:LOCALAPPDATA = $localAppDataHome - $env:USERPROFILE = $agentHome - $env:HOME = $agentHome - $env:DOTNET_SKIP_FIRST_TIME_EXPERIENCE = "1" - $env:DOTNET_NOLOGO = "1" - Add-Content -LiteralPath $JobLogPath -Value "[$([DateTimeOffset]::UtcNow.ToString("O"))] $JobCodexCommand $($JobArgs -join ' ')" - Get-Content -LiteralPath $JobPromptPath -Raw | & $JobCodexCommand @JobArgs 2>&1 | Tee-Object -FilePath $JobLogPath -Append - [pscustomobject]@{ - ExitCode = $LASTEXITCODE - LogPath = $JobLogPath - } - } -} - -function Wait-CodexJobs { - param([System.Management.Automation.Job[]]$Jobs) - - foreach ($job in $Jobs) { - Wait-Job -Job $job | Out-Null - } - - $failures = @() - foreach ($job in $Jobs) { - $received = Receive-Job -Job $job -Keep - $exitRecord = $received | Where-Object { $_.PSObject.Properties.Name -contains "ExitCode" } | Select-Object -Last 1 - if ($null -eq $exitRecord -or $exitRecord.ExitCode -ne 0) { - $failures += $job.Name - } - } - - Remove-Job -Job $Jobs -Force - if ($failures.Count -gt 0) { - throw "External Codex job(s) failed: $($failures -join ', ')" - } -} - -function New-AgentWorktree { - param( - [string]$RepoRoot, - [string]$WorktreeRoot, - [string]$LogPath - ) - - New-Item -ItemType Directory -Force -Path (Split-Path -Parent $WorktreeRoot) | Out-Null - if (Test-Path -LiteralPath $WorktreeRoot) { - throw "Agent worktree already exists: $WorktreeRoot" - } - - Invoke-LoggedProcess ` - -FilePath "git" ` - -ArgumentList @( - "worktree", - "add", - "--quiet", - "--detach", - $WorktreeRoot, - "HEAD" - ) ` - -LogPath $LogPath - - return $WorktreeRoot -} - -function Assert-SongCandidates { - param( - [string]$PatchDirectory, - [int]$ExpectedCount - ) - - $files = @(Get-ChildItem -LiteralPath $PatchDirectory -Filter "*.aqua" -File -Recurse) - if ($files.Count -ne $ExpectedCount) { - throw "Song challenge wrote $($files.Count) .aqua candidates; expected $ExpectedCount." - } - - foreach ($file in $files) { - $stem = [IO.Path]::GetFileNameWithoutExtension($file.Name) - if ($stem -cnotmatch '^[a-z0-9]+([-_][a-z0-9]+)*__[a-z0-9]+([-_][a-z0-9]+)*__[a-z0-9]+([-_][a-z0-9]+)*$') { - throw "Candidate '$stem' must be ____.aqua with lowercase slug segments." - } - } -} - -function Assert-AgentSelfIterationEvidence { - param( - [string]$PassDirectory, - [int]$AgentsPerPass, - [int]$SongsPerAgent, - [int]$IterationsPerTarget - ) - - $failures = New-Object System.Collections.Generic.List[string] - foreach ($agent in 1..$AgentsPerPass) { - $agentId = "agent-{0:00}" -f $agent - $agentDir = Join-Path $PassDirectory $agentId - $iterationRoot = Join-Path $agentDir "iterations" - $spectrogramReview = Join-Path $agentDir "spectrogram-review.md" - if (!(Test-Path -LiteralPath $spectrogramReview)) { - $failures.Add("$agentId missing spectrogram-review.md") - } - else { - $reviewText = Get-Content -LiteralPath $spectrogramReview -Raw - foreach ($song in 1..$SongsPerAgent) { - $songId = "target-{0:00}" -f $song - foreach ($attempt in 1..$IterationsPerTarget) { - $attemptId = "attempt-{0:00}" -f $attempt - if ($reviewText -notmatch [regex]::Escape($songId) -or $reviewText -notmatch [regex]::Escape($attemptId)) { - $failures.Add("$agentId spectrogram-review.md does not name $songId $attemptId") - } - } - } - - if ($reviewText -notmatch "Visible mismatch|mismatch" -or - $reviewText -notmatch "Responsible lane|owner lane|Responsible lanes" -or - $reviewText -notmatch "Still failed|Residual|failed") { - $failures.Add("$agentId spectrogram-review.md lacks mismatch/owner/failure review language") - } - } - - foreach ($song in 1..$SongsPerAgent) { - $songId = "target-{0:00}" -f $song - foreach ($attempt in 1..$IterationsPerTarget) { - $attemptId = "attempt-{0:00}" -f $attempt - $attemptDir = Join-Path (Join-Path $iterationRoot $attemptId) $songId - $summary = Get-ChildItem -LiteralPath $attemptDir -Filter "summary.csv" -File -Recurse -ErrorAction SilentlyContinue | Select-Object -First 1 - if ($null -eq $summary) { - $failures.Add("$agentId $songId $attemptId missing summary.csv") - continue - } - - $renderFailure = Get-ChildItem -LiteralPath $attemptDir -Filter "render-failure.txt" -File -Recurse -ErrorAction SilentlyContinue | Select-Object -First 1 - $candidateLogMel = Get-ChildItem -LiteralPath $attemptDir -Filter "candidate-logmel-spectrogram.csv" -File -Recurse -ErrorAction SilentlyContinue | Select-Object -First 1 - if ($null -eq $renderFailure -and $null -eq $candidateLogMel) { - $failures.Add("$agentId $songId $attemptId has summary.csv but no candidate log-mel spectrogram or render-failure.txt") - } - } - } - } - - if ($failures.Count -gt 0) { - throw "Self-iteration evidence incomplete:`n$($failures -join "`n")" - } -} - -function Get-SongSources { - param( - [string]$Source, - [string]$SourceFolder - ) - - if ($SourceFolder.Length -gt 0) { - $files = @(Get-ChildItem -LiteralPath $SourceFolder -File -Recurse | - Where-Object { $_.Extension -in @(".mp3", ".wav", ".flac", ".aiff", ".aif", ".ogg", ".m4a", ".mp4") } | - Sort-Object FullName) - if ($files.Count -eq 0) { - throw "No supported song files found in '$SourceFolder'." - } - - return @($files | ForEach-Object { $_.FullName }) - } - - return @($Source) -} - -function Write-PassPlaylist { - param( - [string]$PassDirectory, - [int]$TopCount - ) - - $summaryFiles = @(Get-ChildItem -LiteralPath $PassDirectory -Filter "summary.csv" -File -Recurse) - $rows = @() - foreach ($summaryFile in $summaryFiles) { - $batchDirectory = Split-Path -Parent $summaryFile.FullName - foreach ($row in (Import-Csv -LiteralPath $summaryFile.FullName)) { - $candidateId = $row.candidate_id - $candidateWav = Join-Path $batchDirectory (Join-Path "song-candidates" (Join-Path $candidateId "audio/candidate.wav")) - $referenceWav = Join-Path (Split-Path -Parent $batchDirectory) "reference.wav" - $motionCoverage = if ([string]::IsNullOrWhiteSpace($row.candidate_motion_coverage)) { 0 } else { [double]$row.candidate_motion_coverage } - $firstSecondEnergyShare = if ([string]::IsNullOrWhiteSpace($row.candidate_first_second_energy_share)) { 1 } else { [double]$row.candidate_first_second_energy_share } - $modeCollapseRisk = if ([string]::IsNullOrWhiteSpace($row.mode_collapse_risk)) { 1 } else { [double]$row.mode_collapse_risk } - $rows += [pscustomobject]@{ - CandidateId = $candidateId - TrialId = $row.trial_id - ReferenceId = $row.reference_id - Verdict = $row.verdict - LogMelCosine = [double]$row.log_mel_cosine - AudioScore = [double]$row.audio_score - RmsRatio = [double]$row.rms_ratio - CentroidRatio = [double]$row.centroid_ratio - MotionCoverage = $motionCoverage - FirstSecondEnergyShare = $firstSecondEnergyShare - ModeCollapseRisk = $modeCollapseRisk - CandidateWav = $candidateWav - ReferenceWav = $referenceWav - SummaryPath = $summaryFile.FullName - } - } - } - - $playable = @($rows | Where-Object { Test-Path -LiteralPath $_.CandidateWav }) - $ranked = @($playable | Sort-Object -Property @{ Expression = "ModeCollapseRisk"; Descending = $false }, @{ Expression = "MotionCoverage"; Descending = $true }, @{ Expression = "LogMelCosine"; Descending = $true }, @{ Expression = "AudioScore"; Descending = $true } | Select-Object -First $TopCount) - $skipped = @($rows | Where-Object { -not (Test-Path -LiteralPath $_.CandidateWav) }) - $playlistPath = Join-Path $PassDirectory "top-scoring-candidates.m3u" - $reportPath = Join-Path $PassDirectory "top-scoring-candidates.md" - $playlist = New-Object System.Collections.Generic.List[string] - $playlist.Add("#EXTM3U") - $report = New-Object System.Collections.Generic.List[string] - $report.Add("# Top Scoring Playable Song Candidates") - $report.Add("") - $report.Add(('playlist: `{0}`' -f $playlistPath)) - $report.Add("") - - $rank = 1 - foreach ($row in $ranked) { - $title = "#{0} {1} collapse={2:0.######} motion={3:0.######} cosine={4:0.######} score={5:0.######} verdict={6}" -f $rank, $row.CandidateId, $row.ModeCollapseRisk, $row.MotionCoverage, $row.LogMelCosine, $row.AudioScore, $row.Verdict - $playlist.Add("#EXTINF:-1,$title") - $playlist.Add($row.CandidateWav) - - $report.Add(('- {0}. `{1}` / verdict `{2}` / collapse `{3:0.######}` / motion `{4:0.######}` / first-second `{5:0.######}` / cosine `{6:0.######}` / score `{7:0.######}` / rms `{8:0.######}` / centroid `{9:0.######}`' -f $rank, $row.CandidateId, $row.Verdict, $row.ModeCollapseRisk, $row.MotionCoverage, $row.FirstSecondEnergyShare, $row.LogMelCosine, $row.AudioScore, $row.RmsRatio, $row.CentroidRatio)) - $report.Add((' - candidate: `{0}`' -f $row.CandidateWav)) - $report.Add((' - reference: `{0}`' -f $row.ReferenceWav)) - $report.Add((' - summary: `{0}`' -f $row.SummaryPath)) - $rank++ - } - - if ($skipped.Count -gt 0) { - $report.Add("") - $report.Add("## Skipped Non-Playable Candidates") - foreach ($row in $skipped | Sort-Object -Property @{ Expression = "ModeCollapseRisk"; Descending = $false }, @{ Expression = "MotionCoverage"; Descending = $true }, @{ Expression = "LogMelCosine"; Descending = $true }, @{ Expression = "AudioScore"; Descending = $true }) { - $report.Add(('- `{0}` / verdict `{1}` / collapse `{2:0.######}` / motion `{3:0.######}` / cosine `{4:0.######}` / score `{5:0.######}` / expected candidate: `{6}`' -f $row.CandidateId, $row.Verdict, $row.ModeCollapseRisk, $row.MotionCoverage, $row.LogMelCosine, $row.AudioScore, $row.CandidateWav)) - } - } - - Set-Content -LiteralPath $playlistPath -Value $playlist - Set-Content -LiteralPath $reportPath -Value $report -} - -function Write-MusicStandardSnapshot { - param( - [string]$StorePath, - [string]$PassDirectory, - [string]$WorkerProject, - [string]$LogPath - ) - - $outputPath = Join-Path $PassDirectory "music-production-quality-standard.md" - try { - Invoke-LoggedProcess ` - -FilePath "dotnet" ` - -ArgumentList @( - "run", - "--project", - $WorkerProject, - "--", - "music-show", - "--store", - $StorePath, - "--knowledge-id", - "music-production-quality-standard-v1", - "--output", - $outputPath - ) ` - -LogPath $LogPath - } - catch { - Add-Content -LiteralPath $LogPath -Value "[$([DateTimeOffset]::UtcNow.ToString("O"))] quality-standard document not present in current learned-only store; wrote pass knowledge snapshot instead." - $reportPath = Join-Path $PassDirectory "music-production-knowledge-report.md" - $indexPath = Join-Path $PassDirectory "music-vector-index-after.md" - $lines = New-Object System.Collections.Generic.List[string] - $lines.Add("# Music Production Quality Standard Snapshot") - $lines.Add("") - $lines.Add("The canonical seed standard was not re-emitted by this learned-only pass. That is expected: pass distillation appends current lessons instead of reseeding manuals and static doctrine.") - $lines.Add("") - $lines.Add(('- store: `{0}`' -f $StorePath)) - $lines.Add(('- distillation report: `{0}`' -f $reportPath)) - $lines.Add(('- vector index: `{0}`' -f $indexPath)) - $lines.Add("") - if (Test-Path -LiteralPath $reportPath) { - $lines.Add("## Current Pass Knowledge Documents") - $lines.Add("") - foreach ($line in (Get-Content -LiteralPath $reportPath | Where-Object { $_ -like '- `*' })) { - $lines.Add($line) - } - } - - Set-Content -LiteralPath $outputPath -Value $lines - } -} - -$repoRoot = Resolve-RepoRoot -$codex = Get-Command $CodexCommand -ErrorAction Stop -$loopId = New-Timestamp -$loopRoot = Join-Path $repoRoot "artifacts/parity/song-snippet-swarms/$loopId" -$logRoot = Join-Path $loopRoot "logs" -$agentWorktreePrefix = Join-Path (Split-Path -Parent $repoRoot) "AquaSynth-agent-$loopId" -$workerProject = Join-Path $repoRoot "tools/IpaTrialWorker/IpaTrialWorker.csproj" -$storePath = Join-Path $loopRoot "song-trial-results.cc" -$seedValue = if ($Seed -eq 0) { Get-Random -Minimum 1 -Maximum ([int]::MaxValue) } else { $Seed } -$songSources = @(Get-SongSources -Source $Source -SourceFolder $SourceFolder) -New-Item -ItemType Directory -Force -Path $loopRoot, $logRoot | Out-Null - -Set-Content -LiteralPath (Join-Path $loopRoot "loop-index.md") -Value @" -# Song Snippet Trial Swarm $loopId - -- repo: $repoRoot -- source: $Source -- source_folder: $SourceFolder -- song_sources: $($songSources -join '; ') -- codex: $($codex.Source) -- passes: $Passes -- agents_per_pass: $AgentsPerPass -- songs_per_agent: $SongsPerAgent -- iterations_per_target: $IterationsPerTarget -- playlist_top_count: $PlaylistTopCount -- seed: $seedValue -- duration_seconds: $DurationSeconds -- full_songs: $FullSongs -- new_segment_per_pass: $NewSegmentPerPass -- random_source_per_agent: $RandomSourcePerAgent -- store: $storePath -- worker: $workerProject -- agent_worktree_prefix: $agentWorktreePrefix - -"@ - -$latestDistilledStore = "" -$musicKnowledgeStore = Join-Path $loopRoot "music-production-knowledge.cc" -Invoke-LoggedProcess ` - -FilePath "dotnet" ` - -ArgumentList @( - "run", - "--project", - $workerProject, - "--", - "music-distill", - "--artifact-root", - $loopRoot, - "--output-store", - $musicKnowledgeStore, - "--output", - (Join-Path $loopRoot "music-production-knowledge-seed.md"), - "--manuals-only", - "true" - ) ` - -LogPath (Join-Path $logRoot "music-knowledge-seed.log") -Invoke-LoggedProcess ` - -FilePath "dotnet" ` - -ArgumentList @( - "run", - "--project", - $workerProject, - "--", - "music-index", - "--store", - $musicKnowledgeStore, - "--output", - (Join-Path $loopRoot "music-vector-index-seed.md"), - "--timeout-seconds", - "300" - ) ` - -LogPath (Join-Path $logRoot "music-knowledge-seed-index.log") -Invoke-LoggedProcess ` - -FilePath "dotnet" ` - -ArgumentList @( - "build", - $workerProject, - "--no-restore", - "--disable-build-servers", - "-p:UseSharedCompilation=false", - "-p:BuildInParallel=false" - ) ` - -LogPath (Join-Path $logRoot "worker-prebuild.log") -$latestMusicKnowledgeStore = $musicKnowledgeStore -for ($pass = 1; $pass -le $Passes; $pass++) { - $passId = "pass-{0:000}" -f $pass - $passDir = Join-Path $loopRoot $passId - $patchRoot = Join-Path $passDir "proposed-patches" - $phaseSeed = if ($NewSegmentPerPass) { $seedValue + (($pass - 1) * 7919) } else { $seedValue } - New-Item -ItemType Directory -Force -Path $passDir, $patchRoot | Out-Null - - $preEvidence = Join-Path $passDir "semantic-search-before.md" - $evidenceStore = if ($latestDistilledStore.Length -gt 0 -and (Test-Path -LiteralPath $latestDistilledStore)) { $latestDistilledStore } else { $storePath } - if (Test-Path -LiteralPath $evidenceStore) { - Invoke-LoggedProcess ` - -FilePath "dotnet" ` - -ArgumentList @( - "run", - "--project", - $workerProject, - "--", - "search", - "--store", - $evidenceStore, - "--query", - "song snippet alien gibberish rhythm tempo timbre spectral envelope modulation scene voices weak promising", - "--limit", - "40", - "--output", - $preEvidence, - "--skip-index", - "true" - ) ` - -LogPath (Join-Path $logRoot "$passId-search-before.log") - } - else { - Set-Content -LiteralPath $preEvidence -Value "# No prior song-snippet evidence yet" - } - - $preMusicEvidence = Join-Path $passDir "music-knowledge-before.md" - if ($latestMusicKnowledgeStore.Length -gt 0 -and (Test-Path -LiteralPath $latestMusicKnowledgeStore)) { - Invoke-LoggedProcess ` - -FilePath "dotnet" ` - -ArgumentList @( - "run", - "--project", - $workerProject, - "--", - "music-search", - "--store", - $latestMusicKnowledgeStore, - "--query", - "AquaSynth DSP manual music theory production arrangement groove harmony melody bass drums syrinx subtractive additive pad texture mix automation failure novelty", - "--limit", - "40", - "--require-vector", - "true", - "--output", - $preMusicEvidence - ) ` - -LogPath (Join-Path $logRoot "$passId-music-search-before.log") - } - else { - Set-Content -LiteralPath $preMusicEvidence -Value "# No prior music-production knowledge store yet" - } - - $jobs = @() - for ($agent = 1; $agent -le $AgentsPerPass; $agent++) { - $agentId = "agent-{0:00}" -f $agent - $agentDir = Join-Path $passDir $agentId - $agentPatchDir = Join-Path $patchRoot $agentId - New-Item -ItemType Directory -Force -Path $agentDir, $agentPatchDir | Out-Null - $agentWorktree = New-AgentWorktree ` - -RepoRoot $repoRoot ` - -WorktreeRoot "$agentWorktreePrefix-$passId-$agentId" ` - -LogPath (Join-Path $logRoot "$passId-$agentId-worktree.log") - $agentWorkerProject = Join-Path $agentWorktree "tools/IpaTrialWorker/IpaTrialWorker.csproj" - Invoke-LoggedProcess ` - -FilePath "dotnet" ` - -ArgumentList @( - "build", - $agentWorkerProject, - "--disable-build-servers", - "-p:UseSharedCompilation=false", - "-p:BuildInParallel=false" - ) ` - -LogPath (Join-Path $logRoot "$passId-$agentId-worker-prebuild.log") - $challengePaths = @() - $challengeReports = @() - $targetPatchDirs = @() - $agentSources = @() - $agentSeeds = @() - for ($song = 1; $song -le $SongsPerAgent; $song++) { - $songId = "target-{0:00}" -f $song - $agentChallengeRoot = Join-Path $agentDir $songId - $agentChallengePath = Join-Path $agentChallengeRoot "challenge.json" - $targetPatchDir = Join-Path $agentPatchDir $songId - New-Item -ItemType Directory -Force -Path $agentChallengeRoot, $targetPatchDir | Out-Null - $sourceIndex = if ($RandomSourcePerAgent) { - (($phaseSeed + ($agent * 1543) + ($song * 7919)) % $songSources.Count) - } - else { - (($phaseSeed - $seedValue) / 7919 + $song - 1) % $songSources.Count - } - $agentSource = $songSources[[int]$sourceIndex] - $agentSeed = $phaseSeed + ($agent * 104729) + ($song * 8191) - $durationArg = if ($FullSongs) { "0" } else { [string]$DurationSeconds } - Invoke-LoggedProcess ` - -FilePath "dotnet" ` - -ArgumentList @( - "run", - "--project", - $workerProject, - "--", - "song-prepare", - "--source", - $agentSource, - "--artifact-root", - $agentChallengeRoot, - "--duration-seconds", - $durationArg, - "--seed", - ([string]$agentSeed), - "--challenge-id", - "song-snippet-$loopId-$passId-$agentId-$songId", - "--output", - $agentChallengePath - ) ` - -LogPath (Join-Path $logRoot "$passId-$agentId-$songId-challenge-prepare.log") - $challengePaths += $agentChallengePath - $challengeReports += (Join-Path $agentChallengeRoot "challenge.md") - $targetPatchDirs += $targetPatchDir - $agentSources += $agentSource - $agentSeeds += $agentSeed - } - $challengeList = ($challengePaths | ForEach-Object { "- frozen challenge JSON: $_" }) -join "`n" - $challengeReportList = ($challengeReports | ForEach-Object { "- human-readable challenge report: $_" }) -join "`n" - $intelligenceReportList = ($challengeReports | ForEach-Object { "- target music intelligence report: $(Join-Path (Split-Path -Parent $_) "intelligence.md")" }) -join "`n" - $targetPatchList = ($targetPatchDirs | ForEach-Object { "- target patch output directory: $_" }) -join "`n" - $agentSourceList = ($agentSources | ForEach-Object { "- assigned source: $_" }) -join "`n" - $agentSeedList = ($agentSeeds | ForEach-Object { "- target seed: $_" }) -join "`n" - $durationLabel = if ($FullSongs) { "the full decoded song duration from each challenge report" } else { "$DurationSeconds seconds" } - $targetKind = if ($FullSongs) { "full-song" } else { "$DurationSeconds second" } - $iterationRoot = Join-Path $agentDir "iterations" - $outputPath = Join-Path $agentDir "hypothesis-agent.md" - $promptPath = Join-Path $agentDir "hypothesis-agent.prompt.md" - $logPath = Join-Path $logRoot "$passId-$agentId-hypothesis-agent.log" - $prompt = @" -You are an AquaSynth producer-apprenticeship worker. - -The dataset is on trial. Your patches, producer briefs, listening journals, spectrogram reviews, failures, and self-critiques become curriculum evidence in CultCache and the vector database. Write useful studio knowledge and reusable reasoning, not a one-off trick that flatters a scalar metric. - -Challenge: -$challengeList -$challengeReportList -$intelligenceReportList -- shared prior evidence: $preEvidence -- shared Qdrant music-production knowledge: $preMusicEvidence -- patch output directory: $agentPatchDir -$targetPatchList -- candidate filename prefix: $agentId -- phase id: $passId -- phase seed: $phaseSeed -- private iteration root: $iterationRoot -- isolated repo worktree for your commands: $agentWorktree -- required self-iteration attempts per target: $IterationsPerTarget -$agentSourceList -$agentSeedList -- required duration: $durationLabel - -Goal: -Write exactly one parseable AquaSynth .aqua patch for each frozen $targetKind reference assigned to you. This is scene-audio parity and producer apprenticeship, not IPA articulation. You may use ordinary voices, FM, AM/tremolo, filters, formants, noise layers, acoustic vocal/syrinx primitives, additive/PAD layers, curves, and helper voices. - -Composition objective: -- The previous corpus learned useful sound-production roles but collapsed into short phrases plus texture. Your job is now composition parity: declare meter, tonal center or progression, instrument lanes, section events, automation, and mix motion before polishing timbre. -- Every final patch must include a composition spine using today's implemented sugar: meter, sequence, chords or scale, and mix where appropriate. These lower to ordinary param and curve owners; they are not hidden magic. -- Treat the target as arranged music across time. There should be distinct musical events or motif mutations after the first second, distributed across the full assigned duration. For 10-second clips, seconds 2, 4, 6, and 8 are useful checkpoints; for 30-second or full-song targets, use section entrances, drops, fills, swells, or mix moves across the beginning, middle, and ending. -- Do not submit the stock attractor: a voiced burst at the start, a copied four-lane kick/snare/hat loop, then textured noise. If the reference really demands that shape, cite target artifacts and listening evidence proving it. - -Generalization: -- You own $SongsPerAgent target patches, and your report must compare all assigned targets and state what reusable scene/instrument knowledge transfers between them. -- The patches may share instrument roles, texture roles, control idioms, and DSL conventions, but each patch should fit its own target's tempo/register/spectral evidence. -- Future agents will receive distilled evidence from this trial when asked to zero-shot an audio production request. Read the shared Qdrant music-production knowledge file before writing patches, then make your studio reports useful retrieval context: name what transferred, what did not, what sounded alive, what sounded fake, and what evidence would change your next patch. - -Producer evidence: -- Write $agentDir/producer-brief.md before patching. For each target, include the artistic reading, likely genre/tempo feel, emotional/energy contour, section map, instrument role map, mix priorities, and the exact challenge artifacts you are trusting. -- Write $agentDir/listening-journal.md during self-iteration. For every attempt, record what you expected, what the rendered audio and spectrogram evidence showed, what sounded alive, what sounded fake or static, and the exact revision you made. -- Write $agentDir/spectrogram-review.md during self-iteration. For every target and every attempt, compare the target log-mel evidence against the candidate log-mel evidence directly. Name the visible mismatch in time and band/register terms, the Aqua owner lane responsible, the edit you made for the next attempt, and what still failed after reviewing the result. -- Write $agentDir/aqua-gap-ledger.md. List missing primitives, syntax sugar, control surfaces, analysis views, or renderer features that made the production harder. Each gap needs current workaround, evidence path, and whether it blocks composition or only polish. -- Write $agentDir/studio-lesson.md at the end. This is the compact lesson for the next musician: keep/cut verdicts, transferable production ideas, rejected tricks, and which AquaSynth abstractions should be mined next. -- The analysis worker records producer_musicianship_score, required_studio_docs_present, template_loop_risk, noise_percussion_risk, composition_section_score, and aqua_gap_count. These are warning lights only. Candidates with missing studio evidence, stock-loop risk, or noise-percussion risk are failure pressure, not curriculum exemplars. - -Self-iteration loop: -- For each target, run exactly $IterationsPerTarget local attempts before publishing the final .aqua file. -- Each attempt must write a candidate under the private iteration root at attempt-NN//patch, run the analysis worker against that one target, inspect the rendered candidate evidence, write the spectrogram review entry, and revise the next attempt. -- Analysis command pattern: - dotnet run --no-build --project "$agentWorkerProject" -- song-score --patch-root "" --challenge "" --artifact-root "" --batch-id "--attempt-NN" --store "/iteration-results.cc" --hypothesizer "$agentId-iteration" -- After each analysis run, read the attempt's evaluator-report.md and summary.csv as machine telemetry, not judgment. If the attempt rendered, also read audio/comparison.txt, audio/candidate-analysis.md, audio/candidate-logmel-spectrogram.csv, audio/candidate-logmel-band-stats.csv, audio/candidate-rms-envelope-autocorr.csv, and audio/candidate-whitened-spectral-autocorr.csv. Compare these with the target analysis_report, log_mel_spectrogram_csv, log_mel_band_stats_csv, rms_envelope_csv, and autocorrelation artifacts named in challenge.md. -- Use those candidate-side facts the same way you use target facts: directly compare log-mel energy by time window and band/register, then use envelope autocorrelation, whitened spectral autocorrelation, centroid/RMS, instrument-role metrics, and chip-distress risk as supporting clues. Move timings, filters, gains, sources, roles, and patterns between attempts. -- The analysis worker records song-continuity metrics: candidate_motion_coverage, motion_coverage_ratio, candidate_first_second_energy_share, first_second_energy_excess, candidate_tail_energy_share, and mode_collapse_risk. A patch that plays a short phrase in the first second and then coasts on low-motion texture/noise is failed song evidence even if its RMS or log-mel score looks tolerable. -- If an attempt has mode_collapse_risk >= .45, the next attempt must add later-section motifs or eventful motion across the target's full duration. Do not merely raise the noise bed or pad gain; that is hiding, not composing. -- If an attempt has high template_loop_risk or noise_percussion_risk, rebuild the role ownership before touching level: drums need pitched body plus filtered skin and target-specific gates; texture needs band limits and musical motion. -- Percussion articulation warning: sequenced gain alone does not retrigger a one-shot drum envelope. For patterned drums, every body/click/skin/hat/clap voice that should strike per step must include `trigger=` matching the lane step, otherwise pitch ramps and envelopes age from song start and later hits become dead-gate mush. -- Keep intermediate candidates inside the private iteration root; publish only one final .aqua per target to the official target patch output directory. - -Reusable abstraction mining: -- Your second job is to act like a musician designing the future patch language. Every attempt should name at least one reusable abstraction that made the patch easier to think about. -- Write $agentDir/abstraction-ledger.md as the report of record for syntax-sugar mining. For each proposed abstraction include: - - name: a lowercase slug such as syrinx-hook, sub-kick-grid, spectral-dust-hat, additive-wash, call-response-bass; - - role: what musical job it owns; - - owner sentence: X owns Y so Z remains true; - - controls: the parameters a musician would expect to tweak; - - current lowering: exact AquaSynth syntax using today's voice, texture, pattern, scale, layer, harmonics, spectrum, param, and curve commands; - - attempt evidence: which attempt used it, score movement, candidate analysis facts, and what changed after listening to the rendered output; - - sugar sketch: the shortest future syntax you wish existed; - - keep/cut verdict: whether this abstraction should be mined into DSL sugar, kept as a stock patch idiom, or discarded. -- Prefer abstractions that transfer across multiple assigned songs. A one-off trick is allowed only if you label it as target-specific and say why it should not become syntax. -- Do not propose sugar that hides ownership. The future shorthand must still lower into visible syrinx, subtractive, additive/PAD, texture, pattern, scale, or curve owners. -- Composition abstractions are now first-class sugar candidates. Prefer reusable names like `metered_progression`, `hook_degrees`, `lane_sequence`, `section_rise`, `drop_fill`, `mix_scene`, or better target-grounded names. Each one must say which `meter`, `sequence`, `chords`, `scale`, `mix`, `param`, and `curve` lines it lowers into. - -Noise and texture: -- Do not model background or recording color as a full-duration raw voice wave=noise bed. That produces static white-noise wash and will be treated as broken subtractive synthesis, not scene modeling. -- Use the shaped texture owner for noise roles, but make it target-specific: texture name=dust_hat role=dust pattern= step= gain=.08 sustain=, texture name=air_wash role=air gain=.035 sustain=, texture name=codec_bed role=codec gain=.04 sustain=. -- texture lowers to a gated noise voice with role-specific bandpass/highpass/lowpass/tremolo defaults and a control curve or pattern gate. Raw voice wave=noise is only acceptable for short transients with explicit gates and narrow filters. - -Instrument ownership: -- This harness is feeding the music-generator curriculum, so do not solve the target with three naked oscillators and a prayer. The scorer now records instrument-role metrics and chip-distress risk in CultCache. -- If the patch has a singing, creature, or alien lead role, use the syrinx/acoustic owner: source_port kind=syrinx, pressure/opening curves, acoustic_network, and acoustic_voice, then shape it with filters/modulation. -- Acoustic/syrinx graph syntax is complete-graph syntax. Do not write isolated source_port or acoustic_network fragments. If you use source_port, you must also define the referenced acoustic_path/path, terminals/connections/radiation_port, wave_clock when needed, acoustic_network, and acoustic_voice. If you cannot build that complete scaffold from a known-valid local patch such as patches/advanced/syrinx-voice.aqua, use a formant-filtered ordinary lead for this attempt and write the missing syrinx scaffold as an Aqua gap instead of submitting a non-rendering badge. -- If the patch has drums or rhythmic transients, use subtractive ownership: pitched sine/triangle body, filtered noise skin, short envelope, and pattern gate. -- For 808 percussion, start from `patches/808/kick.aqua`, `snare.aqua`, `hat.aqua`, and `clap.aqua` as reference shapes. In the song patch, split them into explicit retriggered layers: kick body/click/ghost, snare body/noise, staggered clap taps, closed/open hats, and optional perc skips. Add `drive`, `fold`, narrow hpf/lpf/bpf values, and sample-hold or square LFO modulators for crushed texture. If the render still sounds like generic pink noise, the drum owner failed; do not solve it with global gain. -- If the patch has a pad, bed, drone, or harmonic wash, use additive/PAD ownership: `layer engine=add` or `engine=pad`, `harmonics`, `spectrum`, and slow modulation. -- Ordinary simple voices are still legal as helpers, but a candidate built mostly from square/sine/saw blips with no syrinx, subtractive drum, additive/PAD, or shaped texture role will be treated as chip-distress-risk evidence. - -Rhythm and tempo: -- The challenge report includes tempo_bpm, beat_seconds, and tempo_confidence, estimated from spectral/RMS onset autocorrelation. -- The challenge report also points to analysis_report, log_mel_spectrogram_csv, log_mel_band_stats_csv, rms_envelope_csv, and rms_envelope_autocorr_csv; read them before writing the patch. -- Use spectrogram band means, first derivatives, second derivatives, and envelope autocorrelation peaks as evidence for which voices should be steady, pulsed, noisy, bright, or accelerating. -- Use those timing facts to build rhythmic controls. -- Current sequencing syntax is Strudel-ish through ordinary AquaSynth parameter curves: - - declare a parameter: `param path=/seq/kick default=0 min=0 max=1 step=.001` - - step a pattern with hold interpolation: `curve name=kick_seq path=/seq/kick points=0:1,0.12:0,0.48:1,0.60:0 interp=hold loop=true` - - new sugar now exists: `pattern name=kick_seq path=/seq/kick pattern=x..x step= high=1 low=0` - - use beat-derived times from `beat_seconds`; eighth notes are `beat_seconds/2`, sixteenths are `beat_seconds/4`. - - bind parameters into voices or primitives, for example gain=@/seq/kick, tremolo_hz=, noise=@/seq/hiss, freq=@/seq/pitch. -- Use `trigger=` on sequenced drum/transient voices when their envelope, pitch fall, FM decay, or filter motion must restart per hit. Example: `voice name=kick_body wave=sine freq=58 gain=@/seq/kick trigger= attack=.001 sustain=.045 decay=.42 sustain_level=.606 pitch_ramp=-3.8 drive=.42 fold=.12`. -- Do not invent unimplemented syntax like `s("bd sn")` inside the `.aqua` candidate. You may propose it in `instrument-conventions.md`. - -Composition sugar available today: -- Set the meter before sequencing: `meter bpm= beats=4`. -- Sequence any instrument lane without hand-declaring the gate parameter: `sequence name=kick pattern=x..x step= high=.8 low=0`, then bind `gain=@/seq/kick`. -- Declare chord/progression control lanes for pads or bass: `chords name=prog root= scale=minor progression=0,5,3,4 voicing=0,2,4 paths=/chords/prog/root,/chords/prog/third,/chords/prog/fifth step=bar`, then bind voices to those paths. -- Use `scale` for sampled note degrees inside the register: `scale name=hook path=/seq/pitch root= scale=minor degrees=0,2,4,2,5,4 step=`. -- Use `mix` for composition-scale lane motion: `mix name=pad points=0:.12,2:.18,4:.08,6:.24,8:.16`, then bind `gain=@/mix/pad/gain`. -- These are Strudel-ish authoring conveniences, but the lowered truth remains inspectable parameters and curves. - -Register and scale: -- The challenge report includes dominant_hz, register_low_hz, register_high_hz, root_note, suggested_scale, and scale_frequencies_hz. -- Songs tend to pick a register and stay there. Treat those bounds as the default melodic playground unless your hypothesis explicitly tests octave spread. -- Current scale sugar is explicit frequency sequencing: - - declare pitch: `param path=/seq/pitch default= min= max= step=.01 unit=Hz` - - step the scale: `curve name=lead_scale path=/seq/pitch points=0:,0.25:,0.5:,0.75: interp=hold loop=true` - - new sugar now exists: `scale name=lead_scale path=/seq/pitch freqs= degrees=0,1,3,2 step=` - - bind it: freq=@/seq/pitch -- Candidate patches may use implemented `pattern` and `scale` sugar or the explicit lowered `param`/`curve` form. Proposed future sugar goes in the report. - -Instrument and DSL convention invention: -- Invent at least three reusable instrument or pattern roles across your assigned targets, such as syrinx-hook, dust-hat-grid, codec-bed, rubber-bass, additive-wash, vowel-drone, or another precise name. -- Write $agentDir/instrument-conventions.md as a concise index that points into abstraction-ledger.md and summarizes: - - the proposed instrument role names; - - the control surfaces each role would want; - - any Strudel-like sugar that would make the patch shorter; - - the exact lowering into today's AquaSynth syntax using explicit voice, texture, pattern, scale, param, and curve lines. -- The `.aqua` candidate must use today's implemented syntax only: `pattern`, `scale`, `param`, `curve`, and ordinary patch/voice syntax are legal. Proposed future sugar is evidence for the next DSL cut, not magic accepted by the parser. -- Today's implemented composition syntax also includes `meter`, `sequence`, `chords`, and `mix`. Prefer those over raw `param`/`curve` boilerplate when writing composition-scale structure. -- Legal oscillator wave= values are sine, square, saw, triangle, and noise only. Use square plus filters/envelopes for pulse-like tone; pulse is not accepted syntax. -- You do not own the main AquaSynth source tree during this job. Your command workspace is an isolated worktree, and shared outputs must be written only under your assigned artifact/report/patch directories. Do not edit main `src/`, `tests/`, `docs/`, `patches/library.yaml`, or shared repo state. Proposed DSL/source changes belong in `abstraction-ledger.md` and `aqua-gap-ledger.md`. - -Evidence contract: -- Read every assigned challenge report, target music intelligence report, $preEvidence, and $preMusicEvidence. -- Write $agentDir/hypotheses.md with: per-target reference features, shared cross-target invariants, cited analysis artifacts, tempo/rhythm plan, register/scale plan, scene voices, synthesis owners, invented instrument roles, expected metric movement on assigned targets, known risks. -- Include a `Composition Map` section in $agentDir/hypotheses.md: meter/time signature, progression or tonal center, instrument lanes, section events after the opening, automation/mix moves, and which visible spectrogram regions should prove the arrangement did not collapse. -- Also write $agentDir/producer-brief.md, $agentDir/listening-journal.md, $agentDir/spectrogram-review.md, $agentDir/aqua-gap-ledger.md, and $agentDir/studio-lesson.md. These reports are now curriculum admission evidence, not decorative paperwork. -- Write exactly one `.aqua` file under each target patch output directory named `____.aqua`. -- Include at least three scene voices or layers in the patch: a primary voice/body, a rhythmic drum/transient/noise role, and a pad/bed/recording-color role. Prefer syrinx for the primary voice when it is voice-like, subtractive for the drum/transient, and additive/PAD or shaped texture for the bed. -- The target must have full-form continuity: distinct musical events or motif mutations after the first second, with audible activity distributed across the beginning, middle, and ending. A one-second riff followed by gently textured pink noise is mode collapse and should not be submitted. -- Background/recording-color layers must use texture or an equivalently gated and band-shaped explicit voice; a static full-duration white-noise bed is failed evidence. -- Make each patch duration/gates cover its matching target duration from the challenge report. - -Return a short final summary naming the patch and report. -"@ - $jobs += Start-CodexAgentJob ` - -RepoRoot $agentWorktree ` - -Prompt $prompt ` - -PromptPath $promptPath ` - -OutputPath $outputPath ` - -LogPath $logPath ` - -CodexCommand $CodexCommand ` - -CodexModel $CodexModel ` - -JobName "$passId-$agentId" ` - -SandboxMode "workspace-write" ` - -WritableDirs @($agentDir, $agentPatchDir) - } - - Wait-CodexJobs -Jobs $jobs - Assert-SongCandidates -PatchDirectory $patchRoot -ExpectedCount ($AgentsPerPass * $SongsPerAgent) - Assert-AgentSelfIterationEvidence ` - -PassDirectory $passDir ` - -AgentsPerPass $AgentsPerPass ` - -SongsPerAgent $SongsPerAgent ` - -IterationsPerTarget $IterationsPerTarget - - for ($agent = 1; $agent -le $AgentsPerPass; $agent++) { - $agentId = "agent-{0:00}" -f $agent - $agentDir = Join-Path $passDir $agentId - for ($song = 1; $song -le $SongsPerAgent; $song++) { - $songId = "target-{0:00}" -f $song - Invoke-LoggedProcess ` - -FilePath "dotnet" ` - -ArgumentList @( - "run", - "--project", - $workerProject, - "--", - "song-score", - "--patch-root", - (Join-Path (Join-Path $patchRoot $agentId) $songId), - "--challenge", - (Join-Path $agentDir "$songId/challenge.json"), - "--artifact-root", - (Join-Path $agentDir $songId), - "--batch-id", - "$passId-$agentId-$songId", - "--store", - $storePath, - "--hypothesizer", - "external-codex-song-swarm-$passId-$agentId-$songId" - ) ` - -LogPath (Join-Path $logRoot "$passId-$agentId-$songId-score-candidate.log") - } - } - - Write-PassPlaylist -PassDirectory $passDir -TopCount $PlaylistTopCount - - $curatorDir = Join-Path $passDir "knowledge-curator" - New-Item -ItemType Directory -Force -Path $curatorDir | Out-Null - $curatorWorktree = New-AgentWorktree ` - -RepoRoot $repoRoot ` - -WorktreeRoot "$agentWorktreePrefix-$passId-knowledge-curator" ` - -LogPath (Join-Path $logRoot "$passId-knowledge-curator-worktree.log") - $curatorPromptPath = Join-Path $curatorDir "knowledge-curator.prompt.md" - $curatorOutputPath = Join-Path $curatorDir "knowledge-curator.md" - $curatorPrompt = @" -You are the AquaSynth music-production knowledge curator for $passId. - -Your only job is to distill musician model output from this phase into actionable and novel knowledgebase entries. Do not write patches. Do not praise effort. Do not summarize everything. Extract the lessons that should change what the next musician does. - -Read: -- pass directory: $passDir -- proposed patches: $patchRoot -- analysis telemetry reports and summary CSV files under each agent target directory -- producer-brief.md, listening-journal.md, spectrogram-review.md, aqua-gap-ledger.md, studio-lesson.md, abstraction-ledger.md, instrument-conventions.md from musician agents -- playlist report: $(Join-Path $passDir "top-scoring-candidates.md") -- prior Qdrant music knowledge injection: $preMusicEvidence - -Write exactly this file: -- $curatorDir/knowledge-curation.md - -Format knowledge-curation.md as compact entries. Each entry must include: -- title: short reusable lesson -- novelty: what this adds beyond the prior Qdrant knowledge file -- owner sentence: X owns Y so Z remains true -- do: concrete steps a fresh AquaSynth musician can apply -- lower to AquaSynth: exact current syntax or patch idiom if applicable -- evidence: file paths, candidate ids, metrics, and musician report lines used -- reject: what not to copy from the phase - -Admission standard: -- Keep only lessons with evidence and a clear next action. -- Treat musician spectrogram-review.md files as the primary evidence for what they saw, tried, and failed to achieve. Metrics may corroborate a lesson, but they must not be the lesson. -- Prefer composition, arrangement, sound design, mixing, and AquaSynth sugar lessons that transfer across targets. -- Reject generic advice, duplicate role-name slogans, and anything that merely restates the prompt. -- If the phase learned mostly negative evidence, write negative entries with precise failure signatures. - -Return a short final note naming knowledge-curation.md. -"@ - $curatorJob = Start-CodexAgentJob ` - -RepoRoot $curatorWorktree ` - -Prompt $curatorPrompt ` - -PromptPath $curatorPromptPath ` - -OutputPath $curatorOutputPath ` - -LogPath (Join-Path $logRoot "$passId-knowledge-curator.log") ` - -CodexCommand $CodexCommand ` - -CodexModel $CodexModel ` - -JobName "$passId-knowledge-curator" ` - -SandboxMode "workspace-write" ` - -WritableDirs @($passDir, $curatorDir) - Wait-CodexJobs -Jobs @($curatorJob) - if (!(Test-Path -LiteralPath (Join-Path $curatorDir "knowledge-curation.md")) -or - ((Get-Item -LiteralPath (Join-Path $curatorDir "knowledge-curation.md")).Length -lt 64)) { - throw "Knowledge curator did not write a usable knowledge-curation.md for $passId." - } - - $distilledStore = Join-Path $passDir "song-trial-results.distilled.cc" - Invoke-LoggedProcess ` - -FilePath "dotnet" ` - -ArgumentList @( - "run", - "--project", - $workerProject, - "--", - "index", - "--store", - $storePath, - "--output", - (Join-Path $passDir "vector-index-after.md"), - "--timeout-seconds", - "300" - ) ` - -LogPath (Join-Path $logRoot "$passId-index-after.log") - - Invoke-LoggedProcess ` - -FilePath "dotnet" ` - -ArgumentList @( - "run", - "--project", - $workerProject, - "--", - "search", - "--store", - $storePath, - "--query", - "$passId song snippet current candidates promising weak rhythm tempo timbre spectral scene voices", - "--limit", - "40", - "--output", - (Join-Path $passDir "semantic-search-after.md"), - "--skip-index", - "true" - ) ` - -LogPath (Join-Path $logRoot "$passId-search-after.log") - - Invoke-LoggedProcess ` - -FilePath "dotnet" ` - -ArgumentList @( - "run", - "--project", - $workerProject, - "--", - "distill", - "--store", - $storePath, - "--output-store", - $distilledStore, - "--output", - (Join-Path $passDir "distillation-report.md"), - "--min-cosine", - "0.35", - "--max-results", - "40" - ) ` - -LogPath (Join-Path $logRoot "$passId-distill.log") - $latestDistilledStore = $distilledStore - - Invoke-LoggedProcess ` - -FilePath "dotnet" ` - -ArgumentList @( - "run", - "--project", - $workerProject, - "--", - "music-distill", - "--artifact-root", - $passDir, - "--input-store", - $musicKnowledgeStore, - "--output-store", - $musicKnowledgeStore, - "--output", - (Join-Path $passDir "music-production-knowledge-report.md"), - "--max-candidates", - "40", - "--include-manuals", - "false", - "--learned-only", - "true" - ) ` - -LogPath (Join-Path $logRoot "$passId-music-distill.log") - - Invoke-LoggedProcess ` - -FilePath "dotnet" ` - -ArgumentList @( - "run", - "--project", - $workerProject, - "--", - "music-index", - "--store", - $musicKnowledgeStore, - "--output", - (Join-Path $passDir "music-vector-index-after.md"), - "--timeout-seconds", - "300" - ) ` - -LogPath (Join-Path $logRoot "$passId-music-index.log") - $latestMusicKnowledgeStore = $musicKnowledgeStore - - Write-MusicStandardSnapshot ` - -StorePath $musicKnowledgeStore ` - -PassDirectory $passDir ` - -WorkerProject $workerProject ` - -LogPath (Join-Path $logRoot "$passId-music-show-standard.log") -} - -Write-Host "Song snippet trial swarm complete: $loopRoot" diff --git a/tools/sound-guard/README.md b/tools/sound-guard/README.md deleted file mode 100644 index eb126b1..0000000 --- a/tools/sound-guard/README.md +++ /dev/null @@ -1,65 +0,0 @@ -# sound-guard - -A regression check for the sound itself. One command renders (or is given) every shipped Dings clip (8 sender voices x 4 events, plus the 4 neutral fallbacks) -and every Earcon Workshop clip (4 identities x 6 events), runs `../aqua-ear` over each, and **exits 1 if any assertion fails**. It exists so a double hit, -a click, clipping, a cut tail or a clip that is suddenly louder than its siblings cannot come back unnoticed (the v3 Void knock, 95 ms into every note, -was a second hit that nothing measured until Meta heard it). - -**It measures signal facts. It cannot judge annoyance, timbre or feel.** A clip can pass every check here and still sound bad; a clip can fail one and -sound fine. Nothing in this tool has heard anything. - -## Run - -``` -python3 tools/sound-guard/guard.py # renders both families into a temp dir (about 10 s), checks 60 clips -python3 tools/sound-guard/guard.py --dings DIR --earcon DIR # check existing output (DIR = finish.py's `out`, and a dir of cli.mjs packs, one subdir per identity) -python3 -m unittest -v test_guard # in tools/sound-guard: the guard's own tests, ~3 s -``` - -`python3` must have numpy, scipy and soundfile (libsndfile with Vorbis), as for aqua-ear; `node` renders and reads the intended note times. This sandbox: -`/var/lib/mind-aqua-self/ogg-venv/bin/python`. Self-render builds the Dings (including the neutral fallbacks, from the Earcon Workshop warm-bell identity) and the earcons itself. Exit 0 = pass, 1 = failed assertion or stale known failure, 2 = tool error (render failed, -aqua-ear's thresholds drifted from the pins, node missing). - -## What is asserted, per clip - -| # | assertion | how | -|---|---|---| -| 1 | one onset per intended note | Intended times: `RHYTHM` in `dings-voices/src/voices.mjs`; `EVENTS` x tempo in `earcon-workshop/web/earcon.js` (both machine readable, read through node). Each note owns the window [t - 20, t + 20] ms. Full band: each window has an onset, the loudest starts within 8 ms of t, an onset before it is a pre-echo only if it is 10 dB or more under it, an onset after it in the window is a double hit, any onset outside every window is stray. High band (>2 kHz): no onset outside any window. Kinds: `missing timing double stray stray_hf` | -| 2 | no click, step or DC | aqua-ear `click_step_dc`: discontinuities on the clip with 20 ms of silence in front (so a non-zero first sample counts), DC on the clip | -| 3 | no clipped samples | aqua-ear `clipping_true_peak` (overs, plateaus at >= 0.99), plus a plateau detector relative to the clip's own peak (WAV only) | -| 4 | true peak under a ceiling | measured on the decoded file; Dings -8 dBTP, Earcon and neutral -2.5 dBTP | -| 5 | tail settled | `abrupt_end` clear on every clip; for the voices built to end by the next onset (Kiko, Libby, Void, Nibu) `overlapping_tails` clear at each following note. Other voices and all earcons ring over the next note by design and are not asserted | -| 6 | loudness spread | LAE (A-weighted exposure, the quantity `finish.py` equalises) of every clip within +-0.5 dB of the median of the 32 sender clips | - -Not asserted: Earcon loudness (the events differ on purpose), anything about the 12 non-shipped Nibu proposal clips. - -## Thresholds: `thresholds.json` - -Every number the guard compares against is in that one file, each with a `why`. `guard.py` has no magic numbers (a test parses its source to prove it) and -`test_guard.py` fails if a threshold has no reason or the code reads a name the file lacks. aqua-ear's own detector boundaries stay in `aqua_ear.py`, so -that file owns them; the guard **pins** the ones it relies on (`aqua_ear_pins`) and refuses to run (exit 2) if they drift, so loosening aqua-ear cannot -loosen the guard silently. Change a number by editing its value and its `why` together. - -Voice policy (also in the file): `swell_voices` (Eureka, Heimdall: slow attack by design, so the full-band count is not asserted), `settle_before_next_voices`, -and `neutral_events` (the neutral clips are Earcon Workshop warm-bell renders; their note times are inferred from the audio). - -## Known failures - -`known_failures` in `thresholds.json` lists clips that fail today, each with the assertion, the measured number, a slack and a reason. The guard prints them on every -run. If one stops failing the run fails (`STALE`: remove the entry); if its number moves by more than the slack the run fails until the entry is re-justified. Today the list is empty: the four neutral fallback clips -were 4.3 to 13.7 dB louder than the sender clips until `finish.py` equalised them with the senders. - -## What the guard cannot see (measured, not guessed) - -- Two hits of the same timbre inside one rising attack, or a flam under about 25 ms whose second hit adds less than 4 dB: the onset detector needs a 4 dB rise. - Depends on phase: a copy of a Void note 15 ms later was caught (10 ms was not); the same copy 10 to 20 ms later was missed on Kiko and Weksa. A spectral-flux detector (listed as not built in aqua-ear) would close it. -- The v3 knock: caught down to 20 dB under its v3 level on every Void motif tried; at 22 dB under only on the loudest clip. Below about -76 dBFS in the high band the - legitimate clips (Aqua's glide, Heimdall's swell) have their own rises, so the floor cannot go lower without false alarms. -- Eureka and Heimdall full-band onsets (swell voices): only high-band strays are asserted for them. -- Flat-topped limiting below 0.98 of the clip's peak on a decoded Ogg (Vorbis rounds the plateau off); a WAV shows it. -- Anything under -80 dBFS in the high band, and everything about how the sound feels. - -aqua-ear gaps the guard works around, found while building it: it misses an onset that is already at full level at sample 0 (so the guard pads 20 ms of silence); it counts -the envelope ripple of low harmonic tones as onsets (so the guard peak-holds the envelope 10 ms; Heimdall gave 50 to 90 onsets a clip); and its `double_hit`/`overlapping_tails` -verdicts fire on 13 of the 32 sender clips (Vorbis pre-echo 12 to 15 ms ahead of an attack, Nibu's 8 kHz grain, ring-over voices), which are not defects. The guard does its own note-aware -check on top of aqua-ear's onset table. These could move into aqua-ear; they were not changed there. diff --git a/tools/sound-guard/guard.py b/tools/sound-guard/guard.py deleted file mode 100644 index 15a7a06..0000000 --- a/tools/sound-guard/guard.py +++ /dev/null @@ -1,361 +0,0 @@ -#!/usr/bin/env python3 -"""sound-guard: one command that renders (or is given) every shipped Dings clip and every Earcon Workshop clip and checks each one with -tools/aqua-ear. Exit 0 = every assertion holds (known failures aside), 1 = something failed or a known failure went stale, 2 = tool error. -It measures signal facts. It cannot judge annoyance, timbre or feel. See README.md. Every number it compares against is in thresholds.json.""" -import argparse, json, os, shutil, subprocess, sys, tempfile -sys.dont_write_bytecode = True # the guard imports from sibling tools; it must not leave __pycache__ in their trees -from pathlib import Path - -HERE = Path(__file__).resolve().parent -TOOLS = HERE.parent -sys.path.insert(0, str(TOOLS / "aqua-ear")) -sys.path.insert(0, str(TOOLS / "dings-voices" / "src")) -import numpy as np -import scipy.signal as ss -from scipy.ndimage import maximum_filter1d -import aqua_ear as ae -from metriclib import lae - -MS_PER_S = 1000 -SHIPPED_RATE = 48000 # Hz: every shipped clip (finish.py asserts it too) -NODE_TIMEOUT_S = 60 -RENDER_TIMEOUT_S = 240 -STDERR_TAIL = 800 -HF_ORDER = 4 # Butterworth order of aqua-ear's high-band channel (aqua_ear.analyze); repeated here because the guard holds the envelope before detecting -SILENT_PEAK = 1e-6 # a clip whose peak is below this is silent: no onsets to look for -SENDERS = ["aqua", "eureka", "heimdall", "kiko", "libby", "nibu", "void", "weksa"] -MOTIFS = ["mention", "dm", "message", "invite"] - - -class GuardError(Exception): - """Tool error (exit 2): the guard could not do its job, which is different from a clip failing.""" - - -def load_thresholds(path=None): - d = json.loads(Path(path or HERE / "thresholds.json").read_text()) - return d - - -def tv(th, name): - return th["thresholds"][name]["value"] - - -def pol(th, name): - return th["voice_policy"][name]["value"] - - -def check_pins(th): - """aqua-ear owns its detector boundaries; the guard pins the ones it relies on so a loosening there cannot loosen the guard silently.""" - bad = [f"{k}: aqua_ear.TH={ae.TH.get(k)!r}, pinned {p['value']!r}" for k, p in th["aqua_ear_pins"].items() if ae.TH.get(k) != p["value"]] - if bad: - raise GuardError("aqua-ear thresholds differ from tools/sound-guard/thresholds.json aqua_ear_pins (re-justify the pin or revert aqua-ear): " + "; ".join(bad)) - - -# ---- one failure -------------------------------------------------------------------------------------------------------- -class Fail: - def __init__(self, assertion, kind, value, msg): - self.assertion, self.kind, self.value, self.msg = assertion, kind, float(value), msg - - def __repr__(self): - return f"{self.assertion}/{self.kind}={self.value:g}: {self.msg}" - - -# ---- measurement ---------------------------------------------------------------------------------------------------------- -def hold(env, n): - """Peak-hold over the last n ms of a 1 ms envelope: rising edges are untouched, valleys shorter than n are filled.""" - return maximum_filter1d(env, size=n, origin=(n - 1) // 2) - - -def onset_rows(x, sr, th): - """Onset rows (aqua-ear's detector and table) on the held full-band and held high-band envelopes of x preceded by pad_ms of silence. - Times are in PADDED ms. Returns (rows, hf_rows, raw_env_full).""" - pad, n = tv(th, "pad_ms"), tv(th, "hold_ms") - xp = np.concatenate([np.zeros(int(sr * pad / MS_PER_S)), x]) - peak = float(np.max(np.abs(x))) if len(x) else 0.0 - if peak <= SILENT_PEAK: - return [], [], ae.envelope_1ms(xp, sr) - raw = ae.envelope_1ms(xp, sr) - h = hold(raw, n) - rows = ae.onset_table(h, ae.detect_onsets(h, float(h.max())), "full") - hf_rows = [] - sos = ss.butter(HF_ORDER, ae.TH["hf_cut_hz"], "highpass", fs=sr, output="sos") - eh = hold(ae.envelope_1ms(ss.sosfiltfilt(sos, xp), sr), n) - floor = tv(th, "hf_floor_dbfs") - if eh.max() > floor: - hf_rows = ae.onset_table(eh, ae.detect_onsets(eh, float(eh.max()), floor), "hf") - return rows, hf_rows, raw - - -def check_onsets(rows, hf_rows, notes_ms, swell, th): - """Assertion 1. Each intended note t owns the window [t - pre, t + post]. Full band (not for swell voices): every window has an onset; - its loudest onset is the note and starts within main_timing_ms of t; an onset before it is a precursor (pre-echo) only if precursor_db under it; - any onset after it in the window is a double hit; any onset outside every window is stray. High band: only strays outside every window.""" - pad, pre, post = tv(th, "pad_ms"), tv(th, "window_pre_ms"), tv(th, "window_post_ms") - wins = [(t + pad - pre, t + pad + post, t + pad) for t in notes_ms] - inside = lambda ms: any(lo <= ms <= hi for lo, hi, _ in wins) - out, mains = [], [] - rel = lambda ms: ms - pad - for lo, hi, t in wins: - w = [r for r in rows if lo <= r["ms"] <= hi] - if not w: - if not swell: - out.append(Fail("onsets", "missing", 1, f"no full-band onset for the note at {rel(t):g} ms (window {rel(lo):g}..{rel(hi):g} ms)")) - continue - main = max(w, key=lambda r: r["peak_dbfs"]) - mains.append(main) - if swell: - continue - if abs(main["ms"] - t) > tv(th, "main_timing_ms"): - out.append(Fail("onsets", "timing", abs(main["ms"] - t), f"note at {rel(t):g} ms: loudest onset at {rel(main['ms'])} ms, {main['ms'] - t:+g} ms off (limit {tv(th, 'main_timing_ms'):g})")) - for r in w: - if r is main: - continue - if r["ms"] > main["ms"]: - out.append(Fail("onsets", "double", 1, f"second full-band onset at {rel(r['ms'])} ms, {r['ms'] - main['ms']} ms after the note at {rel(main['ms'])} ms ({r['peak_dbfs'] - main['peak_dbfs']:+.1f} dB re it)")) - elif main["peak_dbfs"] - r["peak_dbfs"] < tv(th, "precursor_db"): - out.append(Fail("onsets", "double", 1, f"onset at {rel(r['ms'])} ms before the note at {rel(main['ms'])} ms is only {main['peak_dbfs'] - r['peak_dbfs']:.1f} dB under it (precursor limit {tv(th, 'precursor_db'):g} dB)")) - if not swell: - for r in rows: - if not inside(r["ms"]): - out.append(Fail("onsets", "stray", 1, f"full-band onset at {rel(r['ms'])} ms ({r['peak_dbfs']} dBFS) is not within a note window")) - for r in hf_rows: - if not inside(r["ms"]): - out.append(Fail("onsets", "stray_hf", 1, f"high-band onset at {rel(r['ms'])} ms ({r['peak_dbfs']} dBFS in the >2 kHz band) is not within a note window")) - return out, mains - - -def flat_top_runs(x, th): - peak = float(np.max(np.abs(x))) - hi = np.abs(x) >= tv(th, "flat_top_rel") * peak - eq = np.concatenate([[False], np.abs(np.diff(x)) < tv(th, "flat_top_eps")]) - ok = hi & eq - runs = run = 0 - for i in range(len(x)): - run = run + 1 if ok[i] else 0 - if run == ae.TH["clip_run"] - 1: - runs += 1 - return runs - - -def check_clip(x, sr, notes_ms, policy, th): - """All per-clip assertions. policy: dict(ceiling_dbtp, swell, settle). Returns (failures, facts).""" - f, facts = [], {} - rows, hf_rows, raw = onset_rows(x, sr, th) - of, mains = check_onsets(rows, hf_rows, notes_ms, policy["swell"], th) - f += of - facts["onsets"] = [r["ms"] - tv(th, "pad_ms") for r in rows] - facts["onsets_hf"] = [r["ms"] - tv(th, "pad_ms") for r in hf_rows] - # 2. click / step / DC: aqua-ear's detector. Steps on the padded clip (so a non-zero first sample counts), DC on the clip itself. - xp = np.concatenate([np.zeros(int(sr * tv(th, "pad_ms") / MS_PER_S)), x]) - steps = ae.det_click_dc(xp, sr)["evidence"]["discontinuities"] - dc = ae.det_click_dc(x, sr)["evidence"]["dc"] - for s in steps: - f.append(Fail("click_step_dc", s["kind"], s["jump"], f"{s['kind']} at {s['ms'] - tv(th, 'pad_ms'):g} ms, jump {s['jump']}")) - if abs(dc) >= ae.TH["dc_abs"]: - f.append(Fail("click_step_dc", "dc", abs(dc), f"DC offset {dc:+.5f} (limit {ae.TH['dc_abs']})")) - # 3 and 4. clipping and true peak - c = ae.det_clip(x, sr) - if c["fired"]: - e = c["evidence"] - f.append(Fail("clipping", "clip", e["over_samples"] + e["plateau_runs"], f"{e['over_samples']} sample(s) over 1.0, {e['plateau_runs']} plateau run(s) at >= {ae.TH['clip_level']}, true peak {e['true_peak_dbtp']:.2f} dBTP")) - runs = flat_top_runs(x, th) - if runs: - f.append(Fail("clipping", "flat_top", runs, f"{runs} run(s) of {ae.TH['clip_run']}+ equal samples at >= {tv(th, 'flat_top_rel')} of the clip's own peak")) - tp = c["evidence"]["true_peak_dbtp"] - facts["true_peak_dbtp"] = round(tp, 2) - if tp > policy["ceiling_dbtp"]: - f.append(Fail("true_peak", "ceiling", tp, f"true peak {tp:.2f} dBTP over the {policy['ceiling_dbtp']:g} dBTP ceiling")) - # 5. tail settled at the end; tail settled before the next note for voices built that way - peak = float(np.max(np.abs(x))) - end = ae.det_end(x, sr, peak) - if end["fired"]: - f.append(Fail("tail_end", "abrupt_end", end["evidence"]["drop_db"], end["verdict"].split(" [")[0])) - if policy["settle"] and len(mains) > 1: - ov = ae.det_overlap(raw, mains) - if ov["fired"]: - h = [e for e in ov["evidence"] if e["tail_db_re_prev_peak"] > ae.TH["overlap_tail_db"]] - f.append(Fail("tail_overlap", "overlap", max(e["tail_db_re_prev_peak"] for e in h), ov["verdict"].split(" [")[0])) - return f, facts - - -def loudness_failures(lae_by_clip, th, neutral=()): - """Assertion 6. Median over the sender clips; every clip (neutral too) within loudness_dev_db of it.""" - sender = [v for k, v in lae_by_clip.items() if k not in neutral] - med = float(np.median(sender)) - band = tv(th, "loudness_dev_db") - out = {} - for k, v in lae_by_clip.items(): - if abs(v - med) > band: - out[k] = Fail("loudness", "outlier", abs(v - med), f"LAE {v:.2f} dB is {v - med:+.2f} dB from the sender median {med:.2f} dB (band +-{band:g})") - return out, med - - -# ---- sources: where the clips and the intended note times come from ------------------------------------------------------------ -def node_json(js): - try: - r = subprocess.run(["node", "--input-type=module", "-e", js], capture_output=True, text=True, timeout=NODE_TIMEOUT_S, check=True) - except (OSError, subprocess.SubprocessError) as e: - raise GuardError(f"node is needed for the intended note times (RHYTHM in voices.mjs, EVENTS in earcon.js): {e}") - return json.loads(r.stdout) - - -def intended(): - js = (f'import {{RHYTHM}} from "{(TOOLS / "dings-voices/src/voices.mjs").as_posix()}";' - f'import {{EVENTS, IDENTITIES}} from "{(TOOLS / "earcon-workshop/web/earcon.js").as_posix()}";' - 'console.log(JSON.stringify({dings:Object.fromEntries(Object.entries(RHYTHM).map(([k,v])=>[k,v.map(n=>n[0])])),' - 'earcon:Object.fromEntries(Object.entries(EVENTS).map(([k,v])=>[k,v.notes.map(n=>n[1])])),identities:Object.keys(IDENTITIES)}))') - return node_json(js) - - -def read(path): - x, sr, ch = ae.load(str(path)) - return x, sr - - -def dings_clips(d, th, want): - """Yield (id, path, family, voice, notes_ms). d is the generator's out dir (manifest.json, senders/, neutral/).""" - d = Path(d) - mf = d / "manifest.json" - if not mf.exists(): - raise GuardError(f"{mf} missing: --dings takes the out dir finish.py writes") - man = json.loads(mf.read_text()) - out = [] - for s in SENDERS: - for m in MOTIFS: - rel = man.get("senders", {}).get(s, {}).get(m) - out.append((f"dings/{s}/{m}", d / rel if rel else None, "dings", s, want["dings"][m])) - nev = pol(th, "neutral_events") - for m in MOTIFS: - rel = man.get("neutral", {}).get(m) - out.append((f"dings/neutral/{m}", d / rel if rel else None, "neutral", "neutral", want["earcon"][nev[m]])) - return out - - -def earcon_clips(d, want): - """d holds one pack per identity (//pack.json + wavs, as cli.mjs writes), or is itself one pack.""" - d = Path(d) - packs = {p.parent.name: p.parent for p in d.glob("*/pack.json")} or ({d.name: d} if (d / "pack.json").exists() else {}) - out = [] - for ident in want["identities"]: - pk = packs.get(ident) - pack = json.loads((pk / "pack.json").read_text()) if pk else None - tempo = pack["params"]["tempo"] if pack else 1 - for ev, times in want["earcon"].items(): - file = pack["events"].get(ev, {}).get("file") if pack else None - out.append((f"earcon/{ident}/{ev}", pk / file if file else None, "earcon", ident, [t * tempo for t in times])) - return out - - -def render_all(tmp): - tmp = Path(tmp) - dv = TOOLS / "dings-voices" / "src" - steps = [(["node", str(dv / "build.mjs"), str(tmp / "dings" / "raw")], None)] - (tmp / "dings" / "out").mkdir(parents=True) - steps.append(([sys.executable, str(dv / "finish.py"), str(tmp / "dings" / "raw"), str(tmp / "dings" / "out")], None)) - for ident in intended()["identities"]: - steps.append((["node", str(TOOLS / "earcon-workshop" / "cli.mjs"), ident, str(tmp / "earcon" / ident)], None)) - for cmd, _ in steps: - r = subprocess.run(cmd, capture_output=True, text=True, timeout=RENDER_TIMEOUT_S, env={**os.environ, "PYTHONDONTWRITEBYTECODE": "1"}) - if r.returncode: - raise GuardError(f"render step failed: {' '.join(cmd[:2])}\n{r.stderr[-STDERR_TAIL:]}") - return tmp / "dings" / "out", tmp / "earcon" - - -# ---- run ----------------------------------------------------------------------------------------------------------------------- -def policy_for(family, voice, th): - if family == "dings": - return dict(ceiling_dbtp=tv(th, "ceiling_dings_dbtp"), swell=voice in pol(th, "swell_voices"), settle=voice in pol(th, "settle_before_next_voices")) - return dict(ceiling_dbtp=tv(th, "ceiling_earcon_dbtp"), swell=False, settle=False) # neutral and earcon - - -def run(clips, th): - """clips: [(id, path, family, voice, notes_ms)]. Returns {id: dict(fails=[Fail], facts)} with loudness folded in.""" - res, laes = {}, {} - for cid, path, fam, voice, notes in clips: - if path is None or not Path(path).exists(): - res[cid] = dict(fails=[Fail("present", "missing", 1, f"clip file missing ({path})")], facts={}) - continue - x, sr = read(path) - if sr != SHIPPED_RATE: - res[cid] = dict(fails=[Fail("present", "sample_rate", sr, f"sample rate {sr}, expected {SHIPPED_RATE}")], facts={}) - continue - f, facts = check_clip(x, sr, notes, policy_for(fam, voice, th), th) - facts["duration_ms"] = round(len(x) * MS_PER_S / sr, 1) - res[cid] = dict(fails=f, facts=facts) - if fam in ("dings", "neutral"): - laes[cid] = lae(x) - facts["lae_db"] = round(laes[cid], 2) - if laes: - lf, med = loudness_failures(laes, th, neutral={k for k in laes if k.startswith("dings/neutral/")}) - for k, fl in lf.items(): - res[k]["fails"].append(fl) - return res - - -def apply_known(res, th): - """Returns (failing, known_lines, stale_lines). A known failure is a (clip, assertion) with the measured value and slack recorded in thresholds.json; - it is printed on every run. If it stops failing it is stale (reported, and the run fails until the entry is removed); if its value moves by more than - slack the run fails until the entry is re-justified.""" - known = {(k["clip"], k["assertion"]): k for k in th.get("known_failures", [])} - failing, known_lines, stale, seen = {}, [], [], set() - for cid, r in res.items(): - for fl in r["fails"]: - k = known.get((cid, fl.assertion)) - if k is None: - failing.setdefault(cid, []).append(fl) - continue - seen.add((cid, fl.assertion)) - if abs(fl.value - k["value"]) > k["slack"]: - failing.setdefault(cid, []).append(Fail(fl.assertion, "known_moved", fl.value, f"known failure moved: recorded {k['value']} +-{k['slack']}, now {fl.value:g} ({fl.msg})")) - else: - known_lines.append(f"KNOWN {cid} [{fl.assertion}/{fl.kind}] {fl.msg} -- {k['reason']}") - for key, k in known.items(): - if key not in seen: - stale.append(f"STALE known failure {key[0]} [{key[1]}] no longer fails: remove it from thresholds.json known_failures") - return failing, known_lines, stale - - -def main(argv=None): - ap = argparse.ArgumentParser(description="Check every shipped Dings clip and every Earcon Workshop clip with aqua-ear. Exit 1 on any failed assertion. With no directory it renders both itself into a temp dir.") - ap.add_argument("--dings", help="out dir of tools/dings-voices (manifest.json, senders/, neutral/)") - ap.add_argument("--earcon", help="dir with one cli.mjs pack per identity (//pack.json)") - ap.add_argument("--thresholds", help="thresholds file (default: next to guard.py)") - ap.add_argument("--keep", action="store_true", help="keep the temp render dir and print it") - a = ap.parse_args(argv) - try: - th = load_thresholds(a.thresholds) - check_pins(th) - want = intended() - tmp = None - dd, ed = a.dings, a.earcon - if not dd or not ed: - tmp = tempfile.mkdtemp(prefix="sound-guard-") - print(f"rendering into {tmp} ...", flush=True) - rd, re_ = render_all(tmp) - dd, ed = dd or rd, ed or re_ - clips = dings_clips(dd, th, want) + earcon_clips(ed, want) - res = run(clips, th) - except GuardError as e: - print(f"sound-guard: error: {e}", file=sys.stderr) - return 2 - failing, known_lines, stale = apply_known(res, th) - for cid, r in res.items(): - tag = "FAIL " if cid in failing else ("known" if any(l.startswith(f"KNOWN {cid} ") for l in known_lines) else "ok ") - print(f"{tag} {cid:34s} peak {r['facts'].get('true_peak_dbtp', '?')} dBTP onsets {r['facts'].get('onsets', [])}") - for cid, fl in failing.items(): - for x in fl: - print(f"FAILED {cid} [{x.assertion}/{x.kind}] {x.msg}") - for l in known_lines + stale: - print(l) - n = len(res) - print(f"\n{n} clips, {len(failing)} failing, {len(known_lines)} known failure(s), {len(stale)} stale known failure(s)." - f" This guard measures signal facts; it cannot judge annoyance, timbre or feel.") - if a.keep and tmp: - print(f"kept {tmp}") - elif tmp: - shutil.rmtree(tmp, ignore_errors=True) - return 1 if failing or stale else 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/tools/sound-guard/test_guard.py b/tools/sound-guard/test_guard.py deleted file mode 100644 index c427513..0000000 --- a/tools/sound-guard/test_guard.py +++ /dev/null @@ -1,216 +0,0 @@ -"""Tests for sound-guard: python3 -m unittest -v test_guard (needs numpy, scipy, soundfile with Vorbis, and node for the generator). -Clips are rendered by the generator into a temp dir and mutated in memory; nothing binary is committed. Each mutant must fail the assertion named.""" -import ast, io, json, os, shutil, subprocess, sys, tempfile, unittest -from pathlib import Path -import numpy as np -import scipy.signal as ss -import soundfile as sf - -sys.path.insert(0, str(Path(__file__).resolve().parent)) -import guard as g - -TH = g.load_thresholds() -SR = 48000 -WANT = g.intended() if shutil.which("node") else None -BASE_PEAK = 10 ** (-9 / 20) # finish.py places the loudest clip at -9 dBTP -SHIPPED_LAE = -31.86 # finish.py's target exposure for the current sender set (metrics.json targetLaeDb) - - -def ms(t): return int(round(t * SR / 1000)) - - -class Fixture(unittest.TestCase): - @classmethod - def setUpClass(cls): - if not shutil.which("node"): - raise unittest.SkipTest("node missing: the generator cannot render") - cls.tmp = tempfile.mkdtemp(prefix="sound-guard-test-") - subprocess.run(["node", str(g.TOOLS / "dings-voices/src/build.mjs"), cls.tmp], check=True, capture_output=True) - cls.raw = {(s, m): sf.read(os.path.join(cls.tmp, f"{s}-{m}.wav"))[0] for s in g.SENDERS for m in g.MOTIFS} - - @classmethod - def tearDownClass(cls): - shutil.rmtree(cls.tmp, ignore_errors=True) - - def clip(self, s, m, peak=None): - """A raw clip at the level finish.py gives it (every clip at one A-weighted exposure), or at an explicit peak.""" - x = self.raw[(s, m)].astype(np.float64) - return x * peak / np.max(np.abs(x)) if peak else x * 10 ** ((SHIPPED_LAE - g.lae(x)) / 20) - - @staticmethod - def ogg(x): - b = io.BytesIO(); sf.write(b, x.astype(np.float32), SR, format="OGG", subtype="VORBIS"); b.seek(0) - return sf.read(b, dtype="float64")[0] - - def check(self, x, voice, motif, family="dings"): - notes = WANT["dings"][motif] if family == "dings" else WANT["earcon"][motif] - return g.check_clip(x, SR, notes, g.policy_for(family, voice, TH), TH)[0] - - def kinds(self, fails): return sorted({(f.assertion, f.kind) for f in fails}) - - def assertFails(self, fails, assertion, kind=None): - got = self.kinds(fails) - self.assertTrue(any(a == assertion and (kind is None or k == kind) for a, k in got), f"expected {assertion}/{kind}, got {got}") - - -class Baselines(Fixture): - def test_unmutated_clips_pass(self): - for s, m in [("void", "dm"), ("void", "invite"), ("void", "mention"), ("libby", "dm"), ("kiko", "invite"), ("weksa", "message"), ("nibu", "invite"), ("heimdall", "dm")]: - for x in (self.clip(s, m), self.ogg(self.clip(s, m))): - self.assertEqual(self.check(x, s, m), [], f"{s}/{m}") - - -def knock(n, at_ms, rel_db, tone_peak, seed=7): - """The v3 Void 'soft knock': noise through a broad band-pass around 1.8 kHz, 4 ms attack, 6 ms decay, 24 ms long (voices.mjs v3 noiseBurst). - v3 level: 36.6 dB under the tone's peak (measured by differencing the v3 and v4 renders).""" - r = np.random.default_rng(seed).uniform(-1, 1, ms(24)) - y = ss.sosfilt(ss.butter(2, [1000, 2800], "bandpass", fs=SR, output="sos"), r) - k = np.arange(len(y)); y *= np.minimum(1, (k + 1) / ms(4)) * np.exp(-k / SR / 0.006) - y *= tone_peak * 10 ** ((-36.6 + rel_db) / 20) / np.max(np.abs(y)) - out = np.zeros(n); i = ms(at_ms); out[i:i + len(y)] = y[:n - i] - return out - - -class Mutants(Fixture): - def test_a_v3_knock_at_three_levels(self): - for m in ("dm", "mention"): - base = self.clip("void", m) - at = 95 if m == "dm" else 190 - for rel in (0, -12, -20): # -22 is caught only on the loudest clip: see README - x = self.ogg(base + knock(len(base), at, rel, np.max(np.abs(base)))) - with self.subTest(motif=m, rel_db=rel): - self.assertFails(self.check(x, "void", m), "onsets", "stray_hf") - - def test_b_clipped_tail(self): - base = self.clip("void", "dm") - x = base.copy(); i = ms(300) - x[i:] = np.clip(x[i:] * 40, -1, 1) # last stretch driven into full scale - self.assertFails(self.check(x, "void", "dm"), "clipping", "clip") # exact plateaus in a WAV - self.assertFails(self.check(self.ogg(x), "void", "dm"), "true_peak") # after Vorbis the plateau is overs / true peak, not equal samples - self.assertFails(self.check(self.ogg(x), "void", "dm"), "clipping", "clip") - - def test_b2_limited_plateau_below_full_scale(self): - x = np.clip(self.clip("void", "mention"), -0.6 * BASE_PEAK, 0.6 * BASE_PEAK) # a limiter flat-top, nowhere near 0.99 - self.assertFails(self.check(x, "void", "mention"), "clipping", "flat_top") - - def test_c_click_and_step(self): - base = self.clip("void", "dm") - click = base.copy(); click[ms(150)] += 0.2 - self.assertFails(self.check(click, "void", "dm"), "click_step_dc") - self.assertFails(self.check(self.ogg(click), "void", "dm"), "click_step_dc") - step = base.copy(); step[ms(150):] += 0.03 - self.assertFails(self.check(step, "void", "dm"), "click_step_dc") - self.assertFails(self.check(self.ogg(step), "void", "dm"), "click_step_dc") - - def test_d_abrupt_cut(self): - base = self.clip("void", "mention") - cut = base[:ms(150)] - self.assertFails(self.check(cut, "void", "mention"), "tail_end", "abrupt_end") - self.assertFails(self.check(self.ogg(cut), "void", "mention"), "tail_end", "abrupt_end") - - def test_e_dc_offset(self): - base = self.clip("void", "dm") + 0.01 - self.assertFails(self.check(base, "void", "dm"), "click_step_dc", "dc") - self.assertFails(self.check(self.ogg(base), "void", "dm"), "click_step_dc", "dc") - - def test_f_loudness_outlier(self): - laes = {f"dings/{s}/{m}": g.lae(self.raw[(s, m)]) for s in g.SENDERS for m in g.MOTIFS} - target = float(np.median(list(laes.values()))) - eq = {} # finish.py equalisation, without the encode - for k, v in laes.items(): eq[k] = target - self.assertEqual(g.loudness_failures(eq, TH)[0], {}) - for db, expect in ((3.0, True), (1.0, True), (0.3, False)): - m = dict(eq); m["dings/void/dm"] = target + db - got = g.loudness_failures(m, TH)[0] - self.assertEqual(list(got), ["dings/void/dm"] if expect else [], f"+{db} dB") - m = dict(eq); m["dings/void/dm"] = target - 3.0 # and a quiet outlier - self.assertEqual(list(g.loudness_failures(m, TH)[0]), ["dings/void/dm"]) - - def test_g_second_hit_in_and_out_of_window(self): - base = self.clip("void", "mention") - self.assertEqual(self.check(self.ogg(base), "void", "mention"), []) - def echo(shift): - x = np.concatenate([base, np.zeros(ms(shift))]); x[ms(shift):] += base - return self.ogg(x) - self.assertFails(self.check(echo(15), "void", "mention"), "onsets", "double") # a flam inside the note window - self.assertFails(self.check(echo(45), "void", "mention"), "onsets", "stray") # a second hit outside it - - def test_h_missing_note_and_late_note(self): - base = self.clip("libby", "dm") - gone = base.copy(); gone[ms(200):] = 0 - self.assertFails(self.check(self.ogg(gone), "libby", "dm"), "onsets", "missing") - late = np.concatenate([base[:ms(200)], np.zeros(ms(12)), base[ms(200):]]) - self.assertFails(self.check(self.ogg(late), "libby", "dm"), "onsets", "timing") - - def test_i_tail_rings_over_next_note(self): - a = self.clip("libby", "mention") - x = a.copy(); x[ms(240):] += a[:len(a) - ms(240)] - self.assertFails(self.check(self.ogg(x), "libby", "dm"), "tail_overlap") - # a ring-over voice (Aqua) is allowed to do it - self.assertNotIn("tail_overlap", [f.assertion for f in self.check(self.ogg(x), "aqua", "dm")]) - - def test_j_true_peak_ceiling(self): - hot = self.clip("void", "mention", peak=10 ** (-3 / 20)) - self.assertFails(self.check(hot, "void", "mention"), "true_peak") - - def test_k_earcon_ceiling_is_its_own(self): - x = self.clip("void", "mention", peak=10 ** (-1.5 / 20)) # over -2.5 dBTP, under the Dings -1 convention - f = g.check_clip(x, SR, [0], g.policy_for("earcon", "warm-bell", TH), TH)[0] - self.assertFails(f, "true_peak") - ok = g.check_clip(self.clip("void", "mention", peak=10 ** (-3.2 / 20)), SR, [0], g.policy_for("earcon", "warm-bell", TH), TH)[0] - self.assertNotIn("true_peak", [i.assertion for i in ok]) - - -class Contract(unittest.TestCase): - def leaves(self, d, path=()): - if isinstance(d, dict) and "value" in d: - yield path, d - elif isinstance(d, dict): - for k, v in d.items(): - if isinstance(v, dict): yield from self.leaves(v, path + (k,)) - - def test_every_threshold_has_a_reason(self): - found = list(self.leaves(TH["thresholds"])) + list(self.leaves(TH["voice_policy"])) + list(self.leaves(TH["aqua_ear_pins"])) - self.assertGreaterEqual(len(found), 20) - for path, leaf in found: - self.assertTrue(isinstance(leaf.get("why"), str) and len(leaf["why"].split()) >= 8, f"{path} needs a real `why`") - - def test_every_threshold_the_code_reads_is_in_the_file(self): - src = (Path(g.__file__)).read_text() - names = set(__import__("re").findall(r'\b(?:tv|pol)\(th, "([a-z_]+)"\)', src)) - have = set(TH["thresholds"]) | set(TH["voice_policy"]) - self.assertEqual(names - have, set()) - self.assertEqual({n for n in TH["thresholds"]} - names, set(), "a threshold nothing reads") - - def test_aqua_ear_pins_hold_and_a_moved_pin_is_refused(self): - g.check_pins(TH) - bad = json.loads(json.dumps(TH)); bad["aqua_ear_pins"]["dc_abs"]["value"] = 0.05 - with self.assertRaises(g.GuardError): g.check_pins(bad) - - def test_known_failures_are_complete_and_stale_ones_are_loud(self): - for k in TH["known_failures"]: - self.assertTrue({"clip", "assertion", "value", "slack", "reason", "measured"} <= set(k), k) - self.assertGreaterEqual(len(k["reason"].split()), 8) - fake = {"known_failures": [{"clip": "c", "assertion": "loudness", "value": 5.0, "slack": 0.1, "reason": "r", "measured": "m"}]} - passing = {"c": dict(fails=[], facts={})} - failing, known, stale = g.apply_known(passing, fake) - self.assertEqual((failing, known, len(stale)), ({}, [], 1)) # started passing: reported - moved = {"c": dict(fails=[g.Fail("loudness", "outlier", 9.0, "x")], facts={})} - self.assertIn("c", g.apply_known(moved, fake)[0]) # got worse: fails until re-justified - same = {"c": dict(fails=[g.Fail("loudness", "outlier", 5.05, "x")], facts={})} - self.assertEqual(g.apply_known(same, fake)[0], {}) # still as recorded: printed, not failing - - def test_guard_source_has_no_magic_numbers(self): - """Numeric literals other than 0, 1, 2 may only be module constants (UPPER_CASE = ...). Everything else is read from thresholds.json.""" - tree = ast.parse(Path(g.__file__).read_text()) - allowed = set() - for n in tree.body: - if isinstance(n, ast.Assign) and all(isinstance(t, ast.Name) and t.id.isupper() for t in n.targets): - allowed |= {id(c) for c in ast.walk(n.value)} - bad = [(c.value, c.lineno) for c in ast.walk(tree) if isinstance(c, ast.Constant) and isinstance(c.value, (int, float)) and not isinstance(c.value, bool) - and c.value not in (0, 1, 2) and id(c) not in allowed] - self.assertEqual(bad, []) - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/sound-guard/thresholds.json b/tools/sound-guard/thresholds.json deleted file mode 100644 index 56c6f28..0000000 --- a/tools/sound-guard/thresholds.json +++ /dev/null @@ -1,148 +0,0 @@ -{ - "format": "aquasynth.sound-guard-thresholds.v1", - "about": "Every number the guard compares against lives in this file and nowhere else (guard.py has none). Each entry has a `why`. test_guard.py fails if one lacks it. Detector boundaries that belong to tools/aqua-ear are pinned, not copied: see aqua_ear_pins.", - "thresholds": { - "pad_ms": { - "value": 20, - "why": "Digital silence prepended before onset analysis. aqua-ear cannot see an onset that is already at full level at sample 0 (Kiko, Void, Aqua, Weksa start inside the first millisecond: their first note was missing from aqua-ear's own onset list). The pad also makes a clip that starts on a non-zero sample a step the click detector sees. Padding is not used for DC or the end checks." - }, - "hold_ms": { - "value": 10, - "why": "Peak-hold applied to aqua-ear's 1 ms envelope before the onset detector (rising edges are untouched, only valleys are filled). A low harmonic tone's envelope ripples at its fundamental and aqua-ear reads each ripple as an onset (Heimdall's 196 Hz horn gave 50 to 90 'onsets' per clip; Earcon Workshop warm-bell 20 to 75). 10 ms is one period of 100 Hz, below every fundamental in the shipped sets (lowest: Heimdall 196 Hz, Earcon fail -4 semitones from 262 Hz)." - }, - "window_pre_ms": { - "value": 20, - "why": "An onset up to this many ms before an intended note start belongs to that note. Measured on the decoded shipped clips: Vorbis pre-echo puts rises 12 to 15 ms ahead of an attack (Aqua message 215 ms for a note at 230, 15 ms early; Aqua dm 228 for 240, 12 early) at -14 to -30 dB re the attack; there is nothing else in a clip that early." - }, - "window_post_ms": { - "value": 20, - "why": "An onset up to this many ms after an intended note start belongs to that note. Measured: first-hit attacks land 0 to 5 ms late and high-band onsets from the attack (Aqua glide, Nibu 8 kHz grain, Void 9 ms attack) land up to +14 ms (Aqua invite 214 for 200). Must stay well below 95 ms, where the v3 Void knock sat, and below the 70 ms spacing of the Earcon message pair (pre 20 + post 20 = 40 ms, no windows overlap)." - }, - "main_timing_ms": { - "value": 8, - "why": "The loudest onset in a note's window must start within this many ms of the intended time. Measured worst offset of a main onset over all strict clips is 5 ms (Void dm second note, 235 for 240); Earcon first notes are 1 to 3 ms early. 8 leaves 3 ms margin; a note 10 ms off is a timing bug." - }, - "precursor_db": { - "value": 10, - "why": "An onset that starts before the main onset of its note (pre-echo, a rise lead-in) is not a second hit if its peak is at least this far under the main onset's peak. Measured pre-echo is 13.7 to 27 dB under (Aqua invite 195 ms: 13.7 dB under). aqua-ear's own 'comparable' limit is 20 dB, which would call Vorbis pre-echo a double hit; 10 dB is lower than any measured pre-echo and still lets any equal-level second hit fail. An onset AFTER the main onset inside the window has no such allowance and always fails on the full-band channel." - }, - "hf_floor_dbfs": { - "value": -80.0, - "why": "High-band (above 2 kHz) onset floor, absolute; aqua-ear uses -75. The detector needs a 4 dB rise above its trough, which is clamped at this floor, so a high-band onset is only seen when it peaks above floor + 4 dB = -76 dBFS. The v3 Void knock measured -53 dBFS in this band at a -9 dBFS clip. Measured on synthetic copies of the v4 Void clips: caught down to a knock 20 dB below the v3 level on all three motifs tried, 22 dB below on the loudest only. -80 is as low as the shipped set allows: at -84 Aqua mention (hf -79 dBFS at 30 ms, glide leakage) and Heimdall (hf rises at -76 under its swell) show strays, so a lower floor would make the guard red on clips nobody can hear differ." - }, - "ceiling_dings_dbtp": { - "value": -8.0, - "why": "True-peak ceiling for the 32 sender clips, measured on the decoded Ogg. finish.py equalises exposure and places the loudest clip at -9.0 dBTP (-8.94 measured after the encode), so no clip should exceed that; -8.0 leaves 1 dB for encoder variation and still fails a spiky clip (a knock or a click raises peak at constant exposure). The delivery convention of -1 dBTP (verify.py) would let a clip 7 dB hotter than designed through." - }, - "ceiling_earcon_dbtp": { - "value": -2.5, - "why": "True-peak ceiling for Earcon Workshop clips and the neutral fallbacks (which are Earcon Workshop warm-bell renders). The default render sets level 0.7 = -3.1 dBFS; measured true peak is -3.09 to -2.66 dBTP over all 24 earcons and 4 neutral clips (the neutral invite is -2.66). -2.5 keeps 0.16 dB margin over the worst, and stays 1.5 dB inside the -1 dBTP delivery convention." - }, - "flat_top_rel": { - "value": 0.98, - "why": "Flat-top (limiter or hard clip) detector for exact sample plateaus: a run of aqua-ear's clip_run equal samples at or above this fraction of the clip's OWN peak. aqua-ear only calls plateaus at >= 0.99 of full scale clipped, and a -9 dBFS clip clipped at -9 dBFS slips past it. Only WAV can show this (a Vorbis decode smooths plateaus away), so on decoded Ogg this check is blind: see README." - }, - "flat_top_eps": { - "value": 1e-06, - "why": "Two samples are 'equal' for the flat-top detector when they differ by less than this (aqua-ear's own equality test in clipping_true_peak)." - }, - "loudness_dev_db": { - "value": 0.5, - "why": "Every sender clip's A-weighted exposure (LAE, metriclib.lae on the decoded file, the quantity finish.py equalises) must lie within this many dB of the median of the 32 shipped sender clips. Measured after the Vorbis encode: spread 0.36 dB, largest deviation from the median 0.33 dB (Aqua invite). 0.5 dB is also the limit tools/dings-voices/src/verify.py already enforces on spread, and is under the ~1 dB a listener notices as a level difference between two tones. Neutral fallbacks are held to the same band against the same median (see known_failures)." - } - }, - "voice_policy": { - "swell_voices": { - "value": [ - "eureka", - "heimdall" - ], - "why": "Voices whose attack is a slow swell by design (voices.mjs: Eureka 70 ms raised-cosine attack, Heimdall a swell over 45% of a 300 ms note). aqua-ear's rise detector turns a swell into a staircase of 'onsets' (Heimdall: 5 to 7 onsets inside one swell) and sees no onset at all when a legato note changes pitch under a held tone (Heimdall invite shows only note 1; Eureka invite shows notes 1 and 2, the second 21 ms late). For these voices the full-band onset count is NOT asserted; the high band still is (a knock or tick is plain there and these voices have no energy above 2 kHz)." - }, - "settle_before_next_voices": { - "value": [ - "kiko", - "libby", - "void", - "nibu" - ], - "why": "Voices whose notes are built to end by the next onset (voices.mjs v4: Kiko and Libby 'a note something follows is shortened to settle before the next one lands'; Void ends by the next onset; Nibu heldLen). For these the previous tail must be below aqua-ear's overlapping_tails limit at each following note. Aqua, Eureka, Heimdall and Weksa notes ring over the next note by design (their length is the motif cap, not the gap) and Earcon Workshop identities decay 0.25 to 0.55 s over note gaps of 70 to 450 ms by design, so overlap is not asserted for them." - }, - "neutral_events": { - "value": { - "mention": "success", - "dm": "waiting", - "message": "message", - "invite": "done" - }, - "why": "The neutral fallback clips carry no machine-readable intent. They are the Earcon Workshop warm-bell renders: durations (770, 1450, 455, 1170 ms) and onset lists equal warm-bell success, waiting, message and done. Note times for the onset check come from that mapping. This is inferred from the audio, not recorded anywhere." - } - }, - "aqua_ear_pins": { - "dc_abs": { - "value": 0.005, - "why": "DC limit in aqua-ear's click_step_dc (-46 dBFS). The guard uses aqua-ear's detector; pinned so a loosening in aqua_ear.py fails the guard instead of silently loosening it." - }, - "step_abs": { - "value": 0.02, - "why": "Minimum second difference for a click or step in aqua-ear's click_step_dc." - }, - "step_ratio": { - "value": 25.0, - "why": "Discontinuity must be this many times its local mean second difference." - }, - "clip_run": { - "value": 3, - "why": "Equal samples at the ceiling that make a clipped plateau." - }, - "clip_level": { - "value": 0.99, - "why": "A plateau counts as clipping at or above this fraction of full scale." - }, - "tp_limit_dbtp": { - "value": 0.0, - "why": "aqua-ear flags a true peak above 0 dBTP (an inter-sample over); the guard's own ceilings are tighter." - }, - "end_decay_db": { - "value": 6.0, - "why": "abrupt_end: the last 3 ms must have fallen this far since 9 ms earlier or it counts as cut." - }, - "end_tail_db": { - "value": -40.0, - "why": "abrupt_end: last 3 ms louder than this re the file peak counts as a cut candidate." - }, - "end_abs_dbfs": { - "value": -70.0, - "why": "abrupt_end: and the last 3 ms must also be louder than this absolute level, so digital silence at the end is never a cut." - }, - "overlap_gap_ms": { - "value": 80.0, - "why": "overlapping_tails: onsets at least this far apart are separate notes." - }, - "overlap_tail_db": { - "value": -40.0, - "why": "overlapping_tails: the previous note's tail must be below this re its peak at the next onset." - }, - "onset_rise_db": { - "value": 4.0, - "why": "Onset detector: rise above the recent trough that counts as an onset." - }, - "trough_window_ms": { - "value": 20, - "why": "Onset detector: how far back the trough is looked for." - }, - "floor_dbfs": { - "value": -60.0, - "why": "Onset detector: absolute floor of the full-band channel." - }, - "rel_floor_db": { - "value": -45.0, - "why": "Onset detector: floor relative to the clip's (held) peak, so a quiet tail wobble far under the note is not an onset." - }, - "hf_cut_hz": { - "value": 2000.0, - "why": "High-band channel cut-off; the v3 Void knock was visible only above this." - } - }, - "known_failures": [] -} diff --git a/tools/vocal-tract-playground/README.md b/tools/vocal-tract-playground/README.md deleted file mode 100644 index c03a8c0..0000000 --- a/tools/vocal-tract-playground/README.md +++ /dev/null @@ -1,27 +0,0 @@ -# AquaSynth Tract Voice Playground - -Touchable audition playground for the Aqua DSL `tract` voice surface. - -Run it from this directory: - -```powershell -node .\serve.mjs -``` - -Then open: - -```text -http://localhost:5125/ -``` - -This is an actual-machine audition surface. The browser sends the visible -controls to `tools/TractGraphRenderer`, which emits an Aqua DSL patch with -`tract propagation=graph`, lowers it through the normal Faust emitter, renders -the compiled DSP, and returns a WAV for playback. - -That makes rendering slower than a browser-native oscillator, but it removes -the fake witness from the feedback loop. The sound you hear is the Aqua DSL -> -Faust graph path that the compiler owns. - -Faust must be available through `PATH` or `FAUST_HOME`, and the .NET SDK must be -available to run the renderer. diff --git a/tools/vocal-tract-playground/app.js b/tools/vocal-tract-playground/app.js deleted file mode 100644 index 95dbfdd..0000000 --- a/tools/vocal-tract-playground/app.js +++ /dev/null @@ -1,403 +0,0 @@ -"use strict"; - -const controlSpecs = [ - ["Frequency", "frequency", "source", 140, 60, 420, "Hz"], - ["Intensity", "intensity", "source", 0.72, 0, 1, ""], - ["Tenseness", "tenseness", "source", 0.60, 0, 1, ""], - ["Tongue index", "tongueIndex", "tract", 12.9, 8, 34, "cell"], - ["Tongue diameter", "tongueDiameter", "tract", 2.43, 0.45, 3.6, "diam"], - ["Velum", "velum", "tract", 0.01, 0.01, 0.4, "diam"], - ["Constriction index", "constrictionIndex", "tract", 32, 2, 43, "cell"], - ["Constriction diameter", "constrictionDiameter", "tract", 1.0, -0.7, 3.4, "diam"], - ["Turbulence", "turbulence", "source", 0.18, 0, 1, ""], - ["Burst", "burst", "source", 0.25, 0, 1, ""], - ["Lip opening", "lipOpening", "tract", 1.5, 0.35, 2.5, "diam"], - ["Glottal reflection", "glottalReflection", "spectral", 0.75, -0.95, 0.95, ""], - ["Lip reflection", "lipReflection", "spectral", -0.85, -0.98, 0.1, ""], - ["Gain", "gain", "source", 0.7, 0, 1, ""] -]; - -const presets = { - open: { - frequency: 140, intensity: 0.72, tenseness: 0.58, tongueIndex: 13, - tongueDiameter: 2.7, velum: 0.01, constrictionIndex: 32, - constrictionDiameter: 1.4, turbulence: 0.08, lipOpening: 1.7, - burst: 0.25, glottalReflection: 0.75, lipReflection: -0.85, gain: 0.72 - }, - ee: { - frequency: 165, intensity: 0.68, tenseness: 0.72, tongueIndex: 27, - tongueDiameter: 1.05, velum: 0.01, constrictionIndex: 34, - constrictionDiameter: 1.2, turbulence: 0.04, lipOpening: 1.1, - burst: 0.25, glottalReflection: 0.75, lipReflection: -0.85, gain: 0.68 - }, - oo: { - frequency: 128, intensity: 0.72, tenseness: 0.55, tongueIndex: 12, - tongueDiameter: 2.9, velum: 0.01, constrictionIndex: 38, - constrictionDiameter: 1.5, turbulence: 0.03, lipOpening: 0.55, - burst: 0.25, glottalReflection: 0.75, lipReflection: -0.9, gain: 0.74 - }, - ss: { - frequency: 130, intensity: 0.48, tenseness: 0.22, tongueIndex: 28, - tongueDiameter: 0.75, velum: 0.01, constrictionIndex: 34, - constrictionDiameter: 0.35, turbulence: 0.95, lipOpening: 1.2, - burst: 0.25, glottalReflection: 0.65, lipReflection: -0.82, gain: 0.78 - }, - ma: { - frequency: 132, intensity: 0.66, tenseness: 0.52, tongueIndex: 14, - tongueDiameter: 2.2, velum: 0.33, constrictionIndex: 18, - constrictionDiameter: 0.8, turbulence: 0.12, lipOpening: 1.35, - burst: 0.25, glottalReflection: 0.78, lipReflection: -0.84, gain: 0.72 - } -}; - -const state = Object.fromEntries(controlSpecs.map(([, id, , value]) => [id, value])); -const controls = new Map(); -let audio = null; -let renderAbort = null; -let animationFrame = 0; -let phase = 0; - -const canvas = document.getElementById("tractCanvas"); -const ctx = canvas.getContext("2d"); -const controlsRoot = document.getElementById("controls"); -const playButton = document.getElementById("playButton"); -const panicButton = document.getElementById("panicButton"); -const renderStatus = document.getElementById("renderStatus"); -const pressureMeter = document.getElementById("pressureMeter"); -const noiseMeter = document.getElementById("noiseMeter"); -const nasalMeter = document.getElementById("nasalMeter"); - -function makeControls() { - for (const [label, id, family, value, min, max, unit] of controlSpecs) { - const row = document.createElement("div"); - row.className = "control"; - row.dataset.family = family; - - const labelEl = document.createElement("label"); - labelEl.htmlFor = id; - labelEl.textContent = label; - - const valueEl = document.createElement("output"); - valueEl.className = "value"; - valueEl.htmlFor = id; - - const input = document.createElement("input"); - input.id = id; - input.type = "range"; - input.min = min.toString(); - input.max = max.toString(); - input.step = max - min > 20 ? "0.01" : "0.001"; - input.value = value.toString(); - - input.addEventListener("input", () => { - state[id] = Number(input.value); - valueEl.value = formatValue(id, state[id], unit); - updateAudio(); - }); - - row.append(labelEl, valueEl, input); - controlsRoot.append(row); - controls.set(id, { input, valueEl, unit }); - } - - syncControls(); -} - -function formatValue(id, value, unit) { - const digits = id.includes("Index") || id === "frequency" ? 1 : 3; - return `${value.toFixed(digits)}${unit ? ` ${unit}` : ""}`; -} - -function syncControls() { - for (const [id, pair] of controls) { - pair.input.value = state[id].toString(); - pair.valueEl.value = formatValue(id, state[id], pair.unit); - } - updateMeters(); - updateAudio(); - draw(); -} - -function applyPreset(name) { - Object.assign(state, presets[name]); - syncControls(); -} - -async function startAudio() { - if (audio) return; - - playButton.disabled = true; - playButton.textContent = "Rendering..."; - setStatus("Rendering Aqua DSL graph through Faust..."); - const context = new AudioContext(); - const master = context.createGain(); - master.gain.value = state.gain; - master.connect(context.destination); - - try { - const { buffer, summary } = await renderCurrentPatch(context); - const source = context.createBufferSource(); - source.buffer = buffer; - source.connect(master); - source.onended = () => { - if (audio?.source === source) { - void stopAudio(); - } - }; - audio = { context, master, source }; - source.start(); - updateAudio(); - setStatus(`Rendered ${summary.samples} samples, peak ${summary.peak.toFixed(3)}, rms ${summary.rms.toFixed(3)}`); - playButton.textContent = "Stop"; - playButton.setAttribute("aria-pressed", "true"); - } catch (error) { - await context.close(); - setStatus(error.message); - playButton.textContent = "Render"; - playButton.setAttribute("aria-pressed", "false"); - } finally { - playButton.disabled = false; - } -} - -async function stopAudio() { - const old = audio; - audio = null; - renderAbort?.abort(); - renderAbort = null; - if (old) { - old.master.gain.setTargetAtTime(0, old.context.currentTime, 0.02); - try { - old.source.stop(); - } catch { - // The source may already have ended. - } - await new Promise(resolve => setTimeout(resolve, 80)); - await old.context.close(); - } - playButton.textContent = "Render"; - playButton.setAttribute("aria-pressed", "false"); - playButton.disabled = false; -} - -function updateAudio() { - updateMeters(); - if (!audio) return; - - audio.master.gain.setTargetAtTime(state.gain, audio.context.currentTime, 0.03); -} - -async function renderCurrentPatch(context) { - renderAbort = new AbortController(); - const response = await fetch("/render", { - method: "POST", - headers: { "content-type": "application/json" }, - body: JSON.stringify({ - ...state, - durationSeconds: 0.72, - sampleRate: Math.round(context.sampleRate) - }), - signal: renderAbort.signal - }); - renderAbort = null; - - const summary = await response.json(); - if (!response.ok) { - throw new Error(summary.error ?? "Graph render failed"); - } - - const wav = await fetch(summary.audioUrl, { cache: "no-store" }); - if (!wav.ok) { - throw new Error(`Rendered WAV was not available: HTTP ${wav.status}`); - } - - return { - summary, - buffer: await context.decodeAudioData(await wav.arrayBuffer()) - }; -} - -function setStatus(message) { - if (renderStatus) renderStatus.textContent = message; -} - -function updateMeters() { - pressureMeter.value = state.intensity; - noiseMeter.value = state.turbulence; - nasalMeter.value = (state.velum - 0.01) / 0.39; -} - -function draw() { - const width = canvas.width; - const height = canvas.height; - ctx.clearRect(0, 0, width, height); - ctx.fillStyle = "#111714"; - ctx.fillRect(0, 0, width, height); - - const cx = width * 0.5; - const cy = height * 0.54; - phase += 0.018 + state.intensity * 0.02; - - drawGrid(width, height); - drawTract(cx, cy, width * 0.76, height * 0.42); - drawReadout(width, height); - - animationFrame = requestAnimationFrame(draw); -} - -function drawGrid(width, height) { - ctx.strokeStyle = "rgba(168, 179, 163, 0.11)"; - ctx.lineWidth = 1; - for (let x = 70; x < width; x += 70) { - ctx.beginPath(); - ctx.moveTo(x, 0); - ctx.lineTo(x, height); - ctx.stroke(); - } - for (let y = 60; y < height; y += 60) { - ctx.beginPath(); - ctx.moveTo(0, y); - ctx.lineTo(width, y); - ctx.stroke(); - } -} - -function drawTract(cx, cy, length, scale) { - const pointsTop = []; - const pointsBottom = []; - const samples = 72; - for (let i = 0; i <= samples; i++) { - const cell = i / samples * 44; - const u = i / samples; - const x = cx - length / 2 + u * length; - let diameter = cell < 7 ? 0.6 : cell < 10 ? 1.1 : 1.5; - if (cell > 10 && cell < 39) { - const angle = 1.1 * Math.PI * (state.tongueIndex - cell) / 22; - const fixedTongueDiameter = 2 + (state.tongueDiameter - 2) / 1.5; - diameter = 1.5 - (1.5 - fixedTongueDiameter + 1.7) * Math.cos(angle); - } - const distance = Math.abs(cell - state.constrictionIndex); - const range = state.constrictionIndex < 25 ? 10 : 5; - if (distance < range) { - const narrowed = Math.max(0, state.constrictionDiameter - 0.3); - const mix = 0.5 * (1 + Math.cos(Math.PI * distance / range)); - diameter = Math.min(diameter, diameter * (1 - mix) + narrowed * mix); - } - if (i === samples) diameter = state.lipOpening; - const radius = Math.max(0.04, diameter / 3.2); - pointsTop.push([x, cy - radius * scale * 0.5]); - pointsBottom.push([x, cy + radius * scale * 0.5]); - } - - const grad = ctx.createLinearGradient(cx - length / 2, cy, cx + length / 2, cy); - grad.addColorStop(0, "#f47f67"); - grad.addColorStop(0.46, "#f2b84b"); - grad.addColorStop(1, "#7fd18b"); - - ctx.beginPath(); - for (let i = 0; i < pointsTop.length; i++) { - const [x, y] = pointsTop[i]; - if (i === 0) ctx.moveTo(x, y); - else ctx.lineTo(x, y); - } - for (let i = pointsBottom.length - 1; i >= 0; i--) { - const [x, y] = pointsBottom[i]; - ctx.lineTo(x, y); - } - ctx.closePath(); - ctx.fillStyle = "rgba(127, 209, 139, 0.17)"; - ctx.fill(); - ctx.strokeStyle = grad; - ctx.lineWidth = 4; - ctx.stroke(); - - drawSource(cx - length * 0.52, cy, scale); - drawLips(cx + length * 0.52, cy, scale); - drawNasalBranch(cx + length * 0.20, cy, scale, state.velum); - drawConstriction(cx - length / 2 + (state.constrictionIndex / 44) * length, cy, scale); - drawWave(cx, cy, length, scale); -} - -function drawSource(x, y, scale) { - const height = scale * (0.20 + state.tenseness * 0.26); - ctx.fillStyle = "#f47f67"; - ctx.fillRect(x - 18, y - height / 2, 10, height); - ctx.fillRect(x + 8, y - height / 2, 10, height); - ctx.fillStyle = "rgba(244, 127, 103, 0.25)"; - ctx.beginPath(); - ctx.arc(x, y, 24 + state.intensity * 28, 0, Math.PI * 2); - ctx.fill(); -} - -function drawLips(x, y, scale) { - const aperture = 8 + state.lipOpening * 24; - ctx.strokeStyle = "#7fd18b"; - ctx.lineWidth = 5; - ctx.beginPath(); - ctx.ellipse(x, y, 28, aperture, 0, 0, Math.PI * 2); - ctx.stroke(); -} - -function drawNasalBranch(x, y, scale, velum) { - const open = (velum - 0.01) / 0.39; - ctx.strokeStyle = `rgba(118, 199, 212, ${0.18 + open * 0.78})`; - ctx.lineWidth = 5 + open * 14; - ctx.beginPath(); - ctx.moveTo(x, y - scale * 0.16); - ctx.bezierCurveTo(x + scale * 0.12, y - scale * 0.55, x + scale * 0.40, y - scale * 0.62, x + scale * 0.60, y - scale * 0.38); - ctx.stroke(); -} - -function drawConstriction(x, y, scale) { - const close = Math.max(0, Math.min(1, (1.2 - state.constrictionDiameter) / 1.2)); - ctx.strokeStyle = `rgba(242, 184, 75, ${0.25 + close * 0.7})`; - ctx.lineWidth = 3 + close * 9; - ctx.beginPath(); - ctx.moveTo(x, y - scale * 0.28); - ctx.lineTo(x, y + scale * 0.28); - ctx.stroke(); -} - -function drawWave(cx, cy, length, scale) { - ctx.strokeStyle = "rgba(240, 244, 237, 0.45)"; - ctx.lineWidth = 2; - ctx.beginPath(); - for (let i = 0; i <= 160; i++) { - const u = i / 160; - const x = cx - length / 2 + u * length; - const amp = (0.10 + state.intensity * 0.22) * scale * (1 - state.turbulence * 0.25); - const y = cy + Math.sin(u * 18 + phase) * amp * Math.sin(Math.PI * u); - if (i === 0) ctx.moveTo(x, y); - else ctx.lineTo(x, y); - } - ctx.stroke(); -} - -function drawReadout(width, height) { - ctx.fillStyle = "#f0f4ed"; - ctx.font = "700 22px system-ui, sans-serif"; - ctx.fillText(`Aqua graph render freq=${state.frequency.toFixed(1)}Hz tense=${state.tenseness.toFixed(2)} velum=${state.velum.toFixed(2)} burst=${state.burst.toFixed(2)}`, 28, 42); - ctx.fillStyle = "#a8b3a3"; - ctx.font = "15px system-ui, sans-serif"; - ctx.fillText("Render-on-demand through Aqua DSL -> Faust graph lowering", 28, height - 24); -} - -document.querySelectorAll("[data-preset]").forEach(button => { - button.addEventListener("click", () => applyPreset(button.dataset.preset)); -}); - -playButton.addEventListener("click", async () => { - if (audio) await stopAudio(); - else await startAudio(); -}); - -panicButton.addEventListener("click", stopAudio); - -makeControls(); -cancelAnimationFrame(animationFrame); -draw(); - -window.AquaTractPlayground = { - state, - presets -}; diff --git a/tools/vocal-tract-playground/index.html b/tools/vocal-tract-playground/index.html deleted file mode 100644 index 649572d..0000000 --- a/tools/vocal-tract-playground/index.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - AquaSynth Tract Voice Playground - - - -
-
-
-
-

AquaSynth lab

-

Tract Voice Playground

-
-
- - -
-
- -
- -
- - - -
-

Ready to render the Aqua DSL graph.

-
-
- - -
- - - - diff --git a/tools/vocal-tract-playground/serve.mjs b/tools/vocal-tract-playground/serve.mjs deleted file mode 100644 index 16613b4..0000000 --- a/tools/vocal-tract-playground/serve.mjs +++ /dev/null @@ -1,135 +0,0 @@ -import { createReadStream, existsSync, mkdirSync, statSync } from "node:fs"; -import { createServer } from "node:http"; -import { spawn } from "node:child_process"; -import { basename, extname, join, normalize, resolve, sep } from "node:path"; - -const root = resolve(import.meta.dirname); -const repoRoot = resolve(root, "..", ".."); -const renderRoot = resolve(repoRoot, "artifacts", "vocal-tract-playground"); -const rendererProject = resolve(repoRoot, "tools", "TractGraphRenderer", "TractGraphRenderer.csproj"); -const port = Number.parseInt(process.env.PORT ?? "5125", 10); -const host = process.env.HOST ?? "127.0.0.1"; - -const types = new Map([ - [".html", "text/html; charset=utf-8"], - [".css", "text/css; charset=utf-8"], - [".js", "text/javascript; charset=utf-8"], - [".wav", "audio/wav"] -]); - -mkdirSync(renderRoot, { recursive: true }); - -function fileFor(url) { - const requestPath = decodeURIComponent(new URL(url, `http://${host}:${port}`).pathname); - if (requestPath.startsWith("/renders/")) { - const file = resolve(join(renderRoot, basename(requestPath))); - return file === renderRoot || file.startsWith(renderRoot + sep) ? file : ""; - } - - const normalized = normalize(requestPath === "/" ? "/index.html" : requestPath); - const file = resolve(join(root, normalized)); - return file === root || file.startsWith(root + sep) ? file : ""; -} - -function readBody(request) { - return new Promise((resolveBody, reject) => { - let body = ""; - request.setEncoding("utf8"); - request.on("data", chunk => { - body += chunk; - if (body.length > 24_000) { - reject(new Error("request body too large")); - request.destroy(); - } - }); - request.on("end", () => resolveBody(body)); - request.on("error", reject); - }); -} - -function renderGraph(body) { - return new Promise((resolveRender, reject) => { - const child = spawn("dotnet", [ - "run", - "--project", - rendererProject, - "-p:UseSharedCompilation=false", - "-p:BuildInParallel=false" - ], { - cwd: repoRoot, - stdio: ["pipe", "pipe", "pipe"] - }); - - let stdout = ""; - let stderr = ""; - child.stdout.setEncoding("utf8"); - child.stderr.setEncoding("utf8"); - child.stdout.on("data", chunk => { stdout += chunk; }); - child.stderr.on("data", chunk => { stderr += chunk; }); - child.on("error", reject); - child.on("close", code => { - if (code !== 0) { - reject(new Error(stderr || stdout || `renderer exited ${code}`)); - return; - } - - try { - resolveRender(JSON.parse(stdout)); - } catch (error) { - reject(new Error(`renderer returned invalid JSON: ${error.message}\n${stdout}`)); - } - }); - child.stdin.end(JSON.stringify(body)); - }); -} - -async function handleRender(request, response) { - try { - const controls = JSON.parse(await readBody(request)); - const fileName = `tract-${Date.now()}-${Math.random().toString(16).slice(2)}.wav`; - const outputPath = resolve(join(renderRoot, fileName)); - const summary = await renderGraph({ - ...controls, - outputPath, - sampleRate: controls.sampleRate ?? 44100, - durationSeconds: controls.durationSeconds ?? 0.57 - }); - - response.writeHead(200, { - "cache-control": "no-store", - "content-type": "application/json; charset=utf-8" - }); - response.end(JSON.stringify({ - ...summary, - audioUrl: `/renders/${fileName}` - })); - } catch (error) { - response.writeHead(500, { - "cache-control": "no-store", - "content-type": "application/json; charset=utf-8" - }); - response.end(JSON.stringify({ error: error.message })); - } -} - -createServer((request, response) => { - if (request.method === "POST" && new URL(request.url ?? "/", `http://${host}:${port}`).pathname === "/render") { - void handleRender(request, response); - return; - } - - const file = fileFor(request.url ?? "/"); - if (!file || !existsSync(file) || !statSync(file).isFile()) { - response.writeHead(404, { "content-type": "text/plain; charset=utf-8" }); - response.end("not found"); - return; - } - - response.writeHead(200, { - "cache-control": "no-store", - "content-type": types.get(extname(file)) ?? "application/octet-stream" - }); - createReadStream(file).pipe(response); -}).listen(port, host, () => { - console.log(`AquaSynth vocal tract playground: http://${host}:${port}/`); -}); diff --git a/tools/vocal-tract-playground/styles.css b/tools/vocal-tract-playground/styles.css deleted file mode 100644 index b37d567..0000000 --- a/tools/vocal-tract-playground/styles.css +++ /dev/null @@ -1,244 +0,0 @@ -:root { - color-scheme: dark; - --bg: #111412; - --ink: #f0f4ed; - --muted: #a8b3a3; - --line: #344035; - --panel: #1a211c; - --panel-2: #202822; - --accent: #7fd18b; - --accent-2: #f2b84b; - --accent-3: #f47f67; - --water: #76c7d4; - --shadow: rgba(0, 0, 0, 0.32); -} - -* { - box-sizing: border-box; -} - -html, -body { - min-height: 100%; -} - -body { - margin: 0; - background: - linear-gradient(180deg, rgba(127, 209, 139, 0.08), transparent 34rem), - var(--bg); - color: var(--ink); - font: 15px/1.45 system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; - letter-spacing: 0; -} - -button, -input { - font: inherit; -} - -button { - min-height: 2.25rem; - border: 1px solid var(--line); - border-radius: 6px; - background: #263229; - color: var(--ink); - cursor: pointer; -} - -button:hover { - border-color: var(--accent); -} - -button:focus-visible, -input:focus-visible { - outline: 2px solid var(--accent-2); - outline-offset: 2px; -} - -.app { - display: grid; - grid-template-columns: minmax(0, 1fr) minmax(20rem, 25rem); - gap: 1rem; - min-height: 100vh; - padding: 1rem; -} - -.stage, -.panel { - min-width: 0; -} - -.stage { - display: grid; - grid-template-rows: auto minmax(0, 1fr); - gap: 1rem; -} - -.topbar { - display: flex; - align-items: center; - justify-content: space-between; - gap: 1rem; - min-height: 4rem; -} - -.eyebrow { - margin: 0 0 0.1rem; - color: var(--accent); - font-size: 0.78rem; - font-weight: 700; - letter-spacing: 0.08em; - text-transform: uppercase; -} - -h1 { - margin: 0; - font-size: clamp(1.4rem, 2.6vw, 2.6rem); - line-height: 1.05; -} - -.transport { - display: flex; - gap: 0.5rem; - flex-wrap: wrap; - justify-content: flex-end; -} - -.transport button { - width: 5.75rem; -} - -#playButton[aria-pressed="true"] { - background: var(--accent); - color: #0c140e; - border-color: var(--accent); -} - -.visual-shell { - display: grid; - grid-template-rows: minmax(18rem, 1fr) auto auto; - gap: 0.75rem; - min-height: 0; - border: 1px solid var(--line); - border-radius: 8px; - background: #151a17; - box-shadow: 0 18px 40px var(--shadow); - overflow: hidden; -} - -canvas { - width: 100%; - height: 100%; - min-height: 18rem; - display: block; -} - -.meter-row { - display: grid; - grid-template-columns: repeat(3, 1fr); - gap: 0.6rem; - padding: 0 0.75rem 0.75rem; -} - -meter { - width: 100%; - height: 0.9rem; -} - -.render-status { - min-height: 1.35rem; - margin: -0.35rem 0 0; - padding: 0 0.75rem 0.75rem; - color: var(--muted); - font-size: 0.92rem; -} - -.panel { - display: grid; - grid-template-rows: auto minmax(0, 1fr); - gap: 0.75rem; - max-height: calc(100vh - 2rem); -} - -.preset-strip { - display: grid; - grid-template-columns: repeat(5, minmax(0, 1fr)); - gap: 0.45rem; -} - -.preset-strip button { - min-width: 0; -} - -.knob-grid { - display: grid; - gap: 0.55rem; - overflow: auto; - padding-right: 0.15rem; -} - -.control { - display: grid; - grid-template-columns: minmax(7rem, 1fr) 4.2rem; - gap: 0.45rem 0.65rem; - align-items: center; - padding: 0.65rem; - border: 1px solid var(--line); - border-radius: 8px; - background: var(--panel); -} - -.control label { - min-width: 0; - font-weight: 650; -} - -.value { - text-align: right; - color: var(--accent-2); - font-variant-numeric: tabular-nums; -} - -.control input[type="range"] { - grid-column: 1 / -1; - width: 100%; - accent-color: var(--accent); -} - -.control[data-family="source"] input[type="range"] { - accent-color: var(--accent-3); -} - -.control[data-family="spectral"] input[type="range"] { - accent-color: var(--water); -} - -@media (max-width: 900px) { - .app { - grid-template-columns: 1fr; - } - - .panel { - max-height: none; - } - - .topbar { - align-items: flex-start; - flex-direction: column; - } -} - -@media (max-width: 520px) { - .app { - padding: 0.75rem; - } - - .preset-strip { - grid-template-columns: repeat(3, minmax(0, 1fr)); - } - - .control { - grid-template-columns: minmax(0, 1fr) 3.5rem; - } -}