commit 57a1ce5e4ecc647214ab4a9f304750297945795b Author: GAJ3T Date: Mon Oct 26 04:19:46 2026 -0400 Copying Repo to Demo diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..29ef56e --- /dev/null +++ b/.gitignore @@ -0,0 +1,25 @@ +# .NET build, test and publication output +**/[Bb]in/ +**/[Oo]bj/ +**/TestResults/ +**/*.trx +**/*.coverage +**/*.coveragexml +artifacts/ +publish/ + +# IDE and local user state +.vs/ +.vscode/ +.idea/ +*.user +*.suo +*.userosscache +*.sln.docstates +*.DotSettings.user +*.ncrunch* +_NCrunch_*/ + +# Operating system state +Thumbs.db +.DS_Store diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 0000000..c20d103 --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,8 @@ + + + enable + enable + true + true + + diff --git a/Directory.Packages.props b/Directory.Packages.props new file mode 100644 index 0000000..e13cde6 --- /dev/null +++ b/Directory.Packages.props @@ -0,0 +1,11 @@ + + + true + + + + + + + + diff --git a/GAJ3T.MusicGen.RiffGrooveBuilder.slnx b/GAJ3T.MusicGen.RiffGrooveBuilder.slnx new file mode 100644 index 0000000..8138d3a --- /dev/null +++ b/GAJ3T.MusicGen.RiffGrooveBuilder.slnx @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/NuGet.config b/NuGet.config new file mode 100644 index 0000000..4d736c1 --- /dev/null +++ b/NuGet.config @@ -0,0 +1,7 @@ + + + + + + + diff --git a/README.md b/README.md new file mode 100644 index 0000000..1807cb1 --- /dev/null +++ b/README.md @@ -0,0 +1,419 @@ +# GAJ3T.MusicGen.Riff-Groove-Builder + +## Current status: published win-x64 MCP MIDI/fallback slice; application acceptance pending + +A .NET 10 console application for a local, stdio MCP workflow +that turns supported musical descriptions into MIDI. Evidence-backed native +instrument files remain blocked on authorized codecs/fixtures. + +The executable implements UTF-8 newline-delimited JSON-RPC and the +**MCP 2025-11-25** initialization lifecycle, ping, tool discovery/call +infrastructure and per-request cancellation. Its production registry exposes +exactly **`list_instrument_profiles`** and **`generate_project`**. +Generation supports explicit AGLP/AGM/AGT/AME documented Lead profiles and +ABJ **Sustain-only** Bass, with real Standard +MIDI, including honestly reported MIDI fallback for unavailable native writers. +It fails unavailable mappings, missing explicit selections and unsupported ABJ +PalmMute rather than dropping roles or substituting Sustain. Core +provides instrument-neutral exact-rational composition models, validation and +deterministic planning for a documented bounded English subset. +Stdout contains protocol messages only; diagnostics go to stderr. Empty stdin +followed by EOF exits silently. Malformed input now returns explicit errors +instead of being discarded. See [the protocol contract](docs/mcp-protocol.md) +for lifecycle, framing limits, errors and unsupported features. + +There are no HTTP listeners, containers, audio, playback/device APIs, or external +LLM calls. Native AGP/SDP support is not implemented. Five documentation-backed +default mappings exist; no installed plugin or Cubase acceptance is claimed. + +The Release Windows x64 self-contained, single-file executable is available +locally in `artifacts\publish\win-x64`. See [local deployment](docs/local-deployment.md) +for the reproducible publish command, copyable VS Code stdio configuration, +explicit tool/profile arguments, extraction facts and the actual published-RPC +generated `artifacts\examples\ame-lead-example.mid`. Isolated/executable-only +launch and MIDI read-back pass on the SDK machine; a runtime-free Windows host +and all licensed-application/native acceptance remain pending. + +See [the text-description contract](docs/text-description-contract.md) for +accepted grammar, explicit-only role/drum-subset selection, defaults and limits. +In-process callers use `DescriptionParser.Parse` then +`CompositionPlanner.Plan(parsed.Description)`, or `CompositionPlanner.Plan(text)`; +`CompositionValidator.Validate` also checks manually constructed models. +Failures carry actionable diagnostics and no partial composition. Logical +drum voices and articulation intentions do not imply verified product mappings. +The full documented four-bar example spans 15,360 ticks at 960 PPQ with +32 lead notes, four sustained bass notes and 48 drum hits. + +Core also provides generic immutable profile validation and typed MIDI +event-intention planning (`InstrumentProfileValidator.Validate`, +`ArticulationPlanner.Plan`): keyswitch/velocity/CC combinations, explicit state, +shared lead-in, deterministic ordering and complete failure diagnostics. +These are not MIDI files or DryWetMIDI events. Generation has separate embedded +identity and versioned mapping catalogs. `InstrumentCatalog.LoadEmbedded()` +declares seven targets; `InstrumentProfileCatalog.LoadEmbedded().Profiles` is +five `Documented` profiles: four Lead guitars and Sustain-only Ample Bass J. +Synthetic profiles exist only in tests, requiring explicit test-only opt-in. +See [the mapping contract](docs/articulation-mappings.md). Infrastructure tests +do not close full Step 4: AMR/SD3 remain unavailable, ABJ PalmMute is unsupported, and installed-product +mapping/application acceptance remains **unverified**. + +The accepted generic Step 4 infrastructure now feeds Step 5's actual type-1 +MIDI writer, tested with synthetic profiles and actual write/read-back of all +admitted documented profiles. This sequencing does not waive +production mapping, native-format or application acceptance gates. + +## MCP profile discovery and generation + +Initialize the process using MCP `2025-11-25`, send `notifications/initialized`, +then use `tools/list` for the strict input/output schemas. Call +`list_instrument_profiles` with `{}` or `{"role":"lead"}` (`bass`/`drums` also +filter). Discovery returns all matching declared identities, admitted profiles, +source evidence, immutable compatibility notes and actual format capabilities. +Two unmapped identities stay visible; native writers are unavailable and all +application compatibility is unverified. + +Example `tools/call` params (JSON, **not** an executable/CLI generation command): + +```json +{ + "name": "generate_project", + "arguments": { + "description": "palm-muted eighth-note lead", + "outputDirectory": "D:\\MusicGenOutputs", + "projectName": "my-riff", + "formats": ["mid"], + "profiles": { + "lead": "ample-aglp-documented-defaults-2026-10-20" + }, + "fallbackToMidi": false + } +} +``` + +This produces one actual `D:\MusicGenOutputs\my-riff.mid` and `status:"complete"`, +with a source-only Documented compatibility warning. AME can be selected using +`ample-ame-documented-defaults-2026-10-20`. No role has an automatic profile +default. Missing/wrong-role/unavailable mappings and profiles for unselected +roles fail the whole request; the supported grammar is unchanged. + +For an explicitly selected Lead+Bass arrangement, use e.g. +`"description":"palm-muted eighth-note lead and sustained bass"` with +`"profiles":{"lead":"ample-agm-documented-defaults-2026-10-20","bass":"ample-abj-documented-defaults-2026-10-20"}`. +One combined MIDI contains Lead channel 0 and Bass channel 1 with a shared +120-tick lead-in. Each selected role still requires an explicit profile ID. +ABJ exposes Sustain only; `palm-muted bass` fails `unsupported_articulation`. +AMR/SD3 are not substitutes or inferred defaults. + +- Omitted formats mean applicable native formats plus MIDI: Lead-only requests + default to `["agp","mid"]`, not SDP. Explicit inapplicable formats fail. +- `fallbackToMidi` defaults to true. Requesting applicable native output yields + `status:"fallback"` and one combined real `.mid`, with per-target reasons and + warnings. An explicitly requested MIDI file is reused, never duplicated or + renamed `.agp`/`.sdp`. With fallback disabled, native requests fail preflight. + MIDI-only requests work even with fallback disabled. +- Results include interpreted settings/defaults, actual paths/byte counts, + per-role/per-format targets, warnings/errors and 960-PPQ lead-in timing. + MCP text content exactly matches `structuredContent`; `isError` is true only + for failed generation results. Invalid JSON contract arguments use `-32602`. +- Output directories are explicit absolute paths. Safe stems, semantic/profile/ + format preflight and no-overwrite staging protect existing output, including + races. Invalid input, MIDI limits, I/O errors and cancellation are not fallback + triggers. No native placeholder files are written. +- Parsing/planning and synchronous file/library work run off the transport reader. + Pings and cancellation remain responsive. DryWetMIDI serialization itself is + synchronous/non-interruptible; cancellation is checked around it and before + publication. Cancellation racing after publication does not undo the file. + Empty directories created by a failed write may remain; unrelated files and + directories are never recursively removed. +- Keep stdin open until responses arrive. EOF cancels active work; piping an + entire generation conversation and immediately closing stdin is not a reliable + generation client. + +See [the protocol/tool contract](docs/mcp-protocol.md#production-tools-step-8) +for failure fields/codes, exact schemas and scope boundaries. + +### Declared targets and honest mapping availability + +| Instrument ID | Code | Product | Existing role | +| --- | --- | --- | --- | +| `ample-abj` | ABJ | Ample Bass J | Bass | +| `ample-aglp` | AGLP | Ample Guitar LP | Lead | +| `ample-agm` | AGM | Ample Guitar M | Lead | +| `ample-agt` | AGT | Ample Guitar T | Lead | +| `ample-ame` | AME | Ample Metal Eclipse | Lead | +| `ample-amr` | AMR | Ample Metal Ray5 | Bass | +| `toontrack-sd3` | SD3 | Superior Drummer 3 | Drums | + +ABJ, AGLP, AGM, AGT and AME report `profile_available`; AMR and SD3 remain +`mapping_unavailable`. Availability means an admitted Documented or Verified map, +**not** native-format support, plugin installation or application acceptance. +`Documented` means published mapping facts; `Verified` remains application-tested. +Production rejects `Synthetic` and `Unverified`. `Select(role, profileId)` preserves explicit role/profile +selection; `SelectInstrument(role, instrumentId, profileId?)` never substitutes +another instrument and requires a profile ID when multiple versions exist. +Acoustic/electric guitars share the existing Lead slot; no extra roles or patterns. + +To add another target with the existing mechanisms, add a definition to +`Generation\Instruments\instruments.json` and, only after evidence review, its +versioned profiles to `Generation\Profiles\instrument-profiles.json`, bound by +required `instrumentId` and matching product name/role. Rebuild/publish to embed +changes. No product subclass, product switch, planner change, runtime profile +directory or VST scanning/loading is involved. See the mapping contract for +official documentation links, strict data validation and the admission procedure. + +The explicit IDs are `ample-aglp-documented-defaults-2026-10-20`, +`ample-agm-documented-defaults-2026-10-20`, `ample-agt-documented-defaults-2026-10-20`, +`ample-ame-documented-defaults-2026-10-20` and +`ample-abj-documented-defaults-2026-10-20`; none is an automatic role default. +Official non-versioned manuals and vendor demo MIDI anchor Sustain 24/PM 26, +AGLP range 40-86, AGM/AGT 40-84 and AME 36-84. AGLP/AGM/AGT Sustain accepts +musical velocities 1-126, AME 64-126, and PM 1-127. AGT uses the genuine named +A6=105 tab-play anchor, not a direct Sustain/PM performance or guessed label. +The official ABJ/ABP-shared demo anchors ABJ Sustain 24, range 35-76, musical +velocities 1-125; PM and accents 126-127 are rejected. Unsupported layers fail, +never clamp. Shared applicability is vendor-listed, not an ABJ-named performance. +The profiles disclose unknown installed versions separately from source/mapping +revisions. Immutable compatibility notes require default tuning/mapping/velocity +settings, instrument mode and MIDI Guitar mode off. Route Lead channel 0 to the +isolated product, and Bass channel 1 to ABJ. Initial articulation is unknown: explicitly pulse only the +first requested state, avoiding combined Sustain/PM switches. +The 120-tick advance/30-tick pulse at 960 PPQ is a deterministic writer policy, +**not** a certified plugin minimum. Sources, revision hashes, limitations and +the exact missing facts for other targets are in the mapping contract. + +## In-process Standard MIDI generation + +`Generation.Midi.MidiEventBuilder.Build(plannedEvent, cancellationToken)` +translates a typed intention without assigning its absolute tick as a delta. +`MidiFileBuilder.Build(composition, eventPlan, cancellationToken)` validates the +composition/plan agreement and returns a DryWetMIDI `MidiFile`. The writer +reuses that builder; callers need not build a second copy first. + +After explicitly selecting evidence-backed profiles and obtaining a successful +`ArticulationPlanner.Plan` result: + +```csharp +// composition and eventPlan are the matching validated Core results. +MidiFileWriter.WriteFile(absoluteMidiPath, composition, eventPlan, cancellationToken); + +// Alternative: a caller-owned writable stream (also supports non-seekable streams). +using var stream = new MemoryStream(); +MidiFileWriter.Write(stream, composition, eventPlan, cancellationToken); +// stream remains open; position is after the written data. +``` + +These APIs are in `GAJ3T.MusicGen.RiffGrooveBuilder.Generation.Midi`. +There are no usable production profile defaults today; synthetic factories and +uses of the planner's explicit opt-in remain in tests. Neither writer nor server +invents synthetic profiles. +Invalid input/unsupported format values throw actionable exceptions; I/O +failures and cancellation propagate, not successful fallback results. + +Output is SMF **type 1**, **960 PPQ**, with `Conductor` then selected `Lead`, +`Bass`, `Drums` tracks, in that order. Tempo/meter stay at tick zero even with +a shared lead-in. Event channels, absolute pitches, velocities, CCs, explicit +note-offs (release velocity zero) and stable same-tick ordering are preserved. +Every track has exactly one End-of-Track at the plan's global `EndTick`, +including trailing rests and later switch release/reset tails. + +- BPM converts to integer microseconds/quarter by nearest-integer, + midpoint-away-from-zero rounding (`123 BPM -> 487805`, `512 -> 117188`). + The unrounded quotient must be in **1..16777215**, as Core already requires. +- DryWetMIDI **8.0.3** takes the actual denominator, not its exponent. Its byte + API supports powers of two through **128**, verified by read-back. Core-valid + **/256 is rejected clearly**, not wrapped, changed or removed from Core. +- Absolute-to-delta arithmetic is checked. Every gap must fit SMF's four-byte + VLQ, **0..268435455**. Because the conductor has no events between tick zero + and its end marker, global `EndTick` also cannot exceed that value. No filler + events or nonstandard five-byte deltas are inserted. The library itself + accepts larger deltas, so the builder enforces this limit. +- The pinned library creates End-of-Track internally. The builder reads a + library-generated empty track with `EndOfTrackStoringPolicy.Store`, inserts + events before its retained marker, and sets that marker's delta. Read-back + tests also use `Store`; the library's default reader otherwise omits markers. + +`Write` borrows the stream and is **not transactional**: a failed/cancelled call +may leave partial or complete bytes; the caller manages position, rollback and +disposal. `WriteFile` requires an explicit fully qualified destination filename +and an existing parent directory. It creates a uniquely named request-owned +`.riffgroove-*.stage` file beside the destination with `CreateNew`, serializes +and closes it, then moves with **no overwrite**, including late collisions. +It never deletes/replaces a pre-existing destination. Failure/cancellation +removes only its own staging file; cleanup failure throws `AggregateException` +with the original error, cleanup error and remaining staging path. +If serialization/cancellation and stage-stream closing both fail, both errors +are also retained in an aggregate rather than hiding the first error. + +Cancellation is checked through event translation, before/after the library's +synchronous serialization, and before publication. That synchronous library +call is **not interruptible**; cancellation observed afterward prevents file +publication. Publication is the commit point; a token signalled after the final +check/during a successful move does not roll back a completed file. This is +single-file staging, not crash-durability or multi-format transactional output. +The combined multi-track arrangement is **not** a single-track Riffer export, +AGP/SDP serialization, or proof of real plugin/Cubase import compatibility. + +## Prerequisites + +- .NET SDK **10.0.400**, as selected by `global.json`. `latestPatch` permits later + patches in the same SDK feature band, not a different major/minor/feature band. +- Access to the official NuGet feed for the initial dependency restore. +- The initial validation environment is Windows x64. No other deployment target + or runtime-free deployment has been validated. + +If `dotnet` is not on PowerShell's PATH but the standard Windows installation +exists, prepend its directory for the current shell only: + +```powershell +$env:PATH = 'C:\Program Files\dotnet;' + $env:PATH +dotnet --list-sdks +``` + +This does not install or modify machine-wide tooling. + +## Restore, build, and test + +From the repository root: + +```powershell +dotnet restore .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx +dotnet build .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-restore +dotnet publish .\src\GAJ3T.MusicGen.RiffGrooveBuilder.Server\GAJ3T.MusicGen.RiffGrooveBuilder.Server.csproj -p:PublishProfile=win-x64 -o .\artifacts\publish\win-x64 +dotnet test .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-build +dotnet restore .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx --locked-mode +``` + +Keep every project's generated `packages.lock.json` and the server's separate +publication `packages.win-x64.lock.json` in source control. Use +`--locked-mode` when verifying that restored dependencies match those locks. +Package versions are centralized as exact ranges in `Directory.Packages.props`: + +| Package | Version | Use | +| --- | --- | --- | +| Melanchall.DryWetMidi | 8.0.3 | All MIDI construction/serialization and semantic file read-back | +| xunit | 2.9.3 | Tests only | +| xunit.runner.visualstudio | 4.0.1 | Private test adapter | +| Microsoft.NET.Test.Sdk | 18.11.0 | Private test infrastructure | + +These stable versions were checked against official NuGet version indexes and +package manifests. No separate coverage package is referenced; any +`Microsoft.CodeCoverage` lock entry is a transitive dependency of the test SDK. + +To exercise a pre-initialization ping manually from PowerShell: + +```powershell +'{"jsonrpc":"2.0","id":1,"method":"ping"}' | & .\src\GAJ3T.MusicGen.RiffGrooveBuilder.Server\bin\Release\net10.0\GAJ3T.MusicGen.RiffGrooveBuilder.Server.exe +$LASTEXITCODE +``` + +The server returns `{"jsonrpc":"2.0","id":1,"result":{}}`; the subsequent +shell command should print `0`. An empty *stream* has no response; a blank +line is a malformed JSON frame and returns a parse error. + +## Project layout and boundaries + +```text +GAJ3T.MusicGen.RiffGrooveBuilder.slnx +src\ + GAJ3T.MusicGen.RiffGrooveBuilder.Core\ # Dependency-free composition, articulation and generation DTOs + GAJ3T.MusicGen.RiffGrooveBuilder.Generation\ # Text/profile/MIDI service, safe writer and embedded catalogs + GAJ3T.MusicGen.RiffGrooveBuilder.Server\ # Stdio protocol, MCP session and two production tools +tests\ + GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\ # Core + Generation + Server + GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\ # Composition/articulation pipeline + real Server process +docs\ + local-deployment.md + format-compatibility.md + mcp-protocol.md + text-description-contract.md + articulation-mappings.md +prompts\ + plan.md + step_1.md + report_1.md + step_2.md + report_2.md + step_3.md + report_3.md + step_4.md + report_4.md +``` + +All five projects target `net10.0`, use `Microsoft.NET.Sdk`, and inherit nullable +analysis, implicit usings, warnings-as-errors, and package lock-file generation. +Only Server is an executable. + +Unit tests retain compiled .NET 10 assembly/dependency smoke checks, and cover +bounded framing, strict UTF-8, JSON-RPC envelopes/errors/IDs, lifecycle state, +typed synthetic tool schemas/results, overlapping handlers, cancellation, +duplicate active IDs, admission bounds and actual I/O failure propagation. +Synthetic tools exist only in test assemblies, never in the production registry. +Composition units cover rational timing/overflow, grammar, defaults/conflicts, +selected roles, exact patterns, range/extent validation, determinism and the +100,000 combined generated-note/hit limit (including its exact boundary). + +Integration tests launch the actual built Server apphost with redirected +streams, the MCP handshake, malformed input/recovery, UTF-8 and size limits, +LF/CRLF, final non-newline frames, EOF, a bounded timeout, and process-owned +cleanup. A build target copies the Server's complete output next to the tests, +so locating its executable is independent of the test runner's current +directory. Cases run both beside the tests and in an existing unrelated OS +directory (`Environment.SystemDirectory` on Windows), without creating or +modifying files outside the checkout. Output/error streams are drained +concurrently; successful runs require exit code zero, valid JSON-RPC output +lines and empty or explicitly expected diagnostic-only stderr. +Additional in-process integration tests exercise the real Core parser/planner/ +validator pipeline, including all roles, selected subsets, non-4/4 denominator +beats and explicit failures. New subprocess generation tests call the actual +production tools using all five admitted capabilities, including explicit +Lead+Bass arrangements, from an unrelated cwd, reopen +RPC-returned MIDI paths with DryWetMIDI, compare metadata/notes/switches/end +markers, and cover native fallback, invalid requests, missing selected mappings, +no overwrite, cancellation and protocol-only stdout. +Synthetic articulation unit/pipeline tests cover profile validation, keyswitch/ +velocity/CC rules and combinations, state conflicts/transitions, exact timing, +shared multi-role lead-in, event pairing/order, final releases, immutable results, +malformed catalogs, documented admission and truthful partial availability. Data-only test +fixtures prove additional identities and multiple mapping/product versions +through the same selection/planner APIs. Their test `Verified` flags exercise +catalog admission, not real-world verification; fixtures are never shipped. +MIDI unit tests cover metadata rounding/limits, denominator 128/256, VLQ +boundaries, event semantics/order/pairing, borrowed streams, no-overwrite races, +owned-stage cleanup and cancellation. Actual file integration tests reuse the +existing synthetic pipeline profiles: all three roles, selected subsets, 3/8, +1,000 repeated 7/8 bars without drift, rests and later control tails. Files are +written beneath test-owned checkout directories, read with DryWetMIDI and +removed; unrelated-cwd output uses an explicit absolute destination. +Documented-profile tests additionally write/read all five profiles through the +actual MIDI writer, covering first Sustain/PM selection, repeated latches, +transitions and numeric pitch/velocity boundaries without combined/stuck switches. +Actual built and published subprocess RPC tests generate complete Lead+Bass +arrangements and one combined fallback artifact, with no stuck notes or role +substitution. These are source/format checks, not real VST or Cubase runs. + +## Native compatibility evidence required + +See [the compatibility inventory](docs/format-compatibility.md). No exact +installed product versions, native fixtures, template/redistribution permission, +native schemas or import acceptance have been supplied for the six requested +Ample products, Superior Drummer 3, or Cubase. Documentation research now +establishes the five bounded default capabilities above, not installation facts. +Folder screenshots identify requested targets, not installed versions, filesystem +paths or verified maps. Articulations must be verified independently per product. + +Before native writers/application-verified profiles, obtain authorized minimal native +fixtures, exact product/version and SD3 library/map settings, supported extension +and import workflow confirmation, and verified MIDI note/keyswitch/CC/velocity/ +timing/channel/state rules. Later application-level acceptance must record +actual successful plugin and Cubase imports. + +DryWetMIDI's Standard MIDI support is **not** proof of AGP or SDP compatibility. +Requested extensions remain unverified for the owner's exact products, and MIDI +fallback would not satisfy the full native requirement. These evidence gates +block later implementation/acceptance, not generic instrument-neutral planning. +Passing generic Step 4/5 tests does not satisfy the production mapping exit +gate for all requested products. Documented-default source readiness is distinct +from real plugin compatibility; +native implementation and real application acceptance remain blocked/pending. +The supported MIDI/fallback public-tool slice is implemented and published for +Windows x64; runtime-free deployment acceptance is still pending. diff --git a/docs/articulation-mappings.md b/docs/articulation-mappings.md new file mode 100644 index 0000000..8295b27 --- /dev/null +++ b/docs/articulation-mappings.md @@ -0,0 +1,568 @@ +# Instrument profile and event-intention contract + +## Status and evidence boundary + +Correction iteration 4 now admits **five Documented default capabilities**: +AGLP/AGM/AGT/AME Lead Sustain/PalmMute, and ABJ Bass **Sustain only**. +AMR and SD3 remain `mapping_unavailable`; ABJ PalmMute explicitly fails +`unsupported_articulation`, not a guessed PM/Dead Note velocity transform. +Published manuals plus vendor demo MIDI provide genuine numeric anchors; +switch timing/routing are disclosed writer policies, not vendor-certified limits. +`Documented` means source-backed defaults, **not installed-plugin acceptance**. +`Verified` remains the application-verified stage; zero shipped profiles have +that status. `Unverified` and `Synthetic` are rejected in production. +Full requested-product/application readiness remains **false / BLOCKED**. +See [the compatibility inventory](format-compatibility.md). + +## Declared instrument catalog (correction iteration 2) + +The owner requested six Ample targets, plus the existing SD3 target. Immutable +Core `InstrumentDefinition` contains only `id`, string `vendor`, `productCode`, +`displayName`, the existing `role`, and `documentationUrl`. It deliberately has +no fabricated version, playable range, controls or native capabilities. + +| ID | Vendor | Code | Display name | Role | Official documentation | +| --- | --- | --- | --- | --- | --- | +| `ample-abj` | Ample Sound | ABJ | Ample Bass J | Bass | [ABJ manual](https://www.amplesound.net/en/Main_Panel_Manual-ABJ.pdf) | +| `ample-aglp` | Ample Sound | AGLP | Ample Guitar LP | Lead | [AGLP manual](https://www.amplesound.net/en/Main_Panel_Manual-AGLP.pdf) | +| `ample-agm` | Ample Sound | AGM | Ample Guitar M | Lead | [AGM manual](https://www.amplesound.net/en/Main_Panel_Manual-AGM.pdf) | +| `ample-agt` | Ample Sound | AGT | Ample Guitar T | Lead | [AGT manual](https://www.amplesound.net/en/Main_Panel_Manual-AGT.pdf) | +| `ample-ame` | Ample Sound | AME | Ample Metal Eclipse | Lead | [AME manual](https://www.amplesound.net/en/Main_Panel_Manual-AME.pdf) | +| `ample-amr` | Ample Sound | AMR | Ample Metal Ray5 | Bass | [AMR manual](https://www.amplesound.net/en/Main_Panel_Manual-AMR.pdf) | +| `toontrack-sd3` | Toontrack | SD3 | Superior Drummer 3 | Drums | [SD3 manual](https://www.toontrack.com/manual/superior-drummer-3/) | + +Names/manual URLs were confirmed through the official rendered website in the +approved correction. Identities are not proof of installation or mapping. +The owner's folder screenshot establishes neither versions, directory paths nor +maps. Acoustic guitars occupy the existing Lead/guitar slot; no new track roles, +extra slots, strumming patterns or per-product articulation assumptions. + +Generation `InstrumentCatalog.LoadEmbedded()` reads `Instruments\instruments.json` +independently of cwd, ordered by ordinal ID. `Find(id)` uses exact IDs and returns +null when unknown; `ForRole(role)` returns an immutable filtered list, rejecting +undefined roles. IDs/codes must contain only nonempty ASCII letters/digits, +dash/underscore/dot. Vendor/display name must be nonempty, trimmed and free of +control characters. Documentation URLs must be absolute HTTP(S), without +credentials or whitespace. Duplicate IDs and duplicate vendor/code or vendor/name +identities are invalid; versions belong in profiles, not duplicate definitions. + +The profile catalog's immutable joined `Instruments` entries expose `Instrument`, +matching versioned `Profiles`, and derived `Availability`: + +- `mapping_unavailable`: no admitted Documented/Verified mapping exists. +- `profile_available`: at least one admitted Documented/Verified mapping exists. + +Neither status asserts native writer support, installed plugins, supported +extensions, or application/Cubase acceptance. All four guitars and Sustain-only +ABJ are available under the scope below; AMR and SD3 remain unavailable. Step 8 exposes +`list_instrument_profiles` and `generate_project` with this same bounded evidence +scope and explicit selection; native writers and application verification remain absent. + +### Adding another instrument as data + +1. Add a JSON definition with a unique ID and identity to + `Generation\Instruments\instruments.json`, with a real documentation URL and + one existing role. Vendor is data, not a product/vendor enum. +2. After authorized documentation review or actual application verification, + add profiles to `Generation\Profiles\instrument-profiles.json`. Each needs a + unique profile ID, required `instrumentId` referencing the definition, matching + role and exact `productName == displayName`, honest product-version scope, + independent mapping revision, evidence and all mapping fields below. + Documented profiles also require explicit compatibility notes. + Multiple versions share an instrument + ID, not a profile ID. Do not fill mapping gaps with test fixture numbers. +3. Run catalog/profile/planner tests, rebuild and publish: resources are embedded. + There are no runtime directories, hot reload, VST scanning/loading, reflection + plugins or external services. Existing mechanisms need no subclass, product + switch or engine change. New mechanisms still require separately reviewed work. + +Test-only JSON fixtures add extra vendor-neutral targets and two versions for +one target; selection and the unchanged planner consume both. Their invented +`Verified` evidence exercises admission validation only, not application truth. +They live solely in the test assembly. Production still rejects `Synthetic` and +`Unverified` profiles, even when every other field/binding is valid. +Future native writers remain format-based, not per-instrument hierarchies; no +writer implementation or unverified shared Ample native format is implied. + +## Additional evidenced capabilities (correction iteration 4, 2026-10-20) + +All five IDs end in `-documented-defaults-2026-10-20`, with instrument prefixes +`ample-aglp`, `ample-agm`, `ample-agt`, `ample-ame` and `ample-abj`. +No role default is authorized; each selected role requires an explicit ID. + +| New profile prefix | Articulations | Absolute switch/range | Musical velocities | Route | +| --- | --- | --- | --- | --- | +| `ample-agm` | Sustain, PalmMute | 24/26; 40-84 | Sustain 1-126, PM 1-127 | Lead channel 0 | +| `ample-agt` | Sustain, PalmMute | 24/26; 40-84 | Sustain 1-126, PM 1-127 | Lead channel 0 | +| `ample-abj` | **Sustain only** | 24; 35-76 | Sustain 1-125; 126-127 are excluded accents | Bass channel 1 | + +These extend, not alter, the AGLP/AME numeric rules and source records below. +They share unknown-initial-articulation initialization and the explicit +velocity-100/120-tick advance/30-tick pulse writer policy. Source/demo timing +is **not** a certified pulse minimum or latency measurement. Bass channel 1 +(display channel 2) is a project routing policy, not the demo's channel 0. +Default tuning/mapping/velocity thresholds, instrument mode, MIDI Guitar mode +off and an isolated idle receiver remain required. Full installed/application +acceptance is still unverified. + +### AGM: direct numeric switches + +The rendered [official download page](https://www.amplesound.net/en/download.asp) +publicly lists both AGM projects: + +- [AGM-Rylynn.zip](https://www.amplesound.net/dl0822/ds/AGM-Rylynn.zip), + HTTP Last-Modified 2019-06-11 17:57:25 GMT, + SHA256 `e88c40ce4e67fde7b692b7f1cd5c4d057d7cd2a50e21d71114379b55d1fabd6f`. + Entry `AGM-Rylynn/AGM3-Rylynn.mid`, 480 PPQ, zero-based track 1 "G1", + channel 0: note 24/velocity 80 on 32215/off 32335. +- [AGM-Dear_Ben.zip](https://www.amplesound.net/dl0822/ds/AGM-Dear_Ben.zip), + HTTP Last-Modified 2019-11-24 16:38:43 GMT, + SHA256 `bb6dd773b5f998a1d0efa80ebc77d6661922e49f137f74a685000792ed618fe5`. + Entry `AGM-Dear Ben/AGM-Dear Ben Tempo 74.mid`, 480 PPQ, track 1 + "AGM ARP", channel 0: note 26/velocity 80 on 28798/off 28858; + note 24/velocity 80 on 30238/off 30298. + +Together with AGM manual pp.6-7 §§2.2.1-2.2.4 (revision/hash below), these +anchor C0=24, D0=26, E1-C5=40-84; Sustain 1-126 excludes Pop at 127. +PM musical velocity 1-127 controls mute depth without a guessed transformation. + +### ABJ: vendor-listed shared source, deliberately Sustain only + +The official download row explicitly lists products **ABJ ABP** for +[AB-Articulations.zip](https://www.amplesound.net/dl0822/ds/AB-Articulations.zip). +HTTP Last-Modified 2019-06-11 17:32:45 GMT, +SHA256 `c3efc1dc787c59a00be7405687488317efaf952822aededf54b9e19f4e145cb7`. +Entry `AB-Articulations/4.2 Articulations & Poly Legato.mid`, 480 PPQ, +track 1 is named **ABP**, channel 0: note 24/velocity 90 on 3720/off 4080; +musical note 40/velocity 90 on 3840. This is vendor-listed shared applicability, +**not** an independently ABJ-named performance or an inferred AMR mapping. +ABJ manual pp.6-7 §§2.2.1-2.2.4 documents C0, B0-E4 and Sustain 1-125; +the numeric anchor yields switch 24/range 35-76. + +The dedicated D0 PalmMute/Dead Note split still lacks its numeric threshold. +That blocks **PM**, not an otherwise supported Sustain-only capability. +Discovery advertises only Sustain; requested ABJ PM fails explicitly with no +file/partial arrangement. No fixed velocity, Sustain fallback or PM rule is +invented. AMR does not inherit this ABJ/ABP source. + +### AGT: confirmed named tab-play anchor, not a direct articulation performance + +The concrete lead was confirmed in the rendered official +[Tab Player documentation](https://www.amplesound.net/en/tutorial-b.asp), +§6.3 **Tab Play Toggle**: MIDI note **A6** controls tab play (high velocity on, +low velocity off). Retrieved 2026-10-20; no HTTP Last-Modified header; +HTML SHA256 `542ae25caec1dfea772fbe9f5cc80be0c12ad3104f057e654410226aa1e69e92`. +This is the vendor's historical applicable Tab Player documentation, not +a note name supplied by our MIDI library or an assumed octave convention. + +The official download row identifies "Tab Project - Wish You Were Here", +products **AGT AGM**, linking +[AGT-Wish_You_Were_Here.zip](https://www.amplesound.net/dl0822/ds/AGT-Wish_You_Were_Here.zip). +HTTP Last-Modified 2019-06-11 18:04:59 GMT, +SHA256 `82a9b42109519d20d9340c6c6cdb972a66663482df483fd0bf5034b84b5d9262`. +The exact entry is `AGT-Wish_You_Were_Here/AGT3-Wish You Were Here Tempo 62.mid` +(underscores in the directory), 480 PPQ. Tracks 1 "Solo" and 2 "Strum" each +contain only note 105/velocity 80, channel 0, on 3840/off 4320. +Matching that tab-play control to the documented named A6 establishes +`C0 = 105 - (6*12 + 9) = 24`, hence D0=26 and E1-C5=40-84 from the reviewed +AGT main-panel table. This is **not** a direct Sustain/PM performance. +Historical source and non-versioned current main-panel revisions are recorded +separately from an unknown installed release. The generated profile does not +trigger Tab Player or emit note 105. + +All four ZIP MIDI streams were re-read with pinned DryWetMIDI 8.0.3; archives, +MIDI, manuals and other vendor entries were not retained. No helper package, +product installation, native-file inspection or access-control bypass was needed. +AMR has no public demo among the nine inspected official rows; no invented URL, +cross-bass substitution or open-ended search was attempted. SD3 stays unavailable. +Built and refreshed published RPC tests exercise every Lead with ABJ, shared +lead-in, separate channels/tracks, exact notes/controls and one fallback artifact. + +## Documentation-backed defaults (correction iteration 3, 2026-10-20) + +This initial AGLP/AME source record is retained. The newly resolved AGM/AGT/ABJ +anchors above supersede the original inventory's missing-anchor conclusions. + +### Published numeric facts and admitted subset + +| Profile ID | Source mapping | Absolute pitches | Musical velocity constraints | +| --- | --- | --- | --- | +| `ample-aglp-documented-defaults-2026-10-20` | AGLP manual PDF pp.6-7, §§2.2.1, 2.2.3, 2.2.5 | Sustain C0 = 24, PM D0 = 26; E1-D5 = 40-86 | Sustain 1-126 (127 is Pop/Pinch Harmonic depending on settings); PM 1-127, lower velocity increases mute depth | +| `ample-ame-documented-defaults-2026-10-20` | AME manual PDF pp.6-7, §§2.2.1-2.2.4 | Sustain C0 = 24, PM D0 = 26; C1-C5 = 36-84 | Sustain 64-126 only (1-15 full mute, 16-31 three-quarter, 32-63 half; 127 Pop/Pinch Harmonic); PM 1-127, lower velocity increases mute depth | + +Neither conversion starts with an assumed octave convention. The official +[download page](https://www.amplesound.net/en/download.asp), inspected rendered, +links these vendor-authored demo archives (read in memory, not redistributed): + +- [AGLP-Prison_Break.zip](https://www.amplesound.net/dl0822/ds/AGLP-Prison_Break.zip): + HTTP Last-Modified 2019-11-24 16:33:18 GMT; + SHA256 `738956bced4e78a00ab755646d34108f9e25c5346ef79b96a5c1664c876f5e5f`. + `AGLP-Prison Break/AGLP-Prison Break-Tempo100.mid`, 480 PPQ, zero-based + track 1: switch 24, velocity 100, on tick 3837/off 3957; track 3: + switch 26, velocity 100, on 34438/off 34558. These are the actual numeric + C0/D0 anchors for the manual's switch labels. +- [AME-Eclipse.zip](https://www.amplesound.net/dl0822/ds/AME-Eclipse.zip): + HTTP Last-Modified 2019-11-24 17:03:34 GMT; + SHA256 `e448d85f9ff80692f625f23ef6ea4dd0b14367b9f92412adbb76aa6e4a987f66`. + `AME-Eclipse/AME-Eclipse-Tempo130.mid`, 480 PPQ, zero-based track 4: + switch 24, velocity 100, on 3720/off 3840, musical C1 pitch 36 at 3840. + C0=24 anchors the manual's D0 two semitones above (26) and C1-C5 (36-84). + Its `1 Channel` variant also contains switch 24. + +Existing pinned DryWetMIDI 8.0.3 read the demo streams; no parallel MIDI parser, +copied demo, sample library or native content was retained. The public +[third-party Eclipse map](https://github.com/zaibuyidao/ReaScripts/blob/98e88777ff4cf2e478d6bc85d35349f62acc7e41/Various/Articulation%20Map/banks/70-96%20Ample%20Metal%20Eclipse%20%28%E9%87%91%E5%B1%9E%E5%90%89%E4%BB%96%29.reabank) +(blob `ea878807ac429bd7294b9f8a8612a9261feacb4f`) corroborates 24/26 only. +Its implementation and velocity interpretations are not copied or substituted +for vendor evidence. The public Reaticulate Rickenbacker bank also uses 24/26, +but a different product does not establish the missing targets' numeric anchors. + +### Source revisions and remaining gaps + +Retrieved 2026-10-20 from each catalog URL. Manuals are **non-versioned**; HTTP +timestamps/hashes identify source revisions, not installed product versions. +`productVersion` explicitly says documented defaults/installed version unknown; +`mappingVersion` is our `published-defaults-2026-10-20.1` data revision. + +| Manual | HTTP Last-Modified (GMT) | SHA256 | +| --- | --- | --- | +| [ABJ](https://www.amplesound.net/en/Main_Panel_Manual-ABJ.pdf) | 2025-04-16 05:04:25 | `9291c4e3027ac1469bd845bb04614f5a2754bd35a4f017bcfd7cdb75db335e7e` | +| [AGLP](https://www.amplesound.net/en/Main_Panel_Manual-AGLP.pdf) | 2025-09-08 09:00:15 | `7b28b62f3c25ecb774227b15beab06f5e0f0c944f35db9e82121028017f9cedb` | +| [AGM](https://www.amplesound.net/en/Main_Panel_Manual-AGM.pdf) | 2025-09-08 09:00:15 | `449bd7b8bca7771dbf8e08e0029d2bbe999f991efe441d7900ee93da29dd86a4` | +| [AGT](https://www.amplesound.net/en/Main_Panel_Manual-AGT.pdf) | 2025-09-08 09:00:02 | `2e5696d750841a47061d37737ec7d8435cb4e30756cda15596d1f89ff87810dd` | +| [AME](https://www.amplesound.net/en/Main_Panel_Manual-AME.pdf) | 2025-09-08 09:00:39 | `ab482f08b0546eca0a4233b8be3776c411b77f3dca96979f529debc2dfc0c4ca` | +| [AMR](https://www.amplesound.net/en/Main_Panel_Manual-AMR.pdf) | 2025-04-16 05:04:22 | `833115ed9d650d9d7dc0a60695a5405f2dca8cf7f0e3e4b7c7bbf6e0baa65428` | +| [Settings/CPC](https://www.amplesound.net/en/Settings_and_CPCv2.pdf) | 2026-06-16 17:25:14 | `d36c4bed2d24da060588230ea7526b7a08fb9346a8b00d8adb622eaecc36bce3` | + +- ABJ pp.6-7 §§2.2.1-2.2.4: Sustain C0, B0-E4, velocities 1-125; + 126-127 Accent; PM D0, E1-D4, high-velocity PM/low-velocity dead notes, + but **no numeric dividing threshold**. No product-specific absolute anchor + was established in iteration 3. Iteration 4 above resolves the Sustain anchor + using the explicitly shared ABJ/ABP demo; dedicated PM remains unsupported. +- AGM pp.6-7 §§2.2.1-2.2.4 and AGT pp.6-7 §§2.2.1-2.2.4: + Sustain C0/PM D0, both E1-C5; sustain 1-126, 127 Pop; PM depth follows + velocity. No product-specific numeric anchor obtained in this bounded pass. + Iteration 4 above resolves AGM via direct switches and AGT via named A6=105; + shared vendor note labels alone were not used as numeric evidence. +- AMR pp.6-7 §§2.2.1-2.2.4: Sustain C0 A0-E4, 64-126 Sustain/127 Accent, + 32-63 PM/1-31 dead; dedicated PM D0 B0-E4 has an unspecified high/low split. + No product-specific numeric anchor established. The PDF calls itself + "Ample Metal R"; the catalog retains the vendor site's Ray5 identity. + Unavailable; a future supported velocity-only subset still needs that anchor. +- Settings/CPC pp.7-9 §§1.2.2-1.2.9 documents single/per-string channels, + MIDI Guitar mode, configurable velocity thresholds and accent settings; + pp.14-15 §1.5 documents user CC assignments. No standard numeric C0 + anchor or keyswitch pulse minimum was found. These settings constrain scope, + not justify invented CCs or plugin-certified timing. +- [SD3 manual](https://www.toontrack.com/manual/superior-drummer-3/): + simplified fetch **and rendered page** require login; stopped without bypass. + The accessible vendor-hosted + [Example-Layout.pdf](https://www.toontrack.com/app/uploads/topic/how-can-i-use-midi-or-notaion-created-in-notion-6-to-drive-superior-drummer/pdf/Example-Layout.pdf), + page 1, is a rendered SD3 **Hansa - Marble Room** layout, not a documented + universal/core default map. It explicitly shows Kick Open 36, Snare Center + 38, Hi-Hat Closed Tip 42 (and C0=24 in that diagram). HTTP Last-Modified + 2026-03-04 08:25:19 GMT. It is a forum attachment; default-state authorship, + core-library applicability, velocity and controller assumptions are not + established. Public forum search corroborates 36/38/42; visible topic + bodies/replies are login-limited. Do **not** promote this Hansa-specific + example or General MIDI convention into an SD3 core/installed map. SD3 stays + unavailable. Needed: authorized default layout for the chosen library/map, + velocity/hi-hat control scope, and installed configuration/application checks. + +All six official main-panel PDFs and Settings/CPC were consulted, not just +search summaries. Rendered vendor links supplied what simplified fetch omitted. +No products were installed, private directories scanned, credentials requested, +access controls bypassed, or manual/native assets retained. + +### Compatibility policies, not published requirements + +The admitted guitar profiles require default tuning/mapping/velocity thresholds, +instrument (not Strummer) mode, MIDI Guitar mode off, and an isolated idle receiver +with no external held keyswitches or custom remapping. They use no guessed CCs, +program changes or per-string routing. Lead routes on zero-based channel 0 +(display channel 1); the host must route/accept it explicitly. + +At 960 PPQ, use switch velocity 100 (present in vendor examples), **120 ticks +advance/30 ticks pulse**. Advance/pulse are conservative deterministic writer +policies, not measured/certified vendor minimums. They are tempo-relative, +not a promise of real-plugin latency compensation; the 480-PPQ demo timings +are evidence of pulses, not the selected writer timing. Switches release before +musical onset. Unknown initial articulation (`null`) selects **only the first +requested state**, never an unconditional Sustain-plus-PM combination. +Repeated latches suppress duplicates; incompatible overlapping state windows +fail rather than change timing. No final articulation reset is guessed; every +emitted switch is released and the last selection stays latched. + +`DocumentedProfileMidiTests` exercises all five admitted capabilities, first Sustain/PM +where supported (ABJ Sustain only), +numeric pitch/velocity boundaries, repeated latching and transitions through +actual file writing/read-back, checking channels/order/timing/pairing and +source immutability. These are source/format tests, not audible plugin checks. + +## Earlier vendor documentation and screenshot review (2026-10-20) + +The following records the earlier limited review; the anchored subset and +current admission decisions above supersede its former empty-catalog gate. + +The official manual links were discovered through Ample's rendered website and +the PDFs were read locally. The earlier simplified HTML retrieval did not expose +these links; that was a retrieval limitation, not evidence that documentation +was unavailable. Documentation research is the assistant's responsibility; +the owner need not reconstruct published mappings through tooltip screenshots. + +Primary sources: + +- [Ample Metal Eclipse main-panel manual](https://www.amplesound.net/en/Main_Panel_Manual-AME.pdf), + sections 2.2.1-2.2.4 (PDF pages 6-7). +- [Ample Metal Ray5 main-panel manual](https://www.amplesound.net/en/Main_Panel_Manual-AMR.pdf), + sections 2.2.1-2.2.4 (PDF pages 6-7). This is the vendor's documented Ray5 + target; the owner's installed bass identity/version is not yet confirmed. +- [Ample Riffer 4 manual](https://www.amplesound.net/en/Guitar_Riffer.pdf), + section 4.4.3 (PDF page 28). + +Both instrument manuals label Sustain with keyswitch C0 and Palm Mute with D0. +The owner's Eclipse screenshots corroborate those labels and identify the open +instrument as Ample Metal Eclipse. They also show Natural Harmonic C#0, +Slide In/Out D#0, Legato Slide E0, Hammer-On/Pull-Off F0, Tap F#0 and +Pinch Harmonic G0. Recording these labels does not implement extra articulations. + +Eclipse's documented Sustain selection uses note velocities 1-15 for full mute, +16-31 for three-quarter mute, 32-63 for half mute and 64-126 for sustain; +velocity 127 has a settings-dependent accent effect. Palm Mute depth increases +as velocity decreases. The owner's tooltip calls the high-velocity effect +Accent; the manual describes Pop/Pinch Harmonic depending on settings. Do not +assume those version/settings-dependent effects are identical. + +Ray5's documented Sustain selection uses 1-31 for dead notes, 32-63 for palm +mute and 64-126 for sustain, with accent at 127. Its dedicated D0 selection +also distinguishes high-velocity palm mute from low-velocity dead notes, but +the cited paragraph does not give a numeric threshold for that split. + +These are vendor note labels and documented velocity facts, not a verified +conversion of C0 to an absolute MIDI number. The reviewed sections do not +establish all switch velocities, lead times, pulse/hold durations, initial +state or release behavior required by the current profile contract. Do not +fill such fields with invented constants or confuse documented defaults +with verification of the owner's installed configuration. + +Riffer documents SMF type 0/1 import with only one track. A combined multi-role +Cubase MIDI arrangement must therefore not be assumed directly importable into +Riffer. This is a MIDI import capability, not an AGP serialization specification. + +The [SD3 online manual](https://www.toontrack.com/manual/superior-drummer-3/) +still requires login in the available browser session. No account credentials +are needed or requested; selected SD3 library/map and any custom overrides +remain unresolved. Native AGP/SDP schemas and application acceptance remain +separate gates. No production catalog data changed during that earlier review. + +The generic mechanism fixtures are invented **Synthetic** test/pipeline/catalog +identities, not vendor mappings or acceptance evidence. No synthetic profiles +are embedded in production. New documented-profile tests separately exercise +the admitted vendor facts above. Step 8's two MCP tools expose only admitted +production profiles and actual MIDI/fallback output, never synthetic fixtures. + +## In-process boundaries + +- Core `InstrumentProfileValidator.Validate(profile)` rejects unverified and + synthetic profiles by default. `allowSynthetic: true` is an explicit testing + opt-in; it does not bless unverified profiles or bypass other validation. +- Core `ArticulationPlanner.Plan(composition, profiles)` revalidates its input + composition and explicit profiles, returning either a complete immutable + `MidiEventPlan` or diagnostics and a null plan. It never mutates the composition. +- Generation `InstrumentProfileCatalog.LoadEmbedded()` loads only the assembly + resources, cross-validating every profile against the declared identity, role + and exact product name. Dangling references or mismatches fail the whole load. + The stream parsers are internal + and exposed to unit tests only. There is no filesystem/network profile discovery, + vendor scanning, runtime editor or plugin system. +- `catalog.Select(role, id)` requires an exact matching role/ID. A missing ID + reports `no_default_profile`; an unknown ID reports `unknown_profile`, and an + existing wrong-role ID reports `profile_role_mismatch`. No + defaults are currently authorized and there is no synthetic/sustain fallback. +- `catalog.SelectInstrument(role, instrumentId, profileId?)` distinguishes + `unknown_instrument`, `instrument_role_mismatch`, `mapping_unavailable`, + `unknown_profile`, `profile_role_mismatch`, `profile_instrument_mismatch` and + `ambiguous_profile`. A known instrument with one admitted candidate can select + it; multiple candidates require an explicit exact profile ID, never the first + item or another guitar/bass. An explicitly empty profile ID fails as + `no_default_profile`; no instrument/profile defaults are silently substituted. +- A missing, malformed or invalid embedded resource throws `InvalidDataException`, + not a successful empty catalog. JSON uses camel-case property names and string + enums, requires every non-optional constructor field (including explicit nullable fields), + rejects null required values, unknown/duplicate properties and integer enums, + and validates every profile/definition. Composite/numeric roles are invalid. + Legacy profiles can omit optional `compatibilityNotes`; Documented profiles + cannot. Present notes require all four fields; missing/blank/invalid fields + fail instead of acquiring defaults. Documented primary sources must be + absolute public HTTP(S) URLs without credentials. An intentional empty JSON + list is valid; profile enumeration is ordinal by ID. + +Core has no DryWetMIDI dependency. These are typed **event intentions**, not SMF +bytes or MIDI-library objects: `PlannedNoteOn`, `PlannedNoteOff` and +`PlannedControlChange`, with absolute ticks, channel, pitch/velocity or CC +number/value. `IsKeyswitch` distinguishes control notes from musical notes; +`IsReset` distinguishes initialization/release/reset controls. +Step 5 now translates these intentions through DryWetMIDI 8.0.3 in Generation's +`MidiEventBuilder`, `MidiFileBuilder` and `MidiFileWriter`, with actual file +write/read-back tests using the extracted test-only synthetic pipeline profiles. +Core still has no library dependency. No native serialization or public +generation tools exist alongside five documented default capabilities. + +## Profile fields + +| Field | Meaning and constraints | +| --- | --- | +| `id` | Stable nonempty ASCII letters/digits/dash/underscore/dot; catalog IDs unique | +| `instrumentId` | Required stable ASCII ID with the same shape; must reference a declared instrument at catalog admission; no inferred/default binding | +| `role` | Existing `Lead`, `Bass` or `Drums` typed role; exactly one matching profile per selected track | +| `productName`, `productVersion`, `mappingVersion` | Nonempty exact identity, honest version/default scope and independent mapping revision; product name matches the definition display name | +| `evidence` | `status` (`Unverified`, `Verified`, `Synthetic`, `Documented`), nonempty `source`, `authorization`, `verificationRecord`; Documented is cited defaults, Verified is application-verified | +| `compatibilityNotes` | Immutable string record: `versionScope`, `configurationRequirements`, `routingPolicy`, `timingPolicy`; required for Documented, optional for legacy Verified/Synthetic; fields must be nonempty, trimmed, without control characters | +| `minimumPitch`, `maximumPitch` | Inclusive ascending absolute MIDI playable range, 0..127 | +| `channel` | Explicit zero-based MIDI channel, 0..15; independently controlled tracks cannot share a channel | +| `initialArticulation` | Null means unknown receiver articulation, forcing the first requested latched selection; a non-null pitched value declares known resting state and must be supported, never momentary; drums require null | +| `initialControllers` | Complete explicit initial state for all CC numbers used by rules; emitted at tick zero | +| `finalResetArticulation` | Optional explicit latched rule to restore after all musical/control releases; null means no articulation reset | +| `finalControllers` | Optional explicit final CC resets; no undeclared controller or contradiction with a final articulation rule | +| `rules` | Nonempty unique articulation/voice rules, as below | + +Synthetic IDs must begin `synthetic-` and product names `Synthetic `. Constructors +snapshot input lists; profiles, rules, results and event collections are read-only. +Verification status is provenance metadata, not a cryptographic attestation: +editing a status to `Verified` cannot establish real-world correctness. Production +resource changes require evidence review; the five bounded documented +capabilities above do not assert full application compatibility. + +All pitches are absolute numbers. Octave labels never determine switch values. +Every keyswitch must be outside the **entire** playable range, not just absent +from the particular composition. Drum rules map existing logical voices to +distinct absolute playable pitches; no GM/SD3 assumption is made. + +## Rules, velocity and state + +A rule contains typed `articulation`, nullable `voice`/`drumPitch`, `behavior`, +nullable `keyswitch`, a required `velocity` layer and explicit `controllers`. +Pitched rules have null voice/drum pitch. Drum rules have a defined voice and +mapped pitch, using the existing sustain intention (logical hits carry no +separate pitched articulation). Unknown articulations/voices fail explicitly. + +The smallest supported velocity contract is an **inclusive requested-velocity +interval** `minimum..maximum`, inside 1..127. A request outside that interval +fails with `velocity_layer_conflict`; it is never clamped. Null `outputVelocity` +preserves musical dynamics. A non-null output explicitly transforms every valid +requested velocity to that one value, which must itself lie within the interval. +This transformation is visible in the profile and event plan, not a mutation of +the source note/hit. No interpolation, inferred sample layers or randomization. +Different articulations with identical control state need disjoint velocity +intervals. State-free disjoint layers can coexist on different musical pitches. + +For example, **test-only** disjoint layers 1..63 (sustain) and 64..127 (palm mute) +accept their exact boundaries. Sustain at 64 fails. An explicit palm-mute output +of 100 preserves the source requested velocity while emitting 100. + +The supported channel-wide state schemes are deliberately bounded: + +- `None`: no keyswitch/CC actions; velocity-only rules need no global state. +- `Latched`: keyswitch actions are fixed-duration note pulses. State is the + switch **pitch and velocity**, plus the complete CC number/value vector. + Emit changes only when this state differs. A repeated identical articulation + does not repeat the switch or CC. Every rule in a latched scheme must specify + its complete state; if switches are used, sustain also needs an explicit + switch. A declared initial switch state is assumed known, not needlessly + re-triggered (backward-compatible known-state behavior). Null means unknown: + the first requested switch is emitted, without a preliminary sustain switch. + Initial CC state is always emitted explicitly. +- `Momentary`: each musical note re-triggers its switch/CC actions, even for a + repeated articulation. Hold the switch until both the musical note ends and + its configured minimum switch duration has elapsed. Then emit its note-off + and restore the explicitly declared initial CC values. A state-free resting + rule expresses sustain after release; no guessed sustain keyswitch is sent. + +`keyswitch` holds absolute pitch, sounding velocity 1..127, nonnegative +`advanceTicks` and positive `durationTicks`. Timing is exact integer ticks at +960 PPQ. For latched actions duration is the pulse length; for momentary actions +it is the minimum hold measured from switch-on, **including advance**. CC actions +occur at the same activation time as the associated keyswitch, or at the musical +start for CC-only rules. CC numbers/values are 0..127, unique within a state. + +Mixed latched/momentary control schemes on one channel are unsupported. Drum +profiles support voice pitches plus latched/momentary complete CC state; pitched +keyswitch state is not a drum mechanism here. Overlapping momentary requests +are rejected, even for identical state, because retrigger/release ownership +would be ambiguous. There is no channel-per-note workaround. + +## Shared timing, transitions and extent + +The planner computes the largest configured switch advance among **requested +rules on selected tracks**, using one `LeadInTicks` for the whole arrangement. +All musical starts and ends receive that same offset. Controls are scheduled at +`shifted musical start - advance`, never clamped to zero. Unselected profiles/ +unused rules do not increase lead-in. CC initialization alone remains at zero. + +The planner checks overlapping control windows (activation through musical end, +or later minimum hold/pulse end). Conflicting channel-wide states fail with +`conflicting_articulation_state`. Thus a nonzero-advance transition cannot +silently change state during a previous incompatible sustained note: provide +enough gap or a separately verified representable mapping. Identical latched +states can support chords; overlapping identical musical pitches cannot be +paired unambiguously and are rejected. Overlapping switch pulses also cannot +create stuck/re-triggered same-pitch controls. + +Ordering is stable by absolute tick, then priority, retaining deterministic +insertion order for ties: + +1. Musical and switch note-offs (priority 0). +2. Initial/release/reset CCs (priority 1). +3. New CC state and switch note-ons (priority 2, CC vector before switch). +4. Musical note-ons (priority 3). + +At a shared note boundary, releases/resets therefore precede the next state and +musical onset. Final resets are only those explicitly requested by the profile. +They occur after the declared shifted musical extent and any later releases; +a final latched reset pulse includes a matching note-off and can extend the plan. +No unrequested “all notes off” or controller resets are injected. + +`MusicalExtentTicks` is the exact unshifted declared bar extent, including +trailing rests. `MusicalEndTick` adds the shared lead-in. `EndTick` is the maximum +of that end and all required control/release/reset events. Checked Int64 timing +includes advance, note ends and final pulses. Range/timing/profile/state errors +yield no usable partial plan. Pairing validation rejects overlapping pitch +ownership and unpaired note-offs before success. + +## MIDI translation boundary (Step 5) + +The writer accepts a validated composition and its matching event plan, not +instrument names or guessed mappings. It preserves the planner's event order, +absolute pitches, transformed output velocities, channels (including the +synthetic drum channel 9), switches, explicit note-offs and CC state. It does +not reconstruct articulations through a high-level note helper or inject +all-notes-off. SMF cannot retain the internal `IsKeyswitch`/`IsReset` flags; +read-back tests distinguish controls from musical notes using the known plan. + +Type-1 output has a tick-zero conductor, selected role tracks at 960 PPQ and +one End-of-Track per track at the global `EndTick`. Exact metadata, limits, +borrowed streams, safe no-overwrite same-directory staging and cancellation +boundaries are documented in [the MIDI API guide](../README.md#in-process-standard-midi-generation). +DryWetMIDI 8.0.3 supports actual meter denominators through 128; Core-valid /256 +fails explicitly at the writer. Four-byte VLQ gaps are checked before output; +the conductor's end gap bounds global `EndTick` to 268435455 ticks. + +Synthetic format tests are not mapping admission or plugin acceptance. The +combined conductor-plus-role arrangement is not the single-track Riffer import +documented above, and no AGP/SDP or Riffer-specific export is implemented. + +## Remaining production gate + +The five admitted capabilities meet a **documented-default source/format** milestone, +not full requested-target or application compatibility. Obtain the missing +AMR numeric anchor/thresholds and authoritative SD3 library/map scope; ABJ's dedicated +PM threshold is still absent and PM is not advertised. +For application-verified readiness, obtain exact installed product/version/settings for each selected Ample target and SD3; +the actual SD3 library/map/overrides; authorized versioned mapping provenance; +verified playable pitches, switch pitches/velocities, layers, CC combinations, +timing/durations, channel behavior, initial/latch/momentary/reset semantics; and +repeatable real-application verification. Native schemas, lawful fixtures/ +template rights, extension/entity semantics and Cubase/plugin import acceptance +remain separate missing gates. Passing synthetic tests does not satisfy any of +those production evidence requirements. The approved generic Step 5 sequencing +does not authorize guessed production profiles, native writers or public tools. diff --git a/docs/format-compatibility.md b/docs/format-compatibility.md new file mode 100644 index 0000000..203cfd3 --- /dev/null +++ b/docs/format-compatibility.md @@ -0,0 +1,324 @@ +# Format compatibility and evidence inventory + +Inventory updated: 2026-10-20. Baseline: Step 1; current infrastructure: Step 9 +supported-slice win-x64 publication and Step 8 +MCP MIDI/fallback slice plus Step 4 correction iteration 4 capabilities and Step 5 MIDI. + +This is the historical compatibility baseline. Step 2 has since implemented +and tested stdio MCP transport/lifecycle; see [the current protocol +contract](mcp-protocol.md). The two production tools do not change any native +format or installed/application verification status below. + +Step 3 added validated instrument-neutral composition planning. Step 4 now adds +generic profile validation, an embedded mapping catalog and typed +keyswitch/velocity/CC event-intention planning, verified with synthetic test-only +profiles. See [the mapping contract](articulation-mappings.md). +The production mapping catalog now contains **five Documented profiles**: +AGLP/AGM/AGT/AME Lead Sustain/PM and ABJ Bass Sustain only, anchored by official +manuals and vendor demo MIDI. See the +[current source review](articulation-mappings.md#additional-evidenced-capabilities-correction-iteration-4-2026-10-20) +for exact URLs, sections, revision hashes, numeric facts and remaining gaps. +**Documented-default subset readiness is separate from full Step 4/application +readiness, which remains false / BLOCKED.** +Step 5 now adds the actual in-process Standard MIDI builder/writer with +DryWetMIDI 8.0.3 file write/read-back tests using synthetic mappings and all five +admitted documented default profiles. +Step 8 exposes profile discovery and actual MIDI generation/fallback through +MCP. No native writers or actual application imports exist. MIDI format and +RPC-to-file behavior are verified, not installed plugin acceptance. +The historical tables below retain their original evidence scope; “future gate” +does not mean the generic infrastructure itself is absent. + +### Supported-slice publication evidence (Step 9) + +The [local deployment guide](local-deployment.md) records the actual Release +win-x64 self-contained, single-file, untrimmed/non-AOT payload, commands and +copyable stdio client configuration. Twenty-eight focused checks launch isolated +copies of the published payload from an unrelated cwd, discover exactly two +tools/seven identities/five Documented profiles and generate/reopen actual MIDI. +They cover all four Lead profiles and real combined Lead+Bass, native/default fallback, disabled fallback, +unavailable selected roles, collisions, errors, protocol-only stdout, ping, +cancellation and active/empty EOF with owned cleanup. + +An executable-only copy also generated MIDI without source DLL/catalogs or +optional symbol/macOS sidecars. Host tracing identifies self-contained/internal +hostpolicy; the two extracted DLLs match the pinned DryWetMIDI 8.0.3 Windows +native assets. The guide records extraction/cache requirements; no device/ +playback API was used. The locally retained, actual published-RPC-generated +`artifacts\examples\ame-lead-example.mid` is a 371-byte type-1/960-PPQ AME Lead +example with 32 musical notes, switch26 on0/off30, lead-in120/end15480, verified +using DryWetMIDI. It is not a copied vendor fixture or application acceptance. + +This verifies supported-slice packaging on an SDK-equipped Windows x64 host. +**Runtime-free Windows launch remains pending**, as do all licensed Cubase/ +Ample/SD3 import/audible checks, AMR/SD3 mappings, ABJ PM and native Steps 6/7. +Full requested-product readiness remains false/blocked. + +### Current instrument metadata scope + +Correction iteration 2 adds a separate embedded declarative instrument catalog: + +| ID | Code | Product | Existing role | +| --- | --- | --- | --- | +| `ample-abj` | ABJ | Ample Bass J | Bass | +| `ample-aglp` | AGLP | Ample Guitar LP | Lead | +| `ample-agm` | AGM | Ample Guitar M | Lead | +| `ample-agt` | AGT | Ample Guitar T | Lead | +| `ample-ame` | AME | Ample Metal Eclipse | Lead | +| `ample-amr` | AMR | Ample Metal Ray5 | Bass | +| `toontrack-sd3` | SD3 | Superior Drummer 3 | Drums | + +The [mapping contract](articulation-mappings.md#declared-instrument-catalog-correction-iteration-2) +records vendor/manual URLs, strict validation and the data-only admission steps. +There are **seven declared identities, five Documented profiles and zero +application-Verified profiles**. ABJ/AGLP/AGM/AGT/AME report `profile_available`; +AMR and SD3 remain `mapping_unavailable`. `profile_available` means +an admitted mapping, not native-format compatibility or installed/application +acceptance. Definitions have no fabricated versions, switches or capabilities. +Profiles bind required `instrumentId` plus matching role/product identity. +Additional existing-mechanism instruments require JSON definitions and authorized +profiles, followed by rebuild/publish, not engine subclasses or product switches. +No runtime profile/VST discovery/loading is added. MCP discovery exposes this +embedded catalog without scanning installations. + +The folder screenshot is not version, path or map evidence. Each product's +articulations/settings need independent verification; acoustic/electric guitars +share the Lead slot without new patterns/roles. Missing mappings block full Step 4 +production readiness, **not** this metadata/catalog extension. + +No owner-created native fixture, exact installed-version confirmation, or +native template permission record has been supplied in this repository. +The owner's screenshots identify Ample Metal Eclipse and expose articulation +labels and velocity behavior. Public vendor manuals have now been consulted; +they are sources for documented defaults, not proof of installed custom settings. +No vendor products were installed, personal directories searched, or licensed +sample content copied. No proprietary schema is implemented. Only the five +bounded documented-default capabilities are admitted; installed configurations remain unknown. + +### Documentation-backed mapping scope (correction iteration 4) + +- `Documented` is a distinct source-backed stage, not `Verified` application + acceptance. Both stages are admissible; `Unverified`/`Synthetic` are rejected. + Existing serialized profiles can omit optional compatibility notes, but + Documented profiles require nonempty validated immutable version scope, + configuration requirements, routing policy and timing policy. Source/mapping + revision is explicitly separate from unknown installed product version. +- AGLP: Sustain 24, PM 26, range 40-86; Sustain musical velocities 1-126. + AME: Sustain 24, PM 26, range 36-84; Sustain 64-126. + AGM/AGT: Sustain 24, PM 26, range 40-84, Sustain 1-126. All guitar PM preserves + 1-127. ABJ: Sustain only, switch 24/range 35-76/velocities 1-125. + AGM uses direct demo switches; AGT's official named A6 tab-play control plus + note 105 in the explicitly AGT/AGM-shared tab demo supplies its numeric anchor, + not a direct Sustain/PM performance. ABJ uses the explicitly vendor-listed + ABJ/ABP shared demo; its track is named ABP, not a separate ABJ performance. + No anchor is based on assumed C0 octave naming. +- Default tuning/mapping/thresholds, instrument mode, MIDI Guitar mode off, + idle isolated receiver, Lead channel 0 and ABJ Bass channel 1 routing are explicit requirements. + Initial articulation is unknown; first requested state is selected alone. + Switch velocity 100 occurs in vendor examples; advance 120/pulse 30 ticks at + 960 PPQ is our deterministic policy, **not** a vendor timing guarantee. + Pairing/order/transitions/boundaries are verified through actual MIDI file + write/read-back; no real plugin, VST host, audible articulation or Cubase + import test was run. Native-format readiness is unaffected. +- ABJ's missing dedicated PM/Dead Note threshold blocks PM, NOT its supported + Sustain-only profile. PM requests explicitly fail without a file or silent + Sustain replacement. AMR still lacks its own absolute anchor; ABJ/ABP + applicability is not extended to AMR. + SD3's manual requires login through both fetch/rendered retrieval; the + accessible Hansa - Marble Room example shows 36/38/42 but is not evidence + of a universal/core default library map or its velocity/hi-hat control scope. + AMR and SD3 stay unavailable. The source review records exact facts/limits. + +**Status meanings:** VERIFIED (planning/toolchain) means the cited public +documentation or local inspection supports only that statement. MISSING means +evidence was not supplied. NOT PERFORMED means no actual application/deployment +check was carried out. Neither missing evidence nor successful compilation is +proof of native compatibility. + +Step numbers below refer to `prompts\plan.md`: 2 protocol; 4 production +profiles/articulations; 5 generic MIDI (accepted infrastructure plus synthetic +format tests, not completed production mapping admission); 6 Ample native +writer; 7 SD3 native writer; 9 deployment/application acceptance. Outstanding +production gates are not Step 1 scaffold failures. + +### Standard MIDI format evidence (Step 5) + +Actual generated `.mid` files are reopened with the pinned library and checked +for type 1, 960 PPQ, tick-zero tempo/meter, conductor plus selected named role +tracks, exact channels/pitches/velocities/CCs/note-offs and stable order/pairing. +The complete synthetic example has 175 channel events, 32/4/48 musical notes, +two switch pairs, and four end markers at tick 15600 (15360 plus shared 240). +Additional file tests cover role subsets, 3/8, 1,000 repeated 7/8 bars, rests, +momentary releases and final reset tails, unrelated cwd and safe no-overwrite. + +Local XML/reflection plus serialization/read-back establish these pinned facts: + +- `TimeSignatureEvent(byte, byte)` takes the denominator itself; /128 round-trips. + The byte API cannot represent Core-valid /256: the writer fails explicitly. +- Tempo is integer microseconds/quarter, nearest-integer with midpoint away from + zero (120 -> 500000; 123 -> 487805; 512 -> 117188). Core's unrounded range + 1..16777215 remains unchanged. +- Library event deltas are Int64 and serialization itself accepts >0x0FFFFFFF. + The builder instead checks four-byte SMF VLQs and rejects larger gaps, + including the conductor's global end gap, without filler events. +- End-of-Track has no public constructor; the library writes it automatically. + The builder retains one from a library-generated empty-track read using + `EndOfTrackStoringPolicy.Store`, inserts events before it and sets its delta. + Tests confirm exactly one end marker per track at the full planned end. + +See [the MIDI API guide](../README.md#in-process-standard-midi-generation) for +stream ownership, single-file staging, cleanup and cancellation boundaries. +The multi-track arrangement is not a Riffer single-track export or AGP/SDP +serialization. Format-writer readiness does not close any production/native/ +Cubase gate below; AMR/SD3 remain unavailable and all five admitted +Documented mappings still lack installed/application acceptance. + +### MCP generation/fallback evidence (Step 8) + +Production advertises exactly `list_instrument_profiles` and `generate_project`. +Real subprocess tests initialize/discover/call the tools from an unrelated cwd, +select explicit AGLP/AGM/AGT/AME and ABJ Documented profiles, obtain actual MIDI paths/byte counts, +and reopen files with DryWetMIDI. The default four-bar PM eighth-note Lead case +is type 1/960 PPQ with Conductor/Lead, 120 BPM/4-4 metadata, 32 pitch-64 velocity-96 +notes, one PM26/100 switch pair at ticks 0/30, shared lead-in 120 and end 15480. +Every target and source-only compatibility warning survives the RPC wrapper. +Lead+Bass cases add Bass channel 1, four pitch-40 velocity-96 sustained notes, +Sustain24/100 on0/off30 and a third track/end marker; Lead stays on channel 0 +with the same shared 120-tick lead-in and 15480 end. Complete and native-fallback +cases retain both roles in exactly one artifact. ABJ PM is explicitly rejected. + +AGP-only, AGP+MIDI and omitted Lead formats produce one real combined `.mid` +with `status:"fallback"`, not a native placeholder; MIDI-only is `complete`, +including fallback disabled. Native requests with fallback disabled fail before +output. Missing explicit Bass selection (`no_default_profile`), unmapped Drums +(`mapping_unavailable`), unsupported ABJ PM, wrong/unselected profiles, inapplicable +formats, unsupported text/MIDI limits, unsafe paths, collisions, I/O and +cancellation do not become successful fallback. Synchronous work is off the +reader; ping/cancellation responsiveness is tested with deterministic blocking. +Read-back validates file semantics only. No application acceptance, native +codec, new mapping, native extension substitution, publishing or deployment +readiness is established by Step 8. + +## Public planning facts versus native compatibility + +| Item | Status | Evidence/source | Required evidence or limitation | Future gate | +| --- | --- | --- | --- | --- | +| MCP stdio framing | VERIFIED (planning) | [MCP 2025-11-25 transport specification][mcp], rechecked during Step 1: UTF-8 JSON-RPC, newline-delimited (not LSP `Content-Length` framing), no non-protocol stdout | Implement and test framing/lifecycle later; the scaffold only discards stdin and emits nothing | Step 2 | +| DryWetMIDI package availability | VERIFIED (package metadata) | Official [8.0.3 package page][drywetmidi], [version index][drywetmidi-index] and [8.0.3 manifest][drywetmidi-manifest]; manifest includes .NET Standard 2.0 | Exact central dependency is 8.0.3; a restore/build/smoke check does not verify proprietary formats or application import | Steps 5–7 use only verified capabilities | +| Stable test dependency availability | VERIFIED (package metadata) | Official NuGet indexes and manifests: [xunit 2.9.3][xunit-manifest], [xunit.runner.visualstudio 4.0.1][adapter-manifest], [Microsoft.NET.Test.Sdk 18.11.0][test-sdk-manifest]; adapter/test SDK include net8.0 groups compatible with net10.0 | Resolve and execute actual tests; versions pinned centrally, no independent coverage package | Step 1 validation, not a native gate | +| Installed .NET toolchain | VERIFIED (local inspection) | `C:\Program Files\dotnet\dotnet.exe --list-sdks` / `--info`: SDK 10.0.400, runtime 10.0.11, win-x64 | `global.json` pins SDK with patch roll-forward; this is development-machine evidence only | Step 1 validation | +| Self-contained, single-file deployment capability | VERIFIED (supported-slice packaging on SDK host) | Actual win-x64 profile/payload, isolated and executable-only RPC generation, read-back and extraction/host-trace tests; [deployment guide](local-deployment.md) | Matching runtime-free host still pending; no application/native acceptance implied | Step 9 full-scope gate remains open | +| AGP/SDP support inferred from MIDI library or .NET | NOT ESTABLISHED | No such evidence supplied; Standard MIDI and deployment docs are not proprietary format specifications | Independent authorized native evidence and real product acceptance are mandatory | Steps 6, 7, 9 | + +## Exact product identity and environment + +The names above are requested targets, not verified installed identities. +ABJ, AGLP, AGM and AGT installed versions/settings and mappings are also unresolved; +the historical Eclipse/Ray rows below do not narrow the expanded requested scope. + +| Item | Status | Evidence/source | Required evidence | Future gate blocked | +| --- | --- | --- | --- | --- | +| Lead: owner's exact Ample “Eclips” product name, edition, version/build | PARTIAL; product identified as Ample Metal Eclipse, version/build unknown | Owner-provided plugin screenshots, 2026-10-20; official Eclipse manual | Installed version/settings, including host/plugin format if relevant | Steps 4, 6, 9 | +| Bass: owner's exact Ample “Ray” product name, edition, version/build | MISSING; unknown | Not supplied | Same identity/version evidence for the bass product independently | Steps 4, 6, 9 | +| Superior Drummer 3 exact version/build | MISSING; unknown | Not supplied | Exact installed version, relevant plugin settings and chosen content library | Steps 4, 7, 9 | +| Cubase exact product/edition/version/build | MISSING; unknown | Not supplied | Acceptance host version, project/import settings and instrument routing | Step 9 | +| SD3 installed library, MIDI map/preset and mapping overrides | MISSING; unknown | Not supplied; do not assume GM mapping | Exact library/version, selected map, custom overrides and reproducible settings | Steps 4, 5, 7, 9 | + +## Native containers, supported workflows and rights + +No native format is assumed to be MIDI, XML, JSON, ZIP, or any other container. +An extension is a requested output name, not proof of product support. + +| Item | Status | Evidence/source | Required evidence | Future gate blocked | +| --- | --- | --- | --- | --- | +| Lead AGP container/schema/version metadata | MISSING; unknown | Not supplied; [Ample manual entry point][ample] did not yield a usable format schema during planning | Lawfully usable specification or owner-created one-variable fixtures identifying container, musical fields, metadata and version behavior | Step 6 (lead) | +| Bass AGP container/schema/version metadata | MISSING; unknown | Not supplied | Independent bass fixtures/specification; establish whether lead/bass actually share a codec rather than assuming | Step 6 (bass) | +| Lead supported import/load path and extension | MISSING; `.agp` requested, support unverified | Not supplied | Exact product/version workflow and confirmation whether `.agp` represents a riff, preset, project or other entity | Steps 6, 9 | +| Bass supported import/load path and extension | MISSING; `.agp` requested, support unverified | Not supplied | Equivalent independent bass workflow/extension confirmation | Steps 6, 9 | +| SD3 SDP container/schema/version metadata | MISSING; unknown | Not supplied; [SD3 manual entry point][sd3] required login during planning | Authorized versioned schema or minimal owner-created fixtures with musical-data semantics | Step 7 | +| Whether SD3 supports the requested `.sdp` extension and musical content | MISSING; unknown, not asserted | Not supplied | Actual supported extension/entity type and documented load/import steps for the installed version | Steps 7, 9; mismatch requires owner decision, not silent substitution | +| Authorized lead/bass/SD3 fixture availability and provenance | MISSING; none supplied | No fixture files in the initial repository | Minimal empty/one-note files, separate changes to pitch, duration, velocity, tempo and each articulation/control; record creating product/version and ownership | Steps 4, 6, 7 | +| Fixture redistribution and template reuse permissions | MISSING; unknown, no permission assumed | Not supplied | Explicit authorization/license scope for analysis, test redistribution and any generated/template-derived output; exclude sample/audio libraries and unrelated projects | Steps 6, 7; no template-based route without rights | +| Native fields express required timing, notes and articulation mechanisms | MISSING; unknown | Not supplied | Evidence-backed capability/limitation table from controlled fixtures and reopening tests; use DryWetMIDI for any actual embedded MIDI payload | Steps 6, 7, 9 | + +## Absolute articulation and MIDI mapping evidence + +All six Ample main-panel manuals and Settings/CPC were read. Vendor demo MIDI +now anchors the admitted AGLP/AME/AGM/AGT/ABJ numeric maps. AMR's anchor and the +selected SD3 default mapping remain unresolved. The following historical +inventory records the broader requested-product gate; the current subset and +explicit policies are described above. There are no synthetic production maps, +guessed octave conversions or claims of application-tested timing. + +| Item | Status | Evidence/source | Required evidence | Future gate blocked | +| --- | --- | --- | --- | --- | +| Absolute playable MIDI notes, lead/bass ranges and SD3 voices | PARTIAL; Ample range labels documented, numeric anchor and SD3 voices unresolved | Official Eclipse/Ray5 manuals, section 2.2.1 | Exact numeric notes/ranges per product/library/map, including control/playable collisions and the octave-label convention | Steps 4, 5, 6, 7 | +| Keyswitch notes, switch velocity and mechanisms | PARTIAL; Ample Sustain C0 and Palm Mute D0 documented; numeric values/complete semantics unresolved | Official manuals, sections 2.2.1-2.2.4; owner Eclipse tooltips | Absolute switch numbers, switch velocities and remaining semantics; consult documentation before requesting local checks | Steps 4, 5, 6, 7 | +| CC numbers, values and combinations (including hi-hat state) | MISSING; unknown | Not supplied | Verified controller numbers/ranges and combined keyswitch/CC behavior, not product-name inference | Steps 4, 5, 6, 7 | +| Velocity layers, legal ranges and transitions | PARTIAL; Ample Sustain layers documented, not all articulation thresholds | Official Eclipse/Ray5 manuals and owner Eclipse Sustain tooltip; see mapping source review | Remaining articulation boundaries, settings-dependent behavior and representability | Steps 4, 5, 6, 7 | +| Channels, routing and simultaneous-state constraints | MISSING; unknown | Not supplied | Numeric channel allocations, plugin multi-channel behavior and conflict rules; planned conventions are not verified plugin mappings | Steps 4, 5, 9 | +| Initial state, persistence/latching, release and reset behavior | MISSING; unknown | Not supplied | Initial state, momentary/latched controls, required releases/resets and supported simultaneous articulations | Steps 4, 5, 6, 7 | +| Control advance, switch duration and musical timing | MISSING; unknown | Not supplied | Required lead-in/advance, event ordering, durations and native timing limitations from controlled tests | Steps 4, 5, 6, 7 | +| SD3 library/map-dependent articulations and velocity interpretation | MISSING; unknown | Not supplied | Mapping/settings evidence for the actual installed SD3 content, including custom overrides and stateful controls | Steps 4, 5, 7, 9 | + +## Actual acceptance checks + +### Native investigation update (2026-10-20) + +Public discovery through the vendor material, web search and GitHub did not +establish an authorized AGP or SDP serialization schema/fixture. Search absence +does not prove a format unsupported. Riffer's documented single-track SMF +import is not a native encoding specification. + +The SD3 manual still requires login in the shared browser session. +[The vendor-hosted SD3P topic](https://www.toontrack.com/forums/topic/sd3p-files/) +also requires login to read its body; public indexed snippets discuss SD3P +project files. This raises an extension/entity question, not authority to +substitute `.sd3p` for the requested `.sdp`, nor a codec for either. + +Until actual native evidence is available, tool capabilities must report no +AGP/SDP writer. Explicit fallback may produce a genuinely generated MIDI file +with per-target warnings; disabled fallback must fail preflight without output. +Never fabricate a container or change its filename extension to claim support. + +| Item | Status | Evidence/source | Required evidence | Future gate blocked | +| --- | --- | --- | --- | --- | +| Generated lead AGP reopened in the owner's Eclips target | NOT PERFORMED | Not supplied; no writer or authorized fixtures | Record exact version, input identifier, load procedure, pitches/timing/velocity/articulation results | Steps 6, 9 | +| Generated bass AGP reopened in the owner's Ray target | NOT PERFORMED | Not supplied; no writer or authorized fixtures | Equivalent independent bass acceptance record | Steps 6, 9 | +| Generated SDP reopened in SD3 | NOT PERFORMED | Not supplied; extension semantics remain unknown | Verified extension/workflow, library/map and drum timing/voice/velocity/articulation results | Steps 7, 9 | +| Standard MIDI imported and routed in Cubase | NOT PERFORMED | Step 5 verifies synthetic MIDI file read-back, not Cubase import | Exact host/version, track separation, timing, tempo/meter and instrument/channel routing evidence | Step 9 | +| Intended articulations verified in actual plugins through Cubase | NOT PERFORMED | Not supplied | Reproducible acceptance session/settings and observed articulation behavior | Step 9 | +| Published executable launched without a separately installed runtime | NOT PERFORMED / pending | Step 9 self-contained publish and unrelated-cwd isolated/executable-only RPC checks pass on SDK machine; bundle inspection/host trace are not a runtime-free host | Matching runtime-free Windows x64 test environment still required | Step 9 | + +## Gate decision + +Missing proprietary evidence does not prevent accepting the Step 1 scaffold. +It **does** prevent declaring native writers or actual plugin/Cubase compatibility +verified. It does not prohibit honest Documented default profiles supported by +sources and disclosed policies. Step 4 still needs the remaining target mappings; +Steps 6 and 7 additionally need schemas/fixtures/rights and successful native +imports. A native extension mismatch requires an owner decision. Do not +fabricate files, relabel MIDI as native output, or treat MIDI fallback as native +acceptance. Automated scaffold results belong in `prompts\report_1.md` and do not +close any of these application-level gates. + +Step 4's generic validator/planner/catalog and synthetic pipeline tests are +automated infrastructure evidence only (see `prompts\report_4.md`). Production +mapping catalog count is five Documented/zero Verified; identity catalog count is +seven. Documented Ample facts above are PARTIAL requested-product evidence, not +missing merely because no owner-run test was supplied. Complete exact-version +profiles and native/application acceptance remain unresolved. Consult available +official documentation first; request owner assistance only for remaining +local settings, inaccessible documentation or real-application acceptance. +Synthetic numbers, compilation and passing tests cannot close those gaps. + +[mcp]: https://modelcontextprotocol.io/specification/2025-11-25/basic/transports +[drywetmidi]: https://www.nuget.org/packages/Melanchall.DryWetMidi/8.0.3 +[drywetmidi-index]: https://api.nuget.org/v3-flatcontainer/melanchall.drywetmidi/index.json +[drywetmidi-manifest]: https://api.nuget.org/v3-flatcontainer/melanchall.drywetmidi/8.0.3/melanchall.drywetmidi.nuspec +[xunit-manifest]: https://api.nuget.org/v3-flatcontainer/xunit/2.9.3/xunit.nuspec +[adapter-manifest]: https://api.nuget.org/v3-flatcontainer/xunit.runner.visualstudio/4.0.1/xunit.runner.visualstudio.nuspec +[test-sdk-manifest]: https://api.nuget.org/v3-flatcontainer/microsoft.net.test.sdk/18.11.0/microsoft.net.test.sdk.nuspec +[single-file]: https://learn.microsoft.com/en-us/dotnet/core/deploying/single-file/overview +[ample]: https://www.amplesound.net/en/manual.asp +[sd3]: https://www.toontrack.com/manual/superior-drummer-3/ diff --git a/docs/local-deployment.md b/docs/local-deployment.md new file mode 100644 index 0000000..d4e721b --- /dev/null +++ b/docs/local-deployment.md @@ -0,0 +1,255 @@ +# Local Windows x64 deployment — supported MIDI slice + +This deploys the two existing stdio MCP tools, not a generation command-line +interface or HTTP service. It supports explicit AGLP/AGM/AGT/AME **Documented-default +Lead** and ABJ **Sustain-only Bass**, with Standard MIDI and explicit MIDI fallback +for unavailable native formats. AMR and SD3 remain unmapped; ABJ PalmMute +explicitly fails rather than substituting Sustain. +No AGP/SDP writer, application-Verified mapping, Cubase/plugin import, playback +or full-product acceptance is claimed. + +## Publish + +From the repository root, using the SDK pinned by `global.json`: + +```powershell +dotnet publish .\src\GAJ3T.MusicGen.RiffGrooveBuilder.Server\GAJ3T.MusicGen.RiffGrooveBuilder.Server.csproj -p:PublishProfile=win-x64 -o .\artifacts\publish\win-x64 +``` + +`Properties\PublishProfiles\win-x64.pubxml` sets Release, `win-x64`, +`SelfContained=true`, `PublishSingleFile=true`, `PublishTrimmed=false`, +`PublishAot=false`, `UseAppHost=true` and +`IncludeNativeLibrariesForSelfExtract=true`. This remains a `net10.0` console +application using `Microsoft.NET.Sdk`, not a web SDK. + +The profile uses `packages.win-x64.lock.json` separately from the ordinary +server `packages.lock.json`: RID/single-file restore needs the SDK's implicit +`Microsoft.NET.ILLink.Tasks` 10.0.11 tooling for single-file analysis even though +trimming/AOT are disabled. This is not an application package addition. +The exact central application/test package pins are unchanged, including +DryWetMIDI **[8.0.3]**. To enforce the publication graph's lock: + +```powershell +dotnet restore .\src\GAJ3T.MusicGen.RiffGrooveBuilder.Server\GAJ3T.MusicGen.RiffGrooveBuilder.Server.csproj -p:PublishProfile=win-x64 --locked-mode +dotnet publish .\src\GAJ3T.MusicGen.RiffGrooveBuilder.Server\GAJ3T.MusicGen.RiffGrooveBuilder.Server.csproj -p:PublishProfile=win-x64 --no-restore -o .\artifacts\publish\win-x64 +``` + +Inspect an existing publication before republishing. Build tools update their +own output files; do not recursively clean unrelated directories. + +## Observed payload and extraction + +The correction iteration 4 publication refresh produced these five files in +`artifacts\publish\win-x64` (original Step 9 inventory is preserved in its report): + +| File | Bytes | Role | +| --- | ---: | --- | +| `GAJ3T.MusicGen.RiffGrooveBuilder.Server.exe` | 74,734,064 | Self-contained single-file executable | +| `GAJ3T.MusicGen.RiffGrooveBuilder.Core.pdb` | 37,636 | Optional debugging symbols | +| `GAJ3T.MusicGen.RiffGrooveBuilder.Generation.pdb` | 20,208 | Optional debugging symbols | +| `GAJ3T.MusicGen.RiffGrooveBuilder.Server.pdb` | 20,320 | Optional debugging symbols | +| `Melanchall_DryWetMidi_Native64.dylib` | 90,600 | Package-copied macOS native sidecar; not used on Windows | + +Refreshed executable SHA256: +`921AADE7FB75222E8A7E5E81151F3DC73747CD8036EE751555A613A5DBDD308E`. + +Symbols and the `.dylib` are not needed for this Windows MIDI-only path: +an **executable-only** isolated copy successfully initialized MCP and generated +readable MIDI from `C:\Windows\System32` (the actual system directory on this host). +There are no loose managed DLLs, catalog JSON, runtimeconfig or deps files in +the published payload. Catalogs and managed dependencies are embedded. + +The pinned package's build targets copy native32/native64 Windows DLLs and a +macOS dylib without RID filtering. With this publish profile the Windows DLLs +are bundled and extracted at startup: + +- `Melanchall_DryWetMidi_Native32.dll`: 57,954 bytes. +- `Melanchall_DryWetMidi_Native64.dll`: 66,926 bytes. + +Tests compare their SHA256 hashes with the inspected 8.0.3 package assets. +Only those two DLLs were extracted in the observed SDK 10.0.400/.NET 10.0.11 +single-file run; no loose `coreclr.dll`, `clrjit.dll` or managed library was +extracted. Host tracing reported “Executing as a self-contained app”, +“Using internal hostpolicy” and `CoreCLR path = '', CoreCLR dir = ''`. +These are actual bundle observations, not a claim that device APIs/native +playback were tested or that every dependency is irrelevant. + +Normal .NET Windows bundle extraction uses the user's `%TEMP%\.net` cache. +It needs writable space; security software may also affect execution/extraction. +`DOTNET_BUNDLE_EXTRACT_BASE_DIR` can select a writable private cache if needed. +Tests set it only for their child process to a task-owned checkout directory, +then delete that directory after process exit. They do not edit machine/user +environment or client settings. No playback/device API is used. + +**Architecture/acceptance:** this payload is for Windows x64 and includes +.NET 10.0.11. It is not an ARM64/macOS/Linux publication. Launch and host tracing +on this SDK-equipped machine verify packaging, **not** a matching runtime-free +Windows installation. That acceptance check remains **pending**; no fake +`DOTNET_ROOT`, runtime removal, VM, container or product installation substitutes +for it. Normal supported-Windows OS prerequisites still apply. + +## Copyable VS Code MCP client configuration + +This is a reference snippet only. No workspace/user/global MCP settings were +modified. If you choose to configure VS Code, put the following server entry in +your chosen MCP configuration and adjust the absolute path for your checkout +or copied executable. The command is the executable itself, with **no shell +wrapper, HTTP URL or generation CLI arguments**: + +```json +{ + "servers": { + "riff-groove-builder": { + "type": "stdio", + "command": "D:\\_Repos\\Code\\GAJ3T\\MCPs\\MusicGen\\GAJ3T.MusicGen.Riff-Groove-Builder.Net\\artifacts\\publish\\win-x64\\GAJ3T.MusicGen.RiffGrooveBuilder.Server.exe", + "args": [] + } + } +} +``` + +The client launches and owns this finite stdio process. MCP uses UTF-8 +newline-delimited JSON-RPC, negotiates `2025-11-25`, then requires +`notifications/initialized` before tool calls. A normal MCP client handles +this handshake. Discover `list_instrument_profiles` and `generate_project`; +profile discovery with `{}` returns seven identities and five Documented profiles +(four Lead Sustain/PM, one Bass Sustain-only; two unavailable identities). +There is no server URL, listener, background service or registration step. + +Call `generate_project` with these **tool arguments** (not executable `args`): + +```json +{ + "description": "4 bars at 120 BPM in E minor, 4/4: palm-muted eighth-note lead", + "outputDirectory": "D:\\MusicGenOutputs", + "projectName": "ame-lead-example", + "formats": ["mid"], + "profiles": { + "lead": "ample-ame-documented-defaults-2026-10-20" + }, + "fallbackToMidi": false +} +``` + +AGLP instead requires the explicit profile +`ample-aglp-documented-defaults-2026-10-20`. No profile is automatically selected. +AGM and AGT also have explicit `ample-agm-documented-defaults-2026-10-20` and +`ample-agt-documented-defaults-2026-10-20` profiles. For Lead+Bass, change +description to `"palm-muted eighth-note lead and sustained bass"` and profiles to: + +```json +{ + "lead": "ample-ame-documented-defaults-2026-10-20", + "bass": "ample-abj-documented-defaults-2026-10-20" +} +``` + +The output is one combined MIDI, not two role files: Lead channel 0 and Bass +channel 1, shared lead-in 120. ABJ supports Sustain velocities 1-125 only; +PalmMute and accent velocities 126-127 fail explicitly. Missing Bass selection +is `no_default_profile`; unmapped Drums is `mapping_unavailable`. Neither is +a silently reduced arrangement. Native fallback still produces one combined +artifact retaining both roles. + +The example returns `status:"complete"`, one absolute +`D:\MusicGenOutputs\ame-lead-example.mid` path and the Documented compatibility +warning. This is **source-backed, NOT installed/application-verified**. Honor +the returned version/configuration/routing/timing notes, including default +tuning/mapping/thresholds, instrument mode, MIDI Guitar mode off, idle isolated +receiver, Lead channel 0 and (when selected) Bass channel 1. The switch advance/pulse timing is engineering +policy, not certified plugin latency or a vendor minimum. + +## Output, fallback, shutdown and troubleshooting + +- The caller supplies an absolute output directory and safe filename stem; + the server creates the directory after preflight. Relative paths, traversal + and unsafe names fail. Existing destinations are never overwritten; use a + new stem on `output_exists`. Request-owned staging is cleaned on failure; + an empty newly created directory may remain after an I/O failure. +- Omitted Lead formats default to `["agp","mid"]`, and omitted + `fallbackToMidi` defaults to true. AGP requests therefore return + `status:"fallback"` and one real `.mid` with explicit native-unavailable + reasons, never a renamed native file. Native requests with fallback disabled + fail before output. SDP is inapplicable to a Lead-only request. +- Failed results have `isError:true`, no artifacts and actionable errors. + Schema/argument violations use JSON-RPC `-32602`; parse errors use `-32700`. + Output permissions/disk failures are errors, not fallback opportunities. +- Keep stdin open until the response arrives. Closing it signals EOF, cancels + active work and ends the process; empty stdin/EOF exits silently with code 0. + Do not pipe a whole generation conversation and immediately close stdin. +- MCP cancellation is observed around synchronous DryWetMIDI serialization + and before publication; it cannot interrupt inside library serialization. + The final no-overwrite move is the commit point. Late cancellation does not + undo a published file. Clients should inspect the completed result. +- Stdout is protocol-only. Consult stderr/client logs for diagnostics, not an + HTTP endpoint. A process launched interactively waits for stdin; that alone + is not a readiness check. Successful initialize/ping/tool responses are. +- For missing tools/profiles, verify you launched the published executable, + completed initialization and rebuilt after catalog changes. Catalogs are + embedded; copying loose JSON beside the executable does not configure them. +- For extraction/launch failures, check Windows x64 compatibility, writable + bundle cache, permissions/security software and stderr. Do not install vendor + software or invoke device APIs merely to use this MIDI-file slice. + +## Automated publication checks and retained example + +Publish first. From the repository root: + +```powershell +dotnet restore .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx --locked-mode +dotnet build .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-restore +dotnet test .\tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests.csproj -c Release --no-build --filter FullyQualifiedName~PublishedServerTests +dotnet test .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-build +``` + +The 28 focused published checks reuse the bounded concurrent-drain process +harness, copy the actual publish payload into a task-owned isolated directory, +use an unrelated existing cwd, and clean only owned files/processes. They also +exercise an executable-only copy with host tracing. Tests fail with a publish +instruction if the payload is missing; they do not silently skip packaging. +`RIFFGROOVE_PUBLISHED_SERVER` optionally selects an **absolute executable path** +for test infrastructure only, not an application configuration feature. + +Checks cover exactly two tools, seven identities/five Documented profiles, all +four explicit Lead profiles, real Lead+Bass MIDI and combined native fallback, +ABJ Sustain-only discovery/PM rejection, missing Bass selection, disabled fallback, unavailable +selected roles, real-file collision preservation, malformed/schema errors, +ping, cancellation, active/empty EOF and protocol-only stdout. + +The eight refreshed published Lead+Bass cases (each guitar plus ABJ, complete +and native fallback) each write/read one **435-byte** MIDI, SHA256 +`F31C7C2236637AF9412738418AF61E7D613D51C89A8FFB43B379012C7798384A`. +Read-back verifies Conductor/Lead/Bass, channels 0/1, 32 Lead and four Bass +musical notes, PM26/Sustain24 on0/off30, shared lead-in120 and three end +markers15480. These test-owned files are removed, not presented as retained +examples or application acceptance. + +The retained `artifacts\examples\ame-lead-example.mid` was generated through +the **published stdio RPC**, not copied from vendor MIDI or an in-process writer. +Pinned DryWetMIDI 8.0.3 reopened the actual returned path and verified type 1, +960 PPQ, Conductor/Lead tracks, tick-zero 120 BPM/4/4, 32 pitch-64 velocity-96 +musical notes at `120 + 480*i`, duration 480, channel 0; switch26/velocity100 +on0/off30, shared lead-in120 and both end markers15480. It is 371 bytes, SHA256: +`6F5791FB5C3A7A17E54AAF6436963E4D5723FB948057585060C09BF9B2AFCA3E`. +It demonstrates file semantics, **not Cubase/Ample import or audible acceptance**. +Publication/examples are ignored generated artifacts, retained locally. + +To generate another retained example through the same test (existing examples +are preserved and a distinct stem is selected): + +```powershell +$env:RIFFGROOVE_RETAIN_EXAMPLE = '1' +try { + dotnet test .\tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests.csproj -c Release --no-build --filter FullyQualifiedName~PublishedRpcGeneratesReadBackExample --logger 'console;verbosity=detailed' +} +finally { + Remove-Item Env:\RIFFGROOVE_RETAIN_EXAMPLE +} +``` + +Without this opt-in, the test reads back and removes its own example. No +long-lived process is left running. See [format compatibility](format-compatibility.md) +and [mapping evidence](articulation-mappings.md) for the still-blocked AMR/SD3 +mappings, ABJ PalmMute, native writers, exact installed versions and licensed-application +acceptance matrix. Successful supported-slice deployment does not complete +the full requested product. diff --git a/docs/mcp-protocol.md b/docs/mcp-protocol.md new file mode 100644 index 0000000..1c8a46e --- /dev/null +++ b/docs/mcp-protocol.md @@ -0,0 +1,272 @@ +# Stdio MCP protocol and generation tools (Steps 2/8) + +## Scope and negotiation + +The .NET 10 Server apphost implements a small local stdio MCP server using +`System.Text.Json` and the BCL. It supports **only MCP `2025-11-25`**. An +`initialize` request for that version is echoed; any other string version +receives `2025-11-25` as the supported alternative. A client that cannot use +this version should disconnect. No network connection is made. + +The only advertised capability is `tools: { "listChanged": false }`. The +production registry contains exactly `list_instrument_profiles` and +`generate_project`. No fake profiles, native writers or synthetic test tools +are advertised. Server identity is +`GAJ3T.MusicGen.RiffGrooveBuilder`, implementation version `0.2.0`. + +## Framing and ownership + +- Messages are strict UTF-8 JSON, delimited by LF or CRLF, not `Content-Length` + framing. A BOM is not removed. Invalid UTF-8 produces `-32700`, never + replacement characters. JSON strings can contain escaped `\n`; a literal + newline terminates the frame. +- The production limit is **1,048,576 UTF-8 bytes per incoming frame**, excluding + its LF or CRLF terminator. Exactly the limit is accepted. Reading uses a + fixed limit-plus-one frame buffer and a 4 KiB read buffer: an oversized + message is drained without accumulating its remainder. At its newline (or + EOF), one bounded `-32600` response with `id: null` and a fixed stderr + diagnostic is emitted, then processing resumes at the next frame. +- JSON parsing also applies `System.Text.Json`'s default maximum nesting depth + of 64. Exceeding it returns a parse error. +- An empty stream produces nothing. A nonempty final frame at EOF is processed + once, even without a trailing newline. A blank line is an empty JSON frame + and returns `-32700`. An incomplete final JSON document returns `-32700`. +- Every output is a complete compact JSON-RPC object followed by LF and a + flush. A write lock prevents concurrent responses from interleaving. A write + already in progress is not truncated by request cancellation. +- The transport borrows its streams; the entry point owns/disposes the streams + it opens. It never disposes the caller's diagnostic writer. +- EOF or Ctrl+C cancels active work and awaits its cancellation/cleanup. There + is no `shutdown` RPC. Fatal input/output failures are written to stderr and + exit with code 1; normal EOF/cancellation exits with code 0. Per-request + unexpected failures return `-32603` and diagnostic details only on stderr. + +## Methods and lifecycle + +| Method | Behavior | +| --- | --- | +| `initialize` | Request, once only. Requires object params containing string `protocolVersion`, object `capabilities`, and `clientInfo` with string `name` and `version`. Optional known metadata/capability fields are type-checked, including icons and nested client capability objects. Unknown client capability keys are allowed but never used. Successful initialization waits for `notifications/initialized`. | +| `notifications/initialized` | Notification with omitted or empty object params (optional object `_meta`). Transitions an initialized session to ready. Out-of-order, repeated or invalid notifications are ignored with a diagnostic and no response. | +| `ping` | Request allowed before, during and after initialization. Omitted/empty object params, optional `_meta`; returns `{}`. | +| `tools/list` | Requires ready state. Omitted/empty object params, optional `_meta`; returns the two production tools in stable name order with input/output schemas. No pagination cursor is issued; any supplied cursor is rejected. | +| `tools/call` | Requires ready state and object params with string `name`, optional object `arguments` (defaults to `{}`), optional `_meta`. Unknown tool or invalid arguments return `-32602`. | +| `notifications/cancelled` | Validates `requestId` and optional string `reason`. Cancels only the matching active request, never `initialize` or the server. Malformed, unknown or completed IDs are ignored. Reasons are not echoed. No notification response; a cancelled request normally has no response either. | + +Fixed method params reject unknown members (including task augmentation); +`_meta` accepts extension fields, and request `_meta.progressToken`, if present, +must be a string or number. Client capabilities and implementation metadata +are not fetched or acted on. Tools cannot run before the complete handshake. +Known tool requests in the wrong state return `-32002`. Repeated initialization +returns `-32002`. Unknown request methods always return `-32601`, including +request-shaped notification methods. + +Valid notifications never receive a response, including unsupported methods +and requests mistakenly sent without an ID. Unsupported notifications are +ignored with a fixed diagnostic; they cannot initialize or invoke a tool. +Malformed envelopes are invalid requests, not valid notifications. + +Resources, prompts, sampling, elicitation, logging RPCs, progress emission, +task APIs, HTTP, server-initiated requests, and list-change notifications are +not implemented or advertised. + +## JSON-RPC validation and errors + +Requests/notifications require `jsonrpc: "2.0"` and a string `method`. Requests +use a string or signed 64-bit integer ID. String and numeric IDs are distinct; +responses preserve their values and types, not necessarily JSON escape spelling. +Null, boolean, fractional/exponent/decimal numeric IDs and integers outside +Int64 are unsupported. An unambiguous valid ID is preserved on an invalid +envelope; otherwise error `id` is null. Duplicate envelope member names and +batch arrays are rejected; MCP batch execution is not supported. + +| Code | Meaning | +| --- | --- | +| `-32700` | Malformed JSON, blank frame, or invalid UTF-8 | +| `-32600` | Invalid envelope/ID, batch, duplicate active request ID, oversized frame | +| `-32601` | Unknown request method | +| `-32602` | Invalid method params, unknown tool, invalid typed/semantic tool arguments or cursor | +| `-32603` | Unexpected handler/result-serialization failure | +| `-32002` | Inappropriate lifecycle state | +| `-32000` | Request admission limit reached | + +There are at most **64 active requests**. Excess requests get an explicit +bounded error without blocking notification dispatch. The ID table never +replaces an active request: a duplicate receives `-32600` without cancelling or +overwriting the original. Async tool work does not block reading cancellation +or unrelated requests. Responses may complete out of order. Once a response +write has started, cancellation may race with its delivery; clients must +tolerate a late response. Registry snapshots and lifecycle/ID state are +synchronized. + +## Typed tool boundary + +Registration is internal application setup, not a user plugin/RPC feature. +Register uniquely named definitions before creating the session; the session +freezes the registry and does not emit list-change notifications. + +`McpToolDefinition` uses non-null object DTO contracts. The same +strict camel-case serializer options generate output/default input JSON Schemas +with the .NET JSON Schema exporter (default JSON Schema 2020-12), deserialize +arguments and serialize results. Required constructor members, non-nullable +properties, types, duplicate properties and unknown members are validated. +Optional semantic validation raises `McpToolInputException` for `-32602`. +Enums serialize as camel-case strings, never integers. Production tools supply +explicit constrained input schemas, matching validators (including exact enum +case, non-null optional inputs, uniqueness and nested profiles), and a small +output-schema refinement for successful versus failed generation. +This remains a typed boundary, not a general-purpose arbitrary JSON Schema +engine; domain constraints are enforced by the registered validator/handler. + +Handlers accept a request-scoped `CancellationToken` and must honor it and +clean up owned resources. They return `McpToolOutcome`: the emitted +object contains `structuredContent`, an identical serialized JSON text block +in `content`, and `isError`. Expected execution failures explicitly return a +typed schema-conforming outcome with `isError: true`; unexpected exceptions +never become successful tool results. + +## Production tools (Step 8) + +### `list_instrument_profiles` + +The optional `role` is exactly `lead`, `bass` or `drums`. Omit it for all; +explicit null, integers, other casing and unknown fields are invalid params. +Output includes: + +- `instruments`: stable `id`, `vendor`, `productCode`, `displayName`, `role`, + `documentationUrl`, `availability` (`profile_available`/`mapping_unavailable`). +- `profiles`: `id`, `instrumentId`, role/product/version/mapping revision, + `playableRange` (absolute minimum/maximum pitches), zero-based `channel`, + `articulations` (mechanisms, velocity constraints, behavior, explicit switch/ + controller/voice data), `evidence`, `compatibilityNotes`, `nativeFormats`, + and `nativeStatus:"unverified"`. +- `formats`: `mid` has `writerStatus:"implemented"`; `agp`/`sdp` have + `writerStatus:"unavailable"`. Each `applicationStatus` is `unverified`. + +Seven declared identities and five Documented profiles are currently +exposed: AGLP/AGM/AGT/AME Lead Sustain/PalmMute, ABJ Bass Sustain only. +AMR and SD3 have no admitted map. ABJ discovery advertises one articulation, +musical velocities 1-125 and zero-based channel 1; Lead uses channel 0. +Documented means source-backed, +not installed/application-verified; no synthetic/test fixture is exposed. +Native format applicability is not writer availability or application acceptance. +The embedded catalog is independent of cwd; runtime profile/VST loading is absent. + +### `generate_project` + +| Input | Contract | +| --- | --- | +| `description` | Required string, 1..16384 characters; the [bounded grammar](text-description-contract.md) applies | +| `outputDirectory` | Required nonempty string; explicit absolute filesystem directory, no traversal/device syntax | +| `projectName` | Required nonempty safe filename stem; no separators, traversal, reserved devices, alternate streams, trailing dot/space | +| `formats` | Optional nonempty unique array of exact strings `agp`, `sdp`, `mid`; omit for applicable native formats plus MIDI | +| `profiles` | Optional fixed object with optional nonempty string `lead`, `bass`, `drums` profile IDs; every selected role needs an explicit matching admitted ID | +| `fallbackToMidi` | Optional boolean, defaults true | + +All fixed request/nested objects reject unknown/duplicate members. Supplied null +fields are not accepted. There is no automatic profile default or substitution. +Only explicitly selected roles are resolved; profiles for unselected roles fail. +Text that omits roles still follows the grammar's three-role default and fails +missing explicit Lead/Bass selections and unavailable Drums instead of silently +removing them. Missing Bass selection now returns `no_default_profile`, not +`mapping_unavailable`; unmapped Drums still returns `mapping_unavailable`. +Explicit ABJ PalmMute fails `unsupported_articulation`, never Sustain fallback. +Role-to-instrument binding is resolved from the admitted profile, not user folders. + +The structured result has all of these required keys: + +```text +status: complete | fallback | failed +interpretedComposition: { tempoBpm, meter, key, bars, roles, defaultsApplied } | null +artifacts: [{ format, roles, absolutePath, byteCount, profileIds }] +targets: [{ + role, instrumentId, profileId, requestedFormat, outcome, + artifactPaths, reasonCode, message +}] +warnings: [{ code, message, role, requestedFormat }] +errors: [{ code, message, field, role }] +timing: { ticksPerQuarterNote, leadInTicks } | null +``` + +Enums are strings (target `outcome`: `written`, `fallback`, `failed`). Nullable +identity/reason/diagnostic fields are serialized explicitly as null, not omitted. +Early failures have null interpreted composition/timing. Other failures can retain +successful interpretation/planning details. The advertised conditional output +schema allows null composition/timing only for `failed`, requires nonempty +artifacts/targets and empty errors for success, and no artifacts plus nonempty +errors for failure. Artifact byte counts and absolute paths describe real, +nonempty files. Every applicable role/requested-format pair has a target; combined +MIDI targets share one path. Inapplicable requested formats instead fail globally. +Structured content is repeated byte-for-byte as serialized JSON in one text block; +`isError` is true only for `failed`, false for `complete` and `fallback`. + +`agp` applies to selected Lead/Bass; `sdp` to selected Drums. Lead-only omitted +formats therefore mean AGP+MIDI, not SDP. Explicit inapplicable formats fail. +Both native writers are absent: applicable native requests with fallback enabled +write exactly one `.mid` for the complete selected event plan. +An explicit MIDI request reuses that artifact. Each native target reports +`native_writer_unavailable`, and a warning discloses unverified compatibility. +There are no native files/placeholders/renamed MIDI files. With fallback disabled, +native requests fail before directory creation/output; MIDI-only still succeeds. +Every selected Documented mapping produces a warning containing source-only +status and the exact version/configuration/routing/timing compatibility notes. + +Expected domain failures return `status:"failed"`, no artifacts, actionable +`errors` and failed targets with no usable paths. Codes include +`no_default_profile` (with available IDs), `unknown_profile`, +`profile_role_mismatch`, `unselected_role_profile`, `mapping_unavailable`, +`inapplicable_format`, `native_fallback_disabled`, `invalid_formats`, +`invalid_output_path`, parser/planner diagnostics, `midi_not_supported`, +`output_exists`, and `output_io_error`. Contract/JSON violations use `-32602` +instead. Invalid mappings/text, MIDI limitations, I/O, cancellation and unexpected +exceptions never trigger native fallback. Unexpected failures use the existing +logged `-32603` boundary, with details on stderr only. + +Semantic/profile/native-format and shared MIDI meter/extent preflight occur +before directory creation. Generation calls the real staged no-overwrite MIDI +writer; early existence checks are not the race-safety mechanism. Only this +request's staging file is cleaned on failure/cancellation; existing destinations, +other requests' files and unrelated files are preserved. A created directory +may remain empty after an I/O failure. Cleanup/close failures retain aggregate +diagnostics and any remaining staging path at the logged error boundary. + +Generation runs on a thread-pool worker, including text planning, profile/event +planning and synchronous filesystem/DryWetMIDI work. The reader stays available +for ping and cancellation; deterministic blocked-work unit tests verify this +even when tiny real requests finish too quickly. Cancellation propagates without +a tool response and is checked before publication. The library's synchronous +serialization has no cancellation API; a token cannot interrupt that call but +observed cancellation afterward prevents publication and cleans staging. +Publication is the commit point; cancellation racing after the last check/move +does not roll back the committed file. EOF cancels active requests: clients must +keep stdin open and wait for responses before closing it. + +## Validation and primary references + +Unit tests cover framing at/over the limit, strict UTF-8/EOF, serialized flushed +writes, envelopes and error codes, negotiation/state, schemas/results, +test-only handlers, cancellation with unrelated work surviving, duplicate +typed IDs, admission limits and fatal I/O. Real-apphost tests cover handshake, +notification silence, malformed-frame recovery, unknown methods/tools, invalid +params, LF/CRLF, Unicode IDs, exact-limit/oversized/invalid-UTF-8 frames and final +frames at EOF from both test-output and unrelated working directories. +Production-tool tests add strict schemas versus serialized results, discovery/ +filtering, real RPC-generated MIDI read-back for all five admitted capabilities +and complete Lead+Bass arrangements, native +fallback and disabled fallback, selected-role/mapping failures, collisions, +responsive ping/cancellation and unchanged stdout purity. +All subprocess tests concurrently drain stdout/stderr and enforce bounded, +process-owned cleanup. Lifetime-token cancellation (the Ctrl+C code path) is +unit-tested; sending an actual interactive Windows console Ctrl+C event is not +an automated apphost test. + +Primary MCP 2025-11-25 sources: + +- [Transports](https://modelcontextprotocol.io/specification/2025-11-25/basic/transports) +- [Lifecycle](https://modelcontextprotocol.io/specification/2025-11-25/basic/lifecycle) +- [Cancellation](https://modelcontextprotocol.io/specification/2025-11-25/basic/utilities/cancellation) +- [Tools](https://modelcontextprotocol.io/specification/2025-11-25/server/tools) +- [Schema](https://modelcontextprotocol.io/specification/2025-11-25/schema) + +Native compatibility and full product readiness remain unverified; see +[the evidence inventory](format-compatibility.md). Publication and actual +plugin/Cubase acceptance belong to later steps. diff --git a/docs/text-description-contract.md b/docs/text-description-contract.md new file mode 100644 index 0000000..c98cd73 --- /dev/null +++ b/docs/text-description-contract.md @@ -0,0 +1,171 @@ +# Bounded text-to-composition contract (Step 3) + +This is a deterministic English subset, not arbitrary English understanding. +The Core API is in-process; Step 8's MCP `generate_project` reuses it unchanged. +This text contract alone implies no production profile, plugin playability, +drum mapping, audio or native-format compatibility. Generic profile/event +planning and a Standard MIDI writer consume successful models. MCP generation +requires explicit admitted profile IDs: AGLP/AGM/AGT/AME Documented Lead profiles +and ABJ Sustain-only Bass exist. ABJ PalmMute explicitly fails +`unsupported_articulation`; AMR and all Drums mappings remain unavailable. +Selecting unavailable roles or omitting a selected role's explicit profile fails the complete +request rather than changing the grammar/defaults or dropping those roles. + +## Grammar + +Input is nonempty text of at most 16,384 UTF-16 characters. Keywords are +case-insensitive; ordinary whitespace (including newlines), commas, colons, +semicolons and full stops separate clauses. `and` can join clauses or numbered +beats. One optional `generate` may prefix the description. Settings and role +clauses can appear in any order. Punctuation separates tokens; it does not +erase unsupported words or turn decimal numbers into integers. + +```text +description = ["generate"] clause { separator clause } +setting = [ "at" ] integer "bpm" + | bar-count ("bar" | "bars") + | [ "in" ] root ("major" | "minor") + | numerator "/" denominator +role = pitched | "drums" | drum-part +pitched = [articulation] [pattern] ("lead guitar" | "lead" | "guitar" | "bass") + | ("lead guitar" | "lead" | "guitar" | "bass") [articulation] [pattern] +pattern = subdivision ["root-note" | "root notes"] + | "sustained" ["root-note" | "root notes"] +subdivision = ("quarter" | "eighth" | "sixteenth") ("note" | "notes") +articulation = "sustain" | "palm-muted" | "palm mute" +drum-part = ("kick" | "snare") "on" ("beat" | "beats") integer + { "and" integer } + | "closed hi-hat" subdivision +root = A..G [ "#" | "b" | "♯" | "♭" ] +bar-count = integer | "one" | "two" | "three" | "four" | "five" | "six" + | "seven" | "eight" | "nine" | "ten" | "eleven" | "twelve" + | "thirteen" | "fourteen" | "fifteen" | "sixteen" +``` + +Hyphens in `eighth-note`, `root-note`, `palm-muted` and `hi-hat` are +interchangeable with spaces. `sustained` specifies the full-bar pattern, not a +vendor articulation. Explicit `palm mute sustained bass` is therefore meaningful. +Role-local modifiers never leak to another role. Patterns cannot straddle a +different clause or be specified both before and after a role. + +Integers are unsigned ASCII decimal tokens (no signs, decimals, exponent +notation, mixed digit/word numbers or thousands separators). Only bar counts +also accept the words one through sixteen. Beat lists use `and`, not commas. +Repeated identical settings/role clauses/parts are accepted once, without +duplicating events; conflicting repetitions and duplicate beats are rejected. +Only one articulation and one pattern are allowed per pitched clause. +No synonyms other than those listed here are promised. + +Examples: + +> Generate 4 bars at 120 BPM in E minor, 4/4: palm-muted eighth-note lead guitar, +> sustained root-note bass, kick on beats 1 and 3, snare on beats 2 and 4, and +> closed hi-hat eighth notes. + +> generate four bars at 120 bpm in F♯ minor: lead guitar palm mute sixteenth notes + +> 3/8, 2 bars: kick on beats 1 and 3, snare on beat 2, closed hi-hat eighth notes + +Unsupported meaningful text is an error, including genres, chord progressions, +tuning, melodies, swing, dynamics/velocity instructions, unknown articulations, +open hi-hat and additional drums. `heavy metal lead`, `120.5 bpm`, `lead legato`, +`bass quarter notes and eighth notes` and `kick on beats 1, 3` do not become +guessed defaults. Failures have stable codes, fields and offending phrases +where applicable, with actionable messages; they expose no partial plan/model. + +## Defaults and role selection + +Every applied default is returned as a field/value pair in `DefaultsApplied`, +on both the parsed description and successful composition: + +| Field | Value when omitted | +| --- | --- | +| `tempoBpm` | 120 | +| `bars` | 4 | +| `meter` | 4/4 | +| `key` | E minor | +| `roles` | lead,bass,drums, **only if no role or drum part is mentioned** | +| `lead.pattern` | eighth notes | +| `bass.pattern` | sustained (one full-bar root note per bar) | +| `lead.articulation`, `bass.articulation` | sustain | +| `lead.rootOctave`, `bass.rootOctave` | 4, 2 (only for selected pitched roles) | +| `lead.velocity`, `bass.velocity`, `drums.velocity` | 96 (only for selected roles) | +| `drums.kick`, `drums.snare`, `drums.closedHiHat` | beats 1 and 3; beats 2 and 4; eighth notes | + +Any explicit role selects **only** the mentioned roles. `bass` produces no lead +or drums; `kick on beat 1` selects drums but adds neither snare nor hi-hat. +`drums` alone (also `lead and drums`) selects the full default drum pattern +only in 4/4. If any drum part is explicit, only explicit parts are generated, +even if `drums` also appears. A non-4/4 request selecting drums must provide +one or more explicit drum parts; no 4/4 pattern is silently applied. +Defaults for unselected roles/omitted explicit-subset drum parts are not applied. + +C4=60, C2=36; add the normalized root pitch class, so E gives lead 64/bass 40. +Enharmonics normalize to pitch classes 0..11 and canonical sharp names +(Db -> C#, B# -> C, Cb -> B). Octaves are chosen *after* normalization; B# +lead is C4=60. Key mode is preserved but does not change repeated root patterns. +These are musical defaults, not production instrument ranges or mappings. + +## Exact timing, validation and resource bounds + +All positions/durations are normalized signed Int64 rational quarter notes; +denominators must be positive. Default rational zero is 0/1. Arithmetic uses +checked integer intermediates and rejects results outside Int64 representation. +Tick conversion at **960 PPQ** must be exact and fit signed Int64. +A bar is `numerator * 4 / denominator` quarter notes. Human beat 1 is the +start of the bar; beat N is `(N-1) * 4 / denominator`, **not** N-1 quarter +notes except in /4 meters. Meter numerator is 1..255; denominator must be a +power of two with an exactly tick-representable denominator beat (1..256). + +Quarter/eighth/sixteenth patterns step by 1, 1/2, 1/4 quarter notes. +The subdivision must divide a bar exactly; no partial final note is truncated. +Sustained pitched notes span a full bar. Kick/snare durations are one +denominator beat; hi-hat durations equal its subdivision. Each event starts +at/after zero, has a positive duration and fits within the declared arrangement. +Gaps/rests are allowed: `kick on beat 1` does not need a last-bar-end hit. +The model's declared musical extent is always all bars, independently of the +last event's end. No planning lead-in is added. + +Bars must be a positive Int32; pitch is 0..127 and sounding velocity 1..127. +Tempo must be positive and finite with `60,000,000 / BPM` in the SMF range +1..16,777,215 microseconds per quarter note. That value is rounded to the +nearest integer, midpoint away from zero, as SMF tempo resolution requires; +the requested BPM remains in the model. The parser accepts integer BPM only. +Undefined enum values, empty/duplicate roles, empty selected tracks and +pitched/drum event-kind mismatches are errors. + +One fixed internal generated-event limit is **100,000** notes plus hits +combined (not MIDI note-ons/offs or switches). Exactly 100,000 is accepted; +100,001 is rejected with `event_limit_exceeded`, without expanding patterns. +Counts, arrangement extent and representability are preflighted with checked +arithmetic before allocating event lists. No public limit override, truncation, +randomization or shared mutable result collection exists. + +The validator also checks manually constructed models, independent of parsing. +Parsing/planning return explicit failure results; only expected numeric, +representability and checked-overflow errors are translated to diagnostics. +Profile ranges, articulation support and switch/channel validation remain +Step 4 and require real evidence, currently absent. + +## Standard MIDI output boundary (Step 5) + +The text parser/planner remains unchanged. After successful composition and +explicit profile/event planning, Generation's in-process +`MidiFileWriter.WriteFile(absolutePath, composition, eventPlan, token)` writes +SMF type 1 at 960 PPQ; `Write(stream, composition, eventPlan, token)` borrows a +writable stream. See [the MIDI API guide](../README.md#in-process-standard-midi-generation) +for exceptions, no-overwrite staging, cleanup and synchronous cancellation limits. + +The conductor's tempo/meter stay at zero; every role uses the same planned +lead-in and global end marker, including rests and later control tails. +The four-bar example's **15,360 unshifted ticks** become **15,600** with the +integration tests' invented 240-tick lead-in. Its 32/4/48 musical counts exclude +keyswitch control notes; those test-only numbers are not vendor mappings. + +Requested BPM remains in the model; output metadata rounds the valid quotient +nearest-integer, midpoint away from zero. DryWetMIDI 8.0.3 accepts the actual +meter denominator through **128**; Core continues accepting **256**, but the +writer rejects /256 with a clear library-limitation exception. Each SMF delta +must be at most **0x0FFFFFFF**; the conductor's unsplit end gap also bounds global +`EndTick`. Long gaps fail, never wrap or acquire filler events. These output +constraints do not silently alter parser/Core validation or musical semantics. diff --git a/global.json b/global.json new file mode 100644 index 0000000..3dbe096 --- /dev/null +++ b/global.json @@ -0,0 +1,7 @@ +{ + "sdk": { + "version": "10.0.400", + "rollForward": "latestPatch", + "allowPrerelease": false + } +} diff --git a/prompts/plan.md b/prompts/plan.md new file mode 100644 index 0000000..b67282a --- /dev/null +++ b/prompts/plan.md @@ -0,0 +1,955 @@ +# GAJ3T.MusicGen.Riff-Groove-Builder: Architecture and Execution Plan + +Status: approved for execution by the owner ("Go for it", 2026-10-19). +Issue and review one worker step at a time; all evidence gates remain in force. + +Execution review log: +- Step 1 accepted on 2026-10-19 after reading `report_1.md`, checking scaffold, + tests and compatibility inventory, and independently running Release + build/test: 8 passed, 0 failed, 0 skipped. Editor test discovery was unavailable; + CLI validation succeeded. Native evidence gates remain open. +- Step 2 accepted on 2026-10-19 after reading `report_2.md`, reviewing transport, + dispatch, lifecycle and tool contracts, and independently running Release + build/test: 130 passed, 0 failed, 0 skipped. Production tools remain empty. +- Step 3 accepted on 2026-10-19 after reading `report_3.md`, checking the text + contract, exact-rational model, parser, planner and validator, and independently + running Release build/test: 318 passed, 0 failed, 0 skipped. Step 4 may implement + generic infrastructure, but production readiness still requires real mappings. +- Step 4 infrastructure reviewed on 2026-10-19 after reading `report_4.md`, + checking profile/catalog validation, event planning and ordering, and + independently running Release build/test: 485 passed, 0 failed, 0 skipped. + Independent locked restore also passed. Full Step 4 is BLOCKED, not accepted: + no authorized production mappings or exact installed-product evidence exists. + The embedded production catalog is deliberately empty. +- Scope revision approved by the owner on 2026-10-20: include ABJ, AGLP, AGM, + AGT, AME and AMR as the initial Ample target set, and make instrument expansion + data-driven. The current `step_4_fix.md` implements this catalog extension + without pretending missing mappings are available. No Step 5 prompt had been + issued at that review; later sequencing is recorded below. Full production + mapping readiness remains a separate review gate. +- Step 4 catalog correction iteration 2 accepted on 2026-10-20 after reading + the appended `report_4.md`, reviewing identity/profile binding, strict catalog + loading, selection, availability and data-only extension tests, and + independently running Release build/test: 566 passed, 0 failed, 0 skipped. + Locked restore and whitespace checks also passed. Seven identities are + declared (six Ample plus SD3); zero production mapping profiles are admitted. + This accepts the catalog extension, not the unresolved full Step 4 gate. +- Sequencing decision on 2026-10-20, following the owner's "now what?": + proceed with generic Step 5 MIDI generation using accepted Step 4 + infrastructure and test-only profiles. The decision form was unavailable; + MIDI-engine-first was selected autonomously as the pragmatic next milestone. + No scope or production compatibility gate is waived. Real profile admission + and native/plugin acceptance remain separate outstanding work. +- Step 5 format writer accepted on 2026-10-20 after reading `report_5.md` and + reviewing conversion, file construction, actual read-back tests and staged + no-overwrite output. Worker Release validation passed all 663 tests. + Independent MIDI/shared-pipeline validation passed 106 tests; independent + locked restore also passed. No synthetic profile was admitted to production. + Documented pinned-library limits include unsupported writer meter /256 and + the standard four-byte delta maximum. Native schemas, real profiles, public + generation tools and application acceptance remain outstanding; no Step 6 + prompt has been issued. +- Continuation on 2026-10-20: the owner requested documentation-backed + profiles, native-format investigation and usable tool/deployment work. + `step_4_fix.md`, correction iteration 3, now handles profile sources and + explicitly separates documented default mappings from installation-tested + mappings. Native-format investigation is independent read-only research; + no native writer is authorized without its own evidence. +- Correction iteration 3 accepted for its bounded source-backed subset: + AGLP and AME now have Documented profiles, genuine absolute-number anchors + from official demo MIDI, and disclosed writer policies. Worker Release/full + validation passed 714 tests; independent source/catalog/MIDI validation + passed 299 tests. Five target mappings and all real-plugin acceptance remain + unresolved. This is not full requested-product readiness. +- Native investigation found no authorized AGP/SDP codec or fixture sufficient + for implementation. SD3's shared manual still requires login; indexed + vendor-domain references to SD3P raise an extension question but do not + establish a substitute or an SDP schema. Native outputs remain unavailable. +- Next sequencing: Step 8 may integrate the accepted MIDI writer and admitted + profiles now, exercising the already planned explicit MIDI-fallback policy. + Steps 6/7 are blocked, not completed. Advertise unavailable native capabilities + truthfully, reject disabled fallback, never rename MIDI as a native file, + and fail unavailable selected roles rather than silently dropping them. +- Step 8 supported MIDI/fallback slice accepted after reading `report_8.md`, + reviewing production registration, schemas, selection, generation and output + safety, and independently running the 272 targeted tests. Worker Release + full validation passed 868 tests. Actual stdio calls produce readable MIDI + using the AGLP/AME Documented profiles; unavailable roles/native formats fail + or fall back explicitly. This is not completion of native Steps 6/7. +- Step 9 may now publish and smoke-test this usable local supported slice. + No runtime-free machine or licensed application acceptance is implied by + a successful development-machine publish/smoke check. +- Step 9 supported publication accepted after reading `report_9.md`, reviewing + the publish profile/lock, isolated published-process tests and deployment + guide, and independently passing all 14 published-process checks. Both + ordinary and publication locked restores passed independently. Worker full + validation passed 882 tests. The retained executable and newly generated + example exist with hashes matching the report; runtime-free Windows and + licensed application acceptance remain pending, native Steps 6/7 blocked. +- A bounded read-only follow-up is checking the vendor's other public demo + archives for remaining product-specific numeric anchors. It does not mutate + the accepted published payload or claim additional mappings supported. +- That follow-up established AGM 24/26 from official AGM demo MIDI and ABJ + numeric evidence from a vendor demo explicitly advertised for ABJ/ABP. + The missing dedicated PalmMute threshold does not invalidate an evidenced + Sustain-only bass capability. Correction iteration 4 will integrate those + supported subsets, investigate only the concrete AGT tab-play anchor lead, + and refresh all affected MCP/publish tests, disclosures and publication. + AMR/SD3 and native codecs remain unavailable unless genuine evidence changes. +- Correction iteration 4 and its publication refresh are accepted for the + documented subset after reading both report appends and reviewing the new + facts/capabilities, profile data and actual MIDI/RPC/publication evidence. + AGM and ABJ Sustain-only anchors are established; AGT's vendor-documented + A6 tab control plus official note105 demo establishes its numeric anchor. + Five profiles now ship: AGLP/AGM/AGT/AME Sustain+PalmMute and ABJ Sustain-only. + Worker full validation passed 936 tests; independent focused validation + passed 521, including refreshed published-process checks. Both locked + restore graphs passed independently. Published executable SHA256 is + `921AADE7FB75222E8A7E5E81151F3DC73747CD8036EE751555A613A5DBDD308E`; + the existing AME example remains byte-identical to its accepted report. + AMR, SD3, ABJ PalmMute, native exporters, licensed-application and + runtime-free-host acceptance remain unresolved, not silently completed. + +## 1. Scope and completion criteria + +Build a .NET 10 console application that an MCP client launches as a local process. +It accepts text descriptions through MCP tools over JSON-RPC/stdin/stdout and +generates musical data for: + +| Role | Target | Required native output | +| --- | --- | --- | +| Lead/guitar slot | Ample Guitar LP (AGLP), Ample Guitar M (AGM), Ample Guitar T (AGT), Ample Metal Eclipse (AME) | `.agp`, subject to per-product verification | +| Bass | Ample Bass J (ABJ), Ample Metal Ray5 (AMR) | `.agp`, subject to per-product verification | +| Drums | Superior Drummer 3, using the owner's exact installed version and MIDI mapping | `.sdp` | +| All selected roles | Cubase MIDI import and instrument routing | Standard MIDI `.mid` | + +Use `Melanchall.DryWetMidi` **8.0.3** for every MIDI construction, read, write, and +manipulation operation. Native container serialization is a separate concern: +DryWetMIDI does not establish the proprietary `.agp` or `.sdp` schemas. + +Deliver a self-contained, locally launched executable. Do not add HTTP endpoints, +containers, audio analysis, audio rendering, playback/device control, a GUI, +cloud services, an external LLM dependency, or Cubase `.cpr` generation. + +"Cubase-compatible" means that MIDI imports into Cubase and native files open +through the corresponding instrument's supported load/import workflow. It does +not mean that Cubase opens `.agp` or `.sdp` as Cubase project files. + +Full completion requires verified native outputs for the requested Ample targets and SD3, +MIDI fallback, articulation correctness, passing automated tests, and documented +application-level import checks. A MIDI-only milestone is useful but is not full +completion of this scope. + +## 2. Current repository and evidence gates + +At initial planning, `src`, `docs`, and `prompts` were empty. Steps 1-3 and the +generic Step 4 infrastructure now exist, as recorded above. The layout below +describes the complete intended solution, not a claim that all modules exist. + +### Verified baseline + +- MCP stdio uses UTF-8, newline-delimited JSON-RPC messages, not LSP + `Content-Length` framing. Stdout must contain protocol messages only. +- The MCP lifecycle includes `initialize`, version/capability negotiation, and + `notifications/initialized`. +- The NuGet page for `Melanchall.DryWetMidi` 8.0.3 documents Standard MIDI File + support. This is not evidence of proprietary native-format support. +- .NET supports RID-specific, self-contained, single-file publication. + +### Native-format and articulation gate + +Do not assume `.agp` or `.sdp` is MIDI, XML, JSON, ZIP, or any other container. +Do not guess note numbers from product names or octave labels. + +For profile admission, distinguish source verification from application +acceptance. A `Documented` mapping may encode published vendor defaults whose +numeric mapping facts are supported by cited sources; any timing/routing +engineering policy and version limitations must be explicit compatibility +notes, not invented vendor requirements. It is not an assertion about the +owner's installed configuration. `Verified` remains the application-verified +stage; `Unverified` and `Synthetic` are not production-selectable. Both +selectable stages must retain provenance, correct catalog binding and strict +numeric/state validation. Public generation with a merely documented mapping +must disclose that distinction and its compatibility assumptions. + +If documentation omits a necessary mapping fact, leave that capability/profile +unavailable. Do not fill it with test values. Native schema/template/import +acceptance is a separate gate and is not established by either profile stage. + +Before implementing a production profile or native writer, obtain: + +1. Exact installed product names, versions, and relevant settings for the + selected Ample targets, SD3, and the Cubase version used for acceptance. +2. Lawfully usable vendor documentation or owner-created native fixtures, with + their versions and provenance recorded. Fixtures must not contain audio + libraries, licensed sample content, credentials, or unrelated user projects. +3. Minimal files saved by the target applications: empty/short pattern, one + note/hit, changed pitch, duration, velocity, tempo, and each supported + articulation/control. Change one property at a time. +4. Confirmation of the exact `.agp` and `.sdp` extensions and whether each + represents a riff, groove, preset, or project in that product/version. +5. Verified MIDI mappings: playable ranges, keyswitches, velocity-layer rules, + controller numbers/values, switch timing, persistence, reset behavior, + channel behavior, and the chosen SD3 drum map. +6. A repeatable import procedure and evidence that generated test files reopen + with the intended musical data in the actual target application. + +The public Ample manual URL did not expose a usable format specification during +planning. The SD3 manual page required login. Consequently, no native schema, +specific keyswitch number, or SD3 extension semantics are asserted here. + +If the target application does not support the requested extension or no +validated generation route can be established, stop that step and report the +blocker. Seek an owner decision; do not silently substitute another native +extension, fabricate a file, automate undocumented GUI actions, or declare the +native requirement complete. MIDI fallback is an explicitly reported degraded +result, not proof that the native writer works. + +## 3. Solution layout + +Use three production projects and two xUnit test projects. Avoid one project per +writer or interface. + +```text +GAJ3T.MusicGen.Riff-Groove-Builder.Net\ + GAJ3T.MusicGen.RiffGrooveBuilder.slnx + global.json + Directory.Build.props + Directory.Packages.props + NuGet.config + .gitignore + README.md + src\ + GAJ3T.MusicGen.RiffGrooveBuilder.Core\ + GAJ3T.MusicGen.RiffGrooveBuilder.Core.csproj + Composition\ # Models, validation, supported text grammar/planner + Instruments\ # Vendor-neutral instrument identity metadata + Articulations\ # Profile models, validation, event planning + Generation\ # Request/result types and writer contracts + GAJ3T.MusicGen.RiffGrooveBuilder.Generation\ + GAJ3T.MusicGen.RiffGrooveBuilder.Generation.csproj + Midi\ # DryWetMIDI event construction and SMF writer + Native\ # Separately verified AGP and SDP serializers + Instruments\ # Embedded declarative instrument catalog + Profiles\ # Embedded, versioned, evidence-backed mappings + Output\ # File staging, publication, cleanup + GenerationService.cs # Shared pipeline and explicit fallback policy + GAJ3T.MusicGen.RiffGrooveBuilder.Server\ + GAJ3T.MusicGen.RiffGrooveBuilder.Server.csproj + Program.cs + Protocol\ # Stdio framing, JSON-RPC, MCP lifecycle + Tools\ # Input/output schemas and handlers + Properties\ + PublishProfiles\ + win-x64.pubxml + tests\ + GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\ + GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests.csproj + Composition\ + Articulations\ + Midi\ + Native\ + Protocol\ + GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\ + GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests.csproj + Stdio\ + Generation\ + Publishing\ + Fixtures\ + agp\ # Only permitted, provenance-recorded fixtures + sdp\ + docs\ + text-description-contract.md + format-compatibility.md + articulation-mappings.md + acceptance-tests.md + local-deployment.md + prompts\ + plan.md + step_N.md # Created one at a time, after approval + report_N.md # Written by the worker + step_N_fix.md # Created only when correction is needed +``` + +References: Core has no project dependencies; Generation references Core; +Server references Core and Generation. Tests reference only the projects they +exercise. Core models use musical values and typed event intentions rather than +DryWetMIDI types; Generation translates these intentions through DryWetMIDI. + +Use `System.Text.Json` and .NET base libraries for protocol/configuration work. +Pin DryWetMIDI exactly to 8.0.3 in central package management. Use xUnit, its +compatible test runner, and `Microsoft.NET.Test.Sdk`, selecting and pinning stable +.NET 10-compatible versions during scaffolding. Do not guess package versions. +Record the installed .NET 10 SDK in `global.json` with patch roll-forward. + +### Instrument identity versus mapping profiles + +The owner-requested initial catalog is: + +| Stable instrument ID | Vendor code | Product | Existing role | +| --- | --- | --- | --- | +| `ample-abj` | ABJ | Ample Bass J | bass | +| `ample-aglp` | AGLP | Ample Guitar LP | lead | +| `ample-agm` | AGM | Ample Guitar M | lead | +| `ample-agt` | AGT | Ample Guitar T | lead | +| `ample-ame` | AME | Ample Metal Eclipse | lead | +| `ample-amr` | AMR | Ample Metal Ray5 | bass | +| `toontrack-sd3` | SD3 | Superior Drummer 3 | drums | + +The six Ample library folders identify requested targets, not installed plugin +versions or verified MIDI/native capabilities. Product names and manual links +are confirmed against the vendor's documentation index. The existing lead slot +can hold one selected acoustic or electric guitar; this scope revision does not +add rhythm/strumming patterns, extra simultaneous guitar slots, or new track roles. + +Use a small vendor-neutral `InstrumentDefinition` for stable ID, vendor, +product code/name, role and documentation link. Store the initial definitions +in an embedded JSON catalog, separately from verified `InstrumentProfile` +data. Every profile references its instrument by `InstrumentId`; an instrument +can have multiple versioned mappings without changing the composition planner. + +Declared targets without verified profiles remain visible as +`mapping_unavailable`, never as playable or natively supported. Catalog/profile +validation checks references, role and product identity. Selection must +distinguish unknown instruments, known instruments without mappings, wrong-role +profiles and ambiguous profile choices. Do not choose the first guitar/bass by +folder order or silently substitute a different product. + +Adding another instrument with existing articulation mechanisms means adding a +catalog definition and an evidence-backed mapping profile, not a subclass, +product-name switch or MIDI engine change. Initially this data is embedded: +changes require build/publish. Runtime profile directories, VST scanning, +binary loading, hot reload and a dynamic plugin framework are not included. +Different mechanisms or unverified native formats still require explicit work. + +Keep export behavior behind format-level contracts when the corresponding +writers are implemented. Share an AGP writer across products only where native +evidence permits; do not add per-instrument writer classes speculatively. + +## 4. Modules and execution flow + +```text +MCP client + -> stdio transport / JSON-RPC dispatcher / MCP lifecycle + -> tool schema validation + -> description parser and composition planner + -> validated, instrument-neutral Composition + -> verified instrument profiles and articulation event planner + -> DryWetMIDI MIDI construction + -> requested native serializers and/or Standard MIDI writer + -> staged files, collision-safe publication, structured tool result +``` + +### Core + +- `Composition`: global tempo, meter, key, bar count, and selected role tracks. +- `TrackPlan`: role, profile ID, logical channel, musical notes/hits, and + articulation/control intentions. Keep control notes separate from played notes. +- `MusicalNote`: MIDI pitch, rational beat start/duration, velocity, articulation. + Use integer/rational timing, never cumulative floating-point beat additions. +- `DescriptionParser` / `CompositionPlanner`: deterministic interpretation, + minimal musical pattern construction, and explicit diagnostics. +- `CompositionValidator`: representable timing/tempo, positive duration, valid + MIDI ranges, valid tracks and profiles, checked arithmetic, and actionable + field-level errors. Reject invalid requests rather than silently clamp. +- `InstrumentProfile` / `ArticulationPlanner`: versioned mapping rules and typed + note/CC/switch event intentions. +- Generation contracts describe requested formats, artifacts, warnings, + per-target outcomes, and typed failures. + +### Generation + +- `MidiEventBuilder` / `MidiFileWriter`: the only layer constructing MIDI events + or writing/reading MIDI, always through DryWetMIDI 8.0.3. +- `AgpWriter`: native Ample serialization, with per-instrument capability checks; + share a codec only if evidence establishes the same format. +- `SdpWriter`: native SD3 serialization for the verified product version/type. +- `GenerationService`: preflight, shared composition/event planning, writer + selection, explicit fallback decisions, and result assembly. +- `OutputPublisher`: temporary staging under the chosen output filesystem, + no-overwrite publication, and cleanup of only files created by this request. + A request never reports success before its output files exist. + +### Server + +- `StdioTransport`: newline framing, UTF-8, serialized stdout writes, stderr-only + diagnostics, EOF/cancellation handling, and bounded message handling. +- `JsonRpcDispatcher`: preserve numeric/string request IDs, distinguish requests + from notifications, and map protocol errors correctly. +- `McpSession`: initialization/version/capability state, ping, and shutdown by + stream closure. Advertise only implemented capabilities. +- Tool handlers validate inputs and call the application service; no music + generation logic inside transport handlers. + +Use a small explicit MCP implementation rather than introducing another runtime +SDK dependency. Target MCP version `2025-11-25`; do not imply support for other +versions until tested. If a client requests an unsupported version, respond with +the server's supported version as specified by MCP and let the client decide +whether to disconnect. + +Support `initialize`, `notifications/initialized`, `ping`, `tools/list`, +`tools/call`, and `notifications/cancelled`. Do not introduce HTTP, resources, +sampling, prompts, or asynchronous task capabilities. Read cancellation +notifications while work runs and propagate cancellation to that request; +keep output writes serialized. Notifications receive no JSON-RPC response. +Do not invent an MCP `shutdown` method. + +Use standard JSON-RPC errors for malformed JSON, invalid envelopes, unknown +methods, invalid tool selection/arguments, and unexpected internal failures. +Represent expected generation failures as MCP tool results with `isError: true` +and actionable diagnostics. Log internal details to stderr, not into stdout or +success-shaped results. + +## 5. Text-to-composition contract + +Proposed initial interpretation approach for owner review: a deterministic, +documented English musical-description subset, not an unrestricted language +model. The MCP host can phrase user intent in this supported vocabulary, but +the server must itself transform the supplied text into musical structure. +It must not require an unimplemented external model or hidden network service. + +The first supported vocabulary covers: + +- Tempo, meter, bar count, and key/root, with documented defaults when omitted. +- Lead, bass, and drum role selection. +- Explicit basic note patterns such as eighth-note root riffs, sustained bass + roots, and drum hit placement/subdivision. +- Only articulations supported by the selected verified profile, including + palm mute where the target actually supports it. + +An acceptance description, once corresponding mappings are verified: + +> Generate 4 bars at 120 BPM in E minor, 4/4: palm-muted eighth-note lead guitar, +> sustained root-note bass, kick on beats 1 and 3, snare on beats 2 and 4, and +> closed hi-hat eighth notes. + +Document the accepted grammar and representative paraphrases before writing +the parser. Explicit choices override documented defaults; contradictory or +unsupported instructions return diagnostics rather than being ignored. +Genre labels alone must not imply invented musical semantics. + +This bounded interpretation is a review decision, not a claim to understand +arbitrary prose. If unrestricted natural-language interpretation is required, +resolve that design with the owner before implementation without adding an +external LLM service beyond the approved scope. + +For repeatability, identical text, profiles, and options produce the same +composition. No randomization, training, or audio-derived data is required. +Return the interpreted settings and applied defaults so the client can inspect +what was actually generated. + +## 6. MCP tool contracts + +Keep the public surface to two tools. Publish JSON Schema input and output +contracts with explicit required fields, enum values, and +`additionalProperties: false` for fixed request objects. + +### `list_instrument_profiles` + +Purpose: expose exact target versions, verified mappings, and real writer +capabilities before generation. + +Parameters: + +| Name | Type | Required | Meaning | +| --- | --- | --- | --- | +| `role` | `"lead"`, `"bass"`, or `"drums"` | No | Filter profiles; omit for all | + +Return `ProfileCatalogResult`: + +- `instruments`: declared identities `{ id, vendor, productCode, displayName, + role, documentationUrl, availability }`, including targets with no mappings. + Availability is `mapping_unavailable` or `profile_available`; neither implies + native-writer or local-plugin acceptance. +- `profiles`: array of `{ id, instrumentId, role, productName, productVersion, mappingVersion, + playableRange, articulations, nativeFormats, nativeStatus }`. +- Each articulation identifies supported mechanisms (`keyswitch`, `velocity`, + `cc`, or a verified combination), constraints, and mapping provenance. +- `nativeStatus` is `verified`, `unverified`, or `unsupported`, not a + hard-coded success flag. Never expose guessed profile values as usable. + +### `generate_project` + +Parameters: + +| Name | Type | Required | Meaning | +| --- | --- | --- | --- | +| `description` | Nonempty string | Yes | Supported musical text | +| `outputDirectory` | Absolute local filesystem path | Yes | Destination chosen by caller | +| `projectName` | Safe filename stem | Yes | Shared artifact filename prefix | +| `formats` | Nonempty unique array of `"agp"`, `"sdp"`, `"mid"` | No | Default: applicable native formats for selected roles plus MIDI | +| `profiles` | Object with optional `lead`, `bass`, `drums` profile IDs | No | Override verified defaults for roles present in the description | +| `fallbackToMidi` | Boolean | No | Default: true; explicit degraded output when a requested native writer cannot represent the composition | + +`agp` applies only to selected lead/bass tracks; `sdp` only to a selected drum +track; `mid` includes all selected tracks. Reject an explicit request for a +format with no applicable selected role rather than returning nothing. +Profile IDs resolve their instrument and must match the corresponding roles. +Multiple guitars/basses do not create new role slots. If no unique verified +default exists, return an error identifying the required profile selection; +never choose an instrument by catalog position. + +Return `GenerationResult`: + +```text +status: "complete" | "fallback" | "failed" +interpretedComposition: { tempoBpm, meter, key, bars, roles, defaultsApplied } +artifacts: [{ format, roles, absolutePath, byteCount, profileIds }] +targets: [{ + role, instrumentId, profileId, requestedFormat, + outcome: "written" | "fallback" | "failed", + artifactPaths, reasonCode?, message? +}] +warnings: [{ code, message, role?, requestedFormat? }] +errors: [{ code, message, field?, role? }] +timing: { ticksPerQuarterNote, leadInTicks } +``` + +Represent early parse failures with `interpretedComposition: null` and +`timing: null`; schemas must allow this only for failed results. Success outputs +have non-null values and existing, nonempty files. + +Expected names are `.lead.agp`, `.bass.agp`, +`.drums.sdp`, and `.mid`, as applicable. The combined +MIDI file has named tracks and distinct channels; drums use MIDI channel 10 +(DryWetMIDI zero-based channel 9), subject to the verified target mapping. + +MCP `tools/call` wraps this object in `structuredContent` and also supplies +serialized JSON in a text `content` entry for client compatibility. +`isError` is false for complete or explicitly requested fallback results and +true for failed results. Each tool's `outputSchema` must match its emitted +structured content. + +### Fallback and filesystem semantics + +- Preflight requested native formats and articulation representability. + Native unavailability or unrepresentable native features may trigger MIDI + fallback only when `fallbackToMidi` is true. +- MIDI fallback must retain the complete selected arrangement and mapped + articulations, not just the part that failed. Reuse the same validated event + plan; produce one combined MIDI artifact, not duplicate copies. +- Native failure must be visible per target and in warnings, even when the + MIDI artifact was explicitly requested already. +- Fallback does not excuse an unknown MIDI mapping, invalid input, corrupt + serializer output, unexpected exception, cancellation, or I/O failure. + These are failures with diagnostics. +- With fallback disabled, an unavailable requested native output fails + preflight without publishing partial outputs. +- Validate `projectName` as a filename stem, not a path. Reject traversal, + reserved names, conflicting destinations, and existing final files. + Do not interpret user text as shell commands. +- Stage and validate every planned artifact before publication. Publish with + no-overwrite operations. Multi-file publication is not inherently atomic: + if a later move fails, remove only this request's published files, report + failure, and explicitly report any cleanup failure and remaining paths. +- Cancellation cleans up only request-owned temporary/output files. + Unexpected errors must not become successful fallback results. + +## 7. MIDI and native format handling + +### Standard MIDI + +- Use Standard MIDI File type 1, 960 ticks per quarter note, a conductor track + containing tempo/time signature, and one named track per selected role. +- Convert rational musical positions to ticks using checked arithmetic. + Validate exact representability; do not accumulate floating-point drift. +- Respect MIDI pitch, velocity, channel, and CC ranges. Use explicit note-off + events; generated musical notes have positive duration and velocity. +- Give simultaneous events deterministic ordering: applicable previous + note-offs/resets, state-changing controls/keyswitches, then musical note-ons. + Target-specific exceptions must be evidence-backed and tested. +- Do not derive pitch numbers from ambiguous octave labels. Store absolute + MIDI numbers and document any user-facing octave naming convention. +- Ensure every track ends after its final note-off/control reset, with proper + End-of-Track events and no stuck keyswitch or musical notes. +- Read generated MIDI back with DryWetMIDI and validate semantic content. + Never implement a handwritten parallel MIDI encoder. + +### `.agp` + +- Establish the versioned container and fields using authorized evidence. +- Determine which musical fields and articulation mechanisms the format can + actually express. Preserve necessary structural/version metadata, not + unrelated user state. +- Serialize a new file or modify a permitted minimal template only when that + route is verified. Never distribute arbitrary vendor project assets. +- If the native format embeds MIDI, build/read that payload with DryWetMIDI. + If it stores native note records instead, serialize the native records from + the same validated composition/event plan; do not mislabel them as MIDI. +- Validate each selected Ample product separately. Round-trip or golden tests + are necessary but cannot replace opening generated files in the actual targets. + +### `.sdp` + +- First verify that SD3 supports `.sdp` for the required musical content and + identify its exact load/import workflow and relevant library/map settings. +- Implement only the validated structure and version, following the same + evidence, metadata, MIDI-payload, and template rules as the AGP writer. +- Do not substitute a MIDI file with an `.sdp` extension or substitute another + SD3 file type without owner approval. +- Confirm timing, drum voices/articulations, and velocity in SD3 after import; + record any target limitation instead of silently dropping information. + +Both native writers implement a small common contract for capability checks +and staged output. Share composition and MIDI construction, not speculative +binary-format abstractions. + +## 8. Articulation mapping + +Embed versioned profile data with the published application. No new runtime +profile editor or user plugin system is needed. + +A profile records: + +- Stable ID, role, product/version, mapping version, provenance, and verification + status. +- Playable pitch range, channel allocation, and initial instrument state. +- Canonical articulations and text aliases, such as `palm mute` -> `palm_mute`. +- For each articulation, the verified ordered actions: keyswitch note and + velocity, switch advance/duration, velocity range/layer constraints, + controller number/value, latch/release/reset behavior, and native support. +- Drum voice/articulation notes and any verified CC-dependent state, such as + hi-hat behavior. Do not assume GM matches the installed SD3 configuration. + +Example transformation, deliberately without invented vendor numbers: + +```text +"palm-muted eighth-note lead" + -> canonical articulation "palm_mute" + -> selected Eclips profile lookup + -> verified keyswitch and/or CC actions + -> velocity chosen within the requested/verified layer + -> musical note at its intended position + -> required release/reset actions +``` + +Tests may use clearly labeled synthetic profiles with concrete values. +Production mappings may contain only verified values. A synthetic profile +must never be returned as a supported Eclips, Ray, or SD3 profile. + +Some switches must precede the first musical note. Compute one shared +nonnegative lead-in offset for all tracks from the largest required advance; +shift the whole arrangement consistently and return `leadInTicks`. Do not +clamp negative switch times to zero or shift only one instrument. If a native +format cannot preserve the required timing, report the limitation and apply +the explicit fallback policy. + +Resolve articulation state transitions deterministically. Emit latched changes +when needed; preserve momentary switch semantics; restore state only where +the verified profile requires it. A track-wide keyswitch/CC state cannot express +conflicting simultaneous articulations: reject or use a verified alternative, +never pretend per-note independence. + +Validate unsupported articulations, velocity-layer conflicts, keyswitch/playable +note collisions, and out-of-range notes before writing files. Velocity layering +controls the receiving plugin's samples; the server does not synthesize audio. + +## 9. Test strategy and acceptance + +Use xUnit. All tests are deterministic, isolate temporary output directories, +and clean up only paths they own. Prefer semantic assertions over fragile +whole-file binary comparisons where native metadata is variable. + +### Unit tests + +- Description grammar, paraphrases, defaults, contradictory/unsupported text, + role selection, and the full documented example. +- Musical validation, rational beat-to-tick conversion, bar boundaries, + invalid ranges, representability, and checked overflow. +- Every supported production articulation rule, plus synthetic tests for + keyswitch, velocity-only, CC-only, combined mechanisms, state transitions, + simultaneous conflicts, and shared lead-in. +- DryWetMIDI-read assertions for file type, resolution, tempo, time signature, + note pitch/start/end/velocity/channel, CC values, event ordering, track names, + matching note-offs, and end positions. For a four-bar 4/4 test at 960 PPQ, + the musical extent must be exactly 15,360 ticks plus the stated lead-in. +- Native structural/golden fixtures, version checks, representability failures, + malformed inputs, and no renamed-MIDI shortcuts. +- MCP envelope validation, request IDs, notification behavior, protocol state, + advertised tool schemas, and schema/result agreement. +- Filename validation, collisions, explicit fallback, disabled fallback, + publication/cleanup failures, and cancellation. + +### Integration tests + +- Launch the actual console process; perform initialization, initialized + notification, profile listing, generation, ping, and clean EOF exit. +- Verify each stdout line is a valid protocol message; logs go only to stderr. + Test malformed input, unknown methods/tools, invalid parameters, cancellation, + and multiple requests without response interleaving. +- Generate the documented lead/bass/drum example through MCP, verify returned + files exist and reopen them; check that target outcomes match actual outputs. +- Exercise all requested formats, selected-role combinations, native fallback, + a request already containing MIDI, and failure with fallback disabled. +- Ensure failed/cancelled operations do not leave undisclosed partial files. +- Run the same handshake/generation checks against the published executable + using a working directory unrelated to the repository. + +### Native and Cubase acceptance + +Record product versions, mapping settings, exact reproduction steps, results, +and test-file identifiers in the acceptance document: + +1. Load generated lead and bass AGP files in the corresponding Ample products. +2. Load the generated SDP file in the verified SD3 workflow. +3. Confirm note counts, positions, lengths, tempo/meter where represented, + velocity layers, and articulation switching. +4. Import the MIDI arrangement into Cubase; check track separation, timing, + tempo/meter import settings, and correct instrument/channel routing. +5. Confirm the intended articulation behavior with the installed plugins. + +Application checks are explicit owner/worker-assisted acceptance, not silently +skipped CI tests. If the licensed applications are unavailable, automated tests +may pass, but native compatibility remains pending and must not be reported as +verified. + +## 10. Build and local publication + +All production projects target `net10.0`, enable nullable reference types and +implicit usings, and treat compiler warnings as errors. Keep package versions +centralized, pin DryWetMIDI 8.0.3, and commit dependency lock files once generated. + +The server uses `Microsoft.NET.Sdk` and `OutputType=Exe`, not a web SDK. +Keep runtime-specific settings in the publish profile: + +```xml + + + Release + win-x64 + true + true + false + false + true + true + + +``` + +`win-x64` is the initial reviewable deployment target for this Windows workspace, +not a claim that one executable runs on every architecture. Other RIDs require +separate publication and validation if later requested. Do not add a platform +matrix beyond the approved deployment target. + +Disable trimming/AOT initially to avoid unverified reflection/serialization or +library incompatibilities. DryWetMIDI device/playback APIs are not used. Verify +the pinned package's deployment behavior instead of assuming a dependency-free +publish. Any native extraction requirement must be documented and smoke-tested. + +Expected commands after implementation: + +```powershell +dotnet restore .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx +dotnet build .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-restore +dotnet test .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-build +dotnet publish .\src\GAJ3T.MusicGen.RiffGrooveBuilder.Server\GAJ3T.MusicGen.RiffGrooveBuilder.Server.csproj -p:PublishProfile=win-x64 -o .\artifacts\publish\win-x64 +``` + +Document an MCP client configuration with the absolute executable command and +stdio transport; do not launch via HTTP or assume the client's working +directory. Embedded profiles must load independently of the current directory. +The executable must launch on a matching Windows machine without a separately +installed .NET runtime; verify this on a runtime-free test environment or record +that acceptance as pending. Merely running it on the SDK development machine +does not prove runtime independence. + +## 11. Phased worker sequence + +This sequence describes future prompts. Do not create `step_1.md` until this +plan has been reviewed. Each step includes implementation, directly related +documentation, tests, and a worker report. Do not launch all steps together. + +### Step 1: Bootstrap the .NET 10 solution and compatibility inventory + +- Create the solution, three production projects, two test projects, central + build/package settings, SDK pin, ignore rules, and minimal README. +- Add DryWetMIDI 8.0.3 and the pinned test dependencies; create only minimal + executable behavior, not a placeholder generation success response. +- Create the compatibility inventory and record required native/profile + evidence as verified, missing, or blocked, without inventing values. +- Tests: solution restore/build, xUnit discovery and one meaningful smoke + assertion, and process startup/EOF with no stdout pollution. +- Exit: reproducible .NET 10 build/test and an explicit evidence inventory. + Missing native evidence remains visible as a future gate, not a scaffold + failure or a reason to fabricate fixtures. + +### Step 2: Implement stdio JSON-RPC and MCP lifecycle + +- Implement framing, envelope validation, dispatch, initialization/version + negotiation, ping, notification rules, stderr diagnostics, and clean exit. +- Establish the tool registry and schema infrastructure; do not advertise an + unimplemented generation tool. +- Tests: protocol units and real subprocess handshake, invalid-message + handling, ID preservation, notification silence, serialized writes, EOF. +- Exit: a protocol-correct stdio server, not just a JSON-reading console loop. + +### Step 3: Implement the composition model and text planner + +- Define request/result models, rational musical timing, composition validation, + documented text grammar/defaults, and deterministic basic patterns. +- Keep parser behavior within the reviewed natural-language contract. +- Tests: documented example, paraphrases, defaults, conflicts, unsupported + requests, timing/range failures, and a planner-to-composition integration test. +- Exit: validated lead/bass/drum compositions from supported descriptions, + with no file-format assumptions. + +### Step 4: Implement verified instrument profiles and articulation planning + +- Implement profile loading/validation and switch/velocity/CC event planning. +- Add the six requested Ample instrument definitions and SD3 to a data-driven + catalog, bind versioned profiles by instrument ID, and keep mapping + availability distinct from target identity. No per-product subclasses. +- Add actual selected-instrument mappings only after their evidence gates pass. +- Tests: each supported mapping and all three mechanisms, combined actions, + state changes, layer boundaries, collision/conflict rejection, and shared + lead-in across a multi-track arrangement. +- Exit: tested event plans and evidence-backed production mappings. + If evidence is missing, synthetic tests do not satisfy the production exit + gate. Accepted generic infrastructure may feed Step 5 under the sequencing + decision above; no real instrument support is implied. + +### Step 5: Implement complete Standard MIDI generation + +- Build the shared DryWetMIDI event pipeline and type-1 writer, including + conductor metadata, role tracks, channels, controls, and output staging. +- Tests: exact read-back assertions, long/repeated patterns without timing + drift, switch timing, note-off ordering, invalid input, and multi-role file + generation in isolated temporary directories. +- Exit: valid articulated MIDI covering the complete selected arrangement, + demonstrated with clearly synthetic profiles through the actual file writer. + Format-writer acceptance does not establish production mapping compatibility. + Do not populate guessed profiles or expose production generation tools to + satisfy this milestone. + +### Step 6: Implement and verify Ample AGP generation + +- Require verified schema/template rights and fixtures before writer work. +- Implement the smallest evidence-backed writer route for the selected Ample products, + including representability checks and version handling. +- Tests: native fixture/structure tests, generated-file semantic checks, + unsupported data failures, and integration with the shared composition plan. +- Exit: generated AGP files reopen correctly in the selected target products, with + acceptance evidence. Structural tests alone do not close this step. + +### Step 7: Implement and verify Superior Drummer SDP generation + +- Require confirmation of `.sdp` semantics, schema, and the installed drum map. +- Implement the supported native writer route without inventing its structure. +- Tests: fixtures/structure, drum mapping, timing/velocity/articulation content, + unsupported features, and integration with the composition/event plan. +- Exit: a generated SDP file reopens correctly in SD3 with recorded acceptance. + An extension mismatch is a scope blocker requiring owner resolution. + +### Step 8: Wire production MCP tools and explicit MIDI fallback + +- Expose the final two tool contracts and connect the full generation service. +- Complete preflight, per-target results, publication rollback/cleanup, + cancellation, profile discovery, and explicit fallback policies. +- Tests: real stdio calls covering all roles/formats, complete/fallback/failed + output shapes, no-overwrite behavior, native unavailability, I/O errors, + cleanup failures, and cancellation. +- Exit: working text-to-files MCP workflow with truthful, schema-valid results. + The MIDI/fallback slice can be accepted while native codecs remain + unavailable; that does not complete Steps 6/7 or the full product scope. + +### Step 9: Publish and complete Cubase/plugin acceptance + +- Add the publish profile, local MCP configuration instructions, and release + acceptance procedures; embed/load profiles without working-directory + assumptions. +- Tests: Release build/test, self-contained publish, published-process + handshake/generation from another directory, runtime-free deployment check, + and the documented Cubase/Ample/SD3 acceptance matrix. +- Exit: reproducible local deployment and all full-scope completion criteria. + Record unavailable manual/environment checks as pending, never as passes. + +Dependencies: 2 and 3 require the scaffold in 1; Step 4 infrastructure requires +3, while its production acceptance also requires verified mapping evidence. +Step 5 requires 3 and accepted Step 4 infrastructure, not completed production +mapping admission. Steps 6 and 7 require 5 plus their applicable production +profiles and native evidence. Step 8's MIDI/fallback slice requires 2, 5, +admitted selected profiles and truthful native-capability preflight; native +success paths require 6/7. Step 9 may publish the usable supported slice, +while full-scope application acceptance still requires the missing native +and product evidence. The orchestration workflow still issues and reviews +only one worker step at a time. Do not bypass production gates; document any +sequencing decision before issuing the affected prompt. + +## 12. Worker prompt and report protocol + +For each approved step, write only that step's detailed worker prompt to +`prompts\step_N.md`. Include: + +1. Objective, scope boundaries, prerequisites, and exact plan exit criteria. +2. Explicit files to create/modify, expanded from the modules listed here. +3. Implementation details, public contracts, verified evidence, and forbidden + assumptions. Instruct the worker to read existing code and preserve others' + work before editing. +4. Required unit and integration test cases, exact validation commands, and + objective expected outputs. Use the smallest covering test selection during + development and appropriate build/integration checks at completion. +5. Documentation changes and any required owner-assisted acceptance. +6. This exact instruction: + +> When complete, write your end-of-step report to ./prompts/report_N.md including: what was implemented, test results (pass/fail with details), any issues encountered, and whether you're ready for the next step + +Replace `N` with the actual step number in the issued prompt. Also require +changed files, commands/exit codes, test counts, unrun/skipped checks and reasons, +compatibility evidence, and explicit blockers. Reports must distinguish +automated results from application-level/manual acceptance. Put the end-of-step +report entirely inside one plain triple-backtick fence, without outside prose. + +After issuing a prompt, wait for the worker's report. Do not implement the +worker's step concurrently or issue a later step in advance. + +### Orchestrator review gate + +Read `prompts\report_N.md` before deciding anything about progression: + +- Compare actual changes and tests with the step objective, contracts, and exit + criteria; a worker's "ready" statement is not sufficient. +- Check actual test evidence and perform focused code/test verification where + needed. Do not infer compatibility from compilation or fixture comparisons. +- Check for scope expansion, placeholder native formats, guessed mappings, + ignored requirements, silent fallbacks, or misleading result statuses. +- Treat failing tests, missing required tests, unrun acceptance, unresolved + blockers, and contradictory reports as not ready. + +If accepted, record the review decision and then create only the next prompt. +If not accepted, create `prompts\step_N_fix.md` with precise findings, bounded +corrections, regression tests, and a requirement to update the corresponding +report with correction evidence. Review that report again before progressing. +If another correction is needed, revise the same fix prompt with a clearly +identified iteration rather than skipping ahead. + +For missing proprietary evidence or product incompatibility, request an owner +decision and adjust the plan only with approval. Do not ask the worker to +"make the tests pass" by weakening assertions, inventing a native schema, or +reclassifying a blocked requirement as complete. + +## 13. Review checklist before execution + +- Approve the three-project architecture, two-tool contract, and sequential + worker/report gates. +- Confirm the deterministic supported-language approach and initial vocabulary. +- Confirm the initial `win-x64` local self-contained deployment target. +- Supply or arrange authorized native-format fixtures, exact product versions, + articulation maps, and access for application-level acceptance. +- Resolve any `.sdp` extension/workflow mismatch before native implementation. + +The owner has approved execution. Create and review worker prompts sequentially, +starting with `prompts\step_1.md`; approval does not waive native evidence gates. + +## 14. Primary references consulted + +- [MCP 2025-11-25 stdio transport](https://modelcontextprotocol.io/specification/2025-11-25/basic/transports) +- [MCP lifecycle and version negotiation](https://modelcontextprotocol.io/specification/2025-11-25/basic/lifecycle) +- [MCP tools and schemas](https://modelcontextprotocol.io/specification/2025-11-25/server/tools) +- [Melanchall.DryWetMidi 8.0.3 on NuGet](https://www.nuget.org/packages/Melanchall.DryWetMidi/8.0.3) +- [DryWetMIDI documentation](https://melanchall.github.io/drywetmidi/) +- [.NET single-file and self-contained publication](https://learn.microsoft.com/en-us/dotnet/core/deploying/single-file/overview) +- [Ample Sound manual entry point](https://www.amplesound.net/en/manual.asp) + (no usable native schema obtained during planning) +- [Superior Drummer 3 manual entry point](https://www.toontrack.com/manual/superior-drummer-3/) + (login required during planning) diff --git a/prompts/report_1.md b/prompts/report_1.md new file mode 100644 index 0000000..cb3489f --- /dev/null +++ b/prompts/report_1.md @@ -0,0 +1,164 @@ +``` +STEP 1 REPORT — Bootstrap and compatibility inventory +Date: 2026-10-19 +Step 1 readiness: TRUE — all required scaffold validations pass. +Ready for the next step: TRUE, subject to orchestrator review/acceptance. +Full product/native compatibility readiness: FALSE; future evidence gates remain. + +IMPLEMENTED +- Generated the .NET 10 XML solution, three production projects and two xUnit + projects using dotnet scaffolding without template restores. +- All five projects use Microsoft.NET.Sdk and net10.0. Common properties enable + nullable, implicit usings, warnings-as-errors and NuGet dependency lock files. + Only Server has OutputType=Exe. +- Reference graph: + Core: no project/package dependencies. + Generation: Core + Melanchall.DryWetMidi 8.0.3. + Server: Core + Generation. + UnitTests: Core + Generation. + IntegrationTests: Server build dependency, ReferenceOutputAssembly=false. +- Server only drains stdin until EOF and exits successfully. It emits no + greeting, stdout, normal-operation stderr or fake JSON-RPC responses. +- Exact central package version ranges, official NuGet-only source, private + test dependencies, generated locks, build/test/IDE ignore rules. +- Unit metadata/dependency smoke tests and real apphost subprocess tests. + Build copies Server output beside the tests; binary discovery uses + AppContext.BaseDirectory, not developer paths or the runner's working directory. +- README records scaffold-only status, prerequisites, commands and evidence + requirements. Compatibility inventory separates public planning facts from + unknown native schemas, mappings, rights and unperformed application checks. +- Removed generated Class1.cs, UnitTest1.cs and Hello World code. No placeholder + domain modules, protocol, music parser, profiles, writers or publish workflow. + +TOOLCHAIN AND PACKAGES +- Installed SDK: 10.0.400, C:\Program Files\dotnet\dotnet.exe. + Installed runtime: 10.0.11; Windows x64. +- global.json: version 10.0.400; rollForward=latestPatch; allowPrerelease=false. +- Melanchall.DryWetMidi: 8.0.3, exact range [8.0.3]. +- xunit: 2.9.3, exact range [2.9.3]. +- xunit.runner.visualstudio: 4.0.1, exact range [4.0.1]. +- Microsoft.NET.Test.Sdk: 18.11.0, exact range [18.11.0]. +- Stable versions and dependency framework groups were checked against official + https://api.nuget.org/v3-flatcontainer//index.json and the selected + version's .nuspec before restore. Adapter/test SDK offer net8.0 assets; + DryWetMIDI offers .NET Standard 2.0. Actual net10.0 build/test succeeded. +- No separate coverage package was added. Microsoft.CodeCoverage 18.11.0 in + test locks is the test SDK's transitive dependency. +- All five packages.lock.json files were generated by NuGet restore, not edited. + +CHANGED FILES (22 worker-created deliverables; paths relative to repository) + .gitignore + global.json + Directory.Build.props + Directory.Packages.props + NuGet.config + GAJ3T.MusicGen.RiffGrooveBuilder.slnx + README.md + docs\format-compatibility.md + src\GAJ3T.MusicGen.RiffGrooveBuilder.Core\GAJ3T.MusicGen.RiffGrooveBuilder.Core.csproj + src\GAJ3T.MusicGen.RiffGrooveBuilder.Core\packages.lock.json + src\GAJ3T.MusicGen.RiffGrooveBuilder.Generation\GAJ3T.MusicGen.RiffGrooveBuilder.Generation.csproj + src\GAJ3T.MusicGen.RiffGrooveBuilder.Generation\packages.lock.json + src\GAJ3T.MusicGen.RiffGrooveBuilder.Server\GAJ3T.MusicGen.RiffGrooveBuilder.Server.csproj + src\GAJ3T.MusicGen.RiffGrooveBuilder.Server\Program.cs + src\GAJ3T.MusicGen.RiffGrooveBuilder.Server\packages.lock.json + tests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests.csproj + tests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\ScaffoldTests.cs + tests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\packages.lock.json + tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests.csproj + tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\Stdio\ProcessStartupTests.cs + tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\packages.lock.json + prompts\report_1.md + +VALIDATION COMMANDS AND RESULTS +Initial toolchain inspection: + & 'C:\Program Files\dotnet\dotnet.exe' --list-sdks + Exit 0: 10.0.400 [C:\Program Files\dotnet\sdk] + & 'C:\Program Files\dotnet\dotnet.exe' --info + Exit 0: SDK 10.0.400; runtime 10.0.11; RID win-x64. + +dotnet was not initially on the worker shell's PATH. For validation shells: + $env:PATH = 'C:\Program Files\dotnet;' + $env:PATH + $env:DOTNET_CLI_TELEMETRY_OPTOUT = '1' + $env:DOTNET_NOLOGO = '1' +This was process-local only. No machine-wide tooling installation/change. + +1. dotnet restore .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx + PASS, exit 0. All five projects restored; five lock files generated. + +2. dotnet build .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-restore + FINAL PASS, exit 0. All five projects built; 0 warnings, 0 errors. + An initial run exited 1 with MSB4012 in the integration artifact-copy target: + MSBuild disallowed concatenating an item transform and a wildcard. Corrected + by putting the resolved Server output directory into a property before globbing. + Repeating the same build command passed. + +3. dotnet test .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-build + PASS, exit 0. Two test assemblies discovered; nonempty execution: + UnitTests: 4 passed, 0 failed, 0 skipped (267 ms reported duration). + IntegrationTests: 4 passed, 0 failed, 0 skipped (386 ms reported duration). + TOTAL: 8 passed, 0 failed, 0 skipped. + +4. dotnet restore .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx --locked-mode + PASS, exit 0. All five projects restored against generated dependency locks. + +Additional checks: +- Editor runTests was attempted with both exact absolute test-file paths. + It returned "No tests found in the files"; this was NOT counted as a pass. + The CLI above independently discovered/executed all eight xUnit cases. +- Editor problems check over src/tests: no errors found. +- git --no-pager diff --check: exit 0. +- Project/lock/prompt-preservation PowerShell audit: exit 0. Verified all five + SDK/target settings and locks, DryWetMIDI resolved only as 8.0.3, unchanged + existing prompt hashes, and no trailing whitespace in untracked source/docs. + +TEST COVERAGE AT THIS STEP +- Three unit theory cases inspect compiled target-framework attributes for + Core, Generation and UnitTests: .NETCoreApp,Version=v10.0. +- One unit fact verifies Generation's resolved runtime-manifest dependency is + exactly DryWetMIDI 8.0.3 and constructs an in-memory MidiFile/TrackChunk using + that package. No production MIDI logic was added to satisfy the test. +- Four integration theory cases start the real Server.exe: + test-output working directory + empty input; + test-output working directory + multiline input; + C:\WINDOWS\system32 + empty input; + C:\WINDOWS\system32 + multiline input. + Each closes stdin, drains stdout/stderr concurrently, and requires exit 0 and + empty stdout/stderr. Server and IntegrationTests compiled framework metadata + are also checked, covering all five projects across the suites. +- Each subprocess has a 15-second operation timeout, bounded cleanup/draining, + process disposal, and failure cleanup scoped to the created process tree. + No process-name killing. The unrelated OS directory is used read-only; + no directories/files are created outside the checkout by these tests. + +ISSUES, SKIPPED CHECKS AND EVIDENCE GATES +- Resolved environment issue: dotnet missing from PATH, installed SDK safely + used via its known executable/current-shell PATH. No install required. +- Resolved implementation issue: initial MSB4012 copy glob, corrected and rebuilt. +- Editor test discovery unavailable for these files; CLI test validation passed. +- No required scaffold check remains skipped or failed. +- No native fixtures or mapping evidence supplied. Exact installed Eclips, + Ray, SD3 and Cubase identities/versions/settings remain unknown. +- AGP lead/bass and SDP containers/schemas and supported load paths/extensions + remain unknown. In particular, SD3 support for the requested .sdp semantics is + not asserted. A mismatch requires an owner decision, not a substituted file. +- Fixture provenance, redistribution/template permission, absolute notes, + switches, CCs, layers/ranges, channels, reset/state/timing rules and SD3 + library/map settings remain missing. +- Real plugin/native reopening, Cubase MIDI import/articulation acceptance, + publishing and runtime-free deployment were NOT PERFORMED: later-step work + requiring implementations and/or owner-supplied licensed environment. +- Future gates: Step 4 production profiles require real mapping evidence; + Steps 6/7 require native schemas, authorized fixtures/rights and actual native + acceptance; Step 9 requires deployment and Cubase/plugin acceptance. + These do not invalidate Step 1 and do not establish full product readiness. + +PRESERVATION AND STOP BOUNDARY +- prompts\plan.md was already modified and prompts\step_1.md already untracked + on entry. Neither was changed by this worker; SHA256 verified unchanged: + plan.md: 7E876E1EE0B02AB6D246BCE26DCF346B1E32D1683B771FA9B90A476769EB8DE5 + step_1.md: 03A51C17645BCB7AC58F02648928FC85B4E32CDB1FF5A458878FB574E63AB0CF +- Build/test binaries and intermediate outputs are ignored, not deliverables. + No scratch files, credentials, vendor assets, new tooling or later-step prompts. +- No commits, delegation or Step 2 implementation. Stopping after this report. +``` diff --git a/prompts/report_2.md b/prompts/report_2.md new file mode 100644 index 0000000..190e7fa --- /dev/null +++ b/prompts/report_2.md @@ -0,0 +1,190 @@ +``` +STEP 2 REPORT — Stdio JSON-RPC and MCP lifecycle +Date: 2026-10-19 +Step 2 readiness: TRUE — required automated checks pass. +Ready for the next step: TRUE, subject to orchestrator review/acceptance. +Full product/native compatibility readiness: FALSE; native evidence is unchanged. + +IMPLEMENTED +- Replaced the input-discard entry point with the .NET 10 stdio MCP server. + Raw protocol streams use UTF-8; stdout contains protocol messages only. + Console diagnostics use UTF-8 stderr, with no startup banner. +- Added bounded newline framing, LF/CRLF acceptance, strict UTF-8 rejection, + serialized complete output writes, per-message flushes and stream ownership. +- Implemented JSON-RPC envelope validation, string/signed-Int64 ID preservation, + batch rejection, duplicate-envelope rejection, explicit protocol errors and + per-request exception/result-serialization boundaries. Actual transport I/O + failures propagate to the entry point and exit nonzero instead of succeeding. +- Implemented initialize, notifications/initialized, ping, tools/list, tools/call + and notifications/cancelled. Version negotiation supports only 2025-11-25, + including returning it as the alternative for an unsupported requested version. +- Initialization validates required fields and known optional client metadata, + icons, nested capability shapes and request metadata. Client capabilities are + not acted on. Ping works at every lifecycle stage; tools require the complete + handshake. Repeated initialization and premature tool requests fail explicitly. +- Production registry is empty: tools/list returns {"tools":[]}. Only the tools + capability is advertised, with listChanged=false. No profile/generation tools, + guessed mappings, fake writers or test-only tools are registered in production. +- Added thread-safe registration/lookup, deterministic discovery and registry + freezing when the session starts. Typed tool contracts use the BCL JSON Schema + exporter and the same strict serializer for schemas, inputs and outputs. + Handlers support semantic input validation, request cancellation, structured + output plus matching JSON text content, and expected isError=true outcomes. +- Added bounded active-request tracking. Awaiting handlers do not prevent reading + notifications/unrelated requests. String/numeric IDs are distinct. Duplicate + active IDs are rejected without replacing/cancelling original work. +- EOF and lifetime cancellation (wired to Ctrl+C) cancel outstanding handlers and + await cleanup. Valid notifications never receive responses. Cancelled work + normally emits no response; unrelated work survives per-request cancellation. +- Updated README and added the current protocol contract. The compatibility + inventory now links to Step 2 without rewriting its historical native evidence. + +PROTOCOL LIMITS AND DECISIONS +- Incoming limit: 1,048,576 UTF-8 bytes, excluding LF or CRLF. Fixed limit-plus-one + frame buffer and 4 KiB read buffer; oversized remainders are drained, not stored. + Exactly the limit is accepted, including with CRLF. One bounded error and fixed + stderr diagnostic is emitted per oversized frame, then the next frame is read. +- Invalid UTF-8: -32700, no replacement decoding. BOM is not stripped. + System.Text.Json's default maximum nesting depth is 64. +- Empty stream: silent EOF. Blank line: parse error. Nonempty final frame without + newline: processed exactly once; malformed final JSON/UTF-8 returns an error. +- IDs: strings or signed 64-bit integer tokens. Decimal/fractional/exponent, + null, boolean, array/object and out-of-range numeric IDs are unsupported. + Unidentifiable/ambiguous IDs use null in errors. +- At most 64 active requests; excess requests return -32000. Invalid lifecycle + state returns -32002. Standard errors: -32700 parse, -32600 invalid request/ + oversized frame/duplicate active ID, -32601 unknown method, -32602 invalid + params/tool selection, -32603 unexpected handler or serialization failure. +- No pagination cursor is issued; supplied cursors are rejected. Fixed method + parameter objects reject unknown fields, including task augmentation; _meta + accepts extension fields and validates request progressToken type. +- Registry is immutable during a session; no list-change notifications. + Typed contracts are not a general arbitrary-JSON-Schema validation engine; + domain constraints belong in registered validators/handlers. +- Cancellation never targets initialize or the entire server. Invalid/unknown/ + completed cancellation IDs are ignored. Already-started output writes complete, + so a cancellation race may still deliver a late response. +- No shutdown method, resources, prompts, sampling, elicitation, logging RPCs, + task APIs, HTTP, server-initiated requests or generation behavior was added. + +CHANGED FILES (21 deliverables, including this report) + README.md + docs\mcp-protocol.md + docs\format-compatibility.md + src\GAJ3T.MusicGen.RiffGrooveBuilder.Server\Program.cs + src\GAJ3T.MusicGen.RiffGrooveBuilder.Server\Protocol\StdioTransport.cs + src\GAJ3T.MusicGen.RiffGrooveBuilder.Server\Protocol\JsonRpcDispatcher.cs + src\GAJ3T.MusicGen.RiffGrooveBuilder.Server\Protocol\McpSession.cs + src\GAJ3T.MusicGen.RiffGrooveBuilder.Server\Protocol\McpParameters.cs + src\GAJ3T.MusicGen.RiffGrooveBuilder.Server\Protocol\JsonRpcError.cs + src\GAJ3T.MusicGen.RiffGrooveBuilder.Server\Tools\McpToolRegistry.cs + src\GAJ3T.MusicGen.RiffGrooveBuilder.Server\Tools\McpToolDefinition.cs + tests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests.csproj + tests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\packages.lock.json + tests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\Protocol\StdioTransportTests.cs + tests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\Protocol\JsonRpcDispatcherTests.cs + tests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\Protocol\McpSessionTests.cs + tests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\Protocol\ProtocolTestConnection.cs + tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\Stdio\ProcessStartupTests.cs + tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\Stdio\McpProtocolTests.cs + tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\Stdio\McpProcess.cs + prompts\report_2.md + +DEPENDENCIES AND VALIDATION +No package was added or upgraded. UnitTests now also references Server. A normal +restore after that project-manifest change regenerated its dependency lock with +the Server project entry; central versions and DryWetMIDI 8.0.3 are unchanged. + +All dotnet commands ran from the repository root with process-local settings: + $env:PATH = 'C:\Program Files\dotnet;' + $env:PATH + $env:DOTNET_CLI_TELEMETRY_OPTOUT = '1' + $env:DOTNET_NOLOGO = '1' +No global PATH/tool installation changes were made. + +1. dotnet restore .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx + PASS, exit 0, five projects restored after the project reference change. + +2. dotnet test .\tests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests.csproj -c Release --no-restore --filter FullyQualifiedName~Protocol + Development run 1: exit 1, CS9007 in two test raw interpolated strings. + Fixed the test interpolation delimiter counts. + Development run 2: exit 1, 103 passed / 1 failed / 0 skipped. The Unicode ID + assertion compared raw escape spelling instead of decoded JSON ID value. + Corrected it to assert ID type and decoded value (not weaken ID preservation). + Subsequent combined protocol runs passed. + +3. dotnet test .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-restore --filter 'FullyQualifiedName~Protocol|FullyQualifiedName~ProcessStartup' + PASS, exit 0. First successful run: 104 protocol units + 14 process cases. + Final targeted run after added regressions: 112 protocol units + 14 process + cases = 126 passed, 0 failed, 0 skipped. + +FINAL REQUIRED ACCEPTANCE COMMANDS +4. dotnet build .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-restore + PASS, exit 0. All five projects built, 0 warnings, 0 errors. + +5. dotnet test .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-build + PASS, exit 0. Both xUnit test assemblies discovered and executed: + UnitTests: 116 passed, 0 failed, 0 skipped (110 ms). + 112 protocol cases + all 4 retained framework/dependency smoke cases. + IntegrationTests: 14 passed, 0 failed, 0 skipped (936 ms). + 4 updated startup cases + 10 additional real-apphost protocol cases. + TOTAL: 130 passed, 0 failed, 0 skipped. + +6. dotnet restore .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx --locked-mode + PASS, exit 0. All five projects restored against their generated locks. + +Additional checks: +- Editor problems tool over src/tests: no errors found (final check). +- git --no-pager diff --check: PASS, exit 0. +- PowerShell trailing-whitespace audit: PASS, exit 0; 29 source/test/doc/lock + files checked, excluding bin/obj. No scratch artifacts were created. +- PowerShell SHA256 preservation audit: PASS, exit 0. The existing orchestrator + prompts and Step 1 report match entry hashes, including the pre-existing + modified plan: + plan.md: 421BE54DC8D428D813BE8A03CA7263C4A981158512191F02789409AF5AEE8677 + step_1.md: 03A51C17645BCB7AC58F02648928FC85B4E32CDB1FF5A458878FB574E63AB0CF + step_2.md: BC6E4DB1A329F02E2DE12EE9C5ED9370390AE12AA585BA557AB47E0B13688E7B + report_1.md: 5B8DFA296AC728CEB6AFFC404D12AACD20FF9C9FE69E3793F6741C728F5AE416 + +TEST EVIDENCE +- Unit transport coverage includes UTF-8/non-ASCII, escaped newlines, invalid + UTF-8 including final EOF, empty/blank/final frames, LF/CRLF, byte limits, + multi-buffer oversize resynchronization, concurrent serialized writes, flushes, + borrowed stream ownership and idle-read cancellation. +- Dispatcher/session coverage includes supported/invalid IDs, malformed JSON, + envelopes/batches, notification silence, initialization validation/version/ + state, ping, empty registry, test-only discovery/schema/result agreement, + strict typed/semantic argument validation and expected tool execution errors. +- Awaiting synthetic handlers exercise cancellation, unrelated request survival, + string/integer ID distinction, duplicate active IDs, overlapping completion, + admission bounds, EOF/lifetime cancellation, internal exceptions, response + serialization failure recovery and actual read/write I/O failure propagation. +- Real Server apphost tests exercise the complete handshake, empty discovery, + ping, no notification reply, per-line valid JSON-RPC, malformed input then + valid requests on the same connection, unknown methods/tools, invalid params, + unsupported-version alternative, repeated initialization, exact 1 MiB/oversize/ + invalid-UTF-8 frames and final non-newline frames. +- Apphost cases run beside test output and in the existing unrelated Windows + system directory. Every process has a 15-second operation timeout, concurrent + stdout/stderr draining, exit-zero assertions and bounded process-owned cleanup. + No process-name killing or filesystem writes outside the checkout are used. + +ISSUES, UNRUN CHECKS AND READINESS +- Resolved the two development-test issues described above; no production + protocol failure remains in final validation. +- Editor test discovery was already known unavailable from Step 1. Used the + explicitly approved CLI fallback; no required test was skipped or counted + from an empty discovery result. +- Ctrl+C's lifetime-token path is unit-tested. An actual interactive Windows + console control event was not injected; real-process EOF shutdown is tested. +- No native/application/deployment checks were performed: composition, real + profiles, MIDI/native writers, publication and licensed plugin/Cubase + acceptance remain later-step work, not Step 2 claims. +- Exact product/version/settings, native schemas/extension semantics, authorized + fixtures/template rights and verified articulation mappings remain missing. + MCP implementation/testing does not establish AGP/SDP or Cubase compatibility. +- No unresolved Step 2 blocker. Automated Step 2 exit criteria are satisfied. + Orchestrator review is still required before progression. +- Preserved prior scaffold work and existing prompt changes. No commits, + delegation, new orchestrator prompts or future-step implementation. + Stopping after this report. +``` diff --git a/prompts/report_3.md b/prompts/report_3.md new file mode 100644 index 0000000..33b6889 --- /dev/null +++ b/prompts/report_3.md @@ -0,0 +1,203 @@ +``` +STEP 3 REPORT — Instrument-neutral composition and deterministic text planning +Date: 2026-10-19 +Step 3 readiness: TRUE — implemented and verified; ready for orchestrator review. +Ready to satisfy Step 4 production exit criteria: FALSE — real mapping evidence +is still absent. Acceptance of Step 3 does not close that evidence gate. + +IMPLEMENTED +- Wrote docs\text-description-contract.md before implementing the parser. + It explicitly defines the bounded English grammar, supported paraphrases, + defaults, role/subset semantics, timing convention, numeric/resource limits + and unsupported instructions. README now describes the in-process API and + distinguishes composition planning from public MCP generation. +- Added dependency-free Core composition models: global BPM, typed meter/key/ + mode, bars, role tracks, absolute pitched notes, logical drum hits, typed + articulation intentions, immutable collection snapshots and applied defaults. + No production profile IDs, playable ranges, channels, vendor switch values + or guessed SD3 MIDI pitches were introduced. +- Added normalized immutable signed-Int64 BeatFraction quarter-note timing. + Default zero is 0/1; denominators must be positive. Arithmetic/comparison + uses checked Int128 intermediates and checked normalized Int64 results. + Conversion to 960 PPQ ticks is exact or fails; no floating-point beat drift. +- Added explicit settings/model validation: positive finite SMF-representable + tempo, meter fields and denominator-beat representability, positive bars, + normalized key/mode, distinct selected roles, nonempty tracks, correct event + kinds, pitch 0..127, sounding velocity 1..127, typed articulation/drum voice, + nonnegative starts, positive durations, exact timing and full event extent. + Declared extent remains all bars even with trailing rests. +- Added parser/planning failure results with stable codes, fields, actionable + messages and offending text where applicable. Failures expose no partial + usable description/composition. Meaningful unconsumed text is rejected. + Expected arithmetic/representability catches are confined to timing/count + preflight and validation, not arbitrary exceptions or fallback-to-defaults. +- Added deterministic root quarter/eighth/sixteenth and full-bar sustained + pitched patterns, explicit kick/snare denominator-beat placement and closed + hi-hat subdivisions. Track ordering and simultaneous hit ordering are stable. + All pattern counts and extent are checked before expanding event lists. +- IntegrationTests now directly references Core. Its existing apphost-copy + target explicitly queries only Server, preventing the added reference from + contaminating server-output discovery. Refreshed its generated lock file. + No new package or package-version change was necessary. +- Retained all previous protocol/scaffold/process tests. No Server production + source changed: its real MCP registry remains empty. Full retained real- + process tests verify that behavior alongside the new in-process pipeline. + +GRAMMAR, DEFAULTS AND LIMIT DECISIONS +- Accepted settings: unsigned ASCII integer BPM; positive Int32 bars (also + one through sixteen in words); numerator/denominator meter; A..G roots with + optional #/b/Unicode sharp/flat and major/minor mode. +- Role aliases: lead guitar/lead/guitar, bass, drums. Supported pitched + modifiers are sustain/palm-muted/palm mute, root-note subdivisions and + sustained roots. Hyphen/space variants, case, whitespace and ordinary + clause punctuation are documented. Modifiers bind to their own role. +- Repeated identical clauses/settings deduplicate; conflicting duplicates, + duplicate beat positions, malformed numbers, unsupported articulations, + genres, chords, tuning, arbitrary melody/dynamics and unknown words fail. +- Defaults: 120 BPM, four bars, 4/4, E minor; lead root octave 4 (C4=60), + bass root octave 2 (C2=36), velocity 96 and sustain articulation. + Enharmonics normalize before selecting the octave: E gives lead 64/bass 40, + B# gives C4/C2, Cb gives B4/B2. These are musical choices, not mappings. +- If no role or drum part is mentioned, select all three. Otherwise select + only explicit roles. Lead defaults to root eighth notes; bass defaults to + one full-bar root note per bar. +- Bare drums in 4/4 defaults to kick 1/3, snare 2/4, eighth-note closed hi-hat. + Any explicit drum part selects only supplied parts, including with a bare + drums clause; no omitted drum part is silently added. Non-4/4 drums require + explicit parts. Every applied default has a field and value; defaults for + unselected roles/omitted subset parts are not applied. +- Meter numerator: 1..255. Denominator: power of two, 1..256, so the human + denominator-note beat is exactly representable at 960 PPQ. In 3/8, beat 2 + is 480 ticks after the bar start, not 960. Bar length is numerator*4/ + denominator quarter notes. Subdivisions must divide the whole bar exactly. +- SMF tempo requires 60,000,000/BPM in 1..16,777,215 microseconds per quarter; + nearest-integer rounding, midpoint away from zero, is documented for future + encoding. Requested BPM remains unchanged in the composition. +- Fixed internal limit: 100,000 generated notes plus logical hits combined. + Exactly 100,000 passes; 100,001 fails with event_limit_exceeded before + pattern expansion. No public override or truncation. Description text is + bounded to 16,384 UTF-16 characters. Checked counts use Int64. + +ACCEPTANCE EXAMPLE AND TEST EVIDENCE +- The exact plan description produces all three tracks, four bars at 120 BPM + in E minor, 4/4, zero planning lead-in, extent 16 quarter notes/15,360 ticks. +- Lead: 32 E4/MIDI-64 palm-mute notes, starts every 480 ticks, duration 480. + Bass: four E2/MIDI-40 sustain notes, starts every 3,840 ticks, duration 3,840. + Kick: eight hits on beats 1/3; snare: eight on beats 2/4; closed hi-hat: + 32 eighth-note hits. All bar starts and durations are checked exactly. +- Tests cover normalization, arithmetic/comparison, exact and fractional ticks, + invalid denominators, wide intermediates and checked overflow; complete + acceptance values/defaults; paraphrases; enharmonic normalization; role-local + modifiers; explicit-only roles/drum subsets; defaults and repeated settings; + rejection of malformed/meaningful leftover instructions; numeric ranges, + event-kind/role validation, complete extents and trailing rests. +- Long repeated pitched and hi-hat patterns verify absence of drift. Non-4/4 + tests verify denominator beats and reject inappropriate default/subdivision + assumptions. Exact event boundaries cover pitched, drums and combined roles; + the combined 100,001 case and Int32.MaxValue bar requests reject pre-expansion. +- Repeated calls and reused parsed descriptions are structurally identical. + Collections are read-only snapshots; source-list mutations and attempts to + mutate results cannot affect another result. +- Ten new integration cases exercise real Core parser -> planner -> validator + in-process, including the complete example, role subsets, 3/8 and failures. + These are not final public MCP generation/file-writing integration claims. + +CHANGED FILES (22 deliverables, including this report) + README.md + docs\text-description-contract.md + src\GAJ3T.MusicGen.RiffGrooveBuilder.Core\Composition\BeatFraction.cs + src\GAJ3T.MusicGen.RiffGrooveBuilder.Core\Composition\Composition.cs + src\GAJ3T.MusicGen.RiffGrooveBuilder.Core\Composition\TrackPlan.cs + src\GAJ3T.MusicGen.RiffGrooveBuilder.Core\Composition\MusicalNote.cs + src\GAJ3T.MusicGen.RiffGrooveBuilder.Core\Composition\DrumHit.cs + src\GAJ3T.MusicGen.RiffGrooveBuilder.Core\Composition\MusicalTypes.cs + src\GAJ3T.MusicGen.RiffGrooveBuilder.Core\Composition\ParsedDescription.cs + src\GAJ3T.MusicGen.RiffGrooveBuilder.Core\Composition\CompositionDiagnostic.cs + src\GAJ3T.MusicGen.RiffGrooveBuilder.Core\Composition\CompositionPlanningResult.cs + src\GAJ3T.MusicGen.RiffGrooveBuilder.Core\Composition\CompositionValidator.cs + src\GAJ3T.MusicGen.RiffGrooveBuilder.Core\Composition\DescriptionParser.cs + src\GAJ3T.MusicGen.RiffGrooveBuilder.Core\Composition\CompositionPlanner.cs + tests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\Composition\BeatFractionTests.cs + tests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\Composition\CompositionValidatorTests.cs + tests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\Composition\DescriptionParserTests.cs + tests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\Composition\CompositionPlannerTests.cs + tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\Composition\CompositionPipelineTests.cs + tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests.csproj + tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\packages.lock.json + prompts\report_3.md + +EXACT VALIDATION COMMANDS AND RESULTS +All dotnet commands ran from the repository root with process-local settings: + $env:PATH = 'C:\Program Files\dotnet;' + $env:PATH + $env:DOTNET_CLI_TELEMETRY_OPTOUT = '1' + $env:DOTNET_NOLOGO = '1' +This uses the installed C:\Program Files\dotnet\dotnet.exe without machine +configuration changes. + +1. dotnet restore .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx + PASS, exit 0. All five projects restored after the project-reference edit. + Only IntegrationTests' generated lock needed the direct Core project entry. + +2. dotnet test .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-restore --filter FullyQualifiedName~Composition + Development run 1: exit 1. + UnitTests: 176 passed / 1 failed / 0 skipped. + IntegrationTests: 9 passed / 1 failed / 0 skipped. + Both failures were incorrect new assertions: the 3/8 two-bar example has + 12 hits (4 kick + 2 snare + 6 hi-hat), not 10; fractional numbered-beat + text correctly returned invalid_number rather than unsupported_text. + Corrected the assertions without permitting fractional beats or dropping + any musical events. + Development run 2: PASS, exit 0. + UnitTests: 177 passed / 0 failed / 0 skipped. + IntegrationTests: 10 passed / 0 failed / 0 skipped. + Added the combined-role 100,001-event regression before final validation. + +FINAL REQUIRED ACCEPTANCE COMMANDS +3. dotnet build .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-restore + PASS, exit 0. All five projects built. 0 warnings, 0 errors. + +4. dotnet test .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-build + PASS, exit 0. Both test assemblies discovered and executed: + UnitTests: 294 passed, 0 failed, 0 skipped (708 ms). + 178 new composition cases + all 116 retained baseline cases. + IntegrationTests: 24 passed, 0 failed, 0 skipped (977 ms). + 10 new Core pipeline cases + all 14 retained real-process cases. + TOTAL: 318 passed, 0 failed, 0 skipped. + 188 new cases + all 130 prior cases. + +5. dotnet restore .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx --locked-mode + PASS, exit 0. All five projects restored using generated locks. + +ADDITIONAL CHECKS +- Editor runTests over the five new test files reported "No tests found". + Used the already-approved CLI fallback; no empty editor discovery was + misreported as a passing test run. +- Final editor problems check over src/tests: no errors found. +- git --no-pager diff --check: PASS, exit 0. +- In-memory PowerShell trailing-whitespace audit: PASS, exit 0; all 21 + Step 3 deliverables preceding this report checked, excluding bin/obj. +- Core project XML audit: PASS, exit 0; no package or project references. +- SHA256 preservation audit: PASS, exit 0; plan.md, step_1.md, step_2.md, + step_3.md, report_1.md and report_2.md unchanged from worker entry. + The pre-existing modified plan was preserved, not reset or edited. + +ISSUES, UNRUN CHECKS AND READINESS +- The two development assertion issues are resolved. No unresolved Step 3 + implementation/test blocker remains. Step 3 is ready for review, not an + authorization to proceed beyond its scope. +- No native/plugin/Cubase imports, MIDI/native output checks, self-contained + publication or public generation-tool integration were run: those require + later steps and/or unavailable authorized production evidence. +- Step 4 evidence remains ABSENT: exact installed product versions/settings, + verified Eclips/Ray playable/articulation/keyswitch/CC/velocity/timing/state/ + channel rules, and the actual SD3 library/drum map have not been supplied. + Native schemas, confirmed AGP/SDP semantics, lawful fixtures/template rights + and successful target-application import evidence also remain unverified. + Musical pitch defaults/logical drum voices do not establish any of these. + Step 4 production mapping exit criteria cannot be declared ready; obtain + evidence/owner direction rather than fabricate profiles or mappings. +- Core remains independent of DryWetMIDI. Production MCP tools remain empty. + No new packages, future-step implementation, orchestrator prompt/plan edits, + commits, delegation or scratch artifacts were introduced. +- Stopping after this report. +``` diff --git a/prompts/report_4.md b/prompts/report_4.md new file mode 100644 index 0000000..6b67e14 --- /dev/null +++ b/prompts/report_4.md @@ -0,0 +1,856 @@ +``` +STEP 4 REPORT — Generic profiles and articulation event intentions +Date: 2026-10-19 + +INFRASTRUCTURE IMPLEMENTATION/TEST STATUS: PASS. +FULL STEP 4 PRODUCTION READINESS: FALSE / BLOCKED. +READY FOR STEP 5: FALSE. No authorized real product mapping evidence exists. +Synthetic passing tests do not satisfy the approved Step 4 production exit gate. + +IMPLEMENTED +- Added immutable Core profile/rule/evidence models, validation, typed MIDI + event intentions, complete-or-failed planning results and diagnostics. + Core has no project/package references and remains independent of DryWetMIDI. +- Profiles identify role, exact product/version, mapping version, authorized + provenance/verification record, inclusive playable range, zero-based channel, + initial state, explicit final resets and supported rules. +- Validation rejects invalid IDs/identity/evidence/status/roles, MIDI ranges, + velocity layers, advances/durations, duplicate rules/CC numbers, ambiguous + layers, incomplete/conflicting state and playable/keyswitch collisions. + Drum mappings are logical-voice-to-absolute-pitch data, with explicit CC state; + no GM/SD3 pitches or real instrument mappings were inferred. +- Planner revalidates composition and explicitly selected matching profiles. + Unsupported articulation, unmapped voice, invalid velocity/pitch, missing/ + unverified profile, track channel collision, conflicting channel-wide state, + overlapping pitch ownership or timing overflow returns diagnostics and no + partial usable plan. Source musical data is preserved. +- Added embedded Generation catalog, loaded from its assembly rather than cwd. + Production resource content is exactly []: zero production profiles/defaults. + Unknown/default selection fails actionably, with no synthetic fallback. + Public loading is embedded-only; internal stream parsing is unit-testable. + Malformed/invalid resources fail explicitly, including missing constructor + fields, null required values, integer enums, unknown/duplicate JSON properties, + duplicate profile IDs and synthetic/unverified entries. +- IntegrationTests now references Generation to exercise the actual catalog. + Its existing Server-only apphost copy target remains unchanged. Refreshed + IntegrationTests' generated dependency lock; no new PackageReference/version. +- Added mapping contract and updated README/compatibility inventory to separate + generic infrastructure from missing production evidence. Server source/tool + registration is unchanged: production MCP tools remain empty. + +MECHANISM, VELOCITY AND STATE DECISIONS +- Reused existing role/articulation/drum-voice enums and exact 960-PPQ timing. + Control advances/durations are explicit signed-Int64 integer ticks. + Events are typed note-on/note-off/CC intentions, not MIDI-library objects, + handwritten MIDI encoding, file output or native serialization. +- Keyswitch-only, velocity-only, CC-only and combined rules are supported. + All pitches are absolute MIDI numbers, independent of octave-label naming. +- Velocity layer bounds are inclusive requested-velocity constraints, 1..127. + Outside-layer input fails, never clamps. Null outputVelocity preserves + dynamics; an explicit fixed output must lie inside the layer. It changes only + emitted velocity, not source dynamics. Identical control states need disjoint + velocity intervals for distinct articulations. +- Latched state includes keyswitch pitch AND switch velocity plus the complete + CC vector. Redundant state actions are suppressed; sustain restoration is an + explicit supported rule, not guessed. Latched switch duration is pulse length. +- Momentary actions retrigger per note. Switch release occurs after both the + musical end and the minimum switch duration measured from switch-on, including + advance. CC release restores explicitly declared initial values. No guessed + sustain switch, all-notes-off or unspecified final reset is emitted. +- Initial CC values emit at tick zero. The declared initial pitched articulation + is known resting state, not an unnecessary initial switch trigger. + Explicit final resets occur after musical extent and any later release; + reset pulse tails extend EndTick when necessary. +- Bounded supported state schemes reject mixed latched/momentary controls on + one channel and ambiguous overlapping momentary retriggers. Drums use voice + pitches and CC state, not pitched-articulation keyswitches. Incompatible + simultaneous/overlapping control windows fail without channel-per-note tricks. + Nonzero-advance transitions cannot change incompatible prior sustained notes. +- One shared LeadInTicks is the maximum configured switch advance among + requested rules on selected tracks. Every musical start/end shifts equally. + No negative control time is clamped and no single role shifts independently. +- Same-tick stable priorities: note-offs (0), initial/release/reset CCs (1), + new CC/switch state (2), musical note-ons (3); ties retain deterministic order. + MusicalExtentTicks preserves all declared bars/trailing rests; MusicalEndTick + adds lead-in; EndTick also includes final control releases/reset pulses. + +TEST EVIDENCE +- 158 new articulation unit cases cover profile validation/ranges/layers, + independent and combined mechanisms, exact event values/channels/timing, + latching/retriggers/sustain/reset state, pairing/order, velocity-coded switch + state, immutable deterministic output, source preservation, unsupported inputs, + drum CC conflicts, channel collisions, fractional timing and checked overflow + including final reset pulses. Catalog cases cover unrelated cwd, honest empty + content, selection failures and malformed/invalid resources. +- 9 new in-process integration cases exercise description -> composition -> + validation -> synthetic profile validation -> event planning, role subsets, + production-catalog absence and explicit failures without partial plans. +- The full documented three-role example uses TEST-ONLY invented mappings: + shared lead-in 240 ticks (lead advance 240, bass advance 120, drums zero); + musical extent 15,360; shifted musical end/plan end 15,600. + Lead has 32 musical notes plus one matched switch pulse; bass has four notes + plus one matched switch pulse; drums have 48 mapped hits plus initial, active + and final CC values. Total: 175 event intentions. Exact switch positions, + output velocity, drum notes/CCs, shifted note starts/ends and pairing are + asserted. Reversed profile enumeration yields identical event sequences. +- These are synthetic in-memory pipeline checks, NOT MIDI-file, native-file, + public MCP generation, Cubase or actual instrument acceptance tests. + +CHANGED FILES (20 deliverables, including this report) + README.md + docs\articulation-mappings.md + docs\format-compatibility.md + src\GAJ3T.MusicGen.RiffGrooveBuilder.Core\Articulations\InstrumentProfile.cs + src\GAJ3T.MusicGen.RiffGrooveBuilder.Core\Articulations\ArticulationRule.cs + src\GAJ3T.MusicGen.RiffGrooveBuilder.Core\Articulations\InstrumentProfileValidator.cs + src\GAJ3T.MusicGen.RiffGrooveBuilder.Core\Articulations\ArticulationPlanner.cs + src\GAJ3T.MusicGen.RiffGrooveBuilder.Core\Articulations\ArticulationPlanningResult.cs + src\GAJ3T.MusicGen.RiffGrooveBuilder.Core\Articulations\PlannedMidiEvent.cs + src\GAJ3T.MusicGen.RiffGrooveBuilder.Generation\Profiles\InstrumentProfileCatalog.cs + src\GAJ3T.MusicGen.RiffGrooveBuilder.Generation\Profiles\instrument-profiles.json + src\GAJ3T.MusicGen.RiffGrooveBuilder.Generation\GAJ3T.MusicGen.RiffGrooveBuilder.Generation.csproj + tests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\Articulations\SyntheticProfiles.cs + tests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\Articulations\InstrumentProfileValidatorTests.cs + tests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\Articulations\ArticulationPlannerTests.cs + tests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\Articulations\InstrumentProfileCatalogTests.cs + tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\Articulations\ArticulationPipelineTests.cs + tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests.csproj + tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\packages.lock.json + prompts\report_4.md + +EXACT VALIDATION COMMANDS AND RESULTS +All dotnet commands ran from the repository root with process-local settings: + $env:PATH = 'C:\Program Files\dotnet;' + $env:PATH + $env:DOTNET_CLI_TELEMETRY_OPTOUT = '1' + $env:DOTNET_NOLOGO = '1' +SDK executable: C:\Program Files\dotnet\dotnet.exe. +Output-only PowerShell formatting shortened repeated repository paths in +development logs; it did not change commands, selectors or test behavior. + +1. dotnet restore .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx + PASS, exit 0, all five projects, after project-reference/resource edits. + Repeated after the friend-test assembly manifest edit: + dotnet restore .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx --verbosity quiet + PASS, exit 0. + +2. Development compilation/test iterations: + dotnet build .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-restore + Initial run: exit 1, 0 warnings, 3 CS8752 errors. Corrected ambiguous + target-typed new expressions passed through a params diagnostic array. + dotnet test .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-restore --filter FullyQualifiedName~Articulation + Initial run: exit 1 before tests; new test helper name conflicted with an + existing Composition namespace, and xUnit analyzers required predicate + Assert.Single/DoesNotContain overloads. Fixed the new tests without weakening + assertions or suppressing analyzers. + dotnet test .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-restore --filter FullyQualifiedName~Articulation --verbosity quiet + One diagnostic retry: exit 1 before fixes. + dotnet build .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-restore --verbosity quiet + Diagnostic build: exit 1, 0 warnings, 18 test compile/analyzer errors. + Corrected focused runs with the quiet test command above: + 144 unit + 9 integration passed, exit 0, 0 failed/skipped; + 151 unit + 9 integration passed, exit 0, 0 failed/skipped; + 160 unit + 9 integration passed, exit 0, 0 failed/skipped. + This broad selector includes TWO retained composition tests whose method + names contain Articulation; do not count them as new Step 4 tests. + +FINAL REQUIRED ACCEPTANCE +3. dotnet build .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-restore + PASS, exit 0. All five projects built; 0 warnings, 0 errors (0.63 s). + +4. dotnet test .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-build + PASS, exit 0. Both assemblies discovered and executed: + UnitTests: 452 passed, 0 failed, 0 skipped (812 ms). + 158 new articulation cases + all 294 retained cases. + IntegrationTests: 33 passed, 0 failed, 0 skipped (1 s). + 9 new articulation pipeline cases + all 24 retained cases. + TOTAL: 485 passed, 0 failed, 0 skipped. + 167 new cases + all 318 prior cases. + +5. dotnet restore .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx --locked-mode + PASS, exit 0. All five projects restored against generated locks. + +6. dotnet test .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-build --filter FullyQualifiedName~.Articulations. --verbosity quiet + PASS, exit 0. Exact new namespace count: 158 unit + 9 integration = + 167 new tests; 0 failed, 0 skipped. + +ADDITIONAL CHECKS +- Editor runTests over all four new test files: "No tests found". + Used the prescribed CLI fallback; empty editor discovery was not called a pass. +- Final editor problems check over src/tests: no errors found. +- git --no-pager diff --check: PASS, exit 0. +- In-memory trailing-whitespace audit of all 19 Step 4 files preceding this + report: PASS, exit 0; no scratch files created. +- Core project XML audit: PASS, zero project/package references. +- Production resource audit: PASS, exact empty list []; registry remains + new McpToolRegistry() with no production tools. +- SHA256 preservation audit: PASS, all eight pre-existing orchestration files + unchanged: plan.md, step_1..4.md and report_1..3.md. The already-modified plan + was preserved, not reset or edited. +- Source/test output-file audit: PASS, no .mid/.midi/.agp/.sdp files. + +BLOCKERS, UNRUN CHECKS AND STOP DECISION +- Development compile/analyzer issues are resolved. No unresolved generic + infrastructure build/test failure remains. Infrastructure is ready for review. +- FULL STEP 4 REMAINS BLOCKED; readiness false. Required actual evidence: + exact installed Eclips/Ray product names/versions/settings; SD3 version, + content library, chosen MIDI map and overrides; authorized versioned mapping + provenance/rights; verified absolute playable/switch/drum pitches, switch + velocities, velocity layers/transformations, CC values/combinations, timing, + durations, channel behavior, initial state, latching, momentary release/reset + semantics and actual application verification for all three targets. +- Native schemas/metadata, authorized minimal fixtures/template permissions, + confirmed AGP/SDP extensions/entity semantics/load workflows and actual + native/plugin/Cubase acceptance evidence also remain absent. Generic MIDI + intentions and test-created numbers establish none of those facts. +- No actual instrument/Cubase imports, MIDI/native writing/read-back, + self-contained publication or public generation-tool acceptance was run: + these require unavailable evidence and/or later authorized steps. +- No production profile, guessed mapping, tool exposure, native/MIDI writer, + new package, later-step prompt, orchestrator edit, commit or delegation. + No personal/vendor-directory search, network evidence fabrication or + application automation was performed. +- Stopping after this report. Do not proceed to Step 5 without actual evidence + and orchestrator/owner resolution of the blocked production gate. + +Correction iteration 2: instrument catalog extension +Date: 2026-10-20 + +CATALOG-EXTENSION IMPLEMENTATION/TEST READINESS: PASS; ready for review. +FULL STEP 4 PRODUCTION MAPPING READINESS: FALSE / BLOCKED. +READY FOR STEP 5: FALSE. Stopping for orchestrator review. +This section updates current scope/status; the infrastructure history above +is retained unchanged. + +IMPLEMENTED AND CONTRACT MIGRATION +- Added immutable vendor-neutral InstrumentDefinition with six metadata fields: + ID, vendor string, product code, display name, existing role and documentation + URL. No vendor/product enum, per-instrument subclass or fabricated version, + playable range, mapping controls, installed/native capability was added. +- Embedded Instruments\instruments.json declares exactly seven identities: + ample-abj / ABJ / Ample Bass J / Bass; + ample-aglp / AGLP / Ample Guitar LP / Lead; + ample-agm / AGM / Ample Guitar M / Lead; + ample-agt / AGT / Ample Guitar T / Lead; + ample-ame / AME / Ample Metal Eclipse / Lead; + ample-amr / AMR / Ample Metal Ray5 / Bass; + toontrack-sd3 / SD3 / Superior Drummer 3 / Drums. + Vendor/manual URLs match the approved correction's official sources. + Four Lead, two Bass, one Drums; acoustic guitars reuse the Lead slot. +- InstrumentCatalog supports embedded-only loading, exact ID lookup, immutable + role filtering and deterministic ordinal-ID ordering independent of cwd. + Invalid/missing/null/unknown/duplicate JSON fields, null entries, invalid + IDs/codes/identity strings, URLs, undefined/numeric/composite roles, duplicate + IDs and duplicate vendor/code or vendor/name identities fail explicitly. + A malformed resource cannot return a successful empty catalog. +- Added required constructor/property InstrumentId to InstrumentProfile, after + profile ID. JSON requires instrumentId; missing/null values fail rather than + acquiring implicit binding. Core validates its stable ASCII ID shape. + Updated existing synthetic unit/pipeline factories and profile-copy calls. + No planner/event-generation behavior or rules were changed. +- InstrumentProfileCatalog validates every binding against a declared + instrument, its existing role and exact ProductName == DisplayName identity. + Dangling IDs, mismatches, duplicate profile IDs and synthetic/unverified + mappings are rejected. Shared internal CatalogJson retains strict parsing; + profile and definition resource failures remain InvalidDataException. +- Preserved Select(role, profileId), requiring explicit role/profile IDs with + no authorized role defaults. Wrong-role profiles now have a distinct failure. + Added SelectInstrument(role, instrumentId, profileId?); only a single matching + verified candidate can resolve without a profile ID. Multiple versions require + explicit choice. No first-candidate selection or cross-product substitution. + Diagnostics distinguish unknown_instrument, instrument_role_mismatch, + mapping_unavailable, unknown_profile, profile_role_mismatch, + profile_instrument_mismatch, ambiguous_profile, no_default_profile and + invalid_role. +- Joined immutable InstrumentProfileCatalog.Instruments entries expose metadata, + matching profiles and derived mapping_unavailable/profile_available status. + These describe mapping admission, not native compatibility or installation. + Current production state: SEVEN identities, ZERO verified mapping profiles, + SEVEN mapping_unavailable entries, ZERO playable production targets. +- Profiles\instrument-profiles.json remains exactly []; no production mapping + was fabricated or changed. Server source/registry is unchanged and empty; + discovery/generation tools remain unexposed, with final integration in Step 8. + +DATA-ONLY EXTENSIBILITY AND REGRESSION EVIDENCE +- Unit-only JSON fixtures add four invented identities from arbitrary vendor + strings, including synthetic-extra with two product/mapping versions. + They are embedded only in UnitTests, never in the production assembly. + Their intentionally invented Verified flags exercise catalog admission, not + vendor mapping truth or actual application verification. Production continues + rejecting actual Synthetic/Unverified status even with complete valid bindings. +- Both extra-target versions bind/select through the same catalog APIs, then + the UNCHANGED ArticulationPlanner produces the expected test-only velocity: + v1 preserves requested 96; v2 emits explicit 110 without mutating source 96. + Ambiguous selection fails; exact version IDs succeed. A single-version + extra instrument resolves explicitly by instrument ID without substitution. +- A data-only combined catalog joins all seven production identities with the + four test identities: 11 metadata entries, four fixture profiles. Existing + seven targets stay mapping_unavailable while the extra target becomes + profile_available. Reversing JSON order yields identical ordered catalog + output and never selects an arbitrary version. +- Tests cover exact seven names/codes/vendors/roles/manual URLs, immutable + collections/filtering, unrelated-cwd loading, malformed/null/duplicate and + invalid data, required profile binding, product/role/reference validation, + verification rejection and all explicit selection/availability outcomes. +- New integration test loads both actual embedded catalogs from the unrelated + existing OS directory, inspects/join-checks all seven targets, rejects missing + mappings actionably, and proves no usable event plan is produced. + Existing synthetic articulation pipeline and real MCP process regressions + remain intact. No MIDI/native file or real application acceptance is implied. +- README and existing mapping/compatibility documents list the expanded scope, + official source links, identity versus mapping/native acceptance, strict APIs, + data-only extension/admission and rebuild/publish requirement. No runtime + directories, scanning/loading, hot reload, external services, new packages, + product-specific switches, writer hierarchy or export implementation. + +CHANGED FILES (22 deliverables including this report) + README.md + docs\articulation-mappings.md + docs\format-compatibility.md + src\GAJ3T.MusicGen.RiffGrooveBuilder.Core\Instruments\InstrumentDefinition.cs + src\GAJ3T.MusicGen.RiffGrooveBuilder.Core\Articulations\InstrumentProfile.cs + src\GAJ3T.MusicGen.RiffGrooveBuilder.Core\Articulations\InstrumentProfileValidator.cs + src\GAJ3T.MusicGen.RiffGrooveBuilder.Generation\CatalogJson.cs + src\GAJ3T.MusicGen.RiffGrooveBuilder.Generation\Instruments\InstrumentCatalog.cs + src\GAJ3T.MusicGen.RiffGrooveBuilder.Generation\Instruments\instruments.json + src\GAJ3T.MusicGen.RiffGrooveBuilder.Generation\Profiles\InstrumentProfileCatalog.cs + src\GAJ3T.MusicGen.RiffGrooveBuilder.Generation\GAJ3T.MusicGen.RiffGrooveBuilder.Generation.csproj + tests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\Instruments\InstrumentCatalogTests.cs + tests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\Instruments\CatalogFixtures.cs + tests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\Instruments\Fixtures\instruments.json + tests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\Instruments\Fixtures\profiles.json + tests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\Articulations\SyntheticProfiles.cs + tests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\Articulations\InstrumentProfileValidatorTests.cs + tests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\Articulations\InstrumentProfileCatalogTests.cs + tests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests.csproj + tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\Instruments\InstrumentCatalogPipelineTests.cs + tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\Articulations\ArticulationPipelineTests.cs + prompts\report_4.md + +EXACT VALIDATION COMMANDS / RESULTS +Repository root; process-local settings for every dotnet shell: + $env:PATH = 'C:\Program Files\dotnet;' + $env:PATH + $env:DOTNET_CLI_TELEMETRY_OPTOUT = '1' + $env:DOTNET_NOLOGO = '1' +Executable: C:\Program Files\dotnet\dotnet.exe. + +1. dotnet restore .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx --locked-mode + Initial post-manifest validation: PASS, exit 0, all five projects up to date. + No package/version/project-reference or lock-file changes were necessary. + +2. dotnet test .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-restore --filter 'FullyQualifiedName~.Articulations.|FullyQualifiedName~.Instruments.' + Development attempts: + - Exit 1: unit compilation stopped on one xUnit2029 assertion-style error; + integration assembly still ran: 10 passed, 0 failed/skipped. + Replaced filtered Assert.Empty with predicate Assert.DoesNotContain. + - Exit 1: shared role-converter insertion had a misplaced method brace + (CS1513/CS1022); corrected structure without suppressing validation. + - Exit 0: 237 unit + 10 integration = 247 passed, 0 failed/skipped. + FINAL after the combined production-plus-fixture extension test: + PASS, exit 0; 238 unit + 10 integration = 248 passed, 0 failed/skipped. + +3. dotnet build .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-restore + FINAL PASS, exit 0; five projects, 0 warnings, 0 errors (0.94 s). + +4. dotnet test .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-build + FINAL PASS, exit 0: + UnitTests: 532 passed, 0 failed, 0 skipped (692 ms). + IntegrationTests: 34 passed, 0 failed, 0 skipped (1 s). + TOTAL: 566 passed, 0 failed, 0 skipped. + Increase over reviewed baseline: 80 unit + 1 integration = 81 new cases. + All 485 reviewed baseline cases are retained and pass. + +5. dotnet restore .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx --locked-mode + FINAL PASS, exit 0; all five projects up to date against existing locks. + +ADDITIONAL CHECKS / PRESERVATION +- Editor runTests over the six relevant test files: "No tests found". + Prescribed CLI fallback above executed the tests; editor absence is not a pass. +- Final editor problems(src/tests): no errors found; CLI compilation is the + authoritative build evidence. +- git --no-pager diff --check: PASS, exit 0. +- Core XML reference audit: zero PackageReference/ProjectReference elements. +- Production mapping resource remains []; Program still constructs an empty + McpToolRegistry. No .mid/.midi/.agp/.sdp files exist under src/tests. +- SHA256 comparison of all nine non-report-4 orchestration files: unchanged + from this worker's entry state, including the owner's already-modified + plan.md and current step_4_fix.md; neither was reset or edited. +- Existing report history is preserved; the entire report uses exactly one + plain triple-backtick fence. No scratch files, commits or delegation. + +EVIDENCE, BLOCKERS AND STOP +- Identity references: official per-product Ample manual URLs in + Instruments\instruments.json and docs\articulation-mappings.md, as supplied by + the approved correction, plus the official SD3 manual URL. Earlier documented + Eclipse/Ray5 manual and owner screenshot findings remain partial evidence. + This iteration did not perform a new vendor/manual or local installation scan. +- ACTUAL PRODUCTION MAPPING VERIFICATION THIS ITERATION: NONE. + The folder screenshot establishes no product versions, filesystem paths or + maps. Do not assume all Ample products share articulations or native formats. +- Catalog-extension readiness is PASS despite missing maps. No unresolved + metadata, selection, compilation or automated-test blocker remains. +- Full Step 4 readiness is FALSE / BLOCKED: ABJ, AGLP, AGM, AGT, AME, AMR and SD3 + still lack complete authorized exact-installed-version/settings mapping + contracts and actual application verification. Required evidence includes + absolute playable/control/drum pitches, switch velocity/advance/duration, + velocity layers/transformations, CC combinations/state, channels, initial/ + latched/momentary/release/reset behavior; SD3 also requires its exact + content library, chosen MIDI map and custom overrides. +- Native schemas/fixture/template rights, requested AGP/SDP extension/entity/load + semantics and actual instrument/Cubase acceptance remain separate unresolved + gates. No MIDI/native writing/read-back, product/Cubase import, publication, + runtime-free or public generation-tool acceptance was run. +- No later step, new tool exposure, export implementation, runtime scanning, + orchestrator prompt/plan edit, package addition, commit or delegation. + STOP after this report for orchestrator review; do not start Step 5. + +=============================================================================== +Correction iteration 3: documentation-backed profiles +Date: 2026-10-20 +Baseline: accepted Step 5 infrastructure, 663 tests. + +BOUNDED CORRECTION STATUS: PASS for the supported, source-backed subset. +ADMITTED: 2 Documented profiles (AGLP and AME); 0 application-Verified profiles. +UNAVAILABLE: ABJ, AGM, AGT, AMR and SD3; all seven identities remain declared. +FULL REQUESTED-PRODUCT / APPLICATION READINESS: FALSE / BLOCKED. +READY FOR NEXT STEP: only for orchestrator review of this bounded subset. +No subsequent step, public tool, native writer or deployment was started. +Earlier report entries above are preserved historical results, not current counts. + +IMPLEMENTATION +- Added MappingVerification.Documented without changing existing enum values: + Unverified=0, Verified=1, Synthetic=2. Documented means cited published defaults; + Verified continues to mean application-verified. Both are production-admissible; + Unverified and Synthetic remain rejected, with only explicit test-only synthetic + opt-in. No documentation-only mapping is called Verified. +- Added immutable MappingCompatibilityNotes: VersionScope, + ConfigurationRequirements, RoutingPolicy and TimingPolicy. The optional final + constructor argument preserves existing constructor/serialized fixture use. + Documented profiles must supply notes; missing/null notes fail explicitly. + Present fields must be nonempty, trimmed and free of control characters. + Serialized nested fields are required; no compatibility policy is defaulted. + Documented primary Source must be an absolute HTTP(S) URL without credentials. +- ProductVersion honestly states "documented defaults; installed version unknown". + MappingVersion is the independent data revision published-defaults-2026-10-20.1. + Evidence records manual sections, source HTTP revisions/hashes, retrieval date, + vendor demo numeric anchors, authorization scope and application-check limits. +- Retained strict InstrumentId/role/exact product-name binding, explicit selection, + immutable catalog data and actionable unsupported-profile diagnostics. + No automatic Lead default or product substitution was introduced. +- Enabled null InitialArticulation for unknown receiver articulation. Planning + explicitly begins with no assumed switch state: the first requested Sustain + OR PalmMute alone is selected. Repeats latch without duplicate pulses. + Existing explicit known-state behavior, complete initial CC initialization, + conflict rejection, source immutability and musical timing are preserved. + Unsupported non-null known initial articulations remain invalid. +- Existing MIDI construction/serialization, pinned library, projects/packages, + track roles, articulations and pattern grammar were not changed. + README and both mapping/compatibility documents explain the current subset. + +EXACT ADMITTED PROFILES / FACTS +1. ample-aglp-documented-defaults-2026-10-20 + Binding: ample-aglp / Lead / Ample Guitar LP. + Sustain switch 24, PalmMute switch 26, playable inclusive range 40-86. + Sustain musical velocity 1-126; 127 is settings-dependent Pop/Pinch Harmonic. + PalmMute preserves velocities 1-127; lower velocity means greater mute depth. +2. ample-ame-documented-defaults-2026-10-20 + Binding: ample-ame / Lead / Ample Metal Eclipse. + Sustain switch 24, PalmMute switch 26, playable inclusive range 36-84. + Sustain musical velocity 64-126 only. Manual's 1-15 full mute, 16-31 3/4 + mute, 32-63 half mute and 127 Pop/Pinch Harmonic are NOT accepted as Sustain. + PalmMute preserves velocities 1-127; lower velocity means greater mute depth. +Out-of-range pitches/layers fail before writing; no clamping or hidden transform. + +PRIMARY SOURCES / REVISION / ABSOLUTE NUMERIC ANCHORS +All sources below were retrieved 2026-10-20. Source revisions are NOT installed +product versions. All six official main-panel PDFs and Settings/CPC were read. +Rendered https://www.amplesound.net/en/manual.asp exposed the official links +when simplified fetching returned no useful manual links. + +- https://www.amplesound.net/en/Main_Panel_Manual-AGLP.pdf + PDF pp.6-7, sections 2.2.1, 2.2.3 and 2.2.5: + C0 Sustain, D0 PalmMute, both E1-D5; velocity facts stated above. + HTTP Last-Modified 2025-09-08 09:00:15 GMT. + SHA256 7b28b62f3c25ecb774227b15beab06f5e0f0c944f35db9e82121028017f9cedb. +- https://www.amplesound.net/en/Main_Panel_Manual-AME.pdf + PDF pp.6-7, sections 2.2.1-2.2.4: + C0 Sustain, D0 PalmMute, both C1-C5; velocity facts stated above. + HTTP Last-Modified 2025-09-08 09:00:39 GMT. + SHA256 ab482f08b0546eca0a4233b8be3776c411b77f3dca96979f529debc2dfc0c4ca. +- The rendered https://www.amplesound.net/en/download.asp links vendor-authored: + https://www.amplesound.net/dl0822/ds/AGLP-Prison_Break.zip + HTTP Last-Modified 2019-11-24 16:33:18 GMT. + SHA256 738956bced4e78a00ab755646d34108f9e25c5346ef79b96a5c1664c876f5e5f. + MIDI entry: AGLP-Prison Break/AGLP-Prison Break-Tempo100.mid, 480 PPQ. + Zero-based track 1: switch 24, velocity 100, on tick 3837/off 3957. + Zero-based track 3: switch 26, velocity 100, on 34438/off 34558. + This is a genuine numeric C0=24/D0=26 anchor; E1-D5 then means 40-86. +- https://www.amplesound.net/dl0822/ds/AME-Eclipse.zip + HTTP Last-Modified 2019-11-24 17:03:34 GMT. + SHA256 e448d85f9ff80692f625f23ef6ea4dd0b14367b9f92412adbb76aa6e4a987f66. + MIDI entry: AME-Eclipse/AME-Eclipse-Tempo130.mid, 480 PPQ. + Zero-based track 4: switch 24, velocity 100, on 3720/off 3840, musical + C1 pitch 36 at 3840. The 1 Channel variant also contains switch 24. + This anchors the manual's C0=24; D0 is two semitones higher (26), C1-C5=36-84. + Numeric conversions were NOT inferred solely from octave labels. +- Demo streams were read using existing pinned DryWetMIDI 8.0.3, in memory. + No alternate handwritten MIDI parser, demo MIDI, archive, sample library, + copied manual or native content was retained or shipped. +- Public third-party numeric corroboration ONLY (no copied implementation): + https://github.com/zaibuyidao/ReaScripts/blob/98e88777ff4cf2e478d6bc85d35349f62acc7e41/Various/Articulation%20Map/banks/70-96%20Ample%20Metal%20Eclipse%20%28%E9%87%91%E5%B1%9E%E5%90%89%E4%BB%96%29.reabank + Blob ea878807ac429bd7294b9f8a8612a9261feacb4f corroborates Eclipse 24/26. + Vendor manual/demo facts remain primary; that map's other interpretations + were not adopted. Reaticulate's Rickenbacker bank uses 24/26 but is a + different product, so it was NOT used to fill other targets' numeric gaps: + https://github.com/jtackaberry/reaticulate/blob/3760589894808c03fac4b07aa0d3a63812484350/userbanks/Ample_Sound/Ample_Sound-Ample_Guitars-Ample_RB_%28Rickenbacker%29.reabank + +RESEARCHED BUT UNAVAILABLE / EXACT REMAINING GAPS +- ABJ: https://www.amplesound.net/en/Main_Panel_Manual-ABJ.pdf + PDF pp.6-7, sections 2.2.1-2.2.4. + HTTP Last-Modified 2025-04-16 05:04:25 GMT. + Sustain C0 B0-E4; musical velocities 1-125 Sustain, 126-127 Accent. + PM D0 E1-D4 distinguishes high-velocity PM and low-velocity Dead Note, + WITHOUT a numeric dividing threshold. No product-specific absolute numeric + anchor was established. Missing anchor and dedicated PM threshold prevent + a complete Sustain/PM profile; no guitar/bass values were substituted. +- AGM: https://www.amplesound.net/en/Main_Panel_Manual-AGM.pdf + PDF pp.6-7, sections 2.2.1-2.2.4. + HTTP Last-Modified 2025-09-08 09:00:15 GMT. + AGT: https://www.amplesound.net/en/Main_Panel_Manual-AGT.pdf + PDF pp.6-7, sections 2.2.1-2.2.4. + HTTP Last-Modified 2025-09-08 09:00:02 GMT. + Both document C0 Sustain/D0 PM, both E1-C5; Sustain 1-126 and Pop at 127; + PM depth depends on velocity. No product-specific numeric anchor was + established. Shared labels and another product's demo are not silently + promoted into exact target evidence. Both remain unavailable. +- AMR: https://www.amplesound.net/en/Main_Panel_Manual-AMR.pdf + PDF pp.6-7, sections 2.2.1-2.2.4. + HTTP Last-Modified 2025-04-16 05:04:22 GMT. + Sustain C0 A0-E4; 64-126 Sustain, 127 Accent, 32-63 PM, 1-31 Dead Note. + Dedicated PM D0 B0-E4 has an unspecified high/low PM/Dead Note split. + No product-specific absolute anchor established; unavailable. Even a future + velocity-only supported subset needs its own absolute numeric anchor. + The PDF title is Ample Metal R; the catalog retains vendor site's Ray5 name. +- https://www.amplesound.net/en/Settings_and_CPCv2.pdf + PDF pp.7-9, sections 1.2.2-1.2.9; pp.14-15, section 1.5. + HTTP Last-Modified 2026-06-16 17:25:14 GMT. + Documents single/per-string channels, MIDI Guitar mode, editable velocity + thresholds/accent behavior and user CC assignment. No numeric C0 anchor or + certified keyswitch advance/pulse minimum was found. Full SHA256 revision + fingerprints for all seven PDFs are in docs/articulation-mappings.md. + The legacy https://www.amplesound.net/en/Ample_Guitar_Manual.pdf was also + checked for a numeric convention; no additional usable anchor was found. +- SD3: https://www.toontrack.com/manual/superior-drummer-3/ + Both simplified fetch and rendered browser require login. Stopped without + credentials/bypass. The accessible vendor-hosted image-only attachment: + https://www.toontrack.com/app/uploads/topic/how-can-i-use-midi-or-notaion-created-in-notion-6-to-drive-superior-drummer/pdf/Example-Layout.pdf + Page 1, HTTP Last-Modified 2026-03-04 08:25:19 GMT, explicitly shows SD3 + Hansa - Marble Room: Kick Open=36, Snare Center=38, Hi-Hat Closed Tip=42. + It also labels C0=24 within that layout. It is a forum attachment, not + an established vendor-authored universal/core default mapping; default-state + authorship, library applicability, velocity and hi-hat/controller assumptions + are unresolved. Public forum search corroborated the numbers, but body/reply + access was login-limited, including: + https://www.toontrack.com/forums/topic/mapping-one-articulation-to-two-midi-notes/ + No SD3 profile is admitted from GM convention or that Hansa-specific example. + Needed: authorized default layout for the selected SD3 library/map and + velocity/controller scope; installed-map/custom-override acceptance remains + a separate application gate. + +EXPLICIT COMPATIBILITY POLICIES / LIMITATIONS +- Non-versioned documented default mappings only. 2019 vendor demo files are + numeric anchors, not claims that a particular release is installed today. +- Default tuning/articulation mappings/velocity thresholds; instrument mode, + not Strummer; MIDI Guitar mode disabled. Isolated idle receiver with no + externally held keyswitches or custom remapping. Unknown articulation is + handled explicitly, but this is not a reset of arbitrary external held notes. +- Writer routing: Lead zero-based channel 0, display channel 1. Host must route + the isolated role to the exact product accepting that channel. No per-string + routing, program changes, guessed controller numbers or automatic settings. +- Writer timing at 960 PPQ: velocity-100 latched switch, 120-tick advance, + 30-tick paired pulse released before musical onset. Velocity 100 occurs in + official examples; timing is deterministic engineering policy, NOT a vendor + minimum, measured plugin latency or VST-certified behavior. Tempo-relative + ticks are explicit; 480-PPQ demo timings are not mislabeled as writer limits. +- Shared lead-in preserves all note intervals/durations/dynamics. First requested + state alone initializes; repeated states suppress duplicate pulses. + Incompatible overlapping control/music state fails; it is not retimed away. + No final articulation reset is invented. Switches release; last selection + remains latched. No claim that the owner's plugin settings match defaults. + +TEST COVERAGE AND EXACT FINAL VALIDATION +- Updated historical empty-catalog expectations to two Documented/five unavailable + with no automatic defaults; preserved strict malformed/binding/failure checks. + Legacy Verified JSON without notes still loads with unchanged semantics. + Missing/null/blank/invalid documented notes, missing nested fields, bad public + source URLs and Synthetic/Unverified status laundering are rejected. +- Both admitted profiles assert exact source/manual/demo revisions, numeric + switches/ranges/layers, identity/role, honest version scope, explicit policies + and immutable data. Outside-range notes and unsupported Sustain layers fail. +- Unknown receiver first Sustain and first PM, repeats, transitions, explicit + known-state compatibility, CC initialization, source preservation and note/ + control pairing are covered. The former null-is-invalid expectation was + intentionally replaced by positive unknown-state regressions; unsupported + known initial articulations still have negative coverage. +- 8 new actual file write/read-back cases: each admitted profile with first + Sustain and PM from CompositionPlanner, plus each profile/first-state boundary + and transition arrangement. Exact Type 1/960 PPQ, role/channel, pitches, + velocities, switch/music order, shared lead-in, durations, repeat suppression, + no overlapping switches, paired releases, EndOfTrack and source immutability + are checked through MidiFileWriter and DryWetMIDI.Read. 3 further integration + cases reject invalid Sustain velocity layers before any output exists. +- Final commands, in order (all exit 0): + 1. dotnet test .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-restore --filter "FullyQualifiedName~Articulations|FullyQualifiedName~Instruments|FullyQualifiedName~DocumentedProfileMidiTests" --verbosity minimal + PASS: 278 unit + 21 integration = 299; 0 failed, 0 skipped. + 2. dotnet build .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-restore --verbosity minimal + PASS: all five projects; 0 warnings, 0 errors. + 3. dotnet test .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-build --verbosity minimal + PASS: 658 unit + 56 integration = 714; 0 failed, 0 skipped. + Baseline 663 -> final 714, net +51, with intentional evidence/initialization + contract expectation updates and retained generic MIDI/protocol regressions. + 4. dotnet restore .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx --locked-mode --verbosity minimal + PASS: all five projects up to date; existing locks/package versions unchanged. + 5. git --no-pager diff --check + PASS before report; report-only append checked separately. +- Existing SDK 10.0.400 and pinned DryWetMIDI [8.0.3] retained. + Editor runTests returned "No tests found"; CLI commands above are actual test + evidence. Editor problems for changed source/new tests reported no errors. +- One initial targeted attempt failed on two xUnit2031 analyzer errors in the + new integration assertions. Replaced Where+Assert.Single with predicate + overloads; subsequent targeted/build/full runs all passed. No unresolved + compiler, analyzer, test or restore failures remain. + +FILES / CLEANUP / BOUNDARY +- Modified 18 directly related deliverables including this report: + README.md; docs/articulation-mappings.md; docs/format-compatibility.md; + Core Articulations/InstrumentProfile.cs, InstrumentProfileValidator.cs, + ArticulationPlanner.cs; Generation Profiles/InstrumentProfileCatalog.cs and + instrument-profiles.json; UnitTests Articulations/SyntheticProfiles.cs, + InstrumentProfileValidatorTests.cs, InstrumentProfileCatalogTests.cs, + ArticulationPlannerTests.cs and new DocumentedProfileTests.cs; + IntegrationTests Articulations/ArticulationPipelineTests.cs, + Instruments/InstrumentCatalogPipelineTests.cs, + Midi/MidiGenerationPipelineTests.cs and new DocumentedProfileMidiTests.cs; + prompts/report_4.md. +- Probed existing PDF helper availability first; pdf-parse was missing. + Used disposable session-only pdf-parse@2.4.5 for in-memory text extraction + and the image-only SD3 layout, then removed the entire helper and rendered + image. No helper manifests/dependencies, manuals, demo MIDI/archives, + generated MIDI/native fixtures or vendor assets remain in source/test trees. + Actual file tests clean up only their own checkout-local output directories. +- No personal/vendor directory scan, product installation, credential request, + account bypass, native format investigation/implementation, new project, + production dependency, public MCP tool, prompt/plan edit, commit or delegation. + Owner's pre-existing prompts/plan.md and prompts/step_4_fix.md edits were left + untouched. Server/public tools and native formats were not changed. + +APPLICATION VERIFICATION / STOP +- APPLICATION VERIFICATION PERFORMED: NONE. No VST, SD3, Ample product, Cubase + import, audible playback, native reopen, publication or runtime-free check. + Source facts and automated MIDI format read-back are NOT those checks. +- Two documentation-backed default profiles are ready for bounded review and + in-process source/format use under their explicit assumptions. Five targets + remain unavailable with exact missing facts above; full requested-product and + actual installed-plugin readiness remain blocked. Native evidence and + deployment/public-tool work require their own authorized steps. +- STOP after this report. Do not start another step. + +=============================================================================== +Correction iteration 4: additional evidenced capabilities +Date: 2026-10-20 +Actual entry baseline: 882 tests; Step 8 tools and Step 9 publication already exist. + +SUPPORTED CAPABILITY CORRECTION / PUBLICATION REFRESH: PASS. +READY FOR ORCHESTRATOR REVIEW: YES, for this bounded documented-default subset. +CURRENT: seven identities, five Documented profiles, zero application-Verified. +Lead: AGLP/AGM/AGT/AME Sustain and PalmMute. Bass: ABJ Sustain only. +UNAVAILABLE: AMR and SD3. ABJ PalmMute remains explicitly unsupported. +Native writers, installed-plugin/Cubase acceptance and runtime-free host +acceptance remain pending/blocked. This is not full requested-product completion. +Earlier report counts/results are preserved history. + +IMPLEMENTED CAPABILITIES / UNCHANGED CONTRACTS +- Added three data-only profiles to the existing embedded catalog: + ample-agm-documented-defaults-2026-10-20 + Lead channel0; Sustain24/PM26; inclusive range40-84; + musical Sustain1-126, PM1-127. + ample-abj-documented-defaults-2026-10-20 + Bass channel1; Sustain24 ONLY; inclusive range35-76; + musical Sustain1-125. Accents126-127 and PalmMute fail explicitly. + ample-agt-documented-defaults-2026-10-20 + Lead channel0; Sustain24/PM26; inclusive range40-84; + musical Sustain1-126, PM1-127. +- AGLP/AME IDs, mapping facts, compatibility/warning semantics and generated + example content are unchanged. No production planner, generation service, + grammar, role/articulation enum, DTO/schema or tool implementation changed. +- New evidence remains Documented, never application-Verified. Unknown installed + version/default scope and independent mapping revision remain explicit. + Compatibility notes disclose source limitations, default tuning/mapping/ + thresholds, instrument mode, MIDI Guitar mode off and isolated idle receivers. +- Reused unknown-initial-articulation selection, explicit paired switch release + and repeat suppression. Writer policy remains switch velocity100, advance120/ + pulse30 ticks at960 PPQ. This is engineering policy, NOT a vendor minimum + or measured/certified plugin timing. ABJ channel1/display2 is our routing policy, + not a claim that the historical channel0 demo mandates a receiver channel. +- Discovery now exposes five profiles/nine articulation entries: four Lead + profiles with two articulations each, one Bass profile with Sustain only. + AMR/SD3 stay visible as mapping_unavailable; no cross-product substitution. + Missing explicit Bass selection is no_default_profile, not mapping_unavailable. + Missing Drums mapping, unknown/wrong-role IDs, unselected-role profiles, + disabled fallback and no-overwrite failures remain explicit. +- Updated affected catalog, discovery, in-process, MIDI, stdio and publication + tests, README and mapping/format/protocol/text/deployment documentation. + Explicit ABJ PM requests fail unsupported_articulation with no file, partial + arrangement, fixed-velocity transformation or implicit Sustain fallback. + +EXACT SOURCES / CONFIRMED ABSOLUTE ANCHORS +All new checks performed 2026-10-20. Official rendered download page: + https://www.amplesound.net/en/download.asp +Publicly linked archives were read unauthenticated and in memory using existing +pinned DryWetMIDI8.0.3. No vendor MIDI/archive/manual/native asset was retained. +Main-panel mapping/velocity facts reuse the already reviewed official manuals; +this was not an open-ended repeat of manual research. + +AGM: + https://www.amplesound.net/en/Main_Panel_Manual-AGM.pdf + PDF pp.6-7 sections2.2.1-2.2.4: C0 Sustain/D0 PM, E1-C5; + musical Sustain1-126/127 Pop, PM depth follows velocity. + HTTP Last-Modified2025-09-08 09:00:15 GMT; + SHA256449bd7b8bca7771dbf8e08e0029d2bbe999f991efe441d7900ee93da29dd86a4. + https://www.amplesound.net/dl0822/ds/AGM-Rylynn.zip + HTTP Last-Modified2019-06-11 17:57:25 GMT; + SHA256e88c40ce4e67fde7b692b7f1cd5c4d057d7cd2a50e21d71114379b55d1fabd6f. + Exact entry AGM-Rylynn/AGM3-Rylynn.mid,480PPQ, zero-based track1 "G1": + channel0 note24/velocity80 on32215/off32335. + https://www.amplesound.net/dl0822/ds/AGM-Dear_Ben.zip + HTTP Last-Modified2019-11-24 16:38:43 GMT; + SHA256bb6dd773b5f998a1d0efa80ebc77d6661922e49f137f74a685000792ed618fe5. + Exact entry AGM-Dear Ben/AGM-Dear Ben Tempo 74.mid,480PPQ, + track1 "AGM ARP", channel0: + note26/velocity80 on28798/off28858; note24/velocity80 on30238/off30298. + These directly anchor C0=24/D0=26, hence E1-C5=40-84. + +ABJ: + https://www.amplesound.net/en/Main_Panel_Manual-ABJ.pdf + PDF pp.6-7 sections2.2.1-2.2.4: C0 Sustain, B0-E4, velocities1-125; + 126-127 Accent. Dedicated D0 PM/Dead Note threshold is unspecified. + HTTP Last-Modified2025-04-16 05:04:25 GMT; + SHA2569291c4e3027ac1469bd845bb04614f5a2754bd35a4f017bcfd7cdb75db335e7e. + Official download row "Project - Ample Bass Articulations" explicitly lists + products ABJ ABP, linking: + https://www.amplesound.net/dl0822/ds/AB-Articulations.zip + HTTP Last-Modified2019-06-11 17:32:45 GMT; + SHA256c3efc1dc787c59a00be7405687488317efaf952822aededf54b9e19f4e145cb7. + Exact entry AB-Articulations/4.2 Articulations & Poly Legato.mid,480PPQ, + track1 "ABP", channel0: note24/velocity90 on3720/off4080; + musical note40/velocity90 on3840. Shared applicability is explicitly vendor- + listed, NOT an independently ABJ-named performance. + This anchors C0=24/B0-E4=35-76 for Sustain. The missing D0 threshold blocks + PM, NOT an otherwise supported Sustain-only profile. AMR does not inherit it. + +AGT CONCLUSION: GENUINE NAMED-NOTE ANCHOR CONFIRMED; PROFILE ADMITTED. + The concrete official Tab Player lead was confirmed in rendered: + https://www.amplesound.net/en/tutorial-b.asp + Section6.3 "Tab Play Toggle" explicitly names MIDI note A6 for tab playback, + high velocity on/low velocity off. This is actual vendor text, not a MIDI- + library-supplied label. Historical applicable Tab Player documentation; + no HTTP Last-Modified header. HTML source SHA256: + 542ae25caec1dfea772fbe9f5cc80be0c12ad3104f057e654410226aa1e69e92. + Official download row "Tab Project - Wish You Were Here" lists AGT AGM: + https://www.amplesound.net/dl0822/ds/AGT-Wish_You_Were_Here.zip + HTTP Last-Modified2019-06-11 18:04:59 GMT; + SHA25682a9b42109519d20d9340c6c6cdb972a66663482df483fd0bf5034b84b5d9262. + Exact entry AGT-Wish_You_Were_Here/AGT3-Wish You Were Here Tempo 62.mid: + the directory uses underscores, correcting the prose entry spelling. + 480PPQ; tracks1 "Solo"/2 "Strum" each contain only note105/velocity80, + channel0 on3840/off4320. + Matching the named A6 tab control to numeric105 establishes: + C0 = 105 - (6*12 + 9) = 24; D0=26; E1-C5=40-84. + This is NOT a direct Sustain/PM performance or an octave label inferred from + an assumed convention. The profile emits no Tab Player/note105 control. + Main-panel source: + https://www.amplesound.net/en/Main_Panel_Manual-AGT.pdf + PDF pp.6-7 sections2.2.1-2.2.4; HTTP Last-Modified2025-09-08 09:00:02 GMT; + SHA2562e5696d750841a47061d37737ec7d8435cb4e30756cda15596d1f89ff87810dd. + Its documented C0/D0, E1-C5 and Sustain1-126/PM1-127 facts are anchored + under explicit historical/default scope, not an installed-release claim. + +LIMITS +- AMR has no public demo archive among the nine inspected official rows. + No invented URL, another bass substitute or open-ended search was attempted. +- SD3 remains unavailable; no GM guess, login bypass or new mapping claim. +- Existing AGP/SDP codecs remain unavailable. No native research/implementation, + package/project, new feature/tool, user/global settings edit or delegation. +- No licensed application, VST hosting, audible articulation, native reopen, + exact installed-setting acceptance or runtime-free Windows host was tested. + +ACTUAL MIDI / RPC / PUBLICATION EVIDENCE +- All five admitted profiles pass real in-process composition->profile->plan-> + MIDI write/read-back. New cases cover AGM/AGT first Sustain/PM, boundaries + and transitions; ABJ first Sustain, pitch35/76 and velocity1/125 boundaries, + separate Bass channel1, PM rejection and accents126/127 rejection. +- Actual built-server RPC and refreshed published-server RPC each exercise all + four Lead profiles with explicit ABJ, both MIDI-only and AGP+MIDI fallback. + Exactly one artifact retains both roles; native fallback has two native + target reasons, two written MIDI target outcomes and source-only warnings. +- Eight detailed refreshed-publication Lead+Bass cases each wrote/read435 bytes: + SHA256 F31C7C2236637AF9412738418AF61E7D613D51C89A8FFB43B379012C7798384A. + Type1/960PPQ, Conductor/Lead/Bass; tick-zero120BPM/4-4; + Lead channel0:32 pitch64/velocity96 notes, start120+480*i/duration480; + Bass channel1:4 pitch40/velocity96 notes, start120+3840*i/duration3840; + PM26/100 and Sustain24/100 on0/off30; shared lead-in120; + 76 channel events, exact paired note-offs and three EOTs at15480. + No stuck switches/notes or silently omitted role. Test-owned files removed. +- Refreshed existing executable: + artifacts/publish/win-x64/GAJ3T.MusicGen.RiffGrooveBuilder.Server.exe + 74,734,064 bytes; SHA256 + 921AADE7FB75222E8A7E5E81151F3DC73747CD8036EE751555A613A5DBDD308E. + Its isolated process advertises the five-profile subset, not stale metadata. +- Preserved existing artifacts/examples/ame-lead-example.mid,371 bytes: + SHA256 6F5791FB5C3A7A17E54AAF6436963E4D5723FB948057585060C09BF9B2AFCA3E. + Before/after hash and explicit read-back test pass; no replacement/new retained + example was made. Full payload inventory/refresh evidence is appended to report9. + +FINAL COMMANDS / RESULTS +All exit0; SDK10.0.400, existing pinned DryWetMIDI[8.0.3]. +1. dotnet build .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-restore --verbosity quiet + PASS,0 warnings/errors; repeated after ordinary restore. +2. dotnet restore .\src\GAJ3T.MusicGen.RiffGrooveBuilder.Server\GAJ3T.MusicGen.RiffGrooveBuilder.Server.csproj -p:PublishProfile=win-x64 --locked-mode --verbosity minimal + PASS, dedicated existing publication lock. +3. dotnet publish .\src\GAJ3T.MusicGen.RiffGrooveBuilder.Server\GAJ3T.MusicGen.RiffGrooveBuilder.Server.csproj -p:PublishProfile=win-x64 --no-restore -o .\artifacts\publish\win-x64 --verbosity minimal + PASS, accepted self-contained/single-file profile retained unchanged. +4. dotnet restore .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx --locked-mode --verbosity minimal + PASS, ordinary solution locks; build then focused/full validation. +5. dotnet test .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-build --filter "FullyQualifiedName~Articulations|FullyQualifiedName~Instruments|FullyQualifiedName~GenerationServiceTests|FullyQualifiedName~MusicGenToolsTests|FullyQualifiedName~DocumentedProfileMidiTests|FullyQualifiedName~McpGenerationTests|FullyQualifiedName~PublishedServerTests" --verbosity quiet + PASS:414 unit+107 integration=521;0 failed/skipped. +6. dotnet test .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-build --verbosity quiet + PASS:794 unit+142 integration=936;0 failed/skipped. + Baseline882 retained with intentional availability/default expectation updates; + net+54 tests (14 unit,40 integration). +7. dotnet test .\tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests.csproj -c Release --no-build --filter FullyQualifiedName~PublishedLeadBassUsesRefreshedProfilesAndOneReadableArtifact --logger 'console;verbosity=detailed' + PASS:8; actual435-byte paths/hashes/read-back reported above. +8. dotnet test .\tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests.csproj -c Release --no-build --filter FullyQualifiedName~PublishedServerTests --verbosity quiet + PASS:28;0 failed/skipped, refreshed payload and retained-example check. +9. Both restore commands repeated with --verbosity quiet after full validation: + PASS, unchanged ordinary/dedicated lock graphs. +10. git --no-pager diff --check: PASS before report; both appends checked afterward. + +DEVELOPMENT ISSUE / PRESERVATION +- Initial focused run had two discovery assertions fail because new AGM scope + disclosed "No exact ... verification is claimed" but lacked the existing + explicit "not" wording assertion. Strengthened the AGM compatibility note: + "installed configuration is not verified". No assertion was weakened. + All final focused/full/publication runs pass. +- Editor runTests reported "No tests found"; CLI runs are actual test evidence. + Editor problems on changed tests reported no errors. +- No new package/helper or project was needed. All vendor data was streamed; + no copied assets remain. No generated MIDI/native/stage/PDF files remain + under src/tests, no owned published-check directories/processes remain. +- Existing publish profile, ordinary/dedicated locks and all production engine/ + MCP code were preserved. Prompt/plan files were not edited; their pre-report + scope hashes remain unchanged. No commit, delegation or settings edit. +- Direct deliverables: profile JSON; affected catalog/articulation/MIDI/service/ + protocol/RPC/publication tests; README and five existing docs; these two report + appends; refreshed ignored publication. No unrelated work/later step started. +- STOP for report review. Supported capabilities/publication pass; runtime-free, + licensed-application, remaining mapping/articulation and native gates stay open. +``` diff --git a/prompts/report_5.md b/prompts/report_5.md new file mode 100644 index 0000000..5c23da2 --- /dev/null +++ b/prompts/report_5.md @@ -0,0 +1,258 @@ +``` +STEP 5 REPORT — Standard MIDI builders and safe single-file writer +Date: 2026-10-20 + +STEP 5 FORMAT-WRITER STATUS: PASS; ready for orchestrator review. +REAL PRODUCTION MAPPING / FULL STEP 4 STATUS: FALSE / BLOCKED. +NATIVE-FORMAT / REAL PLUGIN / CUBASE ACCEPTANCE: NOT VERIFIED. +NEXT NATIVE STEP: still requires its authorized evidence; not started. + +IMPLEMENTED +- Added Generation.Midi.MidiEventBuilder.Build, MidiFileBuilder.Build, + MidiFileWriter.Write and MidiFileWriter.WriteFile, with CancellationToken. + Only the existing pinned DryWetMIDI 8.0.3 constructs/reads/writes MIDI. + Core, production mappings, server source and production registry are unchanged. +- Preflight validates the composition, matching selected roles and bar extent, + shared lead-in/end, possible event count, supported event types and ranges, + stable order, checked timing/deltas, track/channel independence, positive + complete note pairing and played-note timing/count/pitched-note agreement. + Drum pitches and output velocities come from the event plan, not guesses. + Invalid/unrepresentable input throws rather than emitting partial success. +- Actual output is SMF type 1, 960 PPQ, named Conductor then selected Lead, + Bass, Drums tracks. No absent-role tracks are added. + Tempo/meter remain at tick zero despite shared lead-in. +- Preserves absolute pitches, transformed output velocities, configured + zero-based channels, CC values, keyswitches and explicit NoteOffEvent + messages (release velocity zero). Direct event insertion preserves the + plan's stable note-off/reset/new-state/musical-on ordering and equal-priority + insertion order; no high-level note/control reordering helper is used. +- Exactly one retained End-of-Track per track is set to the global EndTick. + Declared rests, lead-in and later release/reset tails are preserved. +- Borrowed writable streams, including non-seekable streams, remain open. + Invalid/read-only/disposed streams fail explicitly. I/O failure propagates. + Stream output is not transactional; failure/cancellation can leave bytes. +- Explicit fully qualified file paths require an existing parent and valid + non-reserved filename. A request-owned uniquely named .riffgroove-*.stage + file is created in that SAME directory with CreateNew and exclusive access. + It is fully written and closed before File.Move(..., overwrite: false). + Early File.Exists checks are not the collision-safety mechanism. +- Failure/cancellation deletes only that request's staging file. Late file + and directory collisions preserve the other owner's destination. + Deletion failure reports AggregateException containing original error, + cleanup error and remaining stage path. Simultaneous serialization/ + cancellation and stage-close errors also retain both original exceptions. +- Cancellation is checked during event translation, before/after synchronous + library serialization and before publication. The synchronous library call + has no cancellation-token API and is not interruptible. Observed cancellation + prevents publication; cancellation after the final check/during a successful + move does not undo that completed publication. This is not multi-file + publication, crash-durability, fallback orchestration or Step 8. +- Extracted the existing integration Example/Profiles/Pitched setup into + Support\SyntheticPipelineProfiles.cs. Both old articulation and new file + pipeline tests use that one factory. Unit MIDI tests reuse SyntheticProfiles. +- Updated README and the three directly related existing contracts/inventory. + No new package/project/interface framework, Core dependency, raw MIDI + encoder, native writer, production profile or MCP tool was added. + +PINNED LIBRARY FINDINGS AND LIMITS +- Inspected existing package XML and reflected existing 8.0.3 assemblies; + no package restore/install was used merely for API inspection. + Package XML/reflection path: + C:\Users\g3\.nuget\packages\melanchall.drywetmidi\8.0.3\lib\net45\ + Actual .NET 10 tests exercise the project's resolved library, and assert + assembly version 8.0.3.0 plus the relevant public API shapes. +- SetTempoEvent(Int64) carries integer microseconds per quarter. + Conversion is Math.Round(60000000d / BPM, MidpointRounding.AwayFromZero). + Read-back verifies 120 -> 500000; 123 -> 487805; 512 -> 117188 + (the last quotient is exactly 117187.5), and exact bounds 1/16777215. + Core's UNROUNDED quotient range 1..16777215 remains enforced; quotients + 0.75 and 16777215.25 fail even though rounding could land inside that range. + Nonpositive/nonfinite BPM and out-of-range tempos also fail. +- TimeSignatureEvent(Byte numerator, Byte denominator) takes the ACTUAL + denominator, not its encoded SMF exponent. /128 round-trips correctly. + The Denominator property/constructor parameter are Byte: Core-valid /256 + cannot be represented through this pinned API. The writer throws a clear + NotSupportedException naming /256 and writer powers-of-two range 1..128. + Core still accepts /256; there is no byte wrap, changed meter or silent + narrowing of Core. The SMF representation itself is not claimed to forbid 256. +- MidiEvent.DeltaTime is Int64. Direct pinned-library serialization ACCEPTS + delta 0x10000000; it does not enforce the standard four-byte VLQ maximum. + The builder therefore uses checked subtraction and accepts only + 0..0x0FFFFFFF (268435455) per gap. Exactly the maximum is serialized and + read back; maximum+1 is rejected before any destination bytes/staging. + Backward delta and checked Int64 subtraction overflow are tested. + Because the conductor has metadata only at zero before its end marker, + its end delta also bounds GLOBAL EndTick to 268435455. No filler events + are inserted to conceal a longer arrangement. +- EndOfTrackEvent has NO public constructor. The library writes EOT + automatically and its normal reader omits it unless + ReadingSettings.EndOfTrackStoringPolicy = Store. + EventsCollection documentation also cautions against adding EOT directly. + The builder obtains each track from a library-generated empty-file read + with Store, inserts ordinary events BEFORE the retained EOT and sets that + marker's delta. No reflection construction or handwritten byte fixture is + used in production. Actual read-back proves one EOT at the intended end, + not a duplicate/default zero-time replacement. +- MidiFile.Write(Stream, MidiFileFormat.MultiTrack, WritingSettings) is the + pinned serialization API. NoteOffAsSilentNoteOn is a BOOLEAN setting, + explicitly false; default-tempo/meter deletion and running status are + explicitly false. Both 120-BPM/4-4 metadata and explicit note-offs survive. +- Early exploratory reflection exposed the nonpublic EOT constructor and + /256 byte conversion failure. One mixed exploratory probe exited 1 after + asking for a nonexistent NoteOffAs enum; the actual boolean API above was + then verified. No guessed enum/API remains in implementation. + +ACTUAL FILE WRITE / READ-BACK EVIDENCE +- New integration pipeline runs description -> parse -> composition -> validate + -> extracted SYNTHETIC profiles -> event plan -> actual staged .mid file -> + DryWetMIDI.Read(path, Store + MissedEndOfTrackPolicy.Abort). + All channel events are compared in sequence against the complete event plan: + absolute tick, event type, channel, pitch/CC number and velocity/CC value. + Complete note-off pairing, names, resolution, format and every EOT are checked. +- Full documented four-bar example was written using an explicit path while + Environment.CurrentDirectory was the unrelated existing Windows system + directory. Owned output directories are beneath the checkout's test output. + No files were written in the system directory. +- Captured actual output: 886 bytes. + SHA256: + B7DC2F2F9944ACA22D32A2D5224E3BAF88194AF4B902C3EE60AB0B496EA6A780 + Read-back: type 1, 960 PPQ, Conductor/Lead/Bass/Drums, 175 channel events, + 32 played lead notes + 4 played bass notes + 48 mapped drum hits, + 2 complete switch pairs, 4 EOTs at tick 15600. + Unshifted musical extent 15360; shared lead-in 240; musical/global end 15600. +- Invented test lead: pitch 64, output velocity 110, channel 0, starts + 240 + 480*i (32 notes); switch 11/91 at tick 0, off at 30. + Invented test bass: pitch 40, velocity 96, channel 1, starts + 240 + 3840*i (4 notes); switch 12/92 at 120, off at 140. + Invented test drums: pitches 50/51/52, channel 9, source hit velocities and + exact shifted starts/ends; CC21 = 0@0, 100@240, 0@15600. + These are NOT Ample/SD3 numbers or application compatibility evidence. +- Reversed profile enumeration produces byte-identical repeated file output; + source composition/event plan JSON remains unchanged. +- Additional actual files cover selected roles (including Lead+Bass), 3/8 at + 123 BPM, 1000 repeated 7/8 bars (14000 sixteenth notes, exact 240-tick + spacing, 3360000 unshifted ticks + 240 lead-in), declared trailing rests, + final reset pulse tail to 4110 and momentary switch release to 20000. + Every track in each file has the same global end. + Unit read-back also covers exact rational triplets at 320-tick spacing. +- File tests cover pre-existing and late-collision no-overwrite behavior, + real staged files, injected serialization error/cancellation, unrelated-file + preservation and explicit cleanup/close failure aggregation. Locked owned + file deletion failure is exercised directly through the cleanup helper. + Borrowed-stream tests exercise actual library writes into failing streams + and cancellation signalled by a write callback at the synchronous boundary. + No disk-full/power-loss or application import scenario is claimed. +- Generated .mid files/test directories are deleted by their owning tests. + Final audits found zero .mid/.midi/.agp/.sdp/.stage files and zero owned + midi-writer-/midi-pipeline- directories under src/tests. + +CHANGED FILES (14 deliverables including this report) + src\GAJ3T.MusicGen.RiffGrooveBuilder.Generation\Midi\MidiEventBuilder.cs + src\GAJ3T.MusicGen.RiffGrooveBuilder.Generation\Midi\MidiFileBuilder.cs + src\GAJ3T.MusicGen.RiffGrooveBuilder.Generation\Midi\MidiFileWriter.cs + tests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\Midi\MidiEventBuilderTests.cs + tests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\Midi\MidiFileBuilderTests.cs + tests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\Midi\MidiFileWriterTests.cs + tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\Midi\MidiGenerationPipelineTests.cs + tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\Articulations\ArticulationPipelineTests.cs + tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\Support\SyntheticPipelineProfiles.cs + README.md + docs\articulation-mappings.md + docs\format-compatibility.md + docs\text-description-contract.md + prompts\report_5.md + +EXACT VALIDATION COMMANDS AND RESULTS +All dotnet commands ran from the repository root with process-local settings: + $env:PATH = 'C:\Program Files\dotnet;' + $env:PATH + $env:DOTNET_CLI_TELEMETRY_OPTOUT = '1' + $env:DOTNET_NOLOGO = '1' +Executable: C:\Program Files\dotnet\dotnet.exe. + +FINAL FOCUSED VALIDATION +1. dotnet test .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-restore --filter FullyQualifiedName~.Midi. --verbosity quiet + PASS, exit 0: 86 unit + 11 integration = 97 passed, 0 failed/skipped. + +FINAL REQUIRED ACCEPTANCE (rerun after the last code/test changes) +2. dotnet build .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-restore + PASS, exit 0; all five projects; 0 warnings, 0 errors (0.63 s). +3. dotnet test .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-build + PASS, exit 0: + UnitTests: 618 passed, 0 failed, 0 skipped (667 ms). + IntegrationTests: 45 passed, 0 failed, 0 skipped (1 s). + TOTAL: 663 passed, 0 failed, 0 skipped. + All 566 accepted baseline cases retained; 97 new Step 5 cases. +4. dotnet restore .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx --locked-mode + PASS, exit 0; all five projects up to date against unchanged locks. + +FILE EVIDENCE COMMAND +5. dotnet test .\tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests.csproj -c Release --no-build --filter FullyQualifiedName~FullExampleWritesActualTypeOneFileFromUnrelatedCwdAndReadsEveryEventBack --logger 'console;verbosity=detailed' + PASS, exit 0: 1 passed, 0 failed/skipped. Printed the 886-byte hash and + read-back facts above. Subsequent final full run also passed this case. + +DEVELOPMENT HISTORY / CORRECTIONS +6. dotnet build .\src\GAJ3T.MusicGen.RiffGrooveBuilder.Generation\GAJ3T.MusicGen.RiffGrooveBuilder.Generation.csproj -c Release --no-restore --verbosity quiet + PASS, exit 0; 0 warnings/errors. +7. dotnet test .\tests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests.csproj -c Release --no-restore --filter FullyQualifiedName~.Midi. --verbosity quiet + Initial: exit 1; 76 passed, 2 failed, 0 skipped. + Corrected test expectations/setup: stable same-priority switch off precedes + musical off in the existing plan; a failing buffered stream must itself + simulate partial write before throwing to test retained partial bytes. + Retry: exit 0; 78 passed, 0 failed/skipped. +8. dotnet test .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-restore --filter 'FullyQualifiedName~.Midi.|FullyQualifiedName~.Articulations.ArticulationPipelineTests' --verbosity quiet + Initial: exit 1; unit 78 passed; integration 18 passed/2 failed. + Next: exit 1; unit 78 passed; integration 19 passed/1 failed. + Corrected new assertions, not existing musical/planner behavior: + 7/8 contains 14, not 28, sixteenth notes per bar; selected sustain rules + still contribute their configured shared 240 lead-in; drum final CC reset + consumes the trailing-rest delta, leaving a zero-delta EOT at the same end. + Final retry: exit 0; unit 78 + integration 20 passed, 0 failed/skipped. + The integration selector includes 9 retained articulation cases. +9. The exact focused command in (1) also passed during test expansion: + 82 unit + 11 integration; then 83 unit + 11 integration; finally 86 + 11. + An earlier full build/test/locked restore passed 615 unit + 45 integration + before the three final stage-close error cases were added; final (2)-(4) + supersede that count. + +Diagnostic no-build commands (all exited 1 on the known failing assertions): + dotnet test .\tests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests.csproj -c Release --no-build --filter 'FullyQualifiedName~InvalidReadOnlyDisposedAndFailingStreamsAreTruthful|FullyQualifiedName~SameTickMomentaryReleaseResetNewStateAndNotesKeepStableOrder' --logger 'console;verbosity=normal' + 0 passed, 2 failed, 0 skipped. + dotnet test .\tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests.csproj -c Release --no-build --filter 'FullyQualifiedName~RestsKeepFullDeclaredBarsEvenAfterLastNoteOff|FullyQualifiedName~LongRepeatedPatternUsesExactTicksWithoutAccumulatedDrift' --logger 'console;verbosity=normal' + 0 passed, 2 failed, 0 skipped. + dotnet test .\tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests.csproj -c Release --no-build --filter FullyQualifiedName~LongRepeatedPatternUsesExactTicksWithoutAccumulatedDrift --logger 'console;verbosity=normal' + 0 passed, 1 failed, 0 skipped. +All development failures above are resolved; final focused/full runs pass. + +ADDITIONAL CHECKS / PRESERVATION / UNRUN CHECKS +- Editor runTests over the three initial MIDI unit files: "No tests found". + Used the prescribed CLI fallback; editor nondiscovery is not a test pass. +- Editor problems over src/tests and final changed source: no errors found. +- git --no-pager diff --check: PASS, exit 0. In-memory whitespace audit of + new source/test files: PASS. No scratch source/log files were retained. +- Core project audit: zero PackageReference/ProjectReference elements. + Embedded production profile JSON remains exactly []; server still constructs + new McpToolRegistry() with no production tools. Full protocol/catalog + regressions pass. No dependency manifests or lock files were changed. +- Entry-state modified prompts\plan.md and untracked prompts\step_5.md were + preserved, not edited/reset. Existing reports/prompts were not modified. + No new later prompt, commit, delegation, native writer or public tool. +- No real Ample/SD3/Cubase imports, installed-plugin scanning, audio/device + work, Riffer-specific single-track export, AGP/SDP serialization, publication + or runtime-free deployment check was performed. These are not Step 5 passes. + +READINESS AND STOP +- No unresolved generic builder/writer build/test blocker remains. + /256 and four-byte-delta limits are explicit tested writer limitations, + not silently changed compositions or fabricated success. +- Format-writer readiness is PASS for the supported limits, subject to + orchestrator review of this report and changes. +- Real mapping admission remains BLOCKED for ABJ/AGLP/AGM/AGT/AME/AMR/SD3: + exact installed versions/settings, complete authorized numeric/timing/ + velocity/channel/state maps and actual application verification are missing. + Synthetic format tests do not establish real plugin compatibility. +- Native schemas, lawful fixtures/template rights, AGP/SDP entity/extension/ + load semantics and plugin/Cubase acceptance remain separate open gates. + The combined type-1 arrangement is not automatically a single-track + Riffer-import file, and MIDI is not a renamed native container. +- Stopping after Step 5 for report review. No Step 6 or profile work started. +``` diff --git a/prompts/report_8.md b/prompts/report_8.md new file mode 100644 index 0000000..f4dda2a --- /dev/null +++ b/prompts/report_8.md @@ -0,0 +1,222 @@ +``` +STEP 8 REPORT — Supported MCP MIDI / explicit native-fallback slice +Date: 2026-10-20 + +SUPPORTED-SLICE IMPLEMENTATION / AUTOMATED VALIDATION: PASS. +READY FOR ORCHESTRATOR REVIEW: YES. +FULL REQUESTED-PRODUCT / NATIVE / APPLICATION READINESS: FALSE / BLOCKED. +Steps 6/7 remain blocked, not completed. Publishing and application acceptance +were not started. Stop here for orchestrator review. + +IMPLEMENTED +- Production registers exactly list_instrument_profiles and generate_project. + Empty and synthetic test registries remain supported; existing lifecycle, + framing, cancellation, admission, internal-error logging and stdout behavior + are preserved. +- Added dependency-free typed Core request/result/discovery DTOs. Tool schemas + use explicit required inputs, fixed objects with additionalProperties:false, + string enums, nonempty unique formats, non-null supplied optional fields and + strict nested profile objects. Runtime validation matches these constraints, + including exact enum casing and duplicate rejection. +- Kept the existing typed registry/serializer. Added only input-schema override, + raw-argument validation and output-schema refinement hooks, plus camel-case + string-enum serialization. Output schemas include required nullable failure + fields and a conditional success/failure constraint. Successful results require + composition/timing, artifacts/targets and no errors; failed results have no + artifacts and nonempty errors. Artifact byte counts must be positive. +- structuredContent and the single text JSON content entry match exactly. + isError is true only for failed results, never complete/explicit MIDI fallback. + Contract errors remain JSON-RPC -32602; unexpected errors remain logged -32603. + +DISCOVERY / EVIDENCE / SELECTION +- Discovery returns seven declared identities and the two admitted Documented + Lead profiles, with role filters retaining unavailable targets: + ample-aglp-documented-defaults-2026-10-20 + ample-ame-documented-defaults-2026-10-20 +- Includes stable/vendor/product identity, documentation URL, instrument/profile + binding, honest product/version and mapping revision, playable range/channel, + articulation mechanisms and constraints, evidence and immutable compatibility + notes. No synthetic fixture is exposed. +- MIDI writer capability is implemented; AGP/SDP writers are unavailable. + Native/application compatibility remains unverified, not application-tested. +- Every Documented generation includes a source-only, NOT installed/application- + verified warning carrying the exact version, configuration, routing and timing + compatibility notes. Writer timing remains engineering policy, not certified + plugin latency or a vendor minimum. +- No automatic role profile defaults or instrument substitutions. Missing Lead + selection lists both available IDs. Missing Bass/Drums mappings fail the whole + arrangement; unknown/wrong-role and unselected-role profiles also fail. + ABJ, AGM, AGT, AMR and SD3 remain unmapped and visible. + +GENERATION / FALLBACK / FILESYSTEM +- Actual pipeline: bounded text parser/composition planner -> admitted explicit + catalog selection -> existing articulation planner -> real safe MIDI writer. + No text grammar, profile values, native codecs or mappings were invented. +- Omitted formats use applicable native formats plus MIDI. Lead-only therefore + means AGP+MIDI, not an inapplicable SDP request. +- Applicable native requests with fallbackToMidi=true (the default) produce one + complete combined MIDI artifact, status=fallback, per-native-target reasons + and native-unavailable warnings. Explicit MIDI reuses that file. +- Disabled native fallback fails preflight with no directory/artifact. + MIDI-only works with fallback=false and status=complete. + Inapplicable formats are errors, not fallback opportunities. +- Result targets cover every applicable selected-role/requested-format pair, + carrying instrumentId/profileId, outcome, actual paths and diagnostics. + All failures have no usable artifact paths or partial success. +- Output is .mid, using the existing type-1/960-PPQ conductor plus + selected named role tracks. Source pitches/velocities and controls survive. +- Extracted genuinely shared filename validation for service and MIDI writer: + reject traversal/separators, reserved Windows devices (including superscript + device digits), alternate streams, control characters and trailing dot/space. + Absolute output directories reject traversal and device syntax, including + alternate separator forms. +- Extracted shared MIDI meter/global-extent capability preflight within + MidiFileBuilder, used by service and builder before directory creation. + /256 and oversized four-byte SMF deltas fail explicitly, never trigger fallback. + No duplicate MIDI construction or speculative multi-output transaction layer. +- Only after semantic/profile/format preflight is the explicit directory created. + Existing writer stages with CreateNew beside the destination and publishes + File.Move(overwrite:false). Existing files, directory collisions and races are + preserved. Failure/cancellation cleans only request-owned staging. + A directory created before an I/O failure may remain empty; unrelated + directories/files are not recursively removed. +- I/O/access errors return actionable failed results, never fallback success. + Unexpected failures propagate to the existing logged internal-error boundary. + Existing writer cleanup/close aggregation remains intact. + +RESPONSIVENESS / CANCELLATION +- GenerationService.GenerateAsync schedules parsing/planning and all synchronous + filesystem/DryWetMIDI work on a worker, off the transport reader. Discovery also + runs its handler work off that reader. +- Deterministic blocked synchronous-work tests prove ping responses and + cancellation can be read before generation completes. Unexpected worker errors + are logged and do not corrupt protocol output. +- Cancellation propagates, prevents publication when observed beforehand and + leaves no request artifact/stage. Existing writer tests exercise cancellation + during synchronous serialization and cleanup. +- DryWetMIDI serialization has no token API and cannot be interrupted internally; + checks occur around it and before publication. Publication remains the commit + point: cancellation racing after the final check/move does not undo that file. + EOF cancels active requests; clients must keep stdin open until responses. + +REAL SUBPROCESS RPC / FILE READ-BACK EVIDENCE +- Tests launch the actual Release Server apphost from an unrelated existing OS + working directory, initialize MCP 2025-11-25, discover both schemas, list real + profiles and invoke generate_project with description: + palm-muted eighth-note lead +- Five real successful file cases: + AME formats=[mid], fallback=false -> complete + AGLP formats=[mid], fallback=false -> complete + AGLP formats=[agp], fallback=true -> fallback + AME formats=[agp,mid], fallback=true -> fallback + AGLP formats omitted, fallback=true -> fallback (AGP+MIDI targets) +- Each response identifies exactly one existing 371-byte .mid, with matching + absolute path/byte count/profile ID/role, source-only warnings and per-target + outcomes. No .agp/.sdp/duplicate .mid placeholder is created. +- Example actual native-only fallback path from the detailed evidence run: + D:\_Repos\Code\GAJ3T\MCPs\MusicGen\GAJ3T.MusicGen.Riff-Groove-Builder.Net\tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\bin\Release\net10.0\rpc-generation-9f89f26e1c5f47caa8882656a55c3357\rpc-song.mid + SHA256: + 6F5791FB5C3A7A17E54AAF6436963E4D5723FB948057585060C09BF9B2AFCA3E + All five files have this same content hash for the common supported PM case; + the selected product/profile remains explicit in response metadata/warnings. +- DryWetMIDI.Read with stored EOTs and missing-EOT abort verifies: + SMF type 1, 960 PPQ; exactly Conductor and Lead; + tick-zero 500000 microseconds/quarter (120 BPM), 4/4 metadata; + 32 pitch-64 velocity-96 musical notes on zero-based channel 0; + starts 120 + 480*i, each duration 480, i=0..31; + one PM26/velocity100 keyswitch at tick0, paired explicit release at30; + 66 channel events, explicit zero-release-velocity note-offs, no stuck notes; + shared lead-in120, musical extent15360, two EOTs at15480. +- Additional actual RPC cases cover role-filter discovery, missing/wrong-role/ + unselected profiles, unavailable selected roles, disabled fallback, inapplicable + formats, invalid text/path/name/contracts, MIDI limits, existing-file protection, + read-ahead cancellation and subsequent ping. Protocol-only stdout and bounded + process-owned cleanup remain enforced. +- Tests read files while present, then delete only their own checkout-local test + directories. The example path is evidence of an actual completed run, not a + promised retained artifact. No vendor/native fixtures or generated files are + retained. + +CHANGED FILES (21 Step 8 deliverables, including this report) + README.md + docs\mcp-protocol.md + docs\format-compatibility.md + docs\articulation-mappings.md + docs\text-description-contract.md + src\GAJ3T.MusicGen.RiffGrooveBuilder.Core\Generation\GenerateProjectRequest.cs + src\GAJ3T.MusicGen.RiffGrooveBuilder.Core\Generation\GenerationResult.cs + src\GAJ3T.MusicGen.RiffGrooveBuilder.Core\Generation\ProfileCatalogResult.cs + src\GAJ3T.MusicGen.RiffGrooveBuilder.Generation\GenerationService.cs + src\GAJ3T.MusicGen.RiffGrooveBuilder.Generation\Output\OutputPath.cs + src\GAJ3T.MusicGen.RiffGrooveBuilder.Generation\Midi\MidiFileBuilder.cs + src\GAJ3T.MusicGen.RiffGrooveBuilder.Generation\Midi\MidiFileWriter.cs + src\GAJ3T.MusicGen.RiffGrooveBuilder.Server\Program.cs + src\GAJ3T.MusicGen.RiffGrooveBuilder.Server\Tools\MusicGenTools.cs + src\GAJ3T.MusicGen.RiffGrooveBuilder.Server\Tools\McpToolDefinition.cs + tests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\Generation\GenerationServiceTests.cs + tests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\Protocol\MusicGenToolsTests.cs + tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\Stdio\McpGenerationTests.cs + tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\Stdio\McpProtocolTests.cs + tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\Stdio\McpProcess.cs + prompts\report_8.md + +EXACT FINAL VALIDATION COMMANDS / COUNTS +Repository root, installed SDK 10.0.400, unchanged DryWetMIDI [8.0.3]. +Each dotnet shell used these process-local settings: + $env:PATH = 'C:\Program Files\dotnet;' + $env:PATH + $env:DOTNET_CLI_TELEMETRY_OPTOUT = '1' + $env:DOTNET_NOLOGO = '1' + +1. dotnet test .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-restore --filter 'FullyQualifiedName~.Generation.|FullyQualifiedName~MusicGenToolsTests|FullyQualifiedName~McpGenerationTests|FullyQualifiedName~McpProtocolTests|FullyQualifiedName~.Midi.' --verbosity minimal + PASS, exit0: 208 unit + 64 integration = 272; 0 failed, 0 skipped. +2. dotnet build .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-restore --verbosity minimal + PASS, exit0: all five projects; 0 warnings, 0 errors. +3. dotnet test .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-build --verbosity minimal + PASS, exit0: 780 unit + 88 integration = 868; 0 failed, 0 skipped. + Accepted baseline714 retained; net +154 (122 unit, 32 subprocess integration). +4. dotnet restore .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx --locked-mode --verbosity minimal + PASS, exit0: all five projects up to date; unchanged manifests/locks/versions. +5. dotnet test .\tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests.csproj -c Release --no-build --filter FullyQualifiedName~RealRpcGeneratesReadableDocumentedMidiAndOneHonestFallbackArtifact --logger 'console;verbosity=detailed' + PASS, exit0: 5 passed, 0 failed/skipped; printed actual paths, 371-byte counts, + hashes and read-back facts above. +6. git --no-pager diff --check + PASS, exit0 before report; report-only addition rechecked afterward. + +DEVELOPMENT CORRECTIONS / OTHER VALIDATION +- Editor runTests reported "No tests found"; used the established dotnet CLI + fallback. This editor result is not counted as passing tests. +- Initial focused unit command: + dotnet test .\tests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests.csproj -c Release --no-restore --filter 'FullyQualifiedName~.Generation.|FullyQualifiedName~MusicGenToolsTests' --verbosity minimal + First attempt: compile failure CS9007 in two new raw interpolated JSON test + strings; replaced them with JsonSerializer-built envelopes. + Next attempt: 110 passed/2 failed, because two new limit tests incorrectly used + "in" before a numeric meter. Corrected tests to the unchanged documented grammar. +- First combined focused build/test attempt: + dotnet test .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-restore --filter 'FullyQualifiedName~.Generation.|FullyQualifiedName~MusicGenToolsTests|FullyQualifiedName~McpGenerationTests|FullyQualifiedName~McpProtocolTests|FullyQualifiedName~MidiFileWriterTests' --verbosity minimal + Unit139 passed; integration compilation failed CS8604 in a new source-note + assertion. Made the asserted source-note string explicitly non-null. +- All above failures were corrected; later focused runs passed before further + coverage expansion, and final commands1-5 passed after the last source/test edit. +- Editor problems over src/tests: no errors. Core csproj still contains zero + PackageReference/ProjectReference elements. No package/project/lock changes. +- Final cleanup audit checks src/tests for .mid/.midi/.agp/.sdp/.stage files and + owned generation/music-tools/rpc-generation test directories. +- Existing source-backed profile work and all other pre-existing modifications, + including prompts\plan.md, prompts\report_4.md, prompts\step_4_fix.md and the + existing prompts\step_8.md, were preserved. No orchestration prompt/plan edits. + +SCOPE / REMAINING BLOCKERS / STOP +- Supported explicit AGLP/AME Lead MIDI and native-fallback MCP slice is usable + and ready for orchestrator review, not full-scope application readiness. +- Five mappings remain unavailable: ABJ/AMR numeric anchors and relevant PM + thresholds, AGM/AGT product-specific numeric anchors, SD3 authorized selected + library/map/controller scope. No Bass/Drums substitute or GM guess was added. +- AGP/SDP authorized codecs/fixtures and exact native-extension/import semantics + remain unresolved. No native writer or native-success claim exists. +- No VST/Ample/SD3/Cubase import, audible/application verification, exact installed + version acceptance, runtime-free deployment or publishing was performed. + Source Documentation, RPC execution and MIDI file read-back are not those gates. +- No new package/project, public CLI generation command, VST scanning/loading, + native format, publishing, commit or delegation. No later worker step started. +- STOP after this report for orchestrator review. +``` diff --git a/prompts/report_9.md b/prompts/report_9.md new file mode 100644 index 0000000..a4f2626 --- /dev/null +++ b/prompts/report_9.md @@ -0,0 +1,345 @@ +``` +STEP 9 REPORT — Supported-slice Windows x64 local MCP publication +Date: 2026-10-20 + +SUPPORTED-SLICE PUBLICATION / AUTOMATED VALIDATION: PASS. +READY FOR ORCHESTRATOR REVIEW: YES. +FULL REQUESTED-PRODUCT / APPLICATION READINESS: FALSE / BLOCKED. +Runtime-free Windows acceptance: PENDING, not performed. +Native Steps 6/7, five mappings and licensed-application acceptance remain open. +Stop here for review; no later step was started. + +IMPLEMENTED / PRESERVATION +- Added Properties\PublishProfiles\win-x64.pubxml: Release, win-x64, + SelfContained=true, PublishSingleFile=true, PublishTrimmed=false, + PublishAot=false, UseAppHost=true, IncludeNativeLibrariesForSelfExtract=true. + Existing assembly/executable name, Microsoft.NET.Sdk/net10.0/OutputType=Exe, + application code, two MCP tools and embedded catalogs are unchanged. +- Added a publication-specific packages.win-x64.lock.json, generated by restore. + Single-file publication needs the SDK's implicit ILLink analysis tool 10.0.11 + and RID graph. The profile selects this separate lock so normal solution + locked restore remains reproducible. No PackageReference, central version, + project or existing packages.lock.json changed in the final result. + DryWetMIDI remains exactly [8.0.3]; all existing test pins are unchanged. + ILLink is SDK build tooling, not an added application feature/dependency. +- Extended the existing McpProcess harness with optional explicit absolute + executable path and child-only environment overrides. Existing callers and + bounded 15-second timeout/concurrent stdout+stderr drains remain supported. + Cleanup kills only its owned Process tree if necessary. +- Added 14 focused PublishedServerTests, reusing existing structured-content + assertions and pinned DryWetMIDI read-back. Existing read-back additionally + checks tick-zero tempo/meter; no alternate MIDI parser was introduced. +- Added docs\local-deployment.md: reproducible/locked publication, exact payload, + native extraction facts, copyable VS Code servers/type=stdio/command/args + configuration, explicit AME/AGLP tool arguments, lifecycle, paths, collisions, + fallback, cancellation, troubleshooting and honest acceptance limits. + Updated README.md and docs\format-compatibility.md accordingly. +- All pre-existing source/profile/MCP changes and orchestration files were + preserved. No prompts/plan or worker-prompt changes, MCP settings edits, + service registration, long-lived service, vendor/system installation, + public CLI generation feature, new project, commit or delegation. + +PERSISTENT ARTIFACTS / EXACT PUBLICATION INVENTORY +Repository: + D:\_Repos\Code\GAJ3T\MCPs\MusicGen\GAJ3T.MusicGen.Riff-Groove-Builder.Net +Published executable: + D:\_Repos\Code\GAJ3T\MCPs\MusicGen\GAJ3T.MusicGen.Riff-Groove-Builder.Net\artifacts\publish\win-x64\GAJ3T.MusicGen.RiffGrooveBuilder.Server.exe +Published directory: artifacts\publish\win-x64 + GAJ3T.MusicGen.RiffGrooveBuilder.Server.exe 74,721,264 bytes + GAJ3T.MusicGen.RiffGrooveBuilder.Core.pdb 37,636 bytes + GAJ3T.MusicGen.RiffGrooveBuilder.Generation.pdb 20,208 bytes + GAJ3T.MusicGen.RiffGrooveBuilder.Server.pdb 20,320 bytes + Melanchall_DryWetMidi_Native64.dylib 90,600 bytes + TOTAL: five files, 74,890,028 bytes. +Executable SHA256: + DC7A1CB45BD61B565016932656CDE0E2D9DE161412269B356D79512595AD1E90 +Publication and generated example remain locally present and git-ignored by the +existing artifacts/ rule; no unrelated artifacts were deleted. + +ACTUAL PUBLISHED-PROCESS / RPC FACTS +- Tests copy the actual five-file publication into a unique checkout-owned + artifacts\checks\published-\payload, not the built Server test copy. + They launch that explicit exe with cwd=the existing Windows system directory + (C:\Windows\System32), redirected UTF-8 streams and bounded cleanup. +- Initialize MCP 2025-11-25 and send notifications/initialized; discover exactly + generate_project and list_instrument_profiles; discovery returns seven + identities, two Documented profiles and five mapping_unavailable identities. + Explicit profiles exercised: + ample-ame-documented-defaults-2026-10-20 + ample-aglp-documented-defaults-2026-10-20 +- Both explicit Lead profiles, formats=["mid"], fallbackToMidi=false produce + status=complete and exactly one actual 371-byte MIDI with compatibility warning. + Text content exactly matches structuredContent; successful isError=false. +- AGP-only, AGP+MIDI and omitted Lead formats produce status=fallback, exactly + one real MIDI and native_writer_unavailable reasons; no native placeholder. + Disabled fallback fails with native_fallback_disabled and no output directory. + Lead+Bass and Lead+Drums fail explicitly with mapping_unavailable, with no + partial artifacts or silently dropped selected role. +- A second request for an already generated MIDI fails with output_exists, + preserves its exact original bytes and an unrelated owner.txt, and leaves + no extra staging/partial artifact. The original MIDI reopens afterward. +- Parse errors (-32700) and contract errors (-32602) leave the process usable. + Initialize/tool/ping replies prove readiness; stdout lines are protocol-only. + Normal completion requires empty stderr, clean EOF exit0 and no extra response. + Empty stdin/EOF exits silently. Cancellation plus ping and a separate active- + generation EOF case leave no output. +- These 14 checks generate eight actual successful MIDI files per focused run, + all read back before owned test cleanup; one collision case reads its file + again after the rejected second request. Retained-example opt-in is separate. +- Final cleanup inspection: zero owned published-check directories and zero + published-check server processes remaining. No long-lived helper was started. + +PINNED PACKAGE / EXTRACTION / PACKAGING FACTS +- Inspected DryWetMIDI 8.0.3's actual package assets/build targets: its None items + copy native32/native64 Windows DLLs and the macOS dylib without RID filtering. + The .dylib remains a Windows-unused sidecar; three PDBs are optional symbols. +- A separate task-owned directory containing ONLY the published .exe also + successfully initialized MCP, generated actual MIDI, passed DryWetMIDI + read-back/ping and exited0 from the unrelated cwd. No source-tree loose + DLL/catalog/cwd dependency, symbols or macOS sidecar was needed for this path. +- DOTNET_BUNDLE_EXTRACT_BASE_DIR was set only in child test processes, beneath + their owned checkout directories; it did not change user/machine settings. + Executable-only startup extracted exactly: + Melanchall_DryWetMidi_Native32.dll 57,954 bytes + SHA256 080346C638E219EC7CD4748E370E5E11931ED3A228C17F76D84C4D10BA9C9E6F + Melanchall_DryWetMidi_Native64.dll 66,926 bytes + SHA256 80CA89AF931E43642A125EC82E253D9BD7002088D000DABA6E0661CDAD89F5AA + Tests compare these with the inspected pinned-package hashes. No loose + managed DryWetMIDI assembly, catalog, coreclr.dll or clrjit.dll was extracted. +- Child-only DOTNET_HOST_TRACE=1 / DOTNET_HOST_TRACEFILE showed: + Executing as a self-contained app as per config file [...] + Using internal hostpolicy + hostpolicy version: 10.0.11 + CoreCLR path = '', CoreCLR dir = '' + Runtimeconfig inspection records includedFrameworks Microsoft.NETCore.App + 10.0.11, not a framework-dependent runtime requirement. +- This is Windows x64 publication on SDK 10.0.400/.NET 10.0.11. Normal bundle + extraction needs a writable cache; the guide explains default/override paths. + Package extraction is not proof of device-library invocation: no playback/ + MIDI-device API was used. Host tracing and SDK-machine execution are NOT + runtime-free host acceptance. No matching runtime-free host was available; + that test remains pending, without simulated DOTNET_ROOT evidence. + +RETAINED ACTUAL RPC-GENERATED EXAMPLE + D:\_Repos\Code\GAJ3T\MCPs\MusicGen\GAJ3T.MusicGen.Riff-Groove-Builder.Net\artifacts\examples\ame-lead-example.mid +Generated by PublishedRpcGeneratesReadBackExample with child published stdio RPC: + description: 4 bars at 120 BPM in E minor, 4/4: palm-muted eighth-note lead + formats: ["mid"] + profiles.lead: ample-ame-documented-defaults-2026-10-20 + fallbackToMidi: false + outputDirectory: \artifacts\examples + projectName: ame-lead-example +Destination did not already exist. Test logic preserves any existing destination +and selects a distinct GUID-suffixed stem on future opt-in runs. +Result: status=complete, one 371-byte MIDI and Documented compatibility warning. +SHA256: + 6F5791FB5C3A7A17E54AAF6436963E4D5723FB948057585060C09BF9B2AFCA3E +Pinned DryWetMIDI 8.0.3 reopened the actual RPC-returned path and checked: + SMF type1, 960 PPQ; exactly Conductor and Lead tracks; + tick-zero 500000 microseconds/quarter (120 BPM), 4/4; + 32 musical notes, pitch64/velocity96/channel0; + starts 120+480*i, duration480, i=0..31, explicit velocity0 note-offs; + one PM switch26/velocity100 at0 with explicit note-off at30; + 66 channel events, shared lead-in120, both EOT markers at15480. +This is newly generated content, not a copied vendor demo/native fixture. +Source-backed Documented compatibility is NOT installed/application-verified; +import/audible behavior and certified vendor timing were not tested. + +FINAL REPRODUCIBLE VALIDATION / RESULTS +Repository-root PowerShell. Each dotnet shell used process-local: + $env:PATH = 'C:\Program Files\dotnet;' + $env:PATH + $env:DOTNET_CLI_TELEMETRY_OPTOUT = '1' + $env:DOTNET_NOLOGO = '1' + +1. dotnet publish .\src\GAJ3T.MusicGen.RiffGrooveBuilder.Server\GAJ3T.MusicGen.RiffGrooveBuilder.Server.csproj -p:PublishProfile=win-x64 -o .\artifacts\publish\win-x64 --verbosity minimal + PASS, exit0; inspected actual payload listed above. +2. dotnet restore .\src\GAJ3T.MusicGen.RiffGrooveBuilder.Server\GAJ3T.MusicGen.RiffGrooveBuilder.Server.csproj -p:PublishProfile=win-x64 --locked-mode --verbosity minimal + PASS, exit0; separate publication lock honored. +3. dotnet publish .\src\GAJ3T.MusicGen.RiffGrooveBuilder.Server\GAJ3T.MusicGen.RiffGrooveBuilder.Server.csproj -p:PublishProfile=win-x64 --no-restore -o .\artifacts\publish\win-x64 --verbosity minimal + PASS, exit0; final retained payload, revalidated afterward. +4. dotnet restore .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx --locked-mode --verbosity minimal + PASS, exit0 before Release build, and again after the full suite. +5. dotnet build .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-restore --verbosity minimal + PASS, exit0; all five projects, 0 warnings, 0 errors. +6. dotnet test .\tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests.csproj -c Release --no-build --filter FullyQualifiedName~PublishedServerTests --verbosity minimal + PASS, exit0; 14 passed, 0 failed/skipped against final published payload. + Earlier build-enabled focused run also passed all 14. +7. $env:RIFFGROOVE_RETAIN_EXAMPLE = '1' + dotnet test .\tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests.csproj -c Release --no-build --filter FullyQualifiedName~PublishedRpcGeneratesReadBackExample --logger 'console;verbosity=detailed' + PASS, exit0; 1 passed, 0 failed/skipped. Printed retained path/hash/read-back + and initialized/ping/empty-stderr/EOF-exit0 facts. Environment was scoped to + this shell; subsequent full-suite shells did not retain more examples. +8. dotnet test .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-build --verbosity minimal + PASS, exit0; 780 unit + 102 integration = 882 passed, 0 failed/skipped. + Accepted baseline868 preserved; net +14 publication integration cases. +9. git --no-pager diff --check + PASS before report; final report-only addition checked afterward. +Editor problems on all three edited/new test files: no errors. + +DEVELOPMENT ISSUES / CORRECTIONS +- Editor runTests returned "No tests found"; not counted as test success. + Used the established dotnet CLI runner instead. +- First focused CLI compile failed CS0050 because a public fixture method + returned internal McpProcess. Made that test helper internal; compiled cleanly. +- Initial publish put RID/single-file implicit tooling into the ordinary server + lock; solution locked restore correctly failed NU1004. Selected a separate + profile lock, republished, then ran one --force-evaluate solution restore to + regenerate the ordinary graph. Existing lock files match their original + contents. Both ordinary and profile locked restores now pass. +- An intermediate 13-case run passed12/failed1: the new extraction assertion + incorrectly expected loose coreclr.dll/clrjit.dll. Actual .NET 10 host tracing + showed internal hostpolicy/CoreCLR and only the two package-native DLLs. + Corrected the test to assert observed self-contained/internal-host facts, + exact extracted file count and pinned native hashes. No production workaround + or runtime-free claim was made. Final expanded14/full882 tests pass. + +STEP 9 FILES + src\GAJ3T.MusicGen.RiffGrooveBuilder.Server\Properties\PublishProfiles\win-x64.pubxml + src\GAJ3T.MusicGen.RiffGrooveBuilder.Server\packages.win-x64.lock.json + tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\Publishing\PublishedServerTests.cs + tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\Stdio\McpProcess.cs + tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\Stdio\McpGenerationTests.cs + docs\local-deployment.md + docs\format-compatibility.md + README.md + prompts\report_9.md + Plus ignored publication/example artifacts listed above. + +REMAINING LIMITS / REVIEW STOP +- Usable supported-slice local publication succeeds; full Step 9/full requested + product exit criteria do not. Runtime-free Windows x64 acceptance is pending. +- Documented AGLP/AME default Lead profiles only. ABJ, AGM, AGT, AMR and SD3 + mappings are unavailable. No new profile, role substitute or GM guess. +- AGP/SDP codecs/authorized fixtures and native semantics remain unresolved; + native writers are unavailable and Steps 6/7 are blocked, not completed. +- No licensed Cubase/Ample/SD3 import, VST hosting, audible articulation, + exact installed-version/settings acceptance or native reopen was performed. + Those are pending and cannot be inferred from RPC/MIDI read-back. +- No user/workspace/global MCP configuration was written. The copyable client + configuration is documentation, not a claim of an actual VS Code client run. +- No runtime-free machine, system runtime removal, VM/container, vendor install, + long-lived service, new feature/project, package upgrade, commit or delegation. +- READY for orchestrator review of the published supported slice only. + STOP; no subsequent step or full-scope acceptance is authorized by this report. + +=============================================================================== +PUBLICATION REFRESH — Correction iteration 4: additional evidenced capabilities +Date: 2026-10-20 +Entry baseline882; original Step9 report/inventory above preserved as history. + +REFRESHED SUPPORTED-SLICE PUBLICATION / AUTOMATED VALIDATION: PASS. +READY FOR ORCHESTRATOR REVIEW: YES. +Runtime-free Windows x64 and licensed-application acceptance: STILL PENDING. +Native Steps6/7: STILL BLOCKED; no codec, native success or extension substitution. + +CURRENT EMBEDDED CAPABILITIES +- Seven identities; five Documented profiles, zero application-Verified. +- Four Lead profiles: AGLP/AGM/AGT/AME, Sustain+PalmMute, zero-based channel0. +- One Bass profile: ABJ Sustain ONLY, velocities1-125/range35-76/channel1. + PM fails unsupported_articulation; accents126-127 are not Sustain. +- Nine articulation entries total; AMR and SD3 remain mapping_unavailable. + MIDI writer implemented; AGP/SDP writers unavailable/application-unverified. +- No automatic role defaults. Missing explicit Bass now fails no_default_profile; + unmapped Drums still fails mapping_unavailable. Unknown/wrong-role profiles, + disabled fallback and no-overwrite remain explicit failures. +- Exact new sources, shared ABJ/ABP scope and AGT named A6=105 anchor conclusion + are recorded in correction iteration4 of report4 and articulation-mappings.md. + AGT is admitted under documented-default scope, NOT a direct Sustain/PM demo + or installed-release claim. No Tab Player/note105 control is emitted. + +EXISTING PUBLISH CONFIGURATION / LOCKS PRESERVED +- Used accepted win-x64.pubxml unchanged: Release, win-x64, self-contained, + single-file, untrimmed, non-AOT, native self-extraction enabled. +- Existing dedicated packages.win-x64.lock.json honored unchanged: + SHA256 AFEB86CEB2EF6A671126A04D8187EF824213E55C2348EA45C7849255332F2193. +- Ordinary solution and publication-specific locked restores both pass. + No project/package/runtime version, settings or publish feature was changed. + SDK10.0.400; DryWetMIDI[8.0.3]; included runtime remains10.0.11. + +REFRESHED PERSISTENT PAYLOAD +Directory: + D:\_Repos\Code\GAJ3T\MCPs\MusicGen\GAJ3T.MusicGen.Riff-Groove-Builder.Net\artifacts\publish\win-x64 +Exactly five files, total74,902,828 bytes: + GAJ3T.MusicGen.RiffGrooveBuilder.Server.exe 74,734,064 + SHA256 921AADE7FB75222E8A7E5E81151F3DC73747CD8036EE751555A613A5DBDD308E + GAJ3T.MusicGen.RiffGrooveBuilder.Core.pdb 37,636 + SHA256 D27A30CDEC00C8E0574648812E4B67A64990196CE8B4FDBD55800F4933612A3C + GAJ3T.MusicGen.RiffGrooveBuilder.Generation.pdb 20,208 + SHA256 FA5AA29C946BD0694E0D4EFCF3B85630AB072EF85123E2F88C2A57D1B10D8B33 + GAJ3T.MusicGen.RiffGrooveBuilder.Server.pdb 20,320 + SHA256 6545B0AA2EDB72E7226A23BA757C527441AC56897A12281B6504D286259984A2 + Melanchall_DryWetMidi_Native64.dylib 90,600 + SHA256 AA08C542E77B045FA1E00D4FEAB21080CEB415C4B6C343B0DBC5704D1FB02F92 +No unrelated artifacts were removed. Publication remains locally retained and +ignored. Metadata from this executable reflects five profiles, not the old two. + +ACTUAL REFRESHED PUBLISHED-PROCESS / MIDI FACTS +- 28 focused PublishedServerTests pass using isolated copies of this actual + refreshed payload and unrelated system-directory cwd. Production still exposes + exactly list_instrument_profiles and generate_project; five Documented profile + IDs and two unmapped identities are asserted through the real stdio process. +- Each of all four explicit Lead profiles produces readable MIDI. The executable- + only/native-extraction/host-trace, protocol purity, ping, cancellation/EOF, + invalid input and collision/no-overwrite regressions remain passing. + No runtime-free host was available; these are SDK-machine packaging checks. +- Eight new published Lead+Bass cases: each AME/AGLP/AGM/AGT with explicit ABJ, + formats=["mid"]/fallback=false and formats=["agp","mid"]/fallback=true. + All produce exactly ONE real435-byte MIDI retaining both roles: + SHA256 F31C7C2236637AF9412738418AF61E7D613D51C89A8FFB43B379012C7798384A. + Read-back with pinned DryWetMIDI verifies: + Type1/960PPQ; Conductor,Lead,Bass; tick-zero120BPM/4-4. + Lead channel0:32 pitch64/velocity96 notes,120+480*i,duration480. + Bass channel1:4 pitch40/velocity96 notes,120+3840*i,duration3840. + PM26/100 and Sustain24/100 each on0/off30; shared lead-in120. + 76 channel events; exact note/control pairing; three EOTs at15480. + Native fallback retains two native-unavailable target reasons, two written + MIDI role outcomes and two Documented disclosures in one artifact. No native + placeholder, partial role drop or duplicate MIDI is generated. +- Published ABJ PM, missing Bass selection, unmapped Drums and unknown/wrong-role + profile tests fail explicitly before output. Existing collision test preserves + its MIDI and unrelated owner file. +- Test-owned generated MIDI/payload copies are read before cleanup, then removed. + Final inspection: no owned published-check directories/processes left. + +ACCEPTED AME EXAMPLE — PRESERVED, NOT REGENERATED OR OVERWRITTEN + artifacts\examples\ame-lead-example.mid,371 bytes. + SHA256 6F5791FB5C3A7A17E54AAF6436963E4D5723FB948057585060C09BF9B2AFCA3E. +Before/after hashes agree; new explicit preservation/read-back test passes. +Original semantics remain Type1/960PPQ, Conductor/Lead,120BPM/4-4, +32 pitch64/velocity96/channel0 notes, PM26/100 on0/off30, +lead-in120/end15480. No additional retained example was requested or created; +the435-byte Lead+Bass files above are transient test evidence. + +EXACT VALIDATION +1. dotnet build .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-restore --verbosity quiet + PASS,0 warnings/errors, before publication and after ordinary locked restore. +2. dotnet restore .\src\GAJ3T.MusicGen.RiffGrooveBuilder.Server\GAJ3T.MusicGen.RiffGrooveBuilder.Server.csproj -p:PublishProfile=win-x64 --locked-mode --verbosity minimal + PASS. +3. dotnet publish .\src\GAJ3T.MusicGen.RiffGrooveBuilder.Server\GAJ3T.MusicGen.RiffGrooveBuilder.Server.csproj -p:PublishProfile=win-x64 --no-restore -o .\artifacts\publish\win-x64 --verbosity minimal + PASS, actual retained payload above. +4. dotnet restore .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx --locked-mode --verbosity minimal + PASS. Both locked restores repeated quietly after full validation: PASS. +5. Combined focused profile/catalog/MIDI/service/MCP/publication selection: + PASS,414 unit+107 integration=521; full filter recorded in report4. +6. dotnet test .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-build --verbosity quiet + PASS,794 unit+142 integration=936;0 failed/skipped. Baseline882,net+54. +7. dotnet test .\tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests.csproj -c Release --no-build --filter FullyQualifiedName~PublishedServerTests --verbosity quiet + PASS,28;0 failed/skipped against refreshed payload. +8. Same project/options, filter FullyQualifiedName~PublishedLeadBassUsesRefreshedProfilesAndOneReadableArtifact --logger 'console;verbosity=detailed': + PASS,8; printed all actual435-byte hashes/read-back facts above. +9. git --no-pager diff --check: PASS before report; both append fences/history + checked afterward. No compiled/test/restore failure remains. + +FILES / SCOPE / STOP +- Refreshed ignored publish payload; expanded PublishedServerTests and reused + shared MCP read-back helpers. Updated existing deployment/compatibility docs + with current capabilities, executable bytes/hash and435-byte evidence. +- Earlier report history remains inside the same single plain code fence. + No prompt/plan edit, settings edit, new package/project, copied vendor asset, + native codec, runtime-free simulation, commit or delegation. +- Documented source-backed MIDI/publication readiness passes only under explicit + defaults, routing and engineering timing assumptions. Installed versions/ + settings, licensed Cubase/Ample/SD3/audible checks, native outputs, AMR/SD3 + maps and ABJ PM are not declared verified or complete. +- STOP for orchestrator review; no later step is started. +``` diff --git a/prompts/step_1.md b/prompts/step_1.md new file mode 100644 index 0000000..d603bac --- /dev/null +++ b/prompts/step_1.md @@ -0,0 +1,180 @@ +# Step 1: Bootstrap the .NET 10 solution and compatibility inventory + +## Objective and stop boundary + +Implement Step 1 of [the approved plan](plan.md): a reproducible .NET 10 +solution with the production/test project structure, a quiet console entry +point, pinned dependencies, meaningful scaffold checks, and an honest native +compatibility evidence inventory. + +Read the approved plan and inspect the current worktree before editing. Preserve +others' work. Work only on this step. Do not implement the MCP protocol, music +parser, articulation profiles, MIDI writers, native writers, or publication +workflow yet. Do not create any later step prompt. Do not make a git commit. + +## Required files + +Create or update these repository-relative files: + +```text +GAJ3T.MusicGen.RiffGrooveBuilder.slnx +global.json +Directory.Build.props +Directory.Packages.props +NuGet.config +.gitignore +README.md +src\GAJ3T.MusicGen.RiffGrooveBuilder.Core\ + GAJ3T.MusicGen.RiffGrooveBuilder.Core.csproj +src\GAJ3T.MusicGen.RiffGrooveBuilder.Generation\ + GAJ3T.MusicGen.RiffGrooveBuilder.Generation.csproj +src\GAJ3T.MusicGen.RiffGrooveBuilder.Server\ + GAJ3T.MusicGen.RiffGrooveBuilder.Server.csproj + Program.cs +tests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\ + GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests.csproj + ScaffoldTests.cs +tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\ + GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests.csproj + Stdio\ProcessStartupTests.cs +docs\format-compatibility.md +prompts\report_1.md +``` + +Create dependency lock files through NuGet restore, not manually. Remove unused +template `Class1.cs`, `UnitTest1.cs`, and "Hello, World!" code. Do not create empty +placeholder source files or all future module directories solely to mimic a tree. + +## Implementation requirements + +### Toolchain and package management + +- Target `net10.0` in all five projects. First inspect the installed SDK. + Pin an available .NET 10 SDK in `global.json` with `rollForward: latestPatch`. + If no .NET 10 SDK is available, report the actual failure before considering + installation; do not change machine-wide tools without authorization. +- Use `Microsoft.NET.Sdk`; only Server has `OutputType=Exe`. Enable nullable, + implicit usings, and warnings-as-errors in common build properties. +- Use central package management. Pin `Melanchall.DryWetMidi` exactly to 8.0.3 + and reference it from Generation. No other MIDI library or package version. +- Select stable, available .NET 10-compatible versions of xUnit, + `xunit.runner.visualstudio`, and `Microsoft.NET.Test.Sdk`. Verify versions + through the package manager/official metadata rather than inventing them. + Keep test-only packages private where applicable. No coverage package or new + tooling is needed. +- Enable NuGet package lock files. Use the official NuGet source only in the + repository configuration; do not put credentials in source control. +- Use `dotnet` project/solution scaffolding and package manager commands where + appropriate. Use `apply_patch` for manual source/document edits. +- Do not restore/install anything until manifests have been created/changed + or a validation command demonstrates a missing dependency. + +### Project references and console startup + +- Core has no project/package dependency. +- Generation references Core and the pinned DryWetMIDI package. +- Server references Core and Generation. +- UnitTests references Core and Generation. IntegrationTests references Server + as needed to reliably build and locate the real console binary. +- The server must not print a greeting, startup banner, or other stdout text. + For this step, it may simply read/discard stdin until EOF and then exit + successfully; document that this is not yet an MCP server. +- Do not emit fake JSON-RPC success responses or advertise unimplemented tools. +- Include no HTTP listeners, web SDKs, containers, playback/device APIs, external + LLM calls, or audio functionality. + +### Compatibility inventory + +Write `docs\format-compatibility.md` as an evidence table covering: + +- Exact Eclips, Ray, SD3, and Cubase product/version details: unknown unless + actual evidence exists. +- AGP lead and bass container/schema, supported import paths and extensions. +- SDP container/schema and whether SD3 actually supports the requested extension. +- Authorized native fixture availability and redistribution/template permission. +- Absolute MIDI note/keyswitch/CC values, velocity layers, ranges, channels, + state/reset behavior, timing, and SD3 mapping/library settings. +- Actual plugin/Cubase import acceptance: not performed unless genuinely tested. + +For each row record status, evidence/source (or "not supplied"), required +evidence, and which future gate it blocks. Distinguish verified planning facts +(MCP framing, DryWetMIDI package availability, .NET deployment capability) +from unknown proprietary format facts. + +No fixture or product mapping is currently supplied. Do not scan arbitrary +personal directories, install vendor products, reuse copyrighted sample +content, fabricate a schema, or present synthetic profiles as real mappings. +Missing native evidence does not prevent Step 1 acceptance, but it must remain +an explicit blocker for the relevant later steps. + +### Documentation and ignore rules + +- README: scope, current scaffold-only status, prerequisites, restore/build/test + commands, project layout, and the native evidence requirement. Do not claim + generation or MCP functionality exists yet. +- `.gitignore`: standard .NET build/test/publish artifacts and IDE state. + Do not ignore source, lock files, docs, or worker prompt/report deliverables. +- Do not alter `prompts\plan.md` or other orchestrator prompts. + +## Required tests + +### Unit + +Add meaningful scaffold assertions that verify the compiled target framework is +.NET 10 and that Generation can resolve the pinned DryWetMIDI dependency. +Use assembly metadata or a small package-level smoke assertion; do not create +production MIDI-generation logic just to make a scaffold test pass. +Avoid tautologies such as `Assert.True(true)`. + +### Integration + +Launch the actual Server binary in a subprocess, not a mock: + +1. Use redirected stdin/stdout/stderr and a bounded timeout. +2. Close stdin to signal EOF. +3. Assert exit code zero and empty stdout (and no unexpected stderr). +4. Verify the same behavior from an isolated working directory unrelated to + the repository. +5. Always terminate/dispose only the process created by the test on failure; + never kill by process name. Avoid deadlock by draining both output streams. +6. Locate binaries without hard-coded absolute developer paths and without + assuming the test process starts at the repository root. + +## Validation + +Run and report these commands (use the test tool for the relevant xUnit tests +when available, with the CLI commands as the reproducible documented form): + +```powershell +dotnet restore .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx +dotnet build .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-restore +dotnet test .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-build +dotnet restore .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx --locked-mode +``` + +All tests must be discovered and pass; an empty test run is not a pass. +Fix issues introduced by this step, but do not expand into future features. +If an environmental/toolchain blocker cannot be resolved safely, record it +explicitly with commands/output and mark readiness false. + +## Acceptance criteria + +- All required projects/files exist with the specified dependency direction. +- Restore, Release build, nonempty test execution, and locked restore pass. +- The real console process exits on EOF and never pollutes stdout. +- Dependencies are pinned, especially DryWetMIDI 8.0.3. +- README matches actual behavior and the compatibility inventory does not + assert unknown proprietary format or product mapping details. +- No unrelated changes, secrets, generated binaries, or later-step features. + +## Mandatory worker report + +When complete, write your end-of-step report to ./prompts/report_1.md including: what was implemented, test results (pass/fail with details), any issues encountered, and whether you're ready for the next step + +The entire report must be inside exactly one plain triple-backtick fence, with +no content before or after it. Include changed files, selected SDK/package +versions, exact validation commands and exit codes, test counts, any skipped +checks and reasons, unresolved evidence gates, and an explicit Step 1 readiness +decision. Distinguish future native blockers from a failed scaffold. + +Stop after writing the report. Do not proceed to Step 2. diff --git a/prompts/step_2.md b/prompts/step_2.md new file mode 100644 index 0000000..126cffa --- /dev/null +++ b/prompts/step_2.md @@ -0,0 +1,172 @@ +# Step 2: Implement stdio JSON-RPC and the MCP lifecycle + +## Objective and prerequisites + +Step 1 has been reviewed and accepted: Release build and all eight scaffold +tests pass. Read [the approved plan](plan.md), [the Step 1 report](report_1.md), +and existing source/tests before editing. + +Implement a protocol-correct .NET 10 stdio MCP server, targeting version +`2025-11-25`. This step is transport/lifecycle/registry infrastructure only. +Stop before composition, real instrument profiles, generation tools or writers. +Do not create later prompts, modify orchestrator prompts/plan, commit, or delegate. + +## Files to create or modify + +```text +src\GAJ3T.MusicGen.RiffGrooveBuilder.Server\ + Program.cs + Protocol\StdioTransport.cs + Protocol\JsonRpcDispatcher.cs + Protocol\McpSession.cs + Protocol\JsonRpcError.cs + Tools\McpToolRegistry.cs + Tools\McpToolDefinition.cs +tests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\ + GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests.csproj + Protocol\StdioTransportTests.cs + Protocol\JsonRpcDispatcherTests.cs + Protocol\McpSessionTests.cs +tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\ + Stdio\ProcessStartupTests.cs + Stdio\McpProtocolTests.cs +README.md +docs\mcp-protocol.md +prompts\report_2.md +``` + +Small directly necessary protocol/test helper files are allowed. Prefer simple +typed contracts over a generic framework. Add a Server project reference to +UnitTests if needed. No new package is required; use System.Text.Json and BCL. +Refresh generated lock files only if the project reference change requires it. + +## Protocol requirements + +### Transport + +- UTF-8, newline-delimited JSON-RPC, never `Content-Length` framing. + Serialized JSON strings may contain escaped newlines, not literal message + framing newlines. Accept LF and CRLF. Flush each completed output message. +- Stdout contains only complete protocol messages. Serialize writes so + overlapping request work cannot interleave JSON. Diagnostics use stderr. +- Bound incoming messages while reading, not only after allocating an + unbounded line. Use a documented internal limit (1 MiB is acceptable). + Reject an oversized frame with an explicit bounded diagnostic/protocol error, + resynchronize at its newline, and test continued operation. +- Reject invalid UTF-8 without silently substituting characters. Handle a final + nonempty frame at EOF explicitly and test the documented behavior. +- EOF and Ctrl+C shut down cleanly, cancelling outstanding work and disposing + only owned resources. An empty stdin stream produces no output. + +### JSON-RPC + +- Require `jsonrpc: "2.0"` and a string method for inbound requests/notifications. + Validate params shape against the method. Preserve supported string/integer + request IDs in responses; do not coerce strings to numbers. +- Reject malformed JSON with -32700, invalid envelopes/batch arrays with + -32600, unknown request methods with -32601, invalid method/tool parameters + with -32602, and unexpected internal failures with -32603. +- Error response `id` is null when no valid request ID can be identified. + Never answer a valid notification, including unknown notifications. +- Do not process JSON-RPC batches as a supported MCP feature. +- An exception boundary may report unexpected per-request failures explicitly, + log details to stderr and return -32603. Do not suppress exceptions into + success results or hide actual I/O failures. + +### Lifecycle + +- Support `initialize`, `notifications/initialized`, `ping`, `tools/list`, + `tools/call`, and `notifications/cancelled`. +- Validate initialization fields per the MCP specification. Return serverInfo, + supported protocolVersion and only implemented capabilities. +- Negotiate version: echo `2025-11-25` when requested; otherwise return + `2025-11-25` as the server's supported alternative. Do not claim support for + other protocol versions. +- Enforce initialization state and reject inappropriate requests with explicit + errors. Permit ping per lifecycle rules. Reject repeated initialization. +- Use stdin closure for shutdown, not an invented `shutdown` method. +- Ignore/log unsupported notifications without replying. +- Track outstanding request IDs and propagate valid cancellation notifications + to the matching active request; cancellation is not cancellation of the whole + server. Keep reading notifications while a handler is awaiting work. +- Keep lifecycle changes/registry access safe when work overlaps. Distinguish + requests with different ID types. Do not let duplicate active IDs cancel or + replace unrelated work. + +### Tool registry + +- Implement registration/lookup and schema serialization for tool definitions. +- Production registry is initially empty: `tools/list` returns `tools: []`. + Do not advertise placeholder profile/generation tools. +- An unknown tool is a protocol/tool-selection error, not a fake successful call. +- Provide a bounded typed handler boundary supporting input validation, + structuredContent plus text content, expected tool errors (`isError: true`), + and cancellation. Synthetic test-only tools can exercise these paths. +- Do not implement MCP resources, prompts, sampling, logging RPCs, task APIs, + HTTP, composition, or real generation in this step. + +Use the primary MCP sources referenced in the plan to resolve protocol details. +Document supported/unsupported methods and capability/version behavior. + +## Required tests + +### Unit tests + +Cover: + +1. LF/CRLF framing, escaped newline content, UTF-8/non-ASCII content, invalid UTF-8, + empty EOF and the documented non-newline final-frame behavior. +2. Message size at/over the limit, resynchronization, complete serialized output. +3. Valid string/integer IDs, malformed JSON, invalid envelopes/IDs, batch + rejection, unknown methods and invalid params. +4. Notifications produce no response, even unknown ones. +5. Initialization success, unsupported-version negotiation, premature requests, + initialized transition, repeated initialization and ping. +6. Empty production registry; test-only registered tool discovery/calls and + schema/content agreement; unknown tool and handler validation failures. +7. A cancellable synthetic handler cancelled while awaiting work, unrelated + request survival, and overlapping response serialization. + +Retain the meaningful framework/dependency scaffold unit tests. + +### Real-process integration tests + +- Update the prior input-discard startup test: only empty EOF remains silently + successful. Non-JSON input must now yield a parse error, not be discarded. +- Launch the real Server apphost, negotiate initialization, send + `notifications/initialized`, list empty tools, ping, and close stdin. +- Assert response IDs, MCP version/capabilities, per-line valid JSON, no + notification reply, empty or diagnostic-only stderr, and exit code zero. +- Exercise malformed input followed by a valid request on the same connection, + unknown method/tool, invalid arguments, and an unrelated working directory. +- Include timeout-bounded cleanup and concurrent draining of stdout/stderr. + Never kill by process name or leave a helper running. + +## Validation and acceptance + +Run targeted protocol tests during development, then: + +```powershell +dotnet build .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-restore +dotnet test .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-build +dotnet restore .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx --locked-mode +``` + +If changed manifests make assets stale, restore after the manifest change. +The installed SDK is at `C:\Program Files\dotnet\dotnet.exe`; use a process-local +PATH adjustment if needed. The editor test tool failed discovery in Step 1; +CLI xUnit execution is the verified fallback, not a skipped test. + +Exit criteria: actual stdio MCP lifecycle works, all tests pass including +retained scaffold coverage, no non-protocol stdout, no unimplemented tools +advertised, documentation matches behavior, and no scope expansion. + +## Mandatory worker report + +When complete, write your end-of-step report to ./prompts/report_2.md including: what was implemented, test results (pass/fail with details), any issues encountered, and whether you're ready for the next step + +Put the entire report inside exactly one plain triple-backtick fence, with no +outside content. Include changed files, exact commands/exit codes, test counts, +protocol limits and decisions, any skipped checks, issues/blockers, and explicit +Step 2 readiness. Native compatibility remains unverified and outside this step. +Stop after writing the report. diff --git a/prompts/step_3.md b/prompts/step_3.md new file mode 100644 index 0000000..5db1595 --- /dev/null +++ b/prompts/step_3.md @@ -0,0 +1,211 @@ +# Step 3: Implement the composition model and deterministic text planner + +## Objective and prerequisites + +Step 2 has been reviewed and accepted: the .NET 10 stdio MCP lifecycle works, +the production tool registry is empty, and all 130 tests pass. + +Read [the approved plan](plan.md), [the Step 2 report](report_2.md), and existing +code before editing. Implement only the instrument-neutral composition model, +validation, documented bounded English grammar, and deterministic basic pattern +planning. This step does not require proprietary mappings. + +Do not implement production profiles, keyswitch/CC event generation, MIDI/native +writers, public generation tools, publication, audio, network calls or an LLM. +Do not alter orchestrator prompts/plan, create later prompts, commit or delegate. + +## Files to create or modify + +```text +src\GAJ3T.MusicGen.RiffGrooveBuilder.Core\ + Composition\BeatFraction.cs + Composition\Composition.cs + Composition\TrackPlan.cs + Composition\MusicalNote.cs + Composition\DrumHit.cs + Composition\CompositionDiagnostic.cs + Composition\CompositionPlanningResult.cs + Composition\CompositionValidator.cs + Composition\DescriptionParser.cs + Composition\CompositionPlanner.cs +tests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\ + Composition\BeatFractionTests.cs + Composition\CompositionValidatorTests.cs + Composition\DescriptionParserTests.cs + Composition\CompositionPlannerTests.cs +tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\ + GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests.csproj + Composition\CompositionPipelineTests.cs +docs\text-description-contract.md +README.md +prompts\report_3.md +``` + +Small directly related typed enums/value objects/helpers may have their own +files if clearer. Avoid public interfaces or abstractions with no actual use. +IntegrationTests may add a Core project reference for in-process full-pipeline +tests; refresh generated locks when required. No new package is needed. + +## Design and implementation details + +### Model and timing + +- Core remains independent of DryWetMIDI and vendor schemas. +- Model tempo, time signature, key/root/mode, bar count, selected role tracks + and notes/hits. Use typed roles (`lead`, `bass`, `drums`), articulations and + drum voices, not unchecked magic strings. +- Pitched notes hold absolute MIDI pitch and musical velocity/duration. + Drum hits hold logical voices (kick, snare, closed hi-hat), not guessed SD3 + note numbers. Articulations remain intentions, not vendor switch values. +- Beat positions/durations are exact fractions of a quarter note. Implement + normalized immutable rational arithmetic with checked integer operations, + comparison, and exact conversion to 960 PPQ ticks. Reject nonpositive + denominators, negative starts and nonpositive durations. +- A bar is `numerator * 4 / denominator` quarter notes. Validate time signature + fields and exact tick representability. Human "beat 1" in a meter refers to + the denominator-note beat; document and test this explicitly. +- Keep track planning independent of production profile verification. Planned + pitches/velocities are musical choices, not evidence of plugin playability. + Vendor ranges, profiles, channels and switch-state validation belong to Step 4. +- Validate MIDI numeric ranges, positive finite/representable SMF tempo, + bar bounds, selected roles, note/hit duration and complete musical extent. + Validate arithmetic/resource bounds before allocating large note lists. +- Diagnostics identify a stable code, field/phrase when applicable, and an + actionable message. Invalid input cannot return a successful empty composition. + Failure results have no usable partial composition. + +### Document the grammar before implementing it + +The initial vocabulary is deliberately bounded; do not claim arbitrary English +understanding. Write the text contract first, then make parser/tests match it. + +Required supported concepts: + +- Bar count, integer BPM, meter, and key/root (major or minor). +- Role clauses for lead/guitar, bass, and drums. +- Repeated root-note quarter/eighth/sixteenth-note lead or bass patterns and + sustained root notes (one full-bar note per bar). +- Canonical sustain and palm-mute articulation intentions, binding modifiers + to the relevant role, not every track. Actual support remains profile-gated. +- Drum placement on explicit numbered beats and closed hi-hat subdivisions. +- Representative documented paraphrases such as `120 BPM` / `120 bpm`, + `4 bars` / `four bars`, `palm-muted` / `palm mute`, and `lead guitar` / `lead`. + Support ordinary whitespace/case/punctuation variation without deleting or + ignoring meaningful unknown text. + +The exact acceptance description from the plan must work: + +> Generate 4 bars at 120 BPM in E minor, 4/4: palm-muted eighth-note lead guitar, +> sustained root-note bass, kick on beats 1 and 3, snare on beats 2 and 4, and +> closed hi-hat eighth notes. + +For that example, with zero lead-in at this planning stage: + +- Four bars of 4/4 span exactly 16 quarter notes / 15,360 ticks. +- Lead: 32 eighth notes; starts every 480 ticks; duration 480 ticks; root E + and palm-mute intention. Bass: four sustained notes, each 3,840 ticks. +- Kick: eight hits at beats 1/3; snare: eight at beats 2/4; closed hi-hat: + 32 eighth-note hits. All start positions repeat on exact bar boundaries. +- Do not infer drum MIDI pitches or keyswitch values. + +Document deterministic defaults, used only when a setting is omitted: +120 BPM, 4 bars, 4/4, E minor; lead root in MIDI octave 4 (C4=60), bass root in +octave 2 (C2=36), velocity 96, sustain articulation unless explicitly changed. +Thus E is MIDI 64 for lead and 40 for bass; these are composition defaults, +not product mappings. Permit root names/accidentals within the documented +key grammar and test enharmonic normalization. + +If no role is mentioned, default to all three. When a role/part is explicitly +mentioned, generate only explicitly selected roles (drum part clauses select +drums). For omitted role patterns, default to root eighth-note lead, +full-bar sustained bass, and the documented 4/4 kick-1/3, snare-2/4, eighth-note +closed-hi-hat pattern. + +Do not silently apply a 4/4 drum default to another meter. For non-4/4 drum +requests, require explicit valid drum part placement/subdivision if no +documented meter-aware default exists. Any omitted defaulted parts/settings +must be visible in `DefaultsApplied`; explicitly selecting a drum subset must +not silently add omitted parts. + +Record every applied default with its value. Reject contradictions, malformed +numbers, duplicate conflicting settings, invalid beat positions, unsupported +articulations/patterns and unconsumed meaningful instructions. Genre labels, +chord progressions, tuning instructions, arbitrary melodies, dynamics outside +the supported grammar, and unknown text are not excuses for guessed behavior. + +For resource safety, choose and document a single internal generated-event +limit, estimate counts using checked arithmetic before expanding patterns, +and return a specific diagnostic when exceeded. Do not add public resource +configuration or silently truncate. Keep this limit generous enough for +ordinary multi-bar descriptions and test its precise boundary. + +### Planning behavior + +- Parser output and the final model must preserve explicitly supplied settings. + Explicit modifiers apply only to their intended clause/role. +- Keep parsing/planning failures explicit. Catch only expected parsing, + representability and checked-arithmetic errors at an appropriate boundary; + do not convert arbitrary exceptions into apparently successful defaults. +- Identical text and options produce structurally identical compositions. +- No randomization, humanization, audio analysis or external semantic service. +- Preserve currently working MCP behavior. The production tool registry stays + empty until Step 8; do not wire a premature generation tool. + +## Required tests + +### Unit tests + +1. Rational normalization/arithmetic/comparison, exact tick conversion, zero/ + invalid denominators, negative positions, fractional unrepresentability and + checked overflow. +2. Full acceptance example with exact values, counts, starts, durations, + articulation intentions, defaults and musical extent. +3. Paraphrases, case/whitespace/punctuation, key accidentals/enharmonics, + explicit role selection and omitted-setting defaults. +4. Pattern subdivisions and sustained notes without drift across many bars. +5. Time-signature quarter-note math and denominator-beat placement in at least + one non-4/4 meter; invalid/nonrepresentable meters and beats rejected. +6. Contradictory settings/clauses, malformed numeric text, unsupported/leftover + meaningful words, unknown articulations and invalid requests. +7. Numeric pitch/velocity/duration bounds and tempo/SMF representability. +8. Exact resource limit and just-over-limit rejection before expensive expansion. +9. Deterministic repeated calls and no shared mutable collection state between + independent composition results. + +### Integration tests + +Call the real Core parser -> planner -> validator pipeline in-process using the +documented full description. Inspect all three tracks and exact musical timing. +Also cover selected-role output, a documented non-4/4 description, and failures +that yield actionable diagnostics with no partial successful composition. +Retain the real-process MCP/scaffold integration tests; do not mistake the +in-process composition check for the final public MCP generation integration. + +## Validation and exit criteria + +Use targeted composition tests during development, then: + +```powershell +dotnet build .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-restore +dotnet test .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-build +dotnet restore .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx --locked-mode +``` + +Restore after any project-manifest change before validating. Installed SDK: +`C:\Program Files\dotnet\dotnet.exe`; editor test discovery was unavailable, +so CLI execution is the known fallback. + +Exit: supported descriptions deterministically produce validated multi-role +compositions with exact timing, rejected text is not silently ignored, tests +all pass, docs match behavior, and production mappings/writers/tools remain +unimplemented rather than fabricated. + +## Mandatory worker report + +When complete, write your end-of-step report to ./prompts/report_3.md including: what was implemented, test results (pass/fail with details), any issues encountered, and whether you're ready for the next step + +Entire report: exactly one plain triple-backtick fence, with no outside prose. +Include changed files, grammar/default decisions and limits, exact commands and +exit codes, test counts, unrun checks and reasons, issues and readiness. +Explicitly note that accepting Step 3 does not satisfy Step 4's real production +mapping evidence gate. Stop after the report. diff --git a/prompts/step_4.md b/prompts/step_4.md new file mode 100644 index 0000000..388058e --- /dev/null +++ b/prompts/step_4.md @@ -0,0 +1,187 @@ +# Step 4: Articulation infrastructure and verified-profile evidence gate + +## Objective and current gate + +Step 3 has been reviewed and accepted. All 318 tests pass; supported text yields +instrument-neutral compositions with exact timing and articulation intentions. + +Read [the approved plan](plan.md), [the Step 3 report](report_3.md), the current +Core composition model, and the compatibility inventory before editing. + +Implement the generic profile validation and articulation event-planning +infrastructure with synthetic test-only profiles. Production Eclips, Ray and +SD3 mapping evidence is currently absent. Implement production profiles only +if actual authorized evidence has appeared in the repository; never invent it. +The infrastructure is actionable now, but synthetic passing tests CANNOT +satisfy Step 4's production exit gate. If evidence remains absent, write a +truthful BLOCKED report with readiness false and stop. Do not proceed to Step 5. + +No later prompts, orchestration-document edits, commits or delegation. + +## Files to create or modify + +```text +src\GAJ3T.MusicGen.RiffGrooveBuilder.Core\ + Articulations\InstrumentProfile.cs + Articulations\ArticulationRule.cs + Articulations\InstrumentProfileValidator.cs + Articulations\ArticulationPlanner.cs + Articulations\ArticulationPlanningResult.cs + Articulations\PlannedMidiEvent.cs +src\GAJ3T.MusicGen.RiffGrooveBuilder.Generation\ + Profiles\InstrumentProfileCatalog.cs + Profiles\instrument-profiles.json + GAJ3T.MusicGen.RiffGrooveBuilder.Generation.csproj +tests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\ + Articulations\InstrumentProfileValidatorTests.cs + Articulations\ArticulationPlannerTests.cs + Articulations\InstrumentProfileCatalogTests.cs +tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\ + GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests.csproj + Articulations\ArticulationPipelineTests.cs +docs\articulation-mappings.md +docs\format-compatibility.md +README.md +prompts\report_4.md +``` + +Small directly necessary typed value objects/test helpers may have separate +files. Add a Generation test reference only if needed. No new packages. +Use BCL JSON serialization for profile data, not a second MIDI library. + +## Implementation requirements + +### Profiles and catalog + +- Reuse existing typed roles/articulation/drum voice enums and exact timing. + Keep Core independent of DryWetMIDI and vendor file serialization. +- A profile identifies role, exact product/version, mapping version, evidence + provenance/verification status, pitch range, channel, initial state and + supported articulation/control rules. Store absolute MIDI numbers; octave + label conventions must not determine switch values. +- Express only the required mechanisms: keyswitch notes with velocity and + advance/duration semantics, velocity-layer constraints or verified + articulation-dependent output, CC number/value actions, and verified + combinations. State/reset semantics must be explicit rather than implicit + defaults guessed from product names. +- Support drum voice-to-note mapping and verified CC state as data. Do not + assume GM or choose real SD3 pitches. +- Validate IDs/roles/versions/evidence, all MIDI ranges, layer boundaries, + nonnegative advances, positive switch durations, duplicate/conflicting rules, + channel/state constraints and switches colliding with playable notes. +- Unsupported articulations or unmapped drum voices are explicit diagnostics. + Invalid/unverified production profiles must not be selectable as usable. +- Embed the profile catalog in Generation and load it independently of cwd. + With no real evidence, its content is an honest empty list, not fake Eclips, + Ray or SD3 entries. Unknown profile/default selection returns actionable + diagnostics; no synthetic production fallback. +- The embedded catalog is the only production data source for now. No + filesystem plugin search, runtime profile editor, user plugin system, vendor + installation scanning, network access or arbitrary configuration discovery. +- Synthetic profiles live only in tests, have obviously synthetic identities, + and are not embedded, returned, or registered as production targets. +- Malformed catalog resources fail explicitly; do not catch them and return + an empty "successful" catalog. The intentionally empty resource is distinct. + +### Event planning + +- Accept a validated composition and explicit matching profiles. Preserve the + source composition; produce a new immutable typed event plan and diagnostics. +- These are MIDI event intentions (pitch/velocity/channel/tick/priority), not + handwritten MIDI encoding or DryWetMIDI event objects. Actual MIDI construction + remains Step 5 and must use DryWetMIDI 8.0.3. +- Include musical note-on/off intentions, mapped drum note-on/off intentions, + keyswitch note-on/off, required CC/state changes and releases/resets. +- Cover keyswitch-only, velocity-only, CC-only and combined rules. Document the + smallest clear velocity-layer semantics and verify boundaries; reject + unsupported/conflicting requested velocities rather than silently clamping. + Any profile-specified articulation transformation must be explicit and + distinguishable from an accidental mutation of musical dynamics. +- Respect configured latched versus momentary behavior. Suppress redundant + latched state changes, not required per-note momentary switches. Never leave + keyswitch notes stuck or issue reset events not specified by the profile. +- Compute the largest required switch advance across selected tracks and use + one shared nonnegative lead-in offset for the entire arrangement. All musical + starts/ends shift consistently; report `LeadInTicks`. Do not clamp controls + to tick zero or shift only one role. +- Preserve deterministic same-tick ordering: previous note-offs/releases, + state-changing controls/keyswitches, then musical note-ons. Ensure transitions + have the intended state when a prior note-off and new note-on share a tick. +- Track-global keyswitch/CC state cannot express conflicting simultaneous + articulations. Reject conflicts unless the actual profile provides a verified + representable route; no channel-per-note workaround or guessed behavior. +- Preflight channel collisions between independently controlled tracks and + profile musical/switch collisions. Validate arithmetic/timing and event + ranges, including lead-in and final releases. +- Return a complete valid plan or explicit failure with no usable partial plan. + Report exact total musical extent plus any final required release event. + No broad catch/silent fallback or success-shaped invalid-input handling. + +### Documentation + +- Explain mapping fields, synthetic-only examples, velocity semantics, state + transition/ordering, channels, shared lead-in, unsupported behavior and evidence. +- Update compatibility inventory with generic infrastructure completed but real + product/version/mapping/native acceptance evidence still missing. +- README must not claim playable Eclips/Ray/SD3 mappings, MIDI files or native + generation exist. The production MCP registry remains empty. + +## Required tests + +### Unit + +1. Profile validation: versions/provenance/status, roles, pitch/channel/velocity/ + CC ranges, layer boundaries, invalid advances/durations, duplicates and + musical/control collisions. +2. Each mechanism separately and combined, using clearly synthetic profiles. +3. Exact resulting note/CC numbers, values, channels, starts, ends and ordering; + note-off pairing, unchanged source data, deterministic immutable results. +4. Latching, repeated same articulation, momentary retrigger/release, transition + to sustain, CC initial/reset state and explicit velocity-layer behavior. +5. Unsupported articulation, unverified/missing profile, unmapped drum voice, + conflicting simultaneous articulation/state and channel collisions. +6. Three-track shared lead-in with different advances, tick-zero boundaries, + same-tick transition ordering, final releases and checked overflow. +7. Embedded catalog loads from unrelated cwd; honest empty production state; + unknown profile resolution errors; malformed data never becomes silent empty. + +### Integration + +Run description -> composition -> profile validation -> event planner with +synthetic profiles. Inspect all three role plans, exact shared timing, switches, +velocity and CC events. Also cover missing production profiles and explicit +failures with no partial plan. Do not write MIDI/native files or expose tools. +Retain all prior tests. + +## Validation and exit gate + +Run targeted articulation tests during development, then Release solution build, +all xUnit tests, and locked restore. Use: + +```powershell +dotnet build .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-restore +dotnet test .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-build +dotnet restore .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx --locked-mode +``` + +Restore after a manifest edit first. SDK executable: +`C:\Program Files\dotnet\dotnet.exe`. CLI is the known test-discovery fallback. + +Two separate conclusions are mandatory: + +1. Infrastructure implementation/test status: pass/fail with exact evidence. +2. Full Step 4 readiness: false/blocked unless actual production mappings for + all three targets satisfy the approved evidence gate. + +If evidence remains missing, do not search personal directories or fabricate +product profiles merely to claim readiness. List exactly what is needed and +stop without Step 5, even if every infrastructure test passes. + +## Mandatory worker report + +When complete, write your end-of-step report to ./prompts/report_4.md including: what was implemented, test results (pass/fail with details), any issues encountered, and whether you're ready for the next step + +Put the entire report in exactly one plain triple-backtick fence, with no +outside content. Include changed files, exact commands/exit codes/counts, +mechanism/velocity/state decisions, skipped checks, missing evidence and the two +distinct readiness conclusions above. Stop after writing the report. diff --git a/prompts/step_4_fix.md b/prompts/step_4_fix.md new file mode 100644 index 0000000..d5a118e --- /dev/null +++ b/prompts/step_4_fix.md @@ -0,0 +1,488 @@ +# Step 4 correction: Active iteration 4, additional evidenced capabilities + +**Only "Correction iteration 4" at the end of this prompt is active.** +Earlier iterations below are retained as completed history, not instructions +to repeat or prohibitions on already accepted Steps 5, 8 and supported Step 9. + +## Archived iteration 2: Extensible instrument catalog + +Status: catalog extension accepted; Step 5 MIDI writer subsequently accepted. + +## Objective and review findings + +The orchestrator read [the Step 4 report](report_4.md), inspected profile +validation, embedded catalog handling and event planning, and independently ran +the Release build/tests: **485 passed, 0 failed, 0 skipped**. Locked restore +also passed. + +Generic infrastructure is implemented and tested. Full Step 4 is not accepted: +the production profile catalog is empty. Official Ample manuals and the owner's +Eclipse screenshots now provide partial source evidence, but complete numeric/ +timing and installed-version mappings are not established. + +The owner has now explicitly requested ABJ, AGLP, AGM, AGT, AME and AMR, with the +ability to add instruments later. Execute the catalog extension below now. +Missing production mappings do NOT block metadata/abstraction work. They DO +block falsely declaring these instruments playable or Step 4 fully accepted. +This iteration replaces the earlier evidence-only correction objective. + +## Files and existing contracts + +Read before editing: + +```text +prompts\plan.md +prompts\step_4.md +prompts\report_4.md +docs\format-compatibility.md +docs\articulation-mappings.md +src\GAJ3T.MusicGen.RiffGrooveBuilder.Core\Articulations\InstrumentProfile.cs +src\GAJ3T.MusicGen.RiffGrooveBuilder.Core\Articulations\ArticulationRule.cs +src\GAJ3T.MusicGen.RiffGrooveBuilder.Core\Articulations\InstrumentProfileValidator.cs +src\GAJ3T.MusicGen.RiffGrooveBuilder.Core\Articulations\ArticulationPlanner.cs +src\GAJ3T.MusicGen.RiffGrooveBuilder.Generation\Profiles\InstrumentProfileCatalog.cs +``` + +Create/modify these directly related surfaces: + +```text +src\GAJ3T.MusicGen.RiffGrooveBuilder.Core\Instruments\InstrumentDefinition.cs +src\GAJ3T.MusicGen.RiffGrooveBuilder.Core\Articulations\InstrumentProfile.cs +src\GAJ3T.MusicGen.RiffGrooveBuilder.Core\Articulations\InstrumentProfileValidator.cs +src\GAJ3T.MusicGen.RiffGrooveBuilder.Generation\Instruments\InstrumentCatalog.cs +src\GAJ3T.MusicGen.RiffGrooveBuilder.Generation\Instruments\instruments.json +src\GAJ3T.MusicGen.RiffGrooveBuilder.Generation\GAJ3T.MusicGen.RiffGrooveBuilder.Generation.csproj +src\GAJ3T.MusicGen.RiffGrooveBuilder.Generation\Profiles\InstrumentProfileCatalog.cs +tests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\Instruments\InstrumentCatalogTests.cs +tests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\Articulations\ +tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\Instruments\InstrumentCatalogPipelineTests.cs +tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\Articulations\ +docs\articulation-mappings.md +docs\format-compatibility.md +README.md +prompts\report_4.md +``` + +Small directly needed result/validation/JSON helper files are allowed. No new +packages or projects. Preserve the existing composition/event planner behavior; +update synthetic test factories for any explicit profile-contract change. +Do not modify orchestrator prompts/plan or create any later step prompt. + +## Active catalog-extension implementation + +### Initial target definitions + +Add exactly these identities to a separate embedded instrument catalog: + +| ID | Code | Display name | Role | Official documentation | +| --- | --- | --- | --- | --- | +| ample-abj | ABJ | Ample Bass J | Bass | https://www.amplesound.net/en/Main_Panel_Manual-ABJ.pdf | +| ample-aglp | AGLP | Ample Guitar LP | Lead | https://www.amplesound.net/en/Main_Panel_Manual-AGLP.pdf | +| ample-agm | AGM | Ample Guitar M | Lead | https://www.amplesound.net/en/Main_Panel_Manual-AGM.pdf | +| ample-agt | AGT | Ample Guitar T | Lead | https://www.amplesound.net/en/Main_Panel_Manual-AGT.pdf | +| ample-ame | AME | Ample Metal Eclipse | Lead | https://www.amplesound.net/en/Main_Panel_Manual-AME.pdf | +| ample-amr | AMR | Ample Metal Ray5 | Bass | https://www.amplesound.net/en/Main_Panel_Manual-AMR.pdf | +| toontrack-sd3 | SD3 | Superior Drummer 3 | Drums | https://www.toontrack.com/manual/superior-drummer-3/ | + +Ample names/manual URLs were confirmed through the rendered official website. +These are requested identities, not proof of installed versions or executable +mapping support. Keep the existing three roles; acoustic guitars occupy the +existing Lead/guitar slot. No new rhythm/chord/strum patterns or extra track slots. + +### Minimal abstractions + +- `InstrumentDefinition`: immutable vendor-neutral ID, vendor, product code, + display name, role and documentation URL. Vendor is data, not an enum listing + individual manufacturers/products. Do not add instrument-specific subclasses. +- `InstrumentCatalog`: strict, immutable, deterministic embedded JSON loading, + lookup and role filtering. Reject malformed/null/unknown/duplicate fields, + duplicate IDs, invalid roles and invalid required identity/URL values. + A malformed resource must never become a successful empty catalog. +- Add a required `InstrumentId` to `InstrumentProfile` and validate its ID shape. + Profiles remain versioned mappings; definitions do not need fabricated + product versions, playable ranges, switches, CCs or native capabilities. +- Update `InstrumentProfileCatalog` to bind each loaded profile to a declared + instrument. Reject dangling IDs, role mismatches and mismatched product + identities. Retain existing verified/synthetic/unverified validation. + Keep strict JSON and no silent default/fallback behavior. +- Preserve the existing role/profile-ID selection API. Add an explicit + instrument-based selection path; diagnostics distinguish unknown instrument, + known instrument without a verified mapping, wrong-instrument/wrong-role + profile and multiple candidate mappings without an explicit choice. + Never select the first candidate or substitute another bass/guitar. +- Expose instrument metadata alongside derived mapping availability, either + through a small catalog-result API or joined catalog view. Use + `mapping_unavailable` / `profile_available`; these are not native-format or + installed-plugin acceptance flags. +- Keep `Profiles\instrument-profiles.json` honestly empty. Do not synthesize + mapping values just to populate six instruments. Synthetic mapped fixtures + belong only in tests and are not shipped or returned as production support. +- Current production resources should have seven identities and zero verified + mapping profiles. The MCP registry remains empty; final discovery/tool + integration still belongs to Step 8, using the updated plan contract. + +### Extensibility boundary + +Adding another instrument with existing mechanisms should require only a JSON +definition plus an evidence-backed profile, not a product-name switch, enum +member, subclass or planner change. Prove this with a test-only extra target. +Initially JSON is embedded and changes require build/publish. Do not add +runtime profile directories, hot reload, VST scanning/loading, reflection +plugins, external services or a configuration framework. + +Keep native writer selection format-based in the architecture. No writer +implementation or speculative `IAmpleVst`/per-instrument export hierarchy is +needed in this step. Reuse actual existing models/helpers rather than creating +parallel profile types or unused interfaces. + +### Documentation + +Update README and existing mapping/compatibility documents to list the six +requested Ample targets plus SD3, explain identity versus verified mapping, +show how to add an instrument as data, state the rebuild requirement and +clearly separate mapping availability from native/application compatibility. +Do not imply the folder screenshot provides versions, directory paths or maps. +Do not assume identical articulations across all Ample products. + +## Remaining production mapping evidence (not a catalog-work prerequisite) + +Before admitting actual mappings, obtain lawfully usable, version-specific evidence: + +1. Exact product/version contract and relevant settings for each selected Ample + target; use official documentation first, not an owner-reconstructed chart. +2. Exact SD3 version, content library, selected MIDI map and any custom overrides. +3. Authorized mapping sources/records and permission for any checked-in fixture + data; no audio samples, vendor libraries or unrelated user projects. +4. Absolute playable and control note numbers, ranges and channel behavior; + octave labels alone are insufficient. +5. Every supported articulation's keyswitch pitch/velocity, advance and duration, + latching/momentary behavior, initial state and releases/resets. +6. Verified velocity-layer boundaries and any required velocity transformation, + plus CC numbers, values, combinations and complete state requirements. +7. Actual verification records establishing the mapping behavior in the named + product/version. A pasted flag saying "Verified" is not evidence. + +Record source, product/version, authorization and verification procedure for +each mapping. Do not search personal/vendor directories or install products. +If necessary evidence remains unavailable, leave production profiles empty, +complete the actionable catalog work/tests, report the gate separately and stop. + +AGP/SDP schema/fixture rights and exact extension/load semantics remain separate +future native gates. Production MIDI mapping evidence does not satisfy them. + +## Future profile admission after evidence arrives (not this iteration) + +- Add versioned evidence-backed profiles for the requested instruments/roles. + Use the actual verified values, not numbers from synthetic tests. +- Preserve strict catalog loading, validation and explicit selection failures. + Specify a default only where the owner/evidence establishes an unambiguous + authorized choice; otherwise require the explicit profile ID. +- Ensure the documented text example's generated pitches, velocity and + articulation intentions are representable. If not, report the conflict and + seek an explicit reviewed resolution rather than silently altering intent. +- Keep generic synthetic regression tests separate from production evidence + tests. Production registration must still reject synthetic/unverified data. +- Do not expose the public generation tools or write MIDI/native files yet. + Those remain future steps, not corrections to this gate. + +## Required catalog-extension tests and validation + +Unit tests: + +- Exact seven IDs/names/codes/roles and source URLs; four Lead, two Bass, + one Drums; immutable ordering/filtering and unrelated-cwd loading. +- A test-only additional instrument and multiple versioned profiles bind and + select through the same catalog APIs, with no product-specific engine logic. +- Malformed resources/fields, duplicate identities, missing/null identity values, + invalid URLs/roles/IDs, dangling profile instrument IDs and product/role + mismatches fail explicitly. +- Known-unmapped versus unknown instrument diagnostics; wrong-instrument, + wrong-role, unknown profile, explicit selection and ambiguous mappings. +- Seven declared production identities do not make the empty production mapping + catalog playable; synthetic/unverified entries remain rejected. +- Preserve existing profile/event-planner tests, adjusted only for the new + explicit instrument-ID contract. Do not weaken validations. + +Integration tests: load the actual embedded catalogs from an unrelated cwd, +join identity/availability, inspect all seven requested targets, and verify +explicit unavailable-mapping diagnostics without fake output. Retain real +MCP process tests and synthetic articulation pipeline regressions. + +Future production mapping tests and actual application verification remain +required when those profiles are admitted, but are not catalog-extension tests. + +Run targeted articulation tests, then: + +```powershell +dotnet build .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-restore +dotnet test .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-build +dotnet restore .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx --locked-mode +``` + +## Report and stop condition + +When complete, write your end-of-step report to ./prompts/report_4.md including: what was implemented, test results (pass/fail with details), any issues encountered, and whether you're ready for the next step + +Preserve the existing report's infrastructure history and add an explicitly +identified "Correction iteration 2: instrument catalog extension" section. +The entire resulting report must remain +inside one plain triple-backtick fence. Include evidence references, actual +production verification, changed files, commands/exit codes/counts, unresolved +limitations and separate infrastructure/full-Step-4 readiness conclusions. + +Report catalog-extension readiness separately from full Step 4 production +readiness. The extension can pass while full Step 4 remains FALSE / BLOCKED. +Include changed files, exact commands/exit codes, test counts, contract migration, +extensibility proof and unresolved mappings. Stop for orchestrator review; +never start Step 5 yourself. + +--- + +## Correction iteration 3: Documentation-backed profiles + +### Objective and baseline + +The owner has requested continuation. Step 5 now writes and reads actual MIDI, +with 663 passing tests. The seven-identity catalog and shared planning engine +exist; production profiles remain empty. Research the published default mappings +and admit only profiles supported by the evidence. Do the documentation work +yourself rather than requiring the owner to reconstruct vendor tables. + +Read the updated plan, existing reports, profile/catalog/planner code, and +mapping/compatibility documents. Treat the earlier prompt iteration above as +historical context. Execute only this iteration; do not change orchestrator +prompts/plan, create later prompts, commit or delegate. + +### Bounded source research + +- Review official manuals for ABJ, AGLP, AGM, AGT, AME and AMR, using the + verified URLs already in the embedded instrument catalog, plus the official + Settings/CPC documentation where needed. The rendered vendor website exposes + links that simplified HTML fetching previously missed. +- Investigate SD3 default kick/snare/closed-hi-hat mappings using accessible + official material and the shared manual page. Do not bypass login, request + credentials, install products or scan personal/vendor directories. +- Establish absolute MIDI numbers with a genuine numeric anchor or authorized + mapping/sample; do not infer a C0 number solely from its octave label. + Public third-party maps may corroborate facts, not silently replace vendor + evidence or introduce unlicensed implementation code. +- Record source URL, section/page, retrieval/source revision, exact supported + facts, gaps, and applicability. Do not copy manuals/sample libraries into the + repository. Temporary PDF extraction helpers belong only in session storage + and must be cleaned up. No production dependency/package changes. +- Focus on the supported Sustain/PalmMute pitched intentions and the three + existing drum voices. Do not expand articulations, patterns or track roles. +- Stop researching an inaccessible source after distinct reasonable retrieval + methods; finish the supported subset and report exact remaining gaps rather + than inventing data or looping. + +### Evidence model and admission + +- Introduce the distinct `MappingVerification.Documented` stage. It means + cited published default mapping facts, NOT real installed-plugin acceptance. + Preserve existing Verified, Unverified and Synthetic semantics. +- Add the smallest immutable compatibility-notes representation needed to + disclose mapping/version scope and timing/routing policies. Keep existing + serialized fixture contracts compatible where practical; required documented + notes must be validated, not silently defaulted. +- Allow Documented and Verified in production catalogs; reject Synthetic and + Unverified as before. Never relabel documentation-only evidence as Verified. +- A profile scoped to documented defaults must say so. Do not invent an exact + installed product version. Keep source/mapping revision separate from a + claimed installed version, making any non-versioned-manual scope explicit. +- Distinguish published switch/range/velocity facts from deterministic writer + policies (channel routing, control ordering/pulse timing). Any policy must be + conservative, explicit in notes and tested, not presented as a vendor-certified + minimum or actual-plugin check. If an essential behavior is unsupported by + evidence, do not admit that profile. +- Preserve exact InstrumentId/role/product binding and truthful availability. + Keep all six requested instruments plus SD3 declared even if some lack a map. + +### Initialization correctness + +Inspect the existing assumption that a pitched plugin already starts in its +declared resting articulation. Reusable MIDI cannot rely on arbitrary receiver +state. Provide an explicit, backward-compatible unknown-initial-state route +for documented mappings where needed (for example, null initial articulation +forces the first requested state to be selected). + +Do not send unnecessary overlapping sustain and palm-mute switches: the manuals +describe combined-switch behavior. Preserve existing explicit known-state +synthetic behavior and add regression tests proving that the first requested +Sustain and PalmMute each initialize correctly, without stuck switches, changed +musical timing or accidentally combined articulations. + +### Files and implementation scope + +Modify only directly necessary files, including: + +```text +src\GAJ3T.MusicGen.RiffGrooveBuilder.Core\Articulations\InstrumentProfile.cs +src\GAJ3T.MusicGen.RiffGrooveBuilder.Core\Articulations\InstrumentProfileValidator.cs +src\GAJ3T.MusicGen.RiffGrooveBuilder.Core\Articulations\ArticulationPlanner.cs +src\GAJ3T.MusicGen.RiffGrooveBuilder.Generation\Profiles\InstrumentProfileCatalog.cs +src\GAJ3T.MusicGen.RiffGrooveBuilder.Generation\Profiles\instrument-profiles.json +tests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\Articulations\ +tests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\Instruments\ +tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\Articulations\ +tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\Midi\ +README.md +docs\articulation-mappings.md +docs\format-compatibility.md +prompts\report_4.md +``` + +Add small directly needed test/helper files if necessary. Do not expose public +MCP tools, implement native writers or alter the tested MIDI serialization +merely to hide missing mapping facts. + +### Required tests and validation + +- Documented admission with source/notes, missing/invalid documented notes, + Verified preservation, Synthetic/Unverified rejection and correct binding. +- Every admitted profile's numeric switch/pitch/range/velocity facts and source + assertions. Unknown/unsupported profiles remain unavailable actionably. +- Unknown receiver-state initialization, repeated latching, state transitions, + first-note timing, note/control pairing and source-data preservation. +- Actual composition -> admitted profile -> plan -> MIDI file write/read-back + for every supported admitted role/profile. These are format/source tests, + not claims that the owner's VSTs were run. +- Retain all 663 baseline tests, updating only intentional evidence-status or + initialization contract assertions with explicit regression coverage. + +Run targeted tests, then Release solution build, all tests and locked restore. +Use the existing SDK and pinned DryWetMIDI 8.0.3. Do not add new packages to the +project. Record exact commands, counts, source evidence and unrun application +checks. + +### Mandatory report and stop + +When complete, write your end-of-step report to ./prompts/report_4.md including: what was implemented, test results (pass/fail with details), any issues encountered, and whether you're ready for the next step + +Preserve previous report history and append "Correction iteration 3: +documentation-backed profiles" inside the same single plain triple-backtick +fence. Report supported profiles, evidence scope, precise unresolved gaps, +test/command results, and source-backed versus application-verified readiness +separately. If no profile can be admitted honestly, state that clearly. +Stop after the report; do not start another step. + +--- + +## Correction iteration 4: Additional evidenced capabilities + +### Objective and baseline + +The bounded read-only follow-up found usable vendor evidence that the first +inventory missed. Current baseline is 882 passing tests, public MCP generation +and a published Windows x64 executable, with AGLP/AME Documented profiles. +Read current source/reports; do not use the old 663-test baseline. + +Implement AGM Sustain/PalmMute and ABJ Sustain-only from the evidence below. +Evaluate one specific AGT anchor lead; admit AGT only if that link is genuinely +confirmed. Preserve the distinction between a supported subset and an entire +instrument/application verified. Refresh the actual published executable after +source/catalog updates so deployment and tests never advertise stale profiles. + +### Concrete official evidence already found + +- AGM: + https://www.amplesound.net/dl0822/ds/AGM-Rylynn.zip + `AGM-Rylynn/AGM3-Rylynn.mid`, 480 PPQ, zero-based track 1 "G1": + note24/velocity80/channel0 on32215/off32335. + HTTP Last-Modified 2019-06-11 17:57:25 GMT. + https://www.amplesound.net/dl0822/ds/AGM-Dear_Ben.zip + `AGM-Dear Ben/AGM-Dear Ben Tempo 74.mid`, 480 PPQ, + track1 "AGM ARP"/channel0: note26/velocity80 on28798/off28858; + note24/velocity80 on30238/off30298. + HTTP Last-Modified 2019-11-24 16:38:43 GMT. + Together with the already reviewed AGM manual: Sustain24/PM26, E1-C5=40-84, + Sustain musical velocities1-126, PM1-127; no installed-release assertion. +- ABJ: + https://www.amplesound.net/dl0822/ds/AB-Articulations.zip + The official download row explicitly advertises products ABJ ABP. + `AB-Articulations/4.2 Articulations & Poly Legato.mid`, 480 PPQ, + track1 "ABP"/channel0: note24/velocity90 on3720/off4080, + musical note40/velocity90 on3840; note26/velocity100 on22980/off23220. + HTTP Last-Modified 2019-06-11 17:32:45 GMT. + Vendor-listed shared applicability is evidence, not an ABJ-named standalone + performance. ABJ manual's C0 and B0-E4 imply Sustain switch24/range35-76. + Sustain musical velocities1-125; 126-127 are accents. + Admit Sustain-only. Do NOT guess the dedicated PM/Dead Note threshold. +- AGT specific remaining lead: + https://www.amplesound.net/dl0822/ds/AGT-Wish_You_Were_Here.zip + Official row lists AGT AGM, "Tab Project". + `AGT-Wish You Were Here/AGT3-Wish You Were Here Tempo 62.mid`, 480 PPQ: + tracks1 "Solo" and2 "Strum" each contain only note105/velocity80, + channel0 on3840/off4320. + HTTP Last-Modified 2019-06-11 18:04:59 GMT. + This is not a direct Sustain/PM performance. Check the actual official + applicable Tab Reader play-note documentation to determine whether 105 can + be unambiguously associated with a named tab-play note and yield the octave + anchor. Do not infer its label solely by applying an assumed convention. + If confirmed, the reviewed AGT C0/D0 and E1-C5/velocity facts may be admitted + under the same documented-default limits; otherwise leave AGT unavailable. +- No AMR/Ray5 public demo archive appeared among the nine inspected official + download rows. Do not invent a URL, substitute another bass, or repeat an + open-ended search. SD3 remains unavailable. + +Verify and record source revisions/hashes as appropriate; inspect public MIDI +using pinned DryWetMIDI, without retaining copied vendor assets. Any temporary +reader/helper remains session-only and must be removed. + +### Implementation and all affected surfaces + +- Reuse existing Documented profiles, compatibility notes, unknown-state + initialization and shared planner. No product subclass, new grammar or + articulation/role enum is required. +- New bass profile uses explicit zero-based channel1 routing policy so existing + Lead channel0 and Bass channel1 can coexist. Distinguish this project routing + and pulse timing policy from vendor-certified requirements. +- ABJ advertises only Sustain. Palm-muted ABJ requests must fail with the + existing explicit unsupported-articulation diagnostic; do not invent a + velocity transform, silently switch to Sustain or make a fake PM claim. +- Keep AMR and SD3 unmapped, and all native codecs unavailable. +- Update all affected discovery/selection/availability/profile-count tests and + docs deliberately, not by weakening their assertions. +- Add real MCP Lead+Bass generation using explicit AME/AGLP/AGM and ABJ profiles, + actual MIDI read-back, shared lead-in, separate channels/tracks, switches, + note/velocity/timing correctness, no stuck notes and one artifact for fallback. +- Preserve negative tests: missing Bass selection is now no_default_profile, + not mapping_unavailable; unmapped Drums remains unavailable. Explicit unknown, + wrong-role, unsupported-ABJ-PM and no-overwrite errors remain actionable. +- Existing AGLP/AME example contents/IDs and warning semantics must remain valid. + +Files may include directly affected profile JSON, existing catalog/planner +tests, documented-profile MIDI tests, GenerationService/MCP tests only for +correct capability expectations, PublishedServerTests and existing docs/README. +Do not change orchestration prompts/plan. No packages/projects or unrelated +production feature work. No commit, delegation or user/global MCP settings. + +### Publication refresh and validation + +Rebuild and publish with the accepted win-x64 profile and its dedicated lock, +then run: + +- Focused new-profile/catalog/actual MIDI/MCP/publication tests. +- Release build and the full suite against the refreshed published payload. +- Both ordinary solution and publication-specific locked restores. +- Existing retained AME example read-back/hash preservation. + +The published metadata must reflect the new admitted subset, not the old +two-profile catalog. Publication refresh is necessary validation/distribution +of this correction, not a new deployment feature or application acceptance. + +### Mandatory reports and stop + +When complete, write your end-of-step report to ./prompts/report_4.md including: what was implemented, test results (pass/fail with details), any issues encountered, and whether you're ready for the next step + +Append "Correction iteration 4: additional evidenced capabilities", preserving +the entire earlier history and its single enclosing plain code fence. +Also append a clearly labeled publication-refresh section to report_9.md with +new payload/example hashes, profile/capability counts and actual published +read-back evidence. Preserve its earlier history inside the single fence. +Do not rewrite historical reports as if their old counts had been different. + +Include exact sources/facts, AGT conclusion, supported/unsupported articulations, +test commands/counts and published readiness. Runtime-free host, licensed app +acceptance, AMR/SD3 and native-format limits remain explicit. +Stop for orchestrator review after both reports. No further steps. diff --git a/prompts/step_5.md b/prompts/step_5.md new file mode 100644 index 0000000..4a2f21c --- /dev/null +++ b/prompts/step_5.md @@ -0,0 +1,197 @@ +# Step 5: Build and verify Standard MIDI file generation + +## Objective and sequencing + +Read [the updated plan](plan.md), [the reviewed infrastructure and catalog +report](report_4.md), and existing source/tests before editing. + +Accepted baseline: .NET 10, DryWetMIDI 8.0.3, generic composition/articulation +planning, seven declared instruments, no admitted production mappings, and +566 passing tests. + +Implement the actual Standard MIDI writer now. Its prerequisite is the accepted +generic Step 4 infrastructure, not verification of every product mapping. +Synthetic profiles may prove format generation in tests only. This does not +authorize guessed Ample/SD3 profiles, public generation tools or compatibility +claims. Native writers and final tool integration remain later work. + +Execute only this step; preserve existing work. Do not alter orchestrator +prompts/plan, create later prompts, commit or delegate. + +## Files to create or modify + +```text +src\GAJ3T.MusicGen.RiffGrooveBuilder.Generation\ + Midi\MidiEventBuilder.cs + Midi\MidiFileBuilder.cs + Midi\MidiFileWriter.cs +tests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\ + Midi\MidiEventBuilderTests.cs + Midi\MidiFileBuilderTests.cs + Midi\MidiFileWriterTests.cs +tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\ + Midi\MidiGenerationPipelineTests.cs + Articulations\ArticulationPipelineTests.cs + Support\SyntheticPipelineProfiles.cs +README.md +docs\articulation-mappings.md +docs\format-compatibility.md +docs\text-description-contract.md +prompts\report_5.md +``` + +Use small directly necessary typed exception/helper files only where justified. +Reuse/extract the existing integration synthetic profile factories rather than +copying the same setup into another test suite. Update only docs affected by +the new writer. No new projects/packages/version upgrades or raw MIDI encoder. + +## Implementation requirements + +### Boundaries and API + +- Core remains independent of DryWetMIDI. +- Generation translates existing `MidiEventPlan`/`PlannedMidiEvent` types into + DryWetMIDI types. Use `Melanchall.DryWetMidi` exactly 8.0.3 for all MIDI + construction, manipulation, serialization and read-back validation. +- Build from a validated composition plus its event plan; preflight null/ + invalid composition, role/extent disagreement, event/timing limits and + unsupported event types before touching final output. +- Prefer a small builder/writer API over unused interfaces, new configuration + frameworks or generic result wrappers. Invalid arguments/unsupported format + values must have actionable exceptions/diagnostics, never success defaults. +- Do not modify profiles, mark synthetic data verified, bypass profile + admission, or change the server's empty production MCP registry. + +### MIDI structure and metadata + +- Write SMF type 1 at 960 ticks per quarter note. +- Add one conductor track and one named track for each selected role, with + deterministic ordering (Lead, Bass, Drums) and no absent-role tracks. +- Place tempo and meter metadata at tick zero in the conductor. + Convert BPM to integer microseconds/quarter with documented nearest-integer, + midpoint-away-from-zero rounding and the existing valid SMF tempo range. + Preserve requested meter semantics; verify the pinned library API instead + of guessing whether it accepts a denominator or its encoded exponent. +- Metadata must remain correct with a shared lead-in. Do not shift tempo/meter + to the first played note. +- Preserve every planned pitch, velocity, channel, note-on, explicit note-off + and CC number/value. Drums use the configured profile channel; the synthetic + standard example uses zero-based 9 (MIDI channel 10). Do not remap channels. +- Preserve stable same-tick priorities already established by the event plan: + old note-offs, initial/release/reset controls, new state/keyswitch actions, + musical note-ons. Do not let a high-level helper reorder controls/notes. +- Add exactly one proper End-of-Track per track at the plan's global EndTick, + preserving full declared bars/trailing rests, shared lead-in and later final + release/reset pulses. No stuck musical or switch notes. +- Use checked absolute-to-delta conversion; no negative/wrapped deltas. + Validate the SMF four-byte VLQ maximum delta (0x0FFFFFFF) before serialization. + Reject unrepresentable gaps explicitly, rather than writing nonstandard + five-byte deltas, silently truncating or inserting undocumented musical data. +- Investigate meter boundaries supported by DryWetMIDI 8.0.3, especially + denominators 128 and 256 (Core accepts through 256). If the library cannot + represent a valid Core meter, fail clearly and document/test that writer + limitation; do not wrap a byte, change meter or narrow Core silently. +- Read files back through DryWetMIDI; round-trip output must preserve exact + semantic content and timing. Do not use a custom byte parser as a substitute. + +### Stream and filesystem output + +- Support writing to a caller-owned writable stream without closing it. + A stream failure propagates; do not report success or hide partial-stream + semantics. Document that caller-owned streams are not transactional. +- Provide actual file output to an explicit absolute destination path, staged + in a uniquely named request-owned temporary file in the same directory. + Write/close the complete file, then move with no overwrite. +- Existing files must never be truncated or replaced, including a destination + collision occurring between preflight and move. Never rely only on File.Exists. +- Validate parent/destination inputs with clear failures. Do not interpret + paths as shell commands or add CLI/server transport features. +- On failure/cancellation, clean up only this request's temporary files. + Report any cleanup failure explicitly without losing the original error. + Never scan/delete unrelated files or remove a pre-existing destination. +- Propagate cancellation through event-building loops and before/after the + library's synchronous serialization and before publication. Document any + non-interruptible synchronous write boundary rather than promising immediate + cancellation. Do not publish after an observed cancellation. +- This is single-file staging only; multi-format transactional publication/ + fallback orchestration remains Step 8. + +## Required tests + +### Unit tests + +1. Each planned event maps to the exact DryWetMIDI event type/values/channel; + note-off is explicit, and unsupported types/ranges fail clearly. +2. Type 1, 960 PPQ, conductor plus selected named tracks, tempo at 120 BPM = + 500,000 microseconds/quarter, documented rounding at a nonintegral quotient, + and correct 4/4 and non-4/4 metadata after serialization/read-back. +3. Tempo lower/upper representability, invalid/nonfinite tempo, meter + denominator boundary behavior, exact delta at/over 0x0FFFFFFF, checked + overflow and mismatched composition/event plan. +4. Same-tick ordering for transitions, keyswitch release, CC reset/new value, + musical note-off/on, including serialization/read-back. +5. Exact End-of-Track positions with trailing rests and final reset tails. + Preserve source composition/event plan and deterministic repeated output. +6. Writable borrowed stream remains open; invalid/read-only/failing streams + fail explicitly. File creation, destination collision/no overwrite, + staging cleanup, I/O failure and cancellation produce truthful outcomes. + +### Integration tests + +- Run real description -> composition -> synthetic profile/event planning -> + writer -> actual temporary `.mid` file -> DryWetMIDI read-back. +- Full documented example: four bars, 4/4, 120 BPM, 15,360 unshifted ticks; + existing synthetic shared lead-in 240 yields musical end 15,600. + Inspect all three role tracks and conductor. +- Assert 32 played lead notes, four bass notes and 48 mapped drum hits, + exact pitches/velocities/channels/ticks, switch pulses, CC state transitions, + event ordering and complete note-off pairing. Distinguish control notes from + musical counts; do not call synthetic numbers real Ample/SD3 mappings. +- Include role subsets, a supported non-4/4 meter, long repeated patterns + without drift, rests and controls extending past musical end. +- Verify writing from an unrelated cwd using explicit paths, no-overwrite and + failure/cancellation cleanup. Tests own isolated directories/resources. +- Retain existing protocol, catalog and planning tests, including empty + production mappings and no premature MCP generation tool. + +## Documentation and non-goals + +Explain the new in-process builder/writer usage, exact output structure, +borrowed-stream/file staging semantics, metadata rounding/limits, cancellation +boundaries, and the distinction between tested MIDI formatting and still +unverified real plugin mappings. + +The combined type-1 Cubase arrangement is not automatically a Riffer-import +file: the vendor manual requires a single track for Riffer import. Do not add +or claim AGP/SDP serialization or a single-track Riffer export in this step. +No audio, VST loading/scanning, cloud, HTTP, playback or containers. + +## Validation and acceptance + +Use focused MIDI tests during development, then run: + +```powershell +dotnet build .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-restore +dotnet test .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-build +dotnet restore .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx --locked-mode +``` + +The installed SDK is `C:\Program Files\dotnet\dotnet.exe`; use a process-local +PATH when necessary. Editor test discovery has been unavailable; CLI xUnit +execution is the known fallback. Do not restore/install new packages merely +to inspect the already-pinned MIDI API; use existing package XML/reflection. + +Exit: real valid type-1 MIDI files generated/read back with complete mapped +event semantics, safe single-file output, passing new and retained tests, +and no false claim that production mappings/native writers are finished. + +## Mandatory worker report + +When complete, write your end-of-step report to ./prompts/report_5.md including: what was implemented, test results (pass/fail with details), any issues encountered, and whether you're ready for the next step + +Put the entire report in exactly one plain triple-backtick fence. Include files, +API and actual pinned-library findings (tempo/meter/delta semantics), exact +commands/exit codes/test counts, file/read-back evidence, skipped checks, limits +and issues. Distinguish Step 5 format-writer readiness from real mapping, +native-format and application acceptance. Stop for orchestrator report review; +do not start Step 6 or another profile step. diff --git a/prompts/step_8.md b/prompts/step_8.md new file mode 100644 index 0000000..1aaeb89 --- /dev/null +++ b/prompts/step_8.md @@ -0,0 +1,186 @@ +# Step 8: Wire truthful profile discovery and MIDI generation into MCP + +## Objective, sequencing and stop boundary + +Read the updated [plan](plan.md), [profile report](report_4.md), [MIDI writer +report](report_5.md), and existing source/tests first. + +Accepted baseline: 714 tests; two source-Documented default profiles (AGLP/AME), +five declared-but-unmapped targets, actual type-1 MIDI writing and no production +MCP tools. The owner requested continuation. + +Implement both planned tools and the real text -> admitted profile -> MIDI +pipeline now. Native codecs remain unavailable: exercise explicit MIDI fallback +without fake writers or success claims. This sequencing does not mark native +Steps 6/7 completed or establish application compatibility. + +Work only this step. Preserve existing changes, especially the source-backed +profile work. Do not modify orchestrator prompts/plan, write later prompts, +commit, delegate, implement AGP/SDP encoding or start publishing. + +## Files and architecture + +Create/modify directly necessary files under: + +```text +src\GAJ3T.MusicGen.RiffGrooveBuilder.Core\Generation\ + GenerateProjectRequest.cs + GenerationResult.cs +src\GAJ3T.MusicGen.RiffGrooveBuilder.Generation\ + GenerationService.cs + Output\ # Shared filename/path validation if needed + Midi\MidiFileWriter.cs # Only for actual shared-helper extraction +src\GAJ3T.MusicGen.RiffGrooveBuilder.Server\ + Program.cs + Tools\MusicGenTools.cs + Tools\McpToolDefinition.cs # Only necessary schema/serialization support +tests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\ + Generation\GenerationServiceTests.cs + Protocol\ # Contract/schema/tool factory coverage +tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\ + Stdio\McpGenerationTests.cs + Stdio\McpProtocolTests.cs + Stdio\McpProcess.cs +README.md +docs\mcp-protocol.md +docs\format-compatibility.md +prompts\report_8.md +``` + +Small genuinely needed DTO/helper files are allowed. Keep Core independent of +DryWetMIDI. No new package, project, HTTP, GUI, runtime profile/VST loading, +audio, cloud, CLI generation command or configuration framework. + +Reuse the existing typed tool registry/serializer, parser, profile catalog, +articulation planner and staged MIDI writer. Avoid duplicate path logic: +extract a small shared helper only if both consumers actually need it. + +## Public tool contracts + +Register exactly `list_instrument_profiles` and `generate_project` in production. +Keep JSON-RPC/MCP lifecycle behavior and stdout purity intact. + +### `list_instrument_profiles` + +- Optional role filter: lead/bass/drums. +- Return all matching declared instruments and their mapping availability, + plus matching admitted profiles. Seven identities remain visible; two + Documented Lead profiles are available, five targets remain unavailable. +- Expose stable IDs, vendor/product identity, role, documentation URL, + profile-to-instrument binding, product/version scope, mapping revision, + playable range, supported articulations/mechanisms, evidence status and + immutable compatibility notes. +- Native statuses are unverified/unavailable with no native writer. MIDI is the + implemented output capability. Mapping availability is not native support or + installed-plugin acceptance. No synthetic/test profile or fixture is exposed. + +### `generate_project` + +Inputs as in the plan: + +- Required description, absolute outputDirectory, safe projectName stem. +- Optional unique nonempty formats array (`agp`, `sdp`, `mid`). +- Optional profiles object (lead/bass/drums profile IDs). +- fallbackToMidi defaults true. + +Publish explicit input/output JSON Schemas: required fields, string enums, +nonempty/unique formats and additionalProperties:false. Actual serialization +must match advertised schemas, including enums and nullable failure fields. +Use minimal shared typed schema support; do not replace the registry framework. + +Result must include the plan's status, interpretedComposition/defaults, artifacts, +per-role/per-requested-format targets (with instrumentId/profileId), warnings, +errors and timing. Byte counts/absolute paths must reflect real existing files. +Wrap structuredContent with matching serialized JSON text content. +isError is true only for failed results, not explicitly requested fallback. + +## Exact generation semantics + +1. Validate request, parse/plan text, then resolve exactly the selected roles. + Profile ID selection must match the role/instrument and catalog admission. + There is no authorized automatic role default: missing selection must give + an actionable diagnostic listing relevant available IDs. Do not choose the + first guitar or silently substitute another instrument. +2. A selected Bass/Drums/unmapped target cannot be dropped just because its + profile is unavailable. Fail explicitly with no artifact. Supplying a + profile for an unselected role also fails rather than being ignored. +3. Every Documented profile generates a compatibility warning containing its + source-only status and relevant configuration/version/routing/timing scope. + It must never be described as installed/application verified. +4. Omitted formats mean applicable native formats for selected roles plus MIDI. + For a Lead-only description that is AGP + MIDI, NOT an inapplicable SDP + request. Explicit inapplicable formats fail actionably. +5. Native AGP/SDP writers do not exist. If applicable native output is requested + with fallback true, produce ONE actual combined MIDI file using the same + complete event plan; return status=fallback, per-target fallback reasons and + native-unavailable warnings. Reuse an explicitly requested MIDI artifact; + do not emit duplicate files or renamed MIDI/native placeholders. +6. If native output is requested with fallback false, fail preflight before any + output. A MIDI-only request succeeds regardless of fallback=false and has + status=complete, with documented-profile warnings as applicable. +7. Output is `.mid`, conductor plus selected named role tracks, + preserving the verified writer semantics, source pitches and controls. +8. Validate filenames/traversal/reserved names and output path. Do not overwrite + existing output, including races. Create the explicitly chosen directory only + after semantic/profile/format preflight. Never invoke a shell for generation. +9. MIDI-format limitations, invalid input, missing mappings, I/O errors, + cancellation and unexpected failures are NOT native-fallback triggers. + Expected failures return actionable fields/codes; unexpected exceptions use + the existing logged JSON-RPC internal-error boundary. Propagate cancellation + and clean only request-owned staging/output paths. +10. Keep actual work off the transport reader's synchronous path so pings and + cancellation can be read while generation runs. Honor cancellation before + publication; document synchronous DryWetMIDI serialization boundaries. + +Single-file staging is already implemented; do not create a speculative +multi-native-output transaction framework. Do not edit the text grammar to +silently accept instrument/genre instructions it does not support. + +## Required tests + +### Unit / contract tests + +- Exactly two registered production tools; empty/test-only registries continue + to work in existing unit tests. +- Discovery filtering, seven identities/two Documented profiles, unavailable + targets, evidence/compatibility and truthful format capabilities. +- Exact input/output schemas versus serialized results; enum/string values, + required/unknown/null fields, defaults, unique/nonempty formats and nested + profile object validation. +- Valid explicit AGLP and AME Lead requests; missing/unknown/wrong-role/unselected + profile, unavailable Bass/Drums, invalid text/path/name/formats, and errors + without partial usable output. +- Native-only and native+MIDI fallback produce one MIDI artifact and complete + per-target diagnostics; disabled fallback fails preflight; MIDI-only works + with fallback disabled; omitted formats respect role applicability. +- Documented warnings always survive successful/fallback generation. +- Collision/no overwrite, cancellation/I/O errors, limits and cleanup. + +### Real subprocess integration + +- Launch the actual server, initialize, discover the two tools, list profiles, + then generate via tools/call using each admitted profile: + description `palm-muted eighth-note lead`, formats=[mid] and a unique stem. +- Read the returned file with DryWetMIDI: type 1/960 PPQ, tempo/meter, conductor/ + Lead, expected notes and switches, lead-in and end markers. +- Native fallback, disabled fallback, no invented AGP/SDP artifacts, invalid + profiles/roles/requests, preserved existing files and no undisclosed partials. +- Assert outputSchema/result shape, structured/text content agreement, isError/ + status consistency, protocol-only stdout, unrelated cwd and bounded cleanup. +- Verify ping and cancellation remain responsive during asynchronous work; + use deterministic unit seams where real tiny requests complete too quickly. +- Update prior real-process empty-discovery expectations to the intentional + two-tool behavior, preserving unrelated protocol regressions. + +## Validation and mandatory report + +Run targeted Generation/MCP tests, then Release build, all xUnit tests and locked +restore. No package changes are needed. Use installed .NET 10 and DryWetMIDI +8.0.3, with the established CLI fallback for unavailable editor discovery. + +When complete, write your end-of-step report to ./prompts/report_8.md including: what was implemented, test results (pass/fail with details), any issues encountered, and whether you're ready for the next step + +Entire report: exactly one plain triple-backtick fence. Include changed files, +exact commands/counts, real RPC-generated file/read-back evidence, documented +profile disclosure, native/mapping limits and explicit supported-slice readiness. +Stop for report review; do not publish or start another worker step. diff --git a/prompts/step_9.md b/prompts/step_9.md new file mode 100644 index 0000000..e72a57d --- /dev/null +++ b/prompts/step_9.md @@ -0,0 +1,145 @@ +# Step 9: Publish and verify the usable local MCP executable + +## Objective, prerequisites and honest completion boundary + +Read the updated [plan](plan.md), [Step 8 report](report_8.md), latest profile +report and current source/tests. + +Accepted supported slice: two real MCP tools, documented AGLP/AME Lead MIDI +generation, explicit native fallback, seven identities/five unavailable mappings, +and 868 passing tests. Step 8 report/code was reviewed; 272 targeted tests passed +independently. Native Steps 6/7 remain blocked, not completed. + +Publish a self-contained Windows x64 local executable and verify real stdio +generation from that published executable. Provide copyable local-client setup +and a retained generated MIDI example. This is a supported-slice deployment, +not a false claim that all products/native formats/application checks passed. + +Execute only this step. Preserve existing work. Do not change orchestrator +prompts/plan, create later prompts, commit, delegate, install products, add HTTP/ +containers/audio/CLI generation features, invent mappings/native output or +modify user VS Code/global MCP settings. + +## Files/artifacts to create or modify + +```text +src\GAJ3T.MusicGen.RiffGrooveBuilder.Server\ + Properties\PublishProfiles\win-x64.pubxml + GAJ3T.MusicGen.RiffGrooveBuilder.Server.csproj # Only if required for publication +tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\ + Publishing\PublishedServerTests.cs + Stdio\McpProcess.cs # Reuse/extend existing harness +docs\local-deployment.md +docs\format-compatibility.md +README.md +prompts\report_9.md +artifacts\publish\win-x64\ # Ignored generated publication +artifacts\examples\ame-lead-example.mid # Actual generated example, not vendor data +``` + +Small necessary test/script helpers are allowed. No production package upgrade +or new project. Dependency locks may change only through restore if RID-specific +assets truly require it; retain exact existing package versions. + +## Publish configuration and execution + +- Keep the existing assembly/executable name so known test/client paths stay + consistent. Use Microsoft.NET.Sdk/net10.0/OutputType=Exe, no web SDK. +- Profile: Release, win-x64, SelfContained=true, PublishSingleFile=true, + PublishTrimmed=false, PublishAot=false, UseAppHost=true, + IncludeNativeLibrariesForSelfExtract=true. +- Embed existing catalogs and preserve cwd-independent resource loading. + Verify the pinned DryWetMIDI package deployment instead of assuming native + extraction/device dependencies irrelevant. Do not use playback/device APIs. +- Publish into the explicit artifacts\publish\win-x64 directory. Inspect any + existing output before cleanup; do not recursively remove broad directories + or delete unrelated files. Build-tool overwrite of its own publication files + is normal; no indiscriminate repository/global cleanup. +- Restore only when changed manifests or the actual publish command requires + missing RID assets/runtime packs. Do not change system SDK/global PATH. + +Expected reproducible command: + +```powershell +dotnet publish .\src\GAJ3T.MusicGen.RiffGrooveBuilder.Server\GAJ3T.MusicGen.RiffGrooveBuilder.Server.csproj -p:PublishProfile=win-x64 -o .\artifacts\publish\win-x64 +``` + +## Real published-process checks + +- Reuse the process/test harness to target an explicit published executable + path. Any optional test-only path override must remain test infrastructure, + not an application CLI/runtime configuration feature. +- Launch from an unrelated existing working directory, with redirected streams, + bounded timeouts, concurrent draining and cleanup scoped to owned processes. +- Initialize MCP, discover exactly two tools, list seven instruments/two + Documented profiles, and generate with explicit admitted AME or AGLP profile. +- Request MIDI-only with fallback=false and inspect the actual returned file + using DryWetMIDI: type1/960 PPQ, conductor/Lead, tempo/meter, 32 expected notes, + switch26 on0/off30, shared lead-in120 and end15480 for the standard PM example. +- Check native-request fallback produces one MIDI, disabled fallback produces + failure/no output, unavailable selected roles remain explicit, and existing + files are preserved. Stdout must contain protocol messages only. +- Confirm no source-tree loose DLL/catalog/cwd dependency is used at runtime. + If possible, launch a copy of the publish payload in an isolated task-owned + directory without build outputs to prove packaging rather than cwd luck. +- Document extraction/sidecars/symbols and OS/architecture assumptions. No + long-lived helper/server should be left running after validation. + +## Retained example + +Through the actual published stdio tool, generate a fresh example using: + +- description: `4 bars at 120 BPM in E minor, 4/4: palm-muted eighth-note lead` +- formats: `["mid"]` +- explicit profile: `ample-ame-documented-defaults-2026-10-20` +- fallbackToMidi: false +- output: the explicit repository artifacts\examples directory +- projectName: `ame-lead-example` + +Retain that generated file as a demonstration the owner can import, with its +Documented compatibility warning and no claim of actual Cubase/VST acceptance. +Verify read-back with the existing DryWetMIDI test infrastructure, not a second +handwritten parser. Never overwrite an existing user example blindly; if the +destination already exists, preserve it and choose/report a distinct new stem. +No fake/vendor MIDI or native fixture is to be copied into this deliverable. + +## Local client instructions + +- Document the absolute published executable command, stdio transport, no HTTP + URL, no shell wrapper requirement, and explicit profile selection. +- Include a copyable VS Code MCP configuration example (servers/type=stdio/ + command/args) and tool arguments for the supported MIDI-only example. +- Do not edit .vscode/mcp.json, user/global settings or register/start a service. +- Clearly state current capability limits: AGLP/AME documented-default Lead only, + five unavailable mappings, no AGP/SDP writer, default native formats trigger + explicit MIDI fallback, and documented mappings are not application-Verified. +- Explain ordinary launch/shutdown (client owns stdin/EOF/process), collisions, + cancellation boundary, output location and troubleshooting via stderr. + +## Runtime-free and application acceptance + +Self-contained publish must include its runtime, but running on the SDK machine +alone is NOT proof of a runtime-free Windows environment. Inspect publication +and, if useful, host tracing to distinguish bundled runtime use; do not present +setting DOTNET_ROOT to a fake path as equivalent to removing system runtimes. + +If no matching runtime-free machine is available, explicitly mark that check +pending. Likewise do not claim Cubase/Ample/SD3 import, audible playback or native +reopen was tested without actually having and operating those applications. +Do not install a container, VM, vendor product or system-wide dependency to +simulate those checks in this step. + +## Validation and mandatory report + +Run focused published-process tests with the actual published payload, then +Release solution build, the complete suite and locked restore. Record the +reproducible publish/test commands, actual file list/size, example read-back, +process readiness/exit evidence and any missing checks. + +When complete, write your end-of-step report to ./prompts/report_9.md including: what was implemented, test results (pass/fail with details), any issues encountered, and whether you're ready for the next step + +Exactly one plain triple-backtick fence encloses the entire report. Distinguish +supported-slice publication success from full requested-product completion. +Include exact artifact/example paths, commands/counts, architecture/extraction +facts and all runtime-free/licensed-app/native/mapping limitations. +Stop after the report for review; do not start further work. diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Articulations/ArticulationPlanner.cs b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Articulations/ArticulationPlanner.cs new file mode 100644 index 0000000..62f245b --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Articulations/ArticulationPlanner.cs @@ -0,0 +1,203 @@ +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition; +using MusicalComposition = GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition.Composition; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.Core.Articulations; + +public static class ArticulationPlanner +{ + private sealed record Resolved(int Pitch, int Velocity, long Start, long End, ArticulationRule Rule); + private sealed record Timed(Resolved Note, long Start, long End, long ControlStart, long Release); + + public static ArticulationPlanningResult Plan(MusicalComposition? composition, + IEnumerable? profiles, bool allowSynthetic = false) + { + var errors = CompositionValidator.Validate(composition) + .Select(e => new ArticulationDiagnostic(e.Code, e.Field, e.Message)).ToList(); + if (errors.Count != 0) + return new(null, errors); + var selected = (profiles ?? []).ToArray(); + foreach (var profile in selected) + errors.AddRange(InstrumentProfileValidator.Validate(profile, allowSynthetic)); + if (errors.Count != 0) + return new(null, errors); + var model = composition!; + foreach (var track in model.Tracks) + if (selected.Count(p => p.Role == track.Role) != 1) + errors.Add(new("missing_or_duplicate_profile", track.Role.ToString(), "Select exactly one documented or application-verified profile for each selected role.")); + if (selected.Any(p => !model.Tracks.Any(t => t.Role == p.Role))) + errors.Add(new("unused_profile", "profiles", "Supply profiles only for selected composition roles.")); + if (selected.Select(p => p.Channel).Distinct().Count() != selected.Length) + errors.Add(new("channel_collision", "profiles.channel", "Independently controlled role tracks require distinct MIDI channels.")); + if (selected.Select(p => p.Id).Distinct(StringComparer.Ordinal).Count() != selected.Length) + errors.Add(new("duplicate_profile_id", "profiles.id", "Select distinct profile IDs.")); + if (errors.Count != 0) + return new(null, errors); + + var resolved = new List<(InstrumentProfile Profile, List Notes)>(); + foreach (var track in model.Tracks.OrderBy(t => t.Role)) + { + var profile = selected.Single(p => p.Role == track.Role); + var notes = new List(); + foreach (var note in track.Notes) + { + var rule = profile.Rules.SingleOrDefault(r => r.Articulation == note.Articulation); + Resolve(note.Pitch, note.Velocity, note.Start, note.Duration, rule, profile, notes, errors); + } + foreach (var hit in track.Hits) + { + var rule = profile.Rules.SingleOrDefault(r => r.Voice == hit.Voice); + if (rule is null) + { + errors.Add(new("unmapped_drum_voice", profile.Id, $"Supply an evidence-backed mapping for {hit.Voice}.")); + continue; + } + Resolve(rule.DrumPitch!.Value, hit.Velocity, hit.Start, hit.Duration, rule, profile, notes, errors); + } + resolved.Add((profile, notes)); + } + if (errors.Count != 0) + return new(null, errors); + + var leadIn = resolved.SelectMany(t => t.Notes).Max(n => n.Rule.Keyswitch?.AdvanceTicks ?? 0); + var extent = model.MusicalExtent.ToTicks(); + var tracks = new List(); + try + { + var musicalEnd = checked(extent + leadIn); + foreach (var (profile, notes) in resolved) + { + var timed = notes.Select(n => + { + var start = checked(n.Start + leadIn); + var end = checked(n.End + leadIn); + var controlStart = checked(start - (n.Rule.Keyswitch?.AdvanceTicks ?? 0)); + var pulseEnd = checked(controlStart + (n.Rule.Keyswitch?.DurationTicks ?? 0)); + return new Timed(n, start, end, controlStart, Math.Max(end, pulseEnd)); + }).OrderBy(n => n.ControlStart).ThenBy(n => n.Start).ThenBy(n => n.Note.Pitch).ToArray(); + CheckStateConflicts(profile, timed, errors); + if (errors.Count == 0) + tracks.Add(BuildTrack(profile, timed, musicalEnd, errors)); + } + return errors.Count == 0 ? new(new MidiEventPlan(leadIn, extent, tracks), []) : new(null, errors); + } + catch (OverflowException) + { + errors.Add(new("arithmetic_overflow", "timing", "Reduce control advance/duration or musical extent to fit signed Int64 event ticks, including final resets.")); + return new(null, errors); + } + } + + private static void Resolve(int pitch, int velocity, BeatFraction start, BeatFraction duration, + ArticulationRule? rule, InstrumentProfile profile, List notes, + List errors) + { + if (rule is null) + { + errors.Add(new("unsupported_articulation", profile.Id, "Select a profile supporting the requested articulation; no sustain fallback is applied.")); + return; + } + if (pitch < profile.MinimumPitch || pitch > profile.MaximumPitch) + errors.Add(new("pitch_out_of_profile_range", profile.Id, $"Pitch {pitch} is outside the evidence-backed playable range.")); + if (velocity < rule.Velocity.Minimum || velocity > rule.Velocity.Maximum) + errors.Add(new("velocity_layer_conflict", profile.Id, $"Requested velocity {velocity} must be inside {rule.Velocity.Minimum}..{rule.Velocity.Maximum}; no clamping is performed.")); + notes.Add(new(pitch, rule.Velocity.OutputVelocity ?? velocity, start.ToTicks(), + (start + duration).ToTicks(), rule)); + } + + private static void CheckStateConflicts(InstrumentProfile profile, Timed[] notes, + List errors) + { + if (!profile.Rules.Any(r => r.Behavior != StateBehavior.None)) + return; + var active = new PriorityQueue(); + var states = new Dictionary(); + foreach (var note in notes) + { + while (active.TryPeek(out var previous, out var release) && release <= note.ControlStart) + { + active.Dequeue(); + if (--states[previous.Note.Rule] == 0) + states.Remove(previous.Note.Rule); + } + if (states.Keys.Any(r => !InstrumentProfileValidator.SameState(r, note.Note.Rule) || + r.Behavior == StateBehavior.Momentary || note.Note.Rule.Behavior == StateBehavior.Momentary)) + { + errors.Add(new("conflicting_articulation_state", profile.Id, + "Overlapping musical/control windows require incompatible channel-wide state or ambiguous momentary retriggers. Separate the notes or use a verified representable profile.")); + return; + } + states.TryGetValue(note.Note.Rule, out var count); + states[note.Note.Rule] = count + 1; + active.Enqueue(note, note.Release); + } + } + + private static PlannedMidiTrack BuildTrack(InstrumentProfile profile, Timed[] notes, long musicalEnd, + List errors) + { + var events = new List(); + var controllers = profile.InitialControllers.ToDictionary(c => c.Number, c => c.Value); + var initialKey = profile.InitialArticulation is { } initial + ? profile.Rules.SingleOrDefault(r => profile.Role != TrackRole.Drums && r.Articulation == initial)?.Keyswitch + : null; + (int Pitch, int Velocity)? switchState = initialKey is null ? null : (initialKey.Pitch, initialKey.Velocity); + foreach (var cc in profile.InitialControllers) + events.Add(new PlannedControlChange(0, profile.Channel, cc.Number, cc.Value, true)); + + void ChangeState(ArticulationRule rule, long tick, bool reset) + { + foreach (var cc in rule.Controllers) + if (rule.Behavior == StateBehavior.Momentary || controllers[cc.Number] != cc.Value) + { + events.Add(new PlannedControlChange(tick, profile.Channel, cc.Number, cc.Value, reset)); + controllers[cc.Number] = cc.Value; + } + if (rule.Keyswitch is { } key && + (rule.Behavior == StateBehavior.Momentary || switchState != (key.Pitch, key.Velocity))) + { + events.Add(new PlannedNoteOn(tick, profile.Channel, key.Pitch, key.Velocity, true)); + events.Add(new PlannedNoteOff(checked(tick + key.DurationTicks), profile.Channel, key.Pitch, true)); + switchState = (key.Pitch, key.Velocity); + } + } + + foreach (var note in notes) + { + var rule = note.Note.Rule; + if (rule.Behavior == StateBehavior.Momentary) + { + foreach (var cc in rule.Controllers) + { + events.Add(new PlannedControlChange(note.ControlStart, profile.Channel, cc.Number, cc.Value, false)); + events.Add(new PlannedControlChange(note.Release, profile.Channel, cc.Number, + controllers[cc.Number], true)); + } + if (rule.Keyswitch is { } key) + { + events.Add(new PlannedNoteOn(note.ControlStart, profile.Channel, key.Pitch, key.Velocity, true)); + events.Add(new PlannedNoteOff(note.Release, profile.Channel, key.Pitch, true)); + } + } + else if (rule.Behavior == StateBehavior.Latched) + ChangeState(rule, note.ControlStart, false); + events.Add(new PlannedNoteOn(note.Start, profile.Channel, note.Note.Pitch, note.Note.Velocity, false)); + events.Add(new PlannedNoteOff(note.End, profile.Channel, note.Note.Pitch, false)); + } + var finalTick = Math.Max(musicalEnd, events.Max(e => e.Tick)); + if (profile.FinalResetArticulation is { } reset) + ChangeState(profile.Rules.Single(r => r.Articulation == reset), finalTick, true); + foreach (var cc in profile.FinalControllers) + if (controllers[cc.Number] != cc.Value) + events.Add(new PlannedControlChange(finalTick, profile.Channel, cc.Number, cc.Value, true)); + var result = new PlannedMidiTrack(profile.Role, profile.Id, events); + var activePitches = new HashSet(); + foreach (var e in result.Events) + { + if (e is PlannedNoteOn on && !activePitches.Add(on.Pitch)) + errors.Add(new("overlapping_midi_pitch", profile.Id, $"Overlapping note-ons on pitch {on.Pitch} cannot be paired unambiguously on this channel.")); + if (e is PlannedNoteOff off && !activePitches.Remove(off.Pitch)) + errors.Add(new("unpaired_note_off", profile.Id, $"A note-off on pitch {off.Pitch} lacks an active note-on.")); + } + return result; + } +} diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Articulations/ArticulationPlanningResult.cs b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Articulations/ArticulationPlanningResult.cs new file mode 100644 index 0000000..5eaf923 --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Articulations/ArticulationPlanningResult.cs @@ -0,0 +1,16 @@ +namespace GAJ3T.MusicGen.RiffGrooveBuilder.Core.Articulations; + +public sealed record ArticulationDiagnostic(string Code, string Field, string Message); + +public sealed class ArticulationPlanningResult +{ + internal ArticulationPlanningResult(MidiEventPlan? plan, IEnumerable diagnostics) + { + Diagnostics = Array.AsReadOnly(diagnostics.ToArray()); + Plan = Diagnostics.Count == 0 ? plan : null; + } + + public bool Success => Plan is not null; + public MidiEventPlan? Plan { get; } + public IReadOnlyList Diagnostics { get; } +} diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Articulations/ArticulationRule.cs b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Articulations/ArticulationRule.cs new file mode 100644 index 0000000..8da9b50 --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Articulations/ArticulationRule.cs @@ -0,0 +1,34 @@ +using System.Text.Json.Serialization; +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.Core.Articulations; + +public enum StateBehavior { None, Latched, Momentary } + +public sealed record KeyswitchAction(int Pitch, int Velocity, long AdvanceTicks, long DurationTicks); +public sealed record VelocityLayer(int Minimum, int Maximum, int? OutputVelocity); + +public sealed class ArticulationRule +{ + [JsonConstructor] + public ArticulationRule(Articulation articulation, DrumVoice? voice, int? drumPitch, + StateBehavior behavior, KeyswitchAction? keyswitch, VelocityLayer velocity, + IReadOnlyList controllers) + { + Articulation = articulation; + Voice = voice; + DrumPitch = drumPitch; + Behavior = behavior; + Keyswitch = keyswitch; + Velocity = velocity; + Controllers = Array.AsReadOnly(controllers.ToArray()); + } + + public Articulation Articulation { get; } + public DrumVoice? Voice { get; } + public int? DrumPitch { get; } + public StateBehavior Behavior { get; } + public KeyswitchAction? Keyswitch { get; } + public VelocityLayer Velocity { get; } + public IReadOnlyList Controllers { get; } +} diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Articulations/InstrumentProfile.cs b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Articulations/InstrumentProfile.cs new file mode 100644 index 0000000..237411f --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Articulations/InstrumentProfile.cs @@ -0,0 +1,59 @@ +using System.Text.Json.Serialization; +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.Core.Articulations; + +public enum MappingVerification { Unverified, Verified, Synthetic, Documented } + +public sealed record MappingEvidence(MappingVerification Status, string Source, string Authorization, + string VerificationRecord); + +public sealed record MappingCompatibilityNotes(string VersionScope, string ConfigurationRequirements, + string RoutingPolicy, string TimingPolicy); + +public sealed record ControllerValue(int Number, int Value); + +public sealed class InstrumentProfile +{ + [JsonConstructor] + public InstrumentProfile(string id, string instrumentId, TrackRole role, string productName, string productVersion, + string mappingVersion, MappingEvidence evidence, int minimumPitch, int maximumPitch, int channel, + Articulation? initialArticulation, IReadOnlyList initialControllers, + Articulation? finalResetArticulation, IReadOnlyList finalControllers, + IReadOnlyList rules, MappingCompatibilityNotes? compatibilityNotes = null) + { + Id = id; + InstrumentId = instrumentId; + Role = role; + ProductName = productName; + ProductVersion = productVersion; + MappingVersion = mappingVersion; + Evidence = evidence; + MinimumPitch = minimumPitch; + MaximumPitch = maximumPitch; + Channel = channel; + InitialArticulation = initialArticulation; + InitialControllers = Array.AsReadOnly(initialControllers.ToArray()); + FinalResetArticulation = finalResetArticulation; + FinalControllers = Array.AsReadOnly(finalControllers.ToArray()); + Rules = Array.AsReadOnly(rules.ToArray()); + CompatibilityNotes = compatibilityNotes; + } + + public string Id { get; } + public string InstrumentId { get; } + public TrackRole Role { get; } + public string ProductName { get; } + public string ProductVersion { get; } + public string MappingVersion { get; } + public MappingEvidence Evidence { get; } + public int MinimumPitch { get; } + public int MaximumPitch { get; } + public int Channel { get; } + public Articulation? InitialArticulation { get; } + public IReadOnlyList InitialControllers { get; } + public Articulation? FinalResetArticulation { get; } + public IReadOnlyList FinalControllers { get; } + public IReadOnlyList Rules { get; } + public MappingCompatibilityNotes? CompatibilityNotes { get; } +} diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Articulations/InstrumentProfileValidator.cs b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Articulations/InstrumentProfileValidator.cs new file mode 100644 index 0000000..3c5c2ab --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Articulations/InstrumentProfileValidator.cs @@ -0,0 +1,169 @@ +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.Core.Articulations; + +public static class InstrumentProfileValidator +{ + public static IReadOnlyList Validate(InstrumentProfile? profile, + bool allowSynthetic = false) + { + var errors = new List(); + void Error(string code, string field, string message) => errors.Add(new(code, field, message)); + if (profile is null) + return new[] { new ArticulationDiagnostic("missing_profile", "profile", "Supply an explicit documented or application-verified matching profile.") }; + + if (string.IsNullOrWhiteSpace(profile.Id) || + profile.Id.Any(c => !char.IsAsciiLetterOrDigit(c) && c is not '-' and not '_' and not '.')) + Error("invalid_profile_id", "id", "Use a stable nonempty ASCII letter/digit, dash, underscore or dot ID."); + if (string.IsNullOrWhiteSpace(profile.InstrumentId) || + profile.InstrumentId.Any(c => !char.IsAsciiLetterOrDigit(c) && c is not '-' and not '_' and not '.')) + Error("invalid_instrument_id", "instrumentId", "Supply the declared instrument's stable ASCII letter/digit, dash, underscore or dot ID."); + foreach (var (field, value) in new[] { ("productName", profile.ProductName), + ("productVersion", profile.ProductVersion), ("mappingVersion", profile.MappingVersion) }) + if (string.IsNullOrWhiteSpace(value)) + Error("missing_identity", field, "Record the exact product identity, product version or explicit documented-default scope, and versioned mapping."); + if (!Enum.IsDefined(profile.Role)) + Error("invalid_role", "role", "Select lead, bass or drums."); + var evidence = profile.Evidence; + if (evidence is null || !Enum.IsDefined(evidence.Status) || + string.IsNullOrWhiteSpace(evidence.Source) || string.IsNullOrWhiteSpace(evidence.Authorization) || + string.IsNullOrWhiteSpace(evidence.VerificationRecord)) + Error("missing_evidence", "evidence", "Record authorized source provenance and a mapping verification record."); + if (evidence?.Status is not (MappingVerification.Verified or MappingVerification.Documented) && + !(allowSynthetic && evidence?.Status == MappingVerification.Synthetic)) + Error("unverified_profile", "evidence.status", "Obtain authorized documented or application-verified mappings; synthetic profiles require explicit test-only opt-in."); + if (evidence?.Status == MappingVerification.Documented && profile.CompatibilityNotes is null) + Error("missing_compatibility_notes", "compatibilityNotes", "Documented mappings require explicit version scope, configuration requirements, routing and timing policies."); + if (profile.CompatibilityNotes is { } notes) + foreach (var (field, value) in new[] { ("versionScope", notes.VersionScope), + ("configurationRequirements", notes.ConfigurationRequirements), ("routingPolicy", notes.RoutingPolicy), + ("timingPolicy", notes.TimingPolicy) }) + if (string.IsNullOrWhiteSpace(value) || value != value.Trim() || value.Any(char.IsControl)) + Error("invalid_compatibility_notes", "compatibilityNotes." + field, "Supply a nonempty trimmed compatibility disclosure without control characters."); + if (evidence?.Status == MappingVerification.Documented && + (!Uri.TryCreate(evidence.Source, UriKind.Absolute, out var source) || + source.Scheme is not ("http" or "https") || !string.IsNullOrEmpty(source.UserInfo))) + Error("invalid_documented_source", "evidence.source", "Cite a public absolute HTTP(S) mapping source without credentials."); + if (evidence?.Status == MappingVerification.Synthetic && + (profile.Id?.StartsWith("synthetic-", StringComparison.Ordinal) != true || + profile.ProductName?.StartsWith("Synthetic ", StringComparison.Ordinal) != true)) + Error("invalid_synthetic_identity", "id", "Test-only identities must start with synthetic- and product names with Synthetic ."); + if (profile.Channel is < 0 or > 15) + Error("invalid_channel", "channel", "Use an explicit zero-based MIDI channel 0..15."); + if (profile.MinimumPitch is < 0 or > 127 || profile.MaximumPitch is < 0 or > 127 || + profile.MinimumPitch > profile.MaximumPitch) + Error("invalid_pitch_range", "playableRange", "Use an inclusive ascending MIDI pitch range inside 0..127."); + + ValidateControllers(profile.InitialControllers, "initialControllers", errors); + ValidateControllers(profile.FinalControllers, "finalControllers", errors); + if (profile.Rules.Count == 0) + Error("missing_rules", "rules", "Provide supported articulation or drum voice rules."); + var keys = new HashSet<(Articulation, DrumVoice?)>(); + var drumPitches = new HashSet(); + for (var i = 0; i < profile.Rules.Count; i++) + { + var rule = profile.Rules[i]; + var field = $"rules[{i}]"; + if (rule is null) + { + Error("invalid_rule", field, "Replace the null rule."); + continue; + } + if (!Enum.IsDefined(rule.Articulation) || !Enum.IsDefined(rule.Behavior)) + Error("invalid_rule", field, "Use defined articulation and state behavior values."); + if (!keys.Add((rule.Articulation, rule.Voice))) + Error("duplicate_rule", field, "Keep one rule per articulation/voice."); + if (profile.Role == TrackRole.Drums) + { + if (rule.Articulation != Articulation.Sustain || rule.Voice is null || + !Enum.IsDefined(rule.Voice.Value) || rule.DrumPitch is null) + Error("invalid_drum_rule", field, "Map a defined logical drum voice to an absolute pitch using sustain intention."); + if (rule.DrumPitch is int pitch && (pitch < profile.MinimumPitch || pitch > profile.MaximumPitch || + pitch is < 0 or > 127 || !drumPitches.Add(pitch))) + Error("invalid_drum_pitch", field, "Use distinct mapped pitches inside the playable MIDI range."); + } + else if (rule.Voice is not null || rule.DrumPitch is not null) + Error("invalid_pitched_rule", field, "Pitched roles must not contain drum mappings."); + if (rule.Velocity is not { } velocity || velocity.Minimum is < 1 or > 127 || + velocity.Maximum is < 1 or > 127 || velocity.Minimum > velocity.Maximum || + (velocity.OutputVelocity is int output && (output < velocity.Minimum || output > velocity.Maximum))) + Error("invalid_velocity_layer", field + ".velocity", "Use inclusive requested velocity bounds 1..127; an explicit output must lie within that layer."); + if (rule.Keyswitch is { } key) + { + if (key.Pitch is < 0 or > 127 || key.Velocity is < 1 or > 127 || + key.AdvanceTicks < 0 || key.DurationTicks <= 0) + Error("invalid_keyswitch", field + ".keyswitch", "Use pitch 0..127, velocity 1..127, nonnegative advance and positive duration ticks."); + if (key.Pitch >= profile.MinimumPitch && key.Pitch <= profile.MaximumPitch) + Error("keyswitch_collision", field + ".keyswitch", "Keep control notes outside the entire playable range."); + } + ValidateControllers(rule.Controllers, field + ".controllers", errors); + var controls = rule.Keyswitch is not null || rule.Controllers.Count != 0; + if ((rule.Behavior == StateBehavior.None) == controls) + Error("invalid_state_behavior", field, "Use None only without controls; controls require explicit latched or momentary behavior."); + } + if (errors.Count != 0) + return errors.AsReadOnly(); + + var rules = profile.Rules; + var behaviors = rules.Where(r => r.Behavior != StateBehavior.None).Select(r => r.Behavior).Distinct().ToArray(); + if (behaviors.Length > 1) + Error("mixed_state_behavior", "rules", "A channel cannot mix latched and momentary control schemes."); + var numbers = rules.SelectMany(r => r.Controllers).Select(c => c.Number).ToHashSet(); + if (!numbers.SetEquals(profile.InitialControllers.Select(c => c.Number)) || + profile.FinalControllers.Any(c => !numbers.Contains(c.Number))) + Error("incomplete_controller_state", "initialControllers", "Declare every controlled CC initially; final resets may reference only these CCs."); + foreach (var rule in rules) + { + if (rule.Behavior != StateBehavior.None && !numbers.SetEquals(rule.Controllers.Select(c => c.Number))) + Error("incomplete_controller_state", "rules", "Each controlled rule must specify the complete channel-wide CC state."); + if (behaviors.Contains(StateBehavior.Latched) && + (rule.Behavior != StateBehavior.Latched || + (rules.Any(r => r.Keyswitch is not null) && rule.Keyswitch is null))) + Error("incomplete_latched_state", "rules", "Every latched articulation must explicitly restore all controls, including a keyswitch if used."); + } + if (profile.Role == TrackRole.Drums) + { + if (profile.InitialArticulation is not null || profile.FinalResetArticulation is not null || + rules.Any(r => r.Keyswitch is not null)) + Error("invalid_drum_state", "initialArticulation", "Drum profiles use explicit CC state and voice pitches, not pitched-articulation keyswitch state."); + } + else + { + var initial = rules.SingleOrDefault(r => r.Articulation == profile.InitialArticulation); + if (profile.InitialArticulation is not null && (initial is null || initial.Behavior == StateBehavior.Momentary || + (initial.Behavior == StateBehavior.None && numbers.Count != 0 && + behaviors.Contains(StateBehavior.Latched)) || + initial.Controllers.Any(c => !profile.InitialControllers.Contains(c)))) + Error("invalid_initial_state", "initialArticulation", "Use null for unknown receiver articulation, or a supported known resting articulation with matching initial CC values, never a held momentary action."); + if (profile.FinalResetArticulation is { } reset && + !rules.Any(r => r.Articulation == reset && r.Behavior == StateBehavior.Latched)) + Error("invalid_final_reset", "finalResetArticulation", "A requested final articulation reset must reference an explicit latched rule."); + if (profile.FinalResetArticulation is { } final && + rules.SingleOrDefault(r => r.Articulation == final) is { } finalRule && + profile.FinalControllers.Any(c => finalRule.Controllers.Any(v => v.Number == c.Number && v.Value != c.Value))) + Error("conflicting_final_reset", "finalControllers", "Final CC values must not contradict the requested final articulation."); + } + for (var i = 0; i < rules.Count; i++) + for (var j = i + 1; j < rules.Count; j++) + if (rules[i].Voice == rules[j].Voice && SameState(rules[i], rules[j]) && + Math.Max(rules[i].Velocity.Minimum, rules[j].Velocity.Minimum) <= + Math.Min(rules[i].Velocity.Maximum, rules[j].Velocity.Maximum)) + Error("ambiguous_velocity_layers", "rules", "Different articulations with identical controls need disjoint velocity layers."); + return errors.AsReadOnly(); + } + + internal static bool SameState(ArticulationRule a, ArticulationRule b) => + a.Behavior == b.Behavior && a.Keyswitch?.Pitch == b.Keyswitch?.Pitch && + a.Keyswitch?.Velocity == b.Keyswitch?.Velocity && + a.Controllers.Count == b.Controllers.Count && a.Controllers.All(b.Controllers.Contains); + + private static void ValidateControllers(IReadOnlyList values, string field, + List errors) + { + var numbers = new HashSet(); + foreach (var value in values) + if (value is null || value.Number is < 0 or > 127 || value.Value is < 0 or > 127 || + !numbers.Add(value.Number)) + errors.Add(new("invalid_controller", field, "Use unique CC numbers and values in 0..127.")); + } +} diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Articulations/PlannedMidiEvent.cs b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Articulations/PlannedMidiEvent.cs new file mode 100644 index 0000000..973fead --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Articulations/PlannedMidiEvent.cs @@ -0,0 +1,58 @@ +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.Core.Articulations; + +public abstract record PlannedMidiEvent(long Tick, int Channel) +{ + public abstract int Priority { get; } +} + +public sealed record PlannedNoteOn(long Tick, int Channel, int Pitch, int Velocity, bool IsKeyswitch) + : PlannedMidiEvent(Tick, Channel) +{ + public override int Priority => IsKeyswitch ? 2 : 3; +} + +public sealed record PlannedNoteOff(long Tick, int Channel, int Pitch, bool IsKeyswitch) + : PlannedMidiEvent(Tick, Channel) +{ + public override int Priority => 0; +} + +public sealed record PlannedControlChange(long Tick, int Channel, int Number, int Value, bool IsReset) + : PlannedMidiEvent(Tick, Channel) +{ + public override int Priority => IsReset ? 1 : 2; +} + +public sealed class PlannedMidiTrack +{ + internal PlannedMidiTrack(TrackRole role, string profileId, IEnumerable events) + { + Role = role; + ProfileId = profileId; + Events = Array.AsReadOnly(events.OrderBy(e => e.Tick).ThenBy(e => e.Priority).ToArray()); + } + + public TrackRole Role { get; } + public string ProfileId { get; } + public IReadOnlyList Events { get; } +} + +public sealed class MidiEventPlan +{ + internal MidiEventPlan(long leadInTicks, long musicalExtentTicks, IEnumerable tracks) + { + LeadInTicks = leadInTicks; + MusicalExtentTicks = musicalExtentTicks; + MusicalEndTick = checked(leadInTicks + musicalExtentTicks); + Tracks = Array.AsReadOnly(tracks.ToArray()); + EndTick = Math.Max(MusicalEndTick, Tracks.SelectMany(t => t.Events).Max(e => e.Tick)); + } + + public long LeadInTicks { get; } + public long MusicalExtentTicks { get; } + public long MusicalEndTick { get; } + public long EndTick { get; } + public IReadOnlyList Tracks { get; } +} diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Composition/BeatFraction.cs b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Composition/BeatFraction.cs new file mode 100644 index 0000000..6e66bda --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Composition/BeatFraction.cs @@ -0,0 +1,76 @@ +using System.Globalization; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition; + +public readonly struct BeatFraction : IEquatable, IComparable +{ + public const int TicksPerQuarterNote = 960; + private readonly long denominator; + + public BeatFraction(long numerator, long denominator = 1) + { + if (denominator <= 0) + throw new ArgumentOutOfRangeException(nameof(denominator), "Use a positive denominator."); + var normalized = Normalize(numerator, denominator); + Numerator = normalized.Numerator; + this.denominator = normalized.Denominator; + } + + public long Numerator { get; } + public long Denominator => denominator == 0 ? 1 : denominator; + public static BeatFraction Zero => default; + + public long ToTicks() + { + var scaled = checked((Int128)Numerator * TicksPerQuarterNote); + if (scaled % Denominator != 0) + throw new ArgumentException("Timing must be exactly representable at 960 PPQ."); + return checked((long)(scaled / Denominator)); + } + + public int CompareTo(BeatFraction other) => + checked((Int128)Numerator * other.Denominator).CompareTo( + checked((Int128)other.Numerator * Denominator)); + + public bool Equals(BeatFraction other) => + Numerator == other.Numerator && Denominator == other.Denominator; + public override bool Equals(object? obj) => obj is BeatFraction other && Equals(other); + public override int GetHashCode() => HashCode.Combine(Numerator, Denominator); + public override string ToString() => string.Create(CultureInfo.InvariantCulture, $"{Numerator}/{Denominator}"); + + public static BeatFraction operator +(BeatFraction a, BeatFraction b) => + FromWide(checked((Int128)a.Numerator * b.Denominator + (Int128)b.Numerator * a.Denominator), + checked((Int128)a.Denominator * b.Denominator)); + public static BeatFraction operator -(BeatFraction a, BeatFraction b) => + FromWide(checked((Int128)a.Numerator * b.Denominator - (Int128)b.Numerator * a.Denominator), + checked((Int128)a.Denominator * b.Denominator)); + public static BeatFraction operator *(BeatFraction a, long b) => + FromWide(checked((Int128)a.Numerator * b), a.Denominator); + public static BeatFraction operator /(BeatFraction a, long b) + { + if (b <= 0) + throw new ArgumentOutOfRangeException(nameof(b), "Use a positive divisor."); + return FromWide(a.Numerator, checked((Int128)a.Denominator * b)); + } + public static bool operator ==(BeatFraction a, BeatFraction b) => a.Equals(b); + public static bool operator !=(BeatFraction a, BeatFraction b) => !a.Equals(b); + public static bool operator <(BeatFraction a, BeatFraction b) => a.CompareTo(b) < 0; + public static bool operator >(BeatFraction a, BeatFraction b) => a.CompareTo(b) > 0; + public static bool operator <=(BeatFraction a, BeatFraction b) => a.CompareTo(b) <= 0; + public static bool operator >=(BeatFraction a, BeatFraction b) => a.CompareTo(b) >= 0; + + private static (long Numerator, long Denominator) Normalize(Int128 numerator, Int128 denominator) + { + var a = Int128.Abs(numerator); + var b = denominator; + while (b != 0) + (a, b) = (b, a % b); + return (checked((long)(numerator / a)), checked((long)(denominator / a))); + } + + private static BeatFraction FromWide(Int128 numerator, Int128 denominator) + { + var normalized = Normalize(numerator, denominator); + return new BeatFraction(normalized.Numerator, normalized.Denominator); + } +} diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Composition/Composition.cs b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Composition/Composition.cs new file mode 100644 index 0000000..a923dc8 --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Composition/Composition.cs @@ -0,0 +1,23 @@ +namespace GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition; + +public sealed class Composition +{ + public Composition(double tempoBpm, TimeSignature meter, MusicalKey key, int bars, + IEnumerable tracks, IEnumerable? defaultsApplied = null) + { + TempoBpm = tempoBpm; + Meter = meter; + Key = key; + Bars = bars; + Tracks = Array.AsReadOnly(tracks.ToArray()); + DefaultsApplied = Array.AsReadOnly((defaultsApplied ?? []).ToArray()); + } + + public double TempoBpm { get; } + public TimeSignature Meter { get; } + public MusicalKey Key { get; } + public int Bars { get; } + public IReadOnlyList Tracks { get; } + public IReadOnlyList DefaultsApplied { get; } + public BeatFraction MusicalExtent => Meter.BarLength * Bars; +} diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Composition/CompositionDiagnostic.cs b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Composition/CompositionDiagnostic.cs new file mode 100644 index 0000000..4178fca --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Composition/CompositionDiagnostic.cs @@ -0,0 +1,3 @@ +namespace GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition; + +public sealed record CompositionDiagnostic(string Code, string Field, string Message, string? Phrase = null); diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Composition/CompositionPlanner.cs b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Composition/CompositionPlanner.cs new file mode 100644 index 0000000..e4dac36 --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Composition/CompositionPlanner.cs @@ -0,0 +1,115 @@ +using static GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition.CompositionValidator; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition; + +public static class CompositionPlanner +{ + public static CompositionPlanningResult Plan(string? description) + { + var parsed = DescriptionParser.Parse(description); + return parsed.Description is { } value ? Plan(value) : new(null, parsed.Diagnostics); + } + + public static CompositionPlanningResult Plan(ParsedDescription description) + { + ArgumentNullException.ThrowIfNull(description); + var errors = ValidateSettings(description.TempoBpm, description.Bars, description.Meter, description.Key); + if (errors.Count != 0) + return new(null, errors); + var preflight = Preflight(description); + if (preflight is not null) + return new(null, [preflight]); + + var barLength = description.Meter.BarLength; + var barTicks = barLength.ToTicks(); + var tracks = new List(); + foreach (var pitched in description.PitchedPatterns) + { + var perBar = CountPerBar(pitched.Pattern, barTicks); + var duration = pitched.Pattern == NotePattern.Sustained ? barLength : Subdivision(pitched.Pattern); + var notes = new List(checked((int)(perBar * description.Bars))); + var pitch = (pitched.Role == TrackRole.Lead ? 60 : 36) + description.Key.RootPitchClass; + for (var bar = 0; bar < description.Bars; bar++) + { + var start = barLength * bar; + for (long i = 0; i < perBar; i++) + notes.Add(new(pitch, start + duration * i, duration, 96, pitched.Articulation)); + } + tracks.Add(new(pitched.Role, notes)); + } + if (description.DrumPatterns.Count != 0) + { + var hits = new List(); + for (var bar = 0; bar < description.Bars; bar++) + { + var start = barLength * bar; + foreach (var drum in description.DrumPatterns) + { + if (drum.Subdivision is { } pattern) + { + var step = Subdivision(pattern); + var perBar = CountPerBar(pattern, barTicks); + for (long i = 0; i < perBar; i++) + hits.Add(new(drum.Voice, start + step * i, step, 96)); + } + else + { + var beat = description.Meter.BeatLength; + foreach (var number in drum.Beats) + hits.Add(new(drum.Voice, start + beat * (number - 1), beat, 96)); + } + } + } + tracks.Add(new(TrackRole.Drums, hits: hits.OrderBy(hit => hit.Start).ThenBy(hit => hit.Voice))); + } + var composition = new Composition(description.TempoBpm, description.Meter, description.Key, + description.Bars, tracks, description.DefaultsApplied); + return new(composition, Validate(composition)); + } + + private static CompositionDiagnostic? Preflight(ParsedDescription description) + { + try + { + var barLength = description.Meter.BarLength; + var barTicks = barLength.ToTicks(); + _ = (barLength * description.Bars).ToTicks(); + long count = 0; + foreach (var pitched in description.PitchedPatterns) + count = checked(count + checked(CountPerBar(pitched.Pattern, barTicks) * description.Bars)); + foreach (var drum in description.DrumPatterns) + { + var perBar = drum.Subdivision is { } pattern ? CountPerBar(pattern, barTicks) : drum.Beats.Count; + count = checked(count + checked(perBar * description.Bars)); + } + if (count > GeneratedEventLimit) + return EventLimitError(); + return null; + } + catch (ArgumentException) + { + return Error("unrepresentable_pattern", "pattern", "Choose a subdivision that divides the complete bar exactly at 960 PPQ."); + } + catch (OverflowException) + { + return Error("arithmetic_overflow", "events", "Reduce bar count/density or timing values to fit checked integer bounds."); + } + } + + private static long CountPerBar(NotePattern pattern, long barTicks) + { + if (pattern == NotePattern.Sustained) return 1; + var step = Subdivision(pattern).ToTicks(); + if (barTicks % step != 0) + throw new ArgumentException("The pattern must divide the bar exactly."); + return barTicks / step; + } + + private static BeatFraction Subdivision(NotePattern pattern) => pattern switch + { + NotePattern.Quarter => new(1), + NotePattern.Eighth => new(1, 2), + NotePattern.Sixteenth => new(1, 4), + _ => throw new ArgumentException("Use a supported repeated-note subdivision.", nameof(pattern)) + }; +} diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Composition/CompositionPlanningResult.cs b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Composition/CompositionPlanningResult.cs new file mode 100644 index 0000000..1ffc987 --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Composition/CompositionPlanningResult.cs @@ -0,0 +1,14 @@ +namespace GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition; + +public sealed class CompositionPlanningResult +{ + internal CompositionPlanningResult(Composition? composition, IEnumerable diagnostics) + { + Diagnostics = Array.AsReadOnly(diagnostics.ToArray()); + Composition = Diagnostics.Count == 0 ? composition : null; + } + + public bool Success => Composition is not null; + public Composition? Composition { get; } + public IReadOnlyList Diagnostics { get; } +} diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Composition/CompositionValidator.cs b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Composition/CompositionValidator.cs new file mode 100644 index 0000000..054bdf4 --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Composition/CompositionValidator.cs @@ -0,0 +1,143 @@ +namespace GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition; + +public static class CompositionValidator +{ + internal const int GeneratedEventLimit = 100_000; + + public static IReadOnlyList Validate(Composition? composition) + { + if (composition is null) + return new[] { Error("invalid_composition", "composition", "Supply a composition to validate.") }; + + var errors = ValidateSettings(composition.TempoBpm, composition.Bars, composition.Meter, composition.Key); + if (errors.Count != 0) + return errors.AsReadOnly(); + + var extent = composition.MusicalExtent; + if (composition.Tracks.Count is < 1 or > 3) + errors.Add(Error("invalid_roles", "tracks", "Select one to three distinct lead, bass or drums tracks.")); + var roles = new HashSet(); + long eventCount = 0; + foreach (var track in composition.Tracks) + { + if (track is null) + { + errors.Add(Error("invalid_track", "tracks", "Replace the null track with a selected role track.")); + continue; + } + eventCount = checked(eventCount + track.Notes.Count + track.Hits.Count); + if (eventCount > GeneratedEventLimit) + return new[] { EventLimitError() }; + if (!Enum.IsDefined(track.Role) || !roles.Add(track.Role)) + errors.Add(Error("invalid_roles", "tracks", "Use only distinct lead, bass and drums roles.")); + } + foreach (var track in composition.Tracks) + { + if (track is null) + continue; + var field = track.Role.ToString().ToLowerInvariant(); + if (track.Notes.Count + track.Hits.Count == 0) + errors.Add(Error("empty_track", field, "Provide at least one note or hit for every selected role.")); + if ((track.Role == TrackRole.Drums && track.Notes.Count != 0) || + (track.Role != TrackRole.Drums && track.Hits.Count != 0)) + errors.Add(Error("event_kind_mismatch", field, "Drums hold logical hits; lead and bass hold pitched notes.")); + for (var i = 0; i < track.Notes.Count; i++) + { + var note = track.Notes[i]; + var path = $"{field}.notes[{i}]"; + if (note is null) + { + errors.Add(Error("invalid_note", path, "Replace the null note with a musical note.")); + continue; + } + if (note.Pitch is < 0 or > 127) + errors.Add(Error("invalid_pitch", $"{path}.pitch", "Use an absolute MIDI pitch from 0 through 127.")); + if (!Enum.IsDefined(note.Articulation)) + errors.Add(Error("invalid_articulation", $"{path}.articulation", "Use sustain or palm-mute intention.")); + ValidateEvent(note.Start, note.Duration, note.Velocity, extent, path, errors); + } + for (var i = 0; i < track.Hits.Count; i++) + { + var hit = track.Hits[i]; + var path = $"{field}.hits[{i}]"; + if (hit is null) + { + errors.Add(Error("invalid_hit", path, "Replace the null hit with a logical drum hit.")); + continue; + } + if (!Enum.IsDefined(hit.Voice)) + errors.Add(Error("invalid_drum_voice", $"{path}.voice", "Use kick, snare or closed hi-hat.")); + ValidateEvent(hit.Start, hit.Duration, hit.Velocity, extent, path, errors); + } + } + return errors.AsReadOnly(); + } + + internal static List ValidateSettings(double tempo, int bars, TimeSignature meter, MusicalKey key) + { + var errors = new List(); + var microseconds = 60_000_000d / tempo; + if (!double.IsFinite(tempo) || tempo <= 0 || microseconds < 1 || microseconds > 0xFFFFFF) + errors.Add(Error("invalid_tempo", "tempoBpm", "Use positive finite BPM with SMF tempo in 1..16,777,215 microseconds per quarter.")); + if (bars <= 0) + errors.Add(Error("invalid_bars", "bars", "Use a positive Int32 bar count.")); + if (key.RootPitchClass is < 0 or > 11 || !Enum.IsDefined(key.Mode)) + errors.Add(Error("invalid_key", "key", "Use a normalized pitch class 0..11 and major or minor mode.")); + if (meter.Numerator is < 1 or > 255 || meter.Denominator <= 0 || + (meter.Denominator & (meter.Denominator - 1)) != 0) + { + errors.Add(Error("invalid_meter", "meter", "Use numerator 1..255 and a positive power-of-two denominator.")); + } + else + { + try + { + _ = meter.BeatLength.ToTicks(); + _ = (meter.BarLength * bars).ToTicks(); + } + catch (ArgumentException) + { + errors.Add(Error("unrepresentable_timing", "meter", "Use a denominator beat exactly representable at 960 PPQ (denominator 1..256).")); + } + catch (OverflowException) + { + errors.Add(Error("arithmetic_overflow", "bars", "Reduce the arrangement extent to fit signed Int64 ticks.")); + } + } + return errors; + } + + private static void ValidateEvent(BeatFraction start, BeatFraction duration, int velocity, + BeatFraction extent, string field, List errors) + { + if (velocity is < 1 or > 127) + errors.Add(Error("invalid_velocity", $"{field}.velocity", "Use a sounding velocity from 1 through 127.")); + if (start < BeatFraction.Zero) + errors.Add(Error("invalid_start", $"{field}.start", "Use a nonnegative musical start.")); + if (duration <= BeatFraction.Zero) + errors.Add(Error("invalid_duration", $"{field}.duration", "Use a strictly positive duration.")); + try + { + _ = start.ToTicks(); + _ = duration.ToTicks(); + var end = start + duration; + _ = end.ToTicks(); + if (start >= extent || end > extent) + errors.Add(Error("event_out_of_bounds", field, "Fit the complete note/hit, including its end, inside the declared bars.")); + } + catch (ArgumentException) + { + errors.Add(Error("unrepresentable_timing", field, "Use start/duration fractions exactly representable at 960 PPQ.")); + } + catch (OverflowException) + { + errors.Add(Error("arithmetic_overflow", field, "Reduce timing values to fit signed Int64 fractions and ticks.")); + } + } + + internal static CompositionDiagnostic EventLimitError() => + Error("event_limit_exceeded", "events", $"Reduce bars/pattern density to at most {GeneratedEventLimit} notes plus hits."); + + internal static CompositionDiagnostic Error(string code, string field, string message, string? phrase = null) => + new(code, field, message, phrase); +} diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Composition/DescriptionParser.cs b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Composition/DescriptionParser.cs new file mode 100644 index 0000000..930609b --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Composition/DescriptionParser.cs @@ -0,0 +1,366 @@ +using System.Globalization; +using System.Text.RegularExpressions; +using static GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition.CompositionValidator; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition; + +public static class DescriptionParser +{ + public static DescriptionParseResult Parse(string? text) + { + if (string.IsNullOrWhiteSpace(text)) + return new(null, [Error("empty_description", "description", "Supply at least one supported setting or role clause.")]); + if (text.Length > 16_384) + return new(null, [Error("description_too_long", "description", "Limit the description to 16,384 characters.")]); + return new Reader(text).Parse(); + } + + private sealed class Reader + { + private readonly string source; + private readonly Match[] tokens; + private readonly List errors = []; + private readonly Dictionary pitched = []; + private readonly Dictionary drums = []; + private readonly HashSet roles = []; + private int position; + private int? tempo; + private int? bars; + private TimeSignature? meter; + private MusicalKey? key; + + internal Reader(string source) + { + this.source = source; + tokens = Regex.Matches(source, + @"[0-9]+(?:\.[0-9]+)*(?:[eE][+-]?[0-9]+)?|[A-Za-z]+|[^\s]", + RegexOptions.CultureInvariant | RegexOptions.NonBacktracking).ToArray(); + } + + internal DescriptionParseResult Parse() + { + Take("generate"); + var clauses = 0; + while (position < tokens.Length) + { + while (IsPunctuation(Current)) + position++; + if (position == tokens.Length) + break; + if (clauses > 0 && Take("and") && position == tokens.Length) + { + Unsupported(); + break; + } + var start = position; + if (!TrySetting() && !TryPitched() && !TryDrum()) + { + position = start; + Unsupported(); + break; + } + clauses++; + if (errors.Count != 0) + break; + } + if (errors.Count != 0) + return new(null, errors); + if (clauses == 0) + return new(null, [Error("empty_description", "description", "Supply at least one supported setting or role clause.", source)]); + + var defaults = new List(); + if (tempo is null) defaults.Add(new("tempoBpm", "120")); + if (bars is null) defaults.Add(new("bars", "4")); + if (meter is null) defaults.Add(new("meter", "4/4")); + if (key is null) defaults.Add(new("key", "E minor")); + var actualMeter = meter ?? new(4, 4); + errors.AddRange(ValidateSettings(tempo ?? 120, bars ?? 4, actualMeter, key ?? new(4, KeyMode.Minor))); + if (roles.Count == 0) + { + roles.UnionWith([TrackRole.Lead, TrackRole.Bass, TrackRole.Drums]); + defaults.Add(new("roles", "lead,bass,drums")); + } + var patterns = new List(); + foreach (var role in new[] { TrackRole.Lead, TrackRole.Bass }) + { + if (!roles.Contains(role)) + continue; + pitched.TryGetValue(role, out var raw); + var name = role.ToString().ToLowerInvariant(); + var pattern = raw?.Pattern ?? (role == TrackRole.Lead ? NotePattern.Eighth : NotePattern.Sustained); + if (raw?.Pattern is null) defaults.Add(new($"{name}.pattern", PatternName(pattern))); + if (raw?.Articulation is null) defaults.Add(new($"{name}.articulation", "sustain")); + defaults.Add(new($"{name}.rootOctave", role == TrackRole.Lead ? "4" : "2")); + defaults.Add(new($"{name}.velocity", "96")); + patterns.Add(new(role, pattern, raw?.Articulation ?? Articulation.Sustain)); + } + if (roles.Contains(TrackRole.Drums)) + { + defaults.Add(new("drums.velocity", "96")); + if (drums.Count == 0) + { + if (actualMeter != new TimeSignature(4, 4)) + errors.Add(Error("explicit_drums_required", "drums", "For non-4/4 meters supply explicit kick/snare beats or closed hi-hat subdivision.")); + else + { + drums.Add(DrumVoice.Kick, new(DrumVoice.Kick, [1, 3], null)); + drums.Add(DrumVoice.Snare, new(DrumVoice.Snare, [2, 4], null)); + drums.Add(DrumVoice.ClosedHiHat, new(DrumVoice.ClosedHiHat, null, NotePattern.Eighth)); + defaults.AddRange([ + new("drums.kick", "beats 1 and 3"), + new("drums.snare", "beats 2 and 4"), + new("drums.closedHiHat", "eighth notes")]); + } + } + foreach (var drum in drums.Values) + { + if (drum.Beats.Any(beat => beat < 1 || beat > actualMeter.Numerator)) + errors.Add(Error("invalid_beat", $"drums.{drum.Voice}", "Use numbered denominator-note beats within the meter numerator.")); + } + } + if (errors.Count != 0) + return new(null, errors); + return new(new ParsedDescription(tempo ?? 120, bars ?? 4, actualMeter, + key ?? new(4, KeyMode.Minor), patterns, drums.Values.OrderBy(drum => drum.Voice), defaults), []); + } + + private bool TrySetting() + { + var start = position; + var hasAt = Take("at"); + if (IsInteger(Current) && Peek(1) == "bpm") + { + var value = ReadInteger("tempoBpm"); + Take("bpm"); + Set(ref tempo, value, "tempoBpm", start); + return true; + } + position = start; + if (hasAt) + return false; + if ((IsInteger(Current) || WordNumber(Current) != 0) && Peek(1) is "bar" or "bars") + { + var value = WordNumber(Current); + if (value == 0) value = ReadInteger("bars"); + else position++; + position++; + Set(ref bars, value, "bars", start); + return true; + } + if (IsInteger(Current) && Peek(1) == "/") + { + var numerator = ReadInteger("meter.numerator"); + position++; + var denominator = ReadInteger("meter.denominator"); + Set(ref meter, new TimeSignature(numerator, denominator), "meter", start); + return true; + } + Take("in"); + if (TryRoot(out var root) && Current is "major" or "minor") + { + var mode = Take("major") ? KeyMode.Major : KeyMode.Minor; + if (mode == KeyMode.Minor) Take("minor"); + Set(ref key, new MusicalKey(root, mode), "key", start); + return true; + } + position = start; + return false; + } + + private bool TryPitched() + { + var start = position; + var articulation = ReadArticulation(); + var pattern = ReadPattern(); + var hasPrefix = position != start; + if (!ReadRole(out var role)) + { + position = start; + return false; + } + if (!hasPrefix) + { + articulation = ReadArticulation(); + pattern = ReadPattern(); + } + var raw = new RawPitched(pattern, articulation); + if (pitched.TryGetValue(role, out var previous) && previous != raw) + errors.Add(Error("conflicting_clause", role.ToString().ToLowerInvariant(), "Supply one consistent pattern/articulation clause for this role.", Phrase(start))); + else + pitched[role] = raw; + roles.Add(role); + return true; + } + + private bool TryDrum() + { + if (Take("drums")) + { + roles.Add(TrackRole.Drums); + return true; + } + var start = position; + DrumVoice voice; + DrumPattern pattern; + if (Take("kick")) voice = DrumVoice.Kick; + else if (Take("snare")) voice = DrumVoice.Snare; + else if (TakePhrase("closed hi hat", true)) + { + var subdivision = ReadSubdivision(); + if (subdivision is null) + { + errors.Add(Error("invalid_drum_pattern", "drums.closedHiHat", "Specify quarter, eighth or sixteenth notes.", Phrase(start))); + return true; + } + AddDrum(new(DrumVoice.ClosedHiHat, null, subdivision), start); + return true; + } + else return false; + if (!Take("on") || !(Take("beats") || Take("beat"))) + { + errors.Add(Error("invalid_drum_pattern", $"drums.{voice}", "Use 'on beat(s)' followed by numbered beats.", Phrase(start))); + return true; + } + var beats = new List { ReadInteger("drums.beats") }; + while (Current == "and" && IsInteger(Peek(1))) + { + position++; + beats.Add(ReadInteger("drums.beats")); + } + if (beats.Distinct().Count() != beats.Count) + errors.Add(Error("duplicate_beat", "drums.beats", "List each numbered beat once.", Phrase(start))); + pattern = new(voice, beats.Order(), null); + AddDrum(pattern, start); + return true; + } + + private void AddDrum(DrumPattern pattern, int start) + { + if (drums.TryGetValue(pattern.Voice, out var previous) && + (previous.Subdivision != pattern.Subdivision || !previous.Beats.SequenceEqual(pattern.Beats))) + errors.Add(Error("conflicting_clause", $"drums.{pattern.Voice}", "Supply one consistent placement/subdivision for this drum voice.", Phrase(start))); + else drums[pattern.Voice] = pattern; + roles.Add(TrackRole.Drums); + } + + private bool ReadRole(out TrackRole role) + { + role = TrackRole.Lead; + if (Take("lead")) { Take("guitar"); return true; } + if (Take("guitar")) return true; + role = TrackRole.Bass; + return Take("bass"); + } + + private Articulation? ReadArticulation() + { + if (Take("sustain")) return Articulation.Sustain; + if (TakePhrase("palm muted", true) || TakePhrase("palm mute", true)) return Articulation.PalmMute; + return null; + } + + private NotePattern? ReadPattern() + { + var pattern = Take("sustained") ? NotePattern.Sustained : ReadSubdivision(); + if (pattern is not null) + { + if (!TakePhrase("root note", true)) + TakePhrase("root notes", true); + } + return pattern; + } + + private NotePattern? ReadSubdivision() + { + var start = position; + NotePattern? result = Take("quarter") ? NotePattern.Quarter : + Take("eighth") ? NotePattern.Eighth : Take("sixteenth") ? NotePattern.Sixteenth : null; + if (result is null) return null; + Take("-"); + if (Take("note") || Take("notes")) return result; + position = start; + return null; + } + + private bool TryRoot(out int pitchClass) + { + pitchClass = 0; + var token = Current; + if (token.Length is < 1 or > 2 || token[0] is < 'a' or > 'g' || + (token.Length == 2 && token[1] != 'b')) + return false; + var natural = token[0] switch { 'c' => 0, 'd' => 2, 'e' => 4, 'f' => 5, 'g' => 7, 'a' => 9, _ => 11 }; + position++; + var accidental = token.Length == 2 ? -1 : + Take("#") || Take("♯") ? 1 : Take("♭") ? -1 : 0; + pitchClass = (natural + accidental + 12) % 12; + return true; + } + + private void Set(ref T? setting, T value, string field, int start) where T : struct + { + if (setting is not null && !EqualityComparer.Default.Equals(setting.Value, value)) + errors.Add(Error("conflicting_setting", field, "Supply this setting once, or repeat the same value.", Phrase(start))); + else setting = value; + } + + private int ReadInteger(string field) + { + if (int.TryParse(Current, NumberStyles.None, CultureInfo.InvariantCulture, out var value)) + { + position++; + return value; + } + errors.Add(Error("invalid_number", field, "Use an unsigned ASCII integer within Int32 range.", Current)); + if (position < tokens.Length) position++; + return 0; + } + + private bool Take(string value) + { + if (Current != value) return false; + position++; + return true; + } + + private bool TakePhrase(string phrase, bool hyphens) + { + var start = position; + var words = phrase.Split(' '); + for (var i = 0; i < words.Length; i++) + { + if (i != 0 && hyphens) Take("-"); + if (Take(words[i])) continue; + position = start; + return false; + } + return true; + } + + private string Current => Token(position); + private string Peek(int offset) => Token(position + offset); + private string Token(int index) => index < tokens.Length ? tokens[index].Value.ToLowerInvariant() : ""; + private string Phrase(int start) => source[tokens[start].Index..(position > start + ? tokens[position - 1].Index + tokens[position - 1].Length : source.Length)]; + private void Unsupported() => errors.Add(Error("unsupported_text", "description", + "Use only documented settings, role patterns and drum clauses; remove or rephrase unconsumed instructions.", + position < tokens.Length ? source[tokens[position].Index..] : "and")); + private static bool IsInteger(string value) => value.Length > 0 && value.All(c => c is >= '0' and <= '9'); + private static bool IsPunctuation(string value) => value is "," or ":" or ";" or "."; + private static int WordNumber(string value) => value switch + { + "one" => 1, "two" => 2, "three" => 3, "four" => 4, "five" => 5, "six" => 6, + "seven" => 7, "eight" => 8, "nine" => 9, "ten" => 10, "eleven" => 11, + "twelve" => 12, "thirteen" => 13, "fourteen" => 14, "fifteen" => 15, "sixteen" => 16, _ => 0 + }; + private sealed record RawPitched(NotePattern? Pattern, Articulation? Articulation); + } + + private static string PatternName(NotePattern pattern) => pattern switch + { + NotePattern.Sustained => "sustained", + NotePattern.Quarter => "quarter notes", + NotePattern.Eighth => "eighth notes", + _ => "sixteenth notes" + }; +} diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Composition/DrumHit.cs b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Composition/DrumHit.cs new file mode 100644 index 0000000..bfb865e --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Composition/DrumHit.cs @@ -0,0 +1,3 @@ +namespace GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition; + +public sealed record DrumHit(DrumVoice Voice, BeatFraction Start, BeatFraction Duration, int Velocity); diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Composition/MusicalNote.cs b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Composition/MusicalNote.cs new file mode 100644 index 0000000..11d52cc --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Composition/MusicalNote.cs @@ -0,0 +1,4 @@ +namespace GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition; + +public sealed record MusicalNote( + int Pitch, BeatFraction Start, BeatFraction Duration, int Velocity, Articulation Articulation); diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Composition/MusicalTypes.cs b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Composition/MusicalTypes.cs new file mode 100644 index 0000000..ae303f6 --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Composition/MusicalTypes.cs @@ -0,0 +1,24 @@ +namespace GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition; + +public enum TrackRole { Lead, Bass, Drums } +public enum Articulation { Sustain, PalmMute } +public enum DrumVoice { Kick, Snare, ClosedHiHat } +public enum KeyMode { Major, Minor } +public enum NotePattern { Sustained, Quarter, Eighth, Sixteenth } + +public readonly record struct TimeSignature(int Numerator, int Denominator) +{ + public BeatFraction BeatLength => new(4, Denominator); + public BeatFraction BarLength => BeatLength * Numerator; + public override string ToString() => $"{Numerator}/{Denominator}"; +} + +public readonly record struct MusicalKey(int RootPitchClass, KeyMode Mode) +{ + public string RootName => RootPitchClass is >= 0 and <= 11 + ? new[] { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" }[RootPitchClass] + : "invalid"; + public override string ToString() => $"{RootName} {Mode.ToString().ToLowerInvariant()}"; +} + +public sealed record AppliedDefault(string Field, string Value); diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Composition/ParsedDescription.cs b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Composition/ParsedDescription.cs new file mode 100644 index 0000000..dd1198d --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Composition/ParsedDescription.cs @@ -0,0 +1,54 @@ +namespace GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition; + +public sealed record PitchedPattern(TrackRole Role, NotePattern Pattern, Articulation Articulation); + +public sealed class DrumPattern +{ + internal DrumPattern(DrumVoice voice, IEnumerable? beats, NotePattern? subdivision) + { + Voice = voice; + Beats = Array.AsReadOnly((beats ?? []).ToArray()); + Subdivision = subdivision; + } + + public DrumVoice Voice { get; } + public IReadOnlyList Beats { get; } + public NotePattern? Subdivision { get; } +} + +public sealed class ParsedDescription +{ + internal ParsedDescription(double tempoBpm, int bars, TimeSignature meter, MusicalKey key, + IEnumerable pitchedPatterns, IEnumerable drumPatterns, + IEnumerable defaultsApplied) + { + TempoBpm = tempoBpm; + Bars = bars; + Meter = meter; + Key = key; + PitchedPatterns = Array.AsReadOnly(pitchedPatterns.ToArray()); + DrumPatterns = Array.AsReadOnly(drumPatterns.ToArray()); + DefaultsApplied = Array.AsReadOnly(defaultsApplied.ToArray()); + } + + public double TempoBpm { get; } + public int Bars { get; } + public TimeSignature Meter { get; } + public MusicalKey Key { get; } + public IReadOnlyList PitchedPatterns { get; } + public IReadOnlyList DrumPatterns { get; } + public IReadOnlyList DefaultsApplied { get; } +} + +public sealed class DescriptionParseResult +{ + internal DescriptionParseResult(ParsedDescription? description, IEnumerable diagnostics) + { + Diagnostics = Array.AsReadOnly(diagnostics.ToArray()); + Description = Diagnostics.Count == 0 ? description : null; + } + + public bool Success => Description is not null; + public ParsedDescription? Description { get; } + public IReadOnlyList Diagnostics { get; } +} diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Composition/TrackPlan.cs b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Composition/TrackPlan.cs new file mode 100644 index 0000000..83c2444 --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Composition/TrackPlan.cs @@ -0,0 +1,15 @@ +namespace GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition; + +public sealed class TrackPlan +{ + public TrackPlan(TrackRole role, IEnumerable? notes = null, IEnumerable? hits = null) + { + Role = role; + Notes = Array.AsReadOnly((notes ?? []).ToArray()); + Hits = Array.AsReadOnly((hits ?? []).ToArray()); + } + + public TrackRole Role { get; } + public IReadOnlyList Notes { get; } + public IReadOnlyList Hits { get; } +} diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/GAJ3T.MusicGen.RiffGrooveBuilder.Core.csproj b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/GAJ3T.MusicGen.RiffGrooveBuilder.Core.csproj new file mode 100644 index 0000000..00b9359 --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/GAJ3T.MusicGen.RiffGrooveBuilder.Core.csproj @@ -0,0 +1,7 @@ + + + + net10.0 + + + diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Generation/GenerateProjectRequest.cs b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Generation/GenerateProjectRequest.cs new file mode 100644 index 0000000..e417669 --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Generation/GenerateProjectRequest.cs @@ -0,0 +1,8 @@ +namespace GAJ3T.MusicGen.RiffGrooveBuilder.Core.Generation; + +public enum OutputFormat { Agp, Sdp, Mid } + +public sealed record SelectedProfiles(string? Lead = null, string? Bass = null, string? Drums = null); + +public sealed record GenerateProjectRequest(string Description, string OutputDirectory, string ProjectName, + IReadOnlyList? Formats = null, SelectedProfiles? Profiles = null, bool FallbackToMidi = true); diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Generation/GenerationResult.cs b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Generation/GenerationResult.cs new file mode 100644 index 0000000..74d37bd --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Generation/GenerationResult.cs @@ -0,0 +1,20 @@ +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.Core.Generation; + +public enum GenerationStatus { Complete, Fallback, Failed } +public enum TargetOutcome { Written, Fallback, Failed } + +public sealed record InterpretedComposition(double TempoBpm, string Meter, string Key, int Bars, + IReadOnlyList Roles, IReadOnlyList DefaultsApplied); +public sealed record GenerationArtifact(OutputFormat Format, IReadOnlyList Roles, + string AbsolutePath, long ByteCount, IReadOnlyList ProfileIds); +public sealed record GenerationTarget(TrackRole Role, string? InstrumentId, string? ProfileId, + OutputFormat RequestedFormat, TargetOutcome Outcome, IReadOnlyList ArtifactPaths, + string? ReasonCode, string? Message); +public sealed record GenerationWarning(string Code, string Message, TrackRole? Role, OutputFormat? RequestedFormat); +public sealed record GenerationError(string Code, string Message, string? Field, TrackRole? Role); +public sealed record GenerationTiming(int TicksPerQuarterNote, long LeadInTicks); +public sealed record GenerationResult(GenerationStatus Status, InterpretedComposition? InterpretedComposition, + IReadOnlyList Artifacts, IReadOnlyList Targets, + IReadOnlyList Warnings, IReadOnlyList Errors, GenerationTiming? Timing); diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Generation/ProfileCatalogResult.cs b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Generation/ProfileCatalogResult.cs new file mode 100644 index 0000000..c04471c --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Generation/ProfileCatalogResult.cs @@ -0,0 +1,28 @@ +using System.Text.Json.Serialization; +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Articulations; +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.Core.Generation; + +public sealed record ListInstrumentProfilesRequest(TrackRole? Role = null); +public enum NativeStatus { Unverified } +public enum WriterStatus { Implemented, Unavailable } +public enum MappingAvailability +{ + [JsonStringEnumMemberName("profile_available")] ProfileAvailable, + [JsonStringEnumMemberName("mapping_unavailable")] MappingUnavailable +} +public enum ArticulationMechanism { Keyswitch, Velocity, Cc } +public sealed record FormatCapability(OutputFormat Format, WriterStatus WriterStatus, NativeStatus ApplicationStatus); +public sealed record DeclaredInstrument(string Id, string Vendor, string ProductCode, string DisplayName, + TrackRole Role, string DocumentationUrl, MappingAvailability Availability); +public sealed record PlayableRange(int MinimumPitch, int MaximumPitch); +public sealed record ProfileArticulation(Articulation Articulation, DrumVoice? Voice, int? DrumPitch, + IReadOnlyList Mechanisms, StateBehavior Behavior, KeyswitchAction? Keyswitch, + VelocityLayer Velocity, IReadOnlyList Controllers); +public sealed record AvailableProfile(string Id, string InstrumentId, TrackRole Role, string ProductName, + string ProductVersion, string MappingVersion, PlayableRange PlayableRange, int Channel, + IReadOnlyList Articulations, MappingEvidence Evidence, + MappingCompatibilityNotes? CompatibilityNotes, IReadOnlyList NativeFormats, NativeStatus NativeStatus); +public sealed record ProfileCatalogResult(IReadOnlyList Instruments, + IReadOnlyList Profiles, IReadOnlyList Formats); diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Instruments/InstrumentDefinition.cs b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Instruments/InstrumentDefinition.cs new file mode 100644 index 0000000..8fa3a75 --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/Instruments/InstrumentDefinition.cs @@ -0,0 +1,6 @@ +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.Core.Instruments; + +public sealed record InstrumentDefinition(string Id, string Vendor, string ProductCode, + string DisplayName, TrackRole Role, string DocumentationUrl); diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/packages.lock.json b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/packages.lock.json new file mode 100644 index 0000000..6afd678 --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Core/packages.lock.json @@ -0,0 +1,6 @@ +{ + "version": 2, + "dependencies": { + "net10.0": {} + } +} \ No newline at end of file diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Generation/CatalogJson.cs b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Generation/CatalogJson.cs new file mode 100644 index 0000000..e0d1210 --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Generation/CatalogJson.cs @@ -0,0 +1,46 @@ +using System.Text.Json; +using System.Text.Json.Serialization; +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.Generation; + +internal static class CatalogJson +{ + internal static T[] Read(Stream resource, string name) + { + var options = new JsonSerializerOptions + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow, + AllowDuplicateProperties = false, + RespectRequiredConstructorParameters = true, + RespectNullableAnnotations = true + }; + options.Converters.Add(new RoleConverter()); + options.Converters.Add(new JsonStringEnumConverter(allowIntegerValues: false)); + try + { + return JsonSerializer.Deserialize(resource, options) + ?? throw new JsonException("The catalog must be a JSON list, not null."); + } + catch (JsonException ex) + { + throw new InvalidDataException($"Malformed {name} catalog; repair the embedded data.", ex); + } + } + + private sealed class RoleConverter : JsonConverter + { + public override TrackRole Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + var role = reader.TokenType == JsonTokenType.String ? reader.GetString() : null; + if (Enum.GetNames().FirstOrDefault(n => + string.Equals(n, role, StringComparison.OrdinalIgnoreCase)) is { } name) + return Enum.Parse(name); + throw new JsonException("Use one role name: Lead, Bass or Drums."); + } + + public override void Write(Utf8JsonWriter writer, TrackRole value, JsonSerializerOptions options) => + writer.WriteStringValue(value.ToString()); + } +} diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Generation/GAJ3T.MusicGen.RiffGrooveBuilder.Generation.csproj b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Generation/GAJ3T.MusicGen.RiffGrooveBuilder.Generation.csproj new file mode 100644 index 0000000..08ebfa1 --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Generation/GAJ3T.MusicGen.RiffGrooveBuilder.Generation.csproj @@ -0,0 +1,18 @@ + + + + + + + + net10.0 + + + + + + + + + + diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Generation/GenerationService.cs b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Generation/GenerationService.cs new file mode 100644 index 0000000..460002d --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Generation/GenerationService.cs @@ -0,0 +1,208 @@ +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Articulations; +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition; +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Generation; +using GAJ3T.MusicGen.RiffGrooveBuilder.Generation.Midi; +using GAJ3T.MusicGen.RiffGrooveBuilder.Generation.Output; +using GAJ3T.MusicGen.RiffGrooveBuilder.Generation.Profiles; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.Generation; + +public sealed class GenerationService +{ + private readonly InstrumentProfileCatalog catalog; + private readonly Action? beforeWrite; + + public GenerationService() : this(InstrumentProfileCatalog.LoadEmbedded()) { } + + internal GenerationService(InstrumentProfileCatalog catalog, Action? beforeWrite = null) + { + this.catalog = catalog; + this.beforeWrite = beforeWrite; + } + + public ProfileCatalogResult ListInstrumentProfiles(ListInstrumentProfilesRequest request) + { + if (request.Role is { } role && !Enum.IsDefined(role)) + throw new ArgumentOutOfRangeException(nameof(request)); + return new( + catalog.Instruments.Where(i => request.Role is null || i.Instrument.Role == request.Role) + .Select(i => new DeclaredInstrument(i.Instrument.Id, i.Instrument.Vendor, i.Instrument.ProductCode, + i.Instrument.DisplayName, i.Instrument.Role, i.Instrument.DocumentationUrl, + i.Profiles.Count == 0 ? MappingAvailability.MappingUnavailable : MappingAvailability.ProfileAvailable)).ToArray(), + catalog.Profiles.Where(p => request.Role is null || p.Role == request.Role).Select(p => + new AvailableProfile(p.Id, p.InstrumentId, p.Role, p.ProductName, p.ProductVersion, p.MappingVersion, + new(p.MinimumPitch, p.MaximumPitch), p.Channel, + p.Rules.Select(r => new ProfileArticulation(r.Articulation, r.Voice, r.DrumPitch, + Mechanisms(r), r.Behavior, r.Keyswitch, r.Velocity, r.Controllers)).ToArray(), + p.Evidence, p.CompatibilityNotes, [NativeFormat(p.Role)], NativeStatus.Unverified)).ToArray(), + [new(OutputFormat.Mid, WriterStatus.Implemented, NativeStatus.Unverified), + new(OutputFormat.Agp, WriterStatus.Unavailable, NativeStatus.Unverified), + new(OutputFormat.Sdp, WriterStatus.Unavailable, NativeStatus.Unverified)]); + } + + // Task.Run isolates parsing, planning and synchronous filesystem/library work from the stdio reader. + public Task GenerateAsync(GenerateProjectRequest request, CancellationToken cancellationToken = default) => + Task.Run(() => Generate(request, cancellationToken), cancellationToken); + + private GenerationResult Generate(GenerateProjectRequest request, CancellationToken token) + { + token.ThrowIfCancellationRequested(); + ArgumentNullException.ThrowIfNull(request); + var errors = new List(); + var warnings = new List(); + var targets = new List(); + InterpretedComposition? interpreted = null; + GenerationTiming? timing = null; + GenerationResult Failed() => new(GenerationStatus.Failed, interpreted, [], + targets.Select(t => t with { Outcome = TargetOutcome.Failed, ArtifactPaths = [], + ReasonCode = t.ReasonCode ?? errors.FirstOrDefault(e => e.Role == t.Role || e.Role is null)?.Code ?? "generation_failed", + Message = t.Message ?? errors.FirstOrDefault(e => e.Role == t.Role || e.Role is null)?.Message ?? "No artifact was published." }).ToArray(), + warnings.ToArray(), errors.ToArray(), timing); + + string directory; + var pathField = "outputDirectory"; + try + { + directory = OutputPath.ResolveDirectory(request.OutputDirectory); + pathField = "projectName"; + ArgumentException.ThrowIfNullOrWhiteSpace(request.ProjectName); + OutputPath.ValidateName(request.ProjectName); + } + catch (Exception e) when (e is ArgumentException or PathTooLongException) + { + errors.Add(new("invalid_output_path", e.Message, pathField, null)); + return Failed(); + } + if (request.Formats is { } supplied && + (supplied.Count == 0 || supplied.Any(f => !Enum.IsDefined(f)) || supplied.Distinct().Count() != supplied.Count)) + { + errors.Add(new("invalid_formats", "Supply a nonempty unique array of agp, sdp, mid, or omit formats.", "formats", null)); + return Failed(); + } + var planned = CompositionPlanner.Plan(request.Description); + if (!planned.Success) + { + errors.AddRange(planned.Diagnostics.Select(d => new GenerationError(d.Code, d.Message, d.Field, null))); + return Failed(); + } + token.ThrowIfCancellationRequested(); + var composition = planned.Composition!; + var roles = composition.Tracks.Select(t => t.Role).ToArray(); + interpreted = new(composition.TempoBpm, composition.Meter.ToString(), composition.Key.ToString(), + composition.Bars, roles, composition.DefaultsApplied); + var formats = request.Formats ?? roles.Select(NativeFormat).Distinct().Append(OutputFormat.Mid).ToArray(); + foreach (var format in formats.Where(f => f != OutputFormat.Mid)) + if (!roles.Any(r => NativeFormat(r) == format)) + errors.Add(new("inapplicable_format", $"{format.ToString().ToLowerInvariant()} has no applicable selected role. Remove it or select its role.", "formats", null)); + var selected = new Dictionary(); + foreach (var role in Enum.GetValues()) + { + var id = role switch { TrackRole.Lead => request.Profiles?.Lead, TrackRole.Bass => request.Profiles?.Bass, _ => request.Profiles?.Drums }; + if (!roles.Contains(role)) + { + if (id is not null) + errors.Add(new("unselected_role_profile", "Remove the profile for this unselected role or explicitly select the role in the description.", $"profiles.{RoleName(role)}", role)); + continue; + } + var selection = catalog.Select(role, id); + if (!selection.Success) + { + var available = catalog.Profiles.Where(p => p.Role == role).Select(p => p.Id).ToArray(); + var choices = available.Length == 0 + ? "No admitted mapping exists for this role; it cannot be omitted from the requested arrangement." + : "Available IDs: " + string.Join(", ", available) + "."; + errors.AddRange(selection.Diagnostics.Select(d => new GenerationError( + available.Length == 0 && string.IsNullOrWhiteSpace(id) ? "mapping_unavailable" : d.Code, d.Message + " " + choices, + $"profiles.{RoleName(role)}", role))); + } + else + { + var profile = selection.Profile!; + selected.Add(role, profile); + if (profile.Evidence.Status == MappingVerification.Documented) + { + var notes = profile.CompatibilityNotes!; + warnings.Add(new("documented_profile", $"{profile.Id}: source-only Documented mapping, NOT installed/application-verified. " + + $"{notes.VersionScope} {notes.ConfigurationRequirements} {notes.RoutingPolicy} {notes.TimingPolicy}", role, null)); + } + } + foreach (var format in formats.Where(f => f == OutputFormat.Mid || NativeFormat(role) == f)) + targets.Add(new(role, selection.Profile?.InstrumentId, id, format, TargetOutcome.Failed, [], null, null)); + } + var nativeRequested = formats.Any(f => f != OutputFormat.Mid && roles.Any(r => NativeFormat(r) == f)); + if (nativeRequested) + { + foreach (var target in targets.Where(t => t.RequestedFormat != OutputFormat.Mid)) + warnings.Add(new("native_writer_unavailable", + $"No authorized {target.RequestedFormat.ToString().ToUpperInvariant()} codec/writer exists; native compatibility is unverified.", + target.Role, target.RequestedFormat)); + for (var i = 0; i < targets.Count; i++) + if (targets[i].RequestedFormat != OutputFormat.Mid) + targets[i] = targets[i] with + { + ReasonCode = "native_writer_unavailable", + Message = "Native writer unavailable; enable MIDI fallback or request only mid." + }; + if (!request.FallbackToMidi) + errors.Add(new("native_fallback_disabled", "Requested native writers are unavailable. Enable fallbackToMidi or request formats=[\"mid\"].", "fallbackToMidi", null)); + } + if (errors.Count != 0) + return Failed(); + var articulation = ArticulationPlanner.Plan(composition, selected.Values); + if (!articulation.Success) + { + errors.AddRange(articulation.Diagnostics.Select(d => new GenerationError(d.Code, d.Message, d.Field, null))); + return Failed(); + } + var plan = articulation.Plan!; + timing = new(960, plan.LeadInTicks); + var path = Path.Combine(directory, request.ProjectName + ".mid"); + try + { + token.ThrowIfCancellationRequested(); + MidiFileBuilder.ValidateFormatLimits(composition.Meter.Denominator, plan.EndTick); + if (File.Exists(path) || Directory.Exists(path)) + { + errors.Add(new("output_exists", $"Destination exists and will not be overwritten: '{path}'. Choose another projectName.", "projectName", null)); + return Failed(); + } + beforeWrite?.Invoke(token); + token.ThrowIfCancellationRequested(); + Directory.CreateDirectory(directory); + MidiFileWriter.WriteFile(path, composition, plan, token); + } + catch (NotSupportedException e) + { + errors.Add(new("midi_not_supported", e.Message, "description", null)); + return Failed(); + } + catch (ArgumentOutOfRangeException e) when (e.ParamName == "tick") + { + errors.Add(new("midi_not_supported", e.Message, "description", null)); + return Failed(); + } + catch (Exception e) when (e is IOException or UnauthorizedAccessException) + { + errors.Add(new("output_io_error", e.Message, "outputDirectory", null)); + return Failed(); + } + // Publication is the commit point. Cancellation racing after the move cannot undo another owner's file. + var artifact = new GenerationArtifact(OutputFormat.Mid, roles, path, new FileInfo(path).Length, + roles.Select(r => selected[r].Id).ToArray()); + return new(nativeRequested ? GenerationStatus.Fallback : GenerationStatus.Complete, interpreted, [artifact], + targets.Select(t => t with + { + Outcome = t.RequestedFormat == OutputFormat.Mid ? TargetOutcome.Written : TargetOutcome.Fallback, + ArtifactPaths = [path], + ReasonCode = t.RequestedFormat == OutputFormat.Mid ? null : "native_writer_unavailable", + Message = t.RequestedFormat == OutputFormat.Mid ? null : "Native writer unavailable; the complete selected arrangement was written once as Standard MIDI." + }).ToArray(), warnings.ToArray(), [], timing); + } + + private static OutputFormat NativeFormat(TrackRole role) => role == TrackRole.Drums ? OutputFormat.Sdp : OutputFormat.Agp; + private static string RoleName(TrackRole role) => role.ToString().ToLowerInvariant(); + private static ArticulationMechanism[] Mechanisms(ArticulationRule rule) => + (rule.Keyswitch is null ? Array.Empty() : [ArticulationMechanism.Keyswitch]) + .Concat([ArticulationMechanism.Velocity]) + .Concat(rule.Controllers.Count == 0 ? [] : new[] { ArticulationMechanism.Cc }).ToArray(); +} diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Generation/Instruments/InstrumentCatalog.cs b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Generation/Instruments/InstrumentCatalog.cs new file mode 100644 index 0000000..15a59ff --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Generation/Instruments/InstrumentCatalog.cs @@ -0,0 +1,64 @@ +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition; +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Instruments; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.Generation.Instruments; + +public sealed class InstrumentCatalog +{ + private InstrumentCatalog(IEnumerable instruments) => + Instruments = Array.AsReadOnly(instruments.OrderBy(i => i.Id, StringComparer.Ordinal).ToArray()); + + public IReadOnlyList Instruments { get; } + + public static InstrumentCatalog LoadEmbedded() + { + using var resource = typeof(InstrumentCatalog).Assembly.GetManifestResourceStream( + "GAJ3T.MusicGen.RiffGrooveBuilder.Generation.Instruments.instruments.json") + ?? throw new InvalidDataException("The embedded instrument catalog is missing."); + return Load(resource); + } + + internal static InstrumentCatalog Load(Stream resource) + { + var instruments = CatalogJson.Read(resource, "instrument"); + var ids = new HashSet(StringComparer.Ordinal); + var products = new HashSet<(string Vendor, string Code)>(); + var names = new HashSet<(string Vendor, string Name)>(); + foreach (var instrument in instruments) + { + if (instrument is null) + throw new InvalidDataException("Invalid instrument catalog: null instrument."); + if (!ValidId(instrument.Id) || !ValidId(instrument.ProductCode) || + !ValidText(instrument.Vendor) || !ValidText(instrument.DisplayName)) + throw new InvalidDataException("Invalid instrument catalog: required identity values must be nonempty, trimmed and valid; IDs/codes use ASCII letters/digits, dash, underscore or dot."); + if (!ids.Add(instrument.Id)) + throw new InvalidDataException($"Invalid instrument catalog: duplicate_instrument_id {instrument.Id}."); + if (!products.Add((instrument.Vendor, instrument.ProductCode)) || + !names.Add((instrument.Vendor, instrument.DisplayName))) + throw new InvalidDataException($"Invalid instrument catalog: duplicate_product_identity {instrument.Id}; use profiles for product/mapping versions."); + if (!Enum.IsDefined(instrument.Role)) + throw new InvalidDataException($"Invalid instrument catalog: invalid_role for {instrument.Id}."); + if (!ValidText(instrument.DocumentationUrl) || instrument.DocumentationUrl.Any(char.IsWhiteSpace) || + !Uri.TryCreate(instrument.DocumentationUrl, UriKind.Absolute, out var url) || + (url.Scheme != Uri.UriSchemeHttps && url.Scheme != Uri.UriSchemeHttp) || + string.IsNullOrEmpty(url.Host) || !string.IsNullOrEmpty(url.UserInfo)) + throw new InvalidDataException($"Invalid instrument catalog: invalid_documentation_url for {instrument.Id}; use an absolute HTTP(S) documentation URL without credentials."); + } + return new(instruments); + } + + public InstrumentDefinition? Find(string id) => Instruments.SingleOrDefault(i => i.Id == id); + + public IReadOnlyList ForRole(TrackRole role) + { + if (!Enum.IsDefined(role)) + throw new ArgumentOutOfRangeException(nameof(role), "Select lead, bass or drums."); + return Array.AsReadOnly(Instruments.Where(i => i.Role == role).ToArray()); + } + + private static bool ValidText(string? value) => !string.IsNullOrWhiteSpace(value) && + value == value.Trim() && !value.Any(char.IsControl); + + private static bool ValidId(string? value) => !string.IsNullOrEmpty(value) && + value.All(c => char.IsAsciiLetterOrDigit(c) || c is '-' or '_' or '.'); +} diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Generation/Instruments/instruments.json b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Generation/Instruments/instruments.json new file mode 100644 index 0000000..6610623 --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Generation/Instruments/instruments.json @@ -0,0 +1,58 @@ +[ + { + "id": "ample-abj", + "vendor": "Ample Sound", + "productCode": "ABJ", + "displayName": "Ample Bass J", + "role": "Bass", + "documentationUrl": "https://www.amplesound.net/en/Main_Panel_Manual-ABJ.pdf" + }, + { + "id": "ample-aglp", + "vendor": "Ample Sound", + "productCode": "AGLP", + "displayName": "Ample Guitar LP", + "role": "Lead", + "documentationUrl": "https://www.amplesound.net/en/Main_Panel_Manual-AGLP.pdf" + }, + { + "id": "ample-agm", + "vendor": "Ample Sound", + "productCode": "AGM", + "displayName": "Ample Guitar M", + "role": "Lead", + "documentationUrl": "https://www.amplesound.net/en/Main_Panel_Manual-AGM.pdf" + }, + { + "id": "ample-agt", + "vendor": "Ample Sound", + "productCode": "AGT", + "displayName": "Ample Guitar T", + "role": "Lead", + "documentationUrl": "https://www.amplesound.net/en/Main_Panel_Manual-AGT.pdf" + }, + { + "id": "ample-ame", + "vendor": "Ample Sound", + "productCode": "AME", + "displayName": "Ample Metal Eclipse", + "role": "Lead", + "documentationUrl": "https://www.amplesound.net/en/Main_Panel_Manual-AME.pdf" + }, + { + "id": "ample-amr", + "vendor": "Ample Sound", + "productCode": "AMR", + "displayName": "Ample Metal Ray5", + "role": "Bass", + "documentationUrl": "https://www.amplesound.net/en/Main_Panel_Manual-AMR.pdf" + }, + { + "id": "toontrack-sd3", + "vendor": "Toontrack", + "productCode": "SD3", + "displayName": "Superior Drummer 3", + "role": "Drums", + "documentationUrl": "https://www.toontrack.com/manual/superior-drummer-3/" + } +] diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Generation/Midi/MidiEventBuilder.cs b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Generation/Midi/MidiEventBuilder.cs new file mode 100644 index 0000000..8d42a7d --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Generation/Midi/MidiEventBuilder.cs @@ -0,0 +1,45 @@ +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Articulations; +using Melanchall.DryWetMidi.Common; +using Melanchall.DryWetMidi.Core; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.Generation.Midi; + +public static class MidiEventBuilder +{ + /// Translates one absolute-time intention; the file builder assigns its delta time. + public static MidiEvent Build(PlannedMidiEvent planned, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(planned); + cancellationToken.ThrowIfCancellationRequested(); + ArgumentOutOfRangeException.ThrowIfNegative(planned.Tick); + Range(planned.Channel, 0, 15, nameof(planned.Channel)); + ChannelEvent result; + switch (planned) + { + case PlannedNoteOn on: + Range(on.Pitch, 0, 127, nameof(on.Pitch)); + Range(on.Velocity, 1, 127, nameof(on.Velocity)); + result = new NoteOnEvent((SevenBitNumber)on.Pitch, (SevenBitNumber)on.Velocity); + break; + case PlannedNoteOff off: + Range(off.Pitch, 0, 127, nameof(off.Pitch)); + result = new NoteOffEvent((SevenBitNumber)off.Pitch, (SevenBitNumber)0); + break; + case PlannedControlChange cc: + Range(cc.Number, 0, 127, nameof(cc.Number)); + Range(cc.Value, 0, 127, nameof(cc.Value)); + result = new ControlChangeEvent((SevenBitNumber)cc.Number, (SevenBitNumber)cc.Value); + break; + default: + throw new NotSupportedException($"Unsupported planned MIDI event type '{planned.GetType().FullName}'."); + } + result.Channel = (FourBitNumber)planned.Channel; + return result; + } + + private static void Range(int value, int minimum, int maximum, string name) + { + if (value < minimum || value > maximum) + throw new ArgumentOutOfRangeException(name, value, $"Use {name} in {minimum}..{maximum}; values are never clamped."); + } +} diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Generation/Midi/MidiFileBuilder.cs b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Generation/Midi/MidiFileBuilder.cs new file mode 100644 index 0000000..1dd38a1 --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Generation/Midi/MidiFileBuilder.cs @@ -0,0 +1,138 @@ +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Articulations; +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition; +using Melanchall.DryWetMidi.Core; +using MusicalComposition = GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition.Composition; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.Generation.Midi; + +public static class MidiFileBuilder +{ + internal const long MaximumDelta = 0x0FFFFFFF; + private static readonly byte[] EmptyTrackFile = CreateEmptyTrackFile(); + + public static MidiFile Build(MusicalComposition composition, MidiEventPlan plan, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(composition); + ArgumentNullException.ThrowIfNull(plan); + cancellationToken.ThrowIfCancellationRequested(); + var diagnostics = CompositionValidator.Validate(composition); + if (diagnostics.Count != 0) + throw new ArgumentException("Invalid composition: " + + string.Join("; ", diagnostics.Select(d => $"{d.Field}: {d.Message}")), nameof(composition)); + if (plan.LeadInTicks < 0 || plan.MusicalExtentTicks != composition.MusicalExtent.ToTicks() || + plan.MusicalEndTick != checked(plan.LeadInTicks + plan.MusicalExtentTicks) || + plan.EndTick < plan.MusicalEndTick) + throw new ArgumentException("Event plan extent/lead-in disagrees with the composition.", nameof(plan)); + var roles = composition.Tracks.Select(t => t.Role).Order().ToArray(); + if (!roles.SequenceEqual(plan.Tracks.Select(t => t.Role).Order())) + throw new ArgumentException("Event plan must contain exactly the selected composition roles, once each.", nameof(plan)); + ValidateFormatLimits(composition.Meter.Denominator, plan.EndTick); + + // 8.0.3 constructs EOT internally. Read a library-generated empty track with Store, + // then insert before its retained EOT, avoiding reflection or handwritten MIDI bytes. + var conductor = CreateTrack(); + conductor.Events.Insert(0, new SequenceTrackNameEvent("Conductor")); + var microseconds = checked((long)Math.Round(60_000_000d / composition.TempoBpm, + MidpointRounding.AwayFromZero)); + conductor.Events.Insert(1, new SetTempoEvent(microseconds)); + conductor.Events.Insert(2, new TimeSignatureEvent(checked((byte)composition.Meter.Numerator), + checked((byte)composition.Meter.Denominator))); + conductor.Events[^1].DeltaTime = DeltaTicks(plan.EndTick, 0); + var chunks = new List { conductor }; + var channels = new HashSet(); + foreach (var plannedTrack in plan.Tracks.OrderBy(t => t.Role)) + { + cancellationToken.ThrowIfCancellationRequested(); + var source = composition.Tracks.Single(t => t.Role == plannedTrack.Role); + // Per note: musical pair, switch pair, 128 active + 128 release CCs; + // per track: 128 initial + 128 final CCs and one final switch pair. + var maximumEvents = checked((long)(source.Notes.Count + source.Hits.Count) * 260 + 258); + if (plannedTrack.Events.Count > maximumEvents) + throw new ArgumentException($"Event plan for {plannedTrack.Role} exceeds the possible note/control count.", nameof(plan)); + var track = CreateTrack(); + track.Events.Insert(0, new SequenceTrackNameEvent(plannedTrack.Role.ToString())); + long previous = 0; + var priority = -1; + int? channel = null; + var active = new Dictionary(); + var played = new List<(long Start, long End, int Pitch)>(); + foreach (var planned in plannedTrack.Events) + { + cancellationToken.ThrowIfCancellationRequested(); + var midiEvent = MidiEventBuilder.Build(planned, cancellationToken); + midiEvent.DeltaTime = DeltaTicks(planned.Tick, previous); + if (planned.Tick > plan.EndTick || (planned.Tick == previous && planned.Priority < priority)) + throw new ArgumentException($"Invalid event end/order in {plannedTrack.Role} at tick {planned.Tick}.", nameof(plan)); + if (channel.HasValue && channel != planned.Channel) + throw new ArgumentException($"Event plan for {plannedTrack.Role} changes channel within its track.", nameof(plan)); + channel = planned.Channel; + if (planned is PlannedNoteOn on && !active.TryAdd(on.Pitch, on)) + throw new ArgumentException($"Overlapping note ownership for pitch {on.Pitch}.", nameof(plan)); + if (planned is PlannedNoteOff off) + { + if (!active.Remove(off.Pitch, out var start) || start.IsKeyswitch != off.IsKeyswitch || start.Tick >= off.Tick) + throw new ArgumentException($"Unpaired/nonpositive note at tick {off.Tick}, pitch {off.Pitch}.", nameof(plan)); + if (!off.IsKeyswitch) + played.Add((start.Tick, off.Tick, off.Pitch)); + } + track.Events.Insert(track.Events.Count - 1, midiEvent); + previous = planned.Tick; + priority = planned.Priority; + } + if (active.Count != 0) + throw new ArgumentException($"Event plan for {plannedTrack.Role} leaves notes active.", nameof(plan)); + if (!channel.HasValue || !channels.Add(channel.Value)) + throw new ArgumentException("Selected role tracks need distinct MIDI channels and nonempty events.", nameof(plan)); + ValidatePlayedNotes(source, played, plan.LeadInTicks); + track.Events[^1].DeltaTime = DeltaTicks(plan.EndTick, previous); + chunks.Add(track); + } + cancellationToken.ThrowIfCancellationRequested(); + return new MidiFile(chunks) { TimeDivision = new TicksPerQuarterNoteTimeDivision(960) }; + } + + private static void ValidatePlayedNotes(TrackPlan source, List<(long Start, long End, int Pitch)> played, long leadIn) + { + var expected = source.Notes.Select(n => (Start: checked(n.Start.ToTicks() + leadIn), + End: checked((n.Start + n.Duration).ToTicks() + leadIn), n.Pitch)) + .Concat(source.Hits.Select(h => (Start: checked(h.Start.ToTicks() + leadIn), + End: checked((h.Start + h.Duration).ToTicks() + leadIn), Pitch: -1))); + var actual = played.Select(n => source.Role == TrackRole.Drums ? (n.Start, n.End, Pitch: -1) : n); + if (!expected.Order().SequenceEqual(actual.Order())) + throw new ArgumentException($"Played note pitches/timing/count for {source.Role} disagree with the composition.", "plan"); + } + + internal static long DeltaTicks(long tick, long previous) + { + var delta = checked(tick - previous); + if (delta is < 0 or > MaximumDelta) + throw new ArgumentOutOfRangeException(nameof(tick), tick, + $"SMF delta from {previous} must be 0..{MaximumDelta} (four-byte VLQ); no filler events are inserted."); + return delta; + } + + internal static void ValidateFormatLimits(int denominator, long endTick) + { + if (denominator > 128) + throw new NotSupportedException("DryWetMIDI 8.0.3 uses a byte denominator: meter /256 is valid in Core but cannot be written. Supported writer denominators are 1..128 (powers of two)."); + _ = DeltaTicks(endTick, 0); + } + + private static byte[] CreateEmptyTrackFile() + { + using var stream = new MemoryStream(); + new MidiFile(new TrackChunk()).Write(stream, MidiFileFormat.MultiTrack); + return stream.ToArray(); + } + + private static TrackChunk CreateTrack() + { + using var stream = new MemoryStream(EmptyTrackFile, writable: false); + return (TrackChunk)MidiFile.Read(stream, new ReadingSettings + { + EndOfTrackStoringPolicy = EndOfTrackStoringPolicy.Store, + MissedEndOfTrackPolicy = MissedEndOfTrackPolicy.Abort + }).Chunks.Single(); + } +} diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Generation/Midi/MidiFileWriter.cs b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Generation/Midi/MidiFileWriter.cs new file mode 100644 index 0000000..e71ac8d --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Generation/Midi/MidiFileWriter.cs @@ -0,0 +1,122 @@ +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Articulations; +using GAJ3T.MusicGen.RiffGrooveBuilder.Generation.Output; +using Melanchall.DryWetMidi.Core; +using MusicalComposition = GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition.Composition; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.Generation.Midi; + +public static class MidiFileWriter +{ + /// Writes a type-1 file without closing the borrowed stream. Failure may leave partial bytes. + public static void Write(Stream destination, MusicalComposition composition, MidiEventPlan plan, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(destination); + if (!destination.CanWrite) + throw new ArgumentException("Supply an open writable stream.", nameof(destination)); + var file = MidiFileBuilder.Build(composition, plan, cancellationToken); + Serialize(file, destination, cancellationToken); + } + + /// Stages beside an explicit absolute destination, then publishes with no overwrite. + public static void WriteFile(string destinationPath, MusicalComposition composition, MidiEventPlan plan, + CancellationToken cancellationToken = default) + { + var path = ValidatePath(destinationPath); + var file = MidiFileBuilder.Build(composition, plan, cancellationToken); + Publish(path, stream => Serialize(file, stream, cancellationToken), cancellationToken); + } + + private static void Serialize(MidiFile file, Stream stream, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + // DryWetMIDI's synchronous serialization has no cancellation token. + file.Write(stream, MidiFileFormat.MultiTrack, new WritingSettings + { + NoteOffAsSilentNoteOn = false, + UseRunningStatus = false, + DeleteDefaultSetTempo = false, + DeleteDefaultTimeSignature = false + }); + cancellationToken.ThrowIfCancellationRequested(); + } + + internal static void Publish(string destinationPath, Action serialize, CancellationToken cancellationToken) + { + var path = ValidatePath(destinationPath); + cancellationToken.ThrowIfCancellationRequested(); + var stagingPath = Path.Combine(Path.GetDirectoryName(path)!, $".riffgroove-{Guid.NewGuid():N}.stage"); + var owned = false; + try + { + var stream = new FileStream(stagingPath, FileMode.CreateNew, FileAccess.Write, FileShare.None); + owned = true; + CompleteStage(stream, serialize, cancellationToken); + cancellationToken.ThrowIfCancellationRequested(); + File.Move(stagingPath, path, overwrite: false); + } + catch (Exception original) + { + if (owned) + Cleanup(stagingPath, original); + throw; + } + } + + internal static void CompleteStage(Stream stream, Action serialize, CancellationToken cancellationToken) + { + Exception? original = null; + try + { + serialize(stream); + cancellationToken.ThrowIfCancellationRequested(); + } + catch (Exception error) + { + original = error; + throw; + } + finally + { + try + { + stream.Dispose(); + } + catch (Exception close) + { + if (original is null) + throw; + throw new AggregateException("MIDI staging failed and its stream could not be closed cleanly.", original, close); + } + } + } + + internal static void Cleanup(string stagingPath, Exception original) + { + try + { + File.Delete(stagingPath); + } + catch (Exception cleanup) + { + throw new AggregateException($"MIDI output failed and request-owned staging file could not be removed: '{stagingPath}'.", + original, cleanup); + } + } + + private static string ValidatePath(string destinationPath) + { + ArgumentException.ThrowIfNullOrWhiteSpace(destinationPath); + if (!Path.IsPathFullyQualified(destinationPath)) + throw new ArgumentException("Supply an explicit fully qualified absolute destination path.", nameof(destinationPath)); + var name = Path.GetFileName(destinationPath); + OutputPath.ValidateName(name); + var path = Path.GetFullPath(destinationPath); + var parent = Path.GetDirectoryName(path)!; + if (!Directory.Exists(parent)) + throw new DirectoryNotFoundException($"MIDI destination parent directory does not exist: '{parent}'."); + if (File.Exists(path) || Directory.Exists(path)) + throw new IOException($"MIDI destination already exists and will not be overwritten: '{path}'."); + return path; + } +} diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Generation/Output/OutputPath.cs b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Generation/Output/OutputPath.cs new file mode 100644 index 0000000..bf89b8b --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Generation/Output/OutputPath.cs @@ -0,0 +1,33 @@ +namespace GAJ3T.MusicGen.RiffGrooveBuilder.Generation.Output; + +internal static class OutputPath +{ + internal static void ValidateName(string name) + { + var stem = name.Split('.')[0].TrimEnd(' '); + if (string.IsNullOrWhiteSpace(name) || name.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0 || + name.Any(c => char.IsControl(c) || "<>:\"/\\|?*".Contains(c)) || + name.EndsWith('.') || name.EndsWith(' ') || name is "." or ".." || + new[] { "CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$" }.Contains(stem, StringComparer.OrdinalIgnoreCase) || + (stem.Length == 4 && (stem.StartsWith("COM", StringComparison.OrdinalIgnoreCase) || + stem.StartsWith("LPT", StringComparison.OrdinalIgnoreCase)) && stem[3] is >= '1' and <= '9' or '¹' or '²' or '³')) + throw new ArgumentException("Supply a valid non-reserved filename stem, not a directory/device/alternate stream."); + } + + internal static string ResolveDirectory(string directory) + { + ArgumentException.ThrowIfNullOrWhiteSpace(directory); + directory = directory.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar); + if (!Path.IsPathFullyQualified(directory) || directory.StartsWith(@"\\?\", StringComparison.Ordinal) || + directory.StartsWith(@"\\.\", StringComparison.Ordinal) || + directory.Split([Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar], + StringSplitOptions.None).Any(p => p is "." or "..")) + throw new ArgumentException("Supply an explicit absolute output directory without traversal or device syntax."); + var full = Path.GetFullPath(directory); + var root = Path.GetPathRoot(full)!; + foreach (var component in full[root.Length..].Split( + [Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar], StringSplitOptions.RemoveEmptyEntries)) + ValidateName(component); + return full; + } +} diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Generation/Profiles/InstrumentProfileCatalog.cs b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Generation/Profiles/InstrumentProfileCatalog.cs new file mode 100644 index 0000000..ce2f56f --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Generation/Profiles/InstrumentProfileCatalog.cs @@ -0,0 +1,120 @@ +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Articulations; +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition; +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Instruments; +using GAJ3T.MusicGen.RiffGrooveBuilder.Generation.Instruments; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.Generation.Profiles; + +public sealed class ProfileSelectionResult +{ + internal ProfileSelectionResult(InstrumentProfile? profile, params ArticulationDiagnostic[] diagnostics) + { + Profile = profile; + Diagnostics = Array.AsReadOnly(diagnostics); + } + + public bool Success => Profile is not null; + public InstrumentProfile? Profile { get; } + public IReadOnlyList Diagnostics { get; } +} + +public sealed class InstrumentProfileCatalog +{ + private InstrumentProfileCatalog(InstrumentProfile[] profiles, InstrumentCatalog instruments) + { + Profiles = Array.AsReadOnly(profiles.OrderBy(p => p.Id, StringComparer.Ordinal).ToArray()); + Instruments = Array.AsReadOnly(instruments.Instruments.Select(i => + new InstrumentCatalogEntry(i, Profiles.Where(p => p.InstrumentId == i.Id))).ToArray()); + } + + public IReadOnlyList Profiles { get; } + public IReadOnlyList Instruments { get; } + + public static InstrumentProfileCatalog LoadEmbedded() + { + using var resource = typeof(InstrumentProfileCatalog).Assembly.GetManifestResourceStream( + "GAJ3T.MusicGen.RiffGrooveBuilder.Generation.Profiles.instrument-profiles.json") + ?? throw new InvalidDataException("The embedded instrument profile catalog is missing."); + return Load(resource); + } + + internal static InstrumentProfileCatalog Load(Stream resource, InstrumentCatalog? instruments = null) + { + instruments ??= InstrumentCatalog.LoadEmbedded(); + var profiles = CatalogJson.Read(resource, "instrument profile"); + var diagnostics = profiles.SelectMany(p => InstrumentProfileValidator.Validate(p)).ToList(); + foreach (var profile in profiles.Where(p => p is not null)) + { + var instrument = instruments.Find(profile.InstrumentId); + if (instrument is null) + diagnostics.Add(new("unknown_instrument", profile.Id + ".instrumentId", "Declare the referenced instrument before admitting its mapping.")); + else + { + if (instrument.Role != profile.Role) + diagnostics.Add(new("profile_role_mismatch", profile.Id + ".role", "The profile role must match its declared instrument.")); + if (!string.Equals(instrument.DisplayName, profile.ProductName, StringComparison.Ordinal)) + diagnostics.Add(new("profile_product_mismatch", profile.Id + ".productName", "The exact product name must match the declared instrument display name.")); + } + } + var ids = profiles.Where(p => p is not null).Select(p => p.Id).ToArray(); + if (ids.Distinct(StringComparer.Ordinal).Count() != ids.Length) + diagnostics.Add(new("duplicate_profile_id", "profiles.id", "Use unique IDs in the embedded profile catalog.")); + if (diagnostics.Count != 0) + throw new InvalidDataException("Invalid or unverified instrument profile catalog: " + + string.Join("; ", diagnostics.Select(d => $"{d.Code} ({d.Field}): {d.Message}"))); + return new(profiles, instruments); + } + + public ProfileSelectionResult Select(TrackRole role, string? id = null) + { + if (!Enum.IsDefined(role)) + return new(null, new ArticulationDiagnostic("invalid_role", "role", "Select lead, bass or drums.")); + if (string.IsNullOrWhiteSpace(id)) + return new(null, new ArticulationDiagnostic("no_default_profile", role.ToString(), + "No production default is authorized. Supply an explicit evidence-backed profile ID; inspect its documented/application-verified scope.")); + var profile = Profiles.SingleOrDefault(p => p.Id == id); + if (profile is null) + return new(null, new ArticulationDiagnostic("unknown_profile", id, "No admitted profile has this ID. Obtain authorized exact-product mapping evidence and compatibility scope; there is no synthetic fallback.")); + return profile.Role == role + ? new(profile) + : new(null, new ArticulationDiagnostic("profile_role_mismatch", id, $"Select an evidence-backed {role} profile, not a {profile.Role} profile.")); + } + + public ProfileSelectionResult SelectInstrument(TrackRole role, string instrumentId, string? profileId = null) + { + if (!Enum.IsDefined(role)) + return new(null, new ArticulationDiagnostic("invalid_role", "role", "Select lead, bass or drums.")); + var entry = Instruments.SingleOrDefault(i => i.Instrument.Id == instrumentId); + if (entry is null) + return new(null, new ArticulationDiagnostic("unknown_instrument", "instrumentId", "Select a declared instrument ID; no other instrument is substituted.")); + if (entry.Instrument.Role != role) + return new(null, new ArticulationDiagnostic("instrument_role_mismatch", "instrumentId", $"The instrument does not occupy the requested {role} slot.")); + if (profileId is not null) + { + var selected = Select(role, profileId); + if (!selected.Success) + return selected; + return selected.Profile!.InstrumentId == instrumentId + ? selected + : new(null, new ArticulationDiagnostic("profile_instrument_mismatch", "profileId", "The selected profile belongs to a different instrument; supply an exact matching profile ID.")); + } + if (entry.Profiles.Count == 0) + return new(null, new ArticulationDiagnostic("mapping_unavailable", "instrumentId", "This instrument is declared but has no admitted mapping. Obtain authorized exact-product numeric mapping evidence and compatibility scope.")); + return entry.Profiles.Count == 1 + ? new(entry.Profiles[0]) + : new(null, new ArticulationDiagnostic("ambiguous_profile", "profileId", "Multiple versioned mappings are available; supply an explicit matching profile ID.")); + } +} + +public sealed class InstrumentCatalogEntry +{ + internal InstrumentCatalogEntry(InstrumentDefinition instrument, IEnumerable profiles) + { + Instrument = instrument; + Profiles = Array.AsReadOnly(profiles.ToArray()); + } + + public InstrumentDefinition Instrument { get; } + public IReadOnlyList Profiles { get; } + public string Availability => Profiles.Count == 0 ? "mapping_unavailable" : "profile_available"; +} diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Generation/Profiles/instrument-profiles.json b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Generation/Profiles/instrument-profiles.json new file mode 100644 index 0000000..dad47ea --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Generation/Profiles/instrument-profiles.json @@ -0,0 +1,228 @@ +[ + { + "id": "ample-aglp-documented-defaults-2026-10-20", + "instrumentId": "ample-aglp", + "role": "Lead", + "productName": "Ample Guitar LP", + "productVersion": "documented defaults; installed version unknown", + "mappingVersion": "published-defaults-2026-10-20.1", + "evidence": { + "status": "Documented", + "source": "https://www.amplesound.net/en/Main_Panel_Manual-AGLP.pdf", + "authorization": "Public vendor-published manual and demo MIDI analyzed for mapping facts only; no vendor assets or implementation code redistributed.", + "verificationRecord": "Retrieved 2026-10-20. Non-versioned manual, HTTP Last-Modified 2025-09-08 09:00:15 GMT, SHA256 7b28b62f3c25ecb774227b15beab06f5e0f0c944f35db9e82121028017f9cedb, PDF pp.6-7 sections 2.2.1, 2.2.3, 2.2.5: C0 Sustain, D0 Palm Mute, both E1-D5; sustain musical velocities 1-126, 127 is settings-dependent Pop/Pinch Harmonic; PM depth varies with velocity. Absolute anchor: https://www.amplesound.net/dl0822/ds/AGLP-Prison_Break.zip (HTTP Last-Modified 2019-11-24 16:33:18 GMT; SHA256 738956bced4e78a00ab755646d34108f9e25c5346ef79b96a5c1664c876f5e5f), AGLP-Prison Break/AGLP-Prison Break-Tempo100.mid, 480 PPQ; track 1 C0 note-on 24 velocity 100 at tick 3837, off 3957; track 3 D0 note-on 26 velocity 100 at 34438, off 34558. This anchors C0=24, D0=26 and E1-D5=40-86, not a guessed octave convention. File/source checks only; no installed-plugin or Cubase acceptance." + }, + "minimumPitch": 40, + "maximumPitch": 86, + "channel": 0, + "initialArticulation": null, + "initialControllers": [], + "finalResetArticulation": null, + "finalControllers": [], + "rules": [ + { + "articulation": "Sustain", + "voice": null, + "drumPitch": null, + "behavior": "Latched", + "keyswitch": { "pitch": 24, "velocity": 100, "advanceTicks": 120, "durationTicks": 30 }, + "velocity": { "minimum": 1, "maximum": 126, "outputVelocity": null }, + "controllers": [] + }, + { + "articulation": "PalmMute", + "voice": null, + "drumPitch": null, + "behavior": "Latched", + "keyswitch": { "pitch": 26, "velocity": 100, "advanceTicks": 120, "durationTicks": 30 }, + "velocity": { "minimum": 1, "maximum": 127, "outputVelocity": null }, + "controllers": [] + } + ], + "compatibilityNotes": { + "versionScope": "Non-versioned published default mapping retrieved 2026-10-20, manual revision identified by HTTP Last-Modified 2025-09-08 and hash in evidence; 2019 vendor demo is an absolute numeric anchor, not proof of any installed release. No exact installed product version or application verification is claimed.", + "configurationRequirements": "Default tuning, articulation mapping and velocity thresholds; instrument mode, not Strummer; MIDI Guitar mode disabled. Isolated idle receiver with no externally held keyswitches. Initial articulation is unknown: explicitly select only the first requested state. Sustain excludes accent velocity 127. Preserve PM dynamics. No custom presets or remapping acceptance is claimed.", + "routingPolicy": "Writer policy: Lead uses zero-based MIDI channel 0 (display channel 1); route the isolated role track to this product, accepting that channel. No per-string routing, program changes or inferred CC assignments.", + "timingPolicy": "Writer policy at 960 PPQ: latched switch velocity 100, 120-tick advance and 30-tick paired pulse; release before musical onset, never initialize both Sustain and PM. Repeated states suppress pulses; incompatible musical/control overlap fails. All musical tracks share lead-in without changing note intervals. No final articulation reset; switches are released and the last state remains selected. Timing is deterministic engineering policy, NOT a vendor minimum or real-plugin timing check." + } + }, + { + "id": "ample-ame-documented-defaults-2026-10-20", + "instrumentId": "ample-ame", + "role": "Lead", + "productName": "Ample Metal Eclipse", + "productVersion": "documented defaults; installed version unknown", + "mappingVersion": "published-defaults-2026-10-20.1", + "evidence": { + "status": "Documented", + "source": "https://www.amplesound.net/en/Main_Panel_Manual-AME.pdf", + "authorization": "Public vendor-published manual and demo MIDI analyzed for mapping facts only; no vendor assets or implementation code redistributed.", + "verificationRecord": "Retrieved 2026-10-20. Non-versioned manual, HTTP Last-Modified 2025-09-08 09:00:39 GMT, SHA256 ab482f08b0546eca0a4233b8be3776c411b77f3dca96979f529debc2dfc0c4ca, PDF pp.6-7 sections 2.2.1-2.2.4: C0 Sustain, D0 Palm Mute, both C1-C5; Sustain musical velocities 64-126 only (1-63 are mute layers, 127 is settings-dependent Pop/Pinch Harmonic); PM depth increases as velocity decreases. Absolute anchor: https://www.amplesound.net/dl0822/ds/AME-Eclipse.zip (HTTP Last-Modified 2019-11-24 17:03:34 GMT; SHA256 e448d85f9ff80692f625f23ef6ea4dd0b14367b9f92412adbb76aa6e4a987f66), AME-Eclipse/AME-Eclipse-Tempo130.mid, 480 PPQ; track 4 C0 note-on 24 velocity 100 at tick 3720, off 3840, then musical C1 note 36 at 3840. This anchors C0=24, D0=26 and C1-C5=36-84, not a guessed octave convention. Public third-party Eclipse map corroborates 24/26 only: https://github.com/zaibuyidao/ReaScripts/blob/98e88777ff4cf2e478d6bc85d35349f62acc7e41/Various/Articulation%20Map/banks/70-96%20Ample%20Metal%20Eclipse%20%28%E9%87%91%E5%B1%9E%E5%90%89%E4%BB%96%29.reabank (blob ea878807ac429bd7294b9f8a8612a9261feacb4f); no code copied. File/source checks only; no installed-plugin or Cubase acceptance." + }, + "minimumPitch": 36, + "maximumPitch": 84, + "channel": 0, + "initialArticulation": null, + "initialControllers": [], + "finalResetArticulation": null, + "finalControllers": [], + "rules": [ + { + "articulation": "Sustain", + "voice": null, + "drumPitch": null, + "behavior": "Latched", + "keyswitch": { "pitch": 24, "velocity": 100, "advanceTicks": 120, "durationTicks": 30 }, + "velocity": { "minimum": 64, "maximum": 126, "outputVelocity": null }, + "controllers": [] + }, + { + "articulation": "PalmMute", + "voice": null, + "drumPitch": null, + "behavior": "Latched", + "keyswitch": { "pitch": 26, "velocity": 100, "advanceTicks": 120, "durationTicks": 30 }, + "velocity": { "minimum": 1, "maximum": 127, "outputVelocity": null }, + "controllers": [] + } + ], + "compatibilityNotes": { + "versionScope": "Non-versioned published default mapping retrieved 2026-10-20, manual revision identified by HTTP Last-Modified 2025-09-08 and hash in evidence; 2019 vendor demo is an absolute numeric anchor, not proof of any installed release. No exact installed product version or application verification is claimed.", + "configurationRequirements": "Default tuning, articulation mapping and velocity thresholds; instrument mode, not Strummer; MIDI Guitar mode disabled. Isolated idle receiver with no externally held keyswitches. Initial articulation is unknown: explicitly select only the first requested state. Sustain accepts only 64-126 to exclude mute layers and accent. Preserve PM dynamics. No custom presets or remapping acceptance is claimed.", + "routingPolicy": "Writer policy: Lead uses zero-based MIDI channel 0 (display channel 1); route the isolated role track to this product, accepting that channel. No per-string routing, program changes or inferred CC assignments.", + "timingPolicy": "Writer policy at 960 PPQ: latched switch velocity 100, 120-tick advance and 30-tick paired pulse; release before musical onset, never initialize both Sustain and PM. Repeated states suppress pulses; incompatible musical/control overlap fails. All musical tracks share lead-in without changing note intervals. No final articulation reset; switches are released and the last state remains selected. Timing is deterministic engineering policy, NOT a vendor minimum or real-plugin timing check." + } + }, + { + "id": "ample-agm-documented-defaults-2026-10-20", + "instrumentId": "ample-agm", + "role": "Lead", + "productName": "Ample Guitar M", + "productVersion": "documented defaults; installed version unknown", + "mappingVersion": "published-defaults-2026-10-20.1", + "evidence": { + "status": "Documented", + "source": "https://www.amplesound.net/en/Main_Panel_Manual-AGM.pdf", + "authorization": "Public vendor-published manual and demo MIDI analyzed for mapping facts only; no vendor assets or implementation code redistributed.", + "verificationRecord": "Retrieved 2026-10-20. Non-versioned manual, HTTP Last-Modified 2025-09-08 09:00:15 GMT, SHA256 449bd7b8bca7771dbf8e08e0029d2bbe999f991efe441d7900ee93da29dd86a4, PDF pp.6-7 sections 2.2.1-2.2.4: C0 Sustain, D0 Palm Mute, both E1-C5; Sustain musical velocities 1-126, 127 Pop; PM depth increases as velocity decreases. Official download page https://www.amplesound.net/en/download.asp lists AGM demos. Absolute anchors: https://www.amplesound.net/dl0822/ds/AGM-Rylynn.zip (HTTP Last-Modified 2019-06-11 17:57:25 GMT; SHA256 e88c40ce4e67fde7b692b7f1cd5c4d057d7cd2a50e21d71114379b55d1fabd6f), AGM-Rylynn/AGM3-Rylynn.mid, 480 PPQ, track 1 G1 channel 0: note 24 velocity 80 on 32215/off 32335; https://www.amplesound.net/dl0822/ds/AGM-Dear_Ben.zip (HTTP Last-Modified 2019-11-24 16:38:43 GMT; SHA256 bb6dd773b5f998a1d0efa80ebc77d6661922e49f137f74a685000792ed618fe5), AGM-Dear Ben/AGM-Dear Ben Tempo 74.mid, 480 PPQ, track 1 AGM ARP channel 0: note 26 velocity 80 on 28798/off 28858, note 24 velocity 80 on 30238/off 30298. These anchor C0=24, D0=26 and E1-C5=40-84 without assuming an octave convention. File/source checks only; no installed-plugin or Cubase acceptance." + }, + "minimumPitch": 40, + "maximumPitch": 84, + "channel": 0, + "initialArticulation": null, + "initialControllers": [], + "finalResetArticulation": null, + "finalControllers": [], + "rules": [ + { + "articulation": "Sustain", + "voice": null, + "drumPitch": null, + "behavior": "Latched", + "keyswitch": { "pitch": 24, "velocity": 100, "advanceTicks": 120, "durationTicks": 30 }, + "velocity": { "minimum": 1, "maximum": 126, "outputVelocity": null }, + "controllers": [] + }, + { + "articulation": "PalmMute", + "voice": null, + "drumPitch": null, + "behavior": "Latched", + "keyswitch": { "pitch": 26, "velocity": 100, "advanceTicks": 120, "durationTicks": 30 }, + "velocity": { "minimum": 1, "maximum": 127, "outputVelocity": null }, + "controllers": [] + } + ], + "compatibilityNotes": { + "versionScope": "Non-versioned published default mapping retrieved 2026-10-20, manual HTTP Last-Modified 2025-09-08 and historical vendor demo revisions/hashes recorded in evidence. No exact installed product version or application verification is claimed; installed configuration is not verified.", + "configurationRequirements": "Default tuning, articulation mapping and velocity thresholds; instrument mode, not Strummer; MIDI Guitar mode disabled. Isolated idle receiver with no externally held keyswitches. Initial articulation is unknown: explicitly select only the first requested state. Sustain excludes Pop velocity 127. Preserve PM dynamics. No custom presets or remapping acceptance is claimed.", + "routingPolicy": "Writer policy: Lead uses zero-based MIDI channel 0 (display channel 1); route the isolated role track to this product, accepting that channel. No per-string routing, program changes or inferred CC assignments.", + "timingPolicy": "Writer policy at 960 PPQ: latched switch velocity 100, 120-tick advance and 30-tick paired pulse; release before musical onset, never initialize both Sustain and PM. Repeated states suppress pulses; incompatible musical/control overlap fails. All musical tracks share lead-in without changing note intervals. No final articulation reset; switches are released and the last state remains selected. Timing is deterministic engineering policy, NOT a vendor minimum or real-plugin timing check." + } + }, + { + "id": "ample-abj-documented-defaults-2026-10-20", + "instrumentId": "ample-abj", + "role": "Bass", + "productName": "Ample Bass J", + "productVersion": "documented defaults; installed version unknown", + "mappingVersion": "published-defaults-2026-10-20.1", + "evidence": { + "status": "Documented", + "source": "https://www.amplesound.net/en/Main_Panel_Manual-ABJ.pdf", + "authorization": "Public vendor-published manual and explicitly ABJ/ABP-shared demo MIDI analyzed for mapping facts only; no vendor assets or implementation code redistributed.", + "verificationRecord": "Retrieved 2026-10-20. Non-versioned manual, HTTP Last-Modified 2025-04-16 05:04:25 GMT, SHA256 9291c4e3027ac1469bd845bb04614f5a2754bd35a4f017bcfd7cdb75db335e7e, PDF pp.6-7 sections 2.2.1-2.2.4: C0 Sustain range B0-E4; Sustain musical velocities 1-125, 126-127 Accent. The dedicated D0 PM/Dead Note split has no numeric threshold, so PM is NOT admitted. Absolute anchor: official https://www.amplesound.net/en/download.asp row Project - Ample Bass Articulations explicitly lists products ABJ ABP, linking https://www.amplesound.net/dl0822/ds/AB-Articulations.zip (HTTP Last-Modified 2019-06-11 17:32:45 GMT; SHA256 c3efc1dc787c59a00be7405687488317efaf952822aededf54b9e19f4e145cb7). Entry AB-Articulations/4.2 Articulations & Poly Legato.mid, 480 PPQ, track 1 ABP channel 0: note 24 velocity 90 on 3720/off 4080, musical note 40 velocity 90 on 3840. This is vendor-listed shared applicability, NOT an independently ABJ-named performance. It anchors C0=24 and B0-E4=35-76. Sustain-only capability; no PM fallback or transformation. File/source checks only; no installed-plugin or Cubase acceptance." + }, + "minimumPitch": 35, + "maximumPitch": 76, + "channel": 1, + "initialArticulation": null, + "initialControllers": [], + "finalResetArticulation": null, + "finalControllers": [], + "rules": [ + { + "articulation": "Sustain", + "voice": null, + "drumPitch": null, + "behavior": "Latched", + "keyswitch": { "pitch": 24, "velocity": 100, "advanceTicks": 120, "durationTicks": 30 }, + "velocity": { "minimum": 1, "maximum": 125, "outputVelocity": null }, + "controllers": [] + } + ], + "compatibilityNotes": { + "versionScope": "Non-versioned published default Sustain-only mapping retrieved 2026-10-20, manual HTTP Last-Modified 2025-04-16 and 2019 vendor demo revision/hash recorded in evidence. Shared ABJ/ABP applicability is explicitly vendor-listed; the MIDI track is named ABP, not an independent ABJ performance. No exact installed product version or application verification is claimed.", + "configurationRequirements": "Default tuning, articulation mapping and velocity thresholds; instrument mode; MIDI Guitar mode disabled. Isolated idle receiver with no externally held keyswitches. Initial articulation is unknown: explicitly select Sustain. Only Sustain musical velocities 1-125 are supported; accents 126-127 and PalmMute are rejected, never transformed or silently substituted. Dedicated PM/Dead Note threshold is undocumented and not guessed.", + "routingPolicy": "Writer policy: Bass uses zero-based MIDI channel 1 (display channel 2), distinct from Lead channel 0. Route the isolated Bass track to Ample Bass J accepting channel 1; historical demo channel 0 is NOT a mandatory receiver channel. No per-string routing, program changes or inferred CC assignments.", + "timingPolicy": "Writer policy at 960 PPQ: latched switch velocity 100, 120-tick advance and 30-tick paired pulse; release before musical onset. Only Sustain is selected, never a Sustain/PM combination. Repeated states suppress pulses. All musical tracks share lead-in without changing note intervals. No final articulation reset; switches are released and the last state remains selected. Timing and routing are deterministic engineering policies, NOT a vendor minimum or real-plugin timing check." + } + }, + { + "id": "ample-agt-documented-defaults-2026-10-20", + "instrumentId": "ample-agt", + "role": "Lead", + "productName": "Ample Guitar T", + "productVersion": "documented defaults; installed version unknown", + "mappingVersion": "published-defaults-2026-10-20.1", + "evidence": { + "status": "Documented", + "source": "https://www.amplesound.net/en/Main_Panel_Manual-AGT.pdf", + "authorization": "Public vendor-published main-panel/Tab Player documentation and explicitly AGT/AGM-shared tab-project MIDI analyzed for mapping facts only; no vendor assets or implementation code redistributed.", + "verificationRecord": "Retrieved 2026-10-20. Non-versioned AGT main-panel manual, HTTP Last-Modified 2025-09-08 09:00:02 GMT, SHA256 2e5696d750841a47061d37737ec7d8435cb4e30756cda15596d1f89ff87810dd, PDF pp.6-7 sections 2.2.1-2.2.4: C0 Sustain, D0 PM, both E1-C5; Sustain musical velocities 1-126, 127 Pop; PM depth follows velocity. Genuine named-note anchor: official rendered https://www.amplesound.net/en/tutorial-b.asp section 6.3 Tab Play Toggle explicitly names MIDI note A6 as the tab-play control (high velocity on, low off); HTML source SHA256 542ae25caec1dfea772fbe9f5cc80be0c12ad3104f057e654410226aa1e69e92, no HTTP Last-Modified supplied. Official download row lists AGT AGM Tab Project - Wish You Were Here: https://www.amplesound.net/dl0822/ds/AGT-Wish_You_Were_Here.zip (HTTP Last-Modified 2019-06-11 18:04:59 GMT; SHA256 82a9b42109519d20d9340c6c6cdb972a66663482df483fd0bf5034b84b5d9262). Exact entry AGT-Wish_You_Were_Here/AGT3-Wish You Were Here Tempo 62.mid, 480 PPQ, tracks 1 Solo and 2 Strum each contain only tab-control note 105 velocity 80 channel 0 on 3840/off 4320. Matching the documented A6 control to numeric 105 establishes C0=105-(6*12+9)=24, D0=26, E1-C5=40-84; NOT a label inferred from an assumed octave convention or a direct Sustain/PM performance. Historical default source scope, not installed-release verification. No tab-play event is generated by this profile. File/source checks only; no installed-plugin or Cubase acceptance." + }, + "minimumPitch": 40, + "maximumPitch": 84, + "channel": 0, + "initialArticulation": null, + "initialControllers": [], + "finalResetArticulation": null, + "finalControllers": [], + "rules": [ + { + "articulation": "Sustain", + "voice": null, + "drumPitch": null, + "behavior": "Latched", + "keyswitch": { "pitch": 24, "velocity": 100, "advanceTicks": 120, "durationTicks": 30 }, + "velocity": { "minimum": 1, "maximum": 126, "outputVelocity": null }, + "controllers": [] + }, + { + "articulation": "PalmMute", + "voice": null, + "drumPitch": null, + "behavior": "Latched", + "keyswitch": { "pitch": 26, "velocity": 100, "advanceTicks": 120, "durationTicks": 30 }, + "velocity": { "minimum": 1, "maximum": 127, "outputVelocity": null }, + "controllers": [] + } + ], + "compatibilityNotes": { + "versionScope": "Non-versioned published default mapping retrieved 2026-10-20; current main-panel source and historical official Tab Player section 6.3/AGT3 demo revisions are separate from an installed release. Numeric anchor is named A6=105 tab control, NOT a direct Sustain/PM performance. No exact installed product version or application verification is claimed.", + "configurationRequirements": "Default tuning, articulation mapping and velocity thresholds; instrument mode, not Strummer or Tab Player; MIDI Guitar mode disabled. Isolated idle receiver with no externally held keyswitches. Initial articulation is unknown: explicitly select only the first requested state. Sustain excludes Pop velocity 127. Preserve PM dynamics. No tab-play triggering, custom presets or remapping acceptance is claimed.", + "routingPolicy": "Writer policy: Lead uses zero-based MIDI channel 0 (display channel 1); route the isolated role track to this product, accepting that channel. No per-string routing, program changes or inferred CC assignments.", + "timingPolicy": "Writer policy at 960 PPQ: latched switch velocity 100, 120-tick advance and 30-tick paired pulse; release before musical onset, never initialize both Sustain and PM. Repeated states suppress pulses; incompatible musical/control overlap fails. All musical tracks share lead-in without changing note intervals. No final articulation reset; switches are released and the last state remains selected. Timing is deterministic engineering policy, NOT a vendor minimum or real-plugin timing check." + } + } +] diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Generation/packages.lock.json b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Generation/packages.lock.json new file mode 100644 index 0000000..b81cbec --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Generation/packages.lock.json @@ -0,0 +1,16 @@ +{ + "version": 2, + "dependencies": { + "net10.0": { + "Melanchall.DryWetMidi": { + "type": "Direct", + "requested": "[8.0.3, 8.0.3]", + "resolved": "8.0.3", + "contentHash": "U+Ubol4MhieY2xgZGqcI8H2F/4HWzWKq8/WPHd1SXS7WXaHyEWMnj56vtxKOJFM5FLbj+NOUny5+X2KAzI0YUg==" + }, + "gaj3t.musicgen.riffgroovebuilder.core": { + "type": "Project" + } + } + } +} \ No newline at end of file diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Server/GAJ3T.MusicGen.RiffGrooveBuilder.Server.csproj b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Server/GAJ3T.MusicGen.RiffGrooveBuilder.Server.csproj new file mode 100644 index 0000000..9acf7fb --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Server/GAJ3T.MusicGen.RiffGrooveBuilder.Server.csproj @@ -0,0 +1,13 @@ + + + + + + + + + Exe + net10.0 + + + diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Server/Program.cs b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Server/Program.cs new file mode 100644 index 0000000..df53107 --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Server/Program.cs @@ -0,0 +1,31 @@ +using System.Text; +using GAJ3T.MusicGen.RiffGrooveBuilder.Server.Protocol; +using GAJ3T.MusicGen.RiffGrooveBuilder.Server.Tools; + +Console.OutputEncoding = new UTF8Encoding(false); +using var stopping = new CancellationTokenSource(); +ConsoleCancelEventHandler onCancel = (_, args) => +{ + args.Cancel = true; + stopping.Cancel(); +}; +Console.CancelKeyPress += onCancel; + +try +{ + using var input = Console.OpenStandardInput(); + using var output = Console.OpenStandardOutput(); + using var transport = new StdioTransport(input, output); + var session = new McpSession(MusicGenTools.CreateRegistry()); + await new JsonRpcDispatcher(transport, session, Console.Error).RunAsync(stopping.Token); + return 0; +} +catch (Exception exception) +{ + await Console.Error.WriteLineAsync($"Fatal stdio failure: {exception}"); + return 1; +} +finally +{ + Console.CancelKeyPress -= onCancel; +} diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Server/Properties/PublishProfiles/win-x64.pubxml b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Server/Properties/PublishProfiles/win-x64.pubxml new file mode 100644 index 0000000..d2eed7e --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Server/Properties/PublishProfiles/win-x64.pubxml @@ -0,0 +1,13 @@ + + + Release + win-x64 + true + true + false + false + true + true + $(MSBuildProjectDirectory)\packages.win-x64.lock.json + + diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Server/Protocol/JsonRpcDispatcher.cs b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Server/Protocol/JsonRpcDispatcher.cs new file mode 100644 index 0000000..2c0c725 --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Server/Protocol/JsonRpcDispatcher.cs @@ -0,0 +1,245 @@ +using System.Runtime.ExceptionServices; +using System.Text.Json; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.Server.Protocol; + +public sealed class JsonRpcDispatcher(StdioTransport transport, McpSession session, TextWriter diagnostics) +{ + public const int MaxActiveRequests = 64; + private readonly object _gate = new(); + private readonly Dictionary _active = []; + private ExceptionDispatchInfo? _fatal; + + private readonly record struct RequestId(string? Text, long? Integer) + { + public static bool TryParse(JsonElement value, out RequestId id) + { + if (value.ValueKind == JsonValueKind.String) + { + id = new(value.GetString(), null); + return true; + } + + if (value.ValueKind == JsonValueKind.Number && value.TryGetInt64(out var number)) + { + id = new(null, number); + return true; + } + + id = default; + return false; + } + } + + private sealed class ActiveRequest(string method, CancellationTokenSource cancellation) + { + public string Method { get; } = method; + public CancellationTokenSource Cancellation { get; } = cancellation; + public TaskCompletionSource Completion { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + } + + public async Task RunAsync(CancellationToken cancellationToken = default) + { + using var stopping = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + try + { + while (await transport.ReadFrameAsync(stopping.Token) is { } frame) + { + if (frame.Error is not null) + { + await diagnostics.WriteLineAsync(frame.Error.Message); + await WriteErrorAsync(null, frame.Error); + continue; + } + + await DispatchAsync(frame.Json!, stopping); + } + } + catch (OperationCanceledException) when (stopping.IsCancellationRequested) + { + } + finally + { + stopping.Cancel(); + Task[] pending; + lock (_gate) + { + pending = _active.Values.Select(request => request.Completion.Task).ToArray(); + } + + await Task.WhenAll(pending); + } + + _fatal?.Throw(); + } + + private async Task DispatchAsync(string json, CancellationTokenSource stopping) + { + JsonDocument document; + try + { + document = JsonDocument.Parse(json); + } + catch (JsonException) + { + await WriteErrorAsync(null, new(JsonRpcError.ParseError, "Parse error.")); + return; + } + + using (document) + { + var root = document.RootElement; + JsonElement? responseId = null; + var key = default(RequestId); + var hasId = root.ValueKind == JsonValueKind.Object && root.TryGetProperty("id", out _); + if (hasId && root.EnumerateObject().Count(p => p.Name == "id") == 1 && + RequestId.TryParse(root.GetProperty("id"), out key)) + { + responseId = root.GetProperty("id").Clone(); + } + + if (root.ValueKind != JsonValueKind.Object || + root.EnumerateObject().GroupBy(p => p.Name, StringComparer.Ordinal).Any(g => g.Count() > 1) || + !root.TryGetProperty("jsonrpc", out var version) || version.ValueKind != JsonValueKind.String || + version.GetString() != "2.0" || + !root.TryGetProperty("method", out var method) || method.ValueKind != JsonValueKind.String || + root.TryGetProperty("result", out _) || root.TryGetProperty("error", out _) || + (hasId && responseId is null)) + { + await WriteErrorAsync(responseId, new(JsonRpcError.InvalidRequest, "Invalid request.")); + return; + } + + var name = method.GetString()!; + JsonElement? parameters = root.TryGetProperty("params", out var supplied) ? supplied.Clone() : null; + if (!hasId) + { + try + { + if (name == "notifications/cancelled") + { + Cancel(parameters); + } + else if (name == "notifications/initialized") + { + session.HandleNotification(name, parameters); + } + else + { + await diagnostics.WriteLineAsync("Ignored unsupported notification."); + } + } + catch (JsonRpcError) + { + await diagnostics.WriteLineAsync("Ignored invalid notification."); + } + + return; + } + + ActiveRequest? active = null; + JsonRpcError? rejection = null; + lock (_gate) + { + if (_active.ContainsKey(key)) + { + rejection = new(JsonRpcError.InvalidRequest, "Request ID is already active."); + } + else if (_active.Count >= MaxActiveRequests) + { + rejection = new(JsonRpcError.Busy, "Too many active requests."); + } + else + { + active = new(name, CancellationTokenSource.CreateLinkedTokenSource(stopping.Token)); + _active.Add(key, active); + } + } + + if (rejection is not null) + { + await WriteErrorAsync(responseId, rejection); + return; + } + + // Executes up to the first await before reading the next frame, preserving lifecycle order. + _ = ExecuteAsync(key, responseId!.Value, name, parameters, active!, stopping); + } + } + + private async Task ExecuteAsync(RequestId key, JsonElement id, string method, JsonElement? parameters, + ActiveRequest active, CancellationTokenSource stopping) + { + try + { + JsonElement response; + try + { + var result = await session.HandleRequestAsync(method, parameters, active.Cancellation.Token); + active.Cancellation.Token.ThrowIfCancellationRequested(); + response = JsonSerializer.SerializeToElement(new { jsonrpc = "2.0", id, result }); + } + catch (OperationCanceledException) when (active.Cancellation.IsCancellationRequested) + { + return; + } + catch (JsonRpcError error) + { + response = JsonSerializer.SerializeToElement(ErrorResponse(id, error)); + } + catch (Exception exception) + { + await diagnostics.WriteLineAsync($"Request handler failed: {exception}"); + response = JsonSerializer.SerializeToElement(ErrorResponse(id, new(JsonRpcError.InternalError, "Internal error."))); + } + + if (!active.Cancellation.IsCancellationRequested) + { + // I/O failures are fatal, not converted into a second response or a success. + await transport.WriteMessageAsync(response); + } + } + catch (Exception exception) + { + lock (_gate) + { + _fatal ??= ExceptionDispatchInfo.Capture(exception); + } + + stopping.Cancel(); + } + finally + { + lock (_gate) + { + _active.Remove(key); + active.Cancellation.Dispose(); + active.Completion.SetResult(); + } + } + } + + private void Cancel(JsonElement? parameters) + { + var input = McpParameters.Object(parameters, true, "requestId", "reason"); + if (!input.TryGetProperty("requestId", out var value) || !RequestId.TryParse(value, out var id)) + { + throw McpParameters.Invalid(); + } + + McpParameters.OptionalKind(input, "reason", JsonValueKind.String); + lock (_gate) + { + if (_active.TryGetValue(id, out var request) && request.Method != "initialize") + { + request.Cancellation.Cancel(); + } + } + } + + private Task WriteErrorAsync(JsonElement? id, JsonRpcError error) => + transport.WriteMessageAsync(ErrorResponse(id, error)); + + private static object ErrorResponse(JsonElement? id, JsonRpcError error) => + new { jsonrpc = "2.0", id, error = new { code = error.Code, message = error.Message } }; +} diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Server/Protocol/JsonRpcError.cs b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Server/Protocol/JsonRpcError.cs new file mode 100644 index 0000000..42893e1 --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Server/Protocol/JsonRpcError.cs @@ -0,0 +1,14 @@ +namespace GAJ3T.MusicGen.RiffGrooveBuilder.Server.Protocol; + +public sealed class JsonRpcError(int code, string message) : Exception(message) +{ + public const int ParseError = -32700; + public const int InvalidRequest = -32600; + public const int MethodNotFound = -32601; + public const int InvalidParams = -32602; + public const int InternalError = -32603; + public const int InvalidState = -32002; + public const int Busy = -32000; + + public int Code { get; } = code; +} diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Server/Protocol/McpParameters.cs b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Server/Protocol/McpParameters.cs new file mode 100644 index 0000000..952bb89 --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Server/Protocol/McpParameters.cs @@ -0,0 +1,50 @@ +using System.Text.Json; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.Server.Protocol; + +internal static class McpParameters +{ + public static JsonElement Object(JsonElement? value, bool required, params string[] fields) + { + var result = value ?? JsonSerializer.SerializeToElement(new { }); + if ((required && value is null) || result.ValueKind != JsonValueKind.Object || + result.EnumerateObject().GroupBy(p => p.Name, StringComparer.Ordinal).Any(g => g.Count() > 1) || + result.EnumerateObject().Any(p => p.Name != "_meta" && !fields.Contains(p.Name, StringComparer.Ordinal)) || + (result.TryGetProperty("_meta", out var meta) && meta.ValueKind != JsonValueKind.Object)) + { + throw Invalid(); + } + + return result; + } + + public static void RequestMetadata(JsonElement input) + { + if (input.TryGetProperty("_meta", out var meta) && + meta.TryGetProperty("progressToken", out var progress) && + progress.ValueKind is not JsonValueKind.String and not JsonValueKind.Number) + { + throw Invalid(); + } + } + + public static string String(JsonElement value, string name) + { + if (!value.TryGetProperty(name, out var member) || member.ValueKind != JsonValueKind.String) + { + throw Invalid(); + } + + return member.GetString()!; + } + + public static void OptionalKind(JsonElement value, string name, JsonValueKind kind) + { + if (value.TryGetProperty(name, out var member) && member.ValueKind != kind) + { + throw Invalid(); + } + } + + public static JsonRpcError Invalid() => new(JsonRpcError.InvalidParams, "Invalid method parameters."); +} diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Server/Protocol/McpSession.cs b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Server/Protocol/McpSession.cs new file mode 100644 index 0000000..c577250 --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Server/Protocol/McpSession.cs @@ -0,0 +1,211 @@ +using System.Text.Json; +using GAJ3T.MusicGen.RiffGrooveBuilder.Server.Tools; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.Server.Protocol; + +public sealed class McpSession +{ + public const string ProtocolVersion = "2025-11-25"; + private readonly McpToolRegistry _registry; + private readonly object _gate = new(); + private SessionState _state; + + private enum SessionState { New, AwaitingInitialized, Ready } + + public McpSession(McpToolRegistry registry) + { + _registry = registry; + registry.Freeze(); + } + + public async Task HandleRequestAsync( + string method, JsonElement? parameters, CancellationToken cancellationToken) + { + if (method == "ping") + { + McpParameters.RequestMetadata(McpParameters.Object(parameters, required: false)); + return new { }; + } + + if (method == "initialize") + { + var input = McpParameters.Object(parameters, true, "protocolVersion", "capabilities", "clientInfo"); + McpParameters.RequestMetadata(input); + ValidateInitialization(input); + lock (_gate) + { + if (_state != SessionState.New) + { + throw new JsonRpcError(JsonRpcError.InvalidState, "Session is already initialized."); + } + + _state = SessionState.AwaitingInitialized; + } + + return new + { + protocolVersion = ProtocolVersion, + capabilities = new { tools = new { listChanged = false } }, + serverInfo = new { name = "GAJ3T.MusicGen.RiffGrooveBuilder", version = "0.2.0" } + }; + } + + if (method is not "tools/list" and not "tools/call") + { + throw new JsonRpcError(JsonRpcError.MethodNotFound, "Method not found."); + } + + lock (_gate) + { + if (_state != SessionState.Ready) + { + throw new JsonRpcError(JsonRpcError.InvalidState, "Complete the MCP initialization handshake first."); + } + } + + if (method == "tools/list") + { + var input = McpParameters.Object(parameters, false, "cursor"); + McpParameters.RequestMetadata(input); + McpParameters.OptionalKind(input, "cursor", JsonValueKind.String); + if (input.TryGetProperty("cursor", out _)) + { + throw new JsonRpcError(JsonRpcError.InvalidParams, "No pagination cursor is valid for this registry."); + } + + return new { tools = _registry.List() }; + } + + var call = McpParameters.Object(parameters, true, "name", "arguments"); + McpParameters.RequestMetadata(call); + var name = McpParameters.String(call, "name"); + McpParameters.OptionalKind(call, "arguments", JsonValueKind.Object); + var tool = _registry.Find(name) + ?? throw new JsonRpcError(JsonRpcError.InvalidParams, "Unknown tool."); + var arguments = call.TryGetProperty("arguments", out var supplied) + ? supplied : JsonSerializer.SerializeToElement(new { }); + return await tool.InvokeAsync(arguments, cancellationToken); + } + + public void HandleNotification(string method, JsonElement? parameters) + { + if (method != "notifications/initialized") + { + return; + } + + McpParameters.Object(parameters, required: false); + lock (_gate) + { + if (_state != SessionState.AwaitingInitialized) + { + throw new JsonRpcError(JsonRpcError.InvalidState, "Unexpected initialized notification."); + } + + _state = SessionState.Ready; + } + } + + private static void ValidateInitialization(JsonElement input) + { + McpParameters.String(input, "protocolVersion"); + if (!input.TryGetProperty("capabilities", out var capabilities) || + capabilities.ValueKind != JsonValueKind.Object || + !input.TryGetProperty("clientInfo", out var info) || info.ValueKind != JsonValueKind.Object) + { + throw McpParameters.Invalid(); + } + + McpParameters.String(info, "name"); + McpParameters.String(info, "version"); + foreach (var field in new[] { "title", "description", "websiteUrl" }) + { + McpParameters.OptionalKind(info, field, JsonValueKind.String); + } + + if (info.TryGetProperty("icons", out var icons)) + { + if (icons.ValueKind != JsonValueKind.Array) + { + throw McpParameters.Invalid(); + } + + foreach (var icon in icons.EnumerateArray()) + { + if (icon.ValueKind != JsonValueKind.Object) + { + throw McpParameters.Invalid(); + } + + McpParameters.String(icon, "src"); + McpParameters.OptionalKind(icon, "mimeType", JsonValueKind.String); + McpParameters.OptionalKind(icon, "theme", JsonValueKind.String); + if (icon.TryGetProperty("theme", out var theme) && theme.GetString() is not "light" and not "dark") + { + throw McpParameters.Invalid(); + } + + if (icon.TryGetProperty("sizes", out var sizes) && + (sizes.ValueKind != JsonValueKind.Array || + sizes.EnumerateArray().Any(size => size.ValueKind != JsonValueKind.String))) + { + throw McpParameters.Invalid(); + } + } + } + + foreach (var field in new[] { "experimental", "roots", "sampling", "elicitation", "tasks" }) + { + McpParameters.OptionalKind(capabilities, field, JsonValueKind.Object); + } + + if (capabilities.TryGetProperty("experimental", out var experimental) && + experimental.EnumerateObject().Any(property => property.Value.ValueKind != JsonValueKind.Object)) + { + throw McpParameters.Invalid(); + } + + if (capabilities.TryGetProperty("roots", out var roots) && + roots.TryGetProperty("listChanged", out var changed) && + changed.ValueKind is not JsonValueKind.True and not JsonValueKind.False) + { + throw McpParameters.Invalid(); + } + + ValidateCapabilityObjects(capabilities); + } + + private static void ValidateCapabilityObjects(JsonElement capabilities) + { + foreach (var (name, children) in new[] + { + ("sampling", new[] { "context", "tools" }), + ("elicitation", new[] { "form", "url" }), + ("tasks", new[] { "list", "cancel", "requests" }) + }) + { + if (!capabilities.TryGetProperty(name, out var capability)) + { + continue; + } + + foreach (var child in children) + { + McpParameters.OptionalKind(capability, child, JsonValueKind.Object); + } + } + + if (capabilities.TryGetProperty("tasks", out var tasks) && + tasks.TryGetProperty("requests", out var requests)) + { + foreach (var (name, method) in new[] { ("sampling", "createMessage"), ("elicitation", "create") }) + { + McpParameters.OptionalKind(requests, name, JsonValueKind.Object); + if (requests.TryGetProperty(name, out var capability)) + { + McpParameters.OptionalKind(capability, method, JsonValueKind.Object); + } + } + } + } +} diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Server/Protocol/StdioTransport.cs b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Server/Protocol/StdioTransport.cs new file mode 100644 index 0000000..c18030c --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Server/Protocol/StdioTransport.cs @@ -0,0 +1,110 @@ +using System.Text; +using System.Text.Json; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.Server.Protocol; + +public sealed record StdioFrame(string? Json, JsonRpcError? Error = null); + +public sealed class StdioTransport : IDisposable +{ + public const int DefaultMaxFrameBytes = 1024 * 1024; + private static readonly UTF8Encoding StrictUtf8 = new(false, true); + private readonly Stream _input; + private readonly Stream _output; + private readonly int _maxFrameBytes; + private readonly byte[] _readBuffer = new byte[4096]; + private readonly byte[] _frameBuffer; + private readonly SemaphoreSlim _writer = new(1, 1); + private int _position; + private int _available; + private bool _eof; + + public StdioTransport(Stream input, Stream output, int maxFrameBytes = DefaultMaxFrameBytes) + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxFrameBytes); + _input = input; + _output = output; + _maxFrameBytes = maxFrameBytes; + _frameBuffer = new byte[checked(maxFrameBytes + 1)]; + } + + public async ValueTask ReadFrameAsync(CancellationToken cancellationToken = default) + { + var length = 0; + var oversized = false; + while (!_eof) + { + if (_position == _available) + { + // WaitAsync also bounds shutdown for streams whose pending read cannot be interrupted. + _available = await _input.ReadAsync(_readBuffer, cancellationToken) + .AsTask().WaitAsync(cancellationToken); + _position = 0; + if (_available == 0) + { + _eof = true; + break; + } + } + + var value = _readBuffer[_position++]; + if (value == (byte)'\n') + { + return Decode(length, oversized, stripCarriageReturn: true); + } + + if (length < _frameBuffer.Length) + { + _frameBuffer[length++] = value; + } + else + { + oversized = true; + } + } + + return length == 0 && !oversized ? null : Decode(length, oversized, stripCarriageReturn: false); + } + + private StdioFrame Decode(int length, bool oversized, bool stripCarriageReturn) + { + if (stripCarriageReturn && length > 0 && _frameBuffer[length - 1] == (byte)'\r') + { + length--; + } + + if (oversized || length > _maxFrameBytes) + { + return new(null, new(JsonRpcError.InvalidRequest, "Frame exceeds the byte limit.")); + } + + try + { + return new(StrictUtf8.GetString(_frameBuffer, 0, length)); + } + catch (DecoderFallbackException) + { + return new(null, new(JsonRpcError.ParseError, "Frame is not valid UTF-8.")); + } + } + + public async Task WriteMessageAsync(object message) + { + var bytes = JsonSerializer.SerializeToUtf8Bytes(message); + await _writer.WaitAsync(); + try + { + // Once a write starts, request cancellation must not truncate the protocol frame. + await _output.WriteAsync(bytes); + await _output.WriteAsync("\n"u8.ToArray()); + await _output.FlushAsync(); + } + finally + { + _writer.Release(); + } + } + + // Streams are borrowed; their owner controls their lifetime. + public void Dispose() => _writer.Dispose(); +} diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Server/Tools/McpToolDefinition.cs b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Server/Tools/McpToolDefinition.cs new file mode 100644 index 0000000..052226b --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Server/Tools/McpToolDefinition.cs @@ -0,0 +1,115 @@ +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Text.Json.Schema; +using System.Text.Json.Serialization; +using System.Text.Json.Serialization.Metadata; +using GAJ3T.MusicGen.RiffGrooveBuilder.Server.Protocol; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.Server.Tools; + +public sealed record McpToolOutcome(T StructuredContent, bool IsError = false) where T : class; + +public sealed class McpToolInputException(string message) : Exception(message); + +public abstract class McpToolDefinition +{ + public abstract object Descriptor { get; } + public abstract string Name { get; } + public abstract Task InvokeAsync(JsonElement arguments, CancellationToken cancellationToken); +} + +public sealed class McpToolDefinition : McpToolDefinition + where TInput : class where TOutput : class +{ + private static readonly JsonSerializerOptions JsonOptions = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow, + AllowDuplicateProperties = false, + RespectNullableAnnotations = true, + RespectRequiredConstructorParameters = true, + TypeInfoResolver = new DefaultJsonTypeInfoResolver(), + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase, allowIntegerValues: false) } + }; + + private readonly Func>> _handler; + private readonly Action? _validate; + private readonly Action? _validateArguments; + + public McpToolDefinition( + string name, string description, + Func>> handler, + Action? validate = null, JsonNode? inputSchema = null, + Action? configureOutputSchema = null, Action? validateArguments = null) + { + if (name.Length is < 1 or > 128 || + name.Any(c => !char.IsAsciiLetterOrDigit(c) && c is not '_' and not '-' and not '.')) + { + throw new ArgumentException("Invalid MCP tool name.", nameof(name)); + } + + Name = name; + _handler = handler; + _validate = validate; + _validateArguments = validateArguments; + var exporter = new JsonSchemaExporterOptions + { + TreatNullObliviousAsNonNullable = true, + TransformSchemaNode = (_, node) => + { + if (node is JsonObject obj && obj.ContainsKey("properties")) + obj["additionalProperties"] = false; + if (node is JsonObject enumObject && enumObject["enum"] is JsonArray values) + enumObject["type"] = values.Any(v => v is null) + ? new JsonArray("string", "null") : JsonValue.Create("string"); + return node; + } + }; + inputSchema ??= JsonOptions.GetJsonSchemaAsNode(typeof(TInput), exporter); + var outputSchema = JsonOptions.GetJsonSchemaAsNode(typeof(TOutput), exporter); + configureOutputSchema?.Invoke(outputSchema); + if (inputSchema["type"]?.ToString() != "object" || outputSchema["type"]?.ToString() != "object") + { + throw new ArgumentException("Tool input and output contracts must be non-null JSON objects."); + } + + Descriptor = new { name, description, inputSchema, outputSchema }; + } + + public override string Name { get; } + public override object Descriptor { get; } + + public override async Task InvokeAsync(JsonElement arguments, CancellationToken cancellationToken) + { + TInput input; + try + { + if (arguments.ValueKind != JsonValueKind.Object) + throw new McpToolInputException("Tool arguments must be an object."); + _validateArguments?.Invoke(arguments); + input = arguments.Deserialize(JsonOptions) + ?? throw new JsonException("Tool arguments must not be null."); + _validate?.Invoke(input); + } + catch (Exception exception) when (exception is JsonException or McpToolInputException) + { + throw new JsonRpcError(JsonRpcError.InvalidParams, "Tool arguments do not satisfy the input contract."); + } + + cancellationToken.ThrowIfCancellationRequested(); + var outcome = await _handler(input, cancellationToken); + cancellationToken.ThrowIfCancellationRequested(); + var structuredContent = JsonSerializer.SerializeToElement(outcome.StructuredContent, JsonOptions); + if (structuredContent.ValueKind != JsonValueKind.Object) + { + throw new InvalidOperationException("Tool returned a non-object result."); + } + + return new + { + structuredContent, + content = new[] { new { type = "text", text = structuredContent.GetRawText() } }, + isError = outcome.IsError + }; + } +} diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Server/Tools/McpToolRegistry.cs b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Server/Tools/McpToolRegistry.cs new file mode 100644 index 0000000..85757e6 --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Server/Tools/McpToolRegistry.cs @@ -0,0 +1,49 @@ +namespace GAJ3T.MusicGen.RiffGrooveBuilder.Server.Tools; + +public sealed class McpToolRegistry +{ + private readonly Dictionary _tools = new(StringComparer.Ordinal); + private readonly object _gate = new(); + private bool _frozen; + + public void Register(McpToolDefinition tool) + { + lock (_gate) + { + if (_frozen) + { + throw new InvalidOperationException("Register tools before starting a session."); + } + + if (!_tools.TryAdd(tool.Name, tool)) + { + throw new ArgumentException("Tool name is already registered.", nameof(tool)); + } + } + } + + internal void Freeze() + { + lock (_gate) + { + _frozen = true; + } + } + + public object[] List() + { + lock (_gate) + { + return _tools.Values.OrderBy(tool => tool.Name, StringComparer.Ordinal) + .Select(tool => tool.Descriptor).ToArray(); + } + } + + public McpToolDefinition? Find(string name) + { + lock (_gate) + { + return _tools.GetValueOrDefault(name); + } + } +} diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Server/Tools/MusicGenTools.cs b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Server/Tools/MusicGenTools.cs new file mode 100644 index 0000000..5da1328 --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Server/Tools/MusicGenTools.cs @@ -0,0 +1,95 @@ +using System.Text.Json; +using System.Text.Json.Nodes; +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Generation; +using GAJ3T.MusicGen.RiffGrooveBuilder.Generation; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.Server.Tools; + +public static class MusicGenTools +{ + public static McpToolRegistry CreateRegistry(GenerationService? service = null) + { + service ??= new GenerationService(); + var registry = new McpToolRegistry(); + registry.Register(new McpToolDefinition( + "list_instrument_profiles", "Discover declared instruments, admitted mappings and truthful writer/evidence capabilities.", + async (request, token) => new(await Task.Run(() => service.ListInstrumentProfiles(request), token)), + inputSchema: JsonNode.Parse(""" + { + "type":"object","additionalProperties":false, + "properties":{"role":{"type":"string","enum":["lead","bass","drums"]}} + } + """)!, + validateArguments: arguments => + { + if (arguments.TryGetProperty("role", out var role) && + (role.ValueKind != JsonValueKind.String || role.GetString() is not ("lead" or "bass" or "drums"))) + throw new McpToolInputException("Use lead, bass or drums; omit the filter for all."); + })); + registry.Register(new McpToolDefinition( + "generate_project", "Generate safe Standard MIDI from supported text and explicit admitted profiles; unavailable native writers require explicit MIDI fallback.", + async (request, token) => + { + var result = await service.GenerateAsync(request, token); + return new(result, result.Status == GenerationStatus.Failed); + }, + validate: ValidateRequest, + inputSchema: JsonNode.Parse(""" + { + "type":"object","additionalProperties":false, + "required":["description","outputDirectory","projectName"], + "properties":{ + "description":{"type":"string","minLength":1,"maxLength":16384}, + "outputDirectory":{"type":"string","minLength":1}, + "projectName":{"type":"string","minLength":1}, + "formats":{"type":"array","minItems":1,"uniqueItems":true, + "items":{"type":"string","enum":["agp","sdp","mid"]}}, + "profiles":{"type":"object","additionalProperties":false,"properties":{ + "lead":{"type":"string","minLength":1}, + "bass":{"type":"string","minLength":1}, + "drums":{"type":"string","minLength":1}}}, + "fallbackToMidi":{"type":"boolean","default":true} + } + } + """)!, + configureOutputSchema: schema => + { + var artifact = schema["properties"]!["artifacts"]!["items"]!["properties"]!; + artifact["byteCount"]!["minimum"] = 1; + artifact["absolutePath"]!["minLength"] = 1; + artifact["roles"]!["minItems"] = 1; + artifact["profileIds"]!["minItems"] = 1; + schema["allOf"] = JsonNode.Parse(""" + [{ + "if":{"properties":{"status":{"enum":["complete","fallback"]}},"required":["status"]}, + "then":{"properties":{ + "interpretedComposition":{"type":"object"},"timing":{"type":"object"}, + "artifacts":{"minItems":1},"targets":{"minItems":1},"errors":{"maxItems":0}}}, + "else":{"properties":{"artifacts":{"maxItems":0},"errors":{"minItems":1}}} + }] + """); + }, + validateArguments: ValidateArguments)); + return registry; + } + + private static void ValidateRequest(GenerateProjectRequest request) + { + if (request.Description.Length is < 1 or > 16384 || + request.OutputDirectory.Length == 0 || request.ProjectName.Length == 0 || + request.Formats is { } formats && (formats.Count == 0 || formats.Distinct().Count() != formats.Count)) + throw new McpToolInputException("Arguments violate length or formats constraints."); + } + + private static void ValidateArguments(JsonElement arguments) + { + if (arguments.TryGetProperty("formats", out var formats) && + (formats.ValueKind != JsonValueKind.Array || + formats.EnumerateArray().Any(f => f.ValueKind != JsonValueKind.String || f.GetString() is not ("agp" or "sdp" or "mid")))) + throw new McpToolInputException("Formats must contain agp, sdp or mid."); + if (arguments.TryGetProperty("profiles", out var profiles) && + (profiles.ValueKind != JsonValueKind.Object || + profiles.EnumerateObject().Any(p => p.Value.ValueKind != JsonValueKind.String || p.Value.GetString()!.Length == 0))) + throw new McpToolInputException("Supplied profile IDs must be nonempty strings."); + } +} diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Server/packages.lock.json b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Server/packages.lock.json new file mode 100644 index 0000000..80b6a4e --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Server/packages.lock.json @@ -0,0 +1,23 @@ +{ + "version": 2, + "dependencies": { + "net10.0": { + "gaj3t.musicgen.riffgroovebuilder.core": { + "type": "Project" + }, + "gaj3t.musicgen.riffgroovebuilder.generation": { + "type": "Project", + "dependencies": { + "GAJ3T.MusicGen.RiffGrooveBuilder.Core": "[1.0.0, )", + "Melanchall.DryWetMidi": "[8.0.3, 8.0.3]" + } + }, + "Melanchall.DryWetMidi": { + "type": "CentralTransitive", + "requested": "[8.0.3, 8.0.3]", + "resolved": "8.0.3", + "contentHash": "U+Ubol4MhieY2xgZGqcI8H2F/4HWzWKq8/WPHd1SXS7WXaHyEWMnj56vtxKOJFM5FLbj+NOUny5+X2KAzI0YUg==" + } + } + } +} \ No newline at end of file diff --git a/src/GAJ3T.MusicGen.RiffGrooveBuilder.Server/packages.win-x64.lock.json b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Server/packages.win-x64.lock.json new file mode 100644 index 0000000..b3443f7 --- /dev/null +++ b/src/GAJ3T.MusicGen.RiffGrooveBuilder.Server/packages.win-x64.lock.json @@ -0,0 +1,30 @@ +{ + "version": 2, + "dependencies": { + "net10.0": { + "Microsoft.NET.ILLink.Tasks": { + "type": "Direct", + "requested": "[10.0.11, )", + "resolved": "10.0.11", + "contentHash": "IBf7lbovvjGWVWXZX5cJ/cO0WXbId0Zq4BuSeT94mGZuOAP66oMeH9PTBZ9Jpp3Jb6jtK0qm/NyUbPRo1gC/wQ==" + }, + "gaj3t.musicgen.riffgroovebuilder.core": { + "type": "Project" + }, + "gaj3t.musicgen.riffgroovebuilder.generation": { + "type": "Project", + "dependencies": { + "GAJ3T.MusicGen.RiffGrooveBuilder.Core": "[1.0.0, )", + "Melanchall.DryWetMidi": "[8.0.3, 8.0.3]" + } + }, + "Melanchall.DryWetMidi": { + "type": "CentralTransitive", + "requested": "[8.0.3, 8.0.3]", + "resolved": "8.0.3", + "contentHash": "U+Ubol4MhieY2xgZGqcI8H2F/4HWzWKq8/WPHd1SXS7WXaHyEWMnj56vtxKOJFM5FLbj+NOUny5+X2KAzI0YUg==" + } + }, + "net10.0/win-x64": {} + } +} \ No newline at end of file diff --git a/tests/GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests/Articulations/ArticulationPipelineTests.cs b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests/Articulations/ArticulationPipelineTests.cs new file mode 100644 index 0000000..b8c2896 --- /dev/null +++ b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests/Articulations/ArticulationPipelineTests.cs @@ -0,0 +1,136 @@ +using System.Text.Json; +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Articulations; +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition; +using GAJ3T.MusicGen.RiffGrooveBuilder.Generation.Profiles; +using static GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests.Support.SyntheticPipelineProfiles; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests.Articulations; + +public sealed class ArticulationPipelineTests +{ + [Fact] + public void ThreeRolePipelineHasOneExactSharedLeadInAndSyntheticCombinedControls() + { + var parsed = DescriptionParser.Parse(Example); + Assert.True(parsed.Success); + var compositionResult = CompositionPlanner.Plan(parsed.Description!); + Assert.True(compositionResult.Success); + var composition = compositionResult.Composition!; + Assert.Empty(CompositionValidator.Validate(composition)); + var profiles = Profiles(); + Assert.All(profiles, p => Assert.Empty(InstrumentProfileValidator.Validate(p, true))); + var before = JsonSerializer.Serialize(composition); + var result = ArticulationPlanner.Plan(composition, profiles, true); + Assert.True(result.Success, string.Join("; ", result.Diagnostics)); + Assert.Empty(result.Diagnostics); + var plan = result.Plan!; + Assert.Equal(240, plan.LeadInTicks); + Assert.Equal(15_360, plan.MusicalExtentTicks); + Assert.Equal(15_600, plan.MusicalEndTick); + Assert.Equal(15_600, plan.EndTick); + Assert.Equal(175, plan.Tracks.Sum(t => t.Events.Count)); + Assert.Equal(new[] { TrackRole.Lead, TrackRole.Bass, TrackRole.Drums }, plan.Tracks.Select(t => t.Role)); + var lead = plan.Tracks[0]; + var bass = plan.Tracks[1]; + var drums = plan.Tracks[2]; + Assert.Equal(new PlannedNoteOn(0, 0, 11, 91, true), + Assert.Single(lead.Events.OfType(), e => e.IsKeyswitch)); + Assert.Contains(new PlannedNoteOff(30, 0, 11, true), lead.Events); + Assert.Equal(new PlannedNoteOn(120, 1, 12, 92, true), + Assert.Single(bass.Events.OfType(), e => e.IsKeyswitch)); + Assert.Contains(new PlannedNoteOff(140, 1, 12, true), bass.Events); + Assert.Equal(new PlannedControlChange[] + { + new(0, 9, 21, 0, true), new(240, 9, 21, 100, false), new(15_600, 9, 21, 0, true) + }, drums.Events.OfType()); + Assert.Equal(Enumerable.Range(0, 32).Select(i => new PlannedNoteOn(240 + i * 480, 0, 64, 110, false)), + lead.Events.OfType().Where(e => !e.IsKeyswitch)); + Assert.Equal(Enumerable.Range(0, 4).Select(i => new PlannedNoteOn(240 + i * 3840, 1, 40, 96, false)), + bass.Events.OfType().Where(e => !e.IsKeyswitch)); + foreach (var (voice, pitch) in new[] { (DrumVoice.Kick, 50), (DrumVoice.Snare, 51), (DrumVoice.ClosedHiHat, 52) }) + { + var hits = composition.Tracks.Single(t => t.Role == TrackRole.Drums).Hits.Where(h => h.Voice == voice); + Assert.Equal(hits.Select(h => new PlannedNoteOn(h.Start.ToTicks() + 240, 9, pitch, h.Velocity, false)), + drums.Events.OfType().Where(e => e.Pitch == pitch)); + Assert.Equal(hits.Select(h => new PlannedNoteOff((h.Start + h.Duration).ToTicks() + 240, 9, pitch, false)), + drums.Events.OfType().Where(e => e.Pitch == pitch)); + } + Assert.All(plan.Tracks, t => + { + Assert.Equal(t.Events.OrderBy(e => e.Tick).ThenBy(e => e.Priority), t.Events); + var active = new HashSet(); + foreach (var e in t.Events) + { + Assert.True(e.Tick >= 0); + if (e is PlannedNoteOn on) Assert.True(active.Add(on.Pitch)); + if (e is PlannedNoteOff off) Assert.True(active.Remove(off.Pitch)); + } + Assert.Empty(active); + }); + Assert.Equal(before, JsonSerializer.Serialize(composition)); + Assert.Equal(JsonSerializer.Serialize(plan), + JsonSerializer.Serialize(ArticulationPlanner.Plan(composition, Profiles().Reverse(), true).Plan)); + var repeated = ArticulationPlanner.Plan(composition, Profiles().Reverse(), true).Plan!; + for (var i = 0; i < plan.Tracks.Count; i++) + Assert.Equal(plan.Tracks[i].Events, repeated.Tracks[i].Events); + Assert.Equal(96, composition.Tracks[0].Notes[0].Velocity); + } + + [Theory] + [InlineData("bass", TrackRole.Bass, 120)] + [InlineData("palm-muted lead", TrackRole.Lead, 240)] + [InlineData("kick on beat 1", TrackRole.Drums, 0)] + public void SelectedSubsetsUseOnlyTheirOwnRequiredAdvance(string text, TrackRole role, long expected) + { + var composition = CompositionPlanner.Plan(text).Composition!; + var result = ArticulationPlanner.Plan(composition, Profiles().Where(p => p.Role == role), true); + Assert.True(result.Success, string.Join("; ", result.Diagnostics)); + Assert.Equal(expected, result.Plan!.LeadInTicks); + Assert.Equal(role, Assert.Single(result.Plan.Tracks).Role); + Assert.Equal(expected, result.Plan.Tracks[0].Events.OfType().First(e => !e.IsKeyswitch).Tick); + } + + [Fact] + public void PartialDocumentedCatalogCannotPlanAllTargetsOrSupplyRoleDefaults() + { + var catalog = InstrumentProfileCatalog.LoadEmbedded(); + Assert.Equal(5, catalog.Profiles.Count); + Assert.All(catalog.Profiles, p => Assert.Equal(MappingVerification.Documented, p.Evidence.Status)); + var composition = CompositionPlanner.Plan(Example).Composition!; + foreach (var role in Enum.GetValues()) + { + Assert.False(catalog.Select(role).Success); + Assert.False(catalog.Select(role, "synthetic-" + role).Success); + } + var result = ArticulationPlanner.Plan(composition, + catalog.Profiles.Where(p => p.InstrumentId is "ample-ame" or "ample-abj")); + Assert.False(result.Success); + Assert.Null(result.Plan); + Assert.Equal("Drums", Assert.Single(result.Diagnostics).Field); + Assert.Equal("missing_or_duplicate_profile", result.Diagnostics[0].Code); + } + + [Theory] + [InlineData("missing", "missing_or_duplicate_profile")] + [InlineData("unverified", "unverified_profile")] + [InlineData("unsupported", "unsupported_articulation")] + [InlineData("unmapped", "unmapped_drum_voice")] + public void PipelineFailuresDoNotExposePartialEventPlans(string scenario, string code) + { + var composition = CompositionPlanner.Plan(Example).Composition!; + var profiles = Profiles(); + if (scenario == "missing") profiles = profiles.Take(2).ToArray(); + if (scenario == "unsupported") profiles[0] = Pitched(TrackRole.Lead, 0, 240, false); + if (scenario == "unmapped") + { + var d = profiles[2]; + profiles[2] = new(d.Id, d.InstrumentId, d.Role, d.ProductName, d.ProductVersion, d.MappingVersion, d.Evidence, + d.MinimumPitch, d.MaximumPitch, d.Channel, null, d.InitialControllers, null, d.FinalControllers, + d.Rules.Where(r => r.Voice != DrumVoice.Snare).ToArray()); + } + var result = ArticulationPlanner.Plan(composition, profiles, allowSynthetic: scenario != "unverified"); + Assert.False(result.Success); + Assert.Null(result.Plan); + Assert.Contains(result.Diagnostics, d => d.Code == code); + } +} diff --git a/tests/GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests/Composition/CompositionPipelineTests.cs b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests/Composition/CompositionPipelineTests.cs new file mode 100644 index 0000000..61ad8bf --- /dev/null +++ b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests/Composition/CompositionPipelineTests.cs @@ -0,0 +1,118 @@ +using System.Text.Json; +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests.Composition; + +public sealed class CompositionPipelineTests +{ + [Fact] + public void DocumentedDescriptionTraversesRealParserPlannerValidator() + { + const string text = "Generate 4 bars at 120 BPM in E minor, 4/4: palm-muted eighth-note lead guitar, sustained root-note bass, kick on beats 1 and 3, snare on beats 2 and 4, and closed hi-hat eighth notes."; + var parsed = DescriptionParser.Parse(text); + Assert.True(parsed.Success); + var result = CompositionPlanner.Plan(parsed.Description!); + Assert.True(result.Success); + Assert.Empty(result.Diagnostics); + var model = result.Composition!; + Assert.Empty(CompositionValidator.Validate(model)); + Assert.Equal(120, model.TempoBpm); + Assert.Equal(4, model.Bars); + Assert.Equal(new TimeSignature(4, 4), model.Meter); + Assert.Equal(new MusicalKey(4, KeyMode.Minor), model.Key); + Assert.Equal(15_360, model.MusicalExtent.ToTicks()); + Assert.Equal(3, model.Tracks.Count); + var lead = Assert.Single(model.Tracks, track => track.Role == TrackRole.Lead); + var bass = Assert.Single(model.Tracks, track => track.Role == TrackRole.Bass); + var drums = Assert.Single(model.Tracks, track => track.Role == TrackRole.Drums); + Assert.Empty(lead.Hits); + Assert.Empty(bass.Hits); + Assert.Empty(drums.Notes); + Assert.Equal(32, lead.Notes.Count); + Assert.Equal(4, bass.Notes.Count); + Assert.Equal(48, drums.Hits.Count); + Assert.Equal(6, model.DefaultsApplied.Count); + for (var bar = 0; bar < 4; bar++) + { + for (var i = 0; i < 8; i++) + { + var note = lead.Notes[bar * 8 + i]; + Assert.Equal(64, note.Pitch); + Assert.Equal(96, note.Velocity); + Assert.Equal(Articulation.PalmMute, note.Articulation); + Assert.Equal(bar * 3840 + i * 480, note.Start.ToTicks()); + Assert.Equal(480, note.Duration.ToTicks()); + } + Assert.Equal(40, bass.Notes[bar].Pitch); + Assert.Equal(Articulation.Sustain, bass.Notes[bar].Articulation); + Assert.Equal(bar * 3840, bass.Notes[bar].Start.ToTicks()); + Assert.Equal(3840, bass.Notes[bar].Duration.ToTicks()); + var barHits = drums.Hits.Where(hit => hit.Start >= new BeatFraction(bar * 4) && + hit.Start < new BeatFraction((bar + 1) * 4)).ToArray(); + Assert.Equal(new long[] { bar * 3840, bar * 3840 + 1920 }, + barHits.Where(hit => hit.Voice == DrumVoice.Kick).Select(hit => hit.Start.ToTicks())); + Assert.Equal(new long[] { bar * 3840 + 960, bar * 3840 + 2880 }, + barHits.Where(hit => hit.Voice == DrumVoice.Snare).Select(hit => hit.Start.ToTicks())); + Assert.Equal(Enumerable.Range(0, 8).Select(i => (long)bar * 3840 + i * 480), + barHits.Where(hit => hit.Voice == DrumVoice.ClosedHiHat).Select(hit => hit.Start.ToTicks())); + Assert.All(barHits, hit => Assert.Equal(hit.Voice == DrumVoice.ClosedHiHat ? 480 : 960, hit.Duration.ToTicks())); + } + Assert.Equal(JsonSerializer.Serialize(model), JsonSerializer.Serialize(CompositionPlanner.Plan(text).Composition)); + } + + [Theory] + [InlineData("bass", TrackRole.Bass, 4)] + [InlineData("palm mute sixteenth notes lead", TrackRole.Lead, 64)] + [InlineData("drums, kick on beats 1 and 3", TrackRole.Drums, 8)] + public void ExplicitRolesAndDrumSubsetsStayExplicit(string text, TrackRole role, int count) + { + var parsed = DescriptionParser.Parse(text); + Assert.True(parsed.Success); + var result = CompositionPlanner.Plan(parsed.Description!); + Assert.True(result.Success); + var track = Assert.Single(result.Composition!.Tracks); + Assert.Equal(role, track.Role); + Assert.Equal(count, track.Notes.Count + track.Hits.Count); + Assert.Empty(CompositionValidator.Validate(result.Composition)); + if (role == TrackRole.Drums) + Assert.All(track.Hits, hit => Assert.Equal(DrumVoice.Kick, hit.Voice)); + } + + [Fact] + public void DocumentedThreeEightDescriptionRetainsDenominatorBeatTiming() + { + var parsed = DescriptionParser.Parse("3/8, 2 bars: kick on beats 1 and 3, snare on beat 2, closed hi-hat eighth notes"); + Assert.True(parsed.Success); + var result = CompositionPlanner.Plan(parsed.Description!); + Assert.True(result.Success); + var model = result.Composition!; + Assert.Empty(CompositionValidator.Validate(model)); + Assert.Equal(2880, model.MusicalExtent.ToTicks()); + var hits = Assert.Single(model.Tracks).Hits; + Assert.Equal(12, hits.Count); + Assert.All(hits, hit => Assert.Equal(480, hit.Duration.ToTicks())); + Assert.Equal(new long[] { 0, 960, 1440, 2400 }, + hits.Where(hit => hit.Voice == DrumVoice.Kick).Select(hit => hit.Start.ToTicks())); + Assert.Equal(new long[] { 480, 1920 }, + hits.Where(hit => hit.Voice == DrumVoice.Snare).Select(hit => hit.Start.ToTicks())); + Assert.DoesNotContain(model.DefaultsApplied, item => item.Field.StartsWith("drums.", StringComparison.Ordinal) && item.Field != "drums.velocity"); + } + + [Theory] + [InlineData("lead legato", "unsupported_text")] + [InlineData("3/8 drums", "explicit_drums_required")] + [InlineData("3/8 kick on beat 4", "invalid_beat")] + [InlineData("3/8 quarter notes lead", "unrepresentable_pattern")] + [InlineData("100001 bars kick on beat 1", "event_limit_exceeded")] + public void RealPipelineFailuresAreActionableAndHaveNoPartialComposition(string text, string code) + { + var result = CompositionPlanner.Plan(text); + Assert.False(result.Success); + Assert.Null(result.Composition); + var diagnostic = Assert.Single(result.Diagnostics); + Assert.Equal(code, diagnostic.Code); + Assert.False(string.IsNullOrWhiteSpace(diagnostic.Field)); + Assert.False(string.IsNullOrWhiteSpace(diagnostic.Message)); + if (code == "unsupported_text") Assert.Contains("legato", diagnostic.Phrase); + } +} diff --git a/tests/GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests/GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests.csproj b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests/GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests.csproj new file mode 100644 index 0000000..cf8152e --- /dev/null +++ b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests/GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests.csproj @@ -0,0 +1,44 @@ + + + + net10.0 + false + true + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + + + + + + <_ServerOutputDirectory>@(_ServerAssembly->'%(RootDir)%(Directory)') + + + <_ServerFiles Include="$(_ServerOutputDirectory)**\*" /> + + + + + \ No newline at end of file diff --git a/tests/GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests/Instruments/InstrumentCatalogPipelineTests.cs b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests/Instruments/InstrumentCatalogPipelineTests.cs new file mode 100644 index 0000000..8bc0ade --- /dev/null +++ b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests/Instruments/InstrumentCatalogPipelineTests.cs @@ -0,0 +1,66 @@ +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Articulations; +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition; +using GAJ3T.MusicGen.RiffGrooveBuilder.Generation.Instruments; +using GAJ3T.MusicGen.RiffGrooveBuilder.Generation.Profiles; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests.Instruments; + +[CollectionDefinition("Instrument catalog working directory", DisableParallelization = true)] +public sealed class InstrumentCatalogWorkingDirectoryCollection; + +[Collection("Instrument catalog working directory")] +public sealed class InstrumentCatalogPipelineTests +{ + [Fact] + public void RealEmbeddedCatalogsJoinSevenTargetsWithFiveDocumentedCapabilitiesFromUnrelatedDirectory() + { + var previous = Environment.CurrentDirectory; + try + { + Environment.CurrentDirectory = Environment.SystemDirectory; + var instruments = InstrumentCatalog.LoadEmbedded(); + var profiles = InstrumentProfileCatalog.LoadEmbedded(); + Assert.Equal(new[] + { + "ample-abj", "ample-aglp", "ample-agm", "ample-agt", "ample-ame", "ample-amr", "toontrack-sd3" + }, instruments.Instruments.Select(i => i.Id)); + Assert.Equal(instruments.Instruments, profiles.Instruments.Select(i => i.Instrument)); + Assert.Equal(4, instruments.ForRole(TrackRole.Lead).Count); + Assert.Equal(2, instruments.ForRole(TrackRole.Bass).Count); + Assert.Single(instruments.ForRole(TrackRole.Drums)); + Assert.Equal(5, profiles.Profiles.Count); + foreach (var entry in profiles.Instruments) + { + var selected = profiles.SelectInstrument(entry.Instrument.Role, entry.Instrument.Id); + if (entry.Instrument.Id is "ample-abj" or "ample-aglp" or "ample-agm" or "ample-agt" or "ample-ame") + { + Assert.Equal("profile_available", entry.Availability); + Assert.True(selected.Success); + Assert.Same(Assert.Single(entry.Profiles), selected.Profile); + Assert.Equal(MappingVerification.Documented, selected.Profile!.Evidence.Status); + } + else + { + Assert.Equal("mapping_unavailable", entry.Availability); + Assert.Empty(entry.Profiles); + Assert.False(selected.Success); + Assert.Null(selected.Profile); + Assert.Equal("mapping_unavailable", Assert.Single(selected.Diagnostics).Code); + } + } + Assert.Equal("unknown_instrument", + Assert.Single(profiles.SelectInstrument(TrackRole.Bass, "not-declared").Diagnostics).Code); + var composition = CompositionPlanner.Plan("lead and bass and drums").Composition!; + var result = ArticulationPlanner.Plan(composition, + profiles.Profiles.Where(p => p.InstrumentId is "ample-ame" or "ample-abj")); + Assert.False(result.Success); + Assert.Null(result.Plan); + Assert.Equal("Drums", Assert.Single(result.Diagnostics).Field); + Assert.Equal("missing_or_duplicate_profile", result.Diagnostics[0].Code); + } + finally + { + Environment.CurrentDirectory = previous; + } + } +} diff --git a/tests/GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests/Midi/DocumentedProfileMidiTests.cs b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests/Midi/DocumentedProfileMidiTests.cs new file mode 100644 index 0000000..5d2e15f --- /dev/null +++ b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests/Midi/DocumentedProfileMidiTests.cs @@ -0,0 +1,216 @@ +using System.Text.Json; +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Articulations; +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition; +using GAJ3T.MusicGen.RiffGrooveBuilder.Generation.Midi; +using GAJ3T.MusicGen.RiffGrooveBuilder.Generation.Profiles; +using Melanchall.DryWetMidi.Core; +using MusicalComposition = GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition.Composition; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests.Midi; + +public sealed class DocumentedProfileMidiTests : IDisposable +{ + private readonly string directory = Path.Combine(AppContext.BaseDirectory, + "documented-midi-" + Guid.NewGuid().ToString("N")); + + [Theory] + [InlineData("ample-aglp", false)] + [InlineData("ample-aglp", true)] + [InlineData("ample-ame", false)] + [InlineData("ample-ame", true)] + [InlineData("ample-agm", false)] + [InlineData("ample-agm", true)] + [InlineData("ample-agt", false)] + [InlineData("ample-agt", true)] + [InlineData("ample-abj", false)] + public void DescriptionThroughEachAdmittedProfileWritesAndReadsActualMidi(string id, bool palmMute) + { + var profile = Select(id); + var composition = CompositionPlanner.Plan(profile.Role == TrackRole.Bass ? "bass" : + palmMute ? "palm-muted lead" : "lead").Composition!; + var (plan, track) = WriteRead(composition, profile); + var switchOn = Assert.Single(track, e => e.Event is NoteOnEvent on && on.NoteNumber < profile.MinimumPitch); + Assert.Equal(0, switchOn.Tick); + Assert.Equal(palmMute ? 26 : 24, (int)((NoteOnEvent)switchOn.Event).NoteNumber); + Assert.Equal(100, (int)((NoteOnEvent)switchOn.Event).Velocity); + Assert.Equal(30, Assert.Single(track, e => e.Event is NoteOffEvent off && + off.NoteNumber < profile.MinimumPitch).Tick); + Assert.Equal(120, plan.LeadInTicks); + Assert.Equal(composition.Tracks[0].Notes.Select(n => n.Start.ToTicks() + 120), + track.Where(e => e.Event is NoteOnEvent on && on.NoteNumber >= profile.MinimumPitch).Select(e => e.Tick)); + Assert.Equal(plan.MusicalEndTick, track.Last().Tick); + } + + [Theory] + [InlineData("ample-aglp", Articulation.Sustain)] + [InlineData("ample-aglp", Articulation.PalmMute)] + [InlineData("ample-ame", Articulation.Sustain)] + [InlineData("ample-ame", Articulation.PalmMute)] + [InlineData("ample-agm", Articulation.Sustain)] + [InlineData("ample-agm", Articulation.PalmMute)] + [InlineData("ample-agt", Articulation.Sustain)] + [InlineData("ample-agt", Articulation.PalmMute)] + public void UnknownStateBoundaryNotesRepeatsAndTransitionsNeverCombineSwitches( + string id, Articulation first) + { + var profile = Select(id); + var second = first == Articulation.Sustain ? Articulation.PalmMute : Articulation.Sustain; + var firstRule = profile.Rules.Single(r => r.Articulation == first); + var secondRule = profile.Rules.Single(r => r.Articulation == second); + var composition = new MusicalComposition(120, new(4, 4), new(4, KeyMode.Minor), 1, + [new(TrackRole.Lead, + [ + new(profile.MinimumPitch, new(0), new(1, 4), firstRule.Velocity.Minimum, first), + new(profile.MaximumPitch, new(1), new(1, 4), firstRule.Velocity.Maximum, first), + new(profile.MinimumPitch, new(2), new(1, 4), secondRule.Velocity.Minimum, second), + new(profile.MaximumPitch, new(3), new(1, 4), firstRule.Velocity.Minimum, first) + ])]); + var (_, track) = WriteRead(composition, profile); + var switches = track.Where(e => e.Event is NoteOnEvent on && on.NoteNumber < profile.MinimumPitch).ToArray(); + Assert.Equal(new long[] { 0, 1920, 2880 }, switches.Select(e => e.Tick)); + Assert.Equal(new[] { firstRule.Keyswitch!.Pitch, secondRule.Keyswitch!.Pitch, firstRule.Keyswitch.Pitch }, + switches.Select(e => (int)((NoteOnEvent)e.Event).NoteNumber)); + Assert.Equal(new long[] { 30, 1950, 2910 }, + track.Where(e => e.Event is NoteOffEvent off && off.NoteNumber < profile.MinimumPitch).Select(e => e.Tick)); + var musical = track.Where(e => e.Event is NoteOnEvent on && on.NoteNumber >= profile.MinimumPitch).ToArray(); + Assert.Equal(new long[] { 120, 1080, 2040, 3000 }, musical.Select(e => e.Tick)); + Assert.Equal(composition.Tracks[0].Notes.Select(n => n.Pitch), + musical.Select(e => (int)((NoteOnEvent)e.Event).NoteNumber)); + Assert.Equal(composition.Tracks[0].Notes.Select(n => n.Velocity), + musical.Select(e => (int)((NoteOnEvent)e.Event).Velocity)); + Assert.Equal(new long[] { 360, 1320, 2280, 3240 }, + track.Where(e => e.Event is NoteOffEvent off && off.NoteNumber >= profile.MinimumPitch).Select(e => e.Tick)); + } + + [Theory] + [InlineData("ample-aglp", 127, "velocity_layer_conflict")] + [InlineData("ample-ame", 63, "velocity_layer_conflict")] + [InlineData("ample-ame", 127, "velocity_layer_conflict")] + [InlineData("ample-agm", 127, "velocity_layer_conflict")] + [InlineData("ample-agt", 127, "velocity_layer_conflict")] + [InlineData("ample-abj", 126, "velocity_layer_conflict")] + [InlineData("ample-abj", 127, "velocity_layer_conflict")] + public void UnsupportedSustainLayersFailBeforeAnyFileIsCreated(string id, int velocity, string code) + { + var profile = Select(id); + var model = new MusicalComposition(120, new(4, 4), new(4, KeyMode.Minor), 1, + [new(profile.Role, [new(64, new(0), new(1), velocity, Articulation.Sustain)])]); + var result = ArticulationPlanner.Plan(model, [profile]); + Assert.False(result.Success); + Assert.Null(result.Plan); + Assert.Contains(result.Diagnostics, d => d.Code == code); + Assert.False(Directory.Exists(directory)); + } + + private static InstrumentProfile Select(string id) + { + var catalog = InstrumentProfileCatalog.LoadEmbedded(); + var role = catalog.Profiles.Single(p => p.InstrumentId == id).Role; + var selection = catalog.SelectInstrument(role, id); + Assert.True(selection.Success, string.Join("; ", selection.Diagnostics)); + var profile = selection.Profile!; + Assert.Equal(MappingVerification.Documented, profile.Evidence.Status); + Assert.Empty(InstrumentProfileValidator.Validate(profile)); + return profile; + } + + private (MidiEventPlan Plan, (long Tick, MidiEvent Event)[] Track) WriteRead( + MusicalComposition composition, InstrumentProfile profile) + { + var before = JsonSerializer.Serialize(new { composition, profile }); + var result = ArticulationPlanner.Plan(composition, [profile]); + Assert.True(result.Success, string.Join("; ", result.Diagnostics)); + var plan = result.Plan!; + Directory.CreateDirectory(directory); + var path = Path.Combine(directory, "documented.mid"); + MidiFileWriter.WriteFile(path, composition, plan); + Assert.True(new FileInfo(path).Length > 0); + var file = MidiFile.Read(path, new ReadingSettings + { EndOfTrackStoringPolicy = EndOfTrackStoringPolicy.Store }); + Assert.Equal(MidiFileFormat.MultiTrack, file.OriginalFormat); + Assert.Equal(960, Assert.IsType(file.TimeDivision).TicksPerQuarterNote); + var chunks = file.Chunks.Cast().ToArray(); + Assert.Equal(2, chunks.Length); + Assert.Equal(profile.Role.ToString(), Assert.Single(chunks[1].Events.OfType()).Text); + long tick = 0; + var actual = chunks[1].Events.Select(e => (Tick: tick += e.DeltaTime, Event: e)).ToArray(); + var channelEvents = actual.Where(e => e.Event is ChannelEvent).ToArray(); + Assert.Equal(plan.Tracks[0].Events.Select(e => e.Tick), channelEvents.Select(e => e.Tick)); + Assert.All(channelEvents, e => Assert.Equal(profile.Channel, (int)((ChannelEvent)e.Event).Channel)); + for (var i = 0; i < channelEvents.Length; i++) + { + if (plan.Tracks[0].Events[i] is PlannedNoteOn expectedOn) + { + var on = Assert.IsType(channelEvents[i].Event); + Assert.Equal(expectedOn.Pitch, (int)on.NoteNumber); + Assert.Equal(expectedOn.Velocity, (int)on.Velocity); + } + else + { + var off = Assert.IsType(channelEvents[i].Event); + Assert.Equal(Assert.IsType(plan.Tracks[0].Events[i]).Pitch, (int)off.NoteNumber); + } + } + var active = new HashSet(); + var heldSwitches = new HashSet(); + foreach (var (_, e) in channelEvents) + { + if (e is NoteOnEvent on) + { + Assert.True(active.Add(on.NoteNumber)); + if (on.NoteNumber < profile.MinimumPitch) + { + Assert.Empty(heldSwitches); + Assert.True(heldSwitches.Add(on.NoteNumber)); + } + } + if (e is NoteOffEvent off) + { + Assert.True(active.Remove(off.NoteNumber)); + heldSwitches.Remove(off.NoteNumber); + } + } + Assert.Empty(active); + Assert.Empty(heldSwitches); + Assert.IsType(actual.Last().Event); + Assert.Equal(plan.EndTick, actual.Last().Tick); + Assert.Equal(before, JsonSerializer.Serialize(new { composition, profile })); + return (plan, actual); + } + + [Fact] + public void AbjSustainOnlyBoundaryDynamicsInitializeOnceOnSeparateBassChannel() + { + var profile = Select("ample-abj"); + var composition = new MusicalComposition(120, new(4, 4), new(4, KeyMode.Minor), 1, + [new(TrackRole.Bass, + [ + new(35, new(0), new(1, 4), 1, Articulation.Sustain), + new(76, new(2), new(1, 4), 125, Articulation.Sustain) + ])]); + var (_, events) = WriteRead(composition, profile); + Assert.Equal(24, (int)((NoteOnEvent)Assert.Single(events, + e => e.Event is NoteOnEvent on && on.NoteNumber < 35).Event).NoteNumber); + Assert.Equal(new[] { 1, 125 }, events.Where(e => e.Event is NoteOnEvent on && on.NoteNumber >= 35) + .Select(e => (int)((NoteOnEvent)e.Event).Velocity)); + Assert.All(events.Where(e => e.Event is ChannelEvent), e => Assert.Equal(1, (int)((ChannelEvent)e.Event).Channel)); + } + + [Fact] + public void AbjPalmMuteIsExplicitlyUnsupportedInsteadOfSubstituted() + { + var profile = Select("ample-abj"); + var composition = CompositionPlanner.Plan("palm-muted bass").Composition!; + var result = ArticulationPlanner.Plan(composition, [profile]); + Assert.False(result.Success); + Assert.Null(result.Plan); + Assert.All(result.Diagnostics, d => Assert.Equal("unsupported_articulation", d.Code)); + Assert.False(Directory.Exists(directory)); + } + + public void Dispose() + { + if (Directory.Exists(directory)) + Directory.Delete(directory, recursive: true); + } +} diff --git a/tests/GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests/Midi/MidiGenerationPipelineTests.cs b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests/Midi/MidiGenerationPipelineTests.cs new file mode 100644 index 0000000..c3ab60a --- /dev/null +++ b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests/Midi/MidiGenerationPipelineTests.cs @@ -0,0 +1,279 @@ +using System.Security.Cryptography; +using System.Text.Json; +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Articulations; +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition; +using GAJ3T.MusicGen.RiffGrooveBuilder.Generation.Midi; +using GAJ3T.MusicGen.RiffGrooveBuilder.Generation.Profiles; +using Melanchall.DryWetMidi.Core; +using Xunit.Abstractions; +using MusicalComposition = GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition.Composition; +using static GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests.Support.SyntheticPipelineProfiles; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests.Midi; + +[CollectionDefinition("MIDI working directory", DisableParallelization = true)] +public sealed class MidiWorkingDirectoryCollection; + +[Collection("MIDI working directory")] +public sealed class MidiGenerationPipelineTests : IDisposable +{ + private readonly string directory = Path.Combine(AppContext.BaseDirectory, "midi-pipeline-" + Guid.NewGuid().ToString("N")); + private readonly ITestOutputHelper output; + + public MidiGenerationPipelineTests(ITestOutputHelper output) + { + this.output = output; + Directory.CreateDirectory(directory); + } + + [Fact] + public void FullExampleWritesActualTypeOneFileFromUnrelatedCwdAndReadsEveryEventBack() + { + var (composition, plan) = Plan(Example); + var before = JsonSerializer.Serialize(new { composition, plan }); + Assert.Equal(240, plan.LeadInTicks); + Assert.Equal(15_360, plan.MusicalExtentTicks); + Assert.Equal(15_600, plan.MusicalEndTick); + Assert.Equal(15_600, plan.EndTick); + var path = Path.Combine(directory, "full-example.mid"); + var previous = Environment.CurrentDirectory; + try + { + Environment.CurrentDirectory = Environment.SystemDirectory; + MidiFileWriter.WriteFile(path, composition, plan); + } + finally + { + Environment.CurrentDirectory = previous; + } + var file = ReadAndAssert(path, plan); + var tracks = file.Chunks.Cast().ToArray(); + Assert.Equal(new[] { "Conductor", "Lead", "Bass", "Drums" }, tracks.Select(Name)); + var conductor = Absolute(tracks[0]); + Assert.Equal(500_000, Assert.IsType( + Assert.Single(conductor, e => e.Event is SetTempoEvent).Event).MicrosecondsPerQuarterNote); + var meter = Assert.Single(tracks[0].Events.OfType()); + Assert.Equal(4, meter.Numerator); + Assert.Equal(4, meter.Denominator); + Assert.All(conductor.Where(e => e.Event is not EndOfTrackEvent), e => Assert.Equal(0, e.Tick)); + Assert.Equal(32, tracks[1].Events.OfType().Count(e => e.NoteNumber == 64)); + Assert.Equal(4, tracks[2].Events.OfType().Count(e => e.NoteNumber == 40)); + Assert.Equal(48, tracks[3].Events.OfType().Count()); + Assert.Equal(Enumerable.Range(0, 32).Select(i => (Tick: 240L + i * 480, Pitch: 64, Velocity: 110, Channel: 0)), + Absolute(tracks[1]).Where(e => e.Event is NoteOnEvent on && on.NoteNumber == 64).Select(Note)); + Assert.Equal(Enumerable.Range(0, 4).Select(i => (Tick: 240L + i * 3840, Pitch: 40, Velocity: 96, Channel: 1)), + Absolute(tracks[2]).Where(e => e.Event is NoteOnEvent on && on.NoteNumber == 40).Select(Note)); + Assert.Equal((0L, 11, 91, 0), Note(Assert.Single(Absolute(tracks[1]), e => e.Event is NoteOnEvent on && on.NoteNumber == 11))); + Assert.Equal(30, Assert.Single(Absolute(tracks[1]), e => e.Event is NoteOffEvent off && off.NoteNumber == 11).Tick); + Assert.Equal((120L, 12, 92, 1), Note(Assert.Single(Absolute(tracks[2]), e => e.Event is NoteOnEvent on && on.NoteNumber == 12))); + Assert.Equal(140, Assert.Single(Absolute(tracks[2]), e => e.Event is NoteOffEvent off && off.NoteNumber == 12).Tick); + Assert.Equal(new[] { (0L, 21, 0), (240L, 21, 100), (15_600L, 21, 0) }, + Absolute(tracks[3]).Where(e => e.Event is ControlChangeEvent).Select(e => + (e.Tick, (int)((ControlChangeEvent)e.Event).ControlNumber, (int)((ControlChangeEvent)e.Event).ControlValue))); + foreach (var (voice, pitch) in new[] { (DrumVoice.Kick, 50), (DrumVoice.Snare, 51), (DrumVoice.ClosedHiHat, 52) }) + { + var expected = composition.Tracks.Single(t => t.Role == TrackRole.Drums).Hits.Where(h => h.Voice == voice); + Assert.Equal(expected.Select(h => (h.Start.ToTicks() + 240, pitch, h.Velocity, 9)), + Absolute(tracks[3]).Where(e => e.Event is NoteOnEvent on && on.NoteNumber == pitch).Select(Note)); + } + var repeated = Plan(Example, Profiles().Reverse()); + var repeatedPath = Path.Combine(directory, "repeat.mid"); + MidiFileWriter.WriteFile(repeatedPath, repeated.Composition, repeated.Plan); + Assert.Equal(File.ReadAllBytes(path), File.ReadAllBytes(repeatedPath)); + Assert.Equal(before, JsonSerializer.Serialize(new { composition, plan })); + output.WriteLine($"Actual .mid write/read-back: bytes={new FileInfo(path).Length}, SHA256={Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(path)))}"); + output.WriteLine("Read-back: type=1, PPQ=960, tracks=4, channel events=175, musical notes=32/4/48, switch pairs=2, EOTs=4 at 15600."); + } + + [Theory] + [InlineData("bass", "Bass", 1, 4)] + [InlineData("palm-muted lead", "Lead", 0, 32)] + [InlineData("kick on beat 1", "Drums", 9, 4)] + [InlineData("lead and bass", "Lead,Bass", 0, 36)] + public void SelectedRolesHaveOnlyTheirNamedTracksAndConfiguredChannels(string text, string names, int firstChannel, int musicalNotes) + { + var (composition, plan) = Plan(text); + var path = Path.Combine(directory, "subset.mid"); + MidiFileWriter.WriteFile(path, composition, plan); + var tracks = ReadAndAssert(path, plan).Chunks.Cast().Skip(1).ToArray(); + Assert.Equal(names.Split(','), tracks.Select(Name)); + Assert.Equal(firstChannel, (int)tracks[0].Events.OfType().First().Channel); + Assert.Equal(musicalNotes, plan.Tracks.Sum(t => t.Events.OfType().Count(e => !e.IsKeyswitch))); + } + + [Fact] + public void NonFourFourDescriptionPreservesDenominatorBeatPositionsAndMetadata() + { + var (composition, plan) = Plan("3/8, 2 bars, 123 bpm: kick on beats 1 and 3, snare on beat 2, closed hi-hat eighth notes"); + var path = Path.Combine(directory, "three-eight.mid"); + MidiFileWriter.WriteFile(path, composition, plan); + var tracks = ReadAndAssert(path, plan).Chunks.Cast().ToArray(); + var meter = Assert.Single(tracks[0].Events.OfType()); + Assert.Equal(3, meter.Numerator); + Assert.Equal(8, meter.Denominator); + Assert.Equal(487_805, Assert.Single(tracks[0].Events.OfType()).MicrosecondsPerQuarterNote); + Assert.Equal(2880, plan.EndTick); + Assert.Equal(new long[] { 0, 960, 1440, 2400 }, + Absolute(tracks[1]).Where(e => e.Event is NoteOnEvent on && on.NoteNumber == 50).Select(e => e.Tick)); + Assert.Equal(12, tracks[1].Events.OfType().Count()); + } + + [Fact] + public void LongRepeatedPatternUsesExactTicksWithoutAccumulatedDrift() + { + var (composition, plan) = Plan("1000 bars, 7/8: sixteenth-note lead"); + var path = Path.Combine(directory, "long.mid"); + MidiFileWriter.WriteFile(path, composition, plan); + var tracks = ReadAndAssert(path, plan).Chunks.Cast().ToArray(); + var notes = Absolute(tracks[1]).Where(e => e.Event is NoteOnEvent).ToArray(); + Assert.Equal(14_000, notes.Length); + Assert.Equal(240, plan.LeadInTicks); + Assert.Equal(Enumerable.Range(0, 14_000).Select(i => 240L + 240L * i), notes.Select(e => e.Tick)); + Assert.Equal(3_360_000, plan.MusicalExtentTicks); + Assert.Equal(3_360_240, plan.EndTick); + Assert.Equal(3_360_240, Absolute(tracks[1]).Last().Tick); + } + + [Fact] + public void RestsKeepFullDeclaredBarsEvenAfterLastNoteOff() + { + var (composition, plan) = Plan("4 bars: kick on beat 1"); + var path = Path.Combine(directory, "rests.mid"); + MidiFileWriter.WriteFile(path, composition, plan); + var track = ReadAndAssert(path, plan).Chunks.Cast().Last(); + Assert.Equal(12_480, Absolute(track).Last(e => e.Event is NoteOffEvent).Tick); + Assert.Equal(15_360, Absolute(track).Last().Tick); + Assert.Equal(2880, track.Events.OfType().Last().DeltaTime); + Assert.Equal(0, track.Events.Last().DeltaTime); + } + + [Theory] + [InlineData(false, 4110)] + [InlineData(true, 20000)] + public void ResetPulseOrMomentaryReleaseTailSetsEveryTracksGlobalEnd(bool momentary, long expectedEnd) + { + var profiles = Profiles(); + var lead = profiles[0]; + var rules = momentary + ? new[] + { + new ArticulationRule(Articulation.Sustain, null, null, StateBehavior.None, null, new(1, 127, null), []), + new ArticulationRule(Articulation.PalmMute, null, null, StateBehavior.Momentary, new(11, 91, 240, 20_000), new(64, 127, 110), []) + } + : lead.Rules; + profiles[0] = new(lead.Id, lead.InstrumentId, lead.Role, lead.ProductName, lead.ProductVersion, + lead.MappingVersion, lead.Evidence, lead.MinimumPitch, lead.MaximumPitch, lead.Channel, + lead.InitialArticulation, lead.InitialControllers, momentary ? null : Articulation.Sustain, lead.FinalControllers, rules); + var (composition, plan) = Plan("1 bar: palm-muted sustained lead, bass, kick on beat 1", profiles); + Assert.Equal(4080, plan.MusicalEndTick); + Assert.Equal(expectedEnd, plan.EndTick); + var path = Path.Combine(directory, "tail.mid"); + MidiFileWriter.WriteFile(path, composition, plan); + var tracks = ReadAndAssert(path, plan).Chunks.Cast().ToArray(); + Assert.All(tracks, t => Assert.Equal(expectedEnd, Absolute(t).Last().Tick)); + var lastOff = Absolute(tracks[1]).Last(e => e.Event is NoteOffEvent); + Assert.Equal(expectedEnd, lastOff.Tick); + Assert.Equal(momentary ? 11 : 10, (int)((NoteOffEvent)lastOff.Event).NoteNumber); + } + + [Fact] + public void RealWriterNoOverwritePreflightAndCancellationLeaveNoUndisclosedFiles() + { + var (composition, plan) = Plan(Example); + var path = Path.Combine(directory, "existing.mid"); + File.WriteAllText(path, "another owner"); + var unrelated = Path.Combine(directory, ".other-owner.stage"); + File.WriteAllText(unrelated, "keep"); + Assert.Throws(() => MidiFileWriter.WriteFile(path, composition, plan)); + Assert.Equal("another owner", File.ReadAllText(path)); + var cancelled = Path.Combine(directory, "cancelled.mid"); + Assert.Throws(() => MidiFileWriter.WriteFile(cancelled, composition, plan, new CancellationToken(true))); + Assert.False(File.Exists(cancelled)); + Assert.Throws(() => MidiFileWriter.WriteFile(Path.Combine(directory, "missing", "fail.mid"), composition, plan)); + Assert.Throws(() => MidiFileWriter.WriteFile(Path.Combine(directory, "invalid.mid"), null!, plan)); + Assert.Equal(new[] { ".other-owner.stage", "existing.mid" }, Directory.GetFiles(directory).Select(Path.GetFileName).Order(StringComparer.Ordinal)); + Assert.Equal("keep", File.ReadAllText(unrelated)); + Assert.DoesNotContain(InstrumentProfileCatalog.LoadEmbedded().Profiles, + p => p.Evidence.Status is MappingVerification.Synthetic or MappingVerification.Unverified); + } + + private static (MusicalComposition Composition, MidiEventPlan Plan) Plan(string text, IEnumerable? profiles = null) + { + var parsed = DescriptionParser.Parse(text); + Assert.True(parsed.Success, string.Join("; ", parsed.Diagnostics)); + var composition = CompositionPlanner.Plan(parsed.Description!); + Assert.True(composition.Success, string.Join("; ", composition.Diagnostics)); + Assert.Empty(CompositionValidator.Validate(composition.Composition)); + var selected = (profiles ?? Profiles()).Where(p => composition.Composition!.Tracks.Any(t => t.Role == p.Role)).ToArray(); + Assert.All(selected, p => Assert.Empty(InstrumentProfileValidator.Validate(p, allowSynthetic: true))); + var planned = ArticulationPlanner.Plan(composition.Composition, selected, allowSynthetic: true); + Assert.True(planned.Success, string.Join("; ", planned.Diagnostics)); + return (composition.Composition!, planned.Plan!); + } + + private static MidiFile ReadAndAssert(string path, MidiEventPlan plan) + { + Assert.True(new FileInfo(path).Length > 0); + var file = MidiFile.Read(path, new ReadingSettings + { + EndOfTrackStoringPolicy = EndOfTrackStoringPolicy.Store, + MissedEndOfTrackPolicy = MissedEndOfTrackPolicy.Abort + }); + Assert.Equal(MidiFileFormat.MultiTrack, file.OriginalFormat); + Assert.Equal(960, Assert.IsType(file.TimeDivision).TicksPerQuarterNote); + var tracks = file.Chunks.Cast().ToArray(); + Assert.Equal(plan.Tracks.Count + 1, tracks.Length); + foreach (var track in tracks) + { + Assert.Single(track.Events.OfType()); + Assert.IsType(track.Events.Last()); + Assert.Equal(plan.EndTick, Absolute(track).Last().Tick); + } + foreach (var planned in plan.Tracks) + { + var track = Assert.Single(tracks, t => Name(t) == planned.Role.ToString()); + var actual = Absolute(track).Where(e => e.Event is ChannelEvent).ToArray(); + Assert.Equal(planned.Events.Select(EventValue), actual.Select(EventValue)); + var active = new HashSet<(int Channel, int Pitch)>(); + foreach (var (_, e) in actual) + { + if (e is NoteOnEvent on) Assert.True(active.Add(((int)on.Channel, (int)on.NoteNumber))); + if (e is NoteOffEvent off) Assert.True(active.Remove(((int)off.Channel, (int)off.NoteNumber))); + } + Assert.Empty(active); + } + return file; + } + + private static string Name(TrackChunk track) => Assert.Single(track.Events.OfType()).Text; + + private static (long Tick, MidiEvent Event)[] Absolute(TrackChunk track) + { + long tick = 0; + return track.Events.Select(e => (Tick: tick = checked(tick + e.DeltaTime), Event: e)).ToArray(); + } + + private static (long Tick, int Pitch, int Velocity, int Channel) Note((long Tick, MidiEvent Event) e) + { + var on = Assert.IsType(e.Event); + return (e.Tick, (int)on.NoteNumber, (int)on.Velocity, (int)on.Channel); + } + + private static (long Tick, string Kind, int Channel, int Number, int Value) EventValue(PlannedMidiEvent e) => e switch + { + PlannedNoteOn on => (e.Tick, "on", e.Channel, on.Pitch, on.Velocity), + PlannedNoteOff off => (e.Tick, "off", e.Channel, off.Pitch, 0), + PlannedControlChange cc => (e.Tick, "cc", e.Channel, cc.Number, cc.Value), + _ => throw new InvalidOperationException("Unexpected planned event.") + }; + + private static (long Tick, string Kind, int Channel, int Number, int Value) EventValue((long Tick, MidiEvent Event) e) => e.Event switch + { + NoteOnEvent on => (e.Tick, "on", (int)on.Channel, (int)on.NoteNumber, (int)on.Velocity), + NoteOffEvent off => (e.Tick, "off", (int)off.Channel, (int)off.NoteNumber, (int)off.Velocity), + ControlChangeEvent cc => (e.Tick, "cc", (int)cc.Channel, (int)cc.ControlNumber, (int)cc.ControlValue), + _ => throw new InvalidOperationException("Unexpected read-back event.") + }; + + public void Dispose() => Directory.Delete(directory, recursive: true); +} diff --git a/tests/GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests/Publishing/PublishedServerTests.cs b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests/Publishing/PublishedServerTests.cs new file mode 100644 index 0000000..ffa0ca2 --- /dev/null +++ b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests/Publishing/PublishedServerTests.cs @@ -0,0 +1,372 @@ +using System.Security.Cryptography; +using System.Text.Json; +using System.Text.Json.Nodes; +using GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests.Stdio; +using Xunit.Abstractions; +using static GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests.Stdio.McpGenerationTests; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests.Publishing; + +public sealed class PublishedServerTests(PublishedPayload payload, ITestOutputHelper output) + : IClassFixture +{ + private const string Ame = "ample-ame-documented-defaults-2026-10-20"; + private const string Aglp = "ample-aglp-documented-defaults-2026-10-20"; + private const string Agm = "ample-agm-documented-defaults-2026-10-20"; + private const string Agt = "ample-agt-documented-defaults-2026-10-20"; + private const string Description = "4 bars at 120 BPM in E minor, 4/4: palm-muted eighth-note lead"; + + private JsonObject Arguments(string profile = Ame) => new() + { + ["description"] = Description, + ["outputDirectory"] = Path.Combine(payload.Root, "output-" + Guid.NewGuid().ToString("N")), + ["projectName"] = "published-song", + ["formats"] = new JsonArray("mid"), + ["profiles"] = new JsonObject { ["lead"] = profile }, + ["fallbackToMidi"] = false + }; + + [Theory] + [InlineData(Ame)] + [InlineData(Aglp)] + [InlineData(Agm)] + [InlineData(Agt)] + public async Task IsolatedPublishedRpcDiscoversAndGeneratesReadableMidi(string profile) + { + await using var server = payload.Start(); + await server.InitializeAsync(); + await server.SendAsync("""{"jsonrpc":"2.0","id":10,"method":"tools/list"}"""); + var tools = (await server.ReadAsync()).GetProperty("result").GetProperty("tools"); + Assert.Equal(new[] { "generate_project", "list_instrument_profiles" }, + tools.EnumerateArray().Select(t => t.GetProperty("name").GetString())); + var discovery = Structured(await server.CallToolAsync("list_instrument_profiles", new { }, 11), false); + Assert.Equal(7, discovery.GetProperty("instruments").GetArrayLength()); + Assert.Equal(2, discovery.GetProperty("instruments").EnumerateArray() + .Count(i => i.GetProperty("availability").GetString() == "mapping_unavailable")); + Assert.Equal(new[] { Abj, Aglp, Agm, Agt, Ame }, discovery.GetProperty("profiles").EnumerateArray() + .Select(p => p.GetProperty("id").GetString())); + Assert.All(discovery.GetProperty("profiles").EnumerateArray(), p => + Assert.Equal("documented", p.GetProperty("evidence").GetProperty("status").GetString())); + var bass = Assert.Single(discovery.GetProperty("profiles").EnumerateArray(), + p => p.GetProperty("id").GetString() == Abj); + Assert.Equal(1, bass.GetProperty("channel").GetInt32()); + Assert.Equal("sustain", Assert.Single(bass.GetProperty("articulations").EnumerateArray()) + .GetProperty("articulation").GetString()); + var arguments = Arguments(profile); + var result = Structured(await server.CallToolAsync("generate_project", arguments, 12), false); + Assert.Equal("complete", result.GetProperty("status").GetString()); + Assert.Equal(120, result.GetProperty("timing").GetProperty("leadInTicks").GetInt64()); + Assert.Contains(result.GetProperty("warnings").EnumerateArray(), w => + w.GetProperty("code").GetString() == "documented_profile" && + w.GetProperty("message").GetString()!.Contains("NOT installed/application-verified")); + VerifyArtifact(result, arguments); + await PingAndFinish(server); + } + + [Theory] + [InlineData("agp")] + [InlineData("agp+mid")] + [InlineData("omitted")] + public async Task PublishedNativeRequestsFallBackToExactlyOneActualMidi(string formats) + { + await using var server = payload.Start(); + await server.InitializeAsync(); + var arguments = Arguments(); + arguments["fallbackToMidi"] = true; + if (formats == "omitted") arguments.Remove("formats"); + else arguments["formats"] = new JsonArray(formats.Split('+').Select(f => (JsonNode?)JsonValue.Create(f)).ToArray()); + var result = Structured(await server.CallToolAsync("generate_project", arguments), false); + Assert.Equal("fallback", result.GetProperty("status").GetString()); + var native = Assert.Single(result.GetProperty("targets").EnumerateArray(), + t => t.GetProperty("requestedFormat").GetString() == "agp"); + Assert.Equal("fallback", native.GetProperty("outcome").GetString()); + Assert.Equal("native_writer_unavailable", native.GetProperty("reasonCode").GetString()); + VerifyArtifact(result, arguments); + await PingAndFinish(server); + } + + [Theory] + [InlineData("disabled", "native_fallback_disabled")] + [InlineData("bass", "no_default_profile")] + [InlineData("drums", "mapping_unavailable")] + [InlineData("abj-pm", "unsupported_articulation")] + [InlineData("unknown", "unknown_profile")] + [InlineData("wrong-role", "profile_role_mismatch")] + public async Task PublishedFailuresNeverDropRolesOrCreateOutput(string scenario, string code) + { + await using var server = payload.Start(); + await server.InitializeAsync(); + var arguments = Arguments(); + if (scenario == "disabled") arguments["formats"] = new JsonArray("agp", "mid"); + else if (scenario == "abj-pm") + { + arguments["description"] = "palm-muted bass"; + arguments["profiles"] = new JsonObject { ["bass"] = Abj }; + } + else if (scenario is "unknown" or "wrong-role") + arguments["profiles"]!["lead"] = scenario == "unknown" ? "unknown-profile" : Abj; + else arguments["description"] = "lead and " + scenario; + var result = Structured(await server.CallToolAsync("generate_project", arguments), true); + Assert.Equal("failed", result.GetProperty("status").GetString()); + Assert.Empty(result.GetProperty("artifacts").EnumerateArray()); + Assert.Contains(result.GetProperty("errors").EnumerateArray(), e => e.GetProperty("code").GetString() == code); + Assert.False(Directory.Exists(arguments["outputDirectory"]!.GetValue())); + await PingAndFinish(server); + } + + [Theory] + [InlineData(Ame, false)] + [InlineData(Ame, true)] + [InlineData(Aglp, false)] + [InlineData(Aglp, true)] + [InlineData(Agm, false)] + [InlineData(Agm, true)] + [InlineData(Agt, false)] + [InlineData(Agt, true)] + public async Task PublishedLeadBassUsesRefreshedProfilesAndOneReadableArtifact(string lead, bool native) + { + await using var server = payload.Start(); + await server.InitializeAsync(); + var arguments = Arguments(lead); + arguments["description"] = LeadBassDescription; + arguments["profiles"] = new JsonObject { ["lead"] = lead, ["bass"] = Abj }; + arguments["formats"] = native ? new JsonArray("agp", "mid") : new JsonArray("mid"); + arguments["fallbackToMidi"] = native; + var result = Structured(await server.CallToolAsync("generate_project", arguments), false); + var path = VerifyLeadBassArtifact(result, arguments, lead, native); + output.WriteLine($"Published Lead+Bass: {lead} + {Abj}; native={native}; bytes={new FileInfo(path).Length}; SHA256={Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(path)))}"); + await PingAndFinish(server); + } + + [Fact] + public void ExistingRetainedAmeExampleIsByteIdenticalAndStillReadable() + { + var path = Path.Combine(PublishedPayload.RepositoryRoot, "artifacts", "examples", "ame-lead-example.mid"); + Assert.True(File.Exists(path), "Preserve the accepted retained AME example."); + Assert.Equal(371, new FileInfo(path).Length); + Assert.Equal("6F5791FB5C3A7A17E54AAF6436963E4D5723FB948057585060C09BF9B2AFCA3E", + Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(path)))); + ReadBack(path); + output.WriteLine("Accepted 371-byte AME example preserved byte-for-byte and read back; no overwrite."); + } + + [Fact] + public async Task PublishedCollisionPreservesActualMidiAndUnrelatedFile() + { + await using var server = payload.Start(); + await server.InitializeAsync(); + var arguments = Arguments(); + var first = Structured(await server.CallToolAsync("generate_project", arguments), false); + var path = VerifyArtifact(first, arguments); + var original = File.ReadAllBytes(path); + var unrelated = Path.Combine(Path.GetDirectoryName(path)!, "owner.txt"); + File.WriteAllText(unrelated, "preserve"); + var second = Structured(await server.CallToolAsync("generate_project", arguments, 2), true); + Assert.Contains(second.GetProperty("errors").EnumerateArray(), e => e.GetProperty("code").GetString() == "output_exists"); + Assert.Empty(second.GetProperty("artifacts").EnumerateArray()); + Assert.Equal(original, File.ReadAllBytes(path)); + Assert.Equal("preserve", File.ReadAllText(unrelated)); + Assert.Equal(2, Directory.GetFiles(Path.GetDirectoryName(path)!).Length); + ReadBack(path); + await PingAndFinish(server); + } + + [Fact] + public async Task PublishedMalformedInputRecoversAndEmptyEofExitsSilently() + { + await using (var empty = payload.Start()) + { + Assert.Empty(await empty.FinishAsync()); + empty.AssertNoMoreResponses(); + } + await using var server = payload.Start(); + await server.SendAsync("not-json"); + Assert.Equal(-32700, (await server.ReadAsync()).GetProperty("error").GetProperty("code").GetInt32()); + await server.InitializeAsync(); + Assert.Equal(-32602, (await server.CallToolAsync("generate_project", new { })).GetProperty("error").GetProperty("code").GetInt32()); + await PingAndFinish(server); + } + + [Fact] + public async Task PublishedCancellationAndEofLeaveNoOutput() + { + await using var server = payload.Start(); + await server.InitializeAsync(); + var arguments = Arguments(); + arguments["description"] = "100000 bars sustained lead"; + var request = JsonSerializer.Serialize(new + { + jsonrpc = "2.0", id = "cancel", method = "tools/call", + @params = new { name = "generate_project", arguments } + }); + await server.SendAsync(request + "\n" + + """{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":"cancel"}}""" + "\n" + + """{"jsonrpc":"2.0","id":"ping","method":"ping"}"""); + Assert.Equal("ping", (await server.ReadAsync()).GetProperty("id").GetString()); + Assert.Empty(await server.FinishAsync()); + server.AssertNoMoreResponses(); + Assert.False(Directory.Exists(arguments["outputDirectory"]!.GetValue())); + } + + [Fact] + public async Task PublishedEofCancelsActiveGenerationWithoutPublication() + { + await using var server = payload.Start(); + await server.InitializeAsync(); + var arguments = Arguments(); + arguments["description"] = "100000 bars sustained lead"; + await server.SendAsync(JsonSerializer.Serialize(new + { + jsonrpc = "2.0", id = "eof", method = "tools/call", + @params = new { name = "generate_project", arguments } + })); + Assert.Empty(await server.FinishAsync()); + server.AssertNoMoreResponses(); + Assert.False(Directory.Exists(arguments["outputDirectory"]!.GetValue())); + } + + [Fact] + public async Task PublishedRpcGeneratesReadBackExample() + { + await using var server = payload.Start(); + await server.InitializeAsync(); + var arguments = Arguments(); + var retain = Environment.GetEnvironmentVariable("RIFFGROOVE_RETAIN_EXAMPLE") == "1"; + if (retain) + { + var examples = Path.Combine(PublishedPayload.RepositoryRoot, "artifacts", "examples"); + var stem = "ame-lead-example"; + if (File.Exists(Path.Combine(examples, stem + ".mid")) || Directory.Exists(Path.Combine(examples, stem + ".mid"))) + stem += "-" + Guid.NewGuid().ToString("N"); + arguments["outputDirectory"] = examples; + arguments["projectName"] = stem; + } + var result = Structured(await server.CallToolAsync("generate_project", arguments), false); + Assert.Equal("complete", result.GetProperty("status").GetString()); + Assert.Contains(result.GetProperty("warnings").EnumerateArray(), + w => w.GetProperty("code").GetString() == "documented_profile"); + VerifyArtifact(result, arguments, exclusiveDirectory: !retain); + await PingAndFinish(server); + } + + [Fact] + public async Task ExecutableAloneGeneratesMidiAndExtractsBundledNativeAssets() + { + var directory = Path.Combine(payload.Root, "executable-only"); + Directory.CreateDirectory(directory); + var executable = Path.Combine(directory, McpProcess.ServerName + ".exe"); + File.Copy(payload.Executable, executable); + var extraction = Path.Combine(payload.Root, "exe-only-extraction"); + var trace = Path.Combine(payload.Root, "host-trace.txt"); + await using var server = new McpProcess(true, executable, new Dictionary + { + ["DOTNET_BUNDLE_EXTRACT_BASE_DIR"] = extraction, + ["DOTNET_HOST_TRACE"] = "1", + ["DOTNET_HOST_TRACEFILE"] = trace + }); + await server.InitializeAsync(); + var arguments = Arguments(); + VerifyArtifact(Structured(await server.CallToolAsync("generate_project", arguments), false), arguments); + await PingAndFinish(server); + Assert.Equal(new[] { executable }, Directory.GetFiles(directory)); + var extracted = Directory.GetFiles(extraction, "*", SearchOption.AllDirectories); + foreach (var name in new[] { "Melanchall_DryWetMidi_Native32.dll", "Melanchall_DryWetMidi_Native64.dll" }) + { + var file = Assert.Single(extracted, p => Path.GetFileName(p) == name); + output.WriteLine($"Extracted {name}: {new FileInfo(file).Length} bytes"); + } + Assert.DoesNotContain(extracted, p => Path.GetFileName(p) == "Melanchall.DryWetMidi.dll"); + Assert.Equal(2, extracted.Length); + Assert.Equal("080346C638E219EC7CD4748E370E5E11931ED3A228C17F76D84C4D10BA9C9E6F", + Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(Assert.Single(extracted, + p => Path.GetFileName(p) == "Melanchall_DryWetMidi_Native32.dll"))))); + Assert.Equal("80CA89AF931E43642A125EC82E253D9BD7002088D000DABA6E0661CDAD89F5AA", + Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(Assert.Single(extracted, + p => Path.GetFileName(p) == "Melanchall_DryWetMidi_Native64.dll"))))); + var hostTrace = File.ReadAllText(trace); + foreach (var line in hostTrace.Split('\n').Where(l => + l.Contains("coreclr", StringComparison.OrdinalIgnoreCase) || + l.Contains("hostpolicy", StringComparison.OrdinalIgnoreCase) || + l.Contains("self-contained", StringComparison.OrdinalIgnoreCase) || + l.Contains("extraction", StringComparison.OrdinalIgnoreCase)).Take(15)) + output.WriteLine(line.TrimEnd()); + output.WriteLine($"Extracted files: {string.Join(", ", extracted.Select(Path.GetFileName))}"); + Assert.Contains("Executing as a self-contained app", hostTrace); + Assert.Contains("Using internal hostpolicy", hostTrace); + Assert.Contains("CoreCLR path = '', CoreCLR dir = ''", hostTrace); + output.WriteLine("Executable-only MIDI generation needs no loose managed DLL/catalog or optional sidecars. Runtime-free host acceptance remains pending."); + } + + private string VerifyArtifact(JsonElement result, JsonObject arguments, bool exclusiveDirectory = true) + { + var artifact = Assert.Single(result.GetProperty("artifacts").EnumerateArray()); + var path = artifact.GetProperty("absolutePath").GetString()!; + var directory = arguments["outputDirectory"]!.GetValue(); + Assert.Equal(Path.Combine(directory, arguments["projectName"]!.GetValue() + ".mid"), path); + Assert.Equal("mid", artifact.GetProperty("format").GetString()); + Assert.Equal(371, new FileInfo(path).Length); + Assert.Equal(new FileInfo(path).Length, artifact.GetProperty("byteCount").GetInt64()); + if (exclusiveDirectory) Assert.Equal(new[] { path }, Directory.GetFiles(directory)); + ReadBack(path); + output.WriteLine($"Published RPC: {path}; bytes={new FileInfo(path).Length}; SHA256={Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(path)))}"); + output.WriteLine("DryWetMIDI 8.0.3: type1/960 PPQ, Conductor/Lead, 120 BPM/4/4, 32 notes64/96, switch26/100 on0/off30, lead-in120, end15480."); + return path; + } + + private async Task PingAndFinish(McpProcess server) + { + await server.SendAsync("""{"jsonrpc":"2.0","id":"ready","method":"ping"}"""); + Assert.Equal("ready", (await server.ReadAsync()).GetProperty("id").GetString()); + Assert.Empty(await server.FinishAsync()); + server.AssertNoMoreResponses(); + output.WriteLine("Initialized/responded to RPC and ping; protocol-only stdout; empty stderr; EOF exit0."); + } +} + +public sealed class PublishedPayload : IDisposable +{ + public static string RepositoryRoot + { + get + { + var directory = new DirectoryInfo(AppContext.BaseDirectory); + while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "global.json"))) + directory = directory.Parent; + return directory?.FullName ?? throw new InvalidOperationException("Cannot locate repository root."); + } + } + + public string Root { get; } = Path.Combine(RepositoryRoot, "artifacts", "checks", "published-" + Guid.NewGuid().ToString("N")); + public string Executable { get; } + + public PublishedPayload() + { + var source = Environment.GetEnvironmentVariable("RIFFGROOVE_PUBLISHED_SERVER") ?? + Path.Combine(RepositoryRoot, "artifacts", "publish", "win-x64", McpProcess.ServerName + ".exe"); + Assert.True(Path.IsPathFullyQualified(source)); + Assert.True(File.Exists(source), $"Publish win-x64 first; published executable missing: {source}"); + var sourceDirectory = Path.GetDirectoryName(source)!; + var files = Directory.GetFiles(sourceDirectory, "*", SearchOption.AllDirectories); + Assert.DoesNotContain(files, f => Path.GetExtension(f) is ".dll" or ".json"); + var isolated = Path.Combine(Root, "payload"); + Directory.CreateDirectory(isolated); + foreach (var file in files) + { + var destination = Path.Combine(isolated, Path.GetRelativePath(sourceDirectory, file)); + Directory.CreateDirectory(Path.GetDirectoryName(destination)!); + File.Copy(file, destination, overwrite: false); + } + Executable = Path.Combine(isolated, Path.GetFileName(source)); + } + + internal McpProcess Start() => new(independentWorkingDirectory: true, executablePath: Executable, + environment: new Dictionary + { + ["DOTNET_BUNDLE_EXTRACT_BASE_DIR"] = Path.Combine(Root, "extraction") + }); + + public void Dispose() + { + if (Directory.Exists(Root)) Directory.Delete(Root, recursive: true); + } +} diff --git a/tests/GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests/Stdio/McpGenerationTests.cs b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests/Stdio/McpGenerationTests.cs new file mode 100644 index 0000000..36d5c4e --- /dev/null +++ b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests/Stdio/McpGenerationTests.cs @@ -0,0 +1,468 @@ +using System.Security.Cryptography; +using System.Text.Json; +using System.Text.Json.Nodes; +using Melanchall.DryWetMidi.Core; +using Xunit.Abstractions; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests.Stdio; + +public sealed class McpGenerationTests(ITestOutputHelper output) : IDisposable +{ + private const string Aglp = "ample-aglp-documented-defaults-2026-10-20"; + private const string Ame = "ample-ame-documented-defaults-2026-10-20"; + private const string Agm = "ample-agm-documented-defaults-2026-10-20"; + private const string Agt = "ample-agt-documented-defaults-2026-10-20"; + internal const string Abj = "ample-abj-documented-defaults-2026-10-20"; + internal const string LeadBassDescription = + "4 bars at 120 BPM in E minor, 4/4: palm-muted eighth-note lead guitar, sustained root-note bass"; + private readonly string directory = Path.Combine(AppContext.BaseDirectory, "rpc-generation-" + Guid.NewGuid().ToString("N")); + + private JsonObject Arguments() => new() + { + ["description"] = "palm-muted eighth-note lead", ["outputDirectory"] = directory, ["projectName"] = "rpc-song", + ["formats"] = new JsonArray("mid"), ["profiles"] = new JsonObject { ["lead"] = Aglp } + }; + + [Theory] + [InlineData(Aglp, "mid", false)] + [InlineData(Ame, "mid", false)] + [InlineData(Aglp, "agp", true)] + [InlineData(Ame, "agp+mid", true)] + [InlineData(Aglp, "omitted", true)] + [InlineData(Agm, "mid", false)] + [InlineData(Agt, "mid", false)] + public async Task RealRpcGeneratesReadableDocumentedMidiAndOneHonestFallbackArtifact(string profileId, string formats, bool fallback) + { + await using var server = new McpProcess(independentWorkingDirectory: true); + await server.InitializeAsync(); + await server.SendAsync("""{"jsonrpc":"2.0","id":10,"method":"tools/list"}"""); + var tools = (await server.ReadAsync()).GetProperty("result").GetProperty("tools").EnumerateArray().ToArray(); + Assert.Equal(new[] { "generate_project", "list_instrument_profiles" }, tools.Select(t => t.GetProperty("name").GetString())); + var schema = tools[0].GetProperty("outputSchema"); + Assert.False(schema.GetProperty("additionalProperties").GetBoolean()); + Assert.True(schema.TryGetProperty("allOf", out _)); + var discovery = Structured(await server.CallToolAsync("list_instrument_profiles", new { }, 11), false); + Assert.Equal(7, discovery.GetProperty("instruments").GetArrayLength()); + Assert.Equal(2, discovery.GetProperty("instruments").EnumerateArray().Count(i => i.GetProperty("availability").GetString() == "mapping_unavailable")); + Assert.Equal(5, discovery.GetProperty("profiles").GetArrayLength()); + Assert.Equal(new[] { Abj, Aglp, Agm, Agt, Ame }, discovery.GetProperty("profiles").EnumerateArray() + .Select(p => p.GetProperty("id").GetString())); + var profile = Assert.Single(discovery.GetProperty("profiles").EnumerateArray(), p => p.GetProperty("id").GetString() == profileId); + Assert.Equal("documented", profile.GetProperty("evidence").GetProperty("status").GetString()); + Assert.Equal("unverified", profile.GetProperty("nativeStatus").GetString()); + Assert.All(discovery.GetProperty("formats").EnumerateArray(), f => + Assert.Equal(f.GetProperty("format").GetString() == "mid" ? "implemented" : "unavailable", f.GetProperty("writerStatus").GetString())); + var arguments = Arguments(); + arguments["profiles"]!["lead"] = profileId; + arguments["fallbackToMidi"] = fallback; + if (formats == "omitted") arguments.Remove("formats"); + else arguments["formats"] = new JsonArray(formats.Split('+').Select(s => (JsonNode?)JsonValue.Create(s)).ToArray()); + var result = Structured(await server.CallToolAsync("generate_project", arguments, 12), false); + AssertShape(schema, result); + Assert.Equal(formats == "mid" ? "complete" : "fallback", result.GetProperty("status").GetString()); + Assert.Empty(result.GetProperty("errors").EnumerateArray()); + var interpreted = result.GetProperty("interpretedComposition"); + Assert.Equal(120, interpreted.GetProperty("tempoBpm").GetDouble()); + Assert.Equal("4/4", interpreted.GetProperty("meter").GetString()); + Assert.Equal("E minor", interpreted.GetProperty("key").GetString()); + Assert.Equal(4, interpreted.GetProperty("bars").GetInt32()); + Assert.Equal(new[] { "lead" }, interpreted.GetProperty("roles").EnumerateArray().Select(r => r.GetString())); + Assert.NotEmpty(interpreted.GetProperty("defaultsApplied").EnumerateArray()); + Assert.Equal(960, result.GetProperty("timing").GetProperty("ticksPerQuarterNote").GetInt32()); + Assert.Equal(120, result.GetProperty("timing").GetProperty("leadInTicks").GetInt64()); + var warning = Assert.Single(result.GetProperty("warnings").EnumerateArray(), w => w.GetProperty("code").GetString() == "documented_profile"); + Assert.Contains("NOT installed/application-verified", warning.GetProperty("message").GetString()); + foreach (var note in profile.GetProperty("compatibilityNotes").EnumerateObject()) + Assert.Contains(note.Value.GetString()!, warning.GetProperty("message").GetString()); + var artifact = Assert.Single(result.GetProperty("artifacts").EnumerateArray()); + Assert.Equal("mid", artifact.GetProperty("format").GetString()); + Assert.Equal(new[] { "lead" }, artifact.GetProperty("roles").EnumerateArray().Select(r => r.GetString())); + Assert.Equal(new[] { profileId }, artifact.GetProperty("profileIds").EnumerateArray().Select(r => r.GetString())); + var path = artifact.GetProperty("absolutePath").GetString()!; + Assert.Equal(Path.Combine(directory, "rpc-song.mid"), path); + Assert.True(Path.IsPathFullyQualified(path)); + Assert.Equal(new FileInfo(path).Length, artifact.GetProperty("byteCount").GetInt64()); + Assert.Equal(new[] { path }, Directory.GetFiles(directory)); + Assert.All(result.GetProperty("targets").EnumerateArray(), target => + { + Assert.Equal("lead", target.GetProperty("role").GetString()); + Assert.Equal(profileId, target.GetProperty("profileId").GetString()); + Assert.Equal(profile.GetProperty("instrumentId").GetString(), target.GetProperty("instrumentId").GetString()); + Assert.Equal(new[] { path }, target.GetProperty("artifactPaths").EnumerateArray().Select(p => p.GetString())); + var native = target.GetProperty("requestedFormat").GetString() != "mid"; + Assert.Equal(native ? "fallback" : "written", target.GetProperty("outcome").GetString()); + if (native) Assert.Equal("native_writer_unavailable", target.GetProperty("reasonCode").GetString()); + else Assert.Equal(JsonValueKind.Null, target.GetProperty("reasonCode").ValueKind); + }); + Assert.Equal(formats is "agp+mid" or "omitted" ? 2 : 1, result.GetProperty("targets").GetArrayLength()); + if (formats != "mid") + Assert.Contains(result.GetProperty("warnings").EnumerateArray(), w => w.GetProperty("code").GetString() == "native_writer_unavailable"); + ReadBack(path); + output.WriteLine($"RPC {profileId}, formats={formats}, status={result.GetProperty("status")}, file={path}"); + output.WriteLine($"Bytes={new FileInfo(path).Length}; SHA256={Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(path)))}"); + output.WriteLine("Read-back: type 1, 960 PPQ; Conductor/Lead; 120 BPM, 4/4; 32 pitch-64 velocity-96 notes; PM26/100 at 0..30; lead-in120; 2 EOTs at15480."); + await server.SendAsync("""{"jsonrpc":"2.0","id":"ping-after-generation","method":"ping"}"""); + Assert.Equal("ping-after-generation", (await server.ReadAsync()).GetProperty("id").GetString()); + Assert.Empty(await server.FinishAsync()); + server.AssertNoMoreResponses(); + } + + [Theory] + [InlineData("bass", 2, 1)] + [InlineData("drums", 1, 0)] + [InlineData("lead", 4, 4)] + public async Task RealDiscoveryRoleFilterKeepsUnavailableTargetsVisible(string role, int instruments, int profiles) + { + await using var server = new McpProcess(true); + await server.InitializeAsync(); + var result = Structured(await server.CallToolAsync("list_instrument_profiles", new { role }), false); + Assert.Equal(instruments, result.GetProperty("instruments").GetArrayLength()); + Assert.Equal(profiles, result.GetProperty("profiles").GetArrayLength()); + Assert.All(result.GetProperty("instruments").EnumerateArray(), i => Assert.Equal(role, i.GetProperty("role").GetString())); + Assert.Empty(await server.FinishAsync()); + server.AssertNoMoreResponses(); + } + + [Theory] + [InlineData("disabled")] + [InlineData("disabled-with-mid")] + [InlineData("missing")] + [InlineData("unknown")] + [InlineData("wrong-role")] + [InlineData("extra-role")] + [InlineData("bass")] + [InlineData("drums")] + [InlineData("combined")] + [InlineData("inapplicable")] + [InlineData("text")] + [InlineData("name")] + [InlineData("path")] + [InlineData("limit")] + [InlineData("abj-pm")] + public async Task RealGenerationExpectedFailuresReturnNoArtifactOrSilentRoleDrop(string scenario) + { + var arguments = Arguments(); + var expectedCode = scenario switch + { + "disabled" or "disabled-with-mid" => "native_fallback_disabled", "missing" => "no_default_profile", + "unknown" => "unknown_profile", "wrong-role" => "profile_role_mismatch", "extra-role" => "unselected_role_profile", + "bass" => "no_default_profile", "drums" or "combined" => "mapping_unavailable", + "abj-pm" => "unsupported_articulation", "inapplicable" => "inapplicable_format", + "text" => "unsupported_text", "limit" => "midi_not_supported", _ => "invalid_output_path" + }; + switch (scenario) + { + case "disabled": + case "disabled-with-mid": + arguments["formats"] = scenario == "disabled" ? new JsonArray("agp") : new JsonArray("agp", "mid"); + arguments["fallbackToMidi"] = false; + break; + case "missing": arguments.Remove("profiles"); break; + case "unknown": arguments["profiles"]!["lead"] = "unknown"; break; + case "wrong-role": + arguments["description"] = "bass"; arguments["profiles"] = new JsonObject { ["bass"] = Aglp }; break; + case "extra-role": arguments["profiles"]!["drums"] = Aglp; break; + case "bass": + case "drums": arguments["description"] = scenario; arguments.Remove("profiles"); break; + case "combined": arguments["description"] = "lead and bass and drums"; break; + case "inapplicable": arguments["formats"] = new JsonArray("sdp"); break; + case "text": arguments["description"] = "heavy metal lead"; break; + case "name": arguments["projectName"] = "..\\escape"; break; + case "path": arguments["outputDirectory"] = "relative"; break; + case "limit": arguments["description"] = "sustained lead 1/256"; break; + case "abj-pm": arguments["description"] = "palm-muted bass"; + arguments["profiles"] = new JsonObject { ["bass"] = Abj }; break; + } + await using var server = new McpProcess(true); + await server.InitializeAsync(); + var result = Structured(await server.CallToolAsync("generate_project", arguments), true); + Assert.Equal("failed", result.GetProperty("status").GetString()); + Assert.Empty(result.GetProperty("artifacts").EnumerateArray()); + Assert.Contains(result.GetProperty("errors").EnumerateArray(), e => e.GetProperty("code").GetString() == expectedCode); + Assert.All(result.GetProperty("targets").EnumerateArray(), t => + { + Assert.Equal("failed", t.GetProperty("outcome").GetString()); + Assert.Empty(t.GetProperty("artifactPaths").EnumerateArray()); + }); + if (scenario == "text") + { + Assert.Equal(JsonValueKind.Null, result.GetProperty("interpretedComposition").ValueKind); + Assert.Equal(JsonValueKind.Null, result.GetProperty("timing").ValueKind); + } + Assert.Empty(Directory.Exists(directory) ? Directory.GetFiles(directory, "*", SearchOption.AllDirectories) : []); + Assert.False(Directory.Exists(directory)); + Assert.Empty(await server.FinishAsync()); + server.AssertNoMoreResponses(); + } + + [Theory] + [InlineData(Aglp, false)] + [InlineData(Aglp, true)] + [InlineData(Ame, false)] + [InlineData(Ame, true)] + [InlineData(Agm, false)] + [InlineData(Agm, true)] + [InlineData(Agt, false)] + [InlineData(Agt, true)] + public async Task RealRpcWritesCompleteLeadBassArrangementOnceWithSeparateChannels(string lead, bool native) + { + await using var server = new McpProcess(true); + await server.InitializeAsync(); + var arguments = Arguments(); + arguments["description"] = LeadBassDescription; + arguments["profiles"] = new JsonObject { ["lead"] = lead, ["bass"] = Abj }; + arguments["formats"] = native ? new JsonArray("agp", "mid") : new JsonArray("mid"); + arguments["fallbackToMidi"] = native; + var result = Structured(await server.CallToolAsync("generate_project", arguments), false); + var path = VerifyLeadBassArtifact(result, arguments, lead, native); + output.WriteLine($"RPC Lead+Bass: {lead} + {Abj}; native={native}; bytes={new FileInfo(path).Length}; SHA256={Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(path)))}"); + Assert.Empty(await server.FinishAsync()); + server.AssertNoMoreResponses(); + } + + internal static string VerifyLeadBassArtifact(JsonElement result, JsonObject arguments, string lead, bool native) + { + Assert.Equal(native ? "fallback" : "complete", result.GetProperty("status").GetString()); + Assert.Empty(result.GetProperty("errors").EnumerateArray()); + Assert.Equal(new[] { "lead", "bass" }, + result.GetProperty("interpretedComposition").GetProperty("roles").EnumerateArray().Select(r => r.GetString())); + Assert.Equal(960, result.GetProperty("timing").GetProperty("ticksPerQuarterNote").GetInt32()); + Assert.Equal(120, result.GetProperty("timing").GetProperty("leadInTicks").GetInt64()); + var artifact = Assert.Single(result.GetProperty("artifacts").EnumerateArray()); + Assert.Equal("mid", artifact.GetProperty("format").GetString()); + Assert.Equal(new[] { "lead", "bass" }, artifact.GetProperty("roles").EnumerateArray().Select(r => r.GetString())); + Assert.Equal(new[] { lead, Abj }, artifact.GetProperty("profileIds").EnumerateArray().Select(r => r.GetString())); + var path = artifact.GetProperty("absolutePath").GetString()!; + Assert.Equal(Path.Combine(arguments["outputDirectory"]!.GetValue(), + arguments["projectName"]!.GetValue() + ".mid"), path); + Assert.Equal(new FileInfo(path).Length, artifact.GetProperty("byteCount").GetInt64()); + Assert.Equal(new[] { path }, Directory.GetFiles(Path.GetDirectoryName(path)!)); + var targets = result.GetProperty("targets").EnumerateArray().ToArray(); + Assert.Equal(native ? 4 : 2, targets.Length); + foreach (var (role, id) in new[] { ("lead", lead), ("bass", Abj) }) + { + var matching = targets.Where(t => t.GetProperty("role").GetString() == role).ToArray(); + Assert.Equal(native ? 2 : 1, matching.Length); + Assert.All(matching, t => + { + Assert.Equal(id, t.GetProperty("profileId").GetString()); + Assert.Equal(id[..id.IndexOf("-documented", StringComparison.Ordinal)], + t.GetProperty("instrumentId").GetString()); + Assert.Equal(new[] { path }, t.GetProperty("artifactPaths").EnumerateArray().Select(p => p.GetString())); + var fallback = t.GetProperty("requestedFormat").GetString() == "agp"; + Assert.Equal(fallback ? "fallback" : "written", t.GetProperty("outcome").GetString()); + if (fallback) + Assert.Equal("native_writer_unavailable", t.GetProperty("reasonCode").GetString()); + }); + } + var warnings = result.GetProperty("warnings").EnumerateArray().ToArray(); + Assert.Equal(2, warnings.Count(w => w.GetProperty("code").GetString() == "documented_profile")); + Assert.Equal(native ? 2 : 0, warnings.Count(w => w.GetProperty("code").GetString() == "native_writer_unavailable")); + Assert.Contains(warnings, w => w.GetProperty("role").GetString() == "bass" && + w.GetProperty("message").GetString()!.Contains("PalmMute are rejected", StringComparison.Ordinal)); + ReadBackLeadBass(path); + return path; + } + + internal static void ReadBackLeadBass(string path) + { + var file = MidiFile.Read(path, new ReadingSettings + { EndOfTrackStoringPolicy = EndOfTrackStoringPolicy.Store, MissedEndOfTrackPolicy = MissedEndOfTrackPolicy.Abort }); + Assert.Equal(MidiFileFormat.MultiTrack, file.OriginalFormat); + Assert.Equal(960, Assert.IsType(file.TimeDivision).TicksPerQuarterNote); + var tracks = file.Chunks.Cast().ToArray(); + Assert.Equal(new[] { "Conductor", "Lead", "Bass" }, + tracks.Select(t => Assert.Single(t.Events.OfType()).Text)); + Assert.Equal(500000, Assert.Single(tracks[0].Events.OfType()).MicrosecondsPerQuarterNote); + var meter = Assert.Single(tracks[0].Events.OfType()); + Assert.Equal(4, meter.Numerator); + Assert.Equal(4, meter.Denominator); + for (var i = 0; i < tracks.Length; i++) + { + long tick = 0; + var events = tracks[i].Events.Select(e => (Tick: tick += e.DeltaTime, Event: e)).ToArray(); + Assert.Equal(15480, Assert.Single(events, e => e.Event is EndOfTrackEvent).Tick); + Assert.Equal(15480, events.Last().Tick); + if (i == 0) + { + Assert.All(events.Where(e => e.Event is SetTempoEvent or TimeSignatureEvent), e => Assert.Equal(0, e.Tick)); + continue; + } + var actual = events.Where(e => e.Event is ChannelEvent).ToArray(); + Assert.Equal(i == 1 ? 66 : 10, actual.Length); + Assert.All(actual, e => Assert.Equal(i - 1, (int)((ChannelEvent)e.Event).Channel)); + var switchOn = Assert.IsType(actual[0].Event); + Assert.Equal(i == 1 ? 26 : 24, (int)switchOn.NoteNumber); + Assert.Equal(100, (int)switchOn.Velocity); + Assert.Equal(0, actual[0].Tick); + var switchOff = Assert.IsType(actual[1].Event); + Assert.Equal((int)switchOn.NoteNumber, (int)switchOff.NoteNumber); + Assert.Equal(0, (int)switchOff.Velocity); + Assert.Equal(30, actual[1].Tick); + var count = i == 1 ? 32 : 4; + var duration = i == 1 ? 480 : 3840; + for (var n = 0; n < count; n++) + { + var on = Assert.IsType(actual[2 + n * 2].Event); + var off = Assert.IsType(actual[3 + n * 2].Event); + Assert.Equal(i == 1 ? 64 : 40, (int)on.NoteNumber); + Assert.Equal(96, (int)on.Velocity); + Assert.Equal((int)on.NoteNumber, (int)off.NoteNumber); + Assert.Equal(0, (int)off.Velocity); + Assert.Equal(120 + n * duration, actual[2 + n * 2].Tick); + Assert.Equal(120 + (n + 1) * duration, actual[3 + n * 2].Tick); + } + } + } + + [Theory] + [InlineData("null-profiles")] + [InlineData("null-id")] + [InlineData("duplicate-formats")] + [InlineData("empty-formats")] + [InlineData("unknown-property")] + [InlineData("unknown-nested")] + [InlineData("wrong-enum-case")] + [InlineData("missing-description")] + public async Task RealRpcRejectsSchemaViolationsAndRemainsUsable(string scenario) + { + var arguments = Arguments(); + switch (scenario) + { + case "null-profiles": arguments["profiles"] = null; break; + case "null-id": arguments["profiles"]!["lead"] = null; break; + case "duplicate-formats": arguments["formats"] = new JsonArray("mid", "mid"); break; + case "empty-formats": arguments["formats"] = new JsonArray(); break; + case "unknown-property": arguments["extra"] = true; break; + case "unknown-nested": arguments["profiles"]!["guitar"] = Aglp; break; + case "wrong-enum-case": arguments["formats"] = new JsonArray("MID"); break; + case "missing-description": arguments.Remove("description"); break; + } + await using var server = new McpProcess(); + await server.InitializeAsync(); + var response = await server.CallToolAsync("generate_project", arguments); + Assert.Equal(-32602, response.GetProperty("error").GetProperty("code").GetInt32()); + await server.SendAsync("""{"jsonrpc":"2.0","id":2,"method":"ping"}"""); + Assert.Equal(2, (await server.ReadAsync()).GetProperty("id").GetInt32()); + Assert.False(Directory.Exists(directory)); + Assert.Empty(await server.FinishAsync()); + server.AssertNoMoreResponses(); + } + + [Fact] + public async Task RealRpcPreservesExistingDestinationAndUnrelatedFiles() + { + Directory.CreateDirectory(directory); + var destination = Path.Combine(directory, "rpc-song.mid"); + var unrelated = Path.Combine(directory, ".unrelated.stage"); + File.WriteAllText(destination, "other owner"); + File.WriteAllText(unrelated, "keep"); + await using var server = new McpProcess(true); + await server.InitializeAsync(); + var result = Structured(await server.CallToolAsync("generate_project", Arguments()), true); + Assert.Contains(result.GetProperty("errors").EnumerateArray(), e => e.GetProperty("code").GetString() == "output_exists"); + Assert.Empty(result.GetProperty("artifacts").EnumerateArray()); + Assert.Equal("other owner", File.ReadAllText(destination)); + Assert.Equal("keep", File.ReadAllText(unrelated)); + Assert.Equal(2, Directory.GetFiles(directory).Length); + Assert.Empty(await server.FinishAsync()); + server.AssertNoMoreResponses(); + } + + [Fact] + public async Task RealRpcCancellationReadAheadAndPingLeaveNoOutput() + { + await using var server = new McpProcess(true); + await server.InitializeAsync(); + var arguments = Arguments(); + arguments["description"] = "100000 bars sustained lead"; + var generate = JsonSerializer.Serialize(new { jsonrpc = "2.0", id = "cancel-me", method = "tools/call", @params = new { name = "generate_project", arguments } }); + await server.SendAsync(generate + "\n" + + """{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":"cancel-me"}}""" + "\n" + + """{"jsonrpc":"2.0","id":"ping","method":"ping"}"""); + Assert.Equal("ping", (await server.ReadAsync()).GetProperty("id").GetString()); + Assert.Empty(await server.FinishAsync()); + server.AssertNoMoreResponses(); + Assert.False(Directory.Exists(directory)); + } + + internal static JsonElement Structured(JsonElement response, bool isError) + { + var result = response.GetProperty("result"); + Assert.Equal(isError, result.GetProperty("isError").GetBoolean()); + var structured = result.GetProperty("structuredContent"); + var text = Assert.Single(result.GetProperty("content").EnumerateArray()); + Assert.Equal("text", text.GetProperty("type").GetString()); + Assert.Equal(structured.GetRawText(), text.GetProperty("text").GetString()); + return structured; + } + + private static void AssertShape(JsonElement schema, JsonElement result) + { + Assert.Equal(schema.GetProperty("properties").EnumerateObject().Select(p => p.Name).Order(), + result.EnumerateObject().Select(p => p.Name).Order()); + Assert.Equal(schema.GetProperty("required").EnumerateArray().Select(p => p.GetString()).Order(), + result.EnumerateObject().Select(p => p.Name).Order()); + foreach (var name in new[] { "artifacts", "targets", "warnings" }) + { + var fields = schema.GetProperty("properties").GetProperty(name).GetProperty("items").GetProperty("required") + .EnumerateArray().Select(p => p.GetString()).Order().ToArray(); + Assert.All(result.GetProperty(name).EnumerateArray(), item => + Assert.Equal(fields, item.EnumerateObject().Select(p => p.Name).Order())); + } + } + + internal static void ReadBack(string path) + { + var file = MidiFile.Read(path, new ReadingSettings + { + EndOfTrackStoringPolicy = EndOfTrackStoringPolicy.Store, + MissedEndOfTrackPolicy = MissedEndOfTrackPolicy.Abort + }); + Assert.Equal(MidiFileFormat.MultiTrack, file.OriginalFormat); + Assert.Equal(960, Assert.IsType(file.TimeDivision).TicksPerQuarterNote); + var tracks = file.Chunks.Cast().ToArray(); + Assert.Equal(2, tracks.Length); + Assert.Equal(new[] { "Conductor", "Lead" }, tracks.Select(t => Assert.Single(t.Events.OfType()).Text)); + Assert.Equal(500000, Assert.Single(tracks[0].Events.OfType()).MicrosecondsPerQuarterNote); + var meter = Assert.Single(tracks[0].Events.OfType()); + Assert.Equal(4, meter.Numerator); + Assert.Equal(4, meter.Denominator); + Assert.All(tracks, track => + { + var tick = 0L; + var events = track.Events.Select(e => (Tick: tick += e.DeltaTime, Event: e)).ToArray(); + Assert.All(events.Where(e => e.Event is SetTempoEvent or TimeSignatureEvent), e => Assert.Equal(0, e.Tick)); + Assert.Equal(15480, Assert.Single(events, e => e.Event is EndOfTrackEvent).Tick); + Assert.Equal(15480, events.Last().Tick); + }); + long time = 0; + var actual = tracks[1].Events.Select(e => (Tick: time += e.DeltaTime, Event: e)).Where(e => e.Event is ChannelEvent).ToArray(); + Assert.Equal(66, actual.Length); + Assert.All(actual, e => Assert.Equal(0, (int)((ChannelEvent)e.Event).Channel)); + var switchOn = Assert.IsType(actual[0].Event); + Assert.Equal(0, actual[0].Tick); + Assert.Equal(26, (int)switchOn.NoteNumber); + Assert.Equal(100, (int)switchOn.Velocity); + var switchOff = Assert.IsType(actual[1].Event); + Assert.Equal(30, actual[1].Tick); + Assert.Equal(26, (int)switchOff.NoteNumber); + Assert.Equal(0, (int)switchOff.Velocity); + for (var i = 0; i < 32; i++) + { + var on = Assert.IsType(actual[2 + i * 2].Event); + var off = Assert.IsType(actual[3 + i * 2].Event); + Assert.Equal(64, (int)on.NoteNumber); + Assert.Equal(96, (int)on.Velocity); + Assert.Equal(64, (int)off.NoteNumber); + Assert.Equal(0, (int)off.Velocity); + Assert.Equal(120 + i * 480, actual[2 + i * 2].Tick); + Assert.Equal(120 + (i + 1) * 480, actual[3 + i * 2].Tick); + } + } + + public void Dispose() + { + if (Directory.Exists(directory)) Directory.Delete(directory, true); + } +} diff --git a/tests/GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests/Stdio/McpProcess.cs b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests/Stdio/McpProcess.cs new file mode 100644 index 0000000..a51b040 --- /dev/null +++ b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests/Stdio/McpProcess.cs @@ -0,0 +1,139 @@ +using System.Diagnostics; +using System.Text; +using System.Text.Json; +using System.Threading.Channels; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests.Stdio; + +internal sealed class McpProcess : IAsyncDisposable +{ + public const string ServerName = "GAJ3T.MusicGen.RiffGrooveBuilder.Server"; + public static string ServerDirectory => Path.Combine(AppContext.BaseDirectory, "Server"); + private readonly Process _process; + private readonly CancellationTokenSource _timeout = new(TimeSpan.FromSeconds(15)); + private readonly Channel _responses = Channel.CreateUnbounded(); + private readonly Task _stdout; + private readonly Task _stderr; + + public McpProcess(bool independentWorkingDirectory = false, string? executablePath = null, + IReadOnlyDictionary? environment = null) + { + var executable = executablePath ?? Path.Combine(ServerDirectory, ServerName + (OperatingSystem.IsWindows() ? ".exe" : "")); + Assert.True(Path.IsPathFullyQualified(executable)); + var workingDirectory = independentWorkingDirectory + ? OperatingSystem.IsWindows() ? Environment.SystemDirectory : Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + : AppContext.BaseDirectory; + Assert.True(File.Exists(executable), $"Server apphost was not built/copied: {executable}"); + Assert.True(Directory.Exists(workingDirectory)); + if (independentWorkingDirectory) + { + Assert.False(Path.GetFullPath(workingDirectory).StartsWith( + Path.GetFullPath(AppContext.BaseDirectory), StringComparison.OrdinalIgnoreCase)); + } + + _process = new Process + { + StartInfo = new ProcessStartInfo + { + FileName = executable, + WorkingDirectory = workingDirectory, + UseShellExecute = false, + RedirectStandardInput = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + StandardInputEncoding = new UTF8Encoding(false), + StandardOutputEncoding = new UTF8Encoding(false, true), + StandardErrorEncoding = new UTF8Encoding(false, true), + CreateNoWindow = true + } + }; + if (environment is not null) + foreach (var (name, value) in environment) _process.StartInfo.Environment[name] = value; + Assert.True(_process.Start()); + _stdout = DrainStdoutAsync(); + _stderr = _process.StandardError.ReadToEndAsync(); + } + + private async Task DrainStdoutAsync() + { + try + { + while (await _process.StandardOutput.ReadLineAsync(_timeout.Token) is { } line) + { + using var message = JsonDocument.Parse(line); + var root = message.RootElement; + Assert.Equal(JsonValueKind.Object, root.ValueKind); + Assert.Equal("2.0", root.GetProperty("jsonrpc").GetString()); + Assert.True(root.TryGetProperty("id", out _)); + Assert.NotEqual(root.TryGetProperty("result", out _), root.TryGetProperty("error", out _)); + await _responses.Writer.WriteAsync(root.Clone(), _timeout.Token); + } + + _responses.Writer.TryComplete(); + } + catch (Exception exception) + { + _responses.Writer.TryComplete(exception); + throw; + } + } + + public async Task SendAsync(string json, string delimiter = "\n") => + await SendBytesAsync(Encoding.UTF8.GetBytes(json + delimiter)); + + public async Task SendBytesAsync(byte[] bytes) + { + await _process.StandardInput.BaseStream.WriteAsync(bytes, _timeout.Token); + await _process.StandardInput.BaseStream.FlushAsync(_timeout.Token); + } + + public async Task ReadAsync() => await _responses.Reader.ReadAsync(_timeout.Token); + + public async Task InitializeAsync() + { + await SendAsync(""" + {"jsonrpc":"2.0","id":"init","method":"initialize","params":{"protocolVersion":"2025-11-25", + "capabilities":{},"clientInfo":{"name":"generation-integration","version":"1"}}} + """.ReplaceLineEndings("")); + Assert.Equal("init", (await ReadAsync()).GetProperty("id").GetString()); + await SendAsync("""{"jsonrpc":"2.0","method":"notifications/initialized"}"""); + } + + public async Task CallToolAsync(string name, object arguments, int id = 1) + { + await SendAsync(JsonSerializer.Serialize(new { jsonrpc = "2.0", id, method = "tools/call", @params = new { name, arguments } })); + var response = await ReadAsync(); + Assert.Equal(id, response.GetProperty("id").GetInt32()); + return response; + } + + public async Task FinishAsync() + { + _process.StandardInput.Close(); + await _process.WaitForExitAsync(_timeout.Token); + await Task.WhenAll(_stdout, _stderr).WaitAsync(_timeout.Token); + Assert.Equal(0, _process.ExitCode); + return await _stderr; + } + + public void AssertNoMoreResponses() => Assert.False(_responses.Reader.TryRead(out _), "Unexpected extra protocol response."); + + public async ValueTask DisposeAsync() + { + try + { + if (!_process.HasExited) + { + _process.Kill(entireProcessTree: true); + await _process.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(5)); + } + + await Task.WhenAll(_stdout, _stderr).WaitAsync(TimeSpan.FromSeconds(5)); + } + finally + { + _process.Dispose(); + _timeout.Dispose(); + } + } +} diff --git a/tests/GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests/Stdio/McpProtocolTests.cs b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests/Stdio/McpProtocolTests.cs new file mode 100644 index 0000000..e07583f --- /dev/null +++ b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests/Stdio/McpProtocolTests.cs @@ -0,0 +1,146 @@ +using System.Text.Json; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests.Stdio; + +public sealed class McpProtocolTests +{ + [Theory] + [InlineData(false, "\n")] + [InlineData(false, "\r\n")] + [InlineData(true, "\n")] + [InlineData(true, "\r\n")] + public async Task RealApphostNegotiatesListsProductionToolsPingsAndExitsCleanly(bool independentWorkingDirectory, string delimiter) + { + await using var server = new McpProcess(independentWorkingDirectory); + await server.SendAsync(""" + {"jsonrpc":"2.0","id":"init-001","method":"initialize", + "params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"音楽 🎸","version":"1"}}} + """.ReplaceLineEndings(""), delimiter); + var initialize = await server.ReadAsync(); + Assert.Equal("init-001", initialize.GetProperty("id").GetString()); + var result = initialize.GetProperty("result"); + Assert.Equal("2025-11-25", result.GetProperty("protocolVersion").GetString()); + Assert.Equal("GAJ3T.MusicGen.RiffGrooveBuilder", result.GetProperty("serverInfo").GetProperty("name").GetString()); + Assert.False(string.IsNullOrWhiteSpace(result.GetProperty("serverInfo").GetProperty("version").GetString())); + var capability = Assert.Single(result.GetProperty("capabilities").EnumerateObject()); + Assert.Equal("tools", capability.Name); + Assert.False(capability.Value.GetProperty("listChanged").GetBoolean()); + + await server.SendAsync("""{"jsonrpc":"2.0","method":"notifications/initialized"}""", delimiter); + await server.SendAsync("""{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":"unknown","reason":"too late"}}""", delimiter); + await server.SendAsync("""{"jsonrpc":"2.0","method":"unsupported/notification"}""", delimiter); + await server.SendAsync("""{"jsonrpc":"2.0","id":2,"method":"tools/list"}""", delimiter); + var listing = await server.ReadAsync(); + Assert.Equal(2, listing.GetProperty("id").GetInt32()); + Assert.Equal(new[] { "generate_project", "list_instrument_profiles" }, + listing.GetProperty("result").GetProperty("tools").EnumerateArray().Select(t => t.GetProperty("name").GetString())); + Assert.False(listing.GetProperty("result").TryGetProperty("nextCursor", out _)); + await server.SendAsync("""{"jsonrpc":"2.0","id":"音楽\n🎸","method":"ping","params":{}}""", delimiter); + var ping = await server.ReadAsync(); + Assert.Equal("音楽\n🎸", ping.GetProperty("id").GetString()); + Assert.Equal("{}", ping.GetProperty("result").GetRawText()); + Assert.Equal("Ignored unsupported notification.", (await server.FinishAsync()).Trim()); + server.AssertNoMoreResponses(); + } + + [Fact] + public async Task RealApphostRecoversFromErrorsAndNegotiatesUnsupportedVersion() + { + await using var server = new McpProcess(independentWorkingDirectory: true); + await server.SendAsync("not-json"); + var malformed = await server.ReadAsync(); + Assert.Equal(JsonValueKind.Null, malformed.GetProperty("id").ValueKind); + Assert.Equal(-32700, ErrorCode(malformed)); + await server.SendAsync("""{"jsonrpc":"2.0","id":0,"method":"tools/list"}"""); + Assert.Equal(-32002, ErrorCode(await server.ReadAsync())); + await server.SendAsync(""" + {"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"future", + "capabilities":{},"clientInfo":{"name":"test","version":"1"}}} + """.ReplaceLineEndings("")); + Assert.Equal("2025-11-25", (await server.ReadAsync()).GetProperty("result").GetProperty("protocolVersion").GetString()); + await server.SendAsync("""{"jsonrpc":"2.0","method":"notifications/initialized"}"""); + + var failures = new[] + { + ("""{"jsonrpc":"2.0","id":"method","method":"unknown"}""", -32601, "method"), + ("""{"jsonrpc":"2.0","id":"tool","method":"tools/call","params":{"name":"generate_project","arguments":{}}}""", -32602, "tool"), + ("""{"jsonrpc":"2.0","id":"args","method":"tools/call","params":{"name":"x","arguments":[]}}""", -32602, "args"), + ("""{"jsonrpc":"2.0","id":"params","method":"ping","params":{"invalid":true}}""", -32602, "params"), + ("""{"jsonrpc":"2.0","id":"repeat","method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"x","version":"1"}}}""", -32002, "repeat"), + ("""[{"jsonrpc":"2.0","id":10,"method":"ping"}]""", -32600, (string?)null) + }; + foreach (var (request, code, id) in failures) + { + await server.SendAsync(request); + var response = await server.ReadAsync(); + Assert.Equal(id, response.GetProperty("id").GetString()); + Assert.Equal(code, ErrorCode(response)); + } + + await server.SendAsync("""{"jsonrpc":"2.0","id":9223372036854775807,"method":"ping"}"""); + Assert.Equal(long.MaxValue, (await server.ReadAsync()).GetProperty("id").GetInt64()); + Assert.Empty(await server.FinishAsync()); + server.AssertNoMoreResponses(); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task RealApphostRejectsBoundedFramingErrorsAndResynchronizes(bool invalidUtf8) + { + await using var server = new McpProcess(); + if (invalidUtf8) + { + await server.SendBytesAsync([0xff, 0xc0, 0x80, (byte)'\n']); + } + else + { + await server.SendAsync(new string('x', 1024 * 1024 + 1)); + } + + var error = await server.ReadAsync(); + Assert.Equal(invalidUtf8 ? -32700 : -32600, ErrorCode(error)); + Assert.Equal(JsonValueKind.Null, error.GetProperty("id").ValueKind); + await server.SendAsync("""{"jsonrpc":"2.0","id":1,"method":"ping"}"""); + Assert.Equal(1, (await server.ReadAsync()).GetProperty("id").GetInt32()); + var diagnostics = await server.FinishAsync(); + Assert.Contains(invalidUtf8 ? "UTF-8" : "byte limit", diagnostics); + Assert.True(diagnostics.Length < 200); + server.AssertNoMoreResponses(); + } + + [Fact] + public async Task RealApphostAcceptsExactlyOneMiBWithCrLf() + { + const string request = """{"jsonrpc":"2.0","id":1,"method":"ping"}"""; + await using var server = new McpProcess(); + await server.SendAsync(request.PadRight(1024 * 1024), "\r\n"); + Assert.Equal(1, (await server.ReadAsync()).GetProperty("id").GetInt32()); + Assert.Empty(await server.FinishAsync()); + server.AssertNoMoreResponses(); + } + + [Theory] + [InlineData("""{"jsonrpc":"2.0","id":1,"method":"ping"}""", true)] + [InlineData("invalid-json", false)] + public async Task RealApphostHandlesFinalNonNewlineFrameAtEof(string input, bool valid) + { + await using var server = new McpProcess(); + await server.SendAsync(input, delimiter: ""); + Assert.Empty(await server.FinishAsync()); + var response = await server.ReadAsync(); + if (valid) + { + Assert.Equal(1, response.GetProperty("id").GetInt32()); + Assert.True(response.TryGetProperty("result", out _)); + } + else + { + Assert.Equal(-32700, ErrorCode(response)); + } + + server.AssertNoMoreResponses(); + } + + private static int ErrorCode(JsonElement response) => response.GetProperty("error").GetProperty("code").GetInt32(); +} diff --git a/tests/GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests/Stdio/ProcessStartupTests.cs b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests/Stdio/ProcessStartupTests.cs new file mode 100644 index 0000000..35c6d1a --- /dev/null +++ b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests/Stdio/ProcessStartupTests.cs @@ -0,0 +1,37 @@ +using System.Reflection; +using System.Runtime.Versioning; +using System.Text.Json; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests.Stdio; + +public sealed class ProcessStartupTests +{ + [Theory] + [InlineData(false, "")] + [InlineData(false, "scaffold input\nanother line\n")] + [InlineData(true, "")] + [InlineData(true, "scaffold input\nanother line\n")] + public async Task ServerHandlesEmptyEofQuietlyButDoesNotDiscardInvalidInput(bool independentWorkingDirectory, string input) + { + Assert.Equal(".NETCoreApp,Version=v10.0", + typeof(ProcessStartupTests).Assembly.GetCustomAttribute()?.FrameworkName); + Assert.Equal(".NETCoreApp,Version=v10.0", + Assembly.LoadFile(Path.Combine(McpProcess.ServerDirectory, McpProcess.ServerName + ".dll")) + .GetCustomAttribute()?.FrameworkName); + + await using var server = new McpProcess(independentWorkingDirectory); + if (input.Length > 0) + { + await server.SendAsync(input, delimiter: ""); + for (var i = 0; i < 2; i++) + { + var response = await server.ReadAsync(); + Assert.Equal(JsonValueKind.Null, response.GetProperty("id").ValueKind); + Assert.Equal(-32700, response.GetProperty("error").GetProperty("code").GetInt32()); + } + } + + Assert.Empty(await server.FinishAsync()); + server.AssertNoMoreResponses(); + } +} diff --git a/tests/GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests/Support/SyntheticPipelineProfiles.cs b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests/Support/SyntheticPipelineProfiles.cs new file mode 100644 index 0000000..ba8b9c4 --- /dev/null +++ b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests/Support/SyntheticPipelineProfiles.cs @@ -0,0 +1,40 @@ +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Articulations; +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests.Support; + +internal static class SyntheticPipelineProfiles +{ + internal const string Example = "Generate 4 bars at 120 BPM in E minor, 4/4: palm-muted eighth-note lead guitar, sustained root-note bass, kick on beats 1 and 3, snare on beats 2 and 4, and closed hi-hat eighth notes."; + + internal static InstrumentProfile[] Profiles() => + [ + Pitched(TrackRole.Lead, 0, 240, true), + Pitched(TrackRole.Bass, 1, 120, true), + new("synthetic-drums", "synthetic-pipeline-drums", TrackRole.Drums, "Synthetic Pipeline Drums", "test-1", "map-test-1", + Evidence(), 40, 80, 9, null, [new(21, 0)], null, [new(21, 0)], + Enum.GetValues().Select((voice, i) => new ArticulationRule( + Articulation.Sustain, voice, 50 + i, StateBehavior.Latched, null, new(1, 127, null), + [new(21, 100)])).ToArray()) + ]; + + internal static InstrumentProfile Pitched(TrackRole role, int channel, long advance, bool palm) + { + var lead = role == TrackRole.Lead; + var rules = new List + { + new(Articulation.Sustain, null, null, StateBehavior.Latched, + new(lead ? 10 : 12, lead ? 90 : 92, advance, lead ? 30 : 20), new(1, 127, null), []) + }; + if (palm) + rules.Add(new(Articulation.PalmMute, null, null, StateBehavior.Latched, + new(lead ? 11 : 13, 91, advance, 30), new(64, 127, lead ? 110 : null), [])); + return new("synthetic-" + role.ToString().ToLowerInvariant(), + "synthetic-pipeline-" + role.ToString().ToLowerInvariant(), role, "Synthetic Pipeline " + role, + "test-1", "map-test-1", Evidence(), lead ? 40 : 20, 100, channel, + lead || !palm ? Articulation.Sustain : Articulation.PalmMute, [], null, [], rules); + } + + private static MappingEvidence Evidence() => new(MappingVerification.Synthetic, + "Invented test-only mapping, no vendor applicability", "Test-authored data", "Synthetic assertions only"); +} diff --git a/tests/GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests/packages.lock.json b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests/packages.lock.json new file mode 100644 index 0000000..4fd4b17 --- /dev/null +++ b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests/packages.lock.json @@ -0,0 +1,108 @@ +{ + "version": 2, + "dependencies": { + "net10.0": { + "Microsoft.NET.Test.Sdk": { + "type": "Direct", + "requested": "[18.11.0, 18.11.0]", + "resolved": "18.11.0", + "contentHash": "xf/bR0LNkhK0SnadDRlZIQmC4sac5Wk0e1WAdiQjRN3MSo6gQ9M2c4c1XRNnVGjfOvckh704W5CJ19AL0/Xsdg==", + "dependencies": { + "Microsoft.CodeCoverage": "18.11.0", + "Microsoft.TestPlatform.TestHost": "18.11.0" + } + }, + "xunit": { + "type": "Direct", + "requested": "[2.9.3, 2.9.3]", + "resolved": "2.9.3", + "contentHash": "TlXQBinK35LpOPKHAqbLY4xlEen9TBafjs0V5KnA4wZsoQLQJiirCR4CbIXvOH8NzkW4YeJKP5P/Bnrodm0h9Q==", + "dependencies": { + "xunit.analyzers": "1.18.0", + "xunit.assert": "2.9.3", + "xunit.core": "[2.9.3]" + } + }, + "xunit.runner.visualstudio": { + "type": "Direct", + "requested": "[4.0.1, 4.0.1]", + "resolved": "4.0.1", + "contentHash": "8CoAaZkniVekR1ycJyxn+hOz+6ZQCDPcoIsIs6ujd4WyFcBMlxGNU15Qb8Uxd4iO4UmOuETb0M6vzBbwX/mfLA==" + }, + "Microsoft.CodeCoverage": { + "type": "Transitive", + "resolved": "18.11.0", + "contentHash": "MhN9wpvL1Es4hfIYslrsVgIsUdDFxuOBTbAl9mGIMvFo8PP5CLf4DrGdNrfwWSyn0lqi6sssm+I/qkkLL3MU+g==" + }, + "Microsoft.TestPlatform.ObjectModel": { + "type": "Transitive", + "resolved": "18.11.0", + "contentHash": "BXBHYnwSOljKute8UYCMXOLAdB7awxEMppPSpqOF1ZxLD/W/OH+vTBgFaXA7q0aditJTVXSMVenel+wOkEIyNg==" + }, + "Microsoft.TestPlatform.TestHost": { + "type": "Transitive", + "resolved": "18.11.0", + "contentHash": "AKjwKpyRBwoQFQmpcchtoYlfJEBlaY/40uxBRi+qXP4NR7xT8t+XTJtOyEyumfvfJcH5pASs75LwNdXYRr4XNA==", + "dependencies": { + "Microsoft.TestPlatform.ObjectModel": "18.11.0" + } + }, + "xunit.abstractions": { + "type": "Transitive", + "resolved": "2.0.3", + "contentHash": "pot1I4YOxlWjIb5jmwvvQNbTrZ3lJQ+jUGkGjWE3hEFM0l5gOnBWS+H3qsex68s5cO52g+44vpGzhAt+42vwKg==" + }, + "xunit.analyzers": { + "type": "Transitive", + "resolved": "1.18.0", + "contentHash": "OtFMHN8yqIcYP9wcVIgJrq01AfTxijjAqVDy/WeQVSyrDC1RzBWeQPztL49DN2syXRah8TYnfvk035s7L95EZQ==" + }, + "xunit.assert": { + "type": "Transitive", + "resolved": "2.9.3", + "contentHash": "/Kq28fCE7MjOV42YLVRAJzRF0WmEqsmflm0cfpMjGtzQ2lR5mYVj1/i0Y8uDAOLczkL3/jArrwehfMD0YogMAA==" + }, + "xunit.core": { + "type": "Transitive", + "resolved": "2.9.3", + "contentHash": "BiAEvqGvyme19wE0wTKdADH+NloYqikiU0mcnmiNyXaF9HyHmE6sr/3DC5vnBkgsWaE6yPyWszKSPSApWdRVeQ==", + "dependencies": { + "xunit.extensibility.core": "[2.9.3]", + "xunit.extensibility.execution": "[2.9.3]" + } + }, + "xunit.extensibility.core": { + "type": "Transitive", + "resolved": "2.9.3", + "contentHash": "kf3si0YTn2a8J8eZNb+zFpwfoyvIrQ7ivNk5ZYA5yuYk1bEtMe4DxJ2CF/qsRgmEnDr7MnW1mxylBaHTZ4qErA==", + "dependencies": { + "xunit.abstractions": "2.0.3" + } + }, + "xunit.extensibility.execution": { + "type": "Transitive", + "resolved": "2.9.3", + "contentHash": "yMb6vMESlSrE3Wfj7V6cjQ3S4TXdXpRqYeNEI3zsX31uTsGMJjEw6oD5F5u1cHnMptjhEECnmZSsPxB6ChZHDQ==", + "dependencies": { + "xunit.extensibility.core": "[2.9.3]" + } + }, + "gaj3t.musicgen.riffgroovebuilder.core": { + "type": "Project" + }, + "gaj3t.musicgen.riffgroovebuilder.generation": { + "type": "Project", + "dependencies": { + "GAJ3T.MusicGen.RiffGrooveBuilder.Core": "[1.0.0, )", + "Melanchall.DryWetMidi": "[8.0.3, 8.0.3]" + } + }, + "Melanchall.DryWetMidi": { + "type": "CentralTransitive", + "requested": "[8.0.3, 8.0.3]", + "resolved": "8.0.3", + "contentHash": "U+Ubol4MhieY2xgZGqcI8H2F/4HWzWKq8/WPHd1SXS7WXaHyEWMnj56vtxKOJFM5FLbj+NOUny5+X2KAzI0YUg==" + } + } + } +} \ No newline at end of file diff --git a/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Articulations/ArticulationPlannerTests.cs b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Articulations/ArticulationPlannerTests.cs new file mode 100644 index 0000000..721d057 --- /dev/null +++ b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Articulations/ArticulationPlannerTests.cs @@ -0,0 +1,468 @@ +using System.Text.Json; +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Articulations; +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition; +using static GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests.Articulations.SyntheticProfiles; +using MusicalComposition = GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition.Composition; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests.Articulations; + +public sealed class ArticulationPlannerTests +{ + private static MidiEventPlan Plan(Data profile, params MusicalNote[] notes) + { + var result = ArticulationPlanner.Plan(Model(notes), [profile.Build()], true); + Assert.True(result.Success, string.Join("; ", result.Diagnostics)); + Assert.Empty(result.Diagnostics); + return result.Plan!; + } + + private static void Fails(ArticulationPlanningResult result, string code) + { + Assert.False(result.Success); + Assert.Null(result.Plan); + Assert.Contains(result.Diagnostics, e => e.Code == code); + } + + [Fact] + public void KeyswitchLatchesSuppressRepeatsAndExplicitlyTransitionsToSustain() + { + var plan = Plan(Switched(), Note(articulation: Articulation.PalmMute), + Note(1, articulation: Articulation.PalmMute), Note(3)); + Assert.Equal(120, plan.LeadInTicks); + Assert.Equal(15_360, plan.MusicalExtentTicks); + Assert.Equal(15_480, plan.MusicalEndTick); + Assert.Equal(15_480, plan.EndTick); + var events = Assert.Single(plan.Tracks).Events; + Assert.Equal(new PlannedNoteOn[] + { + new(0, 0, 11, 91, true), new(2880, 0, 10, 90, true) + }, events.OfType().Where(e => e.IsKeyswitch)); + Assert.Equal(new PlannedNoteOff[] + { + new(30, 0, 11, true), new(2910, 0, 10, true) + }, events.OfType().Where(e => e.IsKeyswitch)); + Assert.Equal(new long[] { 120, 1080, 3000 }, + events.OfType().Where(e => !e.IsKeyswitch).Select(e => e.Tick)); + Assert.Equal(new long[] { 1080, 2040, 3960 }, + events.OfType().Where(e => !e.IsKeyswitch).Select(e => e.Tick)); + AssertPairs(plan); + } + + [Fact] + public void InitialLatchedStateDoesNotEmitAnUnrequestedSwitch() + { + var plan = Plan(Switched(), Note()); + Assert.DoesNotContain(plan.Tracks[0].Events.OfType(), e => e.IsKeyswitch); + } + + [Theory] + [InlineData(Articulation.Sustain, 10, 90)] + [InlineData(Articulation.PalmMute, 11, 91)] + public void UnknownReceiverSelectsOnlyFirstRequestedStateAndSuppressesRepeatedLatches( + Articulation first, int pitch, int velocity) + { + var other = first == Articulation.Sustain ? Articulation.PalmMute : Articulation.Sustain; + var model = Model(Note(articulation: first), Note(2, articulation: first), Note(4, articulation: other)); + var source = JsonSerializer.Serialize(model); + var data = Switched(cc: true) with { Initial = null }; + var result = ArticulationPlanner.Plan(model, [data.Build()], true); + Assert.True(result.Success, string.Join("; ", result.Diagnostics)); + var plan = result.Plan!; + var events = plan.Tracks[0].Events; + Assert.Equal(120, plan.LeadInTicks); + var switches = events.OfType().Where(e => e.IsKeyswitch).ToArray(); + Assert.Equal(new PlannedNoteOn(0, 0, pitch, velocity, true), switches[0]); + Assert.Equal(2, switches.Length); + Assert.Equal(3840, switches[1].Tick); + Assert.NotEqual(switches[0].Pitch, switches[1].Pitch); + Assert.Equal(new long[] { 30, 3870 }, + events.OfType().Where(e => e.IsKeyswitch).Select(e => e.Tick)); + Assert.Equal(new long[] { 120, 2040, 3960 }, + events.OfType().Where(e => !e.IsKeyswitch).Select(e => e.Tick)); + Assert.Equal(new long[] { 1080, 3000, 4920 }, + events.OfType().Where(e => !e.IsKeyswitch).Select(e => e.Tick)); + Assert.Equal(source, JsonSerializer.Serialize(model)); + AssertPairs(plan); + } + + [Theory] + [InlineData(1, Articulation.Sustain)] + [InlineData(63, Articulation.Sustain)] + [InlineData(64, Articulation.PalmMute)] + [InlineData(127, Articulation.PalmMute)] + public void VelocityOnlyPreservesDynamicsAtInclusiveLayerBoundaries(int velocity, Articulation articulation) + { + var plan = Plan(new Data { Rules = [Rule(max: 63), Rule(Articulation.PalmMute, min: 64)] }, + Note(velocity: velocity, articulation: articulation)); + Assert.Equal(0, plan.LeadInTicks); + Assert.Equal(new PlannedNoteOn(0, 0, 64, velocity, false), + Assert.Single(plan.Tracks[0].Events.OfType())); + Assert.Equal(new PlannedNoteOff(960, 0, 64, false), + Assert.Single(plan.Tracks[0].Events.OfType())); + } + + [Theory] + [InlineData(64, Articulation.Sustain)] + [InlineData(63, Articulation.PalmMute)] + public void VelocityLayerConflictsNeverClamp(int velocity, Articulation articulation) => + Fails(ArticulationPlanner.Plan(Model(Note(velocity: velocity, articulation: articulation)), + [new Data { Rules = [Rule(max: 63), Rule(Articulation.PalmMute, min: 64)] }.Build()], true), + "velocity_layer_conflict"); + + [Fact] + public void ExplicitVelocityTransformationDoesNotMutateMusicalDynamics() + { + var note = Note(velocity: 80, articulation: Articulation.PalmMute); + var plan = Plan(new Data { Rules = [Rule(max: 63), Rule(Articulation.PalmMute, min: 64, output: 100)] }, note); + Assert.Equal(100, Assert.Single(plan.Tracks[0].Events.OfType()).Velocity); + Assert.Equal(80, note.Velocity); + } + + [Fact] + public void CcOnlyUsesInitialStateSuppressesRepeatsAndAppliesOnlyExplicitFinalReset() + { + var data = new Data + { + InitialControllers = [new(20, 0)], FinalControllers = [new(20, 0)], + Rules = + [ + Rule(behavior: StateBehavior.Latched, cc: [new(20, 0)]), + Rule(Articulation.PalmMute, StateBehavior.Latched, cc: [new(20, 100)]) + ] + }; + var plan = Plan(data, Note(articulation: Articulation.PalmMute), + Note(1, articulation: Articulation.PalmMute)); + Assert.Equal(new PlannedControlChange[] + { + new(0, 0, 20, 0, true), new(0, 0, 20, 100, false), new(15_360, 0, 20, 0, true) + }, plan.Tracks[0].Events.OfType()); + Assert.DoesNotContain(plan.Tracks[0].Events.OfType(), e => e.IsKeyswitch); + var withoutReset = Plan(data with { FinalControllers = [] }, Note(articulation: Articulation.PalmMute)); + Assert.Equal(2, withoutReset.Tracks[0].Events.OfType().Count()); + AssertPairs(plan); + } + + [Fact] + public void CombinedKeyswitchVelocityAndCcHaveExactValuesAndStableOrder() + { + var data = Switched(cc: true) with + { + Rules = + [ + Rule(behavior: StateBehavior.Latched, key: new(10, 90, 120, 30), cc: [new(20, 0)]), + Rule(Articulation.PalmMute, StateBehavior.Latched, new(11, 91, 120, 30), + [new(20, 100)], min: 64, output: 110) + ] + }; + var plan = Plan(data, Note(velocity: 96, articulation: Articulation.PalmMute)); + Assert.Equal(new PlannedMidiEvent[] + { + new PlannedControlChange(0, 0, 20, 0, true), + new PlannedControlChange(0, 0, 20, 100, false), + new PlannedNoteOn(0, 0, 11, 91, true), + new PlannedNoteOff(30, 0, 11, true), + new PlannedNoteOn(120, 0, 64, 110, false), + new PlannedNoteOff(1080, 0, 64, false) + }, plan.Tracks[0].Events); + AssertPairs(plan); + } + + [Fact] + public void MomentaryControlsRetriggerAndRestoreInitialCcWithoutExtraSustainSwitch() + { + var plan = Plan(Switched(StateBehavior.Momentary, cc: true), + Note(articulation: Articulation.PalmMute), Note(2, articulation: Articulation.PalmMute), Note(4)); + Assert.Equal(new PlannedNoteOn[] { new(0, 0, 11, 91, true), new(1920, 0, 11, 91, true) }, + plan.Tracks[0].Events.OfType().Where(e => e.IsKeyswitch)); + Assert.Equal(new PlannedNoteOff[] { new(1080, 0, 11, true), new(3000, 0, 11, true) }, + plan.Tracks[0].Events.OfType().Where(e => e.IsKeyswitch)); + Assert.Equal(new PlannedControlChange[] + { + new(0, 0, 20, 0, true), new(0, 0, 20, 100, false), + new(1080, 0, 20, 0, true), new(1920, 0, 20, 100, false), new(3000, 0, 20, 0, true) + }, plan.Tracks[0].Events.OfType()); + AssertPairs(plan); + } + + [Fact] + public void MomentaryMinimumHoldDurationExtendsFinalReleaseBeyondMusicalExtent() + { + var plan = Plan(Switched(StateBehavior.Momentary, duration: 2000, cc: true), + Note(15, articulation: Articulation.PalmMute)); + Assert.Equal(15_480, plan.MusicalEndTick); + Assert.Equal(16_400, plan.EndTick); + Assert.Contains(new PlannedNoteOff(16_400, 0, 11, true), plan.Tracks[0].Events); + Assert.Contains(new PlannedControlChange(16_400, 0, 20, 0, true), plan.Tracks[0].Events); + AssertPairs(plan); + } + + [Fact] + public void ExplicitFinalLatchedResetIncludesItsPulseTail() + { + var plan = Plan(Switched() with { Reset = Articulation.Sustain }, + Note(15, articulation: Articulation.PalmMute)); + Assert.Equal(15_510, plan.EndTick); + Assert.Contains(new PlannedNoteOn(15_480, 0, 10, 90, true), plan.Tracks[0].Events); + Assert.Contains(new PlannedNoteOff(15_510, 0, 10, true), plan.Tracks[0].Events); + AssertPairs(plan); + } + + [Fact] + public void SameTickReleasesPrecedeResetsThenStateChangesThenMusicalNotes() + { + var plan = Plan(Switched(StateBehavior.Momentary, advance: 0, duration: 1, cc: true), + Note(articulation: Articulation.PalmMute), Note(1, articulation: Articulation.PalmMute)); + var boundary = plan.Tracks[0].Events.Where(e => e.Tick == 960).ToArray(); + Assert.Equal(new[] { 0, 0, 1, 2, 2, 3 }, boundary.Select(e => e.Priority)); + Assert.IsType(boundary[2]); + Assert.Equal(0, ((PlannedControlChange)boundary[2]).Value); + Assert.Equal(100, ((PlannedControlChange)boundary[3]).Value); + AssertPairs(plan); + } + + [Fact] + public void AdjacentLatchedTransitionWithZeroAdvanceUsesNewStateAtBoundary() + { + var plan = Plan(Switched(advance: 0, cc: true), Note(articulation: Articulation.PalmMute), Note(1)); + var boundary = plan.Tracks[0].Events.Where(e => e.Tick == 960).ToArray(); + Assert.Equal(new[] { 0, 2, 2, 3 }, boundary.Select(e => e.Priority)); + Assert.Equal(new PlannedControlChange(960, 0, 20, 0, false), boundary[1]); + Assert.Equal(new PlannedNoteOn(960, 0, 10, 90, true), boundary[2]); + } + + [Fact] + public void DistinctVelocityLayersCanCoexistWithoutChannelWideControls() + { + var plan = Plan(new Data { Rules = [Rule(max: 63), Rule(Articulation.PalmMute, min: 64)] }, + Note(pitch: 64, velocity: 50), Note(pitch: 65, velocity: 100, articulation: Articulation.PalmMute)); + Assert.Equal(2, plan.Tracks[0].Events.OfType().Count()); + AssertPairs(plan); + } + + [Fact] + public void SameLatchedStateAllowsChordAndEmitsOneSwitch() + { + var plan = Plan(Switched(), Note(articulation: Articulation.PalmMute), + Note(pitch: 65, articulation: Articulation.PalmMute)); + Assert.Single(plan.Tracks[0].Events.OfType(), e => e.IsKeyswitch); + AssertPairs(plan); + } + + [Fact] + public void KeyswitchVelocityIsPartOfLatchedStateEvenWhenPitchIsIdentical() + { + var data = new Data + { + Rules = + [ + Rule(behavior: StateBehavior.Latched, key: new(10, 30, 0, 1)), + Rule(Articulation.PalmMute, StateBehavior.Latched, new(10, 100, 0, 1)) + ] + }; + var plan = Plan(data, Note(articulation: Articulation.PalmMute), Note(1)); + Assert.Equal(new[] { 100, 30 }, plan.Tracks[0].Events.OfType() + .Where(e => e.IsKeyswitch).Select(e => e.Velocity)); + Fails(ArticulationPlanner.Plan(Model(Note(articulation: Articulation.PalmMute), Note(pitch: 65)), + [data.Build()], true), "conflicting_articulation_state"); + AssertPairs(plan); + } + + [Fact] + public void CcOnlyMomentaryRetriggersEveryNoteAndRestoresExplicitBaseline() + { + var data = new Data + { + Channel = 15, InitialControllers = [new(0, 127)], + Rules = [Rule(), Rule(Articulation.PalmMute, StateBehavior.Momentary, cc: [new(0, 0)])] + }; + var plan = Plan(data, Note(articulation: Articulation.PalmMute), + Note(1, articulation: Articulation.PalmMute), Note(2)); + Assert.Equal(new PlannedControlChange[] + { + new(0, 15, 0, 127, true), new(0, 15, 0, 0, false), + new(960, 15, 0, 127, true), new(960, 15, 0, 0, false), new(1920, 15, 0, 127, true) + }, plan.Tracks[0].Events.OfType()); + Assert.DoesNotContain(plan.Tracks[0].Events.OfType(), e => e.IsKeyswitch); + AssertPairs(plan); + } + + [Fact] + public void DrumsWithConflictingCcStateCannotSoundTogether() + { + var composition = new MusicalComposition(120, new(4, 4), new(4, KeyMode.Minor), 1, + [new(TrackRole.Drums, hits: + [new(DrumVoice.Kick, new(0), new(1), 96), new(DrumVoice.Snare, new(0), new(1), 96)])]); + var data = new Data + { + Role = TrackRole.Drums, Initial = null, InitialControllers = [new(20, 0)], + Rules = + [ + Rule(behavior: StateBehavior.Latched, cc: [new(20, 0)], voice: DrumVoice.Kick, drumPitch: 50), + Rule(behavior: StateBehavior.Latched, cc: [new(20, 127)], voice: DrumVoice.Snare, drumPitch: 51) + ] + }; + Fails(ArticulationPlanner.Plan(composition, [data.Build()], true), "conflicting_articulation_state"); + } + + [Fact] + public void NonrepresentableSourceTimingFailsWithoutPartialEvents() + { + var note = new MusicalNote(64, new(0), new(1, 7), 96, Articulation.Sustain); + Fails(ArticulationPlanner.Plan(Model(note), [new Data().Build()], true), "unrepresentable_timing"); + } + + [Fact] + public void FinalResetPulseOverflowIsCheckedAfterOtherwiseRepresentableEvents() => + Fails(ArticulationPlanner.Plan(Model(Note(articulation: Articulation.PalmMute)), + [(Switched(advance: 0, duration: long.MaxValue - 1000) with + { Reset = Articulation.Sustain }).Build()], true), "arithmetic_overflow"); + + [Fact] + public void FractionalTickRepresentableAdvanceAndMusicalTimingStayExact() + { + var note = new MusicalNote(64, new(1, 4), new(1, 4), 127, Articulation.PalmMute); + var plan = Plan(Switched(advance: 1, duration: 1), note); + Assert.Equal(1, plan.LeadInTicks); + Assert.Contains(new PlannedNoteOn(240, 0, 11, 91, true), plan.Tracks[0].Events); + Assert.Contains(new PlannedNoteOn(241, 0, 64, 127, false), plan.Tracks[0].Events); + Assert.Contains(new PlannedNoteOff(481, 0, 64, false), plan.Tracks[0].Events); + AssertPairs(plan); + } + + [Fact] + public void UnusedRuleDoesNotAddLeadInOrCauseHypotheticalOverflow() + { + var data = new Data + { + Rules = + [ + Rule(behavior: StateBehavior.Latched, key: new(10, 90, 0, 1)), + Rule(Articulation.PalmMute, StateBehavior.Latched, new(11, 91, long.MaxValue, 1)) + ] + }; + var plan = Plan(data, Note()); + Assert.Equal(0, plan.LeadInTicks); + Assert.Equal(new PlannedNoteOn(0, 0, 64, 96, false), + Assert.Single(plan.Tracks[0].Events.OfType())); + } + + [Theory] + [InlineData(StateBehavior.Latched, 0)] + [InlineData(StateBehavior.Momentary, 0)] + [InlineData(StateBehavior.Latched, 120)] + public void ConflictingSimultaneousArticulationsFail(StateBehavior behavior, long advance) => + Fails(ArticulationPlanner.Plan(Model(Note(articulation: Articulation.PalmMute), Note(pitch: 65)), + [Switched(behavior, advance).Build()], true), "conflicting_articulation_state"); + + [Fact] + public void AdvanceIntoPreviousSustainedNoteIsNotSilentlyAccepted() => + Fails(ArticulationPlanner.Plan(Model(Note(), Note(1, articulation: Articulation.PalmMute)), + [Switched().Build()], true), "conflicting_articulation_state"); + + [Fact] + public void OverlappingMomentarySameStateCannotRetriggerAmbiguously() => + Fails(ArticulationPlanner.Plan(Model(Note(articulation: Articulation.PalmMute), + Note(pitch: 65, articulation: Articulation.PalmMute)), + [Switched(StateBehavior.Momentary).Build()], true), "conflicting_articulation_state"); + + [Fact] + public void OverlappingSameMusicalPitchFailsEvenWithoutControls() => + Fails(ArticulationPlanner.Plan(Model(Note(duration: 2), Note(1)), + [new Data().Build()], true), "overlapping_midi_pitch"); + + [Theory] + [InlineData(39)] + [InlineData(101)] + public void OutOfProfilePitchesFail(int pitch) => + Fails(ArticulationPlanner.Plan(Model(Note(pitch: pitch)), [new Data().Build()], true), + "pitch_out_of_profile_range"); + + [Fact] + public void UnsupportedArticulationIsNotReplacedBySustain() => + Fails(ArticulationPlanner.Plan(Model(Note(articulation: Articulation.PalmMute)), + [new Data().Build()], true), "unsupported_articulation"); + + [Fact] + public void ProfilesMustBeExplicitMatchedVerifiedAndUnique() + { + var composition = Model(Note()); + Fails(ArticulationPlanner.Plan(composition, null), "missing_or_duplicate_profile"); + Fails(ArticulationPlanner.Plan(composition, [null!]), "missing_profile"); + Fails(ArticulationPlanner.Plan(composition, [new Data().Build()]), "unverified_profile"); + Fails(ArticulationPlanner.Plan(composition, [new Data().Build(), new Data().Build()], true), "missing_or_duplicate_profile"); + Fails(ArticulationPlanner.Plan(composition, [new Data { Role = TrackRole.Bass }.Build()], true), "unused_profile"); + Fails(ArticulationPlanner.Plan(null, [new Data().Build()], true), "invalid_composition"); + Fails(ArticulationPlanner.Plan(Model(Note(velocity: 0)), [new Data().Build()], true), "invalid_velocity"); + } + + [Fact] + public void IndependentlyControlledChannelsCannotCollide() + { + var composition = new MusicalComposition(120, new(4, 4), new(4, KeyMode.Minor), 1, + [new(TrackRole.Lead, [Note()]), new(TrackRole.Bass, [Note(pitch: 40)])]); + Fails(ArticulationPlanner.Plan(composition, + [new Data().Build(), new Data { Role = TrackRole.Bass, Id = "synthetic-bass" }.Build()], true), + "channel_collision"); + } + + [Theory] + [InlineData(long.MaxValue, 1, false)] + [InlineData(120, long.MaxValue, true)] + public void CheckedAdvanceReleaseAndFinalResetOverflowFails(long advance, long duration, bool reset) => + Fails(ArticulationPlanner.Plan(Model(Note(15, articulation: Articulation.PalmMute)), + [(Switched(advance: advance, duration: duration) with + { Reset = reset ? Articulation.Sustain : null }).Build()], true), "arithmetic_overflow"); + + [Fact] + public void UnmappedDrumVoiceFailsWithoutPartialPlan() + { + var composition = new MusicalComposition(120, new(4, 4), new(4, KeyMode.Minor), 1, + [new(TrackRole.Drums, hits: [new(DrumVoice.Snare, new(0), new(1), 96)])]); + var profile = new Data { Role = TrackRole.Drums, Initial = null, + Rules = [Rule(voice: DrumVoice.Kick, drumPitch: 50)] }.Build(); + Fails(ArticulationPlanner.Plan(composition, [profile], true), "unmapped_drum_voice"); + } + + [Fact] + public void DeterministicImmutableResultsPreserveSourceAndTrailingRests() + { + var source = Model(Note(articulation: Articulation.PalmMute)); + var before = JsonSerializer.Serialize(source); + var profile = Switched().Build(); + var first = ArticulationPlanner.Plan(source, [profile], true).Plan!; + var second = ArticulationPlanner.Plan(source, [profile], true).Plan!; + Assert.Equal(before, JsonSerializer.Serialize(source)); + Assert.Equal(JsonSerializer.Serialize(first), JsonSerializer.Serialize(second)); + Assert.Equal(first.Tracks[0].Events, second.Tracks[0].Events); + Assert.Equal(15_480, first.EndTick); + Assert.Throws(() => ((IList)first.Tracks).Clear()); + Assert.Throws(() => ((IList)first.Tracks[0].Events).Clear()); + AssertPairs(first); + } + + private static void AssertPairs(MidiEventPlan plan) + { + foreach (var track in plan.Tracks) + { + var active = new Dictionary(); + Assert.Equal(track.Events.OrderBy(e => e.Tick).ThenBy(e => e.Priority), track.Events); + foreach (var e in track.Events) + { + Assert.InRange(e.Tick, 0, plan.EndTick); + Assert.InRange(e.Channel, 0, 15); + if (e is PlannedNoteOn on) + { + Assert.InRange(on.Pitch, 0, 127); + Assert.InRange(on.Velocity, 1, 127); + Assert.True(active.TryAdd(on.Pitch, on.Tick)); + } + if (e is PlannedNoteOff off) + { + Assert.True(active.Remove(off.Pitch, out var start)); + Assert.True(off.Tick > start); + } + } + Assert.Empty(active); + } + } +} diff --git a/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Articulations/DocumentedProfileTests.cs b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Articulations/DocumentedProfileTests.cs new file mode 100644 index 0000000..e6269f5 --- /dev/null +++ b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Articulations/DocumentedProfileTests.cs @@ -0,0 +1,242 @@ +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Text.Json.Serialization; +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Articulations; +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition; +using GAJ3T.MusicGen.RiffGrooveBuilder.Generation.Profiles; +using MusicalComposition = GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition.Composition; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests.Articulations; + +public sealed class DocumentedProfileTests +{ + [Theory] + [InlineData("aglp", "Ample Guitar LP", 40, 86, 1, "7b28b62f3c25ecb774227b15beab06f5e0f0c944f35db9e82121028017f9cedb", + "AGLP-Prison_Break.zip", "3837")] + [InlineData("ame", "Ample Metal Eclipse", 36, 84, 64, "ab482f08b0546eca0a4233b8be3776c411b77f3dca96979f529debc2dfc0c4ca", + "AME-Eclipse.zip", "3720")] + [InlineData("agm", "Ample Guitar M", 40, 84, 1, "449bd7b8bca7771dbf8e08e0029d2bbe999f991efe441d7900ee93da29dd86a4", + "AGM-Dear_Ben.zip", "28798")] + [InlineData("agt", "Ample Guitar T", 40, 84, 1, "2e5696d750841a47061d37737ec7d8435cb4e30756cda15596d1f89ff87810dd", + "AGT-Wish_You_Were_Here.zip", "3840")] + public void EveryAdmittedMappingHasExactNumericFactsAndVendorAnchors(string code, string name, + int minimum, int maximum, int sustainMinimum, string hash, string sample, string anchorTick) + { + var catalog = InstrumentProfileCatalog.LoadEmbedded(); + var profile = catalog.SelectInstrument(TrackRole.Lead, "ample-" + code).Profile!; + Assert.Equal($"ample-{code}-documented-defaults-2026-10-20", profile.Id); + Assert.Equal(name, profile.ProductName); + Assert.Equal(TrackRole.Lead, profile.Role); + Assert.Equal(MappingVerification.Documented, profile.Evidence.Status); + Assert.Equal($"https://www.amplesound.net/en/Main_Panel_Manual-{code.ToUpperInvariant()}.pdf", + profile.Evidence.Source); + Assert.Contains(hash, profile.Evidence.VerificationRecord); + Assert.Contains("https://www.amplesound.net/dl0822/ds/" + sample, profile.Evidence.VerificationRecord); + Assert.Contains(anchorTick, profile.Evidence.VerificationRecord); + Assert.Contains("480 PPQ", profile.Evidence.VerificationRecord); + Assert.Contains("2026-10-20", profile.Evidence.VerificationRecord); + Assert.Contains("PDF pp.6-7", profile.Evidence.VerificationRecord); + Assert.Equal("documented defaults; installed version unknown", profile.ProductVersion); + Assert.Equal("published-defaults-2026-10-20.1", profile.MappingVersion); + Assert.Equal(minimum, profile.MinimumPitch); + Assert.Equal(maximum, profile.MaximumPitch); + Assert.Equal(0, profile.Channel); + Assert.Null(profile.InitialArticulation); + Assert.Null(profile.FinalResetArticulation); + Assert.Empty(profile.InitialControllers); + Assert.Empty(profile.FinalControllers); + Assert.Equal(2, profile.Rules.Count); + foreach (var (articulation, pitch, low, high) in new[] + { + (Articulation.Sustain, 24, sustainMinimum, 126), (Articulation.PalmMute, 26, 1, 127) + }) + { + var rule = Assert.Single(profile.Rules, r => r.Articulation == articulation); + Assert.Equal(StateBehavior.Latched, rule.Behavior); + Assert.Equal(new KeyswitchAction(pitch, 100, 120, 30), rule.Keyswitch); + Assert.Equal(low, rule.Velocity.Minimum); + Assert.Equal(high, rule.Velocity.Maximum); + Assert.Null(rule.Velocity.OutputVelocity); + Assert.Empty(rule.Controllers); + Assert.Null(rule.Voice); + Assert.Null(rule.DrumPitch); + } + var notes = Assert.IsType(profile.CompatibilityNotes); + Assert.Contains("Non-versioned", notes.VersionScope); + Assert.Contains("installed", notes.VersionScope); + Assert.Contains("MIDI Guitar mode disabled", notes.ConfigurationRequirements); + Assert.Contains("unknown", notes.ConfigurationRequirements); + Assert.Contains("channel 0", notes.RoutingPolicy); + Assert.Contains("120-tick advance and 30-tick", notes.TimingPolicy); + Assert.Contains("NOT a vendor minimum", notes.TimingPolicy); + Assert.Empty(InstrumentProfileValidator.Validate(profile)); + var changed = notes with { TimingPolicy = "Changed copy" }; + Assert.NotEqual(changed.TimingPolicy, profile.CompatibilityNotes!.TimingPolicy); + } + + [Theory] + [InlineData("ample-amr", TrackRole.Bass)] + [InlineData("toontrack-sd3", TrackRole.Drums)] + public void UnsupportedSourcesRemainUnavailableWithoutSubstitution(string instrumentId, TrackRole role) + { + var catalog = InstrumentProfileCatalog.LoadEmbedded(); + var result = catalog.SelectInstrument(role, instrumentId); + Assert.False(result.Success); + Assert.Equal("mapping_unavailable", Assert.Single(result.Diagnostics).Code); + Assert.Contains("numeric mapping evidence", result.Diagnostics[0].Message); + Assert.Empty(Assert.Single(catalog.Instruments, i => i.Instrument.Id == instrumentId).Profiles); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void MissingOrNullDocumentedNotesFailInsteadOfAcquiringDefaults(bool remove) + { + var json = Embedded(); + if (remove) + json[0]!.AsObject().Remove("compatibilityNotes"); + else + json[0]!["compatibilityNotes"] = null; + Assert.Contains("missing_compatibility_notes", Assert.Throws(() => Load(json)).Message); + } + + [Theory] + [InlineData("versionScope")] + [InlineData("configurationRequirements")] + [InlineData("routingPolicy")] + [InlineData("timingPolicy")] + public void EachDocumentedNoteIsRequiredInSerializedData(string field) + { + var json = Embedded(); + json[0]!["compatibilityNotes"]!.AsObject().Remove(field); + Assert.Contains("Malformed", Assert.Throws(() => Load(json)).Message); + json = Embedded(); + json[0]!["compatibilityNotes"]![field] = " "; + Assert.Contains("invalid_compatibility_notes", Assert.Throws(() => Load(json)).Message); + } + + [Theory] + [InlineData("instrumentId", "does-not-exist", "unknown_instrument")] + [InlineData("role", "Drums", "profile_role_mismatch")] + [InlineData("productName", "Other product", "profile_product_mismatch")] + public void DocumentedAdmissionStillRequiresExactBinding(string field, string value, string diagnostic) + { + var json = Embedded(); + json[0]![field] = value; + Assert.Contains(diagnostic, Assert.Throws(() => Load(json)).Message); + } + + [Fact] + public void LegacyVerifiedJsonWithoutNotesStillLoadsUnchanged() + { + var json = Embedded(); + foreach (var profile in json) + { + profile!["evidence"]!["status"] = "Verified"; + profile.AsObject().Remove("compatibilityNotes"); + } + Assert.All(Load(json).Profiles, p => + { + Assert.Equal(MappingVerification.Verified, p.Evidence.Status); + Assert.Null(p.CompatibilityNotes); + }); + } + + [Theory] + [InlineData("Synthetic")] + [InlineData("Unverified")] + public void DocumentedSourcesAndNotesCannotLaunderRejectedStatuses(string status) + { + var json = Embedded(); + json[0]!["evidence"]!["status"] = status; + Assert.Contains("unverified_profile", Assert.Throws(() => Load(json)).Message); + } + + [Theory] + [InlineData("ample-aglp", 39)] + [InlineData("ample-aglp", 87)] + [InlineData("ample-ame", 35)] + [InlineData("ample-ame", 85)] + [InlineData("ample-agm", 39)] + [InlineData("ample-agm", 85)] + [InlineData("ample-agt", 39)] + [InlineData("ample-agt", 85)] + [InlineData("ample-abj", 34)] + [InlineData("ample-abj", 77)] + public void NumericPlayableRangeBoundariesAreEnforcedBeforePlanning(string instrumentId, int pitch) + { + var profile = InstrumentProfileCatalog.LoadEmbedded().Profiles.Single(p => p.InstrumentId == instrumentId); + var model = new MusicalComposition(120, new(4, 4), new(4, KeyMode.Minor), 1, + [new(profile.Role, [SyntheticProfiles.Note(pitch: pitch)])]); + var result = ArticulationPlanner.Plan(model, [profile]); + Assert.False(result.Success); + Assert.Null(result.Plan); + Assert.Equal("pitch_out_of_profile_range", Assert.Single(result.Diagnostics).Code); + } + + [Fact] + public void AbjSharedVendorAnchorAdmitsOnlySustainAndDisclosesItsExactLimits() + { + var profile = InstrumentProfileCatalog.LoadEmbedded().SelectInstrument(TrackRole.Bass, "ample-abj").Profile!; + Assert.Equal("ample-abj-documented-defaults-2026-10-20", profile.Id); + Assert.Equal("Ample Bass J", profile.ProductName); + Assert.Equal(MappingVerification.Documented, profile.Evidence.Status); + Assert.Equal("https://www.amplesound.net/en/Main_Panel_Manual-ABJ.pdf", profile.Evidence.Source); + foreach (var fact in new[] { "9291c4e3027ac1469bd845bb04614f5a2754bd35a4f017bcfd7cdb75db335e7e", + "https://www.amplesound.net/en/download.asp", "ABJ ABP", "AB-Articulations.zip", + "c3efc1dc787c59a00be7405687488317efaf952822aededf54b9e19f4e145cb7", + "AB-Articulations/4.2 Articulations & Poly Legato.mid", "track 1 ABP", "3720/off 4080", + "NOT an independently ABJ-named performance" }) + Assert.Contains(fact, profile.Evidence.VerificationRecord); + Assert.Equal(35, profile.MinimumPitch); + Assert.Equal(76, profile.MaximumPitch); + Assert.Equal(1, profile.Channel); + Assert.Null(profile.InitialArticulation); + Assert.Null(profile.FinalResetArticulation); + Assert.Empty(profile.InitialControllers); + Assert.Empty(profile.FinalControllers); + var rule = Assert.Single(profile.Rules); + Assert.Equal(Articulation.Sustain, rule.Articulation); + Assert.Equal(StateBehavior.Latched, rule.Behavior); + Assert.Equal(new KeyswitchAction(24, 100, 120, 30), rule.Keyswitch); + Assert.Equal(new VelocityLayer(1, 125, null), rule.Velocity); + Assert.Null(rule.Voice); + Assert.Null(rule.DrumPitch); + Assert.Empty(rule.Controllers); + Assert.Contains("PalmMute are rejected", profile.CompatibilityNotes!.ConfigurationRequirements); + Assert.Contains("NOT a mandatory receiver channel", profile.CompatibilityNotes.RoutingPolicy); + Assert.Empty(InstrumentProfileValidator.Validate(profile)); + } + + [Fact] + public void AgmAndAgtProvenanceIncludesIndependentAbsoluteAndNamedTabControlAnchors() + { + var catalog = InstrumentProfileCatalog.LoadEmbedded(); + var agm = catalog.SelectInstrument(TrackRole.Lead, "ample-agm").Profile!; + foreach (var fact in new[] { "AGM-Rylynn/AGM3-Rylynn.mid", "32215/off 32335", + "AGM-Dear Ben/AGM-Dear Ben Tempo 74.mid", "28798/off 28858", "30238/off 30298" }) + Assert.Contains(fact, agm.Evidence.VerificationRecord); + var agt = catalog.SelectInstrument(TrackRole.Lead, "ample-agt").Profile!; + foreach (var fact in new[] { "https://www.amplesound.net/en/tutorial-b.asp", "6.3 Tab Play Toggle", + "MIDI note A6", "AGT-Wish_You_Were_Here/AGT3-Wish You Were Here Tempo 62.mid", + "105 velocity 80", "3840/off 4320", "C0=105-(6*12+9)=24", "NOT a label inferred", + "82a9b42109519d20d9340c6c6cdb972a66663482df483fd0bf5034b84b5d9262" }) + Assert.Contains(fact, agt.Evidence.VerificationRecord); + Assert.Contains("NOT a direct Sustain/PM performance", agt.CompatibilityNotes!.VersionScope); + Assert.DoesNotContain(agt.Rules, r => r.Keyswitch?.Pitch == 105); + } + + private static JsonArray Embedded() + { + var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; + options.Converters.Add(new JsonStringEnumConverter()); + return JsonSerializer.SerializeToNode(InstrumentProfileCatalog.LoadEmbedded().Profiles, options)!.AsArray(); + } + + private static InstrumentProfileCatalog Load(JsonArray json) + { + using var stream = new MemoryStream(Encoding.UTF8.GetBytes(json.ToJsonString())); + return InstrumentProfileCatalog.Load(stream); + } +} diff --git a/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Articulations/InstrumentProfileCatalogTests.cs b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Articulations/InstrumentProfileCatalogTests.cs new file mode 100644 index 0000000..3e34582 --- /dev/null +++ b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Articulations/InstrumentProfileCatalogTests.cs @@ -0,0 +1,318 @@ +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Text.Json.Serialization; +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Articulations; +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition; +using GAJ3T.MusicGen.RiffGrooveBuilder.Generation.Instruments; +using GAJ3T.MusicGen.RiffGrooveBuilder.Generation.Profiles; +using GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests.Instruments; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests.Articulations; + +[CollectionDefinition("Catalog working directory", DisableParallelization = true)] +public sealed class CatalogWorkingDirectoryCollection; + +[Collection("Catalog working directory")] +public sealed class InstrumentProfileCatalogTests +{ + [Fact] + public void EmbeddedCatalogIsDocumentedAndIndependentOfWorkingDirectory() + { + var previous = Environment.CurrentDirectory; + try + { + Environment.CurrentDirectory = Environment.SystemDirectory; + var catalog = InstrumentProfileCatalog.LoadEmbedded(); + Assert.Equal(5, catalog.Profiles.Count); + Assert.All(catalog.Profiles, p => Assert.Equal(MappingVerification.Documented, p.Evidence.Status)); + Assert.Throws(() => ((IList)catalog.Profiles).Clear()); + Assert.DoesNotContain(typeof(InstrumentProfileCatalog).Assembly.GetManifestResourceNames(), + n => n.Contains("synthetic", StringComparison.OrdinalIgnoreCase)); + } + finally + { + Environment.CurrentDirectory = previous; + } + } + + [Theory] + [InlineData(TrackRole.Lead)] + [InlineData(TrackRole.Bass)] + [InlineData(TrackRole.Drums)] + public void UnknownAndDefaultSelectionFailActionably(TrackRole role) + { + var catalog = InstrumentProfileCatalog.LoadEmbedded(); + foreach (var id in new string?[] { null, "", "does-not-exist", "synthetic-lead" }) + { + var result = catalog.Select(role, id); + Assert.False(result.Success); + Assert.Null(result.Profile); + Assert.Equal(string.IsNullOrEmpty(id) ? "no_default_profile" : "unknown_profile", + Assert.Single(result.Diagnostics).Code); + Assert.Contains("evidence", result.Diagnostics[0].Message); + } + Assert.Equal("invalid_role", Assert.Single(catalog.Select((TrackRole)999).Diagnostics).Code); + } + + [Theory] + [InlineData("")] + [InlineData("{")] + [InlineData("{}")] + [InlineData("null")] + [InlineData("[null]")] + [InlineData("[{}]")] + [InlineData("[{\"unexpected\":1}]")] + [InlineData("[] garbage")] + public void MalformedCatalogNeverBecomesSuccessfulEmpty(string json) => + Assert.Throws(() => Load(json)); + + [Theory] + [InlineData(MappingVerification.Synthetic)] + [InlineData(MappingVerification.Unverified)] + public void CompleteSyntheticOrUnverifiedResourcesAreNeverProductionSelectable(MappingVerification status) + { + var data = new SyntheticProfiles.Data(); + var profile = (data with { Evidence = data.Evidence with { Status = status } }).Build(); + var json = Serialize(profile); + var error = Assert.Throws(() => Load(json)); + Assert.Contains("unverified_profile", error.Message); + } + + [Theory] + [InlineData("instrumentId")] + [InlineData("productVersion")] + [InlineData("channel")] + [InlineData("initialArticulation")] + [InlineData("finalResetArticulation")] + [InlineData("initialControllers")] + [InlineData("finalControllers")] + [InlineData("rules")] + [InlineData("evidence")] + public void MissingConstructorFieldsAreMalformedRatherThanDefaulted(string field) + { + var node = JsonNode.Parse(Serialize(new SyntheticProfiles.Data().Build()))!; + node[0]!.AsObject().Remove(field); + var error = Assert.Throws(() => Load(node.ToJsonString())); + Assert.Contains("Malformed", error.Message); + } + + [Theory] + [InlineData("instrumentId")] + [InlineData("initialControllers")] + [InlineData("finalControllers")] + [InlineData("rules")] + [InlineData("evidence")] + public void NullRequiredFieldsFailExplicitly(string field) + { + var node = JsonNode.Parse(Serialize(new SyntheticProfiles.Data().Build()))!; + node[0]![field] = null; + Assert.Throws(() => Load(node.ToJsonString())); + } + + [Fact] + public void NumericEnumsAndUnknownPropertiesAreMalformed() + { + var node = JsonNode.Parse(Serialize(new SyntheticProfiles.Data().Build()))!; + node[0]!["role"] = 0; + Assert.Throws(() => Load(node.ToJsonString())); + node[0]!["role"] = "Lead"; + node[0]!["inventedMapping"] = 1; + Assert.Throws(() => Load(node.ToJsonString())); + } + + [Fact] + public void DuplicateJsonPropertiesCannotSilentlyOverwriteMappingEvidence() + { + var json = Serialize(new SyntheticProfiles.Data().Build()) + .Replace("\"channel\":0", "\"channel\":0,\"channel\":15", StringComparison.Ordinal); + var error = Assert.Throws(() => Load(json)); + Assert.Contains("Malformed", error.Message); + } + + [Fact] + public void DuplicateCatalogIdsAreRejectedAsWellAsUnverifiedEvidence() + { + var node = JsonNode.Parse(Serialize(new SyntheticProfiles.Data().Build()))!.AsArray(); + node.Add(node[0]!.DeepClone()); + var error = Assert.Throws(() => Load(node.ToJsonString())); + Assert.Contains("duplicate_profile_id", error.Message); + Assert.Contains("unverified_profile", error.Message); + } + + [Theory] + [InlineData("articulation")] + [InlineData("voice")] + [InlineData("drumPitch")] + [InlineData("behavior")] + [InlineData("keyswitch")] + [InlineData("velocity")] + [InlineData("controllers")] + public void MissingNestedRuleFieldsCannotAcquireImplicitDefaults(string field) + { + var node = JsonNode.Parse(Serialize(new SyntheticProfiles.Data().Build()))!; + node[0]!["rules"]![0]!.AsObject().Remove(field); + var error = Assert.Throws(() => Load(node.ToJsonString())); + Assert.Contains("Malformed", error.Message); + } + + [Theory] + [InlineData("instrumentId", "does-not-exist", "unknown_instrument")] + [InlineData("instrumentId", "bad id", "invalid_instrument_id")] + [InlineData("instrumentId", "", "invalid_instrument_id")] + [InlineData("instrumentId", "SYNTHETIC-EXTRA", "unknown_instrument")] + [InlineData("role", "Bass", "profile_role_mismatch")] + [InlineData("productName", "Synthetic Other", "profile_product_mismatch")] + [InlineData("productName", "synthetic extra", "profile_product_mismatch")] + public void ProfilesMustBindExactDeclaredIdentityAndRole(string field, string value, string code) + { + var node = JsonNode.Parse(CatalogFixtures.Read("profiles.json"))!; + node[0]![field] = value; + var error = Assert.Throws(() => CatalogFixtures.Profiles(node.ToJsonString())); + Assert.Contains(code, error.Message); + } + + [Theory] + [InlineData("Synthetic")] + [InlineData("Unverified")] + public void EvenCompleteDeclaredBindingsCannotAdmitSyntheticOrUnverifiedMappings(string status) + { + var node = JsonNode.Parse(CatalogFixtures.Read("profiles.json"))!; + node[0]!["evidence"]!["status"] = status; + Assert.Contains("unverified_profile", + Assert.Throws(() => CatalogFixtures.Profiles(node.ToJsonString())).Message); + } + + [Fact] + public void VerifiedFixtureDuplicatesStillFailAndEnumerationOrderDoesNotSelectAVersion() + { + var node = JsonNode.Parse(CatalogFixtures.Read("profiles.json"))!.AsArray(); + node.Add(node[0]!.DeepClone()); + Assert.Contains("duplicate_profile_id", + Assert.Throws(() => CatalogFixtures.Profiles(node.ToJsonString())).Message); + node.RemoveAt(node.Count - 1); + var reversed = new JsonArray(node.Reverse().Select(i => i!.DeepClone()).ToArray()); + var catalog = CatalogFixtures.Profiles(); + var reordered = CatalogFixtures.Profiles(reversed.ToJsonString()); + Assert.Equal(JsonSerializer.Serialize(catalog), JsonSerializer.Serialize(reordered)); + Assert.Equal(catalog.Profiles.OrderBy(p => p.Id, StringComparer.Ordinal), catalog.Profiles); + Assert.Equal("ambiguous_profile", + Assert.Single(reordered.SelectInstrument(TrackRole.Lead, "synthetic-extra").Diagnostics).Code); + } + + [Theory] + [InlineData(TrackRole.Lead, "unknown", null, "unknown_instrument")] + [InlineData(TrackRole.Lead, "synthetic-unmapped", null, "mapping_unavailable")] + [InlineData(TrackRole.Lead, "synthetic-extra", null, "ambiguous_profile")] + [InlineData(TrackRole.Bass, "synthetic-extra", null, "instrument_role_mismatch")] + [InlineData(TrackRole.Lead, "synthetic-extra", "synthetic-other-v1", "profile_instrument_mismatch")] + [InlineData(TrackRole.Lead, "synthetic-extra", "synthetic-bass-v1", "profile_role_mismatch")] + [InlineData(TrackRole.Lead, "synthetic-extra", "unknown", "unknown_profile")] + [InlineData(TrackRole.Lead, "synthetic-extra", "", "no_default_profile")] + [InlineData(TrackRole.Lead, "synthetic-unmapped", "synthetic-other-v1", "profile_instrument_mismatch")] + [InlineData((TrackRole)100, "synthetic-extra", null, "invalid_role")] + public void ExplicitInstrumentSelectionHasDistinctNoFallbackFailures(TrackRole role, string instrumentId, + string? profileId, string code) + { + var result = CatalogFixtures.Profiles().SelectInstrument(role, instrumentId, profileId); + Assert.False(result.Success); + Assert.Null(result.Profile); + Assert.Equal(code, Assert.Single(result.Diagnostics).Code); + } + + [Fact] + public void AdditionalInstrumentAndMultipleVersionedMappingsWorkThroughUnchangedPlanner() + { + var catalog = CatalogFixtures.Profiles(); + var extra = Assert.Single(catalog.Instruments, i => i.Instrument.Id == "synthetic-extra"); + Assert.Equal("profile_available", extra.Availability); + Assert.Equal(new[] { "test-1", "test-2" }, extra.Profiles.Select(p => p.ProductVersion)); + Assert.Equal(new[] { "test-map-1", "test-map-2" }, extra.Profiles.Select(p => p.MappingVersion)); + var composition = CompositionPlanner.Plan("lead").Composition!; + foreach (var (id, velocity) in new[] { ("synthetic-extra-v1", 96), ("synthetic-extra-v2", 110) }) + { + var selection = catalog.SelectInstrument(TrackRole.Lead, "synthetic-extra", id); + Assert.True(selection.Success); + Assert.Empty(selection.Diagnostics); + Assert.Same(catalog.Select(TrackRole.Lead, id).Profile, selection.Profile); + var result = ArticulationPlanner.Plan(composition, [selection.Profile!]); + Assert.True(result.Success, string.Join("; ", result.Diagnostics)); + var track = Assert.Single(result.Plan!.Tracks); + Assert.Equal(id, track.ProfileId); + Assert.All(track.Events.OfType(), n => Assert.Equal(velocity, n.Velocity)); + Assert.Equal(96, composition.Tracks[0].Notes[0].Velocity); + } + Assert.True(catalog.SelectInstrument(TrackRole.Lead, "synthetic-other").Success); + Assert.True(catalog.SelectInstrument(TrackRole.Bass, "synthetic-bass").Success); + Assert.Equal("profile_role_mismatch", + Assert.Single(catalog.Select(TrackRole.Bass, "synthetic-extra-v1").Diagnostics).Code); + Assert.Equal("no_default_profile", Assert.Single(catalog.Select(TrackRole.Lead).Diagnostics).Code); + Assert.Equal("mapping_unavailable", + Assert.Single(catalog.Instruments, i => i.Instrument.Id == "synthetic-unmapped").Availability); + Assert.Throws(() => ((IList)catalog.Instruments).Clear()); + Assert.Throws(() => ((IList)extra.Profiles).Clear()); + Assert.Throws(() => ((IList)catalog.Profiles).Clear()); + } + + [Fact] + public void ProductionIdentityMetadataNeverClaimsMappingOrNativeAcceptance() + { + var catalog = InstrumentProfileCatalog.LoadEmbedded(); + Assert.Equal(7, catalog.Instruments.Count); + Assert.All(catalog.Instruments, entry => + { + var selected = catalog.SelectInstrument(entry.Instrument.Role, entry.Instrument.Id); + if (entry.Instrument.Id is "ample-abj" or "ample-aglp" or "ample-agm" or "ample-agt" or "ample-ame") + { + Assert.Equal("profile_available", entry.Availability); + Assert.True(selected.Success); + Assert.Same(Assert.Single(entry.Profiles), selected.Profile); + Assert.Equal(MappingVerification.Documented, selected.Profile!.Evidence.Status); + Assert.NotNull(selected.Profile.CompatibilityNotes); + } + else + { + Assert.Equal("mapping_unavailable", entry.Availability); + Assert.Empty(entry.Profiles); + Assert.False(selected.Success); + Assert.Equal("mapping_unavailable", Assert.Single(selected.Diagnostics).Code); + } + }); + Assert.Equal(5, catalog.Profiles.Count); + Assert.DoesNotContain(typeof(InstrumentProfileCatalog).Assembly.GetManifestResourceNames(), + n => n.Contains("Fixture", StringComparison.OrdinalIgnoreCase)); + } + + [Fact] + public void DataOnlyExtensionCanJoinExistingTargetsWithoutChangingTheirAvailability() + { + var production = InstrumentCatalog.LoadEmbedded(); + var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; + options.Converters.Add(new JsonStringEnumConverter()); + var definitions = JsonSerializer.SerializeToNode(production.Instruments, options)!.AsArray(); + foreach (var definition in JsonNode.Parse(CatalogFixtures.Read("instruments.json"))!.AsArray()) + definitions.Add(definition!.DeepClone()); + var extended = CatalogFixtures.Profiles(instruments: CatalogFixtures.Instruments(definitions.ToJsonString())); + Assert.Equal(11, extended.Instruments.Count); + Assert.All(extended.Instruments.Where(i => production.Find(i.Instrument.Id) is not null), + i => Assert.Equal("mapping_unavailable", i.Availability)); + Assert.Equal("profile_available", + Assert.Single(extended.Instruments, i => i.Instrument.Id == "synthetic-extra").Availability); + Assert.True(extended.SelectInstrument(TrackRole.Lead, "synthetic-extra", "synthetic-extra-v2").Success); + Assert.Equal("mapping_unavailable", + Assert.Single(extended.SelectInstrument(TrackRole.Lead, "ample-ame").Diagnostics).Code); + } + + private static InstrumentProfileCatalog Load(string json) + { + using var stream = new MemoryStream(Encoding.UTF8.GetBytes(json)); + return InstrumentProfileCatalog.Load(stream); + } + + private static string Serialize(InstrumentProfile profile) + { + var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; + options.Converters.Add(new JsonStringEnumConverter()); + return JsonSerializer.Serialize(new[] { profile }, options); + } +} diff --git a/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Articulations/InstrumentProfileValidatorTests.cs b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Articulations/InstrumentProfileValidatorTests.cs new file mode 100644 index 0000000..4858e04 --- /dev/null +++ b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Articulations/InstrumentProfileValidatorTests.cs @@ -0,0 +1,211 @@ +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Articulations; +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition; +using static GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests.Articulations.SyntheticProfiles; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests.Articulations; + +public sealed class InstrumentProfileValidatorTests +{ + public static IEnumerable InvalidProfiles() + { + var p = new Data(); + var key = Switched(); + yield return Case(p with { Id = "" }, "invalid_profile_id"); + yield return Case(p with { Id = "bad id" }, "invalid_profile_id"); + foreach (var id in new string[] { null!, "", " ", "bad id", "bad/path", "é" }) + yield return Case(p with { InstrumentId = id }, "invalid_instrument_id"); + yield return Case(p with { ProductName = "" }, "missing_identity"); + yield return Case(p with { ProductVersion = " " }, "missing_identity"); + yield return Case(p with { MappingVersion = "" }, "missing_identity"); + yield return Case(p with { Role = (TrackRole)100 }, "invalid_role"); + yield return Case(p with { Evidence = p.Evidence with { Source = "" } }, "missing_evidence"); + yield return Case(p with { Evidence = p.Evidence with { Authorization = "" } }, "missing_evidence"); + yield return Case(p with { Evidence = p.Evidence with { VerificationRecord = "" } }, "missing_evidence"); + yield return Case(p with { Evidence = p.Evidence with { Status = MappingVerification.Unverified } }, "unverified_profile"); + yield return Case(p with { Evidence = p.Evidence with { Status = (MappingVerification)999 } }, "missing_evidence"); + yield return Case(p with { Evidence = null! }, "missing_evidence"); + yield return Case(p with { Id = "not-test" }, "invalid_synthetic_identity"); + yield return Case(p with { ProductName = "Not test" }, "invalid_synthetic_identity"); + yield return Case(p with { Channel = -1 }, "invalid_channel"); + yield return Case(p with { Channel = 16 }, "invalid_channel"); + yield return Case(p with { MinimumPitch = -1 }, "invalid_pitch_range"); + yield return Case(p with { MaximumPitch = 128 }, "invalid_pitch_range"); + yield return Case(p with { MinimumPitch = 101 }, "invalid_pitch_range"); + yield return Case(p with { Rules = [] }, "missing_rules"); + yield return Case(p with { Rules = [null!] }, "invalid_rule"); + yield return Case(p with { Rules = [Rule(), Rule()] }, "duplicate_rule"); + yield return Case(p with { Rules = [Rule((Articulation)123)] }, "invalid_rule"); + yield return Case(p with { Rules = [Rule(behavior: (StateBehavior)123)] }, "invalid_rule"); + yield return Case(p with { Rules = [Rule(min: 0)] }, "invalid_velocity_layer"); + yield return Case(p with { Rules = [Rule(max: 128)] }, "invalid_velocity_layer"); + yield return Case(p with { Rules = [Rule(min: 70, max: 69)] }, "invalid_velocity_layer"); + yield return Case(p with { Rules = [Rule(min: 60, max: 100, output: 59)] }, "invalid_velocity_layer"); + yield return Case(p with { Rules = [Rule(output: 128)] }, "invalid_velocity_layer"); + yield return Case(p with { Rules = [new(Articulation.Sustain, null, null, StateBehavior.None, null, null!, [])] }, "invalid_velocity_layer"); + foreach (var action in new[] { new KeyswitchAction(-1, 90, 0, 1), new(128, 90, 0, 1), + new(10, 0, 0, 1), new(10, 128, 0, 1), new(10, 90, -1, 1), + new(10, 90, 0, 0), new(10, 90, 0, -1) }) + yield return Case(key with { Rules = [Rule(behavior: StateBehavior.Latched, key: action)] }, "invalid_keyswitch"); + foreach (var pitch in new[] { 40, 64, 100 }) + yield return Case(key with { Rules = [Rule(behavior: StateBehavior.Latched, key: new(pitch, 90, 0, 1))] }, "keyswitch_collision"); + yield return Case(p with { Rules = [Rule(key: new(10, 90, 0, 1))] }, "invalid_state_behavior"); + yield return Case(p with { Rules = [Rule(behavior: StateBehavior.Latched)] }, "invalid_state_behavior"); + foreach (var cc in new[] { new ControllerValue(-1, 0), new(128, 0), new(1, -1), new(1, 128), null! }) + yield return Case(p with { InitialControllers = [cc] }, "invalid_controller"); + yield return Case(p with { InitialControllers = [new(1, 0), new(1, 0)] }, "invalid_controller"); + yield return Case(p with { FinalControllers = [new(1, 128)] }, "invalid_controller"); + yield return Case(p with { Rules = [Rule(behavior: StateBehavior.Latched, cc: [new(128, 0)])] }, "invalid_controller"); + yield return Case(Switched(cc: true) with { InitialControllers = [] }, "incomplete_controller_state"); + yield return Case(p with { InitialControllers = [new(1, 0)] }, "incomplete_controller_state"); + yield return Case(key with { FinalControllers = [new(1, 0)] }, "incomplete_controller_state"); + yield return Case(key with { Initial = Articulation.PalmMute, Rules = [key.Rules[0]] }, "invalid_initial_state"); + yield return Case(key with { Initial = (Articulation)99 }, "invalid_initial_state"); + yield return Case(Switched(StateBehavior.Momentary) with { Initial = Articulation.PalmMute }, "invalid_initial_state"); + yield return Case(p with { Reset = Articulation.PalmMute }, "invalid_final_reset"); + yield return Case(Switched(cc: true) with { InitialControllers = [new(20, 1)] }, "invalid_initial_state"); + yield return Case(Switched(cc: true) with { Reset = Articulation.Sustain, FinalControllers = [new(20, 100)] }, "conflicting_final_reset"); + yield return Case(p with { Rules = [Rule(), Rule(Articulation.PalmMute)] }, "ambiguous_velocity_layers"); + yield return Case(p with { Rules = [Rule(max: 64), Rule(Articulation.PalmMute, min: 64)] }, "ambiguous_velocity_layers"); + yield return Case(p with { Rules = [Rule(voice: DrumVoice.Kick, drumPitch: 50)] }, "invalid_pitched_rule"); + yield return Case(key with { Rules = [key.Rules[0], Rule(Articulation.PalmMute)] }, "incomplete_latched_state"); + yield return Case(key with { Rules = [key.Rules[0], Rule(Articulation.PalmMute, StateBehavior.Momentary, new(11, 90, 0, 1))] }, "mixed_state_behavior"); + yield return Case(Switched(cc: true) with { Rules = [Switched(cc: true).Rules[0], key.Rules[1]] }, "incomplete_controller_state"); + var drums = p with { Role = TrackRole.Drums, Initial = null, Rules = [Rule(voice: DrumVoice.Kick, drumPitch: 50)] }; + yield return Case(drums with { Rules = [Rule()] }, "invalid_drum_rule"); + yield return Case(drums with { Rules = [Rule(voice: (DrumVoice)99, drumPitch: 50)] }, "invalid_drum_rule"); + yield return Case(drums with { Rules = [Rule(Articulation.PalmMute, voice: DrumVoice.Kick, drumPitch: 50)] }, "invalid_drum_rule"); + yield return Case(drums with { Rules = [Rule(voice: DrumVoice.Kick, drumPitch: 101)] }, "invalid_drum_pitch"); + yield return Case(drums with { Rules = [Rule(voice: DrumVoice.Kick, drumPitch: 50), Rule(voice: DrumVoice.Snare, drumPitch: 50)] }, "invalid_drum_pitch"); + yield return Case(drums with { Initial = Articulation.Sustain }, "invalid_drum_state"); + yield return Case(drums with { Rules = [Rule(behavior: StateBehavior.Latched, key: new(10, 90, 0, 1), voice: DrumVoice.Kick, drumPitch: 50)] }, "invalid_drum_state"); + } + + private static object[] Case(Data data, string code) => [data.Build(), code]; + + [Theory] + [MemberData(nameof(InvalidProfiles))] + public void RejectsInvalidProfiles(InstrumentProfile profile, string code) => + Assert.Contains(InstrumentProfileValidator.Validate(profile, allowSynthetic: true), e => e.Code == code); + + [Fact] + public void SyntheticRequiresExplicitOptInAndMissingProfileFails() + { + Assert.Contains(InstrumentProfileValidator.Validate(new Data().Build()), e => e.Code == "unverified_profile"); + Assert.Equal("missing_profile", Assert.Single(InstrumentProfileValidator.Validate(null)).Code); + } + + [Theory] + [InlineData(MappingVerification.Verified, true)] + [InlineData(MappingVerification.Documented, true)] + [InlineData(MappingVerification.Unverified, false)] + [InlineData(MappingVerification.Synthetic, false)] + public void ProductionEvidenceStagesStayDistinct(MappingVerification status, bool admitted) + { + var data = new Data(); + var profile = (data with + { + Evidence = data.Evidence with { Status = status, Source = "https://example.org/mapping" }, + CompatibilityNotes = Notes + }).Build(); + Assert.Equal(admitted, InstrumentProfileValidator.Validate(profile).Count == 0); + Assert.Equal(status, profile.Evidence.Status); + Assert.Equal(0, (int)MappingVerification.Unverified); + Assert.Equal(1, (int)MappingVerification.Verified); + Assert.Equal(2, (int)MappingVerification.Synthetic); + } + + private static MappingCompatibilityNotes Notes => new("Test-only non-versioned source scope", + "Test default configuration", "Test explicit channel policy", "Test timing policy, not vendor minima"); + + [Fact] + public void DocumentedRequiresNotesWhileLegacyVerifiedDoesNotAcquireDefaults() + { + var data = new Data(); + Assert.Null(data.Build().CompatibilityNotes); + Assert.Empty(InstrumentProfileValidator.Validate((data with + { Evidence = data.Evidence with { Status = MappingVerification.Verified } }).Build())); + var profile = (data with { Evidence = data.Evidence with + { Status = MappingVerification.Documented, Source = "https://example.org/mapping" } }).Build(); + Assert.Equal("missing_compatibility_notes", Assert.Single(InstrumentProfileValidator.Validate(profile)).Code); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + [InlineData(" padded")] + [InlineData("line\nbreak")] + public void EveryCompatibilityDisclosureMustBeExplicitAndValid(string? value) + { + foreach (var notes in new[] { Notes with { VersionScope = value! }, + Notes with { ConfigurationRequirements = value! }, Notes with { RoutingPolicy = value! }, + Notes with { TimingPolicy = value! } }) + { + var data = new Data(); + var profile = (data with { CompatibilityNotes = notes, + Evidence = data.Evidence with { Status = MappingVerification.Documented, + Source = "https://example.org/mapping" } }).Build(); + Assert.Equal("invalid_compatibility_notes", Assert.Single(InstrumentProfileValidator.Validate(profile)).Code); + } + } + + [Theory] + [InlineData("uncited")] + [InlineData("file:///manual.pdf")] + [InlineData("https://user:secret@example.org/manual")] + public void DocumentedSourcesMustBePublicHttpUrls(string source) + { + var data = new Data(); + Assert.Contains(InstrumentProfileValidator.Validate((data with { CompatibilityNotes = Notes, + Evidence = data.Evidence with { Status = MappingVerification.Documented, Source = source } }).Build()), + e => e.Code == "invalid_documented_source"); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void UnknownArticulationIsValidWithExplicitInitialControllerState(bool cc) => + Assert.Empty(InstrumentProfileValidator.Validate((Switched(cc: cc) with { Initial = null }).Build(), true)); + + [Theory] + [InlineData(0, 1, 127)] + [InlineData(15, 1, 1)] + [InlineData(9, 127, 127)] + public void InclusiveMidiBoundariesAreValid(int channel, int min, int max) + { + var p = new Data { Channel = channel, MinimumPitch = 0, MaximumPitch = 127, + Rules = [Rule(min: min, max: max)] }.Build(); + Assert.Empty(InstrumentProfileValidator.Validate(p, true)); + } + + [Theory] + [InlineData(StateBehavior.Latched, false)] + [InlineData(StateBehavior.Latched, true)] + [InlineData(StateBehavior.Momentary, false)] + [InlineData(StateBehavior.Momentary, true)] + public void ExplicitControlSchemesAreValid(StateBehavior behavior, bool cc) => + Assert.Empty(InstrumentProfileValidator.Validate(Switched(behavior, advance: 0, duration: 1, cc: cc).Build(), true)); + + [Fact] + public void VelocityOnlyHasDisjointInclusiveLayers() => + Assert.Empty(InstrumentProfileValidator.Validate(new Data + { + Rules = [Rule(max: 63), Rule(Articulation.PalmMute, min: 64, output: 100)] + }.Build(), true)); + + [Fact] + public void ProfilesAndRulesSnapshotInputCollections() + { + var controllers = new[] { new ControllerValue(20, 0) }; + var rules = new[] { Rule(behavior: StateBehavior.Latched, cc: controllers) }; + var data = new Data { Rules = rules, InitialControllers = controllers }; + var profile = data.Build(); + controllers[0] = new(21, 127); + rules[0] = Rule(Articulation.PalmMute); + Assert.Equal(20, profile.InitialControllers[0].Number); + Assert.Equal(20, profile.Rules[0].Controllers[0].Number); + Assert.Equal(Articulation.Sustain, profile.Rules[0].Articulation); + Assert.Throws(() => ((IList)profile.Rules).Clear()); + Assert.Throws(() => ((IList)profile.InitialControllers).Clear()); + } +} diff --git a/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Articulations/SyntheticProfiles.cs b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Articulations/SyntheticProfiles.cs new file mode 100644 index 0000000..1ac4e7a --- /dev/null +++ b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Articulations/SyntheticProfiles.cs @@ -0,0 +1,58 @@ +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Articulations; +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition; +using MusicalComposition = GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition.Composition; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests.Articulations; + +internal static class SyntheticProfiles +{ + internal sealed record Data + { + public string Id { get; init; } = "synthetic-lead"; + public string InstrumentId { get; init; } = "synthetic-instrument"; + public TrackRole Role { get; init; } = TrackRole.Lead; + public string ProductName { get; init; } = "Synthetic Test Instrument"; + public string ProductVersion { get; init; } = "test-1"; + public string MappingVersion { get; init; } = "test-map-1"; + public MappingEvidence Evidence { get; init; } = new(MappingVerification.Synthetic, + "Test-authored invented values; not vendor evidence", "Test code only", "Synthetic assertions only"); + public MappingCompatibilityNotes? CompatibilityNotes { get; init; } + public int MinimumPitch { get; init; } = 40; + public int MaximumPitch { get; init; } = 100; + public int Channel { get; init; } + public Articulation? Initial { get; init; } = Articulation.Sustain; + public ControllerValue[] InitialControllers { get; init; } = []; + public Articulation? Reset { get; init; } + public ControllerValue[] FinalControllers { get; init; } = []; + public ArticulationRule[] Rules { get; init; } = [Rule(Articulation.Sustain)]; + public InstrumentProfile Build() => new(Id, InstrumentId, Role, ProductName, ProductVersion, MappingVersion, + Evidence, MinimumPitch, MaximumPitch, Channel, Initial, InitialControllers, Reset, FinalControllers, Rules, + CompatibilityNotes); + } + + internal static ArticulationRule Rule(Articulation articulation = Articulation.Sustain, + StateBehavior behavior = StateBehavior.None, KeyswitchAction? key = null, + ControllerValue[]? cc = null, int min = 1, int max = 127, int? output = null, + DrumVoice? voice = null, int? drumPitch = null) => + new(articulation, voice, drumPitch, behavior, key, new(min, max, output), cc ?? []); + + internal static Data Switched(StateBehavior behavior = StateBehavior.Latched, long advance = 120, + long duration = 30, bool cc = false) => new() + { + InitialControllers = cc ? [new(20, 0)] : [], + Rules = + [ + behavior == StateBehavior.Latched + ? Rule(behavior: behavior, key: new(10, 90, advance, duration), cc: cc ? [new(20, 0)] : []) + : Rule(), + Rule(Articulation.PalmMute, behavior, new(11, 91, advance, duration), cc ? [new(20, 100)] : []) + ] + }; + + internal static MusicalComposition Model(params MusicalNote[] notes) => + new(120, new(4, 4), new(4, KeyMode.Minor), 4, [new(TrackRole.Lead, notes)]); + + internal static MusicalNote Note(long start = 0, long duration = 1, int pitch = 64, + int velocity = 96, Articulation articulation = Articulation.Sustain) => + new(pitch, new(start), new(duration), velocity, articulation); +} diff --git a/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Composition/BeatFractionTests.cs b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Composition/BeatFractionTests.cs new file mode 100644 index 0000000..ea8c93f --- /dev/null +++ b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Composition/BeatFractionTests.cs @@ -0,0 +1,90 @@ +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests.Composition; + +public sealed class BeatFractionTests +{ + [Theory] + [InlineData(2, 4, 1, 2)] + [InlineData(-6, 9, -2, 3)] + [InlineData(0, 123, 0, 1)] + [InlineData(long.MinValue, 2, long.MinValue / 2, 1)] + public void Normalizes(long numerator, long denominator, long expectedNumerator, long expectedDenominator) + { + var fraction = new BeatFraction(numerator, denominator); + Assert.Equal(expectedNumerator, fraction.Numerator); + Assert.Equal(expectedDenominator, fraction.Denominator); + Assert.Equal(new BeatFraction(expectedNumerator, expectedDenominator).GetHashCode(), fraction.GetHashCode()); + } + + [Theory] + [InlineData(0)] + [InlineData(-1)] + [InlineData(long.MinValue)] + public void RejectsNonpositiveDenominator(long denominator) => + Assert.Throws(() => new BeatFraction(1, denominator)); + + [Fact] + public void DefaultIsNormalizedZero() + { + Assert.Equal(new BeatFraction(0), default(BeatFraction)); + Assert.Equal(1, default(BeatFraction).Denominator); + Assert.Equal(0, default(BeatFraction).ToTicks()); + } + + [Fact] + public void ArithmeticAndComparisonAreExact() + { + var half = new BeatFraction(1, 2); + var third = new BeatFraction(1, 3); + Assert.Equal(new BeatFraction(5, 6), half + third); + Assert.Equal(new BeatFraction(1, 6), half - third); + Assert.Equal(new BeatFraction(3, 2), half * 3); + Assert.Equal(new BeatFraction(1, 6), half / 3); + Assert.True(third < half); + Assert.True(half > third); + Assert.True(half <= new BeatFraction(2, 4)); + Assert.True(half >= new BeatFraction(2, 4)); + Assert.True(half != third); + Assert.True(half == new BeatFraction(2, 4)); + Assert.Equal(-1, third.CompareTo(half)); + Assert.Equal("1/2", half.ToString()); + Assert.False(half.Equals(null)); + } + + [Theory] + [InlineData(1, 2, 480)] + [InlineData(1, 3, 320)] + [InlineData(16, 1, 15360)] + [InlineData(1, 960, 1)] + public void ConvertsOnlyExactTicks(long numerator, long denominator, long ticks) => + Assert.Equal(ticks, new BeatFraction(numerator, denominator).ToTicks()); + + [Theory] + [InlineData(1, 7)] + [InlineData(1, 1920)] + public void RejectsFractionalTicks(long numerator, long denominator) => + Assert.Throws(() => new BeatFraction(numerator, denominator).ToTicks()); + + [Fact] + public void CheckedOperationsRejectOverflow() + { + Assert.Throws(() => new BeatFraction(long.MaxValue) + new BeatFraction(1)); + Assert.Throws(() => new BeatFraction(long.MinValue) - new BeatFraction(1)); + Assert.Throws(() => new BeatFraction(long.MaxValue) * 2); + Assert.Throws(() => new BeatFraction(1, long.MaxValue) / 2); + Assert.Throws(() => new BeatFraction(long.MaxValue).ToTicks()); + Assert.Throws(() => new BeatFraction(long.MinValue) * -1); + Assert.Throws(() => new BeatFraction(1) / 0); + Assert.Throws(() => new BeatFraction(1) / -1); + } + + [Fact] + public void WideIntermediatesDoNotRejectRepresentableNormalizedResults() + { + var large = new BeatFraction(long.MaxValue, 2); + Assert.Equal(new BeatFraction(long.MaxValue), large + large); + Assert.True(new BeatFraction(long.MaxValue, long.MaxValue - 1) > new BeatFraction(long.MaxValue - 1, long.MaxValue)); + Assert.Equal(new BeatFraction(1), new BeatFraction(1, long.MaxValue) * long.MaxValue); + } +} diff --git a/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Composition/CompositionPlannerTests.cs b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Composition/CompositionPlannerTests.cs new file mode 100644 index 0000000..b119475 --- /dev/null +++ b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Composition/CompositionPlannerTests.cs @@ -0,0 +1,242 @@ +using System.Text.Json; +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition; +using Model = GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition.Composition; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests.Composition; + +public sealed class CompositionPlannerTests +{ + [Fact] + public void AcceptanceExampleHasExactCountsPitchArticulationAndCompleteTiming() + { + var result = CompositionPlanner.Plan(DescriptionParserTests.Example); + Assert.True(result.Success, string.Join("; ", result.Diagnostics)); + Assert.Empty(result.Diagnostics); + var composition = result.Composition!; + Assert.Equal(new BeatFraction(16), composition.MusicalExtent); + Assert.Equal(15_360, composition.MusicalExtent.ToTicks()); + Assert.Equal(new[] { TrackRole.Lead, TrackRole.Bass, TrackRole.Drums }, composition.Tracks.Select(track => track.Role)); + var lead = composition.Tracks[0]; + Assert.Equal(32, lead.Notes.Count); + for (var i = 0; i < lead.Notes.Count; i++) + { + Assert.Equal(new MusicalNote(64, new(i, 2), new(1, 2), 96, Articulation.PalmMute), lead.Notes[i]); + Assert.Equal(i * 480, lead.Notes[i].Start.ToTicks()); + Assert.Equal(480, lead.Notes[i].Duration.ToTicks()); + } + var bass = composition.Tracks[1]; + Assert.Equal(4, bass.Notes.Count); + for (var i = 0; i < 4; i++) + { + Assert.Equal(new MusicalNote(40, new(i * 4), new(4), 96, Articulation.Sustain), bass.Notes[i]); + Assert.Equal(i * 3840, bass.Notes[i].Start.ToTicks()); + Assert.Equal(3840, bass.Notes[i].Duration.ToTicks()); + } + var hits = composition.Tracks[2].Hits; + Assert.Equal(48, hits.Count); + AssertDrum(hits, DrumVoice.Kick, 8, [0, 1920], 960); + AssertDrum(hits, DrumVoice.Snare, 8, [960, 2880], 960); + AssertDrum(hits, DrumVoice.ClosedHiHat, 32, [0, 480, 960, 1440, 1920, 2400, 2880, 3360], 480); + Assert.All(composition.Tracks, track => Assert.All(track.Notes, note => Assert.True(note.Start + note.Duration <= composition.MusicalExtent))); + Assert.All(hits, hit => Assert.True(hit.Start + hit.Duration <= composition.MusicalExtent)); + Assert.Empty(CompositionValidator.Validate(composition)); + } + + [Theory] + [InlineData("quarter notes", 4, 960)] + [InlineData("eighth notes", 8, 480)] + [InlineData("sixteenth notes", 16, 240)] + [InlineData("sustained root notes", 1, 3840)] + public void RepeatedPitchedPatternsNeverDrift(string pattern, int perBar, int duration) + { + var composition = CompositionPlanner.Plan($"257 bars: {pattern} bass").Composition!; + var notes = Assert.Single(composition.Tracks).Notes; + Assert.Equal(257 * perBar, notes.Count); + for (var i = 0; i < notes.Count; i++) + { + Assert.Equal((long)i * duration, notes[i].Start.ToTicks()); + Assert.Equal(duration, notes[i].Duration.ToTicks()); + } + Assert.Equal(257L * 3840, (notes[^1].Start + notes[^1].Duration).ToTicks()); + } + + [Theory] + [InlineData("quarter notes", 4, 960)] + [InlineData("eighth notes", 8, 480)] + [InlineData("sixteenth notes", 16, 240)] + public void HiHatSubdivisionsNeverDrift(string pattern, int perBar, int duration) + { + var composition = CompositionPlanner.Plan($"101 bars: closed hi-hat {pattern}").Composition!; + var hits = Assert.Single(composition.Tracks).Hits; + Assert.Equal(101 * perBar, hits.Count); + for (var i = 0; i < hits.Count; i++) + { + Assert.Equal((long)i * duration, hits[i].Start.ToTicks()); + Assert.Equal(duration, hits[i].Duration.ToTicks()); + } + } + + [Fact] + public void NonFourFourUsesDenominatorBeatsNotQuarterBeats() + { + var composition = CompositionPlanner.Plan("3/8, 2 bars: kick on beats 1 and 3, snare on beat 2, closed hi-hat eighth notes").Composition!; + Assert.Equal(new BeatFraction(3, 2), composition.Meter.BarLength); + Assert.Equal(2880, composition.MusicalExtent.ToTicks()); + var hits = Assert.Single(composition.Tracks).Hits; + Assert.Equal(new long[] { 0, 960, 1440, 2400 }, hits.Where(hit => hit.Voice == DrumVoice.Kick).Select(hit => hit.Start.ToTicks())); + Assert.Equal(new long[] { 480, 1920 }, hits.Where(hit => hit.Voice == DrumVoice.Snare).Select(hit => hit.Start.ToTicks())); + Assert.All(hits, hit => Assert.Equal(480, hit.Duration.ToTicks())); + } + + [Theory] + [InlineData("3/4, lead", 24, 11520)] + [InlineData("6/8, lead", 24, 11520)] + [InlineData("5/16, bass", 4, 4800)] + public void PitchedOnlyMetersDoNotRequireDrumDefaults(string text, int count, long extent) + { + var result = CompositionPlanner.Plan(text); + Assert.True(result.Success); + Assert.Equal(count, Assert.Single(result.Composition!.Tracks).Notes.Count); + Assert.Equal(extent, result.Composition.MusicalExtent.ToTicks()); + } + + [Fact] + public void ExplicitGlobalsAndIndependentRoleModifiersArePreserved() + { + var composition = CompositionPlanner.Plan("7 bars, 90 bpm, 3/4, in Db major: lead sustain quarter notes, bass palm mute sustained").Composition!; + Assert.Equal(90, composition.TempoBpm); + Assert.Equal(7, composition.Bars); + Assert.Equal(new TimeSignature(3, 4), composition.Meter); + Assert.Equal(new MusicalKey(1, KeyMode.Major), composition.Key); + Assert.All(composition.Tracks[0].Notes, note => + { + Assert.Equal(61, note.Pitch); + Assert.Equal(Articulation.Sustain, note.Articulation); + }); + Assert.All(composition.Tracks[1].Notes, note => + { + Assert.Equal(37, note.Pitch); + Assert.Equal(new BeatFraction(3), note.Duration); + Assert.Equal(Articulation.PalmMute, note.Articulation); + }); + Assert.Equal(4, composition.DefaultsApplied.Count); + } + + [Theory] + [InlineData("B# major", 60, 36)] + [InlineData("Cb minor", 71, 47)] + [InlineData("F♯ minor", 66, 42)] + public void RootOctavesFollowNormalizedPitchClass(string key, int lead, int bass) + { + var composition = CompositionPlanner.Plan($"{key}: lead and bass").Composition!; + Assert.All(composition.Tracks[0].Notes, note => Assert.Equal(lead, note.Pitch)); + Assert.All(composition.Tracks[1].Notes, note => Assert.Equal(bass, note.Pitch)); + } + + [Theory] + [InlineData("bass", TrackRole.Bass, 4)] + [InlineData("lead guitar", TrackRole.Lead, 32)] + [InlineData("kick on beat 1", TrackRole.Drums, 4)] + [InlineData("drums kick on beat 1", TrackRole.Drums, 4)] + public void SelectedRolesAndExplicitDrumSubsetsDoNotExpand(string text, TrackRole role, int events) + { + var track = Assert.Single(CompositionPlanner.Plan(text).Composition!.Tracks); + Assert.Equal(role, track.Role); + Assert.Equal(events, track.Notes.Count + track.Hits.Count); + if (role == TrackRole.Drums) Assert.All(track.Hits, hit => Assert.Equal(DrumVoice.Kick, hit.Voice)); + } + + [Theory] + [InlineData("3/8 quarter notes lead", "unrepresentable_pattern")] + [InlineData("1/256 eighth notes lead", "unrepresentable_pattern")] + [InlineData("5/16 closed hi-hat eighth notes", "unrepresentable_pattern")] + [InlineData("3/8 drums", "explicit_drums_required")] + [InlineData("4 bars lead with vibrato", "unsupported_text")] + [InlineData("3/8 kick on beat 4", "invalid_beat")] + [InlineData("2147483647 bars lead", "event_limit_exceeded")] + [InlineData("255/1 2147483647 bars sixteenth notes bass", "event_limit_exceeded")] + public void PlanningFailuresExposeNoPartialComposition(string text, string code) + { + var result = CompositionPlanner.Plan(text); + Assert.False(result.Success); + Assert.Null(result.Composition); + Assert.Contains(result.Diagnostics, error => error.Code == code && error.Message.Length > 0); + } + + [Theory] + [InlineData("100000 bars sustained lead")] + [InlineData("100000 bars kick on beat 1")] + [InlineData("12500 bars eighth notes lead")] + [InlineData("10000 bars sustained lead, sustained bass, closed hi-hat eighth notes")] + public void ExactCombinedEventLimitIsAccepted(string text) + { + var result = CompositionPlanner.Plan(text); + Assert.True(result.Success, string.Join("; ", result.Diagnostics)); + Assert.Equal(100_000, result.Composition!.Tracks.Sum(track => track.Notes.Count + track.Hits.Count)); + } + + [Theory] + [InlineData("100001 bars sustained lead")] + [InlineData("100001 bars kick on beat 1")] + [InlineData("9091 bars sustained lead, eighth notes bass, kick on beats 1 and 3")] + [InlineData("100000 bars sustained lead and bass")] + [InlineData("12501 bars eighth notes lead")] + public void LimitExceededIsSpecificAndNeverTruncated(string text) + { + var result = CompositionPlanner.Plan(text); + Assert.False(result.Success); + Assert.Null(result.Composition); + Assert.Equal("event_limit_exceeded", Assert.Single(result.Diagnostics).Code); + } + + [Fact] + public void ResultsAreDeterministicAndCollectionSnapshotsAreIndependent() + { + var first = CompositionPlanner.Plan(DescriptionParserTests.Example).Composition!; + var second = CompositionPlanner.Plan(DescriptionParserTests.Example).Composition!; + Assert.Equal(JsonSerializer.Serialize(first), JsonSerializer.Serialize(second)); + Assert.NotSame(first.Tracks, second.Tracks); + Assert.NotSame(first.DefaultsApplied, second.DefaultsApplied); + Assert.NotSame(first.Tracks[0].Notes, second.Tracks[0].Notes); + Assert.Throws(() => ((IList)first.Tracks).Clear()); + Assert.Throws(() => ((IList)first.Tracks[0].Notes).Clear()); + Assert.Throws(() => ((IList)first.Tracks[2].Hits).Clear()); + Assert.Throws(() => ((IList)first.DefaultsApplied).Clear()); + + var notes = new List { new(64, new(0), new(1), 96, Articulation.Sustain) }; + var track = new TrackPlan(TrackRole.Lead, notes); + notes.Clear(); + Assert.Single(track.Notes); + var tracks = new List { track }; + var defaults = new List { new("bars", "4") }; + var composition = new Model(120, new(4, 4), new(4, KeyMode.Minor), 4, tracks, defaults); + tracks.Clear(); + defaults.Clear(); + Assert.Single(composition.Tracks); + Assert.Single(composition.DefaultsApplied); + } + + [Fact] + public void ParsedPlanCanBeReusedWithoutSharedMutableState() + { + var parsed = DescriptionParser.Parse(DescriptionParserTests.Example).Description!; + var first = CompositionPlanner.Plan(parsed).Composition!; + var second = CompositionPlanner.Plan(parsed).Composition!; + Assert.Equal(JsonSerializer.Serialize(first), JsonSerializer.Serialize(second)); + Assert.NotSame(first.Tracks[2].Hits, second.Tracks[2].Hits); + Assert.Throws(() => ((IList)parsed.DrumPatterns[0].Beats).Clear()); + Assert.Throws(() => ((IList)parsed.PitchedPatterns).Clear()); + } + + private static void AssertDrum(IReadOnlyList hits, DrumVoice voice, int count, long[] startsInBar, long duration) + { + var selected = hits.Where(hit => hit.Voice == voice).ToArray(); + Assert.Equal(count, selected.Length); + for (var i = 0; i < count; i++) + { + Assert.Equal((i / startsInBar.Length) * 3840 + startsInBar[i % startsInBar.Length], selected[i].Start.ToTicks()); + Assert.Equal(duration, selected[i].Duration.ToTicks()); + Assert.Equal(96, selected[i].Velocity); + } + } +} diff --git a/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Composition/CompositionValidatorTests.cs b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Composition/CompositionValidatorTests.cs new file mode 100644 index 0000000..5715c72 --- /dev/null +++ b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Composition/CompositionValidatorTests.cs @@ -0,0 +1,166 @@ +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition; +using Model = GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition.Composition; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests.Composition; + +public sealed class CompositionValidatorTests +{ + private static MusicalNote Note(int pitch = 64, int velocity = 96, + BeatFraction? start = null, BeatFraction? duration = null, Articulation articulation = Articulation.Sustain) => + new(pitch, start ?? new(0), duration ?? new(1), velocity, articulation); + + private static Model ModelOf(IEnumerable? tracks = null, double tempo = 120, + int bars = 4, TimeSignature? meter = null, MusicalKey? key = null) => + new(tempo, meter ?? new(4, 4), key ?? new(4, KeyMode.Minor), bars, + tracks ?? [new TrackPlan(TrackRole.Lead, [Note()])]); + + [Fact] + public void AcceptsValidMusicalValuesWithoutAnyProductMapping() + { + Assert.Empty(CompositionValidator.Validate(ModelOf())); + Assert.Empty(CompositionValidator.Validate(ModelOf(tempo: 137, meter: new(3, 8)))); + Assert.Empty(CompositionValidator.Validate(ModelOf(meter: new(255, 256), tracks: + [new TrackPlan(TrackRole.Bass, [Note(pitch: 0, velocity: 1, duration: new(1, 64))])]))); + Assert.Empty(CompositionValidator.Validate(ModelOf(tracks: [new TrackPlan(TrackRole.Lead, + [Note(pitch: 127, velocity: 127, articulation: Articulation.PalmMute)])]))); + } + + [Theory] + [InlineData(0)] + [InlineData(-1)] + [InlineData(double.NaN)] + [InlineData(double.PositiveInfinity)] + [InlineData(double.NegativeInfinity)] + [InlineData(double.Epsilon)] + [InlineData(3)] + [InlineData(60000001)] + public void RejectsInvalidOrUnrepresentableTempo(double tempo) => + AssertCode(ModelOf(tempo: tempo), "invalid_tempo"); + + [Theory] + [InlineData(60000000)] + [InlineData(60000000d / 16777215d)] + [InlineData(137)] + public void AcceptsSmfTempoBoundariesAndQuantizableTempo(double tempo) => + Assert.Empty(CompositionValidator.Validate(ModelOf(tempo: tempo))); + + [Theory] + [InlineData(0)] + [InlineData(-1)] + [InlineData(int.MinValue)] + public void RejectsNonpositiveBars(int bars) => AssertCode(ModelOf(bars: bars), "invalid_bars"); + + [Theory] + [InlineData(0, 4, "invalid_meter")] + [InlineData(256, 4, "invalid_meter")] + [InlineData(4, 0, "invalid_meter")] + [InlineData(4, -4, "invalid_meter")] + [InlineData(4, 3, "invalid_meter")] + [InlineData(4, 512, "unrepresentable_timing")] + [InlineData(4, 1073741824, "unrepresentable_timing")] + public void ValidatesMeterFieldsAndDenominatorBeats(int numerator, int denominator, string code) => + AssertCode(ModelOf(meter: new(numerator, denominator)), code); + + [Theory] + [InlineData(-1)] + [InlineData(12)] + public void RejectsInvalidKey(int pitchClass) => + AssertCode(ModelOf(key: new(pitchClass, KeyMode.Minor)), "invalid_key"); + + [Fact] + public void RejectsUndefinedKeyMode() => AssertCode(ModelOf(key: new(4, (KeyMode)99)), "invalid_key"); + + [Theory] + [InlineData(-1)] + [InlineData(128)] + public void RejectsOutOfRangePitch(int pitch) => + AssertCode(ModelOf([new TrackPlan(TrackRole.Lead, [Note(pitch: pitch)])]), "invalid_pitch"); + + [Theory] + [InlineData(0)] + [InlineData(-1)] + [InlineData(128)] + public void RejectsOutOfRangeVelocityOnBothKinds(int velocity) + { + AssertCode(ModelOf([new TrackPlan(TrackRole.Lead, [Note(velocity: velocity)])]), "invalid_velocity"); + AssertCode(ModelOf([new TrackPlan(TrackRole.Drums, hits: [new(DrumVoice.Kick, new(0), new(1), velocity)])]), "invalid_velocity"); + } + + [Fact] + public void RejectsInvalidStartDurationAndExtent() + { + AssertCode(ModelOf([new TrackPlan(TrackRole.Lead, [Note(start: new(-1))])]), "invalid_start"); + AssertCode(ModelOf([new TrackPlan(TrackRole.Lead, [Note(duration: new(0))])]), "invalid_duration"); + AssertCode(ModelOf([new TrackPlan(TrackRole.Lead, [Note(duration: new(-1))])]), "invalid_duration"); + AssertCode(ModelOf([new TrackPlan(TrackRole.Lead, [Note(start: new(16))])]), "event_out_of_bounds"); + AssertCode(ModelOf([new TrackPlan(TrackRole.Lead, [Note(start: new(15), duration: new(2))])]), "event_out_of_bounds"); + AssertCode(ModelOf([new TrackPlan(TrackRole.Drums, hits: [new(DrumVoice.Snare, new(15), new(2), 96)])]), "event_out_of_bounds"); + Assert.Empty(CompositionValidator.Validate(ModelOf([new TrackPlan(TrackRole.Lead, [Note(start: new(15))])]))); + } + + [Fact] + public void RejectsUnrepresentableStartOrDuration() + { + AssertCode(ModelOf([new TrackPlan(TrackRole.Lead, [Note(start: new(1, 7))])]), "unrepresentable_timing"); + AssertCode(ModelOf([new TrackPlan(TrackRole.Lead, [Note(duration: new(1, 7))])]), "unrepresentable_timing"); + } + + [Fact] + public void RejectsOverflowInsteadOfWrapping() + { + AssertCode(ModelOf([new TrackPlan(TrackRole.Lead, [Note(start: new(long.MaxValue))])]), "arithmetic_overflow"); + AssertCode(ModelOf([new TrackPlan(TrackRole.Lead, [Note(duration: new(long.MaxValue))])]), "arithmetic_overflow"); + } + + [Fact] + public void RequiresDistinctSelectedNonemptyRolesAndCorrectEventKinds() + { + AssertCode(ModelOf([]), "invalid_roles"); + AssertCode(ModelOf([new TrackPlan(TrackRole.Lead)]), "empty_track"); + AssertCode(ModelOf([new TrackPlan((TrackRole)99, [Note()])]), "invalid_roles"); + AssertCode(ModelOf([new TrackPlan(TrackRole.Lead, [Note()]), new TrackPlan(TrackRole.Lead, [Note()])]), "invalid_roles"); + AssertCode(ModelOf([new TrackPlan(TrackRole.Drums, [Note()])]), "event_kind_mismatch"); + AssertCode(ModelOf([new TrackPlan(TrackRole.Bass, hits: [new(DrumVoice.Kick, new(0), new(1), 96)])]), "event_kind_mismatch"); + AssertCode(ModelOf([new TrackPlan(TrackRole.Lead, [Note(articulation: (Articulation)99)])]), "invalid_articulation"); + AssertCode(ModelOf([new TrackPlan(TrackRole.Drums, hits: [new((DrumVoice)99, new(0), new(1), 96)])]), "invalid_drum_voice"); + } + + [Fact] + public void NullModelsAndElementsHaveActionableDiagnostics() + { + Assert.Equal("invalid_composition", Assert.Single(CompositionValidator.Validate(null)).Code); + AssertCode(ModelOf([null!]), "invalid_track"); + AssertCode(ModelOf([new TrackPlan(TrackRole.Lead, [null!])]), "invalid_note"); + AssertCode(ModelOf([new TrackPlan(TrackRole.Drums, hits: [null!])]), "invalid_hit"); + } + + [Fact] + public void ManualModelsRespectExactCombinedEventLimit() + { + var notes = Enumerable.Repeat(Note(), 50_000).ToArray(); + var hits = Enumerable.Repeat(new DrumHit(DrumVoice.Kick, new(0), new(1), 96), 50_000).ToArray(); + var model = ModelOf([new TrackPlan(TrackRole.Lead, notes), new TrackPlan(TrackRole.Drums, hits: hits)]); + Assert.Empty(CompositionValidator.Validate(model)); + AssertCode(ModelOf([new TrackPlan(TrackRole.Lead, notes.Append(Note())), new TrackPlan(TrackRole.Drums, hits: hits)]), + "event_limit_exceeded"); + } + + [Fact] + public void DeclaredMusicalExtentPreservesTrailingRests() + { + var composition = ModelOf([new TrackPlan(TrackRole.Drums, hits: [new(DrumVoice.Kick, new(0), new(1), 96)])]); + Assert.Empty(CompositionValidator.Validate(composition)); + Assert.Equal(new BeatFraction(16), composition.MusicalExtent); + } + + private static void AssertCode(Model model, string code) + { + var errors = CompositionValidator.Validate(model); + Assert.Contains(errors, error => error.Code == code); + Assert.All(errors, error => + { + Assert.False(string.IsNullOrWhiteSpace(error.Field)); + Assert.False(string.IsNullOrWhiteSpace(error.Message)); + }); + } +} diff --git a/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Composition/DescriptionParserTests.cs b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Composition/DescriptionParserTests.cs new file mode 100644 index 0000000..44ec444 --- /dev/null +++ b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Composition/DescriptionParserTests.cs @@ -0,0 +1,215 @@ +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests.Composition; + +public sealed class DescriptionParserTests +{ + internal const string Example = "Generate 4 bars at 120 BPM in E minor, 4/4: palm-muted eighth-note lead guitar, sustained root-note bass, kick on beats 1 and 3, snare on beats 2 and 4, and closed hi-hat eighth notes."; + + [Fact] + public void AcceptanceExamplePreservesExplicitSettingsAndScopedIntentions() + { + var result = DescriptionParser.Parse(Example); + Assert.True(result.Success); + Assert.Empty(result.Diagnostics); + var description = Assert.IsType(result.Description); + Assert.Equal(120, description.TempoBpm); + Assert.Equal(4, description.Bars); + Assert.Equal(new TimeSignature(4, 4), description.Meter); + Assert.Equal(new MusicalKey(4, KeyMode.Minor), description.Key); + Assert.Equal(new PitchedPattern(TrackRole.Lead, NotePattern.Eighth, Articulation.PalmMute), description.PitchedPatterns[0]); + Assert.Equal(new PitchedPattern(TrackRole.Bass, NotePattern.Sustained, Articulation.Sustain), description.PitchedPatterns[1]); + Assert.Equal(3, description.DrumPatterns.Count); + Assert.Equal(new[] { 1, 3 }, description.DrumPatterns[0].Beats); + Assert.Equal(new[] { 2, 4 }, description.DrumPatterns[1].Beats); + Assert.Equal(NotePattern.Eighth, description.DrumPatterns[2].Subdivision); + Assert.Equal(new AppliedDefault[] + { + new("lead.rootOctave", "4"), new("lead.velocity", "96"), + new("bass.articulation", "sustain"), new("bass.rootOctave", "2"), + new("bass.velocity", "96"), new("drums.velocity", "96") + }, description.DefaultsApplied); + } + + [Theory] + [InlineData("generate four bars at 120 bpm in E minor, 4/4: palm mute eighth notes lead; sustained root notes bass; kick on beats 1 and 3; snare on beats 2 and 4; closed hi hat eighth notes")] + [InlineData(" GENERATE\tFOUR BARS\nAT 120 BPM IN E MINOR: 4/4; LEAD GUITAR PALM MUTED EIGHTH-NOTE, BASS SUSTAINED ROOT-NOTE, KICK ON BEATS 1 AND 3, SNARE ON BEATS 2 AND 4 AND CLOSED HI-HAT EIGHTH NOTES. ")] + public void DocumentedParaphrasesPreserveSettings(string text) + { + var result = DescriptionParser.Parse(text); + Assert.True(result.Success, string.Join("; ", result.Diagnostics)); + Assert.Equal(4, result.Description!.Bars); + Assert.Equal(120, result.Description.TempoBpm); + Assert.Equal(Articulation.PalmMute, result.Description.PitchedPatterns[0].Articulation); + Assert.Equal(Articulation.Sustain, result.Description.PitchedPatterns[1].Articulation); + } + + [Theory] + [InlineData("Db", 1, "C#")] + [InlineData("C#", 1, "C#")] + [InlineData("F♯", 6, "F#")] + [InlineData("G♭", 6, "F#")] + [InlineData("B#", 0, "C")] + [InlineData("Cb", 11, "B")] + [InlineData("E#", 5, "F")] + [InlineData("Fb", 4, "E")] + [InlineData("Bb", 10, "A#")] + public void NormalizesEnharmonics(string root, int pitchClass, string name) + { + var description = DescriptionParser.Parse($"in {root} major: bass").Description!; + Assert.Equal(new MusicalKey(pitchClass, KeyMode.Major), description.Key); + Assert.Equal(name, description.Key.RootName); + Assert.DoesNotContain(description.DefaultsApplied, value => value.Field == "key"); + } + + [Fact] + public void EveryOmittedDefaultHasAValue() + { + var description = DescriptionParser.Parse("120 BPM").Description!; + Assert.Equal(new AppliedDefault[] + { + new("bars", "4"), new("meter", "4/4"), new("key", "E minor"), + new("roles", "lead,bass,drums"), new("lead.pattern", "eighth notes"), + new("lead.articulation", "sustain"), new("lead.rootOctave", "4"), new("lead.velocity", "96"), + new("bass.pattern", "sustained"), new("bass.articulation", "sustain"), + new("bass.rootOctave", "2"), new("bass.velocity", "96"), new("drums.velocity", "96"), + new("drums.kick", "beats 1 and 3"), new("drums.snare", "beats 2 and 4"), + new("drums.closedHiHat", "eighth notes") + }, description.DefaultsApplied); + } + + [Theory] + [InlineData("lead", 1, 0)] + [InlineData("guitar", 1, 0)] + [InlineData("lead guitar and bass", 2, 0)] + [InlineData("bass", 1, 0)] + [InlineData("drums", 0, 3)] + [InlineData("kick on beat 1", 0, 1)] + [InlineData("drums, kick on beat 1", 0, 1)] + [InlineData("snare on beat 4, closed hi-hat sixteenth notes", 0, 2)] + [InlineData("bass and closed hi hat quarter notes", 1, 1)] + public void OnlyExplicitRolesAndPartsAreSelected(string text, int pitched, int drumParts) + { + var result = DescriptionParser.Parse(text); + Assert.True(result.Success); + Assert.Equal(pitched, result.Description!.PitchedPatterns.Count); + Assert.Equal(drumParts, result.Description.DrumPatterns.Count); + Assert.DoesNotContain(result.Description.DefaultsApplied, value => value.Field == "roles"); + if (text.Contains("kick on")) + Assert.DoesNotContain(result.Description.DefaultsApplied, value => value.Field is "drums.snare" or "drums.closedHiHat" or "drums.kick"); + } + + [Fact] + public void ExplicitPatternAndArticulationDoNotAppearAsDefaults() + { + var description = DescriptionParser.Parse("bass palm mute quarter notes").Description!; + Assert.Equal(new PitchedPattern(TrackRole.Bass, NotePattern.Quarter, Articulation.PalmMute), Assert.Single(description.PitchedPatterns)); + Assert.DoesNotContain(description.DefaultsApplied, value => value.Field is "bass.pattern" or "bass.articulation" || value.Field.StartsWith("lead.", StringComparison.Ordinal)); + } + + [Theory] + [InlineData("120 bpm 121 bpm", "conflicting_setting")] + [InlineData("4 bars, five bars", "conflicting_setting")] + [InlineData("E minor D major", "conflicting_setting")] + [InlineData("4/4 3/4", "conflicting_setting")] + [InlineData("lead quarter notes, eighth notes lead", "conflicting_clause")] + [InlineData("lead, palm mute lead", "conflicting_clause")] + [InlineData("kick on beat 1, kick on beat 2", "conflicting_clause")] + [InlineData("closed hi hat quarter notes, closed hi hat eighth notes", "conflicting_clause")] + [InlineData("kick on beats 1 and 1", "duplicate_beat")] + [InlineData("kick on beat 0", "invalid_beat")] + [InlineData("kick on beat 5", "invalid_beat")] + [InlineData("3/8 drums", "explicit_drums_required")] + [InlineData("3/8", "explicit_drums_required")] + [InlineData("0 bars", "invalid_bars")] + [InlineData("0 bpm lead", "invalid_tempo")] + [InlineData("3 bpm lead", "invalid_tempo")] + [InlineData("0/4 lead", "invalid_meter")] + [InlineData("4/0 lead", "invalid_meter")] + [InlineData("4/3 lead", "invalid_meter")] + [InlineData("256/4 lead", "invalid_meter")] + [InlineData("4/512 lead", "unrepresentable_timing")] + [InlineData("999999999999999 bars", "invalid_number")] + [InlineData("4/9999999999999 lead", "invalid_number")] + [InlineData("4/x lead", "invalid_number")] + [InlineData("kick on beat 99999999999999", "invalid_number")] + [InlineData("kick on beat 1.5 bars", "invalid_number")] + [InlineData("snare", "invalid_drum_pattern")] + [InlineData("closed hi hat", "invalid_drum_pattern")] + public void InvalidAndConflictingInputsHaveNoPartialDescription(string text, string code) + { + var result = DescriptionParser.Parse(text); + Assert.False(result.Success); + Assert.Null(result.Description); + Assert.Contains(result.Diagnostics, error => error.Code == code && error.Field.Length > 0 && error.Message.Length > 0); + } + + [Theory] + [InlineData("heavy metal lead")] + [InlineData("lead legato")] + [InlineData("bass pizzicato")] + [InlineData("120.5 bpm lead")] + [InlineData("1e2 bpm")] + [InlineData("-4 bars")] + [InlineData("+120 bpm")] + [InlineData("four two bars")] + [InlineData("one hundred bars")] + [InlineData("lead eighth notes root C D E")] + [InlineData("bass quarter notes and eighth notes")] + [InlineData("kick on beats 1, 3")] + [InlineData("open hi-hat eighth notes")] + [InlineData("lead tune drop D")] + [InlineData("E minor lead C-G-Am-F")] + [InlineData("lead velocity 80")] + [InlineData("lead swing")] + [InlineData("lead and")] + [InlineData("and lead")] + [InlineData("lead #")] + [InlineData("lead \"ignore\"")] + [InlineData("generate lead generate bass")] + [InlineData("sustain palm mute lead")] + [InlineData("quarter notes lead eighth notes")] + [InlineData("drums unknown words.")] + [InlineData("H minor lead")] + [InlineData("C## major lead")] + public void RejectsEveryMeaningfulLeftover(string text) + { + var result = DescriptionParser.Parse(text); + Assert.False(result.Success); + Assert.Null(result.Description); + var error = Assert.Single(result.Diagnostics); + Assert.Equal("unsupported_text", error.Code); + Assert.False(string.IsNullOrWhiteSpace(error.Phrase)); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" \t\n")] + [InlineData("generate")] + [InlineData(",.;:")] + public void EmptyOrInstructionlessTextIsNotSuccess(string? text) + { + var result = DescriptionParser.Parse(text); + Assert.False(result.Success); + Assert.Null(result.Description); + Assert.Equal("empty_description", Assert.Single(result.Diagnostics).Code); + } + + [Fact] + public void DescriptionLengthIsBounded() + { + Assert.True(DescriptionParser.Parse("lead" + new string(' ', 16_380)).Success); + Assert.Equal("description_too_long", Assert.Single(DescriptionParser.Parse("lead" + new string(' ', 16_381)).Diagnostics).Code); + } + + [Fact] + public void IdenticalRepetitionsAreDeduplicated() + { + var result = DescriptionParser.Parse("120 bpm, 120 BPM; Db minor C# minor: lead lead, kick on beats 1 and 3, kick on beats 3 and 1"); + Assert.True(result.Success); + Assert.Single(result.Description!.PitchedPatterns); + Assert.Single(result.Description.DrumPatterns); + Assert.Equal(new[] { 1, 3 }, result.Description.DrumPatterns[0].Beats); + } +} diff --git a/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests.csproj b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests.csproj new file mode 100644 index 0000000..0e9a34a --- /dev/null +++ b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests.csproj @@ -0,0 +1,28 @@ + + + + net10.0 + false + true + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Generation/GenerationServiceTests.cs b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Generation/GenerationServiceTests.cs new file mode 100644 index 0000000..c3af85a --- /dev/null +++ b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Generation/GenerationServiceTests.cs @@ -0,0 +1,409 @@ +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Articulations; +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition; +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Generation; +using GAJ3T.MusicGen.RiffGrooveBuilder.Generation; +using GAJ3T.MusicGen.RiffGrooveBuilder.Generation.Profiles; +using Melanchall.DryWetMidi.Core; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests.Generation; + +public sealed class GenerationServiceTests : IDisposable +{ + public const string Aglp = "ample-aglp-documented-defaults-2026-10-20"; + public const string Ame = "ample-ame-documented-defaults-2026-10-20"; + public const string Agm = "ample-agm-documented-defaults-2026-10-20"; + public const string Agt = "ample-agt-documented-defaults-2026-10-20"; + public const string Abj = "ample-abj-documented-defaults-2026-10-20"; + private readonly string directory = Path.Combine(AppContext.BaseDirectory, "generation-" + Guid.NewGuid().ToString("N")); + private readonly GenerationService service = new(); + + private GenerateProjectRequest Request() => new("palm-muted eighth-note lead", directory, "song", + [OutputFormat.Mid], new(Aglp)); + + [Theory] + [InlineData(null, 7, 5)] + [InlineData(TrackRole.Lead, 4, 4)] + [InlineData(TrackRole.Bass, 2, 1)] + [InlineData(TrackRole.Drums, 1, 0)] + public void DiscoveryIncludesUnmappedIdentitiesAndHonestCapabilities(TrackRole? role, int instruments, int profiles) + { + var result = service.ListInstrumentProfiles(new(role)); + Assert.Equal(instruments, result.Instruments.Count); + Assert.Equal(profiles, result.Profiles.Count); + if (role is null) + { + Assert.Equal(new[] { "ample-abj", "ample-aglp", "ample-agm", "ample-agt", "ample-ame", "ample-amr", "toontrack-sd3" }, + result.Instruments.Select(i => i.Id)); + Assert.Equal(new[] { Abj, Aglp, Agm, Agt, Ame }, result.Profiles.Select(p => p.Id)); + } + Assert.All(result.Instruments, i => + { + Assert.True(Uri.IsWellFormedUriString(i.DocumentationUrl, UriKind.Absolute)); + Assert.Equal(result.Profiles.Any(p => p.InstrumentId == i.Id) ? MappingAvailability.ProfileAvailable : MappingAvailability.MappingUnavailable, i.Availability); + if (role is not null) Assert.Equal(role, i.Role); + }); + Assert.All(result.Profiles, p => + { + Assert.Equal(MappingVerification.Documented, p.Evidence.Status); + Assert.NotEmpty(p.Evidence.Source); + Assert.NotEmpty(p.Evidence.VerificationRecord); + Assert.NotNull(p.CompatibilityNotes); + Assert.Contains("not", p.CompatibilityNotes.VersionScope, StringComparison.OrdinalIgnoreCase); + Assert.Equal(NativeStatus.Unverified, p.NativeStatus); + Assert.Equal(new[] { OutputFormat.Agp }, p.NativeFormats); + Assert.Equal(p.Role == TrackRole.Bass ? 1 : 0, p.Channel); + Assert.Equal(p.Role == TrackRole.Bass ? new[] { Articulation.Sustain } : + [Articulation.Sustain, Articulation.PalmMute], p.Articulations.Select(a => a.Articulation)); + Assert.All(p.Articulations, a => + { + Assert.Equal(new[] { ArticulationMechanism.Keyswitch, ArticulationMechanism.Velocity }, a.Mechanisms); + Assert.NotNull(a.Keyswitch); + Assert.Equal(120, a.Keyswitch.AdvanceTicks); + Assert.Equal(30, a.Keyswitch.DurationTicks); + }); + }); + Assert.Equal(WriterStatus.Implemented, Assert.Single(result.Formats, f => f.Format == OutputFormat.Mid).WriterStatus); + Assert.All(result.Formats.Where(f => f.Format != OutputFormat.Mid), f => Assert.Equal(WriterStatus.Unavailable, f.WriterStatus)); + Assert.All(result.Formats, f => Assert.Equal(NativeStatus.Unverified, f.ApplicationStatus)); + } + + [Theory] + [InlineData(Aglp, false)] + [InlineData(Aglp, true)] + [InlineData(Ame, false)] + [InlineData(Ame, true)] + [InlineData(Agm, false)] + [InlineData(Agm, true)] + [InlineData(Agt, false)] + [InlineData(Agt, true)] + public async Task ExplicitDocumentedMidiOnlySucceedsRegardlessOfFallbackFlag(string id, bool fallback) + { + var result = await service.GenerateAsync(Request() with { Profiles = new(id), FallbackToMidi = fallback }); + Assert.Equal(GenerationStatus.Complete, result.Status); + Assert.Empty(result.Errors); + var artifact = Assert.Single(result.Artifacts); + Assert.Equal(OutputFormat.Mid, artifact.Format); + Assert.Equal(new[] { TrackRole.Lead }, artifact.Roles); + Assert.Equal(new[] { id }, artifact.ProfileIds); + Assert.Equal(Path.Combine(directory, "song.mid"), artifact.AbsolutePath); + Assert.Equal(new FileInfo(artifact.AbsolutePath).Length, artifact.ByteCount); + Assert.True(artifact.ByteCount > 0); + var target = Assert.Single(result.Targets); + Assert.Equal(id[..id.IndexOf("-documented", StringComparison.Ordinal)], target.InstrumentId); + Assert.Equal(id, target.ProfileId); + Assert.Equal(TargetOutcome.Written, target.Outcome); + Assert.Null(target.ReasonCode); + var warning = Assert.Single(result.Warnings); + Assert.Equal("documented_profile", warning.Code); + Assert.Contains("NOT installed/application-verified", warning.Message); + var notes = InstrumentProfileCatalog.LoadEmbedded().Select(TrackRole.Lead, id).Profile!.CompatibilityNotes!; + Assert.Contains(notes.VersionScope, warning.Message); + Assert.Contains(notes.ConfigurationRequirements, warning.Message); + Assert.Contains(notes.RoutingPolicy, warning.Message); + Assert.Contains(notes.TimingPolicy, warning.Message); + Assert.Equal(120, result.Timing!.LeadInTicks); + Assert.Equal(960, result.Timing.TicksPerQuarterNote); + Assert.Equal(4, result.InterpretedComposition!.Bars); + Assert.NotEmpty(result.InterpretedComposition.DefaultsApplied); + Assert.Equal(MidiFileFormat.MultiTrack, MidiFile.Read(artifact.AbsolutePath).OriginalFormat); + Assert.Equal(new[] { artifact.AbsolutePath }, Directory.GetFiles(directory)); + } + + [Fact] + public async Task ExplicitAbjSustainOnlyProducesBassOnItsDisclosedChannel() + { + var result = await service.GenerateAsync(Request() with { Description = "sustained bass", + Profiles = new(Bass: Abj), FallbackToMidi = false }); + Assert.Equal(GenerationStatus.Complete, result.Status); + var artifact = Assert.Single(result.Artifacts); + Assert.Equal(new[] { TrackRole.Bass }, artifact.Roles); + Assert.Equal(new[] { Abj }, artifact.ProfileIds); + var track = MidiFile.Read(artifact.AbsolutePath).Chunks.Cast().Last(); + Assert.Equal("Bass", Assert.Single(track.Events.OfType()).Text); + Assert.All(track.Events.OfType(), e => Assert.Equal(1, (int)e.Channel)); + Assert.Equal(new[] { 24, 40, 40, 40, 40 }, track.Events.OfType().Select(e => (int)e.NoteNumber)); + Assert.Contains("PalmMute are rejected", Assert.Single(result.Warnings).Message); + } + + [Theory] + [InlineData("palm-muted bass")] + [InlineData("palm-muted lead and palm-muted bass")] + public async Task UnsupportedAbjPalmMuteFailsWholeArrangementWithoutDirectoryOrSubstitution(string text) + { + var result = await service.GenerateAsync(Request() with { Description = text, + Profiles = new(text.Contains("lead", StringComparison.Ordinal) ? Ame : null, Abj) }); + AssertFailure(result, "unsupported_articulation"); + Assert.All(result.Targets, t => Assert.Equal(TargetOutcome.Failed, t.Outcome)); + Assert.False(Directory.Exists(directory)); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + [InlineData(null)] + public async Task NativeOnlyNativePlusMidiAndOmittedFormatsReuseOneRealMidi(bool? includeMidi) + { + var formats = includeMidi is null ? null : includeMidi.Value + ? new[] { OutputFormat.Agp, OutputFormat.Mid } : new[] { OutputFormat.Agp }; + var result = await service.GenerateAsync(Request() with { Formats = formats }); + Assert.Equal(GenerationStatus.Fallback, result.Status); + Assert.Empty(result.Errors); + var artifact = Assert.Single(result.Artifacts); + Assert.Equal(OutputFormat.Mid, artifact.Format); + Assert.Single(Directory.GetFiles(directory)); + Assert.Equal(includeMidi == false ? 1 : 2, result.Targets.Count); + var native = Assert.Single(result.Targets, t => t.RequestedFormat == OutputFormat.Agp); + Assert.Equal(TargetOutcome.Fallback, native.Outcome); + Assert.Equal("native_writer_unavailable", native.ReasonCode); + Assert.All(result.Targets, t => Assert.Equal(new[] { artifact.AbsolutePath }, t.ArtifactPaths)); + Assert.Contains(result.Warnings, w => w.Code == "native_writer_unavailable" && w.RequestedFormat == OutputFormat.Agp); + Assert.Contains(result.Warnings, w => w.Code == "documented_profile"); + Assert.DoesNotContain(result.Targets, t => t.RequestedFormat == OutputFormat.Sdp); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + [InlineData(null)] + public async Task DisabledNativeFallbackFailsBeforeDirectoryCreation(bool? explicitMidi) + { + var result = await service.GenerateAsync(Request() with + { + Formats = explicitMidi is null ? null : explicitMidi.Value ? [OutputFormat.Agp, OutputFormat.Mid] : [OutputFormat.Agp], + FallbackToMidi = false + }); + AssertFailure(result, "native_fallback_disabled"); + Assert.Contains(result.Targets, t => t.RequestedFormat == OutputFormat.Agp && t.ReasonCode == "native_writer_unavailable"); + Assert.False(Directory.Exists(directory)); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("unknown")] + [InlineData("ample-agm")] + [InlineData("ample-aglp")] + public async Task MissingOrUnknownProfileNeverSelectsFirstInstrument(string? id) + { + var result = await service.GenerateAsync(Request() with { Profiles = id is null ? null : new(id) }); + Assert.Equal(GenerationStatus.Failed, result.Status); + Assert.Contains(result.Errors, e => e.Message.Contains(Aglp, StringComparison.Ordinal) && e.Message.Contains(Ame, StringComparison.Ordinal)); + Assert.Empty(result.Artifacts); + Assert.False(Directory.Exists(directory)); + } + + [Theory] + [InlineData("bass", false, "no_default_profile")] + [InlineData("drums", false, "mapping_unavailable")] + [InlineData("lead and bass", true, "no_default_profile")] + [InlineData("lead and drums", true, "mapping_unavailable")] + [InlineData("120 bpm", true, "mapping_unavailable")] + public async Task MissingSelectedRoleMappingFailsWholeArrangement(string text, bool leadProfile, string code) + { + var result = await service.GenerateAsync(Request() with { Description = text, Profiles = leadProfile ? new(Aglp) : null }); + AssertFailure(result, code); + Assert.NotNull(result.InterpretedComposition); + Assert.Contains(result.Targets, t => t.Role != TrackRole.Lead && t.ProfileId is null && t.InstrumentId is null); + Assert.False(Directory.Exists(directory)); + } + + [Theory] + [InlineData("bass", false)] + [InlineData("drums", false)] + [InlineData("lead", true)] + public async Task WrongRoleAndUnselectedProfilesFail(string text, bool extra) + { + var request = Request() with { Description = text, Profiles = extra ? new(Aglp, Aglp) : text == "bass" ? new(Bass: Aglp) : new(Drums: Aglp) }; + var result = await service.GenerateAsync(request); + AssertFailure(result, extra ? "unselected_role_profile" : "profile_role_mismatch"); + Assert.False(Directory.Exists(directory)); + } + + [Theory] + [InlineData("lead", OutputFormat.Sdp)] + [InlineData("bass", OutputFormat.Sdp)] + [InlineData("drums", OutputFormat.Agp)] + public async Task InapplicableNativeFormatIsAnErrorNotFallback(string text, OutputFormat format) + { + var result = await service.GenerateAsync(Request() with { Description = text, Formats = [format], Profiles = text == "lead" ? new(Aglp) : null }); + AssertFailure(result, "inapplicable_format"); + Assert.False(Directory.Exists(directory)); + } + + [Theory] + [InlineData("")] + [InlineData("funky music please")] + [InlineData("0 bars lead")] + [InlineData("999999999999999999 bars lead")] + [InlineData("20000 bars sixteenth-note lead")] + public async Task InvalidDescriptionAndPlannerLimitsProduceNoPartialOutput(string text) + { + var result = await service.GenerateAsync(Request() with { Description = text }); + Assert.Equal(GenerationStatus.Failed, result.Status); + Assert.Null(result.InterpretedComposition); + Assert.Null(result.Timing); + Assert.NotEmpty(result.Errors); + Assert.Empty(result.Artifacts); + Assert.False(Directory.Exists(directory)); + } + + [Theory] + [InlineData("../escape")] + [InlineData("..\\escape")] + [InlineData("CON")] + [InlineData("con.name")] + [InlineData("CON .name")] + [InlineData("COM¹")] + [InlineData("LPT²")] + [InlineData("LPT9")] + [InlineData("NUL")] + [InlineData("a:stream")] + [InlineData("bad?")] + [InlineData("song.")] + [InlineData("song ")] + [InlineData("")] + [InlineData("..")] + public async Task UnsafeNamesAreRejected(string name) + { + AssertFailure(await service.GenerateAsync(Request() with { ProjectName = name }), "invalid_output_path"); + Assert.False(Directory.Exists(directory)); + } + + [Theory] + [InlineData("")] + [InlineData("relative")] + [InlineData("..\\relative")] + [InlineData(@"\\?\C:\device")] + [InlineData(@"\\.\NUL")] + public async Task InvalidDirectoryIsRejected(string path) + { + AssertFailure(await service.GenerateAsync(Request() with { OutputDirectory = path }), "invalid_output_path"); + Assert.False(Directory.Exists(directory)); + } + + [Fact] + public async Task AbsoluteTraversalIsRejected() + { + AssertFailure(await service.GenerateAsync(Request() with { OutputDirectory = Path.Combine(directory, "..", "escape") }), "invalid_output_path"); + AssertFailure(await service.GenerateAsync(Request() with { OutputDirectory = directory + "/../escape" }), "invalid_output_path"); + AssertFailure(await service.GenerateAsync(Request() with { OutputDirectory = directory + "\\CON\\child" }), "invalid_output_path"); + Assert.False(Directory.Exists(directory)); + } + + [Theory] + [InlineData(0)] + [InlineData(1)] + [InlineData(2)] + public async Task InvalidFormatsFailEarly(int variant) + { + OutputFormat[] formats = variant switch { 0 => [], 1 => [OutputFormat.Mid, OutputFormat.Mid], _ => [(OutputFormat)99] }; + AssertFailure(await service.GenerateAsync(Request() with { Formats = formats }), "invalid_formats"); + Assert.False(Directory.Exists(directory)); + } + + [Theory] + [InlineData("sustained lead 1/256")] + [InlineData("1000 bars sustained lead 255/1")] + public async Task MidiLibraryAndStandardLimitsAreFailuresNotFallback(string text) + { + var result = await service.GenerateAsync(Request() with { Description = text, Formats = [OutputFormat.Agp] }); + AssertFailure(result, "midi_not_supported"); + Assert.False(Directory.Exists(directory)); + } + + [Fact] + public async Task ExistingFileAndUnrelatedStageArePreserved() + { + Directory.CreateDirectory(directory); + var path = Path.Combine(directory, "song.mid"); + var stage = Path.Combine(directory, ".unrelated.stage"); + File.WriteAllText(path, "other owner"); + File.WriteAllText(stage, "keep"); + AssertFailure(await service.GenerateAsync(Request()), "output_exists"); + Assert.Equal("other owner", File.ReadAllText(path)); + Assert.Equal("keep", File.ReadAllText(stage)); + Assert.Equal(2, Directory.GetFiles(directory).Length); + } + + [Fact] + public async Task DirectoryCollisionAndRacingFileCannotBeOverwritten() + { + Directory.CreateDirectory(directory); + var path = Path.Combine(directory, "song.mid"); + var racing = new GenerationService(InstrumentProfileCatalog.LoadEmbedded(), _ => File.WriteAllText(path, "racer")); + AssertFailure(await racing.GenerateAsync(Request()), "output_io_error"); + Assert.Equal("racer", File.ReadAllText(path)); + File.Delete(path); + Directory.CreateDirectory(path); + AssertFailure(await service.GenerateAsync(Request()), "output_exists"); + Assert.Empty(Directory.GetFiles(directory, "*", SearchOption.AllDirectories)); + } + + [Fact] + public async Task ConcurrentRequestsPublishAtMostOneWholeMidi() + { + var results = await Task.WhenAll(service.GenerateAsync(Request()), service.GenerateAsync(Request())); + Assert.Single(results, r => r.Status == GenerationStatus.Complete); + Assert.Single(results, r => r.Status == GenerationStatus.Failed); + Assert.Single(Directory.GetFiles(directory)); + Assert.Equal(MidiFileFormat.MultiTrack, MidiFile.Read(Path.Combine(directory, "song.mid")).OriginalFormat); + } + + [Fact] + public async Task IoFailureNeverBecomesSuccessfulFallback() + { + Directory.CreateDirectory(directory); + var file = Path.Combine(directory, "not-directory"); + File.WriteAllText(file, "keep"); + AssertFailure(await service.GenerateAsync(Request() with { OutputDirectory = file, Formats = [OutputFormat.Agp] }), "output_io_error"); + Assert.Equal("keep", File.ReadAllText(file)); + Assert.Single(Directory.GetFiles(directory)); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task ExpectedIoAndAccessErrorsHaveActionableResults(bool accessDenied) + { + var failing = new GenerationService(InstrumentProfileCatalog.LoadEmbedded(), _ => + { + if (accessDenied) throw new UnauthorizedAccessException("test access denied"); + throw new IOException("test I/O failure"); + }); + var result = await failing.GenerateAsync(Request() with { Formats = [OutputFormat.Agp, OutputFormat.Mid] }); + AssertFailure(result, "output_io_error"); + Assert.Equal(2, result.Targets.Count); + Assert.False(Directory.Exists(directory)); + } + + [Fact] + public async Task CancellationBeforeWorkAndBeforeOutputPropagates() + { + await Assert.ThrowsAnyAsync(() => service.GenerateAsync(Request(), new(true))); + using var cancellation = new CancellationTokenSource(); + var cancellable = new GenerationService(InstrumentProfileCatalog.LoadEmbedded(), _ => cancellation.Cancel()); + await Assert.ThrowsAnyAsync(() => cancellable.GenerateAsync(Request(), cancellation.Token)); + Assert.False(Directory.Exists(directory)); + } + + [Fact] + public async Task UnexpectedFailurePropagatesRatherThanMasqueradingAsFallback() + { + var broken = new GenerationService(InstrumentProfileCatalog.LoadEmbedded(), _ => throw new InvalidOperationException("unexpected-test-failure")); + await Assert.ThrowsAsync(() => broken.GenerateAsync(Request() with { Formats = [OutputFormat.Agp] })); + Assert.False(Directory.Exists(directory)); + } + + private static void AssertFailure(GenerationResult result, string code) + { + Assert.Equal(GenerationStatus.Failed, result.Status); + Assert.Contains(result.Errors, e => e.Code == code); + Assert.Empty(result.Artifacts); + Assert.All(result.Targets, t => { Assert.Equal(TargetOutcome.Failed, t.Outcome); Assert.Empty(t.ArtifactPaths); Assert.NotNull(t.ReasonCode); }); + } + + public void Dispose() + { + if (Directory.Exists(directory)) Directory.Delete(directory, recursive: true); + } +} diff --git a/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Instruments/CatalogFixtures.cs b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Instruments/CatalogFixtures.cs new file mode 100644 index 0000000..7566084 --- /dev/null +++ b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Instruments/CatalogFixtures.cs @@ -0,0 +1,29 @@ +using System.Text; +using GAJ3T.MusicGen.RiffGrooveBuilder.Generation.Instruments; +using GAJ3T.MusicGen.RiffGrooveBuilder.Generation.Profiles; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests.Instruments; + +internal static class CatalogFixtures +{ + internal static string Read(string name) + { + using var stream = typeof(CatalogFixtures).Assembly.GetManifestResourceStream( + "GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests.Instruments.Fixtures." + name) + ?? throw new InvalidDataException("Missing test-only fixture."); + using var reader = new StreamReader(stream); + return reader.ReadToEnd(); + } + + internal static InstrumentCatalog Instruments(string? json = null) + { + using var stream = new MemoryStream(Encoding.UTF8.GetBytes(json ?? Read("instruments.json"))); + return InstrumentCatalog.Load(stream); + } + + internal static InstrumentProfileCatalog Profiles(string? json = null, InstrumentCatalog? instruments = null) + { + using var stream = new MemoryStream(Encoding.UTF8.GetBytes(json ?? Read("profiles.json"))); + return InstrumentProfileCatalog.Load(stream, instruments ?? Instruments()); + } +} diff --git a/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Instruments/Fixtures/instruments.json b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Instruments/Fixtures/instruments.json new file mode 100644 index 0000000..178cbe2 --- /dev/null +++ b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Instruments/Fixtures/instruments.json @@ -0,0 +1,22 @@ +[ + { + "id": "synthetic-unmapped", "vendor": "Fixture Vendor", "productCode": "UNMAPPED", + "displayName": "Synthetic Unmapped", "role": "Lead", + "documentationUrl": "https://example.invalid/unmapped" + }, + { + "id": "synthetic-other", "vendor": "Other Fixture Vendor", "productCode": "OTHER", + "displayName": "Synthetic Other", "role": "Lead", + "documentationUrl": "https://example.invalid/other" + }, + { + "id": "synthetic-extra", "vendor": "Fixture Vendor", "productCode": "EXTRA", + "displayName": "Synthetic Extra", "role": "Lead", + "documentationUrl": "https://example.invalid/extra" + }, + { + "id": "synthetic-bass", "vendor": "Fixture Vendor", "productCode": "BASS", + "displayName": "Synthetic Bass", "role": "Bass", + "documentationUrl": "https://example.invalid/bass" + } +] diff --git a/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Instruments/Fixtures/profiles.json b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Instruments/Fixtures/profiles.json new file mode 100644 index 0000000..0fc79ce --- /dev/null +++ b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Instruments/Fixtures/profiles.json @@ -0,0 +1,70 @@ +[ + { + "id": "synthetic-extra-v2", "instrumentId": "synthetic-extra", "role": "Lead", + "productName": "Synthetic Extra", "productVersion": "test-2", "mappingVersion": "test-map-2", + "evidence": { + "status": "Verified", "source": "TEST ONLY: invented catalog admission fixture, not vendor evidence", + "authorization": "Test-authored data only", + "verificationRecord": "Catalog and planner assertions only; NOT application verification" + }, + "minimumPitch": 40, "maximumPitch": 100, "channel": 0, + "initialArticulation": "Sustain", "initialControllers": [], + "finalResetArticulation": null, "finalControllers": [], + "rules": [{ + "articulation": "Sustain", "voice": null, "drumPitch": null, "behavior": "None", + "keyswitch": null, "velocity": { "minimum": 1, "maximum": 127, "outputVelocity": 110 }, + "controllers": [] + }] + }, + { + "id": "synthetic-other-v1", "instrumentId": "synthetic-other", "role": "Lead", + "productName": "Synthetic Other", "productVersion": "test-1", "mappingVersion": "test-map-1", + "evidence": { + "status": "Verified", "source": "TEST ONLY: invented catalog admission fixture, not vendor evidence", + "authorization": "Test-authored data only", + "verificationRecord": "Catalog and planner assertions only; NOT application verification" + }, + "minimumPitch": 40, "maximumPitch": 100, "channel": 0, + "initialArticulation": "Sustain", "initialControllers": [], + "finalResetArticulation": null, "finalControllers": [], + "rules": [{ + "articulation": "Sustain", "voice": null, "drumPitch": null, "behavior": "None", + "keyswitch": null, "velocity": { "minimum": 1, "maximum": 127, "outputVelocity": null }, + "controllers": [] + }] + }, + { + "id": "synthetic-extra-v1", "instrumentId": "synthetic-extra", "role": "Lead", + "productName": "Synthetic Extra", "productVersion": "test-1", "mappingVersion": "test-map-1", + "evidence": { + "status": "Verified", "source": "TEST ONLY: invented catalog admission fixture, not vendor evidence", + "authorization": "Test-authored data only", + "verificationRecord": "Catalog and planner assertions only; NOT application verification" + }, + "minimumPitch": 40, "maximumPitch": 100, "channel": 0, + "initialArticulation": "Sustain", "initialControllers": [], + "finalResetArticulation": null, "finalControllers": [], + "rules": [{ + "articulation": "Sustain", "voice": null, "drumPitch": null, "behavior": "None", + "keyswitch": null, "velocity": { "minimum": 1, "maximum": 127, "outputVelocity": null }, + "controllers": [] + }] + }, + { + "id": "synthetic-bass-v1", "instrumentId": "synthetic-bass", "role": "Bass", + "productName": "Synthetic Bass", "productVersion": "test-1", "mappingVersion": "test-map-1", + "evidence": { + "status": "Verified", "source": "TEST ONLY: invented catalog admission fixture, not vendor evidence", + "authorization": "Test-authored data only", + "verificationRecord": "Catalog and planner assertions only; NOT application verification" + }, + "minimumPitch": 20, "maximumPitch": 80, "channel": 1, + "initialArticulation": "Sustain", "initialControllers": [], + "finalResetArticulation": null, "finalControllers": [], + "rules": [{ + "articulation": "Sustain", "voice": null, "drumPitch": null, "behavior": "None", + "keyswitch": null, "velocity": { "minimum": 1, "maximum": 127, "outputVelocity": null }, + "controllers": [] + }] + } +] diff --git a/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Instruments/InstrumentCatalogTests.cs b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Instruments/InstrumentCatalogTests.cs new file mode 100644 index 0000000..c9ca10e --- /dev/null +++ b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Instruments/InstrumentCatalogTests.cs @@ -0,0 +1,161 @@ +using System.Text.Json.Nodes; +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition; +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Instruments; +using GAJ3T.MusicGen.RiffGrooveBuilder.Generation.Instruments; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests.Instruments; + +[Collection("Catalog working directory")] +public sealed class InstrumentCatalogTests +{ + public static TheoryData Targets => new() + { + { "ample-abj", "ABJ", "Ample Bass J", TrackRole.Bass, "Ample Sound", "https://www.amplesound.net/en/Main_Panel_Manual-ABJ.pdf" }, + { "ample-aglp", "AGLP", "Ample Guitar LP", TrackRole.Lead, "Ample Sound", "https://www.amplesound.net/en/Main_Panel_Manual-AGLP.pdf" }, + { "ample-agm", "AGM", "Ample Guitar M", TrackRole.Lead, "Ample Sound", "https://www.amplesound.net/en/Main_Panel_Manual-AGM.pdf" }, + { "ample-agt", "AGT", "Ample Guitar T", TrackRole.Lead, "Ample Sound", "https://www.amplesound.net/en/Main_Panel_Manual-AGT.pdf" }, + { "ample-ame", "AME", "Ample Metal Eclipse", TrackRole.Lead, "Ample Sound", "https://www.amplesound.net/en/Main_Panel_Manual-AME.pdf" }, + { "ample-amr", "AMR", "Ample Metal Ray5", TrackRole.Bass, "Ample Sound", "https://www.amplesound.net/en/Main_Panel_Manual-AMR.pdf" }, + { "toontrack-sd3", "SD3", "Superior Drummer 3", TrackRole.Drums, "Toontrack", "https://www.toontrack.com/manual/superior-drummer-3/" } + }; + + [Theory] + [MemberData(nameof(Targets))] + public void ExactRequestedIdentityHasNoInventedVersionOrMapping(string id, string code, string name, + TrackRole role, string vendor, string url) + { + var instrument = InstrumentCatalog.LoadEmbedded().Find(id); + Assert.Equal(new InstrumentDefinition(id, vendor, code, name, role, url), instrument); + Assert.Equal(6, typeof(InstrumentDefinition).GetProperties().Length); + } + + [Fact] + public void EmbeddedMetadataIsOrderedImmutableAndIndependentOfWorkingDirectory() + { + var previous = Environment.CurrentDirectory; + try + { + Environment.CurrentDirectory = Environment.SystemDirectory; + var catalog = InstrumentCatalog.LoadEmbedded(); + Assert.Equal(7, catalog.Instruments.Count); + Assert.Equal(catalog.Instruments.OrderBy(i => i.Id, StringComparer.Ordinal), catalog.Instruments); + Assert.Equal(4, catalog.ForRole(TrackRole.Lead).Count); + Assert.Equal(2, catalog.ForRole(TrackRole.Bass).Count); + Assert.Single(catalog.ForRole(TrackRole.Drums)); + Assert.Equal(catalog.Instruments.Where(i => i.Role == TrackRole.Lead), catalog.ForRole(TrackRole.Lead)); + Assert.Throws(() => ((IList)catalog.Instruments).Clear()); + Assert.Throws(() => ((IList)catalog.ForRole(TrackRole.Lead)).Clear()); + Assert.Null(catalog.Find("unknown")); + Assert.Null(catalog.Find("AMPLE-ABJ")); + Assert.Throws(() => catalog.ForRole((TrackRole)100)); + } + finally + { + Environment.CurrentDirectory = previous; + } + } + + [Theory] + [InlineData("")] + [InlineData("{")] + [InlineData("{}")] + [InlineData("null")] + [InlineData("[null]")] + [InlineData("[{}]")] + [InlineData("[{\"unknown\":1}]")] + [InlineData("[] garbage")] + public void MalformedResourcesNeverBecomeSuccessfulEmptyCatalogs(string json) => + Assert.Throws(() => CatalogFixtures.Instruments(json)); + + [Theory] + [InlineData("id")] + [InlineData("vendor")] + [InlineData("productCode")] + [InlineData("displayName")] + [InlineData("role")] + [InlineData("documentationUrl")] + public void MissingAndNullRequiredFieldsFail(string field) + { + var node = JsonNode.Parse(CatalogFixtures.Read("instruments.json"))!; + node[0]!.AsObject().Remove(field); + Assert.Throws(() => CatalogFixtures.Instruments(node.ToJsonString())); + node[0]![field] = null; + Assert.Throws(() => CatalogFixtures.Instruments(node.ToJsonString())); + } + + [Theory] + [InlineData("id", "")] + [InlineData("id", "bad id")] + [InlineData("id", "é")] + [InlineData("id", "bad/path")] + [InlineData("vendor", " ")] + [InlineData("vendor", " Vendor")] + [InlineData("vendor", "Vendor\nName")] + [InlineData("productCode", "")] + [InlineData("productCode", "bad code")] + [InlineData("displayName", "")] + [InlineData("displayName", "Product ")] + [InlineData("role", "Unknown")] + [InlineData("role", "999")] + [InlineData("role", "Lead, Bass")] + [InlineData("role", "Lead, Lead")] + [InlineData("documentationUrl", "")] + [InlineData("documentationUrl", "relative/manual.pdf")] + [InlineData("documentationUrl", "file:///C:/manual.pdf")] + [InlineData("documentationUrl", "ftp://example.invalid/manual")] + [InlineData("documentationUrl", "https://")] + [InlineData("documentationUrl", "https://user:password@example.invalid/manual")] + [InlineData("documentationUrl", "https://example.invalid/a b")] + [InlineData("documentationUrl", " https://example.invalid/manual")] + public void InvalidRequiredIdentityRoleAndUrlValuesFail(string field, string value) + { + var node = JsonNode.Parse(CatalogFixtures.Read("instruments.json"))!; + node[0]![field] = value; + Assert.Throws(() => CatalogFixtures.Instruments(node.ToJsonString())); + } + + [Fact] + public void NumericRoleUnknownDuplicateFieldsAndDuplicateIdsAreRejected() + { + var json = CatalogFixtures.Read("instruments.json"); + var node = JsonNode.Parse(json)!; + node[0]!["role"] = 0; + Assert.Throws(() => CatalogFixtures.Instruments(node.ToJsonString())); + node[0]!["role"] = "Lead"; + node[0]!["unexpected"] = true; + Assert.Throws(() => CatalogFixtures.Instruments(node.ToJsonString())); + Assert.Throws(() => CatalogFixtures.Instruments( + json.Replace("\"role\": \"Lead\"", "\"role\": \"Lead\", \"role\": \"Bass\"", StringComparison.Ordinal))); + node = JsonNode.Parse(json)!; + node.AsArray().Add(node[0]!.DeepClone()); + Assert.Contains("duplicate_instrument_id", + Assert.Throws(() => CatalogFixtures.Instruments(node.ToJsonString())).Message); + } + + [Fact] + public void TestOnlyAdditionalTargetsLoadAsDataInDeterministicOrder() + { + var node = JsonNode.Parse(CatalogFixtures.Read("instruments.json"))!.AsArray(); + var reversed = new JsonArray(node.Reverse().Select(i => i!.DeepClone()).ToArray()); + var catalog = CatalogFixtures.Instruments(); + Assert.Equal(catalog.Instruments, CatalogFixtures.Instruments(reversed.ToJsonString()).Instruments); + Assert.Equal("Fixture Vendor", catalog.Find("synthetic-extra")!.Vendor); + Assert.Equal(3, catalog.ForRole(TrackRole.Lead).Count); + Assert.DoesNotContain(InstrumentCatalog.LoadEmbedded().Instruments, + i => i.Id.StartsWith("synthetic-", StringComparison.Ordinal)); + } + + [Theory] + [InlineData("productCode", "DIFFERENT")] + [InlineData("displayName", "Synthetic Different")] + public void OneProductCannotAcquireMultipleInstrumentIdentities(string field, string differentValue) + { + var node = JsonNode.Parse(CatalogFixtures.Read("instruments.json"))!.AsArray(); + var duplicate = node[0]!.DeepClone(); + duplicate["id"] = "synthetic-duplicate"; + duplicate[field] = differentValue; + node.Add(duplicate); + Assert.Contains("duplicate_product_identity", + Assert.Throws(() => CatalogFixtures.Instruments(node.ToJsonString())).Message); + } +} diff --git a/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Midi/MidiEventBuilderTests.cs b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Midi/MidiEventBuilderTests.cs new file mode 100644 index 0000000..8bb79e9 --- /dev/null +++ b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Midi/MidiEventBuilderTests.cs @@ -0,0 +1,85 @@ +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Articulations; +using GAJ3T.MusicGen.RiffGrooveBuilder.Generation.Midi; +using Melanchall.DryWetMidi.Core; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests.Midi; + +public sealed class MidiEventBuilderTests +{ + [Theory] + [InlineData(false, 0, 0, 1)] + [InlineData(true, 15, 127, 127)] + [InlineData(false, 9, 50, 96)] + public void NoteOnPreservesAllValues(bool keyswitch, int channel, int pitch, int velocity) + { + var source = new PlannedNoteOn(123, channel, pitch, velocity, keyswitch); + var actual = Assert.IsType(MidiEventBuilder.Build(source)); + Assert.Equal(channel, (int)actual.Channel); + Assert.Equal(pitch, (int)actual.NoteNumber); + Assert.Equal(velocity, (int)actual.Velocity); + Assert.Equal(0, actual.DeltaTime); + Assert.Equal(123, source.Tick); + } + + [Theory] + [InlineData(false, 0, 0)] + [InlineData(true, 15, 127)] + public void NoteOffIsExplicitWithZeroReleaseVelocity(bool keyswitch, int channel, int pitch) + { + var actual = Assert.IsType(MidiEventBuilder.Build(new PlannedNoteOff(456, channel, pitch, keyswitch))); + Assert.Equal(channel, (int)actual.Channel); + Assert.Equal(pitch, (int)actual.NoteNumber); + Assert.Equal(0, (int)actual.Velocity); + } + + [Theory] + [InlineData(0, 0, 0, false)] + [InlineData(15, 127, 127, true)] + [InlineData(9, 21, 100, false)] + public void ControlChangePreservesValues(int channel, int number, int value, bool reset) + { + var actual = Assert.IsType(MidiEventBuilder.Build(new PlannedControlChange(42, channel, number, value, reset))); + Assert.Equal(channel, (int)actual.Channel); + Assert.Equal(number, (int)actual.ControlNumber); + Assert.Equal(value, (int)actual.ControlValue); + } + + public static IEnumerable InvalidEvents() + { + yield return [new PlannedNoteOn(-1, 0, 64, 96, false)]; + foreach (var channel in new[] { -1, 16, 256 }) + yield return [new PlannedNoteOn(0, channel, 64, 96, false)]; + foreach (var pitch in new[] { -1, 128, 256 }) + { + yield return [new PlannedNoteOn(0, 0, pitch, 96, false)]; + yield return [new PlannedNoteOff(0, 0, pitch, true)]; + } + foreach (var velocity in new[] { -1, 0, 128, 256 }) + yield return [new PlannedNoteOn(0, 0, 64, velocity, true)]; + foreach (var value in new[] { -1, 128, 256 }) + { + yield return [new PlannedControlChange(0, 9, value, 0, false)]; + yield return [new PlannedControlChange(0, 9, 21, value, true)]; + } + } + + [Theory] + [MemberData(nameof(InvalidEvents))] + public void InvalidRangesNeverWrapOrClamp(PlannedMidiEvent planned) => + Assert.Throws(() => MidiEventBuilder.Build(planned)); + + [Fact] + public void UnknownTypeNullAndCancellationFailExplicitly() + { + Assert.Throws(() => MidiEventBuilder.Build(null!)); + var error = Assert.Throws(() => MidiEventBuilder.Build(new UnknownEvent())); + Assert.Contains(nameof(UnknownEvent), error.Message); + Assert.Throws(() => MidiEventBuilder.Build( + new PlannedNoteOff(0, 0, 64, false), new CancellationToken(true))); + } + + private sealed record UnknownEvent() : PlannedMidiEvent(0, 0) + { + public override int Priority => 2; + } +} diff --git a/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Midi/MidiFileBuilderTests.cs b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Midi/MidiFileBuilderTests.cs new file mode 100644 index 0000000..15410f5 --- /dev/null +++ b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Midi/MidiFileBuilderTests.cs @@ -0,0 +1,278 @@ +using System.Text.Json; +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Articulations; +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition; +using GAJ3T.MusicGen.RiffGrooveBuilder.Generation.Midi; +using GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests.Articulations; +using Melanchall.DryWetMidi.Core; +using MusicalComposition = GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition.Composition; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests.Midi; + +public sealed class MidiFileBuilderTests +{ + [Fact] + public void TypeOneResolutionNamedTracksMetadataAndTrailingRestRoundTrip() + { + var (composition, plan) = MidiTestData.Arrangement(); + var file = MidiTestData.RoundTrip(MidiFileBuilder.Build(composition, plan)); + Assert.Equal(MidiFileFormat.MultiTrack, file.OriginalFormat); + Assert.Equal(960, Assert.IsType(file.TimeDivision).TicksPerQuarterNote); + var tracks = file.Chunks.Cast().ToArray(); + Assert.Equal(new[] { "Conductor", "Lead" }, tracks.Select(t => Assert.Single(t.Events.OfType()).Text)); + Assert.Equal(500_000, Assert.Single(tracks[0].Events.OfType()).MicrosecondsPerQuarterNote); + var meter = Assert.Single(tracks[0].Events.OfType()); + Assert.Equal(4, meter.Numerator); + Assert.Equal(4, meter.Denominator); + Assert.All(MidiTestData.Absolute(tracks[0]).Where(e => e.Event is not EndOfTrackEvent), e => Assert.Equal(0, e.Tick)); + Assert.All(tracks, t => + { + Assert.Single(t.Events.OfType()); + Assert.IsType(t.Events.Last()); + Assert.Equal(15_360, MidiTestData.Absolute(t).Last().Tick); + }); + Assert.Equal(960, MidiTestData.Absolute(tracks[1]).Single(e => e.Event is NoteOffEvent).Tick); + Assert.Equal(0, (int)Assert.Single(tracks[1].Events.OfType()).Velocity); + } + + [Theory] + [InlineData(120, 500000)] + [InlineData(123, 487805)] + [InlineData(128, 468750)] + [InlineData(256, 234375)] + [InlineData(512, 117188)] + [InlineData(60000000, 1)] + public void TempoUsesNearestIntegerMidpointAwayFromZero(double bpm, long expected) + { + var (original, plan) = MidiTestData.Arrangement(); + var composition = new MusicalComposition(bpm, original.Meter, original.Key, original.Bars, original.Tracks); + var file = MidiTestData.RoundTrip(MidiFileBuilder.Build(composition, plan)); + Assert.Equal(expected, Assert.Single(file.Chunks.OfType().First().Events.OfType()).MicrosecondsPerQuarterNote); + } + + [Fact] + public void LowerTempoBoundaryIsRepresentableWithoutClamping() + { + var (original, plan) = MidiTestData.Arrangement(); + var composition = new MusicalComposition(60_000_000d / 0xFFFFFF, original.Meter, original.Key, original.Bars, original.Tracks); + Assert.Empty(CompositionValidator.Validate(composition)); + var file = MidiTestData.RoundTrip(MidiFileBuilder.Build(composition, plan)); + Assert.Equal(0xFFFFFF, Assert.Single(file.Chunks.OfType().First().Events.OfType()).MicrosecondsPerQuarterNote); + } + + [Theory] + [InlineData(0)] + [InlineData(-120)] + [InlineData(double.NaN)] + [InlineData(double.PositiveInfinity)] + [InlineData(double.NegativeInfinity)] + [InlineData(60000001)] + [InlineData(3)] + public void InvalidTempoFailsBeforeSerialization(double bpm) + { + var (original, plan) = MidiTestData.Arrangement(); + var composition = new MusicalComposition(bpm, original.Meter, original.Key, original.Bars, original.Tracks); + Assert.Contains("tempoBpm", Assert.Throws(() => MidiFileBuilder.Build(composition, plan)).Message); + } + + [Theory] + [InlineData(0.75)] + [InlineData(16777215.25)] + public void RoundingDoesNotAdmitTemposOutsideExistingUnroundedCoreRange(double quotient) + { + var (original, plan) = MidiTestData.Arrangement(); + var composition = new MusicalComposition(60_000_000d / quotient, + original.Meter, original.Key, original.Bars, original.Tracks); + Assert.Contains("tempoBpm", Assert.Throws(() => MidiFileBuilder.Build(composition, plan)).Message); + } + + [Theory] + [InlineData(3, 8)] + [InlineData(7, 16)] + [InlineData(255, 1)] + [InlineData(4, 128)] + public void LibraryTakesActualDenominatorNotExponent(int numerator, int denominator) + { + var composition = new MusicalComposition(120, new(numerator, denominator), new(4, KeyMode.Minor), 1, + [new(TrackRole.Lead, [new(64, BeatFraction.Zero, new(4, denominator), 96, Articulation.Sustain)])]); + var plan = MidiTestData.Plan(composition); + var file = MidiTestData.RoundTrip(MidiFileBuilder.Build(composition, plan)); + var meter = Assert.Single(file.Chunks.OfType().First().Events.OfType()); + Assert.Equal(numerator, (int)meter.Numerator); + Assert.Equal(denominator, (int)meter.Denominator); + Assert.All(file.Chunks.Cast(), t => Assert.Equal(composition.MusicalExtent.ToTicks(), MidiTestData.Absolute(t).Last().Tick)); + } + + [Fact] + public void CoreDenominator256FailsClearlyWithoutByteWrapOrCoreChange() + { + var composition = new MusicalComposition(120, new(4, 256), new(4, KeyMode.Minor), 1, + [new(TrackRole.Lead, [new(64, BeatFraction.Zero, new(1, 64), 96, Articulation.Sustain)])]); + Assert.Empty(CompositionValidator.Validate(composition)); + var plan = MidiTestData.Plan(composition); + var error = Assert.Throws(() => MidiFileBuilder.Build(composition, plan)); + Assert.Contains("/256", error.Message); + Assert.Contains("1..128", error.Message); + } + + [Theory] + [InlineData(0x0FFFFFFF, true)] + [InlineData(0x10000000, false)] + public void GlobalConductorEndGapEnforcesFourByteVlq(long endTick, bool accepted) + { + var composition = SyntheticProfiles.Model(SyntheticProfiles.Note(articulation: Articulation.PalmMute)); + var profile = SyntheticProfiles.Switched(advance: endTick - 15_360).Build(); + var plan = MidiTestData.Plan(composition, profile); + Assert.Equal(endTick, plan.EndTick); + if (!accepted) + { + Assert.Contains("four-byte VLQ", Assert.Throws(() => MidiFileBuilder.Build(composition, plan)).Message); + return; + } + var file = MidiTestData.RoundTrip(MidiFileBuilder.Build(composition, plan)); + Assert.All(file.Chunks.Cast(), t => Assert.Equal(endTick, MidiTestData.Absolute(t).Last().Tick)); + Assert.Equal(endTick, file.Chunks.Cast().First().Events.Last().DeltaTime); + } + + [Fact] + public void DeltaConversionIsCheckedAndRejectsBackwardTime() + { + Assert.Equal(0, MidiFileBuilder.DeltaTicks(long.MaxValue, long.MaxValue)); + Assert.Equal(0x0FFFFFFF, MidiFileBuilder.DeltaTicks(long.MaxValue, long.MaxValue - 0x0FFFFFFF)); + Assert.Throws(() => MidiFileBuilder.DeltaTicks(0, 1)); + Assert.Throws(() => MidiFileBuilder.DeltaTicks(0x10000000, 0)); + Assert.Throws(() => MidiFileBuilder.DeltaTicks(long.MaxValue, -1)); + } + + [Fact] + public void NullInvalidAndMismatchedCompositionFailWithoutDefaults() + { + var (composition, plan) = MidiTestData.Arrangement(); + Assert.Throws(() => MidiFileBuilder.Build(null!, plan)); + Assert.Throws(() => MidiFileBuilder.Build(composition, null!)); + Assert.Throws(() => MidiFileBuilder.Build(new(120, new(4, 4), composition.Key, 4, []), plan)); + Assert.Contains("extent", Assert.Throws(() => MidiFileBuilder.Build( + new(120, composition.Meter, composition.Key, 5, composition.Tracks), plan)).Message); + Assert.Contains("roles", Assert.Throws(() => MidiFileBuilder.Build( + new(120, composition.Meter, composition.Key, 4, [new(TrackRole.Bass, composition.Tracks[0].Notes)]), plan)).Message); + Assert.Contains("disagree", Assert.Throws(() => MidiFileBuilder.Build( + SyntheticProfiles.Model(SyntheticProfiles.Note(pitch: 65)), plan)).Message); + Assert.Contains("disagree", Assert.Throws(() => MidiFileBuilder.Build( + SyntheticProfiles.Model(SyntheticProfiles.Note(start: 1)), plan)).Message); + Assert.Throws(() => MidiFileBuilder.Build(composition, plan, new CancellationToken(true))); + } + + [Fact] + public void SameTickMomentaryReleaseResetNewStateAndNotesKeepStableOrder() + { + var composition = SyntheticProfiles.Model( + SyntheticProfiles.Note(0, 1, articulation: Articulation.PalmMute), + SyntheticProfiles.Note(1, 1, articulation: Articulation.PalmMute)); + var profile = SyntheticProfiles.Switched(StateBehavior.Momentary, advance: 0, duration: 30, cc: true).Build(); + var plan = MidiTestData.Plan(composition, profile); + var track = MidiTestData.RoundTrip(MidiFileBuilder.Build(composition, plan)).Chunks.Cast().Last(); + var boundary = MidiTestData.Absolute(track).Where(e => e.Tick == 960).Select(e => e.Event).ToArray(); + Assert.Collection(boundary, + e => Assert.Equal(11, (int)Assert.IsType(e).NoteNumber), + e => Assert.Equal(64, (int)Assert.IsType(e).NoteNumber), + e => Assert.Equal(0, (int)Assert.IsType(e).ControlValue), + e => Assert.Equal(100, (int)Assert.IsType(e).ControlValue), + e => Assert.Equal(11, (int)Assert.IsType(e).NoteNumber), + e => Assert.Equal(64, (int)Assert.IsType(e).NoteNumber)); + } + + [Fact] + public void ExactRationalTripletsRetainTheirPlannedTicksAfterReadBack() + { + var composition = SyntheticProfiles.Model(Enumerable.Range(0, 12) + .Select(i => new MusicalNote(64, new(i, 3), new(1, 3), 96, Articulation.Sustain)).ToArray()); + var plan = MidiTestData.Plan(composition); + var track = MidiTestData.RoundTrip(MidiFileBuilder.Build(composition, plan)).Chunks.Cast().Last(); + var events = MidiTestData.Absolute(track); + Assert.Equal(Enumerable.Range(0, 12).Select(i => i * 320L), + events.Where(e => e.Event is NoteOnEvent).Select(e => e.Tick)); + Assert.Equal(Enumerable.Range(1, 12).Select(i => i * 320L), + events.Where(e => e.Event is NoteOffEvent).Select(e => e.Tick)); + } + + [Fact] + public void FinalResetPulseTailExtendsEveryTrackWithoutSourceMutation() + { + var composition = SyntheticProfiles.Model(SyntheticProfiles.Note(0, 16, articulation: Articulation.PalmMute)); + var data = SyntheticProfiles.Switched(advance: 120, duration: 30, cc: true) with + { + Reset = Articulation.Sustain, + FinalControllers = [new(20, 0)] + }; + var plan = MidiTestData.Plan(composition, data.Build()); + Assert.Equal(15_480, plan.MusicalEndTick); + Assert.Equal(15_510, plan.EndTick); + var before = JsonSerializer.Serialize(new { composition, plan }); + var first = MidiFileBuilder.Build(composition, plan); + var second = MidiFileBuilder.Build(composition, plan); + Assert.Equal(before, JsonSerializer.Serialize(new { composition, plan })); + Assert.Equal(MidiTestData.Bytes(first), MidiTestData.Bytes(second)); + var file = MidiTestData.RoundTrip(first); + Assert.All(file.Chunks.Cast(), t => Assert.Equal(15_510, MidiTestData.Absolute(t).Last().Tick)); + var tail = MidiTestData.Absolute(file.Chunks.Cast().Last()).Where(e => e.Tick >= 15_480).ToArray(); + Assert.Collection(tail, + e => Assert.IsType(e.Event), + e => Assert.Equal(0, (int)Assert.IsType(e.Event).ControlValue), + e => Assert.Equal(10, (int)Assert.IsType(e.Event).NoteNumber), + e => Assert.Equal(10, (int)Assert.IsType(e.Event).NoteNumber), + e => Assert.IsType(e.Event)); + } + + [Fact] + public void PinnedLibraryDoesNotEnforceSmfVlqLimitItself() + { + Assert.Equal(new Version(8, 0, 3, 0), typeof(MidiFile).Assembly.GetName().Version); + Assert.Empty(typeof(EndOfTrackEvent).GetConstructors()); + Assert.Equal(typeof(byte), typeof(TimeSignatureEvent).GetProperty(nameof(TimeSignatureEvent.Denominator))!.PropertyType); + var file = new MidiFile(new TrackChunk(new ControlChangeEvent { DeltaTime = 0x10000000 })); + using var stream = new MemoryStream(); + file.Write(stream, MidiFileFormat.MultiTrack); + Assert.True(stream.Length > 0); + Assert.Throws(() => MidiFileBuilder.DeltaTicks(0x10000000, 0)); + } +} + +internal static class MidiTestData +{ + internal static (MusicalComposition Composition, MidiEventPlan Plan) Arrangement() + { + var composition = SyntheticProfiles.Model(SyntheticProfiles.Note()); + return (composition, Plan(composition)); + } + + internal static MidiEventPlan Plan(MusicalComposition composition, InstrumentProfile? profile = null) + { + var result = ArticulationPlanner.Plan(composition, [profile ?? new SyntheticProfiles.Data().Build()], allowSynthetic: true); + Assert.True(result.Success, string.Join("; ", result.Diagnostics)); + return result.Plan!; + } + + internal static byte[] Bytes(MidiFile file) + { + using var stream = new MemoryStream(); + file.Write(stream, MidiFileFormat.MultiTrack); + return stream.ToArray(); + } + + internal static MidiFile RoundTrip(MidiFile file) + { + using var stream = new MemoryStream(Bytes(file)); + return Read(stream); + } + + internal static MidiFile Read(Stream stream) => MidiFile.Read(stream, new ReadingSettings + { + EndOfTrackStoringPolicy = EndOfTrackStoringPolicy.Store, + MissedEndOfTrackPolicy = MissedEndOfTrackPolicy.Abort + }); + + internal static (long Tick, MidiEvent Event)[] Absolute(TrackChunk track) + { + long tick = 0; + return track.Events.Select(e => (Tick: tick = checked(tick + e.DeltaTime), Event: e)).ToArray(); + } +} diff --git a/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Midi/MidiFileWriterTests.cs b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Midi/MidiFileWriterTests.cs new file mode 100644 index 0000000..f2f2a95 --- /dev/null +++ b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Midi/MidiFileWriterTests.cs @@ -0,0 +1,294 @@ +using GAJ3T.MusicGen.RiffGrooveBuilder.Generation.Midi; +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition; +using GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests.Articulations; +using Melanchall.DryWetMidi.Core; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests.Midi; + +public sealed class MidiFileWriterTests : IDisposable +{ + private readonly string directory = Path.Combine(AppContext.BaseDirectory, "midi-writer-" + Guid.NewGuid().ToString("N")); + + public MidiFileWriterTests() => Directory.CreateDirectory(directory); + + [Fact] + public void BorrowedWritableStreamStaysOpenAndReadsBack() + { + var (composition, plan) = MidiTestData.Arrangement(); + using var stream = new MemoryStream(); + MidiFileWriter.Write(stream, composition, plan); + Assert.True(stream.CanWrite); + stream.Position = 0; + var read = MidiTestData.Read(stream); + Assert.Equal(MidiFileFormat.MultiTrack, read.OriginalFormat); + Assert.Equal(2, read.Chunks.Count); + Assert.True(stream.CanWrite); + } + + [Fact] + public void BorrowedNonseekableStreamIsSupported() + { + var (composition, plan) = MidiTestData.Arrangement(); + using var stream = new ObservedStream(); + MidiFileWriter.Write(stream, composition, plan); + Assert.False(stream.Closed); + using var bytes = new MemoryStream(stream.Bytes); + Assert.Equal(2, MidiTestData.Read(bytes).Chunks.Count); + } + + [Fact] + public void InvalidReadOnlyDisposedAndFailingStreamsAreTruthful() + { + var (composition, plan) = MidiTestData.Arrangement(); + Assert.Throws(() => MidiFileWriter.Write(null!, composition, plan)); + using var readOnly = new MemoryStream([], writable: false); + Assert.Throws(() => MidiFileWriter.Write(readOnly, composition, plan)); + var disposed = new MemoryStream(); + disposed.Dispose(); + Assert.Throws(() => MidiFileWriter.Write(disposed, composition, plan)); + using var failing = new ObservedStream(failAfter: 20); + var error = Assert.Throws(() => MidiFileWriter.Write(failing, composition, plan)); + Assert.Equal("synthetic stream failure", error.Message); + Assert.False(failing.Closed); + Assert.NotEmpty(failing.Bytes); + } + + [Fact] + public void StreamPreflightFailureOrPrecancellationWritesNothing() + { + var (composition, plan) = MidiTestData.Arrangement(); + using var stream = new MemoryStream(); + Assert.Throws(() => MidiFileWriter.Write(stream, null!, plan)); + Assert.Empty(stream.ToArray()); + Assert.Throws(() => MidiFileWriter.Write(stream, composition, plan, new CancellationToken(true))); + Assert.Empty(stream.ToArray()); + Assert.True(stream.CanWrite); + } + + [Fact] + public void CancellationObservedAfterSynchronousWriteLeavesBorrowedPartialOrCompleteBytes() + { + var (composition, plan) = MidiTestData.Arrangement(); + using var cancellation = new CancellationTokenSource(); + using var stream = new ObservedStream(afterWrite: cancellation.Cancel); + Assert.Throws(() => MidiFileWriter.Write(stream, composition, plan, cancellation.Token)); + Assert.NotEmpty(stream.Bytes); + Assert.False(stream.Closed); + } + + [Fact] + public void ActualFileIsReadableAndPreexistingDestinationNeverChanges() + { + var (composition, plan) = MidiTestData.Arrangement(); + var path = Path.Combine(directory, "song.mid"); + var unrelated = Path.Combine(directory, ".unrelated.stage"); + File.WriteAllText(unrelated, "keep"); + MidiFileWriter.WriteFile(path, composition, plan); + var before = File.ReadAllBytes(path); + using (var stream = File.OpenRead(path)) + Assert.Equal(MidiFileFormat.MultiTrack, MidiTestData.Read(stream).OriginalFormat); + Assert.Throws(() => MidiFileWriter.WriteFile(path, composition, plan)); + Assert.Equal(before, File.ReadAllBytes(path)); + Assert.Equal("keep", File.ReadAllText(unrelated)); + Assert.Equal(2, Directory.GetFiles(directory).Length); + } + + [Fact] + public void CollisionAfterStagingUsesAtomicNoOverwriteMoveAndRemovesOnlyOwnedStage() + { + var path = Path.Combine(directory, "collision.mid"); + string? stage = null; + Assert.Throws(() => MidiFileWriter.Publish(path, stream => + { + stage = Assert.IsType(stream).Name; + Assert.Equal(directory, Path.GetDirectoryName(stage)); + Assert.NotEqual(path, stage); + stream.WriteByte(42); + File.WriteAllText(path, "racing owner"); + }, CancellationToken.None)); + Assert.Equal("racing owner", File.ReadAllText(path)); + Assert.False(File.Exists(stage)); + Assert.Single(Directory.GetFiles(directory)); + } + + [Fact] + public void LateDirectoryCollisionAlsoPreservesDestinationAndCleansOnlyStage() + { + var path = Path.Combine(directory, "racing-directory.mid"); + Assert.Throws(() => MidiFileWriter.Publish(path, stream => + { + stream.WriteByte(42); + Directory.CreateDirectory(path); + }, CancellationToken.None)); + Assert.True(Directory.Exists(path)); + Assert.Empty(Directory.GetFiles(directory)); + } + + [Fact] + public void UnrepresentablePlanNeverCreatesStageOrTouchesBorrowedBytes() + { + var composition = SyntheticProfiles.Model(SyntheticProfiles.Note(articulation: Articulation.PalmMute)); + var plan = MidiTestData.Plan(composition, SyntheticProfiles.Switched(advance: 0x10000000).Build()); + var path = Path.Combine(directory, "too-long.mid"); + Assert.Throws(() => MidiFileWriter.WriteFile(path, composition, plan)); + using var stream = new MemoryStream(); + Assert.Throws(() => MidiFileWriter.Write(stream, composition, plan)); + Assert.Empty(stream.ToArray()); + Assert.Empty(Directory.GetFileSystemEntries(directory)); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void FailedOrCancelledStagingCleansOwnedFileAndPreservesOtherFiles(bool cancel) + { + var path = Path.Combine(directory, "failed.mid"); + var unrelated = Path.Combine(directory, ".other-request.stage"); + File.WriteAllText(unrelated, "keep"); + using var cancellation = new CancellationTokenSource(); + string? stage = null; + var original = new IOException("synthetic staging failure"); + var error = Record.Exception(() => MidiFileWriter.Publish(path, stream => + { + stage = Assert.IsType(stream).Name; + stream.WriteByte(42); + if (cancel) cancellation.Cancel(); + else throw original; + }, cancellation.Token)); + if (cancel) Assert.IsType(error); + else Assert.Same(original, error); + Assert.False(File.Exists(stage)); + Assert.False(File.Exists(path)); + Assert.Equal("keep", File.ReadAllText(unrelated)); + Assert.Single(Directory.GetFiles(directory)); + } + + [Fact] + public void CleanupFailureExplicitlyRetainsOriginalErrorAndOwnedPath() + { + var stage = Path.Combine(directory, ".locked-owned.stage"); + var original = new OperationCanceledException("original cancellation"); + using (var locked = new FileStream(stage, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + { + var error = Assert.Throws(() => MidiFileWriter.Cleanup(stage, original)); + Assert.Contains(stage, error.Message); + Assert.Same(original, error.InnerExceptions[0]); + Assert.IsType(error.InnerExceptions[1]); + Assert.True(File.Exists(stage)); + } + File.Delete(stage); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void StageCloseFailureIsReportedWithoutHidingOriginalWriteOrCancellation(bool cancel) + { + using var cancellation = new CancellationTokenSource(); + var original = new IOException("original write error"); + var close = new IOException("synthetic close error"); + var stream = new CloseFailingStream(close); + var error = Assert.Throws(() => MidiFileWriter.CompleteStage(stream, _ => + { + if (cancel) cancellation.Cancel(); + else throw original; + }, cancellation.Token)); + if (cancel) Assert.IsType(error.InnerExceptions[0]); + else Assert.Same(original, error.InnerExceptions[0]); + Assert.Same(close, error.InnerExceptions[1]); + Assert.False(stream.CanWrite); + } + + [Fact] + public void StageCloseFailureAloneDoesNotBecomeSuccess() + { + var close = new IOException("synthetic close error"); + var stream = new CloseFailingStream(close); + Assert.Same(close, Assert.Throws(() => + MidiFileWriter.CompleteStage(stream, _ => { }, CancellationToken.None))); + Assert.False(stream.CanWrite); + } + + [Theory] + [InlineData("")] + [InlineData("relative.mid")] + [InlineData(@"C:drive-relative.mid")] + public void DestinationRequiresExplicitAbsoluteFilePath(string path) + { + var (composition, plan) = MidiTestData.Arrangement(); + Assert.ThrowsAny(() => MidiFileWriter.WriteFile(path, composition, plan)); + Assert.Empty(Directory.GetFiles(directory)); + } + + [Theory] + [InlineData("CON.mid")] + [InlineData("aux.mid")] + [InlineData("COM1.mid")] + [InlineData("LPT9.mid")] + [InlineData("song.mid:stream")] + [InlineData("song.mid.")] + [InlineData("song.mid ")] + [InlineData("bad?.mid")] + public void InvalidReservedAndAlternateStreamNamesFailBeforeStaging(string name) + { + var (composition, plan) = MidiTestData.Arrangement(); + Assert.Throws(() => MidiFileWriter.WriteFile(Path.Combine(directory, name), composition, plan)); + Assert.Empty(Directory.GetFiles(directory)); + } + + [Fact] + public void MissingParentDirectoryDestinationPreflightAndCancellationDoNotCreateOutputs() + { + var (composition, plan) = MidiTestData.Arrangement(); + Assert.Throws(() => MidiFileWriter.WriteFile(Path.Combine(directory, "absent", "song.mid"), composition, plan)); + Assert.Throws(() => MidiFileWriter.WriteFile(directory, composition, plan)); + Assert.Throws(() => MidiFileWriter.WriteFile(directory + Path.DirectorySeparatorChar, composition, plan)); + var path = Path.Combine(directory, "song.mid"); + Assert.Throws(() => MidiFileWriter.WriteFile(path, null!, plan)); + Assert.Throws(() => MidiFileWriter.WriteFile(path, composition, plan, new CancellationToken(true))); + Assert.Empty(Directory.GetFileSystemEntries(directory)); + } + + public void Dispose() => Directory.Delete(directory, recursive: true); + + private sealed class CloseFailingStream(Exception error) : MemoryStream + { + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + throw error; + } + } + + private sealed class ObservedStream(int failAfter = int.MaxValue, Action? afterWrite = null) : Stream + { + private readonly MemoryStream inner = new(); + public byte[] Bytes => inner.ToArray(); + public bool Closed { get; private set; } + public override bool CanRead => false; + public override bool CanSeek => false; + public override bool CanWrite => !Closed; + public override long Length => throw new NotSupportedException(); + public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } + public override void Write(byte[] buffer, int offset, int count) + { + if (inner.Length + count > failAfter) + { + inner.Write(buffer, offset, checked((int)(failAfter - inner.Length))); + throw new IOException("synthetic stream failure"); + } + inner.Write(buffer, offset, count); + afterWrite?.Invoke(); + } + public override void Flush() { } + public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + protected override void Dispose(bool disposing) + { + Closed = true; + if (disposing) inner.Dispose(); + base.Dispose(disposing); + } + } +} diff --git a/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Protocol/JsonRpcDispatcherTests.cs b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Protocol/JsonRpcDispatcherTests.cs new file mode 100644 index 0000000..e9bf076 --- /dev/null +++ b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Protocol/JsonRpcDispatcherTests.cs @@ -0,0 +1,376 @@ +using System.Text; +using System.Text.Json; +using GAJ3T.MusicGen.RiffGrooveBuilder.Server.Protocol; +using GAJ3T.MusicGen.RiffGrooveBuilder.Server.Tools; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests.Protocol; + +public sealed class JsonRpcDispatcherTests +{ + [Theory] + [InlineData("0")] + [InlineData("-9223372036854775808")] + [InlineData("9223372036854775807")] + [InlineData("\"1\"")] + [InlineData("\"\"")] + [InlineData("\"音楽\\n🎸\"")] + public async Task PreservesStringAndSignedIntegerIds(string id) + { + await using var connection = new ProtocolTestConnection(); + await connection.SendAsync($$"""{"jsonrpc":"2.0","id":{{id}},"method":"ping"}"""); + var response = await connection.ReadAsync(); + var expectedId = ProtocolTestConnection.Json(id); + var actualId = response.GetProperty("id"); + Assert.Equal(expectedId.ValueKind, actualId.ValueKind); + if (expectedId.ValueKind == JsonValueKind.String) + { + Assert.Equal(expectedId.GetString(), actualId.GetString()); + } + else + { + Assert.Equal(expectedId.GetInt64(), actualId.GetInt64()); + } + Assert.Equal("{}", response.GetProperty("result").GetRawText()); + await connection.AssertNoMoreResponsesAsync(); + } + + [Theory] + [InlineData("{")] + [InlineData("not-json")] + [InlineData("")] + [InlineData("""{"jsonrpc":"2.0","id":1,"method":"ping",}""")] + [InlineData("""{"jsonrpc":"2.0","id":1,"method":"ping" /* comment */}""")] + public async Task MalformedJsonReturnsParseErrorAndRecovers(string invalid) + { + await using var connection = new ProtocolTestConnection(); + await connection.SendAsync(invalid); + var error = await connection.ReadAsync(); + Assert.Equal(-32700, ErrorCode(error)); + Assert.Equal(JsonValueKind.Null, error.GetProperty("id").ValueKind); + await connection.SendAsync("""{"jsonrpc":"2.0","id":2,"method":"ping"}"""); + Assert.Equal(2, (await connection.ReadAsync()).GetProperty("id").GetInt32()); + await connection.AssertNoMoreResponsesAsync(); + } + + [Theory] + [InlineData("[]")] + [InlineData("""[{"jsonrpc":"2.0","id":1,"method":"ping"}]""")] + [InlineData("{}")] + [InlineData("null")] + [InlineData("123")] + [InlineData("""{"jsonrpc":"2.0","id":null,"method":"ping"}""")] + [InlineData("""{"jsonrpc":"2.0","id":true,"method":"ping"}""")] + [InlineData("""{"jsonrpc":"2.0","id":{},"method":"ping"}""")] + [InlineData("""{"jsonrpc":"2.0","id":1.5,"method":"ping"}""")] + [InlineData("""{"jsonrpc":"2.0","id":1.0,"method":"ping"}""")] + [InlineData("""{"jsonrpc":"2.0","id":9223372036854775808,"method":"ping"}""")] + [InlineData("""{"jsonrpc":"2.0","id":[],"method":"ping"}""")] + [InlineData("""{"jsonrpc":"2.0","id":1,"id":2,"method":"ping"}""")] + public async Task InvalidEnvelopeOrUnsupportedIdReturnsNullId(string invalid) + { + await using var connection = new ProtocolTestConnection(); + await connection.SendAsync(invalid); + var response = await connection.ReadAsync(); + Assert.Equal(-32600, ErrorCode(response)); + Assert.Equal(JsonValueKind.Null, response.GetProperty("id").ValueKind); + await connection.AssertNoMoreResponsesAsync(); + } + + [Theory] + [InlineData("""{"id":"valid","method":"ping"}""")] + [InlineData("""{"jsonrpc":"1.0","id":"valid","method":"ping"}""")] + [InlineData("""{"jsonrpc":2,"id":"valid","method":"ping"}""")] + [InlineData("""{"jsonrpc":"2.0","id":"valid","method":42}""")] + [InlineData("""{"jsonrpc":"2.0","id":"valid","method":"ping","result":{}}""")] + [InlineData("""{"jsonrpc":"2.0","id":"valid","method":"ping","method":"initialize"}""")] + public async Task IdentifiableValidIdIsPreservedOnInvalidEnvelope(string invalid) + { + await using var connection = new ProtocolTestConnection(); + await connection.SendAsync(invalid); + var response = await connection.ReadAsync(); + Assert.Equal(-32600, ErrorCode(response)); + Assert.Equal("valid", response.GetProperty("id").GetString()); + } + + [Theory] + [InlineData("unknown", null, -32601)] + [InlineData("shutdown", null, -32601)] + [InlineData("notifications/initialized", null, -32601)] + [InlineData("ping", "[]", -32602)] + [InlineData("ping", "true", -32602)] + [InlineData("ping", "null", -32602)] + [InlineData("tools/list", null, -32002)] + public async Task DispatchesExplicitRequestErrors(string method, string? parameters, int code) + { + await using var connection = new ProtocolTestConnection(); + var suffix = parameters is null ? "" : ",\"params\":" + parameters; + await connection.SendAsync($$"""{"jsonrpc":"2.0","id":1,"method":"{{method}}"{{suffix}}}"""); + Assert.Equal(code, ErrorCode(await connection.ReadAsync())); + } + + [Fact] + public async Task NotificationsAreSilentAndInitializeWithoutIdDoesNotChangeLifecycle() + { + await using var connection = new ProtocolTestConnection(); + foreach (var message in new[] + { + """{"jsonrpc":"2.0","method":"ping"}""", + """{"jsonrpc":"2.0","method":"unknown","params":{}}""", + """{"jsonrpc":"2.0","method":"notifications/initialized"}""", + """{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":[]}}""", + """{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":"missing"}}""", + $$"""{"jsonrpc":"2.0","method":"initialize","params":{{ProtocolTestConnection.Initialization}}}""" + }) + { + await connection.SendAsync(message); + } + + await connection.SendAsync("""{"jsonrpc":"2.0","id":12,"method":"tools/list"}"""); + var response = await connection.ReadAsync(); + Assert.Equal(12, response.GetProperty("id").GetInt32()); + Assert.Equal(-32002, ErrorCode(response)); + await connection.AssertNoMoreResponsesAsync(); + Assert.Contains("Ignored", connection.Diagnostics.ToString()); + } + + [Fact] + public async Task HandlerFailureReturnsInternalErrorOnlyAndTheConnectionSurvives() + { + var registry = new McpToolRegistry(); + registry.Register(new McpToolDefinition( + "test.failure", "Synthetic failing tool.", (_, _) => + throw new InvalidOperationException("test-only diagnostic detail"))); + await using var connection = new ProtocolTestConnection(registry); + await connection.ReadyAsync(); + await connection.SendAsync(""" + {"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"test.failure","arguments":{"text":"go"}}} + """); + var response = await connection.ReadAsync(); + Assert.Equal(-32603, ErrorCode(response)); + Assert.DoesNotContain("test-only diagnostic detail", response.GetRawText()); + Assert.Contains("test-only diagnostic detail", connection.Diagnostics.ToString()); + await connection.SendAsync("""{"jsonrpc":"2.0","id":2,"method":"ping"}"""); + Assert.Equal(2, (await connection.ReadAsync()).GetProperty("id").GetInt32()); + await connection.AssertNoMoreResponsesAsync(); + } + + [Fact] + public async Task CancellationTargetsTypedIdDuplicateDoesNotReplaceWorkAndOtherRequestSurvives() + { + var stringStarted = Signal(); + var numericStarted = Signal(); + var stringCancelled = Signal(); + var numericRelease = Signal(); + var registry = new McpToolRegistry(); + registry.Register(new McpToolDefinition( + "test.wait", "Synthetic cancellable tool.", async (input, token) => + { + if (input.Text == "string") + { + stringStarted.SetResult(); + try + { + await Task.Delay(Timeout.InfiniteTimeSpan, token); + } + catch (OperationCanceledException) + { + stringCancelled.SetResult(); + throw; + } + } + else + { + numericStarted.SetResult(); + await numericRelease.Task.WaitAsync(token); + } + + return new(new(input.Text, "complete")); + })); + await using var connection = new ProtocolTestConnection(registry); + await connection.ReadyAsync(); + await connection.SendAsync(""" + {"jsonrpc":"2.0","id":"7","method":"tools/call","params":{"name":"test.wait","arguments":{"text":"string"}}} + """); + await connection.SendAsync(""" + {"jsonrpc":"2.0","id":7,"method":"tools/call","params":{"name":"test.wait","arguments":{"text":"integer"}}} + """); + await Task.WhenAll(stringStarted.Task, numericStarted.Task).WaitAsync(TimeSpan.FromSeconds(5)); + await connection.SendAsync("""{"jsonrpc":"2.0","id":"7","method":"ping"}"""); + Assert.Equal(-32600, ErrorCode(await connection.ReadAsync())); + await connection.SendAsync("""{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":7,"reason":false}}"""); + await connection.SendAsync("""{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":"7","reason":"unit test"}}"""); + await stringCancelled.Task.WaitAsync(TimeSpan.FromSeconds(5)); + await connection.SendAsync("""{"jsonrpc":"2.0","id":"still-alive","method":"ping"}"""); + Assert.Equal("still-alive", (await connection.ReadAsync()).GetProperty("id").GetString()); + numericRelease.SetResult(); + var survivor = await connection.ReadAsync(); + Assert.Equal(7, survivor.GetProperty("id").GetInt32()); + Assert.Equal("integer", survivor.GetProperty("result").GetProperty("structuredContent").GetProperty("text").GetString()); + await connection.AssertNoMoreResponsesAsync(); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task EofOrLifetimeCancellationStopsOutstandingWorkWithoutAResponse(bool eof) + { + var started = Signal(); + var cancelled = Signal(); + var registry = new McpToolRegistry(); + registry.Register(new McpToolDefinition( + "test.wait", "Synthetic EOF cancellation.", async (_, token) => + { + started.SetResult(); + try + { + await Task.Delay(Timeout.InfiniteTimeSpan, token); + } + finally + { + cancelled.SetResult(); + } + + throw new InvalidOperationException("Unreachable"); + })); + await using var connection = new ProtocolTestConnection(registry); + await connection.ReadyAsync(); + await connection.SendAsync(""" + {"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"test.wait","arguments":{"text":"go"}}} + """); + await started.Task.WaitAsync(TimeSpan.FromSeconds(5)); + if (!eof) + { + await connection.CancelAsync(); + } + + await connection.AssertNoMoreResponsesAsync(); + Assert.True(cancelled.Task.IsCompletedSuccessfully); + } + + [Fact] + public async Task ActiveRequestBoundRejectsNewWorkButStillReadsCancellation() + { + var started = 0; + var allStarted = Signal(); + var registry = new McpToolRegistry(); + registry.Register(new McpToolDefinition( + "test.wait", "Synthetic admission bound.", async (_, token) => + { + if (Interlocked.Increment(ref started) == JsonRpcDispatcher.MaxActiveRequests) + { + allStarted.SetResult(); + } + + await Task.Delay(Timeout.InfiniteTimeSpan, token); + throw new InvalidOperationException("Unreachable"); + })); + await using var connection = new ProtocolTestConnection(registry); + await connection.ReadyAsync(); + for (var id = 0; id < JsonRpcDispatcher.MaxActiveRequests; id++) + { + await connection.SendAsync($$$$""" + {"jsonrpc":"2.0","id":{{{{id}}}},"method":"tools/call","params":{"name":"test.wait","arguments":{"text":"go"}}} + """); + } + + await allStarted.Task.WaitAsync(TimeSpan.FromSeconds(5)); + await connection.SendAsync("""{"jsonrpc":"2.0","id":"overflow","method":"ping"}"""); + Assert.Equal(-32000, ErrorCode(await connection.ReadAsync())); + await connection.SendAsync("""{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":0}}"""); + await connection.AssertNoMoreResponsesAsync(); + Assert.Equal(JsonRpcDispatcher.MaxActiveRequests, started); + } + + [Fact] + public async Task OverlappingHandlersProduceSeparateValidResponses() + { + const int count = 25; + var release = Signal(); + var allStarted = Signal(); + var started = 0; + var registry = new McpToolRegistry(); + registry.Register(new McpToolDefinition( + "test.overlap", "Synthetic overlapping handler.", async (input, token) => + { + if (Interlocked.Increment(ref started) == count) + { + allStarted.SetResult(); + } + + await release.Task.WaitAsync(token); + return new(new(input.Text, "complete")); + })); + await using var connection = new ProtocolTestConnection(registry); + await connection.ReadyAsync(); + for (var id = 0; id < count; id++) + { + await connection.SendAsync($$$$""" + {"jsonrpc":"2.0","id":{{{{id}}}},"method":"tools/call","params":{"name":"test.overlap","arguments":{"text":"音楽\nline"}}} + """); + } + + await allStarted.Task.WaitAsync(TimeSpan.FromSeconds(5)); + release.SetResult(); + var ids = new List(); + for (var i = 0; i < count; i++) + { + var response = await connection.ReadAsync(); + ids.Add(response.GetProperty("id").GetInt32()); + Assert.Equal("音楽\nline", response.GetProperty("result").GetProperty("structuredContent").GetProperty("text").GetString()); + } + + Assert.Equal(Enumerable.Range(0, count), ids.Order()); + await connection.AssertNoMoreResponsesAsync(); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task ActualIoFailureIsNotHiddenAsSuccessfulShutdown(bool writing) + { + using var failing = new FailingStream(); + using var input = new MemoryStream(Encoding.UTF8.GetBytes("""{"jsonrpc":"2.0","id":1,"method":"ping"}""" + "\n")); + using var transport = new StdioTransport(writing ? input : failing, writing ? failing : Stream.Null); + var dispatcher = new JsonRpcDispatcher(transport, new McpSession(new()), TextWriter.Null); + await Assert.ThrowsAsync(() => dispatcher.RunAsync().WaitAsync(TimeSpan.FromSeconds(5))); + } + + [Fact] + public async Task ResponseSerializationFailureIsAnInternalRequestErrorNotATransportFailure() + { + var registry = new McpToolRegistry(); + registry.Register(new UnserializableTool()); + await using var connection = new ProtocolTestConnection(registry); + await connection.ReadyAsync(); + await connection.SendAsync("""{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"test.bad-result"}}"""); + Assert.Equal(-32603, ErrorCode(await connection.ReadAsync())); + await connection.SendAsync("""{"jsonrpc":"2.0","id":2,"method":"ping"}"""); + Assert.Equal(2, (await connection.ReadAsync()).GetProperty("id").GetInt32()); + Assert.Contains("Request handler failed:", connection.Diagnostics.ToString()); + await connection.AssertNoMoreResponsesAsync(); + } + + private static int ErrorCode(JsonElement response) + { + Assert.False(response.TryGetProperty("result", out _)); + return response.GetProperty("error").GetProperty("code").GetInt32(); + } + + private static TaskCompletionSource Signal() => new(TaskCreationOptions.RunContinuationsAsynchronously); + + private sealed class UnserializableTool : McpToolDefinition + { + public override object Descriptor => new { name = Name }; + public override string Name => "test.bad-result"; + public override Task InvokeAsync(JsonElement arguments, CancellationToken cancellationToken) => + Task.FromResult(new { unsupported = typeof(string) }); + } + + private sealed class FailingStream : MemoryStream + { + public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) => + ValueTask.FromException(new IOException("Synthetic read failure")); + public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) => + ValueTask.FromException(new IOException("Synthetic write failure")); + } +} diff --git a/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Protocol/McpSessionTests.cs b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Protocol/McpSessionTests.cs new file mode 100644 index 0000000..412919d --- /dev/null +++ b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Protocol/McpSessionTests.cs @@ -0,0 +1,202 @@ +using System.Text.Json; +using GAJ3T.MusicGen.RiffGrooveBuilder.Server.Protocol; +using GAJ3T.MusicGen.RiffGrooveBuilder.Server.Tools; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests.Protocol; + +public sealed class McpSessionTests +{ + internal sealed record EchoInput(string Text); + internal sealed record EchoOutput(string Text, string Status); + + internal static McpToolDefinition EchoTool() => + new("test.echo", "Synthetic test-only echo.", (input, _) => + Task.FromResult(new McpToolOutcome( + new(input.Text, input.Text == "expected failure" ? "failed" : "complete"), + IsError: input.Text == "expected failure")), + input => + { + if (string.IsNullOrWhiteSpace(input.Text)) + { + throw new McpToolInputException("text must be nonempty"); + } + }); + + internal static async Task ReadySessionAsync(McpToolRegistry? registry = null) + { + var session = new McpSession(registry ?? new()); + await session.HandleRequestAsync("initialize", ProtocolTestConnection.Json(ProtocolTestConnection.Initialization), default); + session.HandleNotification("notifications/initialized", null); + return session; + } + + private static async Task RequestAsync(McpSession session, string method, string? parameters = null) => + JsonSerializer.SerializeToElement(await session.HandleRequestAsync( + method, parameters is null ? null : ProtocolTestConnection.Json(parameters), default)); + + [Theory] + [InlineData("2025-11-25")] + [InlineData("2024-11-05")] + [InlineData("future-unknown")] + public async Task InitializesAndNegotiatesOnlyTheImplementedVersion(string requested) + { + var session = new McpSession(new()); + var result = await RequestAsync(session, "initialize", + ProtocolTestConnection.Initialization.Replace("2025-11-25", requested, StringComparison.Ordinal)); + Assert.Equal("2025-11-25", result.GetProperty("protocolVersion").GetString()); + Assert.Equal("GAJ3T.MusicGen.RiffGrooveBuilder", result.GetProperty("serverInfo").GetProperty("name").GetString()); + Assert.False(string.IsNullOrEmpty(result.GetProperty("serverInfo").GetProperty("version").GetString())); + var capability = Assert.Single(result.GetProperty("capabilities").EnumerateObject()); + Assert.Equal("tools", capability.Name); + Assert.False(capability.Value.GetProperty("listChanged").GetBoolean()); + session.HandleNotification("notifications/initialized", null); + Assert.Empty((await RequestAsync(session, "tools/list")).GetProperty("tools").EnumerateArray()); + } + + [Theory] + [InlineData(null)] + [InlineData("{}")] + [InlineData("[]")] + [InlineData("""{"protocolVersion":42,"capabilities":{},"clientInfo":{"name":"x","version":"1"}}""")] + [InlineData("""{"protocolVersion":"x","capabilities":[],"clientInfo":{"name":"x","version":"1"}}""")] + [InlineData("""{"protocolVersion":"x","capabilities":{},"clientInfo":{"name":"x"}}""")] + [InlineData("""{"protocolVersion":"x","capabilities":{},"clientInfo":{"name":1,"version":"1"}}""")] + [InlineData("""{"protocolVersion":"x","capabilities":{},"clientInfo":{"name":"x","version":"1","title":false}}""")] + [InlineData("""{"protocolVersion":"x","capabilities":{"roots":{"listChanged":"yes"}},"clientInfo":{"name":"x","version":"1"}}""")] + [InlineData("""{"protocolVersion":"x","capabilities":{"sampling":{"tools":false}},"clientInfo":{"name":"x","version":"1"}}""")] + [InlineData("""{"protocolVersion":"x","capabilities":{"elicitation":{"url":null}},"clientInfo":{"name":"x","version":"1"}}""")] + [InlineData("""{"protocolVersion":"x","capabilities":{"tasks":{"requests":{"sampling":{"createMessage":false}}}},"clientInfo":{"name":"x","version":"1"}}""")] + [InlineData("""{"protocolVersion":"x","capabilities":{},"clientInfo":{"name":"x","version":"1","icons":[{"src":"x","sizes":[42]}]}}""")] + [InlineData("""{"protocolVersion":"x","capabilities":{},"clientInfo":{"name":"x","version":"1","icons":[{"src":"x","theme":"invalid"}]}}""")] + [InlineData("""{"protocolVersion":"x","capabilities":{"experimental":{"extension":false}},"clientInfo":{"name":"x","version":"1"}}""")] + [InlineData("""{"protocolVersion":"x","capabilities":{},"clientInfo":{"name":"x","version":"1"},"_meta":{"progressToken":true}}""")] + public async Task InvalidInitializationDoesNotAdvanceTheSession(string? parameters) + { + var session = new McpSession(new()); + var error = await Assert.ThrowsAsync(() => RequestAsync(session, "initialize", parameters)); + Assert.Equal(-32602, error.Code); + Assert.True((await RequestAsync(session, "initialize", ProtocolTestConnection.Initialization)).TryGetProperty("serverInfo", out _)); + } + + [Fact] + public async Task AcceptsOptionalClientMetadataAndCapabilitiesWithoutAdvertisingTheirFeatures() + { + var session = new McpSession(new()); + var result = await RequestAsync(session, "initialize", """ + {"protocolVersion":"2025-11-25","capabilities":{"roots":{"listChanged":true}, + "sampling":{"tools":{},"context":{}},"elicitation":{"form":{},"url":{}}, + "tasks":{"list":{},"cancel":{},"requests":{"sampling":{"createMessage":{}},"elicitation":{"create":{}}}}, + "custom.extension":{},"experimental":{"extension":{}}}, + "clientInfo":{"name":"client","version":"1","description":"desc","title":"Client", + "websiteUrl":"https://example.test","icons":[{"src":"data:image/png;base64,","sizes":["any"],"theme":"dark"}]}, + "_meta":{"custom/key":"value"}} + """); + Assert.Single(result.GetProperty("capabilities").EnumerateObject()); + } + + [Fact] + public async Task RequiresTheWholeHandshakeRejectsRepeatsAndAllowsPingAtEveryStage() + { + var session = new McpSession(new()); + Assert.Equal("{}", (await RequestAsync(session, "ping")).GetRawText()); + Assert.Throws(() => session.HandleNotification("notifications/initialized", null)); + Assert.Equal(-32002, (await Assert.ThrowsAsync(() => RequestAsync(session, "tools/list"))).Code); + await RequestAsync(session, "initialize", ProtocolTestConnection.Initialization); + Assert.Equal("{}", (await RequestAsync(session, "ping", """{"_meta":{}}""")).GetRawText()); + Assert.Equal(-32002, (await Assert.ThrowsAsync(() => RequestAsync(session, "tools/list"))).Code); + Assert.Equal(-32002, (await Assert.ThrowsAsync(() => RequestAsync(session, "initialize", ProtocolTestConnection.Initialization))).Code); + Assert.Throws(() => session.HandleNotification("notifications/initialized", ProtocolTestConnection.Json("""{"bad":true}"""))); + session.HandleNotification("notifications/initialized", ProtocolTestConnection.Json("""{"_meta":{}}""")); + Assert.Empty((await RequestAsync(session, "tools/list")).GetProperty("tools").EnumerateArray()); + Assert.Equal("{}", (await RequestAsync(session, "ping", "{}")).GetRawText()); + Assert.Throws(() => session.HandleNotification("notifications/initialized", null)); + Assert.Equal(-32002, (await Assert.ThrowsAsync(() => RequestAsync(session, "initialize", ProtocolTestConnection.Initialization))).Code); + } + + [Theory] + [InlineData("ping", "null")] + [InlineData("ping", "[]")] + [InlineData("ping", """{"extra":1}""")] + [InlineData("ping", """{"_meta":42}""")] + [InlineData("ping", """{"_meta":{"progressToken":null}}""")] + [InlineData("tools/list", """{"cursor":"not-issued"}""")] + [InlineData("tools/list", """{"cursor":null}""")] + [InlineData("tools/call", null)] + [InlineData("tools/call", "{}")] + [InlineData("tools/call", """{"name":12}""")] + [InlineData("tools/call", """{"name":"unknown"}""")] + [InlineData("tools/call", """{"name":"unknown","arguments":[]}""")] + [InlineData("tools/call", """{"name":"unknown","arguments":{},"task":{"ttl":1000}}""")] + [InlineData("tools/call", """{"name":"a","name":"b"}""")] + public async Task InvalidMethodAndToolSelectionParametersAreProtocolErrors(string method, string? parameters) + { + var session = await ReadySessionAsync(); + Assert.Equal(-32602, (await Assert.ThrowsAsync(() => RequestAsync(session, method, parameters))).Code); + } + + [Fact] + public async Task RegistryIsEmptyInProductionAndIsFrozenPerSession() + { + var registry = new McpToolRegistry(); + Assert.Empty(registry.List()); + Assert.Null(registry.Find("generate_project")); + registry.Register(EchoTool()); + Assert.Throws(() => registry.Register(EchoTool())); + var session = await ReadySessionAsync(registry); + Assert.Throws(() => registry.Register(EchoTool())); + Assert.Null(registry.Find("TEST.ECHO")); + Assert.Equal(-32601, (await Assert.ThrowsAsync(() => RequestAsync(session, "shutdown"))).Code); + } + + [Theory] + [InlineData("écho\n🎸", false)] + [InlineData("expected failure", true)] + public async Task ToolSchemasComeFromTypedContractsAndContentMatchesStructuredResult(string text, bool isError) + { + var registry = new McpToolRegistry(); + registry.Register(EchoTool()); + var session = await ReadySessionAsync(registry); + var tool = Assert.Single((await RequestAsync(session, "tools/list")).GetProperty("tools").EnumerateArray()); + Assert.Equal("test.echo", tool.GetProperty("name").GetString()); + foreach (var schemaName in new[] { "inputSchema", "outputSchema" }) + { + var schema = tool.GetProperty(schemaName); + Assert.Equal("object", schema.GetProperty("type").GetString()); + Assert.False(schema.GetProperty("additionalProperties").GetBoolean()); + Assert.Contains(schema.GetProperty("required").EnumerateArray(), field => field.GetString() == "text"); + Assert.Equal("string", schema.GetProperty("properties").GetProperty("text").GetProperty("type").GetString()); + } + + var result = await RequestAsync(session, "tools/call", JsonSerializer.Serialize(new + { + name = "test.echo", arguments = new { text } + })); + Assert.Equal(isError, result.GetProperty("isError").GetBoolean()); + var structured = result.GetProperty("structuredContent"); + Assert.Equal(text, structured.GetProperty("text").GetString()); + Assert.Equal(isError ? "failed" : "complete", structured.GetProperty("status").GetString()); + var content = Assert.Single(result.GetProperty("content").EnumerateArray()); + Assert.Equal("text", content.GetProperty("type").GetString()); + Assert.Equal(structured.GetRawText(), content.GetProperty("text").GetString()); + var schemaProperties = tool.GetProperty("outputSchema").GetProperty("properties"); + Assert.Equal(schemaProperties.EnumerateObject().Select(p => p.Name).Order(), + structured.EnumerateObject().Select(p => p.Name).Order()); + } + + [Theory] + [InlineData("{}")] + [InlineData("""{"text":null}""")] + [InlineData("""{"text":123}""")] + [InlineData("""{"text":"valid","extra":true}""")] + [InlineData("""{"text":" "}""")] + [InlineData("""{"text":"one","text":"two"}""")] + public async Task TypedAndSemanticValidationFailBeforeTheHandler(string arguments) + { + var registry = new McpToolRegistry(); + registry.Register(EchoTool()); + var session = await ReadySessionAsync(registry); + var error = await Assert.ThrowsAsync(() => RequestAsync(session, "tools/call", + $$"""{"name":"test.echo","arguments":{{arguments}}}""")); + Assert.Equal(-32602, error.Code); + } +} diff --git a/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Protocol/MusicGenToolsTests.cs b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Protocol/MusicGenToolsTests.cs new file mode 100644 index 0000000..afcac01 --- /dev/null +++ b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Protocol/MusicGenToolsTests.cs @@ -0,0 +1,323 @@ +using System.Text.Json; +using System.Text.Json.Nodes; +using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Generation; +using GAJ3T.MusicGen.RiffGrooveBuilder.Generation; +using GAJ3T.MusicGen.RiffGrooveBuilder.Generation.Profiles; +using GAJ3T.MusicGen.RiffGrooveBuilder.Server.Protocol; +using GAJ3T.MusicGen.RiffGrooveBuilder.Server.Tools; +using GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests.Generation; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests.Protocol; + +public sealed class MusicGenToolsTests : IDisposable +{ + private readonly string directory = Path.Combine(AppContext.BaseDirectory, "music-tools-" + Guid.NewGuid().ToString("N")); + + private JsonElement Arguments() => JsonSerializer.SerializeToElement(new + { + description = "palm-muted eighth-note lead", outputDirectory = directory, projectName = "song", + formats = new[] { "mid" }, profiles = new { lead = GenerationServiceTests.Aglp } + }); + + [Fact] + public void FactoryRegistersExactlyTwoProductionToolsWithExplicitStrictSchemas() + { + var registry = MusicGenTools.CreateRegistry(); + Assert.Equal(new[] { "generate_project", "list_instrument_profiles" }, registry.List() + .Select(t => JsonSerializer.SerializeToElement(t).GetProperty("name").GetString())); + Assert.Empty(new McpToolRegistry().List()); + var descriptor = JsonSerializer.SerializeToElement(registry.Find("generate_project")!.Descriptor); + var input = descriptor.GetProperty("inputSchema"); + Assert.False(input.GetProperty("additionalProperties").GetBoolean()); + Assert.Equal(new[] { "description", "outputDirectory", "projectName" }, input.GetProperty("required").EnumerateArray().Select(e => e.GetString())); + var properties = input.GetProperty("properties"); + Assert.Equal(1, properties.GetProperty("formats").GetProperty("minItems").GetInt32()); + Assert.True(properties.GetProperty("formats").GetProperty("uniqueItems").GetBoolean()); + Assert.Equal(new[] { "agp", "sdp", "mid" }, properties.GetProperty("formats").GetProperty("items").GetProperty("enum").EnumerateArray().Select(e => e.GetString())); + Assert.True(properties.GetProperty("fallbackToMidi").GetProperty("default").GetBoolean()); + Assert.False(properties.GetProperty("profiles").GetProperty("additionalProperties").GetBoolean()); + SchemaAssert.Matches(input, Arguments()); + var output = descriptor.GetProperty("outputSchema"); + Assert.Equal(new[] { "complete", "fallback", "failed" }, output.GetProperty("properties").GetProperty("status").GetProperty("enum").EnumerateArray().Select(e => e.GetString())); + Assert.True(output.TryGetProperty("allOf", out _)); + } + + [Theory] + [InlineData("{}")] + [InlineData("""{"role":"lead"}""")] + [InlineData("""{"role":"bass"}""")] + [InlineData("""{"role":"drums"}""")] + public async Task DiscoverySerializationMatchesAdvertisedOutputAndText(string json) + { + var tool = MusicGenTools.CreateRegistry().Find("list_instrument_profiles")!; + var result = await tool.InvokeAsync(ProtocolTestConnection.Json(json), CancellationToken.None); + AssertOutput(tool, result, false); + var structured = JsonSerializer.SerializeToElement(result).GetProperty("structuredContent"); + var filter = ProtocolTestConnection.Json(json); + var role = filter.TryGetProperty("role", out var supplied) ? supplied.GetString() : null; + Assert.Equal(role switch { "lead" => 4, "bass" => 1, "drums" => 0, _ => 5 }, + structured.GetProperty("profiles").GetArrayLength()); + if (role == "bass") + { + var bass = Assert.Single(structured.GetProperty("profiles").EnumerateArray()); + Assert.Equal(GenerationServiceTests.Abj, bass.GetProperty("id").GetString()); + Assert.Equal("sustain", Assert.Single(bass.GetProperty("articulations").EnumerateArray()) + .GetProperty("articulation").GetString()); + Assert.Equal(1, bass.GetProperty("channel").GetInt32()); + } + } + + [Theory] + [InlineData("""{"role":null}""")] + [InlineData("""{"role":0}""")] + [InlineData("""{"role":"Lead"}""")] + [InlineData("""{"role":"LEAD"}""")] + [InlineData("""{"role":"other"}""")] + [InlineData("""{"unknown":1}""")] + [InlineData("""{"role":"lead","role":"bass"}""")] + [InlineData("null")] + [InlineData("[]")] + public async Task DiscoveryRejectsValuesNotInItsInputSchema(string json) + { + var error = await Assert.ThrowsAsync(() => MusicGenTools.CreateRegistry() + .Find("list_instrument_profiles")!.InvokeAsync(ProtocolTestConnection.Json(json), CancellationToken.None)); + Assert.Equal(-32602, error.Code); + } + + [Theory] + [InlineData("description", null)] + [InlineData("description", "null")] + [InlineData("description", "1")] + [InlineData("description", "\"\"")] + [InlineData("outputDirectory", null)] + [InlineData("outputDirectory", "null")] + [InlineData("outputDirectory", "\"\"")] + [InlineData("projectName", null)] + [InlineData("projectName", "null")] + [InlineData("projectName", "\"\"")] + [InlineData("formats", "[]")] + [InlineData("formats", "null")] + [InlineData("formats", """["mid","mid"]""")] + [InlineData("formats", """["Mid"]""")] + [InlineData("formats", """["MID"]""")] + [InlineData("formats", """["mp3"]""")] + [InlineData("formats", "[0]")] + [InlineData("profiles", "null")] + [InlineData("profiles", "[]")] + [InlineData("profiles", """{"lead":null}""")] + [InlineData("profiles", """{"lead":""}""")] + [InlineData("profiles", """{"lead":123}""")] + [InlineData("profiles", """{"guitar":"x"}""")] + [InlineData("profiles", """{"lead":"one","lead":"two"}""")] + [InlineData("fallbackToMidi", "null")] + [InlineData("fallbackToMidi", "\"true\"")] + [InlineData("unknown", "true")] + public async Task GenerationRejectsMissingNullUnknownEnumAndArrayContractViolations(string field, string? replacement) + { + var arguments = JsonNode.Parse(Arguments().GetRawText())!.AsObject(); + if (replacement is null) arguments.Remove(field); + else arguments[field] = JsonNode.Parse(replacement); + var tool = MusicGenTools.CreateRegistry().Find("generate_project")!; + var error = await Assert.ThrowsAsync(() => tool.InvokeAsync( + ProtocolTestConnection.Json(arguments.ToJsonString()), CancellationToken.None)); + Assert.Equal(-32602, error.Code); + Assert.False(Directory.Exists(directory)); + } + + [Fact] + public async Task DuplicateRootPropertyAndExcessiveDescriptionAreRejected() + { + var tool = MusicGenTools.CreateRegistry().Find("generate_project")!; + var duplicate = Arguments().GetRawText().Replace("\"description\":", "\"description\":\"lead\",\"description\":", StringComparison.Ordinal); + Assert.Equal(-32602, (await Assert.ThrowsAsync(() => tool.InvokeAsync(ProtocolTestConnection.Json(duplicate), CancellationToken.None))).Code); + var arguments = JsonNode.Parse(Arguments().GetRawText())!; + arguments["description"] = new string('x', 16385); + Assert.Equal(-32602, (await Assert.ThrowsAsync(() => tool.InvokeAsync( + ProtocolTestConnection.Json(arguments.ToJsonString()), CancellationToken.None))).Code); + } + + [Theory] + [InlineData("complete")] + [InlineData("fallback")] + [InlineData("failed")] + [InlineData("parse-failed")] + public async Task EveryGenerationOutcomeMatchesItsSchemaAndContent(string status) + { + var arguments = JsonNode.Parse(Arguments().GetRawText())!; + if (status == "fallback") arguments["formats"] = new JsonArray("agp", "mid"); + if (status == "failed") arguments.AsObject().Remove("profiles"); + if (status == "parse-failed") arguments["description"] = "unsupported request"; + var tool = MusicGenTools.CreateRegistry().Find("generate_project")!; + var response = await tool.InvokeAsync(ProtocolTestConnection.Json(arguments.ToJsonString()), CancellationToken.None); + var structured = AssertOutput(tool, response, status is "failed" or "parse-failed"); + Assert.Equal(status == "parse-failed" ? "failed" : status, structured.GetProperty("status").GetString()); + if (status == "parse-failed") + { + Assert.Equal(JsonValueKind.Null, structured.GetProperty("timing").ValueKind); + Assert.Equal(JsonValueKind.Null, structured.GetProperty("interpretedComposition").ValueKind); + } + else if (status == "complete") + { + var invalid = JsonNode.Parse(structured.GetRawText())!; + invalid["timing"] = null; + Assert.ThrowsAny(() => SchemaAssert.Matches( + JsonSerializer.SerializeToElement(tool.Descriptor).GetProperty("outputSchema"), + ProtocolTestConnection.Json(invalid.ToJsonString()))); + } + } + + [Theory] + [InlineData("unknown")] + [InlineData("numeric-enum")] + [InlineData("missing-required")] + [InlineData("zero-bytes")] + public async Task OutputSchemaRejectsIncorrectSerializedShapes(string mutation) + { + var tool = MusicGenTools.CreateRegistry().Find("generate_project")!; + var response = JsonSerializer.SerializeToElement(await tool.InvokeAsync(Arguments(), CancellationToken.None)); + var invalid = JsonNode.Parse(response.GetProperty("structuredContent").GetRawText())!.AsObject(); + switch (mutation) + { + case "unknown": invalid["extra"] = true; break; + case "numeric-enum": invalid["status"] = 0; break; + case "missing-required": invalid.Remove("timing"); break; + case "zero-bytes": invalid["artifacts"]![0]!["byteCount"] = 0; break; + } + Assert.ThrowsAny(() => SchemaAssert.Matches( + JsonSerializer.SerializeToElement(tool.Descriptor).GetProperty("outputSchema"), + ProtocolTestConnection.Json(invalid.ToJsonString()))); + } + + [Fact] + public async Task OmittedFormatsAndFallbackUseDocumentedDefaultsButNoProfileDefault() + { + var arguments = JsonNode.Parse(Arguments().GetRawText())!; + arguments.AsObject().Remove("formats"); + var tool = MusicGenTools.CreateRegistry().Find("generate_project")!; + var structured = AssertOutput(tool, await tool.InvokeAsync( + ProtocolTestConnection.Json(arguments.ToJsonString()), CancellationToken.None), false); + Assert.Equal("fallback", structured.GetProperty("status").GetString()); + Assert.Equal(2, structured.GetProperty("targets").GetArrayLength()); + Assert.Single(structured.GetProperty("artifacts").EnumerateArray()); + } + + [Fact] + public async Task PingAndCancellationStayResponsiveDuringSynchronousGenerationWork() + { + var started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var cancelled = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var service = new GenerationService(InstrumentProfileCatalog.LoadEmbedded(), token => + { + started.SetResult(); + if (!token.WaitHandle.WaitOne(TimeSpan.FromSeconds(5))) throw new TimeoutException("Transport reader was blocked."); + cancelled.SetResult(); + token.ThrowIfCancellationRequested(); + }); + await using var connection = new ProtocolTestConnection(MusicGenTools.CreateRegistry(service)); + await connection.ReadyAsync(); + await connection.SendAsync(Call("generate")); + await started.Task.WaitAsync(TimeSpan.FromSeconds(5)); + await connection.SendAsync("""{"jsonrpc":"2.0","id":"ping","method":"ping"}"""); + Assert.Equal("ping", (await connection.ReadAsync()).GetProperty("id").GetString()); + await connection.SendAsync("""{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":"generate"}}"""); + await cancelled.Task.WaitAsync(TimeSpan.FromSeconds(5)); + await connection.SendAsync("""{"jsonrpc":"2.0","id":"after-cancel","method":"ping"}"""); + Assert.Equal("after-cancel", (await connection.ReadAsync()).GetProperty("id").GetString()); + await connection.AssertNoMoreResponsesAsync(); + Assert.False(Directory.Exists(directory)); + Assert.Empty(connection.Diagnostics.ToString()); + } + + [Fact] + public async Task UnexpectedGenerationFailureUsesExistingLoggedInternalErrorBoundary() + { + var service = new GenerationService(InstrumentProfileCatalog.LoadEmbedded(), _ => throw new InvalidOperationException("test unexpected generation detail")); + await using var connection = new ProtocolTestConnection(MusicGenTools.CreateRegistry(service)); + await connection.ReadyAsync(); + await connection.SendAsync(Call("failure")); + var response = await connection.ReadAsync(); + Assert.Equal(-32603, response.GetProperty("error").GetProperty("code").GetInt32()); + Assert.DoesNotContain("unexpected generation detail", response.GetRawText()); + Assert.Contains("unexpected generation detail", connection.Diagnostics.ToString()); + Assert.False(Directory.Exists(directory)); + await connection.AssertNoMoreResponsesAsync(); + } + + private static JsonElement AssertOutput(McpToolDefinition tool, object response, bool isError) + { + var root = JsonSerializer.SerializeToElement(response); + Assert.Equal(isError, root.GetProperty("isError").GetBoolean()); + var structured = root.GetProperty("structuredContent"); + var text = Assert.Single(root.GetProperty("content").EnumerateArray()); + Assert.Equal("text", text.GetProperty("type").GetString()); + Assert.Equal(structured.GetRawText(), text.GetProperty("text").GetString()); + SchemaAssert.Matches(JsonSerializer.SerializeToElement(tool.Descriptor).GetProperty("outputSchema"), structured); + return structured; + } + + private string Call(string id) => JsonSerializer.Serialize(new + { + jsonrpc = "2.0", id, method = "tools/call", @params = new { name = "generate_project", arguments = Arguments() } + }); + + public void Dispose() + { + if (Directory.Exists(directory)) Directory.Delete(directory, true); + } +} + +// Covers the keywords emitted by the typed contracts, not a runtime schema engine. +internal static class SchemaAssert +{ + internal static void Matches(JsonElement schema, JsonElement value) + { + if (schema.TryGetProperty("type", out var type)) + { + var actual = value.ValueKind switch + { + JsonValueKind.Object => "object", JsonValueKind.Array => "array", JsonValueKind.String => "string", + JsonValueKind.Number => value.TryGetInt64(out _) ? "integer" : "number", + JsonValueKind.True or JsonValueKind.False => "boolean", _ => "null" + }; + var types = type.ValueKind == JsonValueKind.Array ? type.EnumerateArray().Select(t => t.GetString()).ToArray() : [type.GetString()]; + Assert.True(types.Contains(actual) || actual == "integer" && types.Contains("number"), $"Expected {type}, got {value}."); + } + if (schema.TryGetProperty("enum", out var enums)) + Assert.Contains(enums.EnumerateArray(), e => JsonElement.DeepEquals(e, value)); + if (value.ValueKind == JsonValueKind.Number && schema.TryGetProperty("minimum", out var minimum)) + Assert.True(value.GetDouble() >= minimum.GetDouble()); + if (value.ValueKind == JsonValueKind.Object) + { + if (schema.TryGetProperty("required", out var required)) + foreach (var field in required.EnumerateArray()) Assert.True(value.TryGetProperty(field.GetString()!, out _), field.GetString()); + if (schema.TryGetProperty("properties", out var properties)) + foreach (var property in value.EnumerateObject()) + { + if (properties.TryGetProperty(property.Name, out var definition)) Matches(definition, property.Value); + else if (schema.TryGetProperty("additionalProperties", out var additional)) Assert.NotEqual(JsonValueKind.False, additional.ValueKind); + } + } + if (value.ValueKind == JsonValueKind.Array) + { + if (schema.TryGetProperty("minItems", out var min)) Assert.True(value.GetArrayLength() >= min.GetInt32()); + if (schema.TryGetProperty("maxItems", out var max)) Assert.True(value.GetArrayLength() <= max.GetInt32()); + if (schema.TryGetProperty("items", out var items)) + foreach (var item in value.EnumerateArray()) Matches(items, item); + if (schema.TryGetProperty("uniqueItems", out var unique) && unique.GetBoolean()) + Assert.Equal(value.GetArrayLength(), value.EnumerateArray().Select(e => e.GetRawText()).Distinct().Count()); + } + if (value.ValueKind == JsonValueKind.String) + { + if (schema.TryGetProperty("minLength", out var min)) Assert.True(value.GetString()!.Length >= min.GetInt32()); + if (schema.TryGetProperty("maxLength", out var max)) Assert.True(value.GetString()!.Length <= max.GetInt32()); + } + if (schema.TryGetProperty("allOf", out var all)) + foreach (var child in all.EnumerateArray()) Matches(child, value); + if (schema.TryGetProperty("if", out var condition)) + { + var matches = true; + try { Matches(condition, value); } catch (Xunit.Sdk.XunitException) { matches = false; } + if (schema.TryGetProperty(matches ? "then" : "else", out var branch)) Matches(branch, value); + } + } +} diff --git a/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Protocol/ProtocolTestConnection.cs b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Protocol/ProtocolTestConnection.cs new file mode 100644 index 0000000..a845733 --- /dev/null +++ b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Protocol/ProtocolTestConnection.cs @@ -0,0 +1,131 @@ +using System.Text; +using System.Text.Json; +using System.Threading.Channels; +using GAJ3T.MusicGen.RiffGrooveBuilder.Server.Protocol; +using GAJ3T.MusicGen.RiffGrooveBuilder.Server.Tools; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests.Protocol; + +internal sealed class ProtocolTestConnection : IAsyncDisposable +{ + public const string Initialization = """ + {"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"unit-tests","version":"1"}} + """; + private readonly ChannelStream _input = new(); + private readonly ChannelStream _output = new(); + private readonly CancellationTokenSource _stopping = new(); + private readonly StdioTransport _transport; + private readonly StreamReader _reader; + private readonly Task _running; + public StringWriter Diagnostics { get; } = new(); + + public ProtocolTestConnection(McpToolRegistry? registry = null) + { + _transport = new(_input, _output); + _reader = new(_output, new UTF8Encoding(false, true), leaveOpen: true); + _running = new JsonRpcDispatcher(_transport, new McpSession(registry ?? new()), Diagnostics) + .RunAsync(_stopping.Token); + } + + public static JsonElement Json(string value) + { + using var document = JsonDocument.Parse(value); + return document.RootElement.Clone(); + } + + public async Task SendAsync(string json) => + await _input.WriteAsync(Encoding.UTF8.GetBytes(json + "\n")); + + public async Task ReadAsync() + { + var line = await _reader.ReadLineAsync().WaitAsync(TimeSpan.FromSeconds(5)); + Assert.NotNull(line); + var result = Json(line); + Assert.Equal("2.0", result.GetProperty("jsonrpc").GetString()); + return result; + } + + public async Task ReadyAsync() + { + await SendAsync($$"""{"jsonrpc":"2.0","id":"init","method":"initialize","params":{{Initialization}}}"""); + Assert.True((await ReadAsync()).TryGetProperty("result", out _)); + await SendAsync("""{"jsonrpc":"2.0","method":"notifications/initialized"}"""); + } + + public async Task CompleteAsync() + { + _input.Complete(); + await _running.WaitAsync(TimeSpan.FromSeconds(5)); + _output.Complete(); + } + + public async Task CancelAsync() + { + _stopping.Cancel(); + await _running.WaitAsync(TimeSpan.FromSeconds(5)); + _output.Complete(); + } + + public async Task AssertNoMoreResponsesAsync() + { + await CompleteAsync(); + Assert.Null(await _reader.ReadLineAsync().WaitAsync(TimeSpan.FromSeconds(5))); + } + + public async ValueTask DisposeAsync() + { + _stopping.Cancel(); + _input.Complete(); + await _running.WaitAsync(TimeSpan.FromSeconds(5)); + _output.Complete(); + _reader.Dispose(); + _transport.Dispose(); + _stopping.Dispose(); + _input.Dispose(); + _output.Dispose(); + Diagnostics.Dispose(); + } +} + +internal sealed class ChannelStream : Stream +{ + private readonly Channel _chunks = Channel.CreateUnbounded(); + private byte[]? _current; + private int _offset; + + public void Complete() => _chunks.Writer.TryComplete(); + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => true; + public override long Length => throw new NotSupportedException(); + public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } + public override void Flush() { } + public override Task FlushAsync(CancellationToken cancellationToken) => Task.CompletedTask; + public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => + _chunks.Writer.TryWrite(buffer.AsSpan(offset, count).ToArray()); + + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + if (_current is null || _offset == _current.Length) + { + if (!await _chunks.Reader.WaitToReadAsync(cancellationToken)) + { + return 0; + } + + _current = await _chunks.Reader.ReadAsync(cancellationToken); + _offset = 0; + } + + var count = Math.Min(buffer.Length, _current.Length - _offset); + _current.AsMemory(_offset, count).CopyTo(buffer); + _offset += count; + return count; + } + + public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) => + _chunks.Writer.WriteAsync(buffer.ToArray(), cancellationToken); +} diff --git a/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Protocol/StdioTransportTests.cs b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Protocol/StdioTransportTests.cs new file mode 100644 index 0000000..4fc4bbb --- /dev/null +++ b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/Protocol/StdioTransportTests.cs @@ -0,0 +1,152 @@ +using System.Text; +using System.Text.Json; +using GAJ3T.MusicGen.RiffGrooveBuilder.Server.Protocol; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests.Protocol; + +public sealed class StdioTransportTests +{ + [Theory] + [InlineData("\n")] + [InlineData("\r\n")] + public async Task ReadsUtf8FramesAndDoesNotSplitEscapedNewlines(string delimiter) + { + const string json = """{"text":"音楽 café 🎸\nsecond line"}"""; + using var input = new MemoryStream(Encoding.UTF8.GetBytes(json + delimiter + "{}" + delimiter)); + using var transport = new StdioTransport(input, Stream.Null); + Assert.Equal(json, (await transport.ReadFrameAsync())?.Json); + Assert.Equal("{}", (await transport.ReadFrameAsync())?.Json); + Assert.Null(await transport.ReadFrameAsync()); + } + + [Fact] + public async Task EmptyEofHasNoFrameButEmptyLinesAreFrames() + { + using var empty = new StdioTransport(Stream.Null, Stream.Null); + Assert.Null(await empty.ReadFrameAsync()); + using var input = new MemoryStream("\n\r\n"u8.ToArray()); + using var transport = new StdioTransport(input, Stream.Null); + Assert.Equal("", (await transport.ReadFrameAsync())?.Json); + Assert.Equal("", (await transport.ReadFrameAsync())?.Json); + Assert.Null(await transport.ReadFrameAsync()); + } + + [Theory] + [InlineData("{}")] + [InlineData("not json")] + [InlineData("{}\r")] + public async Task NonemptyFinalFrameIsDeliveredOnceWithoutRequiringNewline(string text) + { + using var input = new MemoryStream(Encoding.UTF8.GetBytes(text)); + using var transport = new StdioTransport(input, Stream.Null); + Assert.Equal(text, (await transport.ReadFrameAsync())?.Json); + Assert.Null(await transport.ReadFrameAsync()); + Assert.Null(await transport.ReadFrameAsync()); + } + + [Theory] + [InlineData(new byte[] { 0xff })] + [InlineData(new byte[] { 0xc0, 0x80 })] + [InlineData(new byte[] { 0xe2, 0x82 })] + [InlineData(new byte[] { 0xed, 0xa0, 0x80 })] + public async Task InvalidUtf8IsRejectedAndNextFrameSurvives(byte[] invalid) + { + using var input = new MemoryStream([.. invalid, (byte)'\n', .. "{}\n"u8.ToArray()]); + using var transport = new StdioTransport(input, Stream.Null); + var rejected = await transport.ReadFrameAsync(); + Assert.Null(rejected?.Json); + Assert.Equal(-32700, rejected?.Error?.Code); + Assert.Equal("{}", (await transport.ReadFrameAsync())?.Json); + } + + [Theory] + [InlineData("12345678\n", true)] + [InlineData("12345678\r\n", true)] + [InlineData("éééé\n", true)] + [InlineData("123456789\n", false)] + [InlineData("123456789\r\n", false)] + [InlineData("ééééa\n", false)] + [InlineData("123456789", false)] + public async Task LimitCountsUtf8BytesExcludingCrLf(string frame, bool accepted) + { + using var input = new MemoryStream(Encoding.UTF8.GetBytes(frame)); + using var transport = new StdioTransport(input, Stream.Null, maxFrameBytes: 8); + var result = Assert.IsType(await transport.ReadFrameAsync()); + Assert.Equal(accepted, result.Error is null); + if (!accepted) + { + Assert.Equal(-32600, result.Error!.Code); + } + } + + [Fact] + public async Task OversizedMultiBufferFrameResynchronizesWithOneBoundedError() + { + using var input = new MemoryStream(Encoding.UTF8.GetBytes(new string('x', 100_000) + "\n{}\n")); + using var transport = new StdioTransport(input, Stream.Null, maxFrameBytes: 32); + var result = await transport.ReadFrameAsync(); + Assert.Equal(-32600, result?.Error?.Code); + Assert.True(result?.Error?.Message.Length < 100); + Assert.Equal("{}", (await transport.ReadFrameAsync())?.Json); + Assert.Null(await transport.ReadFrameAsync()); + } + + [Fact] + public async Task ConcurrentWritesAreCompleteFlushedJsonLinesAndStreamsRemainOwnedByCaller() + { + using var output = new YieldingStream(); + using (var transport = new StdioTransport(Stream.Null, output)) + { + await Task.WhenAll(Enumerable.Range(0, 100) + .Select(id => transport.WriteMessageAsync(new { id, text = "音楽\nsecond line" }))); + } + + Assert.Equal(100, output.Flushes); + var lines = Encoding.UTF8.GetString(output.ToArray()).Split('\n'); + Assert.Equal("", lines[^1]); + var ids = lines[..^1].Select(line => + { + using var json = JsonDocument.Parse(line); + Assert.Equal("音楽\nsecond line", json.RootElement.GetProperty("text").GetString()); + return json.RootElement.GetProperty("id").GetInt32(); + }); + Assert.Equal(Enumerable.Range(0, 100), ids.Order()); + Assert.True(output.CanWrite); + } + + [Fact] + public async Task CancellationInterruptsAnIdleRead() + { + using var input = new ChannelStream(); + using var transport = new StdioTransport(input, Stream.Null); + using var cancellation = new CancellationTokenSource(); + var read = transport.ReadFrameAsync(cancellation.Token).AsTask(); + cancellation.Cancel(); + await Assert.ThrowsAnyAsync(() => read.WaitAsync(TimeSpan.FromSeconds(3))); + } + + [Fact] + public async Task InvalidUtf8InFinalFrameIsRejectedRatherThanSilentlyReplaced() + { + using var input = new MemoryStream([0xe2, 0x82]); + using var transport = new StdioTransport(input, Stream.Null); + Assert.Equal(-32700, (await transport.ReadFrameAsync())?.Error?.Code); + Assert.Null(await transport.ReadFrameAsync()); + } + + private sealed class YieldingStream : MemoryStream + { + public int Flushes { get; private set; } + public override async ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) + { + await Task.Yield(); + await base.WriteAsync(buffer, cancellationToken); + } + + public override Task FlushAsync(CancellationToken cancellationToken) + { + Flushes++; + return base.FlushAsync(cancellationToken); + } + } +} diff --git a/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/ScaffoldTests.cs b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/ScaffoldTests.cs new file mode 100644 index 0000000..69e8500 --- /dev/null +++ b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/ScaffoldTests.cs @@ -0,0 +1,45 @@ +using System.Reflection; +using System.Runtime.Versioning; +using System.Text.Json; +using Melanchall.DryWetMidi.Core; + +namespace GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests; + +public sealed class ScaffoldTests +{ + [Theory] + [InlineData("GAJ3T.MusicGen.RiffGrooveBuilder.Core")] + [InlineData("GAJ3T.MusicGen.RiffGrooveBuilder.Generation")] + [InlineData("GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests")] + public void CompiledAssemblyTargetsNet10(string assemblyName) + { + var assembly = Assembly.Load(assemblyName); + var framework = assembly.GetCustomAttribute(); + + Assert.NotNull(framework); + Assert.Equal(".NETCoreApp,Version=v10.0", framework.FrameworkName); + } + + [Fact] + public void GenerationResolvesPinnedDryWetMidiAndCanConstructAnInMemoryFile() + { + var manifestPath = Path.Combine( + AppContext.BaseDirectory, + $"{typeof(ScaffoldTests).Assembly.GetName().Name}.deps.json"); + using var manifest = JsonDocument.Parse(File.ReadAllText(manifestPath)); + var runtimeTarget = manifest.RootElement.GetProperty("runtimeTarget") + .GetProperty("name").GetString()!; + var dependencies = manifest.RootElement.GetProperty("targets").GetProperty(runtimeTarget); + var generation = Assert.Single( + dependencies.EnumerateObject(), + dependency => dependency.Name.StartsWith( + "GAJ3T.MusicGen.RiffGrooveBuilder.Generation/", StringComparison.Ordinal)); + + Assert.Equal("8.0.3", generation.Value.GetProperty("dependencies") + .GetProperty("Melanchall.DryWetMidi").GetString()); + + var midi = new MidiFile(new TrackChunk()); + Assert.Single(midi.GetTrackChunks()); + Assert.Equal("Melanchall.DryWetMidi", typeof(MidiFile).Assembly.GetName().Name); + } +} diff --git a/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/packages.lock.json b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/packages.lock.json new file mode 100644 index 0000000..324782b --- /dev/null +++ b/tests/GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests/packages.lock.json @@ -0,0 +1,115 @@ +{ + "version": 2, + "dependencies": { + "net10.0": { + "Microsoft.NET.Test.Sdk": { + "type": "Direct", + "requested": "[18.11.0, 18.11.0]", + "resolved": "18.11.0", + "contentHash": "xf/bR0LNkhK0SnadDRlZIQmC4sac5Wk0e1WAdiQjRN3MSo6gQ9M2c4c1XRNnVGjfOvckh704W5CJ19AL0/Xsdg==", + "dependencies": { + "Microsoft.CodeCoverage": "18.11.0", + "Microsoft.TestPlatform.TestHost": "18.11.0" + } + }, + "xunit": { + "type": "Direct", + "requested": "[2.9.3, 2.9.3]", + "resolved": "2.9.3", + "contentHash": "TlXQBinK35LpOPKHAqbLY4xlEen9TBafjs0V5KnA4wZsoQLQJiirCR4CbIXvOH8NzkW4YeJKP5P/Bnrodm0h9Q==", + "dependencies": { + "xunit.analyzers": "1.18.0", + "xunit.assert": "2.9.3", + "xunit.core": "[2.9.3]" + } + }, + "xunit.runner.visualstudio": { + "type": "Direct", + "requested": "[4.0.1, 4.0.1]", + "resolved": "4.0.1", + "contentHash": "8CoAaZkniVekR1ycJyxn+hOz+6ZQCDPcoIsIs6ujd4WyFcBMlxGNU15Qb8Uxd4iO4UmOuETb0M6vzBbwX/mfLA==" + }, + "Microsoft.CodeCoverage": { + "type": "Transitive", + "resolved": "18.11.0", + "contentHash": "MhN9wpvL1Es4hfIYslrsVgIsUdDFxuOBTbAl9mGIMvFo8PP5CLf4DrGdNrfwWSyn0lqi6sssm+I/qkkLL3MU+g==" + }, + "Microsoft.TestPlatform.ObjectModel": { + "type": "Transitive", + "resolved": "18.11.0", + "contentHash": "BXBHYnwSOljKute8UYCMXOLAdB7awxEMppPSpqOF1ZxLD/W/OH+vTBgFaXA7q0aditJTVXSMVenel+wOkEIyNg==" + }, + "Microsoft.TestPlatform.TestHost": { + "type": "Transitive", + "resolved": "18.11.0", + "contentHash": "AKjwKpyRBwoQFQmpcchtoYlfJEBlaY/40uxBRi+qXP4NR7xT8t+XTJtOyEyumfvfJcH5pASs75LwNdXYRr4XNA==", + "dependencies": { + "Microsoft.TestPlatform.ObjectModel": "18.11.0" + } + }, + "xunit.abstractions": { + "type": "Transitive", + "resolved": "2.0.3", + "contentHash": "pot1I4YOxlWjIb5jmwvvQNbTrZ3lJQ+jUGkGjWE3hEFM0l5gOnBWS+H3qsex68s5cO52g+44vpGzhAt+42vwKg==" + }, + "xunit.analyzers": { + "type": "Transitive", + "resolved": "1.18.0", + "contentHash": "OtFMHN8yqIcYP9wcVIgJrq01AfTxijjAqVDy/WeQVSyrDC1RzBWeQPztL49DN2syXRah8TYnfvk035s7L95EZQ==" + }, + "xunit.assert": { + "type": "Transitive", + "resolved": "2.9.3", + "contentHash": "/Kq28fCE7MjOV42YLVRAJzRF0WmEqsmflm0cfpMjGtzQ2lR5mYVj1/i0Y8uDAOLczkL3/jArrwehfMD0YogMAA==" + }, + "xunit.core": { + "type": "Transitive", + "resolved": "2.9.3", + "contentHash": "BiAEvqGvyme19wE0wTKdADH+NloYqikiU0mcnmiNyXaF9HyHmE6sr/3DC5vnBkgsWaE6yPyWszKSPSApWdRVeQ==", + "dependencies": { + "xunit.extensibility.core": "[2.9.3]", + "xunit.extensibility.execution": "[2.9.3]" + } + }, + "xunit.extensibility.core": { + "type": "Transitive", + "resolved": "2.9.3", + "contentHash": "kf3si0YTn2a8J8eZNb+zFpwfoyvIrQ7ivNk5ZYA5yuYk1bEtMe4DxJ2CF/qsRgmEnDr7MnW1mxylBaHTZ4qErA==", + "dependencies": { + "xunit.abstractions": "2.0.3" + } + }, + "xunit.extensibility.execution": { + "type": "Transitive", + "resolved": "2.9.3", + "contentHash": "yMb6vMESlSrE3Wfj7V6cjQ3S4TXdXpRqYeNEI3zsX31uTsGMJjEw6oD5F5u1cHnMptjhEECnmZSsPxB6ChZHDQ==", + "dependencies": { + "xunit.extensibility.core": "[2.9.3]" + } + }, + "gaj3t.musicgen.riffgroovebuilder.core": { + "type": "Project" + }, + "gaj3t.musicgen.riffgroovebuilder.generation": { + "type": "Project", + "dependencies": { + "GAJ3T.MusicGen.RiffGrooveBuilder.Core": "[1.0.0, )", + "Melanchall.DryWetMidi": "[8.0.3, 8.0.3]" + } + }, + "gaj3t.musicgen.riffgroovebuilder.server": { + "type": "Project", + "dependencies": { + "GAJ3T.MusicGen.RiffGrooveBuilder.Core": "[1.0.0, )", + "GAJ3T.MusicGen.RiffGrooveBuilder.Generation": "[1.0.0, )" + } + }, + "Melanchall.DryWetMidi": { + "type": "CentralTransitive", + "requested": "[8.0.3, 8.0.3]", + "resolved": "8.0.3", + "contentHash": "U+Ubol4MhieY2xgZGqcI8H2F/4HWzWKq8/WPHd1SXS7WXaHyEWMnj56vtxKOJFM5FLbj+NOUny5+X2KAzI0YUg==" + } + } + } +} \ No newline at end of file