Add patch parameter contracts

This commit is contained in:
Meta Vens 2026-05-13 00:28:31 +01:00
commit 8827a232a8
8 changed files with 188 additions and 13 deletions

View file

@ -56,6 +56,12 @@ public static class FaustEmitter
source.AppendLine("lfo_hold(hz, phase) = no.noise : ba.latch(os.oscrs(hz));");
source.AppendLine();
EmitParameterControls(source, patch, warnings);
if (patch.Parameters.Count > 0)
{
source.AppendLine();
}
foreach (var (target, name) in ModTargets)
{
source.AppendLine($"patch_mod_{name} = {ModExpressionForTarget(patch.Controls, target)};");
@ -72,10 +78,24 @@ public static class FaustEmitter
var final = $"({string.Join(" + ", voices)}) * {F(patch.Gain)}";
if (patch.SoftClip) final = $"softclip({final})";
if (patch.Parameters.Count > 0)
{
final = $"({final}) + 0.0 * ({string.Join(" + ", patch.Parameters.Select((_, i) => ParameterIdentifier(i)))})";
}
source.AppendLine(options.Stereo ? $"process = {final} <: _,_;" : $"process = {final};");
return new FaustExport(source.ToString(), warnings);
}
private static void EmitParameterControls(StringBuilder source, SynthPatch patch, List<string> warnings)
{
for (var i = 0; i < patch.Parameters.Count; i++)
{
var parameter = patch.Parameters[i];
warnings.Add($"parameter {parameter.Path}: declared as a runtime control; target binding is not implemented yet");
source.AppendLine($"{ParameterIdentifier(i)} = hslider(\"{Escape(parameter.Path)}\", {F(parameter.Default)}, {F(parameter.Min)}, {F(parameter.Max)}, {F(parameter.Step)}) : si.smoo;");
}
}
private static void EmitVoice(StringBuilder source, SynthPatch patch, Voice voice, string name, List<string> warnings)
{
if (voice.Filter.LowPassResonance != 0)
@ -221,6 +241,8 @@ public static class FaustEmitter
private static string FmDecay(float seconds) => seconds > 0 ? $"exp(-age / {F(Math.Max(seconds, 0.0001f))})" : "1.0";
private static string ParameterIdentifier(int index) => $"patch_param_{index}";
private static string Escape(string value) => value.Replace("\\", "\\\\").Replace("\"", "\\\"");
}

View file

@ -89,6 +89,35 @@ public sealed record Modulator(
public sealed record ControlLane(string Name, Modulator Modulator);
public sealed record PatchParameter(
string Path,
string Label,
float Default,
float Min,
float Max,
float Step,
string Unit = "",
string AutomationRate = "control",
string Notes = "");
public sealed record ReferenceSource(
string Kind,
string Uri,
string License,
string Hash,
string Notes = "");
public sealed record ReferenceFeature(string Name, string Value, string Notes = "");
public sealed record ReferencePatch(
string Id,
string Family,
string Name,
ReferenceSource Source,
IReadOnlyList<ReferenceFeature> Features,
IReadOnlyList<PatchParameter> Parameters,
string? AquariumScript = null);
public sealed record Repeat(float IntervalSeconds);
public sealed record Voice
@ -111,6 +140,7 @@ public sealed record SynthPatch
{
public IReadOnlyList<Voice> Voices { get; init; } = Array.Empty<Voice>();
public IReadOnlyList<ControlLane> Controls { get; init; } = Array.Empty<ControlLane>();
public IReadOnlyList<PatchParameter> Parameters { get; init; } = Array.Empty<PatchParameter>();
public Repeat? Repeat { get; init; }
public float Gain { get; init; } = 1;
public bool SoftClip { get; init; } = true;

View file

@ -31,6 +31,7 @@ public static class PatchScript
{
private readonly Dictionary<string, Dictionary<string, string>> _templates = new(StringComparer.OrdinalIgnoreCase);
private readonly List<ControlLane> _controls = [];
private readonly List<PatchParameter> _parameters = [];
private readonly Dictionary<string, string> _defaults = new(StringComparer.OrdinalIgnoreCase);
public List<Voice> Voices { get; } = [];
@ -42,6 +43,7 @@ public static class PatchScript
{
Voices = Voices,
Controls = _controls,
Parameters = _parameters,
Repeat = Repeat,
Gain = Gain,
SoftClip = SoftClip
@ -80,6 +82,9 @@ public static class PatchScript
case "control":
AddControlLane(fields, line);
break;
case "param":
AddParameter(fields, line);
break;
case "sfxr":
AddSfxrPatch(ParseSfxrCommand(fields, line));
break;
@ -235,6 +240,51 @@ public static class PatchScript
GetFloat(fields, line, 0, "bias", "b"))));
}
private void AddParameter(IReadOnlyDictionary<string, string> fields, int line)
{
var path = Required(fields, "path", line);
if (!path.StartsWith('/'))
{
throw new PatchScriptException(line, "parameter path must start with `/`");
}
if (_parameters.Any(parameter => parameter.Path.Equals(path, StringComparison.OrdinalIgnoreCase)))
{
throw new PatchScriptException(line, $"duplicate parameter path `{path}`");
}
var label = TryGetAny(fields, ["label", "name", "n"], out var labelText)
? labelText
: path.Split('/', StringSplitOptions.RemoveEmptyEntries).LastOrDefault() ?? path;
var min = GetFloat(fields, line, 0, "min");
var max = GetFloat(fields, line, 1, "max");
var step = GetFloat(fields, line, 0.001f, "step");
var fallbackDefault = Math.Clamp(0.5f, Math.Min(min, max), Math.Max(min, max));
var defaultValue = GetFloat(fields, line, fallbackDefault, "default", "value", "v");
if (max < min)
{
throw new PatchScriptException(line, "parameter max must be greater than or equal to min");
}
if (step < 0)
{
throw new PatchScriptException(line, "parameter step must be non-negative");
}
if (defaultValue < min || defaultValue > max)
{
throw new PatchScriptException(line, "parameter default must be inside min/max");
}
_parameters.Add(new PatchParameter(
path,
label,
defaultValue,
min,
max,
step,
GetAny(fields, ["unit"], ""),
GetAny(fields, ["rate", "automation", "automation_rate"], "control"),
GetAny(fields, ["notes", "note"], "")));
}
private void AddSfxrPatch(SfxrParams parameters)
{
var mapped = parameters.ToPatch();
@ -362,6 +412,7 @@ public static class PatchScript
"v" or "voice" => "voice",
"mod" or "wob" or "wobble" or "bus" => "mod",
"lfo" or "control" => "control",
"param" or "parameter" => "param",
"s" or "sfxr" => "sfxr",
_ => command
};

View file

@ -8,3 +8,4 @@
{"kind":"runtime_patch_parameters","lesson":"Synth patches must expose expressive runtime parameters. Faust supports this through UI controls and hosted parameter APIs, so Aquarium should compile a graph once and vary declared parameter values without recompilation. Recompile only for structural graph changes.","source":"user asked whether Faust can vary one number without recompiling"}
{"kind":"synth_test_ownership","lesson":"AquariumSynthCSharp owns reference-patch correctness. Aquarium should only smoke-test the engine synth host and bundled Faust boundary; SFXR/BFXR/reference parity belongs here so the engine can keep moving while the synth library is under active surgery.","source":"user questioned synth tests living in Aquarium"}
{"kind":"package_boundary","lesson":"Aquarium consumes AquariumSynth.Dsl through a pinned package, not a live project reference. Breaking changes in AquariumSynthCSharp are allowed during synth construction as long as a new package version is packed and Aquarium is updated deliberately when the boundary should move.","source":"user wanted Aquarium builds insulated from synth-agent work"}
{"kind":"runtime_patch_parameters","lesson":"Aquarium patch scripts now have first-class `param` declarations and patch/reference model contracts. Faust emission exposes declared parameters as smoothed hslider controls, but target binding is intentionally still absent and warned about; do not claim parameters shape sound until binding is designed.","source":"parameter contract implementation on 2026-05-13"}

View file

@ -10,6 +10,8 @@
],
"own_here": [
"patch graph model",
"patch parameter contracts",
"reference patch contracts",
"patch script parser",
"SFXR atoms and parameter mapping",
"analysis/comparison metrics",
@ -47,8 +49,8 @@
"aquarium_requirement": "Aquarium DSL patches must be able to declare stable exposed parameters with path/default/min/max/step metadata so callers can vary sound without recompiling."
},
"last_verified": {
"command": "dotnet test",
"result": "15 passed",
"commit": "pending reference roadmap handoff"
"command": "dotnet test AquariumSynthCSharp.slnx --no-restore",
"result": "20 passed",
"commit": "pending parameter contract commit"
}
}

View file

@ -5,13 +5,23 @@ targets, not through speculative field sprawl. `state/spine.yaml` and
`docs/reference-synth-roadmap.md` are the handoff surfaces for agents working on
the synth library while Aquarium work continues elsewhere.
The next likely slice is parameter contracts, then DX7/Dexed:
Completed this slice:
- Add explicit patch parameter contracts: stable path, label, default, min, max,
step, unit/scale, and automation-rate notes.
- Update Faust emission so declared parameters become runtime controls instead
of baked constants.
- Add neutral reference model contracts with provenance/license/hash fields.
- Added explicit `PatchParameter` contracts: stable path, label, default, min,
max, step, unit, automation-rate notes, and notes.
- Added neutral `ReferencePatch`, `ReferenceSource`, and `ReferenceFeature`
contracts with provenance/license/hash-ready fields.
- Added `param` script declarations and duplicate parameter path validation.
- Updated Faust emission so declared parameters produce smoothed `hslider`
controls. Target binding is not implemented yet and emits a warning; do not
pretend the parameter value shapes sound until binding exists.
- Verified with `dotnet test AquariumSynthCSharp.slnx --no-restore`: 20 passed.
Next likely slice:
- Decide whether `param` should bind to explicit semantic targets such as
`target=lpf` or whether fields should accept parameter references such as
`lpf=@/macro/brightness`. Do not add both without a clear ownership model.
- Implement a DX7 SysEx parser skeleton for single voices and cartridge payloads.
- Extract operator topology, envelopes, ratios, feedback, levels, LFO, and pitch
envelope into feature records before trying to translate.

View file

@ -1,6 +1,6 @@
project: AquariumSynthCSharp
spine_version: 1
updated: 2026-05-12T23:08:00+01:00
updated: 2026-05-13T00:27:06+01:00
prime_directive: >
Build coherent synth machinery. References exist to reveal missing structure,
@ -20,6 +20,7 @@ current_mechanism:
tests: tests/AquariumSynth.Dsl.Tests/PatchScriptTests.cs
doctrine: docs/audio-doctrine.md
roadmap: docs/reference-synth-roadmap.md
parameter_contracts: src/AquariumSynth.Dsl/Model.cs
live_invariants:
- Aquarium owns its patch graph; external synths are references, not runtime dependencies.
@ -75,9 +76,9 @@ reference_targets:
next_agent_start_here:
recommended_first_task: >
Implement reference model and patch parameter contracts, then add a DX7
SysEx parser skeleton with feature extraction tests. Do not start by
importing a giant bank.
Decide whether parameter declarations need explicit target binding before
DX7 work, then add a DX7 SysEx parser skeleton with feature extraction
tests. Do not start by importing a giant bank.
must_read:
- AGENTS.md
- docs/audio-doctrine.md
@ -88,6 +89,15 @@ next_agent_start_here:
verification:
- "dotnet test AquariumSynthCSharp.slnx --no-restore"
completed_slices:
- date: 2026-05-13
summary: >
Added PatchParameter and ReferencePatch contracts, `param` script parsing,
duplicate path validation, and Faust hslider emission for declared
controls. Parameter target binding is intentionally not implemented yet;
the emitter warns so the gap stays visible.
verification: "dotnet test AquariumSynthCSharp.slnx --no-restore: 20 passed"
cut_line:
- "Cut any importer that cannot state source provenance and license."
- "Cut weak tests that only prove parser leniency."

View file

@ -65,6 +65,31 @@ public sealed class PatchScriptTests
Assert.Equal(.01f, lane.Modulator.Bias, 5);
}
[Fact]
public void ParserPreservesDeclaredPatchParameters()
{
var patch = PatchScript.Parse("param name=brightness path=/macro/brightness default=.45 min=0 max=1 step=.001 unit=normalized rate=control;v w=saw f=80");
var parameter = Assert.Single(patch.Parameters);
Assert.Equal("/macro/brightness", parameter.Path);
Assert.Equal("brightness", parameter.Label);
Assert.Equal(.45f, parameter.Default, 5);
Assert.Equal(0, parameter.Min);
Assert.Equal(1, parameter.Max);
Assert.Equal(.001f, parameter.Step, 5);
Assert.Equal("normalized", parameter.Unit);
Assert.Equal("control", parameter.AutomationRate);
}
[Fact]
public void ParserRejectsDuplicatePatchParameterPaths()
{
var exception = Assert.Throws<PatchScriptException>(() =>
PatchScript.Parse("param path=/macro/brightness;param path=/macro/brightness;v w=sin"));
Assert.Contains("duplicate parameter path", exception.Message);
}
[Fact]
public void BuiltInExampleParsesAndExportsFaust()
{
@ -176,6 +201,16 @@ public sealed class PatchScriptTests
Assert.Contains("<: _,_;", export.Source);
}
[Fact]
public void FaustEmitterExposesDeclaredPatchParametersAsControls()
{
var export = FaustEmitter.EmitScript("param path=/macro/brightness default=.45 min=0 max=1 step=.001;v w=saw f=80");
Assert.Contains("patch_param_0 = hslider(\"/macro/brightness\", 0.45, 0, 1, 0.001) : si.smoo;", export.Source);
Assert.Contains("patch_param_0", export.Source);
Assert.Contains("target binding is not implemented yet", Assert.Single(export.Warnings));
}
[Fact]
public async Task FaustCompilerValidatesGeneratedSourceWhenInstalled()
{
@ -190,6 +225,20 @@ public sealed class PatchScriptTests
Assert.True(validation.Success, validation.Stderr);
}
[Fact]
public async Task FaustCompilerValidatesParameterizedPatchWhenInstalled()
{
var export = FaustEmitter.EmitScript("param path=/macro/brightness default=.45 min=0 max=1 step=.001;v w=saw f=80");
var validation = await FaustCompiler.ValidateAsync(export.Source);
if (validation is null)
{
return;
}
Assert.True(validation.Success, validation.Stderr);
}
[Fact]
public async Task FaustCompilerCanEmitCSharpWhenInstalled()
{