steward cleanup: drop dead scaffolding, finish Dings Step 4, retire AquaSynth-rs note

- Update AquaSynth.sln: remove BirdSyrinxGolf and IpaTrialWorker; add AquaSynth.Dings and AquaSynthDingsHost.
- Delete zero-consumer dead scaffolding: tools/BirdSyrinxGolf, tools/run-ipa-trial-loop.ps1, tools/run-ipa-trial-swarm.ps1, tools/run-song-snippet-trial-swarm.ps1, tools/vocal-tract-playground, tools/TractGraphRenderer, tools/sound-guard, tools/publish-stable, tools/export-provider-advertisement.mjs, docs/fixtures/aquasynth-provider-advertisement.json, state/scratch.md; trim stale README pointers in tools/dings-voices/README.md and tools/aqua-ear/README.md.
- Finish Dings Step 4: remove deprecated pre-filter in DingService.PlayAsync so DingCatalog.PlayRejection in DingsPlaybackHost is the single validation gate; update DingsBridgeTests to verify forwarding and host rejection surfacing; drop raw-C#-source-text regex checks from DingCatalogTests.
- Retire the stale AquaSynth-rs branch claim in AGENTS.md.
This commit is contained in:
Meta Vens 2026-12-03 21:04:05 +01:00
commit c5771e58a3
30 changed files with 63 additions and 7318 deletions

View file

@ -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

View file

@ -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

View file

@ -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."
]
}

View file

@ -13,8 +13,8 @@ public static class DingCatalog
public static DingPatchIdentity Identity(DingInstrument instrument) =>
new($"dings.{instrument.Id}", $"dings_{instrument.Id.Replace('-', '_')}", 1);
/// <summary>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.</summary>
/// <summary>The play validation gate. The Host is its single enforcing owner (every pipe client passes it).
/// Returns the rejection text, or null when valid.</summary>
public static string? PlayRejection(string eventId, string instrumentId, float gain)
{
if (!Events.ContainsKey(eventId)) return $"Unknown event '{eventId}'.";

File diff suppressed because it is too large Load diff

View file

@ -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);

View file

@ -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<ArgumentException>(() => 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<InvalidOperationException>(() => service.PlayAsync("nope", "warm-bell", .5f, CancellationToken.None));
Assert.Equal(DingCatalog.PlayRejection("nope", "warm-bell", .5f), badEvent.Message);
var badInstrument = await Assert.ThrowsAsync<ArgumentException>(() => service.PlayAsync("task.complete", "nope", .5f, CancellationToken.None));
var badInstrument = await Assert.ThrowsAsync<InvalidOperationException>(() => service.PlayAsync("task.complete", "nope", .5f, CancellationToken.None));
Assert.Equal(DingCatalog.PlayRejection("task.complete", "nope", .5f), badInstrument.Message);
await Assert.ThrowsAsync<ArgumentOutOfRangeException>(() => service.PlayAsync("task.complete", "warm-bell", 1.5f, CancellationToken.None));
Assert.Empty(host.Commands);
var badGain = await Assert.ThrowsAsync<InvalidOperationException>(() => 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<InvalidOperationException>(() => 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<DingsCommand> Commands { get; } = [];
public float Volume { get; set; } = 1;
public bool Muted { get; set; }
public bool EnforceCatalogGate { get; init; }
public Task<DingsResponse> 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));

View file

@ -6,15 +6,9 @@ public sealed class DingService(IDingsHostClient host)
{
public async Task<object> 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<DingsResponse> StopAllAsync(CancellationToken cancellationToken) => EnsureSuccess(await host.SendAsync(new(DingsProtocol.Version, DingsCommandKind.StopAll), cancellationToken));

View file

@ -1,20 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectReference Include="..\..\src\AquaSynth.Core\AquaSynth.Core.csproj" />
<ProjectReference Include="..\..\src\AquaSynth.Faust\AquaSynth.Faust.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="NAudio" Version="2.2.1" />
<PackageReference Include="NVorbis" Version="0.10.5" />
</ItemGroup>
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View file

@ -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<ResultRow>();
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<SyrinxCandidate> 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<ResultRow> 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<float> 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<float>();
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<float> samples, int sampleRate, IReadOnlyList<int> 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<float>();
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<float>();
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<string> 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<float> 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<float> 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<float> 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<float> 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<float> 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);

View file

@ -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<RenderRequest>(
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<float> 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);

View file

@ -1,16 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\AquaSynth.Core\AquaSynth.Core.csproj" />
<ProjectReference Include="..\..\src\AquaSynth.Faust\AquaSynth.Faust.csproj" />
</ItemGroup>
</Project>

View file

@ -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 <dir of runs>` (see tools/dings-voices/README.md, Publishing).

View file

@ -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 <publishDir> # 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 <dir of runs>`). 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.

View file

@ -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;
});

View file

@ -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'<div class="{MARK}" style="{BANNER_CSS}"><!--{MARK}-->{inner}</div>\n'
def put_banner(path, inner):
"""Insert (or replace) the marked banner right after <body>, else after </head>, else at the top. Idempotent."""
s = open(path, encoding="utf-8").read()
s = re.sub(rf'<div class="{MARK}".*?</div>\n?', "", s, flags=re.S)
b = banner(inner)
m = re.search(r"<body[^>]*>", s, re.I) or re.search(r"</head>", 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"<strong>The one Dings page.</strong> {base}/dings/ always shows the latest version; it is overwritten in place. "
f"Current: <code>{html.escape(label)}</code>, AquaSynth <code>{rev()}</code>. 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'<a href="{html.escape(r)}/{html.escape(f)}">{html.escape(f)}</a>' for f in files)
img = next((f for f in ("compare.png", "spectrogram.png") if f in files), None)
pic = f'<p><a href="{html.escape(r)}/{img}"><img src="{html.escape(r)}/{img}" alt="{html.escape(r)}" style="max-width:100%"></a></p>' if img else ""
items.append(f"<section><h2>{html.escape(r)}</h2>{pic}<p>{links}</p></section>")
page = ('<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">'
"<title>aqua-ear examples</title></head><body style=\"font:1rem/1.5 system-ui,sans-serif;max-width:60rem;margin:0 auto;padding:1rem\">"
"<h1>aqua-ear examples</h1><p>Pictures and reports from <code>tools/aqua-ear</code> (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 <code>{rev()}</code>.</p>" + "".join(items) + "</body></html>\n")
open(os.path.join(stage, "index.html"), "w").write(page)
put_banner(os.path.join(stage, "index.html"), f"<strong>The one aqua-ear examples page.</strong> {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"<strong>Old per-version page.</strong> The one Dings page is <a href=\"{base}/dings/\">{base}/dings/</a> (always the latest); listen there."
if dings else
f"<strong>Old per-version page, kept for the record.</strong> One-place rule: current Dings are at <a href=\"{base}/dings/\">{base}/dings/</a>, "
f"aqua-ear examples at <a href=\"{base}/ear/\">{base}/ear/</a>.")
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('<!doctype html><html lang="en"><head><meta charset="utf-8"><title>' + html.escape(d) + "</title></head><body><h1>" + html.escape(d)
+ "</h1><ul>" + "".join(f'<li><a href="{html.escape(f)}">{html.escape(f)}</a></li>' for f in files) + "</ul></body></html>\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()

View file

@ -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"<html><body>VERSION-{tag}</body></html>"); 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()

View file

@ -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("<!doctype html><html><head><title>x</title></head><body><h1>v</h1></body></html>")
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('<div class="aqua-stable-banner"'), 1)
self.assertTrue(os.path.exists(self.root + "/dings/out/senders/a.ogg")); self.assertIn("dings-voices-abc1234", open(self.root + "/dings/VERSION").read())
self.assertEqual(sorted(f for f in os.listdir(self.root) if not f.endswith(".lock")), ["dings"]) # no staging leftovers
def test_new_version_replaces_old_files(self):
run("dings", self.src, "--root", self.root); os.remove(self.src + "/out/senders/a.ogg"); open(self.src + "/out/senders/b.ogg", "wb").write(b"OggS")
run("dings", self.src, "--root", self.root); self.assertEqual(os.listdir(self.root + "/dings/out/senders"), ["b.ogg"])
def test_refuses_a_dir_that_is_not_a_built_page(self):
r = run("dings", self.t.name, "--root", self.root); self.assertNotEqual(r.returncode, 0); self.assertFalse(os.path.exists(self.root + "/dings"))
def test_failed_publish_keeps_the_previous_page(self):
run("dings", self.src, "--root", self.root); before = tree(self.root + "/dings")
os.remove(self.src + "/index.html"); self.assertNotEqual(run("dings", self.src, "--root", self.root).returncode, 0); self.assertEqual(before, tree(self.root + "/dings"))
def test_banners_added_once_to_old_dirs_and_nothing_deleted(self):
run("dings", self.src, "--root", self.root)
for d, body in (("dings-voices-old", "<html><body><p>old</p></body></html>"), ("trial-1", "<p>no body tag</p>")):
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('<div class="aqua-stable-banner"'), 1); self.assertIn("/dings/", p)
self.assertIn("old", open(self.root + "/dings-voices-old/index.html").read()); self.assertTrue(os.path.exists(self.root + "/aqua-ear-examples/x.png"))
self.assertEqual(open(self.root + "/dings/index.html").read().count("Old per-version"), 0) # the stable page is not an old page
def test_ear_index_lists_runs(self):
e = os.path.join(self.t.name, "ear-src"); os.makedirs(e + "/void-x"); open(e + "/void-x/compare.png", "wb").write(b"p")
self.assertEqual(run("ear", e, "--root", self.root).returncode, 0); p = open(self.root + "/ear/index.html").read(); self.assertIn("void-x/compare.png", p)
if __name__ == "__main__": unittest.main()

View file

@ -1,577 +0,0 @@
param(
[int]$Rounds = 5,
[string]$BatchId = "five-seed-trials",
[string]$CodexCommand = "codex",
[string]$CodexModel = "gpt-5.3-codex",
[switch]$AllowCodexSourceEdits,
[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 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 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 <targetId>__<family>__<hypothesis-name>.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 <targetId>__<family>__<hypothesis-name>.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 "<your evidence question>" --limit 20 --output "$roundDir/search-<topic>.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 "<trial id from search>" --output "$roundDir/detail-<candidate>.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 <targetId>__<family>__<hypothesis-name>.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: <targetId>__<family>__<hypothesis-name>.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 "<trial id from current round search>" --output "$roundDir/eval-detail-<candidate>.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 <targetId>__<family>__<hypothesis-name>.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: `<file-or-module> | <invariant> | <expected metric movement>`.
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"

View file

@ -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 <targetId>__<family>__<hypothesis-name>.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 "<your evidence question>" --limit 20 --output "$laneDir/search-<topic>.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 "<trial id from search>" --output "$laneDir/detail-<candidate>.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 <targetId>__<family>__<hypothesis-name>.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 "<weak current pass 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 "<promising current pass 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 <targetId>__<family>__<hypothesis-name>.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 `<file-or-module> | <invariant> | <expected metric movement>`.
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"

View file

@ -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 <agent-id>__<family>__<hypothesis>.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/<target-id>/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 "<attempt-patch-dir>" --challenge "<challenge-json>" --artifact-root "<attempt-dir>" --batch-id "<agent-id>-<target-id>-attempt-NN" --store "<attempt-dir>/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=<step_seconds>` 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=<target-derived-pattern> step=<beat_seconds/4> gain=.08 sustain=<duration_seconds>, texture name=air_wash role=air gain=.035 sustain=<duration_seconds>, texture name=codec_bed role=codec gain=.04 sustain=<duration_seconds>.
- 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=<beat_seconds/4> 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=<tempo_bpm/60>, noise=@/seq/hiss, freq=@/seq/pitch.
- Use `trigger=<step_seconds>` 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=<beat_seconds/4> 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=<tempo_bpm> beats=4`.
- Sequence any instrument lane without hand-declaring the gate parameter: `sequence name=kick pattern=x..x step=<beat_seconds> high=.8 low=0`, then bind `gain=@/seq/kick`.
- Declare chord/progression control lanes for pads or bass: `chords name=prog root=<root_hz> 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=<root_hz> scale=minor degrees=0,2,4,2,5,4 step=<beat_seconds/2>`.
- 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=<dominant_hz> min=<register_low_hz> max=<register_high_hz> step=.01 unit=Hz`
- step the scale: `curve name=lead_scale path=/seq/pitch points=0:<scale0>,0.25:<scale1>,0.5:<scale2>,0.75:<scale3> interp=hold loop=true`
- new sugar now exists: `scale name=lead_scale path=/seq/pitch freqs=<scale_frequencies_hz> degrees=0,1,3,2 step=<beat_seconds/4>`
- 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 `<agent-id>__<family>__<hypothesis>.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"

View file

@ -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.

View file

@ -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 (<d>/<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 (<dir>/<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())

View file

@ -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()

View file

@ -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": []
}

View file

@ -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.

View file

@ -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
};

View file

@ -1,49 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>AquaSynth Tract Voice Playground</title>
<link rel="stylesheet" href="./styles.css">
</head>
<body>
<main class="app">
<section class="stage">
<header class="topbar">
<div>
<p class="eyebrow">AquaSynth lab</p>
<h1>Tract Voice Playground</h1>
</div>
<div class="transport" role="group" aria-label="Transport">
<button id="playButton" type="button" aria-pressed="false" title="Render and play actual Aqua graph audio">Render</button>
<button id="panicButton" type="button" title="Stop playback or render">Stop</button>
</div>
</header>
<div class="visual-shell">
<canvas id="tractCanvas" width="1100" height="520" aria-label="Vocal tract control visualization"></canvas>
<div class="meter-row" aria-label="Output meters">
<meter id="pressureMeter" min="0" max="1" value="0"></meter>
<meter id="noiseMeter" min="0" max="1" value="0"></meter>
<meter id="nasalMeter" min="0" max="1" value="0"></meter>
</div>
<p id="renderStatus" class="render-status" role="status">Ready to render the Aqua DSL graph.</p>
</div>
</section>
<aside class="panel" aria-label="Controls">
<section class="preset-strip" aria-label="Presets">
<button type="button" data-preset="open">Open</button>
<button type="button" data-preset="ee">Ee</button>
<button type="button" data-preset="oo">Oo</button>
<button type="button" data-preset="ss">Ss</button>
<button type="button" data-preset="ma">Ma</button>
</section>
<section class="knob-grid" id="controls"></section>
</aside>
</main>
<script src="./app.js"></script>
</body>
</html>

View file

@ -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}/`);
});

View file

@ -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;
}
}