From 0f0de0dd8ea8beb764768d8cd431857e64c16e79 Mon Sep 17 00:00:00 2001 From: Aqua Date: Thu, 12 Nov 2026 10:33:48 +0000 Subject: [PATCH 01/19] Dings: DingCatalog.Identity owns PatchId/FaustName/revision derivation (step 1); record owner as ruled, migration plan Co-Authored-By: Claude Sonnet 5.5 --- docs/dings-patch-identity-authority-map.md | 24 ++++++++++++++++- src/AquaSynth.Dings/DingCatalog.cs | 7 +++++ tests/AquaSynth.Dsl.Tests/DingCatalogTests.cs | 26 ++++++++++++++++++- tools/AquaLower/Program.cs | 2 +- tools/AquaSynthDingsHost/AquaDaemonClient.cs | 3 ++- tools/earcon-workshop/web/earcon.js | 2 ++ 6 files changed, 60 insertions(+), 4 deletions(-) diff --git a/docs/dings-patch-identity-authority-map.md b/docs/dings-patch-identity-authority-map.md index dc09396..a3d5133 100644 --- a/docs/dings-patch-identity-authority-map.md +++ b/docs/dings-patch-identity-authority-map.md @@ -259,7 +259,9 @@ user. Any process of that user can send `Play`. There is no per-caller identity pipe: `DingsCommand` carries an instrument, not a caller, so the Host cannot know who asked. -## PROPOSED: one owner (a recommendation for the stewarding decision, not decided) +**Status (2026-11-12): the owner is RULED.** The operator tier, relayed through Persona, ruled that `DingCatalog` is the single owner of Dings patch identity. The sections below were written as a proposal; they are kept as the analysis behind the ruling. Their per-step claims are still unverified plans, except step 1, which landed on branch `aqua/dingcatalog-owner-step1`. + +## One owner: DingCatalog (ruled; analysis below was written as a PROPOSAL) **Proposal.** `DingCatalog` (`src/AquaSynth.Dings`) becomes the only place that decides what a voice is, and also the only place that derives the daemon keys from it. Its @@ -268,6 +270,8 @@ and one function in that assembly produces `PatchId`, `FaustName` and the revisi the daemon (`AquaLower` and the test need only the faust-name part of it, not `patchId` or revision). Everything else keys on the catalog id and takes the rest from the catalog. +End state versus this change: the content revision named above is deferred (step 3 of the migration order). Until it lands, `revision` is the literal 1 and the catalog function returns it; the revision hash is not part of the first consolidation. + **What the others become.** - B (Host/daemon): the Host stops composing `patchId`/`faustName`/`revision`; it calls the catalog function. `AquaLower/Program.cs:19` and `DingCatalogTests.cs:45` call only the faust-name slice of it. The daemon @@ -338,3 +342,21 @@ what the MCP bridge can learn about its caller. and whether the Host's `Ping`/`GetVolume` have different callers in practice. The pipe protocol above is from reading, not from a captured exchange. Nothing was built, run, or listened to for this note. + +## Migration plan (ruled 2026-11-12: DingCatalog is the owner) + +Rules for every step: deprecate before removing (mark the old path with a pointer, keep it working, delete in a later pass after the window); `patchId`, `faustName`, `revision = 1`, session ids, compile keys and `sessions/<...>.cc` names stay byte-identical until step 3; no change to the Host or pipe protocol. Deprecation window: one merged release of the owner path with the old path still working and marked; removal only in a separate PR after the operator hears or reviews nothing regressed. + +**Step 1 (done in this change).** `DingCatalog.Identity(instrument)` returns `PatchId`, `FaustName`, `Revision` (literal 1). `AquaDaemonClient` and `AquaLower --dings` call it. The guard test no longer carries a private copy of the rule: it compares against literals per instrument, and `IdentityPinsTheOldDerivedValuesForAllFourInstruments` pins the old derived values for all four. +- Verify: the pin test; `DingCatalogTests` and `StoreFileNameTests`; `AquaLower --dings tools/aqua-feel/lowered-dings` leaves `git status` clean (the checked-in mirror is byte-identical). +- Not verified: the Host sending the same JSON to the daemon at runtime (compile-checked and read, not run against a daemon). +- Rollback: revert the commit; no stored state or wire format moved. +- Echo sites in this step: the `lowered-dings` mirror is tied to the catalog by `AquaLower` calling `Identity` and stays test-guarded. Earcon Workshop `IDENTITIES` is NOT tied: it is browser JS with its own voice model (`fmRatio`, `harmonics`, seconds-based decay) and shares only ids, so tying needs a generated file and a build step, which is step 5. It is marked deprecated with a pointer, and still works. + +**Step 2. Agent identity for the registry** (`AgentInstrumentRegistry` key). Blocked on the open question (what the bridge can learn about its caller). Verify: a test that the same agent id maps to the same instrument across sessions, and listening before and after, which nobody has done. Deprecate: keep the session-id keyed path behind the new key for one release. Rollback: revert; assignments are an in-memory cache. + +**Step 3. Content revision** (replace the literal 1 with a catalog hash). Deliberately breaks byte-identity: compile keys, session ids and `sessions/<...>.cc` names all change. Needs its own ruling on what feeds the hash and whether old session files are left or removed. Verify: receipts before and after, with the old keys listed as expected to change. Rollback: revert to literal 1; new session files stay as orphans, harmless. + +**Step 4. One validation gate** (`DingService` versus `DingsPlaybackHost`). Make the Host the owner and let the bridge forward; keep the bridge check as deprecated fail-fast for one window. Verify: `DingsBridgeTests`. Rollback: revert; both gates read one dictionary, so behaviour is the same either way. + +**Step 5. Echo sites by reference.** (a) Neutral fallback in `tools/dings-voices/build.mjs` names a catalog instrument id. (b) Earcon Workshop `IDENTITIES`: export the shared ids and root frequencies from the catalog into a checked-in file (as `lowered-dings` is), guarded by a test, and have `earcon.js` read it; the voice-model parameters stay workshop-owned and the drifted values (table in section E) need an owner's decision first. Deprecation: `IDENTITIES` keeps its inline values, marked, until the generated file is read in production. Verify: `tools/earcon-workshop/test.mjs`, the guard test, and an ear check, since the workshop values were never tuned to the catalog. Rollback: revert; the inline values still exist. diff --git a/src/AquaSynth.Dings/DingCatalog.cs b/src/AquaSynth.Dings/DingCatalog.cs index 4da53ec..5f1241f 100644 --- a/src/AquaSynth.Dings/DingCatalog.cs +++ b/src/AquaSynth.Dings/DingCatalog.cs @@ -4,8 +4,15 @@ public sealed record DingNote(double Semitones, int DelayMilliseconds, float Gai public sealed record DingEvent(string Id, string Meaning, IReadOnlyList Notes); public sealed record DingInstrument(string Id, string Description, string TimbreFamily, string Script, float RootFrequency, float Brightness, float DecaySeconds, bool UsesNoise); +/// The daemon-facing identity of a catalog instrument. Revision is the literal 1 until the deferred content-revision step. +public sealed record DingPatchIdentity(string PatchId, string FaustName, int Revision); + public static class DingCatalog { + /// The only derivation of PatchId, FaustName and revision from an instrument id. Host, AquaLower and the tests call this. + public static DingPatchIdentity Identity(DingInstrument instrument) => + new($"dings.{instrument.Id}", $"dings_{instrument.Id.Replace('-', '_')}", 1); + public static readonly IReadOnlyDictionary Events = new DingEvent[] { new("session.start", "Opening welcome", [new(0, 0), new(7, 220)]), diff --git a/tests/AquaSynth.Dsl.Tests/DingCatalogTests.cs b/tests/AquaSynth.Dsl.Tests/DingCatalogTests.cs index 5e6f9a6..bd5f555 100644 --- a/tests/AquaSynth.Dsl.Tests/DingCatalogTests.cs +++ b/tests/AquaSynth.Dsl.Tests/DingCatalogTests.cs @@ -34,6 +34,30 @@ public sealed class DingCatalogTests Assert.InRange(pair.Second.DelayMilliseconds - pair.First.DelayMilliseconds, 180, 320); } + // Independent oracle: literals captured from the pre-DingCatalog.Identity derivation in AquaDaemonClient/AquaLower. + // Session ids, compile keys and store file names hang off these; they must not move without the deferred revision decision. + private static readonly Dictionary Pinned = new() + { + ["warm-bell"] = ("dings.warm-bell", "dings_warm_bell"), + ["glass-chime"] = ("dings.glass-chime", "dings_glass_chime"), + ["soft-triangle"] = ("dings.soft-triangle", "dings_soft_triangle"), + ["muted-pluck"] = ("dings.muted-pluck", "dings_muted_pluck"), + }; + private static Dictionary PinnedFaustNames => Pinned.ToDictionary(x => x.Key, x => x.Value.FaustName); + + [Fact] + public void IdentityPinsTheOldDerivedValuesForAllFourInstruments() + { + Assert.Equal(Pinned.Keys.Order(), DingCatalog.Instruments.Keys.Order()); + foreach (var instrument in DingCatalog.Instruments.Values) + { + var identity = DingCatalog.Identity(instrument); + Assert.Equal(Pinned[instrument.Id].PatchId, identity.PatchId); + Assert.Equal(Pinned[instrument.Id].FaustName, identity.FaustName); + Assert.Equal(1, identity.Revision); + } + } + // tools/aqua-feel measures the lowered files in tools/aqua-feel/lowered-dings; regenerate them with // `dotnet run --project tools/AquaLower -- --dings tools/aqua-feel/lowered-dings` when the catalog changes. [Fact] @@ -42,7 +66,7 @@ public sealed class DingCatalogTests var dir = Path.Combine(RepositoryRoot(), "tools", "aqua-feel", "lowered-dings"); foreach (var instrument in DingCatalog.Instruments.Values) { - var expected = FaustEmitter.EmitScript(instrument.Script, new FaustExportOptions("dings_" + instrument.Id.Replace('-', '_'))).Source; + var expected = FaustEmitter.EmitScript(instrument.Script, new FaustExportOptions(PinnedFaustNames[instrument.Id])).Source; Assert.Equal(expected, File.ReadAllText(Path.Combine(dir, instrument.Id + ".dsp"))); } diff --git a/tools/AquaLower/Program.cs b/tools/AquaLower/Program.cs index 8ee3fd7..103b913 100644 --- a/tools/AquaLower/Program.cs +++ b/tools/AquaLower/Program.cs @@ -16,7 +16,7 @@ if (args.Length == 2 && args[0] == "--dings") var instruments = new List(); foreach (var ins in DingCatalog.Instruments.Values.OrderBy(i => i.Id, StringComparer.Ordinal)) { - var export = FaustEmitter.EmitScript(ins.Script, new FaustExportOptions("dings_" + ins.Id.Replace('-', '_'))); + var export = FaustEmitter.EmitScript(ins.Script, new FaustExportOptions(DingCatalog.Identity(ins).FaustName)); File.WriteAllText(Path.Combine(dingDir, ins.Id + ".dsp"), export.Source); instruments.Add(new { id = ins.Id, rootFrequency = ins.RootFrequency, dsp = ins.Id + ".dsp", controlPath = "/ding/frequency", warnings = export.Warnings }); Console.WriteLine($"{ins.Id}: {export.Source.Length} chars, {export.Warnings.Count} warnings"); diff --git a/tools/AquaSynthDingsHost/AquaDaemonClient.cs b/tools/AquaSynthDingsHost/AquaDaemonClient.cs index 2d5a15e..aa4de12 100644 --- a/tools/AquaSynthDingsHost/AquaDaemonClient.cs +++ b/tools/AquaSynthDingsHost/AquaDaemonClient.cs @@ -17,7 +17,8 @@ public sealed class AquaDaemonClient : IAsyncDisposable { EnsureStarted(); var id = $"ding-{Guid.NewGuid():N}"; - var envelope = new { command = "instrument.sample", payload = new { commandId = id, patchId = $"dings.{instrument.Id}", faustName = $"dings_{instrument.Id.Replace('-', '_')}", script = instrument.Script, durationSeconds = 1.5f, gain, controls = new Dictionary { ["/ding/frequency"] = frequency }, revision = 1 } }; + var identity = DingCatalog.Identity(instrument); + var envelope = new { command = "instrument.sample", payload = new { commandId = id, patchId = identity.PatchId, faustName = identity.FaustName, script = instrument.Script, durationSeconds = 1.5f, gain, controls = new Dictionary { ["/ding/frequency"] = frequency }, revision = identity.Revision } }; await process!.StandardInput.WriteLineAsync(JsonSerializer.Serialize(envelope, json)); await process.StandardInput.FlushAsync(cancellationToken); var line = await process.StandardOutput.ReadLineAsync(cancellationToken) ?? throw new InvalidOperationException("Aqua daemon closed before returning a render receipt."); diff --git a/tools/earcon-workshop/web/earcon.js b/tools/earcon-workshop/web/earcon.js index 6dcee6a..6eae20c 100644 --- a/tools/earcon-workshop/web/earcon.js +++ b/tools/earcon-workshop/web/earcon.js @@ -17,6 +17,8 @@ export const EVENTS = { waiting: { label: "Waiting", meaning: "Needs you: quiet, sparse, slow low sway, three soft notes", notes: [[0, 0, 0.55], [5, 450, 0.55], [0, 900, 0.55]] }, }; +// DEPRECATED as an identity owner (ruled 2026-11-12: DingCatalog owns Dings patch identity; see +// docs/dings-patch-identity-authority-map.md, 'Migration plan'). Kept working; do not add ids or copy catalog values here. // Timbre identities. rootHz in the calm mid register; fmRatio/fmIndex/fmDecay shape the bell; harmonics > 0 selects the // additive triangle; attack is seconds. Values start from the Dings catalog instruments and were not tuned by ear. export const IDENTITIES = { From ea500d1327f7d9a26df5f70d2cfba191a25d8c3a Mon Sep 17 00:00:00 2001 From: Aqua Date: Thu, 12 Nov 2026 10:40:04 +0000 Subject: [PATCH 02/19] Dings authority doc: post-step-1 state, re-verified citations, one migration list; caller source-check test Co-Authored-By: Claude Sonnet 5.5 --- docs/dings-patch-identity-authority-map.md | 78 ++++++++----------- tests/AquaSynth.Dsl.Tests/DingCatalogTests.cs | 12 +++ 2 files changed, 45 insertions(+), 45 deletions(-) diff --git a/docs/dings-patch-identity-authority-map.md b/docs/dings-patch-identity-authority-map.md index a3d5133..b6e70e4 100644 --- a/docs/dings-patch-identity-authority-map.md +++ b/docs/dings-patch-identity-authority-map.md @@ -31,14 +31,14 @@ code. The grouping above follows who writes the key. ## A. `DingCatalog` instrument id and script -- Where: `src/AquaSynth.Dings/DingCatalog.cs:22-28` (four instruments), built by the - private `Instrument(...)` at `:48-50`, which writes the `Script` string (an AquaSynth patch script, `param path=...; voice wave=...`, that `FaustEmitter.EmitScript` lowers to Faust; not Faust source) and +- Where: `src/AquaSynth.Dings/DingCatalog.cs:29-35` (four instruments), built by the + private `Instrument(...)` at `:56-57`, which writes the `Script` string (an AquaSynth patch script, `param path=...; voice wave=...`, that `FaustEmitter.EmitScript` lowers to Faust; not Faust source) and fixes `RootFrequency = 261.6256f` for all four. - Keys on: the instrument `Id` string (`warm-bell`, `glass-chime`, `soft-triangle`, - `muted-pluck`), case-insensitive dictionary (`:28`). Events are a separate keyed - dictionary (`:9-20`, nine ids) and are not voice identity. + `muted-pluck`), case-insensitive dictionary (`:35`). Events are a separate keyed + dictionary (`:16-27`, nine ids) and are not voice identity. - Lifetime: compiled in. Changing an entry means a new build of every consumer. -- Writer: whoever edits the file. `ValidateCuration` (`:31-46`) is the only gate. +- Writer: whoever edits the file. `ValidateCuration` (`:37-54`) is the only gate. - Readers: `Host/DingsPlaybackHost.cs:66-67`, `Mcp/DingService.cs:9-10`, `Mcp/AgentInstrumentRegistry.cs:11`, `Mcp/DingTools.cs:28,31,49`, `tools/AquaLower/Program.cs:17`, and the tests `DingCatalogTests`. @@ -47,12 +47,15 @@ code. The grouping above follows who writes the key. ## B. Host and daemon derivation of the patch -The Host does not pass the catalog id through. It builds the daemon's identity fields -itself, and the daemon builds more keys from them. +The Host does not pass the catalog id through. It sends the daemon identity fields +derived from it by `DingCatalog.Identity` (`DingCatalog.cs:12-14`, added in step 1; before +it, at `965dfe8` (origin/main before this change), `AquaDaemonClient.cs:20` composed the strings inline), and the daemon +builds more keys from them. -- `Host/AquaDaemonClient.cs:20` per note: `patchId = "dings." + instrument.Id`, - `faustName = "dings_" + instrument.Id.Replace('-', '_')`, `revision = 1` (a literal), - `durationSeconds = 1.5f`, `controls["/ding/frequency"]`. +- `Host/AquaDaemonClient.cs:20-21` per note: `var identity = DingCatalog.Identity(instrument)` + gives `patchId = "dings." + id`, `faustName = "dings_" + id with - as _`, `revision = 1` + (a literal inside `Identity`); the same envelope sets `durationSeconds = 1.5f` and + `controls["/ding/frequency"]`. - `src/AquaSynth.Faust/NativeFaustRuntime.cs:596-599`: the compile key is SHA-256 of `"{revision}\n{faustName}\n{script}"`. `patchId` is not in it. So two ids with the same name and script share a compile key; one id with an edited script gets a new key even @@ -84,13 +87,14 @@ itself, and the daemon builds more keys from them. emitted source carry the rewritten name, while the compile key (`:596-599`) hashes the raw `identity.FaustName`. Two raw names that sanitise alike compile alike but key differently. -- The `dings_` rule is written three times: `AquaDaemonClient.cs:20` and - `tools/AquaLower/Program.cs:19`, and - `DingCatalogTests.cs:45` (`LoweredDingsFedToTheFeelMeterMatchTheCatalog` builds the - name with the same expression). Nothing ties the three together except the test. +- The `dings_` rule now lives once, in `DingCatalog.Identity`. `AquaDaemonClient.cs:20` + and `tools/AquaLower/Program.cs:19` call it; `LoweredDingsFedToTheFeelMeterMatchTheCatalog` + compares against a literal per instrument, and `CallersDeriveIdentityOnlyThroughTheCatalog` + fails if either caller stops calling it. (History: at `965dfe8` the rule was written three + times, in those two files and in the test at `DingCatalogTests.cs:45`.) - Writer: the Host (fields) and the daemon (session id, file names). Readers: the daemon's compile/render path and receipts; no Dings code reads the patch id back. -- `Host/AquaDaemonClient.cs:23-28` returns the WAV path from the receipt. The Host +- `Host/AquaDaemonClient.cs:24-29` returns the WAV path from the receipt. The Host never asks the daemon which patch rendered it. ## C. MCP `AgentInstrumentRegistry` @@ -143,7 +147,7 @@ itself, and the daemon builds more keys from them. ids; its comment (`:21`) says values "start from the Dings catalog instruments and were not tuned by ear". The values have drifted from the catalog: - | id | catalog root / decay (`DingCatalog.cs:24-27`) | workshop `rootHz` / `decay` | + | id | catalog root / decay (`DingCatalog.cs:31-34`) | workshop `rootHz` / `decay` | |---|---|---| | warm-bell | 261.6256 / 1.15 | 261.6256 / 0.55 | | glass-chime | 261.6256 / 0.85 | 329.6276 / 0.45 | @@ -177,10 +181,11 @@ itself, and the daemon builds more keys from them. 4. **Same id, different sound.** `warm-bell` is a catalog instrument (A), a workshop identity (E) and the neutral fallback voice (D). Three definitions, parameter sets that have drifted (table above). -5. **Derivation written three times.** `dings_` in `AquaDaemonClient.cs:20`, - `AquaLower/Program.cs:19`, and the test; and the `dings.` patch id appears in - `StoreFileNameTests` as a literal. A rename rule changed in one place breaks - store-file naming in another without a compile error. +5. **Derivation (resolved by step 1 for the code callers).** At `965dfe8` the `dings_` + rule was written three times (`AquaDaemonClient.cs:20`, `AquaLower/Program.cs:19`, the + test). Now it is in `DingCatalog.Identity`. What remains: the `dings.` patch id appears + in `StoreFileNameTests` as a literal, and the test pins literals, so a rename of the rule + fails those tests on purpose rather than silently moving store file names. 6. **Double validation.** `DingService.cs:9-11` and `DingsPlaybackHost.cs:66-68` each decide whether an id is valid. Safe while both read one dictionary. @@ -267,14 +272,14 @@ asked. what a voice is, and also the only place that derives the daemon keys from it. Its instrument gains a content revision (a hash of `Script` plus the parameters that matter), and one function in that assembly produces `PatchId`, `FaustName` and the revision for -the daemon (`AquaLower` and the test need only the faust-name part of it, not +the daemon (`AquaLower` needs only the faust-name part of it, not `patchId` or revision). Everything else keys on the catalog id and takes the rest from the catalog. -End state versus this change: the content revision named above is deferred (step 3 of the migration order). Until it lands, `revision` is the literal 1 and the catalog function returns it; the revision hash is not part of the first consolidation. +End state versus this change: the content revision named above is deferred (step 3 of the Migration plan below). Until it lands, `revision` is the literal 1 and the catalog function returns it; the revision hash is not part of the first consolidation. **What the others become.** - B (Host/daemon): the Host stops composing `patchId`/`faustName`/`revision`; it calls - the catalog function. `AquaLower/Program.cs:19` and `DingCatalogTests.cs:45` call only the faust-name slice of it. The daemon + the catalog function. `AquaLower/Program.cs:19` calls only the faust-name slice of it (done in step 1); the test pins literals instead of calling it. The daemon keeps its session and file naming; those are daemon-internal and derive from what it is given. - C (registry): stays in the bridge as a cache of choices, but its assignment function @@ -294,32 +299,15 @@ End state versus this change: the content revision named above is deferred (step definition of the script, and is the only one the host cannot run without. C, D and E are all consumers or approximations of it by name. -**Migration order** (each step independent and reversible): -1. Add the catalog function; switch `AquaDaemonClient.cs:20` and `AquaLower` onto it; - delete the test's private copy (see the oracle risk below). Pure refactor while - `revision` stays the literal 1: the compile key, and so the session id, stay equal - for unchanged scripts, which is checkable by comparing receipts before and after. -2. Decide the agent-identity question (below); change the registry key. Wire-visible: - existing sessions lose their hashed assignment. -3. Content revision: DEFERRED, not scheduled here. Replacing the literal `revision = 1` - with a catalog hash changes every compile key and session id (and the - `sessions/<...>.cc` file names), so it breaks step 1's equality check by design. It - needs its own decision on what feeds the hash and whether old session files are - left or removed. -4. Remove the duplicate gates in `DingService.cs:9-11` or have the Host's gate be the - single one (the bridge then only forwards). Keep whichever side the tests - (`DingsBridgeTests`) need for fail-fast, but one of them must be the owner. -5. Point the neutral fallback and Earcon Workshop at the catalog. +**Migration order.** One list only: the "Migration plan" section at the end of this note (the original five-item order was merged into it). **Risks.** - Step 2 changes what agents hear on first use after deploy; nobody has listened to a before/after. - The deferred content revision changes session ids and session file names, visible in receipts but not read by anything I found. -- Oracle loss in step 1: deleting the test's private `"dings_" + id` copy makes - `LoweredDingsFedToTheFeelMeterMatchTheCatalog` compare the shared function against - itself. The test should keep an independent expected value (a literal per instrument - or the checked-in `.dsp` header) so a wrong rule still fails. +- Oracle loss in step 1 (handled): the guard test uses a literal per instrument, so it does + not compare the shared function against itself. - Collapsing 8 senders onto 4 instruments would lose distinctness; the proposal does not do that, and I am recommending against it without having listened to either set. - Moving derivation to the catalog assembly makes `AquaSynth.Dings` the home of @@ -347,7 +335,7 @@ what the MCP bridge can learn about its caller. Rules for every step: deprecate before removing (mark the old path with a pointer, keep it working, delete in a later pass after the window); `patchId`, `faustName`, `revision = 1`, session ids, compile keys and `sessions/<...>.cc` names stay byte-identical until step 3; no change to the Host or pipe protocol. Deprecation window: one merged release of the owner path with the old path still working and marked; removal only in a separate PR after the operator hears or reviews nothing regressed. -**Step 1 (done in this change).** `DingCatalog.Identity(instrument)` returns `PatchId`, `FaustName`, `Revision` (literal 1). `AquaDaemonClient` and `AquaLower --dings` call it. The guard test no longer carries a private copy of the rule: it compares against literals per instrument, and `IdentityPinsTheOldDerivedValuesForAllFourInstruments` pins the old derived values for all four. +**Step 1 (done in this change).** `DingCatalog.Identity(instrument)` returns `PatchId`, `FaustName`, `Revision` (literal 1). `AquaDaemonClient` and `AquaLower --dings` call it. The guard test no longer carries a private copy of the rule: it compares against literals per instrument, and `IdentityPinsTheOldDerivedValuesForAllFourInstruments` pins the old derived values for all four. `CallersDeriveIdentityOnlyThroughTheCatalog` reads `AquaDaemonClient.cs` and `AquaLower/Program.cs` and fails if either lacks the `DingCatalog.Identity(` call or reintroduces a `"dings_"` / `$"dings` literal (a source check, not a behaviour check). - Verify: the pin test; `DingCatalogTests` and `StoreFileNameTests`; `AquaLower --dings tools/aqua-feel/lowered-dings` leaves `git status` clean (the checked-in mirror is byte-identical). - Not verified: the Host sending the same JSON to the daemon at runtime (compile-checked and read, not run against a daemon). - Rollback: revert the commit; no stored state or wire format moved. @@ -357,6 +345,6 @@ Rules for every step: deprecate before removing (mark the old path with a pointe **Step 3. Content revision** (replace the literal 1 with a catalog hash). Deliberately breaks byte-identity: compile keys, session ids and `sessions/<...>.cc` names all change. Needs its own ruling on what feeds the hash and whether old session files are left or removed. Verify: receipts before and after, with the old keys listed as expected to change. Rollback: revert to literal 1; new session files stay as orphans, harmless. -**Step 4. One validation gate** (`DingService` versus `DingsPlaybackHost`). Make the Host the owner and let the bridge forward; keep the bridge check as deprecated fail-fast for one window. Verify: `DingsBridgeTests`. Rollback: revert; both gates read one dictionary, so behaviour is the same either way. +**Step 4. One validation gate** (`DingService.cs:9-11` versus `DingsPlaybackHost.cs:66-68`). Make the Host the owner and let the bridge forward (the bridge's check, which `DingsBridgeTests` may need for fail-fast, stays as the deprecated path); keep the bridge check as deprecated fail-fast for one window. Verify: `DingsBridgeTests`. Rollback: revert; both gates read one dictionary, so behaviour is the same either way. **Step 5. Echo sites by reference.** (a) Neutral fallback in `tools/dings-voices/build.mjs` names a catalog instrument id. (b) Earcon Workshop `IDENTITIES`: export the shared ids and root frequencies from the catalog into a checked-in file (as `lowered-dings` is), guarded by a test, and have `earcon.js` read it; the voice-model parameters stay workshop-owned and the drifted values (table in section E) need an owner's decision first. Deprecation: `IDENTITIES` keeps its inline values, marked, until the generated file is read in production. Verify: `tools/earcon-workshop/test.mjs`, the guard test, and an ear check, since the workshop values were never tuned to the catalog. Rollback: revert; the inline values still exist. diff --git a/tests/AquaSynth.Dsl.Tests/DingCatalogTests.cs b/tests/AquaSynth.Dsl.Tests/DingCatalogTests.cs index bd5f555..fcec7e5 100644 --- a/tests/AquaSynth.Dsl.Tests/DingCatalogTests.cs +++ b/tests/AquaSynth.Dsl.Tests/DingCatalogTests.cs @@ -84,6 +84,18 @@ 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); From e3d1a7eeba394d167f6ffb21c01c8e244fc5aba6 Mon Sep 17 00:00:00 2001 From: Aqua Date: Thu, 12 Nov 2026 10:46:34 +0000 Subject: [PATCH 03/19] Dings: one play validation gate (DingCatalog.PlayRejection), Host enforces; bridge check deprecated (migration step 4) Co-Authored-By: Claude Sonnet 5.5 --- docs/dings-patch-identity-authority-map.md | 5 ++++- src/AquaSynth.Dings/DingCatalog.cs | 10 ++++++++++ tests/AquaSynth.Dsl.Tests/DingCatalogTests.cs | 20 +++++++++++++++++++ tests/AquaSynth.Dsl.Tests/DingsBridgeTests.cs | 14 +++++++++++++ tools/AquaSynthDingsHost/DingsPlaybackHost.cs | 6 +++--- tools/AquaSynthDingsMcp/DingService.cs | 3 +++ 6 files changed, 54 insertions(+), 4 deletions(-) diff --git a/docs/dings-patch-identity-authority-map.md b/docs/dings-patch-identity-authority-map.md index b6e70e4..a5e6d29 100644 --- a/docs/dings-patch-identity-authority-map.md +++ b/docs/dings-patch-identity-authority-map.md @@ -345,6 +345,9 @@ Rules for every step: deprecate before removing (mark the old path with a pointe **Step 3. Content revision** (replace the literal 1 with a catalog hash). Deliberately breaks byte-identity: compile keys, session ids and `sessions/<...>.cc` names all change. Needs its own ruling on what feeds the hash and whether old session files are left or removed. Verify: receipts before and after, with the old keys listed as expected to change. Rollback: revert to literal 1; new session files stay as orphans, harmless. -**Step 4. One validation gate** (`DingService.cs:9-11` versus `DingsPlaybackHost.cs:66-68`). Make the Host the owner and let the bridge forward (the bridge's check, which `DingsBridgeTests` may need for fail-fast, stays as the deprecated path); keep the bridge check as deprecated fail-fast for one window. Verify: `DingsBridgeTests`. Rollback: revert; both gates read one dictionary, so behaviour is the same either way. +**Step 4. One validation gate (done in this change).** Finding: both gates already read the same `DingCatalog.Events` / `DingCatalog.Instruments` dictionaries, so the change is the single rule text, not the data. The Host was already the only enforcing gate (every pipe client passes it); the bridge check is a pre-filter that cannot be forwarded away without a visible change (bridge throws `ArgumentException` / `ArgumentOutOfRangeException`, the Host path surfaces as `InvalidOperationException`; the bridge also lets a NaN gain through to the Host's rejection). So: `DingCatalog.PlayRejection(eventId, instrumentId, gain)` is now the one rule and returns the Host's exact rejection text or null; `DingsPlaybackHost.PlayAsync` calls it (same texts, same `rejected` status, same non-finite gain rejection). `DingService.PlayAsync` keeps its own check unchanged, marked DEPRECATED with a pointer comment; remove it only in a separate PR after the window. No protocol change, no identity change, no audible change. +- Verify (ran): `DingCatalogTests` + `DingsBridgeTests` + all `Ding*`/`StoreFileName*` focused tests (79 passed, includes the step-1 identity pins untouched); `dotnet build tools/AquaSynthDingsHost` clean. New tests pin the gate texts (incl. NaN/Infinity), that the Host calls the gate and carries no second copy of the text, and that the deprecated bridge path keeps its exception types, sends nothing to the Host when it rejects, and agrees with the gate's texts. Each was mutation-checked (text change, gate call removed from Host, bridge exception type/text changed, NaN check dropped): each mutation failed at least one test. +- Not verified: the Host rejecting over a live pipe (compile-checked and read; no Host test project exists and none was added); nothing heard. +- Rollback: revert; both gates read one dictionary, so behaviour is the same either way. **Step 5. Echo sites by reference.** (a) Neutral fallback in `tools/dings-voices/build.mjs` names a catalog instrument id. (b) Earcon Workshop `IDENTITIES`: export the shared ids and root frequencies from the catalog into a checked-in file (as `lowered-dings` is), guarded by a test, and have `earcon.js` read it; the voice-model parameters stay workshop-owned and the drifted values (table in section E) need an owner's decision first. Deprecation: `IDENTITIES` keeps its inline values, marked, until the generated file is read in production. Verify: `tools/earcon-workshop/test.mjs`, the guard test, and an ear check, since the workshop values were never tuned to the catalog. Rollback: revert; the inline values still exist. diff --git a/src/AquaSynth.Dings/DingCatalog.cs b/src/AquaSynth.Dings/DingCatalog.cs index 5f1241f..df4659e 100644 --- a/src/AquaSynth.Dings/DingCatalog.cs +++ b/src/AquaSynth.Dings/DingCatalog.cs @@ -13,6 +13,16 @@ public static class DingCatalog public static DingPatchIdentity Identity(DingInstrument instrument) => new($"dings.{instrument.Id}", $"dings_{instrument.Id.Replace('-', '_')}", 1); + /// The play validation gate. The Host is its enforcing owner (every pipe client passes it); the MCP bridge's + /// own check in DingService.PlayAsync is a deprecated fail-fast path. Returns the rejection text, or null when valid. + public static string? PlayRejection(string eventId, string instrumentId, float gain) + { + if (!Events.ContainsKey(eventId)) return $"Unknown event '{eventId}'."; + if (!Instruments.ContainsKey(instrumentId)) return $"Unknown instrument '{instrumentId}'."; + if (!float.IsFinite(gain) || gain is < 0 or > 1) return "Gain must be between 0 and 1."; + return null; + } + public static readonly IReadOnlyDictionary Events = new DingEvent[] { new("session.start", "Opening welcome", [new(0, 0), new(7, 220)]), diff --git a/tests/AquaSynth.Dsl.Tests/DingCatalogTests.cs b/tests/AquaSynth.Dsl.Tests/DingCatalogTests.cs index fcec7e5..c8ffd59 100644 --- a/tests/AquaSynth.Dsl.Tests/DingCatalogTests.cs +++ b/tests/AquaSynth.Dsl.Tests/DingCatalogTests.cs @@ -9,6 +9,26 @@ public sealed class DingCatalogTests public void CuratedInstrumentsStayDistinctAndInsidePleasantnessEnvelope() => Assert.Empty(DingCatalog.ValidateCuration()); + [Fact] + public void PlayRejectionIsTheHostGateWithPinnedTexts() + { + Assert.Null(DingCatalog.PlayRejection("task.complete", "warm-bell", 0)); + Assert.Null(DingCatalog.PlayRejection("task.complete", "warm-bell", 1)); + Assert.Equal("Unknown event 'nope'.", DingCatalog.PlayRejection("nope", "warm-bell", .5f)); + Assert.Equal("Unknown instrument 'nope'.", DingCatalog.PlayRejection("task.complete", "nope", .5f)); + Assert.Equal("Unknown event 'nope'.", DingCatalog.PlayRejection("nope", "nope", 2f)); + foreach (var gain in new[] { -.01f, 1.01f, float.NaN, float.PositiveInfinity }) + Assert.Equal("Gain must be between 0 and 1.", DingCatalog.PlayRejection("task.complete", "warm-bell", gain)); + } + + [Fact] + public void HostCallsTheGateAndOwnsNoSecondCopy() + { + var host = File.ReadAllText(Path.Combine(RepositoryRoot(), "tools", "AquaSynthDingsHost", "DingsPlaybackHost.cs")); + Assert.Contains("DingCatalog.PlayRejection(", host, StringComparison.Ordinal); + Assert.DoesNotContain("Unknown event", host, StringComparison.Ordinal); + } + [Fact] public void MinimalDingsVocabularyIsComplete() { diff --git a/tests/AquaSynth.Dsl.Tests/DingsBridgeTests.cs b/tests/AquaSynth.Dsl.Tests/DingsBridgeTests.cs index 959235d..c46f924 100644 --- a/tests/AquaSynth.Dsl.Tests/DingsBridgeTests.cs +++ b/tests/AquaSynth.Dsl.Tests/DingsBridgeTests.cs @@ -31,6 +31,20 @@ public sealed class DingsBridgeTests Assert.Equal(.7f, host.Commands.Single().Value); } + [Fact] + public async Task DeprecatedBridgeFailFastKeepsItsErrorsAndTextsAgreeWithTheHostGate() + { + var host = new FakeHostClient(); + var service = new DingService(host); + + var badEvent = await Assert.ThrowsAsync(() => service.PlayAsync("nope", "warm-bell", .5f, CancellationToken.None)); + Assert.Equal(DingCatalog.PlayRejection("nope", "warm-bell", .5f), badEvent.Message); + var badInstrument = await Assert.ThrowsAsync(() => service.PlayAsync("task.complete", "nope", .5f, CancellationToken.None)); + Assert.Equal(DingCatalog.PlayRejection("task.complete", "nope", .5f), badInstrument.Message); + await Assert.ThrowsAsync(() => service.PlayAsync("task.complete", "warm-bell", 1.5f, CancellationToken.None)); + Assert.Empty(host.Commands); + } + [Fact] public void BridgeProjectContainsNoAudioOutputOwner() { diff --git a/tools/AquaSynthDingsHost/DingsPlaybackHost.cs b/tools/AquaSynthDingsHost/DingsPlaybackHost.cs index d0ffae3..afd6843 100644 --- a/tools/AquaSynthDingsHost/DingsPlaybackHost.cs +++ b/tools/AquaSynthDingsHost/DingsPlaybackHost.cs @@ -63,9 +63,9 @@ public sealed class DingsPlaybackHost : IAsyncDisposable private async Task PlayAsync(DingsCommand command, CancellationToken cancellationToken) { - if (!DingCatalog.Events.TryGetValue(command.EventId, out var dingEvent)) return Response(false, "rejected", $"Unknown event '{command.EventId}'."); - if (!DingCatalog.Instruments.TryGetValue(command.InstrumentId, out var instrument)) return Response(false, "rejected", $"Unknown instrument '{command.InstrumentId}'."); - if (!float.IsFinite(command.Value) || command.Value is < 0 or > 1) return Response(false, "rejected", "Gain must be between 0 and 1."); + if (DingCatalog.PlayRejection(command.EventId, command.InstrumentId, command.Value) is { } rejection) return Response(false, "rejected", rejection); + var dingEvent = DingCatalog.Events[command.EventId]; + var instrument = DingCatalog.Instruments[command.InstrumentId]; var playbackId = $"ding-{Guid.NewGuid():N}"; foreach (var note in dingEvent.Notes) { diff --git a/tools/AquaSynthDingsMcp/DingService.cs b/tools/AquaSynthDingsMcp/DingService.cs index 4ca715e..6d53486 100644 --- a/tools/AquaSynthDingsMcp/DingService.cs +++ b/tools/AquaSynthDingsMcp/DingService.cs @@ -6,6 +6,9 @@ public sealed class DingService(IDingsHostClient host) { public async Task PlayAsync(string eventId, string instrumentId, float gain, CancellationToken cancellationToken) { + // DEPRECATED fail-fast path: the Host enforces the real gate (DingCatalog.PlayRejection, called by DingsPlaybackHost.PlayAsync). + // Kept for one window because its exception types and the NaN pass-through to the Host's rejection are observable; see + // docs/dings-patch-identity-authority-map.md, Migration plan step 4. Remove only in a separate PR. if (!DingCatalog.Events.TryGetValue(eventId, out var dingEvent)) throw new ArgumentException($"Unknown event '{eventId}'."); if (!DingCatalog.Instruments.TryGetValue(instrumentId, out var instrument)) throw new ArgumentException($"Unknown instrument '{instrumentId}'."); if (gain is < 0 or > 1) throw new ArgumentOutOfRangeException(nameof(gain), "Gain must be between 0 and 1."); From d427f046b5c0f6795f92fa1a53f2a236ff0dd927 Mon Sep 17 00:00:00 2001 From: Aqua Date: Thu, 12 Nov 2026 10:46:57 +0000 Subject: [PATCH 04/19] aqua-trial: isolate the noise-slider kill; LF-normalise the DSP hash on both sides - test.mjs: a failing test no longer aborts the run, so a mutation shows every test that kills it. - New test: the noise slider is live (noise 20 vs 100 differ, rasp-band ratio 0.2 at rpm 4800) while noise 100 stays identical to thruster.dsp. - logic.js dspHash (CRLF folded to LF, then sha-256) is the one normalisation; the page export and analyze.mjs both use it. LF text hashes as before, so old exports stay valid. - Tests: CRLF == LF hash, LF == plain sha-256, analyze CLI raises no foreign-DSP warning for a CRLF checkout. Co-Authored-By: Claude Sonnet 5.5 --- tools/aqua-trial/analyze.mjs | 5 ++-- tools/aqua-trial/logic.js | 4 +++ tools/aqua-trial/test.mjs | 46 ++++++++++++++++++++++++++++++++--- tools/aqua-trial/web/trial.js | 4 +-- 4 files changed, 51 insertions(+), 8 deletions(-) diff --git a/tools/aqua-trial/analyze.mjs b/tools/aqua-trial/analyze.mjs index ba23943..c11d5dd 100644 --- a/tools/aqua-trial/analyze.mjs +++ b/tools/aqua-trial/analyze.mjs @@ -3,10 +3,9 @@ // and whether render peak / rms predicted the ratings. Usage: node analyze.mjs export1.json [export2.json ...] // Pure functions are exported for test.mjs; the CLI runs only when this file is the entry point. import { readFileSync } from "node:fs"; -import { createHash } from "node:crypto"; import { dirname, join } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; -import { rng, shuffle, SCHEMA } from "./logic.js"; +import { rng, shuffle, dspHash, SCHEMA } from "./logic.js"; export const mean = (xs) => xs.reduce((a, b) => a + b, 0) / xs.length; export const sd = (xs) => (xs.length < 2 ? NaN : Math.sqrt(xs.reduce((a, x) => a + (x - mean(xs)) ** 2, 0) / (xs.length - 1))); @@ -102,6 +101,6 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) if (e.schema !== SCHEMA) throw new Error(`${p}: schema ${e.schema}, expected ${SCHEMA}`); return e; }); - const expectedDsp = createHash("sha256").update(readFileSync(join(dirname(fileURLToPath(import.meta.url)), "thruster-trial.dsp"))).digest("hex"); + const expectedDsp = await dspHash(readFileSync(join(dirname(fileURLToPath(import.meta.url)), "thruster-trial.dsp"), "utf8")); console.log(format(analyze(exports, { expectedDsp }))); } diff --git a/tools/aqua-trial/logic.js b/tools/aqua-trial/logic.js index 95ddcb6..20cf589 100644 --- a/tools/aqua-trial/logic.js +++ b/tools/aqua-trial/logic.js @@ -73,6 +73,10 @@ export async function sha256Hex(text) { return [...d].map((b) => b.toString(16).padStart(2, "0")).join(""); } +// The DSP identity an export records and analyze.mjs compares: sha-256 of the source text with CRLF folded to LF, so a CRLF +// checkout of the same DSP hashes the same. LF text hashes exactly as before, so exports made before this stay valid. +export const dspHash = (text) => sha256Hex(String(text).replace(/\r\n/g, "\n")); + // answers: [{ A: {rating, word, time, plays}, B: {...} }] aligned with design. export function buildExport({ seed, design, renders, answers, dspSha256, sampleRate, userAgent, exportedAt }) { if (!/^[0-9a-f]{64}$/.test(dspSha256 ?? "")) throw new Error("export needs the sha-256 of the DSP source that was rendered"); diff --git a/tools/aqua-trial/test.mjs b/tools/aqua-trial/test.mjs index 36167a7..98cbf5d 100644 --- a/tools/aqua-trial/test.mjs +++ b/tools/aqua-trial/test.mjs @@ -5,14 +5,19 @@ import assert from "node:assert/strict"; import { readFileSync } from "node:fs"; import { dirname, join, resolve } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; -import { makeDesign, variants, stats, cleanWord, validRating, buildExport, sha256Hex, renderVariant, rng, shuffle, SCHEMA, PATCH } from "./logic.js"; +import { makeDesign, variants, stats, cleanWord, validRating, buildExport, sha256Hex, dspHash, renderVariant, rng, shuffle, SCHEMA, PATCH } from "./logic.js"; import { analyze, format, mean, sd, spearman, ranks, pearson } from "./analyze.mjs"; const here = dirname(fileURLToPath(import.meta.url)); const dist = resolve(process.argv[2] ?? join(here, "dist")); -const DSP_SHA = await sha256Hex(readFileSync(join(here, "thruster-trial.dsp"), "utf8")); +const DSP_SHA = await dspHash(readFileSync(join(here, "thruster-trial.dsp"), "utf8")); let n = 0; -const t = async (name, fn) => { await fn(); n++; console.log(`ok ${name}`); }; +const failed = []; +// A failing test is reported and the run goes on, so a mutation of the patch shows every test it kills, not only the first. +const t = async (name, fn) => { + try { await fn(); n++; console.log(`ok ${name}`); } + catch (e) { failed.push(name); console.log(`FAIL ${name}\n ${String(e.message).split("\n")[0].slice(0, 200)}`); } +}; await t("design: every unordered pair once, both positions used, replayable from the seed", () => { const d = makeDesign(7); @@ -159,6 +164,31 @@ await t("analyze CLI: runs on export files and rejects a foreign schema", async assert.equal(spawnSync("node", [join(here, "analyze.mjs")]).status, 2); }); +await t("dsp hash: CRLF and LF text hash equal, LF text hashes as plain sha-256 (old exports stay valid), other text differs", async () => { + const lf = readFileSync(join(here, "thruster-trial.dsp"), "utf8").replace(/\r\n/g, "\n"); + assert.equal(await dspHash(lf.replace(/\n/g, "\r\n")), await dspHash(lf)); + assert.equal(await dspHash(lf), await sha256Hex(lf)); + assert.equal(await dspHash(lf), DSP_SHA); + assert.notEqual(await dspHash(lf + " "), await dspHash(lf)); + assert.notEqual(await dspHash("a\nb"), await dspHash("a b")); +}); + +await t("analyze CLI: a CRLF checkout of the same DSP raises no foreign-DSP warning; a changed DSP still does", async () => { + const { execFileSync } = await import("node:child_process"); + const { mkdtempSync, writeFileSync, copyFileSync } = await import("node:fs"); + const { tmpdir } = await import("node:os"); + const lf = readFileSync(join(here, "thruster-trial.dsp"), "utf8"); + const run = (dsp) => { + const d = mkdtempSync(join(tmpdir(), "trial-crlf-")); + for (const f of ["analyze.mjs", "logic.js"]) copyFileSync(join(here, f), join(d, f)); + writeFileSync(join(d, "thruster-trial.dsp"), dsp); + writeFileSync(join(d, "e.json"), JSON.stringify(fakeExport(5, 48000).doc)); + return execFileSync("node", [join(d, "analyze.mjs"), join(d, "e.json")], { encoding: "utf8" }); + }; + assert.doesNotMatch(run(lf.replace(/\n/g, "\r\n")), /WARNING/); + assert.match(run(lf + "// edited\n"), /WARNING/); +}); + // --- the patch, through the runtime the page loads --- const { instantiateFaustModuleFromFile, LibFaust, FaustCompiler, FaustMonoDspGenerator } = await import(pathToFileURL(join(dist, "vendor/faustwasm/index.js")).href); @@ -261,4 +291,14 @@ await t("patch: the noise knob scales rasp and rattle together at rpm 600 (what assert.ok(Math.abs(half / full - 0.5) < 0.05, `half/full ${half / full}`); }); +await t("patch: the noise slider is live: noise 20 differs from noise 100 by the rasp-band ratio 0.2 at rpm 4800, while noise 100 stays identical to thruster.dsp", async () => { + const at = (noise) => renderVariant(trial.g, trial.controls, { params: { rpm: 4800, noise } }, SR, 1); + const [x20, x100, ref] = [await at(20), await at(100), await renderVariant(base.g, base.controls, { params: { rpm: 4800 } }, SR, 1)]; + assert.ok(maxDiffOf(x100, ref) < 1e-6, `noise 100 vs thruster.dsp: ${maxDiffOf(x100, ref)}`); + assert.ok(maxDiffOf(x20, x100) > 1e-2, `noise 20 and noise 100 must render different signals: ${maxDiffOf(x20, x100)}`); + const r = Math.sqrt(highBandEnergy(x20.samples) / highBandEnergy(x100.samples)); + assert.ok(Math.abs(r - 0.2) < 0.03, `rasp band amplitude ratio ${r}, expected 0.2`); +}); + +if (failed.length) { console.log(`${n} passed, ${failed.length} FAILED`); process.exit(1); } console.log(`${n} passed`); diff --git a/tools/aqua-trial/web/trial.js b/tools/aqua-trial/web/trial.js index dec8677..f5d4523 100644 --- a/tools/aqua-trial/web/trial.js +++ b/tools/aqua-trial/web/trial.js @@ -3,7 +3,7 @@ // Nothing here makes a network request after the page assets load, and nothing is written to storage. import { instantiateFaustModuleFromFile, LibFaust, FaustCompiler, FaustMonoDspGenerator } from "./vendor/faustwasm/index.js"; import { controlsOf } from "./ui.js"; -import { variants, makeDesign, renderVariant, cleanWord, validRating, buildExport, sha256Hex, PATCH } from "./logic.js"; +import { variants, makeDesign, renderVariant, cleanWord, validRating, buildExport, dspHash, PATCH } from "./logic.js"; const $ = (s, root = document) => root.querySelector(s); const status = (t) => { $("#status").textContent = t; }; @@ -39,7 +39,7 @@ async function start() { const compiler = new FaustCompiler(new LibFaust(await instantiateFaustModuleFromFile("./vendor/libfaust-wasm/libfaust-wasm.js"))); const g = new FaustMonoDspGenerator(); const dspText = await (await fetch(`./${PATCH}.dsp`)).text(); - dspSha256 = await sha256Hex(dspText); // the exact source compiled, so an export names the DSP that produced it + dspSha256 = await dspHash(dspText); // the exact source compiled, so an export names the DSP that produced it if (!await g.compile(compiler, "thruster_trial", dspText, "-ftz 2")) throw new Error(compiler.getErrorMessage()); const controls = controlsOf(JSON.parse(g.factory.json)); for (const v of variants()) { From 3bd2698d59f6f6c9e37f74547fad060502fd4873 Mon Sep 17 00:00:00 2001 From: Aqua Date: Thu, 12 Nov 2026 10:52:06 +0000 Subject: [PATCH 05/19] Dings step 4 fixes: exact-shape Host gate source check; refresh doc citations and double-validation text Co-Authored-By: Claude Sonnet 5.5 --- docs/dings-patch-identity-authority-map.md | 26 ++++++++++--------- tests/AquaSynth.Dsl.Tests/DingCatalogTests.cs | 12 +++++++-- 2 files changed, 24 insertions(+), 14 deletions(-) diff --git a/docs/dings-patch-identity-authority-map.md b/docs/dings-patch-identity-authority-map.md index a5e6d29..df1bee0 100644 --- a/docs/dings-patch-identity-authority-map.md +++ b/docs/dings-patch-identity-authority-map.md @@ -31,15 +31,15 @@ code. The grouping above follows who writes the key. ## A. `DingCatalog` instrument id and script -- Where: `src/AquaSynth.Dings/DingCatalog.cs:29-35` (four instruments), built by the +- Where: `src/AquaSynth.Dings/DingCatalog.cs:39-45` (four instruments), built by the private `Instrument(...)` at `:56-57`, which writes the `Script` string (an AquaSynth patch script, `param path=...; voice wave=...`, that `FaustEmitter.EmitScript` lowers to Faust; not Faust source) and fixes `RootFrequency = 261.6256f` for all four. - Keys on: the instrument `Id` string (`warm-bell`, `glass-chime`, `soft-triangle`, `muted-pluck`), case-insensitive dictionary (`:35`). Events are a separate keyed dictionary (`:16-27`, nine ids) and are not voice identity. - Lifetime: compiled in. Changing an entry means a new build of every consumer. -- Writer: whoever edits the file. `ValidateCuration` (`:37-54`) is the only gate. -- Readers: `Host/DingsPlaybackHost.cs:66-67`, `Mcp/DingService.cs:9-10`, +- Writer: whoever edits the file. `ValidateCuration` (`:47-64`) is the only gate. +- Readers: `Host/DingsPlaybackHost.cs:66-68` (via `DingCatalog.PlayRejection`, `DingCatalog.cs:17-24`), `Mcp/DingService.cs:12-13`, `Mcp/AgentInstrumentRegistry.cs:11`, `Mcp/DingTools.cs:28,31,49`, `tools/AquaLower/Program.cs:17`, and the tests `DingCatalogTests`. - Content hash: none. The id is a label; the script is the content. Nothing here says @@ -114,10 +114,11 @@ builds more keys from them. observe a reconnect.) - Writer: the agent, through `claim_instrument`, or the hash. Reader: `play_ding` (`DingTools.cs:16`) and `get_agent_instrument` (`:19`). -- Also decides: `DingService.PlayAsync` (`Mcp/DingService.cs:9-11`) re-validates event, - instrument and gain, and the Host validates the same three again - (`DingsPlaybackHost.cs:66-68`). Two gates on one decision; they agree today because - both read `DingCatalog`. +- Also decides: `DingService.PlayAsync` (`Mcp/DingService.cs:12-14`) validates event, + instrument and gain, and the Host validates the same three (`DingsPlaybackHost.cs:66-68`). + Post-step-4 state: the Host owns the gate through `DingCatalog.PlayRejection`; the + bridge copy is the DEPRECATED fail-fast path (see Migration plan, Step 4). They agree + because both read `DingCatalog`. ## D. `tools/dings-voices` sender voices @@ -147,7 +148,7 @@ builds more keys from them. ids; its comment (`:21`) says values "start from the Dings catalog instruments and were not tuned by ear". The values have drifted from the catalog: - | id | catalog root / decay (`DingCatalog.cs:31-34`) | workshop `rootHz` / `decay` | + | id | catalog root / decay (`DingCatalog.cs:41-44`) | workshop `rootHz` / `decay` | |---|---|---| | warm-bell | 261.6256 / 1.15 | 261.6256 / 0.55 | | glass-chime | 261.6256 / 0.85 | 329.6276 / 0.45 | @@ -186,8 +187,9 @@ builds more keys from them. test). Now it is in `DingCatalog.Identity`. What remains: the `dings.` patch id appears in `StoreFileNameTests` as a literal, and the test pins literals, so a rename of the rule fails those tests on purpose rather than silently moving store file names. -6. **Double validation.** `DingService.cs:9-11` and `DingsPlaybackHost.cs:66-68` each - decide whether an id is valid. Safe while both read one dictionary. +6. **Double validation (step 4 done).** The Host owns the gate (`DingsPlaybackHost.cs:66` + calls `DingCatalog.PlayRejection`); `DingService.cs:12-14` is the deprecated bridge + fail-fast copy. Still two checks until the bridge copy is removed; safe while both read one dictionary. ## The Host pipe protocol, as read from source @@ -248,7 +250,7 @@ response `Version` (`:46`). Connect timeout 350 ms; on `TimeoutException` or directory the repo root found by walking up to `AquaSynth.sln`) and retries up to 20 times at 500 ms connect with 100 ms gaps, all inside a 15 s overall timeout. A `Succeeded = false` response is turned into `InvalidOperationException(response.Message)` -by `DingService.EnsureSuccess` (`DingService.cs:22-26`). +by `DingService.EnsureSuccess` (`DingService.cs:25-29`). **MCP side, for completeness.** Tools (`Mcp/DingTools.cs`): `play_ding`, `get_agent_instrument`, `claim_instrument`, `list_ding_events`, `list_instruments`, @@ -346,7 +348,7 @@ Rules for every step: deprecate before removing (mark the old path with a pointe **Step 3. Content revision** (replace the literal 1 with a catalog hash). Deliberately breaks byte-identity: compile keys, session ids and `sessions/<...>.cc` names all change. Needs its own ruling on what feeds the hash and whether old session files are left or removed. Verify: receipts before and after, with the old keys listed as expected to change. Rollback: revert to literal 1; new session files stay as orphans, harmless. **Step 4. One validation gate (done in this change).** Finding: both gates already read the same `DingCatalog.Events` / `DingCatalog.Instruments` dictionaries, so the change is the single rule text, not the data. The Host was already the only enforcing gate (every pipe client passes it); the bridge check is a pre-filter that cannot be forwarded away without a visible change (bridge throws `ArgumentException` / `ArgumentOutOfRangeException`, the Host path surfaces as `InvalidOperationException`; the bridge also lets a NaN gain through to the Host's rejection). So: `DingCatalog.PlayRejection(eventId, instrumentId, gain)` is now the one rule and returns the Host's exact rejection text or null; `DingsPlaybackHost.PlayAsync` calls it (same texts, same `rejected` status, same non-finite gain rejection). `DingService.PlayAsync` keeps its own check unchanged, marked DEPRECATED with a pointer comment; remove it only in a separate PR after the window. No protocol change, no identity change, no audible change. -- Verify (ran): `DingCatalogTests` + `DingsBridgeTests` + all `Ding*`/`StoreFileName*` focused tests (79 passed, includes the step-1 identity pins untouched); `dotnet build tools/AquaSynthDingsHost` clean. New tests pin the gate texts (incl. NaN/Infinity), that the Host calls the gate and carries no second copy of the text, and that the deprecated bridge path keeps its exception types, sends nothing to the Host when it rejects, and agrees with the gate's texts. Each was mutation-checked (text change, gate call removed from Host, bridge exception type/text changed, NaN check dropped): each mutation failed at least one test. +- Verify (ran): `DingCatalogTests` + `DingsBridgeTests` + all `Ding*`/`StoreFileName*` focused tests (79 passed, includes the step-1 identity pins untouched); `dotnet build tools/AquaSynthDingsHost` clean. New tests pin the gate texts (incl. NaN/Infinity), the exact guard statement in the Host source (`PlayRejection(...) is { } x` followed by `return Response(false, "rejected", x)`, comment-stripped; a source-shape check, not a behaviour check, so it cannot see a bypass built some other way), and that the deprecated bridge path keeps its exception types, sends nothing to the Host when it rejects, and agrees with the gate's texts. Each was mutation-checked (text change, gate call removed from Host, bridge exception type/text changed, NaN check dropped): each mutation failed at least one test. - Not verified: the Host rejecting over a live pipe (compile-checked and read; no Host test project exists and none was added); nothing heard. - Rollback: revert; both gates read one dictionary, so behaviour is the same either way. diff --git a/tests/AquaSynth.Dsl.Tests/DingCatalogTests.cs b/tests/AquaSynth.Dsl.Tests/DingCatalogTests.cs index c8ffd59..126b93f 100644 --- a/tests/AquaSynth.Dsl.Tests/DingCatalogTests.cs +++ b/tests/AquaSynth.Dsl.Tests/DingCatalogTests.cs @@ -24,9 +24,17 @@ public sealed class DingCatalogTests [Fact] public void HostCallsTheGateAndOwnsNoSecondCopy() { - var host = File.ReadAllText(Path.Combine(RepositoryRoot(), "tools", "AquaSynthDingsHost", "DingsPlaybackHost.cs")); - Assert.Contains("DingCatalog.PlayRejection(", host, StringComparison.Ordinal); + 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] From 7458fbd93c707e69615afa0917dc07d5088e0d67 Mon Sep 17 00:00:00 2001 From: Aqua Date: Thu, 12 Nov 2026 11:00:00 +0000 Subject: [PATCH 06/19] Dings migration: step 5a ties the neutral fallback id to the catalog mirror; steps 2, 3, 5b recorded as STOPPED with their unblockers Co-Authored-By: Claude Sonnet 5.5 --- docs/dings-patch-identity-authority-map.md | 8 +++++--- tools/dings-voices/README.md | 4 ++-- tools/dings-voices/src/build.mjs | 6 +++--- tools/dings-voices/src/neutral_instrument.test.mjs | 11 +++++++++++ tools/dings-voices/src/voices.mjs | 2 ++ 5 files changed, 23 insertions(+), 8 deletions(-) create mode 100644 tools/dings-voices/src/neutral_instrument.test.mjs diff --git a/docs/dings-patch-identity-authority-map.md b/docs/dings-patch-identity-authority-map.md index df1bee0..78b7b40 100644 --- a/docs/dings-patch-identity-authority-map.md +++ b/docs/dings-patch-identity-authority-map.md @@ -1,5 +1,7 @@ # Dings patch identity: authority map +**Status (2026-11-12).** Done: step 1 (identity from the catalog, `2e28f56`), step 4 (one validation gate, `e188424`), step 5a (neutral fallback id tied to the catalog mirror, this change). Stopped, with the unblock for each in the Migration plan: step 2 (needs the MCP caller-identity fact and a listening), step 3 (needs a ruling that breaks the byte-identity rule), step 5b (needs a generated file, an owner's decision on drifted values and an ear check). + Serves follow-up `aqua-body:follow_up:aquasynth-dings-authority-map`. Claims are from source at `c0fe4ee` (origin/main). Nothing was built or run; the one place behaviour is inferred rather than read is marked. Paths are repo-relative; `Host` = @@ -343,13 +345,13 @@ Rules for every step: deprecate before removing (mark the old path with a pointe - Rollback: revert the commit; no stored state or wire format moved. - Echo sites in this step: the `lowered-dings` mirror is tied to the catalog by `AquaLower` calling `Identity` and stays test-guarded. Earcon Workshop `IDENTITIES` is NOT tied: it is browser JS with its own voice model (`fmRatio`, `harmonics`, seconds-based decay) and shares only ids, so tying needs a generated file and a build step, which is step 5. It is marked deprecated with a pointer, and still works. -**Step 2. Agent identity for the registry** (`AgentInstrumentRegistry` key). Blocked on the open question (what the bridge can learn about its caller). Verify: a test that the same agent id maps to the same instrument across sessions, and listening before and after, which nobody has done. Deprecate: keep the session-id keyed path behind the new key for one release. Rollback: revert; assignments are an in-memory cache. +**Step 2. Agent identity for the registry** (`AgentInstrumentRegistry` key). STOPPED, not implemented. Needs a fact nobody has: what the MCP bridge can learn about its caller. The only identity read in source is `server.SessionId` (`tools/AquaSynthDingsMcp/DingTools.cs:45`); the MCP SDK's client-info fields and the harness configuration were not inspected. It also needs a before/after listening that nobody has done, because a new key changes which instrument an agent hears on first use after deploy. Unblock with: (1) the fact, i.e. whether the MCP SDK / harness exposes a stable agent or client identity to a server tool call (supplied by whoever reads the SDK source or runs the bridge under the harness: Aqua can read the SDK, the harness owner can say what a client sends); (2) a ruling on which field becomes the key; (3) an operator listening of old vs new assignment for the agents in use. Verify: a test that the same agent id maps to the same instrument across sessions, and the listening above. Deprecate: keep the session-id keyed path behind the new key for one release. Rollback: revert; assignments are an in-memory cache. -**Step 3. Content revision** (replace the literal 1 with a catalog hash). Deliberately breaks byte-identity: compile keys, session ids and `sessions/<...>.cc` names all change. Needs its own ruling on what feeds the hash and whether old session files are left or removed. Verify: receipts before and after, with the old keys listed as expected to change. Rollback: revert to literal 1; new session files stay as orphans, harmless. +**Step 3. Content revision** (replace the literal 1 with a catalog hash). STOPPED, not implemented. It deliberately breaks byte-identity: compile keys, session ids and `sessions/<...>.cc` names all change, which is contrary to the standing rule above that they stay byte-identical until this step. So it needs its own ruling before anyone cuts: what feeds the hash (script text only, or events, root frequency and control path too) and whether old session files are left or removed. Unblock with that ruling, from the operator (the migration owner who set the rule); Aqua can draft the options but not choose. Verify: receipts before and after, with the old keys listed as expected to change. Rollback: revert to literal 1; new session files stay as orphans, harmless. **Step 4. One validation gate (done in this change).** Finding: both gates already read the same `DingCatalog.Events` / `DingCatalog.Instruments` dictionaries, so the change is the single rule text, not the data. The Host was already the only enforcing gate (every pipe client passes it); the bridge check is a pre-filter that cannot be forwarded away without a visible change (bridge throws `ArgumentException` / `ArgumentOutOfRangeException`, the Host path surfaces as `InvalidOperationException`; the bridge also lets a NaN gain through to the Host's rejection). So: `DingCatalog.PlayRejection(eventId, instrumentId, gain)` is now the one rule and returns the Host's exact rejection text or null; `DingsPlaybackHost.PlayAsync` calls it (same texts, same `rejected` status, same non-finite gain rejection). `DingService.PlayAsync` keeps its own check unchanged, marked DEPRECATED with a pointer comment; remove it only in a separate PR after the window. No protocol change, no identity change, no audible change. - Verify (ran): `DingCatalogTests` + `DingsBridgeTests` + all `Ding*`/`StoreFileName*` focused tests (79 passed, includes the step-1 identity pins untouched); `dotnet build tools/AquaSynthDingsHost` clean. New tests pin the gate texts (incl. NaN/Infinity), the exact guard statement in the Host source (`PlayRejection(...) is { } x` followed by `return Response(false, "rejected", x)`, comment-stripped; a source-shape check, not a behaviour check, so it cannot see a bypass built some other way), and that the deprecated bridge path keeps its exception types, sends nothing to the Host when it rejects, and agrees with the gate's texts. Each was mutation-checked (text change, gate call removed from Host, bridge exception type/text changed, NaN check dropped): each mutation failed at least one test. - Not verified: the Host rejecting over a live pipe (compile-checked and read; no Host test project exists and none was added); nothing heard. - Rollback: revert; both gates read one dictionary, so behaviour is the same either way. -**Step 5. Echo sites by reference.** (a) Neutral fallback in `tools/dings-voices/build.mjs` names a catalog instrument id. (b) Earcon Workshop `IDENTITIES`: export the shared ids and root frequencies from the catalog into a checked-in file (as `lowered-dings` is), guarded by a test, and have `earcon.js` read it; the voice-model parameters stay workshop-owned and the drifted values (table in section E) need an owner's decision first. Deprecation: `IDENTITIES` keeps its inline values, marked, until the generated file is read in production. Verify: `tools/earcon-workshop/test.mjs`, the guard test, and an ear check, since the workshop values were never tuned to the catalog. Rollback: revert; the inline values still exist. +**Step 5. Echo sites by reference.** (a) DONE in this change. `tools/dings-voices/src/voices.mjs:11` now holds `NEUTRAL_INSTRUMENT_ID = "warm-bell"` (was a literal in `build.mjs`), `build.mjs:13` renders `renderFamily(NEUTRAL_INSTRUMENT_ID)`, and `tools/dings-voices/src/neutral_instrument.test.mjs` asserts the id is one of the `tools/aqua-feel/lowered-dings/*.dsp` names, the checked-in mirror that `AquaLower` generates from `DingCatalog` and `DingCatalogTests.LoweredDingsFedToTheFeelMeterMatchTheCatalog` (`tests/AquaSynth.Dsl.Tests/DingCatalogTests.cs:92`) guards. The constant lives in `voices.mjs` because `build.mjs` writes files on import and cannot be loaded by a test. The test is wired into the `Run` line of `tools/dings-voices/README.md` (dings-voices has no package.json or test runner; `polyphony.test.mjs` is run the same way). Verify (ran): `node src/neutral_instrument.test.mjs` passes (1 assertion file, 2 asserts); changing the id to `bogus-bell` makes it fail with `neutral instrument "bogus-bell" is not a catalog id`; `node src/polyphony.test.mjs` still passes; `node src/build.mjs` writes `neutral-{dm,invite,mention,message}.wav` with identical sha256 before and after (`a3bf9076...`, `4a4652d6...`, `25938d0e...`, `26f1d74a...`). No audible change; nothing heard. Rollback: revert; nothing else reads the constant. (b) STOPPED, not implemented. Intent: export the shared ids and root frequencies from the catalog into a checked-in file (as `lowered-dings` is), guarded by a test, and have `earcon.js` read it. It needs a generated file plus a build step, and the Earcon Workshop is browser JS with its own voice model (`tools/earcon-workshop/web/earcon.js:24`, `IDENTITIES`), so the generator has no existing home. It also needs an owner's decision on the drifted values (table in section E: root 329.6276 vs 261.6256 for glass-chime, 293.6648 vs 261.6256 for muted-pluck; decay is in different units) and an ear check, since the workshop values were never tuned to the catalog. Unblock with: (1) the workshop owner's ruling per drifted value: catalog wins, workshop wins, or the id is dropped from `IDENTITIES`; (2) a ruling on where the generator runs (AquaLower flag or a node script); (3) an operator ear check of the four identities after the change. Deprecation: `IDENTITIES` keeps its inline values, marked, until the generated file is read in production. Verify: `tools/earcon-workshop/test.mjs`, the guard test, and the ear check. Rollback: revert; the inline values still exist. diff --git a/tools/dings-voices/README.md b/tools/dings-voices/README.md index c7bcbca..66e5b10 100644 --- a/tools/dings-voices/README.md +++ b/tools/dings-voices/README.md @@ -6,14 +6,14 @@ Generates eight sender voices (aqua, eureka, heimdall, kiko, libby, nibu, void, - `src/voices.mjs` - the voices and the shared rhythm family (event = rhythm, sender = timbre). Pure JS, deterministic; uses only the sample rate from `../earcon-workshop/web/earcon.js`. - `src/build.mjs ` - renders the 32 clips at unit scale. `src/finish.py ` - equal A-weighted exposure, Ogg encode, decode-back measurement, manifest, `metrics.json` (needs numpy and soundfile with Vorbis). `src/metriclib.py`, `src/measure.py` - measurements (true peak, A-weighted exposure, onset, end-of-clip checks). -- `src/gen_page.py ` - writes `index.html` (no autoplay) from `metrics.json`, `voices.json` and the `inspect_clips.py` output under `findings/`. `src/verify.py [dir]` - checks the files against the limits and manifest schema. `src/inspect_clips.py ` - spectrogram + 1 ms envelope PNGs and onset lists for every Void clip, multi-note checks for Nibu. `src/polyphony.test.mjs` - a clip is the sum of per-note renders and notes do not depend on each other. +- `src/gen_page.py ` - writes `index.html` (no autoplay) from `metrics.json`, `voices.json` and the `inspect_clips.py` output under `findings/`. `src/verify.py [dir]` - checks the files against the limits and manifest schema. `src/inspect_clips.py ` - spectrogram + 1 ms envelope PNGs and onset lists for every Void clip, multi-note checks for Nibu. `src/neutral_instrument.test.mjs` - the neutral fallback's instrument id (`NEUTRAL_INSTRUMENT_ID` in `voices.mjs`) is a `DingCatalog` id present in `tools/aqua-feel/lowered-dings/*.dsp`. `src/polyphony.test.mjs` - a clip is the sum of per-note renders and notes do not depend on each other. - v3: `renderNote` renders each note in its own buffer with its own noise stream; Libby/Kiko notes that something follows end by the next onset and the last rings; Nibu has three no-glide proposals (`NIBU_PROPOSALS`, encoded under `out/proposals/`); Kiko is struck glass; Void's tick is a soft knock. - 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/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`). +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) diff --git a/tools/dings-voices/src/build.mjs b/tools/dings-voices/src/build.mjs index e8d461a..841b3dc 100644 --- a/tools/dings-voices/src/build.mjs +++ b/tools/dings-voices/src/build.mjs @@ -1,16 +1,16 @@ // node build.mjs : render every sender x motif at unit scale to float32 mono WAV (finish.py does loudness, ogg and metrics). import { mkdirSync, writeFileSync } from "node:fs"; import { join } from "node:path"; -import { SENDERS, MOTIFS, renderClip, VOICES, RHYTHM, NIBU_PROPOSALS } from "./voices.mjs"; +import { SENDERS, MOTIFS, renderClip, VOICES, RHYTHM, NIBU_PROPOSALS, NEUTRAL_INSTRUMENT_ID } from "./voices.mjs"; import { SR, renderFamily } from "../../earcon-workshop/web/earcon.js"; const out = process.argv[2]; mkdirSync(out, { recursive: true }); const wav32 = (x) => { const b = Buffer.alloc(44 + x.length * 4); b.write("RIFF", 0); b.writeUInt32LE(36 + x.length * 4, 4); b.write("WAVEfmt ", 8); b.writeUInt32LE(16, 16); b.writeUInt16LE(3, 20); b.writeUInt16LE(1, 22); b.writeUInt32LE(SR, 24); b.writeUInt32LE(SR * 4, 28); b.writeUInt16LE(4, 32); b.writeUInt16LE(32, 34); b.write("data", 36); b.writeUInt32LE(x.length * 4, 40); x.forEach((v, i) => b.writeFloatLE(v, 44 + i * 4)); return b; }; const NAMES = [...SENDERS, ...Object.keys(NIBU_PROPOSALS)]; for (const s of NAMES) for (const m of MOTIFS) writeFileSync(join(out, `${s}-${m}.wav`), wav32(renderClip(s, m))); -// Neutral fallback: the Earcon Workshop warm-bell identity at default sliders (renderFamily peak-normalises the whole family), one event per motif. +// Neutral fallback: the Earcon Workshop identity named by NEUTRAL_INSTRUMENT_ID at default sliders (renderFamily peak-normalises the whole family), one event per motif. // The mapping is provisional and was chosen for distinctness only (it matches the Ratatoskr handoff b3eb9d01); finish.py equalises these to the sender median. export const NEUTRAL_EVENT = { mention: "warning", dm: "waiting", message: "message", invite: "done" }; -const fam = renderFamily("warm-bell"); +const fam = renderFamily(NEUTRAL_INSTRUMENT_ID); for (const m of MOTIFS) writeFileSync(join(out, `neutral-${m}.wav`), wav32(fam.items.find((it) => it.event === NEUTRAL_EVENT[m]).samples)); writeFileSync(join(out, "voices.json"), JSON.stringify({ voices: Object.fromEntries([...SENDERS.map((s) => [s, VOICES[s]]), ...Object.entries(NIBU_PROPOSALS)].map(([s, v]) => [s, { object: v.object, family: v.family, caption: v.caption }])), rhythm: RHYTHM }, null, 1)); console.log(`wrote ${NAMES.length * MOTIFS.length} raw clips and ${MOTIFS.length} neutral clips to ${out}`); diff --git a/tools/dings-voices/src/neutral_instrument.test.mjs b/tools/dings-voices/src/neutral_instrument.test.mjs new file mode 100644 index 0000000..d3459fb --- /dev/null +++ b/tools/dings-voices/src/neutral_instrument.test.mjs @@ -0,0 +1,11 @@ +// node neutral_instrument.test.mjs: the instrument id build.mjs renders for the neutral fallback is a DingCatalog id. +// The catalog's checked-in mirror is tools/aqua-feel/lowered-dings/*.dsp (AquaLower generates it; a dotnet test guards it). +import assert from "node:assert/strict"; +import { readdirSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import { NEUTRAL_INSTRUMENT_ID } from "./voices.mjs"; +const dir = fileURLToPath(new URL("../../aqua-feel/lowered-dings/", import.meta.url)); +const ids = readdirSync(dir).filter((f) => f.endsWith(".dsp")).map((f) => f.slice(0, -4)); +assert.ok(ids.length > 0, `no .dsp files in ${dir}`); +assert.ok(ids.includes(NEUTRAL_INSTRUMENT_ID), `neutral instrument "${NEUTRAL_INSTRUMENT_ID}" is not a catalog id (${ids.join(", ")})`); +console.log(`ok: ${NEUTRAL_INSTRUMENT_ID} in catalog mirror {${ids.join(", ")}}`); diff --git a/tools/dings-voices/src/voices.mjs b/tools/dings-voices/src/voices.mjs index effb869..8bbc567 100644 --- a/tools/dings-voices/src/voices.mjs +++ b/tools/dings-voices/src/voices.mjs @@ -7,6 +7,8 @@ import { SR } from "../../earcon-workshop/web/earcon.js"; const TAU = Math.PI * 2; export const SENDERS = ["aqua", "eureka", "heimdall", "kiko", "libby", "nibu", "void", "weksa"]; export const MOTIFS = ["mention", "dm", "message", "invite"]; +// The DingCatalog instrument id whose Earcon Workshop voice build.mjs renders as the neutral fallback; neutral_instrument.test.mjs ties it to the catalog mirror. +export const NEUTRAL_INSTRUMENT_ID = "warm-bell"; // Shared rhythm family: onset times in ms and a rising scale degree (semitones) per onset. Rhythm tells the event: // mention = one note, message = quick pair, dm = slow pair, invite = long gap then short (an opening, then in). From af0e44f9b6139c726061bca35c0f32464e5493f5 Mon Sep 17 00:00:00 2001 From: Aqua Date: Thu, 12 Nov 2026 16:49:16 +0000 Subject: [PATCH 07/19] Tract: burst gain no longer leaks past its plosive; 14-clip listening kit (#47) Shipped by Aqua (Self) after Soul PASS (aqua-body:follow_up:soul-pr47-verdict-20261112; two Low findings). UNHEARD. Co-Authored-By: Claude Sonnet 5.5 --- .../articulatory-vocal-tract-sources.md | 18 ++- src/AquaSynth.Core/PatchScript.cs | 29 ++++- .../StressAndReleaseRenderTests.cs | 24 ++++ tools/WordRender/Program.cs | 12 +- .../kits/tract-weak-spots/kit.json | 117 ++++++++++++++++++ .../kits/tract-weak-spots/phones/ama.json | 1 + .../kits/tract-weak-spots/phones/ana.json | 1 + .../kits/tract-weak-spots/phones/ba.json | 1 + .../kits/tract-weak-spots/phones/bin.json | 1 + .../kits/tract-weak-spots/phones/bun.json | 1 + .../kits/tract-weak-spots/phones/nibu.json | 1 + .../tract-weak-spots/phones/nibu_flat.json | 1 + .../kits/tract-weak-spots/phones/v_ah.json | 1 + .../kits/tract-weak-spots/phones/v_ah_s.json | 1 + .../kits/tract-weak-spots/phones/v_e.json | 1 + .../kits/tract-weak-spots/phones/v_e_s.json | 1 + .../kits/tract-weak-spots/phones/v_i.json | 1 + .../kits/tract-weak-spots/phones/v_i_s.json | 1 + .../kits/tract-weak-spots/phones/v_ih.json | 1 + .../kits/tract-weak-spots/phones/v_o.json | 1 + .../kits/tract-weak-spots/phones/v_o_s.json | 1 + .../tract-weak-spots/phones/v_oo_short.json | 1 + .../kits/tract-weak-spots/phones/v_u.json | 1 + .../kits/tract-weak-spots/phones/v_u_s.json | 1 + .../kits/tract-weak-spots/render.sh | 29 +++++ tools/formant-check/weak_spots.py | 117 ++++++++++++++++++ 26 files changed, 357 insertions(+), 8 deletions(-) create mode 100644 tools/aqua-listen/kits/tract-weak-spots/kit.json create mode 100644 tools/aqua-listen/kits/tract-weak-spots/phones/ama.json create mode 100644 tools/aqua-listen/kits/tract-weak-spots/phones/ana.json create mode 100644 tools/aqua-listen/kits/tract-weak-spots/phones/ba.json create mode 100644 tools/aqua-listen/kits/tract-weak-spots/phones/bin.json create mode 100644 tools/aqua-listen/kits/tract-weak-spots/phones/bun.json create mode 100644 tools/aqua-listen/kits/tract-weak-spots/phones/nibu.json create mode 100644 tools/aqua-listen/kits/tract-weak-spots/phones/nibu_flat.json create mode 100644 tools/aqua-listen/kits/tract-weak-spots/phones/v_ah.json create mode 100644 tools/aqua-listen/kits/tract-weak-spots/phones/v_ah_s.json create mode 100644 tools/aqua-listen/kits/tract-weak-spots/phones/v_e.json create mode 100644 tools/aqua-listen/kits/tract-weak-spots/phones/v_e_s.json create mode 100644 tools/aqua-listen/kits/tract-weak-spots/phones/v_i.json create mode 100644 tools/aqua-listen/kits/tract-weak-spots/phones/v_i_s.json create mode 100644 tools/aqua-listen/kits/tract-weak-spots/phones/v_ih.json create mode 100644 tools/aqua-listen/kits/tract-weak-spots/phones/v_o.json create mode 100644 tools/aqua-listen/kits/tract-weak-spots/phones/v_o_s.json create mode 100644 tools/aqua-listen/kits/tract-weak-spots/phones/v_oo_short.json create mode 100644 tools/aqua-listen/kits/tract-weak-spots/phones/v_u.json create mode 100644 tools/aqua-listen/kits/tract-weak-spots/phones/v_u_s.json create mode 100755 tools/aqua-listen/kits/tract-weak-spots/render.sh create mode 100644 tools/formant-check/weak_spots.py diff --git a/docs/research/articulatory-vocal-tract-sources.md b/docs/research/articulatory-vocal-tract-sources.md index 61a0f69..b45fdc8 100644 --- a/docs/research/articulatory-vocal-tract-sources.md +++ b/docs/research/articulatory-vocal-tract-sources.md @@ -127,9 +127,23 @@ resolution), release 60-95 ms peak 0.0695, vowel 0.129. The wall radiation reads level of -30 dB; the primary level was not retrieved, and the 2.4 manual's skin radiation, Birkholz & Zhang 2025, is the reference to read). In a vowel the term moves the f0 line by under 1 dB; the 200 and 300 Hz harmonics move up to +1.5 dB on one open vowel (wall-only measurement, Soul pass). The band is two second-order sections, not a brick wall: with the mouth and the velum shut the bar sits about 25 dB down above 300 Hz. The burst itself (difference of renders with and without `release_flow`) peaks at about 0.006-0.008, -24 dB re the vowel peak; the release peak in the table above is the voicing breaking through as the contact opens. Burst gain 0.06 is a DESIGN VALUE. -Weak spots found in the renders: (1) the vowel level is not steady, it rises for about 100 ms after onset (ɑ: rms 0.028 at 80 ms to 0.079 at 160 ms) so any window early in a vowel -reads low; the cause is not isolated (surface smoothing and the pressure ramp are the suspects). (2) /n/ murmur 2 dB above /m/ (above). (3) The voice bar's level is a design value and its band +Weak spots found in the renders, 2026-11-08 (not re-measured on 2026-11-12 unless named in the next paragraph): (1) the vowel level is not steady, it rises for about 100 ms after onset (ɑ: rms 0.028 at 80 ms to 0.079 at 160 ms) so any window early in a vowel +reads low; the cause is not isolated (surface smoothing and the pressure ramp are the suspects). (3) The voice bar's level is a design value and its band (90-300 Hz) assumes f0 of 90 Hz and up. (4) Only f0 and level of the first vowel are checked per cue; the cues' perceptual strength is unknown. Everything here is a measurement, nothing was heard. +Re-measure 2026-11-12 on main c0e6b98 (`tools/formant-check/weak_spots.py` over renders from `tools/aqua-listen/kits/tract-weak-spots/render.sh`; the renders reproduce the table above: /ɪ/ 375/2024 Hz, /ʊ/ 486/894 Hz, murmurs -11.81 and -9.64 dB, /i/ in /nibu/ +0.21 dB). Unheard. +- Stress level (100-170 ms of each vowel, stressed against unstressed, f0 rise split from the rest by a render of the unstressed vowel at 148.4 Hz): total i +1.22, ɑ +1.67, u +2.07, e +2.99, o +1.69 dB (mean 1.93, sd 0.60); + the f0 rise alone -0.80, +0.03, +0.17, +1.23, -0.07 dB; the rest (the amplitude factor 1.30 = 2.28 dB nominal, with the longer vowel) +2.02, +1.64, +1.90, +1.76, +1.76 dB (sd 0.14). The scatter between vowels is the f0 rise; the amplitude cue itself is even. + No level the f0 rise cannot move was found cheap, so the five-vowel-mean basis stands (`aqua-body:question:stress-amplitude-calibration-basis`); the rest sits 0.46 dB under the nominal 2.28 dB, cause not isolated. +- Plosive release: a defect was found and fixed. `release_flow` was held at the burst gain from the plosive's gesture on (a surface holds its first value before its first point and its last after its last), so every later contact state made noise: + the difference of the renders with and without `release_flow` peaked at 0.0302 in the final /n/ and tail of /bɪn/ (above its 0.0226 at the release, 81 ms), 0.0126 in /bʊn/; in /nibu/ (flat) the leading /n/ carried it backward: peak 0.0688, rms 0.0067 against the /n/'s own 0.0058. + After the fix (`BurstGainAroundGesture`: zero before and after the plosive, the gain through it) the same difference is 0.0 from 120 ms after the release and the burst itself is unchanged (0.0226 at 81 ms in /bɪn/). Burst alone, after the fix: /bɪn/ 0.0226 (-15.1 dB re its vowel peak 0.129), /ba/ 0.0142 (-24.0 dB re 0.225), /bʊn/ 0.0130 (-24.3 dB re 0.213), + each falling to a tenth in 15-17 ms; the earlier "0.006-0.008, -24 dB" figure above does not hold for /bɪn/. The release peak of the full render (voicing breaking through) is -5.4, -6.3, -5.9 dB re the vowel peak. Test `PlosiveBurstExistsOnlyAroundItsOwnRelease`. +- Nasals: /m/ -11.81 dB, /n/ -9.64 dB re the flanking vowels, Burg N1 295 and 332 Hz. The 2 dB is not harmonic sampling: /n/ minus /m/ is 2.01, 2.17, 2.05, 1.61 dB at f0 110, 140, 170, 200 Hz. Band levels of the murmur (0-400, 400-800, 800-1600, 1600-3200 Hz): /m/ 36.3, 23.6, 21.3, 2.7; /n/ 38.4, 28.2, 16.8, 0.9 dB. + The cause (the shorter oral side branch, 7.1 cm against 9.6 cm from the velum junction) is a candidate, not shown. Open. +- Lax vowels: /ɪ/ and /ʊ/ are in the DSL table (`StoryVowelAreas`) and render in `WordRender` (/bɪn/, /bʊn/, isolated). Burg F1/F2: /ɪ/ 375/2024 against the tube chain 346/1987 (+8.5/+1.8 %), Hillenbrand 429/2034 (-12.5/-0.5 %), Peterson & Barney 392/1993 (-4.3/+1.5 %); + /ʊ/ 486/894 against 478/850 (+1.7/+5.2 %), 469/1123 (+3.7/-20.4 %), 437/1023 (+11.3/-12.6 %). No defect found. +- Phones the tract cannot make: `WordRender` refuses /t/, /d/, /k/, /l/ with exit 4 (`UNSUPPORTED PHONES (the tract has no gesture for them; nothing rendered): t`); the table holds p b m n s z ʃ ʒ ʍ w and the Story vowels. A direct `phoneme_gesture` on an unknown IPA symbol still falls back to an alveolar approximant (`GestureDescriptor`); not changed here. + Mutations (hand-applied, restored, each run against the named tests): pitch ratio ignored, burst removed, burst not shaped by opening, burst gain x20 (0.06 to 1.2), stress duration ignored, stress pitch ignored, stress amplitude ignored, secondary equal to primary, probe timeline sample rate re-hardcoded to 48000: nine of nine killed. Script: `work/mut-b3.sh` in the aqua workspace. diff --git a/src/AquaSynth.Core/PatchScript.cs b/src/AquaSynth.Core/PatchScript.cs index ff2f3db..2fdea8d 100644 --- a/src/AquaSynth.Core/PatchScript.cs +++ b/src/AquaSynth.Core/PatchScript.cs @@ -1567,8 +1567,10 @@ public static class PatchScript AddAuthoredSpline($"{name}_contact", "/vocal/contacts/0/opening", start, duration, (0, 0.02f), (0.65f, 0.02f), (1, 0.9f)); AddAuthoredSpline($"{name}_stored_pressure", "/vocal/contacts/0/stored_pressure", start, duration, (0, 0.4f), (0.65f, 0.75f), (1, 0.05f)); // The release burst is turbulence at the opening constriction: its gain is held for the plosive and the exporter shapes - // it by the stored pressure and the opening (see PrimitiveContactExpression). - HoldOnSurface($"{name}_release_flow", "/vocal/contacts/0/release_flow", start, duration, PlosiveBurstGain); + // it by the stored pressure and the opening (see PrimitiveContactExpression). The gain exists only around this plosive: + // a surface holds its last value after its last point (and its first before its first), so a gain left at its level + // made noise at every later contact state, the final nasal's closure and the tail included. + BurstGainAroundGesture($"{name}_release_flow", "/vocal/contacts/0/release_flow", start, duration, PlosiveBurstGain); AddAuthoredSpline($"{name}_velum", "/vocal/branches/0/opening", start, duration, (0, VelumClosed), (1, VelumClosed)); } else if (tokens.Contains("fricative")) @@ -1627,6 +1629,29 @@ public static class PatchScript AddAuthoredSpline(name, surfacePath, start, duration, (0, normalized), (1, normalized)); } + // Zero before and after the gesture, the gain through it; the ramps are 0.15 of the gesture long and run into the neighbouring + // phones (the leading one is cut where the word begins). + private void BurstGainAroundGesture(string name, string surfacePath, float start, float duration, float gain) + { + if (!_controlSurfacesByPath.TryGetValue(surfacePath, out var surface) || surface.MaxValue <= surface.MinValue) + { + return; + } + + var level = Math.Clamp((gain - surface.MinValue) / (surface.MaxValue - surface.MinValue), 0, 1); + var handle = duration * 0.25f; + ControlSplinePoint At(float time, float value) => new(time, value, handle, value, handle, value); + var ramp = duration * 0.15f; + var points = new List(); + if (start > 0) points.Add(At(Math.Max(0, start - ramp), 0)); + points.Add(At(start, level)); + points.Add(At(start + duration, level)); + points.Add(At(start + duration + ramp, 0)); + var spline = new ControlSpline(UniqueSplineName(name), surfacePath, points.ToArray(), ControlSplineInterpolation.Bezier); + _controlSplines.Add(spline); + _controlSplinesByName[spline.Name] = spline; + } + private static string GestureDescriptor(string ipa, IReadOnlyDictionary fields) { var explicitDescriptor = GetAny(fields, ["descriptor", "desc", "features"], ""); diff --git a/tests/AquaSynth.Dsl.Tests/StressAndReleaseRenderTests.cs b/tests/AquaSynth.Dsl.Tests/StressAndReleaseRenderTests.cs index bebfa1c..1ea7b08 100644 --- a/tests/AquaSynth.Dsl.Tests/StressAndReleaseRenderTests.cs +++ b/tests/AquaSynth.Dsl.Tests/StressAndReleaseRenderTests.cs @@ -114,6 +114,30 @@ public sealed class StressAndReleaseRenderTests(ITestOutputHelper output) Assert.True(burstPeak < vowelPeak / 2, "the burst stays well under the following vowel's peak (the b level fix)"); } + // The burst is noise whose amplitude is release_flow times the stored pressure through the opening, and release_flow was held at its + // gain from the plosive's gesture on, so it never ended: every later contact state made noise too. In /bin/ the "burst" alone (the + // difference of the renders with and without release_flow) peaked at 0.0302 in the final /n/ and the tail, above its 0.0226 at the + // release itself, and in /nibu/ the leading /n/ and /i/ carried it backward (a spline holds its first value before its first point). + [Fact] + public void PlosiveBurstExistsOnlyAroundItsOwnRelease() + { + IpaGestureExperimentTarget Phone(string label, string ipa, float seconds) => new($"w_{label}", ipa, "", seconds); + var script = IpaGestureExperiment.BuildWordScript( + [(Phone("0_n", "n", 0.095f), 1f), (Phone("1_a", "a", 0.18f), 1f), (Phone("2_b", "b", 0.095f), 1f), (Phone("3_a", "a", 0.18f), 1f), (Phone("4_n", "n", 0.095f), 1f)], 140); + var withBurst = Render(script, 0.77f); + var withoutBurst = Render(script, 0.77f, p => p with { ControlSplines = p.ControlSplines.Where(s => !s.SurfacePath.EndsWith("/release_flow", StringComparison.Ordinal)).ToArray() }); + if (withBurst is null || withoutBurst is null) return; + var burst = withBurst.Zip(withoutBurst, (x, y) => x - y).ToArray(); + const double bFrom = 0.275, bTo = 0.37; + var atRelease = Peak(burst, bFrom + 0.095 * 0.6, bTo + 0.02); + var leading = Peak(burst, 0, bFrom); + var trailing = Peak(burst, bTo + 0.12, 0.77); + output.WriteLine($"burst peak {atRelease:F4} at the release, {leading:F4} before the plosive (n, a), {trailing:F4} after it (a, n, tail)"); + Assert.True(atRelease > 0.004, "the burst is still there at the release"); + Assert.True(leading < atRelease / 20, "no burst noise before the plosive's own gesture"); + Assert.True(trailing < atRelease / 10, "no burst noise in the vowel, the nasal and the tail after the plosive"); + } + // /ɑ C ɑ/ at the scaffold's own durations (vowel 0.18 s, consonant 0.095 s). Returns the render and the consonant's [start, end). private (float[]? Samples, double From, double To) VowelConsonantVowel(string ipa, float frequency = 140) { diff --git a/tools/WordRender/Program.cs b/tools/WordRender/Program.cs index 1b597e2..bfee4d6 100644 --- a/tools/WordRender/Program.cs +++ b/tools/WordRender/Program.cs @@ -8,10 +8,12 @@ using AquaSynth.Faust; // Offline probe: one word, segmented by Weksa (the phones line of `weksa lower --phones`), as a run of IPA gestures on the // IpaGestureExperiment scaffold, rendered through the native libfaust path to a mono 16-bit WAV plus script.aqua, source.dsp // and manifest.json. It measures peak, rms and NaN; it cannot say how the word sounds. -// usage: WordRender